answer
stringlengths
15
1.25M
#! /usr/bin/env python # -*- coding: utf-8 -*- import json import cgi import urllib2 myip = urllib2.urlopen('http://members.3322.org/dyndns/getip').read() myip=myip.strip() #SSR JSON f = file("/usr/local/shadowsocksr/mudb.json"); json = json.load(f); form = cgi.FieldStorage() getport = form['port'].value getpasswd = form['passwd'].value portexist=0 passwdcorrect=0 for x in json: #json if(str(x[u"port"]) == str(getport)): portexist=1 if(str(x[u"passwd"]) == str(getpasswd)): passwdcorrect=1 jsonmethod=str(x[u"method"]) jsonobfs=str(x[u"obfs"]) jsonprotocol=str(x[u"protocol"]) break if(portexist==0): getport = "" myip = "" getpasswd = "" jsonmethod = "" jsonprotocol = "" jsonobfs = "" if(portexist!=0 and passwdcorrect==0): getport = "" myip = "" getpasswd = "" jsonmethod = "" jsonprotocol = "" jsonobfs = "" header = ''' <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta content="IE=edge" http-equiv="X-UA-Compatible"> <meta content="initial-scale=1.0, width=device-width" name="viewport"> <title></title> <!-- css --> <link href="../css/base.min.css" rel="stylesheet"> <!-- favicon --> <!-- ... --> <!-- ie --> <!--[if lt IE 9]> <script src="../js/html5shiv.js" type="text/javascript"></script> <script src="../js/respond.js" type="text/javascript"></script> <![endif]--> </head> <body> <div class="content"> <div class="content-heading"> <div class="container"> <h1 class="heading">&nbsp;&nbsp;</h1> </div> </div> <div class="content-inner"> <div class="container"> ''' footer = ''' </div> </div> </div> <footer class="footer"> <div class="container"> <p>Hello</p> </div> </footer> <script src="../js/base.min.js" type="text/javascript"></script> </body> </html> ''' print header formhtml = ''' <div class="card-wrap"> <div class="row"> <div class="col-lg-4 col-sm-6"> <div class="card card-green"> <a class="card-side" href="/"><span class="card-heading"></span></a> <div class="card-main"> <div class="card-inner"> <p> <strong></strong> %s </br></br> <strong></strong> %s </br></br> <strong></strong> %s </br></br> <strong> </strong> %s </br></br> <strong> </strong> </br>%s </br></br> <strong></strong> </br>%s </p> </div> <div class="card-action"> <ul class="nav nav-list pull-left"> <li> <a href="../index.html"><span class="icon icon-check"></span>&nbsp;</a> </li> </ul> </div> </div> </div> </div> </div> </div> ''' print formhtml % (myip,getport,getpasswd,jsonmethod,jsonprotocol,jsonobfs) print footer f.close();
<?xml version="1.0" encoding="utf-8"?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http: <html xmlns="http: <head> <title>ActionView::Rendering</title> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /> <link rel="stylesheet" href="../../css/reset.css" type="text/css" media="screen" /> <link rel="stylesheet" href="../../css/main.css" type="text/css" media="screen" /> <link rel="stylesheet" href="../../css/github.css" type="text/css" media="screen" /> <script src="../../js/jquery-1.3.2.min.js" type="text/javascript" charset="utf-8"></script> <script src="../../js/jquery-effect.js" type="text/javascript" charset="utf-8"></script> <script src="../../js/main.js" type="text/javascript" charset="utf-8"></script> <script src="../../js/highlight.pack.js" type="text/javascript" charset="utf-8"></script> </head> <body> <div class="banner"> <span>Ruby on Rails 4.2.6</span><br /> <h1> <span class="type">Module</span> ActionView::Rendering </h1> <ul class="files"> <li><a href="../../files/__/__/_rbenv/versions/2_4_0/lib/ruby/gems/2_4_0/gems/actionview-4_2_6/lib/action_view/rendering_rb.html">/home/user/.rbenv/versions/2.4.0/lib/ruby/gems/2.4.0/gems/actionview-4.2.6/lib/action_view/rendering.rb</a></li> </ul> </div> <div id="bodyContent"> <div id="content"> <!-- Namespace --> <div class="sectiontitle">Namespace</div> <ul> <li> <span class="type">MODULE</span> <a href="Rendering/ClassMethods.html">ActionView::Rendering::ClassMethods</a> </li> </ul> <!-- Method ref --> <div class="sectiontitle">Methods</div> <dl class="methods"> <dt>R</dt> <dd> <ul> <li> <a href="#<API key>">render_to_body</a>, </li> <li> <a href="#<API key>">rendered_format</a> </li> </ul> </dd> <dt>V</dt> <dd> <ul> <li> <a href="#<API key>">view_context</a>, </li> <li> <a href="#<API key>">view_context_class</a>, </li> <li> <a href="#<API key>">view_renderer</a> </li> </ul> </dd> </dl> <!-- Includes --> <div class="sectiontitle">Included Modules</div> <ul> <li> <a href="ViewPaths.html"> ActionView::ViewPaths </a> </li> </ul> <!-- Methods --> <div class="sectiontitle">Instance Public methods</div> <div class="method"> <div class="title method-title" id="<API key>"> <b>render_to_body</b>(options = {}) <a href="../../classes/ActionView/Rendering.html#<API key>" name="<API key>" class="permalink">Link</a> </div> <div class="description"> </div> <div class="sourcecode"> <p class="source-link"> Source: <a href="javascript:toggleSource('<API key>')" id="<API key>">show</a> </p> <div id="<API key>" class="dyn-source"> <pre><span class="ruby-comment"># File ../../.rbenv/versions/2.4.0/lib/ruby/gems/2.4.0/gems/actionview-4.2.6/lib/action_view/rendering.rb, line 81</span> <span class="ruby-keyword">def</span> <span class="ruby-keyword ruby-title">render_to_body</span>(<span class="ruby-identifier">options</span> = {}) <span class="ruby-identifier">_process_options</span>(<span class="ruby-identifier">options</span>) <span class="ruby-identifier">_render_template</span>(<span class="ruby-identifier">options</span>) <span class="ruby-keyword">end</span></pre> </div> </div> </div> <div class="method"> <div class="title method-title" id="<API key>"> <b>rendered_format</b>() <a href="../../classes/ActionView/Rendering.html#<API key>" name="<API key>" class="permalink">Link</a> </div> <div class="description"> </div> <div class="sourcecode"> <p class="source-link"> Source: <a href="javascript:toggleSource('<API key>')" id="<API key>">show</a> </p> <div id="<API key>" class="dyn-source"> <pre><span class="ruby-comment"># File ../../.rbenv/versions/2.4.0/lib/ruby/gems/2.4.0/gems/actionview-4.2.6/lib/action_view/rendering.rb, line 86</span> <span class="ruby-keyword">def</span> <span class="ruby-keyword ruby-title">rendered_format</span> <span class="ruby-constant">Mime</span>[<span class="ruby-identifier">lookup_context</span>.<span class="ruby-identifier">rendered_format</span>] <span class="ruby-keyword">end</span></pre> </div> </div> </div> <div class="method"> <div class="title method-title" id="<API key>"> <b>view_context</b>() <a href="../../classes/ActionView/Rendering.html#<API key>" name="<API key>" class="permalink">Link</a> </div> <div class="description"> <p>An instance of a view class. The default view class is <a href="Base.html">ActionView::Base</a></p> <p>The view class must have the following methods: View.new[lookup_context, assigns, controller]</p> <pre><code>Create a new ActionView instance for a controller and we can also pass the arguments.</code></pre> <p>View#render(option)</p> <pre><code>Returns String with the rendered template </code></pre> <p>Override this method in a module to change the default behavior.</p> </div> <div class="sourcecode"> <p class="source-link"> Source: <a href="javascript:toggleSource('<API key>')" id="<API key>">show</a> </p> <div id="<API key>" class="dyn-source"> <pre><span class="ruby-comment"># File ../../.rbenv/versions/2.4.0/lib/ruby/gems/2.4.0/gems/actionview-4.2.6/lib/action_view/rendering.rb, line 71</span> <span class="ruby-keyword">def</span> <span class="ruby-keyword ruby-title">view_context</span> <span class="ruby-identifier">view_context_class</span>.<span class="ruby-identifier">new</span>(<span class="ruby-identifier">view_renderer</span>, <span class="ruby-identifier">view_assigns</span>, <span class="ruby-keyword">self</span>) <span class="ruby-keyword">end</span></pre> </div> </div> </div> <div class="method"> <div class="title method-title" id="<API key>"> <b>view_context_class</b>() <a href="../../classes/ActionView/Rendering.html#<API key>" name="<API key>" class="permalink">Link</a> </div> <div class="description"> </div> <div class="sourcecode"> <p class="source-link"> Source: <a href="javascript:toggleSource('<API key>')" id="<API key>">show</a> </p> <div id="<API key>" class="dyn-source"> <pre><span class="ruby-comment"># File ../../.rbenv/versions/2.4.0/lib/ruby/gems/2.4.0/gems/actionview-4.2.6/lib/action_view/rendering.rb, line 58</span> <span class="ruby-keyword">def</span> <span class="ruby-keyword ruby-title">view_context_class</span> <span class="ruby-ivar">@_view_context_class</span> <span class="ruby-operator">||=</span> <span class="ruby-keyword">self</span>.<span class="ruby-identifier">class</span>.<span class="ruby-identifier">view_context_class</span> <span class="ruby-keyword">end</span></pre> </div> </div> </div> <div class="method"> <div class="title method-title" id="<API key>"> <b>view_renderer</b>() <a href="../../classes/ActionView/Rendering.html#<API key>" name="<API key>" class="permalink">Link</a> </div> <div class="description"> <p>Returns an object that is able to render templates. :api: private</p> </div> <div class="sourcecode"> <p class="source-link"> Source: <a href="javascript:toggleSource('<API key>')" id="<API key>">show</a> </p> <div id="<API key>" class="dyn-source"> <pre><span class="ruby-comment"># File ../../.rbenv/versions/2.4.0/lib/ruby/gems/2.4.0/gems/actionview-4.2.6/lib/action_view/rendering.rb, line 77</span> <span class="ruby-keyword">def</span> <span class="ruby-keyword ruby-title">view_renderer</span> <span class="ruby-ivar">@_view_renderer</span> <span class="ruby-operator">||=</span> <span class="ruby-constant">ActionView</span><span class="ruby-operator">::</span><span class="ruby-constant">Renderer</span>.<span class="ruby-identifier">new</span>(<span class="ruby-identifier">lookup_context</span>) <span class="ruby-keyword">end</span></pre> </div> </div> </div> </div> </div> </body> </html>
<div class="histogram-chart"> <linechart ng-if="histogramChart.data.bins" data="histogramChart.data" options="histogramChart.options" ></linechart> </div>
package fr.ribesg.imag.moustacheuml.modele.lien; import fr.ribesg.imag.moustacheuml.modele.boite.Boite; public abstract class Lien { private final Boite source; private final Boite destination; private Navigabilite navigabilite; private final TypeLien type; protected Lien(Boite source, Boite destination, TypeLien type, Navigabilite navigabilite) { this.source = source; this.destination = destination; this.type = type; this.navigabilite = navigabilite; } public Boite getSource() { return source; } public Boite getDestination() { return destination; } public TypeLien getType() { return type; } public Navigabilite getNavigabilite() { return navigabilite; } public void setNavigabilite(Navigabilite navigabilite) { this.navigabilite = navigabilite; } public String getId() { return "Lien=" + getSource().getId() + "-" + getDestination().getId() + "-" + hashCode(); } @Override public int hashCode() { int result = navigabilite.hashCode(); result = 31 * result + type.hashCode(); return result; } }
#include "cli.h" CLI::CLI(XOAICup* parent) : QObject(parent) { exit(0); }
package com.csy.mission.manager; import java.util.ArrayList; import java.util.Date; import java.util.List; import org.springframework.beans.BeanUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.csy.dao.<API key>; import com.csy.dao.MissionMapperExt; import com.csy.mission.domain.dto.MissionDTO; import com.csy.mission.domain.dto.MissionExtendDTO; import com.csy.mission.domain.dto.MissionSearchDTO; import com.csy.mission.domain.emus.MissionCodeStatusEn; import com.csy.mission.domain.emus.MissionIpEn; import com.csy.mission.domain.emus.MissionTypeEn; import com.csy.model.Mission; import com.csy.model.MissionCode; import com.csy.model.MissionExample; import com.csy.model.MissionWithBLOBs; import com.csy.model.base.DateUtil; import com.csy.model.base.Pagination; import com.csy.model.base.StringUtils; @Service public class MissionManager { @Autowired private MissionMapperExt missionMapperExt; @Autowired private <API key> <API key>; public MissionExtendDTO insertMission(MissionExtendDTO missionDTO,String staffCode) { MissionWithBLOBs mission = new MissionWithBLOBs(); BeanUtils.copyProperties(missionDTO, mission); mission.setCreator(staffCode); mission.setCreateTm(new Date()); mission.setModifior(staffCode); mission.setModifyTm(new Date()); mission.setSignNum(0); if(StringUtils.isNotEmpty(missionDTO.getBeginDate())) { mission.setBeginTm(DateUtil.parse(missionDTO.getBeginDate(),DateUtil.YYYY_MM_DD_HH_DD_SS)); } if(StringUtils.isNotEmpty(missionDTO.getEndDate())) { mission.setEndTm(DateUtil.parse(missionDTO.getEndDate(),DateUtil.YYYY_MM_DD_HH_DD_SS)); } missionMapperExt.insert(mission); missionDTO.setId(mission.getId()); return missionDTO; } public void updateMission(MissionDTO missionDTO,String staffCode) { MissionWithBLOBs mission = new MissionWithBLOBs(); BeanUtils.copyProperties(missionDTO, mission); mission.setModifior(staffCode); mission.setModifyTm(new Date()); missionMapperExt.<API key>(mission); } public Pagination<MissionDTO> pageSearch(MissionSearchDTO searchDTO) { Pagination<MissionDTO> pagination = new Pagination<MissionDTO>(searchDTO.getCurrentPage(),searchDTO.getPageSize()); MissionExample example = bulidExample(searchDTO); long count = missionMapperExt.countByExample(example); pagination.setTotalCount((int)count); if(count>0) { List<Mission> newsList= missionMapperExt.<API key>(example, pagination.getOffset(), pagination.getPageSize()); List<MissionDTO> retList = new ArrayList<MissionDTO>(newsList.size()); for (Mission result : newsList) { MissionDTO missionDTO = new MissionDTO(); BeanUtils.copyProperties(result, missionDTO); retList.add(missionDTO); // missionDTO.setCreateDate(DateUtil.toLocaleString(result.getCreateTm(), "YYYY-MM-dd")); if(result.getType()!=null) missionDTO.setTypeCN(MissionTypeEn.toEnum(result.getType().byteValue()).getMean()); } pagination.setList(retList); } return pagination; } public MissionExtendDTO detail(int missionId) { MissionWithBLOBs mission = missionMapperExt.selectByPrimaryKey(missionId); MissionExtendDTO extendDTO = new MissionExtendDTO(); BeanUtils.copyProperties(mission, extendDTO); extendDTO.setTypeCN(MissionTypeEn.toEnum(mission.getType()).getMean()); return extendDTO; } public void remove(int missionId) { missionMapperExt.deleteByPrimaryKey(missionId); } public List<MissionDTO> list(MissionSearchDTO searchDTO) { MissionExample example = bulidExample(searchDTO); List<Mission> list = missionMapperExt.selectByExample(example); List<MissionDTO> retList = new ArrayList<MissionDTO>(list.size()); for (Mission result : list) { MissionDTO missionDTO = new MissionDTO(); BeanUtils.copyProperties(result, missionDTO); missionDTO.setModifyDate(DateUtil.toLocaleString(result.getModifyTm(),DateUtil.YYYY_MM_DD)); if(result.getIpChange()==null?false:true) missionDTO.setIpChangeCn(MissionIpEn.toEnum((byte)1).getMean()); else missionDTO.setIpChangeCn(MissionIpEn.toEnum((byte)0).getMean()); retList.add(missionDTO); } return retList; } private MissionExample bulidExample(MissionSearchDTO searchDTO) { MissionExample example = new MissionExample(); MissionExample.Criteria criteria = example.createCriteria(); if(StringUtils.isNotEmpty(searchDTO.getMissionTitle())) { criteria.andMissionTitleLike("%"+searchDTO.getMissionTitle()+"%"); } if(searchDTO.getStatus()!=null) { // criteria.andstat } if(searchDTO.getType()!=null) { criteria.andTypeEqualTo(searchDTO.getType()); } if(StringUtils.isNotEmpty(searchDTO.getBeginTm())) { criteria.<API key>(DateUtil.parse(searchDTO.getBeginTm(),DateUtil.YYYY_MM_DD_HH_DD_SS)); } if(StringUtils.isNotEmpty(searchDTO.getEndTm())) { criteria.andBeginTmLessThan(DateUtil.parse(searchDTO.getEndTm(),DateUtil.YYYY_MM_DD_HH_DD_SS)); } example.setOrderByClause("begin_tm desc"); return example; } public void createMission(String[][] bodys,MissionExtendDTO missionDTO,String staffCode) { missionDTO = insertMission(missionDTO,staffCode); inserBatch(bodys,missionDTO.getId()); } public void inserBatch(String[][] bodys, int missionId) { List<MissionCode> list = new ArrayList<>(); for(String[] body:bodys) { MissionCode code = new MissionCode(); code.setCode(body[0]); code.setCreateTm(new Date()); code.setMissionId(missionId); code.setStatus(MissionCodeStatusEn.UNUSE.getCode()); list.add(code); } <API key>.insertBatch(list); } public void signNumAdd(Integer id) { missionMapperExt.signNumAdd(id); } }
using System; using System.Runtime.InteropServices; using WhiteMagic.WinAPI.Structures; namespace WhiteMagic.WinAPI { public static class Advapi32 { [DllImport("advapi32.dll", SetLastError = true)] [return: MarshalAs(UnmanagedType.Bool)] public static extern bool OpenProcessToken(IntPtr ProcessHandle, TokenObject DesiredAccess, out IntPtr TokenHandle); [DllImport("advapi32.dll", SetLastError = true, CharSet = CharSet.Auto)] [return: MarshalAs(UnmanagedType.Bool)] public static extern bool <API key>(string lpSystemName, string lpName, out LUID lpLuid); [DllImport("advapi32.dll", SetLastError = true)] [return: MarshalAs(UnmanagedType.Bool)] public static extern bool <API key>(IntPtr TokenHandle, [MarshalAs(UnmanagedType.Bool)]bool <API key>, ref TOKEN_PRIVILEGES NewState, UInt32 Zero, IntPtr Null1, IntPtr Null2); } }
package org.fracturedatlas.athena.plugin.available.web; import java.util.ArrayList; import java.util.List; import org.fracturedatlas.athena.apa.ApaAdapter; import org.fracturedatlas.athena.apa.impl.jpa.PropField; import org.fracturedatlas.athena.apa.impl.jpa.ValueType; import org.fracturedatlas.athena.client.PField; import org.fracturedatlas.athena.client.PTicket; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.context.ApplicationContext; import org.springframework.context.support.<API key>; public abstract class BaseManagerTest { protected ApaAdapter apa; protected ApplicationContext context; protected List<PTicket> ticketsToDelete = new ArrayList<PTicket>(); protected List<PropField> propFieldsToDelete = new ArrayList<PropField>(); Logger logger = LoggerFactory.getLogger(this.getClass().getName()); public BaseManagerTest() { context = new <API key>("<API key>.xml"); apa = (ApaAdapter)context.getBean("apa"); } public PField addPropField(ValueType valueType, String name, Boolean strict) { PropField pf = apa.savePropField(new PropField(valueType, name, strict)); propFieldsToDelete.add(pf); return pf.toClientField(); } public void teardownTickets() { for (PTicket t : ticketsToDelete) { try { apa.deleteRecord(t.getType(), t.getId()); } catch (Exception ignored) { logger.error(ignored.getMessage(), ignored); } } for (PropField pf : propFieldsToDelete) { try { apa.deletePropField(pf); } catch (Exception ignored) { //ignored } } } public PTicket createRecord(String type, String... keyValues) { PTicket t = new PTicket(type); for(int i=0; i < keyValues.length; i+=2) { t.put(keyValues[i], keyValues[i+1]); } return t; } }
package com.berryworks.edireader; public interface TransactionCallback { public void startTransaction(String segmentType); public void endTransaction(); }
package com.harium.keel.cluster.distance; public interface DistanceMeasure { double distance(double[] a, double[] b); }
package org.antlr.runtime.debug; import org.antlr.runtime.<API key>; import org.antlr.runtime.Token; import org.antlr.runtime.BaseRecognizer; import org.antlr.runtime.tree.TreeAdaptor; import java.io.*; import java.net.ServerSocket; import java.net.Socket; /** A proxy debug event listener that forwards events over a socket to * a debugger (or any other listener) using a simple text-based protocol; * one event per line. ANTLRWorks listens on server socket with a * <API key> instance. These two objects must therefore * be kept in sync. New events must be handled on both sides of socket. */ public class <API key> extends <API key> { public static final int <API key> = 49100; // was 49153 protected int port = <API key>; protected ServerSocket serverSocket; protected Socket socket; protected String grammarFileName; protected PrintWriter out; protected BufferedReader in; /** Who am i debugging? */ protected BaseRecognizer recognizer; /** Almost certainly the recognizer will have adaptor set, but * we don't know how to cast it (Parser or TreeParser) to get * the adaptor field. Must be set with a constructor. :( */ protected TreeAdaptor adaptor; public <API key>(BaseRecognizer recognizer, TreeAdaptor adaptor) { this(recognizer, <API key>, adaptor); } public <API key>(BaseRecognizer recognizer, int port, TreeAdaptor adaptor) { this.grammarFileName = recognizer.getGrammarFileName(); this.adaptor = adaptor; this.port = port; } public void handshake() throws IOException { if ( serverSocket==null ) { serverSocket = new ServerSocket(port); socket = serverSocket.accept(); socket.setTcpNoDelay(true); OutputStream os = socket.getOutputStream(); OutputStreamWriter osw = new OutputStreamWriter(os, "UTF8"); out = new PrintWriter(new BufferedWriter(osw)); InputStream is = socket.getInputStream(); InputStreamReader isr = new InputStreamReader(is, "UTF8"); in = new BufferedReader(isr); out.println("ANTLR "+ DebugEventListener.PROTOCOL_VERSION); out.println("grammar \""+ grammarFileName); out.flush(); ack(); } } public void commence() { // don't bother sending event; listener will trigger upon connection } public void terminate() { transmit("terminate"); out.close(); try { socket.close(); } catch (IOException ioe) { ioe.printStackTrace(System.err); } } protected void ack() { try { in.readLine(); } catch (IOException ioe) { ioe.printStackTrace(System.err); } } protected void transmit(String event) { out.println(event); out.flush(); ack(); } public void enterRule(String grammarFileName, String ruleName) { transmit("enterRule\t"+grammarFileName+"\t"+ruleName); } public void enterAlt(int alt) { transmit("enterAlt\t"+alt); } public void exitRule(String grammarFileName, String ruleName) { transmit("exitRule\t"+grammarFileName+"\t"+ruleName); } public void enterSubRule(int decisionNumber) { transmit("enterSubRule\t"+decisionNumber); } public void exitSubRule(int decisionNumber) { transmit("exitSubRule\t"+decisionNumber); } public void enterDecision(int decisionNumber) { transmit("enterDecision\t"+decisionNumber); } public void exitDecision(int decisionNumber) { transmit("exitDecision\t"+decisionNumber); } public void consumeToken(Token t) { String buf = serializeToken(t); transmit("consumeToken\t"+buf); } public void consumeHiddenToken(Token t) { String buf = serializeToken(t); transmit("consumeHiddenToken\t"+buf); } public void LT(int i, Token t) { if(t != null) transmit("LT\t"+i+"\t"+serializeToken(t)); } public void mark(int i) { transmit("mark\t"+i); } public void rewind(int i) { transmit("rewind\t"+i); } public void rewind() { transmit("rewind"); } public void beginBacktrack(int level) { transmit("beginBacktrack\t"+level); } public void endBacktrack(int level, boolean successful) { transmit("endBacktrack\t"+level+"\t"+(successful?TRUE:FALSE)); } public void location(int line, int pos) { transmit("location\t"+line+"\t"+pos); } public void <API key>(<API key> e) { StringBuffer buf = new StringBuffer(50); buf.append("exception\t"); buf.append(e.getClass().getName()); // dump only the data common to all exceptions for now buf.append("\t"); buf.append(e.index); buf.append("\t"); buf.append(e.line); buf.append("\t"); buf.append(e.charPositionInLine); transmit(buf.toString()); } public void beginResync() { transmit("beginResync"); } public void endResync() { transmit("endResync"); } public void semanticPredicate(boolean result, String predicate) { StringBuffer buf = new StringBuffer(50); buf.append("semanticPredicate\t"); buf.append(result); serializeText(buf, predicate); transmit(buf.toString()); } // A S T P a r s i n g E v e n t s public void consumeNode(Object t) { StringBuffer buf = new StringBuffer(50); buf.append("consumeNode"); serializeNode(buf, t); transmit(buf.toString()); } public void LT(int i, Object t) { int ID = adaptor.getUniqueID(t); String text = adaptor.getText(t); int type = adaptor.getType(t); StringBuffer buf = new StringBuffer(50); buf.append("LN\t"); // lookahead node; distinguish from LT in protocol buf.append(i); serializeNode(buf, t); transmit(buf.toString()); } protected void serializeNode(StringBuffer buf, Object t) { int ID = adaptor.getUniqueID(t); String text = adaptor.getText(t); int type = adaptor.getType(t); buf.append("\t"); buf.append(ID); buf.append("\t"); buf.append(type); Token token = adaptor.getToken(t); int line = -1; int pos = -1; if ( token!=null ) { line = token.getLine(); pos = token.<API key>(); } buf.append("\t"); buf.append(line); buf.append("\t"); buf.append(pos); int tokenIndex = adaptor.getTokenStartIndex(t); buf.append("\t"); buf.append(tokenIndex); serializeText(buf, text); } // A S T E v e n t s public void nilNode(Object t) { int ID = adaptor.getUniqueID(t); transmit("nilNode\t"+ID); } public void errorNode(Object t) { int ID = adaptor.getUniqueID(t); String text = t.toString(); StringBuffer buf = new StringBuffer(50); buf.append("errorNode\t"); buf.append(ID); buf.append("\t"); buf.append(Token.INVALID_TOKEN_TYPE); serializeText(buf, text); transmit(buf.toString()); } public void createNode(Object t) { int ID = adaptor.getUniqueID(t); String text = adaptor.getText(t); int type = adaptor.getType(t); StringBuffer buf = new StringBuffer(50); buf.append("<API key>\t"); buf.append(ID); buf.append("\t"); buf.append(type); serializeText(buf, text); transmit(buf.toString()); } public void createNode(Object node, Token token) { int ID = adaptor.getUniqueID(node); int tokenIndex = token.getTokenIndex(); transmit("createNode\t"+ID+"\t"+tokenIndex); } public void becomeRoot(Object newRoot, Object oldRoot) { int newRootID = adaptor.getUniqueID(newRoot); int oldRootID = adaptor.getUniqueID(oldRoot); transmit("becomeRoot\t"+newRootID+"\t"+oldRootID); } public void addChild(Object root, Object child) { int rootID = adaptor.getUniqueID(root); int childID = adaptor.getUniqueID(child); transmit("addChild\t"+rootID+"\t"+childID); } public void setTokenBoundaries(Object t, int tokenStartIndex, int tokenStopIndex) { int ID = adaptor.getUniqueID(t); transmit("setTokenBoundaries\t"+ID+"\t"+tokenStartIndex+"\t"+tokenStopIndex); } // support public void setTreeAdaptor(TreeAdaptor adaptor) { this.adaptor = adaptor; } public TreeAdaptor getTreeAdaptor() { return adaptor; } protected String serializeToken(Token t) { StringBuffer buf = new StringBuffer(50); buf.append(t.getTokenIndex()); buf.append('\t'); buf.append(t.getType()); buf.append('\t'); buf.append(t.getChannel()); buf.append('\t'); buf.append(t.getLine()); buf.append('\t'); buf.append(t.<API key>()); serializeText(buf, t.getText()); return buf.toString(); } protected void serializeText(StringBuffer buf, String text) { buf.append("\t\""); if ( text==null ) { text = ""; } // escape \n and \r all text for token appears to exist on one line // this escape is slow but easy to understand text = escapeNewlines(text); buf.append(text); } protected String escapeNewlines(String txt) { txt = txt.replaceAll("%","%25"); // escape all escape char ;) txt = txt.replaceAll("\n","%0A"); // escape \n txt = txt.replaceAll("\r","%0D"); // escape \r return txt; } }
#include "abstract_link.h" using namespace domain; AbstractLink::AbstractLink(QObject* parent): QObject(parent) {} AbstractLink::~AbstractLink() {}
#ifndef _INPUT_H #define _INPUT_H #include "cmi.h" void inputInit(void); void inputProcess(cmiToken *t); #endif
'use strict'; define(['angular', 'angular-mocks'], function() { describe('the non-conformant measurements table service', function() { var <API key>; var resultsTableService = jasmine.createSpyObj('ResultsTableService', ['createInputColumns']); beforeEach(module('trialverse.results', function($provide) { $provide.value('ResultsTableService', resultsTableService); })); beforeEach(inject(function(<API key>) { <API key> = <API key>; })); describe('<API key>', function() { it('should map results by label and group', function() { var arms = [{ label: 'arm 1', armURI: 'http://arms/arm1' }]; var groups = []; var resultValuesObjects = [{ comment: 'comment1', uri: 'uri 1', armUri: 'http://arms/arm1', instance: 'instance1' }, { comment: 'comment2', uri: 'uri 2', armUri: 'http://arms/arm1', instance: 'instance1' }, { comment: 'comment3', uri: 'uri 3', armUri: 'http://arms/arm1', instance: 'instance1' }]; var expectedResult = { comment1: { 'http://arms/arm1': { group: arms[0], results: [resultValuesObjects[0]] } }, comment2: { 'http://arms/arm1': { group: arms[0], results: [resultValuesObjects[1]] } }, comment3: { 'http://arms/arm1': { group: arms[0], results: [resultValuesObjects[2]] } } }; var result = <API key>.<API key>(arms, groups, resultValuesObjects); expect(result).toEqual(expectedResult); }); }); describe('createInputRows', function() { var resultRows, expectedRow; beforeEach(function() { var arm ={ label: 'arm 1', armURI: 'http://arms/arm1' }; var <API key> = { comment1: { 'http://arms/arm1': { group: arm, results: [{ comment: 'comment1', uri: 'uri 1', armUri: 'http://arms/arm1', instance: 'instance1' }] } }, comment2: { 'http://arms/arm1': { group: arm, results: [{ comment: 'comment2', uri: 'uri 2', armUri: 'http://arms/arm1', instance: 'instance1' }] } }, comment3: { 'http://arms/arm1': { group: arm, results: [{ comment: 'comment3', uri: 'uri 3', armUri: 'http://arms/arm1', instance: 'instance1' }] } } }; var variable = { label: 'foo' }; expectedRow = { variable: variable, group: { 'label': 'arm 1', 'armURI': 'http://arms/arm1' }, label: 'comment1', numberOfGroups: 1, inputColumns: undefined, <API key>: ['instance1'] }; resultRows = <API key>.createInputRows(variable, <API key>); }); it('should build te non-conformant table rows', function() { expect(resultRows.length).toEqual(3); expect(resultRows[0]).toEqual(expectedRow); expect(resultsTableService.createInputColumns).toHaveBeenCalled(); }); }); }); });
/* * dnn_configuration.h * * */ #ifndef <API key> #define <API key> #include <string.h> #include "../external/cJSON.h" #include "../include/list.h" #include "../include/keyValuePair.h" #include "../include/binary.h" #include "acs_info.h" #include "ambr.h" #include "frame_route_info.h" #include "ip_address.h" #include "nidd_information.h" #include "<API key>.h" #include "pdu_session_types.h" #include "ssc_modes.h" #include "<API key>.h" #include "up_security.h" #ifdef __cplusplus extern "C" { #endif typedef struct <API key> <API key>; typedef struct <API key> { struct <API key> *pdu_session_types; struct OpenAPI_ssc_modes_s *ssc_modes; int iwk_eps_ind; struct <API key> *_5g_qos_profile; struct OpenAPI_ambr_s *session_ambr; char *<API key>; OpenAPI_list_t *static_ip_address; struct <API key> *up_security; <API key> <API key>; int <API key>; char *nidd_nef_id; struct <API key> *nidd_info; int <API key>; struct OpenAPI_acs_info_s *acs_info; OpenAPI_list_t *<API key>; OpenAPI_list_t *<API key>; int atsss_allowed; } <API key>; <API key> *<API key>( <API key> *pdu_session_types, OpenAPI_ssc_modes_t *ssc_modes, int iwk_eps_ind, <API key> *_5g_qos_profile, OpenAPI_ambr_t *session_ambr, char *<API key>, OpenAPI_list_t *static_ip_address, <API key> *up_security, <API key> <API key>, int <API key>, char *nidd_nef_id, <API key> *nidd_info, int <API key>, OpenAPI_acs_info_t *acs_info, OpenAPI_list_t *<API key>, OpenAPI_list_t *<API key>, int atsss_allowed ); void <API key>(<API key> *dnn_configuration); <API key> *<API key>(cJSON *<API key>); cJSON *<API key>(<API key> *dnn_configuration); <API key> *<API key>(<API key> *dst, <API key> *src); #ifdef __cplusplus } #endif #endif /* <API key> */
{-# LANGUAGE QuasiQuotes,DataKinds,GADTs,RankNTypes,ScopedTypeVariables,KindSignatures,TemplateHaskell, FlexibleInstances,TypeFamilies #-} module Z3Tutorial where import Language.SMTLib2 import Language.SMTLib2.Pipe (createPipe) import Language.SMTLib2.Debug (debugBackend) import qualified Language.SMTLib2.Internals.Type.List as List import qualified Language.SMTLib2.Internals.Expression as SMT import qualified Language.SMTLib2.Internals.Type as Type import Data.Proxy import Data.GADT.Compare import Data.GADT.Show import Data.Typeable runExample :: (forall b. Backend b => SMT b r) -> IO r runExample ex = withBackend (fmap debugBackend $ createPipe "z3" ["-in","-smt2"]) ex query :: (Backend b) => List Repr tps -> (List (Expr b) tps -> SMT b ()) -> SMT b (Maybe (List Value tps)) query tps f = do args <- List.mapM declareVar tps f args res <- checkSat case res of Sat -> do vals <- List.mapM getValue args return $ Just vals _ -> return Nothing -- | Basic commands example1 :: Backend b => SMT b (Maybe Integer) example1 = do a <- declareVar int f <- declareFun (int ::: bool ::: Nil) int assert $ a .>. cint 10 assert $ fun f (a .:. true .:. nil) .<. cint 100 res <- checkSat case res of Sat -> do IntValue v <- getValue a return $ Just v _ -> return Nothing -- | Using scopes example2 :: Backend b => SMT b (Maybe (Integer,Integer,Integer),Maybe (Integer,Integer,Integer)) example2 = do x <- declareVar int y <- declareVar int z <- declareVar int q1 <- stack $ do x .+. y .==. cint 10 >>= assert x .+. (cint 2 .*. y) .==. cint 20 >>= assert r1 <- checkSat case r1 of Sat -> do IntValue vx <- getValue x IntValue vy <- getValue y IntValue vz <- getValue z return (Just (vx,vy,vz)) _ -> return Nothing q2 <- stack $ do (cint 3 .*. x) .+. y .==. cint 10 >>= assert (cint 2 .*. x) .+. (cint 2 .*. y) .==. cint 21 >>= assert r2 <- checkSat case r2 of Sat -> do IntValue vx <- getValue x IntValue vy <- getValue y IntValue vz <- getValue z return (Just (vx,vy,vz)) _ -> return Nothing return (q1,q2) -- | Propositional Logic example3 :: Backend b => SMT b CheckSatResult example3 = do p <- declareVar bool q <- declareVar bool r <- declareVar bool conjecture <- ((p .=>. q) .&. (q .=>. r)) .=>. (p .=>. r) >>= defineVar not' conjecture >>= assert checkSat -- | Satisfiability and Validity example4 :: Backend b => SMT b CheckSatResult example4 = do a <- declareVarNamed bool "a" b <- declareVarNamed bool "b" demorgan <- (a .&. b) .==. (not' $ (not' a) .|. (not' b)) >>= defineVarNamed "demorgan" not' demorgan >>= assert checkSat -- | Uninterpreted functions and constants example5 :: Backend b => SMT b (Maybe (Integer,Integer)) example5 = do f <- declareFun (int ::: Nil) int a <- declareVar int b <- declareVar int a .>. cint 20 >>= assert b .>. a >>= assert assert $ (fun f (cint 10 .:. nil)) .==. cint 1 r <- checkSat case r of Sat -> do IntValue ra <- getValue a IntValue rb <- getValue b return $ Just (ra,rb) _ -> return Nothing example6 :: Backend b => SMT b (Maybe (List Value '[IntType,IntType,IntType,RealType,RealType])) example6 = query (int ::: int ::: int ::: real ::: real ::: Nil) (\(a ::: b ::: c ::: d ::: e ::: Nil) -> do a .>. b .+. cint 2 >>= assert a .==. (cint 2 .*. c) .+. cint 10 >>= assert c .+. b .<=. cint 1000 >>= assert d .>=. e >>= assert) example7 :: Backend b => SMT b (Maybe (List Value [IntType,IntType,IntType,RealType,RealType])) example7 = query (int ::: int ::: int ::: real ::: real ::: Nil) (\(a ::: b ::: c ::: d ::: e ::: Nil) -> do e .>. toReal (a .+. b) .+. creal 2 >>= assert d .==. toReal c .+. creal 0.5 >>= assert a .>. b >>= assert) example8 :: Backend b => SMT b (Maybe (List Value [RealType,RealType])) example8 = query (real ::: real ::: Nil) (\(b ::: c ::: Nil) -> do mult [b,b,b] .+. (b .*. c) .==. creal 3.0 >>= assert) example9 :: Backend b => SMT b (Maybe (List Value [RealType,RealType,RealType])) example9 = query (real ::: real ::: real ::: Nil) (\(x ::: y ::: z ::: Nil) -> do x .*. x .==. x .*. creal 2 >>= assert x .*. y .==. x >>= assert (y .-. creal 1) .*. z .==. creal 1 >>= assert) example10 :: Backend b => SMT b (Maybe (List Value [IntType,IntType,IntType,IntType,IntType,IntType,IntType,RealType,RealType])) example10 = query (int ::: int ::: int ::: int ::: int ::: int ::: int ::: real ::: real ::: Nil) (\(a ::: r1 ::: r2 ::: r3 ::: r4 ::: r5 ::: r6 ::: b ::: c ::: Nil) -> do a .==. cint 10 >>= assert r1 .==. a `div'` cint 4 >>= assert r2 .==. a `mod'` cint 4 >>= assert r3 .==. a `rem'` cint 4 >>= assert r4 .==. a `div'` cint (-4) >>= assert r5 .==. a `mod'` cint (-4) >>= assert r6 .==. a `rem'` cint (-4) >>= assert b .>=. c ./. creal 3 >>= assert c .>=. creal 20 >>= assert) example11 :: Backend b => SMT b (Maybe (List Value '[BitVecType 64,BitVecType 64])) example11 = query (bitvec (bw Proxy) ::: bitvec (bw Proxy) ::: Nil) (\(x ::: y ::: Nil) -> do not' (bvand (bvnot x) (bvnot y) .==. bvnot (bvor x y)) >>= assert) example13 :: Backend b => SMT b CheckSatResult example13 = do let w = bw (Proxy::Proxy 4) isPowerOfTwo <- defineFunNamed "isPowerOfTwo" (bitvec w ::: Nil) $ \(x ::: Nil) -> cbv 0 w .==. bvand x (bvsub x (cbv 1 w)) a <- declareVarNamed (bitvec w) "a" args <- sequence [ a .==. cbv n w | n <- [0,1,2,4,8]] assert $ not' (fun isPowerOfTwo (a .:. nil) .==. or' args) checkSat example14 :: Backend b => SMT b (Maybe (List Value [BitVecType 8,BitVecType 8])) example14 = query (bitvec (bw Proxy) ::: bitvec (bw Proxy) ::: Nil) $ \(a ::: b ::: Nil) -> do not' (bvule a b .==. bvsle a b) >>= assert example15 :: Backend b => SMT b (Integer,Integer) example15 = do x <- declareVar int y <- declareVar int a1 <- declareVar (array (int ::: Nil) int) select1 a1 x .==. x >>= assert store1 a1 x y .==. a1 >>= assert --not' (x .==. y) >>= assert checkSat IntValue vx <- getValue x IntValue vy <- getValue y return (vx,vy) example16 :: Backend b => SMT b (Integer,Integer,CheckSatResult) example16 = do all1 <- declareVar (array (int ::: Nil) int) a <- declareVar int i <- declareVar int all1 .==. constArray (int ::: Nil) (cint 1) >>= assert a .==. select1 all1 i >>= assert checkSat IntValue va <- getValue a IntValue vi <- getValue i assert $ not' (a .==. cint 1) r <- checkSat return (va,vi,r) -- | Mapping Functions on Arrays example17 :: Backend b => SMT b (CheckSatResult,CheckSatResult,String,CheckSatResult) example17 = do a <- declareVar (array (int ::: Nil) bool) b <- declareVar (array (int ::: Nil) bool) c <- declareVar (array (int ::: Nil) bool) x <- declareVar int r1 <- stack $ do not' (map' (SMT.Logic SMT.And $(nat 2)) (a .:. b .:. nil) .==. (map' SMT.Not ((map' (SMT.Logic SMT.Or $(nat 2)) ((map' SMT.Not (b .:. nil)) .:. (map' SMT.Not (a .:. nil)) .:. nil)) .:. nil))) >>= assert map' SMT.Not (a .:. nil) .==. b >>= assert checkSat r2 <- stack $ do select (map' (SMT.Logic SMT.And $(nat 2)) (a .:. b .:. nil)) (x .:. nil) .&. not' (select a (x .:. nil)) >>= assert checkSat (r3,r4) <- stack $ do select (map' (SMT.Logic SMT.Or $(nat 2)) (a .:. b .:. nil)) (x .:. nil) .&. not' (select a (x .:. nil)) >>= assert p <- checkSat mdl <- getModel not' (select b (x .:. nil)) >>= assert q <- checkSat return (mdl,q) return (r1,r2,show r3,r4) -- | Bags as Arrays example18 :: Backend b => SMT b String example18 = do let a = array (int ::: int ::: Nil) int bagUnion <- defineFunNamed "bag-union" (a ::: a ::: Nil) $ \(x ::: y ::: Nil) -> map' (SMT.Arith Type.NumInt SMT.Plus $(nat 2)) (x .:. y .:. nil) s1 <- declareVarNamed a "s1" s2 <- declareVarNamed a "s2" s3 <- declareVarNamed a "s3" s3 .==. fun bagUnion (s1 .:. s2 .:. nil) >>= assert select s1 (cint 0 .:. cint 0 .:. nil) .==. cint 5 >>= assert select s2 (cint 0 .:. cint 0 .:. nil) .==. cint 3 >>= assert select s2 (cint 1 .:. cint 2 .:. nil) .==. cint 4 >>= assert checkSat fmap show getModel -- Datatypes data Pair par (e :: Type -> *) where MkPair :: e t1 -> e t2 -> Pair '[t1,t2] e instance Type.IsDatatype Pair where type Parameters Pair = 'S ('S 'Z) type Signature Pair = '[ '[ ParameterType Z, ParameterType (S Z) ] ] data Datatype Pair = Pair deriving (Eq,Ord) data Constr Pair sig where ConMkPair :: Type.Constr Pair '[ ParameterType Z, ParameterType (S Z) ] data Field Pair sig where First :: Type.Field Pair (ParameterType Z) Second :: Type.Field Pair (ParameterType (S Z)) datatypeGet (MkPair x y) = (Pair,getType x ::: getType y ::: Nil) parameters _ = Succ (Succ Zero) datatypeName _ = "Pair" constructors Pair = ConMkPair ::: Nil constrName ConMkPair = "MkPair" test _ _ = True fields ConMkPair = First ::: Second ::: Nil construct (_ ::: _ ::: Nil) ConMkPair (x ::: y ::: Nil) = MkPair x y deconstruct (MkPair x y) = Type.ConApp (getType x ::: getType y ::: Nil) ConMkPair (x ::: y ::: Nil) fieldType First = ParameterRepr Zero fieldType Second = ParameterRepr (Succ Zero) fieldName First = "first" fieldName Second = "second" fieldGet (MkPair x _) First = x fieldGet (MkPair _ y) Second = y instance GEq (Type.Constr Pair) where geq ConMkPair ConMkPair = Just Refl instance GCompare (Type.Constr Pair) where gcompare ConMkPair ConMkPair = GEQ instance GEq (Type.Field Pair) where geq First First = Just Refl geq Second Second = Just Refl geq _ _ = Nothing instance GCompare (Type.Field Pair) where gcompare First First = GEQ gcompare First _ = GLT gcompare _ First = GGT gcompare Second Second = GEQ -- | Records example19 :: Backend b => SMT b (Pair '[IntType,IntType] Value,Pair '[IntType,IntType] Value,CheckSatResult) example19 = do let dt = Pair registerDatatype dt p1 <- declareVar (DataRepr dt (int ::: int ::: Nil)) p2 <- declareVar (DataRepr dt (int ::: int ::: Nil)) assert $ p1 .==. p2 assert $ (p1 .#. Second) .>. cint 20 checkSat DataValue v1 <- getValue p1 DataValue v2 <- getValue p2 assert $ not' $ (p1 .#. First) .==. (p2 .#. First) r <- checkSat return (v1,v2,r) data S' (par :: [Type]) (e :: Type -> *) where A :: S' '[] e B :: S' '[] e C :: S' '[] e instance Type.IsDatatype S' where type Parameters S' = 'Z type Signature S' = '[ '[], '[], '[] ] data Datatype S' = S' deriving (Eq,Ord) data Constr S' sig where MkA :: Type.Constr S' '[] MkB :: Type.Constr S' '[] MkC :: Type.Constr S' '[] data Field S' sig datatypeGet A = (S',Nil) datatypeGet B = (S',Nil) datatypeGet C = (S',Nil) parameters _ = Zero datatypeName _ = "S" constructors S' = MkA ::: MkB ::: MkC ::: Nil constrName MkA = "A" constrName MkB = "B" constrName MkC = "C" test A MkA = True test B MkB = True test C MkC = True test _ _ = False fields MkA = Nil fields MkB = Nil fields MkC = Nil construct Nil MkA Nil = A construct Nil MkB Nil = B construct Nil MkC Nil = C deconstruct A = Type.ConApp Nil MkA Nil deconstruct B = Type.ConApp Nil MkB Nil deconstruct C = Type.ConApp Nil MkC Nil fieldName = undefined fieldType = undefined fieldGet = undefined instance GEq (Type.Constr S') where geq MkA MkA = Just Refl geq MkB MkB = Just Refl geq MkC MkC = Just Refl geq _ _ = Nothing instance GCompare (Type.Constr S') where gcompare MkA MkA = GEQ gcompare MkA _ = GLT gcompare _ MkA = GGT gcompare MkB MkB = GEQ gcompare MkB _ = GLT gcompare _ MkB = GGT gcompare MkC MkC = GEQ instance GEq (Type.Field S') where geq = undefined instance GCompare (Type.Field S') where gcompare = undefined -- | Scalars example20 :: Backend b => SMT b (CheckSatResult,CheckSatResult) example20 = do registerDatatype S' x <- declareVarNamed (dt S') "x" y <- declareVarNamed (dt S') "y" z <- declareVarNamed (dt S') "z" u <- declareVarNamed (dt S') "u" assert $ distinct [x,y,z] r1 <- checkSat assert $ distinct [x,y,z,u] r2 <- checkSat return (r1,r2) data Lst (par :: [Type]) e where Nil' :: Repr t -> Lst '[t] e Cons' :: e t -> e (DataType Lst '[t]) -> Lst '[t] e instance Type.IsDatatype Lst where type Parameters Lst = 'S 'Z type Signature Lst = '[ '[], '[ParameterType 'Z,DataType Lst '[ParameterType 'Z] ] ] data Datatype Lst = Lst deriving (Eq,Ord) data Constr Lst sig where MkNil :: Type.Constr Lst '[] MkCons :: Type.Constr Lst '[ParameterType 'Z,DataType Lst '[ParameterType 'Z] ] data Field Lst tp where Hd :: Type.Field Lst (ParameterType 'Z) Tl :: Type.Field Lst (DataType Lst '[ParameterType 'Z]) datatypeGet (Nil' tp) = (Lst,tp ::: Nil) datatypeGet (Cons' e _) = (Lst,getType e ::: Nil) parameters _ = Succ Zero datatypeName _ = "Lst" constructors _ = MkNil ::: MkCons ::: Nil constrName MkNil = "nil" constrName MkCons = "cons" test (Nil' _) MkNil = True test (Cons' _ _) MkCons = True test _ _ = False fields MkNil = Nil fields MkCons = Hd ::: Tl ::: Nil construct (tp ::: Nil) MkNil Nil = Nil' tp construct (tp ::: Nil) MkCons (hd ::: tl ::: Nil) = Cons' hd tl deconstruct (Nil' tp) = Type.ConApp (tp ::: Nil) MkNil Nil deconstruct (Cons' x xs) = Type.ConApp (getType x ::: Nil) MkCons (x ::: xs ::: Nil) fieldName Hd = "hd" fieldName Tl = "tl" fieldType Hd = ParameterRepr Zero fieldType Tl = DataRepr Lst (ParameterRepr Zero ::: Nil) fieldGet (Cons' hd _) Hd = hd fieldGet (Cons' _ tl) Tl = tl instance GEq (Type.Constr Lst) where geq MkNil MkNil = Just Refl geq MkCons MkCons = Just Refl geq _ _ = Nothing instance GCompare (Type.Constr Lst) where gcompare MkNil MkNil = GEQ gcompare MkNil _ = GLT gcompare _ MkNil = GGT gcompare MkCons MkCons = GEQ instance GEq (Type.Field Lst) where geq Hd Hd = Just Refl geq Tl Tl = Just Refl geq _ _ = Nothing instance GCompare (Type.Field Lst) where gcompare Hd Hd = GEQ gcompare Hd _ = GLT gcompare _ Hd = GGT gcompare Tl Tl = GEQ -- | Recursive datatypes example21 :: Backend b => SMT b (CheckSatResult,CheckSatResult) example21 = do registerDatatype Lst l1 <- declareVarNamed (dt' Lst (int ::: Nil)) "l1" l2 <- declareVarNamed (dt' Lst (int ::: Nil)) "l2" l3 <- declareVarNamed (dt' Lst (int ::: Nil)) "l3" x <- declareVarNamed int "x" assert $ not' $ l1 .==. cdt (Nil' int) assert $ not' $ l2 .==. cdt (Nil' int) assert $ (l1 .#. Hd) .==. (l2 .#. Hd) assert $ not' $ l1 .==. l2 assert $ l3 .==. (mk Lst (int ::: Nil) MkCons (x ::: l2 ::: Nil)) assert $ x .>. cint 100 r1 <- checkSat getModel assert $ (l1 .#. Tl) .==. (l2 .#. Tl) r2 <- checkSat return (r1,r2) data Tree par e where Leaf :: Repr t -> Tree '[t] e Node :: e t -> e (DataType TreeList '[t]) -> Tree '[t] e data TreeList par e where TLNil :: Repr t -> TreeList '[t] e TLCons :: e (DataType Tree '[t]) -> e (DataType TreeList '[t]) -> TreeList '[t] e instance Type.IsDatatype Tree where type Parameters Tree = 'S 'Z type Signature Tree = '[ '[], '[ParameterType 'Z,DataType TreeList '[ParameterType 'Z]] ] data Datatype Tree = Tree deriving (Eq,Ord) data Constr Tree sig where MkLeaf :: Type.Constr Tree '[] MkNode :: Type.Constr Tree '[ParameterType 'Z,DataType TreeList '[ParameterType 'Z]] data Field Tree tp where TValue :: Type.Field Tree (ParameterType 'Z) TChildren :: Type.Field Tree (DataType TreeList '[ParameterType 'Z]) datatypeGet (Leaf tp) = (Tree,tp ::: Nil) datatypeGet (Node v _) = (Tree,getType v:::Nil) parameters _ = Succ Zero datatypeName _ = "Tree" constructors _ = MkLeaf ::: MkNode ::: Nil constrName MkLeaf = "leaf" constrName MkNode = "node" test (Leaf _) MkLeaf = True test (Node _ _) MkNode = True test _ _ = False fields MkLeaf = Nil fields MkNode = TValue ::: TChildren ::: Nil construct (tp ::: Nil) MkLeaf Nil = Leaf tp construct (tp ::: Nil) MkNode (v ::: ch ::: Nil) = Node v ch deconstruct (Leaf tp) = Type.ConApp (tp ::: Nil) MkLeaf Nil deconstruct (Node x xs) = Type.ConApp (getType x ::: Nil) MkNode (x:::xs:::Nil) fieldName TValue = "value" fieldName TChildren = "children" fieldType TValue = ParameterRepr Zero fieldType TChildren = DataRepr TreeList (ParameterRepr Zero ::: Nil) fieldGet (Node x _) TValue = x fieldGet (Node _ xs) TChildren = xs instance Type.IsDatatype TreeList where type Parameters TreeList = 'S 'Z type Signature TreeList = '[ '[], '[ DataType Tree '[ParameterType 'Z] , DataType TreeList '[ParameterType 'Z]] ] data Datatype TreeList = TreeList deriving (Eq,Ord) data Constr TreeList sig where MkTLNil :: Type.Constr TreeList '[] MkTLCons :: Type.Constr TreeList '[ DataType Tree '[ParameterType 'Z] , DataType TreeList '[ParameterType 'Z]] data Field TreeList sig where Car :: Type.Field TreeList (DataType Tree '[ParameterType 'Z]) Cdr :: Type.Field TreeList (DataType TreeList '[ParameterType 'Z]) datatypeGet (TLNil tp) = (TreeList,tp:::Nil) datatypeGet (TLCons x _) = case getType x of DataRepr _ (tp:::Nil) -> (TreeList,tp:::Nil) parameters _ = Succ Zero datatypeName _ = "TreeList" constructors _ = MkTLNil ::: MkTLCons ::: Nil constrName MkTLNil = "nil" constrName MkTLCons = "cons" test (TLNil _) MkTLNil = True test (TLCons _ _) MkTLCons = True test _ _ = False fields MkTLNil = Nil fields MkTLCons = Car ::: Cdr ::: Nil construct (tp ::: Nil) MkTLNil Nil = TLNil tp construct (tp ::: Nil) MkTLCons (x:::xs:::Nil) = TLCons x xs deconstruct (TLNil tp) = Type.ConApp (tp:::Nil) MkTLNil Nil deconstruct (TLCons x xs) = case getType x of DataRepr _ (tp:::Nil) -> Type.ConApp (tp:::Nil) MkTLCons (x:::xs:::Nil) fieldName Car = "car" fieldName Cdr = "cdr" fieldType Car = DataRepr Tree (ParameterRepr Zero:::Nil) fieldType Cdr = DataRepr TreeList (ParameterRepr Zero:::Nil) fieldGet (TLCons x _) Car = x fieldGet (TLCons _ xs) Cdr = xs instance GEq (Type.Constr Tree) where geq MkLeaf MkLeaf = Just Refl geq MkNode MkNode = Just Refl geq _ _ = Nothing instance GEq (Type.Constr TreeList) where geq MkTLNil MkTLNil = Just Refl geq MkTLCons MkTLCons = Just Refl geq _ _ = Nothing instance GCompare (Type.Constr Tree) where gcompare MkLeaf MkLeaf = GEQ gcompare MkLeaf _ = GLT gcompare _ MkLeaf = GGT gcompare MkNode MkNode = GEQ instance GCompare (Type.Constr TreeList) where gcompare MkTLNil MkTLNil = GEQ gcompare MkTLNil _ = GLT gcompare _ MkTLNil = GGT gcompare MkTLCons MkTLCons = GEQ instance GEq (Type.Field Tree) where geq TValue TValue = Just Refl geq TChildren TChildren = Just Refl geq _ _ = Nothing instance GEq (Type.Field TreeList) where geq Car Car = Just Refl geq Cdr Cdr = Just Refl geq _ _ = Nothing instance GCompare (Type.Field Tree) where gcompare TValue TValue = GEQ gcompare TValue _ = GLT gcompare _ TValue = GGT gcompare TChildren TChildren = GEQ instance GCompare (Type.Field TreeList) where gcompare Car Car = GEQ gcompare Car _ = GLT gcompare _ Car = GGT gcompare Cdr Cdr = GEQ -- | Mutually recursive datatypes example22 :: Backend b => SMT b (CheckSatResult) example22 = do registerDatatype Tree t1 <- declareVarNamed (dt' Tree (int:::Nil)) "t1" t2 <- declareVarNamed (dt' Tree (bool:::Nil)) "t2" assert $ not' $ t1 .==. cdt (Leaf int) assert $ (t1 .#. TValue) .>. cint 20 assert $ not' $ is t2 MkLeaf assert $ not' $ t2 .#. TValue r <- checkSat getModel return r
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations class Migration(migrations.Migration): dependencies = [ ('search', '<API key>'), ] operations = [ migrations.AddField( model_name='searchquery', name='scope', field=models.IntegerField(default=0), preserve_default=True, ), ]
require 'spec_helper' describe 'mediawiki::files', :type => :define do let(:pre_condition) do 'include apache' end context 'using default parameters on Debian' do let(:facts) do { # the module concat needs this. Normaly set by concat through pluginsync :concat_basedir => '/tmp/concatdir', :osfamily => 'Debian', :operatingsystem => 'Debian', :<API key> => '6', 'apache::params::user' => 'foobar', } end let(:params) do { :target_dir => '/usr/share/mediawiki' } end let(:title) do '/etc/mediawiki/dummy_instance/api.php' end it { should contain_file('/etc/mediawiki/dummy_instance/api.php').with( 'ensure' => 'link', 'path' => '/etc/mediawiki/dummy_instance/api.php', 'owner' => 'www-data', 'group' => 'www-data', 'mode' => '0755', 'target' => '/usr/share/mediawiki/api.php' ) } end end
/* ///////////////////////////////////////////////////////////////////////////// // Calculates moments for ALL objects in an image in one pass; replacement for // mb_imgmoments called in mb_imgfeatures, where mb_imgmoments calculates // moments for one object per call (requires an image containing 1 object only // // [M00, M10, M01, OBJS] = gp_moments_1(IMAGE, LABELLED_IMAGE) // where: // -M00, M10, M01 are 1xnum_of_objects matrices containing moments for each // object // -OBJS is a 1xnum_of_objects matrix containing the size of each object // -IMAGE is an image of type UINT8 containing N objects // -LABELLED_IMAGE is a matrix with size==IMAGE, of type INT32, generated // by BWLABEL(IMAGE) after binarization of IMAGE // // 08-Aug-01 G. Porreca // ///////////////////////////////////////////////////////////////////////////// */ #include "mex.h" void mexFunction(int nlhs, /* number of pointers to return args */ mxArray *plhs[], /*vector of pointers to return args */ int nrhs, /*number of pointers to input args */ const mxArray *prhs[]){ /*vector of pointers to input args */ /*INPUT ARGUMENTS */ int *image; /* original image */ int *labeled; /* labeled object image */ /*OUTPUT ARGUMENTS */ double *a; /* moment00 */ double *b; /* moment10 (X) */ double *c; /* moment01 (Y) */ double *d; /* object sizes */ /* LOCAL VARIABLES */ int f, index, yrows, xcols, moment_length ; /* perform type checking on input matrices */ if( !mxIsInt32( prhs[0])) mexErrMsgTxt("Input IMAGE must be of class int32"); image = (int*) mxGetData( prhs[0]); if( !mxIsInt32( prhs[1])) mexErrMsgTxt("Input LABELLED IMAGE must be of class int32"); labeled = (int*) mxGetData( prhs[1]); /* size of input image (and labeled image) */ yrows = mxGetM(prhs[0]); xcols = mxGetN(prhs[0]); /* size of output moment matrices (num_of_objects) */ moment_length = number_of_objects(labeled, xcols, yrows); /* assign mxArrays to output arguments */ plhs[0] = <API key>(1,moment_length, mxREAL); plhs[1] = <API key>(1,moment_length, mxREAL); plhs[2] = <API key>(1,moment_length, mxREAL); plhs[3] = <API key>(1,moment_length, mxREAL); /* get C pointers to output arguments */ a = mxGetPr(plhs[0]); b = mxGetPr(plhs[1]); c = mxGetPr(plhs[2]); d = mxGetPr(plhs[3]); /* calculate moments and object sizes */ f = calc_Moments(image, labeled, xcols, yrows, moment_length, a, b, c, d); } /*end mexFunction(...) */ /* determine the number of objects in the labeled image; i.e. the object with the highest number + 1 (object[0:N-1], num_of_objs[1:N]) */ int number_of_objects(int *label, /* labeled object image */ int xcols, /* number of columns in image */ int yrows){ /* number of rows in image */ int i, j, index=0, high; for(i = 0; i < xcols; i++){ for(j = 0; j < yrows; j++){ if( *(label + index) > high){ high = *(label + index); } index++; } /* end for j */ } /* end for i */ return high + 1; } /* end number_of_objects(...) */ /* calculate the moments for each object in the image in one pass */ int calc_Moments(int *img, /* original image */ int *labl, /* labeled object image*/ int xcols, /* number of columns in img*/ int yrows, /* number of rows in img*/ int num_objs, /* number of objects (1:N) in img*/ double *a, /* moment00 */ double *b, /* moment10 (X)*/ double *c, /* moment01 (Y)*/ double *d){ /* object sizes*/ int i, index=0, j, moment_index; /*return arrays will be incremented below; initialize them*/ for(i = 0; i < num_objs; i++){ *(a + i) = 0; *(b + i) = 0; *(c + i) = 0; *(d + i) = 0; } /*end for i*/ /*iterate on the number of pixels*/ for(i = 0; i < xcols; i++){ for(j = 0; j < yrows; j++){ index = (i * yrows) + j; moment_index = *(labl + index); /*sum of fluorescence for the current object*/ *(a + moment_index) = *(a + moment_index) + *(img + index); /* X-weighted sum of fluorescence (i) for the current object*/ *(b + moment_index) = *(b + moment_index) + (*(img + index) * (i+1)); /* Y-weighted sum of fluorescence (j) for the current object*/ *(c + moment_index) = *(c + moment_index) + (*(img + index) * (j+1)); /*increment the number of pixels (size) for the current object*/ *(d + moment_index) = *(d + moment_index) + 1; } /*end for j*/ } /*end for i*/ return 0; } /*end calcMoments(...) */
<?php ?> <?php if (isset($_POST['do'])) { $sbnc->Call('eraselog'); $errorIsset = 1; $errorType = 'success'; $errorMessage = $lang['user_log_erased']; } $log = $sbnc->Call('getlog', array("0", "999")); //Checks for the log, to make it all look nice, and give no errors if (is_a($log, 'itype_exception')) { $logState = "empty"; $logString = "<div class=\"mid\"><b>" . $lang['user_log_empty'] . ".</b></div>"; } else { if (count($log) == 0) { $logState = "empty"; $logString = "<div class=\"mid\"><b>" . $lang['user_log_empty'] . ".</b></div>"; } else { $logString = $log; } } //Set data if (!empty($errorIsset)) { $data->assign('errorSet', $errorIsset); $data->assign('errorType', $errorType); $data->assign('errorMessage', $errorMessage); } $data->assign('logState', $logState); $data->assign('logString', $logString); $data->assign('submitValue', $lang['user_log_erase']); //Output the page $data->assign('header', $dwoo->get(new Dwoo_Template_File('template/' . $template . '/header.html'), $data)); $data->assign('footer', $dwoo->get(new Dwoo_Template_File('template/' . $template . '/footer.html'), $data)); $dwoo->output(new Dwoo_Template_File('template/' . $template . '/log.html'), $data); ?>
package pl.marjusz; import java.util.concurrent.locks.ReentrantLock; public class Main { public static void main(String[] args) { BankAccount account = new BankAccount(1000.0,"12345-678"); new Thread(()->{account.deposit(300); account.withdraw(50); account.printAccountNumber();}).start(); new Thread(()->{account.deposit(203.75); account.withdraw(100); account.printAccountNumber();}).start(); } }
#include "config.h" #include <string.h> #include <gegl.h> #include "libgimpmath/gimpmath.h" #include "paint-types.h" #include "base/boundary.h" #include "base/pixel-region.h" #include "base/temp-buf.h" #include "paint-funcs/paint-funcs.h" #include "core/gimpbrush.h" #include "core/gimpbrushgenerated.h" #include "core/gimpdrawable.h" #include "core/gimpdynamics.h" #include "core/gimpdynamicsoutput.h" #include "core/gimperror.h" #include "core/gimpimage.h" #include "core/gimpmarshal.h" #include "core/gimpbrush-transform.h" #include "gimpbrushcore.h" #include "<API key>.h" #include "gimppaintoptions.h" #include "gimp-intl.h" #define EPSILON 0.00001 enum { SET_BRUSH, SET_DYNAMICS, LAST_SIGNAL }; /* local function prototypes */ static void <API key> (GObject *object); static gboolean <API key> (GimpPaintCore *core, GimpDrawable *drawable, GimpPaintOptions *paint_options, const GimpCoords *coords, GError **error); static gboolean <API key> (GimpPaintCore *core, GimpDrawable *drawable, GimpPaintOptions *paint_options, GimpPaintState paint_state, guint32 time); static void <API key> (GimpPaintCore *core, GimpDrawable *drawable, GimpPaintOptions *paint_options, GimpPaintState paint_state, guint32 time); static void <API key> (GimpPaintCore *core, GimpDrawable *drawable, GimpPaintOptions *paint_options, guint32 time); static TempBuf *<API key> (GimpPaintCore *paint_core, GimpDrawable *drawable, GimpPaintOptions *paint_options, const GimpCoords *coords); static void <API key> (GimpBrushCore *core, GimpBrush *brush); static void <API key> (GimpBrushCore *core, GimpDynamics *dynamics); static inline void rotate_pointers (gulong **p, guint32 n); static TempBuf * <API key> (GimpBrushCore *core, TempBuf *mask, gdouble x, gdouble y); static TempBuf * <API key> (GimpBrushCore *core, TempBuf *brush_mask, gdouble x, gdouble y, gdouble pressure); static TempBuf * <API key> (GimpBrushCore *core, TempBuf *brush_mask, gdouble x, gdouble y); static TempBuf * <API key> (GimpBrushCore *core, GimpBrush *brush); static TempBuf * <API key> (GimpBrushCore *core, GimpBrush *brush); static void <API key> (GimpBrush *brush, GimpBrushCore *core); /* brush pipe utility functions */ static void <API key> (GimpImage *dest, GimpDrawable *drawable, TempBuf *pixmap_mask, TempBuf *brush_mask, guchar *d, gint x, gint y, gint bytes, gint width, <API key> mode); G_DEFINE_TYPE (GimpBrushCore, gimp_brush_core, <API key>) #define parent_class <API key> static guint core_signals[LAST_SIGNAL] = { 0, }; static void <API key> (GimpBrushCoreClass *klass) { GObjectClass *object_class = G_OBJECT_CLASS (klass); GimpPaintCoreClass *paint_core_class = <API key> (klass); core_signals[SET_BRUSH] = g_signal_new ("set-brush", G_TYPE_FROM_CLASS (klass), G_SIGNAL_RUN_LAST, G_STRUCT_OFFSET (GimpBrushCoreClass, set_brush), NULL, NULL, <API key>, G_TYPE_NONE, 1, GIMP_TYPE_BRUSH); core_signals[SET_DYNAMICS] = g_signal_new ("set-dynamics", G_TYPE_FROM_CLASS (klass), G_SIGNAL_RUN_LAST, G_STRUCT_OFFSET (GimpBrushCoreClass, set_dynamics), NULL, NULL, <API key>, G_TYPE_NONE, 1, GIMP_TYPE_DYNAMICS); object_class->finalize = <API key>; paint_core_class->start = <API key>; paint_core_class->pre_paint = <API key>; paint_core_class->post_paint = <API key>; paint_core_class->interpolate = <API key>; paint_core_class->get_paint_area = <API key>; klass-><API key> = FALSE; klass-><API key> = TRUE; klass-><API key> = TRUE; klass->set_brush = <API key>; klass->set_dynamics = <API key>; } static void <API key> (GimpBrushCore *core) { gint i, j; core->main_brush = NULL; core->brush = NULL; core->dynamics = NULL; core->spacing = 1.0; core->scale = 1.0; core->angle = 1.0; core->hardness = 1.0; core->force = 1.0; core->pressure_brush = NULL; core->last_solid_brush = NULL; core->solid_cache_invalid = FALSE; core->transform_brush = NULL; core-><API key> = NULL; core-><API key> = 0; core-><API key> = 0; core->last_scale = 1.0; core->transform_pixmap = NULL; core-><API key> = NULL; core-><API key> = 0; core-><API key> = 0; core->last_brush_mask = NULL; core->cache_invalid = FALSE; core->rand = g_rand_new (); core->brush_bound_segs = NULL; core->n_brush_bound_segs = 0; core->brush_bound_width = 0; core->brush_bound_height = 0; for (i = 0; i < <API key>; i++) { for (j = 0; j < <API key>; j++) { core->solid_brushes[i][j] = NULL; } } for (i = 0; i < <API key> - 1; ++i) { core->jitter_lut_y[i] = cos (gimp_deg_to_rad (i * 360 / <API key>)); core->jitter_lut_x[i] = sin (gimp_deg_to_rad (i * 360 / <API key>)); } g_assert (<API key> == KERNEL_SUBSAMPLE); for (i = 0; i < KERNEL_SUBSAMPLE + 1; i++) { for (j = 0; j < KERNEL_SUBSAMPLE + 1; j++) { core->kernel_brushes[i][j] = NULL; } } } static void <API key> (GObject *object) { GimpBrushCore *core = GIMP_BRUSH_CORE (object); gint i, j; if (core->pressure_brush) { temp_buf_free (core->pressure_brush); core->pressure_brush = NULL; } for (i = 0; i < <API key>; i++) for (j = 0; j < <API key>; j++) if (core->solid_brushes[i][j]) { temp_buf_free (core->solid_brushes[i][j]); core->solid_brushes[i][j] = NULL; } if (core->transform_brush) { temp_buf_free (core->transform_brush); core->transform_brush = NULL; } if (core->transform_pixmap) { temp_buf_free (core->transform_pixmap); core->transform_pixmap = NULL; } if (core->rand) { g_rand_free (core->rand); core->rand = NULL; } for (i = 0; i < KERNEL_SUBSAMPLE + 1; i++) for (j = 0; j < KERNEL_SUBSAMPLE + 1; j++) if (core->kernel_brushes[i][j]) { temp_buf_free (core->kernel_brushes[i][j]); core->kernel_brushes[i][j] = NULL; } if (core->main_brush) { <API key> (core->main_brush, <API key>, core); g_object_unref (core->main_brush); core->main_brush = NULL; } if (core->dynamics) { g_object_unref (core->dynamics); core->dynamics = NULL; } if (core->brush_bound_segs) { g_free (core->brush_bound_segs); core->brush_bound_segs = NULL; core->n_brush_bound_segs = 0; core->brush_bound_width = 0; core->brush_bound_height = 0; } G_OBJECT_CLASS (parent_class)->finalize (object); } static gboolean <API key> (GimpPaintCore *paint_core, GimpDrawable *drawable, GimpPaintOptions *paint_options, GimpPaintState paint_state, guint32 time) { GimpBrushCore *core = GIMP_BRUSH_CORE (paint_core); if (paint_state == <API key>) { GimpCoords last_coords; GimpCoords current_coords; gdouble scale; <API key> (paint_core, &last_coords); <API key> (paint_core, &current_coords); /* If we current point == last point, check if the brush * wants to be painted in that case. (Direction dependent * pixmap brush pipes don't, as they don't know which * pixmap to select.) */ if (last_coords.x == current_coords.x && last_coords.y == current_coords.y && ! <API key> (core->main_brush, &last_coords, &current_coords)) { return FALSE; } /*No drawing anything if the scale is too small*/ if (<API key> (core)-><API key>) { GimpImage *image = gimp_item_get_image (GIMP_ITEM (drawable)); gdouble fade_point; if (<API key> (core)-><API key>) { fade_point = <API key> (paint_options, image, paint_core->pixel_dist); scale = paint_options->brush_size / MAX (core->main_brush->mask->width, core->main_brush->mask->height) * <API key> (core->dynamics->size_output, &current_coords, paint_options, fade_point); if (scale < 0.0001) return FALSE; } } if (<API key> (paint_core)-><API key>) { core->brush = <API key> (core->main_brush, &last_coords, &current_coords); } } return TRUE; } static void <API key> (GimpPaintCore *paint_core, GimpDrawable *drawable, GimpPaintOptions *paint_options, GimpPaintState paint_state, guint32 time) { GimpBrushCore *core = GIMP_BRUSH_CORE (paint_core); if (paint_state == <API key>) { core->brush = core->main_brush; } } static gboolean <API key> (GimpPaintCore *paint_core, GimpDrawable *drawable, GimpPaintOptions *paint_options, const GimpCoords *coords, GError **error) { GimpBrushCore *core = GIMP_BRUSH_CORE (paint_core); GimpBrush *brush; GimpDynamics *dynamics; brush = <API key> (GIMP_CONTEXT (paint_options)); if (core->main_brush != brush) <API key> (core, brush); dynamics = <API key> (GIMP_CONTEXT (paint_options)); if (core->dynamics != dynamics) <API key> (core, dynamics); if (! core->main_brush) { g_set_error_literal (error, GIMP_ERROR, GIMP_FAILED, _("No brushes available for use with this tool.")); return FALSE; } if (! core->dynamics) { g_set_error_literal (error, GIMP_ERROR, GIMP_FAILED, _("No paint dynamics available for use with this tool.")); return FALSE; } if (<API key> (core)-><API key>) { <API key> (paint_core, drawable, paint_options, coords); } core->spacing = (gdouble) <API key> (core->main_brush) / 100.0; core->brush = core->main_brush; core->jitter = <API key> (paint_options, gimp_item_get_image (GIMP_ITEM (drawable))); return TRUE; } /** * <API key> * @x: points to a gdouble * * Adjusts *x such that it is not too close to an integer. This is used * for decision algorithms that would be vulnerable to rounding glitches * if exact integers were input. * * Side effects: Changes the value of *x **/ static void <API key> (gdouble *x) { const gdouble integral = floor (*x); const gdouble fractional = *x - integral; if (fractional < EPSILON) { *x = integral + EPSILON; } else if (fractional > (1 -EPSILON)) { *x = integral + (1 - EPSILON); } } static void <API key> (GimpPaintCore *paint_core, GimpDrawable *drawable, GimpPaintOptions *paint_options, guint32 time) { GimpBrushCore *core = GIMP_BRUSH_CORE (paint_core); GimpImage *image = gimp_item_get_image (GIMP_ITEM (drawable)); GimpCoords last_coords; GimpCoords current_coords; GimpVector2 delta_vec; gdouble delta_pressure; gdouble delta_xtilt, delta_ytilt; gdouble delta_wheel; gdouble delta_velocity; gdouble temp_direction; GimpVector2 temp_vec; gint n, num_points; gdouble t0, dt, tn; gdouble st_factor, st_offset; gdouble initial; gdouble dist; gdouble total; gdouble pixel_dist; gdouble pixel_initial; gdouble xd, yd; gdouble mag; gdouble dyn_spacing = core->spacing; gdouble fade_point; gboolean use_dyn_spacing; g_return_if_fail (GIMP_IS_BRUSH (core->brush)); <API key> (paint_core, &last_coords); <API key> (paint_core, &current_coords); /*Zero sized brushes are unfit for interpolate, * so we just let paint core fail onits own **/ if (core->scale == 0.0) { <API key> (paint_core, &current_coords); <API key> (paint_core, drawable, paint_options, <API key>, time); return; } fade_point = <API key> (paint_options, image, paint_core->pixel_dist); use_dyn_spacing = <API key> (core->dynamics->spacing_output); if (use_dyn_spacing) { dyn_spacing = <API key> (core->dynamics->spacing_output, &current_coords, paint_options, fade_point); /* Dynamic spacing assumes that the value set in core is the min * value and the max is full 200% spacing. This approach differs * from the usual factor from user input approach because making * spacing smaller than the nominal value is unlikely and * spacing has a hard defined max. */ dyn_spacing = (core->spacing + ((2.0 - core->spacing) * ( 1.0 - dyn_spacing))); /* Limiting spacing to minimum 1% */ dyn_spacing = MAX (core->spacing, dyn_spacing); } <API key> (&last_coords.x); <API key> (&last_coords.y); <API key> (&current_coords.x); <API key> (&current_coords.y); delta_vec.x = current_coords.x - last_coords.x; delta_vec.y = current_coords.y - last_coords.y; delta_pressure = current_coords.pressure - last_coords.pressure; delta_xtilt = current_coords.xtilt - last_coords.xtilt; delta_ytilt = current_coords.ytilt - last_coords.ytilt; delta_wheel = current_coords.wheel - last_coords.wheel; delta_velocity = current_coords.velocity - last_coords.velocity; temp_direction = current_coords.direction; /* return if there has been no motion */ if (! delta_vec.x && ! delta_vec.y && ! delta_pressure && ! delta_xtilt && ! delta_ytilt && ! delta_wheel && ! delta_velocity) return; /* calculate the distance traveled in the coordinate space of the brush */ temp_vec = core->brush->x_axis; gimp_vector2_mul (&temp_vec, core->scale); mag = gimp_vector2_length (&temp_vec); xd = <API key> (&delta_vec, &temp_vec) / (mag * mag); temp_vec = core->brush->y_axis; gimp_vector2_mul (&temp_vec, core->scale); mag = gimp_vector2_length (&temp_vec); yd = <API key> (&delta_vec, &temp_vec) / (mag * mag); dist = 0.5 * sqrt (xd * xd + yd * yd); total = dist + paint_core->distance; initial = paint_core->distance; pixel_dist = gimp_vector2_length (&delta_vec); pixel_initial = paint_core->pixel_dist; if (delta_vec.x * delta_vec.x > delta_vec.y * delta_vec.y) { st_factor = delta_vec.x; st_offset = last_coords.x - 0.5; } else { st_factor = delta_vec.y; st_offset = last_coords.y - 0.5; } if (use_dyn_spacing) { gint s0; num_points = dist / dyn_spacing; s0 = (gint) floor (st_offset + 0.5); t0 = (s0 - st_offset) / st_factor; dt = dyn_spacing / dist; if (num_points == 0) return; } else if (fabs (st_factor) > dist / core->spacing) { /* The stripe principle leads to brush positions that are spaced * *closer* than the official brush spacing. Use the official * spacing instead. This is the common case when the brush spacing * is large. * The net effect is then to put a lower bound on the spacing, but * one that varies with the slope of the line. This is suppose to * make thin lines (say, with a 1x1 brush) prettier while leaving * lines with larger brush spacing as they used to look in 1.2.x. */ dt = core->spacing / dist; n = (gint) (initial / core->spacing + 1.0 + EPSILON); t0 = (n * core->spacing - initial) / dist; num_points = 1 + (gint) floor ((1 + EPSILON - t0) / dt); /* if we arnt going to paint anything this time and the brush * has only moved on one axis return without updating the brush * position, distance etc. so that we can more accurately space * brush strokes when curves are supplied to us in single pixel * chunks. */ if (num_points == 0 && (delta_vec.x == 0 || delta_vec.y == 0)) return; } else if (fabs (st_factor) < EPSILON) { /* Hm, we've hardly moved at all. Don't draw anything, but reset the * old coordinates and hope we've gone longer the next time... */ current_coords.x = last_coords.x; current_coords.y = last_coords.y; <API key> (paint_core, &current_coords); /* ... but go along with the current pressure, tilt and wheel */ return; } else { gint direction = st_factor > 0 ? 1 : -1; gint x, y; gint s0, sn; /* Choose the first and last stripe to paint. * FIRST PRIORITY is to avoid gaps painting with a 1x1 aliasing * brush when a horizontalish line segment follows a verticalish * one or vice versa - no matter what the angle between the two * lines is. This will also limit the local thinning that a 1x1 * subsampled brush may suffer in the same situation. * SECOND PRIORITY is to avoid making free-hand drawings * unpleasantly fat by plotting redundant points. * These are achieved by the following rules, but it is a little * tricky to see just why. Do not change this algorithm unless you * are sure you know what you're doing! */ /* Basic case: round the beginning and ending point to nearest * stripe center. */ s0 = (gint) floor (st_offset + 0.5); sn = (gint) floor (st_offset + st_factor + 0.5); t0 = (s0 - st_offset) / st_factor; tn = (sn - st_offset) / st_factor; x = (gint) floor (last_coords.x + t0 * delta_vec.x); y = (gint) floor (last_coords.y + t0 * delta_vec.y); if (t0 < 0.0 && !( x == (gint) floor (last_coords.x) && y == (gint) floor (last_coords.y) )) { /* Exception A: If the first stripe's brush position is * EXTRApolated into a different pixel square than the * ideal starting point, dont't plot it. */ s0 += direction; } else if (x == (gint) floor (paint_core->last_paint.x) && y == (gint) floor (paint_core->last_paint.y)) { /* Exception B: If first stripe's brush position is within the * same pixel square as the last plot of the previous line, * don't plot it either. */ s0 += direction; } x = (gint) floor (last_coords.x + tn * delta_vec.x); y = (gint) floor (last_coords.y + tn * delta_vec.y); if (tn > 1.0 && !( x == (gint) floor (current_coords.x) && y == (gint) floor (current_coords.y))) { /* Exception C: If the last stripe's brush position is * EXTRApolated into a different pixel square than the * ideal ending point, don't plot it. */ sn -= direction; } t0 = (s0 - st_offset) / st_factor; tn = (sn - st_offset) / st_factor; dt = direction * 1.0 / st_factor; num_points = 1 + direction * (sn - s0); if (num_points >= 1) { /* Hack the reported total distance such that it looks to the * next line as if the the last pixel plotted were at an integer * multiple of the brush spacing. This helps prevent artifacts * for connected lines when the brush spacing is such that some * slopes will use the stripe regime and other slopes will use * the nominal brush spacing. */ if (tn < 1) total = initial + tn * dist; total = core->spacing * (gint) (total / core->spacing + 0.5); total += (1.0 - tn) * dist; } } for (n = 0; n < num_points; n++) { gdouble t = t0 + n * dt; gdouble p = (gdouble) n / num_points; current_coords.x = last_coords.x + t * delta_vec.x; current_coords.y = last_coords.y + t * delta_vec.y; current_coords.pressure = last_coords.pressure + p * delta_pressure; current_coords.xtilt = last_coords.xtilt + p * delta_xtilt; current_coords.ytilt = last_coords.ytilt + p * delta_ytilt; current_coords.wheel = last_coords.wheel + p * delta_wheel; current_coords.velocity = last_coords.velocity + p * delta_velocity; current_coords.direction = temp_direction; if (core->jitter > 0.0) { gdouble dyn_jitter; gdouble jitter_dist; gint32 jitter_angle; dyn_jitter = core->jitter * <API key> (core->dynamics->jitter_output, &current_coords, paint_options, fade_point); jitter_dist = g_rand_double_range (core->rand, 0, dyn_jitter); jitter_angle = g_rand_int_range (core->rand, 0, <API key>); current_coords.x += (core->brush->x_axis.x + core->brush->y_axis.x) * jitter_dist * core->jitter_lut_x[jitter_angle] * core->scale; current_coords.y += (core->brush->y_axis.y + core->brush->x_axis.y) * jitter_dist * core->jitter_lut_y[jitter_angle] * core->scale; } <API key> (paint_core, &current_coords); paint_core->distance = initial + t * dist; paint_core->pixel_dist = pixel_initial + t * pixel_dist; <API key> (paint_core, drawable, paint_options, <API key>, time); } current_coords.x = last_coords.x + delta_vec.x; current_coords.y = last_coords.y + delta_vec.y; current_coords.pressure = last_coords.pressure + delta_pressure; current_coords.xtilt = last_coords.xtilt + delta_xtilt; current_coords.ytilt = last_coords.ytilt + delta_ytilt; current_coords.wheel = last_coords.wheel + delta_wheel; current_coords.velocity = last_coords.velocity + delta_velocity; <API key> (paint_core, &current_coords); <API key> (paint_core, &current_coords); paint_core->distance = total; paint_core->pixel_dist = pixel_initial + pixel_dist; } static TempBuf * <API key> (GimpPaintCore *paint_core, GimpDrawable *drawable, GimpPaintOptions *paint_options, const GimpCoords *coords) { GimpBrushCore *core = GIMP_BRUSH_CORE (paint_core); gint x, y; gint x1, y1, x2, y2; gint drawable_width, drawable_height; gint brush_width, brush_height; if (<API key> (core)-><API key>) { <API key> (paint_core, drawable, paint_options, coords); } core->scale = <API key> (core->main_brush, core->scale); <API key> (core->brush, core->scale, core->aspect_ratio, core->angle, &brush_width, &brush_height); /* adjust the x and y coordinates to the upper left corner of the brush */ x = (gint) floor (coords->x) - (brush_width / 2); y = (gint) floor (coords->y) - (brush_height / 2); drawable_width = gimp_item_get_width (GIMP_ITEM (drawable)); drawable_height = <API key> (GIMP_ITEM (drawable)); x1 = CLAMP (x - 1, 0, drawable_width); y1 = CLAMP (y - 1, 0, drawable_height); x2 = CLAMP (x + brush_width + 1, 0, drawable_width); y2 = CLAMP (y + brush_height + 1, 0, drawable_height); /* configure the canvas buffer */ if ((x2 - x1) && (y2 - y1)) { gint bytes; bytes = <API key> (drawable); paint_core->canvas_buf = temp_buf_resize (paint_core->canvas_buf, bytes, x1, y1, (x2 - x1), (y2 - y1)); return paint_core->canvas_buf; } return NULL; } static void <API key> (GimpBrushCore *core, GimpBrush *brush) { if (core->main_brush) { <API key> (core->main_brush, <API key>, core); g_object_unref (core->main_brush); core->main_brush = NULL; } if (core->brush_bound_segs) { g_free (core->brush_bound_segs); core->brush_bound_segs = NULL; core->n_brush_bound_segs = 0; core->brush_bound_width = 0; core->brush_bound_height = 0; } core->main_brush = brush; if (core->main_brush) { g_object_ref (core->main_brush); g_signal_connect (core->main_brush, "invalidate-preview", G_CALLBACK (<API key>), core); } } static void <API key> (GimpBrushCore *core, GimpDynamics *dynamics) { if (core->dynamics) g_object_unref (core->dynamics); core->dynamics = dynamics; if (core->dynamics) g_object_ref (core->dynamics); } void <API key> (GimpBrushCore *core, GimpBrush *brush) { g_return_if_fail (GIMP_IS_BRUSH_CORE (core)); g_return_if_fail (brush == NULL || GIMP_IS_BRUSH (brush)); g_signal_emit (core, core_signals[SET_BRUSH], 0, brush); } void <API key> (GimpBrushCore *core, GimpDynamics *dynamics) { g_return_if_fail (GIMP_IS_BRUSH_CORE (core)); g_return_if_fail (dynamics == NULL || GIMP_IS_DYNAMICS (dynamics)); g_signal_emit (core, core_signals[SET_DYNAMICS], 0, dynamics); } void <API key> (GimpBrushCore *core, GimpPaintOptions *paint_options) { TempBuf *mask = NULL; gdouble scale; g_return_if_fail (GIMP_IS_BRUSH_CORE (core)); g_return_if_fail (core->main_brush != NULL); g_return_if_fail (core->brush_bound_segs == NULL); scale = paint_options->brush_size / MAX (core->main_brush->mask->width, core->main_brush->mask->height); if (scale > 0.0) { scale = <API key> (core->main_brush, scale); /* Generated brushes are a bit special */ if (<API key> (core->main_brush)) { GimpBrushGenerated *generated_brush; gdouble ratio; generated_brush = <API key> (core->main_brush); ratio = <API key> (generated_brush); <API key> (generated_brush, <API key>, core); <API key> (generated_brush, 1.0); mask = <API key> (core->main_brush, 1.0, 0.0, 0.0, 1.0); <API key> (generated_brush, ratio); <API key> (generated_brush, <API key>, core); } else { mask = <API key> (core->main_brush, 1.0, 0.0, 0.0, 1.0); } } if (mask) { PixelRegion PR = { 0, }; <API key> (&PR, mask, 0, 0, mask->width, mask->height); /* Large, complex brush outlines are a performance problem. * Smooth the mask in order to obtain a simpler boundary. */ if (mask->width > 32 && mask->height > 32) smooth_region (&PR); core->brush_bound_segs = boundary_find (&PR, <API key>, 0, 0, PR.w, PR.h, 0, &core->n_brush_bound_segs); core->brush_bound_width = mask->width; core->brush_bound_height = mask->height; temp_buf_free (mask); } } gboolean <API key> (GimpBrushCore *core, GimpMatrix3 *matrix) { gdouble scale; gdouble angle; gdouble aspect_ratio; gdouble height; gdouble width; gdouble scale_x = core->scale; gdouble scale_y = core->scale; <API key> (GIMP_IS_BRUSH_CORE (core), FALSE); <API key> (matrix != 0, FALSE); <API key> (core->main_brush != NULL, FALSE); <API key> (core->brush_bound_segs != NULL, FALSE); <API key> (matrix); scale = core->scale; angle = core->angle; aspect_ratio = core->aspect_ratio; /* Generated brushes have their angle applied on top of base angle */ if (<API key> (core->main_brush)) { GimpBrushGenerated *generated_brush; gdouble base_angle; generated_brush = <API key> (core->main_brush); base_angle = <API key> (generated_brush); angle = angle + base_angle / 360; if (aspect_ratio == 0.0) aspect_ratio = (<API key> (generated_brush) - 1) / 19.0 * 20.0; } height = core->brush_bound_width; width = core->brush_bound_height; if (aspect_ratio < 0.0) { scale_x = scale * (1.0 - (fabs (aspect_ratio) / 20.0)); scale_y = scale; } else if (aspect_ratio > 0.0) { scale_x = scale; scale_y = scale * (1.0 - (aspect_ratio / 20.0)); } if (scale > 0.0) { scale = <API key> (core->main_brush, scale); <API key> (height, width, scale, aspect_ratio, angle, matrix); /* FIXME. Do noy use scale_x/scale_y */ core-><API key> = core->brush_bound_width * scale_x; core-><API key> = core->brush_bound_height * scale_y; return TRUE; } return FALSE; } void <API key> (GimpBrushCore *core, GimpDrawable *drawable, const GimpCoords *coords, gdouble brush_opacity, gdouble image_opacity, <API key> paint_mode, <API key> brush_hardness, gdouble dynamic_force, <API key> mode) { TempBuf *brush_mask = <API key> (core, coords, brush_hardness, dynamic_force); if (brush_mask) { GimpPaintCore *paint_core = GIMP_PAINT_CORE (core); PixelRegion brush_maskPR; gint x; gint y; gint off_x; gint off_y; x = (gint) floor (coords->x) - (brush_mask->width >> 1); y = (gint) floor (coords->y) - (brush_mask->height >> 1); off_x = (x < 0) ? -x : 0; off_y = (y < 0) ? -y : 0; <API key> (&brush_maskPR, brush_mask, off_x, off_y, paint_core->canvas_buf->width, paint_core->canvas_buf->height); <API key> (paint_core, &brush_maskPR, drawable, brush_opacity, image_opacity, paint_mode, mode); } } /* Similar to <API key>, but replaces the alpha channel * rather than using it to composite (i.e. transparent over opaque * becomes transparent rather than opauqe. */ void <API key> (GimpBrushCore *core, GimpDrawable *drawable, const GimpCoords *coords, gdouble brush_opacity, gdouble image_opacity, <API key> brush_hardness, gdouble dynamic_force, <API key> mode) { TempBuf *brush_mask = <API key> (core, coords, brush_hardness, dynamic_force); if (brush_mask) { GimpPaintCore *paint_core = GIMP_PAINT_CORE (core); PixelRegion brush_maskPR; gint x; gint y; gint off_x; gint off_y; x = (gint) floor (coords->x) - (brush_mask->width >> 1); y = (gint) floor (coords->y) - (brush_mask->height >> 1); off_x = (x < 0) ? -x : 0; off_y = (y < 0) ? -y : 0; <API key> (&brush_maskPR, brush_mask, off_x, off_y, paint_core->canvas_buf->width, paint_core->canvas_buf->height); <API key> (paint_core, &brush_maskPR, drawable, brush_opacity, image_opacity, mode); } } static void <API key> (GimpBrush *brush, GimpBrushCore *core) { /* Make sure we don't cache data for a brush that has changed */ core->cache_invalid = TRUE; core->solid_cache_invalid = TRUE; /* Set the same brush again so the "set-brush" signal is emitted */ <API key> (core, brush); } static inline void rotate_pointers (gulong **p, guint32 n) { guint32 i; gulong *tmp; tmp = p[0]; for (i = 0; i < n-1; i++) p[i] = p[i+1]; p[i] = tmp; } static TempBuf * <API key> (GimpBrushCore *core, TempBuf *mask, gdouble x, gdouble y) { TempBuf *dest; gdouble left; const guchar *m; guchar *d; const gint *k; gint index1; gint index2; gint dest_offset_x = 0; gint dest_offset_y = 0; const gint *kernel; gint i, j; gint r, s; gulong *accum[KERNEL_HEIGHT]; const guchar empty = TRANSPARENT_OPACITY; gint offs; while (x < 0) x += mask->width; left = x - floor (x); index1 = (gint) (left * (gdouble) (KERNEL_SUBSAMPLE + 1)); while (y < 0) y += mask->height; left = y - floor (y); index2 = (gint) (left * (gdouble) (KERNEL_SUBSAMPLE + 1)); if ((mask->width % 2) == 0) { index1 += KERNEL_SUBSAMPLE >> 1; if (index1 > KERNEL_SUBSAMPLE) { index1 -= KERNEL_SUBSAMPLE + 1; dest_offset_x = 1; } } if ((mask->height % 2) == 0) { index2 += KERNEL_SUBSAMPLE >> 1; if (index2 > KERNEL_SUBSAMPLE) { index2 -= KERNEL_SUBSAMPLE + 1; dest_offset_y = 1; } } kernel = subsample[index2][index1]; if (mask == core->last_brush_mask && ! core->cache_invalid) { if (core->kernel_brushes[index2][index1]) return core->kernel_brushes[index2][index1]; } else { for (i = 0; i < KERNEL_SUBSAMPLE + 1; i++) for (j = 0; j < KERNEL_SUBSAMPLE + 1; j++) if (core->kernel_brushes[i][j]) { temp_buf_free (core->kernel_brushes[i][j]); core->kernel_brushes[i][j] = NULL; } core->last_brush_mask = mask; core->cache_invalid = FALSE; } dest = temp_buf_new (mask->width + 2, mask->height + 2, 1, 0, 0, &empty); /* Allocate and initialize the accum buffer */ for (i = 0; i < KERNEL_HEIGHT ; i++) accum[i] = g_new0 (gulong, dest->width + 1); core->kernel_brushes[index2][index1] = dest; m = temp_buf_get_data (mask); for (i = 0; i < mask->height; i++) { for (j = 0; j < mask->width; j++) { k = kernel; for (r = 0; r < KERNEL_HEIGHT; r++) { offs = j + dest_offset_x; s = KERNEL_WIDTH; while (s accum[r][offs++] += *m * *k++; } m++; } /* store the accum buffer into the destination mask */ d = temp_buf_get_data (dest) + (i + dest_offset_y) * dest->width; for (j = 0; j < dest->width; j++) *d++ = (accum[0][j] + 127) / KERNEL_SUM; rotate_pointers (accum, KERNEL_HEIGHT); memset (accum[KERNEL_HEIGHT - 1], 0, sizeof (gulong) * dest->width); } /* store the rest of the accum buffer into the dest mask */ while (i + dest_offset_y < dest->height) { d = temp_buf_get_data (dest) + (i + dest_offset_y) * dest->width; for (j = 0; j < dest->width; j++) *d++ = (accum[0][j] + (KERNEL_SUM / 2)) / KERNEL_SUM; rotate_pointers (accum, KERNEL_HEIGHT); i++; } for (i = 0; i < KERNEL_HEIGHT ; i++) g_free (accum[i]); return dest; } /* #define FANCY_PRESSURE */ static TempBuf * <API key> (GimpBrushCore *core, TempBuf *brush_mask, gdouble x, gdouble y, gdouble pressure) { static guchar mapi[256]; const guchar *source; guchar *dest; TempBuf *subsample_mask; const guchar empty = TRANSPARENT_OPACITY; gint i; /* Get the raw subsampled mask */ subsample_mask = <API key> (core, brush_mask, x, y); /* Special case pressure = 0.5 */ if ((gint) (pressure * 100 + 0.5) == 50) return subsample_mask; if (core->pressure_brush) temp_buf_free (core->pressure_brush); core->pressure_brush = temp_buf_new (brush_mask->width + 2, brush_mask->height + 2, 1, 0, 0, &empty); #ifdef FANCY_PRESSURE /* Create the pressure profile * * It is: I'(I) = tanh (20 * (pressure - 0.5) * I) : pressure > 0.5 * I'(I) = 1 - tanh (20 * (0.5 - pressure) * (1 - I)) : pressure < 0.5 * * It looks like: * * low pressure medium pressure high pressure * * | / -- * | / / * / / | * -- / | */ { gdouble map[256]; gdouble ds, s, c; ds = (pressure - 0.5) * (20.0 / 256.0); s = 0; c = 1.0; if (ds > 0) { for (i = 0; i < 256; i++) { map[i] = s / c; s += c * ds; c += s * ds; } for (i = 0; i < 256; i++) mapi[i] = (gint) (255 * map[i] / map[255]); } else { ds = -ds; for (i = 255; i >= 0; i { map[i] = s / c; s += c * ds; c += s * ds; } for (i = 0; i < 256; i++) mapi[i] = (gint) (255 * (1 - map[i] / map[0])); } } #else /* ! FANCY_PRESSURE */ { gdouble j, k; j = pressure + pressure; k = 0; for (i = 0; i < 256; i++) { if (k > 255) mapi[i] = 255; else mapi[i] = (guchar) k; k += j; } } #endif /* FANCY_PRESSURE */ /* Now convert the brush */ source = temp_buf_get_data (subsample_mask); dest = temp_buf_get_data (core->pressure_brush); i = subsample_mask->width * subsample_mask->height; while (i *dest++ = mapi[(*source++)]; return core->pressure_brush; } static TempBuf * <API key> (GimpBrushCore *core, TempBuf *brush_mask, gdouble x, gdouble y) { TempBuf *dest; const guchar *m; guchar *d; gint dest_offset_x = 0; gint dest_offset_y = 0; gint i, j; const guchar empty = TRANSPARENT_OPACITY; if ((brush_mask->width % 2) == 0) { while (x < 0) x += brush_mask->width; if ((x - floor (x)) >= 0.5) dest_offset_x++; } if ((brush_mask->height % 2) == 0) { while (y < 0) y += brush_mask->height; if ((y - floor (y)) >= 0.5) dest_offset_y++; } if (! core->solid_cache_invalid && brush_mask == core->last_solid_brush) { if (core->solid_brushes[dest_offset_y][dest_offset_x]) return core->solid_brushes[dest_offset_y][dest_offset_x]; } else { for (i = 0; i < <API key>; i++) for (j = 0; j < <API key>; j++) if (core->solid_brushes[i][j]) { temp_buf_free (core->solid_brushes[i][j]); core->solid_brushes[i][j] = NULL; } core->last_solid_brush = brush_mask; core->solid_cache_invalid = FALSE; } dest = temp_buf_new (brush_mask->width + 2, brush_mask->height + 2, 1, 0, 0, &empty); core->solid_brushes[dest_offset_y][dest_offset_x] = dest; m = temp_buf_get_data (brush_mask); d = (temp_buf_get_data (dest) + (dest_offset_y + 1) * dest->width + (dest_offset_x + 1)); for (i = 0; i < brush_mask->height; i++) { for (j = 0; j < brush_mask->width; j++) *d++ = (*m++) ? OPAQUE_OPACITY : TRANSPARENT_OPACITY; d += 2; } return dest; } static TempBuf * <API key> (GimpBrushCore *core, GimpBrush *brush) { gint width; gint height; if (core->scale <= 0.0) return NULL; /* Should never happen now, with scale clamping. */ if ((core->scale == 1.0) && (core->angle == 0.0) && (core->hardness == 1.0) && (core->aspect_ratio == 0.0)) return brush->mask; <API key> (brush, core->scale, core->aspect_ratio, core->angle, &width, &height); if (! core->cache_invalid && core->transform_brush && brush->mask == core-><API key> && width == core-><API key> && height == core-><API key> && core->scale == core->last_scale && core->angle == core->last_angle && core->hardness == core->last_hardness && core->aspect_ratio == core->last_aspect_ratio) { return core->transform_brush; } core-><API key> = brush->mask; core-><API key> = width; core-><API key> = height; core->last_scale = core->scale; core->last_angle = core->angle; core->last_hardness = core->hardness; core->last_aspect_ratio = core->aspect_ratio; if (core->transform_brush) temp_buf_free (core->transform_brush); core->transform_brush = <API key> (brush, core->scale, core->aspect_ratio, core->angle, core->hardness); core->cache_invalid = TRUE; core->solid_cache_invalid = TRUE; return core->transform_brush; } static TempBuf * <API key> (GimpBrushCore *core, GimpBrush *brush) { gint width; gint height; if (core->scale <= 0.0) return NULL; if ((core->scale == 1.0) && (core->angle == 0.0) && (core->hardness == 1.0) && (core->aspect_ratio == 0.0)) return brush->pixmap; <API key> (brush, core->scale, core->aspect_ratio, core->angle, &width, &height); if (! core->cache_invalid && core->transform_pixmap && brush->pixmap == core-><API key> && width == core-><API key> && height == core-><API key> && core->angle == core->last_angle && core->hardness == core->last_hardness && core->aspect_ratio == core->last_aspect_ratio) { return core->transform_pixmap; } core-><API key> = brush->pixmap; core-><API key> = width; core-><API key> = height; core->last_angle = core->angle; core->last_hardness = core->hardness; core->last_aspect_ratio = core->aspect_ratio; if (core->transform_pixmap) temp_buf_free (core->transform_pixmap); core->transform_pixmap = <API key> (brush, core->scale, core->aspect_ratio, core->angle, core->hardness); core->cache_invalid = TRUE; return core->transform_pixmap; } TempBuf * <API key> (GimpBrushCore *core, const GimpCoords *coords, <API key> brush_hardness, gdouble dynamic_force) { TempBuf *mask; mask = <API key> (core, core->brush); if (! mask) return NULL; switch (brush_hardness) { case GIMP_BRUSH_SOFT: mask = <API key> (core, mask, coords->x, coords->y); break; case GIMP_BRUSH_HARD: mask = <API key> (core, mask, coords->x, coords->y); break; case GIMP_BRUSH_PRESSURE: mask = <API key> (core, mask, coords->x, coords->y, dynamic_force); break; default: break; } return mask; } void <API key> (GimpPaintCore *paint_core, GimpDrawable *drawable, GimpPaintOptions *paint_options, const GimpCoords *coords) { GimpBrushCore *core = GIMP_BRUSH_CORE (paint_core); gdouble fade_point = 1.0; if (core->main_brush) core->scale = paint_options->brush_size / MAX (core->main_brush->mask->width, core->main_brush->mask->height); else core->scale = -1; core->angle = paint_options->brush_angle; core->aspect_ratio = paint_options->brush_aspect_ratio; if (! GIMP_IS_DYNAMICS (core->dynamics)) return; if (<API key> (core)-><API key>) { gdouble dyn_aspect_ratio = 0.0; if (drawable) { GimpImage *image = gimp_item_get_image (GIMP_ITEM (drawable)); fade_point = <API key> (paint_options, image, paint_core->pixel_dist); } core->scale *= <API key> (core->dynamics->size_output, coords, paint_options, fade_point); core->angle += <API key> (core->dynamics->angle_output, coords, paint_options, fade_point); core->hardness = <API key> (core->dynamics->hardness_output, coords, paint_options, fade_point); dyn_aspect_ratio = <API key> (core->dynamics->aspect_ratio_output, coords, paint_options, fade_point); /* Zero aspect ratio is special cased to half of all ar range, * to force dynamics to have any effect . Forcing to full results * in disapearing stamp if applied to maximum. */ if (<API key> (core->dynamics->aspect_ratio_output)) { if (core->aspect_ratio == 0.0) core->aspect_ratio = 10.0 * dyn_aspect_ratio; else core->aspect_ratio *= dyn_aspect_ratio; } } } /* Brush pipe utility functions */ void <API key> (GimpBrushCore *core, GimpDrawable *drawable, const GimpCoords *coords, TempBuf *area, <API key> mode) { GimpImage *image; PixelRegion destPR; void *pr; guchar *d; gint ulx; gint uly; gint offsetx; gint offsety; gint y; TempBuf *pixmap_mask; TempBuf *brush_mask; g_return_if_fail (GIMP_IS_BRUSH (core->brush)); g_return_if_fail (core->brush->pixmap != NULL); image = gimp_item_get_image (GIMP_ITEM (drawable)); /* scale the brushes */ pixmap_mask = <API key> (core, core->brush); if (! pixmap_mask) return; if (mode != GIMP_BRUSH_HARD) brush_mask = <API key> (core, core->brush); else brush_mask = NULL; <API key> (&destPR, area, 0, 0, area->width, area->height); pr = <API key> (1, &destPR); /* Calculate upper left corner of brush as in * <API key>. Ugly to have to do this here, too. */ ulx = (gint) floor (coords->x) - (pixmap_mask->width >> 1); uly = (gint) floor (coords->y) - (pixmap_mask->height >> 1); /* Not sure why this is necessary, but empirically the code does * not work without it for even-sided brushes. See bug #166622. */ if (pixmap_mask->width %2 == 0) ulx += ROUND (coords->x) - floor (coords->x); if (pixmap_mask->height %2 == 0) uly += ROUND (coords->y) - floor (coords->y); offsetx = area->x - ulx; offsety = area->y - uly; for (; pr != NULL; pr = <API key> (pr)) { d = destPR.data; for (y = 0; y < destPR.h; y++) { <API key> (image, drawable, pixmap_mask, brush_mask, d, offsetx, y + offsety, destPR.bytes, destPR.w, mode); d += destPR.rowstride; } } } static void <API key> (GimpImage *dest, GimpDrawable *drawable, TempBuf *pixmap_mask, TempBuf *brush_mask, guchar *d, gint x, gint y, gint bytes, gint width, <API key> mode) { const guchar *mask; guchar *b; guchar *p; gdouble alpha; const gdouble factor = 0.00392156986; /* 1.0 / 255.0 */ gint x_index; gint i; /* Make sure x, y are positive */ while (x < 0) x += pixmap_mask->width; while (y < 0) y += pixmap_mask->height; /* Point to the approriate scanline */ b = (temp_buf_get_data (pixmap_mask) + (y % pixmap_mask->height) * pixmap_mask->width * pixmap_mask->bytes); if (mode == GIMP_BRUSH_SOFT && brush_mask) { /* ditto, except for the brush mask, so we can pre-multiply the * alpha value */ mask = (temp_buf_get_data (brush_mask) + (y % brush_mask->height) * brush_mask->width); for (i = 0; i < width; i++) { gint byte_loop; /* attempt to avoid doing this calc twice in the loop */ x_index = ((i + x) % pixmap_mask->width); p = b + x_index * pixmap_mask->bytes; d[bytes - 1] = mask[x_index]; /* multiply alpha into the pixmap data * maybe we could do this at tool creation or brush switch time? * and compute it for the whole brush at once and cache it? */ alpha = d[bytes - 1] * factor; if (alpha) for (byte_loop = 0; byte_loop < bytes - 1; byte_loop++) d[byte_loop] *= alpha; <API key> (dest, gimp_drawable_type (drawable), d, GIMP_RGB, p); d += bytes; } } else { for (i = 0; i < width; i++) { /* attempt to avoid doing this calc twice in the loop */ x_index = ((i + x) % pixmap_mask->width); p = b + x_index * pixmap_mask->bytes; d[bytes - 1] = 255; /* multiply alpha into the pixmap data * maybe we could do this at tool creation or brush switch time? * and compute it for the whole brush at once and cache it? */ <API key> (dest, gimp_drawable_type (drawable), d, GIMP_RGB, p); d += bytes; } } }
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * DataTables features */ .dataTables_wrapper { position: relative; clear: both; zoom: 1; /* Feeling sorry for IE */ } .<API key> { position: absolute; top: 50%; left: 50%; width: 250px; height: 30px; margin-left: -125px; margin-top: -15px; padding: 14px 0 2px 0; border: 1px solid #ddd; text-align: center; color: #999; font-size: 14px; background-color: white; } .dataTables_length { margin-bottom: 10px; width: 40%; float: left; } .dataTables_filter { margin-bottom: 10px; width: 50%; float: right; text-align: right; } .dataTables_info { width: 60%; float: left; } .dataTables_paginate { float: right; text-align: right; } /* Pagination nested */ .<API key>, .<API key>, .<API key>, .<API key> { height: 19px; float: left; cursor: pointer; *cursor: hand; color: #111 !important; } .<API key>:hover, .<API key>:hover, .<API key>:hover, .<API key>:hover { text-decoration: none !important; } .<API key>:active, .<API key>:active, .<API key>:active, .<API key>:active { outline: none; } .<API key>, .<API key> { color: #666 !important; } .<API key>, .<API key> { padding-left: 23px; } .<API key>, .<API key> { padding-right: 23px; margin-left: 10px; } .<API key> { background: url('../images/back_disabled.png') no-repeat top left; } .<API key> { background: url('../images/back_enabled.png') no-repeat top left; } .<API key>:hover { background: url('../images/back_enabled_hover.png') no-repeat top left; } .<API key> { background: url('../images/forward_disabled.png') no-repeat top right; } .<API key> { background: url('../images/forward_enabled.png') no-repeat top right; } .<API key>:hover { background: url('../images/<API key>.png') no-repeat top right; } /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * DataTables display */ #AnzeigenTable thead th{ padding: 10px; } #<API key> { border-right: 1px solid black; border-bottom: 1px solid black; } #theadBorderBottom { border-bottom: 1px solid black; } table.display { /*margin: 0 auto;*/ clear: both; width: 100%; border: 1px solid black; } table.display thead th { margin: 300px 18px 300px 10px; padding: 300px 18px 300px 10px; border-bottom: 1px solid black; font-weight: bold; cursor: pointer; * cursor: hand; } table.display tfoot th { padding: 3px 18px 3px 10px; border-top: 1px solid black; font-weight: bold; } table.display tr.heading2 td { border-bottom: 1px solid #aaa; } table.display td { padding: 300px 10px; } table.display td.center { text-align: center; } /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * DataTables sorting */ .sorting_asc { background: url('../images/sort_asc.png') no-repeat center right; } .sorting_desc { background: url('../images/sort_desc.png') no-repeat center right; } .sorting { background: url('../images/sort_both.png') no-repeat center right; } .<API key> { background: url('../images/sort_asc_disabled.png') no-repeat center right; } .<API key> { background: url('../images/sort_desc_disabled.png') no-repeat center right; } th:active { margin-top: 50px; outline: none; } /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * DataTables row classes */ table.display tr.odd.gradeA { background-color: #ddffdd; } table.display tr.even.gradeA { background-color: #eeffee; } table.display tr.odd.gradeC { background-color: #ddddff; } table.display tr.even.gradeC { background-color: #eeeeff; } table.display tr.odd.gradeX { background-color: #ffdddd; } table.display tr.even.gradeX { background-color: #ffeeee; } table.display tr.odd.gradeU { background-color: #ddd; } table.display tr.even.gradeU { background-color: #eee; } tr.odd { background-color: #E2E4FF; } tr.even { background-color: white; } /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * Misc */ .dataTables_scroll { clear: both; } .<API key> { *margin-top: -1px; -<API key>: touch; } .top, .bottom { padding: 15px; background-color: #F5F5F5; border: 1px solid #CCCCCC; } .top .dataTables_info { float: none; } .clear { clear: both; } .dataTables_empty { text-align: center; } tfoot input { margin: 0.5em 0; width: 100%; color: #444; } tfoot input.search_init { color: #999; } td.group { background-color: #d1cfd0; border-bottom: 2px solid #A19B9E; border-top: 2px solid #A19B9E; } td.details { background-color: #d1cfd0; border: 2px solid #A19B9E; } .<API key> div.dataTables_info { width: 40%; } .paging_full_numbers { width: 400px; height: 22px; line-height: 22px; } .paging_full_numbers a:active { outline: none } .paging_full_numbers a:hover { text-decoration: none; } .paging_full_numbers a.paginate_button, .paging_full_numbers a.paginate_active { border: 1px solid #aaa; -<API key>: 5px; -moz-border-radius: 5px; padding: 2px 5px; margin: 0 3px; cursor: pointer; *cursor: hand; color: #333 !important; } .paging_full_numbers a.paginate_button { background-color: #ddd; } .paging_full_numbers a.paginate_button:hover { background-color: #ccc; text-decoration: none !important; } .paging_full_numbers a.paginate_active { background-color: #99B3FF; } table.display tr.even.row_selected td { background-color: #B0BED9; } table.display tr.odd.row_selected td { background-color: #9FAFD1; } /* * Sorting classes for columns */ /* For the standard odd/even */ tr.odd td.sorting_1 { background-color: #D3D6FF; } tr.odd td.sorting_2 { background-color: #DADCFF; } tr.odd td.sorting_3 { background-color: #E0E2FF; } tr.even td.sorting_1 { background-color: #EAEBFF; } tr.even td.sorting_2 { background-color: #F2F3FF; } tr.even td.sorting_3 { background-color: #F9F9FF; } /* For the Conditional-CSS grading rows */ /* Colour calculations (based off the main row colours) Level 1: dd > c4 ee > d5 Level 2: dd > d1 ee > e2 */ tr.odd.gradeA td.sorting_1 { background-color: #c4ffc4; } tr.odd.gradeA td.sorting_2 { background-color: #d1ffd1; } tr.odd.gradeA td.sorting_3 { background-color: #d1ffd1; } tr.even.gradeA td.sorting_1 { background-color: #d5ffd5; } tr.even.gradeA td.sorting_2 { background-color: #e2ffe2; } tr.even.gradeA td.sorting_3 { background-color: #e2ffe2; } tr.odd.gradeC td.sorting_1 { background-color: #c4c4ff; } tr.odd.gradeC td.sorting_2 { background-color: #d1d1ff; } tr.odd.gradeC td.sorting_3 { background-color: #d1d1ff; } tr.even.gradeC td.sorting_1 { background-color: #d5d5ff; } tr.even.gradeC td.sorting_2 { background-color: #e2e2ff; } tr.even.gradeC td.sorting_3 { background-color: #e2e2ff; } tr.odd.gradeX td.sorting_1 { background-color: #ffc4c4; } tr.odd.gradeX td.sorting_2 { background-color: #ffd1d1; } tr.odd.gradeX td.sorting_3 { background-color: #ffd1d1; } tr.even.gradeX td.sorting_1 { background-color: #ffd5d5; } tr.even.gradeX td.sorting_2 { background-color: #ffe2e2; } tr.even.gradeX td.sorting_3 { background-color: #ffe2e2; } tr.odd.gradeU td.sorting_1 { background-color: #c4c4c4; } tr.odd.gradeU td.sorting_2 { background-color: #d1d1d1; } tr.odd.gradeU td.sorting_3 { background-color: #d1d1d1; } tr.even.gradeU td.sorting_1 { background-color: #d5d5d5; } tr.even.gradeU td.sorting_2 { background-color: #e2e2e2; } tr.even.gradeU td.sorting_3 { background-color: #e2e2e2; } /* * Row highlighting example */ .ex_highlight #example tbody tr.even:hover, #example tbody tr.even td.highlighted { background-color: #ECFFB3; } .ex_highlight #example tbody tr.odd:hover, #example tbody tr.odd td.highlighted { background-color: #E6FF99; } .ex_highlight_row #example tr.even:hover { background-color: #ECFFB3; } .ex_highlight_row #example tr.even:hover td.sorting_1 { background-color: #DDFF75; } .ex_highlight_row #example tr.even:hover td.sorting_2 { background-color: #E7FF9E; } .ex_highlight_row #example tr.even:hover td.sorting_3 { background-color: #E2FF89; } .ex_highlight_row #example tr.odd:hover { background-color: #E6FF99; } .ex_highlight_row #example tr.odd:hover td.sorting_1 { background-color: #D6FF5C; } .ex_highlight_row #example tr.odd:hover td.sorting_2 { background-color: #E0FF84; } .ex_highlight_row #example tr.odd:hover td.sorting_3 { background-color: #DBFF70; } /* * KeyTable */ table.KeyTable td { border: 3px solid transparent; } table.KeyTable td.focus { border: 3px solid #3366FF; } table.display tr.gradeA { background-color: #eeffee; } table.display tr.gradeC { background-color: #ddddff; } table.display tr.gradeX { background-color: #ffdddd; } table.display tr.gradeU { background-color: #ddd; } div.box { height: 100px; padding: 10px; overflow: auto; border: 1px solid #8080FF; background-color: #E5E5FF; }
package org.awesomeapp.messenger.tasks; import android.app.Activity; import android.content.ContentUris; import android.content.ContentValues; import android.content.Context; import android.database.Cursor; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.drawable.BitmapDrawable; import android.net.Uri; import android.os.AsyncTask; import android.os.Handler; import android.os.IBinder; import android.os.RemoteException; import android.text.TextUtils; import android.util.Log; import org.awesomeapp.messenger.ImApp; import org.awesomeapp.messenger.crypto.otr.<API key>; import org.awesomeapp.messenger.model.Contact; import org.awesomeapp.messenger.model.ImConnection; import org.awesomeapp.messenger.model.ImErrorInfo; import org.awesomeapp.messenger.model.Server; import org.awesomeapp.messenger.provider.Imps; import org.awesomeapp.messenger.service.IChatSession; import org.awesomeapp.messenger.service.IChatSessionManager; import org.awesomeapp.messenger.service.IContactList; import org.awesomeapp.messenger.service.IContactListManager; import org.awesomeapp.messenger.service.IImConnection; import org.awesomeapp.messenger.service.adapters.ChatSessionAdapter; import org.awesomeapp.messenger.ui.legacy.DatabaseUtils; import org.awesomeapp.messenger.ui.legacy.SignInHelper; import org.awesomeapp.messenger.ui.legacy.SimpleAlertHandler; import org.awesomeapp.messenger.ui.onboarding.OnboardingAccount; import org.awesomeapp.messenger.ui.onboarding.OnboardingActivity; import org.awesomeapp.messenger.ui.onboarding.OnboardingManager; import org.awesomeapp.messenger.util.AssetUtil; import org.json.JSONException; import java.io.<API key>; import java.io.IOException; import java.security.KeyPair; import java.util.ArrayList; import java.util.Collection; import java.util.List; import im.zom.messenger.R; public class MigrateAccountTask extends AsyncTask<Server, Void, OnboardingAccount> { Activity mContext; IImConnection mConn; String mDomain; long mAccountId; long mProviderId; ImApp mApp; IImConnection mNewConn; OnboardingAccount mNewAccount; <API key> mListener; Handler mHandler = new Handler(); ArrayList<String> mContacts; public MigrateAccountTask(Activity context, ImApp app, long providerId, long accountId, <API key> listener) { mContext = context; mAccountId = accountId; mProviderId = providerId; mApp = app; mListener = listener; mConn = app.getConnection(providerId, accountId); Cursor cursor = context.getContentResolver().query(Imps.ProviderSettings.CONTENT_URI, new String[]{Imps.ProviderSettings.NAME, Imps.ProviderSettings.VALUE}, Imps.ProviderSettings.PROVIDER + "=?", new String[]{Long.toString(mProviderId)}, null); if (cursor == null) return; Imps.ProviderSettings.QueryMap providerSettings = new Imps.ProviderSettings.QueryMap( cursor, context.getContentResolver(), mProviderId, false, null); mDomain = providerSettings.getDomain(); providerSettings.close(); if (!cursor.isClosed()) cursor.close(); mContacts = new ArrayList<>(); } @Override protected OnboardingAccount doInBackground(Server... newServers) { //get existing account username String nickname = Imps.Account.getNickname(mContext.getContentResolver(), mAccountId); String username = Imps.Account.getUserName(mContext.getContentResolver(), mAccountId); String password = Imps.Account.getPassword(mContext.getContentResolver(), mAccountId); <API key> keyMan = <API key>.getInstance(mContext); KeyPair keyPair = keyMan.<API key>(); String fingerprint = keyMan.getFingerprint(keyPair.getPublic()); //find or use provided new server/domain for (Server newServer : newServers) { if (mDomain.equals(newServer.domain)) continue; //don't migrate to the same server... to to = //register account on new domain with same password mNewAccount = registerNewAccount(nickname, username, password, newServer.domain, newServer.server); if (mNewAccount == null) continue; //try the next server String newJabberId = mNewAccount.username + '@' + mNewAccount.domain; keyMan.storeKeyPair(newJabberId, keyPair); //send migration message to existing contacts and/or sessions try { boolean <API key> = mConn.getState() == ImConnection.LOGGED_IN; //login and set new default account SignInHelper signInHelper = new SignInHelper(mContext, mHandler); signInHelper.activateAccount(mNewAccount.providerId, mNewAccount.accountId); signInHelper.signIn(mNewAccount.password, mNewAccount.providerId, mNewAccount.accountId, true); mNewConn = mApp.getConnection(mNewAccount.providerId, mNewAccount.accountId); while (mNewConn.getState() != ImConnection.LOGGED_IN) { try { Thread.sleep(500); } catch (Exception e) { } } String inviteLink = OnboardingManager.generateInviteLink(mContext, newJabberId, fingerprint, nickname, true); String migrateMessage = mContext.getString(R.string.migrate_message) + ' ' + inviteLink; IChatSessionManager sessionMgr = mConn.<API key>(); IContactListManager clManager = mConn.<API key>(); List<IContactList> listOfLists = clManager.getContactLists(); if (<API key>) { for (IContactList contactList : listOfLists) { String[] contacts = contactList.getContacts(); for (String contact : contacts) { mContacts.add(contact); IChatSession session = sessionMgr.getChatSession(contact); if (session == null) { session = sessionMgr.createChatSession(contact, true); } if (!session.isEncrypted()) { //try to kick off some encryption here session.<API key>().startChatEncryption(); try { Thread.sleep(500); } //just wait a half second here? catch (Exception e) { } } session.sendMessage(migrateMessage, false); //archive existing contact clManager.archiveContact(contact, session.isGroupChatSession() ? Imps.Contacts.TYPE_NORMAL : Imps.Contacts.TYPE_GROUP, true); } } } else { String[] offlineAddresses = clManager.getOfflineAddresses(); for (String address : offlineAddresses) { mContacts.add(address); clManager.archiveContact(address, Imps.Contacts.TYPE_NORMAL, true); } } for (String contact : mContacts) { addToContactList(mNewConn, contact, keyMan.<API key>(contact), null); } if (<API key>) { //archive existing conversations and contacts List<IChatSession> listSession = mConn.<API key>().<API key>(); for (IChatSession session : listSession) { session.leave(); } mConn.<API key>(newJabberId); } migrateAvatars(username, newJabberId); mApp.setDefaultAccount(mNewAccount.providerId, mNewAccount.accountId); //logout of existing account setKeepSignedIn(mAccountId, false); if (<API key>) mConn.logout(); return mNewAccount; } catch (Exception e) { Log.e(ImApp.LOG_TAG, "error with migration", e); } } //failed return null; } @Override protected void onPostExecute(OnboardingAccount account) { super.onPostExecute(account); if (account == null) { if (mListener != null) mListener.migrateFailed(mProviderId,mAccountId); } else { if (mListener != null) mListener.migrateComplete(account); } } private OnboardingAccount registerNewAccount (String nickname, String username, String password, String domain, String server) { try { OnboardingAccount result = OnboardingManager.registerAccount(mContext, nickname, username, password, domain, server, 5222); return result; } catch (JSONException jse) { } return null; } private int addToContactList (IImConnection conn, String address, String otrFingperint, String nickname) { int res = -1; try { IContactList list = getContactList(conn); if (list != null) { res = list.addContact(address, nickname); if (res != ImErrorInfo.NO_ERROR) { //what to do here? } if (!TextUtils.isEmpty(otrFingperint)) { <API key>.getInstance(mApp).verifyUser(address, otrFingperint); } //Contact contact = new Contact(new XmppAddress(address),address); //IContactListManager contactListMgr = conn.<API key>(); //contactListMgr.approveSubscription(contact); } } catch (RemoteException re) { Log.e(ImApp.LOG_TAG, "error adding contact", re); } return res; } private IContactList getContactList(IImConnection conn) { if (conn == null) { return null; } try { IContactListManager contactListMgr = conn.<API key>(); // Use the default list List<IBinder> lists = contactListMgr.getContactLists(); for (IBinder binder : lists) { IContactList list = IContactList.Stub.asInterface(binder); if (list.isDefault()) { return list; } } // No default list, use the first one as default list if (!lists.isEmpty()) { return IContactList.Stub.asInterface(lists.get(0)); } return null; } catch (RemoteException e) { // If the service has died, there is no list for now. return null; } } public interface <API key> { public void migrateComplete (OnboardingAccount account); public void migrateFailed (long providerId, long accountId); } private void setKeepSignedIn(final long accountId, boolean signin) { Uri mAccountUri = ContentUris.withAppendedId(Imps.Account.CONTENT_URI, accountId); ContentValues values = new ContentValues(); values.put(Imps.Account.KEEP_SIGNED_IN, signin); mContext.getContentResolver().update(mAccountUri, values, null, null); } private void migrateAvatars (String oldUsername, String newUsername) { try { //first copy the old avatar over to the new account byte[] oldAvatar = DatabaseUtils.<API key>(mContext.getContentResolver(),oldUsername); if (oldAvatar != null) { setAvatar(newUsername, oldAvatar); } //now change the older avatar, so the vcard gets reloaded Bitmap bitmap = BitmapFactory.decodeStream(mContext.getAssets().open("stickers/olo and shimi/4greeting.png")); setAvatar(oldUsername, bitmap); } catch (Exception ioe) { ioe.printStackTrace(); } } private void setAvatar(String address, Bitmap bmp) { try { <API key> stream = new <API key>(); bmp.compress(Bitmap.CompressFormat.JPEG, 90, stream); byte[] <API key> = stream.toByteArray(); String avatarHash = "nohash"; DatabaseUtils.insertAvatarBlob(mContext.getContentResolver(), Imps.Avatars.CONTENT_URI, mProviderId, mAccountId, <API key>, avatarHash, address); } catch (Exception e) { Log.w(ImApp.LOG_TAG, "error loading image bytes", e); } } private void setAvatar(String address, byte[] <API key>) { try { String avatarHash = "nohash"; DatabaseUtils.insertAvatarBlob(mContext.getContentResolver(), Imps.Avatars.CONTENT_URI, mProviderId, mAccountId, <API key>, avatarHash, address); } catch (Exception e) { Log.w(ImApp.LOG_TAG, "error loading image bytes", e); } } }
package com.github.schmidtbochum.chunkclaim; import java.util.ArrayList; import java.util.Date; import java.util.Iterator; import org.bukkit.Location; public class PlayerData { // String[] builderNames zu arraylist constructor public float credits = ChunkClaim.plugin.config_startCredits; public float bonus = 0L; public String playerName; public ArrayList<String> builderNames = new ArrayList<String>(); public Date lastLogin = new Date(); public Date firstJoin = new Date(); public Chunk lastChunk = null; public Visualization <API key> = null; public Location <API key> = null; public boolean ignorechunks = false; public int getCredits() { return (int) credits; } }
#include "cmd/SetThreadCmd.h" #include "model/ConnectionModel.h" #include "model/InputModel.h" SetThreadCmd::SetThreadCmd(ConnectionModel* connection, ThreadModel* newThread, QUndoCommand* parent) : QUndoCommand(QObject::tr("set thread"), parent), m_model(connection), m_oldThread(connection->thread()), m_newThread(newThread) { } void SetThreadCmd::redo() { m_model->doSetThread(m_newThread); } void SetThreadCmd::undo() { m_model->doSetThread(m_oldThread); }
{% comment %} <! Please see srs_base.html for license information. {% endcomment %} {% load static %} <div class="modal-header"> <button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button> <h4 class="modal-title">Rating history for <u>{{ game_verbose }}</u>, match type <u>{{ match_type_verbose }}</u></h4> </div> <div class="modal-body"> <img id="ts_graph" width=0 height=0 src="{% url 'srs/ts_history_graph' game_abbr accountid match_type %}" onload="fix_size()"/> <img id="loader_img" src="{% static "img/loading_bar.gif" %}" style="border: none; display: block; margin: 0 auto;"/> </div> <div class="modal-footer"> <button type="button" class="btn btn-default" data-dismiss="modal">Close</button> </div>
package visan.ui; import java.io.File; import java.io.FilenameFilter; public class VisFilter implements FilenameFilter { @Override public boolean accept(File directory, String fileName) { if (fileName.toLowerCase().endsWith(".vis")) { return true; } return false; } }
<?php namespace TYPO3\Flow\Validation; use TYPO3\Flow\Annotations as Flow; use TYPO3\Flow\Object\Configuration\Configuration; use TYPO3\Flow\Object\<API key>; use TYPO3\Flow\Reflection\ReflectionService; use TYPO3\Flow\Utility\Exception\<API key>; use TYPO3\Flow\Utility\TypeHandling; use TYPO3\Flow\Validation\Validator\<API key>; use TYPO3\Flow\Validation\Validator\ValidatorInterface; use TYPO3\Flow\Validation\Validator\<API key>; use TYPO3\Flow\Validation\Validator\<API key>; /** * Validator resolver to automatically find a appropriate validator for a given subject * * @Flow\Scope("singleton") * @api */ class ValidatorResolver { /** * Match validator names and options * @var string */ const <API key> = '/ (?:^|,\s*) (?P<validatorName>[a-z0-9\\\\]+) \s* (?:\( (?P<validatorOptions>(?:\s*[a-z0-9]+\s*=\s*(?: "(?:\\\\"|[^"])*" |\'(?:\\\\\'|[^\'])*\' |(?:\s|[^,"\']*) )(?:\s|,)*)*) \))? /ixS'; /** * Match validator options (to parse actual options) * @var string */ const <API key> = '/ \s* (?P<optionName>[a-z0-9]+) \s*=\s* (?P<optionValue> "(?:\\\\"|[^"])*" |\'(?:\\\\\'|[^\'])*\' |(?:\s|[^,"\']*) ) /ixS'; /** * @Flow\Inject * @var <API key> */ protected $objectManager; /** * @Flow\Inject * @var ReflectionService */ protected $reflectionService; /** * @var array */ protected $<API key> = []; /** * Get a validator for a given data type. Returns a validator implementing * the ValidatorInterface or NULL if no validator * could be resolved. * * @param string $validatorType Either one of the built-in data types or fully qualified validator class name * @param array $validatorOptions Options to be passed to the validator * @return ValidatorInterface * @throws Exception\<API key> * @throws Exception\<API key> * @api */ public function createValidator($validatorType, array $validatorOptions = []) { $validatorObjectName = $this-><API key>($validatorType); if ($validatorObjectName === false) { return null; } switch ($this->objectManager->getScope($validatorObjectName)) { case Configuration::SCOPE_PROTOTYPE: $validator = new $validatorObjectName($validatorOptions); break; case Configuration::SCOPE_SINGLETON: if (count($validatorOptions) > 0) { throw new Exception\<API key>('The validator "' . $validatorObjectName . '" is of scope singleton, but configured to be used with options. A validator with options must be of scope prototype.', 1358958575); } $validator = $this->objectManager->get($validatorObjectName); break; default: throw new Exception\<API key>('The validator "' . $validatorObjectName . '" is not of scope singleton or prototype!', 1300694835); } if (!($validator instanceof ValidatorInterface)) { throw new Exception\<API key>(sprintf('The validator "%s" does not implement %s!', $validatorObjectName, ValidatorInterface::class), 1300694875); } return $validator; } /** * Resolves and returns the base validator conjunction for the given data type. * * If no validation is necessary, the returned validator is empty. * * @param string $targetClassName Fully qualified class name of the target class, ie. the class which should be validated * @param array $validationGroups The validation groups to build the validator for * @return <API key> The validator conjunction * @api */ public function <API key>($targetClassName, array $validationGroups = ['Default']) { $targetClassName = trim($targetClassName, ' \\'); $indexKey = $targetClassName . '##' . implode('##', $validationGroups); if (!array_key_exists($indexKey, $this-><API key>)) { $this-><API key>($indexKey, $targetClassName, $validationGroups); } return $this-><API key>[$indexKey]; } /** * Detects and registers any validators for arguments: * - by the data type specified in the param annotations * - additional validators specified in the validate annotations of a method * * @param string $className * @param string $methodName * @param array $methodParameters Optional pre-compiled array of method parameters * @param array $<API key> Optional pre-compiled array of validate annotations (as array) * @return array An Array of <API key> for each method parameters. * @throws Exception\<API key> * @throws Exception\<API key> * @throws Exception\<API key> */ public function <API key>($className, $methodName, array $methodParameters = null, array $<API key> = null) { $<API key> = []; if ($methodParameters === null) { $methodParameters = $this->reflectionService->getMethodParameters($className, $methodName); } if (count($methodParameters) === 0) { return $<API key>; } foreach ($methodParameters as $parameterName => $methodParameter) { $<API key> = $this->createValidator(<API key>::class); if (!array_key_exists('type', $methodParameter)) { throw new Exception\<API key>('Missing type information, probably no @param annotation for parameter "$' . $parameterName . '" in ' . $className . '->' . $methodName . '()', 1281962564); } if (strpos($methodParameter['type'], '\\') === false) { $typeValidator = $this->createValidator($methodParameter['type']); } else { $typeValidator = null; } if ($typeValidator !== null) { $<API key>->addValidator($typeValidator); } $<API key>[$parameterName] = $<API key>; } if ($<API key> === null) { $validateAnnotations = $this->reflectionService-><API key>($className, $methodName, Flow\Validate::class); $<API key> = array_map(function ($validateAnnotation) { return [ 'type' => $validateAnnotation->type, 'options' => $validateAnnotation->options, 'argumentName' => $validateAnnotation->argumentName, ]; }, $validateAnnotations); } foreach ($<API key> as $<API key>) { $newValidator = $this->createValidator($<API key>['type'], $<API key>['options']); if ($newValidator === null) { throw new Exception\<API key>('Invalid validate annotation in ' . $className . '->' . $methodName . '(): Could not resolve class name for validator "' . $<API key>['type'] . '".', 1239853109); } if (isset($<API key>[$<API key>['argumentName']])) { $<API key>[$<API key>['argumentName']]->addValidator($newValidator); } elseif (strpos($<API key>['argumentName'], '.') !== false) { $objectPath = explode('.', $<API key>['argumentName']); $argumentName = array_shift($objectPath); $<API key>[$argumentName]->addValidator($this-><API key>($objectPath, $newValidator)); } else { throw new Exception\<API key>('Invalid validate annotation in ' . $className . '->' . $methodName . '(): Validator specified for argument name "' . $<API key>['argumentName'] . '", but this argument does not exist.', 1253172726); } } return $<API key>; } /** * Resets the <API key> * It is usually not required to reset the ValidatorResolver during one request. This method is mainly useful for functional tests * * @return void */ public function reset() { $this-><API key> = []; } /** * Builds a chain of nested object validators by specification of the given * object path. * * @param array $objectPath The object path * @param ValidatorInterface $propertyValidator The validator which should be added to the property specified by objectPath * @return <API key> */ protected function <API key>(array $objectPath, ValidatorInterface $propertyValidator) { $rootObjectValidator = new <API key>([]); $<API key> = $rootObjectValidator; while (count($objectPath) > 1) { $subObjectValidator = new <API key>([]); $subPropertyName = array_shift($objectPath); $<API key>-><API key>($subPropertyName, $subObjectValidator); $<API key> = $subObjectValidator; } $<API key>-><API key>(array_shift($objectPath), $propertyValidator); return $rootObjectValidator; } /** * Builds a base validator conjunction for the given data type. * * The base validation rules are those which were declared directly in a class (typically * a model) through some validate annotations on properties. * * If a property holds a class for which a base validator exists, that property will be * checked as well, regardless of a validate annotation * * Additionally, if a custom validator was defined for the class in question, it will be added * to the end of the conjunction. A custom validator is found if it follows the naming convention * "Replace '\Model\' by '\Validator\' and append 'Validator'". * * Example: $targetClassName is Neos\Foo\Domain\Model\Quux, then the validator will be found if it has the * name Neos\Foo\Domain\Validator\QuuxValidator * * @param string $indexKey The key to use as index in $this-><API key>; calculated from target class name and validation groups * @param string $targetClassName The data type to build the validation conjunction for. Needs to be the fully qualified class name. * @param array $validationGroups The validation groups to build the validator for * @return void * @throws Exception\<API key> * @throws \<API key> */ protected function <API key>($indexKey, $targetClassName, array $validationGroups) { $<API key> = new <API key>(); $this-><API key>[$indexKey] = $<API key>; if (!TypeHandling::isSimpleType($targetClassName) && class_exists($targetClassName)) { // Model based validator $classSchema = $this->reflectionService->getClassSchema($targetClassName); if ($classSchema !== null && $classSchema->isAggregateRoot()) { $objectValidator = new <API key>(array()); } else { $objectValidator = new <API key>([]); } $<API key>->addValidator($objectValidator); foreach ($this->reflectionService-><API key>($targetClassName) as $classPropertyName) { $<API key> = $this->reflectionService-><API key>($targetClassName, $classPropertyName); if (!isset($<API key>['var'])) { throw new \<API key>(sprintf('There is no @var annotation for property "%s" in class "%s".', $classPropertyName, $targetClassName), 1363778104); } try { $parsedType = TypeHandling::parseType(trim(implode('', $<API key>['var']), ' \\')); } catch (<API key> $exception) { throw new \<API key>(sprintf(' @var annotation of ' . $exception->getMessage(), 'class "' . $targetClassName . '", property "' . $classPropertyName . '"'), 1315564744, $exception); } if ($this->reflectionService-><API key>($targetClassName, $classPropertyName, Flow\IgnoreValidation::class)) { continue; } $<API key> = $parsedType['type']; if (TypeHandling::isCollectionType($<API key>) === true) { $collectionValidator = $this->createValidator(Validator\CollectionValidator::class, ['elementType' => $parsedType['elementType'], 'validationGroups' => $validationGroups]); $objectValidator-><API key>($classPropertyName, $collectionValidator); } elseif (!TypeHandling::isSimpleType($<API key>) && $this->objectManager->isRegistered($<API key>) && $this->objectManager->getScope($<API key>) === Configuration::SCOPE_PROTOTYPE) { $<API key> = $this-><API key>($<API key>, $validationGroups); if (count($<API key>) > 0) { $objectValidator-><API key>($classPropertyName, $<API key>); } } $validateAnnotations = $this->reflectionService-><API key>($targetClassName, $classPropertyName, Flow\Validate::class); foreach ($validateAnnotations as $validateAnnotation) { if (count(array_intersect($validateAnnotation->validationGroups, $validationGroups)) === 0) { // In this case, the validation groups for the property do not match current validation context continue; } $newValidator = $this->createValidator($validateAnnotation->type, $validateAnnotation->options); if ($newValidator === null) { throw new Exception\<API key>('Invalid validate annotation in ' . $targetClassName . '::' . $classPropertyName . ': Could not resolve class name for validator "' . $validateAnnotation->type . '".', 1241098027); } $objectValidator-><API key>($classPropertyName, $newValidator); } } if (count($objectValidator-><API key>()) === 0) { $<API key>->removeValidator($objectValidator); } } $this->addCustomValidators($targetClassName, $<API key>); } /** * This adds custom validators to the passed $<API key>. * * A custom validator is found if it follows the naming convention "Replace '\Model\' by '\Validator\' and * append 'Validator'". If found, it will be added to the $<API key>. * * In addition canValidate() will be called on all implementations of the <API key> to find * all validators that could validate the target. The one with the highest priority will be added as well. * If multiple validators have the same priority, which one will be added is not deterministic. * * @param string $targetClassName * @param <API key> $<API key> * @return NULL|Validator\<API key> */ protected function addCustomValidators($targetClassName, <API key> &$<API key>) { // Custom validator for the class $<API key> = null; $<API key> = str_replace('\\Model\\', '\\Validator\\', $targetClassName) . 'Validator'; $customValidator = $this->createValidator($<API key>); if ($customValidator !== null) { $<API key>->addValidator($customValidator); $<API key> = get_class($customValidator); } // find polytype validator for class $<API key> = []; $<API key> = static::<API key>($this->objectManager); foreach ($<API key> as $<API key>) { $<API key> = $this->createValidator($<API key>); // skip custom validator already added above if ($<API key> === get_class($<API key>)) { continue; } if ($<API key>->canValidate($targetClassName)) { $<API key>[$<API key>->getPriority()] = $<API key>; } } if (count($<API key>) > 0) { ksort($<API key>); $<API key>->addValidator(array_pop($<API key>)); } } /** * Returns a map of object validator class names. * * @param <API key> $objectManager * @return array Array of object validator class names * @Flow\CompileStatic */ public static function <API key>($objectManager) { $reflectionService = $objectManager->get(ReflectionService::class); $result = $reflectionService-><API key>(Validator\<API key>::class); return $result; } /** * Returns the class name of an appropriate validator for the given type. If no * validator is available FALSE is returned * * @param string $validatorType Either the fully qualified class name of the validator or the short name of a built-in validator * @return string|boolean Class name of the validator or FALSE if not available */ protected function <API key>($validatorType) { $validatorType = ltrim($validatorType, '\\'); $validatorClassNames = static::<API key>($this->objectManager); if ($this->objectManager->isRegistered($validatorType) && isset($validatorClassNames[$validatorType])) { return $validatorType; } if (strpos($validatorType, ':') !== false) { list($packageName, $<API key>) = explode(':', $validatorType); $possibleClassName = sprintf('%s\Validation\Validator\%sValidator', str_replace('.', '\\', $packageName), $this->getValidatorType($<API key>)); } else { $possibleClassName = sprintf('TYPO3\Flow\Validation\Validator\%sValidator', $this->getValidatorType($validatorType)); } if ($this->objectManager->isRegistered($possibleClassName) && isset($validatorClassNames[$possibleClassName])) { return $possibleClassName; } return false; } /** * Returns all class names implementing the ValidatorInterface. * * @param <API key> $objectManager * @return array Array of class names implementing ValidatorInterface indexed by class name * @Flow\CompileStatic */ public static function <API key>($objectManager) { $reflectionService = $objectManager->get(ReflectionService::class); $classNames = $reflectionService-><API key>(ValidatorInterface::class); return array_flip($classNames); } /** * Used to map PHP types to validator types. * * @param string $type Data type to unify * @return string unified data type */ protected function getValidatorType($type) { switch ($type) { case 'int': $type = 'Integer'; break; case 'bool': $type = 'Boolean'; break; case 'double': $type = 'Float'; break; case 'numeric': $type = 'Number'; break; case 'mixed': $type = 'Raw'; break; default: $type = ucfirst($type); } return $type; } }
<?php /* CAT:Barcode */ /* pChart library inclusions */ include("../class/pDraw.class.php"); include("../class/pBarcode39.class.php"); include("../class/pBarcode128.class.php"); include("../class/pImage.class.php"); /* Create the pChart object */ $myPicture = new pImage(600, 310, NULL, TRUE); /* Draw the rounded box */ $myPicture->setShadow(TRUE, array("X" => 2, "Y" => 2, "R" => 0, "G" => 0, "B" => 0, "Alpha" => 30)); $Settings = array("R" => 255, "G" => 255, "B" => 255, "BorderR" => 0, "BorderG" => 0, "BorderB" => 0); $myPicture-><API key>(10, 10, 590, 300, 10, $Settings); /* Draw the cell divisions */ $myPicture->setShadow(FALSE); $Settings = array("R" => 0, "G" => 0, "B" => 0); $myPicture->drawLine(10, 110, 590, 110, $Settings); $myPicture->drawLine(200, 10, 200, 110, $Settings); $myPicture->drawLine(400, 10, 400, 110, $Settings); $myPicture->drawLine(10, 160, 590, 160, $Settings); $myPicture->drawLine(220, 160, 220, 200, $Settings); $myPicture->drawLine(320, 160, 320, 200, $Settings); $myPicture->drawLine(10, 200, 590, 200, $Settings); $myPicture->drawLine(400, 220, 400, 300, $Settings); /* Write the fields labels */ $myPicture->setFontProperties(array("FontName" => "../fonts/Forgotte.ttf", "FontSize" => 10)); $Settings = array("R" => 0, "G" => 0, "B" => 0, "Align" => TEXT_ALIGN_TOPLEFT); $myPicture->drawText(20, 20, "FROM", $Settings); $myPicture->drawText(210, 20, "TO", $Settings); $myPicture->drawText(20, 120, "ACCT.\r\nNUMBER", $Settings); $myPicture->drawText(20, 166, "QUANTITY", $Settings); $myPicture->drawText(230, 166, "SHIPMENT CODE", $Settings); $myPicture->drawText(330, 166, "SENDER CODE", $Settings); $myPicture->drawText(410, 220, "MFG DATE", $Settings); $myPicture->drawText(410, 260, "NET WEIGTH", $Settings); /* Filling the fields values */ $myPicture->setFontProperties(array("FontName" => "../fonts/Forgotte.ttf", "FontSize" => 16)); $myPicture->drawText(70, 20, "BEBEER INC\r\n342, MAIN STREET\r\n33000 BORDEAUX\r\nFRANCE", $Settings); $myPicture->drawText(250, 20, "MUSTAFA'S BAR\r\n18, CAPITOL STREET\r\n31000 TOULOUSE\r\nFRANCE", $Settings); $myPicture->setFontProperties(array("FontName" => "../fonts/Forgotte.ttf", "FontSize" => 35)); $myPicture->drawText(100, 120, "2342355552340", $Settings); $myPicture->setFontProperties(array("FontName" => "../fonts/Forgotte.ttf", "FontSize" => 20)); $Settings = array("R" => 0, "G" => 0, "B" => 0, "Align" => TEXT_ALIGN_TOPRIGHT); $myPicture->drawText(210, 180, "75 CANS", $Settings); $myPicture->drawText(310, 180, "TLSE", $Settings); $myPicture->drawText(580, 180, "WAREHOUSE#SLOT#B15", $Settings); $Settings = array("R" => 0, "G" => 0, "B" => 0, "Align" => TEXT_ALIGN_TOPLEFT); $myPicture->drawText(410, 236, "06/06/2010", $Settings); $myPicture->drawText(410, 276, "12.340 Kg", $Settings); /* Create the barcode 39 object */ $Barcode39 = new pBarcode39("../"); $myPicture->setFontProperties(array("FontName" => "../fonts/pf_arma_five.ttf", "FontSize" => 6)); $Settings = array("ShowLegend" => TRUE, "Height" => 55, "DrawArea" => TRUE, "DrawArea" => FALSE); $Barcode39->draw($myPicture, "12250000234502", 30, 220, $Settings); $Settings = array("ShowLegend" => TRUE, "Height" => 14, "DrawArea" => TRUE, "DrawArea" => FALSE); $Barcode39->draw($myPicture, "75 cans", 260, 220, $Settings); $Barcode39->draw($myPicture, "06062010", 260, 260, $Settings); /* Create the barcode 128 object */ $Barcode128 = new pBarcode128("../"); $Settings = array("ShowLegend" => TRUE, "Height" => 65, "DrawArea" => TRUE, "DrawArea" => FALSE); $Barcode128->draw($myPicture, "TLSE", 450, 25, $Settings); /* Render the picture (choose the best way) */ $myPicture->autoOutput("pictures/example.barcode.png"); ?>
#ifndef BFHEADER_H_ #define BFHEADER_H_ #include "stdint.h" #define BF_MAGIC 0x4246 #define BF_INDENT 0x10 #define MEMORY_PTR_MAX 65535 #define SECTION_CODE 0x01 #define SECTION_DATA 0x02 #define SECTION_VIDEO 0x03 typedef struct _BfSection_t{ uint16_t FileBase;//Relative shift from the beginning of file uint16_t MemoryBase;//Physical address to load uint16_t FileSize;//How much Bytes of data can be loaded to memory uint16_t MemorySize;//How much Words in Memory should be allocated uint8_t type; uint8_t pad; }BfSection_t; typedef struct _BfHeader_t{ uint16_t Magic;//BF should contain "BF" symbols uint8_t Machine;//8bit of 16bit mode uint8_t HeaderSize; uint8_t SectionNum; uint8_t flags; uint16_t IpEntry;//IP start address uint16_t ApEntry;//AP start address } BfHeader_t; #endif /* BFHEADER_H_ */
// <API key>.cpp // revbayes-proj #include "<API key>.h" #include "<API key>.h" #include "ArgumentRule.h" #include "ModelVector.h" #include "MemberProcedure.h" #include "Natural.h" #include "RlBoolean.h" using namespace RevLanguage; <API key>::<API key>(void) : ModelObject<RevBayesCore::<API key>>() { } <API key>::<API key>( const RevBayesCore::<API key> &v) : ModelObject<RevBayesCore::<API key>>( v.clone() ) { } <API key>::<API key>( RevBayesCore::<API key> *v) : ModelObject<RevBayesCore::<API key>>( v ) { } <API key>::<API key>( RevBayesCore::TypedDagNode<RevBayesCore::<API key>> *m) : ModelObject<RevBayesCore::<API key>>( m ) { } <API key>* <API key>::clone() const { return new <API key>( *this ); } /* Get Rev type of object */ const std::string& <API key>::getClassType(void) { static std::string rev_type = "<API key>"; return rev_type; } /* Get class type spec describing type of object */ const TypeSpec& <API key>::getClassTypeSpec(void) { static TypeSpec rev_type_spec = TypeSpec( getClassType(), new TypeSpec( RevObject::getClassTypeSpec() ) ); return rev_type_spec; } /** Get the type spec of this class. We return a member variable because instances might have different element types. */ const TypeSpec& <API key>::getTypeSpec(void) const { static TypeSpec type_spec = getClassTypeSpec(); return type_spec; }
<?php require_once('engines/lcml/main.php'); class body_smart extends base_null { function body($obj) { $data = array(); if($qlist = $obj->get('_queries')) { $db = new driver_mysql($obj->db_name()); foreach($qlist as $qname => $q) { $cache = false; if(preg_match("!^(.+)\|(\d+)$!s", $q, $m)) { $q = $m[1]; $cache = $m[2]; } if(preg_match("/!(.+)$/s", $q, $m)) $data[$qname] = $db->get($m[1], false, $cache); else $data[$qname] = $db->get_array($q, false, $cache); } } $data['template_dir'] = $obj->class_dir(); $data['this'] = $obj; $obj->template_data_fill(); require_once('engines/smarty/assign.php'); return lcml_smart(<API key>($obj->body_template(), $data)); } }
/** * Model container for 'Curve Fitting' simulation. * * @author Andrey Zelenkov (Mlearner) */ import <API key> from '../../../../axon/js/<API key>.js'; import NumberProperty from '../../../../axon/js/NumberProperty.js'; import curveFitting from '../../curveFitting.js'; import <API key> from '../<API key>.js'; import createPoints from './createPoints.js'; import Curve from './Curve.js'; import FitType from './FitType.js'; class CurveFittingModel { constructor() { // @public {Property.<number>} order of the polynomial that describes the curve, valid values are 1, 2, 3 this.orderProperty = new NumberProperty( 1, { validValues: [ 1, 2, 3 ] } ); // @public {Property.<FitType>}, the method of fitting the curve to data points this.fitProperty = new <API key>( FitType, FitType.BEST ); // @public {Property.<number>[]}, user input values for coefficients of the polynomial, starting from lowest // order x^0 to x^3 const <API key> = range => new NumberProperty( range.defaultValue, { range: range } ); this.sliderPropertyArray = [ <API key>( <API key>.CONSTANT_RANGE ), <API key>( <API key>.LINEAR_RANGE ), <API key>( <API key>.QUADRATIC_RANGE ), <API key>( <API key>.CUBIC_RANGE ) ]; // @public {Points} - Points for plotting curve. This includes points that are outside the bounds of the graph, // so be careful to call getRelevantPoints when using points in calculations. Order of the points doesn't matter. this.points = createPoints(); // @public {Curve} - the model of the curve this.curve = new Curve( this.points, this.sliderPropertyArray, this.orderProperty, this.fitProperty ); // @private {function} this.updateCurveFit = () => { this.curve.updateFit(); }; // validate Property values and update curve fit; unlink unnecessary present for the lifetime of the sim this.orderProperty.link( () => { this.updateCurveFit(); } ); // unlink unnecessary, present for the lifetime of the sim this.fitProperty.link( this.updateCurveFit ); // a change of any of the value sliders force an update of the curve model // unlinks unnecessary: present for lifetime of the sim this.sliderPropertyArray.forEach( sliderProperty => { sliderProperty.link( this.updateCurveFit ); } ); // Add internal listeners for adding and removing points this.points.<API key>( point => { this.addPoint( point ); } ); this.points.<API key>( point => { this.removePoint( point ); } ); } /** * Resets the model * @public */ reset() { this.sliderPropertyArray.forEach( sliderProperty => { sliderProperty.reset(); } ); this.orderProperty.reset(); this.fitProperty.reset(); this.points.reset(); this.curve.reset(); } /** * Adds a point * * @param {Point} point * @private */ addPoint( point ) { // These are unlinked in removePoint point.positionProperty.link( this.updateCurveFit ); point.<API key>.link( this.updateCurveFit ); point.deltaProperty.link( this.updateCurveFit ); const removePointListener = () => { if ( this.points.includes( point ) ) { this.points.remove( point ); } point.<API key>.removeListener( removePointListener ); }; // remove points when they have returned to the bucket // listener removes itself when called point.<API key>.addListener( removePointListener ); } /** * Removes a point * * @param {Point} point * @private */ removePoint( point ) { // These were linked in addPoint point.positionProperty.unlink( this.updateCurveFit ); point.<API key>.unlink( this.updateCurveFit ); point.deltaProperty.unlink( this.updateCurveFit ); this.updateCurveFit(); } } curveFitting.register( 'CurveFittingModel', CurveFittingModel ); export default CurveFittingModel;
{% extends 'main.html' %} {% block body %} <div class="row"> <div class="col-md-9"><h1>#{{problem[0]}}. {{problem[2]}}</h1></div> <div class="btn-group col-md-3"> <h1></h1> <button class="btn btn-info" onclick="window.location.href='/problem/{{problem[0]}}'"></button> <button data-toggle="dropdown" class="btn btn-info dropdown-toggle"><span class="caret"></span></button> <ul class="dropdown-menu" > <li> <a href="/problem/{{problem[0]}}/status"></a> </li> <li> <a href="#post"></a> </li> <li> <a href="#msg"></a> </li> <li class="divider"> </li> <li> <a href="/problem/{{problem[0]}}/edit/0"></a> </li> </ul> </div> </div> <br> <form class="form-horizontal"> <fieldset> <legend></legend> {% raw xsrf_form_html()%} <div class="form-group"> <label for="inputLang" class="col-lg-2 control-label"></label> <div class="col-lg-10"> <span class="help-block">['Error', 'C++', 'C', 'Python3', 'Python2.7'][ ? ]</span> <input class="form-control" name="lang" id="inputLang" value="1" disabled=""> </div> </div> <div class="form-group"> <label for="inputCode" class="col-lg-2 control-label"></label> <div class="col-lg-10"> <textarea class="form-control" rows="14" id="inputCode" name="code" required></textarea> </div> </div> <div class="form-group"> <div class="col-lg-10 col-lg-offset-2"> <button type="submit" formmethod="post" class="btn btn-primary"></button> </div> </div> </fieldset> </form> {% end %}
<!DOCTYPE html PUBLIC "- <html> <head> <title>Singular 2-0-4 Manual: 5.1.101 quot</title> <meta name="description" content="Singular 2-0-4 Manual: 5.1.101 quot"> <meta name="keywords" content="Singular 2-0-4 Manual: 5.1.101 quot"> <meta name="resource-type" content="document"> <meta name="distribution" content="global"> <meta name="Generator" content="texi2html"> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> <style type="text/css"> <! a.summary-letter {text-decoration: none} blockquote.smallquotation {font-size: smaller} div.display {margin-left: 3.2em} div.example {margin-left: 3.2em} div.lisp {margin-left: 3.2em} div.smalldisplay {margin-left: 3.2em} div.smallexample {margin-left: 3.2em} div.smalllisp {margin-left: 3.2em} pre.display {font-family: serif} pre.format {font-family: serif} pre.menu-comment {font-family: serif} pre.menu-preformatted {font-family: serif} pre.smalldisplay {font-family: serif; font-size: smaller} pre.smallexample {font-size: smaller} pre.smallformat {font-family: serif; font-size: smaller} pre.smalllisp {font-size: smaller} span.nocodebreak {white-space:pre} span.nolinebreak {white-space:pre} span.roman {font-family:serif; font-weight:normal} span.sansserif {font-family:sans-serif; font-weight:normal} ul.no-bullet {list-style: none} </style> </head> <body lang="en" background="../singular_images/Mybg.png"> <a name="quot"></a> <table border="0" cellpadding="0" cellspacing="0"> <tr valign="top"> <td align="left"> <table class="header" cellpadding="1" cellspacing="1" border="0"> <tr valign="top" align="left"> <td valign="middle" align="left"> <a href="index.htm"><img src="../singular_images/<API key>.png" width="50" border="0" alt="Top"></a> </td> </tr> <tr valign="top" align="left"> <td valign="middle" align="left"><a href="qhweight.html#qhweight" title="Previous section in reading order"><img src="../singular_images/a_left.png" border="0" alt="Back: 5.1.100 qhweight" align="middle"></a></td> </tr> <tr valign="top" align="left"> <td valign="middle" align="left"><a href="quote.html#quote" title="Next section in reading order"><img src="../singular_images/a_right.png" border="0" alt="Forward: 5.1.102 quote" align="middle"></a></td> </tr> <tr valign="top" align="left"> <td valign="middle" align="left"><a href="<API key>.html#<API key>" title="Beginning of this chapter or previous chapter"><img src="../singular_images/a_leftdouble.png" border="0" alt="FastBack: 5 Functions and system variables" align="middle"></a></td> </tr> <tr valign="top" align="left"> <td valign="middle" align="left"><a href="Tricks-and-pitfalls.html#Tricks-and-pitfalls" title="Next chapter"><img src="../singular_images/a_rightdouble.png" border="0" alt="FastForward: 6 Tricks and pitfalls" align="middle"></a></td> </tr> <tr valign="top" align="left"> <td valign="middle" align="left"><a href="Functions.html#Functions" title="Up section"><img src="../singular_images/a_up.png" border="0" alt="Up: 5.1 Functions" align="middle"></a></td> </tr> <tr valign="top" align="left"> <td valign="middle" align="left"><a href="index.htm#Preface" title="Cover (top) of document"><img src="../singular_images/a_top.png" border="0" alt="Top: 1 Preface" align="middle"></a></td> </tr> <tr valign="top" align="left"> <td valign="middle" align="left"><a href="sing_toc.htm#SEC_Contents" title="Table of contents"><img src="../singular_images/a_tableofcon.png" border="0" alt="Contents: Table of Contents" align="middle"></a></td> </tr> <tr valign="top" align="left"> <td valign="middle" align="left"><a href="Index.html#Index" title="Index"><img src="../singular_images/a_index.png" border="0" alt="Index: F Index" align="middle"></a></td> </tr> <tr valign="top" align="left"> <td valign="middle" align="left"><a href="sing_abt.htm#SEC_About" title="About (help)"><img src="../singular_images/a_help.png" border="0" alt="About: About This Document" align="middle"></a></td> </tr> </table> </td> <td align="left"> <a name="quot-1"></a> <h3 class="subsection">5.1.101 quot</h3> <a name="index-quot"></a> <p>Procedure from library <code>standard.lib</code> (see <a href="standard_005flib.html#standard_005flib">standard_lib</a>). </p> <dl compact="compact"> <dt><strong>Syntax:</strong></dt> <dd><p><code>quot (</code> module_expression<code>,</code> module_expression <code>)</code> <br><code>quot (</code> module_expression<code>,</code> module_expression<code>,</code> int_expression <code>)</code> <br><code>quot (</code> ideal_expression<code>,</code> ideal_expression <code>)</code> <br><code>quot (</code> ideal_expression<code>,</code> ideal_expression<code>,</code> int_expression <code>)</code> </p> </dd> <dt><strong>Type:</strong></dt> <dd><p>ideal </p> </dd> <dt><strong>Syntax:</strong></dt> <dd><p><code>quot (</code> module_expression<code>,</code> ideal_expression <code>)</code> </p> </dd> <dt><strong>Type:</strong></dt> <dd><p>module </p> </dd> <dt><strong>Purpose:</strong></dt> <dd><p>computes the quotient of the 1st and the 2nd argument. If a 3rd argument &rsquo;n&rsquo; is given the n-th method is used (n=1...5). </p> </dd> </dl> <p><strong>Example:</strong> </p><div class="smallexample"> <pre class="smallexample"> ring r=181,(x,y,z),(c,ls); ideal id1=maxideal(4); ideal id2=x2+xyz,y2-z3y,z3+y5xz; option(prot); ideal id3=quotient(id1,id2); &rarr; [1023:1]4(14)s(13)s(12)s(11)s(10)s(9)s(8)s(7)s(6)s(5)s(4)s(3)s(2)sss &rarr; product criterion:12 chain criterion:0 &rarr; {3}[1023:3]8(2)s(4)s(5)s9s.s.s.s.s.s &rarr; product criterion:0 chain criterion:39 id3; &rarr; id3[1]=z2 &rarr; id3[2]=yz &rarr; id3[3]=y2 &rarr; id3[4]=xz &rarr; id3[5]=xy &rarr; id3[6]=x2 ideal id4=quot(id1,id2,1); &rarr; [1023:2]4(14)s(13)s(12)s(11)s(10)s(9)s(8)s(7)s(6)s(5)s(4)s(3)s(2)sss &rarr; product criterion:0 chain criterion:0 &rarr; (S:3)rtrtrt &rarr; {1}[1023:3]4(2)s(4)s(5)s5s.s(3)s(2)sss &rarr; product criterion:0 chain criterion:39 &rarr; {1}[1023:3]4(5)s(4)s(3)s(2)sss &rarr; product criterion:0 chain criterion:9 &rarr; [255:3]3(11)s(10)sss(9)s(10)s(8)ss(7)s(8)s(6)s(7)s4(5) &rarr; product criterion:12 chain criterion:9 &rarr; {1}[1023:3]4(2)sss &rarr; product criterion:0 chain criterion:12 &rarr; [255:3]2(8)s(7)s(6)s3(5)ssssss4 &rarr; product criterion:15 chain criterion:3 id4; &rarr; id4[1]=z2 &rarr; id4[2]=yz &rarr; id4[3]=xz &rarr; id4[4]=y2 &rarr; id4[5]=xy &rarr; id4[6]=x2 ideal id5=quot(id1,id2,2); &rarr; [1023:2]4(14)s(13)s(12)s(11)s(10)s(9)s(8)s(7)s(6)s(5)s(4)s(3)s(2)sss &rarr; product criterion:0 chain criterion:0 &rarr; (S:3)rtrtrt &rarr; {1}[1023:3]4(2)sss &rarr; product criterion:0 chain criterion:12 &rarr; {1}[1023:3]4(5)s(4)s(3)s(2)sss &rarr; product criterion:0 chain criterion:9 &rarr; [255:3]2(8)s(7)s(6)s3(5)s(4)s(3)s(2)sss &rarr; product criterion:15 chain criterion:0 id5; &rarr; id5[1]=z2 &rarr; id5[2]=yz &rarr; id5[3]=xz &rarr; id5[4]=y2 &rarr; id5[5]=xy &rarr; id5[6]=x2 </pre></div> <p><strong>See also:</strong> <a href="quotient.html#quotient">quotient</a>. </p> </td> </tr> </table> <hr> <table class="header" cellpadding="1" cellspacing="1" border="0"> <tr><td valign="middle" align="left"> <a href="index.htm"><img src="../singular_images/<API key>.png" width="50" border="0" alt="Top"></a> </td> <td valign="middle" align="left"><a href="qhweight.html#qhweight" title="Previous section in reading order"><img src="../singular_images/a_left.png" border="0" alt="Back: 5.1.100 qhweight" align="middle"></a></td> <td valign="middle" align="left"><a href="quote.html#quote" title="Next section in reading order"><img src="../singular_images/a_right.png" border="0" alt="Forward: 5.1.102 quote" align="middle"></a></td> <td valign="middle" align="left"><a href="<API key>.html#<API key>" title="Beginning of this chapter or previous chapter"><img src="../singular_images/a_leftdouble.png" border="0" alt="FastBack: 5 Functions and system variables" align="middle"></a></td> <td valign="middle" align="left"><a href="Tricks-and-pitfalls.html#Tricks-and-pitfalls" title="Next chapter"><img src="../singular_images/a_rightdouble.png" border="0" alt="FastForward: 6 Tricks and pitfalls" align="middle"></a></td> <td valign="middle" align="left"><a href="Functions.html#Functions" title="Up section"><img src="../singular_images/a_up.png" border="0" alt="Up: 5.1 Functions" align="middle"></a></td> <td valign="middle" align="left"><a href="index.htm#Preface" title="Cover (top) of document"><img src="../singular_images/a_top.png" border="0" alt="Top: 1 Preface" align="middle"></a></td> <td valign="middle" align="left"><a href="sing_toc.htm#SEC_Contents" title="Table of contents"><img src="../singular_images/a_tableofcon.png" border="0" alt="Contents: Table of Contents" align="middle"></a></td> <td valign="middle" align="left"><a href="Index.html#Index" title="Index"><img src="../singular_images/a_index.png" border="0" alt="Index: F Index" align="middle"></a></td> <td valign="middle" align="left"><a href="sing_abt.htm#SEC_About" title="About (help)"><img src="../singular_images/a_help.png" border="0" alt="About: About This Document" align="middle"></a></td> </tr></table> <font size="-1"> &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; User manual for <a href="http: generated by <a href="http: </font> </body> </html>
var colorpick = new Array(); function connectionDelete(id, newConnection) { if(newConnection){ var aid = document.getElementById('newCalendarAid' + id).value; var row = document.getElementById('newCalendar' + id); row.parentNode.removeChild(row); //add almanach to selection list for(var i = 0; i < document.getElementById('calendarSelection').options.length; i ++){ if(document.getElementById('calendarSelection').options[i].value == aid){ document.getElementById('calendarSelection').options[i].style.display = "block"; break; } } } else { if(confirm("Soll dieser Termin wirklich nicht in den Kalender eingetragen werden?")) { var aid = document.getElementById('almanachId' + id).value; //delete line in table document.getElementById('Calendar'+ id).style.display = "none"; document.getElementById('connectionDeleted' + id).value = "1"; //add almanach to selection list for(var i = 0; i < document.getElementById('calendarSelection').options.length; i ++){ if(document.getElementById('calendarSelection').options[i].value == aid){ document.getElementById('calendarSelection').options[i].style.display = "block"; break; } } document.getElementById("calendarSelection").selectedIndex = "0"; } } } function calendarInput() { var e = document.getElementById("calendarSelection"); var aid = e.options[e.selectedIndex].value; var almanachName = e.options[e.selectedIndex].text; var newId = parseInt(document.getElementById('newCalendarsNum').value); var allowDateColoring = document.getElementById('allowDateColoring').value; if(aid <= 0) return; table = document.getElementById('calendarlist').<API key>('tbody')[0]; document.getElementById('newCalendarsNum').value = newId + 1; var newRow = table.insertRow(table.rows.length); newRow.setAttribute("id", "newCalendar" + newId, 0); //first cell ist aid input var input = document.createElement("input"); input.type = "text"; input.value = aid; input.style.display = "none"; input.id = "newCalendarAid" + newId; input.setAttribute("name", "newCalendarAid" + newId); //third cell chooses the color var div = document.createElement("div"); div.className = "z-formrow"; var colorinput = document.createElement("input"); colorinput.type = "text"; colorinput.id = "<API key>" + newId; colorinput.setAttribute("name", "<API key>" + newId); colorinput.className = "colorpicker"; colorinput.size = 7; colorinput.maxLength = 7; div.appendChild(colorinput); //last cell, to delete the heredity var a = document.createElement("A"); a.className = "z-button"; a.onclick = function() { connectionDelete( newId , true); } a.innerHTML = document.getElementById('deleteImage').innerHTML; var cell1 = newRow.insertCell(0); var cell2 = newRow.insertCell(1); var cell3 = newRow.insertCell(2); var cell4 = newRow.insertCell(3); cell1.appendChild(input); cell2.innerHTML = almanachName; if(allowDateColoring != 0) cell3.appendChild(div); cell4.appendChild(a); //newRow.innerHTML = returns['newHeredity']; //delete almanach from dropdown for(var i = 0; i < document.getElementById('calendarSelection').options.length; i ++){ if(document.getElementById('calendarSelection').options[i].value == aid){ document.getElementById('calendarSelection').options[i].style.display = "none"; break; } } document.getElementById("calendarSelection").selectedIndex = "0"; //Colorpicker erstellen: var name = "<API key>"; name = name + newId; colorpick[colorpick.length] = new PickyColor({ field: name, color: '', colorWell: name, closeText: "Schließen" }); }
import {PluginError, color, log} from 'gulp-util'; import config from 'config/webpack'; import webpack from 'webpack'; export default function buildAssets(cb) { const statsOpts = { colors: true, hash: global.args.verbose, version: global.args.verbose, timings: global.args.verbose, assets: global.args.verbose, chunks: global.args.verbose, chunkModules: false, modules: false, cached: global.args.verbose, reasons: global.args.verbose, source: global.args.verbose, errorDetails: true, chunkOrigins: false }; webpack(config).run((err, stats) => { if (err) { log('build:assets', color.magenta(err.toString())); if (process.env.NODE_ENV === 'test') { throw err; } return cb(new PluginError('build:assets', err)); } if (stats.hasErrors()) { log('build:assets', stats.toString(statsOpts)); if (process.env.NODE_ENV === 'test') { throw new Error('Webpack build failed with errors.'); } return cb(); } if (global.args.verbose) { log('build:assets', stats.toString(statsOpts)); } cb(); }); }
<?php /** * IP * * @author Lukin <my@lukin.cn> * @version $Id$ */ class QQWry { private $fp = null; private $start = 0, $end = 0, $ctype = 0; private $fstart = 0, $lstart = 0, $offset = 0; // QQWry instance private static $instance; /** * Returns QQWry instance. * * @static * @param string $dat_file * @return QQWry */ public static function &instance($dat_file) { if (!self::$instance) { self::$instance = new QQWry($dat_file); } return self::$instance; } public function __construct($dat_file) { if (is_ifile($dat_file)) { $this->fp = fopen($dat_file,'rb'); } } private function init() { $this->start = $this->end = $this->ctype = $this->fstart = $this->lstart = $this->offset = 0; } private function start($number) { fseek($this->fp, $this->fstart + $number * 7); $buf = fread($this->fp, 7); $this->offset = ord($buf[4]) + (ord($buf[5]) * 256) + (ord($buf[6]) * 256 * 256); $this->start = ord($buf[0]) + (ord($buf[1]) * 256) + (ord($buf[2]) * 256 * 256) + (ord($buf[3]) * 256 * 256 * 256); return $this->start; } private function end() { fseek($this->fp, $this->offset); $buf = fread($this->fp, 5); $this->end = ord($buf[0]) + (ord($buf[1]) * 256) + (ord($buf[2]) * 256 * 256) + (ord($buf[3]) * 256 * 256 * 256); $this->ctype = ord($buf[4]); return $this->end; } private function get_addr() { $result = array(); switch ($this->ctype) { case 1: case 2: $result['Country'] = $this->get_str($this->offset + 4); $result['Local'] = (1 == $this->ctype) ? '' : $this->get_str($this->offset + 8); break; default : $result['Country'] = $this->get_str($this->offset + 4); $result['Local'] = $this->get_str(ftell($this->fp)); } return $result; } private function get_str($offset) { $result = ''; while (true) { fseek($this->fp, $offset); $flag = ord(fgetc($this->fp)); if ($flag == 1 || $flag == 2) { $buf = fread($this->fp, 3); if ($flag == 2) { $this->ctype = 2; $this->offset = $offset - 4; } $offset = ord($buf[0]) + (ord($buf[1]) * 256) + (ord($buf[2]) * 256 * 256); } else { break; } } if ($offset < 12) return $result; fseek($this->fp, $offset); while (true) { $c = fgetc($this->fp); if (ord($c[0]) == 0) break; $result.= $c; } return $result; } public function ip2addr($ipaddr) { if (!$this->fp) return $ipaddr; if (strpos($ipaddr, '.') !== false) { if (preg_match('/^(127)/', $ipaddr)) return __(''); $ip = sprintf('%u',ip2long($ipaddr)); } else { $ip = $ipaddr; } $this->init(); fseek($this->fp, 0); $buf = fread($this->fp, 8); $this->fstart = ord($buf[0]) + (ord($buf[1])*256) + (ord($buf[2])*256*256) + (ord($buf[3])*256*256*256); $this->lstart = ord($buf[4]) + (ord($buf[5])*256) + (ord($buf[6])*256*256) + (ord($buf[7])*256*256*256); $count = floor(($this->lstart - $this->fstart) / 7); if ($count <= 1) { fclose($this->fp); return $ipaddr; } $start = 0; $end = $count; while ($start < $end - 1) { $number = floor(($start + $end) / 2); $this->start($number); if ($ip == $this->start) { $start = $number; break; } if ($ip > $this->start) $start = $number; else $end = $number; } $this->start($start); $this->end(); if (($this->start <= $ip) && ($this->end >= $ip)) { $result = $this->get_addr(); } else { $result = array( 'Country' => __(''), 'Local' => '', ); } $result = trim(implode(' ', $result)); $result = iconv('GBK', 'UTF-8', $result); return $result; } public function __destruct() { if ($this->fp) fclose($this->fp); } }
<?php include 'settings.php'; require_once 'libops.php'; $page = unparty($_POST["page"]); $packs = MapPacks::get(); $str = ''; for ($i = 0; $i < 10; $i++) { if ($packs[$i+$page*10] == null) break; if ($i != 0) { echo '|'; $str .= ','; } $mp = $packs[$i+$page*10]; echo "1:".$mp["packID"].":2:".$mp["packName"].":3:".$mp["packLevels"].":4:".$mp["packStars"].":5:".$mp["packCoins"].":6:".$mp["packDifficulty"].":7:".$mp["packColor"].":8:".$mp["packColor"]; $str .= $mp['packID']; } echo '#' . count($packs) . ":$page:10#" . MapPacks::generate_hash($str);
#!/bin/sh # This file is part of InfiniSQL (tm). It is available either under the # This copy of InfiniSQL is free software: you can redistribute it and/or # (at your option) any later version. # InfiniSQL is distributed in the hope that it will be useful, # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # along with InfiniSQL. It should be in the top level of the source # directory in a file entitled "COPYING". for HOST in `grep -v '^#' clients | cut -f 1` do echo $HOST ssh $HOST "pkill -9 perl" ssh $HOST "pkill pgbench" done
# Demo code for statistical analysis of computational model (simulated data) Ito et al., 2017 # Takuya Ito (takuya.ito@rutgers.edu) ## Import modules import numpy as np import os import scipy.stats as stats import statsmodels.api as sm from scipy.stats import gamma import sys import <API key> as mreg import sklearn.svm as svm def setUpActFlowMat(subj,net,fromnet,tasks,nodespercommunity,nblocks=20,datadir='./'): """ Retrieves a predicted target network's activation pattern for a given source network. Organizes prediction data as sample (block) x feature (regions) matrix Parameters: subj = subjID (numeric) net = the target network (0 through 5; numeric) fromnet = the source network (0 through 5; numeric) tasks = taskIDs (array). tasks 1-4 are for the top down only task. tasks 5-9 are for the top down AND bottom up task stimulation. nodespercommunity = number of nodes per community; default 50 nblocks = number of blocks per task condition. Default = 20 per condition, 80 in total. datadir = directory that holds the simulation data Returns svmmat = a sample (block) X feature (regional activations) matrix labels = task condition labels associated for each block """ nsamples = len(tasks)*nblocks nfeatures = nodespercommunity # regions per network svm_mat = np.zeros((nsamples,nfeatures)) labels = np.zeros((nsamples,)) indir = datadir + '/actflow_predictions/' indcount = 0 for task in tasks: filename = 'subj'+str(subj)+'_task'+str(task)+'_net'+str(fromnet)+'tonet'+str(net)+'_multregFC.txt' actflowdat = np.loadtxt(indir+filename,delimiter=',') svm_mat[indcount:(indcount+nblocks),:] = actflowdat.T labels[indcount:(indcount+nblocks)] = task indcount += nblocks return svm_mat, labels def setUpBetasMat(subj,net,tasks,Ci,nodespercommunity,nblocks=20,datadir='./'): """ Retrieves a network's *actual* activation pattern. Organizes data as sample (block) x feature (regions) matrix Parameters: subj = subjID (numeric) net = the network's activation pattern to retreive (0 through 5; numeric) tasks = taskIDs (array). tasks 1-4 are for the top down only task. tasks 5-9 are for the top down AND bottom up task stimulation. nodespercommunity = number of nodes per community; default 50 nblocks = number of blocks per task condition. Default = 20 per condition, 80 in total. datadir = directory that holds the simulation data Returns svmmat = a sample (block) X feature (regional activations) matrix labels = task condition labels associated for each block """ nfeatures = nodespercommunity # Number of regions for each network nsamples = len(tasks)*nblocks svm_mat = np.zeros((nsamples,nfeatures)) labels =np.zeros((nsamples,)) net_ind = np.where(Ci==net)[0] #net_ind = np.arange(net*nodespercommunity,net*nodespercommunity+nodespercommunity) indir = datadir + '/task_betas/' indcount = 0 for task in tasks: filename = 'subj'+str(subj)+'_task'+str(task)+'_allblocks.txt' betas = np.loadtxt(indir + filename, delimiter=',') # Get relevant network data svm_mat[indcount:(indcount+nblocks),:] = betas[net_ind,:].T # get all trials labels[indcount:(indcount+nblocks)] = task indcount += nblocks # Demean svm_mat across features for each sample mean_tmp = np.mean(svm_mat,axis=1) mean_tmp.shape = (len(mean_tmp),1) svm_mat = svm_mat - mean_tmp return svm_mat, labels def <API key>((subj,net,fromnet,tasks,nblocks,Ci,nodespercommunity,datadir)): """ Runs a leave-block-out CV style RSA analysis (leaving 4 blocks out per CV) This code performs the 2nd and 3rd steps in the 'information transfer mapping' procedure Trains on predicted ActFlow data Tests on real data (betas) Parameters: subj = subjID (numeric) net = the target network (0 through 5; numeric) fromnet = the source network (0 through 5; numeric) tasks = taskIDs (array). tasks 1-4 are for the top down only task. tasks 5-9 are for the top down AND bottom up task stimulation. nblocks = number of blocks per task condition. Default = 20 per condition, 80 in total. Ci = community affiliation vector nodespercommunity = number of nodes per community; default 50 datadir = directory that holds the simulation data Returns info_transfer_est = the average information transfer estimate """ actflow_mat, labels = setUpActFlowMat(subj,net,fromnet,tasks,nodespercommunity,nblocks=nblocks,datadir=datadir) real_mat, labels = setUpBetasMat(subj,net,tasks,Ci,nodespercommunity,nblocks=nblocks,datadir=datadir) ncvs = nblocks indices = np.arange(actflow_mat.shape[0]) matched_rhos = [] mismatch_rhos = [] for cv in range(ncvs): task_ind = {} prototype = {} # Construct prototypes of each task for task in tasks: # Get indices for this particular task task_ind[task] = np.where(labels==task)[0] # Decide which one is your 'comparison test trial' will be test_ind = task_ind[task][cv] # Find the indices for the prototypes train_ind = np.setxor1d(test_ind,task_ind[task]) prototype[task] = np.mean(real_mat[train_ind,:],axis=0) # Now compare each pair of tasks with the prototype for task_a in tasks: for task_b in tasks: test_ind = task_ind[task_a][cv] # Compare task a rho_tmp = stats.spearmanr(prototype[task_b].T,actflow_mat[test_ind,:].T)[0] # With task b rho_tmp = np.arctanh(rho_tmp) if task_a==task_b: # Match! matched_rhos.append(rho_tmp) else: mismatch_rhos.append(rho_tmp) # Get averages matched_rhos_avg = np.mean(matched_rhos) mismatch_rhos_avg = np.mean(mismatch_rhos) info_transfer_est = matched_rhos_avg - mismatch_rhos_avg return info_transfer_est def <API key>((subj,net,fromnet,tasks,nblocks,Ci,nodespercommunity,datadir)): """ Runs a leave-block-out CV style SVM analysis (leaving 4 blocks out per CV) This analysis corresponds to the SVM analysis in Supplementary Fig. 3 Trains on predicted ActFlow data Tests on real data (betas) Parameters: subj = subjID (numeric) net = the target network (0 through 5; numeric) fromnet = the source network (0 through 5; numeric) tasks = taskIDs (array). tasks 1-4 are for the top down only task. tasks 5-9 are for the top down AND bottom up task stimulation. nblocks = number of blocks per task condition. Default = 20 per condition, 80 in total. Ci = community affiliation vector nodespercommunity = number of nodes per community; default 50 datadir = directory that holds the simulation data Returns The mean decoding accuracy on the target network's actual activation pattern """ actflow_mat, labels = setUpActFlowMat(subj,net,fromnet,tasks,nodespercommunity,nblocks=nblocks,datadir=datadir) real_mat, labels = setUpBetasMat(subj,net,tasks,Ci,nodespercommunity,nblocks=nblocks,datadir=datadir) # Normalize #actflow_mat = preprocessing.scale(actflow_mat, axis=0) #real_mat = preprocessing.scale(real_mat, axis=0) ncvs = nblocks indices = np.arange(actflow_mat.shape[0]) clf = svm.SVC(C=1.0,kernel='linear') accuracy = [] # Starting test indices test_ind = np.arange(0,80,20) for cv in range(ncvs): train_ind = np.setxor1d(test_ind,indices) trainset = actflow_mat[train_ind,:] testset = real_mat[test_ind,:] trainset_labels = labels[train_ind] testset_labels = labels[test_ind] # Normalize the train set across samples (for each feature) trainset_mean = np.mean(trainset,axis=0) trainset_mean.shape = (1,len(trainset_mean)) trainset_std = np.std(trainset, axis=0) trainset_std.shape = (1,len(trainset_std)) trainset = np.divide((trainset - trainset_mean),trainset_std) # Normalize test set using the mean and std from the trainset (to avoid non-circularity) testset = np.divide((testset - trainset_mean),trainset_std) clf.fit(trainset, trainset_labels) accuracy.append(clf.score(testset, testset_labels)) # Change new testing group test_ind += 1 return np.mean(accuracy)
#include "sae_par.h" #include "ary1.h" #include "star/hds.h" #include "mers.h" void ary1Annpl( int erase, AryPCB **pcb, int *status ) { /* Local variables: */ int tstat; /* Temporary status variable */ /* Save the status value and mark the error stack. */ tstat = *status; errMark(); /* If required, erase the associated object, annulling it's locator in the process. */ *status = SAI__OK; if( erase ){ ary1Antmp( &(*pcb)->loc, status ); /* Otherwise, simply annul the locator. */ } else { datAnnul( &(*pcb)->loc, status ); } /* Release the PCB slot. */ *pcb = ary1Rls( (AryObject *) *pcb, status ); /* Annul any error if STATUS was previously bad, otherwise let the new error report stand. */ if( *status != SAI__OK ){ if( tstat != SAI__OK ){ errAnnul( status ); *status = tstat; /* Call error tracing routine if appropriate. */ } else { ary1Trace( "ary1Annpl", status ); } } else { *status = tstat; } /* Release error stack. */ errRlse(); }
<?php require('./system.php'); function CheckPostComplect() { $input = array( 'login' => Filter::input('login'), 'pass' => Filter::input('pass'), 'repass' => Filter::input('repass'), 'email' => Filter::input('email', 'post', 'mail'), 'female' => Filter::input('female', 'post', 'bool'), 'verificate' => Filter::input('verificate', 'get'), 'id' => Filter::input('id', 'post', 'int'), 'method' => false ); if (!$input['id']) $input['id'] = Filter::input('id', 'get', 'int'); if ($input['login'] and $input['pass'] and $input['repass']) $input['method'] = 1; if ($input['verificate'] and $input['id']) $input['method'] = 2; return $input; } $input = CheckPostComplect(); if (!$input['method']) exit; loadTool('ajax.php'); if ($config['p_logic'] != 'usual' and $config['p_logic'] != 'xauth' and $config['p_logic'] != 'authme') aExit(1, 'Registration is blocked. Used auth script from main CMS'); DBinit('register'); loadTool('user.class.php'); $rcodes = array(); function tryExit() { global $rcodes; $message = ''; $rnum = sizeof($rcodes); if (!$rnum) return; for ($i = 0; $i < $rnum; $i++) { $modifed = true; switch ($rcodes[$i]) { case 2 : $message .= lng('INCORRECT') . '. (' . lng('LOGIN') . ')'; break; case 3 : $message .= lng('INCORRECT') . '. (' . lng('PASS') . ')'; break; case 4 : $message .= lng('INCORRECT') . '. (' . lng('REPASS') . ')'; break; case 12 : $message .= lng('INCORRECT') . '. (' . lng('EMAIL') . ')'; break; case 6 : $message .= lng('INCORRECT_LEN') . '. (' . lng('LOGIN') . ')'; break; case 7 : $message .= lng('INCORRECT_LEN') . '. (' . lng('PASS') . ')'; break; case 8 : $message .= lng('INCORRECT_LEN') . '. (' . lng('REPASS') . ')'; break; case 9 : $message .= lng('REPASSVSPASS'); break; case 13 : $message .= lng('INCORRECT_LEN') . '. (' . lng('EMAIL') . ')'; break; default : $modifed = false; break; } if ($modifed) $message .= "<br />"; } aExit(2, $message); } if ($input['method'] == 2) { $tmp_user = new User($input['id']); if ($tmp_user->id() and !strcmp($tmp_user->getVerificationStr(), $input['verificate'])) $tmp_user->changeGroup(1); exit(View::ShowStaticPage('<API key>.html', 'other/')); } RefreshBans(); $female = ($input['female']) ? 1 : 0; if (!CanAccess()) aExit(11, lng('IP_BANNED')); if (empty($input['login']) || empty($input['pass']) || empty($input['repass'])) aExit(1, lng('INCOMPLETE_FORM')); if (!preg_match("/^[a-zA-Z0-9_-]+$/", $input['login'])) $rcodes[] = 2; if (!preg_match("/^[a-zA-Z0-9_-]+$/", $input['pass'])) $rcodes[] = 3; if (!preg_match("/^[a-zA-Z0-9_-]+$/", $input['repass'])) $rcodes[] = 4; if (!$input['email']) $rcodes[] = 12; tryExit(); $sql = "SELECT COUNT(*) FROM `{$bd_names['users']}` " . "WHERE `{$bd_users['login']}`=:login"; $line = getDB()->fetchRow($sql, array('login' => $input['login']), 'num'); if ($line[0]) aExit(5, lng('AUTH_EXIST_LOGIN')); $sql = "SELECT COUNT(*) FROM `{$bd_names['users']}` " . "WHERE `{$bd_users['email']}`=:email"; $line = getDB()->fetchRow($sql, array('email' => $input['email']), 'num'); if ($line[0]) aExit(15, lng('AUTH_EXIST_EMAIL')); if ((strlen($input['login']) < 4) or (strlen($input['login']) > 15)) $rcodes[] = 6; if ((strlen($input['pass']) < 4) or (strlen($input['pass']) > 15)) $rcodes[] = 7; if ((strlen($input['repass']) < 4) or (strlen($input['repass']) > 15)) $rcodes[] = 8; if (strlen($input['email']) > 50) $rcodes[] = 13; if (strcmp($input['pass'], $input['repass'])) $rcodes[] = 9; tryExit(); $verification = (bool) sqlConfigGet('email-verification'); if ($verification) $group = 4; else $group = 1; $sql = "INSERT INTO `{$bd_names['users']}` (" . "`{$bd_users['login']}`," . "`{$bd_users['password']}`," . "`{$bd_users['ip']}`," . "`{$bd_users['female']}`," . "`{$bd_users['ctime']}`," . "`{$bd_users['group']}`) VALUES(:login, :pass, :ip, '$female', NOW(),'$group')"; $result = getDB()->ask($sql, array( 'login' => $input['login'], 'pass' => MCRAuth::createPass($input['pass']), 'ip' => GetRealIp() )); if (!$result) aExit(14); $tmp_user = new User(getDB()->lastInsertId()); $tmp_user->setDefaultSkin(); $next_reg = (int) sqlConfigGet('next-reg-time'); if ($next_reg > 0) getDB()->ask("INSERT INTO `{$bd_names['ip_banning']}` (`IP`,`time_start`,`ban_until`) " . "VALUES (:ip, NOW(), NOW()+INTERVAL $next_reg HOUR)", array('ip' => $_SERVER['REMOTE_ADDR'])); if ($tmp_user->changeEmail($input['email'], $verification) > 1) aExit(14, lng('MAIL_FAIL')); if (!$verification) aExit(0, lng('REG_COMPLETE') . '. <a href="#" class="btn" onclick="Login();">' . lng('ENTER') . '</a>'); else aExit(0, lng('REG_COMPLETE') . '. ' . lng('REG_CONFIRM_INFO'));
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace SystemsGame { static class Singiltons { public static Network LocalNetwork = new Network("Local", false); public static ComputerSystem LocalHost; public static Session LocalSession; public static Random rand = new Random(); public static List<Network> Networks = new List<Network>(); private static char[] <API key> = "0123456789ABCDEF".ToCharArray(); public static string GetRandomWord(int length) { string str = ""; for (int i = 0; i < length; i++) { str += <API key>[rand.Next(<API key>.Length)]; } return str; } public static void GenerateNetworks() { LocalHost = new ComputerSystem(LocalNetwork); LocalNetwork.AllSystems.Add(LocalHost); LocalSession = new Session(LocalHost.GetUser("Admin")); for (int i = 0; i < 5; i++) { Networks.Add(new Network()); } } } }
<!DOCTYPE HTML PUBLIC "- <!--NewPage <HTML> <HEAD> <!-- Generated by javadoc (build 1.6.0_05) on Mon Feb 23 23:48:53 EST 2009 --> <TITLE> ObedientViewFactory (KawigiEdit) </TITLE> <META NAME="date" CONTENT="2009-02-23"> <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="ObedientViewFactory (KawigiEdit)"; } } </SCRIPT> <NOSCRIPT> </NOSCRIPT> </HEAD> <BODY BGCOLOR="white" onload="windowTitle();"> <HR> <A NAME="navbar_top"></A> <A HREF="#skip-navbar_top" title="Skip navigation links"></A> <TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0" SUMMARY=""> <TR> <TD COLSPAN=2 BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A NAME="navbar_top_firstrow"></A> <TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3" SUMMARY=""> <TR ALIGN="center" VALIGN="top"> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../overview-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="package-summary.html"><FONT CLASS="NavBarFont1"><B>Package</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> &nbsp;<FONT CLASS="NavBarFont1Rev"><B>Class</B></FONT>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="package-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../index-all.html"><FONT CLASS="NavBarFont1"><B>Index</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A>&nbsp;</TD> </TR> </TABLE> </TD> <TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM> </EM> </TD> </TR> <TR> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> &nbsp;<A HREF="../../kawigi/editor/LineNumbers.html" title="class in kawigi.editor"><B>PREV CLASS</B></A>&nbsp; &nbsp;<A HREF="../../kawigi/editor/VBView.html" title="class in kawigi.editor"><B>NEXT CLASS</B></A></FONT></TD> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> <A HREF="../../index.html?kawigi/editor/ObedientViewFactory.html" target="_top"><B>FRAMES</B></A> &nbsp; &nbsp;<A HREF="ObedientViewFactory.html" target="_top"><B>NO FRAMES</B></A> &nbsp; &nbsp;<SCRIPT type="text/javascript"> <! if(window==top) { document.writeln('<A HREF="../../allclasses-noframe.html"><B>All Classes</B></A>'); } </SCRIPT> <NOSCRIPT> <A HREF="../../allclasses-noframe.html"><B>All Classes</B></A> </NOSCRIPT> </FONT></TD> </TR> <TR> <TD VALIGN="top" CLASS="NavBarCell3"><FONT SIZE="-2"> SUMMARY:&nbsp;NESTED&nbsp;|&nbsp;<A HREF="#field_summary">FIELD</A>&nbsp;|&nbsp;<A HREF="#constructor_summary">CONSTR</A>&nbsp;|&nbsp;<A HREF="#method_summary">METHOD</A></FONT></TD> <TD VALIGN="top" CLASS="NavBarCell3"><FONT SIZE="-2"> DETAIL:&nbsp;<A HREF="#field_detail">FIELD</A>&nbsp;|&nbsp;<A HREF="#constructor_detail">CONSTR</A>&nbsp;|&nbsp;<A HREF="#method_detail">METHOD</A></FONT></TD> </TR> </TABLE> <A NAME="skip-navbar_top"></A> <HR> <H2> <FONT SIZE="-1"> kawigi.editor</FONT> <BR> Class ObedientViewFactory</H2> <PRE> java.lang.Object <IMG SRC="../../resources/inherit.gif" ALT="extended by "><B>kawigi.editor.ObedientViewFactory</B> </PRE> <DL> <DT><B>All Implemented Interfaces:</B> <DD>javax.swing.text.ViewFactory</DD> </DL> <HR> <DL> <DT><PRE>public class <B>ObedientViewFactory</B><DT>extends java.lang.Object<DT>implements javax.swing.text.ViewFactory</DL> </PRE> <P> Obedient because it returns what I tell it to. Also sounds better than "HackedViewFactory". <P> <P> <HR> <P> <A NAME="field_summary"></A> <TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY=""> <TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor"> <TH ALIGN="left" COLSPAN="2"><FONT SIZE="+2"> <B>Field Summary</B></FONT></TH> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1"> <CODE>protected &nbsp;java.lang.Class&lt;? extends javax.swing.text.View&gt;</CODE></FONT></TD> <TD><CODE><B><A HREF="../../kawigi/editor/ObedientViewFactory.html#viewClass">viewClass</A></B></CODE> <BR> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Class from which Views are made in this ViewFactory.</TD> </TR> </TABLE> &nbsp; <A NAME="constructor_summary"></A> <TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY=""> <TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor"> <TH ALIGN="left" COLSPAN="2"><FONT SIZE="+2"> <B>Constructor Summary</B></FONT></TH> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD><CODE><B><A HREF="../../kawigi/editor/ObedientViewFactory.html#ObedientViewFactory()">ObedientViewFactory</A></B>()</CODE> <BR> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Creates an ObedientViewFactory with no default View implementation.</TD> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD><CODE><B><A HREF="../../kawigi/editor/ObedientViewFactory.html#ObedientViewFactory(java.lang.Class)">ObedientViewFactory</A></B>(java.lang.Class&lt;? extends javax.swing.text.View&gt;&nbsp;v)</CODE> <BR> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Creates an ObedientViewFactory using v as the View implementation class.</TD> </TR> </TABLE> &nbsp; <A NAME="method_summary"></A> <TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY=""> <TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor"> <TH ALIGN="left" COLSPAN="2"><FONT SIZE="+2"> <B>Method Summary</B></FONT></TH> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1"> <CODE>&nbsp;javax.swing.text.View</CODE></FONT></TD> <TD><CODE><B><A HREF="../../kawigi/editor/ObedientViewFactory.html#create(javax.swing.text.Element)">create</A></B>(javax.swing.text.Element&nbsp;elem)</CODE> <BR> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Creates a View instance of the class designated to this ViewFactory.</TD> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1"> <CODE>&nbsp;void</CODE></FONT></TD> <TD><CODE><B><A HREF="../../kawigi/editor/ObedientViewFactory.html#setViewClass(java.lang.Class)">setViewClass</A></B>(java.lang.Class&lt;? extends javax.swing.text.View&gt;&nbsp;v)</CODE> <BR> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Sets the class of the View implementation to be used.</TD> </TR> </TABLE> &nbsp;<A NAME="<API key>.lang.Object"></A> <TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY=""> <TR BGCOLOR="#EEEEFF" CLASS="<API key>"> <TH ALIGN="left"><B>Methods inherited from class java.lang.Object</B></TH> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD><CODE>clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait</CODE></TD> </TR> </TABLE> &nbsp; <P> <A NAME="field_detail"></A> <TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY=""> <TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor"> <TH ALIGN="left" COLSPAN="1"><FONT SIZE="+2"> <B>Field Detail</B></FONT></TH> </TR> </TABLE> <A NAME="viewClass"></A><H3> viewClass</H3> <PRE> protected java.lang.Class&lt;? extends javax.swing.text.View&gt; <B>viewClass</B></PRE> <DL> <DD>Class from which Views are made in this ViewFactory. <P> <DL> </DL> </DL> <A NAME="constructor_detail"></A> <TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY=""> <TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor"> <TH ALIGN="left" COLSPAN="1"><FONT SIZE="+2"> <B>Constructor Detail</B></FONT></TH> </TR> </TABLE> <A NAME="ObedientViewFactory()"></A><H3> ObedientViewFactory</H3> <PRE> public <B>ObedientViewFactory</B>()</PRE> <DL> <DD>Creates an ObedientViewFactory with no default View implementation. <P> </DL> <HR> <A NAME="ObedientViewFactory(java.lang.Class)"></A><H3> ObedientViewFactory</H3> <PRE> public <B>ObedientViewFactory</B>(java.lang.Class&lt;? extends javax.swing.text.View&gt;&nbsp;v)</PRE> <DL> <DD>Creates an ObedientViewFactory using v as the View implementation class. v should be compatible with javax.swing.text.View. <P> </DL> <A NAME="method_detail"></A> <TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY=""> <TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor"> <TH ALIGN="left" COLSPAN="1"><FONT SIZE="+2"> <B>Method Detail</B></FONT></TH> </TR> </TABLE> <A NAME="setViewClass(java.lang.Class)"></A><H3> setViewClass</H3> <PRE> public void <B>setViewClass</B>(java.lang.Class&lt;? extends javax.swing.text.View&gt;&nbsp;v)</PRE> <DL> <DD>Sets the class of the View implementation to be used. v should be compatible with javax.swing.text.View. <P> <DD><DL> </DL> </DD> <DD><DL> </DL> </DD> </DL> <HR> <A NAME="create(javax.swing.text.Element)"></A><H3> create</H3> <PRE> public javax.swing.text.View <B>create</B>(javax.swing.text.Element&nbsp;elem)</PRE> <DL> <DD>Creates a View instance of the class designated to this ViewFactory. If it fails for some reason (i.e. - no View class specified or the given view class doesn't except a single Element parameter for its constructor), a GenericView is returned. <P> <DD><DL> <DT><B>Specified by:</B><DD><CODE>create</CODE> in interface <CODE>javax.swing.text.ViewFactory</CODE></DL> </DD> <DD><DL> </DL> </DD> </DL> <HR> <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="<API key>"></A> <TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3" SUMMARY=""> <TR ALIGN="center" VALIGN="top"> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../overview-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="package-summary.html"><FONT CLASS="NavBarFont1"><B>Package</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> &nbsp;<FONT CLASS="NavBarFont1Rev"><B>Class</B></FONT>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="package-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../index-all.html"><FONT CLASS="NavBarFont1"><B>Index</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A>&nbsp;</TD> </TR> </TABLE> </TD> <TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM> </EM> </TD> </TR> <TR> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> &nbsp;<A HREF="../../kawigi/editor/LineNumbers.html" title="class in kawigi.editor"><B>PREV CLASS</B></A>&nbsp; &nbsp;<A HREF="../../kawigi/editor/VBView.html" title="class in kawigi.editor"><B>NEXT CLASS</B></A></FONT></TD> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> <A HREF="../../index.html?kawigi/editor/ObedientViewFactory.html" target="_top"><B>FRAMES</B></A> &nbsp; &nbsp;<A HREF="ObedientViewFactory.html" target="_top"><B>NO FRAMES</B></A> &nbsp; &nbsp;<SCRIPT type="text/javascript"> <! if(window==top) { document.writeln('<A HREF="../../allclasses-noframe.html"><B>All Classes</B></A>'); } </SCRIPT> <NOSCRIPT> <A HREF="../../allclasses-noframe.html"><B>All Classes</B></A> </NOSCRIPT> </FONT></TD> </TR> <TR> <TD VALIGN="top" CLASS="NavBarCell3"><FONT SIZE="-2"> SUMMARY:&nbsp;NESTED&nbsp;|&nbsp;<A HREF="#field_summary">FIELD</A>&nbsp;|&nbsp;<A HREF="#constructor_summary">CONSTR</A>&nbsp;|&nbsp;<A HREF="#method_summary">METHOD</A></FONT></TD> <TD VALIGN="top" CLASS="NavBarCell3"><FONT SIZE="-2"> DETAIL:&nbsp;<A HREF="#field_detail">FIELD</A>&nbsp;|&nbsp;<A HREF="#constructor_detail">CONSTR</A>&nbsp;|&nbsp;<A HREF="#method_detail">METHOD</A></FONT></TD> </TR> </TABLE> <A NAME="skip-navbar_bottom"></A> <HR> </BODY> </HTML>
#pragma once #define RAD_TO_DEG(deg) ((deg) * 180.0 / M_PI) #define DEG_TO_RAD(rad) ((rad) * M_PI / 180.0) class CBasePlayer; class BotProfile; enum PriorityType { PRIORITY_LOW, PRIORITY_MEDIUM, PRIORITY_HIGH, <API key> }; // Simple class for tracking intervals of game time class IntervalTimer { public: IntervalTimer() { m_timestamp = -1.0f; } void Reset() { m_timestamp = gpGlobals->time; } void Start() { m_timestamp = gpGlobals->time; } void Invalidate() { m_timestamp = -1.0f; } bool HasStarted() const { return (m_timestamp > 0.0f); } // if not started, elapsed time is very large float GetElapsedTime() const { return (HasStarted()) ? (gpGlobals->time - m_timestamp) : 99999.9f; } bool IsLessThen(float duration) const { return (gpGlobals->time - m_timestamp < duration) ? true : false; } bool IsGreaterThen(float duration) const { return (gpGlobals->time - m_timestamp > duration) ? true : false; } private: float m_timestamp; }; // Simple class for counting down a short interval of time class CountdownTimer { public: CountdownTimer() { m_timestamp = -1.0f; m_duration = 0.0f; } void Reset() { m_timestamp = gpGlobals->time + m_duration; } void Start(float duration) { m_timestamp = gpGlobals->time + duration; m_duration = duration; } bool HasStarted() const { return (m_timestamp > 0.0f); } void Invalidate() { m_timestamp = -1.0f; } bool IsElapsed() const { return (gpGlobals->time > m_timestamp); } private: float m_duration; float m_timestamp; }; // Return true if the given entity is valid inline bool IsEntityValid(CBaseEntity *pEntity) { if (!pEntity) return false; if (FNullEnt(pEntity->pev)) return false; if (FStrEq(STRING(pEntity->pev->netname), "")) return false; if (pEntity->IsDormant()) return false; return true; } // Given two line segments: startA to endA, and startB to endB, return true if they intesect // and put the intersection point in "result". // Note that this computes the intersection of the 2D (x,y) projection of the line segments. inline bool IsIntersecting2D(const Vector &startA, const Vector &endA, const Vector &startB, const Vector &endB, Vector *result = nullptr) { float denom = (endA.x - startA.x) * (endB.y - startB.y) - (endA.y - startA.y) * (endB.x - startB.x); if (denom == 0.0f) { // parallel return false; } float numS = (startA.y - startB.y) * (endB.x - startB.x) - (startA.x - startB.x) * (endB.y - startB.y); if (numS == 0.0f) { // coincident return true; } float numT = (startA.y - startB.y) * (endA.x - startA.x) - (startA.x - startB.x) * (endA.y - startA.y); float s = numS / denom; if (s < 0.0f || s > 1.0f) { // intersection is not within line segment of startA to endA return false; } float t = numT / denom; if (t < 0.0f || t > 1.0f) { // intersection is not within line segment of startB to endB return false; } // compute intesection point if (result) { *result = startA + s * (endA - startA); } return true; } // Iterate over all active players in the game, invoking functor on each. // If functor returns false, stop iteration and return false. template <typename Functor> bool ForEachPlayer(Functor &func) { for (int i = 1; i <= gpGlobals->maxClients; i++) { CBasePlayer *pPlayer = UTIL_PlayerByIndex(i); if (!IsEntityValid(pPlayer)) continue; if (!pPlayer->IsPlayer()) continue; if (func(pPlayer) == false) return false; } return true; } #define IS_ALIVE true int UTIL_HumansOnTeam(int teamID, bool isAlive = false); #define IGNORE_SPECTATORS true int UTIL_HumansInGame(bool ignoreSpectators = false); bool UTIL_IsNameTaken(const char *name, bool ignoreHumans = false); int UTIL_ClientsInGame(); int <API key>(); int <API key>(); int UTIL_BotsInGame(); bool <API key>(TeamName kickTeam); bool UTIL_IsTeamAllBots(int team); CBasePlayer *<API key>(const Vector *pos, float *distance = nullptr); CBasePlayer *<API key>(const Vector *pos, int team, float *distance = nullptr); const char *UTIL_GetBotPrefix(); void <API key>(char *name, int nameLength, const BotProfile *profile); bool <API key>(const Vector &spot, int team, float maxRange = -1.0f); CBasePlayer *UTIL_GetLocalPlayer(); Vector UTIL_ComputeOrigin(entvars_t *pevVars); Vector UTIL_ComputeOrigin(CBaseEntity *pEntity); Vector UTIL_ComputeOrigin(edict_t *pentEdict); void <API key>(int iIndex, Vector vecEnd, int iLifetime, byte bRed, byte bGreen, byte bBlue); void UTIL_DrawBeamPoints(Vector vecStart, Vector vecEnd, int iLifetime, byte bRed, byte bGreen, byte bBlue); void UTIL_DrawBox(struct Extent *extent, int lifetime, int red, int green, int blue); // Echos text to the console, and prints it on the client's screen. This is NOT tied to the developer cvar. // If you are adding debugging output in cstrike, use UTIL_DPrintf() (debug.h) instead. void CONSOLE_ECHO(const char *pszMsg, ...); void CONSOLE_ECHO_LOGGED(const char *pszMsg, ...); void BotPrecache(); void InitBotTrig(); float BotCOS(float angle); float BotSIN(float angle); bool IsGameEventAudible(enum GameEventType event, CBaseEntity *pEntity, CBaseEntity *pOther, float *range, PriorityType *priority, bool *isHostile); void <API key>(const char *message);
Numeric types in popco ==== Overview By default popco2 uses the vectorz (i.e. vectorz-clj) implementation of core.matrix. vectorz only supports java.lang.Double numbers, which is a good option in general. However, for certain kinds of testing, it can be useful to switch to a different numeric type. To do this, you need to make sure that all numbers used in data structures are of an appropriate type. Doubles anywhere are likely to spread through contagion. In Clojure, if numbers of two types are combined, the result will have the rightmost of those in the list below: <pre> Long, BigInt, Ratio, BigDec, Double </pre> Also note that a Ratio that resolves to an integer will turn into a BigInt. Switching numeric types In order to switch from Doubles to something else, you need to modify three things in the source: 1. In popco/core/popco.clj, comment out the first of these lines, and uncomment the other one: <pre> (mx/<API key> :vectorz) ;(mx/<API key> :ndarray) </pre> 2. In popco/core/constants.clj, comment/uncomment lines so that all of the constants are of the same numeric type. 3. There are three matrix*.clj files in popco/nn. These define one or two wrapper functions for core.matrix functions. popco uses matrix.clj, and you need to copy the appropriate matrix_*.clj file into it. **matrix_default.clj** just defines popco names for the core.matrix functions. There is no change in behavior. These are functions that will infect popco with Doubles, so you don't want these versions if you're trying to use a different numeric type. **matrix_altnumbers.clj** wraps the core.matrix functions in code that does something extra. These are needed if you want to override the default behavior of these functions. Since they do extra work, they should be a little bit slower than the original core.matrix functions, so I don't want them for routine use. *To go back to Doubles*, just undo the preceding, of course. How to keep this system working To make this scheme work, you should consistently use the constants from the file constants.clj. Among other things, intead of using 1, 0, and -1, use +one+, +zero+, and +neg-one+. This applies to the files that specify particular simulations. Miscellaneous notes Ratios/BigInts are gawdawful slow, after the first tick or so. Expect to wait at least 15 minutes to get from one tick to the next, with a population of three persons. BigDecimals may cause a non-terminating decimal expanation exception, making them unusable. This is an inherent difficult with BigDecimals: Since they try to use as many decimal places as is necessary, any number that requires an infinite number of decimal places (such as 1/3), won't be representable in BigDecimals.
using FluentValidation; using NzbDrone.Core.Configuration; using NzbDrone.Core.Validation.Paths; namespace NzbDrone.Api.Config { public class <API key> : <API key><<API key>> { public <API key>(IConfigService configService, RootFolderValidator rootFolderValidator, PathExistsValidator pathExistsValidator, <API key> <API key>) : base(configService) { SharedValidator.RuleFor(c => c.<API key>) .Cascade(CascadeMode.StopOnFirstFailure) .IsValidPath() .SetValidator(rootFolderValidator) .SetValidator(<API key>) .SetValidator(pathExistsValidator) .When(c => !string.IsNullOrWhiteSpace(c.<API key>)); } protected override <API key> ToResource(IConfigService model) { return <API key>.ToResource(model); } } }
#!/usr/bin/python from PyQt4 import QtCore, QtGui class Bubble(QtGui.QLabel): def __init__(self,text): super(Bubble,self).__init__(text) self.setContentsMargins(5,5,5,5) def paintEvent(self, e): p = QtGui.QPainter(self) p.setRenderHint(QtGui.QPainter.Antialiasing,True) p.drawRoundedRect(0,0,self.width()-1,self.height()-1,5,5) super(Bubble,self).paintEvent(e) class MyWidget(QtGui.QWidget): def __init__(self,text,left=True): super(MyWidget,self).__init__() hbox = QtGui.QHBoxLayout() label = Bubble(text) if left is not True: hbox.addSpacerItem(QtGui.QSpacerItem(1,1,QtGui.QSizePolicy.Expanding,QtGui.QSizePolicy.Preferred)) hbox.addWidget(label) if left is True: hbox.addSpacerItem(QtGui.QSpacerItem(1,1,QtGui.QSizePolicy.Expanding,QtGui.QSizePolicy.Preferred)) hbox.setContentsMargins(0,0,0,0) self.setLayout(hbox) self.setContentsMargins(0,0,0,0) if __name__ == '__main__': a = QtGui.QApplication([]) w = QtGui.QWidget() vbox = QtGui.QVBoxLayout() vbox.addWidget(MyWidget("Left side.. and also check everything needed to fuck around\n\n\n")) vbox.addWidget(MyWidget("Right side",left=False)) vbox.addWidget(MyWidget("Left side")) vbox.addWidget(MyWidget("Left side")) w.setLayout(vbox) w.show() a.exec_()
var <API key> = [ [ "<API key>", "<API key>.html#<API key>", null ], [ "<API key>", "<API key>.html#<API key>", null ] ];
package io.github.zkhan93.hisab.ui.dialog; import android.app.Dialog; import android.app.DialogFragment; import android.content.DialogInterface; import android.os.Bundle; import android.support.design.widget.TextInputEditText; import android.support.v7.app.AlertDialog; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import butterknife.BindView; import butterknife.ButterKnife; import io.github.zkhan93.hisab.R; import io.github.zkhan93.hisab.model.callback.GroupRenameClbk; import io.github.zkhan93.hisab.ui.ExpensesFragment; import io.github.zkhan93.hisab.ui.MainActivity; public class RenameGroupDialog extends DialogFragment { public static final String TAG = RenameGroupDialog.class.getSimpleName(); @BindView(R.id.group_name) TextInputEditText groupName; GroupRenameClbk groupRenameClbk; @Override public Dialog onCreateDialog(Bundle savedInstanceState) { AlertDialog.Builder builder = new AlertDialog.Builder(getActivity()); builder.setTitle(R.string.title_rename_grp); View view = LayoutInflater.from(getActivity()).inflate(R.layout.dialog_rename_group, null); ButterKnife.bind(this, view); groupRenameClbk = (GroupRenameClbk) ((MainActivity) getActivity()).<API key>().findFragmentByTag (ExpensesFragment.TAG); if (savedInstanceState == null) { Bundle bundle = getArguments(); if (bundle != null) { String name = bundle.getString("name"); if (name != null) groupName.setText(name); } } else { groupName.setText(savedInstanceState.getString("name")); } builder.setView(view); builder.setPositiveButton(R.string.label_done, new DialogInterface .OnClickListener() { @Override public void onClick(DialogInterface dialogInterface, int i) { if (groupRenameClbk != null) groupRenameClbk.renameTo(groupName.getText().toString()); else Log.e(TAG, "no GroupRenameCallback added to RenameGroupDialog, you need to " + "implement GroupRenameClbk in host Activity"); } }).setNegativeButton(R.string.label_cancel, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialogInterface, int i) { dialogInterface.dismiss(); } }); return builder.create(); } @Override public void onSaveInstanceState(Bundle outState) { super.onSaveInstanceState(outState); outState.putString("name", groupName.getText().toString()); } @Override public void onActivityCreated(Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); getDialog().getWindow().getAttributes().windowAnimations = R.style.DialogAnimation; } }
#include "m_pd.h" static t_class *lpreson_tilde_class; typedef struct _lpreson_control { t_float *c_residual, *c_output; t_atom *x_parcors; /* t_atom x_parc_interp_one[MAXPOLES]; t_int x_parc_ord_one; t_atom x_parc_interp_two[MAXPOLES]; t_int x_parc_ord_two; */ } t_lpreson_control; typedef struct _lpreson_tilde { t_object x_obj; t_float f_dummy; t_int x_order; t_lpreson_control x_ctl; } t_lpreson_tilde; t_int *<API key>(t_int *w) { t_object x_obj; t_lpreson_tilde *x = (t_lpreson_tilde *)(w[1]); t_lpreson_control *ctl = (t_lpreson_control *)(w[2]); int n = (int)(w[3]); t_float *in = ctl->c_residual; t_float *out = ctl->c_output; t_int ord = x->x_order; float mem[ord+1]; /* * Do the inverse filtering * * 'data_in' : residual signal (length 'len') * 'data_out' : output frame (length 'len') * 'coeff' : the parcor coefficients (length 'tap') * 'lattice_iir' : filter memory - Previously initialised using <API key>() * */ int k, i; float sri; for (i=0;i<=ord;i++) { // SETFLOAT (&schur->x_parcors[i],0); mem[i] = 0.0; } for (k = 0; k < n; k++ ) { /* Synthesis filter - Lattice structure */ sri = in[k]; for (i=0; i<ord; i++) { t_float parcor = atom_getfloatarg ((ord-1-i),ord,ctl->x_parcors); sri = sri - parcor * mem[ord-1-i]; mem[ord-i] = mem[ord-1-i] + parcor*sri; } out[k] = sri; mem[0] = sri; } /* next k */ return(w+4); } static void lpreson_tilde_list(t_lpreson_tilde *x, t_symbol *s, int argc, t_atom *argv) { if (argc) { // x->x_ctl.parc_interp_two = copybytes(x->x_ctl.parc_interp_one, x->x_ctl.parc_ord_one * sizeof(t_atom)); // x->x_ctl.parc_ord_two = x->x_ctl.parc_ord_one; // x->x_ctl.parc_interp_one = copybytes(x->x_ctl.parcors, x->x_order * sizeof(t_atom)); // x->x_ctl.parc_ord_one = x->x_order; freebytes(x->x_ctl.x_parcors, x->x_order * sizeof(t_atom)); } x->x_ctl.x_parcors = copybytes(argv, argc * sizeof(t_atom)); x->x_order = argc; } void *lpreson_tilde_dsp(t_lpreson_tilde *x, t_signal **sp) { x->x_ctl.c_residual = sp[0]->s_vec; x->x_ctl.c_output = sp[1]->s_vec; dsp_add(<API key>, 3, x, &x->x_ctl, sp[0]->s_n); return (void *)x; } void *lpreson_tilde_new(t_floatarg f) { t_lpreson_tilde *x = (t_lpreson_tilde *)pd_new(lpreson_tilde_class); x->x_order = f >= 1 ? (int)f : 5; outlet_new(&x->x_obj, &s_signal); return (void *)x; } void lpreson_tilde_setup(void) { lpreson_tilde_class = class_new(gensym("lpreson~"), (t_newmethod)lpreson_tilde_new, 0, sizeof(t_lpreson_tilde), CLASS_DEFAULT, A_DEFFLOAT, 0); post(". . Lattice IIR filter for lpc. . . . . . ."); post(". . by Nicolas Chetry <okin@altern.org> . ."); post(". & Edward Kelly <morph_2016@yahoo.co.uk> ."); class_addmethod(lpreson_tilde_class, (t_method)lpreson_tilde_dsp, gensym("dsp"), 0); class_addlist(lpreson_tilde_class, lpreson_tilde_list); CLASS_MAINSIGNALIN(lpreson_tilde_class, t_lpreson_tilde, f_dummy); }
//lazy loading, one time event. document.addEventListener('dblclick', function(event){ document.removeEventListener(event.type, arguments.callee); let msg = { type: "load_popover" }; chrome.runtime.sendMessage(msg, function(response){ if (response.isLoaded){ //repeat dblclick for triggering on new scripts if loaded setTimeout(function(){document.body.dispatchEvent(event)}, 20); } }); });
# coding: utf-8 from pprint import pformat from six import iteritems import re class <API key>(object): """ NOTE: This class is auto generated by the swagger code generator program. Do not edit the class manually. """ def __init__(self, error=None): """ <API key> - a model defined in Swagger :param dict swaggerTypes: The key is attribute name and the value is attribute type. :param dict attributeMap: The key is attribute name and the value is json key in definition. """ self.swagger_types = { 'error': 'str' } self.attribute_map = { 'error': 'error' } self._error = error @property def error(self): """ Gets the error of this <API key>. Internal server error message :return: The error of this <API key>. :rtype: str """ return self._error @error.setter def error(self, error): """ Sets the error of this <API key>. Internal server error message :param error: The error of this <API key>. :type: str """ self._error = error def to_dict(self): """ Returns the model properties as a dict """ result = {} for attr, _ in iteritems(self.swagger_types): value = getattr(self, attr) if isinstance(value, list): result[attr] = list(map( lambda x: x.to_dict() if hasattr(x, "to_dict") else x, value )) elif hasattr(value, "to_dict"): result[attr] = value.to_dict() elif isinstance(value, dict): result[attr] = dict(map( lambda item: (item[0], item[1].to_dict()) if hasattr(item[1], "to_dict") else item, value.items() )) else: result[attr] = value return result def to_str(self): """ Returns the string representation of the model """ return pformat(self.to_dict()) def __repr__(self): """ For `print` and `pprint` """ return self.to_str() def __eq__(self, other): """ Returns true if both objects are equal """ if not isinstance(other, <API key>): return False return self.__dict__ == other.__dict__ def __ne__(self, other): """ Returns true if both objects are not equal """ return not self == other
package example.bar object Bar { def bar(): Unit = println("bar") }
#include <fx.h> #include <Scintilla.h> #include <FXScintilla.h> #include "sl.h" #include "compat.h" #include "appname.h" #include "macro.h" #include "intl.h" #include "help.h" #include "helptext.h" #include "help_lua.h" #define sendString(iMessage, wParam, lParam) sendMessage(iMessage, wParam, reinterpret_cast<long>(lParam)) #ifdef FOX_1_7_50_OR_NEWER # define RxFind(rx,subj,start,beg,end,npar) (rx.search(subj,strlen(subj),start,strlen(subj),FXRex::Normal,beg,end,npar)>=0) #else # define RxFind(rx,subj,start,beg,end,npar) (rx.match(subj,beg,end,REX_FORWARD,npar,start)) #endif enum { SCHLP_FIXED, SCHLP_ITALIC, SCHLP_BOLD, SCHLP_LINK, SCHLP_H1, SCHLP_NORMAL }; #define SCHLP_FIRST SCHLP_FIXED #define SCHLP_LAST SCHLP_NORMAL #define SCHLP_LOGO SCHLP_LAST+1 /* The help files are written in a very crude markup (markdown?) language. Anything that matches one of the regex phrases below will be formatted accordingly. Link text is formatted as a "hyperlink" that, when clicked, will jump to the section header containing the identical text. Nested markup is not allowed! */ static const char* phrases[] = { "===(.+?)===", // monospace font "///(.+?)///", // italic font "%%%(.+?)%%%", // bold font "@@@(.+?)@@@", // link text " NULL }; #if ((FOX_MAJOR>1) || (FOX_MINOR>7) || ((FOX_MINOR==7) && (FOX_LEVEL>=23))) # define <API key> ".config" #else # define <API key> ".foxrc" #endif /* Instead of "hard-coding" these strings in hundreds of places in the text files, just use these generic "macros" - each regex placeholder will be replaced with its corresponding "real" name. */ static const char* replacements[] = { "\\<__APP__\\>", APP_NAME, "\\<__EXE__\\>", EXE_NAME, "\\<__MOD__\\>", LUA_MODULE_NAME, "\\<__CFG__\\>", <API key>, NULL, NULL }; typedef struct _HelpLink { struct _HelpLink*next; int pos; char* href; } HelpLink; class SciHelp: public FXScintilla { FXDECLARE(SciHelp) SciHelp(){} void*links; void*sects; void freelists(); long last_pos; long jump_pos; bool find(const FXString &what); void replace(const char*oldstr, const char*newstr); public: SciHelp(FXComposite*p, FXObject*tgt=NULL, FXSelector sel=0, FXuint opts=LAYOUT_FILL, bool dark=false); ~SciHelp(); void parse(const char*txt, unsigned int size); long onLeftBtnRelease(FXObject*o, FXSelector sel, void*p); long onCommand(FXObject*o, FXSelector sel, void*p); FXTextField *srchbox; const char*loaded; enum { ID_SCINTILLA=FXScintilla::ID_LAST, ID_GOBACK, ID_SEARCH, ID_ZOOMIN, ID_ZOOMOUT, ID_LAST }; }; FXDEFMAP(SciHelp) SciHelpMap[]={ FXMAPFUNCS(SEL_COMMAND, SciHelp::ID_SCINTILLA,SciHelp::ID_ZOOMOUT, SciHelp::onCommand), FXMAPFUNC(<API key>, 0, SciHelp::onLeftBtnRelease) }; FXIMPLEMENT(SciHelp,FXScintilla,SciHelpMap,ARRAYNUMBER(SciHelpMap)) SciHelp::SciHelp(FXComposite*p,FXObject*tgt,FXSelector sel, FXuint opts, bool dark): FXScintilla(p, this, ID_SCINTILLA, opts) { links=NULL; sects=NULL; last_pos=0; jump_pos=-1; loaded=NULL; sendMessage(SCI_ASSIGNCMDKEY,SCK_HOME,SCI_DOCUMENTSTART); sendMessage(SCI_ASSIGNCMDKEY,SCK_END,SCI_DOCUMENTEND); long def_fg = dark? FXRGB(250, 250, 250) : FXRGB( 80, 80, 80); long def_bg = dark? FXRGB( 60, 60, 80) : FXRGB(250, 250, 250); long lnk_fg = dark? FXRGB(128, 160, 255) : FXRGB( 0, 0, 192); long lnk_bg = def_bg; long hot_fg = dark? FXRGB(224, 224, 80) : FXRGB( 0, 0, 255); long hot_bg = dark? FXRGB(128, 80, 0) : FXRGB(255, 255, 128); long mno_fg = dark? FXRGB(255, 144, 128) : FXRGB(128, 0, 0); long mno_bg=def_bg; long hdr_fg = dark? FXRGB( 96, 96, 160) : FXRGB(228, 228, 192); long hdr_bg = dark? FXRGB(192, 255, 192) : FXRGB( 0, 0, 96); long lgo_fg = dark? FXRGB(255, 144, 128) : FXRGB(128, 0, 0); long lgo_bg=def_bg; sendMessage(<API key>, false,0); sendMessage(SCI_SETWRAPMODE,SC_WRAP_WORD,0); sendMessage(SCI_SETMARGINWIDTHN,1,0); sendMessage(SCI_SETCARETSTYLE,<API key>,0); sendMessage(SCI_SETMARGINLEFT,0,4); sendMessage(SCI_SETMARGINRIGHT,0,4); sendMessage(<API key>,true,hot_fg); sendMessage(<API key>,true,hot_bg); sendMessage(SCI_STYLESETBACK,STYLE_DEFAULT,def_bg); for (FXint i=SCHLP_FIRST; i<=SCHLP_LAST; i++) { sendMessage(SCI_STYLESETSIZE, i, 10); sendString(SCI_STYLESETFONT, i, "Sans Serif"); sendMessage(SCI_STYLESETFORE,i,def_fg); sendMessage(SCI_STYLESETBACK,i,def_bg); sendMessage(<API key>,i,true); } sendMessage(SCI_STYLESETHOTSPOT, SCHLP_LINK, true); sendMessage(<API key>, SCHLP_LINK, true); sendMessage(SCI_STYLESETFORE,SCHLP_LINK,lnk_fg); sendMessage(SCI_STYLESETBACK,SCHLP_LINK,lnk_bg); sendMessage(SCI_STYLESETSIZE, SCHLP_H1, 14); sendMessage(SCI_STYLESETBACK,SCHLP_H1,hdr_fg); sendMessage(SCI_STYLESETFORE,SCHLP_H1,hdr_bg); sendMessage(SCI_STYLESETBOLD,SCHLP_BOLD,true); sendMessage(SCI_STYLESETITALIC,SCHLP_ITALIC,true); sendString(SCI_STYLESETFONT, SCHLP_FIXED, "Courier"); sendMessage(SCI_STYLESETSIZE, SCHLP_FIXED, 10); sendMessage(SCI_STYLESETFORE,SCHLP_FIXED,mno_fg); sendMessage(SCI_STYLESETBACK,SCHLP_FIXED,mno_bg); sendString(SCI_STYLESETFONT, SCHLP_LOGO, "Serif"); sendMessage(SCI_STYLESETSIZE, SCHLP_LOGO, 10); sendMessage(SCI_STYLESETFORE,SCHLP_LOGO,lgo_fg); sendMessage(SCI_STYLESETBACK,SCHLP_LOGO,lgo_bg); sendMessage(SCI_STARTSTYLING,0,0xff); horizontalScrollBar()->hide(); sendMessage(SCI_SETHSCROLLBAR,false,0); sendMessage(SCI_SETYCARETPOLICY,CARET_EVEN|CARET_STRICT,0); } void SciHelp::replace(const char*oldstr, const char*newstr) { const char*content; FXint beg[3]={0,0,0}; FXint end[3]={0,0,0}; FXRex generic_rx(oldstr, REX_NORMAL|REX_NEWLINE); content=(const char*)(sendMessage(<API key>,0,0)); FXint n=strlen(newstr); while (RxFind(generic_rx,content,0,beg,end,1)) { sendMessage(SCI_SETTARGETSTART,beg[0],0); sendMessage(SCI_SETTARGETEND,end[0],0); sendString(SCI_REPLACETARGET,n,newstr); content=(const char*)(sendMessage(<API key>,0,0)); } } static char*my_strndup(const char*src,int len) { char*dst=(char*)calloc(len+1,1); strncpy(dst,src,len); return dst; } void SciHelp::parse(const char*txt, unsigned int size) { FXint beg[3]={0,0,0}; FXint end[3]={0,0,0}; loaded=txt; const char *content=NULL; getApp()->beginWaitCursor(); freelists(); sendMessage(SCI_SETREADONLY,false,0); sendMessage(SCI_CLEARALL,0,0); sendString(SCI_APPENDTEXT, size, txt); sendString(SCI_APPENDTEXT, 32,FXString('\n',32).text()); sendMessage(SCI_SETSTYLING,sendMessage(SCI_GETLENGTH,0,0),SCHLP_NORMAL); sendMessage(SCI_STARTSTYLING,0,0xff); // Translate markup tags into scintilla styles... for (FXint i=SCHLP_FIRST; i<SCHLP_LAST; i++) { content=(const char*)(sendMessage(<API key>,0,0)); FXRex rx(phrases[i], REX_CAPTURE|REX_NEWLINE); while (RxFind(rx,content,0,beg,end,2)) { sendMessage(SCI_SETTARGETSTART,beg[0],0); sendMessage(SCI_SETTARGETEND,end[0],0); char*tmp=my_strndup(content+beg[1], end[1]-beg[1]); sendString(SCI_REPLACETARGET,end[1]-beg[1],tmp); if ((i==SCHLP_H1)||(i==SCHLP_LINK)) { HelpLink*link=(HelpLink*)calloc(1, sizeof(HelpLink)); link->pos=0; link->href=tmp; if (i==SCHLP_H1) { sects=sl_push(sects,link); } else { links=sl_push(links,link); } } else { free(tmp); } sendMessage(SCI_STARTSTYLING,beg[0],0xff); sendMessage(SCI_SETSTYLING,(end[1]-beg[1])+((i==SCHLP_H1)?1:0),i); content=(const char*)(sendMessage(<API key>,0,0)); } } // replace generic placeholders with the real names... for (const char**c=replacements; *c; c+=2) { replace(*c,*(c+1)); } // Make the editor's name stand out a little... FXRex appname_rx("\\<"APP_NAME"\\>", REX_NORMAL|REX_NEWLINE); content=(const char*)(sendMessage(<API key>,0,0)); FXint p=0; while (RxFind(appname_rx,content,p,beg,end,1)) { sendMessage(SCI_STARTSTYLING,beg[0],0xff); sendMessage(SCI_SETSTYLING,(end[0]-beg[0]),SCHLP_LOGO); p=end[0]; } sendMessage(SCI_SETREADONLY,true,0); links=sl_reverse(links); sects=sl_reverse(sects); // Populate our list elements with their positions in the document... HelpLink*link=(HelpLink*)links; HelpLink*sect=(HelpLink*)sects; long len=sendMessage(SCI_GETLENGTH,0,0); for (long p1=0; p1<len;) { int style=sendMessage(SCI_GETSTYLEAT,p1,0); switch (style) { case SCHLP_H1: { sect->pos=p1; sect=sect->next; break; } case SCHLP_LINK: { link->pos=p1; link=link->next; break; } } while ( (sendMessage(SCI_GETSTYLEAT,p1,0)==style) && (p1<len) ) { p1++; } } getApp()->endWaitCursor(); } static void free_link_cb(void *p) { if (p) { HelpLink*link=(HelpLink*)p; if (link->href) { delete link->href; } delete link; } } void SciHelp::freelists() { if (links) { sl_free(links, free_link_cb); links=NULL; } if (sects) { sl_free(sects, free_link_cb); sects=NULL; } last_pos=0; jump_pos=-1; } SciHelp::~SciHelp() { freelists(); } static int lookup_link(void *rec, void *p) { HelpLink*link=(HelpLink*)rec; if ( link && ( link->pos == *(int*)p) ) { return -1; } else { return 0; } } static int lookup_sect(void *rec, void *p) { HelpLink*sect=(HelpLink*)rec; char*href=(char*)p; if ( sect && sect->href && ( strcmp(sect->href,href) == 0 ) ) { return -1; } else { return 0; } } long SciHelp::onLeftBtnRelease(FXObject*o, FXSelector sel, void*p) { FXint prev_x; FXint prev_y; getPosition(prev_x,prev_y); long rv = FXScintilla::onLeftBtnRelease(o,sel,p); if (jump_pos>=0) { sendMessage(SCI_GOTOPOS,jump_pos,0); long th=sendMessage(SCI_TEXTHEIGHT,0,0); #ifdef FOX_1_6 setPosition(0,-((vertical->getPosition()+(getViewportHeight()/2))-th)); #else setPosition(0,-((vertical->getPosition()+(getVisibleHeight()/2))-th)); #endif last_pos=jump_pos; jump_pos=-1; } else { setPosition(prev_x,prev_y); } return rv; } long SciHelp::onCommand(FXObject*o, FXSelector sel, void*p) { switch (FXSELID(sel)) { case ID_SCINTILLA: { SCNotification* scn = static_cast<SCNotification*>(p); if ((scn->nmhdr.code==SCN_HOTSPOTCLICK) && links && sects) { int pos=scn->position; while (sendMessage(SCI_GETSTYLEAT, pos,0)==SCHLP_LINK) { pos pos++; HelpLink*link = (HelpLink*) sl_map(links, lookup_link, &pos); if (link && link->href) { HelpLink*sect = (HelpLink*) sl_map(sects, lookup_sect, link->href); if (sect) { jump_pos=sect->pos; } } } return 0; } case ID_GOBACK:{ FXint x,y; getPosition(x,y); setPosition(0,last_pos); last_pos=y; return 1; } case ID_SEARCH: { if (srchbox->getText().length()) { find(srchbox->getText()); } else { srchbox->setFocus(); } return 1; } case ID_ZOOMIN:{ sendMessage(SCI_ZOOMIN,0,0); return 1; } case ID_ZOOMOUT:{ sendMessage(SCI_ZOOMOUT,0,0); return 1; } } return 0; } bool SciHelp::find(const FXString &what) { long start=sendMessage(SCI_GETCURRENTPOS,0,0); long end=sendMessage(SCI_GETLENGTH,0,0); sendMessage(SCI_SETTARGETSTART,start,0); sendMessage(SCI_SETTARGETEND,end,0); long found=sendString(SCI_SEARCHINTARGET,what.length(), what.text()); if (found==-1) { start=0; sendMessage(SCI_SETTARGETSTART,start,0); sendMessage(SCI_SETTARGETEND,end,0); found=sendString(SCI_SEARCHINTARGET,what.length(), what.text()); } if (found>=0) { sendMessage(SCI_SETSEL, sendMessage(SCI_GETTARGETSTART,0,0), sendMessage(SCI_GETTARGETEND,0,0) ); sendMessage(SCI_SCROLLCARET,0,0); return true; } return false; } #define PAD(w,p) \ w->setPadTop(p); \ w->setPadBottom(p); \ w->setPadLeft(p); \ w->setPadRight(p); class HelpDialog; static HelpDialog *instance = NULL; #define HELP_DECOR DECOR_TITLE|DECOR_BORDER|DECOR_MINIMIZE|DECOR_MAXIMIZE|DECOR_CLOSE|DECOR_RESIZE #define RAISED FRAME_RAISED|FRAME_THICK #define TEXTFIELD_OPTS TEXTFIELD_NORMAL|<API key> class HelpDialog: public FXDialogBox { FXDECLARE(HelpDialog) HelpDialog(){} SciHelp*sc; public: HelpDialog(FXMainWindow*win, bool dark):FXDialogBox(win->getApp(),_(APP_NAME" Help"),HELP_DECOR) { FXint w=getApp()->getRootWindow()->getWidth(); FXint h=getApp()->getRootWindow()->getHeight(); setWidth( (FXint)( w>800 ? w*0.6875 : w*0.875 ) ); setHeight( (FXint)( h>600 ? h*0.667 : h*0.75 ) ); setX((w-getWidth())/2); setY((h-getHeight())/2); PAD(this,1); FXVerticalFrame *vbox=new FXVerticalFrame(this, LAYOUT_FILL|FRAME_NONE); PAD(vbox,0); vbox->setVSpacing(1); FXHorizontalFrame*scfrm=new FXHorizontalFrame(vbox, LAYOUT_FILL|FRAME_SUNKEN|FRAME_THICK); PAD(scfrm,0); sc=new SciHelp(scfrm, NULL,0, LAYOUT_FILL|HSCROLLER_NEVER,dark); setUserData(sc); FXHorizontalFrame *btns=new FXHorizontalFrame(vbox, LAYOUT_SIDE_BOTTOM|LAYOUT_FILL_X|RAISED); new FXButton(btns,_(" &Back "), NULL, sc, SciHelp::ID_GOBACK, RAISED); new FXLabel(btns, " "); sc->srchbox=new FXTextField(btns,24,sc, SciHelp::ID_SEARCH,TEXTFIELD_OPTS); new FXButton(btns,_(" &Find "), NULL, sc, SciHelp::ID_SEARCH, RAISED); btns=new FXHorizontalFrame(btns, LAYOUT_RIGHT|LAYOUT_FILL_X|FRAME_NONE,0,0,0,0, 16,8,0,0,0,0); new FXButton(btns," + ", NULL, sc, SciHelp::ID_ZOOMIN, RAISED|LAYOUT_LEFT); new FXButton(btns," - ", NULL, sc, SciHelp::ID_ZOOMOUT, RAISED|LAYOUT_LEFT); new FXButton(btns,_(" &Close "), NULL, this, FXDialogBox::ID_CLOSE, RAISED|LAYOUT_RIGHT); setIcon(win->getIcon()); changeFocus(sc->srchbox); create(); SetupXAtoms(this, "help", APP_NAME); show(); getApp()->runWhileEvents(); } long onCmdClose(FXObject*o, FXSelector sel, void*p) { instance=NULL; return FXDialogBox::onCmdClose(o,sel,p); } void Load(FXint which) { sc->hide(); const char*todo=NULL; unsigned int len=0; switch (which) { case 0: { todo=(const char*)helptext; len=sizeof(helptext); break; } case 1: { todo=(const char*)help_lua; len=sizeof(help_lua); break; } } if (sc->loaded!=todo) { sc->parse(todo,len); } sc->show(); if (shown()) { hide(); } show(PLACEMENT_SCREEN); } }; FXDEFMAP(HelpDialog) HelpDialogMap[] = { FXMAPFUNC(SEL_COMMAND, FXDialogBox::ID_CLOSE, HelpDialog::onCmdClose), }; FXIMPLEMENT(HelpDialog,FXDialogBox,HelpDialogMap,ARRAYNUMBER(HelpDialogMap)); void show_help(FXMainWindow*win, FXint which, bool dark) { if (!instance) { instance=new HelpDialog(win,dark); } instance->Load(which); }
/*! \file \brief Declaration of the <API key> */ #ifndef <API key> #define <API key> /* system include */ /* local include */ #include "neoip_namespace.hpp" // list of include which are almost always needed when using this one #include "neoip_wikidbg_obj.hpp" <API key>; // list of forward declaration class <API key>; // declaration of the wikidbg_init_cb_t for ntudp_full_t void <API key>(<API key> &keyword_db) throw(); NEOIP_NAMESPACE_END #endif /* <API key> */
Imports ESRI.ArcGIS.Geodatabase Imports ESRI.ArcGIS.Geometry Public Class VctField #Region "" Private p_Name As String Private p_Type As enumFieldType Private p_Length As Integer Private p_DecimalLength As Integer = 0 #End Region #Region "" Public Property Name() As String Get Return Me.p_Name End Get Set(ByVal value As String) Me.p_Name = value End Set End Property Public Property Type() As enumFieldType Get Return Me.p_Type End Get Set(ByVal value As enumFieldType) Me.p_Type = value End Set End Property Public Property Length() As Integer Get Return Me.p_Length End Get Set(ByVal value As Integer) Me.p_Length = value End Set End Property Public Property DecimalLength() As Integer Get Return Me.p_DecimalLength End Get Set(ByVal value As Integer) Me.p_DecimalLength = value End Set End Property #End Region #Region "" Public Function ConvertToESRIField() As IField Dim mField As IField = New FieldClass Dim mFieldEdit As IFieldEdit = mField mFieldEdit.Name_2 = Me.Name Select Case Me.Type Case enumFieldType.VctBoolean mFieldEdit.Type_2 = esriFieldType.<API key> Case enumFieldType.VctDateTime mFieldEdit.Type_2 = esriFieldType.esriFieldTypeDate Case enumFieldType.VctDouble mFieldEdit.Type_2 = esriFieldType.esriFieldTypeDouble Case enumFieldType.VctInt mFieldEdit.Type_2 = esriFieldType.<API key> Case enumFieldType.VctString mFieldEdit.Type_2 = esriFieldType.esriFieldTypeString Case enumFieldType.VctVarbin ' mFieldEdit.Type_2 = esriFieldType.esriFieldTypeBlob End Select ' mFieldEdit.Precision_2 = Me.DecimalLength 'mFieldEdit.Length_2 = Me.Length Return mField End Function #End Region End Class
#!/usr/bin/env python3 """ Setup for root_script. """ # core python libaries import setuptools # third party libaries # custom libraries setuptools.setup()
package net.labhackercd.nhegatu.data.provider; import android.net.Uri; public class EDMContract { /** TODO: Columns? */ public static final String CONTENT_AUTHORITY = "net.labhackercd.edemocracia"; public static final Uri BASE_CONTENT_URI = Uri.parse("content://" + CONTENT_AUTHORITY); private static final String PATH_GROUPS = "groups"; private static final String PATH_THREADS = "threads"; private static final String PATH_CATEGORIES = "categories"; public static final class Group { public static final Uri CONTENT_URI = BASE_CONTENT_URI.buildUpon().appendPath(PATH_GROUPS).build(); public static final String CONTENT_TYPE = "vnd.android.cursor.dir/vnd.edemocracia.group"; public static final String CONTENT_ITEM_TYPE = "vnd.android.cursor.item/vnd.edemocracia.group"; } public static final class Category { public static final Uri CONTENT_URI = BASE_CONTENT_URI.buildUpon().appendPath(PATH_CATEGORIES).build(); public static final String CONTENT_ITEM_TYPE = "vnd.android.cursor.item/vnd.edemocracia.category"; } public static final class Thread { public static final Uri CONTENT_URI = BASE_CONTENT_URI.buildUpon().appendPath(PATH_THREADS).build(); public static final String CONTENT_ITEM_TYPE = "vnd.android.cursor.item/vnd.edemocracia.thread"; } public static final class Message { public static final Uri CONTENT_URI = BASE_CONTENT_URI.buildUpon().appendPath(PATH_THREADS).build(); public static final String CONTENT_TYPE = "vnd.android.cursor.dir/vnd.edemocracia.message"; public static final String CONTENT_ITEM_TYPE = "vnd.android.cursor.item/vnd.edemocracia.message"; } }
package org.cgiar.ccafs.marlo.data.manager; import org.cgiar.ccafs.marlo.data.model.ProjectPolicyCrp; import java.util.List; /** * @author CCAFS */ public interface <API key> { /** * This method removes a specific projectPolicyCrp value from the database. * * @param projectPolicyCrpId is the projectPolicyCrp identifier. * @return true if the projectPolicyCrp was successfully deleted, false otherwise. */ public void <API key>(long projectPolicyCrpId); /** * This method validate if the projectPolicyCrp identify with the given id exists in the system. * * @param projectPolicyCrpID is a projectPolicyCrp identifier. * @return true if the projectPolicyCrp exists, false otherwise. */ public boolean <API key>(long projectPolicyCrpID); /** * This method gets a list of projectPolicyCrp that are active * * @return a list from ProjectPolicyCrp null if no exist records */ public List<ProjectPolicyCrp> findAll(); /** * This method gets a list of projectPolicyCrp by a given projectPolicy identifier. * * @param policyId is the projectPolicy identifier. * @return a list of projectPolicyCenter objects. */ public List<ProjectPolicyCrp> <API key>(Long policyId); /** * This method gets a projectPolicyCrp object by a given projectPolicyCrp identifier. * * @param projectPolicyCrpID is the projectPolicyCrp identifier. * @return a ProjectPolicyCrp object. */ public ProjectPolicyCrp <API key>(long projectPolicyCrpID); /** * This method get the information of a projectPolicyCrp * * @param policyID - policy identifier * @param crpID - CRP/Platform identifier * @param phaseID - phase identifier * @return ProjectPolicyCrp object that contains information.. */ public ProjectPolicyCrp <API key>(long policyID, long crpID, long phaseID); /** * This method saves the information of the given projectPolicyCrp * * @param projectPolicyCrp - is the projectPolicyCrp object with the new information to be added/updated. * @return a number greater than 0 representing the new ID assigned by the database, 0 if the projectPolicyCrp was * updated * or -1 is some error occurred. */ public ProjectPolicyCrp <API key>(ProjectPolicyCrp projectPolicyCrp); }
package com.mclab1.palace.customer; import java.util.ArrayList; import android.content.Intent; import android.os.Bundle; import android.support.v4.app.Fragment; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.AdapterView.OnItemClickListener; import ro.ui.pttdroid.guider.R; import com.etsy.android.grid.StaggeredGridView; import com.nhaarman.listviewanimations.swinginadapters.prepared.<API key>; public class <API key> extends Fragment { private SampleAdapter mAdapter; private StaggeredGridView mGridView; public static final String tag = "<API key>"; @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // Inflate the layout for this fragment return inflater.inflate(R.layout.<API key>, container, false); } private void gen_test_data() { ArrayList<CustomerItem> testDStrings = new ArrayList<CustomerItem>(); testDStrings.add(new CustomerItem()); testDStrings.add(new CustomerItem()); testDStrings.add(new CustomerItem()); testDStrings.add(new CustomerItem()); testDStrings.add(new CustomerItem()); mAdapter.addAll(testDStrings); <API key> <API key> = new <API key>( mAdapter); <API key>.setAbsListView(mGridView); <API key>.<API key>(1); mGridView.setAdapter(<API key>); mGridView.<API key>(new OnItemClickListener() { @Override public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) { Log.i(tag, "Clicket" + String.valueOf(arg2)); CustomerItem customerItem = mAdapter.getItem(arg2); Intent intent = new Intent(getActivity(), <API key>.class); Bundle bundle = new Bundle(); bundle.putString("title", customerItem.title); bundle.putString("content", customerItem.content); bundle.putString("photo", customerItem.image_path); intent.putExtras(bundle); getActivity().startActivity(intent); } }); mAdapter.<API key>(); } @Override public void onActivityCreated(final Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); mGridView = (StaggeredGridView) getView().findViewById(R.id.grid_view); if (mAdapter == null) { mAdapter = new SampleAdapter(getActivity(), R.id.txt_line1); } gen_test_data(); } }
using CP77.CR2W.Reflection; namespace CP77.CR2W.Types { [REDMeta] public class <API key> : questIConditionType { public <API key>(CR2WFile cr2w, CVariable parent, string name) : base(cr2w, parent, name) { } } }
class Bppsuite < Formula desc "The Bio++ Program Suite" homepage "http://bioweb.me/biopp" url "https://github.com/BioPP/bppsuite/archive/v2.4.1.tar.gz" sha256 "<SHA256-like>" depends_on "cmake" => :build depends_on "libbpp-phyl" depends_on "libbpp-popgen" def install mkdir "build" do system "cmake", "..", *std_cmake_args system "make", "install" end end test do system "bppml" system "bpppopstats" system "bppdist" system "bppseqgen" system "bppseqman" system "bpppars" system "bppalnscore" end end
#include <QDebug> #include <QString> #include <QList> #include <QMap> #include <QFile> #include <QTextStream> #include "PraalineCore/Annotation/AnnotationTierGroup.h" #include "PraalineCore/Annotation/IntervalTier.h" #include "PraalineCore/Corpus/CorpusCommunication.h" #include "PraalineCore/Datastore/CorpusRepository.h" #include "PraalineCore/Datastore/AnnotationDatastore.h" using namespace Praaline::Core; #include "PraalineASR/Sphinx/<API key>.h" #include "PraalineASR/Sphinx/<API key>.h" using namespace Praaline::ASR; #include "BroadClassAligner.h" struct <API key> { QString defaultBroadClass; QList<QString> <API key>; QHash<QString, QString> correspondances; <API key> dictionary; }; BroadClassAligner::BroadClassAligner() : d(new <API key>) { d->defaultBroadClass = "VV"; } BroadClassAligner::~BroadClassAligner() { delete d; } void BroadClassAligner::<API key>(const QString &name, const QList<QString> &phonemes) { d-><API key> << name; foreach (QString ph, phonemes) { d->correspondances.insert(ph, name); } } void BroadClassAligner::resetClasses() { d-><API key>.clear(); d->correspondances.clear(); } void BroadClassAligner::initialiseFR() { resetClasses(); d->defaultBroadClass = "VV"; <API key>("PP", QList<QString>() << "p" << "b" << "t" << "d" << "k" << "g"); // plosives <API key>("FF", QList<QString>() << "f" << "v" << "s" << "z" << "S" << "Z"); // fricatives <API key>("NN", QList<QString>() << "m" << "n"); // nasals <API key>("LL", QList<QString>() << "l" << "R"); // liquids <API key>("GG", QList<QString>() << "w" << "H" << "j"); // glides <API key>("VV", QList<QString>() << "i" << "e" << "E" << "a" << "A" << "o" << "O" << "y" << "2" << "9" << "u" << "U~"); // vowels <API key>("VN", QList<QString>() << "e~" << "a~" << "o~" << "9~"); // nasal vowels <API key>("EE", QList<QString>() << "@"); // schwa <API key>("SIL", QList<QString>() << "_" << "dummy" << "#"); // silence } void BroadClassAligner::initialiseFRcv() { resetClasses(); d->defaultBroadClass = "V"; <API key>("C", QList<QString>() << "p" << "b" << "t" << "d" << "k" << "g" << "f" << "v" << "s" << "z" << "S" << "Z" << "m" << "n" << "l" << "R" << "w" << "H" << "j"); <API key>("V", QList<QString>() << "i" << "e" << "E" << "a" << "A" << "o" << "O" << "y" << "2" << "9" << "u" << "U~" << "e~" << "a~" << "o~" << "9~" << "@"); <API key>("SIL", QList<QString>() << "_" << "dummy" << "#"); // silence } void BroadClassAligner::initialiseFRSphinx() { resetClasses(); d->defaultBroadClass = "VV"; <API key>("PP", QList<QString>() << "pp" << "bb" << "tt" << "dd" << "kk" << "gg"); // plosives <API key>("FF", QList<QString>() << "ff" << "vv" << "ss" << "zz" << "ch" << "jj"); // fricatives <API key>("NN", QList<QString>() << "mm" << "nn" << "gn"); // nasals <API key>("LL", QList<QString>() << "ll" << "rr"); // liquids <API key>("GG", QList<QString>() << "ww" << "uy" << "yy"); // glides <API key>("VV", QList<QString>() << "ii" << "ei" << "ai" << "aa" << "au" << "oo" << "ou" << "uu" << "eu" << "oe"); // vowels <API key>("VN", QList<QString>() << "in" << "an" << "on" << "un"); // nasal vowels <API key>("EE", QList<QString>() << "ee"); // schwa <API key>("SIL", QList<QString>() << "_"); // silence } QString BroadClassAligner::phonemeToBroadClass(const QString &phoneme) const { return d->correspondances.value(phoneme.trimmed(), d->defaultBroadClass); } bool BroadClassAligner::adaptDictionary(const QString &filenameInput, const QString &filenameOutput) const { QMap<QString, QString> dictionary; QFile fileDicIn(filenameInput); if ( !fileDicIn.open( QIODevice::ReadOnly | QIODevice::Text ) ) return false; QTextStream dicIn(&fileDicIn); dicIn.setCodec("UTF-8"); while (!dicIn.atEnd()) { QString line = dicIn.readLine(); if (!line.contains(" ")) continue; QStringList phonetisation = line.section(" ", 1, -1).split(" "); QStringList broadphonetisation; foreach (QString ph, phonetisation) { broadphonetisation << phonemeToBroadClass(ph); } dictionary.insert(broadphonetisation.join(""), broadphonetisation.join(" ")); } fileDicIn.close(); // Create broad phonetic class transcription dictionary QFile fileDicOut(filenameOutput); if ( !fileDicOut.open( QIODevice::WriteOnly | QIODevice::Text ) ) return false; QTextStream dicOut(&fileDicOut); dicOut.setCodec("UTF-8"); foreach (QString word, dictionary.keys()) { dicOut << word << " " << dictionary.value(word) << "\n"; } fileDicOut.close(); return true; } void BroadClassAligner::<API key>(IntervalTier *tier, const QString &attributeBroadClass) const { if (!tier) return; foreach (Interval *phone, tier->intervals()) { QString p = phonemeToBroadClass(phone->text()); // qDebug() << phone->text() << " " << p; phone->setAttribute(attributeBroadClass, p); } } void BroadClassAligner::update<API key>(IntervalTier *tier_phone, const QString &<API key>, IntervalTier *tier_token, const QString &<API key>) const { if (!tier_phone) return; if (!tier_token) return; foreach (Interval *token, tier_token->intervals()) { QList<Interval *> phones = tier_phone-><API key>(token); QString bcptranscript, bcphonetisation; foreach (Interval *ph, phones) { QString p = ph->attribute(<API key>).toString(); if (p != "SIL") { bcptranscript.append(p); bcphonetisation.append(p).append(" "); } } token->setAttribute(<API key>, bcptranscript); d->dictionary.addWord(bcptranscript, bcphonetisation); } } void BroadClassAligner::prepareTiers(QList<CorpusCommunication *> communications) { foreach (CorpusCommunication *com, communications) { if (!com) return; if (!com->repository()) return; foreach (CorpusAnnotation *annot, com->annotations()) { <API key> tiersAll = com->repository()->annotations()->getTiersAllSpeakers(annot->ID()); foreach (QString speakerID, tiersAll.keys()) { AnnotationTierGroup *tiers = tiersAll.value(speakerID); if (!tiers) continue; IntervalTier *tier_phone = tiers-><API key>("cid_phoneme"); if (!tier_phone) continue; <API key>(tier_phone, "<API key>"); IntervalTier *tier_token = tiers-><API key>("cid_syll"); if (!tier_token) continue; update<API key>(tier_phone, "<API key>", tier_token, "<API key>"); tier_token->replace("<API key>", "SIL", ""); com->repository()->annotations()->saveTier(annot->ID(), speakerID, tier_phone); com->repository()->annotations()->saveTier(annot->ID(), speakerID, tier_token); } qDeleteAll(tiersAll); } } } void BroadClassAligner::<API key>(QList<CorpusCommunication *> communications, const QString &outputPath) { QScopedPointer<<API key>> trainer(new <API key>); QStringList unknownWords; initialiseFRcv(); // BPCA.buildDictionary("/home/george/broad-align/etc/original-french-62k.dic", // "/home/george/broad-align/etc/broad.dic"); prepareTiers(communications); d->dictionary.writeToFile(outputPath + "/broad.dic"); trainer->setTierUtterances("cid_transcription", ""); trainer->setTierTokens("cid_syll", "<API key>"); trainer->setOutputPath(outputPath); trainer-><API key>(d->dictionary); trainer->createFiles(communications, unknownWords, true, false); }
// modification, are permitted provided that the following conditions are // met: // with the distribution. // * Neither the name of Google Inc. nor the names of its // contributors may be used to endorse or promote products derived // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // 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. #ifndef <API key> #define <API key> #include "assembler.h" #include "frames.h" #include "v8globals.h" namespace v8 { namespace internal { // Static helper functions // Generate a MemOperand for loading a field from an object. inline MemOperand FieldMemOperand(Register object, int offset) { return MemOperand(object, offset - kHeapObjectTag); } inline Operand SmiUntagOperand(Register object) { return Operand(object, ASR, kSmiTagSize); } // Give alias names to registers const Register cp = { 8 }; // JavaScript context pointer const Register kRootRegister = { 10 }; // Roots array pointer. // Flags used for the AllocateInNewSpace functions. enum AllocationFlags { // No special flags. NO_ALLOCATION_FLAGS = 0, // Return the pointer to the allocated already tagged as a heap object. TAG_OBJECT = 1 << 0, // The content of the result register already contains the allocation top in // new space. RESULT_CONTAINS_TOP = 1 << 1, // Specify that the requested size of the space to allocate is specified in // words instead of bytes. SIZE_IN_WORDS = 1 << 2 }; // Flags used for the <API key> function. enum ObjectToDoubleFlags { // No special flags. <API key> = 0, // Object is known to be a non smi. OBJECT_NOT_SMI = 1 << 0, // Don't load NaNs or infinities, branch to the non number case instead. <API key> = 1 << 1 }; enum RememberedSetAction { EMIT_REMEMBERED_SET, OMIT_REMEMBERED_SET }; enum SmiCheck { INLINE_SMI_CHECK, OMIT_SMI_CHECK }; enum LinkRegisterStatus { kLRHasNotBeenSaved, kLRHasBeenSaved }; #ifdef DEBUG bool AreAliased(Register reg1, Register reg2, Register reg3 = no_reg, Register reg4 = no_reg, Register reg5 = no_reg, Register reg6 = no_reg); #endif // MacroAssembler implements a collection of frequently used macros. class MacroAssembler: public Assembler { public: // The isolate parameter can be NULL if the macro assembler should // not use isolate-dependent functionality. In this case, it's the // responsibility of the caller to never invoke such function on the // macro assembler. MacroAssembler(Isolate* isolate, void* buffer, int size); // Jump, Call, and Ret pseudo instructions implementing inter-working. void Jump(Register target, Condition cond = al); void Jump(Address target, RelocInfo::Mode rmode, Condition cond = al); void Jump(Handle<Code> code, RelocInfo::Mode rmode, Condition cond = al); static int CallSize(Register target, Condition cond = al); void Call(Register target, Condition cond = al); static int CallSize(Address target, RelocInfo::Mode rmode, Condition cond = al); void Call(Address target, RelocInfo::Mode rmode, Condition cond = al); static int CallSize(Handle<Code> code, RelocInfo::Mode rmode = RelocInfo::CODE_TARGET, unsigned ast_id = kNoASTId, Condition cond = al); void Call(Handle<Code> code, RelocInfo::Mode rmode = RelocInfo::CODE_TARGET, unsigned ast_id = kNoASTId, Condition cond = al); void Ret(Condition cond = al); // Emit code to discard a non-negative number of pointer-sized elements // from the stack, clobbering only the sp register. void Drop(int count, Condition cond = al); void Ret(int drop, Condition cond = al); // Swap two registers. If the scratch register is omitted then a slightly // less efficient form using xor instead of mov is emitted. void Swap(Register reg1, Register reg2, Register scratch = no_reg, Condition cond = al); void And(Register dst, Register src1, const Operand& src2, Condition cond = al); void Ubfx(Register dst, Register src, int lsb, int width, Condition cond = al); void Sbfx(Register dst, Register src, int lsb, int width, Condition cond = al); // The scratch register is not used for ARMv7. // scratch can be the same register as src (in which case it is trashed), but // not the same as dst. void Bfi(Register dst, Register src, Register scratch, int lsb, int width, Condition cond = al); void Bfc(Register dst, int lsb, int width, Condition cond = al); void Usat(Register dst, int satpos, const Operand& src, Condition cond = al); void Call(Label* target); // Register move. May do nothing if the registers are identical. void Move(Register dst, Handle<Object> value); void Move(Register dst, Register src, Condition cond = al); void Move(DoubleRegister dst, DoubleRegister src); // Load an object from the root table. void LoadRoot(Register destination, Heap::RootListIndex index, Condition cond = al); // Store an object to the root table. void StoreRoot(Register source, Heap::RootListIndex index, Condition cond = al); void LoadHeapObject(Register dst, Handle<HeapObject> object); void LoadObject(Register result, Handle<Object> object) { if (object->IsHeapObject()) { LoadHeapObject(result, Handle<HeapObject>::cast(object)); } else { Move(result, object); } } // GC Support void <API key>(Register object, Register value, Register address); enum <API key> { kReturnAtEnd, kFallThroughAtEnd }; // Record in the remembered set the fact that we have a pointer to new space // at the address pointed to by the addr register. Only works if addr is not // in new space. void RememberedSetHelper(Register object, // Used for debug code. Register addr, Register scratch, SaveFPRegsMode save_fp, <API key> and_then); void CheckPageFlag(Register object, Register scratch, int mask, Condition cc, Label* condition_met); // Check if object is in new space. Jumps if the object is not in new space. // The register scratch can be object itself, but scratch will be clobbered. void JumpIfNotInNewSpace(Register object, Register scratch, Label* branch) { InNewSpace(object, scratch, ne, branch); } // Check if object is in new space. Jumps if the object is in new space. // The register scratch can be object itself, but it will be clobbered. void JumpIfInNewSpace(Register object, Register scratch, Label* branch) { InNewSpace(object, scratch, eq, branch); } // Check if an object has a given incremental marking color. void HasColor(Register object, Register scratch0, Register scratch1, Label* has_color, int first_bit, int second_bit); void JumpIfBlack(Register object, Register scratch0, Register scratch1, Label* on_black); // Checks the color of an object. If the object is already grey or black // then we just fall through, since it is already live. If it is white and // we can determine that it doesn't need to be scanned, then we just mark it // black and fall through. For the rest we jump to the label so the // incremental marker can fix its assumptions. void EnsureNotWhite(Register object, Register scratch1, Register scratch2, Register scratch3, Label* <API key>); // Detects conservatively whether an object is data-only, i.e. it does need to // be scanned by the garbage collector. void JumpIfDataObject(Register value, Register scratch, Label* not_data_object); // Notify the garbage collector that we wrote a pointer into an object. // |object| is the object being stored into, |value| is the object being // stored. value and scratch registers are clobbered by the operation. // The offset is the offset from the start of the object, not the offset from // the tagged HeapObject pointer. For use with FieldOperand(reg, off). void RecordWriteField( Register object, int offset, Register value, Register scratch, LinkRegisterStatus lr_status, SaveFPRegsMode save_fp, RememberedSetAction <API key> = EMIT_REMEMBERED_SET, SmiCheck smi_check = INLINE_SMI_CHECK); // As above, but the offset has the tag presubtracted. For use with // MemOperand(reg, off). inline void <API key>( Register context, int offset, Register value, Register scratch, LinkRegisterStatus lr_status, SaveFPRegsMode save_fp, RememberedSetAction <API key> = EMIT_REMEMBERED_SET, SmiCheck smi_check = INLINE_SMI_CHECK) { RecordWriteField(context, offset + kHeapObjectTag, value, scratch, lr_status, save_fp, <API key>, smi_check); } // For a given |object| notify the garbage collector that the slot |address| // has been written. |value| is the object being stored. The value and // address registers are clobbered by the operation. void RecordWrite( Register object, Register address, Register value, LinkRegisterStatus lr_status, SaveFPRegsMode save_fp, RememberedSetAction <API key> = EMIT_REMEMBERED_SET, SmiCheck smi_check = INLINE_SMI_CHECK); // Push a handle. void Push(Handle<Object> handle); // Push two registers. Pushes leftmost register first (to highest address). void Push(Register src1, Register src2, Condition cond = al) { ASSERT(!src1.is(src2)); if (src1.code() > src2.code()) { stm(db_w, sp, src1.bit() | src2.bit(), cond); } else { str(src1, MemOperand(sp, 4, NegPreIndex), cond); str(src2, MemOperand(sp, 4, NegPreIndex), cond); } } // Push three registers. Pushes leftmost register first (to highest address). void Push(Register src1, Register src2, Register src3, Condition cond = al) { ASSERT(!src1.is(src2)); ASSERT(!src2.is(src3)); ASSERT(!src1.is(src3)); if (src1.code() > src2.code()) { if (src2.code() > src3.code()) { stm(db_w, sp, src1.bit() | src2.bit() | src3.bit(), cond); } else { stm(db_w, sp, src1.bit() | src2.bit(), cond); str(src3, MemOperand(sp, 4, NegPreIndex), cond); } } else { str(src1, MemOperand(sp, 4, NegPreIndex), cond); Push(src2, src3, cond); } } // Push four registers. Pushes leftmost register first (to highest address). void Push(Register src1, Register src2, Register src3, Register src4, Condition cond = al) { ASSERT(!src1.is(src2)); ASSERT(!src2.is(src3)); ASSERT(!src1.is(src3)); ASSERT(!src1.is(src4)); ASSERT(!src2.is(src4)); ASSERT(!src3.is(src4)); if (src1.code() > src2.code()) { if (src2.code() > src3.code()) { if (src3.code() > src4.code()) { stm(db_w, sp, src1.bit() | src2.bit() | src3.bit() | src4.bit(), cond); } else { stm(db_w, sp, src1.bit() | src2.bit() | src3.bit(), cond); str(src4, MemOperand(sp, 4, NegPreIndex), cond); } } else { stm(db_w, sp, src1.bit() | src2.bit(), cond); Push(src3, src4, cond); } } else { str(src1, MemOperand(sp, 4, NegPreIndex), cond); Push(src2, src3, src4, cond); } } // Pop two registers. Pops rightmost register first (from lower address). void Pop(Register src1, Register src2, Condition cond = al) { ASSERT(!src1.is(src2)); if (src1.code() > src2.code()) { ldm(ia_w, sp, src1.bit() | src2.bit(), cond); } else { ldr(src2, MemOperand(sp, 4, PostIndex), cond); ldr(src1, MemOperand(sp, 4, PostIndex), cond); } } // Pop three registers. Pops rightmost register first (from lower address). void Pop(Register src1, Register src2, Register src3, Condition cond = al) { ASSERT(!src1.is(src2)); ASSERT(!src2.is(src3)); ASSERT(!src1.is(src3)); if (src1.code() > src2.code()) { if (src2.code() > src3.code()) { ldm(ia_w, sp, src1.bit() | src2.bit() | src3.bit(), cond); } else { ldr(src3, MemOperand(sp, 4, PostIndex), cond); ldm(ia_w, sp, src1.bit() | src2.bit(), cond); } } else { Pop(src2, src3, cond); str(src1, MemOperand(sp, 4, PostIndex), cond); } } // Pop four registers. Pops rightmost register first (from lower address). void Pop(Register src1, Register src2, Register src3, Register src4, Condition cond = al) { ASSERT(!src1.is(src2)); ASSERT(!src2.is(src3)); ASSERT(!src1.is(src3)); ASSERT(!src1.is(src4)); ASSERT(!src2.is(src4)); ASSERT(!src3.is(src4)); if (src1.code() > src2.code()) { if (src2.code() > src3.code()) { if (src3.code() > src4.code()) { ldm(ia_w, sp, src1.bit() | src2.bit() | src3.bit() | src4.bit(), cond); } else { ldr(src4, MemOperand(sp, 4, PostIndex), cond); ldm(ia_w, sp, src1.bit() | src2.bit() | src3.bit(), cond); } } else { Pop(src3, src4, cond); ldm(ia_w, sp, src1.bit() | src2.bit(), cond); } } else { Pop(src2, src3, src4, cond); ldr(src1, MemOperand(sp, 4, PostIndex), cond); } } // Push and pop the registers that can hold pointers, as defined by the // RegList constant <API key>. void <API key>(); void <API key>(); void <API key>(); void <API key>(); // Store value in register src in the safepoint stack slot for // register dst. void <API key>(Register src, Register dst); void <API key>(Register src, Register dst); // Load the value of the src register from its safepoint stack slot // into register dst. void <API key>(Register dst, Register src); // Load two consecutive registers with two consecutive memory locations. void Ldrd(Register dst1, Register dst2, const MemOperand& src, Condition cond = al); // Store two consecutive registers to two consecutive memory locations. void Strd(Register src1, Register src2, const MemOperand& dst, Condition cond = al); // Clear specified FPSCR bits. void ClearFPSCRBits(const uint32_t bits_to_clear, const Register scratch, const Condition cond = al); // Compare double values and move the result to the normal condition flags. void <API key>(const DwVfpRegister src1, const DwVfpRegister src2, const Condition cond = al); void <API key>(const DwVfpRegister src1, const double src2, const Condition cond = al); // Compare double values and then load the fpscr flags to a register. void <API key>(const DwVfpRegister src1, const DwVfpRegister src2, const Register fpscr_flags, const Condition cond = al); void <API key>(const DwVfpRegister src1, const double src2, const Register fpscr_flags, const Condition cond = al); void Vmov(const DwVfpRegister dst, const double imm, const Condition cond = al); // Enter exit frame. // stack_space - extra stack space, used for alignment before call to C. void EnterExitFrame(bool save_doubles, int stack_space = 0); // Leave the current exit frame. Expects the return value in r0. // Expect the number of values, pushed prior to the exit frame, to // remove in a register (or no_reg, if there is nothing to remove). void LeaveExitFrame(bool save_doubles, Register argument_count); // Get the actual activation frame alignment for target environment. static int <API key>(); void LoadContext(Register dst, int <API key>); // Conditionally load the cached Array transitioned map of type // transitioned_kind from the global context if the map in register // map_in_out is the cached Array map in the global context of // expected_kind. void <API key>( ElementsKind expected_kind, ElementsKind transitioned_kind, Register map_in_out, Register scratch, Label* no_map_match); // Load the initial map for new Arrays from a JSFunction. void LoadInitialArrayMap(Register function_in, Register scratch, Register map_out); void LoadGlobalFunction(int index, Register function); // Load the initial map from the global function. The registers // function and map can be the same, function is then overwritten. void <API key>(Register function, Register map, Register scratch); void <API key>() { ExternalReference roots_array_start = ExternalReference::roots_array_start(isolate()); mov(kRootRegister, Operand(roots_array_start)); } // JavaScript invokes // Set up call kind marking in ecx. The method takes ecx as an // explicit first parameter to make the code more readable at the // call sites. void SetCallKind(Register dst, CallKind kind); // Invoke the JavaScript function code by either calling or jumping. void InvokeCode(Register code, const ParameterCount& expected, const ParameterCount& actual, InvokeFlag flag, const CallWrapper& call_wrapper, CallKind call_kind); void InvokeCode(Handle<Code> code, const ParameterCount& expected, const ParameterCount& actual, RelocInfo::Mode rmode, InvokeFlag flag, CallKind call_kind); // Invoke the JavaScript function in the given register. Changes the // current context to the context in the function before invoking. void InvokeFunction(Register function, const ParameterCount& actual, InvokeFlag flag, const CallWrapper& call_wrapper, CallKind call_kind); void InvokeFunction(Handle<JSFunction> function, const ParameterCount& actual, InvokeFlag flag, const CallWrapper& call_wrapper, CallKind call_kind); void <API key>(Register heap_object, Register map, Register scratch, Label* fail); void <API key>(Register map, Register scratch, Label* fail); void <API key>(Register object, Register scratch, Label* fail); #ifdef <API key> // Debugger Support void DebugBreak(); #endif // Exception handling // Push a new try handler and link into try handler chain. void PushTryHandler(StackHandler::Kind kind, int handler_index); // Unlink the stack handler on top of the stack from the try handler chain. // Must preserve the result register. void PopTryHandler(); // Passes thrown value to the handler of top of the try handler chain. void Throw(Register value); // Propagates an uncatchable exception to the top of the current JS stack's // handler chain. void ThrowUncatchable(Register value); // Inline caching support // Generate code for checking access rights - used for security checks // on access to global objects across environments. The holder register // is left untouched, whereas both scratch registers are clobbered. void <API key>(Register holder_reg, Register scratch, Label* miss); void GetNumberHash(Register t0, Register scratch); void <API key>(Label* miss, Register elements, Register key, Register result, Register t0, Register t1, Register t2); inline void MarkCode(NopMarkerTypes type) { nop(type); } // Check if the given instruction is a 'type' marker. // i.e. check if is is a mov r<type>, r<type> (referenced as nop(type)) // These instructions are generated to mark special location in the code, // like some special IC code. static inline bool IsMarkedCode(Instr instr, int type) { ASSERT((FIRST_IC_MARKER <= type) && (type < LAST_CODE_MARKER)); return IsNop(instr, type); } static inline int GetCodeMarker(Instr instr) { int dst_reg_offset = 12; int dst_mask = 0xf << dst_reg_offset; int src_mask = 0xf; int dst_reg = (instr & dst_mask) >> dst_reg_offset; int src_reg = instr & src_mask; uint32_t non_register_mask = ~(dst_mask | src_mask); uint32_t mov_mask = al | 13 << 21; // Return <n> if we have a mov rn rn, else return -1. int type = ((instr & non_register_mask) == mov_mask) && (dst_reg == src_reg) && (FIRST_IC_MARKER <= dst_reg) && (dst_reg < LAST_CODE_MARKER) ? src_reg : -1; ASSERT((type == -1) || ((FIRST_IC_MARKER <= type) && (type < LAST_CODE_MARKER))); return type; } // Allocation support // Allocate an object in new space. The object_size is specified // either in bytes or in words if the allocation flag SIZE_IN_WORDS // is passed. If the new space is exhausted control continues at the // gc_required label. The allocated object is returned in result. If // the flag <API key> is true the result is tagged as as // a heap object. All registers are clobbered also when control // continues at the gc_required label. void AllocateInNewSpace(int object_size, Register result, Register scratch1, Register scratch2, Label* gc_required, AllocationFlags flags); void AllocateInNewSpace(Register object_size, Register result, Register scratch1, Register scratch2, Label* gc_required, AllocationFlags flags); // Undo allocation in new space. The object passed and objects allocated after // it will no longer be allocated. The caller must make sure that no pointers // are left to the object(s) no longer allocated as they would be invalid when // allocation is undone. void <API key>(Register object, Register scratch); void <API key>(Register result, Register length, Register scratch1, Register scratch2, Register scratch3, Label* gc_required); void AllocateAsciiString(Register result, Register length, Register scratch1, Register scratch2, Register scratch3, Label* gc_required); void <API key>(Register result, Register length, Register scratch1, Register scratch2, Label* gc_required); void <API key>(Register result, Register length, Register scratch1, Register scratch2, Label* gc_required); void <API key>(Register result, Register length, Register scratch1, Register scratch2, Label* gc_required); void <API key>(Register result, Register length, Register scratch1, Register scratch2, Label* gc_required); // Allocates a heap number or jumps to the gc_required label if the young // space is full and a scavenge is needed. All registers are clobbered also // when control continues at the gc_required label. void AllocateHeapNumber(Register result, Register scratch1, Register scratch2, Register heap_number_map, Label* gc_required); void <API key>(Register result, DwVfpRegister value, Register scratch1, Register scratch2, Register heap_number_map, Label* gc_required); // Copies a fixed number of fields of heap objects from src to dst. void CopyFields(Register dst, Register src, RegList temps, int field_count); // Copies a number of bytes from src to dst. All registers are clobbered. On // exit src and dst will point to the place just after where the last byte was // read or written and length will be zero. void CopyBytes(Register src, Register dst, Register length, Register scratch); // Initialize fields with filler values. Fields starting at |start_offset| // not including end_offset are overwritten with the value in |filler|. At // the end the loop, |start_offset| takes the value of |end_offset|. void <API key>(Register start_offset, Register end_offset, Register filler); // Support functions. // Try to get function prototype of a function and puts the value in // the result register. Checks that the function really is a // function and jumps to the miss label if the fast checks fail. The // function register will be untouched; the other registers may be // clobbered. void <API key>(Register function, Register result, Register scratch, Label* miss, bool <API key> = false); // Compare object type for heap object. heap_object contains a non-Smi // whose object type should be compared with the given type. This both // sets the flags and leaves the object type in the type_reg register. // It leaves the map in the map register (unless the type_reg and map register // are the same register). It leaves the heap object in the heap_object // register unless the heap_object register is the same register as one of the // other registers. void CompareObjectType(Register heap_object, Register map, Register type_reg, InstanceType type); // Compare instance type in a map. map contains a valid map object whose // object type should be compared with the given type. This both // sets the flags and leaves the object type in the type_reg register. void CompareInstanceType(Register map, Register type_reg, InstanceType type); // Check if a map for a JSObject indicates that the object has fast elements. // Jump to the specified label if it does not. void CheckFastElements(Register map, Register scratch, Label* fail); // Check if a map for a JSObject indicates that the object can have both smi // and HeapObject elements. Jump to the specified label if it does not. void <API key>(Register map, Register scratch, Label* fail); // Check if a map for a JSObject indicates that the object has fast smi only // elements. Jump to the specified label if it does not. void <API key>(Register map, Register scratch, Label* fail); // Check to see if maybe_number can be stored as a double in // FastDoubleElements. If it can, store it at the index specified by key in // the FastDoubleElements array elements. Otherwise jump to fail, in which // case scratch2, scratch3 and scratch4 are unmodified. void <API key>(Register value_reg, Register key_reg, Register receiver_reg, Register elements_reg, Register scratch1, Register scratch2, Register scratch3, Register scratch4, Label* fail); // Compare an object's map with the specified map and its transitioned // elements maps if mode is <API key>. Condition flags are // set with result of map compare. If multiple map compares are required, the // compare sequences branches to early_success. void CompareMap(Register obj, Register scratch, Handle<Map> map, Label* early_success, CompareMapMode mode = REQUIRE_EXACT_MAP); // Check if the map of an object is equal to a specified map and branch to // label if not. Skip the smi check if not required (object is known to be a // heap object). If mode is <API key>, then also match // against maps that are ElementsKind transition maps of the specified map. void CheckMap(Register obj, Register scratch, Handle<Map> map, Label* fail, SmiCheckType smi_check_type, CompareMapMode mode = REQUIRE_EXACT_MAP); void CheckMap(Register obj, Register scratch, Heap::RootListIndex index, Label* fail, SmiCheckType smi_check_type); // Check if the map of an object is equal to a specified map and branch to a // specified target if equal. Skip the smi check if not required (object is // known to be a heap object) void DispatchMap(Register obj, Register scratch, Handle<Map> map, Handle<Code> success, SmiCheckType smi_check_type); // Compare the object in a register to a value from the root list. // Uses the ip register as scratch. void CompareRoot(Register obj, Heap::RootListIndex index); // Load and check the instance type of an object for being a string. // Loads the type into the second argument register. // Returns a condition that will be enabled if the object was a string. Condition IsObjectStringType(Register obj, Register type) { ldr(type, FieldMemOperand(obj, HeapObject::kMapOffset)); ldrb(type, FieldMemOperand(type, Map::kInstanceTypeOffset)); tst(type, Operand(kIsNotStringMask)); ASSERT_EQ(0, kStringTag); return eq; } // occurred. void IllegalOperation(int num_arguments); // Picks out an array index from the hash field. // Register use: // hash - holds the index's hash. Clobbered. // index - holds the overwritten index on exit. void IndexFromHash(Register hash, Register index); // Get the number of least significant bits from a register void GetLeastBitsFromSmi(Register dst, Register src, int num_least_bits); void <API key>(Register dst, Register src, int mun_least_bits); // Uses VFP instructions to Convert a Smi to a double. void <API key>(Register inReg, Register outHighReg, Register outLowReg); // Load the value of a number object into a VFP double register. If the object // is not a number a jump to the label not_number is performed and the VFP // double register is unchanged. void <API key>( Register object, DwVfpRegister value, Register scratch1, Register scratch2, Register heap_number_map, SwVfpRegister scratch3, Label* not_number, ObjectToDoubleFlags flags = <API key>); // Load the value of a smi object into a VFP double register. The register // scratch1 can be the same register as smi in which case smi will hold the // untagged value afterwards. void <API key>(Register smi, DwVfpRegister value, Register scratch1, SwVfpRegister scratch2); // Convert the HeapNumber pointed to by source to a 32bits signed integer // dest. If the HeapNumber does not fit into a 32bits signed integer branch // to not_int32 label. If VFP3 is available double_scratch is used but not // scratch2. void ConvertToInt32(Register source, Register dest, Register scratch, Register scratch2, DwVfpRegister double_scratch, Label *not_int32); // Truncates a double using a specific rounding mode. // Clears the z flag (ne condition) if an overflow occurs. // If exact_conversion is true, the z flag is also cleared if the conversion // was inexact, i.e. if the double value could not be converted exactly // to a 32bit integer. void EmitVFPTruncate(VFPRoundingMode rounding_mode, SwVfpRegister result, DwVfpRegister double_input, Register scratch1, Register scratch2, <API key> check = <API key>); // Helper for EmitECMATruncate. // This will truncate a floating-point value outside of the singed 32bit // integer range to a 32bit signed integer. // Expects the double value loaded in input_high and input_low. // Exits with the answer in 'result'. // Note that this code does not work for values in the 32bit range! void <API key>(Register result, Register input_high, Register input_low, Register scratch); // Performs a truncating conversion of a floating point number as used by // the JS bitwise operations. See ECMA-262 9.5: ToInt32. // Exits with 'result' holding the answer and all other registers clobbered. void EmitECMATruncate(Register result, DwVfpRegister double_input, SwVfpRegister single_scratch, Register scratch, Register scratch2, Register scratch3); // Count leading zeros in a 32 bit word. On ARM5 and later it uses the clz // instruction. On pre-ARM5 hardware this routine gives the wrong answer // for 0 (31 instead of 32). Source and scratch can be the same in which case // the source is clobbered. Source and zeros can also be the same in which // case scratch should be a different register. void CountLeadingZeros(Register zeros, Register source, Register scratch); // Runtime calls // Call a code stub. void CallStub(CodeStub* stub, Condition cond = al); // Call a code stub. void TailCallStub(CodeStub* stub, Condition cond = al); // Call a runtime routine. void CallRuntime(const Runtime::Function* f, int num_arguments); void <API key>(Runtime::FunctionId id); // Convenience function: Same as above, but takes the fid instead. void CallRuntime(Runtime::FunctionId fid, int num_arguments); // Convenience function: call an external reference. void <API key>(const ExternalReference& ext, int num_arguments); // Tail call of a runtime routine (jump). // Like <API key>, but also takes care of passing the number // of parameters. void <API key>(const ExternalReference& ext, int num_arguments, int result_size); // Convenience function: tail call a runtime routine (jump). void TailCallRuntime(Runtime::FunctionId fid, int num_arguments, int result_size); int <API key>(int num_reg_arguments, int <API key>); // Before calling a C-function from generated code, align arguments on stack. // After aligning the frame, non-register arguments must be stored in // sp[0], sp[4], etc., not pushed. The argument count assumes all arguments // are word sized. If double arguments are used, this function assumes that // all double arguments are stored before core registers; otherwise the // correct alignment of the double values is not guaranteed. // Some compilers/platforms require the stack to be aligned when calling // C++ code. // Needs a scratch register to do some arithmetic. This register will be // trashed. void <API key>(int num_reg_arguments, int <API key>, Register scratch); void <API key>(int num_reg_arguments, Register scratch); // There are two ways of passing double arguments on ARM, depending on // whether soft or hard floating point ABI is used. These functions // abstract parameter passing for the three different ways we call // C functions from generated code. void <API key>(DoubleRegister dreg); void <API key>(DoubleRegister dreg1, DoubleRegister dreg2); void <API key>(DoubleRegister dreg, Register reg); // Calls a C function and cleans up the space for arguments allocated // by <API key>. The called function is not allowed to trigger a // garbage collection, since that might move the code and invalidate the // return address (unless this is somehow accounted for by the called // function). void CallCFunction(ExternalReference function, int num_arguments); void CallCFunction(Register function, int num_arguments); void CallCFunction(ExternalReference function, int num_reg_arguments, int <API key>); void CallCFunction(Register function, int num_reg_arguments, int <API key>); void <API key>(const DoubleRegister dst); // Calls an API function. Allocates HandleScope, extracts returned value // from handle and propagates exceptions. Restores context. stack_space // - space to be unwound on exit (includes the call JS arguments space and // the additional space allocated for the fast call). void <API key>(ExternalReference function, int stack_space); // Jump to a runtime routine. void <API key>(const ExternalReference& builtin); // Invoke specified builtin JavaScript function. Adds an entry to // the unresolved list if the name does not resolve. void InvokeBuiltin(Builtins::JavaScript id, InvokeFlag flag, const CallWrapper& call_wrapper = NullCallWrapper()); // Store the code object for the given builtin in the target register and // setup the function in r1. void GetBuiltinEntry(Register target, Builtins::JavaScript id); // Store the function for the given builtin in the target register. void GetBuiltinFunction(Register target, Builtins::JavaScript id); Handle<Object> CodeObject() { ASSERT(!code_object_.is_null()); return code_object_; } // StatsCounter support void SetCounter(StatsCounter* counter, int value, Register scratch1, Register scratch2); void IncrementCounter(StatsCounter* counter, int value, Register scratch1, Register scratch2); void DecrementCounter(StatsCounter* counter, int value, Register scratch1, Register scratch2); // Debugging // Calls Abort(msg) if the condition cond is not satisfied. // Use --debug_code to enable. void Assert(Condition cond, const char* msg); void <API key>(Register reg, Heap::RootListIndex index); void AssertFastElements(Register elements); // Like Assert(), but always enabled. void Check(Condition cond, const char* msg); // Print a message to stdout and abort execution. void Abort(const char* msg); // Verify restrictions about code generated in stubs. void set_generating_stub(bool value) { generating_stub_ = value; } bool generating_stub() { return generating_stub_; } void <API key>(bool value) { allow_stub_calls_ = value; } bool allow_stub_calls() { return allow_stub_calls_; } void set_has_frame(bool value) { has_frame_ = value; } bool has_frame() { return has_frame_; } inline bool AllowThisStubCall(CodeStub* stub); // EABI variant for double arguments in use. bool use_eabi_hardfloat() { #if USE_EABI_HARDFLOAT return true; #else return false; #endif } // Number utilities // Check whether the value of reg is a power of two and not zero. If not // control continues at the label not_power_of_two. If reg is a power of two // the register scratch contains the value of (reg - 1) when control falls // through. void <API key>(Register reg, Register scratch, Label* <API key>); // Check whether the value of reg is a power of two and not zero. // Control falls through if it is, with scratch containing the mask // value (reg - 1). // Otherwise control jumps to the 'zero_and_neg' label if the value of reg is // zero or negative, or jumps to the 'not_power_of_two' label if the value is // strictly positive but not a power of two. void <API key>(Register reg, Register scratch, Label* zero_and_neg, Label* not_power_of_two); // Smi utilities void SmiTag(Register reg, SBit s = LeaveCC) { add(reg, reg, Operand(reg), s); } void SmiTag(Register dst, Register src, SBit s = LeaveCC) { add(dst, src, Operand(src), s); } // Try to convert int32 to smi. If the value is to large, preserve // the original value and jump to not_a_smi. Destroys scratch and // sets flags. void TrySmiTag(Register reg, Label* not_a_smi, Register scratch) { mov(scratch, reg); SmiTag(scratch, SetCC); b(vs, not_a_smi); mov(reg, scratch); } void SmiUntag(Register reg, SBit s = LeaveCC) { mov(reg, Operand(reg, ASR, kSmiTagSize), s); } void SmiUntag(Register dst, Register src, SBit s = LeaveCC) { mov(dst, Operand(src, ASR, kSmiTagSize), s); } // Untag the source value into destination and jump if source is a smi. // Souce and destination can be the same register. void UntagAndJumpIfSmi(Register dst, Register src, Label* smi_case); // Untag the source value into destination and jump if source is not a smi. // Souce and destination can be the same register. void <API key>(Register dst, Register src, Label* non_smi_case); // Jump the register contains a smi. inline void JumpIfSmi(Register value, Label* smi_label) { tst(value, Operand(kSmiTagMask)); b(eq, smi_label); } // Jump if either of the registers contain a non-smi. inline void JumpIfNotSmi(Register value, Label* not_smi_label) { tst(value, Operand(kSmiTagMask)); b(ne, not_smi_label); } // Jump if either of the registers contain a non-smi. void JumpIfNotBothSmi(Register reg1, Register reg2, Label* on_not_both_smi); // Jump if either of the registers contain a smi. void JumpIfEitherSmi(Register reg1, Register reg2, Label* on_either_smi); // Abort execution if argument is a smi. Used in debug code. void AbortIfSmi(Register object); void AbortIfNotSmi(Register object); // Abort execution if argument is a string. Used in debug code. void AbortIfNotString(Register object); // Abort execution if argument is not the root value with the given index. void AbortIfNotRootValue(Register src, Heap::RootListIndex root_value_index, const char* message); // HeapNumber utilities void JumpIfNotHeapNumber(Register object, Register heap_number_map, Register scratch, Label* on_not_heap_number); // String utilities // Checks if both objects are sequential ASCII strings and jumps to label // if either is not. Assumes that neither object is a smi. void <API key>(Register object1, Register object2, Register scratch1, Register scratch2, Label* failure); // Checks if both objects are sequential ASCII strings and jumps to label // if either is not. void <API key>(Register first, Register second, Register scratch1, Register scratch2, Label* <API key>); // Checks if both instance types are sequential ASCII strings and jumps to // label if either is not. void <API key>( Register <API key>, Register <API key>, Register scratch1, Register scratch2, Label* failure); // Check if instance type is sequential ASCII string and jump to label if // it is not. void <API key>(Register type, Register scratch, Label* failure); // Patching helpers. // Get the location of a relocated constant (its address in the constant pool) // from its load site. void <API key>(Register ldr_location, Register result); void ClampUint8(Register output_reg, Register input_reg); void ClampDoubleToUint8(Register result_reg, DoubleRegister input_reg, DoubleRegister temp_double_reg); void <API key>(Register map, Register descriptors); // Activation support. void EnterFrame(StackFrame::Type type); void LeaveFrame(StackFrame::Type type); // Expects object in r0 and returns map with validated enum cache // in r0. Assumes that any other register can be used as a scratch. void CheckEnumCache(Register null_value, Label* call_runtime); private: void CallCFunctionHelper(Register function, int num_reg_arguments, int <API key>); void Jump(intptr_t target, RelocInfo::Mode rmode, Condition cond = al); // Helper functions for generating invokes. void InvokePrologue(const ParameterCount& expected, const ParameterCount& actual, Handle<Code> code_constant, Register code_reg, Label* done, bool* <API key>, InvokeFlag flag, const CallWrapper& call_wrapper, CallKind call_kind); void InitializeNewString(Register string, Register length, Heap::RootListIndex map_index, Register scratch1, Register scratch2); // Helper for implementing JumpIfNotInNewSpace and JumpIfInNewSpace. void InNewSpace(Register object, Register scratch, Condition cond, // eq for new space, ne otherwise. Label* branch); // Helper for finding the mark bits for an address. Afterwards, the // bitmap register points at the word with the mark bits and the mask // the position of the first bit. Leaves addr_reg unchanged. inline void GetMarkBits(Register addr_reg, Register bitmap_reg, Register mask_reg); // Helper for throwing exceptions. Compute a handler address and jump to // it. See the implementation for register usage. void JumpToHandlerEntry(); // Compute memory operands for safepoint stack slots. static int <API key>(int reg_code); MemOperand <API key>(Register reg); MemOperand <API key>(Register reg); bool generating_stub_; bool allow_stub_calls_; bool has_frame_; // This handle will be patched with the code object on installation. Handle<Object> code_object_; // Needs access to <API key> for optimized frame // traversal. friend class OptimizedFrame; }; // The code patcher is used to patch (typically) small parts of code e.g. for // debugging and other types of instrumentation. When using the code patcher // relocation information. If any of these constraints are violated it causes // an assertion to fail. class CodePatcher { public: CodePatcher(byte* address, int instructions); virtual ~CodePatcher(); // Macro assembler to emit code. MacroAssembler* masm() { return &masm_; } // Emit an instruction directly. void Emit(Instr instr); // Emit an address directly. void Emit(Address addr); // Emit the condition part of an instruction leaving the rest of the current // instruction unchanged. void EmitCondition(Condition cond); private: byte* address_; // The address of the code being patched. int instructions_; // Number of instructions of the expected patch size. int size_; // Number of bytes of the expected patch size. MacroAssembler masm_; // Macro assembler used to generate the code. }; // Static helper functions. inline MemOperand ContextOperand(Register context, int index) { return MemOperand(context, Context::SlotOffset(index)); } inline MemOperand GlobalObjectOperand() { return ContextOperand(cp, Context::GLOBAL_INDEX); } static inline MemOperand <API key>() { return ContextOperand(cp, Context::QML_GLOBAL_INDEX); } #ifdef <API key> #define <API key>(x) #define <API key>(x) <API key>(x) #define __FILE_LINE__ __FILE__ ":" <API key>(__LINE__) #define ACCESS_MASM(masm) masm->stop(__FILE_LINE__); masm-> #else #define ACCESS_MASM(masm) masm-> #endif } } // namespace v8::internal #endif // <API key>
Script.delay=1000--int "Delay" Script.activatetime=0 function Script:Activate()--in self.activatetime = Time:GetCurrent()+self.delay end function Script:UpdatePhysics() if self.activatetime>0 then if Time:GetCurrent()>self.activatetime then self.activatetime=0 self.component:CallOutputs("Activate") end end end
using NitroxModel.DataStructures.Util; using <API key>.DataStructures.GameLogic; using <API key>.Packets; using NitroxServer.Communication.Packets.Processors.Abstract; using NitroxServer.GameLogic; using NitroxServer.GameLogic.Vehicles; namespace <API key>.Communication.Packets.Processors { public class <API key> : <API key><RocketElevatorCall> { private readonly VehicleManager vehicleManager; private readonly PlayerManager playerManager; public <API key>(VehicleManager vehicleManager, PlayerManager playerManager) { this.vehicleManager = vehicleManager; this.playerManager = playerManager; } public override void Process(RocketElevatorCall packet, NitroxServer.Player player) { Optional<NeptuneRocketModel> opRocket = vehicleManager.GetVehicleModel<NeptuneRocketModel>(packet.Id); if (opRocket.HasValue) { opRocket.Value.ElevatorUp = packet.Up; } else { Log.Error($"{nameof(<API key>)}: Can't find server model for rocket with id {packet.Id}"); } playerManager.<API key>(packet, player); } } }
import math def poohbear(code): out = [] step = 1024 capa = step mem = bytearray('\0' * capa, 'ascii') mc = capa copied = None loop = [] cl = len(code) cc = 0 while cc < cl: c = code[cc] if c == '+': mem[mc] = 0 if mem[mc] == 255 else mem[mc] + 1 elif c == '-': mem[mc] = 255 if mem[mc] == 0 else mem[mc] - 1 elif c == '>': if mc == capa: mem += bytearray('\0' * step, 'ascii') mc += 1 elif c == '<': if mc == 0: mem = bytearray('\0' * step, 'ascii') + mem mc = step mc -= 1 elif c == 'c': copied = mem[mc] elif c == 'p': mem[mc] = copied elif c == 'W': if mem[mc] is not 0: loop.append(cc) print 'W', mem[mc], loop else: ec = code[cc:].find('E') if ec >= 0: cc += ec + 1 continue else: break elif c == 'E': cc = loop.pop() print 'E', loop, cc continue elif c == 'P': out.append(chr(mem[mc])) elif c == 'N': out.append(str(mem[mc])) elif c == 'T': mem[mc] = mem[mc] * 2 % 256 elif c == 'Q': mem[mc] = mem[mc] ** 2 % 256 elif c == 'U': mem[mc] = int(math.sqrt(mem[mc])) elif c == 'L': mem[mc] += 2 elif c == 'I': mem[mc] -= 2 elif c == 'V': mem[mc] elif c == 'A': mem[mc] += copied elif c == 'B': mem[mc] -= copied elif c == 'Y': mem[mc] *= copied elif c == 'D': mem[mc] //= copied cc += 1 return ''.join(out) if __name__ == '__main__': print(poohbear('LQTcQAP>pQBBTAI-PA-PPL+P<BVPAL+T+P>PL+PBLPBP<DLLLT+P'), 'Hello World!') print(poohbear('+LTQII>+WN<P>+E'))
/* global test, expect, jasmine */ import configureStore from '../client/configureStore.js' import { LOADED, NOT_LOADED, NOT_DOWNLOADED } from '../utils/constants.js' import { addManga, removeManga, updatePage, loadChapter, VISIT_MANGA, DIFF_CHANGES } from '../client/actions/manga.js' jasmine.<API key> = 10000 test('manga reducer', () => { const store = configureStore(false) const mangaName = 'onepunch-man' const getManga = (store) => store.getState().manga.get(mangaName) return store .dispatch(addManga(`http: .then(() => { expect(store.getState().manga.has(mangaName)).toEqual(true) // Test if visiting the manga sets the 'new' property to false. expect(getManga(store).get('new')).toEqual(true) store.dispatch({ type: VISIT_MANGA, mangaName }) expect(getManga(store).get('new')).toEqual(false) // Test loading a chapter. return store.dispatch(loadChapter(store.getState().manga.get(mangaName), 0, true)) }).then(() => { // Test that chapter was loaded. expect(getManga(store).getIn(['chapters', 0, 'loadState'])).toEqual(LOADED) // Test updating a page. const pages = getManga(store).getIn(['chapters', 0, 'pages']).count() store.dispatch(updatePage(getManga(store), 0, pages - 1)) expect(getManga(store).getIn(['chapters', 0, 'currentPage'])).toEqual(pages - 1) store.dispatch(updatePage(store.getState().manga.get(mangaName), 0, -(pages - 1))) expect(getManga(store).getIn(['chapters', 0, 'currentPage'])).toEqual(0) // Test that attempting to update a page out of bounds won't update the page. store.dispatch(updatePage(getManga(store), 0, 100)) expect(getManga(store).getIn(['chapters', 0, 'currentPage'])).toEqual(0) store.dispatch(updatePage(getManga(store), 0, -200)) expect(getManga(store).getIn(['chapters', 0, 'currentPage'])).toEqual(0) // Test diffing manga changes. const oldManga = getManga(store) const newManga = oldManga.update('chapters', (chapters) => chapters.push({ name: 'A new chapter!', url: 'www.google.com', date: '1/1/1', loadState: NOT_LOADED, download: { state: NOT_DOWNLOADED, progress: 0 }, currentPage: 0, pages: [] })) store.dispatch({ type: DIFF_CHANGES, manga: newManga.toJS() }) // Check if all of the old chapters are still the same. for (let i = 0; i < oldManga.get('chapters').count(); i++) { const oldChapter = oldManga.getIn(['chapters', i]).toJS() const newChapter = getManga(store).getIn(['chapters', i]).toJS() expect(oldChapter).toEqual(newChapter) } // Check if there is a new chapter added. expect(getManga(store).get('chapters').count()).toEqual(newManga.get('chapters').count()) // Test removing the manga. store.dispatch(removeManga(mangaName)) expect(store.getState().manga.has(mangaName)).toEqual(false) }) })
<!DOCTYPE HTML PUBLIC "- <!-- NewPage --> <html lang="en"> <head> <!-- Generated by javadoc (version 1.7.0_02) on Thu Oct 10 13:06:25 EDT 2013 --> <title>BinOpDiv</title> <meta name="date" content="2013-10-10"> <link rel="stylesheet" type="text/css" href="../../../stylesheet.css" title="Style"> </head> <body> <script type="text/javascript"><! if (location.href.indexOf('is-external=true') == -1) { parent.document.title="BinOpDiv"; } </script> <noscript> <div>JavaScript is disabled on your browser.</div> </noscript> <div class="topNav"><a name="navbar_top"> </a><a href="#skip-navbar_top" title="Skip navigation links"></a><a name="navbar_top_firstrow"> </a> <ul class="navList" title="Navigation"> <li><a href="../../../overview-summary.html">Overview</a></li> <li><a href="package-summary.html">Package</a></li> <li class="navBarCell1Rev">Class</li> <li><a href="class-use/BinOpDiv.html">Use</a></li> <li><a href="package-tree.html">Tree</a></li> <li><a href="../../../index-files/index-1.html">Index</a></li> <li><a href="../../../help-doc.html">Help</a></li> </ul> </div> <div class="subNav"> <ul class="navList"> <li><a href="../../../sial/parser/Ast/BinaryExpression.html" title="class in sial.parser.Ast"><span class="strong">Prev Class</span></a></li> <li><a href="../../../sial/parser/Ast/BinOpMinus.html" title="class in sial.parser.Ast"><span class="strong">Next Class</span></a></li> </ul> <ul class="navList"> <li><a href="../../../index.html?sial/parser/Ast/BinOpDiv.html" target="_top">Frames</a></li> <li><a href="BinOpDiv.html" target="_top">No Frames</a></li> </ul> <ul class="navList" id="<API key>"> <li><a href="../../../allclasses-noframe.html">All Classes</a></li> </ul> <div> <script type="text/javascript"><! allClassesLink = document.getElementById("<API key>"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } </script> </div> <div> <ul class="subNavList"> <li>Summary:&nbsp;</li> <li>Nested&nbsp;|&nbsp;</li> <li>Field&nbsp;|&nbsp;</li> <li><a href="#constructor_summary">Constr</a>&nbsp;|&nbsp;</li> <li><a href="#method_summary">Method</a></li> </ul> <ul class="subNavList"> <li>Detail:&nbsp;</li> <li>Field&nbsp;|&nbsp;</li> <li><a href="#constructor_detail">Constr</a>&nbsp;|&nbsp;</li> <li><a href="#method_detail">Method</a></li> </ul> </div> <a name="skip-navbar_top"> </a></div> <div class="header"> <div class="subTitle">sial.parser.Ast</div> <h2 title="Class BinOpDiv" class="title">Class BinOpDiv</h2> </div> <div class="contentContainer"> <ul class="inheritance"> <li>java.lang.Object</li> <li> <ul class="inheritance"> <li><a href="../../../sial/parser/Ast/ASTNode.html" title="class in sial.parser.Ast">sial.parser.Ast.ASTNode</a></li> <li> <ul class="inheritance"> <li><a href="../../../sial/parser/Ast/ASTNodeToken.html" title="class in sial.parser.Ast">sial.parser.Ast.ASTNodeToken</a></li> <li> <ul class="inheritance"> <li>sial.parser.Ast.BinOpDiv</li> </ul> </li> </ul> </li> </ul> </li> </ul> <div class="description"> <ul class="blockList"> <li class="blockList"> <dl> <dt>All Implemented Interfaces:</dt> <dd>lpg.runtime.IAst, <a href="../../../sial/parser/Ast/IASTNodeToken.html" title="interface in sial.parser.Ast">IASTNodeToken</a>, <a href="../../../sial/parser/Ast/IBinOp.html" title="interface in sial.parser.Ast">IBinOp</a></dd> </dl> <hr> <br> <pre>public class <span class="strong">BinOpDiv</span> extends <a href="../../../sial/parser/Ast/ASTNodeToken.html" title="class in sial.parser.Ast">ASTNodeToken</a> implements <a href="../../../sial/parser/Ast/IBinOp.html" title="interface in sial.parser.Ast">IBinOp</a></pre> <div class="block"><b> <li>Rule 119: BinOp ::= / </b></div> </li> </ul> </div> <div class="summary"> <ul class="blockList"> <li class="blockList"> <ul class="blockList"> <li class="blockList"><a name="constructor_summary"> </a> <h3>Constructor Summary</h3> <table class="overviewSummary" border="0" cellpadding="3" cellspacing="0" summary="Constructor Summary table, listing constructors, and an explanation"> <caption><span>Constructors</span><span class="tabEnd">&nbsp;</span></caption> <tr> <th class="colOne" scope="col">Constructor and Description</th> </tr> <tr class="altColor"> <td class="colOne"><code><strong><a href="../../../sial/parser/Ast/BinOpDiv.html#BinOpDiv(lpg.runtime.IToken)">BinOpDiv</a></strong>(lpg.runtime.IToken&nbsp;token)</code>&nbsp;</td> </tr> </table> </li> </ul> <ul class="blockList"> <li class="blockList"><a name="method_summary"> </a> <h3>Method Summary</h3> <table class="overviewSummary" border="0" cellpadding="3" cellspacing="0" summary="Method Summary table, listing methods, and an explanation"> <caption><span>Methods</span><span class="tabEnd">&nbsp;</span></caption> <tr> <th class="colFirst" scope="col">Modifier and Type</th> <th class="colLast" scope="col">Method and Description</th> </tr> <tr class="altColor"> <td class="colFirst"><code>void</code></td> <td class="colLast"><code><strong><a href="../../../sial/parser/Ast/BinOpDiv.html#accept(lpg.runtime.IAstVisitor)">accept</a></strong>(lpg.runtime.IAstVisitor&nbsp;v)</code>&nbsp;</td> </tr> <tr class="rowColor"> <td class="colFirst"><code>void</code></td> <td class="colLast"><code><strong><a href="../../../sial/parser/Ast/BinOpDiv.html#enter(sial.parser.Ast.Visitor)">enter</a></strong>(<a href="../../../sial/parser/Ast/Visitor.html" title="interface in sial.parser.Ast">Visitor</a>&nbsp;v)</code>&nbsp;</td> </tr> <tr class="altColor"> <td class="colFirst"><code>lpg.runtime.IToken</code></td> <td class="colLast"><code><strong><a href="../../../sial/parser/Ast/BinOpDiv.html#getSLASH()">getSLASH</a></strong>()</code>&nbsp;</td> </tr> </table> <ul class="blockList"> <li class="blockList"><a name="<API key>.parser.Ast.ASTNodeToken"> </a> <h3>Methods inherited from class&nbsp;sial.parser.Ast.<a href="../../../sial/parser/Ast/ASTNodeToken.html" title="class in sial.parser.Ast">ASTNodeToken</a></h3> <code><a href="../../../sial/parser/Ast/ASTNodeToken.html#equals(java.lang.Object)">equals</a>, <a href="../../../sial/parser/Ast/ASTNodeToken.html#getAllChildren()">getAllChildren</a>, <a href="../../../sial/parser/Ast/ASTNodeToken.html#getIToken()">getIToken</a>, <a href="../../../sial/parser/Ast/ASTNodeToken.html#hashCode()">hashCode</a>, <a href="../../../sial/parser/Ast/ASTNodeToken.html#toString()">toString</a></code></li> </ul> <ul class="blockList"> <li class="blockList"><a name="<API key>.parser.Ast.ASTNode"> </a> <h3>Methods inherited from class&nbsp;sial.parser.Ast.<a href="../../../sial/parser/Ast/ASTNode.html" title="class in sial.parser.Ast">ASTNode</a></h3> <code><a href="../../../sial/parser/Ast/ASTNode.html#getChildren()">getChildren</a>, <a href="../../../sial/parser/Ast/ASTNode.html#<API key>()"><API key></a>, <a href="../../../sial/parser/Ast/ASTNode.html#getLeftIToken()">getLeftIToken</a>, <a href="../../../sial/parser/Ast/ASTNode.html#getNextAst()">getNextAst</a>, <a href="../../../sial/parser/Ast/ASTNode.html#getParent()">getParent</a>, <a href="../../../sial/parser/Ast/ASTNode.html#<API key>()"><API key></a>, <a href="../../../sial/parser/Ast/ASTNode.html#getRightIToken()">getRightIToken</a></code></li> </ul> <ul class="blockList"> <li class="blockList"><a name="<API key>.lang.Object"> </a> <h3>Methods inherited from class&nbsp;java.lang.Object</h3> <code>getClass, notify, notifyAll, wait, wait, wait</code></li> </ul> <ul class="blockList"> <li class="blockList"><a name="<API key>.parser.Ast.IASTNodeToken"> </a> <h3>Methods inherited from interface&nbsp;sial.parser.Ast.<a href="../../../sial/parser/Ast/IASTNodeToken.html" title="interface in sial.parser.Ast">IASTNodeToken</a></h3> <code><a href="../../../sial/parser/Ast/IASTNodeToken.html#getLeftIToken()">getLeftIToken</a>, <a href="../../../sial/parser/Ast/IASTNodeToken.html#getRightIToken()">getRightIToken</a></code></li> </ul> </li> </ul> </li> </ul> </div> <div class="details"> <ul class="blockList"> <li class="blockList"> <ul class="blockList"> <li class="blockList"><a name="constructor_detail"> </a> <h3>Constructor Detail</h3> <a name="BinOpDiv(lpg.runtime.IToken)"> </a> <ul class="blockListLast"> <li class="blockList"> <h4>BinOpDiv</h4> <pre>public&nbsp;BinOpDiv(lpg.runtime.IToken&nbsp;token)</pre> </li> </ul> </li> </ul> <ul class="blockList"> <li class="blockList"><a name="method_detail"> </a> <h3>Method Detail</h3> <a name="accept(lpg.runtime.IAstVisitor)"> </a> <ul class="blockList"> <li class="blockList"> <h4>accept</h4> <pre>public&nbsp;void&nbsp;accept(lpg.runtime.IAstVisitor&nbsp;v)</pre> <dl> <dt><strong>Specified by:</strong></dt> <dd><code>accept</code>&nbsp;in interface&nbsp;<code>lpg.runtime.IAst</code></dd> <dt><strong>Specified by:</strong></dt> <dd><code><a href="../../../sial/parser/Ast/IASTNodeToken.html#accept(lpg.runtime.IAstVisitor)">accept</a></code>&nbsp;in interface&nbsp;<code><a href="../../../sial/parser/Ast/IASTNodeToken.html" title="interface in sial.parser.Ast">IASTNodeToken</a></code></dd> <dt><strong>Overrides:</strong></dt> <dd><code><a href="../../../sial/parser/Ast/ASTNodeToken.html#accept(lpg.runtime.IAstVisitor)">accept</a></code>&nbsp;in class&nbsp;<code><a href="../../../sial/parser/Ast/ASTNodeToken.html" title="class in sial.parser.Ast">ASTNodeToken</a></code></dd> </dl> </li> </ul> <a name="enter(sial.parser.Ast.Visitor)"> </a> <ul class="blockList"> <li class="blockList"> <h4>enter</h4> <pre>public&nbsp;void&nbsp;enter(<a href="../../../sial/parser/Ast/Visitor.html" title="interface in sial.parser.Ast">Visitor</a>&nbsp;v)</pre> <dl> <dt><strong>Overrides:</strong></dt> <dd><code><a href="../../../sial/parser/Ast/ASTNodeToken.html#enter(sial.parser.Ast.Visitor)">enter</a></code>&nbsp;in class&nbsp;<code><a href="../../../sial/parser/Ast/ASTNodeToken.html" title="class in sial.parser.Ast">ASTNodeToken</a></code></dd> </dl> </li> </ul> <a name="getSLASH()"> </a> <ul class="blockListLast"> <li class="blockList"> <h4>getSLASH</h4> <pre>public&nbsp;lpg.runtime.IToken&nbsp;getSLASH()</pre> </li> </ul> </li> </ul> </li> </ul> </div> </div> <div class="bottomNav"><a name="navbar_bottom"> </a><a href="#skip-navbar_bottom" title="Skip navigation links"></a><a name="<API key>"> </a> <ul class="navList" title="Navigation"> <li><a href="../../../overview-summary.html">Overview</a></li> <li><a href="package-summary.html">Package</a></li> <li class="navBarCell1Rev">Class</li> <li><a href="class-use/BinOpDiv.html">Use</a></li> <li><a href="package-tree.html">Tree</a></li> <li><a href="../../../index-files/index-1.html">Index</a></li> <li><a href="../../../help-doc.html">Help</a></li> </ul> </div> <div class="subNav"> <ul class="navList"> <li><a href="../../../sial/parser/Ast/BinaryExpression.html" title="class in sial.parser.Ast"><span class="strong">Prev Class</span></a></li> <li><a href="../../../sial/parser/Ast/BinOpMinus.html" title="class in sial.parser.Ast"><span class="strong">Next Class</span></a></li> </ul> <ul class="navList"> <li><a href="../../../index.html?sial/parser/Ast/BinOpDiv.html" target="_top">Frames</a></li> <li><a href="BinOpDiv.html" target="_top">No Frames</a></li> </ul> <ul class="navList" id="<API key>"> <li><a href="../../../allclasses-noframe.html">All Classes</a></li> </ul> <div> <script type="text/javascript"><! allClassesLink = document.getElementById("<API key>"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } </script> </div> <div> <ul class="subNavList"> <li>Summary:&nbsp;</li> <li>Nested&nbsp;|&nbsp;</li> <li>Field&nbsp;|&nbsp;</li> <li><a href="#constructor_summary">Constr</a>&nbsp;|&nbsp;</li> <li><a href="#method_summary">Method</a></li> </ul> <ul class="subNavList"> <li>Detail:&nbsp;</li> <li>Field&nbsp;|&nbsp;</li> <li><a href="#constructor_detail">Constr</a>&nbsp;|&nbsp;</li> <li><a href="#method_detail">Method</a></li> </ul> </div> <a name="skip-navbar_bottom"> </a></div> </body> </html>
package multichain.object; /** * @author Ub - H. MARTEAU * @version 2.0.1 */ public class NetworkInfoNetwork { String name = null; Boolean limited = null; Boolean reachable = null; String proxy = null; /** * @return the name */ public String getName() { return name; } /** * @param name * the name to set */ public void setName(final String name) { this.name = name; } /** * @return the limited */ public Boolean getLimited() { return limited; } /** * @param limited * the limited to set */ public void setLimited(final Boolean limited) { this.limited = limited; } /** * @return the reachable */ public Boolean getReachable() { return reachable; } /** * @param reachable * the reachable to set */ public void setReachable(final Boolean reachable) { this.reachable = reachable; } /** * @return the proxy */ public String getProxy() { return proxy; } /** * @param proxy * the proxy to set */ public void setProxy(final String proxy) { this.proxy = proxy; } /* * (non-Javadoc) * * @see java.lang.Object#toString() */ @Override public String toString() { return String.format("NetworkInfoNetwork [name=%s, limited=%s, reachable=%s, proxy=%s]", name, limited, reachable, proxy); } }
package confmgr import ( "net/http" ) type Route struct { Name string Method string Pattern string HandlerFunc http.HandlerFunc } type Routes []Route func (c *ConfMgr) RouteDefinitions() Routes { return Routes{ Route{ "Index", "GET", "/", handlerDecorate(c.Index), }, Route{ "HandleAdminListKeys", "GET", "/admin/keys", handlerDecorate(c.HandleAdminListKeys), }, Route{ "<API key>", "GET", "/admin/keys/{filter}", handlerDecorate(c.<API key>), }, Route{ "<API key>", "GET", "/admin/util/hashfields/{keyName}", handlerDecorate(c.<API key>), }, Route{ "<API key>", "GET", "/admin/util/type/{keyName}", handlerDecorate(c.<API key>), }, Route{ "HandleAdminGetKey", "GET", "/admin/key/{keyName}", handlerDecorate(c.HandleAdminKeyGet), }, Route{ "HandleAdminKeyStore", "POST", "/admin/key/{keyName}", handlerDecorate(c.HandleAdminKeyStore), }, Route{ "<API key>", "DELETE", "/admin/key/{keyName}", handlerDecorate(c.<API key>), }, Route{ "<API key>", "GET", "/admin/key/{keyName}/{fieldName}", handlerDecorate(c.<API key>), }, Route{ "<API key>", "PATCH", "/admin/key/append/{keyName}", handlerDecorate(c.<API key>), }, Route{ "<API key>", "POST", "/admin/key/{keyName}/{fieldName}", handlerDecorate(c.<API key>), }, Route{ "<API key>", "GET", "/admin/key/{keyName}/index/{listIndex:[0-9]+}", handlerDecorate(c.<API key>), }, Route{ "HandleLookupHash", "GET", "/hash/{keyName}", handlerDecorate(c.HandleLookupHash), }, Route{ "HandleLookupString", "GET", "/string/{keyName}", handlerDecorate(c.HandleLookupString), }, Route{ "HandleLookupList", "GET", "/list/{keyName}", handlerDecorate(c.HandleLookupList), }, Route{ "<API key>", "GET", "/string/{keyName}/{fieldName}", handlerDecorate(c.<API key>), }, Route{ "<API key>", "GET", "/string/{keyName}/index/{listIndex}", handlerDecorate(c.<API key>), }, } }
project dev [Git workflow](refs/projects.md) Data Viz [R plotting](refs/vis.md) R lang [R links](refs/R.md) Web [jekyll](https://jekyllrb.com/community/) [yandex web](https://events.yandex.ru/lib/talks/537/) RNA-seq links [time course](refs/time-course.md) [single cells](refs/single-cells.md) Stats [statistics](refs/stat.md) NGS [variant calling](refs/variant.md) BIO [bio links](refs/bio.md)
from .MetadataDict import MetadataDict from .Job import JobInfo, Job, JobStatusError, JobError
using Newtonsoft.Json; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace <API key>.Attributes { public class CivilizationEthos : Attribute { private string _opposite; public string Opposite { get { return _opposite; } set { if (_opposite != value) { _opposite = value; <API key>("Opposite"); } } } private int _strength; public int Strength { get { return _strength; } set { if (_strength != value) { _strength = value; <API key>("Value"); } } } } }
//Our includes #include "cwGLViewer.h" #include "cwCamera.h" #include "cwCamera.h" #include "cwLine3D.h" #include "cwPlane.h" #include "cwRegularTile.h" #include "cwEdgeTile.h" #include "cwShaderDebugger.h" #include "cwGLShader.h" #include "cwGLTerrain.h" #include "cwGLLinePlot.h" #include "cwCavingRegion.h" #include "cwCave.h" #include "cwStation.h" #include "cw3dRegionViewer.h" #include "cwGLScraps.h" #include "<API key>.h" #include "cwGLGridPlane.h" #include "<API key>.h" #include "cwProjection.h" #include "cwScene.h" #include "<API key>.h" #include "<API key>.h" //Qt includes #include <QPainter> #include <QString> #include <QVector3D> #include <QRect> #include <QMouseEvent> #include <QWheelEvent> #include <QDebug> #include <QtConcurrentMap> #include <QFontMetrics> #include <QRay3D> #include <QGLFunctions> //const float cw3dRegionViewer::DefaultPitch = 90.0f; //const float cw3dRegionViewer::DefaultAzimuth = 0.0f; cw3dRegionViewer::cw3dRegionViewer(QQuickItem *parent) : cwGLViewer(parent) { //TODO: Not all Mac and Windows support multi-sampling //#ifndef Q_OS_WIN // setAntialiasing(true); //#endif OrthognalProjection = new <API key>(this); OrthognalProjection->setViewer(this); OrthognalProjection->setEnabled(true); <API key> = new <API key>(this); <API key>->setViewer(this); <API key>->setEnabled(false); } /** \brief Called when the viewer's size changes This updates the projection matrix for the view */ void cw3dRegionViewer::resizeGL() { emit resized(); } ** // Initializes the last click for the panning state //void cw3dRegionViewer::startPanning(QPoint position) { // QPoint mappedPosition = Camera->mapToGLViewport(position); // <API key> = unProject(mappedPosition); / <API key> = QVector3D(mappedPosition); // //Get the ray from the front of the screen to the back of the screen // //Using the center of the screen // QMatrix4x4 eyeMatrix = camera()-><API key>().inverted(); // QVector3D front = eyeMatrix.map(QVector3D(0.0, 0.0, -1.0)); // QVector3D back = eyeMatrix.map(QVector3D(0.0, 0.0, 1.0)); // QVector3D direction = QVector3D(front - back).normalized(); // //Create the plane // PanPlane = QPlane3D(<API key>, direction); // TranslatePosition = position; // <API key>(); ** // Pans the view allow the a plane //void cw3dRegionViewer::pan(QPoint position) { // TranslatePosition = position; // if(!TranslateTimer->isActive()) { // TranslateTimer->start(); ** // Called when the rotation is about to begin //void cw3dRegionViewer::startRotating(QPoint position) { // position = Camera->mapToGLViewport(position); // <API key> = unProject(position); // LastMousePosition = position; ** // Rotates the view //void cw3dRegionViewer::rotate(QPoint position) { // <API key> = position; // if(!<API key>->isActive()) { // <API key>->start(); ** // Zooms the view //void cw3dRegionViewer::zoom(QPoint position, int delta) { // ZoomPosition = position; // if(!<API key>->isActive()) { // <API key>->start(); // ZoomDelta = delta; // } else { // ZoomDelta += delta; ** // \brief Resets the view //void cw3dRegionViewer::resetView() { // Pitch = DefaultPitch; // Azimuth = DefaultAzimuth; // setCurrentRotation(defaultRotation()); // QMatrix4x4 viewMatrix; // viewMatrix.translate(QVector3D(0.0, 0.0, -50)); // Camera->setViewMatrix(viewMatrix); // update(); ** // * @brief cw3dRegionViewer::rotateLastPosition // * This is called by the timer, after the timer has consumed mouse events. This prevents // * rendering thread to be starved //void cw3dRegionViewer::rotateLastPosition() // QPoint position = <API key>; // position = Camera->mapToGLViewport(position); // QPoint <API key> = position; // QPointF delta = LastMousePosition - <API key>; // LastMousePosition = <API key>; // delta /= 2.0; // //Calculate the new pitch // Pitch = clampPitch(Pitch + delta.y()); // emit pitchChanged(); // //Calculate the new azimuth // Azimuth = clampAzimuth(Azimuth - delta.x()); // emit azimuthChanged(); // <API key>(); ** // * @brief cw3dRegionViewer::zoomLastPosition // * This is called by the timer, after the timer has consumed mouse events. This prevents // * rendering thread to be starved //void cw3dRegionViewer::zoomLastPosition() // switch(Camera->projection().type()) { // case cwProjection::Perspective: // case cwProjection::PerspectiveFrustum: // zoomPerspective(); // break; // case cwProjection::Ortho: // zoomOrtho(); // break; // default: // qDebug() << "Can't zoom because of an unknown projection"; // return; ** // * @brief cw3dRegionViewer::<API key> // * This is called by the timer, after the timer has consumed mouse events. This prevents // * rendering thread to be starved //void cw3dRegionViewer::<API key>() // QPoint position = TranslatePosition; // QPoint mappedPos = Camera->mapToGLViewport(position); // //Get the ray from the front of the screen to the back of the screen // QVector3D front = Camera->unProject(mappedPos, 0.0); // QVector3D back = Camera->unProject(mappedPos, 1.0); // QVector3D direction = front - back; // direction.normalize(); // //Create the ray that'll intersect // QRay3D ray(front, direction); // //Find the intsection on the plane // double t = PanPlane.intersection(ray); //xyPlane.intersectAsRay(ray, &hasIntersection); // //Ray and plane are parallel, can't do anything with this // if(qIsNaN(t)) { return; } // QVector3D intersection = ray.point(t); // QVector3D translateAmount = intersection - <API key>; // QMatrix4x4 viewMatrix = Camera->viewMatrix(); // viewMatrix.translate(translateAmount); // Camera->setViewMatrix(viewMatrix); // //Update the gl window // update(); //** / \brief Sets the caving region for the renderer / */ /void cw3dRegionViewer::setCavingRegion(cwCavingRegion* region) { / if(Region != region) { / Region = region; / emit cavingRegionChanged(); / } /} ** // * @brief cw3dRegionViewer::<API key> // * This sets up the interaction timers. This prevents the operating system from firing more // * mouse events than it needs to. // * On linux, mouse events are fired very, very quickly, causing the rendering thread to strave // * The timers prevent the starvation //void cw3dRegionViewer::<API key>() // int interactionInterval = 15; //1/60; //60hz // <API key> = new QTimer(this); // <API key> = new QTimer(this); // TranslateTimer = new QTimer(this); // <API key>->setInterval(interactionInterval); // <API key>->setSingleShot(true); // <API key>->setInterval(interactionInterval); // <API key>->setSingleShot(true); // TranslateTimer->setInterval(interactionInterval); // TranslateTimer->setSingleShot(true); // connect(<API key>, &QTimer::timeout, this, &cw3dRegionViewer::rotateLastPosition); // connect(<API key>, &QTimer::timeout, this, &cw3dRegionViewer::zoomLastPosition); // connect(TranslateTimer, &QTimer::timeout, this, &cw3dRegionViewer::<API key>); //void cw3dRegionViewer::setCurrentRotation(QQuaternion rotation) // CurrentRotation = rotation; // emit rotationChanged(); //QQuaternion cw3dRegionViewer::defaultRotation() const // QQuaternion pitchQuat = QQuaternion::fromAxisAndAngle(1.0, 0.0, 0.0, DefaultPitch); // QQuaternion azimuthQuat = QQuaternion::fromAxisAndAngle(0.0, 0.0, 1.0, DefaultAzimuth); // return pitchQuat * azimuthQuat; //void cw3dRegionViewer::<API key>() // QQuaternion pitchQuat = QQuaternion::fromAxisAndAngle(1.0, 0.0, 0.0, Pitch); // QQuaternion azimuthQuat = QQuaternion::fromAxisAndAngle(0.0, 0.0, 1.0, Azimuth); // QQuaternion newQuat = pitchQuat * azimuthQuat; // QQuaternion rotationDifferance = CurrentRotation.conjugate() * newQuat; // setCurrentRotation(newQuat); // QMatrix4x4 viewMatrix = Camera->viewMatrix(); // viewMatrix.translate(<API key>); // viewMatrix.rotate(rotationDifferance); // viewMatrix.translate(-<API key>); // Camera->setViewMatrix(viewMatrix); // update(); ** // * @brief cw3dRegionViewer::clampAzimuth // * @param azimuth // * @return This clamps the azimuth between 0.0 and 360.0 //double cw3dRegionViewer::clampAzimuth(double azimuth) const // azimuth = fmod(azimuth, 360.0); // if(azimuth < 0) { // azimuth += 360.0; // return azimuth; ** // * @brief cw3dRegionViewer::clampPitch // * @param pitch // * @return This clamps the pitch from -90 to 90 //double cw3dRegionViewer::clampPitch(double pitch) const // return qMin(90.0, qMax(-90.0, pitch)); ** // * @brief cw3dRegionViewer::zoomPerspective // * Zoom with a perspective transfromation //void cw3dRegionViewer::zoomPerspective() // int delta = ZoomDelta; // QPoint position = ZoomPosition; // //Make the event position into gl viewport // QPoint mappedPos = Camera->mapToGLViewport(position); // //Get the ray from the front of the screen to the back of the screen // QVector3D front = Camera->unProject(mappedPos, 0.0); // //Find the intsection on the plane // QVector3D intersection = unProject(mappedPos); // //Smallray // QVector3D ray = intersection - front; // float rayLength = ray.length(); // ray.normalize(); // float t = .0005 * delta; // t = qMax(-1.0f, qMin(1.0f, t)); // t = rayLength * t; // QVector3D newPositionDelta = ray * t; // QMatrix4x4 viewMatrix = Camera->viewMatrix(); // viewMatrix.translate(newPositionDelta); // Camera->setViewMatrix(viewMatrix); ** // * @brief cw3dRegionViewer::zoomOrtho // * Zoom with an orthoganal projection //void cw3dRegionViewer::zoomOrtho() // int delta = ZoomDelta; // QPoint position = ZoomPosition; // //Make the event position into gl viewport // QPoint mappedPos = Camera->mapToGLViewport(position); // double direction = delta > 0 ? 1.075 : 0.925; // double zoomLevel = camera()->zoomScale() * direction; // QVector3D before = Camera->unProject(mappedPos, 1.0); // Camera->setZoomScale(zoomLevel); // QVector3D after = Camera->unProject(mappedPos, 1.0); // QVector3D changeInPosition = after - before; // QMatrix4x4 <API key> = Camera->viewMatrix(); // <API key>.translate(changeInPosition); // Camera->setViewMatrix(<API key>); //** / * @brief cw3dRegionViewer::orthoProjection / * @return This get the current ortho projection at the current zoom level / */ /cwProjection cw3dRegionViewer::<API key>() const /{ / cwProjection projection; / projection.setOrtho(-width() / 2.0 * ZoomLevel, width() / 2.0 * ZoomLevel, -height() / 2.0 * ZoomLevel, height() / 2.0 * ZoomLevel, -10000, 10000); / return projection; /} //** / * @brief cw3dRegionViewer::<API key> / * @return The current prespective projection for the viewer / */ /cwProjection cw3dRegionViewer::<API key>() const /{ / cwProjection projection; / projection.setPerspective(55, width() / (float)height(), 1, 10000); / return projection; /} ** //Gets rotation current global rotation //*/ //QQuaternion cw3dRegionViewer::rotation() const { // return defaultRotation().conjugate() * CurrentRotation; ** //*/ //*/
<html> <pre> Critical Path Scheduling (Algorithm 40) CACM September, 1961 Alexander, N. P. CA610905 JB March 16, 1978 9:44 PM 289 5 289 289 5 289 289 5 289 </pre> </html>
local CHANCES = 50 local WATERINGCAN_ID = 7734 local WATERED = {7673, 7670, 7680, 7682, 7684, 7686, 7688, 7690, 7992, 7994, 9982, 9990, 9986, 9988} local PLANTSPECIES = {7680, 7682, 7684, 7686, 9982, 9986} local PLANTADVANCES = { [7679] = {7670, 7673}, [7681] = {7688, 7680}, [7683] = {7690, 7682}, [7685] = {7692, 7684}, [7687] = {7694, 7686}, [9983] = {9990, 9982}, [9987] = {9988, 9986}} local LASTSTADIUM = {7689, 7691, 7693, 7695, 9991, 9989} local WHITEREDPLANTS = { [7674] = 7688, [7675] = 7690, [7676] = 7692, [7677] = 7694, [9984] = 9990, [9985] = 9988} function onUse(cid, item, fromPosition, itemEx, toPosition) local RANDOM = math.random(100) if WHITEREDPLANTS[itemEx.itemid] ~= nil then doCreatureSay(cid,"You finally remembered to water your plant and it recovered.",TALKTYPE_ORANGE_1) doTransformItem(itemEx.uid,WHITEREDPLANTS[itemEx.itemid]) elseif itemEx.itemid == 7655 then doCreatureSay(cid,"You should plant some seeds first.",TALKTYPE_ORANGE_1) elseif itemEx.itemid == 7665 then doCreatureSay(cid,"You watered your plant.",TALKTYPE_ORANGE_1) doTransformItem(itemEx.uid,itemEx.itemid+8) elseif isInArray(WATERED,itemEx.itemid) == TRUE then doCreatureSay(cid,"Your plant doesn't need water.",TALKTYPE_ORANGE_1) elseif PLANTADVANCES[itemEx.itemid] ~= nil then if RANDOM <= CHANCES then doTransformItem(itemEx.uid,PLANTADVANCES[itemEx.itemid][1]) doCreatureSay(cid,"Your plant has grown to the next stage!",TALKTYPE_ORANGE_1) else doTransformItem(itemEx.uid,PLANTADVANCES[itemEx.itemid][2]) doCreatureSay(cid,"You watered your plant.",TALKTYPE_ORANGE_1) end elseif itemEx.itemid == 7678 then if RANDOM <= CHANCES then doCreatureSay(cid,"Your plant has grown to the next stage!",TALKTYPE_ORANGE_1) doTransformItem(itemEx.uid,PLANTSPECIES[math.random(4)]) else doCreatureSay(cid,"You watered your plant.",TALKTYPE_ORANGE_1) doTransformItem(itemEx.uid,itemEx.itemid-8) end elseif isInArray(LASTSTADIUM, itemEx.itemid) == TRUE then doCreatureSay(cid,"You watered your plant.",TALKTYPE_ORANGE_1) doTransformItem(itemEx.uid,itemEx.itemid-1) end doDecayItem(itemEx.uid) return TRUE end
#ifndef GAME_REVIEW_PAGE_H #define GAME_REVIEW_PAGE_H #include "basepage.h" #include "videoreviewer.h" namespace gc { /** * Page class in the wizard application used to review the gameplay and collect review data. */ class GameReviewPage : public BasePage { Q_OBJECT public: /** * Class constructor. * @param pParent Instance of a QWidget with the parent of this page. * The default is NULL. */ GameReviewPage(QWidget *pParent = NULL); protected: /** * Initialization method called everytime the page is displayed. */ void initializePage(); /** * Validates and terminates the page, stopping and unloading the video when * the subject clicks on "Continue". * @return True if the process can continue, false otherwise. */ bool validatePage(); /** * Overload the method that indicates to the main window that the review * is completed (so the continue button can be displayed). */ bool isComplete() const; protected slots: /** * Captures the indication from the VideoReviwer that the review has been * completed by the subject. */ void onReviewCompleted(); private: /** Instance of the class used to allow the user reviewing the gameplay. */ VideoReviewer *m_pReviewer; /** Indication that the review has been completed by the subject. */ bool m_bCompleted; }; } #endif // GAME_REVIEW_PAGE_H
#ifndef <API key> # define <API key> /** * @brief Specifies the type of function which is called when a data element is * destroyed. It is passed the pointer to the data element and should free any * memory and resources allocated for it. * @param data[in] : the data element */ typedef int (*t_destroy_func)(void *data); /** * @brief A function of this signature is used to copy the node data when doing * a deep-copy of a data. * @param data[in] : a pointer to the data which should be copied * @param user_data[in] : additional data * @return A pointer to the copy */ typedef void *(*t_copy_func)(void *data); /** * @brief Specifies the type of functions passed threw *_foreach() function * @param data[in] : the element's data * @param user_data[in] : additional data */ typedef int (*t_foreach_func)(void *data, void *user_data); /** * @brief Compare two user value * @param src[in] : source * @param dst[in] : destination * @return < 0 if src is less than dst, = 0 if equal, > 0 if greater */ typedef int (*t_compare_func)(void *src, void *dst); #endif /* !<API key> */
#pragma once @file AC_PI_2D.h @brief Generic PID algorithm, with EEPROM-backed storage of constants. #include <AP_Common/AP_Common.h> #include <AP_Param/AP_Param.h> #include <stdlib.h> #include <cmath> #define <API key> 20.0f // default input filter frequency #define <API key> 0.01f // minimum input filter frequency @class AC_PI_2D @brief Copter PID control class class AC_PI_2D { public: // Constructor for PID AC_PI_2D(float initial_p, float initial_i, float initial_imax, float initial_filt_hz, float dt); // set time step in seconds void set_dt(float dt); // set_input - set input to PID controller // input is filtered before the PID controllers are run // this should be called before any other calls to get_p, get_i or get_d void set_input(const Vector2f &input); void set_input(const Vector3f &input) { set_input(Vector2f(input.x, input.y)); } // get_pi - get results from pid controller Vector2f get_pi(); Vector2f get_p() const; Vector2f get_i(); Vector2f get_i_shrink(); // get_i but do not allow integrator to grow (it may shrink) // reset_I - reset the integrator void reset_I(); // reset_filter - input filter will be reset to the next value provided to set_input() void reset_filter(); // load gain from eeprom void load_gains(); // save gain to eeprom void save_gains(); operator function call for easy initialisation void operator() (float p, float i, float imaxval, float input_filt_hz, float dt); // get accessors AP_Float &kP() { return _kp; } AP_Float &kI() { return _ki; } float imax() const { return _imax.get(); } float filt_hz() const { return _filt_hz.get(); } float get_filt_alpha() const { return _filt_alpha; } // set accessors void kP(float v) { _kp.set(v); } void kI(float v) { _ki.set(v); } void imax(float v) { _imax.set(fabsf(v)); } void filt_hz(float hz); Vector2f get_integrator() const { return _integrator; } void set_integrator(const Vector2f &i) { _integrator = i; } void set_integrator(const Vector3f &i) { _integrator.x = i.x; _integrator.y = i.y; } // parameter var table static const struct AP_Param::GroupInfo var_info[]; private: // calc_filt_alpha - recalculate the input filter alpha void calc_filt_alpha(); // parameters AP_Float _kp; AP_Float _ki; AP_Float _imax; AP_Float _filt_hz; // PID Input filter frequency in Hz // flags struct ac_pid_flags { bool _reset_filter : 1; // true when input filter should be reset during next call to set_input } _flags; // internal variables float _dt; // timestep in seconds Vector2f _integrator; // integrator value Vector2f _input; // last input for derivative float _filt_alpha; // input filter alpha };
<!DOCTYPE html> <html> <head> <title>Canvas experiment 1</title> <script type="text/javascript"> function onLoad() { var context1 = document.getElementById("canvas1").getContext('2d'); var context2 = document.getElementById("canvas2").getContext('2d'); context1.fillStyle= "rgba(255,0,0,.5)"; context1.fillRect(20, 20, 40, 40); context2.fillStyle = "rgba(0,255,0,.5)"; context2.fillRect(40, 40, 40, 40); } </script> <style> #canvasContainer { border: 1px solid black; position: relative; width: 400px; height: 300px; } #canvas1 { position: absolute; top: 0; left: 0; z-index: 1; } #canvas2 { position: absolute; top: 0; left: 0; z-index: 2; } </style> </head> <body onload="onLoad()"> <h1>what happens when two canvases live on top of each other?</h1> <div id="canvasContainer"> <canvas id="canvas1" width="400" height="300"></canvas> <canvas id="canvas2" width="400" height="300"></canvas> </div> <h2>they do the right thing, nice :)</h2> </body> </html>
'use strict'; var esprima = require('esprima'); var os = require('os'); // Automatically calculates and returns End of Line, // based on the input text. function getEOL(text) { var idx = 0, unix = 0, windows = 0; while (idx < text.length) { idx = text.indexOf('\n', idx); if (idx == -1) { break; } if (idx > 0 && text[idx - 1] === '\r') { windows++; } else { unix++; } idx++; } if (unix === windows) { return os.EOL; } return unix > windows ? '\n' : '\r\n'; } // Tokenizes JSON or JavaScript via Esprima, enumerates and returns // all regular expressions as an array of absolute location indexes // within the source: [{start, end}, {start, end},...] function parseRegEx(code) { var result = []; // NOTE: Even though we do not need the location details, // using option `loc` makes `tokenize` perform 40% faster. esprima.tokenize(code, {loc: true, range: true}, function (node) { if (node.type === 'RegularExpression') { result.push({ start: node.range[0] + 1, // next after the opening `/` end: node.range[1] - 1 // previous to the closing `/` }); } }); return result; } // Executes a linear search through an array of absolute regEx indexes, // to find whether the passed index is inside one of the regEx entries. function indexInRegEx(idx, regExData) { // regExData - the output provided by parseRegEx; var mid, low = 0, high = regExData.length - 1; while (low <= high) { mid = Math.round((low + high) / 2); var a = regExData[mid]; if (idx >= a.start) { if (idx <= a.end) { return true; } low = mid + 1; } else { high = mid - 1; } } return false; } // Checks the text for being HTML, by verifying // whether `<` is the first non-empty symbol. function isHtml(text) { var s, idx = 0; do { s = text[idx]; if (s !== ' ' && s !== '\t' && s !== '\r' && s !== '\n') { return s === '<'; } } while (++idx < text.length); } // Returns space symbol multiplied n times. // istanbul ignore next // we are not generating test coverage for this // function, since it is <API key>. function getSpaces(n) { if (typeof String.prototype.repeat === 'function') { return ' '.repeat(n); } else { return new Array(n + 1).join(' '); } } module.exports = { getEOL: getEOL, getSpaces: getSpaces, parseRegEx: parseRegEx, indexInRegEx: indexInRegEx, isHtml: isHtml };
<!DOCTYPE HTML PUBLIC "- <!-- NewPage --> <html lang="ja"> <head> <!-- Generated by javadoc (1.8.0_40) on Sun Apr 10 20:00:10 JST 2016 --> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title> org.bukkit.command.defaults.ClearCommand (Bukkit 1.9.2-R0.1-SNAPSHOT API)</title> <meta name="date" content="2016-04-10"> <link rel="stylesheet" type="text/css" href="../../../../../stylesheet.css" title="Style"> <script type="text/javascript" src="../../../../../script.js"></script> </head> <body> <script type="text/javascript"><! try { if (location.href.indexOf('is-external=true') == -1) { parent.document.title="\u30AF\u30E9\u30B9 org.bukkit.command.defaults.ClearCommand\u306E\u4F7F\u7528 (Bukkit 1.9.2-R0.1-SNAPSHOT API)"; } } catch(err) { } </script> <noscript> <div>JavaScript</div> </noscript> <div class="topNav"><a name="navbar.top"> </a> <div class="skipNav"><a href="#skip.navbar.top" title=""></a></div> <a name="navbar.top.firstrow"> </a> <ul class="navList" title=""> <li><a href="../../../../../overview-summary.html"></a></li> <li><a href="../package-summary.html"></a></li> <li><a href="../../../../../org/bukkit/command/defaults/ClearCommand.html" title="org.bukkit.command.defaults"></a></li> <li class="navBarCell1Rev"></li> <li><a href="../package-tree.html"></a></li> <li><a href="../../../../../deprecated-list.html"></a></li> <li><a href="../../../../../index-all.html"></a></li> <li><a href="../../../../../help-doc.html"></a></li> </ul> </div> <div class="subNav"> <ul class="navList"> <li></li> <li></li> </ul> <ul class="navList"> <li><a href="../../../../../index.html?org/bukkit/command/defaults/class-use/ClearCommand.html" target="_top"></a></li> <li><a href="ClearCommand.html" target="_top"></a></li> </ul> <ul class="navList" id="<API key>"> <li><a href="../../../../../allclasses-noframe.html"></a></li> </ul> <div> <script type="text/javascript"><! allClassesLink = document.getElementById("<API key>"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } </script> </div> <a name="skip.navbar.top"> </a></div> <div class="header"> <h2 title=" org.bukkit.command.defaults.ClearCommand" class="title"><br>org.bukkit.command.defaults.ClearCommand</h2> </div> <div class="classUseContainer">org.bukkit.command.defaults.ClearCommand</div> <div class="bottomNav"><a name="navbar.bottom"> </a> <div class="skipNav"><a href="#skip.navbar.bottom" title=""></a></div> <a name="navbar.bottom.firstrow"> </a> <ul class="navList" title=""> <li><a href="../../../../../overview-summary.html"></a></li> <li><a href="../package-summary.html"></a></li> <li><a href="../../../../../org/bukkit/command/defaults/ClearCommand.html" title="org.bukkit.command.defaults"></a></li> <li class="navBarCell1Rev"></li> <li><a href="../package-tree.html"></a></li> <li><a href="../../../../../deprecated-list.html"></a></li> <li><a href="../../../../../index-all.html"></a></li> <li><a href="../../../../../help-doc.html"></a></li> </ul> </div> <div class="subNav"> <ul class="navList"> <li></li> <li></li> </ul> <ul class="navList"> <li><a href="../../../../../index.html?org/bukkit/command/defaults/class-use/ClearCommand.html" target="_top"></a></li> <li><a href="ClearCommand.html" target="_top"></a></li> </ul> <ul class="navList" id="<API key>"> <li><a href="../../../../../allclasses-noframe.html"></a></li> </ul> <div> <script type="text/javascript"><! allClassesLink = document.getElementById("<API key>"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } </script> </div> <a name="skip.navbar.bottom"> </a></div> <p class="legalCopy"><small>Copyright & </body> </html>
/** * Module, pure virtual class, ancestor of all modules. */ #ifndef <API key> #define <API key> #include <config.h> #include <string> #include <vector> #include <queue> #include "Object.h" #include "Resource.h" class Module : public Object { public: enum Type { INVALID = 0, INPUT = 1, OUTPUT = 2, SIMPLE = 3, MULTI = 4, }; Module(ObjectRegistry *objects, const char *id, int threadIndex): Object(objects, id, threadIndex), threadIndex(threadIndex) {}; virtual ~Module() {}; virtual bool Init(std::vector<std::pair<std::string, std::string> > *args); virtual Module::Type GetType(); int GetThreadIndex(); void Start(); void Stop(); void Pause(); void Resume(); Resource *ProcessInput(bool sleep); Resource *ProcessOutput(Resource *resource); Resource *ProcessSimple(Resource *resource); // returns true if busy (working on resources) bool ProcessMulti(std::queue<Resource*> *inputResources, std::queue<Resource*> *outputResources, int *expectingResources, int *processingResources); protected: int threadIndex; virtual void StartSync(); virtual void StopSync(); virtual void PauseSync(); virtual void ResumeSync(); virtual Resource *ProcessInputSync(bool sleep); // Output module: consume resource, return resource to be deleted virtual Resource *ProcessOutputSync(Resource *resource); // Simple module: one resource a time virtual Resource *ProcessSimpleSync(Resource *resource); // Multi modules use input/output interface: inputResources should be // consumed, outputResources should be produced Returns number of // currently processing resources (not counting inputResources and // outputResources). expectingResources is number of resources module is // expecting on the input next time. ProcessMulti is allowed to produce // new resources virtual bool ProcessMultiSync(std::queue<Resource*> *inputResources, std::queue<Resource*> *outputResources, int *expectingResources, int *processingResources); }; inline int Module::GetThreadIndex() { return threadIndex; } inline void Module::Start() { ObjectLockWrite(); StartSync(); ObjectUnlock(); } inline void Module::Stop() { ObjectLockWrite(); StopSync(); ObjectUnlock(); } inline void Module::Pause() { ObjectLockWrite(); PauseSync(); ObjectUnlock(); } inline void Module::Resume() { ObjectLockWrite(); ResumeSync(); ObjectUnlock(); } inline Resource *Module::ProcessInput(bool sleep) { ObjectLockWrite(); Resource *result = ProcessInputSync(sleep); ObjectUnlock(); return result; } inline Resource *Module::ProcessOutput(Resource *resource) { ObjectLockWrite(); resource = ProcessOutputSync(resource); ObjectUnlock(); return resource; } inline Resource *Module::ProcessSimple(Resource *resource) { ObjectLockWrite(); resource = ProcessSimpleSync(resource); ObjectUnlock(); return resource; } inline bool Module::ProcessMulti(std::queue<Resource*> *inputResources, std::queue<Resource*> *outputResources, int *expectingResources, int *processingResources) { ObjectLockWrite(); bool result = ProcessMultiSync(inputResources, outputResources, expectingResources, processingResources); ObjectUnlock(); return result; } #endif
<?php namespace CaT\Ilse\Aux; /** * Logs which task is currently running. */ interface TaskLogger { /** * Task needs to succeed in order for the whole process * to go on. * * @param string $title * @param callable $task * @return mixed what callable returns */ public function always($title, callable $task); /** * Task may fail, process continues. * * @param string $title * @param callable $task * @return mixed what callable returns */ public function eventually($title, callable $task); /** * Task needs to succeed in order for the whole process * to go on. * * Start a process that expected nested processes * * @param string $title * @param callable $task * @return mixed what callable returns */ public function progressing($title, callable $task); }
<?php namespace App\Modules\Tasks; use Illuminate\Database\Eloquent\Model; use App\Modules\Tasks\Models\Task; use App\User; use App\Module; class TasksModule extends Module { public function __constuct(){ $this->name = "Tasks"; } public function getData(){ return Task::orderBy('created_at', 'asc')->get(); } public function getView(bool $editable){ if($editable){ return "Tasks::tasks"; } return "Tasks::tasksView"; } public function getDataForUser(User $user){ return $user->tasks()->orderBy('created_at', 'asc')->get(); } }
#include <ogdf/basic/basic.h> #ifdef __APPLE__ #include <stdlib.h> #include <malloc/malloc.h> #include <sys/types.h> #include <sys/sysctl.h> #include <sys/utsname.h> #include <mach/vm_statistics.h> #include <mach/mach.h> #include <mach/machine.h> #elif defined(OGDF_SYSTEM_UNIX) #include <malloc.h> #endif #if defined(OGDF_SYSTEM_WINDOWS) || defined(__CYGWIN__) #include <Psapi.h> #endif #if defined(__MINGW32__) #include <malloc.h> #endif #if defined(_MSC_VER) || defined(__MINGW64__) #include <intrin.h> #elif defined(OGDF_SYSTEM_UNIX) || (defined(__MINGW32__) && !defined(__MINGW64__)) #include <unistd.h> #include <fcntl.h> #include <sys/time.h> #include <stdint.h> static void __cpuid(int CPUInfo[4], int infoType) { uint32_t a = CPUInfo[0]; uint32_t b = CPUInfo[1]; uint32_t c = CPUInfo[2]; uint32_t d = CPUInfo[3]; #if defined(__i386__) || defined(__x86_64__) && !defined(__APPLE__) __asm__ __volatile__ ("xchgl %%ebx,%0\n\t" "cpuid \n\t" "xchgl %%ebx,%0\n\t" : "+r" (b), "=a" (a), "=c" (c), "=d" (d) : "1" (infoType), "2" (c)); #else // not supported on other systems! a = b = c = d = 0; #endif CPUInfo[0] = a; CPUInfo[1] = b; CPUInfo[2] = c; CPUInfo[3] = d; } #endif namespace ogdf { unsigned int System::s_cpuFeatures; int System::s_cacheSize; int System::s_cacheLine; int System::s_pageSize; int System::<API key>; #if defined(OGDF_SYSTEM_WINDOWS) || defined(__CYGWIN__) LARGE_INTEGER System::<API key>; #endif void System::init() { s_cpuFeatures = 0; s_cacheSize = 0; s_cacheLine = 0; // currently not working for shared libs on Linux #if !defined(OGDF_DLL) || !defined(OGDF_SYSTEM_UNIX) int CPUInfo[4] = {-1}; __cpuid(CPUInfo, 0); unsigned int nIds = CPUInfo[0]; if(nIds >= 1) { __cpuid(CPUInfo, 1); int featureInfoECX = CPUInfo[2]; int featureInfoEDX = CPUInfo[3]; if(featureInfoEDX & (1 << 23)) s_cpuFeatures |= cpufmMMX; if(featureInfoEDX & (1 << 25)) s_cpuFeatures |= cpufmSSE; if(featureInfoEDX & (1 << 26)) s_cpuFeatures |= cpufmSSE2; if(featureInfoECX & (1 << 0)) s_cpuFeatures |= cpufmSSE3; if(featureInfoECX & (1 << 9)) s_cpuFeatures |= cpufmSSSE3; if(featureInfoECX & (1 << 19)) s_cpuFeatures |= cpufmSSE4_1; if(featureInfoECX & (1 << 20)) s_cpuFeatures |= cpufmSSE4_2; if(featureInfoECX & (1 << 5)) s_cpuFeatures |= cpufmVMX; if(featureInfoECX & (1 << 6)) s_cpuFeatures |= cpufmSMX; if(featureInfoECX & (1 << 7)) s_cpuFeatures |= cpufmEST; if(featureInfoECX & (1 << 3)) s_cpuFeatures |= cpufmMONITOR; } __cpuid(CPUInfo, 0x80000000); unsigned int nExIds = CPUInfo[0]; if(nExIds >= 0x80000006) { __cpuid(CPUInfo, 0x80000006); s_cacheLine = CPUInfo[2] & 0xff; s_cacheSize = (CPUInfo[2] >> 16) & 0xffff; } #if defined(OGDF_SYSTEM_WINDOWS) || defined(__CYGWIN__) <API key>(&<API key>); SYSTEM_INFO siSysInfo; GetSystemInfo(&siSysInfo); s_pageSize = siSysInfo.dwPageSize; <API key> = siSysInfo.<API key>; #elif defined(OGDF_SYSTEM_UNIX) && defined(__APPLE__) unsigned long long value; size_t size = sizeof( value ); if (sysctlbyname("hw.pagesize", &value, &size, NULL, 0) !=-1) s_pageSize = (int)value; else s_pageSize = 0; if (sysctlbyname("hw.ncpu", &value, &size, NULL, 0) !=-1) <API key> = (int)value; else <API key> = 1; #endif #elif defined(OGDF_SYSTEM_UNIX) s_pageSize = sysconf(_SC_PAGESIZE); <API key> = (int)sysconf(<API key>); #else s_pageSize = 0; // just a placeholder!!! <API key> = 1; // just a placeholder!!! #endif } #if defined(OGDF_SYSTEM_WINDOWS) || defined(__CYGWIN__) void System::getHPCounter(LARGE_INTEGER &counter) { <API key>(&counter); } double System::elapsedSeconds( const LARGE_INTEGER &startCounter, const LARGE_INTEGER &endCounter) { return double(endCounter.QuadPart - startCounter.QuadPart) / <API key>.QuadPart; } __int64 System::usedRealTime(__int64 &t) { __int64 tStart = t; t = GetTickCount(); return t - tStart; } long long System::physicalMemory() { #if !defined(__CYGWIN__) || (_WIN32_WINNT >= 0x0500) MEMORYSTATUSEX statex; statex.dwLength = sizeof (statex); <API key> (&statex); return statex.ullTotalPhys; #else MEMORYSTATUS stat; stat.dwLength = sizeof (stat); GlobalMemoryStatus (&stat); return stat.dwTotalPhys; #endif } long long System::<API key>() { #if !defined(__CYGWIN__) || (_WIN32_WINNT >= 0x0500) MEMORYSTATUSEX statex; statex.dwLength = sizeof (statex); <API key> (&statex); return statex.ullAvailPhys; #else MEMORYSTATUS stat; stat.dwLength = sizeof (stat); GlobalMemoryStatus (&stat); return stat.dwAvailPhys; #endif } size_t System::memoryUsedByProcess() { <API key> pmc; <API key>(GetCurrentProcess(), &pmc, sizeof(pmc)); return pmc.WorkingSetSize; } size_t System::<API key>() { <API key> pmc; <API key>(GetCurrentProcess(), &pmc, sizeof(pmc)); return pmc.PeakWorkingSetSize; } #elif __APPLE__ long long System::physicalMemory() { unsigned long long value; size_t size = sizeof( value ); if (sysctlbyname("hw.memsize", &value, &size, NULL, 0) !=-1) return value; else return 0; } long long System::<API key>() { unsigned long long pageSize; long long result; size_t size = sizeof( pageSize ); sysctlbyname("hw.pagesize", &pageSize, &size, NULL, 0); <API key> vm_stat; int count = ((<API key>) (sizeof(<API key>)/sizeof(integer_t))); host_statistics(mach_host_self(), HOST_VM_INFO, (integer_t*)&vm_stat, (<API key>*)&count); result = (unsigned long long)(vm_stat.free_count + vm_stat.inactive_count) * pageSize; return result; } size_t System::memoryUsedByProcess() { /*int pid = getpid(); static char filename[32]; sprintf(filename, 32, "/proc/%d/statm", pid); int fd = open(filename, O_RDONLY, 0); if(fd==-1) OGDF_THROW(Exception); static char sbuf[256]; sbuf[read(fd, sbuf, sizeof(sbuf) - 1)] = 0; close(fd); long size, resident, share, trs, lrs, drs, dt; sscanf(sbuf, "%ld %ld %ld %ld %ld %ld %ld", &size, // total program size (in pages) &resident, // number of resident set (non-swapped) pages (4k) &share, // number of pages of shared (mmap'd) memory &trs, // text resident set size &lrs, // shared-lib resident set size &drs, // data resident set size &dt); // dirty pages return resident*4*1024;*/ return 0; } #else // LINUX, NOT MAC OS long long System::physicalMemory() { return (long long)(sysconf(_SC_PHYS_PAGES)) * sysconf(_SC_PAGESIZE); } long long System::<API key>() { return (long long)(sysconf(_SC_AVPHYS_PAGES)) * sysconf(_SC_PAGESIZE); } size_t System::memoryUsedByProcess() { int pid = getpid(); static char filename[32]; sprintf(filename, 32, "/proc/%d/statm", pid); int fd = open(filename, O_RDONLY, 0); if(fd==-1) OGDF_THROW(Exception); static char sbuf[256]; sbuf[read(fd, sbuf, sizeof(sbuf) - 1)] = 0; close(fd); long size, resident, share, trs, lrs, drs, dt; sscanf(sbuf, "%ld %ld %ld %ld %ld %ld %ld", &size, // total program size (in pages) &resident, // number of resident set (non-swapped) pages (4k) &share, // number of pages of shared (mmap'd) memory &trs, // text resident set size &lrs, // shared-lib resident set size &drs, // data resident set size &dt); // dirty pages return resident*4*1024; } #endif #ifdef OGDF_SYSTEM_WINDOWS size_t System::<API key>() { _HEAPINFO hinfo; int heapstatus; hinfo._pentry = NULL; size_t allocMem = 0; while((heapstatus = _heapwalk(&hinfo)) == _HEAPOK) { if(hinfo._useflag == _USEDENTRY) allocMem += hinfo._size; } return allocMem; } size_t System::<API key>() { _HEAPINFO hinfo; int heapstatus; hinfo._pentry = NULL; size_t allocMem = 0; while((heapstatus = _heapwalk(&hinfo)) == _HEAPOK) { if(hinfo._useflag == _FREEENTRY) allocMem += hinfo._size; } return allocMem; } #elif __APPLE__ size_t System::<API key>() { return mstats().chunks_used; } size_t System::<API key>() { return mstats().chunks_free; } #else size_t System::<API key>() { return mallinfo().uordblks; } size_t System::<API key>() { return mallinfo().fordblks; } #endif #if !defined(OGDF_SYSTEM_WINDOWS) && !defined(__CYGWIN__) __int64 System::usedRealTime(__int64 &t) { __int64 tStart = t; timeval tv; gettimeofday(&tv, 0); t = __int64(tv.tv_sec) * 1000 + tv.tv_usec/1000; return t - tStart; } #endif size_t System::<API key>() { return PoolMemoryAllocator::<API key>(); } size_t System::<API key>() { return PoolMemoryAllocator::<API key>(); } size_t System::<API key>() { return PoolMemoryAllocator::<API key>(); } } // namespace ogdf
package keel.GraphInterKeel.datacf.visualizeData; public class <API key> extends javax.swing.JPanel { /** * <p> * Class that implements a Panel for datasets * </p> */ /** * <p> * Constructor that initializes the panel * </p> */ public <API key>() { initComponents(); } /** * <p> * This method is called from within the constructor to * initialize the form. * </p> * <p> * WARNING: Do NOT modify this code. The content of this method is * always regenerated by the Form Editor. * </p> */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { dataSetScrollPane = new javax.swing.JScrollPane(); dataSetTextArea = new javax.swing.JTextArea(); setBorder(javax.swing.BorderFactory.createTitledBorder(javax.swing.BorderFactory.createEtchedBorder(), "Content")); setName("Form"); // NOI18N dataSetScrollPane.setName("dataSetScrollPane"); // NOI18N dataSetTextArea.setColumns(20); dataSetTextArea.setRows(5); dataSetTextArea.setName("dataSetTextArea"); // NOI18N dataSetScrollPane.setViewportView(dataSetTextArea); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this); this.setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(dataSetScrollPane, javax.swing.GroupLayout.DEFAULT_SIZE, 388, Short.MAX_VALUE) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(dataSetScrollPane, javax.swing.GroupLayout.DEFAULT_SIZE, 272, Short.MAX_VALUE) ); }// </editor-fold>//GEN-END:initComponents // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JScrollPane dataSetScrollPane; private javax.swing.JTextArea dataSetTextArea; // End of variables declaration//GEN-END:variables /** * <p> * Sets text for dataset area * </p> * @param text Test for dataset area */ public void setTextData(String text) { this.dataSetTextArea.setText(text); } /** * <p> * Sets care postion for dataset area * </p> * @param care Care postion for dataset area */ public void setCaret(int care) { this.dataSetTextArea.setCaretPosition(care); } }
/* global DynCSS */ DynCSS.defineModule('rz_box', function (api, v, res) { 'use strict'; function <API key>(childWidthString, hSpace) { this.childWidths = []; this.hSpace = ''; if (childWidthString && hSpace) { this.setChildWidth(childWidthString, hSpace); } } /** * @public * @param {String} childWidthString * @param {String} hSpace */ <API key>.prototype.setChildWidth = function (childWidthString, hSpace) { this.hSpace = hSpace; this.childWidths = this.<API key>(childWidthString); return this; }; /** * @private * @param childWidthString * @returns {Array} */ <API key>.prototype.<API key> = function (childWidthString) { var columns = childWidthString.trim().replace(/\s+/g, ' ').split(' '); var numberOfColumns = columns.length; var col; var childWidth = []; for (var i = 0; i < numberOfColumns; i++) { col = {}; var type = columns[i].match(/px|%$/); var valign = columns[i].match(/^[mu]/); col.unit = type !== null ? type[0] : ''; col.valign = valign !== null ? valign[0] : ''; col.value = parseFloat(columns[i].replace(/[mu]|%|px/g, '').replace(',', '.')); col.hidden = (['0', '0%', '0px'].indexOf(columns[i]) >= 0); col.index = i; childWidth.push(col); } return childWidth; }; var hSpace = v.cssHSpace || 0; var vSpace = v.cssVSpace || 0; var colBoxHelper = new <API key>(v.cssChildWidth, hSpace); var columns = colBoxHelper.childWidths; var numberOfColumns = columns.length; var hiddenStyle = { '%%display': 'none' }; var result = {}; // add spacers var spacer = []; // array to preserve order in CSS output spacer.push({ '&:nth-child(1n)': { display: 'table-cell', '%%width': hSpace, '%%height': 0 } }); var spacerRows = {}; spacerRows['&:nth-child(' + numberOfColumns * 2 + 'n)'] = { display: 'table-row', '%%width': 0, '%%height': vSpace }; spacer.push(spacerRows); result['& > .isColumnBoxTable > .boxSpacer'] = spacer; // generate CSS for each column (where the children will be placed into) for (var i = 0; i < numberOfColumns; i++) { var column = columns[i]; var verticalAlignValue = ((column.valign == 'u') ? 'bottom' : ((column.valign == 'm') ? 'middle' : '')); var columnWidth = '' + column.value + column.unit; var cellSelector = '& > .isColumnBoxTable > .isColumnBoxCell:nth-child(' + numberOfColumns * 2 + 'n+' + (i * 2 + 1) + ')'; result[cellSelector] = { '%%display': 'table-cell', // %% to preserve order by prevent DynCSS merging '%%width': columnWidth }; if (verticalAlignValue) { result[cellSelector]['vertical-align'] = verticalAlignValue; } // logic for hiding cells if (column.hidden) { var isLastColumn = i == (numberOfColumns - 1); var <API key> = '& > .isColumnBoxTable > .boxSpacer:nth-child(' + numberOfColumns * 2 + 'n+' + (isLastColumn ? i * 2 : i * 2 + 2) + ')'; result[cellSelector]['%%display'] = 'none'; result[<API key>] = hiddenStyle; } } // box preview for empty cells result['& > .isColumnBoxTable > .boxPreview:nth-child(1n+' + (numberOfColumns * 2 + 1) + ')'] = hiddenStyle; result['& > .isColumnBoxTable > .boxSpacer.boxPreviewSpacer:nth-child(1n+' + (numberOfColumns * 2) + ')'] = hiddenStyle; // horizontal align of this module if (v.<API key>) { switch (v.cssHorizontalAlign) { case 'center': result.marginLeft = 'auto !important'; result.marginRight = 'auto !important'; break; case 'right': result.marginLeft = 'auto !important'; result.marginRight = '0 !important'; break; default: result.marginLeft = '0 !important'; result.marginRight = 'auto !important'; break; } } // vertical align of child modules result['& > .isColumnBoxTable > .isColumnBoxCell'] = { 'vertical-align': v.cssVerticalAlign || 'top' }; return result; }, { <API key>: true });
-- Tabelstructuur voor tabel `ldapauth_server` CREATE TABLE `ldapauth_server` ( `id` int(11) NOT NULL, `hostname` varchar(190) COLLATE utf8mb4_unicode_ci NOT NULL, `port` int(11) NOT NULL DEFAULT '389', `encryption` enum('ssl','tls') COLLATE utf8mb4_unicode_ci DEFAULT 'tls', `username` VARCHAR(190) NULL DEFAULT NULL, `password` VARCHAR(512) NULL COLLATE ascii_bin DEFAULT NULL, `usernameAttribute` varchar(190) COLLATE utf8mb4_unicode_ci NOT NULL DEFAULT 'uid', `peopleDN` varchar(190) COLLATE utf8mb4_unicode_ci NOT NULL DEFAULT 'ou=people,dc=example,dc=com', `groupsDN` varchar(190) COLLATE utf8mb4_unicode_ci DEFAULT 'ou=groups,dc=example,dc=com', `imapHostname` varchar(190) COLLATE utf8mb4_unicode_ci DEFAULT NULL, `imapPort` int(11) NOT NULL DEFAULT '143', `imapEncryption` enum('tls','ssl') COLLATE utf8mb4_unicode_ci DEFAULT 'tls', `<API key>` tinyint(1) NOT NULL DEFAULT '1', `<API key>` tinyint(1) NOT NULL DEFAULT '0', `smtpHostname` varchar(190) COLLATE utf8mb4_unicode_ci DEFAULT NULL, `smtpPort` int(11) NOT NULL DEFAULT '587', `smtpUsername` varchar(190) COLLATE utf8mb4_unicode_ci DEFAULT NULL, `smtpPassword` varchar(512) COLLATE ascii_bin DEFAULT NULL, `<API key>` tinyint(1) NOT NULL DEFAULT '0', `smtpEncryption` enum('tls','ssl') COLLATE utf8mb4_unicode_ci DEFAULT NULL, `<API key>` tinyint(1) NOT NULL DEFAULT '1' ) ENGINE=InnoDB; -- Tabelstructuur voor tabel `<API key>` CREATE TABLE `<API key>` ( `id` int(11) NOT NULL, `serverId` int(11) NOT NULL, `name` varchar(190) COLLATE utf8mb4_unicode_ci NOT NULL DEFAULT '*' ) ENGINE=InnoDB; -- Tabelstructuur voor tabel `<API key>` CREATE TABLE `<API key>` ( `serverId` int(11) NOT NULL, `groupId` int(11) NOT NULL ) ENGINE=InnoDB; -- Indexen voor tabel `ldapauth_server` ALTER TABLE `ldapauth_server` ADD PRIMARY KEY (`id`); -- Indexen voor tabel `<API key>` ALTER TABLE `<API key>` ADD PRIMARY KEY (`id`), ADD KEY `serverId` (`serverId`); -- Indexen voor tabel `<API key>` ALTER TABLE `<API key>` ADD PRIMARY KEY (`serverId`,`groupId`), ADD KEY `groupId` (`groupId`); -- AUTO_INCREMENT voor een tabel `ldapauth_server` ALTER TABLE `ldapauth_server` MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=2; -- AUTO_INCREMENT voor een tabel `<API key>` ALTER TABLE `<API key>` MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=2; -- Beperkingen voor tabel `<API key>` ALTER TABLE `<API key>` ADD CONSTRAINT `ldap<API key>` FOREIGN KEY (`serverId`) REFERENCES `ldapauth_server` (`id`) ON DELETE CASCADE; -- Beperkingen voor tabel `<API key>` ALTER TABLE `<API key>` ADD CONSTRAINT `ldap<API key>` FOREIGN KEY (`serverId`) REFERENCES `ldapauth_server` (`id`) ON DELETE CASCADE, ADD CONSTRAINT `ldap<API key>` FOREIGN KEY (`groupId`) REFERENCES `core_group` (`id`) ON DELETE CASCADE;
<?php namespace Render\IconHelper; use Render\InfoStorage\MediaInfoStorage\<API key>; class SimpleIconHelper implements IIconHelper { /** * @var string */ private $iconDirectory; /** * @var string */ private $fallBackIconName; /** * @param string $iconDirectory * @param string $fallBackIconName */ public function __construct($iconDirectory, $fallBackIconName) { $this->iconDirectory = $iconDirectory; $this->fallBackIconName = $fallBackIconName; } /** * Returns the filePath to the related icon * * @param string $mediaFilePath * * @return string */ public function getIconFilePath($mediaFilePath) { $fileExtension = $this->getFileExtension($mediaFilePath); $iconFileName = $this-><API key>($fileExtension); $iconFilePath = $this->createIconPath($iconFileName); if (!file_exists($iconFilePath)) { return $this->createIconPath($this->fallBackIconName); } return $iconFilePath; } /** * @param string $mediaFilePath * * @return string */ protected function getFileExtension($mediaFilePath) { $fileName = basename($mediaFilePath); return substr(strrchr(strtolower($fileName), '.'), 1); } /** * @param $fileExtension * * @return string */ protected function <API key>($fileExtension) { return 'icon_' . $fileExtension . '.png'; } /** * @param $iconFileName * * @return string */ protected function createIconPath($iconFileName) { return $this->iconDirectory . DIRECTORY_SEPARATOR . $iconFileName; } }
package com.bahram.relationshippoints.GUI.thirdParty.<API key>; import android.annotation.SuppressLint; import android.content.Context; import android.graphics.Canvas; import android.graphics.drawable.Drawable; import android.os.Build; import android.util.AttributeSet; import android.util.SparseArray; import android.view.View; import android.view.ViewGroup; import android.view.animation.Animation; import android.view.animation.Animation.AnimationListener; import android.view.animation.Transformation; import android.widget.AbsListView; import android.widget.<API key>; import android.widget.<API key>; import android.widget.ExpandableListView; import java.util.ArrayList; import java.util.List; public class <API key> extends ExpandableListView { /* * A detailed explanation for how this class works: * * Animating the ExpandableListView was no easy task. The way that this * class does it is by exploiting how an ExpandableListView works. * * Normally when {@link ExpandableListView#collapseGroup(int)} or * {@link ExpandableListView#expandGroup(int)} is called, the view toggles * the flag for a group and calls <API key> to cause the ListView * to refresh all of it's view. This time however, depending on whether a * group is expanded or collapsed, certain childViews will either be ignored * or added to the list. * * Knowing this, we can come up with a way to animate our views. For * instance for group expansion, we tell the adapter to animate the * children of a certain group. We then expand the group which causes the * ExpandableListView to refresh all views on screen. The way that * ExpandableListView does this is by calling getView() in the adapter. * However since the adapter knows that we are animating a certain group, * instead of returning the real views for the children of the group being * animated, it will return a fake dummy view. This dummy view will then * draw the real child views within it's dispatchDraw function. The reason * we do this is so that we can animate all of it's children by simply * animating the dummy view. After we complete the animation, we tell the * adapter to stop animating the group and call <API key>. Now * the ExpandableListView is forced to refresh it's views again, except this * time, it will get the real views for the expanded group. * * So, to list it all out, when {@link #<API key>(int)} is * called the following happens: * * 1. The ExpandableListView tells the adapter to animate a certain group. * 2. The ExpandableListView calls expandGroup. * 3. ExpandGroup calls <API key>. * 4. As an result, getChildView is called for expanding group. * 5. Since the adapter is in "animating mode", it will return a dummy view. * 6. This dummy view draws the actual children of the expanding group. * 7. This dummy view's height is animated from 0 to it's expanded height. * 8. Once the animation completes, the adapter is notified to stop * animating the group and <API key> is called again. * 9. This forces the ExpandableListView to refresh all of it's views again. * 10.This time when getChildView is called, it will return the actual * child views. * * For animating the collapse of a group is a bit more difficult since we * can't call collapseGroup from the start as it would just ignore the * child items, giving up no chance to do any sort of animation. Instead * what we have to do is play the animation first and call collapseGroup * after the animation is done. * * So, to list it all out, when {@link #<API key>(int)} is * called the following happens: * * 1. The ExpandableListView tells the adapter to animate a certain group. * 2. The ExpandableListView calls <API key>. * 3. As an result, getChildView is called for expanding group. * 4. Since the adapter is in "animating mode", it will return a dummy view. * 5. This dummy view draws the actual children of the expanding group. * 6. This dummy view's height is animated from it's current height to 0. * 7. Once the animation completes, the adapter is notified to stop * animating the group and <API key> is called again. * 8. collapseGroup is finally called. * 9. This forces the ExpandableListView to refresh all of it's views again. * 10.This time when the ListView will not get any of the child views for * the collapsed group. */ @SuppressWarnings("unused") private static final String TAG = <API key>.class.getSimpleName(); /** * The duration of the expand/collapse animations */ private static final int ANIMATION_DURATION = 300; private <API key> adapter; public <API key>(Context context) { super(context); } public <API key>(Context context, AttributeSet attrs) { super(context, attrs); } public <API key>(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); } /** * @see ExpandableListView#setAdapter(<API key>) */ public void setAdapter(<API key> adapter) { super.setAdapter(adapter); // Make sure that the adapter extends <API key> if( adapter instanceof <API key> ) { this.adapter = (<API key>) adapter; this.adapter.setParent(this); } else { throw new ClassCastException(adapter.toString() + " must implement <API key>"); } } /** * Expands the given group with an animation. * * @param groupPos The position of the group to expand * @return Returns true if the group was expanded. False if the group was * already expanded. */ @SuppressLint("NewApi") public boolean <API key>(int groupPos) { boolean lastGroup = groupPos == adapter.getGroupCount() - 1; if( lastGroup && Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH ) { return expandGroup(groupPos, true); } int groupFlatPos = getFlatListPosition(<API key>(groupPos)); if( groupFlatPos != -1 ) { int childIndex = groupFlatPos - <API key>(); if( childIndex < getChildCount() ) { // Get the view for the group is it is on screen... View v = getChildAt(childIndex); if( v.getBottom() >= getBottom() ) { // If the user is not going to be able to see the animation // we just expand the group without an animation. // This resolves the case where getChildView will not be // called if the children of the group is not on screen // We need to notify the adapter that the group was expanded // without it's knowledge adapter.notifyGroupExpanded(groupPos); return expandGroup(groupPos); } } } // Let the adapter know that we are starting the animation... adapter.<API key>(groupPos, 0); // Finally call expandGroup (note that expandGroup will call // <API key> so we don't need to) return expandGroup(groupPos); } /** * Collapses the given group with an animation. * * @param groupPos The position of the group to collapse * @return Returns true if the group was collapsed. False if the group was * already collapsed. */ public boolean <API key>(int groupPos) { int groupFlatPos = getFlatListPosition(<API key>(groupPos)); if( groupFlatPos != -1 ) { int childIndex = groupFlatPos - <API key>(); if( childIndex >= 0 && childIndex < getChildCount() ) { // Get the view for the group is it is on screen... View v = getChildAt(childIndex); if( v.getBottom() >= getBottom() ) { // If the user is not going to be able to see the animation // we just collapse the group without an animation. // This resolves the case where getChildView will not be // called if the children of the group is not on screen return collapseGroup(groupPos); } } else { // If the group is offscreen, we can just collapse it without an animation... return collapseGroup(groupPos); } } // Get the position of the firstChild visible from the top of the screen long packedPos = <API key>(<API key>()); int firstChildPos = <API key>(packedPos); int firstGroupPos = <API key>(packedPos); // If the first visible view on the screen is a child view AND it's a // child of the group we are trying to collapse, then set that // as the first child position of the group... see // {@link #<API key>(int, int)} for why this is necessary firstChildPos = firstChildPos == -1 || firstGroupPos != groupPos ? 0 : firstChildPos; // Let the adapter know that we are going to start animating the // collapse animation. adapter.<API key>(groupPos, firstChildPos); // Force the listview to refresh it's views adapter.<API key>(); return isGroupExpanded(groupPos); } private int <API key>() { return ANIMATION_DURATION; } /** * Used for holding information regarding the group. */ private static class GroupInfo { boolean animating = false; boolean expanding = false; int firstChildPosition; /** * This variable contains the last known height value of the dummy view. * We save this information so that if the user collapses a group * before it fully expands, the collapse animation will start from the * CURRENT height of the dummy view and not from the full expanded * height. */ int dummyHeight = -1; } /** * A specialized adapter for use with the <API key>. All * adapters used with <API key> MUST extend this class. */ public static abstract class <API key> extends <API key> { private SparseArray<GroupInfo> groupInfo = new SparseArray<>(); private <API key> parent; private static final int STATE_IDLE = 0; private static final int STATE_EXPANDING = 1; private static final int STATE_COLLAPSING = 2; private void setParent(<API key> parent) { this.parent = parent; } public int getRealChildType(int groupPosition, int childPosition) { return 0; } public int <API key>() { return 1; } public abstract View getRealChildView(int groupPosition, int childPosition, boolean isLastChild, View convertView, ViewGroup parent); public abstract int <API key>(int groupPosition); private GroupInfo getGroupInfo(int groupPosition) { GroupInfo info = groupInfo.get(groupPosition); if( info == null ) { info = new GroupInfo(); groupInfo.put(groupPosition, info); } return info; } public void notifyGroupExpanded(int groupPosition) { GroupInfo info = getGroupInfo(groupPosition); info.dummyHeight = -1; } private void <API key>(int groupPosition, int firstChildPosition) { GroupInfo info = getGroupInfo(groupPosition); info.animating = true; info.firstChildPosition = firstChildPosition; info.expanding = true; } private void <API key>(int groupPosition, int firstChildPosition) { GroupInfo info = getGroupInfo(groupPosition); info.animating = true; info.firstChildPosition = firstChildPosition; info.expanding = false; } private void stopAnimation(int groupPosition) { GroupInfo info = getGroupInfo(groupPosition); info.animating = false; } /** * Override {@link #getRealChildType(int, int)} instead. */ @Override public final int getChildType(int groupPosition, int childPosition) { GroupInfo info = getGroupInfo(groupPosition); if( info.animating ) { // If we are animating this group, then all of it's children // are going to be dummy views which we will say is type 0. return 0; } else { // If we are not animating this group, then we will add 1 to // the type it has so that no type id conflicts will occur // unless getRealChildType() returns MAX_INT return getRealChildType(groupPosition, childPosition) + 1; } } /** * Override {@link #<API key>()} instead. */ @Override public final int getChildTypeCount() { // Return 1 more than the childTypeCount to account for DummyView return <API key>() + 1; } protected ViewGroup.LayoutParams <API key>() { return new AbsListView.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT, 0); } /** * Override {@link #getChildView(int, int, boolean, View, ViewGroup)} instead. */ @Override public final View getChildView(final int groupPosition, int childPosition, boolean isLastChild, View convertView, final ViewGroup parent) { final GroupInfo info = getGroupInfo(groupPosition); if( info.animating ) { // If this group is animating, return the a DummyView... if( convertView instanceof DummyView == false ) { convertView = new DummyView(parent.getContext()); convertView.setLayoutParams(new AbsListView.LayoutParams(LayoutParams.MATCH_PARENT, 0)); } if( childPosition < info.firstChildPosition ) { // The reason why we do this is to support the collapse // this group when the group view is not visible but the // children of this group are. When <API key> // is called, the ExpandableListView tries to keep the // list position the same by saving the first visible item // and jumping back to that item after the views have been // refreshed. Now the problem is, if a group has 2 items // and the first visible item is the 2nd child of the group // and this group is collapsed, then the dummy view will be // used for the group. But now the group only has 1 item // which is the dummy view, thus when the ListView is trying // to restore the scroll position, it will try to jump to // the second item of the group. But this group no longer // has a second item, so it is forced to jump to the next // group. This will cause a very ugly visual glitch. So // the way that we counteract this is by creating as many // dummy views as we need to maintain the scroll position // of the ListView after <API key> has been // called. convertView.getLayoutParams().height = 0; return convertView; } final ExpandableListView listView = (ExpandableListView) parent; final DummyView dummyView = (DummyView) convertView; // Clear the views that the dummy view draws. dummyView.clearViews(); // Set the style of the divider dummyView.setDivider(listView.getDivider(), parent.getMeasuredWidth(), listView.getDividerHeight()); // Make measure specs to measure child views final int measureSpecW = MeasureSpec.makeMeasureSpec(parent.getWidth(), MeasureSpec.EXACTLY); final int measureSpecH = MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED); int totalHeight = 0; int clipHeight = parent.getHeight(); final int len = <API key>(groupPosition); for( int i = info.firstChildPosition; i < len; i++ ) { View childView = getRealChildView(groupPosition, i, (i == len - 1), null, parent); LayoutParams p = (LayoutParams) childView.getLayoutParams(); if( p == null ) { p = (AbsListView.LayoutParams) <API key>(); childView.setLayoutParams(p); } int lpHeight = p.height; int childHeightSpec; if( lpHeight > 0 ) { childHeightSpec = MeasureSpec.makeMeasureSpec(lpHeight, MeasureSpec.EXACTLY); } else { childHeightSpec = measureSpecH; } childView.measure(measureSpecW, childHeightSpec); totalHeight += childView.getMeasuredHeight(); if( totalHeight < clipHeight ) { // we only need to draw enough views to fool the user... dummyView.addFakeView(childView); } else { dummyView.addFakeView(childView); // if this group has too many views, we don't want to // calculate the height of everything... just do a light // approximation and break int averageHeight = totalHeight / (i + 1); totalHeight += (len - i - 1) * averageHeight; break; } } Object o; int state = (o = dummyView.getTag()) == null ? STATE_IDLE : (Integer) o; if( info.expanding && state != STATE_EXPANDING ) { ExpandAnimation ani = new ExpandAnimation(dummyView, 0, totalHeight, info); ani.setDuration(this.parent.<API key>()); ani.<API key>(new AnimationListener() { @Override public void onAnimationEnd(Animation animation) { stopAnimation(groupPosition); <API key>(); dummyView.setTag(STATE_IDLE); } @Override public void onAnimationRepeat(Animation animation) { } @Override public void onAnimationStart(Animation animation) { } }); dummyView.startAnimation(ani); dummyView.setTag(STATE_EXPANDING); } else if( !info.expanding && state != STATE_COLLAPSING ) { if( info.dummyHeight == -1 ) { info.dummyHeight = totalHeight; } ExpandAnimation ani = new ExpandAnimation(dummyView, info.dummyHeight, 0, info); ani.setDuration(this.parent.<API key>()); ani.<API key>(new AnimationListener() { @Override public void onAnimationEnd(Animation animation) { stopAnimation(groupPosition); listView.collapseGroup(groupPosition); <API key>(); info.dummyHeight = -1; dummyView.setTag(STATE_IDLE); } @Override public void onAnimationRepeat(Animation animation) { } @Override public void onAnimationStart(Animation animation) { } }); dummyView.startAnimation(ani); dummyView.setTag(STATE_COLLAPSING); } return convertView; } else { return getRealChildView(groupPosition, childPosition, isLastChild, convertView, parent); } } @Override public final int getChildrenCount(int groupPosition) { GroupInfo info = getGroupInfo(groupPosition); if( info.animating ) { return info.firstChildPosition + 1; } else { return <API key>(groupPosition); } } } private static class DummyView extends View { private List<View> views = new ArrayList<>(); private Drawable divider; private int dividerWidth; private int dividerHeight; public DummyView(Context context) { super(context); } public void setDivider(Drawable divider, int dividerWidth, int dividerHeight) { if( divider != null ) { this.divider = divider; this.dividerWidth = dividerWidth; this.dividerHeight = dividerHeight; divider.setBounds(0, 0, dividerWidth, dividerHeight); } } /** * Add a view for the DummyView to draw. * * @param childView View to draw */ public void addFakeView(View childView) { childView.layout(0, 0, getWidth(), childView.getMeasuredHeight()); views.add(childView); } @Override protected void onLayout(boolean changed, int left, int top, int right, int bottom) { super.onLayout(changed, left, top, right, bottom); final int len = views.size(); for( int i = 0; i < len; i++ ) { View v = views.get(i); v.layout(left, top, left + v.getMeasuredWidth(), top + v.getMeasuredHeight()); } } public void clearViews() { views.clear(); } @Override public void dispatchDraw(Canvas canvas) { canvas.save(); if( divider != null ) { divider.setBounds(0, 0, dividerWidth, dividerHeight); } final int len = views.size(); for( int i = 0; i < len; i++ ) { View v = views.get(i); canvas.save(); canvas.clipRect(0, 0, getWidth(), v.getMeasuredHeight()); v.draw(canvas); canvas.restore(); if( divider != null ) { divider.draw(canvas); canvas.translate(0, dividerHeight); } canvas.translate(0, v.getMeasuredHeight()); } canvas.restore(); } } private static class ExpandAnimation extends Animation { private int baseHeight; private int delta; private View view; private GroupInfo groupInfo; private ExpandAnimation(View v, int startHeight, int endHeight, GroupInfo info) { baseHeight = startHeight; delta = endHeight - startHeight; view = v; groupInfo = info; view.getLayoutParams().height = startHeight; view.requestLayout(); } @Override protected void applyTransformation(float interpolatedTime, Transformation t) { super.applyTransformation(interpolatedTime, t); if( interpolatedTime < 1.0f ) { int val = baseHeight + (int) (delta * interpolatedTime); view.getLayoutParams().height = val; groupInfo.dummyHeight = val; view.requestLayout(); } else { int val = baseHeight + delta; view.getLayoutParams().height = val; groupInfo.dummyHeight = val; view.requestLayout(); } } } }
<!DOCTYPE html PUBLIC "- <html xmlns="http: <head> <meta http-equiv="content-type" content="text/html; charset=UTF-8" /> <title>VersionUtil xref</title> <link type="text/css" rel="stylesheet" href="../../../stylesheet.css" /> </head> <body> <div id="overview"><a href="../../../../apidocs/org/slf4j/impl/VersionUtil.html">View Javadoc</a></div><pre> <a class="jxr_linenumber" name="1" href="#1">1</a> <strong class="jxr_keyword">package</strong> org.slf4j.impl; <a class="jxr_linenumber" name="2" href="#2">2</a> <a class="jxr_linenumber" name="3" href="#3">3</a> <strong class="jxr_keyword">import</strong> java.lang.reflect.Method; <a class="jxr_linenumber" name="4" href="#4">4</a> <a class="jxr_linenumber" name="5" href="#5">5</a> <strong class="jxr_keyword">import</strong> org.slf4j.helpers.Util; <a class="jxr_linenumber" name="6" href="#6">6</a> <a class="jxr_linenumber" name="7" href="#7">7</a> <strong class="jxr_keyword">public</strong> <strong class="jxr_keyword">class</strong> <a href="../../../org/slf4j/impl/VersionUtil.html">VersionUtil</a> { <a class="jxr_linenumber" name="8" href="#8">8</a> <strong class="jxr_keyword">static</strong> <strong class="jxr_keyword">final</strong> <strong class="jxr_keyword">int</strong> MINIMAL_VERSION = 5; <a class="jxr_linenumber" name="9" href="#9">9</a> <a class="jxr_linenumber" name="10" href="#10">10</a> <strong class="jxr_keyword">static</strong> <strong class="jxr_keyword">public</strong> <strong class="jxr_keyword">int</strong> getJavaMajorVersion() { <a class="jxr_linenumber" name="11" href="#11">11</a> String javaVersionString = Util.<API key>(<span class="jxr_string">"java.version"</span>); <a class="jxr_linenumber" name="12" href="#12">12</a> <strong class="jxr_keyword">return</strong> getJavaMajorVersion(javaVersionString); <a class="jxr_linenumber" name="13" href="#13">13</a> } <a class="jxr_linenumber" name="14" href="#14">14</a> <a class="jxr_linenumber" name="15" href="#15">15</a> <strong class="jxr_keyword">static</strong> <strong class="jxr_keyword">int</strong> getJavaMajorVersion(String versionString) { <a class="jxr_linenumber" name="16" href="#16">16</a> <strong class="jxr_keyword">if</strong> (versionString == <strong class="jxr_keyword">null</strong>) <a class="jxr_linenumber" name="17" href="#17">17</a> <strong class="jxr_keyword">return</strong> MINIMAL_VERSION; <a class="jxr_linenumber" name="18" href="#18">18</a> <strong class="jxr_keyword">if</strong> (versionString.startsWith(<span class="jxr_string">"1."</span>)) { <a class="jxr_linenumber" name="19" href="#19">19</a> <strong class="jxr_keyword">return</strong> versionString.charAt(2) - '0'; <a class="jxr_linenumber" name="20" href="#20">20</a> } <strong class="jxr_keyword">else</strong> { <a class="jxr_linenumber" name="21" href="#21">21</a> <em class="jxr_comment">// we running under Java 9 or later</em> <a class="jxr_linenumber" name="22" href="#22">22</a> <strong class="jxr_keyword">try</strong> { <a class="jxr_linenumber" name="23" href="#23">23</a> Method versionMethod = Runtime.<strong class="jxr_keyword">class</strong>.getMethod(<span class="jxr_string">"version"</span>); <a class="jxr_linenumber" name="24" href="#24">24</a> Object versionObj = versionMethod.invoke(<strong class="jxr_keyword">null</strong>); <a class="jxr_linenumber" name="25" href="#25">25</a> Method majorMethod = versionObj.getClass().getMethod(<span class="jxr_string">"major"</span>); <a class="jxr_linenumber" name="26" href="#26">26</a> Integer resultInteger = (Integer) majorMethod.invoke(versionObj); <a class="jxr_linenumber" name="27" href="#27">27</a> <strong class="jxr_keyword">return</strong> resultInteger.intValue(); <a class="jxr_linenumber" name="28" href="#28">28</a> } <strong class="jxr_keyword">catch</strong> (Exception e) { <a class="jxr_linenumber" name="29" href="#29">29</a> <strong class="jxr_keyword">return</strong> MINIMAL_VERSION; <a class="jxr_linenumber" name="30" href="#30">30</a> } <a class="jxr_linenumber" name="31" href="#31">31</a> } <a class="jxr_linenumber" name="32" href="#32">32</a> } <a class="jxr_linenumber" name="33" href="#33">33</a> } </pre> <hr/><div id="footer">This page was automatically generated by <a href="http://maven.apache.org/">Maven</a></div></body> </html>
#ifndef GEOMETRY_UTILS_HPP #define GEOMETRY_UTILS_HPP #include <glm/glm.hpp> namespace geometry { enum <API key> { COLINEAR, CLOCKWISE, COUNTER_CLOCKWISE }; <API key> <API key>(glm::vec2 a, glm::vec2 b, glm::vec2 c) noexcept; bool <API key>(glm::vec2 a1, glm::vec2 b1, glm::vec2 a4, glm::vec2 b4) noexcept; } #endif
//MergeSort #include "questao4.h" void intercala(int *vet, int p, int q, int r) { int i, j, k, *w; w = (int *) malloc((r - p) * sizeof (int)); i = p; j = q; k = 0; while (i < q && j < r) { if (vet[i] <= vet[j]) w[k++] = vet[i++]; else w[k++] = vet[j++]; } while (i < q) { w[k++] = vet[i++]; } while (j < r) { w[k++] = vet[j++]; } for (i = p; i < r; ++i) { vet[i] = w[i - p]; } free(w); } // A funcao mergesort rearranja o vetor v[p..r-1] em ordem crescente. void Merge(int *vet, int p, int r) { int q; if (p < r) { q = (p + r) / 2; Merge(vet, p, q); Merge(vet, q + 1, r); intercala(vet, p, q, r); } } void MergeSort(int *v, int n) { Merge(v, 0, n - 1); }
#ifndef __output_plugin_h__ #define __output_plugin_h__ #define <API key> 0x1000 #define <API key> (<API key> + 6) typedef int output_version_type; typedef int(*output_init_type)(void); typedef int(*output_open_type)(const char *path); typedef void(*output_close_type)(void); typedef int(*output_write_type)(short *data, int short_count); typedef int(*<API key>)(void *data); typedef int(*<API key>)(int *frag_size, int *frag_count, int *channels); typedef unsigned int(*<API key>)(unsigned int rate); typedef int(*<API key>)(void); typedef int(*<API key>)(void); typedef struct _output_plugin { /** * Version of output plugin. Must be <API key> */ output_version_type version; /** * Name of output plugin */ const char *name; /** * Author of the plugin */ const char *author; /** * Initialize output plugin. Called before the plugin is * opened for use */ output_init_type init; /** * @param path The path or device designation that should be used * * Opens the output plugin. A value of 1 should be returned on * success, 0 on failure. */ output_open_type open; /** * Close the output plugin */ output_close_type close; /** * @param data Buffer that contains the data * @param byte_count Number of bytes that should be read from the buffer * * Write out data to the output device. This is a byte count and * will typically be the same size as a fragment. A value of 1 should * be returned on success, 0 on failure. */ output_write_type write; /** * @param data pointer to bufs structure in AlsaNode * * This function is used for callback based plugins like JACK */ <API key> start_callbacks; /** * @param frag_size Fragment size to use (in bytes) * @param frag_count Fragment count to use (in bytes) * @param channels Number of channels to use * * Set up the output device with the given parameters. Some output * devices do not accept such configurations in which case they * should just be ignored, but still expect frag_size data chunks * in the write function. A value of 1 should be returned on success, * 0 on failure. */ <API key> set_buffer; /** * @param rate Sample rate to use * * Set the sample rate of the output device. A value of 1 should be * returned on success, 0 on failure. */ <API key> set_sample_rate; /** * Returns the number of bytes pending in the hardware buffer of * output device. This function is optional. */ <API key> get_queue_count; /** * Returns the latency of the output device in bytes. This function * is optional. */ <API key> get_latency; } output_plugin; typedef output_plugin*(*<API key>)(void); #ifdef __cplusplus extern "C" #endif output_plugin* output_plugin_info (void); #endif
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.StringTokenizer; class Main { public static void main (String [] abc) throws IOException { BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); int testCaseCount=Integer.parseInt(br.readLine()); for (int testCase=0;testCase<testCaseCount;testCase++) { br.readLine(); //empty space. StringTokenizer st=new StringTokenizer(br.readLine()); ArrayList<Integer> indexList=new ArrayList<>(); int size=-1; while (st.hasMoreTokens()) { int index=Integer.parseInt(st.nextToken()); indexList.add(index-1); size=Math.max(index,size); } String [] values=new String [size]; st=new StringTokenizer(br.readLine()); for (int i=0;i<size;i++) values[indexList.get(i)]=st.nextToken(); for (String s : values) System.out.println(s); if (testCase<testCaseCount-1) System.out.println(); } } }