code
stringlengths
3
1.05M
repo_name
stringlengths
4
116
path
stringlengths
3
942
language
stringclasses
30 values
license
stringclasses
15 values
size
int32
3
1.05M
#!/usr/bin/env python3 '''NSEC3 opt-out flag test based on RFC-5155 example.''' from dnstest.test import Test t = Test() knot = t.server("knot") knot.DIG_TIMEOUT = 2 bind = t.server("bind") zone = t.zone("example.", storage=".") t.link(zone, knot) t.link(zone, bind) t.start() # B1. Name Error. resp = knot.dig("a.c.x.w.example.", "A", dnssec=True) resp.check(rcode="NXDOMAIN", flags="QR AA", eflags="DO") resp.cmp(bind) # B2. No Data Error. resp = knot.dig("ns1.example.", "MX", dnssec=True) resp.check(rcode="NOERROR", flags="QR AA", eflags="DO") resp.cmp(bind) # B2.1. No Data Error, Empty Non-Terminal. resp = knot.dig("y.w.example.", "A", dnssec=True) resp.check(rcode="NOERROR", flags="QR AA", eflags="DO") resp.cmp(bind) # B3. Referral to an Opt-Out Unsigned Zone. resp = knot.dig("mc.c.example.", "MX", dnssec=True) resp.check(rcode="NOERROR", flags="QR", noflags="AA", eflags="DO") resp.cmp(bind) # B4. Wildcard Expansion. resp = knot.dig("a.z.w.example.", "MX", dnssec=True) resp.check(rcode="NOERROR", flags="QR AA", eflags="DO") resp.cmp(bind) # B5. Wildcard No Data Error. resp = knot.dig("a.z.w.example.", "AAAA", dnssec=True) resp.check(rcode="NOERROR", flags="QR AA", eflags="DO") # @note Commented out because BIND9 (as of 9.9.4) does not return # a closest encloser wildcard NSEC3 RR. # See RFC5155 appendix B.5, page 46 #resp.cmp(bind) # B6. DS Child Zone No Data Error. resp = knot.dig("example.", "DS", dnssec=True) resp.check(rcode="NOERROR", flags="QR AA", eflags="DO") resp.cmp(bind) t.end()
jkadlec/knot-dns-zoneapi
tests-extra/tests/basic/opt-out/test.py
Python
gpl-3.0
1,542
import codecs import yaml import operator import os import tempfile import textwrap import re import ast from mako.template import Template from .. import Messages, blocks from ..Constants import TOP_BLOCK_FILE_MODE from .FlowGraphProxy import FlowGraphProxy from ..utils import expr_utils from .top_block import TopBlockGenerator DATA_DIR = os.path.dirname(__file__) HEADER_TEMPLATE = os.path.join(DATA_DIR, 'cpp_templates/flow_graph.hpp.mako') SOURCE_TEMPLATE = os.path.join(DATA_DIR, 'cpp_templates/flow_graph.cpp.mako') CMAKE_TEMPLATE = os.path.join(DATA_DIR, 'cpp_templates/CMakeLists.txt.mako') header_template = Template(filename=HEADER_TEMPLATE) source_template = Template(filename=SOURCE_TEMPLATE) cmake_template = Template(filename=CMAKE_TEMPLATE) class CppTopBlockGenerator(TopBlockGenerator): def __init__(self, flow_graph, file_path): """ Initialize the C++ top block generator object. Args: flow_graph: the flow graph object file_path: the path where we want to create a new directory with C++ files """ self._flow_graph = FlowGraphProxy(flow_graph) self._generate_options = self._flow_graph.get_option('generate_options') self._mode = TOP_BLOCK_FILE_MODE # Handle the case where the directory is read-only # In this case, use the system's temp directory if not os.access(file_path, os.W_OK): file_path = tempfile.gettempdir() # When generating C++ code, we create a new directory # (file_path) and generate the files inside that directory filename = self._flow_graph.get_option('id') self.file_path = os.path.join(file_path, filename) self._dirname = file_path def write(self): """create directory, generate output and write it to files""" self._warnings() fg = self._flow_graph platform = fg.parent self.title = fg.get_option('title') or fg.get_option('id').replace('_', ' ').title() variables = fg.get_cpp_variables() parameters = fg.get_parameters() monitors = fg.get_monitors() self._variable_types() self._parameter_types() self.namespace = { 'flow_graph': fg, 'variables': variables, 'parameters': parameters, 'monitors': monitors, 'generate_options': self._generate_options, 'config': platform.config } if not os.path.exists(self.file_path): os.makedirs(self.file_path) for filename, data in self._build_cpp_header_code_from_template(): with codecs.open(filename, 'w', encoding='utf-8') as fp: fp.write(data) if not self._generate_options.startswith('hb'): if not os.path.exists(os.path.join(self.file_path, 'build')): os.makedirs(os.path.join(self.file_path, 'build')) for filename, data in self._build_cpp_source_code_from_template(): with codecs.open(filename, 'w', encoding='utf-8') as fp: fp.write(data) if fg.get_option('gen_cmake') == 'On': for filename, data in self._build_cmake_code_from_template(): with codecs.open(filename, 'w', encoding='utf-8') as fp: fp.write(data) def _build_cpp_source_code_from_template(self): """ Convert the flow graph to a C++ source file. Returns: a string of C++ code """ file_path = self.file_path + '/' + self._flow_graph.get_option('id') + '.cpp' output = [] flow_graph_code = source_template.render( title=self.title, includes=self._includes(), blocks=self._blocks(), callbacks=self._callbacks(), connections=self._connections(), **self.namespace ) # strip trailing white-space flow_graph_code = "\n".join(line.rstrip() for line in flow_graph_code.split("\n")) output.append((file_path, flow_graph_code)) return output def _build_cpp_header_code_from_template(self): """ Convert the flow graph to a C++ header file. Returns: a string of C++ code """ file_path = self.file_path + '/' + self._flow_graph.get_option('id') + '.hpp' output = [] flow_graph_code = header_template.render( title=self.title, includes=self._includes(), blocks=self._blocks(), callbacks=self._callbacks(), connections=self._connections(), **self.namespace ) # strip trailing white-space flow_graph_code = "\n".join(line.rstrip() for line in flow_graph_code.split("\n")) output.append((file_path, flow_graph_code)) return output def _build_cmake_code_from_template(self): """ Convert the flow graph to a CMakeLists.txt file. Returns: a string of CMake code """ filename = 'CMakeLists.txt' file_path = os.path.join(self.file_path, filename) cmake_tuples = [] cmake_opt = self._flow_graph.get_option("cmake_opt") cmake_opt = " " + cmake_opt # To make sure we get rid of the "-D"s when splitting for opt_string in cmake_opt.split(" -D"): opt_string = opt_string.strip() if opt_string: cmake_tuples.append(tuple(opt_string.split("="))) output = [] flow_graph_code = cmake_template.render( title=self.title, includes=self._includes(), blocks=self._blocks(), callbacks=self._callbacks(), connections=self._connections(), links=self._links(), cmake_tuples=cmake_tuples, **self.namespace ) # strip trailing white-space flow_graph_code = "\n".join(line.rstrip() for line in flow_graph_code.split("\n")) output.append((file_path, flow_graph_code)) return output def _links(self): fg = self._flow_graph links = fg.links() seen = set() output = [] for link_list in links: if link_list: for link in link_list: seen.add(link) return list(seen) def _includes(self): fg = self._flow_graph includes = fg.includes() seen = set() output = [] def is_duplicate(l): if l.startswith('#include') and l in seen: return True seen.add(line) return False for block_ in includes: for include_ in block_: if not include_: continue line = include_.rstrip() if not is_duplicate(line): output.append(line) return output def _blocks(self): fg = self._flow_graph parameters = fg.get_parameters() # List of blocks not including variables and imports and parameters and disabled def _get_block_sort_text(block): code = block.cpp_templates.render('make').replace(block.name, ' ') try: code += block.params['gui_hint'].get_value() # Newer gui markup w/ qtgui except: pass return code blocks = [ b for b in fg.blocks if b.enabled and not (b.get_bypassed() or b.is_import or b in parameters or b.key == 'options' or b.is_virtual_source() or b.is_virtual_sink()) ] blocks = expr_utils.sort_objects(blocks, operator.attrgetter('name'), _get_block_sort_text) blocks_make = [] for block in blocks: translations = block.cpp_templates.render('translations') make = block.cpp_templates.render('make') declarations = block.cpp_templates.render('declarations') if translations: translations = yaml.safe_load(translations) else: translations = {} translations.update( {r"gr\.sizeof_([\w_]+)": r"sizeof(\1)"} ) for key in translations: make = re.sub(key.replace("\\\\", "\\"), translations[key], make) declarations = declarations.replace(key, translations[key]) if make: blocks_make.append((block, make, declarations)) elif 'qt' in block.key: # The QT Widget blocks are technically variables, # but they contain some code we don't want to miss blocks_make.append(('', make, declarations)) return blocks_make def _variable_types(self): fg = self._flow_graph variables = fg.get_cpp_variables() type_translation = {'complex': 'gr_complex', 'real': 'double', 'float': 'float', 'int': 'int', 'complex_vector': 'std::vector<gr_complex>', 'real_vector': 'std::vector<double>', 'float_vector': 'std::vector<float>', 'int_vector': 'std::vector<int>', 'string': 'std::string', 'bool': 'bool'} # If the type is explcitly specified, translate to the corresponding C++ type for var in list(variables): if var.params['value'].dtype != 'raw': var.vtype = type_translation[var.params['value'].dtype] variables.remove(var) # If the type is 'raw', we'll need to evaluate the variable to infer the type. # Create an executable fragment of code containing all 'raw' variables in # order to infer the lvalue types. # # Note that this differs from using ast.literal_eval() as literal_eval evaluates one # variable at a time. The code fragment below evaluates all variables together which # allows the variables to reference each other (i.e. a = b * c). prog = 'def get_decl_types():\n' prog += '\tvar_types = {}\n' for var in variables: prog += '\t' + str(var.params['id'].value) + '=' + str(var.params['value'].value) + '\n' prog += '\tvar_types = {}\n'; for var in variables: prog += '\tvar_types[\'' + str(var.params['id'].value) + '\'] = type(' + str(var.params['id'].value) + ')\n' prog += '\treturn var_types' # Execute the code fragment in a separate namespace and retrieve the lvalue types var_types = {} namespace = {} try: exec(prog, namespace) var_types = namespace['get_decl_types']() except Exception as excp: print('Failed to get parameter lvalue types: %s' %(excp)) # Format the rvalue of each variable expression for var in variables: var.format_expr(var_types[str(var.params['id'].value)]) def _parameter_types(self): fg = self._flow_graph parameters = fg.get_parameters() for param in parameters: type_translation = {'eng_float' : 'double', 'intx' : 'int', 'str' : 'std::string', 'complex': 'gr_complex'}; param.vtype = type_translation[param.params['type'].value] if param.vtype == 'gr_complex': evaluated = ast.literal_eval(param.params['value'].value.strip()) cpp_cmplx = '{' + str(evaluated.real) + ', ' + str(evaluated.imag) + '}' # Update the 'var_make' entry in the cpp_templates dictionary d = param.cpp_templates cpp_expr = d['var_make'].replace('${value}', cpp_cmplx) d.update({'var_make':cpp_expr}) param.cpp_templates = d def _callbacks(self): fg = self._flow_graph variables = fg.get_cpp_variables() parameters = fg.get_parameters() # List of variable names var_ids = [var.name for var in parameters + variables] replace_dict = dict((var_id, 'this->' + var_id) for var_id in var_ids) callbacks_all = [] for block in fg.iter_enabled_blocks(): if not (block.is_virtual_sink() or block.is_virtual_source()): callbacks_all.extend(expr_utils.expr_replace(cb, replace_dict) for cb in block.get_cpp_callbacks()) # Map var id to callbacks def uses_var_id(callback): used = expr_utils.get_variable_dependencies(callback, [var_id]) return used and ('this->' + var_id in callback) # callback might contain var_id itself callbacks = {} for var_id in var_ids: callbacks[var_id] = [callback for callback in callbacks_all if uses_var_id(callback)] return callbacks def _connections(self): fg = self._flow_graph templates = {key: Template(text) for key, text in fg.parent_platform.cpp_connection_templates.items()} def make_port_sig(port): if port.parent.key in ('pad_source', 'pad_sink'): block = 'self()' key = fg.get_pad_port_global_key(port) else: block = 'this->' + port.parent_block.name key = port.key if not key.isdigit(): # TODO What use case is this supporting? toks = re.findall(r'\d+', key) if len(toks) > 0: key = toks[0] else: # Assume key is a string key = '"' + key + '"' return '{block}, {key}'.format(block=block, key=key) connections = fg.get_enabled_connections() # Get the virtual blocks and resolve their connections connection_factory = fg.parent_platform.Connection virtual_source_connections = [c for c in connections if isinstance(c.source_block, blocks.VirtualSource)] for connection in virtual_source_connections: sink = connection.sink_port for source in connection.source_port.resolve_virtual_source(): resolved = connection_factory(fg.orignal_flowgraph, source, sink) connections.append(resolved) virtual_connections = [c for c in connections if (isinstance(c.source_block, blocks.VirtualSource) or isinstance(c.sink_block, blocks.VirtualSink))] for connection in virtual_connections: # Remove the virtual connection connections.remove(connection) # Bypassing blocks: Need to find all the enabled connections for the block using # the *connections* object rather than get_connections(). Create new connections # that bypass the selected block and remove the existing ones. This allows adjacent # bypassed blocks to see the newly created connections to downstream blocks, # allowing them to correctly construct bypass connections. bypassed_blocks = fg.get_bypassed_blocks() for block in bypassed_blocks: # Get the upstream connection (off of the sink ports) # Use *connections* not get_connections() source_connection = [c for c in connections if c.sink_port == block.sinks[0]] # The source connection should never have more than one element. assert (len(source_connection) == 1) # Get the source of the connection. source_port = source_connection[0].source_port # Loop through all the downstream connections for sink in (c for c in connections if c.source_port == block.sources[0]): if not sink.enabled: # Ignore disabled connections continue connection = connection_factory(fg.orignal_flowgraph, source_port, sink.sink_port) connections.append(connection) # Remove this sink connection connections.remove(sink) # Remove the source connection connections.remove(source_connection[0]) # List of connections where each endpoint is enabled (sorted by domains, block names) def by_domain_and_blocks(c): return c.type, c.source_block.name, c.sink_block.name rendered = [] for con in sorted(connections, key=by_domain_and_blocks): template = templates[con.type] if con.source_port.dtype != 'bus': code = template.render(make_port_sig=make_port_sig, source=con.source_port, sink=con.sink_port) if not self._generate_options.startswith('hb'): code = 'this->tb->' + code rendered.append(code) else: # Bus ports need to iterate over the underlying connections and then render # the code for each subconnection porta = con.source_port portb = con.sink_port fg = self._flow_graph if porta.dtype == 'bus' and portb.dtype == 'bus': # which bus port is this relative to the bus structure if len(porta.bus_structure) == len(portb.bus_structure): for port_num in porta.bus_structure: hidden_porta = porta.parent.sources[port_num] hidden_portb = portb.parent.sinks[port_num] connection = fg.parent_platform.Connection( parent=self, source=hidden_porta, sink=hidden_portb) code = template.render(make_port_sig=make_port_sig, source=hidden_porta, sink=hidden_portb) if not self._generate_options.startswith('hb'): code = 'this->tb->' + code rendered.append(code) return rendered
mrjacobagilbert/gnuradio
grc/core/generator/cpp_top_block.py
Python
gpl-3.0
17,872
// uScript uScript_Scrollbar.cs // (C) 2015 Detox Studios LLC using UnityEngine; using System.Collections; //Unity 4.6 and above only #if !UNITY_3_5 && !UNITY_4_0 && !UNITY_4_1 && !UNITY_4_2 && !UNITY_4_3 && !UNITY_4_4 && !UNITY_4_5 [NodePath("Events/UI Events")] [NodeCopyright("Copyright 2015 by Detox Studios LLC")] [NodeToolTip("Fires an event signal when a scrollbar's value has changed.")] [NodeAuthor("Detox Studios LLC", "http://www.detoxstudios.com")] [NodeHelp("http://docs.uscript.net/#3-Working_With_uScript/3.4-Nodes.htm")] [FriendlyName("UI Scrollbar Events", "Fires an event signal when Instance Scrollbar receives a value changed event.")] public class uScript_Scrollbar : uScriptEvent { public delegate void uScriptEventHandler(object sender, ScrollbarEventArgs args); public class ScrollbarEventArgs : System.EventArgs { private float m_ScrollbarValue; [FriendlyName("Scrollbar Value")] public float ScrollbarValue { get { return m_ScrollbarValue; } set { m_ScrollbarValue = value; } } public ScrollbarEventArgs(float scrollbarValue) { m_ScrollbarValue = scrollbarValue; } } [FriendlyName("On Scrollbar Value Changed")] public event uScriptEventHandler OnScrollbarValueChanged; public void Start() { UnityEngine.UI.Scrollbar scrollbar = GetComponent<UnityEngine.UI.Scrollbar>(); scrollbar.onValueChanged.RemoveAllListeners(); scrollbar.onValueChanged.AddListener(HandleScrollbar); } void HandleScrollbar(float value) { if ( OnScrollbarValueChanged != null ) OnScrollbarValueChanged( this, new ScrollbarEventArgs(value) ); } } #endif
neroziros/GameJam2017
Assets/uScript/uScriptRuntime/Nodes/Events/uScript_Scrollbar.cs
C#
gpl-3.0
1,698
# -*- coding: utf-8 -*- # Author: Aziz Köksal from __future__ import unicode_literals from dil.token_list import TOK import re class Token: """ kind = The kind of the token. is_ws = Is this a whitespace token? ws = Preceding whitespace characters. text = The text of the token. value = The value (str,int,float etc.) of the token. next = Next token in the list. prev = Previous token in the list. """ def __init__(self, kind, ws, text): self.kind = kind self.is_ws = (2 <= kind <= 7) #kind in (2, 3, 4, 5, 6, 7) self.ws = ws self.text = text self.value = None self.next = self.prev = None self.linnum = None def __unicode__(self): return self.text __str__ = __unicode__ # Create a table of whitespace strings. ws_table = " "*20 ws_table = [ws_table[:i] for i in range(1,21)] def create_tokens(token_list): str_list = token_list[0] # The first element must be the string list. token_list = token_list[1] head = Token(TOK.HEAD, "", "") line_num = 1 prev = head result = [None]*len(token_list) # Reserve space. i = 0 for tup in token_list: kind = tup[0] if kind == TOK.Newline: line_num += 1 ws = tup[1] if type(ws) == int: # Get ws from the table if short enough, otherwise create it. ws = ws_table[ws] if ws < 20 else " "*ws # Get the text of the token from str_list if there's a 3rd element, # otherwise get it from the table TOK.str. text = str_list[tup[2]] if len(tup) >= 3 else TOK.str[kind] # Create the token. token = Token(kind, ws, text) token.linnum = line_num token.prev = prev # Link to the previous token. prev.next = token # Link to this token from the previous one. prev = token result[i] = token token.value = parse_funcs[kind](token, (tup, str_list)) i += 1 return result escape_table = { "'":39,'"':34,'?':63,'\\':92,'a':7,'b':8,'f':12,'n':10,'r':13,'t':9,'v':11 } rx_newline = re.compile("\r\n?|\n|\u2028|\u2029") rx_escape = re.compile( r"\\(?:u[0-9a-fA-F]{4}|U[0-9a-fA-F]{8}|[0-7]{1,3}|&\w+;|.)" ) def escape2char(s): """ E.g. "\\u0041" -> 'A' """ from htmlentitydefs import name2codepoint c = s[1] if c in 'xuU': c = int(s[2:], 16) elif c.isdigit(): c = int(s[1:], 8) elif c == '&': c = name2codepoint.get(s[2:-1], 0xFFFD) else: c = escape_table.get(c, 0xFFFD) return unichr(c) def parse_str(t, more): s = t.text.rstrip("cwd") # Strip suffix. c = s[0] if c == 'r': # Raw string. s = s[2:-1] elif c == '`': # Raw string. s = s[1:-1] elif c == '\\': # Escape string. return rx_escape.sub(lambda m: escape2char(m.group()), s) + "\0" elif c == '"': # Normal string with escape sequences. s = rx_escape.sub(lambda m: escape2char(m.group()), s[1:-1]) elif c == 'q': # Delimited or token string. if s[1] == '"': # Delimited string. if s[2] in "[({<": s = s[3:-2] # E.g.: q"[abcd]" -> abcd else: # Get the identifier delimiter. |q"Identifier\n| -> 2 + len(delim) + 1 m = rx_newline.search(s) assert m delim_len = m.start() - 2 s = s[2+delim_len+1 : -delim_len-1] elif s[1] == '{': # Token string. s = s[2:-1] elif c == 'x': # Hex string. s = s[2:-1] # x"XX" -> XX result = "" n = None for hexd in s: #rx_hexdigits.findall(s): # Regexp not really needed. d = ord(hexd) if not 48 <= d <= 57 and not 97 <= (d|0x20) <= 102: continue hexd = int(hexd, 16) if n == None: n = hexd continue result += unichr((n << 4) + hexd) n = None return result + "\0" return rx_newline.sub("\n", s) + "\0" # Convert newlines and zero-terminate. def parse_chr(t, more): s = t.text[1:-1] # Remove single quotes. 'x' -> x if s[0] == '\\': return escape2char(s) return s def parse_int(t, more): s = t.text.replace("_", "") # Strip underscore separators. base = 10 if len(s) >= 2: if s[1] in 'xX': base = 16 elif s[1] in 'bB': base = 2 elif s[0] == '0': base = 8 return int(s.rstrip("uUL"), base) def parse_float(t, more): # TODO: use mpmath for multiprecission floats. Python has no long doubles. # (http://code.google.com/p/mpmath/) s = t.text.replace("_", "") # Strip underscore separators. imag_or_real = 1j if s[-1] == 'i' else 1. float_ = float.fromhex if s[1:2] in 'xX' else float return float_(s.rstrip("fFLi")) * imag_or_real def get_time(t, more): return 0 # TODO: def get_timestamp(t, more): return 0 # TODO: def get_date(t, more): return 0 # TODO: def get_line(t, more): return t.linnum # TODO: def get_file(t, more): return "" # TODO: def get_vendor(t, more): return "DIL" def get_version(t, more): return "x.xxx" # TODO: def get_parse_funcs(): return_None = lambda t,m: None func_list = [return_None] * TOK.MAX for kind, func in ( (TOK.Identifier, lambda t,x: t.text),(TOK.String, parse_str), (TOK.CharLiteral, parse_chr),(TOK.FILE, get_file),(TOK.LINE, get_line), (TOK.DATE, get_date),(TOK.TIME, get_time),(TOK.TIMESTAMP, get_timestamp), (TOK.VENDOR, get_vendor),(TOK.VERSION, get_version), (TOK.Int32, parse_int),(TOK.Int64, parse_int),(TOK.Uint32, parse_int), (TOK.Uint64, parse_int),(TOK.Float32, parse_float), (TOK.Float64, parse_float),(TOK.Float80, parse_float), (TOK.Imaginary32, parse_float),(TOK.Imaginary64, parse_float), (TOK.Imaginary80, parse_float) ): func_list[kind] = func return tuple(func_list) parse_funcs = get_parse_funcs()
SiegeLord/dil
scripts/dil/token.py
Python
gpl-3.0
5,585
/* Descritivo das funções relacionadas aos eventos e as passagens */ /* Biblioteca dinamica requisitada */ #include "Eventos.h" /* Lista das funcoes de manipulacao sobre os eventos e as passagens */ /* 1 - Funcao inicia_simu, controla a inicializacao das variaveis do Aeroporto a cada hora ** de simulacao */ void inicia_simu (Aeroporto *aero){ /* 'aero' armazena o Aeroporto; 'numaprox' e 'numdeco' armazenam os numeros ** de aproximacoes e decolagens para a proxima 1 hora de simulacao; 'quant' ** armazena quantidades a serem variadas na funcao; 'temp' armazena a identificacao ** do voo a ser inserido em alguma fila */ int numaprox, numdeco, quant; char *temp = (char *) malloc (TAMp * sizeof(char)); /* Teste de alocacao */ if (temp == NULL){ printf ("\nERRO ALOCACAO DE STRING\n"); exit (-6); } /* Determinacao do numero de voos para aproximacao e decolagem para a proxima ** hora de simulacao */ numaprox = gera_aleatorio (0, 28); numdeco = gera_aleatorio (0, 28); /* Inicializacao do Aeroporto para trabalho na proxima hora */ inicia_aero (aero, numaprox+numdeco); /* Montagem e Ordenacao da fila Aproximacao */ for(quant = 0; quant < numaprox; quant++){ zera_string (temp, TAMp); temp = monta_nome (); add_aprox (aero->filaap, temp); } ordena_aprox (aero->filaap); /* Montagem da fila Decolagem */ for(quant = 0; quant < numdeco; quant++){ zera_string (temp, TAMp); temp = monta_nome (); add_deco (aero->filade, temp); } } /* 2 - Funcao aproxima_aero, realiza o consumo do combustivel dos voos da fila Aproximacao */ void aproxima_aero (Aeroporto *aero){ /* 'aero' armazena o Aeroporto; 'voo' armazena o elemento da fila Aproximacao a ser manipulado; ** 'ind' armazena o indice para o elemento 'voo' */ Aviao *voo; int ind; /* Havendo fila Aproximacao */ if (aero->filaap->inicio != NULL){ voo = aero->filaap->inicio; /* Percorrer toda a fila Aproximacao */ for (ind = aero->filaap->quant; ind > 0; ind--){ voo->comb--; voo = voo->proximo; } } } /* 3 - Funcao aterrissa_aero, realiza o procedimento de pouso para o primeiro voo da fila ** Aproximacao */ void aterrissa_aero (Aeroporto *aero, int ind){ /* 'aero' armazena o Aeroporto; 'ind' armazena o indice para manuseio de uma pista especifica; ** 'pista' armazena a pista a ser manipulada; 'voo' armazena o voo a ser manipulado */ Pista *pista = (aero->pista + ind); Aviao *voo = retira_aprox (aero->filaap); /* Configuracao do voo para pouso */ voo->status = 'P'; voo->comb--; /* Configuracao da pista manipulada */ pista->status = 'O'; pista->voo = voo; } /* 4 - Funcao decola_aero, realiza o procedimento de decolagem para o primeiro voo da fila ** Decolagem */ void decola_aero (Aeroporto *aero, int ind){ /* 'aero' armazena o Aeroporto; 'ind' armazena o indice para manuseio de uma pista especifica; ** 'pista' armazena a pista a ser manipulada; 'voo' armazena o voo a ser manipulado */ Pista *pista = (aero->pista + ind); Aviao *voo = retira_deco (aero->filade); /* Configuracao da pista manipulada, caso haja voo */ if (voo != NULL){ pista->status = 79; pista->voo = voo; } } /* 5 - Funcao aborta_voo, realiza o alerta de emergencia conflitante para o Aeroporto, ** redirecionando o voo para o aeroporto mais proximo */ void aborta_voo (Aeroporto *aero){ /* 'aero' armazena o Aeroporto; 'voo' armazena o voo a ser manipulado; 'ind' o indice da ** identificacao do voo; 'arq' armazena o ponteiro do arquivo a ser escrito o alerta */ Aviao *voo = retira_aprox (aero->filaap); int ind; FILE *arq = fopen ("Simulacao Aeroporto_Lucas e Rodrigo.txt", "a"); /* Teste de alocacao */ if (arq == NULL){ printf ("\nERRO AO ABRIR ARQUIVO\n"); exit (-8); } /* Exibicao na tela da manobra de redirecionamento de voo */ printf ("\nALERTA!!!!\n"); printf ("Nao ha pistas disponiveis, e o voo "); for (ind = 0; ind < TAMp; ind++) printf ("%c", voo->nome[ind]); printf (" esta em emergencia!\n"); printf ("Logo foi redirecionado para outro aeroporto!\n\n"); /* Escrita no arquivo da manobra de redirecionamento de voo */ fprintf (arq, "\nALERTA!!!!\n"); fprintf (arq, "Nao ha pistas disponiveis, e o voo "); for (ind = 0; ind < TAMp; ind++) fprintf (arq, "%c", voo->nome[ind]); fprintf (arq, " esta em emergencia!\n"); fprintf (arq, "Logo foi redirecionado para outro aeroporto!\n\n"); /* Liberacao da responsabilidade do Aeroporto sobre o dado voo */ libera_aviao (voo); fclose (arq); } /* 6 - Funcao verifica_pista, verifica o status da pista */ int verifica_pista (Pista *pista){ /* 'pista' armazena a Pista a ser verificada */ /* Estando livre */ if (pista->status == 76) return 0; /* Estando ocupada */ else return 1; } /* 7 - Funcao hora_atual, configura o tempo de simulacao para o horario real */ struct tm * hora_atual (){ /* 'tempo_atual' armazena a hora local do computador; ** 'info_tempo' e' uma struct do tipo tm, que possui informacoes sobre o tempo local */ time_t tempo_atual; struct tm *info_tempo; /* obtendo a hora atual e guardando-a em uma struct tm ** definida na biblioteca <time.h> */ time(&tempo_atual); info_tempo = localtime(&tempo_atual); return info_tempo; } /* 8 - Funcao incre_tempo, realiza o incremento da hora atual em relacao aos ciclos, de 5 min */ void incre_tempo (struct tm *tempo){ /* 'tempo' armazena a hora corrente da simulacao */ tempo->tm_min += TEMPO; /* Verificacao dos minutos equivalentes a hora posterior */ if(tempo->tm_min >= 60){ tempo->tm_min -= 60; tempo->tm_hour++; } } /* 9 - Funcao imprime_hora, exibe na tela a hora na simulacao */ void imprime_hora (struct tm *tempo){ /* 'tempo' armazena a hora corrente da simulacao */ printf("Data: %.2d/%.2d/%.2d\n", tempo->tm_mday, tempo->tm_mon+1, tempo->tm_year+1900); printf("Hora na simulacao: %.2d:%.2d:%.2d\n", tempo->tm_hour, tempo->tm_min, tempo->tm_sec); } /* 10 - Funcao imprime_hora_arq, escreve num arquivo a hora na simulacao */ void imprime_hora_arq (FILE *arq, struct tm *tempo){ /* 'arq' armazena o arquivo a escrito; 'tempo' armazena a hora corrente da simulacao */ fprintf(arq, "Data: %.2d/%.2d/%.2d\n", tempo->tm_mday, tempo->tm_mon+1, tempo->tm_year+1900); fprintf(arq, "Hora na simulacao: %.2d:%.2d:%.2d\n", tempo->tm_hour, tempo->tm_min, tempo->tm_sec); } /* 11 - Funcao gera_aleatorio, gera numero inteiro aleatorio dado um intervalo */ int gera_aleatorio (int minimo, int maximo){ /* 'minimo' e 'maximo' armazenam o valor minimo e o valor maximo, respectivamente, ** para o intervalo de geracao; 'gerado' armazena o numero gerado no corrente intervalo */ int gerado; /* Geracao do numero aleatorio */ gerado = minimo + (rand()%(maximo-minimo+1)); return gerado; } /* 12 - Funcao zera_string, inicializa a string com '\0' em todos os elementos*/ void zera_string (char *palavra, int tamanho){ /* 'palavra' armazena a string a ser inicializada; 'tamanho' armazena ** o tamanho dentro da string a ser inicializada, podendo ser parcial ou integral; ** 'indice' armazena o indice da string*/ int indice; /* Inicializar a string como NULL*/ for(indice = 0 ; indice < tamanho; indice++) *(palavra+indice) = '\0'; } /* 13 - Funcao ler_resposta, realiza a validacao da resposta para progresso da simulacao */ char ler_resposta (){ /* 'resposta' armazena a resposta do usuario para a pergunta */ char resposta; /* Enquanto for invalida */ do{ scanf ("%c", &resposta); /* Sendo uma resposta invalida */ if ((resposta != 's') && (resposta != 'S') && (resposta != 'n') && (resposta != 'N')) printf ("Resposta invalida, digite novamente!\n"); }while ((resposta != 's') && (resposta != 'S') && (resposta != 'n') && (resposta != 'N')); return resposta; }
rodrigofegui/UnB
2015.1/Estrutura de Dados/Projetos/Projeto 2/Projeto 2 - Simulacao_Definitivo/Eventos.c
C
gpl-3.0
8,313
<?php /** * @package Joomla.Administrator * @subpackage com_menus * * @copyright Copyright (C) 2005 - 2016 Open Source Matters, Inc. All rights reserved. * @license GNU General Public License version 2 or later; see LICENSE.txt */ defined('JPATH_BASE') or die; JFormHelper::loadFieldClass('list'); /** * Form Field class for the Joomla Framework. * * @since 1.6 */ class JFormFieldMenuOrdering extends JFormFieldList { /** * The form field type. * * @var string * @since 1.7 */ protected $type = 'MenuOrdering'; /** * Method to get the list of siblings in a menu. * The method requires that parent be set. * * @return array The field option objects or false if the parent field has not been set * * @since 1.7 */ protected function getOptions() { $options = array(); // Get the parent $parent_id = $this->form->getValue('parent_id', 0); if (empty($parent_id)) { return false; } $db = JFactory::getDbo(); $query = $db->getQuery(true) ->select('a.id AS value, a.title AS text') ->from('#__menu AS a') ->where('a.published >= 0') ->where('a.parent_id =' . (int) $parent_id); if ($menuType = $this->form->getValue('menutype')) { $query->where('a.menutype = ' . $db->quote($menuType)); } else { $query->where('a.menutype != ' . $db->quote('')); } $query->order('a.lft ASC'); // Get the options. $db->setQuery($query); try { $options = $db->loadObjectList(); } catch (RuntimeException $e) { JFactory::getApplication()->enqueueMessage( $e->getMessage(), 'error' ); } $options = array_merge( array(array('value' => '-1', 'text' => JText::_('COM_MENUS_ITEM_FIELD_ORDERING_VALUE_FIRST'))), $options, array(array('value' => '-2', 'text' => JText::_('COM_MENUS_ITEM_FIELD_ORDERING_VALUE_LAST'))) ); // Merge any additional options in the XML definition. $options = array_merge(parent::getOptions(), $options); return $options; } /** * Method to get the field input markup. * * @return string The field input markup. * * @since 1.7 */ protected function getInput() { if ($this->form->getValue('id', 0) == 0) { return '<span class="readonly">' . JText::_('COM_MENUS_ITEM_FIELD_ORDERING_TEXT') . '</span>'; } else { return parent::getInput(); } } }
joomlatools/joomla-platform
app/administrator/components/com_menus/models/fields/menuordering.php
PHP
gpl-3.0
2,352
/* * Broadcom Proprietary and Confidential. Copyright 2016 Broadcom * All Rights Reserved. * * This is UNPUBLISHED PROPRIETARY SOURCE CODE of Broadcom Corporation; * the contents of this file may not be disclosed to third parties, copied * or duplicated in any form, in whole or in part, without the prior * written permission of Broadcom Corporation. * * Broadcom AMBA Interconnect definitions. * * $Id: aidmp.h 476460 2014-05-08 21:57:58Z badhikar $ */ #ifndef _AIDMP_H #define _AIDMP_H /* Manufacturer Ids */ #define MFGID_ARM 0x43b #define MFGID_BRCM 0x4bf #define MFGID_MIPS 0x4a7 /* Component Classes */ #define CC_SIM 0 #define CC_EROM 1 #define CC_CORESIGHT 9 #define CC_VERIF 0xb #define CC_OPTIMO 0xd #define CC_GEN 0xe #define CC_PRIMECELL 0xf /* Enumeration ROM registers */ #define ER_EROMENTRY 0x000 #define ER_REMAPCONTROL 0xe00 #define ER_REMAPSELECT 0xe04 #define ER_MASTERSELECT 0xe10 #define ER_ITCR 0xf00 #define ER_ITIP 0xf04 /* Erom entries */ #define ER_TAG 0xe #define ER_TAG1 0x6 #define ER_VALID 1 #define ER_CI 0 #define ER_MP 2 #define ER_ADD 4 #define ER_END 0xe #define ER_BAD 0xffffffff /* EROM CompIdentA */ #define CIA_MFG_MASK 0xfff00000 #define CIA_MFG_SHIFT 20 #define CIA_CID_MASK 0x000fff00 #define CIA_CID_SHIFT 8 #define CIA_CCL_MASK 0x000000f0 #define CIA_CCL_SHIFT 4 /* EROM CompIdentB */ #define CIB_REV_MASK 0xff000000 #define CIB_REV_SHIFT 24 #define CIB_NSW_MASK 0x00f80000 #define CIB_NSW_SHIFT 19 #define CIB_NMW_MASK 0x0007c000 #define CIB_NMW_SHIFT 14 #define CIB_NSP_MASK 0x00003e00 #define CIB_NSP_SHIFT 9 #define CIB_NMP_MASK 0x000001f0 #define CIB_NMP_SHIFT 4 /* EROM MasterPortDesc */ #define MPD_MUI_MASK 0x0000ff00 #define MPD_MUI_SHIFT 8 #define MPD_MP_MASK 0x000000f0 #define MPD_MP_SHIFT 4 /* EROM AddrDesc */ #define AD_ADDR_MASK 0xfffff000 #define AD_SP_MASK 0x00000f00 #define AD_SP_SHIFT 8 #define AD_ST_MASK 0x000000c0 #define AD_ST_SHIFT 6 #define AD_ST_SLAVE 0x00000000 #define AD_ST_BRIDGE 0x00000040 #define AD_ST_SWRAP 0x00000080 #define AD_ST_MWRAP 0x000000c0 #define AD_SZ_MASK 0x00000030 #define AD_SZ_SHIFT 4 #define AD_SZ_4K 0x00000000 #define AD_SZ_8K 0x00000010 #define AD_SZ_16K 0x00000020 #define AD_SZ_SZD 0x00000030 #define AD_AG32 0x00000008 #define AD_ADDR_ALIGN 0x00000fff #define AD_SZ_BASE 0x00001000 /* 4KB */ /* EROM SizeDesc */ #define SD_SZ_MASK 0xfffff000 #define SD_SG32 0x00000008 #define SD_SZ_ALIGN 0x00000fff #if !defined(_LANGUAGE_ASSEMBLY) && !defined(__ASSEMBLY__) typedef volatile struct _aidmp { uint32 oobselina30; /* 0x000 */ uint32 oobselina74; /* 0x004 */ uint32 PAD[6]; uint32 oobselinb30; /* 0x020 */ uint32 oobselinb74; /* 0x024 */ uint32 PAD[6]; uint32 oobselinc30; /* 0x040 */ uint32 oobselinc74; /* 0x044 */ uint32 PAD[6]; uint32 oobselind30; /* 0x060 */ uint32 oobselind74; /* 0x064 */ uint32 PAD[38]; uint32 oobselouta30; /* 0x100 */ uint32 oobselouta74; /* 0x104 */ uint32 PAD[6]; uint32 oobseloutb30; /* 0x120 */ uint32 oobseloutb74; /* 0x124 */ uint32 PAD[6]; uint32 oobseloutc30; /* 0x140 */ uint32 oobseloutc74; /* 0x144 */ uint32 PAD[6]; uint32 oobseloutd30; /* 0x160 */ uint32 oobseloutd74; /* 0x164 */ uint32 PAD[38]; uint32 oobsynca; /* 0x200 */ uint32 oobseloutaen; /* 0x204 */ uint32 PAD[6]; uint32 oobsyncb; /* 0x220 */ uint32 oobseloutben; /* 0x224 */ uint32 PAD[6]; uint32 oobsyncc; /* 0x240 */ uint32 oobseloutcen; /* 0x244 */ uint32 PAD[6]; uint32 oobsyncd; /* 0x260 */ uint32 oobseloutden; /* 0x264 */ uint32 PAD[38]; uint32 oobaextwidth; /* 0x300 */ uint32 oobainwidth; /* 0x304 */ uint32 oobaoutwidth; /* 0x308 */ uint32 PAD[5]; uint32 oobbextwidth; /* 0x320 */ uint32 oobbinwidth; /* 0x324 */ uint32 oobboutwidth; /* 0x328 */ uint32 PAD[5]; uint32 oobcextwidth; /* 0x340 */ uint32 oobcinwidth; /* 0x344 */ uint32 oobcoutwidth; /* 0x348 */ uint32 PAD[5]; uint32 oobdextwidth; /* 0x360 */ uint32 oobdinwidth; /* 0x364 */ uint32 oobdoutwidth; /* 0x368 */ uint32 PAD[37]; uint32 ioctrlset; /* 0x400 */ uint32 ioctrlclear; /* 0x404 */ uint32 ioctrl; /* 0x408 */ uint32 PAD[61]; uint32 iostatus; /* 0x500 */ uint32 PAD[127]; uint32 ioctrlwidth; /* 0x700 */ uint32 iostatuswidth; /* 0x704 */ uint32 PAD[62]; uint32 resetctrl; /* 0x800 */ uint32 resetstatus; /* 0x804 */ uint32 resetreadid; /* 0x808 */ uint32 resetwriteid; /* 0x80c */ uint32 PAD[60]; uint32 errlogctrl; /* 0x900 */ uint32 errlogdone; /* 0x904 */ uint32 errlogstatus; /* 0x908 */ uint32 errlogaddrlo; /* 0x90c */ uint32 errlogaddrhi; /* 0x910 */ uint32 errlogid; /* 0x914 */ uint32 errloguser; /* 0x918 */ uint32 errlogflags; /* 0x91c */ uint32 PAD[56]; uint32 intstatus; /* 0xa00 */ uint32 PAD[255]; uint32 config; /* 0xe00 */ uint32 PAD[63]; uint32 itcr; /* 0xf00 */ uint32 PAD[3]; uint32 itipooba; /* 0xf10 */ uint32 itipoobb; /* 0xf14 */ uint32 itipoobc; /* 0xf18 */ uint32 itipoobd; /* 0xf1c */ uint32 PAD[4]; uint32 itipoobaout; /* 0xf30 */ uint32 itipoobbout; /* 0xf34 */ uint32 itipoobcout; /* 0xf38 */ uint32 itipoobdout; /* 0xf3c */ uint32 PAD[4]; uint32 itopooba; /* 0xf50 */ uint32 itopoobb; /* 0xf54 */ uint32 itopoobc; /* 0xf58 */ uint32 itopoobd; /* 0xf5c */ uint32 PAD[4]; uint32 itopoobain; /* 0xf70 */ uint32 itopoobbin; /* 0xf74 */ uint32 itopoobcin; /* 0xf78 */ uint32 itopoobdin; /* 0xf7c */ uint32 PAD[4]; uint32 itopreset; /* 0xf90 */ uint32 PAD[15]; uint32 peripherialid4; /* 0xfd0 */ uint32 peripherialid5; /* 0xfd4 */ uint32 peripherialid6; /* 0xfd8 */ uint32 peripherialid7; /* 0xfdc */ uint32 peripherialid0; /* 0xfe0 */ uint32 peripherialid1; /* 0xfe4 */ uint32 peripherialid2; /* 0xfe8 */ uint32 peripherialid3; /* 0xfec */ uint32 componentid0; /* 0xff0 */ uint32 componentid1; /* 0xff4 */ uint32 componentid2; /* 0xff8 */ uint32 componentid3; /* 0xffc */ } aidmp_t; #endif /* !_LANGUAGE_ASSEMBLY && !__ASSEMBLY__ */ /* Out-of-band Router registers */ #define OOB_BUSCONFIG 0x020 #define OOB_STATUSA 0x100 #define OOB_STATUSB 0x104 #define OOB_STATUSC 0x108 #define OOB_STATUSD 0x10c #define OOB_ENABLEA0 0x200 #define OOB_ENABLEA1 0x204 #define OOB_ENABLEA2 0x208 #define OOB_ENABLEA3 0x20c #define OOB_ENABLEB0 0x280 #define OOB_ENABLEB1 0x284 #define OOB_ENABLEB2 0x288 #define OOB_ENABLEB3 0x28c #define OOB_ENABLEC0 0x300 #define OOB_ENABLEC1 0x304 #define OOB_ENABLEC2 0x308 #define OOB_ENABLEC3 0x30c #define OOB_ENABLED0 0x380 #define OOB_ENABLED1 0x384 #define OOB_ENABLED2 0x388 #define OOB_ENABLED3 0x38c #define OOB_ITCR 0xf00 #define OOB_ITIPOOBA 0xf10 #define OOB_ITIPOOBB 0xf14 #define OOB_ITIPOOBC 0xf18 #define OOB_ITIPOOBD 0xf1c #define OOB_ITOPOOBA 0xf30 #define OOB_ITOPOOBB 0xf34 #define OOB_ITOPOOBC 0xf38 #define OOB_ITOPOOBD 0xf3c /* DMP wrapper registers */ #define AI_OOBSELINA30 0x000 #define AI_OOBSELINA74 0x004 #define AI_OOBSELINB30 0x020 #define AI_OOBSELINB74 0x024 #define AI_OOBSELINC30 0x040 #define AI_OOBSELINC74 0x044 #define AI_OOBSELIND30 0x060 #define AI_OOBSELIND74 0x064 #define AI_OOBSELOUTA30 0x100 #define AI_OOBSELOUTA74 0x104 #define AI_OOBSELOUTB30 0x120 #define AI_OOBSELOUTB74 0x124 #define AI_OOBSELOUTC30 0x140 #define AI_OOBSELOUTC74 0x144 #define AI_OOBSELOUTD30 0x160 #define AI_OOBSELOUTD74 0x164 #define AI_OOBSYNCA 0x200 #define AI_OOBSELOUTAEN 0x204 #define AI_OOBSYNCB 0x220 #define AI_OOBSELOUTBEN 0x224 #define AI_OOBSYNCC 0x240 #define AI_OOBSELOUTCEN 0x244 #define AI_OOBSYNCD 0x260 #define AI_OOBSELOUTDEN 0x264 #define AI_OOBAEXTWIDTH 0x300 #define AI_OOBAINWIDTH 0x304 #define AI_OOBAOUTWIDTH 0x308 #define AI_OOBBEXTWIDTH 0x320 #define AI_OOBBINWIDTH 0x324 #define AI_OOBBOUTWIDTH 0x328 #define AI_OOBCEXTWIDTH 0x340 #define AI_OOBCINWIDTH 0x344 #define AI_OOBCOUTWIDTH 0x348 #define AI_OOBDEXTWIDTH 0x360 #define AI_OOBDINWIDTH 0x364 #define AI_OOBDOUTWIDTH 0x368 #if defined(IL_BIGENDIAN) && defined(BCMHND74K) /* Selective swapped defines for those registers we need in * big-endian code. */ #define AI_IOCTRLSET 0x404 #define AI_IOCTRLCLEAR 0x400 #define AI_IOCTRL 0x40c #define AI_IOSTATUS 0x504 #define AI_RESETCTRL 0x804 #define AI_RESETSTATUS 0x800 #else /* !IL_BIGENDIAN || !BCMHND74K */ #define AI_IOCTRLSET 0x400 #define AI_IOCTRLCLEAR 0x404 #define AI_IOCTRL 0x408 #define AI_IOSTATUS 0x500 #define AI_RESETCTRL 0x800 #define AI_RESETSTATUS 0x804 #endif /* IL_BIGENDIAN && BCMHND74K */ #define AI_IOCTRLWIDTH 0x700 #define AI_IOSTATUSWIDTH 0x704 #define AI_RESETREADID 0x808 #define AI_RESETWRITEID 0x80c #define AI_ERRLOGCTRL 0x900 #define AI_ERRLOGDONE 0x904 #define AI_ERRLOGSTATUS 0x908 #define AI_ERRLOGADDRLO 0x90c #define AI_ERRLOGADDRHI 0x910 #define AI_ERRLOGID 0x914 #define AI_ERRLOGUSER 0x918 #define AI_ERRLOGFLAGS 0x91c #define AI_INTSTATUS 0xa00 #define AI_CONFIG 0xe00 #define AI_ITCR 0xf00 #define AI_ITIPOOBA 0xf10 #define AI_ITIPOOBB 0xf14 #define AI_ITIPOOBC 0xf18 #define AI_ITIPOOBD 0xf1c #define AI_ITIPOOBAOUT 0xf30 #define AI_ITIPOOBBOUT 0xf34 #define AI_ITIPOOBCOUT 0xf38 #define AI_ITIPOOBDOUT 0xf3c #define AI_ITOPOOBA 0xf50 #define AI_ITOPOOBB 0xf54 #define AI_ITOPOOBC 0xf58 #define AI_ITOPOOBD 0xf5c #define AI_ITOPOOBAIN 0xf70 #define AI_ITOPOOBBIN 0xf74 #define AI_ITOPOOBCIN 0xf78 #define AI_ITOPOOBDIN 0xf7c #define AI_ITOPRESET 0xf90 #define AI_PERIPHERIALID4 0xfd0 #define AI_PERIPHERIALID5 0xfd4 #define AI_PERIPHERIALID6 0xfd8 #define AI_PERIPHERIALID7 0xfdc #define AI_PERIPHERIALID0 0xfe0 #define AI_PERIPHERIALID1 0xfe4 #define AI_PERIPHERIALID2 0xfe8 #define AI_PERIPHERIALID3 0xfec #define AI_COMPONENTID0 0xff0 #define AI_COMPONENTID1 0xff4 #define AI_COMPONENTID2 0xff8 #define AI_COMPONENTID3 0xffc /* resetctrl */ #define AIRC_RESET 1 /* errlogctrl */ #define AIELC_TO_EXP_MASK 0x0000001f0 /* backplane timeout exponent */ #define AIELC_TO_EXP_SHIFT 4 #define AIELC_TO_ENAB_SHIFT 9 /* backplane timeout enable */ /* errlogdone */ #define AIELD_ERRDONE_MASK 0x3 /* errlogstatus */ #define AIELS_TIMEOUT_MASK 0x3 /* config */ #define AICFG_OOB 0x00000020 #define AICFG_IOS 0x00000010 #define AICFG_IOC 0x00000008 #define AICFG_TO 0x00000004 #define AICFG_ERRL 0x00000002 #define AICFG_RST 0x00000001 /* bit defines for AI_OOBSELOUTB74 reg */ #define OOB_SEL_OUTEN_B_5 15 #define OOB_SEL_OUTEN_B_6 23 /* AI_OOBSEL for A/B/C/D, 0-7 */ #define AI_OOBSEL_MASK 0x1F #define AI_OOBSEL_0_SHIFT 0 #define AI_OOBSEL_1_SHIFT 8 #define AI_OOBSEL_2_SHIFT 16 #define AI_OOBSEL_3_SHIFT 24 #define AI_OOBSEL_4_SHIFT 0 #define AI_OOBSEL_5_SHIFT 8 #define AI_OOBSEL_6_SHIFT 16 #define AI_OOBSEL_7_SHIFT 24 #define AI_OOBSEL_SINK_COUNT 8 #define AI_OOBSEL_SOURCE_COUNT 8 #define AI_OOBSEL_BUSLINE_COUNT 32 #define AI_IOCTRL_ENABLE_D11_PME (1 << 14) #endif /* _AIDMP_H */
XuGuohui/firmware
hal/src/duo/wiced/platform/MCU/BCM4390x/peripherals/include/aidmp.h
C
gpl-3.0
10,873
/* $Id: libxslt.c 42 2007-12-07 06:09:35Z transami $ */ /* Please see the LICENSE file for copyright and distribution information */ #include "libxslt.h" #include "libxml/xmlversion.h" VALUE cLibXSLT; VALUE cXSLT; VALUE eXSLTError; /* * Document-class: LibXSLT::XSLT * * The libxslt gem provides Ruby language bindings for GNOME's Libxslt * toolkit. It is free software, released under the MIT License. * * Using the bindings is straightforward: * * stylesheet_doc = XML::Document.file('stylesheet_file') * stylesheet = XSLT::Stylesheet.new(stylesheet_doc) * * xml_doc = XML::Document.file('xml_file') * result = stylesheet.apply(xml_doc) * * */ #ifdef RDOC_NEVER_DEFINED cLibXSLT = rb_define_module("XSLT"); #endif #if defined(_WIN32) __declspec(dllexport) #endif void Init_libxslt_ruby(void) { LIBXML_TEST_VERSION; cLibXSLT = rb_define_module("LibXSLT"); cXSLT = rb_define_module_under(cLibXSLT, "XSLT"); rb_define_const(cXSLT, "MAX_DEPTH", INT2NUM(xsltMaxDepth)); rb_define_const(cXSLT, "MAX_SORT", INT2NUM(XSLT_MAX_SORT)); rb_define_const(cXSLT, "ENGINE_VERSION", rb_str_new2(xsltEngineVersion)); rb_define_const(cXSLT, "LIBXSLT_VERSION", INT2NUM(xsltLibxsltVersion)); rb_define_const(cXSLT, "LIBXML_VERSION", INT2NUM(xsltLibxmlVersion)); rb_define_const(cXSLT, "XSLT_NAMESPACE", rb_str_new2((const char*)XSLT_NAMESPACE)); rb_define_const(cXSLT, "DEFAULT_VENDOR", rb_str_new2(XSLT_DEFAULT_VENDOR)); rb_define_const(cXSLT, "DEFAULT_VERSION", rb_str_new2(XSLT_DEFAULT_VERSION)); rb_define_const(cXSLT, "DEFAULT_URL", rb_str_new2(XSLT_DEFAULT_URL)); rb_define_const(cXSLT, "NAMESPACE_LIBXSLT", rb_str_new2((const char*)XSLT_LIBXSLT_NAMESPACE)); rb_define_const(cXSLT, "NAMESPACE_NORM_SAXON", rb_str_new2((const char*)XSLT_NORM_SAXON_NAMESPACE)); rb_define_const(cXSLT, "NAMESPACE_SAXON", rb_str_new2((const char*)XSLT_SAXON_NAMESPACE)); rb_define_const(cXSLT, "NAMESPACE_XT", rb_str_new2((const char*)XSLT_XT_NAMESPACE)); rb_define_const(cXSLT, "NAMESPACE_XALAN", rb_str_new2((const char*)XSLT_XALAN_NAMESPACE)); eXSLTError = rb_define_class_under(cLibXSLT, "XSLTError", rb_eRuntimeError); ruby_init_xslt_stylesheet(); /* Now load exslt. */ exsltRegisterAll(); }
petrsigut/unico
vendor/gems/libxslt-ruby-0.9.2/ext/libxslt/libxslt.c
C
gpl-3.0
2,244
/*---------------------------------------------------------------------------*\ ========= | \\ / F ield | OpenFOAM: The Open Source CFD Toolbox \\ / O peration | \\ / A nd | Copyright (C) 2008-2010 OpenCFD Ltd. \\/ M anipulation | ------------------------------------------------------------------------------- License This file is part of OpenFOAM. OpenFOAM is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. OpenFOAM is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with OpenFOAM. If not, see <http://www.gnu.org/licenses/>. Class Foam::LocalInteraction Description Patch interaction specified on a patch-by-patch basis \*---------------------------------------------------------------------------*/ #ifndef LocalInteraction_H #define LocalInteraction_H #include "PatchInteractionModel.H" #include "patchInteractionData.H" // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // namespace Foam { /*---------------------------------------------------------------------------*\ Class LocalInteraction Declaration \*---------------------------------------------------------------------------*/ template<class CloudType> class LocalInteraction : public PatchInteractionModel<CloudType> { // Private data //- List of participating patches const List<patchInteractionData> patchData_; //- List of participating patch ids List<label> patchIds_; // Private member functions //- Returns local patchI if patch is in patchIds_ list label applyToPatch(const label globalPatchI) const; public: //- Runtime type information TypeName("LocalInteraction"); // Constructors //- Construct from dictionary LocalInteraction(const dictionary& dict, CloudType& cloud); //- Destructor virtual ~LocalInteraction(); // Member Functions //- Flag to indicate whether model activates patch interaction model virtual bool active() const; //- Apply velocity correction // Returns true if particle remains in same cell virtual bool correct ( const polyPatch& pp, const label faceId, bool& keepParticle, bool& active, vector& U ) const; }; // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // } // End namespace Foam // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // #ifdef NoRepository # include "LocalInteraction.C" #endif // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // #endif // ************************************************************************* //
OpenCFD/OpenFOAM-1.7.x
src/lagrangian/intermediate/submodels/Kinematic/PatchInteractionModel/LocalInteraction/LocalInteraction.H
C++
gpl-3.0
3,267
///////////////////////////////////////////////////////////////////////////// // // Project ProjectForge Community Edition // www.projectforge.org // // Copyright (C) 2001-2014 Kai Reinhard ([email protected]) // // ProjectForge is dual-licensed. // // This community edition is free software; you can redistribute it and/or // modify it under the terms of the GNU General Public License as published // by the Free Software Foundation; version 3 of the License. // // This community edition is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General // Public License for more details. // // You should have received a copy of the GNU General Public License along // with this program; if not, see http://www.gnu.org/licenses/. // ///////////////////////////////////////////////////////////////////////////// package org.projectforge.plugins.skillmatrix; import java.io.Serializable; import org.apache.log4j.Logger; import org.apache.wicket.model.Model; import org.apache.wicket.spring.injection.annot.SpringBean; import org.projectforge.user.PFUserDO; import org.projectforge.web.user.UserSelectPanel; import org.projectforge.web.wicket.AbstractListForm; import org.projectforge.web.wicket.bootstrap.GridSize; import org.projectforge.web.wicket.flowlayout.FieldsetPanel; /** * The list formular for the list view. * @author Werner Feder ([email protected]) */ public class TrainingAttendeeListForm extends AbstractListForm<TrainingAttendeeFilter, TrainingAttendeeListPage> implements Serializable { private static final long serialVersionUID = 314512845221133499L; private static final Logger log = Logger.getLogger(TrainingAttendeeListForm.class); @SpringBean(name = "trainingDao") private TrainingDao trainingDao; @SpringBean(name = "skillDao") private SkillDao skillDao; /** * @param parentPage */ public TrainingAttendeeListForm(final TrainingAttendeeListPage parentPage) { super(parentPage); } @SuppressWarnings("serial") @Override protected void init() { super.init(); gridBuilder.newSplitPanel(GridSize.COL33); { // Training final FieldsetPanel fs = gridBuilder.newFieldset(getString("plugins.skillmatrix.skilltraining.training")); final TrainingSelectPanel trainingSelectPanel = new TrainingSelectPanel(fs.newChildId(), new Model<TrainingDO>() { @Override public TrainingDO getObject() { return trainingDao.getById(getSearchFilter().getTrainingId()); } @Override public void setObject(final TrainingDO object) { if (object == null) { getSearchFilter().setTrainingId(null); } else { getSearchFilter().setTrainingId(object.getId()); } } }, parentPage, "trainingId"); fs.add(trainingSelectPanel); trainingSelectPanel.setDefaultFormProcessing(false); trainingSelectPanel.init().withAutoSubmit(true); } gridBuilder.newSplitPanel(GridSize.COL66); { // Attendee final FieldsetPanel fs = gridBuilder.newFieldset(getString("plugins.skillmatrix.skilltraining.attendee.menu")); final UserSelectPanel attendeeSelectPanel = new UserSelectPanel(fs.newChildId(), new Model<PFUserDO>() { @Override public PFUserDO getObject() { return userGroupCache.getUser(getSearchFilter().getAttendeeId()); } @Override public void setObject(final PFUserDO object) { if (object == null) { getSearchFilter().setAttendeeId(null); } else { getSearchFilter().setAttendeeId(object.getId()); } } }, parentPage, "attendeeId"); fs.add(attendeeSelectPanel); attendeeSelectPanel.setDefaultFormProcessing(false); attendeeSelectPanel.init().withAutoSubmit(true); } } /** * @see org.projectforge.web.wicket.AbstractListForm#newSearchFilterInstance() */ @Override protected TrainingAttendeeFilter newSearchFilterInstance() { return new TrainingAttendeeFilter(); } /** * @see org.projectforge.web.wicket.AbstractListForm#getLogger() */ @Override protected Logger getLogger() { return log; } }
linqingyicen/projectforge-webapp
src/main/java/org/projectforge/plugins/skillmatrix/TrainingAttendeeListForm.java
Java
gpl-3.0
4,396
#ifndef _NEONTEST_H #define _NEONTEST_H void neontest(); #endif
Tsunamical/nds4droid
app/src/main/jni/desmume/src/android/neontest.h
C
gpl-3.0
70
<p> navigation works! </p>
iproduct/course-angular2
05-ng2-components/src/app/core/navigation/navigation.component.html
HTML
gpl-3.0
28
package com.service.model; import javax.xml.bind.annotation.XmlRootElement; @XmlRootElement public class RestObject { private int id; private String value; public int getId() { return id; } public void setId(int id) { this.id = id; } public String getValue() { return value; } public void setValue(String value) { this.value = value; } }
hacktheworldguys/hacktheworld
RestExample/src/com/service/model/RestObject.java
Java
gpl-3.0
389
# -*- 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 os from collections import OrderedDict import pytest BAD_FINDER_PATHS = [ "lang/foo.<ext>", "<language_code>/<foo>.<ext>", "<language_code>/foo.po", "../<language_code>/foo.<ext>", "<language_code>/../foo.<ext>", "<language_code>/..", "foo/@<language_code>/bar.<ext>"] ROOT_PATHS = OrderedDict() ROOT_PATHS["<language_code>.<ext>"] = "" ROOT_PATHS["foo/<language_code>.<ext>"] = "foo" ROOT_PATHS["foo/bar/baz-<filename>-<language_code>.<ext>"] = "foo/bar" MATCHES = OrderedDict() MATCHES["po/<language_code>.<ext>"] = ( ["en.po", "foo/bar/en.po"], [("po/en.po", dict(language_code="en", ext="po"))]) MATCHES["po-<filename>/<language_code>.<ext>"] = ( ["en.po", "po/en.po"], [("po-foo/en.po", dict(language_code="en", filename="foo", ext="po"))]) MATCHES["po/<filename>-<language_code>.<ext>"] = ( ["en.po", "po/en.po"], [("po/foo-en.po", dict(language_code="en", filename="foo", ext="po"))]) MATCHES["<language_code>/<dir_path>/<filename>.<ext>"] = ( ["foo.po"], [("en/foo.po", dict(language_code="en", dir_path="", filename="foo", ext="po")), ("en/foo.pot", dict(language_code="en", dir_path="", filename="foo", ext="pot")), ("en/bar/baz/foo.po", dict(language_code="en", dir_path="bar/baz", filename="foo", ext="po"))]) MATCHES["<dir_path>/<language_code>/<filename>.<ext>"] = ( ["foo.po", "en/foo.poo"], [("en/foo.po", dict(language_code="en", dir_path="", filename="foo", ext="po")), ("en/foo.pot", dict(language_code="en", dir_path="", filename="foo", ext="pot")), ("bar/baz/en/foo.po", dict(language_code="en", dir_path="bar/baz", filename="foo", ext="po"))]) FINDER_REGEXES = [ "<language_code>.<ext>", "<language_code>/<filename>.<ext>", "<dir_path>/<language_code>.<ext>", "<language_code><dir_path>/<filename>.<ext>"] FILES = OrderedDict() FILES["gnu_style/po/<language_code>.<ext>"] = ( ("gnu_style/po/language0.po", dict(language_code="language0", ext="po", filename="language0", dir_path="")), ("gnu_style/po/language1.po", dict(language_code="language1", ext="po", filename="language1", dir_path=""))) FILES["gnu_style_named_files/po/<filename>-<language_code>.<ext>"] = ( ("gnu_style_named_files/po/example1-language1.po", dict(language_code="language1", filename="example1", ext="po", dir_path="")), ("gnu_style_named_files/po/example1-language0.po", dict(language_code="language0", filename="example1", ext="po", dir_path="")), ("gnu_style_named_files/po/example2-language1.po", dict(language_code="language1", filename="example2", ext="po", dir_path="")), ("gnu_style_named_files/po/example2-language0.po", dict(language_code="language0", filename="example2", ext="po", dir_path=""))) FILES["gnu_style_named_folders/po-<filename>/<language_code>.<ext>"] = ( ("gnu_style_named_folders/po-example1/language1.po", dict(language_code="language1", filename="example1", ext="po", dir_path="")), ("gnu_style_named_folders/po-example1/language0.po", dict(language_code="language0", filename="example1", ext="po", dir_path="")), ("gnu_style_named_folders/po-example2/language1.po", dict(language_code="language1", filename="example2", ext="po", dir_path="")), ("gnu_style_named_folders/po-example2/language0.po", dict(language_code="language0", filename="example2", ext="po", dir_path=""))) FILES["non_gnu_style/locales/<language_code>/<dir_path>/<filename>.<ext>"] = ( ("non_gnu_style/locales/language1/example1.po", dict(language_code=u"language1", filename=u"example1", ext=u"po", dir_path=u"")), ("non_gnu_style/locales/language0/example1.po", dict(language_code=u"language0", filename=u"example1", ext=u"po", dir_path=u"")), ("non_gnu_style/locales/language1/example2.po", dict(language_code=u"language1", filename=u"example2", ext=u"po", dir_path=u"")), ("non_gnu_style/locales/language0/example2.po", dict(language_code=u"language0", filename=u"example2", ext=u"po", dir_path=u"")), ("non_gnu_style/locales/language1/subsubdir/example3.po", dict(language_code=u"language1", filename=u"example3", ext=u"po", dir_path=u"subsubdir")), ("non_gnu_style/locales/language0/subsubdir/example3.po", dict(language_code=u"language0", filename=u"example3", ext=u"po", dir_path=u"subsubdir")), ("non_gnu_style/locales/language1/subsubdir/example4.po", dict(language_code=u"language1", filename=u"example4", ext=u"po", dir_path=u"subsubdir")), ("non_gnu_style/locales/language0/subsubdir/example4.po", dict(language_code=u"language0", filename=u"example4", ext=u"po", dir_path=u"subsubdir"))) @pytest.fixture(params=FINDER_REGEXES) def finder_regexes(request): return request.param @pytest.fixture(params=BAD_FINDER_PATHS) def bad_finder_paths(request): return request.param @pytest.fixture(params=FILES.keys()) def finder_files(request): return request.param, FILES[request.param] @pytest.fixture def fs_finder(test_fs, finder_files): from pootle_fs.finder import TranslationFileFinder translation_path, expected = finder_files test_filepath = test_fs.path("data/fs/example_fs") finder = TranslationFileFinder( os.path.join( test_filepath, translation_path)) expected = [ (os.path.join(test_filepath, path), parsed) for path, parsed in expected] return finder, expected @pytest.fixture(params=MATCHES.keys()) def finder_matches(request): return [request.param] + list(MATCHES[request.param]) @pytest.fixture(params=ROOT_PATHS.keys()) def finder_root_paths(request): return request.param, ROOT_PATHS[request.param]
Finntack/pootle
pytest_pootle/fixtures/pootle_fs/finder.py
Python
gpl-3.0
6,563
#region License // Copyright (c) 2013, ClearCanvas Inc. // All rights reserved. // http://www.ClearCanvas.ca // // This file is part of the ClearCanvas RIS/PACS open source project. // // The ClearCanvas RIS/PACS open source project is free software: you can // redistribute it and/or modify it under the terms of the GNU General Public // License as published by the Free Software Foundation, either version 3 of the // License, or (at your option) any later version. // // The ClearCanvas RIS/PACS open source project is distributed in the hope that it // will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General // Public License for more details. // // You should have received a copy of the GNU General Public License along with // the ClearCanvas RIS/PACS open source project. If not, see // <http://www.gnu.org/licenses/>. #endregion using Macro.Common; using Macro.ImageServer.Model; namespace Macro.ImageServer.Rules.OnlineRetentionAction { [ExtensionOf(typeof(SampleRuleExtensionPoint))] public class SimpleOnlineRetention : SampleRuleBase { public SimpleOnlineRetention() : base("SimpleOnlineRetention", "Simple Online Retention", ServerRuleTypeEnum.OnlineRetention, "Sample_OnlineRetentionSimple.xml") { ApplyTimeList.Add(ServerRuleApplyTimeEnum.StudyArchived); ApplyTimeList.Add(ServerRuleApplyTimeEnum.StudyRestored); } } }
mayioit/MacroMedicalSystem
ImageServer/Rules/OnlineRetentionAction/Sample_OnlineRetention.cs
C#
gpl-3.0
1,482
# Area Rating Creates areas on the map that have an associate rating value which changes based on actions taken in those areas.
tbeswick96/UKSF-SR5-7-11
addons/arearating/README.md
Markdown
gpl-3.0
129
/* * Copyright 2014 Ryan Jones * Copyright 2010 Giesecke & Devrient GmbH. * * This file was modified from the original source: * https://code.google.com/p/seek-for-android/ * * This file is part of smartcard-reader, package org.docrj.smartcard.reader. * * smartcard-reader 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. * * smartcard-reader 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 smartcard-reader. If not, see <http://www.gnu.org/licenses/>. */ package org.docrj.smartcard.iso7816; import java.security.AccessControlException; public class ResponseApdu { protected int mSw1 = 0x00; protected int mSw2 = 0x00; protected byte[] mData = new byte[0]; protected byte[] mBytes = new byte[0]; public ResponseApdu(byte[] respApdu) { if (respApdu.length < 2) { return; } if (respApdu.length > 2) { mData = new byte[respApdu.length - 2]; System.arraycopy(respApdu, 0, mData, 0, respApdu.length - 2); } mSw1 = 0x00FF & respApdu[respApdu.length - 2]; mSw2 = 0x00FF & respApdu[respApdu.length - 1]; mBytes = respApdu; } public int getSW1() { return mSw1; } public int getSW2() { return mSw2; } public int getSW1SW2() { return (mSw1 << 8) | mSw2; } public byte[] getData() { return mData; } public byte[] toBytes() { return mBytes; } public void checkLengthAndStatus(int length, int sw1sw2, String message) throws AccessControlException { if (getSW1SW2() != sw1sw2 || mData.length != length) { throw new AccessControlException("ResponseApdu is wrong at " + message); } } public void checkLengthAndStatus(int length, int[] sw1sw2List, String message) throws AccessControlException { if (mData.length != length) { throw new AccessControlException("ResponseApdu is wrong at " + message); } for (int sw1sw2 : sw1sw2List) { if (getSW1SW2() == sw1sw2) { return; // sw1sw2 matches => return } } throw new AccessControlException("ResponseApdu is wrong at " + message); } public void checkStatus(int[] sw1sw2List, String message) throws AccessControlException { for (int sw1sw2 : sw1sw2List) { if (getSW1SW2() == sw1sw2) { return; // sw1sw2 matches => return } } throw new AccessControlException("ResponseApdu is wrong at " + message); } public void checkStatus(int sw1sw2, String message) throws AccessControlException { if (getSW1SW2() != sw1sw2) { throw new AccessControlException("ResponseApdu is wrong at " + message); } } public boolean isStatus(int sw1sw2) { if (getSW1SW2() == sw1sw2) { return true; } else { return false; } } }
danieldizzy/smartcard-reader
app/src/main/java/org/docrj/smartcard/iso7816/ResponseApdu.java
Java
gpl-3.0
3,521
url: http://sanskrit.jnu.ac.in/sandhi/viccheda.jsp?itext=जोशिनो गृहवाटिकाया<html> <title>Sanskrit Sandhi Splitter at J.N.U. New Delhi</title> <META CONTENT='text/hetml CHARSET=UTF-8' HTTP-EQUIV='Content-Type'/> <META NAME="Author" CONTENT="Dr. Girish Nath Jha"> <META NAME="Keywords" CONTENT="Dr. Girish Nath Jha, Sachin, Diwakar Mishra, Sanskrit Computational Linguistics, Sanskrit informatics, Sanskrit computing, Sanskrit language processing, Sanskrit and computer, computer processing of sanskrit, subanta, tinanta, POS tagger, tagset, Indian languages, linguistics, amarakosha, amarakosa, Indian tradition, Indian heritage, Machine translation, AI, MT divergence, Sandhi, kridanta, taddhita, e-learning, corpus, etext, e-text, Sanskrit blog, Panini, Bhartrhari, Bhartrihari, Patanjali, karaka, mahabharata, ashtadhyayi, astadhyayi, indexer, indexing, lexical resources, Sanskrit, thesaurus, samasa, gender analysis in Sanskrit, Hindi, saHiT, language technology, NLP"> <META NAME="Description" CONTENT="Dr. Girish Nath Jha, Sachin, Diwakar Mishra, Sanskrit Computational Linguistics, Sanskrit informatics, Sanskrit computing, Sanskrit language processing, Sanskrit and computer, computer processing of sanskrit, subanta, tinanta, POS tagger, tagset, Indian languages, linguistics, amarakosha, amarakosa, Indian tradition, Indian heritage, Machine translation, AI, MT divergence, Sandhi, kridanta, taddhita, e-learning, corpus, etext, e-text, Sanskrit blog, Panini, Bhartrhari, Bhartrihari, Patanjali, karaka, mahabharata, ashtadhyayi, astadhyayi, indexer, indexing, lexical resources, Sanskrit, thesaurus, samasa, gender analysis in Sanskrit, Hindi, saHiT, language technology, NLP"> <head> <head> <style> <!-- div.Section1 {page:Section1;} --> </style> <head> <meta http-equiv=Content-Type content="text/html; charset=utf-8"> <script language="JavaScript" src=../js/menuitems.js></script> <script language="JavaScript" src="../js/mm_menu.js"></script> <meta name=Author content="Dr. Girish Nath Jha, JNU, New Delhi"> </head> <body lang=EN-US link=blue vlink=blue style='tab-interval:.5in'> <div class=Section1> <div align=center> <table border=1 cellspacing=0 cellpadding=0 width=802 style='width:601.5pt; border-collapse:collapse;border:none;mso-border-alt:outset navy .75pt'> <tr> <td width=800 style='width:600.0pt;border:inset navy .75pt;padding:.75pt .75pt .75pt .75pt'> <script language="JavaScript1.2">mmLoadMenus();</script> <img width=800 height=130 id="_x0000_i1028" src="../images/header1.jpg" border=0> </td> </tr> <tr> <td width=818 style='width:613.5pt;border:inset navy .75pt;border-top:none; mso-border-top-alt:inset navy .75pt;padding:.75pt .75pt .75pt .75pt'> <p align="center"><a href="../"><span style='text-decoration:none;text-underline: none'><img border=1 width=49 height=26 id="_x0000_i1037" src="../images/backtohome.jpg"></span></a><span style='text-underline: none'> </span><a href="javascript:;" onmouseover="MM_showMenu(window.mm_menu_0821171051_0,6,29,null,'image2')" onmouseout="MM_startTimeout();"><span style='text-decoration:none;text-underline: none'><img border=1 id=image2 src="../images/lang_tool.jpg" name=image2 width="192" height="25"></span></a><span style='text-underline: none'> </span><a href="javascript:;" onmouseover="MM_showMenu(window.mm_menu_0821171909_0,6,29,null,'image3')" onmouseout="MM_startTimeout();"><span style='text-decoration:none;text-underline: none'><img border=1 id=image3 src="../images/lexical.jpg" name=image3 width="137" height="25"></span></a><span style='text-underline: none'> </span><a href="javascript:;" onmouseover="MM_showMenu(window.mm_menu_0821171609_0,6,29,null,'image1')" onmouseout="MM_startTimeout();"><span style='text-decoration:none;text-underline: none'><img border=1 id=image1 src="../images/elearning.jpg" name=image1 width="77" height="25"></span></a><span style='text-underline: none'> </span><a href="javascript:;" onmouseover="MM_showMenu(window.mm_menu_0821171809_0,6,29,null,'image4')" onmouseout="MM_startTimeout();"><span style='text-decoration:none;text-underline: none'><img border=1 id=image4 src="../images/corpora.jpg" name=image4 width="105" height="26"></span></a><span style='text-underline: none'> </span><a href="javascript:;" onmouseover="MM_showMenu(window.mm_menu_0821171709_0,6,29,null,'image5')" onmouseout="MM_startTimeout();"><span style='text-decoration:none;text-underline: none'><img border=1 id=image5 src="../images/rstudents.jpg" name=image5 width="125" height="26"></span></a><span style='text-underline: none'> </span> <a href="javascript:;" onmouseover="MM_showMenu(window.mm_menu_0821171409_0,6,29,null,'image6')" onmouseout="MM_startTimeout();"><span style='text-decoration:none;text-underline: none'><img border=1 id=image6 src="../images/feedback.jpg" name=image6 width="80" height="25"></span></a><span style='text-underline: none'> </span> <!--- <a href="../user/feedback.jsp"><img border="1" src="../images/feedback.jpg" width="80" height="25"></a> ---> </td> </tr> <tr> <td width="800"> <p align="center"><font color="#FF9933"><span style='font-size:18.0pt; '><b>Sanskrit Sandhi Recognizer and Analyzer</b></span></font></p> The Sanskrit sandhi splitter (VOWEL SANDHI) was developed as part of M.Phil. research by <a href="mailto:[email protected]">Sachin Kumar</a> (M.Phil. 2005-2007), and <a href=mailto:[email protected]>Diwakar Mishra</a> (M.Phil. 2007-2009) under the supervision of <a href=http://www.jnu.ac.in/faculty/gnjha>Dr. Girish Nath Jha</a>. The coding for this application has been done by Dr. Girish Nath Jha and Diwakar Mishra. <!---Please send feedback to to <a href="mailto:[email protected]">Dr. Girish Nath Jha</A>--->The Devanagari input mechanism has been developed in Javascript by Satyendra Kumar Chaube, Dr. Girish Nath Jha and Dharm Singh Rathore. </center> <table border=0 width=100%> <tr> <td valign=top width=48%> <table> <tr> <td> <FORM METHOD=get ACTION=viccheda.jsp#results name="iform" accept-Charset="UTF-8"> <font size=2><b>Enter Sanskrit text for sandhi processing (संधि-विच्छेद हेतु पाठ्य दें) using adjacent keyboard OR Use our inbuilt <a href=../js/itrans.html target=_blank>iTRANS</a>-Devanagari unicode converter for fast typing<br> <a href=sandhitest.txt>examples</a> <TEXTAREA name=itext COLS=40 ROWS=9 onkeypress=checkKeycode(event) onkeyup=iu()> जोशिनो गृहवाटिकाया</TEXTAREA> </td> </tr> <tr> <td> <font color=red size=2>Run in debug mode</font> <input type=checkbox name="debug" value="ON"> <br> <input type=submit value="Click to sandhi-split (संधि-विच्छेद करें)"></span><br> </td> </tr> </table> </td> <td valign=top width=52%> <table> <tr> <td> <head> <SCRIPT language=JavaScript src="../js/devkb.js"></SCRIPT> <head> <TEXTAREA name=itrans rows=5 cols=10 style="display:none"></TEXTAREA> <INPUT name=lastChar type=hidden> <table border=2 style="background-color:#fff;"> <tbody> <tr > <td> <input type=button name="btn" style="width: 24px" value="&#x0905;" onClick="keyboard(this.value)"> <input type=button name="btn" style="width: 24px" value="&#x0906;" onClick="keyboard(this.value)"> <input type=button name="btn" style="width: 24px" value="&#x0907;" onClick="keyboard(this.value)"> <input type=button name="btn" style="width: 24px" value="&#x0908;" onClick="keyboard(this.value)"> <input type=button name="btn" style="width: 24px" value="&#x0909;" onClick="keyboard(this.value)"> <input type=button name="btn" style="width: 24px" value="&#x090A;" onClick="keyboard(this.value)"> <input type=button name="btn" style="width: 24px" value="&#x090F;" onClick="keyboard(this.value)"> <input type=button name="btn" style="width: 24px" value="&#x0910;" onClick="keyboard(this.value)"> <input type=button name="btn" style="width: 24px" value="&#x0913;" onClick="keyboard(this.value)"> <input type=button name="btn" style="width: 24px" value="&#x0914;" onClick="keyboard(this.value)"> <input type=button name="btn" style="width: 24px" value="&#x0905;&#x0902;" onClick="keyboard(this.value)"> <input type=button name="btn" style="width: 24px" value="&#x0905;&#x0903;" onClick="keyboard(this.value)"> <input type=button name="btn" style="width: 24px" value="&#x090D;" onClick="keyboard(this.value)"> <input type=button name="btn" style="width: 24px" value="&#x0911;" onClick="keyboard(this.value)"> </td> </tr> <tr> <td> <input type=button name="btn" style="width: 24px" value="&#x094D;" onClick="keyboard(this.value)"> <input type=button name="btn" style="width: 24px" value="&#x093E;" onClick="keyboard(this.value)"> <input type=button name="btn" style="width: 24px" value="&#x093F;" onClick="keyboard(this.value)"> <input type=button name="btn" style="width: 24px" value="&#x0940;" onClick="keyboard(this.value)"> <input type=button name="btn" style="width: 24px" value="&#x0941;" onClick="keyboard(this.value)"> <input type=button name="btn" style="width: 24px" value="&#x0942;" onClick="keyboard(this.value)"> <input type=button name="btn" style="width: 24px" value="&#x0947;" onClick="keyboard(this.value)"> <input type=button name="btn" style="width: 24px" value="&#x0948;" onClick="keyboard(this.value)"> <input type=button name="btn" style="width: 24px" value="&#x094B;" onClick="keyboard(this.value)"> <input type=button name="btn" style="width: 24px" value="&#x094C;" onClick="keyboard(this.value)"> <input type=button name="btn" style="width: 24px" value="&#x0902;" onClick="keyboard(this.value)"> <input type=button name="btn" style="width: 24px" value="&#x0903;" onClick="keyboard(this.value)"> <input type=button name="btn" style="width: 24px" value="&#x0945;" onClick="keyboard(this.value)"> <input type=button name="btn" style="width: 24px" value="&#x0949;" onClick="keyboard(this.value)"> </td> </tr> <tr> <td> <input type=button name="btn" style="width: 24px" value="&#x0915;" onClick="keyboard(this.value)"> <input type=button name="btn" style="width: 24px" value="&#x0916;" onClick="keyboard(this.value)"> <input type=button name="btn" style="width: 24px" value="&#x0917;" onClick="keyboard(this.value)"> <input type=button name="btn" style="width: 24px" value="&#x0918;" onClick="keyboard(this.value)"> <input type=button name="btn" style="width: 24px" value="&#x0919;" onClick="keyboard(this.value)"> <input type=button name="btn" style="width: 24px" value="&#x091A;" onClick="keyboard(this.value)"> <input type=button name="btn" style="width: 24px" value="&#x091B;" onClick="keyboard(this.value)"> <input type=button name="btn" style="width: 24px" value="&#x091C;" onClick="keyboard(this.value)"> <input type=button name="btn" style="width: 24px" value="&#x091D;" onClick="keyboard(this.value)"> <input type=button name="btn" style="width: 24px" value="&#x091E;" onClick="keyboard(this.value)"> <input type=button name="btn" style="width: 100px" value="Backspace" onClick="BackSpace()"> </td> </tr> <tr> <td> <input type=button name="btn" style="width: 24px" value="+" onClick="keyboard(this.value)"> <input type=button name="btn" style="width: 24px" value="&#x091F;" onClick="keyboard(this.value)"> <input type=button name="btn" style="width: 24px" value="&#x0920;" onClick="keyboard(this.value)"> <input type=button name="btn" style="width: 24px" value="&#x0921;" onClick="keyboard(this.value)"> <input type=button name="btn" style="width: 24px" value="&#x0922;" onClick="keyboard(this.value)"> <input type=button name="btn" style="width: 24px" value="&#x0923;" onClick="keyboard(this.value)"> <input type=button name="btn" style="width: 24px" value=""> <input type=button name="btn" style="width: 24px" value=""> <input type=button name="btn" style="width: 24px" value=""> <input type=button name="btn" style="width: 24px" value="&#x0924;" onClick="keyboard(this.value)"> <input type=button name="btn" style="width: 24px" value="&#x0925;" onClick="keyboard(this.value)"> <input type=button name="btn" style="width: 24px" value="&#x0926;" onClick="keyboard(this.value)"> <input type=button name="btn" style="width: 24px" value="&#x0927;" onClick="keyboard(this.value)"> <input type=button name="btn" style="width: 24px" value="&#x0928;" onClick="keyboard(this.value)"> </td> </tr> <tr> <td> <input type=button name="btn" style="width: 24px" value="/" onClick="keyboard(this.value)"> <input type=button name="btn" style="width: 24px" value="&#x092A;" onClick="keyboard(this.value)"> <input type=button name="btn" style="width: 24px" value="&#x092B;" onClick="keyboard(this.value)"> <input type=button name="btn" style="width: 24px" value="&#x092C;" onClick="keyboard(this.value)"> <input type=button name="btn" style="width: 24px" value="&#x092D;" onClick="keyboard(this.value)"> <input type=button name="btn" style="width: 24px" value="&#x092E;" onClick="keyboard(this.value)"> <input type=button name="btn" style="width: 24px" value=""> <input type=button name="btn" style="width: 24px" value=""> <input type=button name="btn" style="width: 24px" value=""> <input type=button name="btn" style="width: 24px" value="&#x092F;" onClick="keyboard(this.value)"> <input type=button name="btn" style="width: 24px" value="&#x0930;" onClick="keyboard(this.value)"> <input type=button name="btn" style="width: 24px" value="&#x0932;" onClick="keyboard(this.value)"> <input type=button name="btn" style="width: 24px" value="&#x0935;" onClick="keyboard(this.value)"> <input type=button name="btn" style="width: 24px" value="&#x0964;" onClick="keyboard(this.value)"> </td> </tr> <tr> <td> <input type=button name="btn" style="width: 24px" value="*" onClick="keyboard(this.value)"> <input type=button name="btn" style="width: 24px" value="&#x0936;" onClick="keyboard(this.value)"> <input type=button name="btn" style="width: 24px" value="&#x0937;" onClick="keyboard(this.value)"> <input type=button name="btn" style="width: 24px" value="&#x0938;" onClick="keyboard(this.value)"> <input type=button name="btn" style="width: 24px" value=""> <input type=button name="btn" style="width: 24px" value="&#x090B;" onClick="keyboard(this.value)"> <input type=button name="btn" style="width: 24px" value="&#x090C;" onClick="keyboard(this.value)"> <input type=button name="btn" style="width: 24px" value="&#x0943;" onClick="keyboard(this.value)"> <input type=button name="btn" style="width: 24px" value="&#x0944;" onClick="keyboard(this.value)"> <input type=button name="btn" style="width: 24px" value=""> <input type=button name="btn" style="width: 24px" value=""> <input type=button name="btn" style="width: 24px" value="&#x0939;" onClick="keyboard(this.value)"> <input type=button name="btn" style="width: 24px" value=""> <input type=button name="btn" style="width: 24px" value="&#x0965;" onClick="keyboard(this.value)"> </td> </tr> <tr> <td> <input type=button name="btn" style="width: 24px" value="&#x0924;&#x094D;&#x0930;" onClick="keyboard(this.value)"> <input type=button name="btn" style="width: 24px" value="&#x091C;&#x094D;&#x091E;" onClick="keyboard(this.value)"> <input type=button name="btn" style="width: 24px" value="&#x0915;&#x094D;&#x0937;" onClick="keyboard(this.value)"> <input type=button name="btn" style="width: 24px" value="&#x0936;&#x094D;&#x0930;" onClick="keyboard(this.value)"> <input type=button name="btn" style="width: 200px" value="Space Bar" onClick="Space()"> <input type=button name="btn" style="width: 24px" value="&#x0901;" onClick="keyboard(this.value)"> <input type=button name="btn" style="width: 24px" value="&#x093C;" onClick="keyboard(this.value)"> </td> </tr> </tbody> </table> </td> </tr> </table> </td> </tr> <tr> </table> </form> <a name=results> <font size=4><b><u>Results</u></b></font> <br> गृहवाटिकाे अा (अयादिसन्धि एचोऽयवायावः)<br> गृहवाटिकाी अा (यण् सन्धि इको यणचि)<br> गृहवाटिकाि अा (यण् सन्धि इको यणचि)<br> <br> <font color=red> <br> <hr> <br> </body> </html>
sanskritiitd/sanskrit
uohCorpus.fil/uoh/uoh.filteredcorpus.txt_output/Aakhyanvallari_ext.txt.out.dict_1959_jnu.html
HTML
gpl-3.0
16,881
/* * Copyright (c) 2015, 2018, Oracle and/or its affiliates. All rights reserved. * * This program is free software; you can redistribute it and/or modify it under * the terms of the GNU General Public License, version 2.0, as published by the * Free Software Foundation. * * This program is also distributed with certain software (including but not * limited to OpenSSL) that is licensed under separate terms, as designated in a * particular file or component or in included license documentation. The * authors of MySQL hereby grant you an additional permission to link the * program and your derivative works with the separately licensed software that * they have included with MySQL. * * Without limiting anything contained in the foregoing, this file, which is * part of MySQL Connector/J, is also subject to the Universal FOSS Exception, * version 1.0, a copy of which can be found at * http://oss.oracle.com/licenses/universal-foss-exception. * * 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, version 2.0, * for more details. * * You should have received a copy of the GNU General Public License along with * this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ package com.mysql.cj.xdevapi; import java.util.Iterator; /** * Base result. */ public interface Result { /** * Get the count of affected items from manipulation statements. * * @return count */ long getAffectedItemsCount(); /** * Count of warnings generated during statement execution. * * @return count */ int getWarningsCount(); /** * Warnings generated during statement execution. * * @return iterator over warnings */ Iterator<Warning> getWarnings(); }
ac2cz/FoxTelem
lib/mysql-connector-java-8.0.13/src/main/user-api/java/com/mysql/cj/xdevapi/Result.java
Java
gpl-3.0
1,996
/* This file is part of the db4o object database http://www.db4o.com Copyright (C) 2004 - 2011 Versant Corporation http://www.versant.com db4o is free software; you can redistribute it and/or modify it under the terms of version 3 of the GNU General Public License as published by the Free Software Foundation. db4o 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/. */ using Db4objects.Db4o.Ext; using Db4oUnit; using Db4oUnit.Mocking; namespace Db4objects.Db4o.Tests.Common.TA { public class ActivatableTestCase : TransparentActivationTestCaseBase { public static void Main(string[] args) { new ActivatableTestCase().RunAll(); } public virtual void TestActivatorIsBoundUponStore() { var mock = StoreNewMock(); AssertSingleBindCall(mock); } /// <exception cref="System.Exception"></exception> public virtual void TestActivatorIsBoundUponRetrieval() { StoreNewMock(); Reopen(); AssertSingleBindCall(RetrieveMock()); } /// <exception cref="System.Exception"></exception> public virtual void TestActivatorIsUnboundUponClose() { var mock = StoreNewMock(); Reopen(); AssertBindUnbindCalls(mock); } public virtual void TestUnbindingIsIsolated() { if (!IsMultiSession()) { return; } var mock1 = StoreNewMock(); Db().Commit(); var mock2 = RetrieveMockFromNewClientAndClose(); AssertBindUnbindCalls(mock2); // mock1 has only be bound by store so far // client.close should have no effect on it mock1.Recorder().Verify(new[] { new MethodCall("bind", new object[] { new _IArgumentCondition_50() }) }); } private MockActivatable RetrieveMockFromNewClientAndClose() { var client = OpenNewSession(); try { return RetrieveMock(client); } finally { client.Close(); } } private void AssertBindUnbindCalls(MockActivatable mock) { mock.Recorder().Verify(new[] { new MethodCall("bind", new[] { MethodCall .IgnoredArgument }), new MethodCall("bind", new object[] {null}) }); } private void AssertSingleBindCall(MockActivatable mock) { mock.Recorder().Verify(new[] { new MethodCall("bind", new[] { MethodCall .IgnoredArgument }) }); } private MockActivatable RetrieveMock() { return RetrieveMock(Db()); } private MockActivatable RetrieveMock(IExtObjectContainer container) { return (MockActivatable) RetrieveOnlyInstance(container, typeof ( MockActivatable)); } private MockActivatable StoreNewMock() { var mock = new MockActivatable(); Store(mock); return mock; } private sealed class _IArgumentCondition_50 : MethodCall.IArgumentCondition { public void Verify(object argument) { Assert.IsNotNull(argument); } } } }
masroore/db4o
Db4objects.Db4o.Tests/Db4objects.Db4o.Tests/Common/TA/ActivatableTestCase.cs
C#
gpl-3.0
3,985
/* Copyright (C) 2002-2013 Free Software Foundation, Inc. This file is part of the GNU C Library. Contributed by Ulrich Drepper <[email protected]>, 2002. The GNU C Library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. The GNU C Library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with the GNU C Library; if not, see <http://www.gnu.org/licenses/>. */ #include <sched.h> #include <setjmp.h> #include <signal.h> #include <stdlib.h> #include <atomic.h> #include <ldsodefs.h> #include <tls.h> #include <stdint.h> #include "kernel-features.h" #define CLONE_SIGNAL (CLONE_SIGHAND | CLONE_THREAD) /* Unless otherwise specified, the thread "register" is going to be initialized with a pointer to the TCB. */ #ifndef TLS_VALUE # define TLS_VALUE pd #endif #ifndef ARCH_CLONE # define ARCH_CLONE __clone #endif #ifndef TLS_MULTIPLE_THREADS_IN_TCB /* Pointer to the corresponding variable in libc. */ int *__libc_multiple_threads_ptr attribute_hidden; #endif struct rtprio; struct thr_param { void (*start_func)(void *); /* thread entry function. */ void *arg; /* argument for entry function. */ char *stack_base; /* stack base address. */ size_t stack_size; /* stack size. */ char *tls_base; /* tls base address. */ size_t tls_size; /* tls size. */ long *child_tid; /* address to store new TID. */ long *parent_tid; /* parent accesses the new TID here. */ int flags; /* thread flags. */ struct rtprio *rtp; /* Real-time scheduling priority */ void *spare[3]; /* TODO: cpu affinity mask etc. */ }; static int do_clone (struct pthread *pd, const struct pthread_attr *attr, int clone_flags, int (*fct) (void *), STACK_VARIABLES_PARMS, int stopped) { #ifdef PREPARE_CREATE PREPARE_CREATE; #endif struct thr_param p; if (__builtin_expect (stopped != 0, 0)) /* We make sure the thread does not run far by forcing it to get a lock. We lock it here too so that the new thread cannot continue until we tell it to. */ lll_lock (pd->lock, LLL_PRIVATE); /* One more thread. We cannot have the thread do this itself, since it might exist but not have been scheduled yet by the time we've returned and need to check the value to behave correctly. We must do it before creating the thread, in case it does get scheduled first and then might mistakenly think it was the only thread. In the failure case, we momentarily store a false value; this doesn't matter because there is no kosher thing a signal handler interrupting us right here can do that cares whether the thread count is correct. */ atomic_increment (&__nptl_nthreads); #if 0 int rc = ARCH_CLONE (fct, STACK_VARIABLES_ARGS, clone_flags, pd, &pd->tid, TLS_VALUE, &pd->tid); #else memset(&p, 0, sizeof(p)); p.start_func = fct; p.arg = pd; p.stack_base = stackaddr; /* first in STACK_VARIABLES_ARGS */ p.stack_size = stacksize; /* second in STACK_VARIABLES_ARGS */ p.tls_base = (char*)pd; p.child_tid = &(pd->ktid); int rc = INLINE_SYSCALL(thr_new, 2, &p, sizeof(p)); if (rc) { errno = rc; rc = -1;; } #endif if (__builtin_expect (rc == -1, 0)) { atomic_decrement (&__nptl_nthreads); /* Oops, we lied for a second. */ pd->ktid = 0; /* Perhaps a thread wants to change the IDs and if waiting for this stillborn thread. */ if (__builtin_expect (atomic_exchange_acq (&pd->setxid_futex, 0) == -2, 0)) lll_futex_wake (&pd->setxid_futex, 1, LLL_PRIVATE); /* Free the resources. */ __deallocate_stack (pd); /* We have to translate error codes. */ return errno == ENOMEM ? EAGAIN : errno; } #warning set scheduling parameters #if 0 /* Now we have the possibility to set scheduling parameters etc. */ if (__builtin_expect (stopped != 0, 0)) { INTERNAL_SYSCALL_DECL (err); int res = 0; /* Set the affinity mask if necessary. */ if (attr->cpuset != NULL) { res = INTERNAL_SYSCALL (sched_setaffinity, err, 3, pd->tid, attr->cpusetsize, attr->cpuset); if (__builtin_expect (INTERNAL_SYSCALL_ERROR_P (res, err), 0)) { /* The operation failed. We have to kill the thread. First send it the cancellation signal. */ INTERNAL_SYSCALL_DECL (err2); err_out: (void) INTERNAL_SYSCALL (tgkill, err2, 3, THREAD_GETMEM (THREAD_SELF, pid), pd->tid, SIGCANCEL); /* We do not free the stack here because the canceled thread itself will do this. */ return (INTERNAL_SYSCALL_ERROR_P (res, err) ? INTERNAL_SYSCALL_ERRNO (res, err) : 0); } } /* Set the scheduling parameters. */ if ((attr->flags & ATTR_FLAG_NOTINHERITSCHED) != 0) { res = INTERNAL_SYSCALL (sched_setscheduler, err, 3, pd->tid, pd->schedpolicy, &pd->schedparam); if (__builtin_expect (INTERNAL_SYSCALL_ERROR_P (res, err), 0)) goto err_out; } } #endif /* We now have for sure more than one thread. The main thread might not yet have the flag set. No need to set the global variable again if this is what we use. */ THREAD_SETMEM (THREAD_SELF, header.multiple_threads, 1); return 0; } static int create_thread (struct pthread *pd, const struct pthread_attr *attr, STACK_VARIABLES_PARMS) { #ifdef TLS_TCB_AT_TP assert (pd->header.tcb != NULL); #endif /* We rely heavily on various flags the CLONE function understands: CLONE_VM, CLONE_FS, CLONE_FILES These flags select semantics with shared address space and file descriptors according to what POSIX requires. CLONE_SIGNAL This flag selects the POSIX signal semantics. CLONE_SETTLS The sixth parameter to CLONE determines the TLS area for the new thread. CLONE_PARENT_SETTID The kernels writes the thread ID of the newly created thread into the location pointed to by the fifth parameters to CLONE. Note that it would be semantically equivalent to use CLONE_CHILD_SETTID but it is be more expensive in the kernel. CLONE_CHILD_CLEARTID The kernels clears the thread ID of a thread that has called sys_exit() in the location pointed to by the seventh parameter to CLONE. The termination signal is chosen to be zero which means no signal is sent. */ #if 1 #define clone_flags 123456 #warning clone #else int clone_flags = (CLONE_VM | CLONE_FS | CLONE_FILES | CLONE_SIGNAL | CLONE_SETTLS | CLONE_PARENT_SETTID | CLONE_CHILD_CLEARTID | CLONE_SYSVSEM | 0); #endif if (__builtin_expect (THREAD_GETMEM (THREAD_SELF, report_events), 0)) { /* The parent thread is supposed to report events. Check whether the TD_CREATE event is needed, too. */ const int _idx = __td_eventword (TD_CREATE); const uint32_t _mask = __td_eventmask (TD_CREATE); if ((_mask & (__nptl_threads_events.event_bits[_idx] | pd->eventbuf.eventmask.event_bits[_idx])) != 0) { /* We always must have the thread start stopped. */ pd->stopped_start = true; /* Create the thread. We always create the thread stopped so that it does not get far before we tell the debugger. */ int res = do_clone (pd, attr, clone_flags, start_thread, STACK_VARIABLES_ARGS, 1); if (res == 0) { /* Now fill in the information about the new thread in the newly created thread's data structure. We cannot let the new thread do this since we don't know whether it was already scheduled when we send the event. */ pd->eventbuf.eventnum = TD_CREATE; pd->eventbuf.eventdata = pd; /* Enqueue the descriptor. */ do pd->nextevent = __nptl_last_event; while (atomic_compare_and_exchange_bool_acq (&__nptl_last_event, pd, pd->nextevent) != 0); /* Now call the function which signals the event. */ __nptl_create_event (); /* And finally restart the new thread. */ lll_unlock (pd->lock, LLL_PRIVATE); } return res; } } #ifdef NEED_DL_SYSINFO assert (THREAD_SELF_SYSINFO == THREAD_SYSINFO (pd)); #endif /* Determine whether the newly created threads has to be started stopped since we have to set the scheduling parameters or set the affinity. */ bool stopped = false; if (attr != NULL && (attr->cpuset != NULL || (attr->flags & ATTR_FLAG_NOTINHERITSCHED) != 0)) stopped = true; pd->stopped_start = stopped; pd->parent_cancelhandling = THREAD_GETMEM (THREAD_SELF, cancelhandling); /* Actually create the thread. */ int res = do_clone (pd, attr, clone_flags, start_thread, STACK_VARIABLES_ARGS, stopped); if (res == 0 && stopped) /* And finally restart the new thread. */ lll_unlock (pd->lock, LLL_PRIVATE); return res; }
KubaKaszycki/kubux
glibc/fbtl/sysdeps/pthread/createthread.c
C
gpl-3.0
9,579
import fnmatch import functools import io import ntpath import os import posixpath import re import sys import weakref try: import threading except ImportError: import dummy_threading as threading from collections import Sequence, defaultdict from contextlib import contextmanager from errno import EINVAL, ENOENT, EEXIST from itertools import chain, count from operator import attrgetter from stat import S_ISDIR, S_ISLNK, S_ISREG supports_symlinks = True try: import nt except ImportError: nt = None else: if sys.getwindowsversion()[:2] >= (6, 0) and sys.version_info >= (3, 2): from nt import _getfinalpathname else: supports_symlinks = False _getfinalpathname = None __all__ = [ "PurePath", "PurePosixPath", "PureNTPath", "Path", "PosixPath", "NTPath", ] # # Internals # def _is_wildcard_pattern(pat): # Whether this pattern needs actual matching using fnmatch, or can # be looked up directly as a file. return "*" in pat or "?" in pat or "[" in pat class _Flavour(object): """A flavour implements a particular (platform-specific) set of path semantics.""" def __init__(self): self.join = self.sep.join def parse_parts(self, parts): parsed = [] sep = self.sep altsep = self.altsep drv = root = '' it = reversed(parts) for part in it: if altsep: part = part.replace(altsep, sep) drv, root, rel = self.splitroot(part) rel = rel.rstrip(sep) parsed.extend(x for x in reversed(rel.split(sep)) if x and x != '.') if drv or root: if not drv: # If no drive is present, try to find one in the previous # parts. This makes the result of parsing e.g. # ("C:", "/", "a") reasonably intuitive. for part in it: drv = self.splitroot(part)[0] if drv: break break if drv or root: parsed.append(drv + root) parsed.reverse() return drv, root, parsed class _NTFlavour(_Flavour): # Reference for NT paths can be found at # http://msdn.microsoft.com/en-us/library/aa365247%28v=vs.85%29.aspx sep = '\\' altsep = '/' has_drv = True pathmod = ntpath is_supported = (nt is not None) drive_letters = ( set(chr(x) for x in range(ord('a'), ord('z') + 1)) | set(chr(x) for x in range(ord('A'), ord('Z') + 1)) ) ext_namespace_prefix = '\\\\?\\' reserved_names = ( {'CON', 'PRN', 'AUX', 'NUL'} | {'COM%d' % i for i in range(1, 10)} | {'LPT%d' % i for i in range(1, 10)} ) # Interesting findings about extended paths: # - '\\?\c:\a', '//?/c:\a' and '//?/c:/a' are all supported # but '\\?\c:/a' is not # - extended paths are always absolute; "relative" extended paths will # fail. def splitroot(self, part, sep=sep): first = part[0:1] second = part[1:2] if (second == sep and first == sep): # XXX extended paths should also disable the collapsing of "." # components (according to MSDN docs). prefix, part = self._split_extended_path(part) first = part[0:1] second = part[1:2] else: prefix = '' third = part[2:3] if (second == sep and first == sep and third != sep): # is a UNC path: # vvvvvvvvvvvvvvvvvvvvv root # \\machine\mountpoint\directory\etc\... # directory ^^^^^^^^^^^^^^ index = part.find(sep, 2) if index != -1: index2 = part.find(sep, index + 1) # a UNC path can't have two slashes in a row # (after the initial two) if index2 != index + 1: if index2 == -1: index2 = len(part) if prefix: return prefix + part[1:index2], sep, part[index2+1:] else: return part[:index2], sep, part[index2+1:] drv = root = '' if second == ':' and first in self.drive_letters: drv = part[:2] part = part[2:] first = third if first == sep: root = first part = part.lstrip(sep) return prefix + drv, root, part def casefold(self, s): return s.lower() def casefold_parts(self, parts): return [p.lower() for p in parts] def resolve(self, path): s = str(path) if not s: return os.getcwd() if _getfinalpathname is not None: return self._ext_to_normal(_getfinalpathname(s)) # Means fallback on absolute return None def _split_extended_path(self, s, ext_prefix=ext_namespace_prefix): prefix = '' if s.startswith(ext_prefix): prefix = s[:4] s = s[4:] if s.startswith('UNC\\'): prefix += s[:3] s = '\\' + s[3:] return prefix, s def _ext_to_normal(self, s): # Turn back an extended path into a normal DOS-like path return self._split_extended_path(s)[1] def is_reserved(self, parts): # NOTE: the rules for reserved names seem somewhat complicated # (e.g. r"..\NUL" is reserved but not r"foo\NUL"). # We err on the side of caution and return True for paths which are # not considered reserved by Windows. if not parts: return False if parts[0].startswith('\\\\'): # UNC paths are never reserved return False return parts[-1].partition('.')[0].upper() in self.reserved_names _NO_FD = None class _PosixFlavour(_Flavour): sep = '/' altsep = '' has_drv = False pathmod = posixpath is_supported = (os.name != 'nt') def splitroot(self, part, sep=sep): if part and part[0] == sep: return '', sep, part.lstrip(sep) else: return '', '', part def casefold(self, s): return s def casefold_parts(self, parts): return parts def resolve(self, path): sep = self.sep def split(p): return [x for x in p.split(sep) if x] def absparts(p): # Our own abspath(), since the posixpath one makes # the mistake of "normalizing" the path without resolving the # symlinks first. if not p.startswith(sep): return split(os.getcwd()) + split(p) else: return split(p) def close(fd): if fd != _NO_FD: os.close(fd) parts = absparts(str(path))[::-1] accessor = path._accessor resolved = cur = "" resolved_fd = _NO_FD symlinks = {} try: while parts: part = parts.pop() cur = resolved + sep + part if cur in symlinks and symlinks[cur] <= len(parts): # We've already seen the symlink and there's not less # work to do than the last time. raise ValueError("Symlink loop from %r" % cur) try: target = accessor.readlink(cur, part, dir_fd=resolved_fd) except OSError as e: if e.errno != EINVAL: raise # Not a symlink resolved_fd = accessor.walk_down(cur, part, dir_fd=resolved_fd) resolved = cur else: # Take note of remaining work from this symlink symlinks[cur] = len(parts) if target.startswith(sep): # Symlink points to absolute path resolved = "" close(resolved_fd) resolved_fd = _NO_FD parts.extend(split(target)[::-1]) finally: close(resolved_fd) return resolved or sep def is_reserved(self, parts): return False _nt_flavour = _NTFlavour() _posix_flavour = _PosixFlavour() _fds_refs = defaultdict(int) _fds_refs_lock = threading.Lock() def _add_fd_ref(fd, lock=_fds_refs_lock): with lock: _fds_refs[fd] += 1 def _sub_fd_ref(fd, lock=_fds_refs_lock): with lock: nrefs = _fds_refs[fd] - 1 if nrefs > 0: _fds_refs[fd] = nrefs else: del _fds_refs[fd] os.close(fd) class _Accessor: """An accessor implements a particular (system-specific or not) way of accessing paths on the filesystem.""" if sys.version_info >= (3, 3): supports_openat = (os.listdir in os.supports_fd and os.supports_dir_fd >= { os.chmod, os.stat, os.mkdir, os.open, os.readlink, os.rename, os.symlink, os.unlink, } ) else: supports_openat = False if supports_openat: def _fdnamepair(pathobj): """Get a (parent fd, name) pair from a path object, suitable for use with the various *at functions.""" parent_fd = pathobj._parent_fd if parent_fd is not None: return parent_fd, pathobj._parts[-1] else: return _NO_FD, str(pathobj) class _OpenatAccessor(_Accessor): def _wrap_atfunc(atfunc): @functools.wraps(atfunc) def wrapped(pathobj, *args, **kwargs): parent_fd, name = _fdnamepair(pathobj) return atfunc(name, *args, dir_fd=parent_fd, **kwargs) return staticmethod(wrapped) def _wrap_binary_atfunc(atfunc): @functools.wraps(atfunc) def wrapped(pathobjA, pathobjB, *args, **kwargs): parent_fd_A, nameA = _fdnamepair(pathobjA) # We allow pathobjB to be a plain str, for convenience if isinstance(pathobjB, Path): parent_fd_B, nameB = _fdnamepair(pathobjB) else: # If it's a str then at best it's cwd-relative parent_fd_B, nameB = _NO_FD, str(pathobjB) return atfunc(nameA, nameB, *args, src_dir_fd=parent_fd_A, dst_dir_fd=parent_fd_B, **kwargs) return staticmethod(wrapped) stat = _wrap_atfunc(os.stat) lstat = _wrap_atfunc(os.lstat) open = _wrap_atfunc(os.open) chmod = _wrap_atfunc(os.chmod) def lchmod(self, pathobj, mode): return self.chmod(pathobj, mode, follow_symlinks=False) mkdir = _wrap_atfunc(os.mkdir) unlink = _wrap_atfunc(os.unlink) rmdir = _wrap_atfunc(os.rmdir) def listdir(self, pathobj): fd = self._make_fd(pathobj, tolerant=False) return os.listdir(fd) rename = _wrap_binary_atfunc(os.rename) def symlink(self, target, pathobj, target_is_directory): parent_fd, name = _fdnamepair(pathobj) os.symlink(str(target), name, dir_fd=parent_fd) def _make_fd(self, pathobj, tolerant=True): fd = pathobj._cached_fd if fd is not None: return fd try: fd = self.open(pathobj, os.O_RDONLY) except (PermissionError, FileNotFoundError): if tolerant: # If the path doesn't exist or is forbidden, just let us # gracefully fallback on fd-less code. return None raise # This ensures the stat information is consistent with the fd. try: st = pathobj._cached_stat = os.fstat(fd) except: os.close(fd) raise if tolerant and not S_ISDIR(st.st_mode): # Not a directory => no point in keeping the fd os.close(fd) return None else: pathobj._cached_fd = fd pathobj._add_managed_fd(fd) return fd def init_path(self, pathobj): self._make_fd(pathobj) def make_child(self, pathobj, args): drv, root, parts = pathobj._flavour.parse_parts(args) if drv or root: # Anchored path => we can't do any better return None # NOTE: In the code below, we want to expose errors instead of # risking race conditions when e.g. a non-existing directory gets # later created. This means we want e.g. non-existing path # components or insufficient permissions to raise an OSError. pathfd = self._make_fd(pathobj, tolerant=False) if not parts: # This is the same path newpath = pathobj._from_parsed_parts( pathobj._drv, pathobj._root, pathobj._parts, init=False) newpath._init(template=pathobj, fd=pathfd) return newpath parent_fd = pathfd for part in parts[:-1]: fd = os.open(part, os.O_RDONLY, dir_fd=parent_fd) if parent_fd != pathfd: # Forget intermediate fds os.close(parent_fd) parent_fd = fd # The last component may or may not exist, it doesn't matter: we # have the fd of its parent newpath = pathobj._from_parsed_parts( pathobj._drv, pathobj._root, pathobj._parts + parts, init=False) newpath._init(template=pathobj, parent_fd=parent_fd) return newpath # Helpers for resolve() def walk_down(self, path, name, dir_fd): if dir_fd != _NO_FD: try: return os.open(name, os.O_RDONLY, dir_fd=dir_fd) finally: os.close(dir_fd) else: return os.open(path, os.O_RDONLY) def readlink(self, path, name, dir_fd): if dir_fd != _NO_FD: return os.readlink(name, dir_fd=dir_fd) else: return os.readlink(path) _openat_accessor = _OpenatAccessor() class _NormalAccessor(_Accessor): def _wrap_strfunc(strfunc): @functools.wraps(strfunc) def wrapped(pathobj, *args): return strfunc(str(pathobj), *args) return staticmethod(wrapped) def _wrap_binary_strfunc(strfunc): @functools.wraps(strfunc) def wrapped(pathobjA, pathobjB, *args): return strfunc(str(pathobjA), str(pathobjB), *args) return staticmethod(wrapped) stat = _wrap_strfunc(os.stat) lstat = _wrap_strfunc(os.lstat) open = _wrap_strfunc(os.open) listdir = _wrap_strfunc(os.listdir) chmod = _wrap_strfunc(os.chmod) if hasattr(os, "lchmod"): lchmod = _wrap_strfunc(os.lchmod) else: def lchmod(self, pathobj, mode): raise NotImplementedError("lchmod() not available on this system") mkdir = _wrap_strfunc(os.mkdir) unlink = _wrap_strfunc(os.unlink) rmdir = _wrap_strfunc(os.rmdir) rename = _wrap_binary_strfunc(os.rename) if nt: if supports_symlinks: symlink = _wrap_binary_strfunc(os.symlink) else: def symlink(a, b, target_is_directory): raise NotImplementedError("symlink() not available on this system") else: # Under POSIX, os.symlink() takes two args @staticmethod def symlink(a, b, target_is_directory): return os.symlink(str(a), str(b)) def init_path(self, pathobj): pass def make_child(self, pathobj, args): return None # Helpers for resolve() def walk_down(self, path, name, dir_fd): assert dir_fd == _NO_FD return _NO_FD def readlink(self, path, name, dir_fd): assert dir_fd == _NO_FD return os.readlink(path) _normal_accessor = _NormalAccessor() # # Globbing helpers # @contextmanager def _cached(func): try: func.__cached__ yield func except AttributeError: cache = {} def wrapper(*args): if args in cache: return cache[args] value = cache[args] = func(*args) return value wrapper.__cached__ = True try: yield wrapper finally: cache.clear() def _make_selector(pattern_parts): pat = pattern_parts[0] child_parts = pattern_parts[1:] if pat == '**': cls = _RecursiveWildcardSelector elif '**' in pat: raise ValueError("Invalid pattern: '**' can only be an entire path component") elif _is_wildcard_pattern(pat): cls = _WildcardSelector else: cls = _PreciseSelector return cls(pat, child_parts) if hasattr(functools, "lru_cache"): _make_selector = functools.lru_cache()(_make_selector) class _Selector: """A selector matches a specific glob pattern part against the children of a given path.""" def __init__(self, child_parts): self.child_parts = child_parts if child_parts: self.successor = _make_selector(child_parts) else: self.successor = _TerminatingSelector() def select_from(self, parent_path): """Iterate over all child paths of `parent_path` matched by this selector. This can contain parent_path itself.""" path_cls = type(parent_path) is_dir = path_cls.is_dir exists = path_cls.exists listdir = parent_path._accessor.listdir return self._select_from(parent_path, is_dir, exists, listdir) class _TerminatingSelector: def _select_from(self, parent_path, is_dir, exists, listdir): yield parent_path class _PreciseSelector(_Selector): def __init__(self, name, child_parts): self.name = name _Selector.__init__(self, child_parts) def _select_from(self, parent_path, is_dir, exists, listdir): if not is_dir(parent_path): return path = parent_path._make_child_relpath(self.name) if exists(path): for p in self.successor._select_from(path, is_dir, exists, listdir): yield p class _WildcardSelector(_Selector): def __init__(self, pat, child_parts): self.pat = re.compile(fnmatch.translate(pat)) _Selector.__init__(self, child_parts) def _select_from(self, parent_path, is_dir, exists, listdir): if not is_dir(parent_path): return cf = parent_path._flavour.casefold for name in listdir(parent_path): casefolded = cf(name) if self.pat.match(casefolded): path = parent_path._make_child_relpath(name) for p in self.successor._select_from(path, is_dir, exists, listdir): yield p class _RecursiveWildcardSelector(_Selector): def __init__(self, pat, child_parts): _Selector.__init__(self, child_parts) def _iterate_directories(self, parent_path, is_dir, listdir): yield parent_path for name in listdir(parent_path): path = parent_path._make_child_relpath(name) if is_dir(path): for p in self._iterate_directories(path, is_dir, listdir): yield p def _select_from(self, parent_path, is_dir, exists, listdir): if not is_dir(parent_path): return with _cached(listdir) as listdir: yielded = set() try: successor_select = self.successor._select_from for starting_point in self._iterate_directories(parent_path, is_dir, listdir): for p in successor_select(starting_point, is_dir, exists, listdir): if p not in yielded: yield p yielded.add(p) finally: yielded.clear() # # Public API # class _PathParts(Sequence): """This object provides sequence-like access to the parts of a path. Don't try to construct it yourself.""" __slots__ = ('_pathcls', '_parts') def __init__(self, path): # We don't store the instance to avoid reference cycles self._pathcls = type(path) self._parts = path._parts def __len__(self): return len(self._parts) def __getitem__(self, idx): if isinstance(idx, slice): return self._pathcls(*self._parts[idx]) return self._parts[idx] def __repr__(self): return "<{}.parts: {!r}>".format(self._pathcls.__name__, self._parts) class PurePath(object): """PurePath represents a filesystem path and offers operations which don't imply any actual filesystem I/O. Depending on your system, instantiating a PurePath will return either a PurePosixPath or a PureNTPath object. You can also instantiate either of these classes directly, regardless of your system. """ __slots__ = ( '_drv', '_root', '_parts', '_str', '_hash', '_pparts', '_cached_cparts', ) def __new__(cls, *args): """Construct a PurePath from one or several strings and or existing PurePath objects. The strings and path objects are combined so as to yield a canonicalized path, which is incorporated into the new PurePath object. """ if cls is PurePath: cls = PureNTPath if os.name == 'nt' else PurePosixPath return cls._from_parts(args) @classmethod def _parse_args(cls, args): # This is useful when you don't want to create an instance, just # canonicalize some constructor arguments. parts = [] for a in args: if isinstance(a, PurePath): parts += a._parts elif isinstance(a, str): # Assuming a str parts.append(a) else: raise TypeError( "argument should be a path or str object, not %r" % type(a)) return cls._flavour.parse_parts(parts) @classmethod def _from_parts(cls, args, init=True): # We need to call _parse_args on the instance, so as to get the # right flavour. self = object.__new__(cls) drv, root, parts = self._parse_args(args) self._drv = drv self._root = root self._parts = parts if init: self._init() return self @classmethod def _from_parsed_parts(cls, drv, root, parts, init=True): self = object.__new__(cls) self._drv = drv self._root = root self._parts = parts if init: self._init() return self @classmethod def _format_parsed_parts(cls, drv, root, parts): if drv or root: return drv + root + cls._flavour.join(parts[1:]) else: return cls._flavour.join(parts) def _init(self): # Overriden in concrete Path pass def _make_child(self, args): # Overriden in concrete Path parts = self._parts[:] parts.extend(args) return self._from_parts(parts) def __str__(self): """Return the string representation of the path, suitable for passing to system calls.""" try: return self._str except AttributeError: self._str = self._format_parsed_parts(self._drv, self._root, self._parts) or '.' return self._str def as_posix(self): """Return the string representation of the path with forward (/) slashes.""" f = self._flavour return str(self).replace(f.sep, '/') def as_bytes(self): """Return the bytes representation of the path. This is only recommended to use under Unix.""" return os.fsencode(str(self)) __bytes__ = as_bytes def __repr__(self): return "{}({!r})".format(self.__class__.__name__, str(self)) @property def _cparts(self): # Cached casefolded parts, for hashing and comparison try: return self._cached_cparts except AttributeError: self._cached_cparts = self._flavour.casefold_parts(self._parts) return self._cached_cparts def __eq__(self, other): return self._cparts == other._cparts and self._flavour is other._flavour def __ne__(self, other): return not self == other def __hash__(self): try: return self._hash except AttributeError: self._hash = hash(tuple(self._cparts)) return self._hash def __lt__(self, other): if self._flavour is not other._flavour: return NotImplemented return self._cparts < other._cparts def __le__(self, other): if self._flavour is not other._flavour: return NotImplemented return self._cparts <= other._cparts def __gt__(self, other): if self._flavour is not other._flavour: return NotImplemented return self._cparts > other._cparts def __ge__(self, other): if self._flavour is not other._flavour: return NotImplemented return self._cparts >= other._cparts drive = property(attrgetter('_drv'), doc="""The drive prefix (letter or UNC path), if any""") root = property(attrgetter('_root'), doc="""The root of the path, if any""") @property def ext(self): """The final component's extension, if any.""" parts = self._parts if len(parts) == (1 if (self._drv or self._root) else 0): return '' basename = parts[-1] if basename == '.': return '' i = basename.find('.') if i == -1: return '' return basename[i:] def relative(self): """Return a new path without any drive and root. """ if self._drv or self._root: return self._from_parsed_parts('', '', self._parts[1:]) else: return self._from_parsed_parts('', '', self._parts) def relative_to(self, *other): """Return the relative path to another path identified by the passed arguments. If the operation is not possible (because this is not a subpath of the other path), raise ValueError. """ # For the purpose of this method, drive and root are considered # separate parts, i.e.: # Path('c:/').relative('c:') gives Path('/') # Path('c:/').relative('/') raise ValueError if not other: raise TypeError("need at least one argument") parts = self._parts drv = self._drv root = self._root if drv or root: if root: abs_parts = [drv, root] + parts[1:] else: abs_parts = [drv] + parts[1:] else: abs_parts = parts to_drv, to_root, to_parts = self._parse_args(other) if to_drv or to_root: if to_root: to_abs_parts = [to_drv, to_root] + to_parts[1:] else: to_abs_parts = [to_drv] + to_parts[1:] else: to_abs_parts = to_parts n = len(to_abs_parts) if n == 0 and (drv or root) or abs_parts[:n] != to_abs_parts: formatted = self._format_parsed_parts(to_drv, to_root, to_parts) raise ValueError("{!r} does not start with {!r}" .format(str(self), str(formatted))) return self._from_parsed_parts('', '', abs_parts[n:]) @property def parts(self): """An object providing sequence-like access to the components in the filesystem path.""" try: return self._pparts except AttributeError: self._pparts = _PathParts(self) return self._pparts def join(self, *args): """Combine this path with one or several arguments, and return a new path representing either a subpath (if all arguments are relative paths) or a totally different path (if one of the arguments is anchored). """ return self._make_child(args) def __getitem__(self, key): if isinstance(key, tuple): return self._make_child(key) else: return self._make_child((key,)) def parent(self, level=1): """A parent or ancestor (if `level` is specified) of this path.""" if level < 1: raise ValueError("`level` must be a non-zero positive integer") drv = self._drv root = self._root parts = self._parts[:-level] if not parts: if level > len(self._parts) - bool(drv or root): raise ValueError("level greater than path length") return self._from_parsed_parts(drv, root, parts) def parents(self): """Iterate over this path's parents, in ascending order.""" drv = self._drv root = self._root parts = self._parts n = len(parts) end = 0 if (drv or root) else -1 for i in range(n - 1, end, -1): yield self._from_parsed_parts(drv, root, parts[:i]) def is_absolute(self): """True if the path is absolute (has both a root and, if applicable, a drive).""" if not self._root: return False return not self._flavour.has_drv or bool(self._drv) def normcase(self): """Return this path, possibly lowercased if the path flavour has case-insensitive path semantics. Calling this method is not needed before comparing Path instances.""" fix = self._flavour.casefold_parts drv, = fix((self._drv,)) root = self._root parts = fix(self._parts) return self._from_parsed_parts(drv, root, parts) def is_reserved(self): """Return True if the path contains one of the special names reserved by the system, if any.""" return self._flavour.is_reserved(self._parts) def match(self, path_pattern): """ Return True if this path matches the given pattern. """ cf = self._flavour.casefold path_pattern = cf(path_pattern) drv, root, pat_parts = self._flavour.parse_parts((path_pattern,)) if not pat_parts: raise ValueError("empty pattern") if drv and drv != cf(self._drv): return False if root and root != cf(self._root): return False parts = self._cparts if drv or root: if len(pat_parts) != len(parts): return False pat_parts = pat_parts[1:] elif len(pat_parts) > len(parts): return False for part, pat in zip(reversed(parts), reversed(pat_parts)): if not fnmatch.fnmatchcase(part, pat): return False return True class PurePosixPath(PurePath): _flavour = _posix_flavour __slots__ = () class PureNTPath(PurePath): _flavour = _nt_flavour __slots__ = () # Filesystem-accessing classes class Path(PurePath): __slots__ = ( '_accessor', '_cached_stat', '_closed', # Used by _OpenatAccessor '_cached_fd', '_parent_fd', '_managed_fds', '__weakref__', ) _wrs = {} _wr_id = count() def __new__(cls, *args, **kwargs): use_openat = kwargs.get('use_openat', False) if cls is Path: cls = NTPath if os.name == 'nt' else PosixPath self = cls._from_parts(args, init=False) if not self._flavour.is_supported: raise NotImplementedError("cannot instantiate %r on your system" % (cls.__name__,)) self._init(use_openat) return self def _init(self, use_openat=False, # Private non-constructor arguments template=None, parent_fd=None, fd=None, ): self._closed = False self._managed_fds = None self._parent_fd = parent_fd self._cached_fd = fd if parent_fd is not None: self._add_managed_fd(parent_fd) if fd is not None: self._add_managed_fd(fd) if template is not None: self._accessor = template._accessor elif use_openat: if not supports_openat: raise NotImplementedError("your system doesn't support openat()") self._accessor = _openat_accessor else: self._accessor = _normal_accessor self._accessor.init_path(self) def _make_child(self, args): child = self._accessor.make_child(self, args) if child is not None: return child parts = self._parts[:] parts.extend(args) return self._from_parts(parts) def _make_child_relpath(self, part): # This is an optimization used for dir walking. `part` must be # a single part relative to this path. child = self._accessor.make_child(self, (part,)) if child is not None: return child parts = self._parts + [part] return self._from_parsed_parts(self._drv, self._root, parts) @property def _stat(self): try: return self._cached_stat except AttributeError: pass st = self._accessor.stat(self) self._cached_stat = st return st @classmethod def _cleanup(cls, fds, wr_id=None): if wr_id is not None: del cls._wrs[wr_id] while fds: _sub_fd_ref(fds.pop()) def _add_managed_fd(self, fd): """Add a file descriptor managed by this object.""" if fd is None: return fds = self._managed_fds if fds is None: # This setup is done lazily so that most path objects avoid it fds = self._managed_fds = [] cleanup = type(self)._cleanup # We can't hash the weakref directly since distinct Path objects # can compare equal. wr_id = next(self._wr_id) wr = weakref.ref(self, lambda wr: cleanup(fds, wr_id)) self._wrs[wr_id] = wr _add_fd_ref(fd) fds.append(fd) def _sub_managed_fd(self, fd): """Remove a file descriptor managed by this object.""" self._managed_fds.remove(fd) _sub_fd_ref(fd) def __enter__(self): if self._closed: self._raise_closed() return self def __exit__(self, t, v, tb): self._closed = True fds = self._managed_fds if fds is not None: self._managed_fds = None self._cached_fd = None self._parent_fd = None self._cleanup(fds) def _raise_closed(self): raise ValueError("I/O operation on closed path") def _opener(self, name, flags, mode=0o777): # A stub for the opener argument to built-in open() return self._accessor.open(self, flags, mode) # Public API @classmethod def cwd(cls, use_openat=False): """Return a new path pointing to the current working directory (as returned by os.getcwd()). """ return cls(os.getcwd(), use_openat=use_openat) def __iter__(self): """Iterate over the files in this directory. Does not yield any result for the special paths '.' and '..'. """ if self._closed: self._raise_closed() for name in self._accessor.listdir(self): if name in {'.', '..'}: # Yielding a path object for these makes little sense continue yield self._make_child_relpath(name) if self._closed: self._raise_closed() def __getattr__(self, name): if name.startswith('st_'): return getattr(self._stat, name) return super(Path, self).__getattribute__(name) def glob(self, pattern): """Iterate over this subtree and yield all existing files (of any kind, including directories) matching the given pattern. """ pattern = self._flavour.casefold(pattern) drv, root, pattern_parts = self._flavour.parse_parts((pattern,)) if drv or root: raise NotImplementedError("Non-relative patterns are unsupported") selector = _make_selector(tuple(pattern_parts)) for p in selector.select_from(self): yield p def rglob(self, pattern): """Recursively yield all existing files (of any kind, including directories) matching the given pattern, anywhere in this subtree. """ pattern = self._flavour.casefold(pattern) drv, root, pattern_parts = self._flavour.parse_parts((pattern,)) if drv or root: raise NotImplementedError("Non-relative patterns are unsupported") selector = _make_selector(("**",) + tuple(pattern_parts)) for p in selector.select_from(self): yield p def absolute(self): """Return an absolute version of this path. This function works even if the path doesn't point to anything. No normalization is done, i.e. all '.' and '..' will be kept along. Use resolve() to get the canonical path to a file. """ # XXX untested yet! if self._closed: self._raise_closed() if self.is_absolute(): return self # FIXME this must defer to the specific flavour (and, under Windows, # use nt._getfullpathname()) obj = self._from_parts([os.getcwd()] + self._parts, init=False) obj._init(template=self, parent_fd=self._parent_fd, fd=self._cached_fd) return obj def resolve(self): """ Make the path absolute, resolving all symlinks on the way and also normalizing it (for example turning slashes into backslashes under Windows). """ if self._closed: self._raise_closed() s = self._flavour.resolve(self) if s is None: # No symlink resolution => for consistency, raise an error if # the path doesn't exist or is forbidden self._stat s = str(self.absolute()) # Now we have no symlinks in the path, it's safe to normalize it. normed = self._flavour.pathmod.normpath(s) obj = self._from_parts((normed,), init=False) obj._init(template=self, parent_fd=self._parent_fd, fd=self._cached_fd) return obj def stat(self): """ Return the result of the stat() system call on this path, like os.stat() does. """ return self._stat def restat(self): """ Same as stat(), but resets the internal cache to force a fresh value. """ try: del self._cached_stat except AttributeError: pass return self._stat def raw_open(self, flags, mode=0o777): """ Open the file pointed by this path and return a file descriptor, as os.open() does. """ if self._closed: self._raise_closed() return self._accessor.open(self, flags, mode) def open(self, mode='r', buffering=-1, encoding=None, errors=None, newline=None): """ Open the file pointed by this path and return a file object, as the built-in open() function does. """ if self._closed: self._raise_closed() if sys.version_info >= (3, 3): return io.open(str(self), mode, buffering, encoding, errors, newline, opener=self._opener) else: return io.open(str(self), mode, buffering, encoding, errors, newline) def touch(self, mode=0o777, exist_ok=True): """ Create this file with the given access mode, if it doesn't exist. """ if self._closed: self._raise_closed() flags = os.O_CREAT if not exist_ok: flags |= os.O_EXCL fd = self.raw_open(flags, mode) os.close(fd) def mkdir(self, mode=0o777, parents=False): if self._closed: self._raise_closed() if not parents: self._accessor.mkdir(self, mode) else: try: self._accessor.mkdir(self, mode) except OSError as e: if e.errno != ENOENT: raise self.parent().mkdir(mode, True) self._accessor.mkdir(self, mode) def chmod(self, mode): """ Change the permissions of the path, like os.chmod(). """ if self._closed: self._raise_closed() self._accessor.chmod(self, mode) def lchmod(self, mode): """ Like chmod(), except if the path points to a symlink, the symlink's permissions are changed, rather than its target's. """ if self._closed: self._raise_closed() self._accessor.lchmod(self, mode) def unlink(self): """ Remove this file or link. If the path is a directory, use rmdir() instead. """ if self._closed: self._raise_closed() self._accessor.unlink(self) def rmdir(self): """ Remove this directory. The directory must be empty. """ if self._closed: self._raise_closed() self._accessor.rmdir(self) def lstat(self): """ Like stat(), except if the path points to a symlink, the symlink's status information is returned, rather than its target's. """ if self._closed: self._raise_closed() return self._accessor.lstat(self) def rename(self, target): """ Rename this path to the given path. """ if self._closed: self._raise_closed() self._accessor.rename(self, target) def symlink_to(self, target, target_is_directory=False): """ Make this path a symlink pointing to the given path. Note the order of arguments (self, target) is the reverse of os.symlink's. """ if self._closed: self._raise_closed() self._accessor.symlink(target, self, target_is_directory) # Convenience functions for querying the stat results def exists(self): """ Whether this path exists. """ try: self.restat() except OSError as e: if e.errno != ENOENT: raise return False return True def is_dir(self): """ Whether this path is a directory. """ return S_ISDIR(self._stat.st_mode) def is_file(self): """ Whether this path is a regular file (also True for symlinks pointing to regular files). """ return S_ISREG(self._stat.st_mode) def is_symlink(self): """ Whether this path is a symbolic link. """ st = self.lstat() return S_ISLNK(st.st_mode) class PosixPath(Path, PurePosixPath): __slots__ = () class NTPath(Path, PureNTPath): __slots__ = ()
maciekswat/ptsa_new
ptsa/data/common/pathlib.py
Python
gpl-3.0
43,840
----------------------------------- -- Area: Pashhow Marshlands -- NPC: Souun, I.M. -- Type: Outpost Conquest Guards -- !pos 470.843 23.465 415.520 109 ----------------------------------- package.loaded["scripts/zones/Pashhow_Marshlands/TextIDs"] = nil; ----------------------------------- require("scripts/globals/conquest"); require("scripts/zones/Pashhow_Marshlands/TextIDs"); local guardnation = dsp.nation.BASTOK; -- SANDORIA, BASTOK, WINDURST, 4 = jeuno local guardtype = 3; -- 1: city, 2: foreign, 3: outpost, 4: border local region = dsp.region.DERFLAND; local csid = 0x7ff9; function onTrade(player,npc,trade) tradeConquestGuard(player,npc,trade,guardnation,guardtype); end; function onTrigger(player,npc) if (player:hasKeyItem(getSupplyKey(region)) and player:getNation() == guardnation) then if (supplyRunFresh(player) == 1) then player:startEvent(csid,16,0,0,0,1,0,0,255); -- you have brought us supplies ! else player:showText(npc, CONQUEST - 1); -- "Hmm... These supplies you have brought us are too old to be of any use." player:delKeyItem(getSupplyKey(region)); player:messageSpecial(KEYITEM_OBTAINED + 1, getSupplyKey(region)); player:setVar("supplyQuest_region",0); end else local arg1 = getArg1(guardnation, player) - 1; if (arg1 >= 1792) then -- foreign, non-allied player:startEvent(csid,1808,0,0,0,0,player:getRank(),0,0); else -- citizen or allied player:startEvent(csid,arg1,0,0x3F0000,0,0,getArg6(player),0,0); end end end; function onEventUpdate(player,csid,option) -- printf("OPTION: %u",option); end; function onEventFinish(player,csid,option) -- printf("OPTION: %u",option); if (option == 1) then local duration = (player:getRank() + getNationRank(player:getNation()) + 3) * 3600; player:delStatusEffect(dsp.effect.SIGIL); player:delStatusEffect(dsp.effect.SANCTION); player:delStatusEffect(dsp.effect.SIGNET); player:addStatusEffect(dsp.effect.SIGNET,0,0,duration); -- Grant Signet elseif (option == 2) then player:delKeyItem(getSupplyKey(region)); player:addCP(supplyReward[region + 1]) player:messageSpecial(CONQUEST); -- "You've earned conquest points!" if (hasOutpost(player, region+5) == 0) then local supply_quests = 2^(region+5); player:addNationTeleport(guardnation,supply_quests); player:setVar("supplyQuest_region",0); end elseif (option == 4) then if (player:delGil(giltosetHP(guardnation,player))) then player:setHomePoint(); player:messageSpecial(CONQUEST + 94); -- "Your home point has been set." else player:messageSpecial(CONQUEST + 95); -- "You do not have enough gil to set your home point here." end end end;
waterlgndx/darkstar
scripts/zones/Pashhow_Marshlands/npcs/Souun_IM.lua
Lua
gpl-3.0
2,942
// RUN: %clang_cc1 -triple x86_64-pc-linux -emit-llvm -o - %s | FileCheck %s // RUN: %clang_cc1 -triple x86_64-apple-darwin -emit-llvm -o - %s | \ // RUN: FileCheck --check-prefix=MACHO %s // CHECK: @_ZN5test11A1aE ={{.*}} constant i32 10, align 4 // CHECK: @_ZN5test212_GLOBAL__N_11AIiE1xE = internal global i32 0, align 4 // CHECK: @_ZN5test31AIiE1xE = weak_odr global i32 0, comdat, align 4 // CHECK: @_ZGVN5test31AIiE1xE = weak_odr global i64 0, comdat($_ZN5test31AIiE1xE) // MACHO: @_ZGVN5test31AIiE1xE = weak_odr global i64 0 // MACHO-NOT: comdat // CHECK: _ZN5test51U2k0E ={{.*}} global i32 0 // CHECK: _ZN5test51U2k1E ={{.*}} global i32 0 // CHECK: _ZN5test51U2k2E ={{.*}} constant i32 76 // CHECK-NOT: test51U2k3E // CHECK-NOT: test51U2k4E // PR5564. namespace test1 { struct A { static const int a = 10; }; const int A::a; struct S { static int i; }; void f() { int a = S::i; } } // Test that we don't use guards for initializing template static data // members with internal linkage. namespace test2 { int foo(); namespace { template <class T> struct A { static int x; }; template <class T> int A<T>::x = foo(); template struct A<int>; } // CHECK-LABEL: define internal void @__cxx_global_var_init() // CHECK: [[TMP:%.*]] = call i32 @_ZN5test23fooEv() // CHECK-NEXT: store i32 [[TMP]], i32* @_ZN5test212_GLOBAL__N_11AIiE1xE, align 4 // CHECK-NEXT: ret void } // Test that we don't use threadsafe statics when initializing // template static data members. namespace test3 { int foo(); template <class T> struct A { static int x; }; template <class T> int A<T>::x = foo(); template struct A<int>; // CHECK-LABEL: define internal void @__cxx_global_var_init.1() {{.*}} comdat($_ZN5test31AIiE1xE) // MACHO-LABEL: define internal void @__cxx_global_var_init.1() // MACHO-NOT: comdat // CHECK: [[GUARDBYTE:%.*]] = load i8, i8* bitcast (i64* @_ZGVN5test31AIiE1xE to i8*) // CHECK-NEXT: [[UNINITIALIZED:%.*]] = icmp eq i8 [[GUARDBYTE]], 0 // CHECK-NEXT: br i1 [[UNINITIALIZED]] // CHECK: [[TMP:%.*]] = call i32 @_ZN5test33fooEv() // CHECK-NEXT: store i32 [[TMP]], i32* @_ZN5test31AIiE1xE, align 4 // CHECK-NEXT: store i64 1, i64* @_ZGVN5test31AIiE1xE // CHECK-NEXT: br label // CHECK: ret void } // Test that we can fold member lookup expressions which resolve to static data // members. namespace test4 { struct A { static const int n = 76; }; int f(A *a) { // CHECK-LABEL: define{{.*}} i32 @_ZN5test41fEPNS_1AE // CHECK: ret i32 76 return a->n; } } // Test that static data members in unions behave properly. namespace test5 { union U { static int k0; static const int k1; static const int k2 = 76; static const int k3; static const int k4 = 81; }; int U::k0; const int U::k1 = (k0 = 9, 42); const int U::k2; // CHECK: store i32 9, i32* @_ZN5test51U2k0E // CHECK: store i32 {{.*}}, i32* @_ZN5test51U2k1E // CHECK-NOT: store {{.*}} i32* @_ZN5test51U2k2E }
sabel83/metashell
3rd/templight/clang/test/CodeGenCXX/static-data-member.cpp
C++
gpl-3.0
3,058
/* * DO NOT EDIT. THIS FILE IS GENERATED FROM e:/builds/moz2_slave/rel-m-beta-xr_w32_bld-00000000/build/xpcom/io/nsIConverterOutputStream.idl */ #ifndef __gen_nsIConverterOutputStream_h__ #define __gen_nsIConverterOutputStream_h__ #ifndef __gen_nsIUnicharOutputStream_h__ #include "nsIUnicharOutputStream.h" #endif /* For IDL files that don't want to include root IDL files. */ #ifndef NS_NO_VTABLE #define NS_NO_VTABLE #endif class nsIOutputStream; /* forward declaration */ /* starting interface: nsIConverterOutputStream */ #define NS_ICONVERTEROUTPUTSTREAM_IID_STR "4b71113a-cb0d-479f-8ed5-01daeba2e8d4" #define NS_ICONVERTEROUTPUTSTREAM_IID \ {0x4b71113a, 0xcb0d, 0x479f, \ { 0x8e, 0xd5, 0x01, 0xda, 0xeb, 0xa2, 0xe8, 0xd4 }} class NS_NO_VTABLE nsIConverterOutputStream : public nsIUnicharOutputStream { public: NS_DECLARE_STATIC_IID_ACCESSOR(NS_ICONVERTEROUTPUTSTREAM_IID) /* void init (in nsIOutputStream aOutStream, in string aCharset, in unsigned long aBufferSize, in PRUnichar aReplacementCharacter); */ NS_IMETHOD Init(nsIOutputStream *aOutStream, const char * aCharset, uint32_t aBufferSize, PRUnichar aReplacementCharacter) = 0; }; NS_DEFINE_STATIC_IID_ACCESSOR(nsIConverterOutputStream, NS_ICONVERTEROUTPUTSTREAM_IID) /* Use this macro when declaring classes that implement this interface. */ #define NS_DECL_NSICONVERTEROUTPUTSTREAM \ NS_IMETHOD Init(nsIOutputStream *aOutStream, const char * aCharset, uint32_t aBufferSize, PRUnichar aReplacementCharacter); /* Use this macro to declare functions that forward the behavior of this interface to another object. */ #define NS_FORWARD_NSICONVERTEROUTPUTSTREAM(_to) \ NS_IMETHOD Init(nsIOutputStream *aOutStream, const char * aCharset, uint32_t aBufferSize, PRUnichar aReplacementCharacter) { return _to Init(aOutStream, aCharset, aBufferSize, aReplacementCharacter); } /* Use this macro to declare functions that forward the behavior of this interface to another object in a safe way. */ #define NS_FORWARD_SAFE_NSICONVERTEROUTPUTSTREAM(_to) \ NS_IMETHOD Init(nsIOutputStream *aOutStream, const char * aCharset, uint32_t aBufferSize, PRUnichar aReplacementCharacter) { return !_to ? NS_ERROR_NULL_POINTER : _to->Init(aOutStream, aCharset, aBufferSize, aReplacementCharacter); } #if 0 /* Use the code below as a template for the implementation class for this interface. */ /* Header file */ class nsConverterOutputStream : public nsIConverterOutputStream { public: NS_DECL_ISUPPORTS NS_DECL_NSICONVERTEROUTPUTSTREAM nsConverterOutputStream(); private: ~nsConverterOutputStream(); protected: /* additional members */ }; /* Implementation file */ NS_IMPL_ISUPPORTS1(nsConverterOutputStream, nsIConverterOutputStream) nsConverterOutputStream::nsConverterOutputStream() { /* member initializers and constructor code */ } nsConverterOutputStream::~nsConverterOutputStream() { /* destructor code */ } /* void init (in nsIOutputStream aOutStream, in string aCharset, in unsigned long aBufferSize, in PRUnichar aReplacementCharacter); */ NS_IMETHODIMP nsConverterOutputStream::Init(nsIOutputStream *aOutStream, const char * aCharset, uint32_t aBufferSize, PRUnichar aReplacementCharacter) { return NS_ERROR_NOT_IMPLEMENTED; } /* End of implementation class template. */ #endif #endif /* __gen_nsIConverterOutputStream_h__ */
DragonZX/fdm
Gecko.SDK/22/include/nsIConverterOutputStream.h
C
gpl-3.0
3,448
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace e10 { class Program { static void Main(string[] args) { Action<int> birMethod; int i = 10; if (i >= 10) birMethod = val => Console.WriteLine($"10dan buyukler icin {val}"); else birMethod = OndanKucukler; birMethod(i); } static void OndanKucukler(int val) { Console.WriteLine("10dan kucukler icin"); } } }
ozanoner/myb
myp242/w2/e10/Program.cs
C#
gpl-3.0
602
using WowPacketParser.Enums; using WowPacketParser.Hotfix; namespace WowPacketParserModule.V9_0_1_36216.Hotfix { [HotfixStructure(DB2Hash.ItemDamageAmmo, HasIndexInData = false)] public class ItemDamageAmmoEntry { public ushort ItemLevel { get; set; } [HotfixArray(7)] public float[] Quality { get; set; } } }
ChipLeo/WowPacketParser
WowPacketParserModule.V9_0_1_36216/Hotfix/ItemDamageAmmoEntry.cs
C#
gpl-3.0
351
// Copyright 2015, 2016 Parity Technologies (UK) Ltd. // This file is part of Parity. // Parity 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. // Parity 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 Parity. If not, see <http://www.gnu.org/licenses/>. use super::super::NetworkConfiguration; use network::NetworkConfiguration as BasicNetworkConfiguration; use std::convert::From; use ipc::binary::{serialize, deserialize}; #[test] fn network_settings_serialize() { let net_cfg = NetworkConfiguration::from(BasicNetworkConfiguration::new_local()); let serialized = serialize(&net_cfg).unwrap(); let deserialized = deserialize::<NetworkConfiguration>(&serialized).unwrap(); assert_eq!(net_cfg.udp_port, deserialized.udp_port); }
immartian/musicoin
sync/src/tests/rpc.rs
Rust
gpl-3.0
1,193
#region License Information (GPL v3) /* ShareX - A program that allows you to take screenshots and share any file type Copyright (c) 2007-2016 ShareX Team This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. Optionally you can also view the license at <http://www.gnu.org/licenses/>. */ #endregion License Information (GPL v3) using CG.Web.MegaApiClient; using ShareX.HelpersLib; using ShareX.UploadersLib.FileUploaders; using ShareX.UploadersLib.ImageUploaders; using ShareX.UploadersLib.TextUploaders; using System.Collections.Generic; namespace ShareX.UploadersLib { public class UploadersConfig : SettingsBase<UploadersConfig> { #region Image uploaders // Imgur public AccountType ImgurAccountType = AccountType.Anonymous; public bool ImgurDirectLink = true; public ImgurThumbnailType ImgurThumbnailType = ImgurThumbnailType.Large_Thumbnail; public bool ImgurUseGIFV = true; public OAuth2Info ImgurOAuth2Info = null; public bool ImgurUploadSelectedAlbum = false; public ImgurAlbumData ImgurSelectedAlbum = null; public List<ImgurAlbumData> ImgurAlbumList = null; // ImageShack public ImageShackOptions ImageShackSettings = new ImageShackOptions(); // TinyPic public AccountType TinyPicAccountType = AccountType.Anonymous; public string TinyPicRegistrationCode = ""; public string TinyPicUsername = ""; public string TinyPicPassword = ""; public bool TinyPicRememberUserPass = false; // Flickr public FlickrAuthInfo FlickrAuthInfo = new FlickrAuthInfo(); public FlickrSettings FlickrSettings = new FlickrSettings(); // Photobucket public OAuthInfo PhotobucketOAuthInfo = null; public PhotobucketAccountInfo PhotobucketAccountInfo = null; // Picasa public OAuth2Info PicasaOAuth2Info = null; public string PicasaAlbumID = ""; // Chevereto public CheveretoUploader CheveretoUploader = new CheveretoUploader("http://ultraimg.com/api/1/upload", "3374fa58c672fcaad8dab979f7687397"); public bool CheveretoDirectURL = true; // SomeImage public string SomeImageAPIKey = ""; public bool SomeImageDirectURL = true; // vgy.me public string VgymeUserKey = ""; #endregion Image uploaders #region Text uploaders // Pastebin public PastebinSettings PastebinSettings = new PastebinSettings(); // Paste.ee public string Paste_eeUserAPIKey = "public"; // Gist public bool GistAnonymousLogin = true; public OAuth2Info GistOAuth2Info = null; public bool GistPublishPublic = false; public bool GistRawURL = false; // uPaste public string UpasteUserKey = ""; public bool UpasteIsPublic = false; // Hastebin public string HastebinCustomDomain = "http://hastebin.com"; public string HastebinSyntaxHighlighting = "hs"; public bool HastebinUseFileExtension = true; // OneTimeSecret public string OneTimeSecretAPIKey = ""; public string OneTimeSecretAPIUsername = ""; #endregion Text uploaders #region File uploaders // Dropbox public OAuth2Info DropboxOAuth2Info = null; //public DropboxAccount DropboxAccount = null; public string DropboxUploadPath = "Public/ShareX/%y/%mo"; public bool DropboxAutoCreateShareableLink = false; public DropboxURLType DropboxURLType = DropboxURLType.Default; public DropboxAccountInfo DropboxAccountInfo = null; // API v1 // FTP Server public List<FTPAccount> FTPAccountList = new List<FTPAccount>(); public int FTPSelectedImage = 0; public int FTPSelectedText = 0; public int FTPSelectedFile = 0; // OneDrive public OAuth2Info OneDriveOAuth2Info = null; public OneDriveFileInfo OneDriveSelectedFolder = OneDrive.RootFolder; public bool OneDriveAutoCreateShareableLink = true; // Google Drive public OAuth2Info GoogleDriveOAuth2Info = null; public bool GoogleDriveIsPublic = true; public bool GoogleDriveDirectLink = false; public bool GoogleDriveUseFolder = false; public string GoogleDriveFolderID = ""; // puush public string PuushAPIKey = ""; // SendSpace public AccountType SendSpaceAccountType = AccountType.Anonymous; public string SendSpaceUsername = ""; public string SendSpacePassword = ""; // Minus public OAuth2Info MinusOAuth2Info = null; public MinusOptions MinusConfig = new MinusOptions(); // Box public OAuth2Info BoxOAuth2Info = null; public BoxFileEntry BoxSelectedFolder = Box.RootFolder; public bool BoxShare = true; // Ge.tt public Ge_ttLogin Ge_ttLogin = null; // Localhostr public string LocalhostrEmail = ""; public string LocalhostrPassword = ""; public bool LocalhostrDirectURL = true; // Shared Folder public List<LocalhostAccount> LocalhostAccountList = new List<LocalhostAccount>(); public int LocalhostSelectedImages = 0; public int LocalhostSelectedText = 0; public int LocalhostSelectedFiles = 0; // Email public string EmailSmtpServer = "smtp.gmail.com"; public int EmailSmtpPort = 587; public string EmailFrom = "[email protected]"; public string EmailPassword = ""; public bool EmailRememberLastTo = true; public string EmailLastTo = ""; public string EmailDefaultSubject = "Sending email from ShareX"; public string EmailDefaultBody = "Screenshot is attached."; public bool EmailAutomaticSend = false; public string EmailAutomaticSendTo = ""; // Jira public string JiraHost = "http://"; public string JiraIssuePrefix = "PROJECT-"; public OAuthInfo JiraOAuthInfo = null; // Mega public MegaApiClient.AuthInfos MegaAuthInfos = null; public string MegaParentNodeId = null; // Amazon S3 public AmazonS3Settings AmazonS3Settings = new AmazonS3Settings() { ObjectPrefix = "ShareX/%y/%mo", UseReducedRedundancyStorage = true }; // ownCloud public string OwnCloudHost = ""; public string OwnCloudUsername = ""; public string OwnCloudPassword = ""; public string OwnCloudPath = "/"; public bool OwnCloudCreateShare = true; public bool OwnCloudDirectLink = false; public bool OwnCloud81Compatibility = false; // MediaFire public string MediaFireUsername = ""; public string MediaFirePassword = ""; public string MediaFirePath = ""; public bool MediaFireUseLongLink = false; // Pushbullet public PushbulletSettings PushbulletSettings = new PushbulletSettings(); // Lambda public LambdaSettings LambdaSettings = new LambdaSettings(); // Lithiio public LithiioSettings LithiioSettings = new LithiioSettings(); // Pomf public PomfUploader PomfUploader = new PomfUploader("https://mixtape.moe/upload.php"); // s-ul public string SulAPIKey = ""; // Seafile public string SeafileAPIURL = ""; public string SeafileAuthToken = ""; public string SeafileRepoID = ""; public string SeafilePath = "/"; public bool SeafileIsLibraryEncrypted = false; public string SeafileEncryptedLibraryPassword = ""; public bool SeafileCreateShareableURL = true; public bool SeafileIgnoreInvalidCert = false; public int SeafileShareDaysToExpire = 0; public string SeafileSharePassword = ""; public string SeafileAccInfoEmail = ""; public string SeafileAccInfoUsage = ""; // Streamable public bool StreamableAnonymous = true; public string StreamableUsername = ""; public string StreamablePassword = ""; public bool StreamableUseDirectURL = false; // Uplea public string UpleaApiKey = ""; public string UpleaEmailAddress = ""; public bool UpleaIsPremiumMember = false; public bool UpleaInstantDownloadEnabled = false; #endregion File uploaders #region URL shorteners // bit.ly public OAuth2Info BitlyOAuth2Info = null; public string BitlyDomain = ""; // Google URL Shortener public AccountType GoogleURLShortenerAccountType = AccountType.Anonymous; public OAuth2Info GoogleURLShortenerOAuth2Info = null; // yourls.org public string YourlsAPIURL = "http://yoursite.com/yourls-api.php"; public string YourlsSignature = ""; public string YourlsUsername = ""; public string YourlsPassword = ""; // adf.ly public string AdFlyAPIKEY = ""; public string AdFlyAPIUID = ""; // coinurl.com public string CoinURLUUID = ""; // polr public string PolrAPIHostname = ""; public string PolrAPIKey = ""; #endregion URL shorteners #region URL sharing services // Twitter public List<OAuthInfo> TwitterOAuthInfoList = new List<OAuthInfo>(); public int TwitterSelectedAccount = 0; public bool TwitterSkipMessageBox = false; public string TwitterDefaultMessage = ""; #endregion URL sharing services #region Custom Uploaders public List<CustomUploaderItem> CustomUploadersList = new List<CustomUploaderItem>(); public int CustomImageUploaderSelected = 0; public int CustomTextUploaderSelected = 0; public int CustomFileUploaderSelected = 0; public int CustomURLShortenerSelected = 0; #endregion Custom Uploaders } }
ElectronicWar/ShareX
ShareX.UploadersLib/UploadersConfig.cs
C#
gpl-3.0
10,792
/* * corem_module.cpp * * This file is part of NEST. * * Copyright (C) 2004 The NEST Initiative * * NEST 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. * * NEST 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 NEST. If not, see <http://www.gnu.org/licenses/>. * */ #include "corem_module.h" // Generated includes: #include "config.h" // include headers with your own stuff #include "corem.h" // Includes from nestkernel: #include "connection_manager_impl.h" #include "connector_model_impl.h" #include "dynamicloader.h" #include "exceptions.h" #include "genericmodel.h" #include "genericmodel_impl.h" #include "kernel_manager.h" #include "model.h" #include "model_manager_impl.h" #include "nestmodule.h" #include "target_identifier.h" // Includes from sli: #include "booldatum.h" #include "integerdatum.h" #include "sliexceptions.h" #include "tokenarray.h" // -- Interface to dynamic module loader --------------------------------------- #if defined( LTX_MODULE ) | defined( LINKED_MODULE ) mynest::corem_module corem_module_LTX_mod; #endif // -- DynModule functions ------------------------------------------------------ mynest::corem_module::corem_module() { #ifdef LINKED_MODULE // register this module at the dynamic loader // this is needed to allow for linking in this module at compile time // all registered modules will be initialized by the main app's dynamic loader nest::DynamicLoaderModule::registerLinkedModule( this ); #endif } mynest::corem_module::~corem_module() { } const std::string mynest::corem_module::name( void ) const { return std::string( "COREM" ); // Return name of the module } const std::string mynest::corem_module::commandstring( void ) const { // Instruct the interpreter to load corem_module-init.sli return std::string( "(corem_module-init) run" ); } //------------------------------------------------------------------------------------- void mynest::corem_module::init( SLIInterpreter* i ) { /* Register a neuron or device model. Give node type as template argument and the name as second argument. */ nest::kernel().model_manager.register_node_model< corem >( "corem" ); } // corem_module::init()
rrcarrillo/COREM
COREM/NEST_Module/corem_module.cpp
C++
gpl-3.0
2,659
using WowPacketParser.Enums; using WowPacketParser.Misc; using WowPacketParser.Parsing; using CoreParsers = WowPacketParser.Parsing.Parsers; namespace WowPacketParserModule.V6_0_2_19033.Parsers { public static class WorldStateHandler { public static void ReadWorldStateBlock(Packet packet, params object[] indexes) { var field = packet.ReadInt32(); var val = packet.ReadInt32(); packet.AddValue("VariableID", field + " - Value: " + val, indexes); } [Parser(Opcode.SMSG_INIT_WORLD_STATES)] public static void HandleInitWorldStates(Packet packet) { packet.ReadInt32<MapId>("MapID"); CoreParsers.WorldStateHandler.CurrentZoneId = packet.ReadInt32<ZoneId>("AreaId"); CoreParsers.WorldStateHandler.CurrentAreaId = packet.ReadInt32<AreaId>("SubareaID"); var numFields = packet.ReadInt32("Field Count"); for (var i = 0; i < numFields; i++) ReadWorldStateBlock(packet); } [Parser(Opcode.SMSG_UPDATE_WORLD_STATE)] public static void HandleUpdateWorldState(Packet packet) { ReadWorldStateBlock(packet); packet.ReadBit("Hidden"); } } }
Carbenium/WowPacketParser
WowPacketParserModule.V6_0_2_19033/Parsers/WorldStateHandler.cs
C#
gpl-3.0
1,265
/* * This file is part of the libsigrok project. * * Copyright (C) 2013 Marc Schink <[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 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include <config.h> #include "protocol.h" extern struct sr_dev_driver ikalogic_scanalogic2_driver_info; extern uint64_t sl2_samplerates[NUM_SAMPLERATES]; static void stop_acquisition(struct sr_dev_inst *sdi) { struct drv_context *drvc = sdi->driver->context; struct dev_context *devc; struct sr_datafeed_packet packet; devc = sdi->priv; /* Remove USB file descriptors from polling. */ usb_source_remove(sdi->session, drvc->sr_ctx); packet.type = SR_DF_END; sr_session_send(devc->cb_data, &packet); sdi->status = SR_ST_ACTIVE; } static void abort_acquisition(struct sr_dev_inst *sdi) { struct drv_context *drvc = sdi->driver->context; struct dev_context *devc; struct sr_datafeed_packet packet; devc = sdi->priv; /* Remove USB file descriptors from polling. */ usb_source_remove(sdi->session, drvc->sr_ctx); packet.type = SR_DF_END; sr_session_send(devc->cb_data, &packet); sdi->driver->dev_close(sdi); } static void buffer_sample_data(const struct sr_dev_inst *sdi) { struct dev_context *devc; unsigned int offset, packet_length; devc = sdi->priv; if (devc->channels[devc->channel]->enabled) { offset = devc->sample_packet * PACKET_NUM_SAMPLE_BYTES; /* * Determine the packet length to ensure that the last packet * will not exceed the buffer size. */ packet_length = MIN(PACKET_NUM_SAMPLE_BYTES, MAX_DEV_SAMPLE_BYTES - offset); /* * Skip the first 4 bytes of the source buffer because they * contain channel and packet information only. */ memcpy(devc->sample_buffer[devc->channel] + offset, devc->xfer_data_in + 4, packet_length); } } static void process_sample_data(const struct sr_dev_inst *sdi) { struct dev_context *devc; struct sr_datafeed_packet packet; struct sr_datafeed_logic logic; uint8_t i, j, tmp, buffer[PACKET_NUM_SAMPLES], *ptr[NUM_CHANNELS]; uint16_t offset, n = 0; int8_t k; devc = sdi->priv; offset = devc->sample_packet * PACKET_NUM_SAMPLE_BYTES; /* * Array of pointers to the sample data of all channels up to the last * enabled one for an uniform access to them. Note that the currently * received samples always belong to the last enabled channel. */ for (i = 0; i < devc->num_enabled_channels - 1; i++) ptr[i] = devc->sample_buffer[devc->channel_map[i]] + offset; /* * Skip the first 4 bytes of the buffer because they contain channel * and packet information only. */ ptr[i] = devc->xfer_data_in + 4; for (i = 0; i < PACKET_NUM_SAMPLE_BYTES; i++) { /* Stop processing if all requested samples are processed. */ if (devc->samples_processed == devc->limit_samples) break; k = 7; if (devc->samples_processed == 0) { /* * Adjust the position of the first sample to be * processed because possibly more samples than * necessary might have been acquired. This is because * the number of acquired samples is always rounded up * to a multiple of 8. */ k = k - (devc->pre_trigger_bytes * 8) + devc->pre_trigger_samples; sr_dbg("Start processing at sample: %d.", 7 - k); /* * Send the trigger before the first sample is * processed if no pre trigger samples were calculated * through the capture ratio. */ if (devc->trigger_type != TRIGGER_TYPE_NONE && devc->pre_trigger_samples == 0) { packet.type = SR_DF_TRIGGER; sr_session_send(devc->cb_data, &packet); } } for (; k >= 0; k--) { /* * Stop processing if all requested samples are * processed. */ if (devc->samples_processed == devc->limit_samples) break; buffer[n] = 0; /* * Extract the current sample for each enabled channel * and store them in the buffer. */ for (j = 0; j < devc->num_enabled_channels; j++) { tmp = (ptr[j][i] & (1 << k)) >> k; buffer[n] |= tmp << devc->channel_map[j]; } n++; devc->samples_processed++; /* * Send all processed samples and the trigger if the * number of processed samples reaches the calculated * number of pre trigger samples. */ if (devc->samples_processed == devc->pre_trigger_samples && devc->trigger_type != TRIGGER_TYPE_NONE) { packet.type = SR_DF_LOGIC; packet.payload = &logic; logic.length = n; logic.unitsize = 1; logic.data = buffer; sr_session_send(devc->cb_data, &packet); packet.type = SR_DF_TRIGGER; sr_session_send(devc->cb_data, &packet); n = 0; } } } if (n > 0) { packet.type = SR_DF_LOGIC; packet.payload = &logic; logic.length = n; logic.unitsize = 1; logic.data = buffer; sr_session_send(devc->cb_data, &packet); } } SR_PRIV int ikalogic_scanalogic2_receive_data(int fd, int revents, void *cb_data) { struct sr_dev_inst *sdi; struct sr_dev_driver *di; struct dev_context *devc; struct drv_context *drvc; struct timeval tv; int64_t current_time, time_elapsed; int ret = 0; (void)fd; (void)revents; if (!(sdi = cb_data)) return TRUE; if (!(devc = sdi->priv)) return TRUE; di = sdi->driver; drvc = di->context; current_time = g_get_monotonic_time(); if (devc->state == STATE_WAIT_DATA_READY && !devc->wait_data_ready_locked) { time_elapsed = current_time - devc->wait_data_ready_time; /* * Check here for stopping in addition to the transfer * callback functions to avoid waiting until the * WAIT_DATA_READY_INTERVAL has expired. */ if (sdi->status == SR_ST_STOPPING) { if (!devc->stopping_in_progress) { devc->next_state = STATE_RESET_AND_IDLE; devc->stopping_in_progress = TRUE; ret = libusb_submit_transfer(devc->xfer_in); } } else if (time_elapsed >= WAIT_DATA_READY_INTERVAL) { devc->wait_data_ready_locked = TRUE; ret = libusb_submit_transfer(devc->xfer_in); } } if (ret != 0) { sr_err("Submit transfer failed: %s.", libusb_error_name(ret)); abort_acquisition(sdi); return TRUE; } tv.tv_sec = 0; tv.tv_usec = 0; libusb_handle_events_timeout_completed(drvc->sr_ctx->libusb_ctx, &tv, NULL); /* Check if an error occurred on a transfer. */ if (devc->transfer_error) abort_acquisition(sdi); return TRUE; } SR_PRIV void LIBUSB_CALL sl2_receive_transfer_in( struct libusb_transfer *transfer) { struct sr_dev_inst *sdi; struct dev_context *devc; uint8_t last_channel; int ret = 0; sdi = transfer->user_data; devc = sdi->priv; if (transfer->status != LIBUSB_TRANSFER_COMPLETED) { sr_err("Transfer to device failed: %s.", libusb_error_name(transfer->status)); devc->transfer_error = TRUE; return; } if (sdi->status == SR_ST_STOPPING && !devc->stopping_in_progress) { devc->next_state = STATE_RESET_AND_IDLE; devc->stopping_in_progress = TRUE; if (libusb_submit_transfer(devc->xfer_in) != 0) { sr_err("Submit transfer failed: %s.", libusb_error_name(ret)); devc->transfer_error = TRUE; } return; } if (devc->state != devc->next_state) sr_spew("State changed from %i to %i.", devc->state, devc->next_state); devc->state = devc->next_state; if (devc->state == STATE_WAIT_DATA_READY) { /* Check if the received data are a valid device status. */ if (devc->xfer_data_in[0] == 0x05) { if (devc->xfer_data_in[1] == STATUS_WAITING_FOR_TRIGGER) sr_dbg("Waiting for trigger."); else if (devc->xfer_data_in[1] == STATUS_SAMPLING) sr_dbg("Sampling in progress."); } /* * Check if the received data are a valid device status and the * sample data are ready. */ if (devc->xfer_data_in[0] == 0x05 && devc->xfer_data_in[1] == STATUS_DATA_READY) { devc->next_state = STATE_RECEIVE_DATA; ret = libusb_submit_transfer(transfer); } else { devc->wait_data_ready_locked = FALSE; devc->wait_data_ready_time = g_get_monotonic_time(); } } else if (devc->state == STATE_RECEIVE_DATA) { last_channel = devc->channel_map[devc->num_enabled_channels - 1]; if (devc->channel < last_channel) { buffer_sample_data(sdi); } else if (devc->channel == last_channel) { process_sample_data(sdi); } else { /* * Stop acquisition because all samples of enabled * channels are processed. */ devc->next_state = STATE_RESET_AND_IDLE; } devc->sample_packet++; devc->sample_packet %= devc->num_sample_packets; if (devc->sample_packet == 0) devc->channel++; ret = libusb_submit_transfer(transfer); } else if (devc->state == STATE_RESET_AND_IDLE) { /* Check if the received data are a valid device status. */ if (devc->xfer_data_in[0] == 0x05) { if (devc->xfer_data_in[1] == STATUS_DEVICE_READY) { devc->next_state = STATE_IDLE; devc->xfer_data_out[0] = CMD_IDLE; } else { devc->next_state = STATE_WAIT_DEVICE_READY; devc->xfer_data_out[0] = CMD_RESET; } ret = libusb_submit_transfer(devc->xfer_out); } else { /* * The received device status is invalid which * indicates that the device is not ready to accept * commands. Request a new device status until a valid * device status is received. */ ret = libusb_submit_transfer(transfer); } } else if (devc->state == STATE_WAIT_DEVICE_READY) { /* Check if the received data are a valid device status. */ if (devc->xfer_data_in[0] == 0x05) { if (devc->xfer_data_in[1] == STATUS_DEVICE_READY) { devc->next_state = STATE_IDLE; devc->xfer_data_out[0] = CMD_IDLE; } else { /* * The received device status is valid but the * device is not ready. Probably the device did * not recognize the last reset. Reset the * device again. */ devc->xfer_data_out[0] = CMD_RESET; } ret = libusb_submit_transfer(devc->xfer_out); } else { /* * The device is not ready and therefore not able to * change to the idle state. Request a new device * status until the device is ready. */ ret = libusb_submit_transfer(transfer); } } if (ret != 0) { sr_err("Submit transfer failed: %s.", libusb_error_name(ret)); devc->transfer_error = TRUE; } } SR_PRIV void LIBUSB_CALL sl2_receive_transfer_out( struct libusb_transfer *transfer) { struct sr_dev_inst *sdi; struct dev_context *devc; int ret = 0; sdi = transfer->user_data; devc = sdi->priv; if (transfer->status != LIBUSB_TRANSFER_COMPLETED) { sr_err("Transfer to device failed: %s.", libusb_error_name(transfer->status)); devc->transfer_error = TRUE; return; } if (sdi->status == SR_ST_STOPPING && !devc->stopping_in_progress) { devc->next_state = STATE_RESET_AND_IDLE; devc->stopping_in_progress = TRUE; if (libusb_submit_transfer(devc->xfer_in) != 0) { sr_err("Submit transfer failed: %s.", libusb_error_name(ret)); devc->transfer_error = TRUE; } return; } if (devc->state != devc->next_state) sr_spew("State changed from %i to %i.", devc->state, devc->next_state); devc->state = devc->next_state; if (devc->state == STATE_IDLE) { stop_acquisition(sdi); } else if (devc->state == STATE_SAMPLE) { devc->next_state = STATE_WAIT_DATA_READY; ret = libusb_submit_transfer(devc->xfer_in); } else if (devc->state == STATE_WAIT_DEVICE_READY) { ret = libusb_submit_transfer(devc->xfer_in); } if (ret != 0) { sr_err("Submit transfer failed: %s.", libusb_error_name(ret)); devc->transfer_error = TRUE; } } SR_PRIV int sl2_set_samplerate(const struct sr_dev_inst *sdi, uint64_t samplerate) { struct dev_context *devc; unsigned int i; devc = sdi->priv; for (i = 0; i < NUM_SAMPLERATES; i++) { if (sl2_samplerates[i] == samplerate) { devc->samplerate = samplerate; devc->samplerate_id = NUM_SAMPLERATES - i - 1; return SR_OK; } } return SR_ERR_ARG; } SR_PRIV int sl2_set_limit_samples(const struct sr_dev_inst *sdi, uint64_t limit_samples) { struct dev_context *devc; devc = sdi->priv; if (limit_samples == 0) { sr_err("Invalid number of limit samples: %" PRIu64 ".", limit_samples); return SR_ERR_ARG; } if (limit_samples > MAX_SAMPLES) limit_samples = MAX_SAMPLES; sr_dbg("Limit samples set to %" PRIu64 ".", limit_samples); devc->limit_samples = limit_samples; return SR_OK; } SR_PRIV int sl2_convert_trigger(const struct sr_dev_inst *sdi) { struct dev_context *devc; struct sr_trigger *trigger; struct sr_trigger_stage *stage; struct sr_trigger_match *match; const GSList *l, *m; int num_triggers_anyedge; devc = sdi->priv; /* Disable the trigger by default. */ devc->trigger_channel = TRIGGER_CHANNEL_0; devc->trigger_type = TRIGGER_TYPE_NONE; if (!(trigger = sr_session_trigger_get(sdi->session))) return SR_OK; if (g_slist_length(trigger->stages) > 1) { sr_err("This device only supports 1 trigger stage."); return SR_ERR; } num_triggers_anyedge = 0; for (l = trigger->stages; l; l = l->next) { stage = l->data; for (m = stage->matches; m; m = m->next) { match = m->data; if (!match->channel->enabled) /* Ignore disabled channels with a trigger. */ continue; devc->trigger_channel = match->channel->index + 1; switch (match->match) { case SR_TRIGGER_RISING: devc->trigger_type = TRIGGER_TYPE_POSEDGE; break; case SR_TRIGGER_FALLING: devc->trigger_type = TRIGGER_TYPE_NEGEDGE; break; case SR_TRIGGER_EDGE: devc->trigger_type = TRIGGER_TYPE_ANYEDGE; num_triggers_anyedge++; break; } } } /* * Set trigger to any edge on all channels if the trigger for each * channel is set to any edge. */ if (num_triggers_anyedge == NUM_CHANNELS) { devc->trigger_channel = TRIGGER_CHANNEL_ALL; devc->trigger_type = TRIGGER_TYPE_ANYEDGE; } sr_dbg("Trigger set to channel 0x%02x and type 0x%02x.", devc->trigger_channel, devc->trigger_type); return SR_OK; } SR_PRIV int sl2_set_capture_ratio(const struct sr_dev_inst *sdi, uint64_t capture_ratio) { struct dev_context *devc; devc = sdi->priv; if (capture_ratio > 100) { sr_err("Invalid capture ratio: %" PRIu64 " %%.", capture_ratio); return SR_ERR_ARG; } sr_info("Capture ratio set to %" PRIu64 " %%.", capture_ratio); devc->capture_ratio = capture_ratio; return SR_OK; } SR_PRIV int sl2_set_after_trigger_delay(const struct sr_dev_inst *sdi, uint64_t after_trigger_delay) { struct dev_context *devc; devc = sdi->priv; if (after_trigger_delay > MAX_AFTER_TRIGGER_DELAY) { sr_err("Invalid after trigger delay: %" PRIu64 " ms.", after_trigger_delay); return SR_ERR_ARG; } sr_info("After trigger delay set to %" PRIu64 " ms.", after_trigger_delay); devc->after_trigger_delay = after_trigger_delay; return SR_OK; } SR_PRIV void sl2_calculate_trigger_samples(const struct sr_dev_inst *sdi) { struct dev_context *devc; uint64_t pre_trigger_samples, post_trigger_samples; uint16_t pre_trigger_bytes, post_trigger_bytes; uint8_t cr; devc = sdi->priv; cr = devc->capture_ratio; /* Ignore the capture ratio if no trigger is enabled. */ if (devc->trigger_type == TRIGGER_TYPE_NONE) cr = 0; pre_trigger_samples = (devc->limit_samples * cr) / 100; post_trigger_samples = (devc->limit_samples * (100 - cr)) / 100; /* * Increase the number of post trigger samples by one to compensate the * possible loss of a sample through integer rounding. */ if (pre_trigger_samples + post_trigger_samples != devc->limit_samples) post_trigger_samples++; /* * The device requires the number of samples in multiples of 8 which * will also be called sample bytes in the following. */ pre_trigger_bytes = pre_trigger_samples / 8; post_trigger_bytes = post_trigger_samples / 8; /* * Round up the number of sample bytes to ensure that at least the * requested number of samples will be acquired. Note that due to this * rounding the buffer to store these sample bytes needs to be at least * one sample byte larger than the minimal number of sample bytes * needed to store the requested samples. */ if (pre_trigger_samples % 8 != 0) pre_trigger_bytes++; if (post_trigger_samples % 8 != 0) post_trigger_bytes++; sr_info("Pre trigger samples: %" PRIu64 ".", pre_trigger_samples); sr_info("Post trigger samples: %" PRIu64 ".", post_trigger_samples); sr_dbg("Pre trigger sample bytes: %" PRIu16 ".", pre_trigger_bytes); sr_dbg("Post trigger sample bytes: %" PRIu16 ".", post_trigger_bytes); devc->pre_trigger_samples = pre_trigger_samples; devc->pre_trigger_bytes = pre_trigger_bytes; devc->post_trigger_bytes = post_trigger_bytes; } SR_PRIV int sl2_get_device_info(struct sr_usb_dev_inst usb, struct device_info *dev_info) { struct drv_context *drvc; uint8_t buffer[PACKET_LENGTH]; int ret; drvc = ikalogic_scanalogic2_driver_info.context; if (!dev_info) return SR_ERR_ARG; if (sr_usb_open(drvc->sr_ctx->libusb_ctx, &usb) != SR_OK) return SR_ERR; /* * Determine if a kernel driver is active on this interface and, if so, * detach it. */ if (libusb_kernel_driver_active(usb.devhdl, USB_INTERFACE) == 1) { ret = libusb_detach_kernel_driver(usb.devhdl, USB_INTERFACE); if (ret < 0) { sr_err("Failed to detach kernel driver: %s.", libusb_error_name(ret)); libusb_close(usb.devhdl); return SR_ERR; } } ret = libusb_claim_interface(usb.devhdl, USB_INTERFACE); if (ret) { sr_err("Failed to claim interface: %s.", libusb_error_name(ret)); libusb_close(usb.devhdl); return SR_ERR; } memset(buffer, 0, sizeof(buffer)); /* * Reset the device to ensure it is in a proper state to request the * device information. */ buffer[0] = CMD_RESET; if ((ret = sl2_transfer_out(usb.devhdl, buffer)) != PACKET_LENGTH) { sr_err("Resetting of device failed: %s.", libusb_error_name(ret)); libusb_release_interface(usb.devhdl, USB_INTERFACE); libusb_close(usb.devhdl); return SR_ERR; } buffer[0] = CMD_INFO; if ((ret = sl2_transfer_out(usb.devhdl, buffer)) != PACKET_LENGTH) { sr_err("Requesting of device information failed: %s.", libusb_error_name(ret)); libusb_release_interface(usb.devhdl, USB_INTERFACE); libusb_close(usb.devhdl); return SR_ERR; } if ((ret = sl2_transfer_in(usb.devhdl, buffer)) != PACKET_LENGTH) { sr_err("Receiving of device information failed: %s.", libusb_error_name(ret)); libusb_release_interface(usb.devhdl, USB_INTERFACE); libusb_close(usb.devhdl); return SR_ERR; } memcpy(&(dev_info->serial), buffer + 1, sizeof(uint32_t)); dev_info->serial = GUINT32_FROM_LE(dev_info->serial); dev_info->fw_ver_major = buffer[5]; dev_info->fw_ver_minor = buffer[6]; buffer[0] = CMD_RESET; if ((ret = sl2_transfer_out(usb.devhdl, buffer)) != PACKET_LENGTH) { sr_err("Device reset failed: %s.", libusb_error_name(ret)); libusb_release_interface(usb.devhdl, USB_INTERFACE); libusb_close(usb.devhdl); return SR_ERR; } /* * Set the device to idle state. If the device is not in idle state it * possibly will reset itself after a few seconds without being used * and thereby close the connection. */ buffer[0] = CMD_IDLE; if ((ret = sl2_transfer_out(usb.devhdl, buffer)) != PACKET_LENGTH) { sr_err("Failed to set device in idle state: %s.", libusb_error_name(ret)); libusb_release_interface(usb.devhdl, USB_INTERFACE); libusb_close(usb.devhdl); return SR_ERR; } ret = libusb_release_interface(usb.devhdl, USB_INTERFACE); if (ret < 0) { sr_err("Failed to release interface: %s.", libusb_error_name(ret)); libusb_close(usb.devhdl); return SR_ERR; } libusb_close(usb.devhdl); return SR_OK; } SR_PRIV int sl2_transfer_in(libusb_device_handle *dev_handle, uint8_t *data) { return libusb_control_transfer(dev_handle, USB_REQUEST_TYPE_IN, USB_HID_GET_REPORT, USB_HID_REPORT_TYPE_FEATURE, USB_INTERFACE, (unsigned char *)data, PACKET_LENGTH, USB_TIMEOUT_MS); } SR_PRIV int sl2_transfer_out(libusb_device_handle *dev_handle, uint8_t *data) { return libusb_control_transfer(dev_handle, USB_REQUEST_TYPE_OUT, USB_HID_SET_REPORT, USB_HID_REPORT_TYPE_FEATURE, USB_INTERFACE, (unsigned char *)data, PACKET_LENGTH, USB_TIMEOUT_MS); }
Matthias-Heidbrink/libsigrok-mh
src/hardware/ikalogic-scanalogic2/protocol.c
C
gpl-3.0
20,616
#ifndef TEST_APKTOOL_H #define TEST_APKTOOL_H #include <QObject> // TestApktool class TestApktool : public QObject { Q_OBJECT private Q_SLOTS: void test(); }; // Apktool class Apktool { public: static bool unpack(const QString FILENAME); static bool get_icons(const QString MANIFEST, bool critical); static bool is_java_installed(); private: static QString read_manifest(const QString FILENAME); static QString parse(QString REGEXP, QString STR); }; #endif // TEST_APKTOOL_H
kefir500/apk-icon-editor
src/tests/test_apktool/test_apktool.h
C
gpl-3.0
512
/*---------------------------------------------------------------------------*\ ========= | \\ / F ield | OpenFOAM: The Open Source CFD Toolbox \\ / O peration | \\ / A nd | OpenQBMM - www.openqbmm.org \\/ M anipulation | ------------------------------------------------------------------------------- Code created 2015-2018 by Alberto Passalacqua Contributed 2018-07-31 to the OpenFOAM Foundation Copyright (C) 2018 OpenFOAM Foundation Copyright (C) 2019 Alberto Passalacqua ------------------------------------------------------------------------------- License This file is derivative work of OpenFOAM. OpenFOAM is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. OpenFOAM is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with OpenFOAM. If not, see <http://www.gnu.org/licenses/>. \*---------------------------------------------------------------------------*/ #include "populationBalanceModel.H" // * * * * * * * * * * * * * * Static Data Members * * * * * * * * * * * * * // namespace Foam { defineTypeNameAndDebug(populationBalanceModel, 0); defineRunTimeSelectionTable(populationBalanceModel, dictionary); } // * * * * * * * * * * * * * * * * Constructors * * * * * * * * * * * * * * // Foam::populationBalanceModel::populationBalanceModel ( const word& name, const dictionary& dict, const surfaceScalarField& phi ) : regIOobject ( IOobject ( IOobject::groupName("populationBalance", name), phi.mesh().time().constant(), phi.mesh(), IOobject::MUST_READ_IF_MODIFIED, IOobject::NO_WRITE, true ) ), name_(name), populationBalanceProperties_ ( phi.mesh().lookupObjectRef<IOdictionary>("populationBalanceProperties") ), phi_(phi) {} // * * * * * * * * * * * * * * * * Destructor * * * * * * * * * * * * * * * // Foam::populationBalanceModel::~populationBalanceModel() {} // ************************************************************************* //
OpenQBMM/OpenQBMM-dev
src/quadratureMethods/populationBalanceModels/populationBalanceModel/populationBalanceModel.C
C++
gpl-3.0
2,579
import leon.collection._ import leon.lang._ import leon.annotation._ import scala.language.postfixOps object Termination { case class Task(tick: BigInt) { require(tick >= 0) } case class Core(tasks: Task, current: Option[BigInt]) def insertBack(): Core = Core(Task(0), None()) def looping(c: Core): Core = { c.current match { case Some(_) => looping(c) case None() => insertBack() } } @ignore def main(args: Array[String]) { looping(Core(Task(0), Some(0))) } }
epfl-lara/leon
src/test/resources/regression/termination/looping/Term.scala
Scala
gpl-3.0
518
/* testuivector.c * * Copyright (C) <2016> Giuseppe Marco Randazzo * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include <stdlib.h> #include "vector.h" /* Extend two vector into one vector*/ void test3() { int i; uivector *v1; uivector *v2; uivector *v1v2; printf("Test 3\n"); initUIVector(&v1); printf("Creating v1\n"); for(i = 1; i < 100; i++){ UIVectorAppend(&v1, i); } printf("Creating v2\n"); NewUIVector(&v2, 100); for(i = 0; i < 100; i++){ v2->data[i] = i; } printf("Appending v1 to v2\n"); v1v2 = UIVectorExtend(v1,v2); printf("Final output\n"); for(i = 0; i < v1v2->size; i++){ printf("%u\n", (unsigned int)v1v2->data[i]); } UIVectorRemoveAt(&v1, 48); DelUIVector(&v1v2); DelUIVector(&v2); DelUIVector(&v1); } /* Initialize the uivector by using initUIVector function and then append values with UIVectorAppend function*/ void test2() { int i; uivector *v; printf("Test 2\n"); initUIVector(&v); printf("Appending 100 value\n"); for(i = 0; i < 100; i++){ UIVectorAppend(&v, i); } printf("Final output\n"); for(i = 0; i < v->size; i++){ printf("%u\n", (unsigned int)v->data[i]); } DelUIVector(&v); } /* Allocate the vector by using the NewDVector function */ void test1() { int i; uivector *v; printf("Test 1\n"); NewUIVector(&v, 100); for(i = 0; i < 100; i++){ v->data[i] = i; } printf("Appending 123 to vector\n"); UIVectorAppend(&v, 123); printf("Final output\n"); for(i = 0; i < v->size; i++){ printf("%u\n", (unsigned int)v->data[i]); } DelUIVector(&v); } int main(void) { test1(); test2(); test3(); return 0; }
gmrandazzo/libscientific
src/testuivector.c
C
gpl-3.0
2,274
/* Output like sprintf to a buffer of specified size. -*- coding: utf-8 -*- Also takes args differently: pass one pointer to the end of the format string in addition to the format string itself. Copyright (C) 1985, 2001-2017 Free Software Foundation, Inc. This file is part of GNU Emacs. GNU Emacs 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. GNU Emacs 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 GNU Emacs. If not, see <http://www.gnu.org/licenses/>. */ /* If you think about replacing this with some similar standard C function of the printf family (such as vsnprintf), please note that this function supports the following Emacs-specific features: . For %c conversions, it produces a string with the multibyte representation of the (`int') argument, suitable for display in an Emacs buffer. . For %s and %c, when field width is specified (e.g., %25s), it accounts for the display width of each character, according to char-width-table. That is, it does not assume that each character takes one column on display. . If the size of the buffer is not enough to produce the formatted string in its entirety, it makes sure that truncation does not chop the last character in the middle of its multibyte sequence, producing an invalid sequence. . It accepts a pointer to the end of the format string, so the format string could include embedded null characters. . It signals an error if the length of the formatted string is about to overflow ptrdiff_t or size_t, to avoid producing strings longer than what Emacs can handle. OTOH, this function supports only a small subset of the standard C formatted output facilities. E.g., %u and %ll are not supported, and precision is ignored %s and %c conversions. (See below for the detailed documentation of what is supported.) However, this is okay, as this function is supposed to be called from `error' and similar functions, and thus does not need to support features beyond those in `Fformat_message', which is used by `error' on the Lisp level. */ /* In the FORMAT argument this function supports ` and ' as directives that output left and right quotes as per ‘text-quoting style’. It also supports the following %-sequences: %s means print a string argument. %S is treated as %s, for loose compatibility with `Fformat_message'. %d means print a `signed int' argument in decimal. %o means print an `unsigned int' argument in octal. %x means print an `unsigned int' argument in hex. %e means print a `double' argument in exponential notation. %f means print a `double' argument in decimal-point notation. %g means print a `double' argument in exponential notation or in decimal-point notation, whichever uses fewer characters. %c means print a `signed int' argument as a single character. %% means produce a literal % character. A %-sequence may contain optional flag, width, and precision specifiers, and a length modifier, as follows: %<flags><width><precision><length>character where flags is [+ -0], width is [0-9]+, precision is .[0-9]+, and length is empty or l or the value of the pD or pI or pMd (sans "d") macros. Also, %% in a format stands for a single % in the output. A % that does not introduce a valid %-sequence causes undefined behavior. The + flag character inserts a + before any positive number, while a space inserts a space before any positive number; these flags only affect %d, %o, %x, %e, %f, and %g sequences. The - and 0 flags affect the width specifier, as described below. For signed numerical arguments only, the ` ' (space) flag causes the result to be prefixed with a space character if it does not start with a sign (+ or -). The l (lower-case letter ell) length modifier is a `long' data type modifier: it is supported for %d, %o, and %x conversions of integral arguments, must immediately precede the conversion specifier, and means that the respective argument is to be treated as `long int' or `unsigned long int'. Similarly, the value of the pD macro means to use ptrdiff_t, the value of the pI macro means to use EMACS_INT or EMACS_UINT, the value of the pMd etc. macros means to use intmax_t or uintmax_t, and the empty length modifier means `int' or `unsigned int'. The width specifier supplies a lower limit for the length of the printed representation. The padding, if any, normally goes on the left, but it goes on the right if the - flag is present. The padding character is normally a space, but (for numerical arguments only) it is 0 if the 0 flag is present. The - flag takes precedence over the 0 flag. For %e, %f, and %g sequences, the number after the "." in the precision specifier says how many decimal places to show; if zero, the decimal point itself is omitted. For %s and %S, the precision specifier is ignored. */ #include <config.h> #include <stdio.h> #include <stdlib.h> #include <float.h> #include <unistd.h> #include <limits.h> #include "lisp.h" /* Since we use the macro CHAR_HEAD_P, we have to include this, but don't have to include others because CHAR_HEAD_P does not contains another macro. */ #include "character.h" /* Generate output from a format-spec FORMAT, terminated at position FORMAT_END. (*FORMAT_END is not part of the format, but must exist and be readable.) Output goes in BUFFER, which has room for BUFSIZE chars. BUFSIZE must be positive. If the output does not fit, truncate it to fit and return BUFSIZE - 1; if this truncates a multibyte sequence, store '\0' into the sequence's first byte. Returns the number of bytes stored into BUFFER, excluding the terminating null byte. Output is always null-terminated. String arguments are passed as C strings. Integers are passed as C integers. */ ptrdiff_t doprnt (char *buffer, ptrdiff_t bufsize, const char *format, const char *format_end, va_list ap) { const char *fmt = format; /* Pointer into format string. */ char *bufptr = buffer; /* Pointer into output buffer. */ /* Enough to handle floating point formats with large numbers. */ enum { SIZE_BOUND_EXTRA = DBL_MAX_10_EXP + 50 }; /* Use this for sprintf unless we need something really big. */ char tembuf[SIZE_BOUND_EXTRA + 50]; /* Size of sprintf_buffer. */ ptrdiff_t size_allocated = sizeof (tembuf); /* Buffer to use for sprintf. Either tembuf or same as BIG_BUFFER. */ char *sprintf_buffer = tembuf; /* Buffer we have got with malloc. */ char *big_buffer = NULL; enum text_quoting_style quoting_style = text_quoting_style (); ptrdiff_t tem = -1; char *string; char fixed_buffer[20]; /* Default buffer for small formatting. */ char *fmtcpy; int minlen; char charbuf[MAX_MULTIBYTE_LENGTH + 1]; /* Used for %c. */ USE_SAFE_ALLOCA; if (format_end == 0) format_end = format + strlen (format); fmtcpy = (format_end - format < sizeof (fixed_buffer) - 1 ? fixed_buffer : SAFE_ALLOCA (format_end - format + 1)); bufsize--; /* Loop until end of format string or buffer full. */ while (fmt < format_end && bufsize > 0) { char const *fmt0 = fmt; char fmtchar = *fmt++; if (fmtchar == '%') { ptrdiff_t size_bound = 0; ptrdiff_t width; /* Columns occupied by STRING on display. */ enum { pDlen = sizeof pD - 1, pIlen = sizeof pI - 1, pMlen = sizeof pMd - 2 }; enum { no_modifier, long_modifier, pD_modifier, pI_modifier, pM_modifier } length_modifier = no_modifier; static char const modifier_len[] = { 0, 1, pDlen, pIlen, pMlen }; int maxmlen = max (max (1, pDlen), max (pIlen, pMlen)); int mlen; /* Copy this one %-spec into fmtcpy. */ string = fmtcpy; *string++ = '%'; while (fmt < format_end) { *string++ = *fmt; if ('0' <= *fmt && *fmt <= '9') { /* Get an idea of how much space we might need. This might be a field width or a precision; e.g. %1.1000f and %1000.1f both might need 1000+ bytes. Parse the width or precision, checking for overflow. */ int n = *fmt - '0'; bool overflow = false; while (fmt + 1 < format_end && '0' <= fmt[1] && fmt[1] <= '9') { overflow |= INT_MULTIPLY_WRAPV (n, 10, &n); overflow |= INT_ADD_WRAPV (n, fmt[1] - '0', &n); *string++ = *++fmt; } if (overflow || min (PTRDIFF_MAX, SIZE_MAX) - SIZE_BOUND_EXTRA < n) error ("Format width or precision too large"); if (size_bound < n) size_bound = n; } else if (! (*fmt == '-' || *fmt == ' ' || *fmt == '.' || *fmt == '+')) break; fmt++; } /* Check for the length modifiers in textual length order, so that longer modifiers override shorter ones. */ for (mlen = 1; mlen <= maxmlen; mlen++) { if (format_end - fmt < mlen) break; if (mlen == 1 && *fmt == 'l') length_modifier = long_modifier; if (mlen == pDlen && memcmp (fmt, pD, pDlen) == 0) length_modifier = pD_modifier; if (mlen == pIlen && memcmp (fmt, pI, pIlen) == 0) length_modifier = pI_modifier; if (mlen == pMlen && memcmp (fmt, pMd, pMlen) == 0) length_modifier = pM_modifier; } mlen = modifier_len[length_modifier]; memcpy (string, fmt + 1, mlen); string += mlen; fmt += mlen; *string = 0; /* Make the size bound large enough to handle floating point formats with large numbers. */ size_bound += SIZE_BOUND_EXTRA; /* Make sure we have that much. */ if (size_bound > size_allocated) { if (big_buffer) xfree (big_buffer); big_buffer = xmalloc (size_bound); sprintf_buffer = big_buffer; size_allocated = size_bound; } minlen = 0; switch (*fmt++) { default: error ("Invalid format operation %s", fmtcpy); /* case 'b': */ case 'l': case 'd': switch (length_modifier) { case no_modifier: { int v = va_arg (ap, int); tem = sprintf (sprintf_buffer, fmtcpy, v); } break; case long_modifier: { long v = va_arg (ap, long); tem = sprintf (sprintf_buffer, fmtcpy, v); } break; case pD_modifier: signed_pD_modifier: { ptrdiff_t v = va_arg (ap, ptrdiff_t); tem = sprintf (sprintf_buffer, fmtcpy, v); } break; case pI_modifier: { EMACS_INT v = va_arg (ap, EMACS_INT); tem = sprintf (sprintf_buffer, fmtcpy, v); } break; case pM_modifier: { intmax_t v = va_arg (ap, intmax_t); tem = sprintf (sprintf_buffer, fmtcpy, v); } break; } /* Now copy into final output, truncating as necessary. */ string = sprintf_buffer; goto doit; case 'o': case 'x': switch (length_modifier) { case no_modifier: { unsigned v = va_arg (ap, unsigned); tem = sprintf (sprintf_buffer, fmtcpy, v); } break; case long_modifier: { unsigned long v = va_arg (ap, unsigned long); tem = sprintf (sprintf_buffer, fmtcpy, v); } break; case pD_modifier: goto signed_pD_modifier; case pI_modifier: { EMACS_UINT v = va_arg (ap, EMACS_UINT); tem = sprintf (sprintf_buffer, fmtcpy, v); } break; case pM_modifier: { uintmax_t v = va_arg (ap, uintmax_t); tem = sprintf (sprintf_buffer, fmtcpy, v); } break; } /* Now copy into final output, truncating as necessary. */ string = sprintf_buffer; goto doit; case 'f': case 'e': case 'g': { double d = va_arg (ap, double); tem = sprintf (sprintf_buffer, fmtcpy, d); /* Now copy into final output, truncating as necessary. */ string = sprintf_buffer; goto doit; } case 'S': string[-1] = 's'; case 's': if (fmtcpy[1] != 's') minlen = atoi (&fmtcpy[1]); string = va_arg (ap, char *); tem = strlen (string); if (STRING_BYTES_BOUND < tem) error ("String for %%s or %%S format is too long"); width = strwidth (string, tem); goto doit1; /* Copy string into final output, truncating if no room. */ doit: eassert (0 <= tem); /* Coming here means STRING contains ASCII only. */ if (STRING_BYTES_BOUND < tem) error ("Format width or precision too large"); width = tem; doit1: /* We have already calculated: TEM -- length of STRING, WIDTH -- columns occupied by STRING when displayed, and MINLEN -- minimum columns of the output. */ if (minlen > 0) { while (minlen > width && bufsize > 0) { *bufptr++ = ' '; bufsize--; minlen--; } minlen = 0; } if (tem > bufsize) { /* Truncate the string at character boundary. */ tem = bufsize; do { tem--; if (CHAR_HEAD_P (string[tem])) { if (BYTES_BY_CHAR_HEAD (string[tem]) <= bufsize - tem) tem = bufsize; break; } } while (tem != 0); memcpy (bufptr, string, tem); bufptr[tem] = 0; /* Trigger exit from the loop, but make sure we return to the caller a value which will indicate that the buffer was too small. */ bufptr += bufsize; bufsize = 0; continue; } memcpy (bufptr, string, tem); bufptr += tem; bufsize -= tem; if (minlen < 0) { while (minlen < - width && bufsize > 0) { *bufptr++ = ' '; bufsize--; minlen++; } minlen = 0; } continue; case 'c': { int chr = va_arg (ap, int); tem = CHAR_STRING (chr, (unsigned char *) charbuf); string = charbuf; string[tem] = 0; width = strwidth (string, tem); if (fmtcpy[1] != 'c') minlen = atoi (&fmtcpy[1]); goto doit1; } case '%': fmt--; /* Drop thru and this % will be treated as normal */ } } char const *src; ptrdiff_t srclen; if (quoting_style == CURVE_QUOTING_STYLE && fmtchar == '`') src = uLSQM, srclen = sizeof uLSQM - 1; else if (quoting_style == CURVE_QUOTING_STYLE && fmtchar == '\'') src = uRSQM, srclen = sizeof uRSQM - 1; else if (quoting_style == STRAIGHT_QUOTING_STYLE && fmtchar == '`') src = "'", srclen = 1; else { while (fmt < format_end && !CHAR_HEAD_P (*fmt)) fmt++; src = fmt0, srclen = fmt - fmt0; } if (bufsize < srclen) { /* Truncate, but return value that will signal to caller that the buffer was too small. */ do *bufptr++ = '\0'; while (--bufsize != 0); } else { do *bufptr++ = *src++; while (--srclen != 0); } } /* If we had to malloc something, free it. */ xfree (big_buffer); *bufptr = 0; /* Make sure our string ends with a '\0' */ SAFE_FREE (); return bufptr - buffer; } /* Format to an unbounded buffer BUF. This is like sprintf, except it is not limited to returning an 'int' so it doesn't have a silly 2 GiB limit on typical 64-bit hosts. However, it is limited to the Emacs-style formats that doprnt supports, and it requotes ` and ' as per ‘text-quoting-style’. Return the number of bytes put into BUF, excluding the terminating '\0'. */ ptrdiff_t esprintf (char *buf, char const *format, ...) { ptrdiff_t nbytes; va_list ap; va_start (ap, format); nbytes = doprnt (buf, TYPE_MAXIMUM (ptrdiff_t), format, 0, ap); va_end (ap); return nbytes; } #if HAVE_MODULES || (defined HAVE_X_WINDOWS && defined USE_X_TOOLKIT) /* Format to buffer *BUF of positive size *BUFSIZE, reallocating *BUF and updating *BUFSIZE if the buffer is too small, and otherwise behaving line esprintf. When reallocating, free *BUF unless it is equal to NONHEAPBUF, and if BUFSIZE_MAX is nonnegative then signal memory exhaustion instead of growing the buffer size past BUFSIZE_MAX. */ ptrdiff_t exprintf (char **buf, ptrdiff_t *bufsize, char const *nonheapbuf, ptrdiff_t bufsize_max, char const *format, ...) { ptrdiff_t nbytes; va_list ap; va_start (ap, format); nbytes = evxprintf (buf, bufsize, nonheapbuf, bufsize_max, format, ap); va_end (ap); return nbytes; } #endif /* Act like exprintf, except take a va_list. */ ptrdiff_t evxprintf (char **buf, ptrdiff_t *bufsize, char const *nonheapbuf, ptrdiff_t bufsize_max, char const *format, va_list ap) { for (;;) { ptrdiff_t nbytes; va_list ap_copy; va_copy (ap_copy, ap); nbytes = doprnt (*buf, *bufsize, format, 0, ap_copy); va_end (ap_copy); if (nbytes < *bufsize - 1) return nbytes; if (*buf != nonheapbuf) { xfree (*buf); *buf = NULL; } *buf = xpalloc (NULL, bufsize, 1, bufsize_max, 1); } }
BusFactor1Inc/ELPE
src/doprnt.c
C
gpl-3.0
17,321
using System; using System.Collections.Generic; using System.Text; namespace OpenDentBusiness.HL7 { ///<summary>A component in HL7 is a subportion of a field. For example, a name field might have LName and FName components. Components are 0-based.</summary> public class ComponentHL7 { public string ComponentVal; public ComponentHL7(string componentVal) { ComponentVal=componentVal; } public override string ToString() { return ComponentVal; } } }
eae/opendental
OpenDentBusiness/HL7/ComponentHL7.cs
C#
gpl-3.0
476
/* * Joinery -- Data frames for Java * Copyright (c) 2014, 2015 IBM Corp. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package joinery; import static org.junit.Assert.assertArrayEquals; import org.junit.Before; import org.junit.Test; public class DataFrameInspectionTest { private DataFrame<Object> df; @Before public void setUp() throws Exception { df = DataFrame.readCsv(ClassLoader.getSystemResourceAsStream("inspection.csv")); } @Test public void testNumeric() { assertArrayEquals( new Object[] { 1L, 2L, 3L, 2L, 3L, 4L }, df.numeric().toArray() ); } @Test public void testNonNumeric() { assertArrayEquals( new Object[] { "alpha", "beta", "gamma" }, df.nonnumeric().toArray() ); } }
lejon/joinery
src/test/java/joinery/DataFrameInspectionTest.java
Java
gpl-3.0
1,455
#ifndef TEST_TYPEMGR_H #define TEST_TYPEMGR_H #include <cppunit/TestFixture.h> #include <cppunit/TestAssert.h> #include <cppunit/TestCaller.h> #include <cppunit/TestSuite.h> #include <cppunit/TestCase.h> #include <cppunit/extensions/TestFactoryRegistry.h> #include <cppunit/extensions/HelperMacros.h> class TypemgrTestFixture : public CppUnit::TestFixture { public: TypemgrTestFixture(); virtual ~TypemgrTestFixture(); void setUp(); void tearDown(); /** @name Test Cases */ // @{ void testConstruction(); void testSameClassReturnedBuiltin(); // @} /** \cond internal */ CPPUNIT_TEST_SUITE( TypemgrTestFixture ); CPPUNIT_TEST( testConstruction ); CPPUNIT_TEST( testSameClassReturnedBuiltin ); CPPUNIT_TEST_SUITE_END(); /** \endcond */ }; #endif
drb27/fl
src/interpreter/tests/test-typemgr.h
C
gpl-3.0
811
// Copyright 2015, 2016 Parity Technologies (UK) Ltd. // This file is part of Parity. // Parity 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. // Parity 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 Parity. If not, see <http://www.gnu.org/licenses/>. //! URL Endpoint traits use hyper::{self, server, net}; use std::collections::BTreeMap; #[derive(Debug, PartialEq, Default, Clone)] pub struct EndpointPath { pub app_id: String, pub host: String, pub port: u16, pub using_dapps_domains: bool, } #[derive(Debug, PartialEq, Clone)] pub struct EndpointInfo { pub name: String, pub description: String, pub version: String, pub author: String, pub icon_url: String, } pub type Endpoints = BTreeMap<String, Box<Endpoint>>; pub type Handler = server::Handler<net::HttpStream> + Send; pub trait Endpoint : Send + Sync { fn info(&self) -> Option<&EndpointInfo> { None } fn to_handler(&self, _path: EndpointPath) -> Box<Handler> { panic!("This Endpoint is asynchronous and requires Control object."); } fn to_async_handler(&self, path: EndpointPath, _control: hyper::Control) -> Box<Handler> { self.to_handler(path) } }
immartian/musicoin
dapps/src/endpoint.rs
Rust
gpl-3.0
1,597
/* Copyright (c) 2003-2014, CKSource - Frederico Knabben. All rights reserved. For licensing, see LICENSE.html or http://ckeditor.com/license */ CKEDITOR.plugins.setLang( 'scayt', 'it', { btn_about: 'About COMS', btn_dictionaries: 'Dizionari', btn_disable: 'Disabilita COMS', btn_enable: 'Abilita COMS', btn_langs:'Lingue', btn_options: 'Opzioni', text_title: 'Controllo Ortografico Mentre Scrivi' });
vanpouckesven/cosnics
src/Chamilo/Libraries/Resources/Javascript/HtmlEditor/Ckeditor/src/plugins/scayt/lang/it.js
JavaScript
gpl-3.0
425
/* * Twidere - Twitter client for Android * * Copyright (C) 2012-2014 Mariotaku Lee <[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 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.mariotaku.twidere.fragment.support; import static org.mariotaku.twidere.util.Utils.configBaseCardAdapter; import static org.mariotaku.twidere.util.Utils.getActivatedAccountIds; import static org.mariotaku.twidere.util.Utils.getNewestMessageIdsFromDatabase; import static org.mariotaku.twidere.util.Utils.getOldestMessageIdsFromDatabase; import static org.mariotaku.twidere.util.Utils.openDirectMessagesConversation; import android.content.BroadcastReceiver; import android.content.ContentResolver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.content.SharedPreferences; import android.database.Cursor; import android.net.Uri; import android.os.Bundle; import android.support.v4.app.LoaderManager.LoaderCallbacks; import android.support.v4.content.CursorLoader; import android.support.v4.content.Loader; import android.view.MenuItem; import android.view.View; import android.widget.AbsListView; import android.widget.ListView; import org.mariotaku.querybuilder.Columns.Column; import org.mariotaku.querybuilder.RawItemArray; import org.mariotaku.querybuilder.Where; import org.mariotaku.twidere.R; import org.mariotaku.twidere.adapter.DirectMessageConversationEntriesAdapter; import org.mariotaku.twidere.provider.TweetStore.Accounts; import org.mariotaku.twidere.provider.TweetStore.DirectMessages; import org.mariotaku.twidere.provider.TweetStore.Statuses; import org.mariotaku.twidere.task.AsyncTask; import org.mariotaku.twidere.util.AsyncTwitterWrapper; import org.mariotaku.twidere.util.MultiSelectManager; import org.mariotaku.twidere.util.content.SupportFragmentReloadCursorObserver; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Set; public class DirectMessagesFragment extends BasePullToRefreshListFragment implements LoaderCallbacks<Cursor> { private final SupportFragmentReloadCursorObserver mReloadContentObserver = new SupportFragmentReloadCursorObserver( this, 0, this); private final BroadcastReceiver mStatusReceiver = new BroadcastReceiver() { @Override public void onReceive(final Context context, final Intent intent) { if (getActivity() == null || !isAdded() || isDetached()) return; final String action = intent.getAction(); if (BROADCAST_TASK_STATE_CHANGED.equals(action)) { updateRefreshState(); } } }; private MultiSelectManager mMultiSelectManager; private SharedPreferences mPreferences; private ListView mListView; private boolean mLoadMoreAutomatically; private DirectMessageConversationEntriesAdapter mAdapter; private int mFirstVisibleItem; private final Map<Long, Set<Long>> mUnreadCountsToRemove = Collections .synchronizedMap(new HashMap<Long, Set<Long>>()); private final Set<Integer> mReadPositions = Collections.synchronizedSet(new HashSet<Integer>()); private RemoveUnreadCountsTask mRemoveUnreadCountsTask; @Override public DirectMessageConversationEntriesAdapter getListAdapter() { return (DirectMessageConversationEntriesAdapter) super.getListAdapter(); } public final Map<Long, Set<Long>> getUnreadCountsToRemove() { return mUnreadCountsToRemove; } @Override public void onActivityCreated(final Bundle savedInstanceState) { mPreferences = getSharedPreferences(SHARED_PREFERENCES_NAME, Context.MODE_PRIVATE); super.onActivityCreated(savedInstanceState); mMultiSelectManager = getMultiSelectManager(); mAdapter = new DirectMessageConversationEntriesAdapter(getActivity()); setListAdapter(mAdapter); mListView = getListView(); if (!mPreferences.getBoolean(KEY_PLAIN_LIST_STYLE, false)) { mListView.setDivider(null); } mListView.setSelector(android.R.color.transparent); getLoaderManager().initLoader(0, null, this); setListShown(false); } @Override public Loader<Cursor> onCreateLoader(final int id, final Bundle args) { final Uri uri = DirectMessages.ConversationEntries.CONTENT_URI; final long account_id = getAccountId(); final long[] account_ids = account_id > 0 ? new long[] { account_id } : getActivatedAccountIds(getActivity()); final boolean no_account_selected = account_ids.length == 0; setEmptyText(no_account_selected ? getString(R.string.no_account_selected) : null); if (!no_account_selected) { getListView().setEmptyView(null); } final Where account_where = Where.in(new Column(Statuses.ACCOUNT_ID), new RawItemArray(account_ids)); return new CursorLoader(getActivity(), uri, null, account_where.getSQL(), null, null); } @Override public void onListItemClick(final ListView l, final View v, final int position, final long id) { if (mMultiSelectManager.isActive()) return; final int pos = position - l.getHeaderViewsCount(); final long conversationId = mAdapter.getConversationId(pos); final long accountId = mAdapter.getAccountId(pos); mReadPositions.add(pos); removeUnreadCounts(); if (conversationId > 0 && accountId > 0) { openDirectMessagesConversation(getActivity(), accountId, conversationId); } } @Override public void onLoaderReset(final Loader<Cursor> loader) { mAdapter.changeCursor(null); } @Override public void onLoadFinished(final Loader<Cursor> loader, final Cursor cursor) { if (getActivity() == null) return; mFirstVisibleItem = -1; mAdapter.changeCursor(cursor); mAdapter.setShowAccountColor(getActivatedAccountIds(getActivity()).length > 1); setListShown(true); } @Override public boolean onOptionsItemSelected(final MenuItem item) { switch (item.getItemId()) { case MENU_COMPOSE: { openDirectMessagesConversation(getActivity(), -1, -1); break; } } return super.onOptionsItemSelected(item); } @Override public void onRefreshFromEnd() { if (mLoadMoreAutomatically) return; loadMoreMessages(); } @Override public void onRefreshFromStart() { new AsyncTask<Void, Void, long[][]>() { @Override protected long[][] doInBackground(final Void... params) { final long[][] result = new long[2][]; result[0] = getActivatedAccountIds(getActivity()); result[1] = getNewestMessageIdsFromDatabase(getActivity(), DirectMessages.Inbox.CONTENT_URI); return result; } @Override protected void onPostExecute(final long[][] result) { final AsyncTwitterWrapper twitter = getTwitterWrapper(); if (twitter == null) return; twitter.getReceivedDirectMessagesAsync(result[0], null, result[1]); twitter.getSentDirectMessagesAsync(result[0], null, null); } }.execute(); } @Override public void onResume() { super.onResume(); mListView.setFastScrollEnabled(mPreferences.getBoolean(KEY_FAST_SCROLL_THUMB, false)); configBaseCardAdapter(getActivity(), mAdapter); mLoadMoreAutomatically = mPreferences.getBoolean(KEY_LOAD_MORE_AUTOMATICALLY, false); } @Override public void onScroll(final AbsListView view, final int firstVisibleItem, final int visibleItemCount, final int totalItemCount) { super.onScroll(view, firstVisibleItem, visibleItemCount, totalItemCount); addReadPosition(firstVisibleItem); } @Override public void onScrollStateChanged(final AbsListView view, final int scrollState) { switch (scrollState) { case SCROLL_STATE_FLING: case SCROLL_STATE_TOUCH_SCROLL: { break; } case SCROLL_STATE_IDLE: { for (int i = mListView.getFirstVisiblePosition(), j = mListView.getLastVisiblePosition(); i < j; i++) { mReadPositions.add(i); } removeUnreadCounts(); break; } } } @Override public void onStart() { super.onStart(); final ContentResolver resolver = getContentResolver(); resolver.registerContentObserver(Accounts.CONTENT_URI, true, mReloadContentObserver); final IntentFilter filter = new IntentFilter(); filter.addAction(BROADCAST_TASK_STATE_CHANGED); registerReceiver(mStatusReceiver, filter); } @Override public void onStop() { unregisterReceiver(mStatusReceiver); final ContentResolver resolver = getContentResolver(); resolver.unregisterContentObserver(mReloadContentObserver); super.onStop(); } @Override public boolean scrollToStart() { final AsyncTwitterWrapper twitter = getTwitterWrapper(); final int tabPosition = getTabPosition(); if (twitter != null && tabPosition >= 0) { twitter.clearUnreadCountAsync(tabPosition); } return super.scrollToStart(); } @Override public void setUserVisibleHint(final boolean isVisibleToUser) { super.setUserVisibleHint(isVisibleToUser); if (isVisibleToUser) { updateRefreshState(); } } protected long getAccountId() { final Bundle args = getArguments(); return args != null ? args.getLong(EXTRA_ACCOUNT_ID, -1) : -1; } @Override protected void onListTouched() { final AsyncTwitterWrapper twitter = getTwitterWrapper(); if (twitter != null) { twitter.clearNotificationAsync(NOTIFICATION_ID_DIRECT_MESSAGES, getAccountId()); } } @Override protected void onReachedBottom() { if (!mLoadMoreAutomatically) return; loadMoreMessages(); } protected void updateRefreshState() { final AsyncTwitterWrapper twitter = getTwitterWrapper(); if (twitter == null || !getUserVisibleHint()) return; setRefreshing(twitter.isReceivedDirectMessagesRefreshing() || twitter.isSentDirectMessagesRefreshing()); } private void addReadPosition(final int firstVisibleItem) { if (mFirstVisibleItem != firstVisibleItem) { mReadPositions.add(firstVisibleItem); } mFirstVisibleItem = firstVisibleItem; } private void addUnreadCountsToRemove(final long account_id, final long id) { if (mUnreadCountsToRemove.containsKey(account_id)) { final Set<Long> counts = mUnreadCountsToRemove.get(account_id); counts.add(id); } else { final Set<Long> counts = new HashSet<Long>(); counts.add(id); mUnreadCountsToRemove.put(account_id, counts); } } private void loadMoreMessages() { if (isRefreshing()) return; new AsyncTask<Void, Void, long[][]>() { @Override protected long[][] doInBackground(final Void... params) { final long[][] result = new long[3][]; result[0] = getActivatedAccountIds(getActivity()); result[1] = getOldestMessageIdsFromDatabase(getActivity(), DirectMessages.Inbox.CONTENT_URI); result[2] = getOldestMessageIdsFromDatabase(getActivity(), DirectMessages.Outbox.CONTENT_URI); return result; } @Override protected void onPostExecute(final long[][] result) { final AsyncTwitterWrapper twitter = getTwitterWrapper(); if (twitter == null) return; twitter.getReceivedDirectMessagesAsync(result[0], result[1], null); twitter.getSentDirectMessagesAsync(result[0], result[2], null); } }.execute(); } private void removeUnreadCounts() { if (mRemoveUnreadCountsTask != null && mRemoveUnreadCountsTask.getStatus() == AsyncTask.Status.RUNNING) return; mRemoveUnreadCountsTask = new RemoveUnreadCountsTask(mReadPositions, this); mRemoveUnreadCountsTask.execute(); } static class RemoveUnreadCountsTask extends AsyncTask<Void, Void, Void> { private final Set<Integer> read_positions; private final DirectMessageConversationEntriesAdapter adapter; private final DirectMessagesFragment fragment; RemoveUnreadCountsTask(final Set<Integer> read_positions, final DirectMessagesFragment fragment) { this.read_positions = Collections.synchronizedSet(new HashSet<Integer>(read_positions)); this.fragment = fragment; adapter = fragment.getListAdapter(); } @Override protected Void doInBackground(final Void... params) { for (final int pos : read_positions) { final long id = adapter.getConversationId(pos), account_id = adapter.getAccountId(pos); fragment.addUnreadCountsToRemove(account_id, id); } return null; } @Override protected void onPostExecute(final Void result) { final AsyncTwitterWrapper twitter = fragment.getTwitterWrapper(); if (twitter != null) { twitter.removeUnreadCountsAsync(fragment.getTabPosition(), fragment.getUnreadCountsToRemove()); } } } }
0359xiaodong/twidere
src/org/mariotaku/twidere/fragment/support/DirectMessagesFragment.java
Java
gpl-3.0
12,757
/****************************************************************************** * Project: PROJ.4 * Purpose: Implementation of pj_log() function. * Author: Frank Warmerdam, [email protected] * ****************************************************************************** * Copyright (c) 2010, Frank Warmerdam * * 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 <stdarg.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include "proj.h" #include "proj_internal.h" /************************************************************************/ /* pj_stderr_logger() */ /************************************************************************/ void pj_stderr_logger( void *app_data, int level, const char *msg ) { (void) app_data; (void) level; fprintf( stderr, "%s\n", msg ); } /************************************************************************/ /* pj_vlog() */ /************************************************************************/ void pj_vlog( projCtx ctx, int level, const char *fmt, va_list args ); /* Workhorse for the log functions - relates to pj_log as vsprintf relates to sprintf */ void pj_vlog( projCtx ctx, int level, const char *fmt, va_list args ) { char *msg_buf; int debug_level = ctx->debug_level; int shutup_unless_errno_set = debug_level < 0; /* For negative debug levels, we first start logging when errno is set */ if (ctx->last_errno==0 && shutup_unless_errno_set) return; if (debug_level < 0) debug_level = -debug_level; if( level > debug_level ) return; msg_buf = (char *) malloc(100000); if( msg_buf == nullptr ) return; /* we should use vsnprintf where available once we add configure detect.*/ vsprintf( msg_buf, fmt, args ); ctx->logger( ctx->logger_app_data, level, msg_buf ); free( msg_buf ); } /************************************************************************/ /* pj_log() */ /************************************************************************/ void pj_log( projCtx ctx, int level, const char *fmt, ... ) { va_list args; if( level > ctx->debug_level ) return; va_start( args, fmt ); pj_vlog( ctx, level, fmt, args ); va_end( args ); }
zcobell/QADCModules
thirdparty/proj-7.2.0/src/log.cpp
C++
gpl-3.0
3,538
/* * ============================================================================= * Simplified BSD License, see http://www.opensource.org/licenses/ * ----------------------------------------------------------------------------- * Copyright (c) 2008-2009, Marco Terzer, Zurich, Switzerland * 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 Swiss Federal Institute of Technology Zurich * nor the names of its contributors may be used to endorse or promote * products derived from this software without specific prior written * permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * ============================================================================= */ package ch.javasoft.metabolic.efm.adj.incore.tree.search; import java.io.IOException; import ch.javasoft.bitset.IBitSet; import ch.javasoft.metabolic.efm.adj.incore.tree.AbstractRoot; import ch.javasoft.metabolic.efm.adj.incore.tree.Node; import ch.javasoft.metabolic.efm.adj.incore.tree.TreeFactory; import ch.javasoft.metabolic.efm.column.AdjCandidates; import ch.javasoft.metabolic.efm.column.Column; import ch.javasoft.metabolic.efm.config.Config; import ch.javasoft.metabolic.efm.memory.SortableMemory; import ch.javasoft.metabolic.efm.model.EfmModel; /** * The <tt>SearchRoot</tt> performs the combinatorial adjacency test with a * linear search of the superset in all three lists. */ public class LinearSearchRoot<T /*traversing token*/> extends AbstractRoot<T> { private final int mRequiredZeroCount; //TODO do this nicer (memory!) public LinearSearchRoot(Config config, EfmModel model, TreeFactory<T> treeFactory, final int requiredZeroCount, final SortableMemory<Column> posCols, final SortableMemory<Column> zeroCols, final SortableMemory<Column> negCols) throws IOException { super(config, model, treeFactory, posCols, zeroCols, negCols); mRequiredZeroCount = requiredZeroCount; } public boolean isRequiredZeroBitCount(T token, int count) { return count >= mRequiredZeroCount; } public void filterAdjacentPairs(T token, Node<T> nodeA, Node<T> nodeB, IBitSet filterCutPattern, SortableMemory<Column> posCols, SortableMemory<Column> zeroCols, SortableMemory<Column> negCols, AdjCandidates<Column> candidates) throws IOException { int len = candidates.size(); int index = 0; while (index < len) { if (hasSuperSet(candidates, index, zeroCols) || hasSuperSet(candidates, index, posCols) || hasSuperSet(candidates, index, negCols) ) { len--; if (index != len) { candidates.swap(index, len); } candidates.removeLast(); } else { index++; } } } private boolean hasSuperSet(AdjCandidates<Column> candidates, int pairIndex, SortableMemory<Column> cols) throws IOException { return candidates.hasSuperSet(pairIndex, cols, 0, cols.getColumnCount()); } }
lmarmiesse/Jvaro
20120810_regEfmtool_2.0/ch/javasoft/metabolic/efm/adj/incore/tree/search/LinearSearchRoot.java
Java
gpl-3.0
4,142
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta name="robots" content="index, follow, all" /> <title>Symfony\Component\Intl\DateFormatter\DateFormat\MinuteTransformer | </title> <link rel="stylesheet" type="text/css" href="../../../../../stylesheet.css"> </head> <body id="class"> <div class="header"> <ul> <li><a href="../../../../../classes.html">Classes</a></li> <li><a href="../../../../../namespaces.html">Namespaces</a></li> <li><a href="../../../../../interfaces.html">Interfaces</a></li> <li><a href="../../../../../traits.html">Traits</a></li> <li><a href="../../../../../doc-index.html">Index</a></li> </ul> <div id="title"></div> <div class="type">Class</div> <h1><a href="../DateFormat.html">Symfony\Component\Intl\DateFormatter\DateFormat</a>\MinuteTransformer</h1> </div> <div class="content"> <p> class <strong>MinuteTransformer</strong> extends <a href="Transformer.html"><abbr title="Symfony\Component\Intl\DateFormatter\DateFormat\Transformer">Transformer</abbr></a></p> <div class="description"> <p>Parser and formatter for minute format</p> <p> </p> </div> <h2>Methods</h2> <table> <tr> <td class="type"> string </td> <td class="last"> <a href="MinuteTransformer.html#method_format">format</a>(<abbr title="Symfony\Component\Intl\DateFormatter\DateFormat\DateTime">DateTime</abbr> $dateTime, int $length) <p>Format a value using a configured DateTime as date/time source</p> </td> <td></td> </tr> <tr> <td class="type"> string </td> <td class="last"> <a href="MinuteTransformer.html#method_getReverseMatchingRegExp">getReverseMatchingRegExp</a>(int $length) <p>Returns a reverse matching regular expression of a string generated by format()</p> </td> <td></td> </tr> <tr> <td class="type"> array </td> <td class="last"> <a href="MinuteTransformer.html#method_extractDateOptions">extractDateOptions</a>(string $matched, int $length) <p>Extract date options from a matched value returned by the processing of the reverse matching regular expression</p> </td> <td></td> </tr> </table> <h2>Details</h2> <h3 id="method_format"> <div class="location">at line 24</div> <code> public string <strong>format</strong>(<abbr title="Symfony\Component\Intl\DateFormatter\DateFormat\DateTime">DateTime</abbr> $dateTime, int $length)</code> </h3> <div class="details"> <p>Format a value using a configured DateTime as date/time source</p> <p> </p> <div class="tags"> <h4>Parameters</h4> <table> <tr> <td><abbr title="Symfony\Component\Intl\DateFormatter\DateFormat\DateTime">DateTime</abbr></td> <td>$dateTime</td> <td>A DateTime object to be used to generate the formatted value</td> </tr> <tr> <td>int</td> <td>$length</td> <td>The formatted value string length</td> </tr> </table> <h4>Return Value</h4> <table> <tr> <td>string</td> <td>The formatted value</td> </tr> </table> </div> </div> <h3 id="method_getReverseMatchingRegExp"> <div class="location">at line 34</div> <code> public string <strong>getReverseMatchingRegExp</strong>(int $length)</code> </h3> <div class="details"> <p>Returns a reverse matching regular expression of a string generated by format()</p> <p> </p> <div class="tags"> <h4>Parameters</h4> <table> <tr> <td>int</td> <td>$length</td> <td>The length of the value to be reverse matched</td> </tr> </table> <h4>Return Value</h4> <table> <tr> <td>string</td> <td>The reverse matching regular expression</td> </tr> </table> </div> </div> <h3 id="method_extractDateOptions"> <div class="location">at line 42</div> <code> public array <strong>extractDateOptions</strong>(string $matched, int $length)</code> </h3> <div class="details"> <p>Extract date options from a matched value returned by the processing of the reverse matching regular expression</p> <p> </p> <div class="tags"> <h4>Parameters</h4> <table> <tr> <td>string</td> <td>$matched</td> <td>The matched value</td> </tr> <tr> <td>int</td> <td>$length</td> <td>The length of the Transformer pattern string</td> </tr> </table> <h4>Return Value</h4> <table> <tr> <td>array</td> <td>An associative array</td> </tr> </table> </div> </div> </div> <div id="footer"> Generated by <a href="http://sami.sensiolabs.org/" target="_top">Sami, the API Documentation Generator</a>. </div> <script type="text/javascript"> var _gaq = _gaq || []; _gaq.push(['_setAccount', 'UA-89393-6']); _gaq.push(['_setDomainName', '.symfony.com']); _gaq.push(['_trackPageview']); (function() { var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true; ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s); })(); </script> </body> </html>
P3PO/the-phpjs-local-docs-collection
symfony2/api/2.5/Symfony/Component/Intl/DateFormatter/DateFormat/MinuteTransformer.html
HTML
gpl-3.0
7,081
/* Copyright © 2015 by The qTox Project This file is part of qTox, a Qt-based graphical interface for Tox. qTox is libre 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. qTox 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 qTox. If not, see <http://www.gnu.org/licenses/>. */ #include "contentdialog.h" #include <QBoxLayout> #include <QDragEnterEvent> #include <QGuiApplication> #include <QMimeData> #include <QShortcut> #include <QSplitter> #include "contentlayout.h" #include "friendwidget.h" #include "groupwidget.h" #include "style.h" #include "widget.h" #include "tool/adjustingscrollarea.h" #include "src/persistence/settings.h" #include "src/friend.h" #include "src/friendlist.h" #include "src/group.h" #include "src/grouplist.h" #include "src/widget/form/chatform.h" #include "src/core/core.h" #include "src/widget/friendlistlayout.h" #include "src/widget/form/settingswidget.h" #include "src/widget/translator.h" ContentDialog* ContentDialog::currentDialog = nullptr; QHash<int, std::tuple<ContentDialog*, GenericChatroomWidget*>> ContentDialog::friendList; QHash<int, std::tuple<ContentDialog*, GenericChatroomWidget*>> ContentDialog::groupList; ContentDialog::ContentDialog(SettingsWidget* settingsWidget, QWidget* parent) : ActivateDialog(parent, Qt::Window) , activeChatroomWidget(nullptr) , settingsWidget(settingsWidget) , videoSurfaceSize(QSize()) , videoCount(0) { QVBoxLayout* boxLayout = new QVBoxLayout(this); boxLayout->setMargin(0); boxLayout->setSpacing(0); splitter = new QSplitter(this); setStyleSheet(Style::getStylesheet(":/ui/contentDialog/contentDialog.css")); splitter->setHandleWidth(6); QWidget *friendWidget = new QWidget(); friendWidget->setSizePolicy(QSizePolicy::Minimum, QSizePolicy::Fixed); friendWidget->setAutoFillBackground(true); friendLayout = new FriendListLayout(); friendLayout->setMargin(0); friendLayout->setSpacing(0); friendWidget->setLayout(friendLayout); onGroupchatPositionChanged(Settings::getInstance().getGroupchatPosition()); QScrollArea *friendScroll = new QScrollArea(this); friendScroll->setMinimumWidth(220); friendScroll->setFrameStyle(QFrame::NoFrame); friendScroll->setLayoutDirection(Qt::RightToLeft); friendScroll->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff); friendScroll->setStyleSheet(Style::getStylesheet(":/ui/friendList/friendList.css")); friendScroll->setWidgetResizable(true); friendScroll->setWidget(friendWidget); QWidget* contentWidget = new QWidget(this); contentWidget->setAutoFillBackground(true); contentLayout = new ContentLayout(contentWidget); contentLayout->setMargin(0); contentLayout->setSpacing(0); splitter->addWidget(friendScroll); splitter->addWidget(contentWidget); splitter->setStretchFactor(1, 1); splitter->setCollapsible(1, false); boxLayout->addWidget(splitter); connect(splitter, &QSplitter::splitterMoved, this, &ContentDialog::saveSplitterState); const Settings& s = Settings::getInstance(); connect(&s, &Settings::groupchatPositionChanged, this, &ContentDialog::onGroupchatPositionChanged); setMinimumSize(500, 220); setAttribute(Qt::WA_DeleteOnClose); QByteArray geometry = Settings::getInstance().getDialogGeometry(); if (!geometry.isNull()) restoreGeometry(geometry); else resize(720, 400); QByteArray splitterState = Settings::getInstance().getDialogSplitterState(); if (!splitterState.isNull()) splitter->restoreState(splitterState); currentDialog = this; setAcceptDrops(true); new QShortcut(Qt::CTRL + Qt::Key_Q, this, SLOT(close())); new QShortcut(Qt::CTRL + Qt::SHIFT + Qt::Key_Tab, this, SLOT(previousContact())); new QShortcut(Qt::CTRL + Qt::Key_Tab, this, SLOT(nextContact())); new QShortcut(Qt::CTRL + Qt::Key_PageUp, this, SLOT(previousContact())); new QShortcut(Qt::CTRL + Qt::Key_PageDown, this, SLOT(nextContact())); connect(Core::getInstance(), &Core::usernameSet, this, &ContentDialog::updateTitleAndStatusIcon); Translator::registerHandler(std::bind(&ContentDialog::retranslateUi, this), this); } ContentDialog::~ContentDialog() { if (currentDialog == this) currentDialog = nullptr; auto friendIt = friendList.begin(); while (friendIt != friendList.end()) { if (std::get<0>(friendIt.value()) == this) { friendIt = friendList.erase(friendIt); continue; } ++friendIt; } auto groupIt = groupList.begin(); while (groupIt != groupList.end()) { if (std::get<0>(groupIt.value()) == this) { groupIt = groupList.erase(groupIt); continue; } ++groupIt; } Translator::unregister(this); } FriendWidget* ContentDialog::addFriend(int friendId, QString id) { FriendWidget* friendWidget = new FriendWidget(friendId, id); friendLayout->addFriendWidget(friendWidget, FriendList::findFriend(friendId)->getStatus()); Friend* frnd = friendWidget->getFriend(); const Settings& s = Settings::getInstance(); connect(frnd, &Friend::displayedNameChanged, this, &ContentDialog::updateFriendWidget); connect(&s, &Settings::compactLayoutChanged, friendWidget, &FriendWidget::compactChange); connect(friendWidget, &FriendWidget::chatroomWidgetClicked, this, &ContentDialog::onChatroomWidgetClicked); connect(friendWidget, SIGNAL(chatroomWidgetClicked(GenericChatroomWidget*)), frnd->getChatForm(), SLOT(focusInput())); connect(Core::getInstance(), &Core::friendAvatarChanged, friendWidget, &FriendWidget::onAvatarChange); connect(Core::getInstance(), &Core::friendAvatarRemoved, friendWidget, &FriendWidget::onAvatarRemoved); ContentDialog* lastDialog = getFriendDialog(friendId); if (lastDialog != nullptr) lastDialog->removeFriend(friendId); friendList.insert(friendId, std::make_tuple(this, friendWidget)); onChatroomWidgetClicked(friendWidget, false); return friendWidget; } GroupWidget* ContentDialog::addGroup(int groupId, const QString& name) { GroupWidget* groupWidget = new GroupWidget(groupId, name); groupLayout.addSortedWidget(groupWidget); const Settings& s = Settings::getInstance(); Group* group = groupWidget->getGroup(); connect(group, &Group::titleChanged, this, &ContentDialog::updateGroupWidget); connect(group, &Group::userListChanged, this, &ContentDialog::updateGroupWidget); connect(&s, &Settings::compactLayoutChanged, groupWidget, &GroupWidget::compactChange); connect(groupWidget, &GroupWidget::chatroomWidgetClicked, this, &ContentDialog::onChatroomWidgetClicked); ContentDialog* lastDialog = getGroupDialog(groupId); if (lastDialog != nullptr) lastDialog->removeGroup(groupId); groupList.insert(groupId, std::make_tuple(this, groupWidget)); onChatroomWidgetClicked(groupWidget, false); return groupWidget; } void ContentDialog::removeFriend(int friendId) { auto iter = friendList.find(friendId); if (iter == friendList.end()) return; FriendWidget* chatroomWidget = static_cast<FriendWidget*>(std::get<1>(iter.value())); disconnect(chatroomWidget->getFriend(), &Friend::displayedNameChanged, this, &ContentDialog::updateFriendWidget); // Need to find replacement to show here instead. if (activeChatroomWidget == chatroomWidget) cycleContacts(true, false); friendLayout->removeFriendWidget(chatroomWidget, Status::Offline); friendLayout->removeFriendWidget(chatroomWidget, Status::Online); chatroomWidget->deleteLater(); friendList.remove(friendId); if (chatroomWidgetCount() == 0) { contentLayout->clear(); activeChatroomWidget = nullptr; deleteLater(); } else { update(); } } void ContentDialog::removeGroup(int groupId) { Group* group = GroupList::findGroup(groupId); if (group) { disconnect(group, &Group::titleChanged, this, &ContentDialog::updateGroupWidget); disconnect(group, &Group::userListChanged, this, &ContentDialog::updateGroupWidget); } auto iter = groupList.find(groupId); if (iter == groupList.end()) return; GenericChatroomWidget* chatroomWidget = std::get<1>(iter.value()); // Need to find replacement to show here instead. if (activeChatroomWidget == chatroomWidget) cycleContacts(true, false); groupLayout.removeSortedWidget(chatroomWidget); chatroomWidget->deleteLater(); groupList.remove(groupId); if (chatroomWidgetCount() == 0) { contentLayout->clear(); activeChatroomWidget = nullptr; deleteLater(); } else { update(); } } bool ContentDialog::hasFriendWidget(int friendId, GenericChatroomWidget* chatroomWidget) { return hasWidget(friendId, chatroomWidget, friendList); } bool ContentDialog::hasGroupWidget(int groupId, GenericChatroomWidget *chatroomWidget) { return hasWidget(groupId, chatroomWidget, groupList); } int ContentDialog::chatroomWidgetCount() const { return friendLayout->friendTotalCount() + groupLayout.getLayout()->count(); } void ContentDialog::ensureSplitterVisible() { if (splitter->sizes().at(0) == 0) splitter->setSizes({1, 1}); update(); } void ContentDialog::cycleContacts(bool forward, bool loop) { Settings::getInstance().getGroupchatPosition(); int index; QLayout* currentLayout; if (activeChatroomWidget->getFriend()) { currentLayout = friendLayout->getLayoutOnline(); index = friendLayout->indexOfFriendWidget(activeChatroomWidget, true); if (index == -1) { currentLayout = friendLayout->getLayoutOffline(); index = friendLayout->indexOfFriendWidget(activeChatroomWidget, false); } } else { currentLayout = groupLayout.getLayout(); index = groupLayout.indexOfSortedWidget(activeChatroomWidget); } if (!loop && index == currentLayout->count() - 1) { bool groupsOnTop = Settings::getInstance().getGroupchatPosition(); bool offlineEmpty = friendLayout->getLayoutOffline()->count() == 0; bool onlineEmpty = offlineEmpty && ((friendLayout->getLayoutOnline()->count() == 0 && groupsOnTop) || !groupsOnTop); bool groupsEmpty = offlineEmpty && ((groupLayout.getLayout()->count() == 0 && !groupsOnTop) || groupsOnTop); if ((currentLayout == friendLayout->getLayoutOffline()) || (currentLayout == friendLayout->getLayoutOnline() && groupsEmpty) || (currentLayout == groupLayout.getLayout() && onlineEmpty)) { forward = !forward; } } index += forward ? 1 : -1; for (;;) { // Bounds checking. if (index < 0) { currentLayout = nextLayout(currentLayout, forward); index = currentLayout->count() - 1; continue; } else if (index >= currentLayout->count()) { currentLayout = nextLayout(currentLayout, forward); index = 0; continue; } GenericChatroomWidget* chatWidget = dynamic_cast<GenericChatroomWidget*>(currentLayout->itemAt(index)->widget()); if (chatWidget != nullptr && chatWidget != activeChatroomWidget) onChatroomWidgetClicked(chatWidget, false); return; } } void ContentDialog::onVideoShow(QSize size) { videoCount++; if (videoCount > 1) return; videoSurfaceSize = size; QSize minSize = minimumSize(); setMinimumSize(minSize + videoSurfaceSize); } void ContentDialog::onVideoHide() { videoCount--; if (videoCount > 0) return; QSize minSize = minimumSize(); setMinimumSize(minSize - videoSurfaceSize); videoSurfaceSize = QSize(); } ContentDialog* ContentDialog::current() { return currentDialog; } bool ContentDialog::existsFriendWidget(int friendId, bool focus) { return existsWidget(friendId, focus, friendList); } bool ContentDialog::existsGroupWidget(int groupId, bool focus) { return existsWidget(groupId, focus, groupList); } void ContentDialog::updateFriendStatus(int friendId) { updateStatus(friendId, friendList); ContentDialog* contentDialog = getFriendDialog(friendId); if (contentDialog != nullptr) { FriendWidget* friendWidget = static_cast<FriendWidget*>(std::get<1>(friendList.find(friendId).value())); contentDialog->friendLayout->addFriendWidget(friendWidget, FriendList::findFriend(friendId)->getStatus()); } } void ContentDialog::updateFriendStatusMessage(int friendId, const QString &message) { auto iter = friendList.find(friendId); if (iter == friendList.end()) return; std::get<1>(iter.value())->setStatusMsg(message); } void ContentDialog::updateGroupStatus(int groupId) { updateStatus(groupId, groupList); } bool ContentDialog::isFriendWidgetActive(int friendId) { return isWidgetActive(friendId, friendList); } bool ContentDialog::isGroupWidgetActive(int groupId) { return isWidgetActive(groupId, groupList); } ContentDialog* ContentDialog::getFriendDialog(int friendId) { return getDialog(friendId, friendList); } ContentDialog* ContentDialog::getGroupDialog(int groupId) { return getDialog(groupId, groupList); } void ContentDialog::updateTitleAndStatusIcon(const QString& username) { if (displayWidget != nullptr) { setWindowTitle(displayWidget->getTitle() + QStringLiteral(" - ") + username); // it's null when it's a groupchat if (displayWidget->getFriend() == nullptr) { setWindowIcon(QIcon(":/img/group.svg")); return; } Status currentStatus = displayWidget->getFriend()->getStatus(); switch(currentStatus) { case Status::Online: setWindowIcon(QIcon(":/img/status/dot_online.svg")); break; case Status::Away: setWindowIcon(QIcon(":/img/status/dot_away.svg")); break; case Status::Busy: setWindowIcon(QIcon(":/img/status/dot_busy.svg")); break; case Status::Offline: setWindowIcon(QIcon(":/img/status/dot_offline.svg")); break; } } else setWindowTitle(username); } void ContentDialog::updateTitle(GenericChatroomWidget* chatroomWidget) { displayWidget = chatroomWidget; updateTitleAndStatusIcon(Core::getInstance()->getUsername()); } void ContentDialog::previousContact() { cycleContacts(false); } void ContentDialog::nextContact() { cycleContacts(true); } bool ContentDialog::event(QEvent* event) { switch (event->type()) { case QEvent::WindowActivate: if (activeChatroomWidget != nullptr) { activeChatroomWidget->resetEventFlags(); activeChatroomWidget->updateStatusLight(); updateTitle(activeChatroomWidget); Friend* frnd = activeChatroomWidget->getFriend(); Group* group = activeChatroomWidget->getGroup(); GenericChatroomWidget *widget = nullptr; if (frnd) widget = frnd->getFriendWidget(); else widget = group->getGroupWidget(); widget->resetEventFlags(); widget->updateStatusLight(); Widget::getInstance()->updateScroll(widget); Widget::getInstance()->resetIcon(); } currentDialog = this; #ifdef Q_OS_MAC emit activated(); #endif default: break; } return ActivateDialog::event(event); } void ContentDialog::dragEnterEvent(QDragEnterEvent *event) { if (event->mimeData()->hasFormat("friend")) { int friendId = event->mimeData()->data("friend").toInt(); auto iter = friendList.find(friendId); // If friend is already in a dialog then you can't drop friend where it already is. if (iter == friendList.end() || std::get<0>(iter.value()) != this) event->acceptProposedAction(); } else if (event->mimeData()->hasFormat("group")) { int groupId = event->mimeData()->data("group").toInt(); auto iter = groupList.find(groupId); if (iter == groupList.end() || std::get<0>(iter.value()) != this) event->acceptProposedAction(); } } void ContentDialog::dropEvent(QDropEvent *event) { if (event->mimeData()->hasFormat("friend")) { int friendId = event->mimeData()->data("friend").toInt(); auto iter = friendList.find(friendId); if (iter != friendList.end()) std::get<0>(iter.value())->removeFriend(friendId); Friend* contact = FriendList::findFriend(friendId); Widget::getInstance()->addFriendDialog(contact, this); ensureSplitterVisible(); } else if (event->mimeData()->hasFormat("group")) { int groupId = event->mimeData()->data("group").toInt(); auto iter = friendList.find(groupId); if (iter != friendList.end()) std::get<0>(iter.value())->removeGroup(groupId); Group* contact = GroupList::findGroup(groupId); Widget::getInstance()->addGroupDialog(contact, this); ensureSplitterVisible(); } } void ContentDialog::changeEvent(QEvent *event) { QWidget::changeEvent(event); if (event->type() == QEvent::ActivationChange) { if (isActiveWindow()) currentDialog = this; } } void ContentDialog::resizeEvent(QResizeEvent* event) { saveDialogGeometry(); QDialog::resizeEvent(event); } void ContentDialog::moveEvent(QMoveEvent* event) { saveDialogGeometry(); QDialog::moveEvent(event); } void ContentDialog::keyPressEvent(QKeyEvent* event) { if (event->key() != Qt::Key_Escape) QDialog::keyPressEvent(event); // Ignore escape keyboard shortcut. } void ContentDialog::onChatroomWidgetClicked(GenericChatroomWidget *widget, bool group) { if (group) { ContentDialog* contentDialog = new ContentDialog(settingsWidget); contentDialog->show(); if (widget->getFriend() != nullptr) { removeFriend(widget->getFriend()->getFriendID()); Widget::getInstance()->addFriendDialog(widget->getFriend(), contentDialog); } else { removeGroup(widget->getGroup()->getGroupId()); Widget::getInstance()->addGroupDialog(widget->getGroup(), contentDialog); } contentDialog->raise(); contentDialog->activateWindow(); return; } // If we clicked on the currently active widget, don't reload and relayout everything if (activeChatroomWidget == widget) return; contentLayout->clear(); if (activeChatroomWidget != nullptr) activeChatroomWidget->setAsInactiveChatroom(); activeChatroomWidget = widget; widget->setChatForm(contentLayout); widget->setAsActiveChatroom(); widget->resetEventFlags(); widget->updateStatusLight(); updateTitle(widget); if (widget->getFriend()) widget->getFriend()->getFriendWidget()->updateStatusLight(); else widget->getGroup()->getGroupWidget()->updateStatusLight(); } void ContentDialog::updateFriendWidget(FriendWidget *w, Status s) { FriendWidget* friendWidget = static_cast<FriendWidget*>(std::get<1>(friendList.find(w->friendId).value())); friendWidget->setName(w->getName()); friendLayout->addFriendWidget(friendWidget, s); } void ContentDialog::updateGroupWidget(GroupWidget *w) { std::get<1>(groupList.find(w->groupId).value())->setName(w->getName()); static_cast<GroupWidget*>(std::get<1>(groupList.find(w->groupId).value()))->onUserListChanged(); } void ContentDialog::onGroupchatPositionChanged(bool top) { friendLayout->removeItem(groupLayout.getLayout()); if (top) friendLayout->insertLayout(0, groupLayout.getLayout()); else friendLayout->insertLayout(1, groupLayout.getLayout()); } void ContentDialog::retranslateUi() { updateTitleAndStatusIcon(Core::getInstance()->getUsername()); } void ContentDialog::saveDialogGeometry() { Settings::getInstance().setDialogGeometry(saveGeometry()); } void ContentDialog::saveSplitterState() { Settings::getInstance().setDialogSplitterState(splitter->saveState()); } bool ContentDialog::hasWidget(int id, GenericChatroomWidget* chatroomWidget, const QHash<int, std::tuple<ContentDialog*, GenericChatroomWidget*>>& list) { auto iter = list.find(id); if (iter == list.end() || std::get<0>(iter.value()) != this) return false; return chatroomWidget == std::get<1>(iter.value()); } bool ContentDialog::existsWidget(int id, bool focus, const QHash<int, std::tuple<ContentDialog*, GenericChatroomWidget*>>& list) { auto iter = list.find(id); if (iter == list.end()) return false; if (focus) { if (std::get<0>(iter.value())->windowState() & Qt::WindowMinimized) std::get<0>(iter.value())->showNormal(); std::get<0>(iter.value())->raise(); std::get<0>(iter.value())->activateWindow(); std::get<0>(iter.value())->onChatroomWidgetClicked(std::get<1>(iter.value()), false); } return true; } void ContentDialog::updateStatus(int id, const QHash<int, std::tuple<ContentDialog *, GenericChatroomWidget *> > &list) { auto iter = list.find(id); if (iter == list.end()) return; GenericChatroomWidget* chatroomWidget = std::get<1>(iter.value()); chatroomWidget->updateStatusLight(); if (chatroomWidget->isActive()) std::get<0>(iter.value())->updateTitle(chatroomWidget); } bool ContentDialog::isWidgetActive(int id, const QHash<int, std::tuple<ContentDialog *, GenericChatroomWidget *> > &list) { auto iter = list.find(id); if (iter == list.end()) return false; return std::get<0>(iter.value())->activeChatroomWidget == std::get<1>(iter.value()); } ContentDialog* ContentDialog::getDialog(int id, const QHash<int, std::tuple<ContentDialog*, GenericChatroomWidget*>>& list) { auto iter = list.find(id); if (iter == list.end()) return nullptr; return std::get<0>(iter.value()); } QLayout* ContentDialog::nextLayout(QLayout* layout, bool forward) const { if (layout == groupLayout.getLayout()) { if (forward) { if (Settings::getInstance().getGroupchatPosition()) return friendLayout->getLayoutOnline(); return friendLayout->getLayoutOffline(); } else { if (Settings::getInstance().getGroupchatPosition()) return friendLayout->getLayoutOffline(); return friendLayout->getLayoutOnline(); } } else if (layout == friendLayout->getLayoutOnline()) { if (forward) { if (Settings::getInstance().getGroupchatPosition()) return friendLayout->getLayoutOffline(); return groupLayout.getLayout(); } else { if (Settings::getInstance().getGroupchatPosition()) return groupLayout.getLayout(); return friendLayout->getLayoutOffline(); } } else if (layout == friendLayout->getLayoutOffline()) { if (forward) { if (Settings::getInstance().getGroupchatPosition()) return groupLayout.getLayout(); return friendLayout->getLayoutOnline(); } else { if (Settings::getInstance().getGroupchatPosition()) return friendLayout->getLayoutOnline(); return groupLayout.getLayout(); } } return nullptr; }
zetok/qTox
src/widget/contentdialog.cpp
C++
gpl-3.0
24,517
#!/bin/bash ## bash function's last echo's output is the function's execution result ## if bash function's execution result is captured by caller, it will be redirect into the variable ## otherwise it will be redirect to stdout ## author: jet ## date: 10/17/2020 function _util_to_uppercase() { if [[ ! -z $1 ]]; then echo $1 | tr '[:lower:]' '[:upper:]' fi } function _util_to_lowercase() { if [[ ! -z $1 ]]; then echo $1 | tr '[:upper:]' '[:lower:]' fi } function _util_append_postfix() { if [[ -z $1 ]]; then echo "no postfix input, skip this" return 1 else local pattern pattern+="\|.*\." pattern+=$(_util_to_lowercase $1) pattern+="\|.*\." pattern+=$(_util_to_uppercase $1) # bash function's return string value is last echo output echo $pattern fi return 0 } function clean() { echo "#[jet] start delete old symbol file" rm -f cs.flist tags cscope.* echo "clean done" echo } function create() { echo "#[jet] start create file list" # local my_target_src_regex="Makefile" local my_target_src_regex if [[ -z $my_target_src_regex ]]; then my_target_src_regex+="Makefile" fi my_target_src_regex+=$(_util_append_postfix "sh") my_target_src_regex+=$(_util_append_postfix "c") my_target_src_regex+=$(_util_append_postfix "cc") my_target_src_regex+=$(_util_append_postfix "cpp") my_target_src_regex+=$(_util_append_postfix "h") my_target_src_regex+=$(_util_append_postfix "hpp") my_target_src_regex+=$(_util_append_postfix "ipp") my_target_src_regex+=$(_util_append_postfix "py") my_target_src_regex+=$(_util_append_postfix "rb") my_target_src_regex+=$(_util_append_postfix "rake") my_target_src_regex+=$(_util_append_postfix "js") my_target_src_regex+=$(_util_append_postfix "go") my_target_src_regex+=$(_util_append_postfix "rs") my_target_src_regex+=$(_util_append_postfix "java") my_target_src_regex+=$(_util_append_postfix "sql") my_target_src_regex+=$(_util_append_postfix "y") my_target_src_regex+=$(_util_append_postfix "xml") my_target_src_regex+=$(_util_append_postfix "html") my_target_src_regex+=$(_util_append_postfix "css") # echo "my_target_src_regex=$my_target_src_regex" find ./ -regex $my_target_src_regex > cs.flist echo "#[jet] start create ctags tags and cscope symbol database" ctags -R -L cs.flist; cscope -Rbqkv -i cs.flist 2>/dev/null echo "#[jet] ------have a look------" ls -la echo } function main() { if [[ -z $1 ]]; then clean create elif [[ $1 == "clean" ]]; then clean else echo "usage:" echo "./cscope.sh [clean]" exit 1 fi } main $*
syslover33/ctank
resources/00_ubuntu/vim_ide/cscope.sh
Shell
gpl-3.0
2,815
<div class="wrap"> <?php echo "<h2>" . __( 'WHEEPL SETTINGS' ) . "</h2>"; ?> <form id="adminSettingsForm" name="admin_settings_form" method="post" action="<?php echo str_replace( '%7E', '~', $_SERVER['REQUEST_URI']); ?>"> <?php echo "<h3>" . __( 'GENERAL' ) . "</h3>"; ?> <?php echo "<h4>" . __( 'admin username: ' ) . "</h4>"; ?> <p style="font-weight: bold; color:#4dcebc;"><?php _e( get_option('whpl_admin') ); ?></p> <?php echo "<h4>" . __( 'site reference: ' ) . "</h4>"; ?> <p style="font-weight: bold; color:#4dcebc;"><?php _e( get_option('whpl_siteRef') ); ?></p> <p><?php _e( 'site reference is a unique identifier that wheepl uses to identify your blog.' ); ?></p> <hr /> <?php echo "<h3>" . __( 'SUPPORT' ) . "</h3>"; ?> <?php echo "<h4>" . __( 'contact us: ' ) . "</h4>"; ?> <p><?php _e( 'breaking your head over something? if you are having any issues or need help troubleshooting the wheepl widget on wordpress, ' ); ?><a href="mailto:[email protected]?subject=WHEEPL WIDGET SUPPORT REQUEST">contact wheepl support</a>.</p> </form> </div>
wp-plugins/wheepl-widget
whpl-options.php
PHP
gpl-3.0
1,163
/* * Copyright (c) 2015 OpenSilk Productions LLC * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.opensilk.music.artwork.fetcher; import org.opensilk.music.artwork.provider.ArtworkComponent; import dagger.Component; import rx.functions.Func2; /** * Created by drew on 5/1/15. */ @ArtworkFetcherScope @Component( dependencies = ArtworkComponent.class, modules = ArtworkFetcherModule.class ) public interface ArtworkFetcherComponent { Func2<ArtworkComponent, ArtworkFetcherService, ArtworkFetcherComponent> FACTORY = new Func2<ArtworkComponent, ArtworkFetcherService, ArtworkFetcherComponent>() { @Override public ArtworkFetcherComponent call(ArtworkComponent artworkComponent, ArtworkFetcherService artworkFetcherService) { return DaggerArtworkFetcherComponent.builder() .artworkComponent(artworkComponent) .artworkFetcherModule(new ArtworkFetcherModule(artworkFetcherService)) .build(); } }; void inject(ArtworkFetcherService service); }
JavierNicolas/JadaMusic
core-artwork/src/main/java/org/opensilk/music/artwork/fetcher/ArtworkFetcherComponent.java
Java
gpl-3.0
1,761
/*---------------------------------------------------------------------------*\ ========= | \\ / F ield | OpenFOAM: The Open Source CFD Toolbox \\ / O peration | Website: https://openfoam.org \\ / A nd | Copyright (C) 2011-2018 OpenFOAM Foundation \\/ M anipulation | ------------------------------------------------------------------------------- License This file is part of OpenFOAM. OpenFOAM is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. OpenFOAM is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with OpenFOAM. If not, see <http://www.gnu.org/licenses/>. \*---------------------------------------------------------------------------*/ #include "edgeMesh.H" #include "boundBox.H" #include "edgeMeshFormat.H" // * * * * * * * * * * * * * * * * Constructors * * * * * * * * * * * * * * // Foam::edgeMesh::edgeMesh ( const fileName& name, const word& ext ) : points_(0), edges_(0), pointEdgesPtr_(nullptr) { read(name, ext); } Foam::edgeMesh::edgeMesh(const fileName& name) : points_(0), edges_(0), pointEdgesPtr_(nullptr) { read(name); } // * * * * * * * * * * * * * * * Member Functions * * * * * * * * * * * * * // bool Foam::edgeMesh::read(const fileName& name) { word ext = name.ext(); if (ext == "gz") { fileName unzipName = name.lessExt(); return read(unzipName, unzipName.ext()); } else { return read(name, ext); } } // Read from file in given format bool Foam::edgeMesh::read ( const fileName& name, const word& ext ) { // read via selector mechanism transfer(New(name, ext)()); return true; } void Foam::edgeMesh::write ( const fileName& name, const edgeMesh& mesh ) { if (debug) { InfoInFunction << "Writing to " << name << endl; } const word ext = name.ext(); writefileExtensionMemberFunctionTable::iterator mfIter = writefileExtensionMemberFunctionTablePtr_->find(ext); if (mfIter == writefileExtensionMemberFunctionTablePtr_->end()) { FatalErrorInFunction << "Unknown file extension " << ext << nl << nl << "Valid types are :" << endl << writefileExtensionMemberFunctionTablePtr_->sortedToc() << exit(FatalError); } else { mfIter()(name, mesh); } } void Foam::edgeMesh::writeStats(Ostream& os) const { os << indent << "points : " << points().size() << nl; os << indent << "edges : " << edges().size() << nl; os << indent << "boundingBox : " << boundBox(this->points()) << endl; } // * * * * * * * * * * * * * * * IOstream Operators * * * * * * * * * * * * // Foam::Ostream& Foam::operator<<(Ostream& os, const edgeMesh& em) { fileFormats::edgeMeshFormat::write(os, em.points_, em.edges_); // Check state of Ostream os.check("Ostream& operator<<(Ostream&, const edgeMesh&)"); return os; } Foam::Istream& Foam::operator>>(Istream& is, edgeMesh& em) { fileFormats::edgeMeshFormat::read(is, em.points_, em.edges_); em.pointEdgesPtr_.clear(); // Check state of Istream is.check("Istream& operator>>(Istream&, edgeMesh&)"); return is; } // ************************************************************************* //
will-bainbridge/OpenFOAM-dev
src/meshTools/edgeMesh/edgeMeshIO.C
C++
gpl-3.0
3,812
/* * ResourceProviderME.java * * 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 * * This was first modified no earlier than May 27, 2008. * */ // Expand to define test define //#define DNOTEST // Expand to define logging define //#define DNOLOGGING package cz.cacek.ebook.util; import java.io.InputStream; import java.io.IOException; import java.util.Hashtable; import cz.cacek.ebook.Common; import com.substanceofcode.utils.CauseException; import com.substanceofcode.utils.CauseRuntimeException; import com.substanceofcode.utils.CauseMemoryException; import com.substanceofcode.utils.StringUtil; import com.substanceofcode.utils.EncodingUtil; import com.substanceofcode.utils.EncodingStreamReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.UnsupportedEncodingException; //#ifdef DLOGGING import net.sf.jlogmicro.util.logging.Logger; import net.sf.jlogmicro.util.logging.Level; //#endif /** * Holds translations for RSSReader - list of resources is from XML properties * in packager application. * @author Josef Cacek [josef.cacek (at) atlas.cz] * @author $Author: ibuntonjr $ * @version $Revision: 934 $ * @created $Date: 2008-07-15 23:33:20 +0200 (Di, 15 Jul 2008) $ */ public final class ResourceProviderME { /** * Singleton instance of ResourceProvider. Due to problems with MIDP, * we have to have a initializer method. */ public static ResourceProviderME provider = null; private Hashtable messages; private Hashtable locMessages; //#ifdef DLOGGING private Logger m_logger = Logger.getLogger("ResourceProviderME"); private boolean m_fineLoggable = m_logger.isLoggable(Level.FINE); private boolean m_finestLoggable = m_logger.isLoggable(Level.FINEST); //#endif private ResourceProviderME() { //#ifdef DTEST long beginMe = System.currentTimeMillis(); System.gc(); long beginMem = Runtime.getRuntime().freeMemory(); //#endif final Hashtable tmpMsgs = new Hashtable(); InputStream is = null; try { is = getClass().getResourceAsStream( "/"+Common.DATA_FOLDER+"/" + Common.LANGUAGE_FILE); if (is == null) { throw new IOException("Unable to read file " + "/"+Common.DATA_FOLDER+"/" + Common.LANGUAGE_FILE); } EncodingUtil encUtl = new EncodingUtil(is); EncodingStreamReader esr = encUtl.getEncodingStreamReader(); StringBuffer inputBuffer; try { inputBuffer = esr.readFile(Common.LANGUAGE_FILE_LEN); } catch (IOException ex) { CauseException cex = new CauseException( "Error while reading file.", ex); throw cex; } finally { if (is != null) { try { is.close(); } catch (Exception e) { } } } String text; /* If not UTF-8, treat it as one since we use XSL to create UTF-8. I couldn't create a file with BOM, so this is the next best thing. */ final String fileEncoding = esr.getFileEncoding(); if (!esr.isUtfDoc()) { esr.setUtfDoc(true); encUtl.getEncoding(fileEncoding, "UTF-8"); } if (esr.isUtfDoc()) { if (esr.isUtf16Doc()) { encUtl.getEncoding(fileEncoding, "UTF-16"); } else { encUtl.getEncoding(fileEncoding, "UTF-8"); } final String docEncoding = encUtl.getDocEncoding(); if (docEncoding.length() == 0) { text = inputBuffer.toString(); } else { try { // We read the bytes in as ISO8859_1, so we must get them // out as that and then encode as they should be. if (fileEncoding.length() == 0) { text = new String(inputBuffer.toString().getBytes(), docEncoding); } else { text = new String(inputBuffer.toString().getBytes( fileEncoding), docEncoding); } } catch (UnsupportedEncodingException e) { //#ifdef DLOGGING m_logger.severe("constructor Could not convert string from,to" + fileEncoding + "," + docEncoding, e); //#endif System.out.println("constructor Could not convert string from,to" + fileEncoding + "," + docEncoding); text = inputBuffer.toString(); } catch (IOException e) { //#ifdef DLOGGING m_logger.severe("constructor Could not convert string from,to" + fileEncoding + "," + docEncoding, e); //#endif System.out.println("constructor Could not convert string from,to" + fileEncoding + "," + docEncoding); text = inputBuffer.toString(); } } } else { text = inputBuffer.toString(); } inputBuffer = null; // Split buffer string by each new line text = StringUtil.replace(text, "\r", ""); String[] lines = StringUtil.split(text, '\n'); text = null; String prevKey = ""; String key; for (int ic = 0; ic < lines.length; lines[ic] = null, ic++) { final String line = lines[ic]; if ((line.length() == 0) || (line.charAt(0) == '#')) { continue; } int indexOfeq = line.indexOf("="); if (indexOfeq < 1) { if (indexOfeq == -1) { if (prevKey.length() > 0) { final String value = (String)tmpMsgs.get(prevKey); if (value == null) { continue; } tmpMsgs.put(prevKey, value + "\n" + line); //#ifdef DLOGGING m_logger.warning("Appending to previous key line=" + line); //#endif continue; } } //#ifdef DLOGGING m_logger.severe("Invalid key no '=' or at beginning of line=" + line); //#endif System.out.println("Invalid entry. No key. line=" + line); continue; } key = line.substring(0, indexOfeq); prevKey = key; String value = line.substring(indexOfeq + 1); if (value.length() == 0) { //#ifdef DLOGGING m_logger.warning("No value after = or at beginning of line=" + line); //#endif System.out.println("Warning entry has no value for " + key); } //#ifdef DLOGGING if (m_finestLoggable) {m_logger.finest("key,value=" + key + "," + value);} //#endif //#ifdef DTEST if (tmpMsgs.containsKey(key)) { String msg = "ResourceProviderME constructor " + "duplicate key=" + key; System.err.println(msg); //#ifdef DLOGGING m_logger.severe(msg); //#endif continue; } //#endif tmpMsgs.put(key, value); } setMessages(tmpMsgs); } catch (CauseMemoryException e) { //#ifdef DLOGGING m_logger.severe("constructor could not initialize.", e); //#endif CauseRuntimeException cex = new CauseRuntimeException( "Out of memory error loading translation.", e); throw cex; } catch (CauseException e) { //#ifdef DLOGGING m_logger.severe("constructor could not initialize.", e); //#endif CauseRuntimeException cex = new CauseRuntimeException( "Error loading translation.", e); throw cex; } catch (Exception e) { //#ifdef DLOGGING m_logger.severe("constructor could not initialize.", e); //#endif CauseRuntimeException cex = new CauseRuntimeException( "Internal error loading translation.", e); throw cex; } catch (OutOfMemoryError e) { //#ifdef DLOGGING m_logger.severe("constructor could not initialize out of memory.", e); //#endif } catch (Throwable e) { //#ifdef DLOGGING m_logger.severe("constructor could not initialize.", e); //#endif CauseRuntimeException cex = new CauseRuntimeException( "Internal error loading translation.", e); throw cex; } finally { if (getMessages() == null) { setMessages(new Hashtable()); } //#ifdef DTEST System.gc(); //#ifdef DLOGGING if (m_finestLoggable) {m_logger.finest("constructor time=" + (System.currentTimeMillis() - beginMe));} if (m_finestLoggable) {m_logger.finest("ResourceProviderME size=" + (beginMem - Runtime.getRuntime().freeMemory()));} //#endif System.out.println("constructor time=" + (System.currentTimeMillis() - beginMe)); System.out.println("ResourceProviderME size=" + (beginMem - Runtime.getRuntime().freeMemory())); //#endif } } /** * Initialize ResourceProviderME. * * @author Irv Bunton */ final public static void initialize() { if (provider == null) { provider = new ResourceProviderME(); } } /** * Returns message identified by given key. * @param aKey * @return message identified by given key */ public synchronized static String get(final String aKey) { final String tmpResult = (String)provider.getMessages().get(aKey); if (tmpResult == null) { Exception e = new Exception("ResourceProviderME.get no value for " + "key=" + aKey); System.err.println(e.getMessage()); e.printStackTrace(); //#ifdef DLOGGING Logger logger = Logger.getLogger("ResourceProviderME"); logger.severe(e.getMessage(), e); //#endif return aKey; } return tmpResult; } /** * Returns message identified by given key and with substitutions of * parameters. * @param aKey * @param aParm1 * @return message identified by given key */ public synchronized static String get(final String aKey, String aParm1) { String msg = get(aKey); return StringUtil.replace(msg, "\\1", aParm1); } public Hashtable getMessages() { synchronized(this) { return messages; } } private void setMessages(final Hashtable aMsgs) { synchronized(this) { messages = aMsgs; } } }
ckaestne/LEADT
workspace/MobileRSSReader_Benchmark/src/cz/cacek/ebook/util/ResourceProviderME.java
Java
gpl-3.0
10,354
// This file is part of VELA-CLARA-Controllers. // //------------------------------------------------------------------------------------// // VELA-CLARA-Controllers 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. // // VELA-CLARA-Controllers 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 VELA-CLARA-Controllers. If not, see <http://www.gnu.org/licenses/>. // #ifndef _VELA_INTERFACE_H #define _VELA_INTERFACE_H // epics #ifndef __CINT__ #include <cadef.h> #endif //stl #include <iostream> #include <map> /// project #include "baseObject.h" #include "structs.h" class interface : public baseObject { public: interface( const bool* show_messages_ptr, const bool * show_debug_messages_ptr ); ~interface(); /// This pure virtual method MUST be overwritten in the derived interface ( making this an abstract base class) /// This also means the destructor need not be protected virtual std::map< VELA_ENUM::ILOCK_NUMBER, VELA_ENUM::ILOCK_STATE > getILockStates( const std::string & name ) = 0; virtual std::map< VELA_ENUM::ILOCK_NUMBER, std::string > getILockStatesStr( const std::string & name ) = 0; double get_CA_PEND_IO_TIMEOUT(); void set_CA_PEND_IO_TIMEOUT( double val ); /// this reports back if the main init tasks: reading config, finding chids, setting up monitors (add your own if needed) has worked bool interfaceInitReport(); protected: void killILockMonitors( );// this should be called in the derived interfface destructor /// send ...1 to enable open / close shutter, screen etc, there for these are available to all interface classes /// send ...0 to send open / close shutter (???, i'm guessing here, but it seems to work) /// i'm also not 100 % certain on the type, but unsigned short works so far /// Other constant numbers could go here if needed const unsigned short EPICS_ACTIVATE, EPICS_SEND, EPICS_RESET; const double DBL_ERR_NUM; bool configFileRead, allChidsInitialised, allMonitorsStarted; double CA_PEND_IO_TIMEOUT; void updateTime( const epicsTimeStamp & stamp, double & val, std::string & str ); /// USE THIS!!! template< class T > bool entryExists( std::map< std::string, T > & m, const std::string & name ) { bool ret = false; auto it = m.find( name ); if( it != m.end() ) ret = true; return ret; } #ifndef __CINT__ /// This is the only ca_client_context attach and detach to this when multi-threading ca_client_context * thisCaContext; void attachTo_thisCAContext(); void detachFrom_thisCAContext(); void addILockChannels( const int numIlocks, const std::string & pvRoot, const std::string & objName,std::map< VELA_ENUM::ILOCK_NUMBER, VELA_ENUM::iLockPVStruct > & iLockPVStructs ); void monitorIlocks( std::map< VELA_ENUM::ILOCK_NUMBER, VELA_ENUM::iLockPVStruct > & iLockPVStructs, std::map< VELA_ENUM::ILOCK_NUMBER, VELA_ENUM::ILOCK_STATE > & iLockStates ); static void staticEntryILockMonitor( event_handler_args args); template< class T, class U > int caput( U TYPE, chid & CHID, T & com, const char * mess1, const char * mess2 ) { ca_put(TYPE, CHID, &com); /// TYPE is DBR_ENUM, etc. return sendToEpics( "ca_put", mess1, mess2 ); } void checkCHIDState( const chid & CHID, const std::string & name ); int sendToEpics( const char * ca, const char * mess1, const char * mess2 ); int sendToEpics( std::string & ca, std::string & mess1, std::string & mess2 ); #endif bool iLocksAreGood( std::map< VELA_ENUM::ILOCK_NUMBER , VELA_ENUM::ILOCK_STATE > & iLockStates ); void printStatusResult( const int status, const char * success, const char * timeout ); /// This is a vector of pointers... no you say !! let's follow Bjarne Stroustrup's advice and "Store many objects in a container by value." ? /// http://stackoverflow.com/questions/24085931/is-using-stdvector-stdshared-ptrconst-t-an-antipattern /// tough... maybe one day we re-factor, for now remember to delete in the destructor std::vector< VELA_ENUM::iLockMonitorStruct * > continuousILockMonitorStructs; private: }; #endif // _VELA_INTERFACE_H
adb-xkc85723/VELA-CLARA-Controllers
Hardware/interface.h
C
gpl-3.0
5,229
<?php /** * Zend Framework * * LICENSE * * This source file is subject to the new BSD license that is bundled * with this package in the file LICENSE.txt. * It is also available through the world-wide-web at this URL: * http://framework.zend.com/license/new-bsd * If you did not receive a copy of the license and are unable to * obtain it through the world-wide-web, please send an email * to [email protected] so we can send you a copy immediately. * * @category Zend * @package Zend_Filter * @copyright Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License * @version $Id$ */ /** * @see Zend_Filter_Decrypt */ // require_once 'Zend/Filter/Decrypt.php'; /** * Decrypts a given file and stores the decrypted file content * * @category Zend * @package Zend_Filter * @copyright Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License */ class Zend_Filter_File_Decrypt extends Zend_Filter_Decrypt { /** * New filename to set * * @var string */ protected $_filename; /** * Returns the new filename where the content will be stored * * @return string */ public function getFilename() { return $this->_filename; } /** * Sets the new filename where the content will be stored * * @param string $filename (Optional) New filename to set * @return Zend_Filter_File_Encryt */ public function setFilename($filename = null) { $this->_filename = $filename; return $this; } /** * Defined by Zend_Filter_Interface * * Decrypts the file $value with the defined settings * * @param string $value Full path of file to change * @return string The filename which has been set, or false when there were errors */ public function filter($value) { if (!file_exists($value)) { // require_once 'Zend/Filter/Exception.php'; throw new Zend_Filter_Exception("File '$value' not found"); } if (!isset($this->_filename)) { $this->_filename = $value; } if (file_exists($this->_filename) and !is_writable($this->_filename)) { // require_once 'Zend/Filter/Exception.php'; throw new Zend_Filter_Exception("File '{$this->_filename}' is not writable"); } $content = file_get_contents($value); if (!$content) { // require_once 'Zend/Filter/Exception.php'; throw new Zend_Filter_Exception("Problem while reading file '$value'"); } $decrypted = parent::filter($content); $result = file_put_contents($this->_filename, $decrypted); if (!$result) { // require_once 'Zend/Filter/Exception.php'; throw new Zend_Filter_Exception("Problem while writing file '{$this->_filename}'"); } return $this->_filename; } }
boydjd/openfisma
library/Zend/Filter/File/Decrypt.php
PHP
gpl-3.0
3,110
/*************************************************************************** * This file belongs to GIMLi (Geophysical Inversion and Modelling) library* * and was created for documentation purposes only. * * DC1dSMOOTH is a smooth inversion of resistivity soundings * * Run with example file using: dc1dsmooth sond1-100dat * ***************************************************************************/ #include <optionmap.h> #include <inversion.h> #include <dc1dmodelling.h> #include <string> using namespace GIMLI; int main( int argc, char *argv [] ) { std::string dataFile( NOT_DEFINED ); double errPerc = 3.0, lambda = 20.0; int nlay = 30; bool verbose = true, lambdaOpt = false, isBlocky = false, optimizeChi1 = false; OptionMap oMap( "DC1dsmooth - smooth 1d dc resistivity inversion" ); oMap.add( lambdaOpt, "O" , "OptimizeLambda", "Optimize model smoothness using L-curve." ); oMap.add( isBlocky, "B" , "BlockyModel" , "Blocky (L1) model constraints." ); oMap.add( optimizeChi1, "C" , "OptimizeChi1" , "Optimize lambda subject to chi^2=1." ); oMap.add( lambda, "l:", "lambda" , "Regularization strength lambda[100]." ); oMap.addLastArg( dataFile, "Datafile" ); oMap.parse( argc, argv ); /*! Data: read data file from column file */ RMatrix abmnr; loadMatrixCol( abmnr, dataFile ); //! read data RVector ab2( abmnr[ 0 ] ); //! first column RVector mn2( abmnr[ 1 ] ); //! second column RVector rhoa( abmnr[ 2 ] ); //! third column /*! Define discretization according to AB/2 */ double maxDep = max( ab2 ) / 2; //! rule of thumb std::cout << "Maximum depth estimated to " << maxDep << std::endl; RVector thk( nlay - 1, maxDep / ( nlay - 1 ) ); thk *= ( maxDep / sum( thk ) / 3 ); /*! Transformations: log for app. resisivity and thickness, logLU for resistivity */ // RTransLogLU transRho( lbound, ubound ); // alternative RTransLog transRho; RTransLog transRhoa; /*! Forward operator, transformations and constraints */ DC1dRhoModelling f( thk, ab2, mn2 ); // f.region( 0 )->setTransModel( transRho ); /*! Set up inversion with full matrix, data and forward operator */ RInversion inv( rhoa, f, verbose ); inv.setTransData( transRhoa ); inv.setTransModel( transRho ); inv.setRelativeError( errPerc / 100.0 ); inv.setLambda( lambda ); inv.setOptimizeLambda( lambdaOpt ); inv.setBlockyModel( isBlocky ); inv.stopAtChi1( false ); RVector model( nlay, median( rhoa ) ); inv.setModel( model ); if ( optimizeChi1 ) { model = inv.runChi1( 0.1 ); } else { model = inv.run(); } if ( verbose ) std::cout << "model = " << model << std::endl; save( model, "resistivity.vec" ); save( thk, "thickness.vec" ); return EXIT_SUCCESS; }
florian-wagner/gimli
doc/tutorial/code/dc1d/dc1dsmooth.cpp
C++
gpl-3.0
3,016
ReadIntegers ============
TongG/ReadIntegers
README.md
Markdown
gpl-3.0
26
/* Copyright (c) 2003-2017, CKSource - Frederico Knabben. All rights reserved. For licensing, see LICENSE.md or http://ckeditor.com/license */ CKEDITOR.plugins.setLang("uploadwidget","ru",{abort:"Загрузка отменена пользователем",doneOne:"Файл успешно загружен",doneMany:"Успешно загружено файлов: %1",uploadOne:"Загрузка файла ({percentage}%)",uploadMany:"Загрузка файлов, {current} из {max} загружено ({percentage}%)..."});
Daniel-KM/Omeka-S
application/asset/vendor/ckeditor/plugins/uploadwidget/lang/ru.js
JavaScript
gpl-3.0
534
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>class CommentController - Rails Application Documentation</title> <script type="text/javascript"> var rdoc_rel_prefix = "./"; </script> <script src="./js/jquery.js"></script> <script src="./js/darkfish.js"></script> <link href="./css/fonts.css" rel="stylesheet"> <link href="./css/rdoc.css" rel="stylesheet"> <body id="top" role="document" class="class"> <nav role="navigation"> <div id="project-navigation"> <div id="home-section" role="region" title="Quick navigation" class="nav-section"> <h2> <a href="./index.html" rel="home">Home</a> </h2> <div id="table-of-contents-navigation"> <a href="./table_of_contents.html#pages">Pages</a> <a href="./table_of_contents.html#classes">Classes</a> <a href="./table_of_contents.html#methods">Methods</a> </div> </div> <div id="search-section" role="search" class="project-section initially-hidden"> <form action="#" method="get" accept-charset="utf-8"> <div id="search-field-wrapper"> <input id="search-field" role="combobox" aria-label="Search" aria-autocomplete="list" aria-controls="search-results" type="text" name="search" placeholder="Search" spellcheck="false" title="Type to search, Up and Down to navigate, Enter to load"> </div> <ul id="search-results" aria-label="Search Results" aria-busy="false" aria-expanded="false" aria-atomic="false" class="initially-hidden"></ul> </form> </div> </div> <div id="class-metadata"> <div id="parent-class-section" class="nav-section"> <h3>Parent</h3> <p class="link"><a href="ApplicationController.html">ApplicationController</a> </div> <div id="includes-section" class="nav-section"> <h3>Included Modules</h3> <ul class="link-list"> <li><a class="include" href="CommentHelper.html">CommentHelper</a> </ul> </div> <!-- Method Quickref --> <div id="method-list-section" class="nav-section"> <h3>Methods</h3> <ul class="link-list" role="directory"> <li ><a href="#method-i-answer_create">#answer_create</a> <li ><a href="#method-i-create">#create</a> <li ><a href="#method-i-create_by_token">#create_by_token</a> <li ><a href="#method-i-delete">#delete</a> <li ><a href="#method-i-index">#index</a> <li ><a href="#method-i-make_answer">#make_answer</a> <li ><a href="#method-i-update">#update</a> </ul> </div> </div> </nav> <main role="main" aria-labelledby="class-CommentController"> <h1 id="class-CommentController" class="class"> class CommentController </h1> <section class="description"> </section> <section id="5Buntitled-5D" class="documentation-section"> <section id="public-instance-5Buntitled-5D-method-details" class="method-section"> <header> <h3>Public Instance Methods</h3> </header> <div id="method-i-answer_create" class="method-detail "> <div class="method-heading"> <span class="method-name">answer_create</span><span class="method-args">()</span> <span class="method-click-advice">click to toggle source</span> </div> <div class="method-description"> <p>create answer comments</p> <div class="method-source-code" id="answer_create-source"> <pre><span class="ruby-comment"># File app/controllers/comment_controller.rb, line 71</span> <span class="ruby-keyword">def</span> <span class="ruby-identifier">answer_create</span> <span class="ruby-ivar">@answer_id</span> = <span class="ruby-identifier">params</span>[<span class="ruby-value">:aid</span>] <span class="ruby-ivar">@comment</span> = <span class="ruby-constant">Comment</span>.<span class="ruby-identifier">new</span>( <span class="ruby-identifier">uid</span><span class="ruby-operator">:</span> <span class="ruby-identifier">current_user</span>.<span class="ruby-identifier">uid</span>, <span class="ruby-identifier">aid</span><span class="ruby-operator">:</span> <span class="ruby-identifier">params</span>[<span class="ruby-value">:aid</span>], <span class="ruby-identifier">comment</span><span class="ruby-operator">:</span> <span class="ruby-identifier">params</span>[<span class="ruby-value">:body</span>], <span class="ruby-identifier">timestamp</span><span class="ruby-operator">:</span> <span class="ruby-constant">Time</span>.<span class="ruby-identifier">now</span>.<span class="ruby-identifier">to_i</span> ) <span class="ruby-keyword">if</span> <span class="ruby-ivar">@comment</span>.<span class="ruby-identifier">save</span> <span class="ruby-ivar">@comment</span>.<span class="ruby-identifier">answer_comment_notify</span>(<span class="ruby-identifier">current_user</span>) <span class="ruby-identifier">respond_to</span> <span class="ruby-keyword">do</span> <span class="ruby-operator">|</span><span class="ruby-identifier">format</span><span class="ruby-operator">|</span> <span class="ruby-identifier">format</span>.<span class="ruby-identifier">js</span> { <span class="ruby-identifier">render</span> <span class="ruby-identifier">template</span><span class="ruby-operator">:</span> <span class="ruby-string">&#39;comment/create&#39;</span> } <span class="ruby-keyword">end</span> <span class="ruby-keyword">else</span> <span class="ruby-identifier">flash</span>[<span class="ruby-value">:error</span>] = <span class="ruby-string">&#39;The comment could not be saved.&#39;</span> <span class="ruby-identifier">render</span> <span class="ruby-identifier">text</span><span class="ruby-operator">:</span> <span class="ruby-string">&#39;failure&#39;</span> <span class="ruby-keyword">end</span> <span class="ruby-keyword">end</span></pre> </div> </div> </div> <div id="method-i-create" class="method-detail "> <div class="method-heading"> <span class="method-name">create</span><span class="method-args">()</span> <span class="method-click-advice">click to toggle source</span> </div> <div class="method-description"> <p>handle some errors!!!!!! create node comments</p> <div class="method-source-code" id="create-source"> <pre><span class="ruby-comment"># File app/controllers/comment_controller.rb, line 15</span> <span class="ruby-keyword">def</span> <span class="ruby-identifier">create</span> <span class="ruby-ivar">@node</span> = <span class="ruby-constant">Node</span>.<span class="ruby-identifier">find</span> <span class="ruby-identifier">params</span>[<span class="ruby-value">:id</span>] <span class="ruby-ivar">@body</span> = <span class="ruby-identifier">params</span>[<span class="ruby-value">:body</span>] <span class="ruby-ivar">@user</span> = <span class="ruby-identifier">current_user</span> <span class="ruby-keyword">begin</span> <span class="ruby-ivar">@comment</span> = <span class="ruby-identifier">create_comment</span>(<span class="ruby-ivar">@node</span>, <span class="ruby-ivar">@user</span>, <span class="ruby-ivar">@body</span>) <span class="ruby-identifier">respond_with</span> <span class="ruby-keyword">do</span> <span class="ruby-operator">|</span><span class="ruby-identifier">format</span><span class="ruby-operator">|</span> <span class="ruby-keyword">if</span> <span class="ruby-identifier">params</span>[<span class="ruby-value">:type</span>] <span class="ruby-operator">&amp;&amp;</span> <span class="ruby-identifier">params</span>[<span class="ruby-value">:type</span>] <span class="ruby-operator">==</span> <span class="ruby-string">&#39;question&#39;</span> <span class="ruby-ivar">@answer_id</span> = <span class="ruby-value">0</span> <span class="ruby-identifier">format</span>.<span class="ruby-identifier">js</span> <span class="ruby-keyword">else</span> <span class="ruby-identifier">format</span>.<span class="ruby-identifier">html</span> <span class="ruby-keyword">do</span> <span class="ruby-keyword">if</span> <span class="ruby-identifier">request</span>.<span class="ruby-identifier">xhr?</span> <span class="ruby-identifier">render</span> <span class="ruby-identifier">partial</span><span class="ruby-operator">:</span> <span class="ruby-string">&#39;notes/comment&#39;</span>, <span class="ruby-identifier">locals</span><span class="ruby-operator">:</span> { <span class="ruby-identifier">comment</span><span class="ruby-operator">:</span> <span class="ruby-ivar">@comment</span> } <span class="ruby-keyword">else</span> <span class="ruby-identifier">flash</span>[<span class="ruby-value">:notice</span>] = <span class="ruby-string">&#39;Comment posted.&#39;</span> <span class="ruby-identifier">redirect_to</span> <span class="ruby-ivar">@node</span>.<span class="ruby-identifier">path</span> <span class="ruby-operator">+</span> <span class="ruby-string">&#39;#last&#39;</span> <span class="ruby-comment"># to last comment</span> <span class="ruby-keyword">end</span> <span class="ruby-keyword">end</span> <span class="ruby-keyword">end</span> <span class="ruby-keyword">end</span> <span class="ruby-keyword">rescue</span> <span class="ruby-constant">CommentError</span> <span class="ruby-identifier">flash</span>[<span class="ruby-value">:error</span>] = <span class="ruby-string">&#39;The comment could not be saved.&#39;</span> <span class="ruby-identifier">render</span> <span class="ruby-identifier">text</span><span class="ruby-operator">:</span> <span class="ruby-string">&#39;failure&#39;</span> <span class="ruby-keyword">end</span> <span class="ruby-keyword">end</span></pre> </div> </div> </div> <div id="method-i-create_by_token" class="method-detail "> <div class="method-heading"> <span class="method-name">create_by_token</span><span class="method-args">()</span> <span class="method-click-advice">click to toggle source</span> </div> <div class="method-description"> <div class="method-source-code" id="create_by_token-source"> <pre><span class="ruby-comment"># File app/controllers/comment_controller.rb, line 43</span> <span class="ruby-keyword">def</span> <span class="ruby-identifier">create_by_token</span> <span class="ruby-ivar">@node</span> = <span class="ruby-constant">Node</span>.<span class="ruby-identifier">find</span> <span class="ruby-identifier">params</span>[<span class="ruby-value">:id</span>] <span class="ruby-ivar">@user</span> = <span class="ruby-constant">User</span>.<span class="ruby-identifier">find_by</span>(<span class="ruby-identifier">username</span><span class="ruby-operator">:</span> <span class="ruby-identifier">params</span>[<span class="ruby-value">:username</span>]) <span class="ruby-ivar">@body</span> = <span class="ruby-identifier">params</span>[<span class="ruby-value">:body</span>] <span class="ruby-ivar">@token</span> = <span class="ruby-identifier">request</span>.<span class="ruby-identifier">headers</span>[<span class="ruby-string">&quot;HTTP_TOKEN&quot;</span>] <span class="ruby-keyword">if</span> <span class="ruby-ivar">@user</span> <span class="ruby-operator">&amp;&amp;</span> <span class="ruby-ivar">@user</span>.<span class="ruby-identifier">token</span> <span class="ruby-operator">==</span> <span class="ruby-ivar">@token</span> <span class="ruby-keyword">begin</span> <span class="ruby-comment"># The create_comment is a function that has been defined inside the</span> <span class="ruby-comment"># CommentHelper module inside app/helpers/comment_helper.rb and can be</span> <span class="ruby-comment"># used in here because the module was `include`d right at the beginning</span> <span class="ruby-ivar">@comment</span> = <span class="ruby-identifier">create_comment</span>(<span class="ruby-ivar">@node</span>, <span class="ruby-ivar">@user</span>, <span class="ruby-ivar">@body</span>) <span class="ruby-identifier">respond_to</span> <span class="ruby-keyword">do</span> <span class="ruby-operator">|</span><span class="ruby-identifier">format</span><span class="ruby-operator">|</span> <span class="ruby-identifier">format</span>.<span class="ruby-identifier">all</span> { <span class="ruby-identifier">render</span> <span class="ruby-value">:nothing</span> =<span class="ruby-operator">&gt;</span> <span class="ruby-keyword">true</span>, <span class="ruby-value">:status</span> =<span class="ruby-operator">&gt;</span> <span class="ruby-value">:created</span> } <span class="ruby-keyword">end</span> <span class="ruby-keyword">rescue</span> <span class="ruby-constant">CommentError</span> <span class="ruby-identifier">respond_to</span> <span class="ruby-keyword">do</span> <span class="ruby-operator">|</span><span class="ruby-identifier">format</span><span class="ruby-operator">|</span> <span class="ruby-identifier">format</span>.<span class="ruby-identifier">all</span> { <span class="ruby-identifier">render</span> <span class="ruby-value">:nothing</span> =<span class="ruby-operator">&gt;</span> <span class="ruby-keyword">true</span>, <span class="ruby-value">:status</span> =<span class="ruby-operator">&gt;</span> <span class="ruby-value">:bad_request</span> } <span class="ruby-keyword">end</span> <span class="ruby-keyword">end</span> <span class="ruby-keyword">else</span> <span class="ruby-identifier">respond_to</span> <span class="ruby-keyword">do</span> <span class="ruby-operator">|</span><span class="ruby-identifier">format</span><span class="ruby-operator">|</span> <span class="ruby-identifier">format</span>.<span class="ruby-identifier">all</span> { <span class="ruby-identifier">render</span> <span class="ruby-value">:nothing</span> =<span class="ruby-operator">&gt;</span> <span class="ruby-keyword">true</span>, <span class="ruby-value">:status</span> =<span class="ruby-operator">&gt;</span> <span class="ruby-value">:unauthorized</span> } <span class="ruby-keyword">end</span> <span class="ruby-keyword">end</span> <span class="ruby-keyword">end</span></pre> </div> </div> </div> <div id="method-i-delete" class="method-detail "> <div class="method-heading"> <span class="method-name">delete</span><span class="method-args">()</span> <span class="method-click-advice">click to toggle source</span> </div> <div class="method-description"> <div class="method-source-code" id="delete-source"> <pre><span class="ruby-comment"># File app/controllers/comment_controller.rb, line 111</span> <span class="ruby-keyword">def</span> <span class="ruby-identifier">delete</span> <span class="ruby-ivar">@comment</span> = <span class="ruby-constant">Comment</span>.<span class="ruby-identifier">find</span> <span class="ruby-identifier">params</span>[<span class="ruby-value">:id</span>] <span class="ruby-identifier">comments_node_and_path</span> <span class="ruby-keyword">if</span> <span class="ruby-identifier">current_user</span>.<span class="ruby-identifier">uid</span> <span class="ruby-operator">==</span> <span class="ruby-ivar">@node</span>.<span class="ruby-identifier">uid</span> <span class="ruby-operator">||</span> <span class="ruby-ivar">@comment</span>.<span class="ruby-identifier">uid</span> <span class="ruby-operator">==</span> <span class="ruby-identifier">current_user</span>.<span class="ruby-identifier">uid</span> <span class="ruby-operator">||</span> <span class="ruby-identifier">current_user</span>.<span class="ruby-identifier">role</span> <span class="ruby-operator">==</span> <span class="ruby-string">&#39;admin&#39;</span> <span class="ruby-operator">||</span> <span class="ruby-identifier">current_user</span>.<span class="ruby-identifier">role</span> <span class="ruby-operator">==</span> <span class="ruby-string">&#39;moderator&#39;</span> <span class="ruby-keyword">if</span> <span class="ruby-ivar">@comment</span>.<span class="ruby-identifier">delete</span> <span class="ruby-identifier">respond_with</span> <span class="ruby-keyword">do</span> <span class="ruby-operator">|</span><span class="ruby-identifier">format</span><span class="ruby-operator">|</span> <span class="ruby-keyword">if</span> <span class="ruby-identifier">params</span>[<span class="ruby-value">:type</span>] <span class="ruby-operator">&amp;&amp;</span> <span class="ruby-identifier">params</span>[<span class="ruby-value">:type</span>] <span class="ruby-operator">==</span> <span class="ruby-string">&#39;question&#39;</span> <span class="ruby-ivar">@answer_id</span> = <span class="ruby-ivar">@comment</span>.<span class="ruby-identifier">aid</span> <span class="ruby-identifier">format</span>.<span class="ruby-identifier">js</span> <span class="ruby-keyword">else</span> <span class="ruby-identifier">format</span>.<span class="ruby-identifier">html</span> <span class="ruby-keyword">do</span> <span class="ruby-keyword">if</span> <span class="ruby-identifier">request</span>.<span class="ruby-identifier">xhr?</span> <span class="ruby-identifier">render</span> <span class="ruby-identifier">text</span><span class="ruby-operator">:</span> <span class="ruby-string">&#39;success&#39;</span> <span class="ruby-keyword">else</span> <span class="ruby-identifier">flash</span>[<span class="ruby-value">:notice</span>] = <span class="ruby-string">&#39;Comment deleted.&#39;</span> <span class="ruby-identifier">redirect_to</span> <span class="ruby-string">&#39;/&#39;</span> <span class="ruby-operator">+</span> <span class="ruby-ivar">@node</span>.<span class="ruby-identifier">path</span> <span class="ruby-keyword">end</span> <span class="ruby-keyword">end</span> <span class="ruby-keyword">end</span> <span class="ruby-keyword">end</span> <span class="ruby-keyword">else</span> <span class="ruby-identifier">flash</span>[<span class="ruby-value">:error</span>] = <span class="ruby-string">&#39;The comment could not be deleted.&#39;</span> <span class="ruby-identifier">render</span> <span class="ruby-identifier">text</span><span class="ruby-operator">:</span> <span class="ruby-string">&#39;failure&#39;</span> <span class="ruby-keyword">end</span> <span class="ruby-keyword">else</span> <span class="ruby-identifier">prompt_login</span> <span class="ruby-string">&#39;Only the comment or post author can delete this comment&#39;</span> <span class="ruby-keyword">end</span> <span class="ruby-keyword">end</span></pre> </div> </div> </div> <div id="method-i-index" class="method-detail "> <div class="method-heading"> <span class="method-name">index</span><span class="method-args">()</span> <span class="method-click-advice">click to toggle source</span> </div> <div class="method-description"> <div class="method-source-code" id="index-source"> <pre><span class="ruby-comment"># File app/controllers/comment_controller.rb, line 7</span> <span class="ruby-keyword">def</span> <span class="ruby-identifier">index</span> <span class="ruby-ivar">@comments</span> = <span class="ruby-constant">Comment</span>.<span class="ruby-identifier">paginate</span>(<span class="ruby-identifier">page</span><span class="ruby-operator">:</span> <span class="ruby-identifier">params</span>[<span class="ruby-value">:page</span>], <span class="ruby-identifier">per_page</span><span class="ruby-operator">:</span> <span class="ruby-value">30</span>) .<span class="ruby-identifier">order</span>(<span class="ruby-string">&#39;timestamp DESC&#39;</span>) <span class="ruby-identifier">render</span> <span class="ruby-identifier">template</span><span class="ruby-operator">:</span> <span class="ruby-string">&#39;comments/index&#39;</span> <span class="ruby-keyword">end</span></pre> </div> </div> </div> <div id="method-i-make_answer" class="method-detail "> <div class="method-heading"> <span class="method-name">make_answer</span><span class="method-args">()</span> <span class="method-click-advice">click to toggle source</span> </div> <div class="method-description"> <div class="method-source-code" id="make_answer-source"> <pre><span class="ruby-comment"># File app/controllers/comment_controller.rb, line 146</span> <span class="ruby-keyword">def</span> <span class="ruby-identifier">make_answer</span> <span class="ruby-ivar">@comment</span> = <span class="ruby-constant">Comment</span>.<span class="ruby-identifier">find</span> <span class="ruby-identifier">params</span>[<span class="ruby-value">:id</span>] <span class="ruby-identifier">comments_node_and_path</span> <span class="ruby-keyword">if</span> <span class="ruby-ivar">@comment</span>.<span class="ruby-identifier">uid</span> <span class="ruby-operator">==</span> <span class="ruby-identifier">current_user</span>.<span class="ruby-identifier">uid</span> <span class="ruby-ivar">@answer</span> = <span class="ruby-constant">Answer</span>.<span class="ruby-identifier">new</span>( <span class="ruby-identifier">nid</span><span class="ruby-operator">:</span> <span class="ruby-ivar">@comment</span>.<span class="ruby-identifier">nid</span>, <span class="ruby-identifier">uid</span><span class="ruby-operator">:</span> <span class="ruby-ivar">@comment</span>.<span class="ruby-identifier">uid</span>, <span class="ruby-identifier">content</span><span class="ruby-operator">:</span> <span class="ruby-ivar">@comment</span>.<span class="ruby-identifier">comment</span> ) <span class="ruby-keyword">if</span> <span class="ruby-ivar">@answer</span>.<span class="ruby-identifier">save</span> <span class="ruby-operator">&amp;&amp;</span> <span class="ruby-ivar">@comment</span>.<span class="ruby-identifier">delete</span> <span class="ruby-ivar">@answer</span>.<span class="ruby-identifier">answer_notify</span>(<span class="ruby-identifier">current_user</span>) <span class="ruby-ivar">@answer_id</span> = <span class="ruby-ivar">@comment</span>.<span class="ruby-identifier">aid</span> <span class="ruby-identifier">respond_with</span> <span class="ruby-keyword">do</span> <span class="ruby-operator">|</span><span class="ruby-identifier">format</span><span class="ruby-operator">|</span> <span class="ruby-identifier">format</span>.<span class="ruby-identifier">js</span> { <span class="ruby-identifier">render</span> <span class="ruby-identifier">template</span><span class="ruby-operator">:</span> <span class="ruby-string">&#39;comment/make_answer&#39;</span> } <span class="ruby-keyword">end</span> <span class="ruby-keyword">else</span> <span class="ruby-identifier">flash</span>[<span class="ruby-value">:error</span>] = <span class="ruby-string">&#39;The comment could not be promoted to answer.&#39;</span> <span class="ruby-identifier">render</span> <span class="ruby-identifier">text</span><span class="ruby-operator">:</span> <span class="ruby-string">&#39;failure&#39;</span> <span class="ruby-keyword">end</span> <span class="ruby-keyword">else</span> <span class="ruby-identifier">prompt_login</span> <span class="ruby-string">&#39;Only the comment author can promote this comment to answer&#39;</span> <span class="ruby-keyword">end</span> <span class="ruby-keyword">end</span></pre> </div> </div> </div> <div id="method-i-update" class="method-detail "> <div class="method-heading"> <span class="method-name">update</span><span class="method-args">()</span> <span class="method-click-advice">click to toggle source</span> </div> <div class="method-description"> <div class="method-source-code" id="update-source"> <pre><span class="ruby-comment"># File app/controllers/comment_controller.rb, line 90</span> <span class="ruby-keyword">def</span> <span class="ruby-identifier">update</span> <span class="ruby-ivar">@comment</span> = <span class="ruby-constant">Comment</span>.<span class="ruby-identifier">find</span> <span class="ruby-identifier">params</span>[<span class="ruby-value">:id</span>] <span class="ruby-identifier">comments_node_and_path</span> <span class="ruby-keyword">if</span> <span class="ruby-ivar">@comment</span>.<span class="ruby-identifier">uid</span> <span class="ruby-operator">==</span> <span class="ruby-identifier">current_user</span>.<span class="ruby-identifier">uid</span> <span class="ruby-comment"># should abstract &quot;.comment&quot; to &quot;.body&quot; for future migration to native db</span> <span class="ruby-ivar">@comment</span>.<span class="ruby-identifier">comment</span> = <span class="ruby-identifier">params</span>[<span class="ruby-value">:body</span>] <span class="ruby-keyword">if</span> <span class="ruby-ivar">@comment</span>.<span class="ruby-identifier">save</span> <span class="ruby-identifier">flash</span>[<span class="ruby-value">:notice</span>] = <span class="ruby-string">&#39;Comment updated.&#39;</span> <span class="ruby-identifier">redirect_to</span> <span class="ruby-ivar">@path</span> <span class="ruby-operator">+</span> <span class="ruby-string">&#39;?_=&#39;</span> <span class="ruby-operator">+</span> <span class="ruby-constant">Time</span>.<span class="ruby-identifier">now</span>.<span class="ruby-identifier">to_i</span>.<span class="ruby-identifier">to_s</span> <span class="ruby-keyword">else</span> <span class="ruby-identifier">flash</span>[<span class="ruby-value">:error</span>] = <span class="ruby-string">&#39;The comment could not be updated.&#39;</span> <span class="ruby-identifier">redirect_to</span> <span class="ruby-ivar">@path</span> <span class="ruby-keyword">end</span> <span class="ruby-keyword">else</span> <span class="ruby-identifier">flash</span>[<span class="ruby-value">:error</span>] = <span class="ruby-string">&#39;Only the author of the comment can edit it.&#39;</span> <span class="ruby-identifier">redirect_to</span> <span class="ruby-ivar">@path</span> <span class="ruby-keyword">end</span> <span class="ruby-keyword">end</span></pre> </div> </div> </div> </section> </section> </main> <footer id="validator-badges" role="contentinfo"> <p><a href="http://validator.w3.org/check/referer">Validate</a> <p>Generated by <a href="http://docs.seattlerb.org/rdoc/">RDoc</a> 4.2.1. <p>Based on <a href="http://deveiate.org/projects/Darkfish-RDoc/">Darkfish</a> by <a href="http://deveiate.org">Michael Granger</a>. </footer>
jywarren/plots2
doc/app/CommentController.html
HTML
gpl-3.0
28,088
# Copyright (C) 2012 Tim Radvan # # This file is part of Kurt. # # Kurt is free software: you can redistribute it and/or modify it under the # terms of the GNU Lesser General Public License as published by the Free # Software Foundation, either version 3 of the License, or (at your option) any # later version. # # Kurt 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 Kurt. If not, see <http://www.gnu.org/licenses/>. """ A Python module for reading and writing Scratch project files. Scratch is created by the Lifelong Kindergarten Group at the MIT Media Lab. See their website: http://scratch.mit.edu/ Classes ------- The main interface: * :class:`Project` The following :class:`Actors <Actor>` may be found on the project stage: * :class:`Stage` * :class:`Sprite` * :class:`Watcher` The two :class:`Scriptables <Scriptable>` (:class:`Stage` and :class:`Sprite`) have instances of the following contained in their attributes: * :class:`Variable` * :class:`List` Scripts use the following classes: * :class:`Block` * :class:`Script` * :class:`Comment` * :class:`BlockType` Media files use the following classes: * :class:`Costume` * :class:`Image` * :class:`Sound` * :class:`Waveform` File Formats ------------ Supported file formats: =============== =========== ========= Format Name Description Extension =============== =========== ========= ``"scratch14"`` Scratch 1.4 ``.sb`` ``"scratch20"`` Scratch 2.0 ``.sb2`` =============== =========== ========= Pass "Format name" as the argument to :attr:`Project.convert`. Kurt provides a superset of the information in each individual format, but will only convert features between a subset of formats. ---- """ __version__ = '2.0.7' from collections import OrderedDict import re import os import random try: from cStringIO import StringIO except ImportError: from StringIO import StringIO import PIL.Image import wave #-- Utils --# def _clean_filename(name): """Strip non-alphanumeric characters to makes name safe to be used as filename.""" return re.sub("[^\w .]", "", name) #-- Project: main class --# class Project(object): """The main kurt class. Stores the contents of a project file. Contents include global variables and lists, the :attr:`stage` and :attr:`sprites`, each with their own :attr:`scripts`, :attr:`costumes`, :attr:`sounds`, :attr:`variables` and :attr:`lists`. A Project can be loaded from or saved to disk in a format which can be read by a Scratch program or one of its derivatives. Loading a project:: p = kurt.Project.load("tests/game.sb") Getting all the scripts:: for scriptable in p.sprites + [p.stage]: for script in scriptable.scripts: print script Creating a new project:: p = kurt.Project() Converting between formats:: p = kurt.Project.load("tests/game.sb") p.convert("scratch20") # [] p.save() # 'tests/game.sb2' """ def __init__(self): self.name = u"" """The name of the project. May be displayed to the user. Doesn't have to match the filename in :attr:`path`. May not be saved for some formats. """ self.path = None """The path to the project file.""" self._plugin = None """The file format plugin used to load this project. Get the current format using the :attr:`format` property. Use :attr:`convert()` to change between formats. """ self.stage = Stage(self) """The :class:`Stage`.""" self.sprites = [] """List of :class:`Sprites <Sprite>`. Use :attr:`get_sprite` to get a sprite by name. """ self.actors = [] """List of each :class:`Actor` on the stage. Includes :class:`Watchers <Watcher>` as well as :class:`Sprites <Sprite>`. Sprites in :attr:`sprites` but not in actors will be added to actors on save. """ self.variables = {} """:class:`dict` of global :class:`Variables <Variable>` by name.""" self.lists = {} """:class:`dict` of global :class:`Lists <List>` by name.""" self.thumbnail = None """An :class:`Image` with a screenshot of the project.""" self.tempo = 60 """The tempo in BPM used for note blocks.""" self.notes = u"Made with Kurt\nhttp://github.com/blob8108/kurt" """Notes about the project, aka project comments. Displayed on the website next to the project. Line endings will be converted to ``\\n``. """ self.author = u"" """The username of the project's author, eg. ``'blob8108'``.""" def __repr__(self): return "<%s.%s()>" % (self.__class__.__module__, self.__class__.__name__) def get_sprite(self, name): """Get a sprite from :attr:`sprites` by name. Returns None if the sprite isn't found. """ for sprite in self.sprites: if sprite.name == name: return sprite @property def format(self): """The file format of the project. :class:`Project` is mainly a universal representation, and so a project has no specfic format. This is the format the project was loaded with. To convert to a different format, use :attr:`save()`. """ if self._plugin: return self._plugin.name @classmethod def load(cls, path, format=None): """Load project from file. Use ``format`` to specify the file format to use. Path can be a file-like object, in which case format is required. Otherwise, can guess the appropriate format from the extension. If you pass a file-like object, you're responsible for closing the file. :param path: Path or file pointer. :param format: :attr:`KurtFileFormat.name` eg. ``"scratch14"``. Overrides the extension. :raises: :class:`UnknownFormat` if the extension is unrecognised. :raises: :py:class:`ValueError` if the format doesn't exist. """ path_was_string = isinstance(path, basestring) if path_was_string: (folder, filename) = os.path.split(path) (name, extension) = os.path.splitext(filename) if format is None: plugin = kurt.plugin.Kurt.get_plugin(extension=extension) if not plugin: raise UnknownFormat(extension) fp = open(path, "rb") else: fp = path assert format, "Format is required" plugin = kurt.plugin.Kurt.get_plugin(format) if not plugin: raise ValueError, "Unknown format %r" % format project = plugin.load(fp) if path_was_string: fp.close() project.convert(plugin) if isinstance(path, basestring): project.path = path if not project.name: project.name = name return project def copy(self): """Return a new Project instance, deep-copying all the attributes.""" p = Project() p.name = self.name p.path = self.path p._plugin = self._plugin p.stage = self.stage.copy() p.stage.project = p for sprite in self.sprites: s = sprite.copy() s.project = p p.sprites.append(s) for actor in self.actors: if isinstance(actor, Sprite): p.actors.append(p.get_sprite(actor.name)) else: a = actor.copy() if isinstance(a, Watcher): if isinstance(a.target, Project): a.target = p elif isinstance(a.target, Stage): a.target = p.stage else: a.target = p.get_sprite(a.target.name) p.actors.append(a) p.variables = dict((n, v.copy()) for (n, v) in self.variables.items()) p.lists = dict((n, l.copy()) for (n, l) in self.lists.items()) p.thumbnail = self.thumbnail p.tempo = self.tempo p.notes = self.notes p.author = self.author return p def convert(self, format): """Convert the project in-place to a different file format. Returns a list of :class:`UnsupportedFeature` objects, which may give warnings about the conversion. :param format: :attr:`KurtFileFormat.name` eg. ``"scratch14"``. :raises: :class:`ValueError` if the format doesn't exist. """ self._plugin = kurt.plugin.Kurt.get_plugin(format) return list(self._normalize()) def save(self, path=None, debug=False): """Save project to file. :param path: Path or file pointer. If you pass a file pointer, you're responsible for closing it. If path is not given, the :attr:`path` attribute is used, usually the original path given to :attr:`load()`. If `path` has the extension of an existing plugin, the project will be converted using :attr:`convert`. Otherwise, the extension will be replaced with the extension of the current plugin. (Note that log output for the conversion will be printed to stdout. If you want to deal with the output, call :attr:`convert` directly.) If the path ends in a folder instead of a file, the filename is based on the project's :attr:`name`. :param debug: If true, return debugging information from the format plugin instead of the path. :raises: :py:class:`ValueError` if there's no path or name. :returns: path to the saved file. """ p = self.copy() plugin = p._plugin # require path p.path = path or self.path if not p.path: raise ValueError, "path is required" if isinstance(p.path, basestring): # split path (folder, filename) = os.path.split(p.path) (name, extension) = os.path.splitext(filename) # get plugin from extension if path: # only if not using self.path try: plugin = kurt.plugin.Kurt.get_plugin(extension=extension) except ValueError: pass # build output path if not name: name = _clean_filename(self.name) if not name: raise ValueError, "name is required" filename = name + plugin.extension p.path = os.path.join(folder, filename) # open fp = open(p.path, "wb") else: fp = p.path path = None if not plugin: raise ValueError, "must convert project to a format before saving" for m in p.convert(plugin): print m result = p._save(fp) if path: fp.close() return result if debug else p.path def _save(self, fp): return self._plugin.save(fp, self) def _normalize(self): """Convert the project to a standardised form for the current plugin. Called after loading, before saving, and when converting to a new format. Yields UnsupportedFeature instances. """ unique_sprite_names = set(sprite.name for sprite in self.sprites) if len(unique_sprite_names) < len(self.sprites): raise ValueError, "Sprite names must be unique" # sync self.sprites and self.actors for sprite in self.sprites: if sprite not in self.actors: self.actors.append(sprite) for actor in self.actors: if isinstance(actor, Sprite): if actor not in self.sprites: raise ValueError, \ "Can't have sprite on stage that isn't in sprites" # normalize Scriptables self.stage._normalize() for sprite in self.sprites: sprite._normalize() # normalize actors for actor in self.actors: if not isinstance(actor, Scriptable): actor._normalize() # make Watchers if needed for thing in [self, self.stage] + self.sprites: for (name, var) in thing.variables.items(): if not var.watcher: var.watcher = kurt.Watcher(thing, kurt.Block("var", name), is_visible=False) self.actors.append(var.watcher) for (name, list_) in thing.lists.items(): if not list_.watcher: list_.watcher = kurt.Watcher(thing, kurt.Block("list", name), is_visible=False) self.actors.append(list_.watcher) # notes - line endings self.notes = self.notes.replace("\r\n", "\n").replace("\r", "\n") # convert scripts def convert_block(block): # convert block try: if isinstance(block.type, CustomBlockType): if "Custom Blocks" not in self._plugin.features: raise BlockNotSupported( "%s doesn't support custom blocks" % self._plugin.display_name) else: # BlockType pbt = block.type.convert(self._plugin) except BlockNotSupported, err: err.message += ". Caused by: %r" % block err.block = block err.scriptable = scriptable err.args = (err.message,) if getattr(block.type, '_workaround', None): block = block.type._workaround(block) if not block: raise else: raise # convert args args = [] for arg in block.args: if isinstance(arg, Block): arg = convert_block(arg) elif isinstance(arg, list): arg = map(convert_block, arg) args.append(arg) block.args = args return block for scriptable in [self.stage] + self.sprites: for script in scriptable.scripts: if isinstance(script, Script): script.blocks = map(convert_block, script.blocks) # workaround unsupported features for feature in kurt.plugin.Feature.FEATURES.values(): if feature not in self._plugin.features: for x in feature.workaround(self): yield UnsupportedFeature(feature, x) # normalize supported features for feature in self._plugin.features: feature.normalize(self) def get_broadcasts(self): def get_broadcasts(block): for (arg, insert) in zip(block.args, block.type.inserts): if isinstance(arg, Block): for b in get_broadcasts(arg): yield b elif isinstance(arg, list): for arg_block in arg: for b in get_broadcasts(arg_block): yield b elif insert.kind == "broadcast": yield arg for scriptable in [self.stage] + self.sprites: for script in scriptable.scripts: for block in script.blocks: for b in get_broadcasts(block): yield b class UnsupportedFeature(object): """The plugin doesn't support this Feature. Output once by Project.convert for each occurence of the feature. """ def __init__(self, feature, obj): self.feature = kurt.plugin.Feature.get(feature) self.obj = obj def __repr__(self): return "<%s.%s(%s)>" % (self.__class__.__module__, self.__class__.__name__, unicode(self)) def __str__(self): return "UnsupportedFeature: %s" % unicode(self) def __unicode__(self): return u"%r: %r" % (self.feature.name, self.obj) #-- Errors --# class UnknownFormat(Exception): """The file extension is not recognised. Raised when :class:`Project` can't find a valid format plugin to handle the file extension. """ pass class UnknownBlock(Exception): """A :class:`Block` with the given command or type cannot be found. Raised by :attr:`BlockType.get`. """ class BlockNotSupported(Exception): """The plugin doesn't support this Block. Raised by :attr:`Block.convert` when it can't find a :class:`PluginBlockType` for the given plugin. """ pass class VectorImageError(Exception): """Tried to construct a raster image from a vector format image file. You shouldn't usally get this error, because Feature("Vector Images") will give a warning instead when the Project is converted. """ pass #-- Actors & Scriptables --# class Actor(object): """An object that goes on the project stage. Subclasses include :class:`Watcher` or :class:`Sprite`. """ class Scriptable(object): """Superclass for all scriptable objects. Subclasses are :class:`Stage` and :class:`Sprite`. """ def __init__(self, project): self.project = project """The :class:`Project` this belongs to.""" self.scripts = [] """The contents of the scripting area. List containing :class:`Scripts <Script>` and :class:`Comments <Comment>`. Will be sorted by y position on load/save. """ self.custom_blocks = {} """Scripts for custom blocks, indexed by :class:`CustomBlockType`.""" self.variables = {} """:class:`dict` of :class:`Variables <Variable>` by name.""" self.lists = {} """:class:`dict` of :class:`Lists <List>` by name.""" self.costumes = [] """List of :class:`Costumes <Costume>`.""" self.sounds = [] """List of :class:`Sounds <Sound>`.""" self.costume = None """The currently selected :class:`Costume`. Defaults to the first costume in :attr:`self.costumes` on save. If a sprite doesn't have a costume, a black 1x1 pixel square will be used. """ self.volume = 100 """The volume in percent used for note and sound blocks.""" def _normalize(self): # costumes if self.costume: # Make sure it's in costumes if self.costume not in self.costumes: self.costumes.append(self.costume) else: # No costume! if self.costumes: self.costume = self.costumes[0] else: BLACK = (0, 0, 0) self.costume = Costume("blank", Image.new((1, 1), BLACK)) self.costumes = [self.costume] # scripts for script in self.scripts: script._normalize() # sort scripts by y position have_position = [s for s in self.scripts if s.pos] no_position = [s for s in self.scripts if not s.pos] have_position.sort(key=lambda s: (s.pos[1], s.pos[0])) self.scripts = have_position + no_position def copy(self, o=None): """Return a new instance, deep-copying all the attributes.""" if o is None: o = self.__class__(self.project) o.scripts = [s.copy() for s in self.scripts] o.variables = dict((n, v.copy()) for (n, v) in self.variables.items()) o.lists = dict((n, l.copy()) for (n, l) in self.lists.items()) o.costumes = [c.copy() for c in self.costumes] o.sounds = [s.copy() for s in self.sounds] o.costume_index = self.costume_index o.volume = self.volume return o @property def costume_index(self): """The index of :attr:`costume` in :attr:`costumes`. None if no costume is selected. """ if self.costume: return self.costumes.index(self.costume) @costume_index.setter def costume_index(self, index): if index is None: self.costume = None else: self.costume = self.costumes[index] def parse(self, text): """Parse the given code and add it to :attr:`scripts`. The syntax matches :attr:`Script.stringify()`. See :mod:`kurt.text` for reference. """ self.scripts.append(kurt.text.parse(text, self)) class Stage(Scriptable): """Represents the background of the project. The stage is similar to a :class:`Sprite`, but has a fixed position. The stage has a fixed size of ``480x360`` pixels. The stage does not require a costume. If none is given, it is assumed to be white (#FFF). Not all formats have stage-specific variables and lists. Global variables and lists are stored on the :class:`Project`. :param project: The :class:`Project` this Stage belongs to. Note that you still need to set :attr:`Project.stage` to this Stage instance. """ name = "Stage" is_draggable = False is_visible = True SIZE = (480, 360) COLOR = (255, 255, 255) def __init__(self, project): Scriptable.__init__(self, project) @property def backgrounds(self): """Alias for :attr:`costumes`.""" return self.costumes @backgrounds.setter def backgrounds(self, value): self.costumes = value def __repr__(self): return "<%s.%s()>" % (self.__class__.__module__, self.__class__.__name__) def _normalize(self): if not self.costume and not self.costumes: self.costume = Costume("blank", Image.new(self.SIZE, self.COLOR)) Scriptable._normalize(self) class Sprite(Scriptable, Actor): """A scriptable object displayed on the project stage. Can be moved and rotated, unlike the :class:`Stage`. Sprites require a :attr:`costume`, and will raise an error when saving without one. :param project: The :class:`Project` this Sprite belongs to. Note that you still need to add this sprite to :attr:`Project.sprites`. """ def __init__(self, project, name): Scriptable.__init__(self, project) self.name = unicode(name) """The name of the sprite, as referred to from scripts and displayed in the Scratch interface. """ self.position = (0, 0) """The ``(x, y)`` position of the centre of the sprite in Scratch co-ordinates. """ self.direction = 90.0 """The angle in degrees the sprite is rotated to.""" self.rotation_style = "normal" """How the sprite's costume rotates with the sprite. Valid values are: ``'normal'`` Continuous rotation with :attr:`direction`. The default. ``'leftRight'`` Don't rotate. Instead, flip the costume for directions with x component < 0. Useful for side-views. ``'none'`` Don't rotate with direction. """ self.size = 100.0 """The scale factor of the sprite in percent. Defaults to 100.""" self.is_draggable = False """True if the sprite can be dragged using the mouse in the player/presentation mode. """ self.is_visible = True """Whether the sprite is shown on the stage. False if the sprite is hidden. """ def _normalize(self): Scriptable._normalize(self) assert self.rotation_style in ("normal", "leftRight", "none") def copy(self): """Return a new instance, deep-copying all the attributes.""" o = self.__class__(self.project, self.name) Scriptable.copy(self, o) o.position = tuple(self.position) o.direction = self.direction o.rotation_style = self.rotation_style o.size = self.size o.is_draggable = self.is_draggable o.is_visible = self.is_visible return o def __repr__(self): return "<%s.%s(%r)>" % (self.__class__.__module__, self.__class__.__name__, self.name) class Watcher(Actor): """A monitor for displaying a data value on the stage. Some formats won't save hidden watchers, and so their position won't be remembered. """ def __init__(self, target, block, style="normal", is_visible=True, pos=None): Actor.__init__(self) assert target is not None self.target = target """The :attr:`Scriptable` or :attr:`Project` the watcher belongs to. """ self.block = block """The :attr:`Block` to evaluate on :attr:`target`. For variables:: kurt.Block('readVariable', 'variable name') For lists:: kurt.Block('contentsOfList:', 'list name') """ self.style = str(style) """How the watcher should appear. Valid values: ``'normal'`` The name of the data is displayed next to its value. The only valid value for list watchers. ``'large'`` The data is displayed in a larger font with no describing text. ``'slider'`` Like the normal style, but displayed with a slider that can change the variable's value. Not valid for reporter block watchers. """ self.pos = pos """``(x, y)`` position of the top-left of the watcher from the top-left of the stage in pixels. None if not specified. """ self.is_visible = bool(is_visible) """Whether the watcher is displayed on the screen. Some formats won't save hidden watchers, and so their position won't be remembered. """ self.slider_min = 0 """Minimum value for slider. Only applies to ``"slider"`` style.""" self.slider_max = 100 """Maximum value for slider. Only applies to ``"slider"`` style.""" self._normalize() def _normalize(self): assert self.style in ("normal", "large", "slider") if self.value: self.value.watcher = self def copy(self): """Return a new instance with the same attributes.""" o = self.__class__(self.target, self.block.copy(), self.style, self.is_visible, self.pos) o.slider_min = self.slider_min o.slider_max = self.slider_max return o @property def kind(self): """The type of value to watch, based on :attr:`block`. One of ``variable``, ``list``, or ``block``. ``block`` watchers watch the value of a reporter block. """ if self.block.type.has_command('readVariable'): return 'variable' elif self.block.type.has_command('contentsOfList:'): return 'list' else: return 'block' @property def value(self): """Return the :class:`Variable` or :class:`List` to watch. Returns ``None`` if it's a block watcher. """ if self.kind == 'variable': return self.target.variables[self.block.args[0]] elif self.kind == 'list': return self.target.lists[self.block.args[0]] def __repr__(self): r = "%s.%s(%r, %r" % (self.__class__.__module__, self.__class__.__name__, self.target, self.block) if self.style != "normal": r += ", style=%r" % self.style if not self.is_visible: r += ", is_visible=False" if self.pos: r += ", pos=%s" % repr(self.pos) r += ")" return r #-- Variables --# class Variable(object): """A memory value used in scripts. There are both :attr:`global variables <Project.variables>` and :attr:`sprite-specific variables <Sprite.variables>`. Some formats also have :attr:`stage-specific variables <Stage.variables>`. """ def __init__(self, value=0, is_cloud=False): self.value = value """The value of the variable, usually a number or a string. For some formats, variables can take list values, and :class:`List` is not used. """ self.is_cloud = bool(is_cloud) """Whether the value of the variable is shared with other users. For Scratch 2.0. """ self.watcher = None """The :class:`Watcher` instance displaying this Variable's value.""" def copy(self): """Return a new instance with the same attributes.""" return self.__class__(self.value, self.is_cloud) def __repr__(self): r = "%s.%s(%r" % (self.__class__.__module__, self.__class__.__name__, self.value) if self.is_cloud: r += ", is_cloud=%r" % self.is_cloud r += ")" return r class List(object): """A sequence of items used in scripts. Each item takes a :class:`Variable`-like value. Lists cannot be nested. However, for some formats, variables can take list values, and this class is not used. """ def __init__(self, items=None, is_cloud=False): self.items = list(items) if items else [] """The items contained in the list. A Python list of unicode strings. """ self.is_cloud = bool(is_cloud) """Whether the value of the list is shared with other users. For Scratch 2.0. """ self.watcher = None """The :class:`Watcher` instance displaying this List's value.""" self._normalize() def _normalize(self): self.items = map(unicode, self.items) def copy(self): """Return a new instance with the same attributes.""" return self.__class__(self.items, self.is_cloud) def __repr__(self): r = "<%s.%s(%i items)>" % (self.__class__.__module__, self.__class__.__name__, len(self.items)) if self.is_cloud: r += ", is_cloud=%r" % self.is_cloud r += ")" return r #-- Color --# class Color(object): """A 24-bit RGB color value. Accepts tuple or hexcode arguments:: >>> kurt.Color('#f08') kurt.Color(255, 0, 136) >>> kurt.Color((255, 0, 136)) kurt.Color(255, 0, 136) >>> kurt.Color('#f0ffee') kurt.Color(240, 255, 238) """ def __init__(self, r, g=None, b=None): if g is None and b is None: if isinstance(r, Color): r = r.value elif isinstance(r, basestring): if not r.startswith("#"): raise ValueError, "invalid color hexcode: %r" % r r = r[1:] if len(r) == 3: r = r[0] + r[0] + r[1] + r[1] + r[2] + r[2] split = (r[0:2], r[2:4], r[4:6]) r = [int(x, 16) for x in split] (r, g, b) = r self.r = int(r) """Red component, 0-255""" self.g = int(g) """Green component, 0-255""" self.b = int(b) """Blue component, 0-255""" @property def value(self): """Return ``(r, g, b)`` tuple.""" return (self.r, self.g, self.b) @value.setter def value(self, value): (self.r, self.g, self.b) = value def __eq__(self, other): return isinstance(other, Color) and self.value == other.value def __ne__(self, other): return not self == other def __iter__(self): return iter(self.value) def __repr__(self): return "%s.%s(%s)" % (self.__class__.__module__, self.__class__.__name__, repr(self.value).strip("()")) def stringify(self): """Returns the color value in hexcode format. eg. ``'#ff1056'`` """ hexcode = "#" for x in self.value: part = hex(x)[2:] if len(part) < 2: part = "0" + part hexcode += part return hexcode @classmethod def random(cls): f = lambda: random.randint(0, 255) return cls(f(), f(), f()) #-- BlockTypes --# class Insert(object): """The specification for an argument to a :class:`BlockType`.""" SHAPE_DEFAULTS = { 'number': 0, 'number-menu': 0, 'stack': [], 'color': Color('#f00'), 'inline': 'nil', # Can't be empty } SHAPE_FMTS = { 'number': '(%s)', 'string': '[%s]', 'readonly-menu': '[%s v]', 'number-menu': '(%s v)', 'color': '[%s]', 'boolean': '<%s>', 'stack': '\n %s\n', 'inline': '%s', 'block': '{%s}', } KIND_OPTIONS = { 'attribute': ['x position', 'y position', 'direction', 'costume #', 'size', 'volume'], 'backdrop': [], 'booleanSensor': ['button pressed', 'A connected', 'B connected', 'C connected', 'D connected'], 'broadcast': [], 'costume': [], 'direction': [], 'drum': range(1, 18), 'effect': ['color', 'fisheye', 'whirl', 'pixelate', 'mosaic', 'brightness', 'ghost'], 'instrument': range(1, 21), 'key': ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', 'space', 'left arrow', 'right arrow', 'up arrow', 'down arrow'], 'list': [], 'listDeleteItem': ['last', 'all'], 'listItem': ['last', 'random'], 'mathOp': ['abs', 'floor', 'ceiling', 'sqrt', 'sin', 'cos', 'tan', 'asin', 'acos', 'atan', 'ln', 'log', 'e ^', '10 ^'], 'motorDirection': ['this way', 'that way', 'reverse'], 'note': [], 'rotationStyle': ['left-right', "don't rotate", 'all around'], 'sensor': ['slider', 'light', 'sound', 'resistance-A', 'resistance-B', 'resistance-C', 'resistance-D'], 'sound': [], 'spriteOnly': ['myself'], 'spriteOrMouse': ['mouse-pointer'], 'spriteOrStage': ['Stage'], 'stageOrThis': ['Stage'], # ? TODO 'stop': ['all', 'this script', 'other scripts in sprite'], 'timeAndDate': ['year', 'month', 'date', 'day of week', 'hour', 'minute', 'second'], 'touching': ['mouse-pointer', 'edge'], 'triggerSensor': ['loudness', 'timer', 'video motion'], 'var': [], 'videoMotionType': ['motion', 'direction'], 'videoState': ['off', 'on', 'on-flipped'], } def __init__(self, shape, kind=None, default=None, name=None, unevaluated=None): self.shape = shape """What kind of values this argument accepts. Shapes that accept a simple data value or a reporter block: ``'number'`` An integer or float number. Defaults to ``0``. ``'string'`` A unicode text value. ``'readonly-menu'`` A choice of string value from a menu. Some readonly inserts do not accept reporter blocks. ``'number-menu'`` Either a number value, or a choice of special value from a menu. Defaults to ``0``. ``'color'`` A :class:`Color` value. Defaults to a random color. Shapes that only accept blocks with the corresponding :attr:`shape`: ``'boolean'`` Accepts a boolean block. ``'stack'`` Accepts a list of stack blocks. Defaults to ``[]``. The block is rendered with a "mouth" into which blocks can be inserted. Special shapes: ``'inline'`` Not actually an insert -- used for variable and list reporters. ``'block'`` Used for the argument to the "define ..." hat block. """ self.kind = kind """Valid arguments for a "menu"-shaped insert. Default is ``None``. Valid values include: * ``'attribute'`` * ``'booleanSensor'`` * ``'broadcast'`` * ``'costume'`` * ``'direction'`` * ``'drum'`` * ``'effect'`` * ``'instrument'`` * ``'key'`` * ``'list'`` * ``'listDeleteItem'`` * ``'listItem'`` * ``'mathOp'`` * ``'motorDirection'`` * ``'note'`` * ``'sensor'`` * ``'sound'`` * ``'spriteOrMouse'`` * ``'spriteOrStage'`` * ``'touching'`` * ``'var'`` Scratch 2.0-specific: * ``'backdrop'`` * ``'rotationStyle'`` * ``'spriteOnly'`` * ``'stageOrThis'`` * ``'stop'`` * ``'timeAndDate'`` * ``'triggerSensor'`` * ``'videoMotionType'`` * ``'videoState'`` """ self.default = default or Insert.SHAPE_DEFAULTS.get(shape, None) """The default value for the insert.""" if unevaluated is None: unevaluated = True if shape == 'stack' else False self.unevaluated = unevaluated """True if the interpreter should evaluate the argument to the block. Defaults to True for 'stack' inserts, False for all others. """ self.name = name """The name of the parameter to a :class:`CustomBlockType`. Not used for :class:`BlockTypes <BlockType>`. """ def __repr__(self): r = "%s.%s(%r" % (self.__class__.__module__, self.__class__.__name__, self.shape) if self.kind != None: r += ", %r" % self.kind if self.default != Insert.SHAPE_DEFAULTS.get(self.shape, None): r += ", default=%r" % self.default if self.unevaluated: r += ", unevaluated=%r" % self.unevaluated if self.name: r += ", name=%r" % self.name r += ")" return r def __eq__(self, other): if isinstance(other, Insert): for name in ("shape", "kind", "default", "unevaluated"): if getattr(self, name) != getattr(other, name): return False else: return True def __ne__(self, other): return not self == other def copy(self): return Insert(self.shape, self.kind, self.default, self.name, self.unevaluated) def stringify(self, value=None, block_plugin=False): if value is None or (value is False and self.shape == "boolean"): value = self.default if value is None: value = "" if isinstance(value, Block): # use block's shape return value.stringify(block_plugin, in_insert=True) else: if hasattr(value, "stringify"): value = value.stringify() elif isinstance(value, list): value = "\n".join(block.stringify(block_plugin) for block in value) if self.shape == 'stack': value = value.replace("\n", "\n ") if block_plugin or self.shape in 'stack': value = Insert.SHAPE_FMTS.get(self.shape, '%s') % (value,) elif self.shape == 'string' or self.kind == 'broadcast': value = unicode(value) if "'" in value: value = '"%s"' % value.replace('"', '\\"') else: value = "'%s'" % value.replace("'", "\\'") return value def options(self, scriptable=None): """Return a list of valid options to a menu insert, given a Scriptable for context. Mostly complete, excepting 'attribute'. """ options = list(Insert.KIND_OPTIONS.get(self.kind, [])) if scriptable: if self.kind == 'var': options += scriptable.variables.keys() options += scriptable.project.variables.keys() elif self.kind == 'list': options += scriptable.lists.keys() options += scriptable.project.lists.keys() elif self.kind == 'costume': options += [c.name for c in scriptable.costumes] elif self.kind == 'backdrop': options += [c.name for c in scriptable.project.stage.costumes] elif self.kind == 'sound': options += [c.name for c in scriptable.sounds] options += [c.name for c in scriptable.project.stage.sounds] elif self.kind in ('spriteOnly', 'spriteOrMouse', 'spriteOrStage', 'touching'): options += [s.name for s in scriptable.project.sprites] elif self.kind == 'attribute': pass # TODO elif self.kind == 'broadcast': options += list(set(scriptable.project.get_broadcasts())) return options class BaseBlockType(object): """Base for :class:`BlockType` and :class:`PluginBlockType`. Defines common attributes. """ SHAPE_FMTS = { 'reporter': '(%s)', 'boolean': '<%s>', } def __init__(self, shape, parts): self.shape = shape """The shape of the block. Valid values: ``'stack'`` The default. Can connect to blocks above and below. Appear jigsaw-shaped. ``'cap'`` Stops the script executing after this block. No blocks can be connected below them. ``'hat'`` A block that starts a script, such as by responding to an event. Can connect to blocks below. ``'reporter'`` Return a value. Can be placed into insert slots of other blocks as an argument to that block. Appear rounded. ``'boolean'`` Like reporter blocks, but return a true/false value. Appear hexagonal. "C"-shaped blocks with "mouths" for stack blocks, such as ``"doIf"``, are specified by adding ``Insert('stack')`` to the end of :attr:`parts`. """ self.parts = parts """A list describing the text and arguments of the block. Contains strings, which are part of the text displayed on the block, and :class:`Insert` instances, which are arguments to the block. """ @property def text(self): """The text displayed on the block. String containing ``"%s"`` in place of inserts. eg. ``'say %s for %s secs'`` """ parts = [("%s" if isinstance(p, Insert) else p) for p in self.parts] parts = [("%%" if p == "%" else p) for p in parts] # escape percent return "".join(parts) @property def inserts(self): """The type of each argument to the block. List of :class:`Insert` instances. """ return [p for p in self.parts if isinstance(p, Insert)] @property def defaults(self): """Default values for block inserts. (See :attr:`Block.args`.)""" return [i.default for i in self.inserts] @property def stripped_text(self): """The :attr:`text`, with spaces and inserts removed. Used by :class:`BlockType.get` to look up blocks. """ return BaseBlockType._strip_text( self.text % tuple((i.default if i.shape == 'inline' else '%s') for i in self.inserts)) @staticmethod def _strip_text(text): """Returns text with spaces and inserts removed.""" text = re.sub(r'[ ,?:]|%s', "", text.lower()) for chr in "-%": new_text = text.replace(chr, "") if new_text: text = new_text return text.lower() def __repr__(self): return "<%s.%s(%r shape=%r)>" % (self.__class__.__module__, self.__class__.__name__, self.text % tuple(i.stringify(None) for i in self.inserts), self.shape) def stringify(self, args=None, block_plugin=False, in_insert=False): if args is None: args = self.defaults args = list(args) r = self.text % tuple(i.stringify(args.pop(0), block_plugin) for i in self.inserts) for insert in self.inserts: if insert.shape == 'stack': return r + "end" fmt = BaseBlockType.SHAPE_FMTS.get(self.shape, "%s") if not block_plugin: fmt = "%s" if fmt == "%s" else "(%s)" if in_insert and fmt == "%s": fmt = "{%s}" return fmt % r def has_insert(self, shape): """Returns True if any of the inserts have the given shape.""" for insert in self.inserts: if insert.shape == shape: return True return False class BlockType(BaseBlockType): """The specification for a type of :class:`Block`. These are initialiased by :class:`Kurt` by combining :class:`PluginBlockType` objects from individual format plugins to create a single :class:`BlockType` for each command. """ def __getstate__(self): """lambda functions are not pickleable so drop them.""" copy = self.__dict__.copy() copy['_workaround'] = None return copy def __init__(self, pbt): if isinstance(pbt, basestring): raise ValueError("Invalid argument. Did you mean `BlockType.get`?") self._plugins = OrderedDict([(pbt.format, pbt)]) """Stores :class:`PluginBlockType` objects for each plugin name.""" self._workaround = None def _add_conversion(self, plugin, pbt): """Add a new PluginBlockType conversion. If the plugin already exists, do nothing. """ assert self.shape == pbt.shape assert len(self.inserts) == len(pbt.inserts) for (i, o) in zip(self.inserts, pbt.inserts): assert i.shape == o.shape assert i.kind == o.kind assert i.unevaluated == o.unevaluated if plugin not in self._plugins: self._plugins[plugin] = pbt def convert(self, plugin=None): """Return a :class:`PluginBlockType` for the given plugin name. If plugin is ``None``, return the first registered plugin. """ if plugin: plugin = kurt.plugin.Kurt.get_plugin(plugin) if plugin.name in self._plugins: return self._plugins[plugin.name] else: err = BlockNotSupported("%s doesn't have %r" % (plugin.display_name, self)) err.block_type = self raise err else: return self.conversions[0] @property def conversions(self): """Return the list of :class:`PluginBlockType` instances.""" return self._plugins.values() def has_conversion(self, plugin): """Return True if the plugin supports this block.""" plugin = kurt.plugin.Kurt.get_plugin(plugin) return plugin.name in self._plugins def has_command(self, command): """Returns True if any of the plugins have the given command.""" for pbt in self._plugins.values(): if pbt.command == command: return True return False @property def shape(self): return self.convert().shape @property def parts(self): return self.convert().parts @classmethod def get(cls, block_type): """Return a :class:`BlockType` instance from the given parameter. * If it's already a BlockType instance, return that. * If it exactly matches the command on a :class:`PluginBlockType`, return the corresponding BlockType. * If it loosely matches the text on a PluginBlockType, return the corresponding BlockType. * If it's a PluginBlockType instance, look for and return the corresponding BlockType. """ if isinstance(block_type, (BlockType, CustomBlockType)): return block_type if isinstance(block_type, PluginBlockType): block_type = block_type.command block = kurt.plugin.Kurt.block_by_command(block_type) if block: return block blocks = kurt.plugin.Kurt.blocks_by_text(block_type) for block in blocks: # check the blocks' commands map to unique blocks if kurt.plugin.Kurt.block_by_command( block.convert().command) != blocks[0]: raise ValueError( "ambigious block text %r, use one of %r instead" % (block_type, [b.convert().command for b in blocks])) if blocks: return blocks[0] raise UnknownBlock, repr(block_type) def __eq__(self, other): if isinstance(other, BlockType): if self.shape == other.shape and self.inserts == other.inserts: for plugin in self._plugins: if plugin in other._plugins: return self._plugins[plugin] == other._plugins[plugin] return False def __ne__(self, other): return not self == other def _add_workaround(self, workaround): self._workaround = workaround class PluginBlockType(BaseBlockType): """Holds plugin-specific :class:`BlockType` attributes. For each block concept, :class:`Kurt` builds a single BlockType that references a corresponding PluginBlockType for each plugin that supports that block. Note that whichever plugin is loaded first takes precedence. """ def __init__(self, category, shape, command, parts, match=None): BaseBlockType.__init__(self, shape, parts) self.format = None """The format plugin the block belongs to.""" self.command = command """The method name from the source code, used to identify the block. eg. ``'say:duration:elapsed:from:'`` """ self.category = category """Where the block is found in the interface. The same blocks may have different categories in different formats. Possible values include:: 'motion', 'looks', 'sound', 'pen', 'control', 'events', 'sensing', 'operators', 'data', 'variables', 'list', 'more blocks', 'motor', 'sensor', 'wedo', 'midi', 'obsolete' """ self._match = match """String -- equivalent command from other plugin. The plugin containing the command to match against must have been registered first. """ def copy(self): return self.__class__(self.category, self.shape, self.command, self.parts, self._match) def __eq__(self, other): if isinstance(other, BlockType): if self.shape == other.shape and self.inserts == other.inserts: for t in self._plugins: if t in other._plugins: return True elif isinstance(other, PluginBlockType): for name in ("shape", "inserts", "command", "format", "category"): if getattr(self, name) != getattr(other, name): return False else: return True return False class CustomBlockType(BaseBlockType): """A user-specified :class:`BlockType`. The script defining the custom block starts with:: kurt.Block("procDef", <CustomBlockType>) And the scripts definining the block follow. The same CustomBlockType instance can then be used in a block in another script:: kurt.Block(<CustomBlocktype>, [args ...,]) """ def __init__(self, shape, parts): BaseBlockType.__init__(self, shape, parts) self.is_atomic = False """True if the block should run without screen refresh.""" #-- Scripts --# class Block(object): """A statement in a graphical programming language. Blocks can connect together to form sequences of commands, which are stored in a :class:`Script`. Blocks perform different commands depending on their type. :param type: A :class:`BlockType` instance, used to identify the command the block performs. Will also exact match a :attr:`command` or loosely match :attr:`text`. :param ``*args``: List of the block's arguments. Arguments can be numbers, strings, Blocks, or lists of Blocks (for 'stack' shaped Inserts). The following constructors are all equivalent:: >>> block = kurt.Block('say:duration:elapsed:from:', 'Hello!', 2) >>> block = kurt.Block("say %s for %s secs", "Hello!", 2) >>> block = kurt.Block("sayforsecs", "Hello!", 2) Using BlockType:: >>> block.type <kurt.BlockType('say [Hello!] for (2) secs', 'stack')> >>> block.args ['Hello!', 2] >>> block2 = kurt.Block(block.type, "Goodbye!", 5) >>> block.stringify() 'say [Hello!] for (2) secs' >>> block2.stringify() 'say [Goodbye!] for (5) secs' """ def __init__(self, block_type, *args): self.type = BlockType.get(block_type) """:class:`BlockType` instance. The command this block performs.""" self.args = [] """List of arguments to the block. The block's parameters are found in :attr:`type.inserts <BlockType.inserts>`. Default values come from :attr:`type.defaults <BlockType.defaults`. """ self.comment = "" """The text of the comment attached to the block. Empty if no comment is attached. Comments can only be attached to stack blocks. """ if self.type: self.args = self.type.defaults[:] for i in xrange(len(args)): if i < len(self.args): self.args[i] = args[i] else: self.args.append(args[i]) self._normalize() def _normalize(self): self.type = BlockType.get(self.type) inserts = list(self.type.inserts) args = [] for arg in self.args: insert = inserts.pop(0) if inserts else None if insert and insert.shape in ('number', 'number-menu'): if isinstance(arg, basestring): try: arg = float(arg) arg = int(arg) if int(arg) == arg else arg except ValueError: pass args.append(arg) self.args = args self.comment = unicode(self.comment) def copy(self): """Return a new Block instance with the same attributes.""" args = [] for arg in self.args: if isinstance(arg, Block): arg = arg.copy() elif isinstance(arg, list): arg = [b.copy() for b in arg] args.append(arg) return Block(self.type, *args) def __eq__(self, other): return ( isinstance(other, Block) and self.type == other.type and self.args == other.args ) def __ne__(self, other): return not self == other def __repr__(self): string = "%s.%s(%s, " % (self.__class__.__module__, self.__class__.__name__, repr(self.type.convert().command if isinstance(self.type, BlockType) else self.type)) for arg in self.args: if isinstance(arg, Block): string = string.rstrip("\n") string += "\n %s,\n" % repr(arg).replace("\n", "\n ") elif isinstance(arg, list): if string.endswith("\n"): string += " " else: string += " " string += "[\n" for block in arg: string += " " string += repr(block).replace("\n", "\n ") string += ",\n" string += " ], " else: string += repr(arg) + ", " string = string.rstrip(" ").rstrip(",") return string + ")" def stringify(self, block_plugin=False, in_insert=False): s = self.type.stringify(self.args, block_plugin, in_insert) if self.comment: i = s.index("\n") if "\n" in s else len(s) indent = "\n" + " " * i + " // " comment = " // " + self.comment.replace("\n", indent) s = s[:i] + comment + s[i:] return s class Script(object): """A single sequence of blocks. Each :class:`Scriptable` can have many Scripts. The first block, ``self.blocks[0]`` is usually a "when" block, eg. an EventHatMorph. Scripts implement the ``list`` interface, so can be indexed directly, eg. ``script[0]``. All other methods like ``append`` also work. """ def __init__(self, blocks=None, pos=None): self.blocks = blocks or [] self.blocks = list(self.blocks) """The list of :class:`Blocks <Block>`.""" self.pos = tuple(pos) if pos else None """``(x, y)`` position from the top-left of the script area in pixels. """ def _normalize(self): self.pos = self.pos self.blocks = list(self.blocks) for block in self.blocks: block._normalize() def copy(self): """Return a new instance with the same attributes.""" return self.__class__([b.copy() for b in self.blocks], tuple(self.pos) if self.pos else None) def __eq__(self, other): return ( isinstance(other, Script) and self.blocks == other.blocks ) def __ne__(self, other): return not self == other def __repr__(self): r = "%s.%s([\n" % (self.__class__.__module__, self.__class__.__name__) for block in self.blocks: r += " " + repr(block).replace("\n", "\n ") + ",\n" r = r.rstrip().rstrip(",") + "]" if self.pos: r += ", pos=%r" % (self.pos,) return r + ")" def stringify(self, block_plugin=False): return "\n".join(block.stringify(block_plugin) for block in self.blocks) # Pretend to be a list def __getattr__(self, name): if name.startswith('__') and name.endswith('__'): return super(Script, self).__getattr__(name) return getattr(self.blocks, name) def __iter__(self): return iter(self.blocks) def __len__(self): return len(self.blocks) def __getitem__(self, index): return self.blocks[index] def __setitem__(self, index, value): self.blocks[index] = value def __delitem__(self, index): del self.blocks[index] class Comment(object): """A free-floating comment in :attr:`Scriptable.scripts`.""" def __init__(self, text, pos=None): self.text = unicode(text) """The text of the comment.""" self.pos = tuple(pos) if pos else None """``(x, y)`` position from the top-left of the script area in pixels. """ def copy(self): return self.__class__(self.text, tuple(self.pos) if self.pos else None) def __repr__(self): r = "%s.%s(%r" % (self.__class__.__module__, self.__class__.__name__, self.text) if self.pos: r += ", pos=%r" % (self.pos,) return r + ")" def stringify(self): return "// " + self.text.replace("\n", "\n// ") def _normalize(self): self.pos = self.pos self.text = unicode(self.text) #-- Costumes --# class Costume(object): """Describes the look of a sprite. The raw image data is stored in :attr:`image`. """ def __init__(self, name, image, rotation_center=None): self.name = unicode(name) """Name used by scripts to refer to this Costume.""" if not rotation_center: rotation_center = (int(image.width / 2), int(image.height / 2)) self.rotation_center = tuple(rotation_center) """``(x, y)`` position from the top-left corner of the point about which the image rotates. Defaults to the center of the image. """ self.image = image """An :class:`Image` instance containing the raw image data.""" def copy(self): """Return a new instance with the same attributes.""" return Costume(self.name, self.image, self.rotation_center) @classmethod def load(self, path): """Load costume from image file. Uses :attr:`Image.load`, but will set the Costume's name based on the image filename. """ (folder, filename) = os.path.split(path) (name, extension) = os.path.splitext(filename) return Costume(name, Image.load(path)) def save(self, path): """Save the costume to an image file at the given path. Uses :attr:`Image.save`, but if the path ends in a folder instead of a file, the filename is based on the costume's :attr:`name`. The image format is guessed from the extension. If path has no extension, the image's :attr:`format` is used. :returns: Path to the saved file. """ (folder, filename) = os.path.split(path) if not filename: filename = _clean_filename(self.name) path = os.path.join(folder, filename) return self.image.save(path) def resize(self, size): """Resize :attr:`image` in-place.""" self.image = self.image.resize(size) def __repr__(self): return "<%s.%s name=%r rotation_center=%d,%d at 0x%X>" % ( self.__class__.__module__, self.__class__.__name__, self.name, self.rotation_center[0], self.rotation_center[1], id(self) ) def __getattr__(self, name): if name in ('width', 'height', 'size'): return getattr(self.image, name) return super(Costume, self).__getattr__(name) class Image(object): """The contents of an image file. Constructing from raw file contents:: Image(file_contents, "JPEG") Constructing from a :class:`PIL.Image.Image` instance:: pil_image = PIL.Image.new("RGBA", (480, 360)) Image(pil_image) Loading from file path:: Image.load("path/to/image.jpg") Images are immutable. If you want to modify an image, get a :class:`PIL.Image.Image` instance from :attr:`pil_image`, modify that, and use it to construct a new Image. Modifying images in-place may break things. The reason for having multiple constructors is so that kurt can implement lazy loading of image data -- in many cases, a PIL image will never need to be created. """ def __init__(self, contents, format=None): self._path = None self._pil_image = None self._contents = None self._format = None self._size = None if isinstance(contents, PIL.Image.Image): self._pil_image = contents else: self._contents = contents self._format = Image.image_format(format) def __getstate__(self): if isinstance(self._pil_image, PIL.Image.Image): copy = self.__dict__.copy() copy['_pil_image'] = { 'data': self._pil_image.tobytes(), 'size': self._pil_image.size, 'mode': self._pil_image.mode} return copy return self.__dict__ def __setstate__(self, data): self.__dict__.update(data) if self._pil_image: self._pil_image = PIL.Image.frombytes(**self._pil_image) # Properties @property def pil_image(self): """A :class:`PIL.Image.Image` instance containing the image data.""" if not self._pil_image: if self._format == "SVG": raise VectorImageError("can't rasterise vector images") self._pil_image = PIL.Image.open(StringIO(self.contents)) return self._pil_image @property def contents(self): """The raw file contents as a string.""" if not self._contents: if self._path: # Read file into memory so we don't run out of file descriptors f = open(self._path, "rb") self._contents = f.read() f.close() elif self._pil_image: # Write PIL image to string f = StringIO() self._pil_image.save(f, self.format) self._contents = f.getvalue() return self._contents @property def format(self): """The format of the image file. An uppercase string corresponding to the :attr:`PIL.ImageFile.ImageFile.format` attribute. Valid values include ``"JPEG"`` and ``"PNG"``. """ if self._format: return self._format elif self.pil_image: return self.pil_image.format @property def extension(self): """The extension of the image's :attr:`format` when written to file. eg ``".png"`` """ return Image.image_extension(self.format) @property def size(self): """``(width, height)`` in pixels.""" if self._size and not self._pil_image: return self._size else: return self.pil_image.size @property def width(self): return self.size[0] @property def height(self): return self.size[1] # Methods @classmethod def load(cls, path): """Load image from file.""" assert os.path.exists(path), "No such file: %r" % path (folder, filename) = os.path.split(path) (name, extension) = os.path.splitext(filename) image = Image(None) image._path = path image._format = Image.image_format(extension) return image def convert(self, *formats): """Return an Image instance with the first matching format. For each format in ``*args``: If the image's :attr:`format` attribute is the same as the format, return self, otherwise try the next format. If none of the formats match, return a new Image instance with the last format. """ for format in formats: format = Image.image_format(format) if self.format == format: return self else: return self._convert(format) def _convert(self, format): """Return a new Image instance with the given format. Returns self if the format is already the same. """ if self.format == format: return self else: image = Image(self.pil_image) image._format = format return image def save(self, path): """Save image to file path. The image format is guessed from the extension. If path has no extension, the image's :attr:`format` is used. :returns: Path to the saved file. """ (folder, filename) = os.path.split(path) (name, extension) = os.path.splitext(filename) if not name: raise ValueError, "name is required" if extension: format = Image.image_format(extension) else: format = self.format filename = name + self.extension path = os.path.join(folder, filename) image = self.convert(format) if image._contents: f = open(path, "wb") f.write(image._contents) f.close() else: image.pil_image.save(path, format) return path @classmethod def new(self, size, fill): """Return a new Image instance filled with a color.""" return Image(PIL.Image.new("RGB", size, fill)) def resize(self, size): """Return a new Image instance with the given size.""" return Image(self.pil_image.resize(size, PIL.Image.ANTIALIAS)) def paste(self, other): """Return a new Image with the given image pasted on top. This image will show through transparent areas of the given image. """ r, g, b, alpha = other.pil_image.split() pil_image = self.pil_image.copy() pil_image.paste(other.pil_image, mask=alpha) return kurt.Image(pil_image) # Static methods @staticmethod def image_format(format_or_extension): if format_or_extension: format = format_or_extension.lstrip(".").upper() if format == "JPG": format = "JPEG" return format @staticmethod def image_extension(format_or_extension): if format_or_extension: extension = format_or_extension.lstrip(".").lower() if extension == "jpeg": extension = "jpg" return "." + extension #-- Sounds --# class Sound(object): """A sound a :class:`Scriptable` can play. The raw sound data is stored in :attr:`waveform`. """ def __init__(self, name, waveform): self.name = name """Name used by scripts to refer to this Sound.""" self.waveform = waveform """A :class:`Waveform` instance containing the raw sound data.""" def copy(self): """Return a new instance with the same attributes.""" return Sound(self.name, self.waveform) @classmethod def load(self, path): """Load sound from wave file. Uses :attr:`Waveform.load`, but will set the Waveform's name based on the sound filename. """ (folder, filename) = os.path.split(path) (name, extension) = os.path.splitext(filename) return Sound(name, Waveform.load(path)) def save(self, path): """Save the sound to a wave file at the given path. Uses :attr:`Waveform.save`, but if the path ends in a folder instead of a file, the filename is based on the project's :attr:`name`. :returns: Path to the saved file. """ (folder, filename) = os.path.split(path) if not filename: filename = _clean_filename(self.name) path = os.path.join(folder, filename) return self.waveform.save(path) def __repr__(self): return "<%s.%s name=%r at 0x%X>" % (self.__class__.__module__, self.__class__.__name__, self.name, id(self)) class Waveform(object): """The contents of a wave file. Only WAV format files are supported. Constructing from raw file contents:: Sound(file_contents) Loading from file path:: Sound.load("path/to/sound.wav") Waveforms are immutable. """ extension = ".wav" def __init__(self, contents, rate=None, sample_count=None): self._path = None self._contents = contents self._rate = rate self._sample_count = sample_count # Properties @property def contents(self): """The raw file contents as a string.""" if not self._contents: if self._path: # Read file into memory so we don't run out of file descriptors f = open(self._path, "rb") self._contents = f.read() f.close() return self._contents @property def _wave(self): """Return a wave.Wave_read instance from the ``wave`` module.""" try: return wave.open(StringIO(self.contents)) except wave.Error, err: err.message += "\nInvalid wave file: %s" % self err.args = (err.message,) raise @property def rate(self): """The sampling rate of the sound.""" if self._rate: return self._rate else: return self._wave.getframerate() @property def sample_count(self): """The number of samples in the sound.""" if self._sample_count: return self._sample_count else: return self._wave.getnframes() # Methods @classmethod def load(cls, path): """Load Waveform from file.""" assert os.path.exists(path), "No such file: %r" % path (folder, filename) = os.path.split(path) (name, extension) = os.path.splitext(filename) wave = Waveform(None) wave._path = path return wave def save(self, path): """Save waveform to file path as a WAV file. :returns: Path to the saved file. """ (folder, filename) = os.path.split(path) (name, extension) = os.path.splitext(filename) if not name: raise ValueError, "name is required" path = os.path.join(folder, name + self.extension) f = open(path, "wb") f.write(self.contents) f.close() return path #-- Import submodules --# import kurt.plugin import kurt.text import kurt.scratch20 import kurt.scratch14
tjvr/kurt
kurt/__init__.py
Python
gpl-3.0
74,227
package jnn.functions.nonparametrized; import java.util.Set; import jnn.functions.DenseToDenseTransform; import jnn.functions.SparseToSparseTransform; import jnn.functions.parametrized.Layer; import jnn.mapping.OutputMappingDenseToDense; import jnn.mapping.OutputMappingSparseToSparse; import jnn.neuron.DenseNeuronArray; import jnn.neuron.SparseNeuronArray; public class X3SigmoidLayer extends Layer implements DenseToDenseTransform, SparseToSparseTransform{ public static X3SigmoidLayer singleton = new X3SigmoidLayer(); @Override public void forward(DenseNeuronArray input, int inputStart, int inputEnd, DenseNeuronArray output, int outputStart, int outputEnd, OutputMappingDenseToDense mapping) { int inputDim = inputEnd - inputStart + 1; int outputDim = outputEnd - outputStart + 1; if(inputDim != outputDim){ throw new RuntimeException(inputDim + " " + outputDim); } for(int i = 0; i < inputDim; i++){ output.addNeuron(i+outputStart, Math.pow(input.getNeuron(i+inputStart),3)); } } @Override public void forward(SparseNeuronArray input, int inputStart, int inputEnd, SparseNeuronArray output, int outputStart, int outputEnd, OutputMappingSparseToSparse mapping) { int inputDim = inputEnd - inputStart + 1; int outputDim = outputEnd - outputStart + 1; if(inputDim != outputDim){ throw new RuntimeException(inputDim + " " + outputDim); } Set<Integer> indexes = input.getNonZeroKeys(); for(int i : indexes){ output.addNeuron(i+outputStart,Math.pow(input.getOutput(i+inputStart),3)); } } @Override public void backward(DenseNeuronArray input, int inputStart, int inputEnd, DenseNeuronArray output, int outputStart, int outputEnd, OutputMappingDenseToDense mapping) { int inputDim = inputEnd - inputStart + 1; int outputDim = outputEnd - outputStart + 1; if(inputDim != outputDim){ throw new RuntimeException(inputDim + " " + outputDim); } for(int i = 0; i < inputDim; i++){ input.addError(i+inputStart, 3*input.getNeuron(i+inputStart)*input.getNeuron(i+inputStart)*output.getError(i+outputStart)); } } @Override public void backward(SparseNeuronArray input, int inputStart, int inputEnd, SparseNeuronArray output, int outputStart, int outputEnd, OutputMappingSparseToSparse mapping) { int inputDim = inputEnd - inputStart + 1; int outputDim = outputEnd - outputStart + 1; if(inputDim != outputDim){ throw new RuntimeException(inputDim + " " + outputDim); } Set<Integer> indexes = input.getNonZeroKeys(); for(int i : indexes){ input.addError(i+inputStart, 3*input.getOutput(i+inputStart)*input.getOutput(i+inputStart)*output.getError(i+outputStart)); } } }
ikekonglp/NN_Parser
src/jnn/functions/nonparametrized/X3SigmoidLayer.java
Java
gpl-3.0
2,675
/* This file is part of the db4o object database http://www.db4o.com Copyright (C) 2004 - 2011 Versant Corporation http://www.versant.com db4o is free software; you can redistribute it and/or modify it under the terms of version 3 of the GNU General Public License as published by the Free Software Foundation. db4o 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/. */ using System; using System.Windows.Forms; using OMControlLibrary.Common; using OME.Logging.Common; namespace OMControlLibrary { public partial class AboutOME : Form { public AboutOME(string db4oVersion) { InitializeComponent(); labeldb4o.Text = "db4o (" + db4oVersion + ")"; } private void buttonOk_Click(object sender, EventArgs e) { Close(); } } }
masroore/db4o
tools/omn/OmControlLibrary/AboutOME.cs
C#
gpl-3.0
1,120
/** * Copyright 2014 Adam Waite * * This file is part of metapop. * * metapop 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. * * metapop 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 metapop. If not, see <http://www.gnu.org/licenses/>. */ package org.fhcrc.honeycomb.metapop.migration; import org.fhcrc.honeycomb.metapop.Population; import org.fhcrc.honeycomb.metapop.OccupiedLocations; import org.fhcrc.honeycomb.metapop.coordinate.Coordinate; import org.fhcrc.honeycomb.metapop.coordinate.CoordinateProvider; import org.fhcrc.honeycomb.metapop.coordinate.picker.CoordinatePicker; import java.util.List; /** * Controls migration * * Created on 30 May, 2013 * * @author Adam Waite * @version $Rev: 2393 $, $Date: 2014-05-24 19:17:59 -0400 (Sat, 24 May 2014) $, $Author: ajwaite $ * */ public abstract class MigrationRule implements CoordinateProvider { private double rate; private CoordinatePicker picker; private Coordinate coordinate; protected MigrationRule() {} public MigrationRule(double rate, CoordinatePicker picker) { this.rate = rate; this.picker = picker; picker.setProvider(this); } public abstract void migrate(OccupiedLocations ols); public double getRate() { return rate; } public CoordinatePicker getPicker() { return picker; } public void setCoordinate(Coordinate coord) { this.coordinate = coord; } @Override public Coordinate getCoordinate() { return coordinate; } @Override public String toString() { return String.format("%s, rate=%s, picker=%s", this.getClass().getSimpleName(), rate, picker); } }
nodice73/metapop
source/org/fhcrc/honeycomb/metapop/migration/MigrationRule.java
Java
gpl-3.0
2,145
/* -------------------------------------------------------------------------------- SPADE - Support for Provenance Auditing in Distributed Environments. Copyright (C) 2015 SRI International This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. -------------------------------------------------------------------------------- */ package spade.transformer; import spade.client.QueryParameters; import spade.core.AbstractEdge; import spade.core.AbstractTransformer; import spade.core.AbstractVertex; import spade.core.Graph; import spade.core.Settings; import spade.reporter.audit.OPMConstants; import spade.utility.CommonFunctions; import spade.utility.FileUtility; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Set; import java.util.logging.Level; import java.util.logging.Logger; import java.util.regex.Matcher; import java.util.regex.Pattern; public class NoEphemeralReads extends AbstractTransformer { private Pattern ignoreFilesPattern = null; // limited = true means that only matching files in the graph should be checked for ephemeral reads. // limited = false means that all files in the graph should be checked for ephemeral reads. public boolean initialize(String arguments){ Map<String, String> argumentsMap = CommonFunctions.parseKeyValPairs(arguments); if("false".equals(argumentsMap.get("limited"))){ return true; }else{ try{ String filepath = Settings.getDefaultConfigFilePath(this.getClass()); ignoreFilesPattern = FileUtility.constructRegexFromFile(filepath); if(ignoreFilesPattern == null){ throw new Exception("Regex read from file '"+filepath+"' cannot be null"); } return true; }catch(Exception e){ Logger.getLogger(getClass().getName()).log(Level.WARNING, null, e); return false; } } } public Graph putGraph(Graph graph, QueryParameters digQueryParams){ AbstractVertex queriedVertex = null; if(digQueryParams != null){ queriedVertex = digQueryParams.getVertex(); } Map<AbstractVertex, Set<String>> fileWrittenBy = new HashMap<AbstractVertex, Set<String>>(); for(AbstractEdge edge : graph.edgeSet()){ AbstractEdge newEdge = createNewWithoutAnnotations(edge); if(OPMConstants.isPathBasedArtifact(newEdge.getChildVertex()) || OPMConstants.isPathBasedArtifact(newEdge.getParentVertex())){ String operation = getAnnotationSafe(newEdge, OPMConstants.EDGE_OPERATION); if(OPMConstants.isOutgoingDataOperation(operation)){ if(fileWrittenBy.get(newEdge.getChildVertex()) == null){ fileWrittenBy.put(newEdge.getChildVertex(), new HashSet<String>()); } fileWrittenBy.get(newEdge.getChildVertex()).add( getAnnotationSafe(newEdge.getParentVertex(), OPMConstants.PROCESS_PID)); } } } Graph resultGraph = new Graph(); for(AbstractEdge edge : graph.edgeSet()){ AbstractEdge newEdge = createNewWithoutAnnotations(edge); if(OPMConstants.isPathBasedArtifact(newEdge.getParentVertex()) && OPMConstants.isIncomingDataOperation(getAnnotationSafe(newEdge, OPMConstants.EDGE_OPERATION))){ AbstractVertex vertex = newEdge.getParentVertex(); String path = getAnnotationSafe(vertex, OPMConstants.ARTIFACT_PATH); if(!pathEqualsVertex(path, queriedVertex)){ //if file passed as an argument then always log it otherwise check further if(isPathInIgnoreFilesPattern(path)){ //if file is not in ignore list then always log it otherwise check further if((fileWrittenBy.get(vertex) == null) || (fileWrittenBy.get(vertex).size() == 1 && fileWrittenBy.get(vertex).toArray()[0].equals( getAnnotationSafe(newEdge.getChildVertex(), OPMConstants.PROCESS_PID)))){ continue; } } } } resultGraph.putVertex(newEdge.getChildVertex()); resultGraph.putVertex(newEdge.getParentVertex()); resultGraph.putEdge(newEdge); } return resultGraph; } private boolean pathEqualsVertex(String path, AbstractVertex vertex){ if(path == null || vertex == null){ return false; } if(OPMConstants.isPathBasedArtifact(vertex)){ String vpath = getAnnotationSafe(vertex, OPMConstants.ARTIFACT_PATH); if(path.equals(vpath)){ return true; } } return false; } private boolean isPathInIgnoreFilesPattern(String path){ if(ignoreFilesPattern == null){ return true; } if(path != null){ Matcher filepathMatcher = ignoreFilesPattern.matcher(path); return filepathMatcher.find(); } return false; } }
sranasir/SPADE
src/spade/transformer/NoEphemeralReads.java
Java
gpl-3.0
5,076
package com.gisnet.cancelacion.config; import com.gisnet.cancelacion.wsclient.autenticacion.ClienteAutenticacionService; import com.gisnet.cancelacion.wsclient.autenticacion.ClienteAutenticacionServiceHandler; import com.gisnet.cancelacion.wsclient.microflujo.ClienteMicroflujoService; import com.gisnet.cancelacion.wsclient.microflujo.ClienteMicroflujoServiceHandler; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; @Configuration public class WebServicesConfig { @Bean ClienteAutenticacionService clienteAutenticacionService() { return new ClienteAutenticacionServiceHandler(); } @Bean ClienteMicroflujoService clienteMicroflujoService() { return new ClienteMicroflujoServiceHandler(); } }
tazvoit/ARPP
cancelacion/cancelacion-web/src/main/java/com/gisnet/cancelacion/config/WebServicesConfig.java
Java
gpl-3.0
810
/* * libgroupme * * libgroupme is the property of its developers. See the COPYRIGHT file * for more details. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #ifndef GROUPME_POD_H #define GROUPME_POD_H #include "libgroupme.h" struct _GroupMePod { PurpleConversation *conv; gchar *id; gchar *title; gchar *imageUrl; // gint64 time; // gchar *location; //GHashTable *members; GSList *toSend; GList *updates; GList *nextUpdateDisplayed; gint lastUpdateId; gboolean pollOutstanding; guint retryPollPodPeriod; guint retryPollPodTimeout; guint catchupPodTimeout; gchar *photosPath; //gchar *updatesPath; }; GroupMePod * GroupMePodNew(); void GroupMePodFree(GroupMePod *pod); void GroupMePodReadLastUpdateIndex(GroupMeAccount *account, GroupMePod *pod); void GroupMePodWriteLastUpdateIndex(GroupMeAccount *account, GroupMePod *pod); GroupMePod * GroupMePodFromHtml(const gchar *html, const gchar **htmlEnd); GroupMePod * GroupMePodFromJson(const gchar *json, const gchar **jsonEnd); //GroupMePod * //GroupMePodMembersFromHtml(gchar *html); void GroupMePodSetTitle(GroupMePod *pod, gchar *newTitle); void GroupMePodSetImageUrl(GroupMePod *pod, gchar *newImageUrl); GroupMeUpdate * GroupMePodGetUpdate(GroupMePod *pod, gint index); void GroupMePodPrependUpdate(GroupMePod *pod, GroupMeUpdate *update); void GroupMePodAppendUpdate(GroupMePod *pod, GroupMeUpdate *update); GroupMeUpdate * GroupMePodNextUpdate(GroupMePod *pod); void GroupMePodResetUpdateIterator(GroupMePod *pod); void GroupMePodImageFromPngData(GroupMeAccount *account, GroupMePod *pod, gchar *data, gsize dataLen); void GroupMePodGeneratePhotoPath(GroupMeAccount *account, GroupMePod *pod); //void //GroupMePodGenerateUpdatePath(GroupMeAccount *account, // GroupMePod *pod); #endif /* GROUPME_UPDATE_H */
jynxkizs/purple-groupme
GroupMePod.h
C
gpl-3.0
2,511
body { font-family: Arial, Helvetica, sans-serif; font-size: small; } h1 { color: gray; } h2 { color: #FF9000; font-size: large; font-family: Arial; } h3 { color: #FF9000; font-size: medium; font-family: Arial; font-style: italic; } #header { width: 700px; margin: 0 auto; } #logo { float: left; margin-right: 10px; } #menu { float: left; width: 25%; } #menuPanel { margin-right: 10px; } .rich-pmenu-selected-element { color: #FF9000; } #login { float: right; width: 25%; } #loginPanel { background-color: #d0d0d0; border-style: solid; border-color: black; border-width: 1px; padding: 10px; margin-left: 10px; } .selected { background: #FF9000; } #content { width: 700px; margin: 0 auto; color: #303030; } .text { overflow: auto; width: 700px; font-family: monospace; white-space: pre-wrap; /* css-3 */ white-space: -moz-pre-wrap !important; /* Mozilla, since 1999 */ white-space: -pre-wrap; /* Opera 4-6 */ white-space: -o-pre-wrap; /* Opera 7 */ word-wrap: break-word; } .text.block { display: block; } .error { border: 1px solid red; background: pink; text-align: center; } .rich-fileupload-list-overflow { height: 50px !important; }
charwliu/eid-idp
eid-idp-admin-webapp/src/main/webapp/style.css
CSS
gpl-3.0
1,195
//---------------------------------------------------------------------------- // Copyright (C) 2004-2014 by EMGU Corporation. All rights reserved. //---------------------------------------------------------------------------- using System; using System.Collections.Generic; using System.Runtime.InteropServices; using System.Text; using Emgu.CV.Structure; using Emgu.CV.Util; using Emgu.Util; namespace Emgu.CV.Features2D { /// <summary> /// Wrapping class for feature detection using the goodFeaturesToTrack() function. /// </summary> public class GFTTDetector : UnmanagedObject, IFeatureDetector { static GFTTDetector() { CvInvoke.CheckLibraryLoaded(); } /// <summary> /// Create a Good Feature to Track detector /// </summary> /// <remarks>The function first calculates the minimal eigenvalue for every source image pixel using cvCornerMinEigenVal function and stores them in eig_image. Then it performs non-maxima suppression (only local maxima in 3x3 neighborhood remain). The next step is rejecting the corners with the minimal eigenvalue less than quality_level?max(eig_image(x,y)). Finally, the function ensures that all the corners found are distanced enough one from another by considering the corners (the most strongest corners are considered first) and checking that the distance between the newly considered feature and the features considered earlier is larger than min_distance. So, the function removes the features than are too close to the stronger features</remarks> /// <param name="maxCorners">The maximum number of features to be detected.</param> /// <param name="qualityLevel">Multiplier for the maxmin eigenvalue; specifies minimal accepted quality of image corners.</param> /// <param name="minDistance">Limit, specifying minimum possible distance between returned corners; Euclidian distance is used.</param> /// <param name="blockSize">Size of the averaging block, passed to underlying cvCornerMinEigenVal or cvCornerHarris used by the function.</param> /// <param name="useHarrisDetector">If true, will use Harris corner detector.</param> /// <param name="k">K</param> public GFTTDetector(int maxCorners = 1000, double qualityLevel = 0.01, double minDistance = 1, int blockSize = 3, bool useHarrisDetector = false, double k = 0.04) { _ptr = CvGFTTDetectorCreate(maxCorners, qualityLevel, minDistance, blockSize, useHarrisDetector, k); } #region IFeatureDetector Members /// <summary> /// Get the feature detector. /// </summary> /// <returns>The feature detector</returns> IntPtr IFeatureDetector.FeatureDetectorPtr { get { return Ptr; } } #endregion IntPtr IAlgorithm.AlgorithmPtr { get { return CvInvoke.cveAlgorithmFromFeatureDetector(((IFeatureDetector)this).FeatureDetectorPtr); } } /// <summary> /// Release the unmanaged memory associated with this detector. /// </summary> protected override void DisposeObject() { if(_ptr != IntPtr.Zero) CvGFTTDetectorRelease(ref _ptr); } [DllImport(CvInvoke.ExternLibrary, CallingConvention = CvInvoke.CvCallingConvention)] internal extern static IntPtr CvGFTTDetectorCreate(int maxCorners, double qualityLevel, double minDistance, int blockSize, bool useHarrisDetector, double k); [DllImport(CvInvoke.ExternLibrary, CallingConvention = CvInvoke.CvCallingConvention)] internal extern static void CvGFTTDetectorRelease(ref IntPtr detector); } }
DatouL/ECE4180FinalProject
Emgu.CV/Features2D/GFTTDetector.cs
C#
gpl-3.0
3,706
<?php /* ########################################################################## # # # Version 4 / / / # # -----------__---/__---__------__----__---/---/- # # | /| / /___) / ) (_ ` / ) /___) / / # # _|/_|/__(___ _(___/_(__)___/___/_(___ _/___/___ # # Free Content / Management System # # / # # # # # # Copyright 2005-2015 by webspell.org # # # # visit webSPELL.org, webspell.info to get webSPELL for free # # - Script runs under the GNU GENERAL PUBLIC LICENSE # # - It's NOT allowed to remove this copyright-tag # # -- http://www.fsf.org/licensing/licenses/gpl.html # # # # Code based on WebSPELL Clanpackage (Michael Gruber - webspell.at), # # Far Development by Development Team - webspell.org # # # # visit webspell.org # # # ########################################################################## */ $language_array = array( /* do not edit above this line */ 'just_rate_between_0_10' => 'Hou koers net 0-10 punte!', 'no_access' => 'geen toegang!' );
nerdiabet/webSPELL
languages/af/rating.php
PHP
gpl-3.0
1,899
package net.minecraft.client.model; import net.minecraft.entity.Entity; import net.minecraftforge.fml.relauncher.Side; import net.minecraftforge.fml.relauncher.SideOnly; @SideOnly(Side.CLIENT) public class ModelHumanoidHead extends ModelSkeletonHead { private final ModelRenderer head = new ModelRenderer(this, 32, 0); public ModelHumanoidHead() { super(0, 0, 64, 64); this.head.addBox(-4.0F, -8.0F, -4.0F, 8, 8, 8, 0.25F); this.head.setRotationPoint(0.0F, 0.0F, 0.0F); } /** * Sets the models various rotation angles then renders the model. */ public void render(Entity entityIn, float p_78088_2_, float p_78088_3_, float p_78088_4_, float p_78088_5_, float p_78088_6_, float scale) { super.render(entityIn, p_78088_2_, p_78088_3_, p_78088_4_, p_78088_5_, p_78088_6_, scale); this.head.render(scale); } /** * Sets the model's various rotation angles. For bipeds, par1 and par2 are used for animating the movement of arms * and legs, where par1 represents the time(so that arms and legs swing back and forth) and par2 represents how * "far" arms and legs can swing at most. */ public void setRotationAngles(float p_78087_1_, float p_78087_2_, float p_78087_3_, float p_78087_4_, float p_78087_5_, float p_78087_6_, Entity entityIn) { super.setRotationAngles(p_78087_1_, p_78087_2_, p_78087_3_, p_78087_4_, p_78087_5_, p_78087_6_, entityIn); this.head.rotateAngleY = this.skeletonHead.rotateAngleY; this.head.rotateAngleX = this.skeletonHead.rotateAngleX; } }
tomtomtom09/CampCraft
build/tmp/recompileMc/sources/net/minecraft/client/model/ModelHumanoidHead.java
Java
gpl-3.0
1,605
(function() { var a=sl(1,9); window.vopr.txt='Сколько всего существует перестановок '+a+'-й степени?'; window.vopr.ver=[a.fct().ts()]; })();
DrMGC/chas-ege
dev/linal/B1/1.js
JavaScript
gpl-3.0
185
function loadText() { document.getElementById("btnClose").value = "Cerrar"; } function writeTitle() { document.write("<title>Vista previa</title>") }
Alex-Bond/Core-package
tests/editors/iseditor2/scripts/language/spanish/preview.js
JavaScript
gpl-3.0
173
# News (Selfoss for desktop) News is a client for the web based RSS reader Selfoss, using modern Gnome technologies. ---------- ### About <img src="https://raw.github.com/rhaglion/news/master/data/image.png" alt="Screenshot" style="width: 200px; float:right"/> News is a modern styled RSS reader using the web tool [Selfoss][1]. It has a good integration into the beautifull Gnome and takes the same way like the desktop *so simple as possible*. </br></br> > **But one warning:** This application is still in heavy developement there > might be bugs and missing features. If you have somthing to metion make this on the [bug tracker][2]. > > **And one request:** User feedback is a very important point for projects in this state of development, so please mention as much as you can. ---------- ### Preparation Please remember as first that you need an working Selfoss instanc, but don't worry thats easy. To get more informations about it look [here][4]. ### Install There is an [Copr-Repo][5] for Fedora 20 and 21. If you use an other operating system or Distribution take a look to the installation from source. ### Install from source First check if all dependencies are installed on your GNU/Linux system, if not do it. Other OS aren't support yet. Sorry about that. > **Dependencies:** Gio-2.0 GLib-2.0 GObject-2.0 Gtk+-3.0 >= 3.10 json-glib-1.0 >=0.16 vala >=0.22 libsoup-2.4 >=2.44 libsecret Now clone the sources from Github. $ git clone [email protected]:mfxbe/news.git Next steps are caused by the early state of development. ## If you like to have favicons copy the content from [SELFOSS URL]/data/favicons/ to ~/.cache/news/favicons/ At last build and install the application. $ cd news $ make # make install #### Use I think this explain itself. But remember the early state of development. #### Remove Go to the news source folder (from the installation). Now run the following command. # make uninstall ---------- ### Develop Do not hesitate to join, do something and make an Pull Request. About problems we can discuss later. ### Translate You like help translating? Perfect! The translation is managed through WebTranslateIt. To start sign up there and look at the [page of this project][6]. ---------- ### Credits & Co. A big thanks to all the developer from Selfoss for the awesome application. If you like to contact me write a mail to [[email protected]][7]. ---------- ### Links * [Selfoss][9] * [Selfoss for Android][10] * [GNOME Project][11] [1]: http://selfoss.aditu.de/ [2]: https://github.com/mfxbe/news/issues [3]: mailto:[email protected] [4]: https://github.com/SSilence/selfoss#installation [5]: http://copr.fedoraproject.org/coprs/rhaglion/news/ [6]: https://webtranslateit.com/en/projects/8895-news [7]: mailto:[email protected] [9]: http://selfoss.aditu.de/ [10]: https://github.com/yDelouis/selfoss-android [11]: https://www.gnome.org/
mfxbe/news
README.md
Markdown
gpl-3.0
2,998
<?php /* Última modificación: 27/02/2008 - 9:15am César III Corrección al seleccionar la imagen derecha, no la guardaba correctamente */ require_once '../lib/common.php'; include ("../header.php"); $conex = conexion(); $consulta="select * from cwconcue"; //echo $consulta_islr; $resultado_islr=query($consulta,$conex); $resultado_iva=query($consulta,$conex); $resultado_tf=query($consulta,$conex); $resultado_fiel=query($consulta,$conex); $resultado_laboral=query($consulta,$conex); $resultado_anticipo=query($consulta,$conex); $resultado_im=query($consulta,$conex); $resultado_bombero=query($consulta,$conex); $resultado_701=query($consulta,$conex); $resultado_702=query($consulta,$conex); $resultado_ret_iva=query($consulta,$conex); $resultado_multa=query($consulta,$conex); cerrar_conexion($conex); $codigo=@$_GET['codigo']; $conexion=conexion_conf(); //echo $conexion; $url="parametroslist"; $modulo="Datos de la Empresa"; $tabla="parametros"; $titulos=array("Nombre","R.I,F.","N.I.T.","Presidente","Período","Departamento","Cargo","Dirección","Estado","Ciudad","Teléfonos","Descripción I.S.L.R.","% I.V.A.","Descripción I.V.A.","Descripción Timbre Fiscal","Descripción Fiel Cumplimiento","Descripción Laboral","Descripción Anticipo","% Impuesto Municipal","Descripción Impuesto Municipal","% Bomberos","Descripción Bombero","Descripción Retención I.V.A.","Descripción Deducción o Multa","Encabezado1","Encabezado2","Encabezado3","Encabezado4"); $indices=array("1","14","15","3","4","2","5","16","18","17","19","7","11","9","38","40","42","44","20","50","21","52","48","55","29","30","31","32","23","24","8","10","37","39","41","43","45","46","47","49","51","53","54","56","57","58"); //$indices=array("1","14","15","3","4","2","5","16","18","17","19","8","7","10","9","11","20","21","23","24","29","30","31","32","35","36","37","38","39","40","41","42","43","44","45","46","47","48","49","50","51","52"); if(isset($_POST['aceptar'])){ //echo "Pase por aqui";exit(0); //$archivo=$HTTP_POST_FILES['imagen_izq']['name']; //$archivo; //exit(0); // $archivo=$HTTP_POST_FILES['imagen_izq']['name']; $archivo=$HTTP_POST_FILES['imagen_izq']; //echo "nombre de archivo:".$archivo; //exit(0); if($archivo!="") { $nombre_archivo1 = $HTTP_POST_FILES['imagen_izq']['name']; $tipo_archivo = $HTTP_POST_FILES['imagen_izq']['type']; $tamano_archivo = $HTTP_POST_FILES['imagen_izq']['size']; if (copy($HTTP_POST_FILES['imagen_izq']['tmp_name'],"../imagenes/".$nombre_archivo1)){ echo "<div align='center' style=\"background-color : #84225b; color : #fdfdfd; font-family : 'Arial Black'; font-size : 15px;\">EL archivo fue cargado exitosamente</div>"; chmod("../imagenes/".$nombre_archivo1,0777); }else{ echo "<div align='center' style=\"background-color : #84225b; color : #fdfdfd; font-family : 'Arial Black'; font-size : 15px;\">Ocurri&oacute; un problema cargando el archivo</div>"; } } $archivo=$HTTP_POST_FILES['imagen_der']['name']; if($archivo!="") { $nombre_archivo2 = $HTTP_POST_FILES['imagen_der']['name']; $tipo_archivo = $HTTP_POST_FILES['imagen_der']['type']; $tamano_archivo = $HTTP_POST_FILES['imagen_der']['size']; if (copy($HTTP_POST_FILES['imagen_der']['tmp_name'], "../imagenes/".$nombre_archivo2)) { echo "<div align='center' style=\"background-color : #84225b; color : #fdfdfd; font-family : 'Arial Black'; font-size : 15px;\">EL archivo fue cargado exitosamente</div>"; chmod("../imagenes/".$nombre_archivo2,0777); }else{ echo "<div align='center' style=\"background-color : #84225b; color : #fdfdfd; font-family : 'Arial Black'; font-size : 15px;\">Ocurri&oacute; un problema cargando el archivo</div>"; } } $consulta="select * from ".$tabla; $resultado= query($consulta,$conexion); $cadena=""; foreach($indices as $valor){ $campo=mysql_field_name($resultado,$valor); if($cadena==""){ $cadena=$cadena.$campo."='".$_POST[$campo]."'"; } else{ $cadena=$cadena.",".$campo."='".$_POST[$campo]."'"; } } //echo "nombre arch ".$nombre_archivo1."<br>"; $cadena1="../imagenes/".$nombre_archivo1; $cadena2="../imagenes/".$nombre_archivo2; if($nombre_archivo1!="") { $cadena=$cadena.",imagen_izq='".$cadena1."'"; } if($nombre_archivo2!="") { $cadena=$cadena.",imagen_der='".$cadena2."'"; } $consulta="update ".$tabla." set ".$cadena." where codigo=".$_POST["codigo"]; //echo "la consulta ".$consulta; //exit(0); $resultado=query($consulta,$conexion) or die("no se actualizo el movimiento"); cerrar_conexion($conexion); echo "<SCRIPT language=\"JavaScript\" type=\"text/javascript\"> parent.cont.location.href=\"".$url.".php?pagina=1\" </SCRIPT>"; } $codigo = @$_GET['codigo']; //$descripcion= @$_GET['descripcion']; $consulta="select * from ".$tabla." where codigo=".$codigo; //echo $consulta; $resultado=query($consulta, $conexion); //echo $resultado; $fila=fetch_array($resultado); //echo $fila; ?> <? $consulta="select moneda from parametros where codigo=".$codigo; $resultado1= query($consulta,$conexion); $fila1=fetch_array($resultado1); ?> <FORM name="sampleform" enctype="multipart/form-data" method="POST" target="_self" action="<?echo $_SERVER['PHP_SELF']; ?>"> <TABLE width="100%" height="100"> <TBODY> <tr> <td colspan="2" height="30" class="tb-tit"><strong>Editar Registro de <?echo $modulo?></strong></td> </tr> <TR><td class=tb-head width="180">C&oacute;digo</td><td><INPUT type="text" name="codigo" size="100" value="<?echo $codigo?>"></td> </tr> <? $i=0; foreach($titulos as $nombre){ if($cont==0) { echo "<td class=\"tb-head\" colspan=\"2\" align=\"center\"><strong>DATOS GENERALES</strong></td>"; } $campo=mysql_field_name($resultado,$indices[$i]); //echo $campo; echo "<TR>";?><td class=tb-head ><?echo "$nombre"?></td> <td><INPUT type="text" name="<?echo $campo?>" size="100" value='<?echo "$fila[$campo]";?>'></td> </tr><? $i++; $cont++; if($cont==11) { echo "<td class=\"tb-head\" colspan=\"2\" align=\"center\"><strong>DATOS DE CUENTA</strong></td>"; } if($cont==11) { echo "<TR>";?><td class=tb-head ><?echo "Sobre Giro P</td>"; echo "<td colspan=\"2\">Si<INPUT type=\"radio\" name=\"sobregirop\" id=\"sobregirop\" value=\"S\""; if ($fila['sobregirop']=='S'){ echo "checked=\"true\" ";} echo ">No<INPUT type=\"radio\" name=\"sobregirop\" id=\"sobregirop\" value=\"N\""; if ($fila['sobregirop']=='N'){ echo "checked=\"true\" ";} echo ">"; echo "<TR>";?><td class=tb-head ><?echo "Sobre Giro F</td>"; echo "<td colspan=\"2\">Si<INPUT type=\"radio\" name=\"sobregirof\" id=\"sobregirof\" value=\"S\""; if ($fila['sobregirof']=='S'){ echo "checked=\"true\" ";} echo ">No<INPUT type=\"radio\" name=\"sobregirof\" id=\"sobregirof\" value=\"N\""; if ($fila['sobregirof']=='N'){ echo "checked=\"true\" ";} echo ">"; } if($cont==11){ $ctaiva=$fila['ctaisrl']; echo "<TR>";?><td class=tb-head ><?echo "Cuenta I.S.L.R</td>"; echo "<td colspan=\"3\"><SELECT name=\"ctaisrl\" id=\"ctaisrl\">"; echo "<option value= \"$ctaiva\">$ctaiva</option>"; while($fila_islr=fetch_array($resultado_islr)){ $codigo_islr=$fila_islr['Cuenta']; //$descripcion_islr=$fila_islr['Descrip']; echo "<option value=\"$codigo_islr\">$codigo_islr</option>"; } echo "</SELECT></td> </tr>"; //cerrar_conexion($conex); } if($cont==12){ $ctaiva=$fila['ctaiva']; echo "<TR>";?><td class=tb-head ><?echo "Cuenta I.V.A.</td>"; echo "<td colspan=\"3\"><SELECT name=\"ctaiva\" id=\"ctaiva\"> "; echo "<option value= \"$ctaiva\">$ctaiva</option>"; while($fila_iva=fetch_array($resultado_iva)){ $codigo_iva=$fila_iva['Cuenta']; //$descripcion_iva=$fila_iva['descripcion']; echo "<option value=\"$codigo_iva\">$codigo_iva</option>"; } echo "</SELECT></td> </tr>"; //cerrar_conexion($conex); //$conexion=conexion_conf(); } if($cont==14){ $ctaiva=$fila['cta_tf']; echo "<TR>";?><td class=tb-head ><?echo "Cuenta Timbre Fiscal</td>"; echo "<td colspan=\"3\"><SELECT name=\"cta_tf\" id=\"cta_tf\">"; echo "<option value= \"$ctaiva\">$ctaiva</option>"; while($fila_tf=fetch_array($resultado_tf)){ $codigo_iva=$fila_tf['Cuenta']; //$descripcion_iva=$fila_iva['descripcion']; echo "<option value=\"$codigo_iva\">$codigo_iva</option>"; } echo "</SELECT></td> </tr>"; //cerrar_conexion($conex); //$conexion=conexion_conf(); } if($cont==15){ $ctaiva=$fila['cta_fiel']; echo "<TR>";?><td class=tb-head ><?echo "Cuenta Fiel Cumplimiento</td>"; echo "<td colspan=\"3\"><SELECT name=\"cta_fiel\" id=\"cta_fiel\">"; echo "<option value= \"$ctaiva\">$ctaiva</option>"; while($fila_iva=fetch_array($resultado_fiel)){ $codigo_iva=$fila_iva['Cuenta']; //$descripcion_iva=$fila_iva['descripcion']; echo "<option value=\"$codigo_iva\">$codigo_iva</option>"; } echo "</SELECT></td> </tr>"; //cerrar_conexion($conex); //$conexion=conexion_conf(); } if($cont==16){ $ctaiva=$fila['cta_laboral']; echo "<TR>";?><td class=tb-head ><?echo "Cuenta Laboral</td>"; echo "<td colspan=\"3\"><SELECT name=\"cta_laboral\" id=\"cta_laboral\">"; echo "<option value= \"$ctaiva\">$ctaiva</option>"; while($fila_iva=fetch_array($resultado_laboral)){ $codigo_iva=$fila_iva['Cuenta']; //$descripcion_iva=$fila_iva['descripcion']; echo "<option value=\"$codigo_iva\">$codigo_iva</option>"; } echo "</SELECT></td> </tr>"; //cerrar_conexion($conex); //$conexion=conexion_conf(); } if($cont==17){ $ctaiva=$fila['cta_anticipo']; echo "<TR>";?><td class=tb-head ><?echo "Cuenta Anticipo</td>"; echo "<td colspan=\"3\"><SELECT name=\"cta_anticipo\" id=\"cta_anticipo\">"; echo "<option value= \"$ctaiva\">$ctaiva</option>"; while($fila_iva=fetch_array($resultado_anticipo)){ $codigo_iva=$fila_iva['Cuenta']; //$descripcion_iva=$fila_iva['descripcion']; echo "<option value=\"$codigo_iva\">$codigo_iva</option>"; } echo "</SELECT></td> </tr>"; //cerrar_conexion($conex); //$conexion=conexion_conf(); } if($cont==18){ $ctaiva=$fila['cta_im']; echo "<TR>";?><td class=tb-head ><?echo "Cuenta Impuesto Municipal</td>"; echo "<td colspan=\"3\"><SELECT name=\"cta_im\" id=\"cta_im\">"; echo "<option value= \"$ctaiva\">$ctaiva</option>"; while($fila_iva=fetch_array($resultado_im)){ $codigo_iva=$fila_iva['Cuenta']; //$descripcion_iva=$fila_iva['descripcion']; echo "<option value=\"$codigo_iva\">$codigo_iva</option>"; } echo "</SELECT></td> </tr>"; //cerrar_conexion($conex); //$conexion=conexion_conf(); } if($cont==20){ $ctaiva=$fila['cta_bombero']; echo "<TR>";?><td class=tb-head ><?echo "Cuenta Bomberos</td>"; echo "<td colspan=\"3\"><SELECT name=\"cta_bombero\" id=\"cta_bombero\">"; echo "<option value= \"$ctaiva\">$ctaiva</option>"; while($fila_iva=fetch_array($resultado_bombero)){ $codigo_iva=$fila_iva['Cuenta']; //$descripcion_iva=$fila_iva['descripcion']; echo "<option value=\"$codigo_iva\">$codigo_iva</option>"; } echo "</SELECT></td> </tr>"; //cerrar_conexion($conex); //$conexion=conexion_conf(); } if($cont==22){ $ctaiva=$fila['cta_701']; echo "<TR>";?><td class=tb-head ><?echo "Cuenta 701</td>"; echo "<td colspan=\"3\"><SELECT name=\"cta_701\" id=\"cta_701\">"; echo "<option value= \"$ctaiva\">$ctaiva</option>"; while($fila_iva=fetch_array($resultado_701)){ $codigo_iva=$fila_iva['Cuenta']; //$descripcion_iva=$fila_iva['descripcion']; echo "<option value=\"$codigo_iva\">$codigo_iva</option>"; } echo "</SELECT></td> </tr>"; //cerrar_conexion($conex); //$conexion=conexion_conf(); } if($cont==22){ $ctaiva=$fila['cta_702']; echo "<TR>";?><td class=tb-head ><?echo "Cuenta 702</td>"; echo "<td colspan=\"3\"><SELECT name=\"cta_702\" id=\"cta_702\">"; echo "<option value= \"$ctaiva\">$ctaiva</option>"; while($fila_iva=fetch_array($resultado_702)){ $codigo_iva=$fila_iva['Cuenta']; //$descripcion_iva=$fila_iva['descripcion']; echo "<option value=\"$codigo_iva\">$codigo_iva</option>"; }$ctaiva=$fila['cta_im']; echo "</SELECT></td> </tr>"; //cerrar_conexion($conex); //$conexion=conexion_conf(); } if($cont==22){ $ctaiva=$fila['cta_ret_iva']; echo "<TR>";?><td class=tb-head ><?echo "Cuenta Retencion I.V.A.</td>"; echo "<td colspan=\"3\"><SELECT name=\"cta_ret_iva\" id=\"cta_ret_iva\">"; echo "<option value= \"$ctaiva\">$ctaiva</option>"; while($fila_iva=fetch_array($resultado_ret_iva)){ $codigo_iva=$fila_iva['Cuenta']; //$descripcion_iva=$fila_iva['descripcion']; echo "<option value=\"$codigo_iva\">$codigo_iva</option>"; } echo "</SELECT></td> </tr>"; //cerrar_conexion($conex); //$conexion=conexion_conf(); } if($cont==23){ $ctaiva=$fila['cta_multa']; echo "<TR>";?><td class=tb-head ><?echo "Cuenta Deducciones o Multas</td>"; echo "<td colspan=\"3\"><SELECT name=\"cta_multa\" id=\"cta_multa\">"; echo "<option value= \"$ctaiva\">$ctaiva</option>"; while($fila_iva=fetch_array($resultado_multa)){ $codigo_iva=$fila_iva['Cuenta']; //$descripcion_iva=$fila_iva['descripcion']; echo "<option value=\"$codigo_iva\">$codigo_iva</option>"; } echo "</SELECT></td> </tr>"; //cerrar_conexion($conex); //$conexion=conexion_conf(); } if($cont==24){ $moneda=$fila1['moneda']; echo "<TR>";?><td class=tb-head ><?echo "Moneda</td>"; echo "<td colspan=\"3\"><SELECT name=\"moneda\" id=\"moneda\">"; echo "<option class=\"tb-fila\" value=\"$moneda\">$moneda</option>"; echo "<option value=\"Bs.F.\">Bolivar Fuerte (Bs.F.)</option>"; echo "<option value=\"Bs.\">Bolivar (Bs.)</option>"; echo "<option value=\"$\">Dolar ($)</option>"; echo "<option value=\"€\">Euros (€)</option>"; echo "</SELECT></td> </tr>"; } //echo"<br>"; if($cont==24) { echo "<td class=\"tb-head\" colspan=\"2\" align=\"center\"><strong>DATOS DE REPORTE</strong></td>"; } if($cont==28) { echo "<TR>";?><td class=tb-head ><?echo "Imagen Izquierda</td>"; echo "<td colspan=\"2\"><INPUT type=\"file\" name=\"imagen_izq\" id=\"imagen_izq\" value=\"\"></td>";//echo $imagenizq; } if($cont==28) { echo "<TR>";?><td class=tb-head ><?echo "Imagen Derecha</td>"; echo "<td colspan=\"2\"><INPUT type=\"file\" name=\"imagen_der\" id=\"imagen_der\" value=\"\"></td>"; //echo $imagender; } if($cont==28) { echo "<tr><td class=\"tb-head\" colspan=\"2\" align=\"center\"><strong>DATOS DE CONFIGURACIÓN DE SISTEMA</strong></td></tr>"; } if($cont==28){ echo "<TR>";?><td class=tb-head ><?echo "Tipo de Presupuesto</td>"; echo "<td colspan=\"3\"><SELECT name=\"tipo_presupuesto\" id=\"tipo_presupuesto\">"; echo "<option class=\"tb-fila\">Seleccione Tipo de Presupuesto a Ejecurar</option>"; echo "<option value=\"0\">Presupuesto por Programatica</option>"; echo "<option value=\"1\">Presupuesto por Proyectos</option>"; echo "</SELECT></td> </tr>"; } if($cont==28){ echo "<TR>";?><td class=tb-head ><?echo "Tipo de Compromisos</td>"; echo "<td colspan=\"3\"><SELECT name=\"tipo_compromiso\" id=\"tipo_compromiso\">"; echo "<option class=\"tb-fila\">Desea Comprometer automaticamente cuando realiza la orden?</option>"; echo "<option value=\"0\">Si</option>"; echo "<option value=\"1\">No</option>"; echo "</SELECT></td> </tr>"; } if($cont==28){ echo "<TR>";?><td class=tb-head ><?echo "Tipo de Causados</td>"; echo "<td colspan=\"3\"><SELECT name=\"tipo_causado\" id=\"tipo_causado\">"; echo "<option class=\"tb-fila\">Desea Causar automaticamente cuando realiza la orden de pago?</option>"; echo "<option value=\"0\">Si</option>"; echo "<option value=\"1\">No</option>"; echo "</SELECT></td> </tr>"; } } ?> <tr class="tb-tit"> <td></td> <td align="right"><INPUT type="submit" name="aceptar" value="Aceptar">&nbsp;<INPUT type="button" name="cancelar" value="Cancelar" onclick="javascript:cerrar('<?echo $url?>');"></td> </tr> </tbody> </table> </FORM> </body> </html> <? cerrar_conexion($conexion); ?>
venenux/zaint
selectraerp/configuracion/parametros_edit2.php
PHP
gpl-3.0
16,852
/* * Copyright (c) 2014 Apple Inc. All rights reserved. * * @APPLE_OSREFERENCE_LICENSE_HEADER_START@ * * This file contains Original Code and/or Modifications of Original Code * as defined in and that are subject to the Apple Public Source License * Version 2.0 (the 'License'). You may not use this file except in * compliance with the License. The rights granted to you under the License * may not be used to create, or enable the creation or redistribution of, * unlawful or unlicensed copies of an Apple operating system, or to * circumvent, violate, or enable the circumvention or violation of, any * terms of an Apple operating system software license agreement. * * Please obtain a copy of the License at * http://www.opensource.apple.com/apsl/ and read it before using this file. * * The Original Code and all software distributed under the License are * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES, * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT. * Please see the License for the specific language governing rights and * limitations under the License. * * @APPLE_OSREFERENCE_LICENSE_HEADER_END@ */ #ifndef _SYS_CSR_H_ #define _SYS_CSR_H_ #include <stdint.h> #include <sys/appleapiopts.h> #include <sys/cdefs.h> #ifdef __APPLE_API_PRIVATE typedef uint32_t csr_config_t; typedef uint32_t csr_op_t; /* Rootless configuration flags */ #define CSR_ALLOW_UNTRUSTED_KEXTS (1 << 0) #define CSR_ALLOW_UNRESTRICTED_FS (1 << 1) #define CSR_ALLOW_TASK_FOR_PID (1 << 2) #define CSR_ALLOW_KERNEL_DEBUGGER (1 << 3) #define CSR_ALLOW_APPLE_INTERNAL (1 << 4) #define CSR_ALLOW_DESTRUCTIVE_DTRACE (1 << 5) /* name deprecated */ #define CSR_ALLOW_UNRESTRICTED_DTRACE (1 << 5) #define CSR_ALLOW_UNRESTRICTED_NVRAM (1 << 6) #define CSR_ALLOW_DEVICE_CONFIGURATION (1 << 7) #define CSR_ALLOW_ANY_RECOVERY_OS (1 << 8) #define CSR_VALID_FLAGS (CSR_ALLOW_UNTRUSTED_KEXTS | \ CSR_ALLOW_UNRESTRICTED_FS | \ CSR_ALLOW_TASK_FOR_PID | \ CSR_ALLOW_KERNEL_DEBUGGER | \ CSR_ALLOW_APPLE_INTERNAL | \ CSR_ALLOW_UNRESTRICTED_DTRACE | \ CSR_ALLOW_UNRESTRICTED_NVRAM | \ CSR_ALLOW_DEVICE_CONFIGURATION | \ CSR_ALLOW_ANY_RECOVERY_OS) /* CSR capabilities that a booter can give to the system */ #define CSR_CAPABILITY_UNLIMITED (1 << 0) #define CSR_CAPABILITY_CONFIG (1 << 1) #define CSR_CAPABILITY_APPLE_INTERNAL (1 << 2) #define CSR_VALID_CAPABILITIES (CSR_CAPABILITY_UNLIMITED | CSR_CAPABILITY_CONFIG | CSR_CAPABILITY_APPLE_INTERNAL) #ifdef PRIVATE /* Private system call interface between Libsyscall and xnu */ /* Syscall flavors */ enum csr_syscalls { CSR_SYSCALL_CHECK, CSR_SYSCALL_GET_ACTIVE_CONFIG, }; #endif /* PRIVATE */ __BEGIN_DECLS #ifdef XNU_KERNEL_PRIVATE void csr_init(void); #endif /* Syscalls */ int csr_check(csr_config_t mask); int csr_get_active_config(csr_config_t *config); __END_DECLS #endif /* __APPLE_API_PRIVATE */ #endif /* _SYS_CSR_H_ */
LubosD/darling
platform-include/sys/csr.h
C
gpl-3.0
3,283
/* base64.cpp and base64.h Copyright (C) 2004-2008 René Nyffenegger This source code is provided 'as-is', without any express or implied warranty. In no event will the author be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this source code must not be misrepresented; you must not claim that you wrote the original source code. If you use this source code in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original source code. 3. This notice may not be removed or altered from any source distribution. René Nyffenegger [email protected] */ /// Adapted from code found on http://stackoverflow.com/questions/180947/base64-decode-snippet-in-c /// Originally by René Nyffenegger, modified by some other guy and then devified by Gav Wood. #include "Base64.h" #include <iostream> using namespace std; using namespace dev; static const std::string base64_chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ" "abcdefghijklmnopqrstuvwxyz" "0123456789+/"; static inline bool is_base64(byte c) { return (isalnum(c) || (c == '+') || (c == '/')); } std::string dev::toBase64(bytesConstRef _in) { std::string ret; int i = 0; int j = 0; byte char_array_3[3]; byte char_array_4[4]; auto buf = _in.data(); auto bufLen = _in.size(); while (bufLen--) { char_array_3[i++] = *(buf++); if (i == 3) { char_array_4[0] = (char_array_3[0] & 0xfc) >> 2; char_array_4[1] = ((char_array_3[0] & 0x03) << 4) + ((char_array_3[1] & 0xf0) >> 4); char_array_4[2] = ((char_array_3[1] & 0x0f) << 2) + ((char_array_3[2] & 0xc0) >> 6); char_array_4[3] = char_array_3[2] & 0x3f; for(i = 0; (i <4) ; i++) ret += base64_chars[char_array_4[i]]; i = 0; } } if (i) { for(j = i; j < 3; j++) char_array_3[j] = '\0'; char_array_4[0] = (char_array_3[0] & 0xfc) >> 2; char_array_4[1] = ((char_array_3[0] & 0x03) << 4) + ((char_array_3[1] & 0xf0) >> 4); char_array_4[2] = ((char_array_3[1] & 0x0f) << 2) + ((char_array_3[2] & 0xc0) >> 6); char_array_4[3] = char_array_3[2] & 0x3f; for (j = 0; (j < i + 1); j++) ret += base64_chars[char_array_4[j]]; while((i++ < 3)) ret += '='; } return ret; } bytes dev::fromBase64(std::string const& encoded_string) { int in_len = encoded_string.size(); int i = 0; int j = 0; int in_ = 0; byte char_array_4[4], char_array_3[3]; bytes ret; while (in_len-- && ( encoded_string[in_] != '=') && is_base64(encoded_string[in_])) { char_array_4[i++] = encoded_string[in_]; in_++; if (i ==4) { for (i = 0; i <4; i++) char_array_4[i] = base64_chars.find(char_array_4[i]); char_array_3[0] = (char_array_4[0] << 2) + ((char_array_4[1] & 0x30) >> 4); char_array_3[1] = ((char_array_4[1] & 0xf) << 4) + ((char_array_4[2] & 0x3c) >> 2); char_array_3[2] = ((char_array_4[2] & 0x3) << 6) + char_array_4[3]; for (i = 0; (i < 3); i++) ret.push_back(char_array_3[i]); i = 0; } } if (i) { for (j = i; j <4; j++) char_array_4[j] = 0; for (j = 0; j <4; j++) char_array_4[j] = base64_chars.find(char_array_4[j]); char_array_3[0] = (char_array_4[0] << 2) + ((char_array_4[1] & 0x30) >> 4); char_array_3[1] = ((char_array_4[1] & 0xf) << 4) + ((char_array_4[2] & 0x3c) >> 2); char_array_3[2] = ((char_array_4[2] & 0x3) << 6) + char_array_4[3]; for (j = 0; (j < i - 1); j++) ret.push_back(char_array_3[j]); } return ret; }
imapp-pl/cpp-ethereum
libdevcore/Base64.cpp
C++
gpl-3.0
3,770
**************************************************************** * FILENAME: NC01.asm * AUTHOR: SEOKJUN HONG * SYSTEM: OFASM v4.0 revision 113 **************************************************************** NC01 CSECT LR 12,15 USING NC01,12 * * 00110101 * 01011100 * Result = 00010100 * CC = 1 * LA 5,=XL4'00110101' NC 0(4,5),=XL4'01011100' L 6,0(5) OFADBGREG 6 * * NC 0(4,5),=XL4'00000000' L 6,0(5) OFADBGREG 6 BR 14 END
Tmaxsoft-Compiler/OFASM-test
Mtest/SEOKJUN/NC02/NC01.asm
Assembly
gpl-3.0
623
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Text; using System.Windows.Forms; using System.Text.RegularExpressions; using System.IO.Ports; using System.IO; using System.Runtime.InteropServices; using System.Xml; using System.Net; namespace MissionPlanner.GCSViews.ConfigurationView { partial class ConfigFirmware : MyUserControl { /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.IContainer components = null; /// <summary> /// Clean up any resources being used. /// </summary> /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param> protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } private Controls.ImageLabel pictureBoxAPM; private Controls.ImageLabel pictureBoxQuad; private Controls.ImageLabel pictureBoxHexa; private Controls.ImageLabel pictureBoxTri; private Controls.ImageLabel pictureBoxY6; private System.Windows.Forms.Label lbl_status; private System.Windows.Forms.ProgressBar progress; private System.Windows.Forms.Label label2; private Controls.ImageLabel pictureBoxHeli; private PictureBox pictureBoxHilimage; private PictureBox pictureBoxAPHil; private PictureBox pictureBoxACHil; private PictureBox pictureBoxACHHil; private Controls.ImageLabel pictureBoxOcta; private Label label1; private Controls.ImageLabel pictureBoxOctaQuad; private void InitializeComponent() { System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(ConfigFirmware)); this.pictureBoxAPM = new MissionPlanner.Controls.ImageLabel(); this.pictureBoxQuad = new MissionPlanner.Controls.ImageLabel(); this.pictureBoxHexa = new MissionPlanner.Controls.ImageLabel(); this.pictureBoxTri = new MissionPlanner.Controls.ImageLabel(); this.pictureBoxY6 = new MissionPlanner.Controls.ImageLabel(); this.lbl_status = new System.Windows.Forms.Label(); this.progress = new System.Windows.Forms.ProgressBar(); this.label2 = new System.Windows.Forms.Label(); this.pictureBoxHeli = new MissionPlanner.Controls.ImageLabel(); this.pictureBoxHilimage = new System.Windows.Forms.PictureBox(); this.pictureBoxAPHil = new System.Windows.Forms.PictureBox(); this.pictureBoxACHil = new System.Windows.Forms.PictureBox(); this.pictureBoxACHHil = new System.Windows.Forms.PictureBox(); this.pictureBoxOcta = new MissionPlanner.Controls.ImageLabel(); this.pictureBoxOctaQuad = new MissionPlanner.Controls.ImageLabel(); this.pictureBoxRover = new MissionPlanner.Controls.ImageLabel(); this.label1 = new System.Windows.Forms.Label(); this.CMB_history = new System.Windows.Forms.ComboBox(); this.CMB_history_label = new System.Windows.Forms.Label(); this.lbl_Custom_firmware_label = new System.Windows.Forms.Label(); this.lbl_devfw = new System.Windows.Forms.Label(); this.lbl_px4io = new System.Windows.Forms.Label(); this.lbl_dlfw = new System.Windows.Forms.Label(); this.lbl_px4bl = new System.Windows.Forms.Label(); ((System.ComponentModel.ISupportInitialize)(this.pictureBoxHilimage)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.pictureBoxAPHil)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.pictureBoxACHil)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.pictureBoxACHHil)).BeginInit(); this.SuspendLayout(); // // pictureBoxAPM // this.pictureBoxAPM.Cursor = System.Windows.Forms.Cursors.Hand; this.pictureBoxAPM.Image = global::MissionPlanner.Properties.Resources.APM_airframes_001; resources.ApplyResources(this.pictureBoxAPM, "pictureBoxAPM"); this.pictureBoxAPM.Name = "pictureBoxAPM"; this.pictureBoxAPM.TabStop = false; this.pictureBoxAPM.Tag = ""; this.pictureBoxAPM.Click += new System.EventHandler(this.pictureBoxFW_Click); // // pictureBoxQuad // this.pictureBoxQuad.Cursor = System.Windows.Forms.Cursors.Hand; this.pictureBoxQuad.Image = global::MissionPlanner.Properties.Resources.FW_icons_2013_logos_04; resources.ApplyResources(this.pictureBoxQuad, "pictureBoxQuad"); this.pictureBoxQuad.Name = "pictureBoxQuad"; this.pictureBoxQuad.TabStop = false; this.pictureBoxQuad.Tag = ""; this.pictureBoxQuad.Click += new System.EventHandler(this.pictureBoxFW_Click); // // pictureBoxHexa // this.pictureBoxHexa.Cursor = System.Windows.Forms.Cursors.Hand; this.pictureBoxHexa.Image = global::MissionPlanner.Properties.Resources.FW_icons_2013_logos_10; resources.ApplyResources(this.pictureBoxHexa, "pictureBoxHexa"); this.pictureBoxHexa.Name = "pictureBoxHexa"; this.pictureBoxHexa.TabStop = false; this.pictureBoxHexa.Tag = ""; this.pictureBoxHexa.Click += new System.EventHandler(this.pictureBoxFW_Click); // // pictureBoxTri // this.pictureBoxTri.Cursor = System.Windows.Forms.Cursors.Hand; this.pictureBoxTri.Image = global::MissionPlanner.Properties.Resources.FW_icons_2013_logos_08; resources.ApplyResources(this.pictureBoxTri, "pictureBoxTri"); this.pictureBoxTri.Name = "pictureBoxTri"; this.pictureBoxTri.TabStop = false; this.pictureBoxTri.Tag = ""; this.pictureBoxTri.Click += new System.EventHandler(this.pictureBoxFW_Click); // // pictureBoxY6 // this.pictureBoxY6.Cursor = System.Windows.Forms.Cursors.Hand; this.pictureBoxY6.Image = global::MissionPlanner.Properties.Resources.y6a; resources.ApplyResources(this.pictureBoxY6, "pictureBoxY6"); this.pictureBoxY6.Name = "pictureBoxY6"; this.pictureBoxY6.TabStop = false; this.pictureBoxY6.Tag = ""; this.pictureBoxY6.Click += new System.EventHandler(this.pictureBoxFW_Click); // // lbl_status // resources.ApplyResources(this.lbl_status, "lbl_status"); this.lbl_status.Name = "lbl_status"; // // progress // resources.ApplyResources(this.progress, "progress"); this.progress.Name = "progress"; this.progress.Step = 1; // // label2 // resources.ApplyResources(this.label2, "label2"); this.label2.Name = "label2"; // // pictureBoxHeli // this.pictureBoxHeli.Cursor = System.Windows.Forms.Cursors.Hand; this.pictureBoxHeli.Image = global::MissionPlanner.Properties.Resources.APM_airframes_08; resources.ApplyResources(this.pictureBoxHeli, "pictureBoxHeli"); this.pictureBoxHeli.Name = "pictureBoxHeli"; this.pictureBoxHeli.TabStop = false; this.pictureBoxHeli.Tag = ""; this.pictureBoxHeli.Click += new System.EventHandler(this.pictureBoxFW_Click); // // pictureBoxHilimage // this.pictureBoxHilimage.Image = global::MissionPlanner.Properties.Resources.hil; resources.ApplyResources(this.pictureBoxHilimage, "pictureBoxHilimage"); this.pictureBoxHilimage.Name = "pictureBoxHilimage"; this.pictureBoxHilimage.TabStop = false; this.pictureBoxHilimage.Tag = ""; // // pictureBoxAPHil // this.pictureBoxAPHil.Cursor = System.Windows.Forms.Cursors.Hand; this.pictureBoxAPHil.Image = global::MissionPlanner.Properties.Resources.hilplane; resources.ApplyResources(this.pictureBoxAPHil, "pictureBoxAPHil"); this.pictureBoxAPHil.Name = "pictureBoxAPHil"; this.pictureBoxAPHil.TabStop = false; this.pictureBoxAPHil.Tag = ""; this.pictureBoxAPHil.Click += new System.EventHandler(this.pictureBoxFW_Click); // // pictureBoxACHil // this.pictureBoxACHil.Cursor = System.Windows.Forms.Cursors.Hand; this.pictureBoxACHil.Image = global::MissionPlanner.Properties.Resources.hilquad; resources.ApplyResources(this.pictureBoxACHil, "pictureBoxACHil"); this.pictureBoxACHil.Name = "pictureBoxACHil"; this.pictureBoxACHil.TabStop = false; this.pictureBoxACHil.Tag = ""; this.pictureBoxACHil.Click += new System.EventHandler(this.pictureBoxFW_Click); // // pictureBoxACHHil // this.pictureBoxACHHil.Cursor = System.Windows.Forms.Cursors.Hand; this.pictureBoxACHHil.Image = global::MissionPlanner.Properties.Resources.hilheli; resources.ApplyResources(this.pictureBoxACHHil, "pictureBoxACHHil"); this.pictureBoxACHHil.Name = "pictureBoxACHHil"; this.pictureBoxACHHil.TabStop = false; this.pictureBoxACHHil.Tag = ""; this.pictureBoxACHHil.Click += new System.EventHandler(this.pictureBoxFW_Click); // // pictureBoxOcta // this.pictureBoxOcta.Image = global::MissionPlanner.Properties.Resources.FW_icons_2013_logos_12; resources.ApplyResources(this.pictureBoxOcta, "pictureBoxOcta"); this.pictureBoxOcta.Name = "pictureBoxOcta"; this.pictureBoxOcta.TabStop = false; this.pictureBoxOcta.Tag = ""; this.pictureBoxOcta.Click += new System.EventHandler(this.pictureBoxFW_Click); // // pictureBoxOctaQuad // this.pictureBoxOctaQuad.Image = global::MissionPlanner.Properties.Resources.x8; resources.ApplyResources(this.pictureBoxOctaQuad, "pictureBoxOctaQuad"); this.pictureBoxOctaQuad.Name = "pictureBoxOctaQuad"; this.pictureBoxOctaQuad.TabStop = false; this.pictureBoxOctaQuad.Tag = ""; this.pictureBoxOctaQuad.Click += new System.EventHandler(this.pictureBoxFW_Click); // // pictureBoxRover // this.pictureBoxRover.Cursor = System.Windows.Forms.Cursors.Hand; this.pictureBoxRover.Image = global::MissionPlanner.Properties.Resources.rover_11; resources.ApplyResources(this.pictureBoxRover, "pictureBoxRover"); this.pictureBoxRover.Name = "pictureBoxRover"; this.pictureBoxRover.TabStop = false; this.pictureBoxRover.Tag = ""; this.pictureBoxRover.Click += new System.EventHandler(this.pictureBoxFW_Click); // // label1 // resources.ApplyResources(this.label1, "label1"); this.label1.Name = "label1"; // // CMB_history // this.CMB_history.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList; this.CMB_history.DropDownWidth = 160; this.CMB_history.FormattingEnabled = true; resources.ApplyResources(this.CMB_history, "CMB_history"); this.CMB_history.Name = "CMB_history"; this.CMB_history.SelectedIndexChanged += new System.EventHandler(this.CMB_history_SelectedIndexChanged); // // CMB_history_label // resources.ApplyResources(this.CMB_history_label, "CMB_history_label"); this.CMB_history_label.Cursor = System.Windows.Forms.Cursors.Hand; this.CMB_history_label.Name = "CMB_history_label"; this.CMB_history_label.Click += new System.EventHandler(this.CMB_history_label_Click); // // lbl_Custom_firmware_label // resources.ApplyResources(this.lbl_Custom_firmware_label, "lbl_Custom_firmware_label"); this.lbl_Custom_firmware_label.Cursor = System.Windows.Forms.Cursors.Hand; this.lbl_Custom_firmware_label.Name = "lbl_Custom_firmware_label"; this.lbl_Custom_firmware_label.Click += new System.EventHandler(this.Custom_firmware_label_Click); // // lbl_devfw // resources.ApplyResources(this.lbl_devfw, "lbl_devfw"); this.lbl_devfw.Cursor = System.Windows.Forms.Cursors.Hand; this.lbl_devfw.Name = "lbl_devfw"; this.lbl_devfw.Click += new System.EventHandler(this.lbl_devfw_Click); // // lbl_px4io // resources.ApplyResources(this.lbl_px4io, "lbl_px4io"); this.lbl_px4io.Cursor = System.Windows.Forms.Cursors.Hand; this.lbl_px4io.Name = "lbl_px4io"; this.lbl_px4io.Click += new System.EventHandler(this.lbl_px4io_Click); // // lbl_dlfw // resources.ApplyResources(this.lbl_dlfw, "lbl_dlfw"); this.lbl_dlfw.Cursor = System.Windows.Forms.Cursors.Hand; this.lbl_dlfw.Name = "lbl_dlfw"; this.lbl_dlfw.Click += new System.EventHandler(this.lbl_dlfw_Click); // // lbl_px4bl // resources.ApplyResources(this.lbl_px4bl, "lbl_px4bl"); this.lbl_px4bl.Cursor = System.Windows.Forms.Cursors.Hand; this.lbl_px4bl.Name = "lbl_px4bl"; this.lbl_px4bl.Click += new System.EventHandler(this.lbl_px4bl_Click); // // ConfigFirmware // resources.ApplyResources(this, "$this"); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.Controls.Add(this.lbl_px4bl); this.Controls.Add(this.lbl_dlfw); this.Controls.Add(this.lbl_px4io); this.Controls.Add(this.lbl_devfw); this.Controls.Add(this.lbl_Custom_firmware_label); this.Controls.Add(this.CMB_history_label); this.Controls.Add(this.pictureBoxRover); this.Controls.Add(this.CMB_history); this.Controls.Add(this.label1); this.Controls.Add(this.label2); this.Controls.Add(this.lbl_status); this.Controls.Add(this.progress); this.Controls.Add(this.pictureBoxACHHil); this.Controls.Add(this.pictureBoxACHil); this.Controls.Add(this.pictureBoxAPHil); this.Controls.Add(this.pictureBoxHilimage); this.Controls.Add(this.pictureBoxOctaQuad); this.Controls.Add(this.pictureBoxOcta); this.Controls.Add(this.pictureBoxHeli); this.Controls.Add(this.pictureBoxY6); this.Controls.Add(this.pictureBoxTri); this.Controls.Add(this.pictureBoxHexa); this.Controls.Add(this.pictureBoxQuad); this.Controls.Add(this.pictureBoxAPM); this.Name = "ConfigFirmware"; ((System.ComponentModel.ISupportInitialize)(this.pictureBoxHilimage)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.pictureBoxAPHil)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.pictureBoxACHil)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.pictureBoxACHHil)).EndInit(); this.ResumeLayout(false); this.PerformLayout(); } private ComboBox CMB_history; private Controls.ImageLabel pictureBoxRover; private Label CMB_history_label; private Label lbl_Custom_firmware_label; private Label lbl_devfw; private Label lbl_px4io; private Label lbl_dlfw; private Label lbl_px4bl; } }
martinbuc/missionplanner
GCSViews/ConfigurationView/ConfigFirmware.Designer.cs
C#
gpl-3.0
16,964
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <!--NewPage--> <HTML> <HEAD> <!-- Generated by javadoc (build 1.6.0_33) on Fri Jun 22 11:01:30 IST 2012 --> <TITLE> de.fuberlin.wiwiss.d2rq.sql (D2RQ) </TITLE> <META NAME="date" CONTENT="2012-06-22"> <LINK REL ="stylesheet" TYPE="text/css" HREF="../../../../../stylesheet.css" TITLE="Style"> <SCRIPT type="text/javascript"> function windowTitle() { if (location.href.indexOf('is-external=true') == -1) { parent.document.title="de.fuberlin.wiwiss.d2rq.sql (D2RQ)"; } } </SCRIPT> <NOSCRIPT> </NOSCRIPT> </HEAD> <BODY BGCOLOR="white" onload="windowTitle();"> <HR> <!-- ========= START OF TOP NAVBAR ======= --> <A NAME="navbar_top"><!-- --></A> <A HREF="#skip-navbar_top" title="Skip navigation links"></A> <TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0" SUMMARY=""> <TR> <TD COLSPAN=2 BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A NAME="navbar_top_firstrow"><!-- --></A> <TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3" SUMMARY=""> <TR ALIGN="center" VALIGN="top"> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../overview-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> &nbsp;<FONT CLASS="NavBarFont1Rev"><B>Package</B></FONT>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <FONT CLASS="NavBarFont1">Class</FONT>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="package-use.html"><FONT CLASS="NavBarFont1"><B>Use</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="package-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../index-files/index-1.html"><FONT CLASS="NavBarFont1"><B>Index</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A>&nbsp;</TD> </TR> </TABLE> </TD> <TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM> </EM> </TD> </TR> <TR> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> &nbsp;<A HREF="../../../../../de/fuberlin/wiwiss/d2rq/server/package-summary.html"><B>PREV PACKAGE</B></A>&nbsp; &nbsp;<A HREF="../../../../../de/fuberlin/wiwiss/d2rq/sql/types/package-summary.html"><B>NEXT PACKAGE</B></A></FONT></TD> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> <A HREF="../../../../../index.html?de/fuberlin/wiwiss/d2rq/sql/package-summary.html" target="_top"><B>FRAMES</B></A> &nbsp; &nbsp;<A HREF="package-summary.html" target="_top"><B>NO FRAMES</B></A> &nbsp; &nbsp;<SCRIPT type="text/javascript"> <!-- if(window==top) { document.writeln('<A HREF="../../../../../allclasses-noframe.html"><B>All Classes</B></A>'); } //--> </SCRIPT> <NOSCRIPT> <A HREF="../../../../../allclasses-noframe.html"><B>All Classes</B></A> </NOSCRIPT> </FONT></TD> </TR> </TABLE> <A NAME="skip-navbar_top"></A> <!-- ========= END OF TOP NAVBAR ========= --> <HR> <H2> Package de.fuberlin.wiwiss.d2rq.sql </H2> SQL query and result processing code. <P> <B>See:</B> <BR> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<A HREF="#package_description"><B>Description</B></A> <P> <TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY=""> <TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor"> <TH ALIGN="left" COLSPAN="2"><FONT SIZE="+2"> <B>Interface Summary</B></FONT></TH> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD WIDTH="15%"><B><A HREF="../../../../../de/fuberlin/wiwiss/d2rq/sql/Quoter.html" title="interface in de.fuberlin.wiwiss.d2rq.sql">Quoter</A></B></TD> <TD>&nbsp;</TD> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD WIDTH="15%"><B><A HREF="../../../../../de/fuberlin/wiwiss/d2rq/sql/ResultRow.html" title="interface in de.fuberlin.wiwiss.d2rq.sql">ResultRow</A></B></TD> <TD>A result row returned by a database query, presented as a map from columns to string values.</TD> </TR> </TABLE> &nbsp; <P> <TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY=""> <TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor"> <TH ALIGN="left" COLSPAN="2"><FONT SIZE="+2"> <B>Class Summary</B></FONT></TH> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD WIDTH="15%"><B><A HREF="../../../../../de/fuberlin/wiwiss/d2rq/sql/BeanCounter.html" title="class in de.fuberlin.wiwiss.d2rq.sql">BeanCounter</A></B></TD> <TD>A class for capturing performance information.</TD> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD WIDTH="15%"><B><A HREF="../../../../../de/fuberlin/wiwiss/d2rq/sql/ConnectedDB.html" title="class in de.fuberlin.wiwiss.d2rq.sql">ConnectedDB</A></B></TD> <TD>TODO Move all engine-specific code from here to <A HREF="../../../../../de/fuberlin/wiwiss/d2rq/sql/vendor/Vendor.html" title="interface in de.fuberlin.wiwiss.d2rq.sql.vendor"><CODE>Vendor</CODE></A> and its implementations</TD> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD WIDTH="15%"><B><A HREF="../../../../../de/fuberlin/wiwiss/d2rq/sql/Quoter.PatternDoublingQuoter.html" title="class in de.fuberlin.wiwiss.d2rq.sql">Quoter.PatternDoublingQuoter</A></B></TD> <TD>&nbsp;</TD> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD WIDTH="15%"><B><A HREF="../../../../../de/fuberlin/wiwiss/d2rq/sql/ResultRowMap.html" title="class in de.fuberlin.wiwiss.d2rq.sql">ResultRowMap</A></B></TD> <TD>A result row returned by a database query, presented as a map from SELECT clause entries to string values.</TD> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD WIDTH="15%"><B><A HREF="../../../../../de/fuberlin/wiwiss/d2rq/sql/SelectStatementBuilder.html" title="class in de.fuberlin.wiwiss.d2rq.sql">SelectStatementBuilder</A></B></TD> <TD>Collects parts of a SELECT query and delivers a corresponding SQL statement.</TD> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD WIDTH="15%"><B><A HREF="../../../../../de/fuberlin/wiwiss/d2rq/sql/SQL.html" title="class in de.fuberlin.wiwiss.d2rq.sql">SQL</A></B></TD> <TD>Parses different types of SQL fragments from Strings, and turns them back into Strings.</TD> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD WIDTH="15%"><B><A HREF="../../../../../de/fuberlin/wiwiss/d2rq/sql/SQLIterator.html" title="class in de.fuberlin.wiwiss.d2rq.sql">SQLIterator</A></B></TD> <TD>Executes an SQL query and delivers result rows as an iterator over <A HREF="../../../../../de/fuberlin/wiwiss/d2rq/sql/ResultRow.html" title="interface in de.fuberlin.wiwiss.d2rq.sql"><CODE>ResultRow</CODE></A>s.</TD> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD WIDTH="15%"><B><A HREF="../../../../../de/fuberlin/wiwiss/d2rq/sql/SQLScriptLoader.html" title="class in de.fuberlin.wiwiss.d2rq.sql">SQLScriptLoader</A></B></TD> <TD>Reads SQL statements from a file or other source.</TD> </TR> </TABLE> &nbsp; <P> <A NAME="package_description"><!-- --></A><H2> Package de.fuberlin.wiwiss.d2rq.sql Description </H2> <P> <p>SQL query and result processing code.</p> <P> <P> <DL> </DL> <HR> <!-- ======= START OF BOTTOM NAVBAR ====== --> <A NAME="navbar_bottom"><!-- --></A> <A HREF="#skip-navbar_bottom" title="Skip navigation links"></A> <TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0" SUMMARY=""> <TR> <TD COLSPAN=2 BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A NAME="navbar_bottom_firstrow"><!-- --></A> <TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3" SUMMARY=""> <TR ALIGN="center" VALIGN="top"> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../overview-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> &nbsp;<FONT CLASS="NavBarFont1Rev"><B>Package</B></FONT>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <FONT CLASS="NavBarFont1">Class</FONT>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="package-use.html"><FONT CLASS="NavBarFont1"><B>Use</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="package-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../index-files/index-1.html"><FONT CLASS="NavBarFont1"><B>Index</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A>&nbsp;</TD> </TR> </TABLE> </TD> <TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM> </EM> </TD> </TR> <TR> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> &nbsp;<A HREF="../../../../../de/fuberlin/wiwiss/d2rq/server/package-summary.html"><B>PREV PACKAGE</B></A>&nbsp; &nbsp;<A HREF="../../../../../de/fuberlin/wiwiss/d2rq/sql/types/package-summary.html"><B>NEXT PACKAGE</B></A></FONT></TD> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> <A HREF="../../../../../index.html?de/fuberlin/wiwiss/d2rq/sql/package-summary.html" target="_top"><B>FRAMES</B></A> &nbsp; &nbsp;<A HREF="package-summary.html" target="_top"><B>NO FRAMES</B></A> &nbsp; &nbsp;<SCRIPT type="text/javascript"> <!-- if(window==top) { document.writeln('<A HREF="../../../../../allclasses-noframe.html"><B>All Classes</B></A>'); } //--> </SCRIPT> <NOSCRIPT> <A HREF="../../../../../allclasses-noframe.html"><B>All Classes</B></A> </NOSCRIPT> </FONT></TD> </TR> </TABLE> <A NAME="skip-navbar_bottom"></A> <!-- ======== END OF BOTTOM NAVBAR ======= --> <HR> </BODY> </HTML>
morelab/c4a_data_repository
LinkedDataInterface/src/ruleEngine/doc/javadoc/de/fuberlin/wiwiss/d2rq/sql/package-summary.html
HTML
gpl-3.0
9,852
<!-- START doctoc generated TOC please keep comment here to allow auto update --> <!-- DON'T EDIT THIS SECTION, INSTEAD RE-RUN doctoc TO UPDATE --> **Table of contents** - [*](#) - [Installation](#installation) - [Table of Contents](#table-of-contents) - [Usage](#usage) - [Related Tools](#related-tools) - [API](#api) - [`VFile()`](#vfile) - [`VFile#contents`](#vfilecontents) - [`VFile#directory`](#vfiledirectory) - [`VFile#filename`](#vfilefilename) - [`VFile#extension`](#vfileextension) - [`VFile#basename()`](#vfilebasename) - [`VFile#quiet`](#vfilequiet) - [`VFile#messages`](#vfilemessages) - [`VFile#history`](#vfilehistory) - [`VFile#toString()`](#vfiletostring) - [`VFile#filePath()`](#vfilefilepath) - [`VFile#move(options)`](#vfilemoveoptions) - [`VFile#namespace(key)`](#vfilenamespacekey) - [`VFile#message(reason[, position[, ruleId]])`](#vfilemessagereason-position-ruleid) - [`VFile#warn(reason[, position[, ruleId]])`](#vfilewarnreason-position-ruleid) - [`VFile#fail(reason[, position[, ruleId]])`](#vfilefailreason-position-ruleid) - [`VFile#hasFailed()`](#vfilehasfailed) - [`VFileMessage`](#vfilemessage) - [License](#license) <!-- END doctoc generated TOC please keep comment here to allow auto update --> # ![vfile](https://cdn.rawgit.com/wooorm/vfile/master/logo.svg) [![Build Status](https://img.shields.io/travis/wooorm/vfile.svg)](https://travis-ci.org/wooorm/vfile) [![Coverage Status](https://img.shields.io/codecov/c/github/wooorm/vfile.svg)](https://codecov.io/github/wooorm/vfile) **VFile** is a virtual file format used by [**retext**](https://github.com/wooorm/retext) (natural language) and [**remark**](https://github.com/wooorm/remark) (markdown). Two processors which parse, transform, and compile text. Both need a virtual representation of files and a place to store metadata and messages. And, they work in the browser. **VFile** provides these requirements. Also, **VFile** exposes a warning mechanism compatible with [**ESLint**](https://github.com/eslint/eslint)s formatters, making it easy to expose [stylish](https://github.com/eslint/eslint/blob/master/lib/formatters/stylish.js) warnings, or export [tap](https://github.com/eslint/eslint/blob/master/lib/formatters/tap.js) compliant messages. > **VFile** is different from (the excellent :+1:) [**vinyl**](https://github.com/wearefractal/vinyl) > in that it does not include file-system or node-only functionality. No > buffers, streams, or stats. In addition, the focus on > [metadata](#vfilenamespacekey) and [messages](#vfilemessagereason-position-ruleid) > are useful when processing a file through a > [middleware](https://github.com/segmentio/ware) pipeline. ## Installation [npm](https://docs.npmjs.com/cli/install): ```bash npm install vfile ``` **VFile** is also available for [duo](http://duojs.org/#getting-started), and as an AMD, CommonJS, and globals module, [uncompressed and compressed](https://github.com/wooorm/vfile/releases). ## Table of Contents * [Usage](#usage) * [Related Tools](#related-tools) * [API](#api) * [VFile()](#vfile-1) * [VFile#contents](#vfilecontents) * [VFile#directory](#vfiledirectory) * [VFile#filename](#vfilefilename) * [VFile#extension](#vfileextension) * [VFile#basename()](#vfilebasename) * [VFile#quiet](#vfilequiet) * [VFile#messages](#vfilemessages) * [VFile#history](#vfilehistory) * [VFile#toString()](#vfiletostring) * [VFile#filePath()](#vfilefilepath) * [VFile#move(options)](#vfilemoveoptions) * [VFile#namespace(key)](#vfilenamespacekey) * [VFile#message(reason\[, position\[, ruleId\]\])](#vfilemessagereason-position-ruleid) * [VFile#warn(reason\[, position\[, ruleId\]\])](#vfilewarnreason-position-ruleid) * [VFile#fail(reason\[, position\[, ruleId\]\])](#vfilefailreason-position-ruleid) * [VFile#hasFailed()](#vfilehasfailed) * [VFileMessage](#vfilemessage) * [License](#license) ## Usage ```js var VFile = require('vfile'); var file = new VFile({ 'directory': '~', 'filename': 'example', 'extension': 'txt', 'contents': 'Foo *bar* baz' }); file.toString(); // 'Foo *bar* baz' file.filePath(); // '~/example.txt' file.move({'extension': 'md'}); file.filePath(); // '~/example.md' file.warn('Something went wrong', {'line': 1, 'column': 3}); // { [~/example.md:1:3: Something went wrong] // name: '~/example.md:1:3', // file: '~/example.md', // reason: 'Something went wrong', // line: 1, // column: 3, // fatal: false } ``` ## Related Tools [**VFile**](#api)s are used by both [**retext**](https://github.com/wooorm/retext) and [**remark**](https://github.com/wooorm/remark). In addition, here’s a list of useful tools: * [`dustinspecker/convert-vinyl-to-vfile`](https://github.com/dustinspecker/convert-vinyl-to-vfile) — Convert a [Vinyl](https://github.com/wearefractal/vinyl) file to a VFile; * [`shinnn/is-vfile-message`](https://github.com/shinnn/is-vfile-message) — Check if a value is a `VFileMessage` object; * [`wooorm/to-vfile`](https://github.com/wooorm/to-vfile) — Create a virtual file from a file-path; * [`wooorm/vfile-find-down`](https://github.com/wooorm/vfile-find-down) — Find one or more files by searching the file system downwards; * [`wooorm/vfile-find-up`](https://github.com/wooorm/vfile-find-up) — Find one or more files by searching the file system upwards; * [`wooorm/vfile-location`](https://github.com/wooorm/vfile-location) — Convert between positions (line and column-based) and offsets (range-based) locations; * [`shinnn/vfile-messages-to-vscode-diagnostics`](https://github.com/shinnn/vfile-messages-to-vscode-diagnostics) — Convert `VFileMessage`s into an array of VS Code diagnostics; * [`wooorm/vfile-reporter`](https://github.com/wooorm/vfile-reporter) — Stylish reporter for virtual files. * [`wooorm/vfile-sort`](https://github.com/wooorm/vfile-sort) — Sort virtual file messages by line/column; ## API ### `VFile()` **VFile** objects make it easy to move files, to trigger warnings and errors, and to store supplementary metadata relating to files, all without accessing the file-system. **Example**: ```js var file = new VFile({ 'directory': '~', 'filename': 'example', 'extension': 'txt', 'contents': 'Foo *bar* baz' }); file === VFile(file); // true file === new VFile(file); // true VFile('foo') instanceof VFile; // true ``` **Signatures**: * `file = VFile(contents|options|vFile?)`. **Parameters**: * `contents` (`string`) — Contents of the file; * `vFile` (`VFile`) — Existing representation, returned without modification; * `options` (`Object`): * `directory` (`string?`, default: `''`) — Parent directory; * `filename` (`string?`, default: `''`) — Name, without extension; * `extension` (`string?`, default: `''`) — Extension(s), without initial dot; * `contents` (`string?`, default: `''`) — Raw value. **Returns**: `vFile` — Instance. **Notes**: `VFile` exposes an interface compatible with ESLint’s formatters. For example, to expose warnings using ESLint’s `compact` formatter, execute the following: ```javascript var compact = require('eslint/lib/formatters/compact'); var VFile = require('vfile'); var vFile = new VFile({ 'directory': '~', 'filename': 'hello', 'extension': 'txt' }); vFile.warn('Whoops, something happened!'); console.log(compact([vFile])); ``` Which would yield the following: ```text ~/hello.txt: line 0, col 0, Warning - Whoops, something happened! 1 problem ``` ### `VFile#contents` `string` — Content of file. ### `VFile#directory` `string` — Path to parent directory. ### `VFile#filename` `string` — Filename. A file-path can still be generated when no filename exists. ### `VFile#extension` `string` — Extension. A file-path can still be generated when no extension exists. ### `VFile#basename()` Get the filename, with extension, if applicable. **Example**: ```js var file = new VFile({ 'directory': '~', 'filename': 'example', 'extension': 'txt' }); file.basename() // example.txt ``` **Signatures**: * `string = vFile.basename()`. **Returns**: `string`— Returns the file path without a directory, if applicable. Otherwise,an empty string is returned. ### `VFile#quiet` `boolean?` — Whether an error created by [`VFile#fail()`](#vfilemessagereason-position-ruleid) is returned (when truthy) or thrown (when falsey). Ensure all `messages` associated with a file are handled properly when setting this to `true`. ### `VFile#messages` `Array.<VFileMessage>` — List of associated messages. **Notes**: `VFile#message()`, and in turn `VFile#warn()` and `VFile#fail()`, return `Error` objects that adhere to the [`VFileMessage`](#vfilemessage) schema. Its results can populate `messages`. ### `VFile#history` `Array.<String>` — List of file-paths the file [`move`](#vfilemoveoptions)d between. ### `VFile#toString()` Get the value of the file. **Example**: ```js var vFile = new VFile('Foo'); String(vFile); // 'Foo' ``` **Signatures**: * `string = vFile.toString()`. **Returns**: `string` — Contents. ### `VFile#filePath()` Get the filename, with extension and directory, if applicable. **Example**: ```js var file = new VFile({ 'directory': '~', 'filename': 'example', 'extension': 'txt' }); String(file.filePath); // ~/example.txt file.filePath() // ~/example.txt ``` **Signatures**: * `string = vFile.filePath()`. **Returns**: `string` — If the `vFile` has a `filename`, it will be prefixed with the directory (slashed), if applicable, and suffixed with the (dotted) extension (if applicable). Otherwise, an empty string is returned. ### `VFile#move(options)` Move a file by passing a new directory, filename, and extension. When these are not given, the default values are kept. **Example**: ```js var file = new VFile({ 'directory': '~', 'filename': 'example', 'extension': 'txt', 'contents': 'Foo *bar* baz' }); file.move({'directory': '/var/www'}); file.filePath(); // '/var/www/example.txt' file.move({'extension': 'md'}); file.filePath(); // '/var/www/example.md' ``` **Signatures**: * `vFile = vFile.move(options?)`. **Parameters**: * `options` (`Object`): * `directory` (`string`, default: `''`) — Parent directory; * `filename` (`string?`, default: `''`) — Name, without extension; * `extension` (`string`, default: `''`) — Extension(s), without initial dot. **Returns**: `vFile` — Context object (chainable). ### `VFile#namespace(key)` Access metadata. **Example**: ```js var file = new VFile('Foo'); file.namespace('foo').bar = 'baz'; console.log(file.namespace('foo').bar) // 'baz'; ``` **Parameters**: * `key` (`string`) — Namespace key. **Returns**: `Object` — Private namespace for metadata. ### `VFile#message(reason[, position[, ruleId]])` Create a message with `reason` at `position`. When an error is passed in as `reason`, copies the stack. This does not add a message to `messages`. **Example**: ```js var file = new VFile(); file.message('Something went wrong'); // { [1:1: Something went wrong] // name: '1:1', // file: '', // reason: 'Something went wrong', // line: null, // column: null } ``` **Signatures**: * `VFileMessage = vFile.message(err|reason, node|location|position?, ruleId?)`. **Parameters**: * `err` (`Error`) — Original error, whose stack and message are used; * `reason` (`string`) — Reason for message; * `node` (`Node`) — Syntax tree object; * `location` (`Object`) — Syntax tree location (found at `node.position`); * `position` (`Object`) — Syntax tree position (found at `node.position.start` or `node.position.end`). * `ruleId` (`string`) — Category of warning. **Returns**: [`VFileMessage`](#vfilemessage) — File-related message with location information. ### `VFile#warn(reason[, position[, ruleId]])` Warn. Creates a non-fatal message (see [`VFile#message()`](#vfilemessagereason-position-ruleid)), and adds it to the file's [`messages`](#vfilemessages) list. **Example**: ```js var file = new VFile(); file.warn('Something went wrong'); // { [1:1: Something went wrong] // name: '1:1', // file: '', // reason: 'Something went wrong', // line: null, // column: null, // fatal: false } ``` **See**: * [`VFile#message`](#vfilemessagereason-position-ruleid) ### `VFile#fail(reason[, position[, ruleId]])` Fail. Creates a fatal message (see `VFile#message()`), sets `fatal: true`, adds it to the file's `messages` list. If `quiet` is not `true`, throws the error. **Example**: ```js var file = new VFile(); file.fail('Something went wrong'); // 1:1: Something went wrong // at VFile.exception (vfile/index.js:296:11) // at VFile.fail (vfile/index.js:360:20) // at repl:1:6 file.quiet = true; file.fail('Something went wrong'); // { [1:1: Something went wrong] // name: '1:1', // file: '', // reason: 'Something went wrong', // line: null, // column: null, // fatal: true } ``` **See**: * [`VFile#message`](#vfilemessagereason-position-ruleid) ### `VFile#hasFailed()` Check if a fatal message occurred making the file no longer processable. **Example**: ```js var file = new VFile(); file.quiet = true; file.hasFailed(); // false file.fail('Something went wrong'); file.hasFailed(); // true ``` **Signatures**: * `boolean = vFile.hasFailed()`. **Returns**: `boolean` — `true` if at least one of file’s `messages` has a `fatal` property set to `true`. ### `VFileMessage` `Error` — File-related message with location information. **Properties**: * `name` (`string`) — (Starting) location of the message, preceded by its file-path when available, and joined by `':'`. Used by the native [`Error#toString()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error/name); * `file` (`string`) — File-path; * `reason` (`string`) — Reason for message; * `line` (`number?`) — Line of error, when available; * `column` (`number?`) — Column of error, when available; * `stack` (`string?`) — Stack of message, when available; * `fatal` (`boolean?`) — Whether the associated file is still processable. * `location` (`object`) — Full range information, when available. Has `start` and `end` properties, both set to an object with `line` and `column`, set to `number?`. ## License [MIT](LICENSE) © [Titus Wormer](http://wooorm.com)
hhkaos/awesome-arcgis
node_modules/vfile/readme.md
Markdown
gpl-3.0
14,782
/* * DO NOT EDIT. THIS FILE IS GENERATED FROM e:/builds/moz2_slave/rel-cen-xr-w32-bld/build/dom/interfaces/notification/nsIDOMDesktopNotification.idl */ #ifndef __gen_nsIDOMDesktopNotification_h__ #define __gen_nsIDOMDesktopNotification_h__ #ifndef __gen_domstubs_h__ #include "domstubs.h" #endif /* For IDL files that don't want to include root IDL files. */ #ifndef NS_NO_VTABLE #define NS_NO_VTABLE #endif class nsIDOMEventListener; /* forward declaration */ class nsIDOMDesktopNotification; /* forward declaration */ /* starting interface: nsIDOMDesktopNotificationCenter */ #define NS_IDOMDESKTOPNOTIFICATIONCENTER_IID_STR "ccea6185-0a3d-45ab-9058-1004dd4b8c50" #define NS_IDOMDESKTOPNOTIFICATIONCENTER_IID \ {0xccea6185, 0x0a3d, 0x45ab, \ { 0x90, 0x58, 0x10, 0x04, 0xdd, 0x4b, 0x8c, 0x50 }} class NS_NO_VTABLE NS_SCRIPTABLE nsIDOMDesktopNotificationCenter : public nsISupports { public: NS_DECLARE_STATIC_IID_ACCESSOR(NS_IDOMDESKTOPNOTIFICATIONCENTER_IID) /* nsIDOMDesktopNotification createNotification (in DOMString title, in DOMString description, [optional] in DOMString iconURL); */ NS_SCRIPTABLE NS_IMETHOD CreateNotification(const nsAString & title, const nsAString & description, const nsAString & iconURL, nsIDOMDesktopNotification **_retval NS_OUTPARAM) = 0; }; NS_DEFINE_STATIC_IID_ACCESSOR(nsIDOMDesktopNotificationCenter, NS_IDOMDESKTOPNOTIFICATIONCENTER_IID) /* Use this macro when declaring classes that implement this interface. */ #define NS_DECL_NSIDOMDESKTOPNOTIFICATIONCENTER \ NS_SCRIPTABLE NS_IMETHOD CreateNotification(const nsAString & title, const nsAString & description, const nsAString & iconURL, nsIDOMDesktopNotification **_retval NS_OUTPARAM); /* Use this macro to declare functions that forward the behavior of this interface to another object. */ #define NS_FORWARD_NSIDOMDESKTOPNOTIFICATIONCENTER(_to) \ NS_SCRIPTABLE NS_IMETHOD CreateNotification(const nsAString & title, const nsAString & description, const nsAString & iconURL, nsIDOMDesktopNotification **_retval NS_OUTPARAM) { return _to CreateNotification(title, description, iconURL, _retval); } /* Use this macro to declare functions that forward the behavior of this interface to another object in a safe way. */ #define NS_FORWARD_SAFE_NSIDOMDESKTOPNOTIFICATIONCENTER(_to) \ NS_SCRIPTABLE NS_IMETHOD CreateNotification(const nsAString & title, const nsAString & description, const nsAString & iconURL, nsIDOMDesktopNotification **_retval NS_OUTPARAM) { return !_to ? NS_ERROR_NULL_POINTER : _to->CreateNotification(title, description, iconURL, _retval); } #if 0 /* Use the code below as a template for the implementation class for this interface. */ /* Header file */ class nsDOMDesktopNotificationCenter : public nsIDOMDesktopNotificationCenter { public: NS_DECL_ISUPPORTS NS_DECL_NSIDOMDESKTOPNOTIFICATIONCENTER nsDOMDesktopNotificationCenter(); private: ~nsDOMDesktopNotificationCenter(); protected: /* additional members */ }; /* Implementation file */ NS_IMPL_ISUPPORTS1(nsDOMDesktopNotificationCenter, nsIDOMDesktopNotificationCenter) nsDOMDesktopNotificationCenter::nsDOMDesktopNotificationCenter() { /* member initializers and constructor code */ } nsDOMDesktopNotificationCenter::~nsDOMDesktopNotificationCenter() { /* destructor code */ } /* nsIDOMDesktopNotification createNotification (in DOMString title, in DOMString description, [optional] in DOMString iconURL); */ NS_IMETHODIMP nsDOMDesktopNotificationCenter::CreateNotification(const nsAString & title, const nsAString & description, const nsAString & iconURL, nsIDOMDesktopNotification **_retval NS_OUTPARAM) { return NS_ERROR_NOT_IMPLEMENTED; } /* End of implementation class template. */ #endif /* starting interface: nsIDOMDesktopNotification */ #define NS_IDOMDESKTOPNOTIFICATION_IID_STR "9131fd07-a7db-4b3a-a98b-6d9f3746682f" #define NS_IDOMDESKTOPNOTIFICATION_IID \ {0x9131fd07, 0xa7db, 0x4b3a, \ { 0xa9, 0x8b, 0x6d, 0x9f, 0x37, 0x46, 0x68, 0x2f }} class NS_NO_VTABLE NS_SCRIPTABLE nsIDOMDesktopNotification : public nsISupports { public: NS_DECLARE_STATIC_IID_ACCESSOR(NS_IDOMDESKTOPNOTIFICATION_IID) /* void show (); */ NS_SCRIPTABLE NS_IMETHOD Show(void) = 0; /* attribute nsIDOMEventListener onclick; */ NS_SCRIPTABLE NS_IMETHOD GetOnclick(nsIDOMEventListener **aOnclick) = 0; NS_SCRIPTABLE NS_IMETHOD SetOnclick(nsIDOMEventListener *aOnclick) = 0; /* attribute nsIDOMEventListener onclose; */ NS_SCRIPTABLE NS_IMETHOD GetOnclose(nsIDOMEventListener **aOnclose) = 0; NS_SCRIPTABLE NS_IMETHOD SetOnclose(nsIDOMEventListener *aOnclose) = 0; }; NS_DEFINE_STATIC_IID_ACCESSOR(nsIDOMDesktopNotification, NS_IDOMDESKTOPNOTIFICATION_IID) /* Use this macro when declaring classes that implement this interface. */ #define NS_DECL_NSIDOMDESKTOPNOTIFICATION \ NS_SCRIPTABLE NS_IMETHOD Show(void); \ NS_SCRIPTABLE NS_IMETHOD GetOnclick(nsIDOMEventListener **aOnclick); \ NS_SCRIPTABLE NS_IMETHOD SetOnclick(nsIDOMEventListener *aOnclick); \ NS_SCRIPTABLE NS_IMETHOD GetOnclose(nsIDOMEventListener **aOnclose); \ NS_SCRIPTABLE NS_IMETHOD SetOnclose(nsIDOMEventListener *aOnclose); /* Use this macro to declare functions that forward the behavior of this interface to another object. */ #define NS_FORWARD_NSIDOMDESKTOPNOTIFICATION(_to) \ NS_SCRIPTABLE NS_IMETHOD Show(void) { return _to Show(); } \ NS_SCRIPTABLE NS_IMETHOD GetOnclick(nsIDOMEventListener **aOnclick) { return _to GetOnclick(aOnclick); } \ NS_SCRIPTABLE NS_IMETHOD SetOnclick(nsIDOMEventListener *aOnclick) { return _to SetOnclick(aOnclick); } \ NS_SCRIPTABLE NS_IMETHOD GetOnclose(nsIDOMEventListener **aOnclose) { return _to GetOnclose(aOnclose); } \ NS_SCRIPTABLE NS_IMETHOD SetOnclose(nsIDOMEventListener *aOnclose) { return _to SetOnclose(aOnclose); } /* Use this macro to declare functions that forward the behavior of this interface to another object in a safe way. */ #define NS_FORWARD_SAFE_NSIDOMDESKTOPNOTIFICATION(_to) \ NS_SCRIPTABLE NS_IMETHOD Show(void) { return !_to ? NS_ERROR_NULL_POINTER : _to->Show(); } \ NS_SCRIPTABLE NS_IMETHOD GetOnclick(nsIDOMEventListener **aOnclick) { return !_to ? NS_ERROR_NULL_POINTER : _to->GetOnclick(aOnclick); } \ NS_SCRIPTABLE NS_IMETHOD SetOnclick(nsIDOMEventListener *aOnclick) { return !_to ? NS_ERROR_NULL_POINTER : _to->SetOnclick(aOnclick); } \ NS_SCRIPTABLE NS_IMETHOD GetOnclose(nsIDOMEventListener **aOnclose) { return !_to ? NS_ERROR_NULL_POINTER : _to->GetOnclose(aOnclose); } \ NS_SCRIPTABLE NS_IMETHOD SetOnclose(nsIDOMEventListener *aOnclose) { return !_to ? NS_ERROR_NULL_POINTER : _to->SetOnclose(aOnclose); } #if 0 /* Use the code below as a template for the implementation class for this interface. */ /* Header file */ class nsDOMDesktopNotification : public nsIDOMDesktopNotification { public: NS_DECL_ISUPPORTS NS_DECL_NSIDOMDESKTOPNOTIFICATION nsDOMDesktopNotification(); private: ~nsDOMDesktopNotification(); protected: /* additional members */ }; /* Implementation file */ NS_IMPL_ISUPPORTS1(nsDOMDesktopNotification, nsIDOMDesktopNotification) nsDOMDesktopNotification::nsDOMDesktopNotification() { /* member initializers and constructor code */ } nsDOMDesktopNotification::~nsDOMDesktopNotification() { /* destructor code */ } /* void show (); */ NS_IMETHODIMP nsDOMDesktopNotification::Show() { return NS_ERROR_NOT_IMPLEMENTED; } /* attribute nsIDOMEventListener onclick; */ NS_IMETHODIMP nsDOMDesktopNotification::GetOnclick(nsIDOMEventListener **aOnclick) { return NS_ERROR_NOT_IMPLEMENTED; } NS_IMETHODIMP nsDOMDesktopNotification::SetOnclick(nsIDOMEventListener *aOnclick) { return NS_ERROR_NOT_IMPLEMENTED; } /* attribute nsIDOMEventListener onclose; */ NS_IMETHODIMP nsDOMDesktopNotification::GetOnclose(nsIDOMEventListener **aOnclose) { return NS_ERROR_NOT_IMPLEMENTED; } NS_IMETHODIMP nsDOMDesktopNotification::SetOnclose(nsIDOMEventListener *aOnclose) { return NS_ERROR_NOT_IMPLEMENTED; } /* End of implementation class template. */ #endif #endif /* __gen_nsIDOMDesktopNotification_h__ */
DragonZX/fdm
Gecko.SDK/2.0/include/nsIDOMDesktopNotification.h
C
gpl-3.0
8,318
package org.andengine.util.adt.list; /** * (c) Zynga 2012 * * @author Nicolas Gramlich <[email protected]> * @since 11:14:45 - 27.01.2012 */ public interface IFloatList { // =========================================================== // Constants // =========================================================== // =========================================================== // Methods // =========================================================== public boolean isEmpty(); public float get(final int pIndex) throws ArrayIndexOutOfBoundsException; public void add(final float pItem); public void add(final int pIndex, final float pItem) throws ArrayIndexOutOfBoundsException; public float remove(final int pIndex) throws ArrayIndexOutOfBoundsException; public int size(); public void clear(); public float[] toArray(); }
erseco/ugr_programacion_ludica
andEngine/src/main/java/org/andengine/util/adt/list/IFloatList.java
Java
gpl-3.0
868
#!/usr/bin/python # -*- coding: utf-8 -*- import numpy as np import matplotlib.pyplot as plt import random class RidgeRegressor(object): """ Linear Least Squares Regression with Tikhonov regularization. More simply called Ridge Regression. We wish to fit our model so both the least squares residuals and L2 norm of the parameters are minimized. argmin Theta ||X*Theta - y||^2 + alpha * ||Theta||^2 A closed form solution is available. Theta = (X'X + G'G)^-1 X'y Where X contains the independent variables, y the dependent variable and G is matrix alpha * I, where alpha is called the regularization parameter. When alpha=0 the regression is equivalent to ordinary least squares. http://en.wikipedia.org/wiki/Linear_least_squares_(mathematics) http://en.wikipedia.org/wiki/Tikhonov_regularization http://en.wikipedia.org/wiki/Ordinary_least_squares """ def fit(self, X, y, alpha=0): """ Fits our model to our training data. Arguments ---------- X: mxn matrix of m examples with n independent variables y: dependent variable vector for m examples alpha: regularization parameter. A value of 0 will model using the ordinary least squares regression. """ print "in fit" X = np.hstack((np.ones((X.shape[0], 1)), X)) G = alpha * np.eye(X.shape[1]) G[0, 0] = 0 # Don't regularize bias self.params = np.dot(np.linalg.inv(np.dot(X.T, X) + np.dot(G.T, G)), np.dot(X.T, y)) print self.params def predict(self, X): """ Predicts the dependent variable of new data using the model. The assumption here is that the new data is iid to the training data. Arguments ---------- X: mxn matrix of m examples with n independent variables alpha: regularization parameter. Default of 0. Returns ---------- Dependent variable vector for m examples """ X = np.hstack((np.ones((X.shape[0], 1)), X)) return np.dot(X, self.params) ##if __name__ == '__main__': ## # Create synthetic data ## X = np.linspace(0, 6, 100) ## y=np.random.normal(size=len(X))/random.randint(1,1000) ## #yhat = y + .5 * np.random.normal(size=len(X)) ## ## # Plot synthetic data ## plt.plot(X, y, 'g') ## #plt.plot(X, yhat, 'rx', label='noisy samples') ## ## # Create feature matrix ## tX = np.array([X]).T ## print tX,X ## #tX = np.hstack((tX, np.power(tX, 2), np.power(tX, 3))) ## #print tX ## ## # Plot regressors ## r = RidgeRegressor() ## r.fit(tX, y) ## #plt.plot(X, r.predict(tX), 'b', label=u'ŷ (alpha=0.0)') ## alpha = 3.0 ## r.fit(tX, y, alpha) ## plt.plot(X, r.predict(tX), 'y', label=u'ŷ (alpha=%.1f)' % alpha) ## ## plt.legend() ## plt.show()
mlskit/astromlskit
REGRESSION/ridge.py
Python
gpl-3.0
2,914
<?php /** * Nooku Platform - http://www.nooku.org/platform * * @copyright Copyright (C) 2007 - 2014 Johan Janssens and Timble CVBA. (http://www.timble.net) * @license GNU GPLv3 <http://www.gnu.org/licenses/gpl.html> * @link https://github.com/nooku/nooku-platform for the canonical source repository */ namespace Nooku\Library; /** * Session Container Interface * * @author Johan Janssens <http://github.com/johanjanssens> * @package Nooku\Library\User */ interface UserSessionContainerInterface { /** * Get a an attribute * * @param string $identifier Attribute identifier, eg .foo.bar * @param mixed $default Default value when the attribute doesn't exist * @return mixed The value */ public function get($identifier, $default = null); /** * Set an attribute * * @param mixed $identifier Attribute identifier, eg foo.bar * @param mixed $value Attribute value * @return UserSessionContainerInterface */ public function set($identifier, $value); /** * Check if an attribute exists * * @param string $identifier Attribute identifier, eg foo.bar * @return boolean */ public function has($identifier); /** * Removes an attribute * * @param string $identifier Attribute identifier, eg foo.bar * @return UserSessionContainerInterface */ public function remove($identifier); /** * Clears out all attributes * * @return UserSessionContainerInterface */ public function clear(); /** * Adds new attributes * * @param array $attributes An array of attributes * @return UserSessionContainerInterface */ public function add(array $attributes); /** * Load the attributes by reference * * After starting a session, PHP retrieves the session data through the session handler and populates $_SESSION * with the result automatically. This function can load the attributes from the $_SESSION global by reference * by passing the $_SESSION to this function. * * @param array|null $session The session attributes to load * @return UserSessionContainerInterface */ public function load(array &$session); /** * Set the session attributes namespace * * @param string $namespace The session attributes namespace * @return UserSessionContainerAbstract */ public function setNamespace($namespace); /** * Get the session attributes namespace * * @return string The session attributes namespace */ public function getNamespace(); /** * Get the session attributes separator * * @return string The session attribute separator */ public function getSeparator(); /** * Get all attributes * * @return array An array of attributes */ public function toArray(); }
babsgosgens/nooku-ember-example-theme
library/user/session/container/interface.php
PHP
gpl-3.0
2,965
#!/usr/bin/python # # dust-cleaner.py - p2pool dust cleaner # groups small 'dust' transactions with zero or minimal fee # COIN_NAME = "monetaryunit" COIN_CODE = "MUE" COIN_RPC_PORT = "29947" FREE_BLOCK_SIZE = 29000 FREE_PRIORITY_THRESHOLD = 10.81 FEE_PER_BLOCK = 0.1 #intentionally set high, pending investigation MAX_STANDARD_TX_SIZE = 350000 from operator import itemgetter import argparse import json import os.path import requests import sys def get_rpc_connection_url(args): if not args.rpc_url: args.rpc_url = "localhost:" + COIN_RPC_PORT if (not args.rpc_user) or (not args.rpc_password): args.rpc_user = None args.rpc_password = None file_data = {} file = open(os.path.join(os.path.expanduser("~"), "." + COIN_NAME, COIN_NAME + ".conf"), "r") for line in file: data = line.split("=") file_data[data[0].strip()] = data[1].strip() file.close() if file_data["rpcuser"]: args.rpc_user = file_data["rpcuser"] if file_data["rpcpassword"]: args.rpc_password = file_data["rpcpassword"] if args.https: url_prefix = "https://" else: url_prefix = "http://" return url_prefix + args.rpc_user + ":" + args.rpc_password + "@" + args.rpc_url def get_cheap_tx(ctx, ignore_list, max_fee = 0): accepted_tx = [] rejected_tx = [] work_ctx = [] for i in range(len(ctx)): tx = ctx[i] if tx["address"] not in ignore_list: tx["priority"] = tx["amount"] * tx["confirmations"] work_ctx.append(tx) work_ctx = sorted(work_ctx, key=itemgetter("priority")) tx_size_bytes = 10 + 34 tx_amount = 0 tx_weight = 0 tx_fee = 0 while work_ctx: tx = work_ctx.pop() next_tx_size_bytes = tx_size_bytes + 150 next_tx_amount = tx_amount + tx["amount"] next_weight = tx_weight + tx["priority"] if (next_tx_size_bytes < FREE_BLOCK_SIZE): next_fee = 0 elif (next_weight / next_tx_size_bytes > FREE_PRIORITY_THRESHOLD): next_fee = int(next_tx_size_bytes / FREE_BLOCK_SIZE) * FEE_PER_BLOCK + FEE_PER_BLOCK if (next_fee > max_fee) or (next_tx_size_bytes > MAX_STANDARD_TX_SIZE): rejected_tx.append(tx) else: accepted_tx.append(tx) tx_fee = next_fee tx_size_bytes = next_tx_size_bytes tx_amount = next_tx_amount tx_weight = next_weight return {"accepted_tx": accepted_tx, "tx_fee": tx_fee, "tx_amount": tx_amount, "tx_size_bytes": tx_size_bytes, "rejected_tx": rejected_tx} def create_json_tx(tx_list, pay_to, tx_amount, fee): work_tx_list = list(tx_list) tx_out_list = [] while work_tx_list: tx = work_tx_list.pop() tx_out_list.append({"txid": tx["txid"], "vout": tx["vout"]}) return [tx_out_list, {pay_to: tx_amount - fee}] if __name__ == "__main__": parser = argparse.ArgumentParser(description = "Joins 'dust' received payments into a manageable new bigger payment to the given address, with minimal transaction fee.") parser.add_argument("address", help = "The MUE address to send the aggregated payments.") parser.add_argument("-f", "--max_fee", help = "The maximum transaction fee allowed. Creates transaction with no fees if omitted.", type = float) parser.add_argument("-i", "--ignore", help = "Address not to be included in the new transaction. \"address\" is always ignored. Can be called multiple times for more than one address.", action = "append") parser.add_argument("-o", "--rpc_url", help = "The wallet RPC URL. Default: localhost:" + COIN_RPC_PORT + ".") parser.add_argument("-u", "--rpc_user", help = "The RPC username. Reads from local config file if either -u or -p are omitted.") parser.add_argument("-p", "--rpc_password", help = "The RPC password. Reads from local config file if either -u or -p are omitted.") parser.add_argument("-s", "--https", help = "Use HTTPS instead of HTTP for the RPC calls.", action = "store_true") parser.add_argument("-g", "--go", help = "Attempts to send transaction to the network. Runs in test mode if omitted.", action = "store_true") args = parser.parse_args() if not args.max_fee: args.max_fee = 0 if args.ignore: args.ignore.append(args.address) else: args.ignore = [args.address] url = get_rpc_connection_url(args) headers = {"content-type": "application/json"} payload = { "method": "listunspent", "params": [], "jsonrpc": "2.0", "id": 0, } try: response = requests.post(url, data = json.dumps(payload), headers = headers).json() except: sys.exit("Failed to retrieve the list of transactions from the wallet. Execution aborted.") best_match = get_cheap_tx(response["result"], args.ignore, args.max_fee) print print "Dust cleaning:" print "- Number of transactions:", len(best_match["accepted_tx"]) print "- Transaction fee:", best_match["tx_fee"], COIN_CODE print "- Dust to collect:", best_match["tx_amount"] - best_match["tx_fee"], COIN_CODE print if not args.go: print "Test mode. Run with --go to actually collect the dust payments." print "Execution aborted." else: try: print "Preparing transaction." tz = create_json_tx(best_match["accepted_tx"], args.address, best_match["tx_amount"], best_match["tx_fee"], ) payload = { "method": "validateaddress", "params": [args.address], "jsonrpc": "2.0", "id": 0, } response = requests.post(url, data = json.dumps(payload), headers = headers).json() if response["result"]["isvalid"] == "False": print "Invalid " + COIN_NAME + " address." exit() payload = { "method": "createrawtransaction", "params": tz, "jsonrpc": "2.0", "id": 0, } response = requests.post(url, data = json.dumps(payload), headers = headers).json() payload = { "method": "signrawtransaction", "params": [response["result"]], "jsonrpc": "2.0", "id": 0, } response = requests.post(url, data = json.dumps(payload), headers = headers).json() payload = { "method": "sendrawtransaction", "params": [response["result"]["hex"]], "jsonrpc": "2.0", "id": 0, } response = requests.post(url, data = json.dumps(payload), headers = headers).json() print "Dust collected." except: sys.exit("Failed to connect to the wallet and send the transaction. Execution aborted.") # ~
bankonme/dust-cleaner
dust-cleaner.py
Python
gpl-3.0
6,965
/* Copyright 2005 Brian McCallister * * 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.skife.csv; import java.io.IOException; /** * Interface for systems that really like interfaces * * @see SimpleWriter */ public interface CSVWriter { /** * Write a row to the CSV file */ void append(Object[] fields) throws IOException; /** * Specify the character to use to seperate fields, defaults to a comma */ void setSeperator(char seperator); /** * Flush after each line? Default is false */ void setAutoFlush(boolean autoFlush); /** * Defaults to the system dependent newline */ void setNewLine(char c); /** * Defaults to the system dependent newline */ void setNewLine(char[] c); /** * Defaults to the system dependent newline */ void setNewLine(String newline); /** * Append a string as a raw line, without any processing * <p> * Useful for comments, etc */ void rawLine(String line) throws IOException; }
technicalguru/csv
src/test/java/org/skife/csv/CSVWriter.java
Java
gpl-3.0
1,572
----------------------------------------- -- Spell: Curaga III -- Restores HP of all party members within area of effect. ----------------------------------------- require("scripts/globals/settings"); require("scripts/globals/status"); require("scripts/globals/magic"); ----------------------------------------- -- OnSpellCast ----------------------------------------- function OnMagicCastingCheck(caster,target,spell) return 0; end; function onSpellCast(caster,target,spell) local minCure = 270; local divisor = 0.6666; local constant = 165; local power = getCurePowerOld(caster); if(power > 460) then divisor = 6.5; constant = 354.6666; elseif(power > 220) then divisor = 2; constant = 275; end local final = getCureFinal(caster,spell,getBaseCureOld(power,divisor,constant),minCure,false); final = final + (final * (target:getMod(MOD_CURE_POTENCY_RCVD)/100)); --Applying server mods.... final = final * CURE_POWER; local diff = (target:getMaxHP() - target:getHP()); if(final > diff) then final = diff; end target:addHP(final); target:wakeUp(); caster:updateEnmityFromCure(target,final); return final; end;
ffxinfinity/ffxinfinity
FFXI Server-Development/Build Files/scripts/globals/spells/curaga_iii.lua
Lua
gpl-3.0
1,148
package nu.nethome.home.items.fineoffset; import org.apache.commons.lang3.Validate; /** * */ public class CounterHistory { long history[]; int nextValuePosition = 0; long totalValues; public CounterHistory(int size) { history = new long[size]; } public void addValue(long value) { history[nextValuePosition] = value; nextValuePosition = (nextValuePosition + 1) % history.length; totalValues++; } public long differenceSince(long value, int timeSince) { Validate.inclusiveBetween(0, history.length, timeSince, "Time Since value not valid"); long counterValueToCompareWith; if (totalValues == 0 || timeSince == 0) { counterValueToCompareWith = value; } else if (totalValues <= timeSince) { counterValueToCompareWith = history[0]; } else { counterValueToCompareWith = getValueTimeAgo(timeSince); } return value - counterValueToCompareWith; } private long getValueTimeAgo(int timeSince) { return history[(nextValuePosition + history.length - timeSince) % history.length]; } public String getHistoryAsString() { StringBuilder result = new StringBuilder(); String divider = ""; for (long i = Math.min(history.length, totalValues); i > 0; i-- ) { result.append(divider); result.append(getValueTimeAgo((int)i)); divider = ","; } return result.toString(); } public void setHistoryFromString(String historyString) { String parts[] = historyString.split(","); for (String value : parts) { addValue(Long.parseLong(value)); } } }
NetHome/NetHomeServer
home-items/rf-items/src/main/java/nu/nethome/home/items/fineoffset/CounterHistory.java
Java
gpl-3.0
1,744
#ifndef MANTID_GEOMETRY_PEAKSHAPE_H_ #define MANTID_GEOMETRY_PEAKSHAPE_H_ #include "MantidKernel/SpecialCoordinateSystem.h" #include "MantidKernel/System.h" #include <boost/optional.hpp> #include <boost/shared_ptr.hpp> #include <string> namespace Mantid { namespace Geometry { /** PeakShape : Abstract type to describes the shape of a peak. Copyright &copy; 2015 ISIS Rutherford Appleton Laboratory, NScD Oak Ridge National Laboratory & European Spallation Source This file is part of Mantid. Mantid 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. Mantid 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/>. File change history is stored at: <https://github.com/mantidproject/mantid> Code Documentation is available at: <http://doxygen.mantidproject.org> */ class DLLExport PeakShape { public: /// Coordinte frame used upon creation virtual Mantid::Kernel::SpecialCoordinateSystem frame() const = 0; /// Serialize virtual std::string toJSON() const = 0; /// Deep copy this virtual PeakShape *clone() const = 0; /// Algorithm virtual std::string algorithmName() const = 0; /// Algorithm Version virtual int algorithmVersion() const = 0; /// Shape name virtual std::string shapeName() const = 0; /// For selecting different radius types. enum RadiusType { Radius = 0, OuterRadius = 1, InnerRadius = 2 }; /// Radius virtual boost::optional<double> radius(RadiusType type) const = 0; /// Destructor virtual ~PeakShape() = default; }; typedef boost::shared_ptr<PeakShape> PeakShape_sptr; typedef boost::shared_ptr<const PeakShape> PeakShape_const_sptr; } // namespace Geometry } // namespace Mantid #endif /* MANTID_GEOMETRY_PEAKSHAPE_H_ */
wdzhou/mantid
Framework/Geometry/inc/MantidGeometry/Crystal/PeakShape.h
C
gpl-3.0
2,197
// Copyright Aleksey Gurtovoy 2002-2004 // // Distributed under the Boost Software License, Version 1.0. // (See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) // // See http://www.boost.org/libs/mpl for documentation. // $Id: bitxor.cpp 49268 2008-10-11 06:26:17Z agurtovoy $ // $Date: 2008-10-10 23:26:17 -0700 (Fri, 10 Oct 2008) $ // $Revision: 49268 $ #define BOOST_MPL_PREPROCESSING_MODE #include <boost/config.hpp> #include <boost/mpl/bitxor.hpp>
cppisfun/GameEngine
foreign/boost/libs/mpl/preprocessed/src/bitxor.cpp
C++
gpl-3.0
513
/* * Simpatico - Simulation Package for Polymeric and Molecular Liquids * * Copyright 2010 - 2017, The Regents of the University of Minnesota * Distributed under the terms of the GNU General Public License. */ #include "ComMSD.h" #include <mcMd/simulation/System.h> // base class template parameter #include <mcMd/simulation/Simulation.h> #include <mcMd/chemistry/Molecule.h> #include <mcMd/chemistry/Atom.h> #include <simp/boundary/Boundary.h> #include <simp/species/Species.h> // forward declaration in header #include <util/space/Dimension.h> #include <util/archives/Serializable_includes.h> #include <util/global.h> namespace McMd { using namespace Util; using namespace Simp; /* * Constructor. */ ComMSD::ComMSD(System& system) : SystemAnalyzer<System>(system), outputFile_(), accumulator_(), truePositions_(), oldPositions_(), shifts_(), speciesId_(-1), nMolecule_(-1), nAtom_(-1), capacity_(-1), isInitialized_(false) { setClassName("ComMSD"); } /* * Read parameters from file, and allocate data array. */ void ComMSD::readParameters(std::istream& in) { // Read interval and parameters for AutoCorrArray readInterval(in); readOutputFileName(in); read<int>(in, "speciesId", speciesId_); read<int>(in, "capacity", capacity_); // Validate parameters if (speciesId_ < 0) UTIL_THROW("Negative speciesId"); if (speciesId_ >= system().simulation().nSpecies()) UTIL_THROW("speciesId > nSpecies"); if (capacity_ <= 0) UTIL_THROW("Negative capacity"); // Maximum possible number of molecules of this species int speciesCapacity; speciesCapacity = system().simulation().species(speciesId_).capacity(); // Allocate local arrays truePositions_.allocate(speciesCapacity); oldPositions_.allocate(speciesCapacity); shifts_.allocate(speciesCapacity); // Allocate memory for the AutoCorrArray accumulator accumulator_.setParam(speciesCapacity, capacity_); // Get number of atoms per molecule. nAtom_ = system().simulation().species(speciesId_).nAtom(); isInitialized_ = true; } /* * Load state from an archive. */ void ComMSD::loadParameters(Serializable::IArchive& ar) { Analyzer::loadParameters(ar); loadParameter<int>(ar, "speciesId", speciesId_); loadParameter<int>(ar, "capacity", capacity_); ar & nAtom_; // Validate parameters if (speciesId_ < 0) { UTIL_THROW("Negative speciesId"); } if (speciesId_ >= system().simulation().nSpecies()) { UTIL_THROW("speciesId > nSpecies"); } if (capacity_ <= 0) { UTIL_THROW("Negative capacity"); } if (nAtom_ != system().simulation().species(speciesId_).nAtom()) { UTIL_THROW("Inconsistent values for nAtom"); } // Maximum possible number of molecules of this species int speciesCapacity; speciesCapacity = system().simulation().species(speciesId_).capacity(); // Allocate memory truePositions_.allocate(speciesCapacity); oldPositions_.allocate(speciesCapacity); shifts_.allocate(speciesCapacity); accumulator_.setParam(speciesCapacity, capacity_); // Finish reading internal state ar & accumulator_; ar & truePositions_; ar & oldPositions_; ar & shifts_; ar & nMolecule_; } /* * Save state to archive. */ void ComMSD::save(Serializable::OArchive& ar) { ar & *this; } /* * Set number of molecules and initialize state. */ void ComMSD::setup() { // Precondition: Confirm that readParam was called if (!isInitialized_) UTIL_THROW("Analyzer not initialized"); // Get number of molecules of this species in this System. nMolecule_ = system().nMolecule(speciesId_); if (nMolecule_ <= 0) UTIL_THROW("nMolecule_ <= 0"); accumulator_.setNEnsemble(nMolecule_); accumulator_.clear(); // Store initial positions, and set initial shift vectors. Vector r; for (int i = 0; i < nMolecule_; ++i) { r = system().molecule(speciesId_, i).atom(0).position(); system().boundary().shift(r); oldPositions_[i] = r; shifts_[i] = IntVector(0); } } /* * Evaluate end-to-end vectors of all chains, add to ensemble. */ void ComMSD::sample(long iStep) { if (!isAtInterval(iStep)) return; // Confirm that nMolecule has remained constant, and nMolecule > 0. if (nMolecule_ <= 0) { UTIL_THROW("nMolecule <= 0"); } if (nMolecule_ != system().nMolecule(speciesId_)) { UTIL_THROW("Number of molecules has changed."); } Vector r; IntVector shift; Vector lengths = system().boundary().lengths(); int i, j; for (i = 0; i < nMolecule_; ++i) { r = system().molecule(speciesId_, i).atom(0).position(); system().boundary().shift(r); // Compare current r to previous position, oldPositions_[i] system().boundary().distanceSq(r, oldPositions_[i], shift); // If atom 0 crossed a boundary, increment its shift vector shifts_[i] += shift; // Store current position in box for comparison to next one oldPositions_[i] = r; // Add the other particle's positions to C.O.M. moleculeCom(i, r); // Reconstruct true position for (j = 0; j < Dimension; ++j) { truePositions_[i][j] = r[j] + double(shifts_[i][j])*lengths[j]; } } accumulator_.sample(truePositions_); } /* * Output results to file after simulation is completed. */ void ComMSD::output() { // Echo parameter to analyzer log file fileMaster().openOutputFile(outputFileName(".prm"), outputFile_); writeParam(outputFile_); outputFile_ << std::endl; outputFile_ << std::endl; outputFile_ << "nMolecule " << accumulator_.nEnsemble() << std::endl; outputFile_ << "bufferCapacity " << accumulator_.bufferCapacity() << std::endl; outputFile_ << "nSample " << accumulator_.nSample() << std::endl; outputFile_ << std::endl; outputFile_ << "Format of *.dat file:" << std::endl; outputFile_ << "[i] [MSD]" << std::endl; outputFile_.close(); // Output statistical analysis to separate data file fileMaster().openOutputFile(outputFileName(".dat"), outputFile_); accumulator_.output(outputFile_); outputFile_.close(); } /* * Evaluate center of mass of a single molecule, given a starting vector R0. */ void ComMSD::moleculeCom(int iMol, Vector &R0) { Vector R = R0, r1, r2, dr; // Assuming a linear chain (including Ring molecules). for (int i = 1; i < nAtom_-1; ++i) { r1 = system().molecule(speciesId_, iMol).atom(i-1).position(); r2 = system().molecule(speciesId_, iMol).atom(i).position(); system().boundary().distanceSq(r2, r1, dr); R += dr; R0 += R; } // Do the average. R0 /= double(nAtom_); } }
dmorse/simpatico
src/mcMd/analyzers/system/ComMSD.cpp
C++
gpl-3.0
7,373
<?php /* Gibbon, Flexible & Open School System Copyright (C) 2010, Ross Parker This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ use Gibbon\Comms\NotificationSender; use Gibbon\Domain\System\SettingGateway; use Gibbon\Data\Validator; require_once '../../gibbon.php'; $_POST = $container->get(Validator::class)->sanitize($_POST); //Module includes include './moduleFunctions.php'; $gibbonFinanceBudgetCycleID = $_POST['gibbonFinanceBudgetCycleID'] ?? ''; $gibbonFinanceBudgetID = $_POST['gibbonFinanceBudgetID'] ?? ''; $gibbonFinanceExpenseID = $_POST['gibbonFinanceExpenseID'] ?? ''; $status2 = $_POST['status2'] ?? ''; $gibbonFinanceBudgetID2 = $_POST['gibbonFinanceBudgetID2'] ?? ''; if ($gibbonFinanceBudgetCycleID == '' or $gibbonFinanceBudgetID == '') { echo 'Fatal error loading this page!'; } else { $URL = $session->get('absoluteURL').'/index.php?q=/modules/'.getModuleName($_POST['address'])."/expenses_manage_approve.php&gibbonFinanceBudgetCycleID=$gibbonFinanceBudgetCycleID&gibbonFinanceBudgetID2=$gibbonFinanceBudgetID2&status2=$status2"; $URLApprove = $session->get('absoluteURL').'/index.php?q=/modules/'.getModuleName($_POST['address'])."/expenses_manage.php&gibbonFinanceBudgetCycleID=$gibbonFinanceBudgetCycleID&gibbonFinanceBudgetID2=$gibbonFinanceBudgetID2&status2=$status2"; if (isActionAccessible($guid, $connection2, '/modules/Finance/expenses_manage_approve.php') == false) { $URL .= '&return=error0'; header("Location: {$URL}"); } else { $highestAction = getHighestGroupedAction($guid, $_POST['address'], $connection2); if ($highestAction == false) { $URL .= '&return=error0'; header("Location: {$URL}"); } else { //Check if params are specified if ($gibbonFinanceExpenseID == '' or $gibbonFinanceBudgetCycleID == '') { $URL .= '&return=error0'; header("Location: {$URL}"); } else { $budgetsAccess = false; if ($highestAction == 'Manage Expenses_all') { //Access to everything $budgetsAccess = true; } else { //Check if have Full or Write in any budgets $budgets = getBudgetsByPerson($connection2, $session->get('gibbonPersonID')); if (is_array($budgets) && count($budgets)>0) { foreach ($budgets as $budget) { if ($budget[2] == 'Full' or $budget[2] == 'Write') { $budgetsAccess = true; } } } } if ($budgetsAccess == false) { $URL .= '&return=error0'; header("Location: {$URL}"); } else { //Get and check settings $settingGateway = $container->get(SettingGateway::class); $expenseApprovalType = $settingGateway->getSettingByScope('Finance', 'expenseApprovalType'); $budgetLevelExpenseApproval = $settingGateway->getSettingByScope('Finance', 'budgetLevelExpenseApproval'); $expenseRequestTemplate = $settingGateway->getSettingByScope('Finance', 'expenseRequestTemplate'); if ($expenseApprovalType == '' or $budgetLevelExpenseApproval == '') { $URL .= '&return=error0'; header("Location: {$URL}"); } else { //Check if there are approvers try { $data = array(); $sql = "SELECT * FROM gibbonFinanceExpenseApprover JOIN gibbonPerson ON (gibbonFinanceExpenseApprover.gibbonPersonID=gibbonPerson.gibbonPersonID) WHERE status='Full'"; $result = $connection2->prepare($sql); $result->execute($data); } catch (PDOException $e) { echo $e->getMessage(); } if ($result->rowCount() < 1) { $URL .= '&return=error0'; header("Location: {$URL}"); } else { //Ready to go! Just check record exists and we have access, and load it ready to use... try { //Set Up filter wheres $data = array('gibbonFinanceBudgetCycleID' => $gibbonFinanceBudgetCycleID, 'gibbonFinanceExpenseID' => $gibbonFinanceExpenseID); //GET THE DATA ACCORDING TO FILTERS if ($highestAction == 'Manage Expenses_all') { //Access to everything $sql = "SELECT gibbonFinanceExpense.*, gibbonFinanceBudget.name AS budget, surname, preferredName, 'Full' AS access FROM gibbonFinanceExpense JOIN gibbonFinanceBudget ON (gibbonFinanceExpense.gibbonFinanceBudgetID=gibbonFinanceBudget.gibbonFinanceBudgetID) JOIN gibbonPerson ON (gibbonFinanceExpense.gibbonPersonIDCreator=gibbonPerson.gibbonPersonID) WHERE gibbonFinanceBudgetCycleID=:gibbonFinanceBudgetCycleID AND gibbonFinanceExpenseID=:gibbonFinanceExpenseID"; } else { //Access only to own budgets $data['gibbonPersonID'] = $session->get('gibbonPersonID'); $sql = "SELECT gibbonFinanceExpense.*, gibbonFinanceBudget.name AS budget, surname, preferredName, access FROM gibbonFinanceExpense JOIN gibbonFinanceBudget ON (gibbonFinanceExpense.gibbonFinanceBudgetID=gibbonFinanceBudget.gibbonFinanceBudgetID) JOIN gibbonFinanceBudgetPerson ON (gibbonFinanceBudgetPerson.gibbonFinanceBudgetID=gibbonFinanceBudget.gibbonFinanceBudgetID) JOIN gibbonPerson ON (gibbonFinanceExpense.gibbonPersonIDCreator=gibbonPerson.gibbonPersonID) WHERE gibbonFinanceBudgetCycleID=:gibbonFinanceBudgetCycleID AND gibbonFinanceExpenseID=:gibbonFinanceExpenseID AND gibbonFinanceBudgetPerson.gibbonPersonID=:gibbonPersonID AND access='Full'"; } $result = $connection2->prepare($sql); $result->execute($data); } catch (PDOException $e) { $URL .= '&return=error2'; header("Location: {$URL}"); exit(); } if ($result->rowCount() != 1) { $URL .= '&return=error0'; header("Location: {$URL}"); } else { $row = $result->fetch(); $approval = $_POST['approval'] ?? ''; if ($approval == 'Approval - Partial') { if ($row['statusApprovalBudgetCleared'] == 'N') { $approval = 'Approval - Partial - Budget'; } else { //Check if school approver, if not, abort $data = array('gibbonPersonID' => $session->get('gibbonPersonID')); $sql = "SELECT * FROM gibbonFinanceExpenseApprover JOIN gibbonPerson ON (gibbonFinanceExpenseApprover.gibbonPersonID=gibbonPerson.gibbonPersonID) WHERE status='Full' AND gibbonFinanceExpenseApprover.gibbonPersonID=:gibbonPersonID"; $result = $connection2->prepare($sql); $result->execute($data); if ($result->rowCount() == 1) { $approval = 'Approval - Partial - School'; } else { $URL .= '&return=error0'; header("Location: {$URL}"); exit(); } } } $comment = $_POST['comment'] ?? ''; if ($approval == '') { $URL .= '&return=error7'; header("Location: {$URL}"); } else { //Write budget change try { $dataBudgetChange = array('gibbonFinanceBudgetID' => $gibbonFinanceBudgetID, 'gibbonFinanceExpenseID' => $gibbonFinanceExpenseID); $sqlBudgetChange = 'UPDATE gibbonFinanceExpense SET gibbonFinanceBudgetID=:gibbonFinanceBudgetID WHERE gibbonFinanceExpenseID=:gibbonFinanceExpenseID'; $resultBudgetChange = $connection2->prepare($sqlBudgetChange); $resultBudgetChange->execute($dataBudgetChange); } catch (PDOException $e) { $URL .= '&return=error2'; header("Location: {$URL}"); exit(); } //Attempt to archive notification archiveNotification($connection2, $guid, $session->get('gibbonPersonID'), "/index.php?q=/modules/Finance/expenses_manage_approve.php&gibbonFinanceExpenseID=$gibbonFinanceExpenseID"); $notificationSender = $container->get(NotificationSender::class); if ($approval == 'Rejection') { //REJECT! //Write back to gibbonFinanceExpense try { $data = array('gibbonFinanceExpenseID' => $gibbonFinanceExpenseID); $sql = "UPDATE gibbonFinanceExpense SET status='Rejected' WHERE gibbonFinanceExpenseID=:gibbonFinanceExpenseID"; $result = $connection2->prepare($sql); $result->execute($data); } catch (PDOException $e) { $URL .= '&return=error2'; header("Location: {$URL}"); exit(); } //Write rejection to log try { $data = array('gibbonFinanceExpenseID' => $gibbonFinanceExpenseID, 'gibbonPersonID' => $session->get('gibbonPersonID'), 'comment' => $comment); $sql = "INSERT INTO gibbonFinanceExpenseLog SET gibbonFinanceExpenseID=:gibbonFinanceExpenseID, gibbonPersonID=:gibbonPersonID, timestamp='".date('Y-m-d H:i:s')."', action='Rejection', comment=:comment"; $result = $connection2->prepare($sql); $result->execute($data); } catch (PDOException $e) { $URL .= '&return=error2'; header("Location: {$URL}"); exit(); } //Notify original creator that it is rejected $notificationText = sprintf(__('Your expense request for "%1$s" in budget "%2$s" has been rejected.'), $row['title'], $row['budget']); $notificationSender->addNotification($row['gibbonPersonIDCreator'], $notificationText, 'Finance', "/index.php?q=/modules/Finance/expenses_manage_view.php&gibbonFinanceExpenseID=$gibbonFinanceExpenseID&gibbonFinanceBudgetCycleID=$gibbonFinanceBudgetCycleID&status2=&gibbonFinanceBudgetID2=".$row['gibbonFinanceBudgetID']); $notificationSender->sendNotifications(); $URLApprove .= '&return=success0'; header("Location: {$URLApprove}"); } elseif ($approval == 'Comment') { //COMMENT! //Write comment to log try { $data = array('gibbonFinanceExpenseID' => $gibbonFinanceExpenseID, 'gibbonPersonID' => $session->get('gibbonPersonID'), 'comment' => $comment); $sql = "INSERT INTO gibbonFinanceExpenseLog SET gibbonFinanceExpenseID=:gibbonFinanceExpenseID, gibbonPersonID=:gibbonPersonID, timestamp='".date('Y-m-d H:i:s')."', action='Comment', comment=:comment"; $result = $connection2->prepare($sql); $result->execute($data); } catch (PDOException $e) { $URL .= '&return=error2'; header("Location: {$URL}"); exit(); } //Notify original creator that it is commented upon $notificationText = sprintf(__('Someone has commented on your expense request for "%1$s" in budget "%2$s".'), $row['title'], $row['budget']); $notificationSender->addNotification($row['gibbonPersonIDCreator'], $notificationText, 'Finance', "/index.php?q=/modules/Finance/expenses_manage_view.php&gibbonFinanceExpenseID=$gibbonFinanceExpenseID&gibbonFinanceBudgetCycleID=$gibbonFinanceBudgetCycleID&status2=&gibbonFinanceBudgetID2=".$row['gibbonFinanceBudgetID']); $notificationSender->sendNotifications(); $URLApprove .= '&return=success0'; header("Location: {$URLApprove}"); } else { //APPROVE! if (approvalRequired($guid, $session->get('gibbonPersonID'), $row['gibbonFinanceExpenseID'], $gibbonFinanceBudgetCycleID, $connection2, true) == false) { $URL .= '&return=error0'; header("Location: {$URL}"); } else { //Add log entry try { $data = array('gibbonFinanceExpenseID' => $gibbonFinanceExpenseID, 'gibbonPersonID' => $session->get('gibbonPersonID'), 'action' => $approval, 'comment' => $comment); $sql = "INSERT INTO gibbonFinanceExpenseLog SET gibbonFinanceExpenseID=:gibbonFinanceExpenseID, gibbonPersonID=:gibbonPersonID, timestamp='".date('Y-m-d H:i:s')."', action=:action, comment=:comment"; $result = $connection2->prepare($sql); $result->execute($data); } catch (PDOException $e) { $URL .= '&return=error2'; header("Location: {$URL}"); exit(); } if ($approval = 'Approval - Partial - Budget') { //If budget-level approval, write that budget passed to expense record try { $data = array('gibbonFinanceExpenseID' => $gibbonFinanceExpenseID); $sql = "UPDATE gibbonFinanceExpense SET statusApprovalBudgetCleared='Y' WHERE gibbonFinanceExpenseID=:gibbonFinanceExpenseID"; $result = $connection2->prepare($sql); $result->execute($data); } catch (PDOException $e) { $URL .= '&return=error2'; header("Location: {$URL}"); exit(); } } //Check for completion status (returns FALSE, none, budget, school) based on log $partialFail = false; $completion = checkLogForApprovalComplete($guid, $gibbonFinanceExpenseID, $connection2); if ($completion == false) { //If false $URL .= '&return=error2'; header("Location: {$URL}"); exit(); } elseif ($completion == 'none') { //If none $URL .= '&return=error2'; header("Location: {$URL}"); exit(); } elseif ($completion == 'budget') { //If budget completion met //Issue Notifications if (setExpenseNotification($guid, $gibbonFinanceExpenseID, $gibbonFinanceBudgetCycleID, $connection2) == false) { $partialFail = true; } //Write back to gibbonFinanceExpense try { $data = array('gibbonFinanceExpenseID' => $gibbonFinanceExpenseID); $sql = "UPDATE gibbonFinanceExpense SET statusApprovalBudgetCleared='Y' WHERE gibbonFinanceExpenseID=:gibbonFinanceExpenseID"; $result = $connection2->prepare($sql); $result->execute($data); } catch (PDOException $e) { $URL .= '&return=error2'; header("Location: {$URL}"); exit(); } if ($partialFail == true) { $URLApprove .= '&return=success1'; header("Location: {$URLApprove}"); } else { $URLApprove .= '&return=success0'; header("Location: {$URLApprove}"); } } elseif ($completion == 'school') { //If school completion met //Write completion to log try { $data = array('gibbonFinanceExpenseID' => $gibbonFinanceExpenseID, 'gibbonPersonID' => $session->get('gibbonPersonID')); $sql = "INSERT INTO gibbonFinanceExpenseLog SET gibbonFinanceExpenseID=:gibbonFinanceExpenseID, gibbonPersonID=:gibbonPersonID, timestamp='".date('Y-m-d H:i:s')."', action='Approval - Final'"; $result = $connection2->prepare($sql); $result->execute($data); } catch (PDOException $e) { $URL .= '&return=error2'; header("Location: {$URL}"); exit(); } //Write back to gibbonFinanceExpense try { $data = array('gibbonFinanceExpenseID' => $gibbonFinanceExpenseID); $sql = "UPDATE gibbonFinanceExpense SET status='Approved' WHERE gibbonFinanceExpenseID=:gibbonFinanceExpenseID"; $result = $connection2->prepare($sql); $result->execute($data); } catch (PDOException $e) { $URL .= '&return=error2'; header("Location: {$URL}"); exit(); } $notificationExtra = ''; //Notify purchasing officer, if a school purchase, and officer set $purchasingOfficer = $settingGateway->getSettingByScope('Finance', 'purchasingOfficer'); if ($purchasingOfficer != false and $purchasingOfficer != '' and $row['purchaseBy'] == 'School') { $notificationText = sprintf(__('A newly approved expense (%1$s) needs to be purchased from budget "%2$s".'), $row['title'], $row['budget']); $notificationSender->addNotification($purchasingOfficer, $notificationText, 'Finance', "/index.php?q=/modules/Finance/expenses_manage_view.php&gibbonFinanceExpenseID=$gibbonFinanceExpenseID&gibbonFinanceBudgetCycleID=$gibbonFinanceBudgetCycleID&status2=&gibbonFinanceBudgetID2=".$row['gibbonFinanceBudgetID']); $notificationSender->sendNotifications(); $notificationExtra = '. '.__('The Purchasing Officer has been alerted, and will purchase the item on your behalf.'); } //Notify original creator that it is approved $notificationText = sprintf(__('Your expense request for "%1$s" in budget "%2$s" has been fully approved.').$notificationExtra, $row['title'], $row['budget']); $notificationSender->addNotification($row['gibbonPersonIDCreator'], $notificationText, 'Finance', "/index.php?q=/modules/Finance/expenses_manage_view.php&gibbonFinanceExpenseID=$gibbonFinanceExpenseID&gibbonFinanceBudgetCycleID=$gibbonFinanceBudgetCycleID&status2=&gibbonFinanceBudgetID2=".$row['gibbonFinanceBudgetID']); $notificationSender->sendNotifications(); $URLApprove .= '&return=success0'; header("Location: {$URLApprove}"); } } } } } } } } } } } }
GibbonEdu/core
modules/Finance/expenses_manage_approveProcess.php
PHP
gpl-3.0
25,606
// Torc - Copyright 2011-2013 University of Southern California. All Rights Reserved. // $HeadURL$ // $Id$ // This program is free software: you can redistribute it and/or modify it under the terms of the // GNU General Public License as published by the Free Software Foundation, either version 3 of the // License, or (at your option) any later version. // // This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; // without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See // the GNU General Public License for more details. // // You should have received a copy of the GNU General Public License along with this program. If // not, see <http://www.gnu.org/licenses/>. #ifndef HAVE_CONFIG_H #include "torc/generic/config.h" #endif #ifdef GENOM_SERIALIZATION #include <boost/archive/binary_iarchive.hpp> #include <boost/archive/binary_oarchive.hpp> #include <boost/serialization/base_object.hpp> #include <boost/serialization/is_abstract.hpp> #endif //GENOM_SERIALIZATION #include "torc/generic/Port.hpp" #include "torc/generic/PortAttributes.hpp" #ifdef GENOM_SERIALIZATION #endif //GENOM_SERIALIZATION namespace torc { namespace generic { Port::Port() : Composite<Port>(), Commentable(), Connectable(), Extern(), Nameable(), PropertyContainer(), Renamable(), Visitable(), ParentedObject<View>(), UserDataContainer(), mDirection(ePortDirectionUndefined), mAttributes() {} Port::~Port() throw () {} /** * Set the direction of port * * @param[in] inSource Direction of port */ void Port::setDirection(const EPortDirection& inSource) { mDirection = inSource; } /** * Set the attributes of the port. Attributes include dcFaninLoad, dcFanoutLoad_ etc. * * @note This method does not check whether prior set of properties exist or not. Newly set property will remove old properties. * * @param[in] inSource Pointer to PortAttributes object. */ void Port::setAttributes(const PortAttributesSharedPtr& inSource) { mAttributes = inSource; } #ifdef GENOM_SERIALIZATION template <class Archive> void Port::serialize(Archive& ar, unsigned int) { ar & boost::serialization::base_object<Commentable>(*this); ar & boost::serialization::base_object<Connectable>(*this); ar & boost::serialization::base_object<Extern>(*this); ar & boost::serialization::base_object<Nameable>(*this); ar & boost::serialization::base_object<PropertyContainer>(*this); ar & boost::serialization::base_object<Renamable>(*this); ar & boost::serialization::base_object<Visitable>(*this); ar & boost::serialization::base_object<Composite<Port> >(*this); ar & mDirection; ar & mAttributes; //We do not serialize the parent pointer } //TO SATISFY THE LINKER template void Port::serialize<boost::archive::binary_iarchive>( boost::archive::binary_iarchive& ar, const unsigned int); template void Port::serialize<boost::archive::binary_oarchive>( boost::archive::binary_oarchive& ar, const unsigned int); #endif //GENOM_SERIALIZATION } // namespace generic } // namespace torc
eddiehung/dox-torc
src/torc/generic/Port.cpp
C++
gpl-3.0
3,061
<?php /** * Zend Framework * * LICENSE * * This source file is subject to the new BSD license that is bundled * with this package in the file LICENSE.txt. * It is also available through the world-wide-web at this URL: * http://framework.zend.com/license/new-bsd * If you did not receive a copy of the license and are unable to * obtain it through the world-wide-web, please send an email * to [email protected] so we can send you a copy immediately. * * @category Zend * @package Zend_Gdata * @subpackage YouTube * @copyright Copyright (c) 2005-2012 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License * @version $Id: SubscriptionFeed.php 24594 2012-01-05 21:27:01Z matthew $ */ /** * @see Zend_Gdata_Media_Feed */ //require_once 'Zend/Gdata/Media/Feed.php'; /** * @see Zend_Gdata_YouTube_SubscriptionEntry */ //require_once 'Zend/Gdata/YouTube/SubscriptionEntry.php'; /** * The YouTube video subscription list flavor of an Atom Feed with media support * Represents a list of individual subscriptions, where each contained entry is * a subscription. * * @category Zend * @package Zend_Gdata * @subpackage YouTube * @copyright Copyright (c) 2005-2012 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License */ class Zend_Gdata_YouTube_SubscriptionFeed extends Zend_Gdata_Media_Feed { /** * The classname for individual feed elements. * * @var string */ protected $_entryClassName = 'Zend_Gdata_YouTube_SubscriptionEntry'; /** * Creates a Subscription feed, representing a list of subscriptions, * usually associated with an individual user. * * @param DOMElement $element (optional) DOMElement from which this * object should be constructed. */ public function __construct($element = null) { $this->registerAllNamespaces(Zend_Gdata_YouTube::$namespaces); parent::__construct($element); } }
sadiqdon/cycommerce
common/lib/Zend/Gdata/YouTube/SubscriptionFeed.php
PHP
gpl-3.0
2,084
----------------------------------- -- Area: Throne Room (165) -- Mob: Count_Andromalius ----------------------------------- -- require("scripts/zones/Throne_Room/MobIDs"); ----------------------------------- -- onMobInitialize ----------------------------------- function onMobInitialize(mob) end; ----------------------------------- -- onMobSpawn ----------------------------------- function onMobSpawn(mob) end; ----------------------------------- -- onMobEngaged ----------------------------------- function onMobEngaged(mob,target) end; ----------------------------------- -- onMobFight ----------------------------------- function onMobFight(mob,target) end; ----------------------------------- -- onMobDeath ----------------------------------- function onMobDeath(mob,killer) end;
salamader/ffxi-a
scripts/zones/Throne_Room/mobs/Count_Andromalius.lua
Lua
gpl-3.0
808
<?php class WpTesting_Query_Passing extends WpTesting_Query_AbstractQuery { /** * @return WpTesting_Query_Passing */ public static function create($className = __CLASS__) { return parent::create($className); } public function findAllPagedSorted($page, $recordsPerPage = 10, $orderBy = array()) { return $this->findAllPagedSortedByParams(array(), $page, $recordsPerPage, $orderBy); } /** * @return fRecordSet|WpTesting_Model_Passing[] */ public function findAllPagedSortedByParams($params, $page, $recordsPerPage = 10, $orderBy = array()) { $conditions = array(); foreach ($params as $key => $value) { if ($value == '-') { if ('user' == $key) { $key = 'respondent_id'; } $conditions[$key . '='] = array(null, ''); continue; } if ('passing_created' == $key) { if (strlen($value) != 6) { continue; } $year = intval(substr($value, 0, 4)); $month = intval(substr($value, 4)); $day = 1; $format = '%04s-%02s-%02s'; $conditions[$key . '>='] = sprintf($format, $year, $month, $day); if ($month < 12) { $month++; } else { $year++; $month = 1; } $conditions[$key . '<'] = sprintf($format, $year, $month, $day); } elseif ('user' == $key) { $key = 'respondent_id'; $value = fRecordSet::build('WpTesting_Model_Respondent', array( 'user_login|user_nicename|user_email|display_name~' => $value, ))->getPrimaryKeys(); $conditions[$key . '='] = $value; } elseif ('passing_ip' == $key) { $conditions[$key . '^~'] = $value; } elseif ('passing_user_agent' == $key) { $conditions[$key . '~'] = $value; } else { $conditions[$key . '='] = $value; } } return fRecordSet::build($this->modelName, $conditions, $orderBy, $recordsPerPage, $page); } /** * @param array $ids * @param array $orderBy * @return fRecordSet|WpTesting_Model_Passing[] */ public function findAllByIds($ids, $orderBy = array()) { return fRecordSet::build($this->modelName, array( 'passing_id=' => $ids, ), $orderBy); } /** * Passings sorted by the order of provided $ids * @param array $ids * @return fRecordSet|WpTesting_Model_Passing[] */ public function findAllByIdsSorted($ids) { $orderBy = (!empty($ids)) ? array('FIELD(passing_id, ' . implode(', ', $ids) . ')' => 'asc') : array(); return $this->findAllByIds($ids, $orderBy); } /** * @return fResult */ public function queryAllMonths() { return $this->queryAllMonthsByRespondent(0); } /** * @param integer $respondentId * @return fResult */ public function queryAllMonthsByRespondent($respondentId) { return $this->singleTranslatedQuery(' SELECT DISTINCT YEAR(passing_created) AS created_year, MONTH(passing_created) AS created_month FROM %r WHERE (respondent_id = %i OR %i = 0) ORDER BY passing_id ', $this->tableName, $respondentId, $respondentId); } /** * @return fResult */ public function countAllStatuses() { return $this->singleTranslatedQuery(' SELECT passing_status, COUNT(*) AS passing_count FROM %r GROUP BY passing_status ', $this->tableName); } }
wp-plugins/wp-testing
src/Query/Passing.php
PHP
gpl-3.0
3,881
#Region "Microsoft.VisualBasic::16174964213d2c8377b9559d5ec7087f, analysis\RNA-Seq\Toolkits.RNA-Seq.RTools\R\DESeq\DESeq.vb" ' Author: ' ' asuka ([email protected]) ' xie ([email protected]) ' xieguigang ([email protected]) ' ' Copyright (c) 2018 GPL3 Licensed ' ' ' GNU GENERAL PUBLIC LICENSE (GPL3) ' ' ' This program is free software: you can redistribute it and/or modify ' it under the terms of the GNU General Public License as published by ' the Free Software Foundation, either version 3 of the License, or ' (at your option) any later version. ' ' This program is distributed in the hope that it will be useful, ' but WITHOUT ANY WARRANTY; without even the implied warranty of ' MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the ' GNU General Public License for more details. ' ' You should have received a copy of the GNU General Public License ' along with this program. If not, see <http://www.gnu.org/licenses/>. ' /********************************************************************************/ ' Summaries: ' Module DESeq ' ' Constructor: (+1 Overloads) Sub New ' Function: __runR, (+3 Overloads) DESeq2, DiffGeneCOGs, FilterDifferentExpression, HTSeqCount ' Initialize, LoadPTT, SaveResult, summarizeOverlaps ' ' ' /********************************************************************************/ #End Region Imports System.Text Imports Microsoft.VisualBasic.ApplicationServices Imports Microsoft.VisualBasic.CommandLine Imports Microsoft.VisualBasic.CommandLine.Reflection Imports Microsoft.VisualBasic.Data.csv Imports Microsoft.VisualBasic.Data.csv.Extensions Imports Microsoft.VisualBasic.Data.csv.IO Imports Microsoft.VisualBasic.Language Imports Microsoft.VisualBasic.Linq.Extensions Imports Microsoft.VisualBasic.Math Imports Microsoft.VisualBasic.Scripting.MetaData Imports RDotNET.Extensions.VisualBasic Imports RDotNET.Extensions.VisualBasic.API Imports RDotNET.Extensions.VisualBasic.API.base Imports SMRUCC.genomics.Assembly Imports SMRUCC.genomics.Assembly.NCBI.GenBank.TabularFormat Imports SMRUCC.genomics.Interops.RNA_Seq.BOW Namespace DESeq2 ''' <summary> ''' Differential analysis of count data – the DESeq2 package ''' (M. I. Love, W. Huber, S. Anders: Moderated estimation of fold change And dispersion For RNA-Seq data With DESeq2. bioRxiv(2014).doi : 10.1101/002832) ''' ''' A basic task in the analysis of count data from RNA-Seq is the detection of differentially ''' expressed genes. The count data are presented As a table which reports, For Each sample, the ''' number Of sequence fragments that have been assigned To Each gene. Analogous data also arise ''' ''' For other assay types, including comparative ChIP-Seq, HiC, shRNA screening, mass spectrometry. ''' An important analysis question Is the quantification And statistical inference Of systematic changes ''' between conditions, as compared To within-condition variability. The package DESeq2 provides ''' methods To test For differential expression by use Of negative binomial generalized linear models; ''' the estimates Of dispersion And logarithmic fold changes incorporate data-driven prior distributions. ''' ''' This vignette explains the use of the package And demonstrates typical work flows. ''' Another vignette, “Beginner’s guide to using the DESeq2 package”, covers similar material but at a slower ''' pace, including the generation Of count tables from FASTQ files. ''' </summary> ''' <remarks> ''' Welcome to 'DESeq'. For improved performance, usability and functionality, please consider migrating to 'DESeq2'. ''' 虽然模块的名称是DESeq,但是在R之中实际调用的包确是DESeq2 ''' </remarks> <Package("DESeq", Description:="Differential analysis of count data – the DESeq2 package (M. I. Love, W. Huber, S. Anders: Moderated estimation of fold change And dispersion For RNA-Seq data With DESeq2. bioRxiv(2014).doi : 10.1101/002832) <br /> <p> A basic task in the analysis of count data from RNA-Seq is the detection of differentially expressed genes. The count data are presented As a table which reports, For Each sample, the number Of sequence fragments that have been assigned To Each gene. Analogous data also arise <br /> For other assay types, including comparative ChIP-Seq, HiC, shRNA screening, mass spectrometry. An important analysis question Is the quantification And statistical inference Of systematic changes between conditions, as compared To within-condition variability. The package DESeq2 provides methods To test For differential expression by use Of negative binomial generalized linear models; the estimates Of dispersion And logarithmic fold changes incorporate data-driven prior distributions. <br /> This vignette explains the use of the package And demonstrates typical work flows. Another vignette, “"Beginner's guide to using the DESeq2 package"”, covers similar material but at a slower pace, including the generation Of count tables from FASTQ files. </p>", Publisher:="", Cites:="Anders, S. and W. Huber (2010). ""Differential expression analysis For sequence count data."" Genome Biol 11(10): R106. <p> High-throughput sequencing assays such as RNA-Seq, ChIP-Seq or barcode counting provide quantitative readouts in the form of count data. To infer differential signal in such data correctly and with good statistical power, estimation of data variability throughout the dynamic range and a suitable error model are required. We propose a method based on the negative binomial distribution, with variance and mean linked by local regression and present an implementation, DESeq, as an R/Bioconductor package. ")> <Cite(Title:="Differential expression analysis for sequence count data", Year:=2010, Volume:=11, Issue:="10", Pages:="R106", Keywords:="Animals Binomial Distribution Chromatin Immunoprecipitation/methods Computational Biology/*methods Drosophila/genetics Gene Expression Profiling/*methods High-Throughput Nucleotide Sequencing/methods Linear Models Models, Genetic Saccharomyces cerevisiae/genetics Sequence Analysis, RNA/*methods Stem Cells Tissue Culture Techniques", Abstract:="High-throughput sequencing assays such as RNA-Seq, ChIP-Seq or barcode counting provide quantitative readouts in the form of count data. To infer differential signal in such data correctly and with good statistical power, estimation of data variability throughout the dynamic range and a suitable error model are required. We propose a method based on the negative binomial distribution, with variance and mean linked by local regression and present an implementation, DESeq, as an R/Bioconductor package.", AuthorAddress:="European Molecular Biology Laboratory, Mayerhofstrasse 1, 69117 Heidelberg, Germany. [email protected]", Authors:="Anders, S. Huber, W.", DOI:="10.1186/gb-2010-11-10-r106", ISSN:="1474-760X (Electronic) 1474-7596 (Linking)", Journal:="Genome biology", PubMed:=20979621)> Public Module DESeq Sub New() Call Settings.Session.Initialize() End Sub ''' <summary> ''' 导出差异表达的基因 ''' </summary> ''' <returns></returns> ''' <ExportAPI("Genes'DifferentExpr")> Public Function FilterDifferentExpression(result As String, Optional log2Fold As Double = 2) As String() Dim LQuery = (From Gene In result.LoadCsv(Of DESeq2Diff)(False).AsParallel Where Math.Abs(Gene.log2FoldChange) >= log2Fold Select Gene.locus_tag).ToArray Return LQuery End Function <ExportAPI("DESeq.COGs")> Public Function DiffGeneCOGs(result As String, PTT As PTT, Optional log2Fold As Double = 2, Optional IdenticalLog2Folds As Double = 1) As DESeqCOGs() Dim DiffCsv = IO.File.Load(result) Dim Diff = DiffCsv.AsDataSource(Of DESeq2Diff)(False) Dim Up = (From Gene In Diff.AsParallel Where Gene.log2FoldChange >= log2Fold Select Gene.locus_tag, COG = PTT.GeneObject(Gene.locus_tag).COG.GetCOGCategory).ToArray log2Fold *= -1 Dim Down = (From Gene In Diff.AsParallel Where Gene.log2FoldChange <= log2Fold Select Gene.locus_tag, COG = PTT.GeneObject(Gene.locus_tag).COG.GetCOGCategory).ToArray Dim ExpressRanks = (From Gene In Diff Select Gene.baseMean).ToArray.Log2Ranks(100) '首先做映射因为需要保持顺序,所以这里不可以使用并行化 Dim IdenticalsRanks = (From i As Integer In Diff.Sequence.AsParallel Let Gene As DESeq2Diff = Diff(i) Where Gene.log2FoldChange <= IdenticalLog2Folds AndAlso Gene.log2FoldChange >= -IdenticalLog2Folds Select Gene, Ranks = ExpressRanks(i)).ToArray Dim InvariantLow = (From Gene In IdenticalsRanks Where Gene.Ranks <= 20 Select Gene.Gene.locus_tag, COG = PTT.GeneObject(Gene.Gene.locus_tag).COG.GetCOGCategory).ToArray Dim InvariantHigh = (From Gene In IdenticalsRanks Where Gene.Ranks >= 80 Select Gene.Gene.locus_tag, COG = PTT.GeneObject(Gene.Gene.locus_tag).COG.GetCOGCategory).ToArray Dim ResultView As New List(Of DESeqCOGs) For Each cat As NCBI.COG.Catalog In NCBI.COG.Function.Default.Catalogs For Each COG In cat.SubClasses Dim View As New DESeqCOGs With { .Category = cat.Class, .CategoryDescription = cat.Description, .COG = COG.Key, .COGDescription = $"[{COG.Key}] {COG.Value}" } View.DiffUp = (From Gene In Up Where InStr(Gene.COG, COG.Key) > 0 Select Gene.locus_tag).ToArray View.DiffDown = (From Gene In Down Where InStr(Gene.COG, COG.Key) > 0 Select Gene.locus_tag).ToArray View.IdenticalLow = (From Gene In InvariantLow Where InStr(Gene.COG, COG.Key) > 0 Select Gene.locus_tag).ToArray View.IdenticalHigh = (From Gene In InvariantHigh Where InStr(Gene.COG, COG.Key) > 0 Select Gene.locus_tag).ToArray Call ResultView.Add(View) Call Console.Write(".") Next Next Return ResultView.ToArray End Function <ExportAPI("Read.PTT")> Public Function LoadPTT(path As String) As PTT Return PTT.Load(path) End Function <ExportAPI("Write.Csv.DESeq2.COGs")> Public Function SaveResult(data As IEnumerable(Of DESeqCOGs), <Parameter("Path.Save")> SaveTo As String) As Boolean Return data.SaveTo(SaveTo, False) End Function ''' <summary> ''' ''' </summary> ''' <param name="R_HOME"></param> ''' <returns></returns> ''' <remarks> ''' For counting aligned reads in genes, the summarizeOverlaps function of GenomicAlignments ''' With mode="Union" Is encouraged, resulting In a SummarizedExperiment Object(easyRNASeq Is ''' another Bioconductor package which can prepare SummarizedExperiment objects as input for DESeq2). ''' ''' 为了计数基因的比对Reads数目, GenomicAlignments 包之中的summarizeOverlaps方法可以生成DESeq2所需要用到的数据 ''' easyRNASeq包也可以用来生成这种数据 ''' </remarks> <ExportAPI("init()", Info:="Initis the R session for the Differential analysis.")> Public Function Initialize(<Parameter("R_HOME", "The R program install location on your computer.")> Optional R_HOME As String = "") As Boolean Try If Not String.IsNullOrEmpty(R_HOME) Then Call TryInit(R_HOME) End If Call library("rtracklayer") Call library("GenomicAlignments") Call library("DESeq2") Return True Catch ex As Exception ex = New Exception("R_HOME: " & R_HOME, ex) Call App.LogException(ex) Call ex.PrintException Return False End Try End Function ''' <summary> ''' 使用这个函数进行分析 ''' </summary> ''' <param name="sampleTable"></param> ''' <param name="directory"></param> ''' <param name="design"></param> ''' <returns></returns> <ExportAPI("DESeq2")> Public Function DESeq2(<Parameter("dataExpr0", "For htseq-count: a data.frame with three or more columns. Each row describes one sample. " & "The first column is the sample name, the second column the file name of the count file generated by htseq-count, and the remaining columns are sample metadata which will be stored in colData")> sampleTable As IO.File, <Parameter("directory", "for htseq-count: the directory relative to which the filenames are specified")> directory As String, <Parameter("design", "A formula which specifies the design of the experiment, taking the form formula(~ x + y + z). " & "By default, the functions in this package will use the last variable in the formula (e.g. z) for presenting results (fold changes, etc.) and plotting.")> design As String, PTT As PTT) As Boolean Dim SampleTables = sampleTable.AsDataSource(Of SampleTable)(False) '为了保持顺序,这里不再使用并行化拓展 Dim countDataTable = HtseqCountMethod.DataFrame((From row As SampleTable In SampleTables Select $"{directory}\{row.fileName}").ToArray, PTT, False) Dim countData As String = directory & "\countData.csv" Dim sbr As StringBuilder = New StringBuilder(My.Resources.DEseq2_Template) Call sbr.Replace("{countData.MAT.csv}", countData.Replace("\", "/")) Call countDataTable.Save(countData, False) '# ({conditionName} <- factor(c({factors}))) '{WRITE_FACTOR_CONDITIONS} Dim Conditions = (From column As String() In sampleTable.Columns.Skip(2) '遍历每一个Factor,取得矩阵之中的每一列的数据作为DataFrame之中的一列 Let Factor As String = column(Scan0) Select Factor, init = $"{Factor} <- factor(c({String.Join(", ", (From s In column.Skip(1) Select """" & s & """").ToArray)}))").ToArray Call sbr.Replace("{WRITE_FACTOR_CONDITIONS}", String.Join(vbCrLf, Conditions.Select(Of String)(Function(obj) obj.init))) Call sbr.Replace("{FACTOR_LIST}", String.Join(", ", Conditions.Select(Of String)(Function(obj) obj.Factor))) Call sbr.Replace("{Condition-Design}", design) Call sbr.Replace("{ColumnNames}", String.Join(", ", SampleTables.Select(Of String)(Function(obj) """" & obj.sampleName & """"))) Call sbr.Replace("{DIR_EXPORT}", FileIO.FileSystem.GetParentPath(countData).Replace("\", "/")) Call sbr.Replace("{ConditionLength}", Conditions.Length) Dim path$ = Nothing Dim DiffCsv As IO.File = __runR(sbr.ToString, directory, path) Return DiffCsv.Save(path) End Function Private Function __runR(RScript As String, directory As String, ByRef diffPath$) As IO.File Dim ScriptPath As String = $"{directory}/R.DESeq.txt" Call RScript.SaveTo(ScriptPath) Call $"Script file saved to {ScriptPath.ToFileURL}...".__DEBUG_ECHO Call "Start running R analysis....".__DEBUG_ECHO Try SyncLock R With R Call .WriteLine(RScript).JoinBy(vbCrLf).__DEBUG_ECHO End With End SyncLock Catch ex As Exception ex = New Exception(RScript, ex) Call ex.PrintException Call base.warning().JoinBy(vbCrLf).__DEBUG_ECHO End Try diffPath = directory & "/diffexpr-results.csv" If Not diffPath.FileExists Then Call "DESeq2 analysis run failure!".__DEBUG_ECHO Return False End If '替换回基因编号 Dim ID As String() = IO.File.Load(directory & "\countData.csv").Column(0).Skip(1).ToArray Dim DiffCsv As IO.File = IO.File.Load(diffPath) DiffCsv(0)(1) = "locus_tag" ' Gene -> locus_tag For i As Integer = 1 To ID.Length Dim row As IO.RowObject = DiffCsv(i) row(1) = ID(i - 1) Next Return DiffCsv End Function ''' <summary> ''' DESeqDataSetFromMatrix(countData, colData, design, ignoreRank = FALSE, ...) ''' </summary> ''' <param name="Experiments"> ''' {column, experiment}, {column, experiment} ''' {80041, NY}, {80042, MMX} ''' </param> ''' <param name="Factors">Column name of the experiments variables</param> ''' <param name="countData">htseq-count::Data.Frame, For matrix input: A matrix of non-negative integers</param> ''' <returns></returns> ''' <ExportAPI("DESeq2", Info:="DESeqDataSetFromMatrix(countData, colData, design, ignoreRank = FALSE, ...)")> Public Function DESeq2(<Parameter("Count.Data", "htseq-count::Data.Frame, For matrix input: A matrix of non-negative integers")> countData As String, <Parameter("Factors", "Column name of the experiments variables.")> Factors As IEnumerable(Of String), Experiments As IEnumerable(Of IEnumerable(Of String))) As Boolean Dim colDataMAT As New IO.File ' For matrix input: a DataFrame or data.frame with at least a single column. Rows of colData correspond to columns of countData. Dim HeadRow = New IO.RowObject From {""} Call HeadRow.AddRange(Factors) '为了保持一一对应关系,在这里不再使用并行化拓展 Call colDataMAT.Add(HeadRow) Call colDataMAT.AppendRange((From Experiment In Experiments Select New RowObject(Experiment)).ToArray) Dim colData As String = $"{FileIO.FileSystem.GetParentPath(countData)}/{BaseName(countData)}.colData.csv" Call colDataMAT.Save(colData, Encoding:=Encoding.ASCII) Dim ScriptBuilder As StringBuilder = New StringBuilder(My.Resources.DEseq2_Template) Call ScriptBuilder.Replace("{countData.MAT.csv}", countData.Replace("\", "/")) '# ({conditionName} <- factor(c({factors}))) '{WRITE_FACTOR_CONDITIONS} Dim Conditions = (From i As Integer In Factors.Sequence '遍历每一个Factor,取得矩阵之中的每一列的数据作为DataFrame之中的一列 Let Factor As String = Factors(i) Let value As String() = (From experiment In Experiments Select experiment(i + 1)).ToArray Select $"{Factor} <- factor(c({String.Join(", ", (From s In value Select """" & s & """").ToArray)}))").ToArray Call ScriptBuilder.Replace("{WRITE_FACTOR_CONDITIONS}", String.Join(vbCrLf, Conditions)) Call ScriptBuilder.Replace("{FACTOR_LIST}", String.Join(", ", Factors.ToArray)) Call ScriptBuilder.Replace("{Condition-Design}", "~" & String.Join("+", Factors.ToArray)) Call ScriptBuilder.Replace("{ColumnNames}", String.Join(", ", (From Expr In Experiments Select """" & Expr.First & """").ToArray)) Call ScriptBuilder.Replace("{DIR_EXPORT}", FileIO.FileSystem.GetParentPath(countData).Replace("\", "/")) Call ScriptBuilder.Replace("{ConditionLength}", Factors.Count) Dim ScriptPath As String = $"{FileIO.FileSystem.GetParentPath(countData)}/{BaseName(countData)}.R.DESeq.txt" Call ScriptBuilder.SaveTo(ScriptPath) Call $"Script file saved to {ScriptPath.ToFileURL}...".__DEBUG_ECHO Call "Start running R analysis....".__DEBUG_ECHO Call TryInit(Settings.Session.GetSettingsFile.R_HOME) Try SyncLock R With R Call .WriteLine(ScriptBuilder.ToString) _ .JoinBy(vbCrLf) _ .__DEBUG_ECHO End With End SyncLock Catch ex As Exception Call Console.WriteLine(ex.ToString) End Try Dim DiffPath As String = FileIO.FileSystem.GetParentPath(countData) & "/diffexpr-results.csv" If Not DiffPath.FileExists Then Return False End If '替换回基因编号 Dim ID = IO.File.Load(countData).Column(0).Skip(1).ToArray Dim DiffCsv = IO.File.Load(DiffPath) For i As Integer = 1 To ID.Count DiffCsv(i)(1) = ID(i - 1) Next Call DiffCsv.Save(DiffPath) Return True End Function ''' <summary> ''' ''' </summary> ''' <param name="SAM"></param> ''' <param name="GFF"></param> ''' <param name="PairedEnd">假若是Paired-End的比对数据,则还需要首先使用samtools工具进行排序</param> ''' <returns></returns> <ExportAPI("HTSeq.Count", Info:="This function required of python, numpy and HTSeq installed on your computer.")> Public Function HTSeqCount(SAM As Value(Of String), GFF As String, Optional PairedEnd As Boolean = True) As Boolean 'python -m HTSeq.scripts.count [options] <alignment_file> <gff_file> Call Settings.Session.Initialize() If Not Settings.Session.SettingsFile.Python.FileExists Then Call "The required python is not installed on your computer!".__DEBUG_ECHO Return False End If If PairedEnd Then '进行排序 Dim Sorted As String = SAM.Value & ".ordered" Call $"The input Sam data file {SAM.Value.ToFileURL} is paired-end data, needs to be sorted.....".__DEBUG_ECHO Call "Start to sorting the sam file....".__DEBUG_ECHO '将sam转换为bam '根据gff文件查找*.fna基因组序列文件 Dim GFF_ID As String = BaseName(GFF) Dim Fna As String = (From path As String In FileIO.FileSystem.GetFiles(FileIO.FileSystem.GetParentPath(GFF), FileIO.SearchOption.SearchTopLevelOnly, "*.fna") Let FNA_ID As String = BaseName(path) Where String.Equals(FNA_ID, GFF_ID, StringComparison.OrdinalIgnoreCase) Select path).FirstOrDefault If Not Fna.FileExists Then '找不到基因组序列文件 Call "Could not found the reference genome fasta file, could not indexing the Sam file for your paired-end data, function exit....".__DEBUG_ECHO Return False End If Fna = Samtools.Indexing(Fna) Call Samtools.Import(SAM, Fna, SAM = (SAM.Value & ".bam")) Call Samtools.Sort(SAM, Sorted) Call $"Samtools sorts job done! Sorted file saved at {Sorted.ToFileURL}".__DEBUG_ECHO SAM = Sorted & ".bam" End If Dim Cli As String = If(PairedEnd, $"-m HTSeq.scripts.count -r name -f bam {SAM.Value.CLIPath} {GFF.CLIPath}", $"-m HTSeq.scripts.count {SAM.Value.CLIPath} {GFF.CLIPath}") 'bam文件还需要加一些开关来指定格式? Dim HTseq As IIORedirectAbstract = New IORedirectFile(Settings.Session.SettingsFile.Python, Cli) Dim i As Boolean = 0 = HTseq.Run() Call Console.WriteLine(HTseq.StandardOutput) Return i End Function ''' <summary> ''' HTSeq-Count ''' </summary> ''' <param name="TestData"> ''' samFile, condition; ''' samFile, condition; ''' ''' </param> ''' <returns></returns> <ExportAPI("DESeq2", Info:="How to use DESeq2 to analyse RNAseq.")> Public Function DESeq2(TestData As IEnumerable(Of Generic.IEnumerable(Of String)), <Parameter("DIR.Export")> Optional Export As String = "./") As Boolean Dim RScript As StringBuilder = New StringBuilder(My.Resources.Invoke_DESeq2) Dim SamList As New List(Of String) Dim ConditionList As New List(Of String) For Each Line In TestData If Line.Count >= 2 Then Call SamList.Add(Line(0)) Call ConditionList.Add(Line(1)) End If Next Dim SourceDir As String = FileIO.FileSystem.GetFileInfo(SamList.First).Directory.FullName.Replace("\", "/") Dim SamFileList As String = String.Join(", ", (From path As String In SamList Select """" & FileIO.FileSystem.GetFileInfo(path).Name & """").ToArray) Dim Conditions As String = String.Join(", ", (From cd As String In ConditionList Select """" & cd & """").ToArray) Dim ConditionLvs As String = String.Join(", ", (From T As String In ConditionList.Distinct Select """" & T & """").ToArray) Export = FileIO.FileSystem.GetDirectoryInfo(Export).FullName.Replace("\", "/") Call RScript.Replace("<*.SAM_FILE_LIST>", SamFileList) Call RScript.Replace("<Conditions_Corresponding_TO_SampleFiles>", Conditions) Call RScript.Replace("<Condition_Levels>", ConditionLvs) Call RScript.Replace("<SAVED_RESULT_CSV>", Export & "/ddsHTSeq.csv") Call RScript.Replace("<MAplot.png>", Export & "/MAplot.png") Call RScript.Replace("<DIR.Source>", SourceDir) Call RScript.SaveTo(Export & "/Invoke_DESeq2.txt", Encoding.ASCII) SyncLock R With R .call = RScript.ToString End With End SyncLock Return True End Function ''' <summary> ''' Counting reads with summarizeOverlaps, Perform overlap queries between reads and genomic features ''' </summary> ''' <returns></returns> ''' <param name="annoGFF">GTF基因组注释文件的文件路径</param> ''' <param name="bamList">Mapping所得到的*.bam二进制文件的文件路径的列表</param> ''' <remarks> ''' 作者推荐使用这个函数方法的模式 ''' ''' ## mode funtions ''' Union(features, reads, ignore.strand=FALSE, inter.feature=TRUE) ''' </remarks> <ExportAPI("DEseq", Info:="GenomicAlignments::summarizeOverlaps Counting reads with summarizeOverlaps")> Public Function summarizeOverlaps(<Parameter("List.Bam", "The file list of the binary format reads mapping file.")> bamList As IEnumerable(Of String), <Parameter("anno.gff", "The gff format genome annotation file, which can be achieved from the ncbi FTP in the same directory of ptt annotation file.")> annoGFF As String) As RDotNET.SymbolicExpression Dim GTF As String = annoGFF.Replace("\", "/") Dim anno As String = $"gffFile <- ""{GTF}""; gff0 <- import(gffFile,format=""gff3"", version=""3"" , asRangedData=F); idx <- mcols(gff0)$source == ""protein_coding"" & seqnames(gff0) == ""1""; gff <- gff0[idx]; ## adjust seqnames to match Bam files seqlevels(gff) <- paste(""chr"", seqlevels(gff), sep=""""); chrgenes <- split(gff, mcols(gff)$gene_id);" '生成基因组的注释数据 Dim Script As String = $"bamlst <- c({ String.Join(", ", (From file As String In bamList Select """" & file.Replace("\", "/") & """").ToArray)}); bamlst <- BamFileList(bamlst); genehits <- summarizeOverlaps(chrgenes, bamlst, mode=""Union"");" Dim DESeq2R As String = "dds <- DESeqDataSet(se = se, design = ~ condition); dds <- DESeq(dds); res <- results(dds); resOrdered <- res[order(res$padj),]; head(resOrdered);" Dim DebugScript = "library(rtracklayer) library(GenomicAlignments) library(DESeq2)" & vbCrLf & anno & vbCrLf & Script & vbCrLf & DESeq2R Call DebugScript.SaveTo(Settings.DataCache & "/DEseq.r.txt") Call DebugScript.__DEBUG_ECHO SyncLock R With R Try .call = anno Catch ex As Exception Throw New Exception(anno & vbCrLf & vbCrLf & ex.ToString) End Try Try .call = Script Catch ex As Exception Throw New Exception(Script & vbCrLf & vbCrLf & ex.ToString) End Try Try .call = DESeq2R Catch ex As Exception Throw New Exception(DESeq2R & vbCrLf & vbCrLf & ex.ToString) End Try Dim result As RDotNET.SymbolicExpression = .GetSymbol("resOrdered") Return result End With End SyncLock End Function End Module End Namespace
xieguigang/GCModeller
src/GCModeller/analysis/RNA-Seq/Toolkits.RNA-Seq.RTools/R/DESeq/DESeq.vb
Visual Basic
gpl-3.0
31,291
#ifndef QLOG_H #define QLOG_H #include <QtGui> #include <logging.h> class QLogger : public QWidget, public Logger { Q_OBJECT public: QLogger(QWidget *); ~QLogger(); public slots: private: }; #endif // QLOG_H
jaromil/FreeJ
qt/qLogging.h
C
gpl-3.0
227
/* * Copyright (C) 2008-2011 The QXmpp developers * * Author: * Manjeet Dahiya * * Source: * http://code.google.com/p/qxmpp * * This file is a part of QXmpp library. * * 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. * */ #include "profileDialog.h" #include "ui_profileDialog.h" #include "utils.h" #include "QXmppClient.h" #include "QXmppVersionIq.h" #include "QXmppVersionManager.h" #include "QXmppRosterManager.h" #include "QXmppUtils.h" #include "QXmppEntityTimeManager.h" #include "QXmppEntityTimeIq.h" #include "QXmppConstants.h" profileDialog::profileDialog(QWidget *parent, const QString& bareJid, QXmppClient& client, capabilitiesCache& caps) : QDialog(parent, Qt::WindowTitleHint|Qt::WindowSystemMenuHint), ui(new Ui::profileDialog), m_bareJid(bareJid), m_xmppClient(client), m_caps(caps) { ui->setupUi(this); bool check = connect(&m_xmppClient.versionManager(), SIGNAL(versionReceived(const QXmppVersionIq&)), SLOT(versionReceived(const QXmppVersionIq&))); Q_ASSERT(check); QXmppEntityTimeManager* timeManager = m_xmppClient.findExtension<QXmppEntityTimeManager>(); if(timeManager) { check = connect(timeManager, SIGNAL(timeReceived(const QXmppEntityTimeIq&)), SLOT(timeReceived(const QXmppEntityTimeIq&))); Q_ASSERT(check); } QStringList resources = m_xmppClient.rosterManager().getResources(bareJid); foreach(QString resource, resources) { QString jid = bareJid + "/" + resource; m_xmppClient.versionManager().requestVersion(jid); if(timeManager) timeManager->requestTime(jid); } updateText(); } profileDialog::~profileDialog() { delete ui; } void profileDialog::setAvatar(const QImage& image) { ui->label_avatar->setPixmap(QPixmap::fromImage(image)); } void profileDialog::setBareJid(const QString& bareJid) { ui->label_jid->setText(bareJid); setWindowTitle(bareJid); } void profileDialog::setFullName(const QString& fullName) { if(fullName.isEmpty()) ui->label_fullName->hide(); else ui->label_fullName->show(); ui->label_fullName->setText(fullName); } void profileDialog::setStatusText(const QString& status) { ui->label_status->setText(status); } void profileDialog::versionReceived(const QXmppVersionIq& ver) { m_versions[jidToResource(ver.from())] = ver; if(ver.type() == QXmppIq::Result) updateText(); } void profileDialog::timeReceived(const QXmppEntityTimeIq& time) { m_time[jidToResource(time.from())] = time; if(time.type() == QXmppIq::Result) updateText(); } void profileDialog::updateText() { QStringList resources = m_xmppClient.rosterManager().getResources(m_bareJid); QString statusText; for(int i = 0; i < resources.count(); ++i) { QString resource = resources.at(i); statusText += "<B>Resource: </B>" + resource; statusText += "<BR>"; QXmppPresence presence = m_xmppClient.rosterManager().getPresence(m_bareJid, resource); statusText += "<B>Status: </B>" + presenceToStatusText(presence); statusText += "<BR>"; if(m_versions.contains(resource)) { statusText += "<B>Software: </B>" + QString("%1 %2 %3"). arg(m_versions[resource].name()). arg(m_versions[resource].version()). arg(m_versions[resource].os()); statusText += "<BR>"; } if(m_time.contains(resource)) { statusText += "<B>Time: </B>" + QString("utc=%1 [tzo=%2]"). arg(m_time[resource].utc().toString()). arg(timezoneOffsetToString(m_time[resource].tzo())); statusText += "<BR>"; } statusText += getCapability(resource); if(i < resources.count() - 1) // skip for the last item statusText += "<BR>"; } setStatusText(statusText); } QString profileDialog::getCapability(const QString& resource) { QMap<QString, QXmppPresence> presences = m_xmppClient.rosterManager(). getAllPresencesForBareJid(m_bareJid); QXmppPresence& pre = presences[resource]; QString nodeVer; QStringList resultFeatures; QStringList resultIdentities; QString node = pre.capabilityNode(); QString ver = pre.capabilityVer().toBase64(); QStringList exts = pre.capabilityExt(); nodeVer = node + "#" + ver; if(m_caps.isCapabilityAvailable(nodeVer)) { resultFeatures << m_caps.getFeatures(nodeVer); resultIdentities << m_caps.getIdentities(nodeVer); } foreach(QString ext, exts) { nodeVer = node + "#" + ext; if(m_caps.isCapabilityAvailable(nodeVer)) { resultFeatures << m_caps.getFeatures(nodeVer); resultIdentities << m_caps.getIdentities(nodeVer); } } resultIdentities.removeDuplicates(); resultFeatures.removeDuplicates(); QString result; result += "<B>Disco Identities:</B><BR>"; result += resultIdentities.join("<BR>"); result += "<BR>"; result += "<B>Disco Features:</B><BR>"; result += resultFeatures.join("<BR>"); result += "<BR>"; return result; }
fredix/geekast
src/externals/qxmpp-0.3.0/examples/GuiClient/profileDialog.cpp
C++
gpl-3.0
5,768
//===-- tsan_platform_linux.cpp -------------------------------------------===// // // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. // See https://llvm.org/LICENSE.txt for license information. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception // //===----------------------------------------------------------------------===// // // This file is a part of ThreadSanitizer (TSan), a race detector. // // Linux- and BSD-specific code. //===----------------------------------------------------------------------===// #include "sanitizer_common/sanitizer_platform.h" #if SANITIZER_LINUX || SANITIZER_FREEBSD || SANITIZER_NETBSD #include "sanitizer_common/sanitizer_common.h" #include "sanitizer_common/sanitizer_libc.h" #include "sanitizer_common/sanitizer_linux.h" #include "sanitizer_common/sanitizer_platform_limits_netbsd.h" #include "sanitizer_common/sanitizer_platform_limits_posix.h" #include "sanitizer_common/sanitizer_posix.h" #include "sanitizer_common/sanitizer_procmaps.h" #include "sanitizer_common/sanitizer_stackdepot.h" #include "sanitizer_common/sanitizer_stoptheworld.h" #include "tsan_flags.h" #include "tsan_platform.h" #include "tsan_rtl.h" #include <fcntl.h> #include <pthread.h> #include <signal.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <stdarg.h> #include <sys/mman.h> #if SANITIZER_LINUX #include <sys/personality.h> #include <setjmp.h> #endif #include <sys/syscall.h> #include <sys/socket.h> #include <sys/time.h> #include <sys/types.h> #include <sys/resource.h> #include <sys/stat.h> #include <unistd.h> #include <sched.h> #include <dlfcn.h> #if SANITIZER_LINUX #define __need_res_state #include <resolv.h> #endif #ifdef sa_handler # undef sa_handler #endif #ifdef sa_sigaction # undef sa_sigaction #endif #if SANITIZER_FREEBSD extern "C" void *__libc_stack_end; void *__libc_stack_end = 0; #endif #if SANITIZER_LINUX && defined(__aarch64__) && !SANITIZER_GO # define INIT_LONGJMP_XOR_KEY 1 #else # define INIT_LONGJMP_XOR_KEY 0 #endif #if INIT_LONGJMP_XOR_KEY #include "interception/interception.h" // Must be declared outside of other namespaces. DECLARE_REAL(int, _setjmp, void *env) #endif namespace __tsan { #if INIT_LONGJMP_XOR_KEY static void InitializeLongjmpXorKey(); static uptr longjmp_xor_key; #endif #ifdef TSAN_RUNTIME_VMA // Runtime detected VMA size. uptr vmaSize; #endif enum { MemTotal = 0, MemShadow = 1, MemMeta = 2, MemFile = 3, MemMmap = 4, MemTrace = 5, MemHeap = 6, MemOther = 7, MemCount = 8, }; void FillProfileCallback(uptr p, uptr rss, bool file, uptr *mem, uptr stats_size) { mem[MemTotal] += rss; if (p >= ShadowBeg() && p < ShadowEnd()) mem[MemShadow] += rss; else if (p >= MetaShadowBeg() && p < MetaShadowEnd()) mem[MemMeta] += rss; #if !SANITIZER_GO else if (p >= HeapMemBeg() && p < HeapMemEnd()) mem[MemHeap] += rss; else if (p >= LoAppMemBeg() && p < LoAppMemEnd()) mem[file ? MemFile : MemMmap] += rss; else if (p >= HiAppMemBeg() && p < HiAppMemEnd()) mem[file ? MemFile : MemMmap] += rss; #else else if (p >= AppMemBeg() && p < AppMemEnd()) mem[file ? MemFile : MemMmap] += rss; #endif else if (p >= TraceMemBeg() && p < TraceMemEnd()) mem[MemTrace] += rss; else mem[MemOther] += rss; } void WriteMemoryProfile(char *buf, uptr buf_size, uptr nthread, uptr nlive) { uptr mem[MemCount]; internal_memset(mem, 0, sizeof(mem[0]) * MemCount); __sanitizer::GetMemoryProfile(FillProfileCallback, mem, 7); StackDepotStats *stacks = StackDepotGetStats(); internal_snprintf(buf, buf_size, "RSS %zd MB: shadow:%zd meta:%zd file:%zd mmap:%zd" " trace:%zd heap:%zd other:%zd stacks=%zd[%zd] nthr=%zd/%zd\n", mem[MemTotal] >> 20, mem[MemShadow] >> 20, mem[MemMeta] >> 20, mem[MemFile] >> 20, mem[MemMmap] >> 20, mem[MemTrace] >> 20, mem[MemHeap] >> 20, mem[MemOther] >> 20, stacks->allocated >> 20, stacks->n_uniq_ids, nlive, nthread); } #if SANITIZER_LINUX void FlushShadowMemoryCallback( const SuspendedThreadsList &suspended_threads_list, void *argument) { ReleaseMemoryPagesToOS(ShadowBeg(), ShadowEnd()); } #endif void FlushShadowMemory() { #if SANITIZER_LINUX StopTheWorld(FlushShadowMemoryCallback, 0); #endif } #if !SANITIZER_GO // Mark shadow for .rodata sections with the special kShadowRodata marker. // Accesses to .rodata can't race, so this saves time, memory and trace space. static void MapRodata() { // First create temp file. const char *tmpdir = GetEnv("TMPDIR"); if (tmpdir == 0) tmpdir = GetEnv("TEST_TMPDIR"); #ifdef P_tmpdir if (tmpdir == 0) tmpdir = P_tmpdir; #endif if (tmpdir == 0) return; char name[256]; internal_snprintf(name, sizeof(name), "%s/tsan.rodata.%d", tmpdir, (int)internal_getpid()); uptr openrv = internal_open(name, O_RDWR | O_CREAT | O_EXCL, 0600); if (internal_iserror(openrv)) return; internal_unlink(name); // Unlink it now, so that we can reuse the buffer. fd_t fd = openrv; // Fill the file with kShadowRodata. const uptr kMarkerSize = 512 * 1024 / sizeof(u64); InternalMmapVector<u64> marker(kMarkerSize); // volatile to prevent insertion of memset for (volatile u64 *p = marker.data(); p < marker.data() + kMarkerSize; p++) *p = kShadowRodata; internal_write(fd, marker.data(), marker.size() * sizeof(u64)); // Map the file into memory. uptr page = internal_mmap(0, GetPageSizeCached(), PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS, fd, 0); if (internal_iserror(page)) { internal_close(fd); return; } // Map the file into shadow of .rodata sections. MemoryMappingLayout proc_maps(/*cache_enabled*/true); // Reusing the buffer 'name'. MemoryMappedSegment segment(name, ARRAY_SIZE(name)); while (proc_maps.Next(&segment)) { if (segment.filename[0] != 0 && segment.filename[0] != '[' && segment.IsReadable() && segment.IsExecutable() && !segment.IsWritable() && IsAppMem(segment.start)) { // Assume it's .rodata char *shadow_start = (char *)MemToShadow(segment.start); char *shadow_end = (char *)MemToShadow(segment.end); for (char *p = shadow_start; p < shadow_end; p += marker.size() * sizeof(u64)) { internal_mmap(p, Min<uptr>(marker.size() * sizeof(u64), shadow_end - p), PROT_READ, MAP_PRIVATE | MAP_FIXED, fd, 0); } } } internal_close(fd); } void InitializeShadowMemoryPlatform() { MapRodata(); } #endif // #if !SANITIZER_GO void InitializePlatformEarly() { #ifdef TSAN_RUNTIME_VMA vmaSize = (MostSignificantSetBitIndex(GET_CURRENT_FRAME()) + 1); #if defined(__aarch64__) # if !SANITIZER_GO if (vmaSize != 39 && vmaSize != 42 && vmaSize != 48) { Printf("FATAL: ThreadSanitizer: unsupported VMA range\n"); Printf("FATAL: Found %zd - Supported 39, 42 and 48\n", vmaSize); Die(); } #else if (vmaSize != 48) { Printf("FATAL: ThreadSanitizer: unsupported VMA range\n"); Printf("FATAL: Found %zd - Supported 48\n", vmaSize); Die(); } #endif #elif defined(__powerpc64__) # if !SANITIZER_GO if (vmaSize != 44 && vmaSize != 46 && vmaSize != 47) { Printf("FATAL: ThreadSanitizer: unsupported VMA range\n"); Printf("FATAL: Found %zd - Supported 44, 46, and 47\n", vmaSize); Die(); } # else if (vmaSize != 46 && vmaSize != 47) { Printf("FATAL: ThreadSanitizer: unsupported VMA range\n"); Printf("FATAL: Found %zd - Supported 46, and 47\n", vmaSize); Die(); } # endif #endif #endif } void InitializePlatform() { DisableCoreDumperIfNecessary(); // Go maps shadow memory lazily and works fine with limited address space. // Unlimited stack is not a problem as well, because the executable // is not compiled with -pie. #if !SANITIZER_GO { bool reexec = false; // TSan doesn't play well with unlimited stack size (as stack // overlaps with shadow memory). If we detect unlimited stack size, // we re-exec the program with limited stack size as a best effort. if (StackSizeIsUnlimited()) { const uptr kMaxStackSize = 32 * 1024 * 1024; VReport(1, "Program is run with unlimited stack size, which wouldn't " "work with ThreadSanitizer.\n" "Re-execing with stack size limited to %zd bytes.\n", kMaxStackSize); SetStackSizeLimitInBytes(kMaxStackSize); reexec = true; } if (!AddressSpaceIsUnlimited()) { Report("WARNING: Program is run with limited virtual address space," " which wouldn't work with ThreadSanitizer.\n"); Report("Re-execing with unlimited virtual address space.\n"); SetAddressSpaceUnlimited(); reexec = true; } #if SANITIZER_LINUX && defined(__aarch64__) // After patch "arm64: mm: support ARCH_MMAP_RND_BITS." is introduced in // linux kernel, the random gap between stack and mapped area is increased // from 128M to 36G on 39-bit aarch64. As it is almost impossible to cover // this big range, we should disable randomized virtual space on aarch64. int old_personality = personality(0xffffffff); if (old_personality != -1 && (old_personality & ADDR_NO_RANDOMIZE) == 0) { VReport(1, "WARNING: Program is run with randomized virtual address " "space, which wouldn't work with ThreadSanitizer.\n" "Re-execing with fixed virtual address space.\n"); CHECK_NE(personality(old_personality | ADDR_NO_RANDOMIZE), -1); reexec = true; } // Initialize the xor key used in {sig}{set,long}jump. InitializeLongjmpXorKey(); #endif if (reexec) ReExec(); } CheckAndProtect(); InitTlsSize(); #endif // !SANITIZER_GO } #if !SANITIZER_GO // Extract file descriptors passed to glibc internal __res_iclose function. // This is required to properly "close" the fds, because we do not see internal // closes within glibc. The code is a pure hack. int ExtractResolvFDs(void *state, int *fds, int nfd) { #if SANITIZER_LINUX && !SANITIZER_ANDROID int cnt = 0; struct __res_state *statp = (struct __res_state*)state; for (int i = 0; i < MAXNS && cnt < nfd; i++) { if (statp->_u._ext.nsaddrs[i] && statp->_u._ext.nssocks[i] != -1) fds[cnt++] = statp->_u._ext.nssocks[i]; } return cnt; #else return 0; #endif } // Extract file descriptors passed via UNIX domain sockets. // This is requried to properly handle "open" of these fds. // see 'man recvmsg' and 'man 3 cmsg'. int ExtractRecvmsgFDs(void *msgp, int *fds, int nfd) { int res = 0; msghdr *msg = (msghdr*)msgp; struct cmsghdr *cmsg = CMSG_FIRSTHDR(msg); for (; cmsg; cmsg = CMSG_NXTHDR(msg, cmsg)) { if (cmsg->cmsg_level != SOL_SOCKET || cmsg->cmsg_type != SCM_RIGHTS) continue; int n = (cmsg->cmsg_len - CMSG_LEN(0)) / sizeof(fds[0]); for (int i = 0; i < n; i++) { fds[res++] = ((int*)CMSG_DATA(cmsg))[i]; if (res == nfd) return res; } } return res; } // Reverse operation of libc stack pointer mangling static uptr UnmangleLongJmpSp(uptr mangled_sp) { #if defined(__x86_64__) # if SANITIZER_LINUX // Reverse of: // xor %fs:0x30, %rsi // rol $0x11, %rsi uptr sp; asm("ror $0x11, %0 \n" "xor %%fs:0x30, %0 \n" : "=r" (sp) : "0" (mangled_sp)); return sp; # else return mangled_sp; # endif #elif defined(__aarch64__) # if SANITIZER_LINUX return mangled_sp ^ longjmp_xor_key; # else return mangled_sp; # endif #elif defined(__powerpc64__) // Reverse of: // ld r4, -28696(r13) // xor r4, r3, r4 uptr xor_key; asm("ld %0, -28696(%%r13)" : "=r" (xor_key)); return mangled_sp ^ xor_key; #elif defined(__mips__) return mangled_sp; #else #error "Unknown platform" #endif } #if SANITIZER_NETBSD # ifdef __x86_64__ # define LONG_JMP_SP_ENV_SLOT 6 # else # error unsupported # endif #elif defined(__powerpc__) # define LONG_JMP_SP_ENV_SLOT 0 #elif SANITIZER_FREEBSD # define LONG_JMP_SP_ENV_SLOT 2 #elif SANITIZER_LINUX # ifdef __aarch64__ # define LONG_JMP_SP_ENV_SLOT 13 # elif defined(__mips64) # define LONG_JMP_SP_ENV_SLOT 1 # else # define LONG_JMP_SP_ENV_SLOT 6 # endif #endif uptr ExtractLongJmpSp(uptr *env) { uptr mangled_sp = env[LONG_JMP_SP_ENV_SLOT]; return UnmangleLongJmpSp(mangled_sp); } #if INIT_LONGJMP_XOR_KEY // GLIBC mangles the function pointers in jmp_buf (used in {set,long}*jmp // functions) by XORing them with a random key. For AArch64 it is a global // variable rather than a TCB one (as for x86_64/powerpc). We obtain the key by // issuing a setjmp and XORing the SP pointer values to derive the key. static void InitializeLongjmpXorKey() { // 1. Call REAL(setjmp), which stores the mangled SP in env. jmp_buf env; REAL(_setjmp)(env); // 2. Retrieve vanilla/mangled SP. uptr sp; asm("mov %0, sp" : "=r" (sp)); uptr mangled_sp = ((uptr *)&env)[LONG_JMP_SP_ENV_SLOT]; // 3. xor SPs to obtain key. longjmp_xor_key = mangled_sp ^ sp; } #endif void ImitateTlsWrite(ThreadState *thr, uptr tls_addr, uptr tls_size) { // Check that the thr object is in tls; const uptr thr_beg = (uptr)thr; const uptr thr_end = (uptr)thr + sizeof(*thr); CHECK_GE(thr_beg, tls_addr); CHECK_LE(thr_beg, tls_addr + tls_size); CHECK_GE(thr_end, tls_addr); CHECK_LE(thr_end, tls_addr + tls_size); // Since the thr object is huge, skip it. MemoryRangeImitateWrite(thr, /*pc=*/2, tls_addr, thr_beg - tls_addr); MemoryRangeImitateWrite(thr, /*pc=*/2, thr_end, tls_addr + tls_size - thr_end); } // Note: this function runs with async signals enabled, // so it must not touch any tsan state. int call_pthread_cancel_with_cleanup(int (*fn)(void *arg), void (*cleanup)(void *arg), void *arg) { // pthread_cleanup_push/pop are hardcore macros mess. // We can't intercept nor call them w/o including pthread.h. int res; pthread_cleanup_push(cleanup, arg); res = fn(arg); pthread_cleanup_pop(0); return res; } #endif // !SANITIZER_GO #if !SANITIZER_GO void ReplaceSystemMalloc() { } #endif #if !SANITIZER_GO #if SANITIZER_ANDROID // On Android, one thread can call intercepted functions after // DestroyThreadState(), so add a fake thread state for "dead" threads. static ThreadState *dead_thread_state = nullptr; ThreadState *cur_thread() { ThreadState* thr = reinterpret_cast<ThreadState*>(*get_android_tls_ptr()); if (thr == nullptr) { __sanitizer_sigset_t emptyset; internal_sigfillset(&emptyset); __sanitizer_sigset_t oldset; CHECK_EQ(0, internal_sigprocmask(SIG_SETMASK, &emptyset, &oldset)); thr = reinterpret_cast<ThreadState*>(*get_android_tls_ptr()); if (thr == nullptr) { thr = reinterpret_cast<ThreadState*>(MmapOrDie(sizeof(ThreadState), "ThreadState")); *get_android_tls_ptr() = reinterpret_cast<uptr>(thr); if (dead_thread_state == nullptr) { dead_thread_state = reinterpret_cast<ThreadState*>( MmapOrDie(sizeof(ThreadState), "ThreadState")); dead_thread_state->fast_state.SetIgnoreBit(); dead_thread_state->ignore_interceptors = 1; dead_thread_state->is_dead = true; *const_cast<int*>(&dead_thread_state->tid) = -1; CHECK_EQ(0, internal_mprotect(dead_thread_state, sizeof(ThreadState), PROT_READ)); } } CHECK_EQ(0, internal_sigprocmask(SIG_SETMASK, &oldset, nullptr)); } return thr; } void set_cur_thread(ThreadState *thr) { *get_android_tls_ptr() = reinterpret_cast<uptr>(thr); } void cur_thread_finalize() { __sanitizer_sigset_t emptyset; internal_sigfillset(&emptyset); __sanitizer_sigset_t oldset; CHECK_EQ(0, internal_sigprocmask(SIG_SETMASK, &emptyset, &oldset)); ThreadState* thr = reinterpret_cast<ThreadState*>(*get_android_tls_ptr()); if (thr != dead_thread_state) { *get_android_tls_ptr() = reinterpret_cast<uptr>(dead_thread_state); UnmapOrDie(thr, sizeof(ThreadState)); } CHECK_EQ(0, internal_sigprocmask(SIG_SETMASK, &oldset, nullptr)); } #endif // SANITIZER_ANDROID #endif // if !SANITIZER_GO } // namespace __tsan #endif // SANITIZER_LINUX || SANITIZER_FREEBSD || SANITIZER_NETBSD
sabel83/metashell
3rd/templight/compiler-rt/lib/tsan/rtl/tsan_platform_linux.cpp
C++
gpl-3.0
16,377
package dna.graph.weights; /** * * 2-dimensional int weight holding two int values (x and y). * * @author benni * */ public class Int2dWeight extends Weight { private int x; private int y; public Int2dWeight(int x, int y) { this.x = x; this.y = y; } public Int2dWeight() { this(0, 0); } public Int2dWeight(String str) { String[] temp = str.split(Weight.WeightSeparator); this.x = Integer.parseInt(temp[0]); this.y = Integer.parseInt(temp[1]); } public Int2dWeight(WeightSelection ws) { this.x = IntWeight.getIntWeight(ws); this.y = IntWeight.getIntWeight(ws); } public int getX() { return this.x; } public void setX(int x) { this.x = x; } public int getY() { return this.y; } public void setY(int y) { this.y = y; } @Override public String asString() { return this.x + Weight.WeightSeparator + this.y; } }
marcel-stud/DNA
src/dna/graph/weights/Int2dWeight.java
Java
gpl-3.0
874