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
/* $XConsortium: misc.c /main/29 1996/11/13 14:43:55 lehors $ */ /****************************************************************************** Copyright (c) 1993 X Consortium Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE X CONSORTIUM BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. Except as contained in this notice, the name of the X Consortium shall not be used in advertising or otherwise to promote the sale, use or other dealings in this Software without prior written authorization from the X Consortium. Author: Ralph Mor, X Consortium ******************************************************************************/ #include "KDE-ICE/ICElib.h" #include "KDE-ICE/ICElibint.h" #include "KDE-ICE/Xtrans.h" #include "KDE-ICE/globals.h" #include <stdio.h> #include <errno.h> #include <string.h> /* * scratch buffer */ char *IceAllocScratch(iceConn, size) IceConn iceConn; unsigned long size; { if(!iceConn->scratch || size > iceConn->scratch_size) { if(iceConn->scratch) free(iceConn->scratch); iceConn->scratch = (char *)malloc((unsigned)size); iceConn->scratch_size = size; } return (iceConn->scratch); } /* * Output/Input buffer functions */ void IceFlush(IceConn iceConn) { (*_IceWriteHandler)(iceConn, (unsigned long)(iceConn->outbufptr - iceConn->outbuf), iceConn->outbuf); iceConn->outbufptr = iceConn->outbuf; } int IceGetOutBufSize(iceConn) IceConn iceConn; { return (iceConn->outbufmax - iceConn->outbuf); } int IceGetInBufSize(iceConn) IceConn iceConn; { return (iceConn->inbufmax - iceConn->inbuf); } /* * informational functions */ IceConnectStatus IceConnectionStatus(iceConn) IceConn iceConn; { return (iceConn->connection_status); } char *IceVendor(iceConn) IceConn iceConn; { char *string = (char *)malloc(strlen(iceConn->vendor) + 1); if(string) strcpy(string, iceConn->vendor); return (string); } char *IceRelease(iceConn) IceConn iceConn; { char *string = (char *)malloc(strlen(iceConn->release) + 1); if(string) strcpy(string, iceConn->release); return (string); } int IceProtocolVersion(iceConn) IceConn iceConn; { return (_IceVersions[iceConn->my_ice_version_index].major_version); } int IceProtocolRevision(iceConn) IceConn iceConn; { return (_IceVersions[iceConn->my_ice_version_index].minor_version); } int IceConnectionNumber(iceConn) IceConn iceConn; { return (_kde_IceTransGetConnectionNumber(iceConn->trans_conn)); } char *IceConnectionString(iceConn) IceConn iceConn; { if(iceConn->connection_string) { char *string = (char *)malloc(strlen(iceConn->connection_string) + 1); if(string) strcpy(string, iceConn->connection_string); return (string); } else return (NULL); } unsigned long IceLastSentSequenceNumber(iceConn) IceConn iceConn; { return (iceConn->send_sequence); } unsigned long IceLastReceivedSequenceNumber(iceConn) IceConn iceConn; { return (iceConn->receive_sequence); } Bool IceSwapping(iceConn) IceConn iceConn; { return (iceConn->swap); } /* * Read "n" bytes from a connection. * * Return Status 0 if we detected an EXPECTED closed connection. * */ Status _IceRead(iceConn, nbytes, ptr) register IceConn iceConn; unsigned long nbytes; register char *ptr; { register unsigned long nleft; nleft = nbytes; while(nleft > 0) { int nread; if(iceConn->io_ok) nread = _kde_IceTransRead(iceConn->trans_conn, ptr, (int)nleft); else return (1); if(nread <= 0) { #ifdef _WIN32 errno = WSAGetLastError(); #endif if(nread < 0 && errno == EINTR) continue; if(iceConn->want_to_close) { /* * We sent a WantToClose message and now we detected that * the other side closed the connection. */ _IceConnectionClosed(iceConn); /* invoke watch procs */ _IceFreeConnection(iceConn); return (0); } else { /* * Fatal IO error. First notify each protocol's IceIOErrorProc * callback, then invoke the application IO error handler. */ iceConn->io_ok = False; if(iceConn->connection_status == IceConnectPending) { /* * Don't invoke IO error handler if we are in the * middle of a connection setup. */ return (1); } if(iceConn->process_msg_info) { int i; for(i = iceConn->his_min_opcode; i <= iceConn->his_max_opcode; i++) { _IceProcessMsgInfo *process; process = &iceConn->process_msg_info[i - iceConn->his_min_opcode]; if(process->in_use) { IceIOErrorProc IOErrProc = process->accept_flag ? process->protocol->accept_client->io_error_proc : process->protocol->orig_client->io_error_proc; if(IOErrProc) (*IOErrProc)(iceConn); } } } (*_IceIOErrorHandler)(iceConn); return (1); } } nleft -= nread; ptr += nread; } return (1); } /* * If we read a message header with a bad major or minor opcode, * we need to advance to the end of the message. This way, the next * message can be processed correctly. */ void _IceReadSkip(iceConn, nbytes) register IceConn iceConn; register unsigned long nbytes; { char temp[512]; while(nbytes > 0) { unsigned long rbytes = nbytes > 512 ? 512 : nbytes; _IceRead(iceConn, rbytes, temp); nbytes -= rbytes; } } /* * Write "n" bytes to a connection. */ void _IceWrite(iceConn, nbytes, ptr) register IceConn iceConn; unsigned long nbytes; register char *ptr; { register unsigned long nleft; nleft = nbytes; while(nleft > 0) { int nwritten; if(iceConn->io_ok) nwritten = _kde_IceTransWrite(iceConn->trans_conn, ptr, (int)nleft); else return; if(nwritten <= 0) { #ifdef _WIN32 errno = WSAGetLastError(); #endif if(nwritten < 0 && errno == EINTR) continue; /* * Fatal IO error. First notify each protocol's IceIOErrorProc * callback, then invoke the application IO error handler. */ iceConn->io_ok = False; if(iceConn->connection_status == IceConnectPending) { /* * Don't invoke IO error handler if we are in the * middle of a connection setup. */ return; } if(iceConn->process_msg_info) { int i; for(i = iceConn->his_min_opcode; i <= iceConn->his_max_opcode; i++) { _IceProcessMsgInfo *process; process = &iceConn->process_msg_info[i - iceConn->his_min_opcode]; if(process->in_use) { IceIOErrorProc IOErrProc = process->accept_flag ? process->protocol->accept_client->io_error_proc : process->protocol->orig_client->io_error_proc; if(IOErrProc) (*IOErrProc)(iceConn); } } } (*_IceIOErrorHandler)(iceConn); return; } nleft -= nwritten; ptr += nwritten; } } #ifdef WORD64 IceWriteData16(iceConn, nbytes, data) IceConn iceConn; unsigned long nbytes; short *data; { int numShorts = nbytes / 2; int index = 0; while(index < numShorts) { int spaceLeft, count, i; int shortsLeft = numShorts - index; spaceLeft = iceConn->outbufmax - iceConn->outbufptr - 1; if(spaceLeft < 2) { IceFlush(iceConn); spaceLeft = iceConn->outbufmax - iceConn->outbufptr - 1; } count = (shortsLeft < spaceLeft / 2) ? shortsLeft : spaceLeft / 2; for(i = 0; i < count; i++) STORE_CARD16(iceConn->outbufptr, data[index++]); } } IceWriteData32(iceConn, nbytes, data) IceConn iceConn; unsigned long nbytes; int *data; { int numLongs = nbytes / 4; int index = 0; while(index < numLongs) { int spaceLeft, count, i; int longsLeft = numLongs - index; spaceLeft = iceConn->outbufmax - iceConn->outbufptr - 1; if(spaceLeft < 4) { IceFlush(iceConn); spaceLeft = iceConn->outbufmax - iceConn->outbufptr - 1; } count = (longsLeft < spaceLeft / 4) ? longsLeft : spaceLeft / 4; for(i = 0; i < count; i++) STORE_CARD32(iceConn->outbufptr, data[index++]); } } IceReadData16(iceConn, swap, nbytes, data) IceConn iceConn; Bool swap; unsigned long nbytes; short *data; { /* NOT IMPLEMENTED YET */ } IceReadData32(iceConn, swap, nbytes, data) IceConn iceConn; Bool swap; unsigned long nbytes; int *data; { /* NOT IMPLEMENTED YET */ } #endif /* WORD64 */ void _IceAddOpcodeMapping(iceConn, hisOpcode, myOpcode) IceConn iceConn; int hisOpcode; int myOpcode; { if(hisOpcode <= 0 || hisOpcode > 255) { return; } else if(iceConn->process_msg_info == NULL) { iceConn->process_msg_info = (_IceProcessMsgInfo *)malloc(sizeof(_IceProcessMsgInfo)); iceConn->his_min_opcode = iceConn->his_max_opcode = hisOpcode; } else if(hisOpcode < iceConn->his_min_opcode) { _IceProcessMsgInfo *oldVec = iceConn->process_msg_info; int oldsize = iceConn->his_max_opcode - iceConn->his_min_opcode + 1; int newsize = iceConn->his_max_opcode - hisOpcode + 1; int i; iceConn->process_msg_info = (_IceProcessMsgInfo *)malloc(newsize * sizeof(_IceProcessMsgInfo)); memcpy(&iceConn->process_msg_info[iceConn->his_min_opcode - hisOpcode], oldVec, oldsize * sizeof(_IceProcessMsgInfo)); free((char *)oldVec); for(i = hisOpcode + 1; i < iceConn->his_min_opcode; i++) { iceConn->process_msg_info[i - iceConn->his_min_opcode].in_use = False; iceConn->process_msg_info[i - iceConn->his_min_opcode].protocol = NULL; } iceConn->his_min_opcode = hisOpcode; } else if(hisOpcode > iceConn->his_max_opcode) { _IceProcessMsgInfo *oldVec = iceConn->process_msg_info; int oldsize = iceConn->his_max_opcode - iceConn->his_min_opcode + 1; int newsize = hisOpcode - iceConn->his_min_opcode + 1; int i; iceConn->process_msg_info = (_IceProcessMsgInfo *)malloc(newsize * sizeof(_IceProcessMsgInfo)); memcpy(iceConn->process_msg_info, oldVec, oldsize * sizeof(_IceProcessMsgInfo)); free((char *)oldVec); for(i = iceConn->his_max_opcode + 1; i < hisOpcode; i++) { iceConn->process_msg_info[i - iceConn->his_min_opcode].in_use = False; iceConn->process_msg_info[i - iceConn->his_min_opcode].protocol = NULL; } iceConn->his_max_opcode = hisOpcode; } iceConn->process_msg_info[hisOpcode - iceConn->his_min_opcode].in_use = True; iceConn->process_msg_info[hisOpcode - iceConn->his_min_opcode].my_opcode = myOpcode; iceConn->process_msg_info[hisOpcode - iceConn->his_min_opcode].protocol = &_IceProtocols[myOpcode - 1]; } char *_IceGetPeerName(iceConn) IceConn iceConn; { return ((char *)_kde_IceTransGetPeerNetworkId(iceConn->trans_conn)); }
serghei/kde3-kdelibs
dcop/KDE-ICE/misc.c
C
gpl-2.0
13,225
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <title>Andrea Madotto | Announcement_11</title> <meta name="description" content="A simple, whitespace theme for academics. Based on [*folio](https://github.com/bogoli/-folio) design. "> <!-- Open Graph --> <meta property="og:site_name" content="A simple, whitespace theme for academics. Based on [*folio](https://github.com/bogoli/-folio) design. " /> <meta property="og:type" content="object" /> <meta property="og:title" content="" /> <meta property="og:url" content="/news/announcement_11/" /> <meta property="og:description" content="Announcement_11" /> <meta property="og:image" content="" /> <!-- Bootstrap & MDB --> <link href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css" rel="stylesheet" integrity="sha512-MoRNloxbStBcD8z3M/2BmnT+rg4IsMxPkXaGh2zD6LGNNFE80W3onsAhRcMAMrSoyWL9xD7Ert0men7vR8LUZg==" crossorigin="anonymous"> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/mdbootstrap/4.19.1/css/mdb.min.css" integrity="sha512-RO38pBRxYH3SoOprtPTD86JFOclM51/XTIdEPh5j8sj4tp8jmQIx26twG52UaLi//hQldfrh7e51WzP9wuP32Q==" crossorigin="anonymous" /> <!-- Fonts & Icons --> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.14.0/css/all.min.css" integrity="sha512-1PKOgIY59xJ8Co8+NE6FZ+LOAZKjy+KY8iq0G4B3CyeY6wYHN3yt9PW0XpSriVlkMXe40PTKnXrLnZ9+fkDaog==" crossorigin="anonymous"> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/academicons/1.9.0/css/academicons.min.css" integrity="sha512-W4yqoT1+8NLkinBLBZko+dFB2ZbHsYLDdr50VElllRcNt2Q4/GSs6u71UHKxB7S6JEMCp5Ve4xjh3eGQl/HRvg==" crossorigin="anonymous"> <link rel="stylesheet" type="text/css" href="https://fonts.googleapis.com/css?family=Roboto:300,400,500,700|Roboto+Slab:100,300,400,500,700|Material+Icons"> <!-- Code Syntax Highlighting --> <link rel="stylesheet" href="https://gitcdn.link/repo/jwarby/jekyll-pygments-themes/master/github.css" /> <!-- Styles --> <link rel="shortcut icon" href="/assets/img/favicon.ico"> <link rel="stylesheet" href="/assets/css/main.css"> <link rel="canonical" href="/news/announcement_11/"> <!-- Theming--> <!-- Global site tag (gtag.js) - Google Analytics --> <script async src="https://www.googletagmanager.com/gtag/js?id=UA-80604868-2"></script> <script> window.dataLayer = window.dataLayer || []; function gtag() { dataLayer.push(arguments); } gtag('js', new Date()); gtag('config', 'UA-80604868-2'); </script> <!-- MathJax --> <script defer type="text/javascript" id="MathJax-script" src="https://cdn.jsdelivr.net/npm/mathjax@3.1.2/es5/tex-mml-chtml.js"></script> <script defer src="https://polyfill.io/v3/polyfill.min.js?features=es6"></script> </head> <body class="fixed-top-nav sticky-bottom-footer"> <!-- Header --> <header> <!-- Nav Bar --> <nav id="navbar" class="navbar navbar-light navbar-expand-sm fixed-top"> <div class="container"> <a class="navbar-brand title font-weight-lighter" href="/"> <span class="font-weight-bold">Andrea</span> Madotto </a> <!-- Navbar Toogle --> <button class="navbar-toggler collapsed ml-auto" type="button" data-toggle="collapse" data-target="#navbarNav" aria-controls="navbarNav" aria-expanded="false" aria-label="Toggle navigation"> <span class="sr-only">Toggle navigation</span> <span class="icon-bar top-bar"></span> <span class="icon-bar middle-bar"></span> <span class="icon-bar bottom-bar"></span> </button> <div class="collapse navbar-collapse text-right" id="navbarNav"> <ul class="navbar-nav ml-auto flex-nowrap"> <!-- About --> <li class="nav-item "> <a class="nav-link" href="/"> About </a> </li> <!-- Blog --> <li class="nav-item "> <a class="nav-link" href="/blog/"> Blog </a> </li> <!-- Other pages --> <li class="nav-item "> <a class="nav-link" href="/CV/"> Curriculum </a> </li> <li class="nav-item "> <a class="nav-link" href="/publications/"> Publications </a> </li> </ul> </div> </div> </nav> </header> <!-- Content --> <div class="container mt-5"> <div class="post"> <header class="post-header"> <h1 class="post-title">Announcement_11</h1> <p class="post-meta">April 3, 2021</p> </header> <article class="post-content"> <p>BiToD accepted at NeurIPS2021 Benchmark Track</p> </article> </div> </div> <!-- Footer --> <footer class="sticky-bottom mt-5"> <div class="container"> &copy; Copyright 2021 Andrea Madotto. Powered by <a href="http://jekyllrb.com/" target="_blank">Jekyll</a> with <a href="https://github.com/alshedivat/al-folio">al-folio</a> theme. Last updated: September 23, 2021. </div> </footer> </body> <!-- jQuery --> <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.5.1/jquery.min.js" integrity="sha512-bLT0Qm9VnAYZDflyKcBaQ2gg0hSYNQrJ8RilYldYQ1FxQYoCLtUjuuRuZo+fjqhx/qtq/1itJ0C2ejDxltZVFg==" crossorigin="anonymous"></script> <!-- Bootsrap & MDB scripts --> <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/2.4.4/umd/popper.min.js" integrity="sha512-eUQ9hGdLjBjY3F41CScH3UX+4JDSI9zXeroz7hJ+RteoCaY+GP/LDoM8AO+Pt+DRFw3nXqsjh9Zsts8hnYv8/A==" crossorigin="anonymous"></script> <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js" integrity="sha512-M5KW3ztuIICmVIhjSqXe01oV2bpe248gOxqmlcYrEzAvws7Pw3z6BK0iGbrwvdrUQUhi3eXgtxp5I8PDo9YfjQ==" crossorigin="anonymous"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/mdbootstrap/4.19.1/js/mdb.min.js" integrity="sha512-Mug9KHKmroQFMLm93zGrjhibM2z2Obg9l6qFG2qKjXEXkMp/VDkI4uju9m4QKPjWSwQ6O2qzZEnJDEeCw0Blcw==" crossorigin="anonymous"></script> <!-- Mansory & imagesLoaded --> <script defer src="https://unpkg.com/masonry-layout@4/dist/masonry.pkgd.min.js"></script> <script defer src="https://unpkg.com/imagesloaded@4/imagesloaded.pkgd.min.js"></script> <script defer src="/assets/js/mansory.js" type="text/javascript"></script> <!-- Load Common JS --> <script src="/assets/js/common.js"></script> <!-- Load DarkMode JS --> <script src="/assets/js/dark_mode.js"></script> </html>
andreamad8/andreamad8.github.io
news/announcement_11/index.html
HTML
gpl-2.0
6,942
"use strict"; var _ = require("lodash"); var Base = require("./Base"); var User = require("./User"); var UpdateMixin = require("./UpdateMixin"); /** * Ticket handler model for the client * * @namespace models.client * @class Handler * @extends models.client.Base * @uses models.client.UpdateMixin */ var Handler = Base.extend({ defaults: function() { return { type: "handlers", createdAt: new Date().toString() }; }, relationsMap: function() { return { handler: User }; }, url: function() { if (this.isNew()) return this.parent.url() + "/handlers"; return _.result(this.parent, "url") + "/handlers/" + this.get("handledById"); }, /** * Return the handler user object * * @method getUser * @return {models.client.User} */ getUser: function(){ return this.rel("handler"); }, }); _.extend(Handler.prototype, UpdateMixin); module.exports = Handler;
opinsys/puavo-ticket
models/client/Handler.js
JavaScript
gpl-2.0
1,015
<!DOCTYPE html> <html xmlns:MadCap="http://www.madcapsoftware.com/Schemas/MadCap.xsd" lang="en-US" xml:lang="en-US" data-mc-search-type="Stem" data-mc-help-system-file-name="Documentation.xml" data-mc-path-to-help-system="../" data-mc-target-type="WebHelp2" data-mc-runtime-file-type="Topic" data-mc-preload-images="false" data-mc-in-preview-mode="false" data-mc-toc-path="Command References|Maestro Command Reference|The Maestro Command Language"> <head> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <meta charset="utf-8" /> <meta http-equiv="X-UA-Compatible" content="IE=edge" /> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <link href="../Skins/Default/Stylesheets/Slideshow.css" rel="stylesheet" type="text/css" data-mc-generated="True" /> <link href="../Skins/Default/Stylesheets/TextEffects.css" rel="stylesheet" type="text/css" data-mc-generated="True" /> <link href="../Skins/Default/Stylesheets/Topic.css" rel="stylesheet" type="text/css" data-mc-generated="True" /> <link href="../Skins/Default/Stylesheets/Components/Styles.css" rel="stylesheet" type="text/css" data-mc-generated="True" /><title>distance</title> <link href="../Resources/Stylesheets/docs.css" rel="stylesheet" /> <script src="../Resources/Scripts/custom.modernizr.js" type="text/javascript"> </script> <script src="../Resources/Scripts/jquery.min.js" type="text/javascript"> </script> <script src="../Resources/Scripts/require.min.js" type="text/javascript"> </script> <script src="../Resources/Scripts/require.config.js" type="text/javascript"> </script> <script src="../Resources/Scripts/foundation.min.js" type="text/javascript"> </script> <script src="../Resources/Scripts/plugins.min.js" type="text/javascript"> </script> <script src="../Resources/Scripts/MadCapAll.js" type="text/javascript"> </script> </head> <body><a name="aanchor1397"></a> <MadCap:concept term="Command References" /><a name="aanchor1398"></a> <MadCap:concept term="Maestro" /> <table class="NavLink" data-mc-conditions="Default.ScreenOnly"> <tr class="NavLink"> <td class="NavLeft"><span class="NavText">◀ <a class="NavLink MCXref xref xrefNavLink" href="displaypiinteractionsmode.html" xrefformat="{paratext}">displaypiinteractionsmode</a></span> </td> <td class="NavCenter"><span class="NavText"><a class="NavLink MCXref xref xrefNavLink" href="maestro_command_referenceTOC.htm" xrefformat="{paratext}">Maestro Command Reference Manual</a></span> </td> <td class="NavRight"><span class="NavText"><a class="NavLink MCXref xref xrefNavLink" href="distancecheck.html" xrefformat="{paratext}">distancecheck</a> ▶</span> </td> </tr> </table> <h1 class="title">distance</h1> <p>Specifies a pair of atoms to have their distance measured and displayed. </p> <p>Syntax: <b>distance</b> <i>surfacename1</i>= &lt;text&gt; <i>surfacename2</i>= &lt;text&gt; <i>surfacex1</i>= &lt;x&gt; <i>surfacex2</i>= &lt;x&gt; <i>surfacey1</i>= &lt;x&gt; <i>surfacey2</i>= &lt;x&gt; <i>surfacez1</i>= &lt;x&gt; <i>surfacez2</i>= &lt;x&gt; <i>xoffset</i>= &lt;x&gt; <i>yoffset</i>= &lt;x&gt; [&lt;atom1&gt; &lt;atom2&gt; ] </p> <p>Options:</p> <dl> <dt><i>surfacename1</i> </dt> <br /> <dd>Specifies the name of surface on which atom1 sits. </dd> <br /> <dd> <table summary=""> <tr align="left"> <td valign="top">Valid values:</td> <td> text strings<br /></td> </tr> <tr align="left"> <td valign="top">Default value: </td> <td valign="top"><b>&#160;</b> <br /> </td> </tr> </table> </dd> <br /> <dt><i>surfacename2</i> </dt> <br /> <dd>Specifies the name of surface on which atom1 sits. </dd> <br /> <dd> <table summary=""> <tr align="left"> <td valign="top">Valid values:</td> <td> text strings<br /></td> </tr> <tr align="left"> <td valign="top">Default value: </td> <td valign="top"><b>&#160;</b> <br /> </td> </tr> </table> </dd> <br /> <dt><i>surfacex1</i> </dt> <br /> <dd>Specifies the X coordinate for atom1 on surface. </dd> <br /> <dd> <table summary=""> <tr align="left"> <td valign="top">Valid values:</td> <td> reals<br /></td> </tr> <tr align="left"> <td valign="top">Default value: </td> <td valign="top"><b>0</b> <br /> </td> </tr> </table> </dd> <br /> <dt><i>surfacex2</i> </dt> <br /> <dd>Specifies the X coordinate for atom2 on surface. </dd> <br /> <dd> <table summary=""> <tr align="left"> <td valign="top">Valid values:</td> <td> reals<br /></td> </tr> <tr align="left"> <td valign="top">Default value: </td> <td valign="top"><b>0</b> <br /> </td> </tr> </table> </dd> <br /> <dt><i>surfacey1</i> </dt> <br /> <dd>Specifies the Y coordinate for atom1 on surface. </dd> <br /> <dd> <table summary=""> <tr align="left"> <td valign="top">Valid values:</td> <td> reals<br /></td> </tr> <tr align="left"> <td valign="top">Default value: </td> <td valign="top"><b>0</b> <br /> </td> </tr> </table> </dd> <br /> <dt><i>surfacey2</i> </dt> <br /> <dd>Specifies the Y coordinate for atom2 on surface. </dd> <br /> <dd> <table summary=""> <tr align="left"> <td valign="top">Valid values:</td> <td> reals<br /></td> </tr> <tr align="left"> <td valign="top">Default value: </td> <td valign="top"><b>0</b> <br /> </td> </tr> </table> </dd> <br /> <dt><i>surfacez1</i> </dt> <br /> <dd>Specifies the Z coordinate for atom1 on surface. </dd> <br /> <dd> <table summary=""> <tr align="left"> <td valign="top">Valid values:</td> <td> reals<br /></td> </tr> <tr align="left"> <td valign="top">Default value: </td> <td valign="top"><b>0</b> <br /> </td> </tr> </table> </dd> <br /> <dt><i>surfacez2</i> </dt> <br /> <dd>Specifies the Z coordinate for atom2 on surface. </dd> <br /> <dd> <table summary=""> <tr align="left"> <td valign="top">Valid values:</td> <td> reals<br /></td> </tr> <tr align="left"> <td valign="top">Default value: </td> <td valign="top"><b>0</b> <br /> </td> </tr> </table> </dd> <br /> <dt><i>xoffset</i> </dt> <br /> <dd>Specifies the X offset in Angstroms. Any distance created after this value is set will use this new value. Can be applied to an existing measurement by respecifying the measurement. Does not affect any already created distances. </dd> <br /> <dd> <table summary=""> <tr align="left"> <td valign="top">Valid values:</td> <td> reals<br /></td> </tr> <tr align="left"> <td valign="top">Default value: </td> <td valign="top"><b>0</b> <br /> </td> </tr> </table> </dd> <br /> <dt><i>yoffset</i> </dt> <br /> <dd>Specifies the Y offset in Angstroms. Any distance created after this value is set will use this new value. Can be applied to an existing measurement by respecifying the measurement. Does not affect any already created distances. </dd> <br /> <dd> <table summary=""> <tr align="left"> <td valign="top">Valid values:</td> <td> reals<br /></td> </tr> <tr align="left"> <td valign="top">Default value: </td> <td valign="top"><b>0</b> <br /> </td> </tr> </table> </dd> <br /> </dl> <p>Operands:</p> <p>&lt;atom1&gt; &lt;atom2&gt; </p> <p>The two atoms between which the distance is to be measured. Note that the specifying a-b is the same as specifying b-a. </p> <table class="NavLink" data-mc-conditions="Default.ScreenOnly"> <tr class="NavLink"> <td class="NavLeft"><span class="NavText">◀ <a class="NavLink MCXref xref xrefNavLink" href="displaypiinteractionsmode.html" xrefformat="{paratext}">displaypiinteractionsmode</a></span> </td> <td class="NavCenter"><span class="NavText"><a class="NavLink MCXref xref xrefNavLink" href="maestro_command_referenceTOC.htm" xrefformat="{paratext}">Maestro Command Reference Manual</a></span> </td> <td class="NavRight"><span class="NavText"><a class="NavLink MCXref xref xrefNavLink" href="distancecheck.html" xrefformat="{paratext}">distancecheck</a> ▶</span> </td> </tr> </table> </body> </html>
platinhom/ManualHom
Schrodinger/Schrodinger_2017-1_docs/maestro_command_reference/distance.html
HTML
gpl-2.0
12,076
<?php /* * Copyright 2014 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ class Google_Service_Dialogflow_GoogleCloudDialogflowV2beta1SuggestSmartRepliesResponse extends Google_Collection { protected $collection_key = 'smartReplyAnswers'; public $contextSize; public $latestMessage; protected $smartReplyAnswersType = 'Google_Service_Dialogflow_GoogleCloudDialogflowV2beta1SmartReplyAnswer'; protected $smartReplyAnswersDataType = 'array'; public function setContextSize($contextSize) { $this->contextSize = $contextSize; } public function getContextSize() { return $this->contextSize; } public function setLatestMessage($latestMessage) { $this->latestMessage = $latestMessage; } public function getLatestMessage() { return $this->latestMessage; } /** * @param Google_Service_Dialogflow_GoogleCloudDialogflowV2beta1SmartReplyAnswer[] */ public function setSmartReplyAnswers($smartReplyAnswers) { $this->smartReplyAnswers = $smartReplyAnswers; } /** * @return Google_Service_Dialogflow_GoogleCloudDialogflowV2beta1SmartReplyAnswer[] */ public function getSmartReplyAnswers() { return $this->smartReplyAnswers; } }
palasthotel/grid-wordpress-box-social
vendor/google/apiclient-services/src/Google/Service/Dialogflow/GoogleCloudDialogflowV2beta1SuggestSmartRepliesResponse.php
PHP
gpl-2.0
1,724
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <!--<link href='https://fonts.googleapis.com/css?family=Amatic+SC' rel='stylesheet' type='text/css'>--> <link href='https://fonts.googleapis.com/css?family=Cabin' rel='stylesheet' type='text/css'> <link rel="stylesheet" href="css/bootstrap.min.css"> <link rel="stylesheet" href="css/bootstrap-theme.min.css"> <link rel="stylesheet" href="css/introjs.css"> <link rel='icon' href='img/favicon.png'> <!-- <link rel="stylesheet" href="css/bootstrap-solarized-dark.css"> --> <link rel="stylesheet" href="css/main.css"> <title>The Deadlock Empire</title> <script src="js/3rdparty/jquery.js"></script> <script src="js/3rdparty/bootstrap.min.js"></script> <script src="js/3rdparty/bootbox.min.js"></script> <script src="js/3rdparty/intro.js"></script> <script src="js/3rdparty/mousetrap.min.js"></script> <script src="js/game_state.js"></script> <script src="js/ui.js"></script> <script src="js/win.js"></script> <script src="js/common.js"></script> <script src="js/language.js"></script> <script src="js/expression.js"></script> <script src="js/variables.js"></script> <script src="js/instructions/instructions.js"></script> <script src="js/instructions/instructions-synchronization.js"></script> <script src="js/instructions/instructions-high-level-synchronization.js"></script> <script src="js/instructions/instructions-queue.js"></script> <script src="js/level.js"></script> <script src="js/thread.js">s</script> <script src="js/main.js"></script> <script src="js/menu.js"></script> <script src="js/content/levels.js"></script> <script src="js/content/dragons.js"></script> <script src="js/content/tutorial.js"></script> <script src="js/content/levels-high-level-primitives.js"></script> <script src="js/content/campaign.js"></script> <!-- Google Analytics. We are deeply sorry if you are offended by our collection of pageview data. We suggest using tracking protection - for example, modern versions of Firefox can automatically disable any tracking scripts. Thank you for playing The Deadlock Empire and we hope you can forgive us for infringing on your privacy. http://hudecekpetr.cz/friend.html --> <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-73203312-1', 'auto'); ga('send', 'pageview'); </script> <!-- Open Graph tags to customize Facebook link previews. --> <meta property="og:url" content="https://deadlockempire.github.io"> <meta property="og:title" content="The Deadlock Empire"> <meta property="og:description" content="Slay dragons, learn concurrency! Play the cunning Scheduler, exploit flawed programs and defeat the armies of the Parallel Wizard."> <meta property="og:image" content="http://deadlockempire.github.io/img/logo-large.png"> </head> <body> <!-- Load Facebook SDK for JavaScript --> <div id="fb-root"></div> <script> (function(d, s, id) { var js, fjs = d.getElementsByTagName(s)[0]; if (d.getElementById(id)) return; js = d.createElement(s); js.id = id; js.src = "//connect.facebook.net/en_US/sdk.js#xfbml=1&version=v2.2&appId=100259203407083"; fjs.parentNode.insertBefore(js, fjs); }(document, 'script', 'facebook-jssdk')); </script> <div id="mainContainer"> <div class="container"> <div id="game-window"> <div id="debug-toolbar" style="border: 1px solid black; width: 100%; margin: 2px; padding: 2px;"> This is the toolbar. | Select level: <select id="levelSelect" > </select> <button class="btn btn-default" id="start">Start</button> | <button class="btn btn-default" id="goToMain">Go To Main Menu</button> | <button class="btn btn-default" id="clearProgress">Clear Saved Progress</button> </div> <div id="mainarea"> </div> <div id="alert" style="display: none; border: 1px solid black;"> <button class="btn btn-default" id="alertHide">[Hide]</button> <span id="alertCaption" style="font-weight: bold;">Title</span><br> <span id="alertText">This is the alert message.</span> </div> <footer> <span class="fb-share-button" data-href="https://deadlockempire.github.io" data-layout="button_count"> </span> <span id="credits"> Got any ideas or feedback? Both are much appreciated at <a href="http://goo.gl/forms/i05ukNUMmB">this form</a>.<br> GitHub: <a href="https://github.com/deadlockempire/deadlockempire.github.io">deadlockempire/deadlockempire.github.io</a>. Made by <a href="http://hudecekpetr.cz">Petr Hudeček</a> and <a href="http://rny.cz">Michal Pokorný</a> at HackCambridge 2016. </span> </footer> </div> </div> <div id="win-screen"> <div class="container"> <div class="top-section"> <span class="icon glyphicon glyphicon-ok"></span> <h3> <span id="win-congratulation"> You win! </span> </h3> <div class="victory-condition"> </div> </div> <div class="win-part"> <div id="win-message"></div> </div> <div class="buttons"> <button id="dismiss-win" class="btn btn-default">Back to the code</button> <button id="win-go-to-menu" class="btn btn-default">Return to Main Menu</button> <button id="win-next-level" class="btn btn-primary">Next challenge&nbsp; <span class="glyphicon glyphicon-chevron-right"></span></button> </div> </div> </div> <div id="lose-screen"> <div class="container"> <div class="top-section"> <span class="icon glyphicon glyphicon-remove"></span> <h3> <span id="fail-heading"> Challenge lost! </span> </h3> </div> <div class="lose-part"> <div id="lose-message"></div> <div class="failure-condition"> </div> </div> <div class="buttons"> <button id="lose-restart" class="btn btn-primary">Reset and try again</button> <button id="lose-step-back" class="btn btn-default">Return to code and undo last step</button> <button id="lose-go-to-menu" class="btn btn-default">Return to Main Menu</button> </div> </div> </div> </div> </body> </html>
deadlockempire/deadlockempire.github.io
index.html
HTML
gpl-2.0
6,972
.cuztom { width: 100%; } .cuztom .cuztom-box-description { padding-bottom: 10px; border-bottom: 1px solid #dfdfdf; font-style: italic; } .cuztom .cuztom-tabs { padding-top: 10px; } .cuztom .js-cuztom-remove-media { display: inline-block; margin-left: 10px; } .cuztom .cuztom-ajax-save { display: inline-block; vertical-align: middle; height: 23px; } /* Wraps */ .cuztom .padding-wrap { padding: 5px 0 0 0; } .cuztom .wp-editor-wrap { margin-bottom: 10px; } .cuztom .cuztom-checkboxes-wrap { width: 30%; margin-right: 10px; display: inline-block; vertical-align: middle; max-height: 100px; overflow-y: scroll; overflow-x: hidden; } .cuztom .cuztom-checkbox-wrap { width: 10%; margin-right: 10px; display: inline-block; vertical-align: middle; } /* Tabs */ .cuztom .cuztom-tabs .ui-state-active { border-color: #ccc; background: #fff; } .cuztom .cuztom-tabs .ui-state-active a { color: #d54e21; } /* Table */ .cuztom .cuztom-table { width: 100%; margin-top: 0; } .cuztom .cuztom-table th { font-weight: normal; text-align: left; vertical-align: top; } .cuztom .cuztom-table th label { font-size: 12px; font-weight: bold; } .cuztom .cuztom-table th .cuztom-required { color: red; } .cuztom .cuztom-table th .cuztom-description, .cuztom .cuztom-table td .cuztom-explanation { font-size: 10px; font-style: italic; font-weight: normal; } .cuztom .cuztom-table td .cuztom-explanation { display: block; } /* Sortable */ .cuztom .cuztom-handle-sortable, .cuztom .cuztom-remove-sortable { display: inline-block; vertical-align: middle; height: 16px; width: 16px; background: url('../images/jquery-ui/ui-icons_454545_256x240.png') no-repeat; } .cuztom .cuztom-handle-sortable { background-position: -132px -48px; cursor: move; } .cuztom .cuztom-remove-sortable { background-position: -77px -128px; cursor: pointer; } .cuztom .cuztom-sortable-item fieldset { display: inline-block; vertical-align: middle; border: 1px solid #ccc; padding: 10px; border-radius: 2px; -webkit-border-radius: 2px; -moz-border-radius: 2px; width: 90%; } /* Input */ .cuztom textarea, .cuztom input[type="text"] { width: 80%; display: inline-block; vertical-align: middle; } .cuztom textarea { height: 100px; } .cuztom select { min-width: 160px; } .cuztom .cuztom-preview { width: 100%; display: block; margin-top: 8px; } .cuztom .cuztom-preview img { max-width: 100%; height: auto; } .cuztom .mceContentBody, .cuztom .mceIframeContainer { background: #fff !important; } .cuztom .mceStatusbar { width: 100% !important; padding-left: 0 !important; text-indent: 10px; } .cuztom.form-field input[type="button"] { width: auto; } /* Misc */ .cuztom .cuztom-mime { padding: 5px 0 5px 25px; display: block; background: url('../images/mime/file.png') 0 2px no-repeat; } .cuztom .wp-picker-container { width: 100%; } .cuztom input[type="text"].wp-color-picker, .cuztom .wp-picker-clear { width: auto; } .cuztom .iris-picker .iris-slider-offset { position: absolute; top: 0px; left: 0; width: 100%; height: 100%; background: none; border: none; } /* Responsive wysiwyg editor */ .cuztom .tmce-active table { max-width: none; } .cuztom .tmce-active table.mceLayout, .cuztom table.mceToolbar { width: 100% !important; height: auto !important; } .cuztom .tmce-active span.mceEditor { display: block !important; } .cuztom .mceToolbar div, .cuztom table.mceToolbar tr { white-space: normal; } .cuztom table.mceToolbar td { display: inline-block; white-space: normal; } /* Side meta box */ #side-sortables .cuztom-table { } #side-sortables .cuztom-table th { padding: 0 0 10px 0; width: 30%; } #side-sortables .cuztom-table td { padding: 0 0 10px 0; width: 70%; } #side-sortables .cuztom-table .cuztom-description, #side-sortables .cuztom-table .cuztom-explanation { display: none; } #side-sortables .cuztom-table .cuztom-input, #side-sortables .cuztom-table .cuztom-checkbox-wrap, #side-sortables .cuztom-table .cuztom-checkboxes-wrap { width: 100%; } #side-sortables .cuztom-table input[type="radio"].cuztom-input, #side-sortables .cuztom-table input[type="checkbox"].cuztom-input { width: auto; } #side-sortables .cuztom-table .cuztom-colorpicker { width: 80%; } #side-sortables .cuztom-table .cuztom-ajax-save { clear: both; } #side-sortables .cuztom-table .cuztom-remove-media { margin-left: 0; }
JeremyCarlsten/WordpressWork
wp-content/plugins/brs-booking-reservation-system-woocommerce/includes/vendor/cuztom/assets/css/style.css
CSS
gpl-2.0
4,693
/* * atmel-pcm.c -- ALSA PCM interface for the Atmel atmel SoC. * * Copyright (C) 2005 SAN People * Copyright (C) 2008 Atmel * * Authors: Sedji Gaouaou <sedji.gaouaou@atmel.com> * * Based on at91-pcm. by: * Frank Mandarino <fmandarino@endrelia.com> * Copyright 2006 Endrelia Technologies Inc. * * Based on pxa2xx-pcm.c by: * * Author: Nicolas Pitre * Created: Nov 30, 2004 * Copyright: (C) 2004 MontaVista Software, Inc. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ #include <linux/module.h> #include <linux/dma-mapping.h> #include <sound/pcm.h> #include <sound/soc.h> #include "atmel-pcm.h" static int atmel_pcm_preallocate_dma_buffer(struct snd_pcm *pcm, int stream) { struct snd_pcm_substream *substream = pcm->streams[stream].substream; struct snd_dma_buffer *buf = &substream->dma_buffer; size_t size = ATMEL_SSC_DMABUF_SIZE; buf->dev.type = SNDRV_DMA_TYPE_DEV; buf->dev.dev = pcm->card->dev; buf->private_data = NULL; buf->area = dma_alloc_coherent(pcm->card->dev, size, &buf->addr, GFP_KERNEL); pr_debug("atmel-pcm: alloc dma buffer: area=%p, addr=%p, size=%zu\n", (void *)buf->area, (void *)buf->addr, size); if (!buf->area) return -ENOMEM; buf->bytes = size; return 0; } int atmel_pcm_mmap(struct snd_pcm_substream *substream, struct vm_area_struct *vma) { return remap_pfn_range(vma, vma->vm_start, substream->dma_buffer.addr >> PAGE_SHIFT, vma->vm_end - vma->vm_start, vma->vm_page_prot); } EXPORT_SYMBOL_GPL(atmel_pcm_mmap); static u64 atmel_pcm_dmamask = DMA_BIT_MASK(32); int atmel_pcm_new(struct snd_soc_pcm_runtime *rtd) { struct snd_card *card = rtd->card->snd_card; struct snd_pcm *pcm = rtd->pcm; int ret = 0; if (!card->dev->dma_mask) card->dev->dma_mask = &atmel_pcm_dmamask; if (!card->dev->coherent_dma_mask) card->dev->coherent_dma_mask = DMA_BIT_MASK(32); if (pcm->streams[SNDRV_PCM_STREAM_PLAYBACK].substream) { pr_debug("atmel-pcm: allocating PCM playback DMA buffer\n"); ret = atmel_pcm_preallocate_dma_buffer(pcm, SNDRV_PCM_STREAM_PLAYBACK); if (ret) goto out; } if (pcm->streams[SNDRV_PCM_STREAM_CAPTURE].substream) { pr_debug("atmel-pcm: allocating PCM capture DMA buffer\n"); ret = atmel_pcm_preallocate_dma_buffer(pcm, SNDRV_PCM_STREAM_CAPTURE); if (ret) goto out; } out: return ret; } EXPORT_SYMBOL_GPL(atmel_pcm_new); void atmel_pcm_free(struct snd_pcm *pcm) { struct snd_pcm_substream *substream; struct snd_dma_buffer *buf; int stream; for (stream = 0; stream < 2; stream++) { substream = pcm->streams[stream].substream; if (!substream) continue; buf = &substream->dma_buffer; if (!buf->area) continue; dma_free_coherent(pcm->card->dev, buf->bytes, buf->area, buf->addr); buf->area = NULL; } } EXPORT_SYMBOL_GPL(atmel_pcm_free);
evolver56k/xpenology
sound/soc/atmel/atmel-pcm.c
C
gpl-2.0
3,483
<?php $file = $_REQUEST['filepath']; if (file_exists($file)) { header('Content-Type: text/html'); header('Content-Encoding: gzip'); header('Content-Length: ' . filesize($file)); ob_clean(); flush(); readfile($file); exit; } ?>
davidguillemet/fashionphotosub
getCacheFile.php
PHP
gpl-2.0
247
package org.cad.interruptus.core.zookeeper; import org.apache.curator.framework.CuratorFramework; public interface ZookeeperLifecycleListener { public void onStart(CuratorFramework curator) throws Exception; public void onStop(CuratorFramework curator) throws Exception; }
interruptus/interruptus
src/main/java/org/cad/interruptus/core/zookeeper/ZookeeperLifecycleListener.java
Java
gpl-2.0
282
/* * Copyright (C) 2005-2009 MaNGOS <http://getmangos.com/> * * Copyright (C) 2008-2010 Trinity <http://www.trinitycore.org/> * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ #include "Common.h" #include "Log.h" #include "Configuration/Config.h" #include "Util.h" #include "Implementation/LoginDatabase.h" // For logging extern LoginDatabaseWorkerPool LoginDatabase; #include <stdarg.h> #include <stdio.h> Log::Log() : raLogfile(NULL), logfile(NULL), gmLogfile(NULL), charLogfile(NULL), dberLogfile(NULL), chatLogfile(NULL), arenaLogFile(NULL), sqlLogFile(NULL), m_gmlog_per_account(false), m_enableLogDBLater(false), m_enableLogDB(false), m_colored(false) { Initialize(); } Log::~Log() { if( logfile != NULL ) fclose(logfile); logfile = NULL; if( gmLogfile != NULL ) fclose(gmLogfile); gmLogfile = NULL; if (charLogfile != NULL) fclose(charLogfile); charLogfile = NULL; if( dberLogfile != NULL ) fclose(dberLogfile); dberLogfile = NULL; if (raLogfile != NULL) fclose(raLogfile); raLogfile = NULL; if (chatLogfile != NULL) fclose(chatLogfile); chatLogfile = NULL; if (arenaLogFile != NULL) fclose(arenaLogFile); arenaLogFile = NULL; if (sqlLogFile != NULL) fclose(sqlLogFile); sqlLogFile = NULL; } void Log::SetLogLevel(char *Level) { int32 NewLevel =atoi((char*)Level); if ( NewLevel <0 ) NewLevel = 0; m_logLevel = NewLevel; outString( "LogLevel is %u",m_logLevel ); } void Log::SetLogFileLevel(char *Level) { int32 NewLevel =atoi((char*)Level); if ( NewLevel <0 ) NewLevel = 0; m_logFileLevel = NewLevel; outString( "LogFileLevel is %u",m_logFileLevel ); } void Log::SetDBLogLevel(char *Level) { int32 NewLevel = atoi((char*)Level); if ( NewLevel < 0 ) NewLevel = 0; m_dbLogLevel = NewLevel; outString( "DBLogLevel is %u",m_dbLogLevel ); } void Log::Initialize() { /// Check whether we'll log GM commands/RA events/character outputs/chat stuffs m_dbChar = sConfig.GetBoolDefault("LogDB.Char", false); m_dbRA = sConfig.GetBoolDefault("LogDB.RA", false); m_dbGM = sConfig.GetBoolDefault("LogDB.GM", false); m_dbChat = sConfig.GetBoolDefault("LogDB.Chat", false); /// Realm must be 0 by default SetRealmID(0); /// Common log files data m_logsDir = sConfig.GetStringDefault("LogsDir",""); if (!m_logsDir.empty()) if ((m_logsDir.at(m_logsDir.length() - 1) != '/') && (m_logsDir.at(m_logsDir.length() - 1) != '\\')) m_logsDir.append("/"); m_logsTimestamp = "_" + GetTimestampStr(); /// Open specific log files logfile = openLogFile("LogFile","LogTimestamp","w"); InitColors(sConfig.GetStringDefault("LogColors", "")); m_gmlog_per_account = sConfig.GetBoolDefault("GmLogPerAccount",false); if(!m_gmlog_per_account) gmLogfile = openLogFile("GMLogFile","GmLogTimestamp","a"); else { // GM log settings for per account case m_gmlog_filename_format = sConfig.GetStringDefault("GMLogFile", ""); if(!m_gmlog_filename_format.empty()) { bool m_gmlog_timestamp = sConfig.GetBoolDefault("GmLogTimestamp",false); size_t dot_pos = m_gmlog_filename_format.find_last_of("."); if(dot_pos!=m_gmlog_filename_format.npos) { if(m_gmlog_timestamp) m_gmlog_filename_format.insert(dot_pos,m_logsTimestamp); m_gmlog_filename_format.insert(dot_pos,"_#%u"); } else { m_gmlog_filename_format += "_#%u"; if(m_gmlog_timestamp) m_gmlog_filename_format += m_logsTimestamp; } m_gmlog_filename_format = m_logsDir + m_gmlog_filename_format; } } charLogfile = openLogFile("CharLogFile", "CharLogTimestamp", "a"); dberLogfile = openLogFile("DBErrorLogFile", NULL, "a"); raLogfile = openLogFile("RaLogFile", NULL, "a"); chatLogfile = openLogFile("ChatLogFile", "ChatLogTimestamp", "a"); arenaLogFile = openLogFile("ArenaLogFile", NULL,"a"); sqlLogFile = openLogFile("SQLDriverLogFile", NULL, "a"); // Main log file settings m_logLevel = sConfig.GetIntDefault("LogLevel", LOGL_NORMAL); m_logFileLevel = sConfig.GetIntDefault("LogFileLevel", LOGL_NORMAL); m_dbLogLevel = sConfig.GetIntDefault("DBLogLevel", LOGL_NORMAL); m_logFilter = 0; if(sConfig.GetBoolDefault("LogFilter_TransportMoves", true)) m_logFilter |= LOG_FILTER_TRANSPORT_MOVES; if(sConfig.GetBoolDefault("LogFilter_CreatureMoves", true)) m_logFilter |= LOG_FILTER_CREATURE_MOVES; if(sConfig.GetBoolDefault("LogFilter_VisibilityChanges", true)) m_logFilter |= LOG_FILTER_VISIBILITY_CHANGES; if(sConfig.GetBoolDefault("LogFilter_AchievementUpdates", true)) m_logFilter |= LOG_FILTER_ACHIEVEMENT_UPDATES; // Char log settings m_charLog_Dump = sConfig.GetBoolDefault("CharLogDump", false); m_charLog_Dump_Separate = sConfig.GetBoolDefault("CharLogDump.Separate", false); if (m_charLog_Dump_Separate) { m_dumpsDir = sConfig.GetStringDefault("CharLogDump.SeparateDir", ""); if (!m_dumpsDir.empty()) if ((m_dumpsDir.at(m_dumpsDir.length() - 1) != '/') && (m_dumpsDir.at(m_dumpsDir.length() - 1) != '\\')) m_dumpsDir.append("/"); } } FILE* Log::openLogFile(char const* configFileName,char const* configTimeStampFlag, char const* mode) { std::string logfn=sConfig.GetStringDefault(configFileName, ""); if(logfn.empty()) return NULL; if(configTimeStampFlag && sConfig.GetBoolDefault(configTimeStampFlag,false)) { size_t dot_pos = logfn.find_last_of("."); if(dot_pos!=logfn.npos) logfn.insert(dot_pos,m_logsTimestamp); else logfn += m_logsTimestamp; } return fopen((m_logsDir+logfn).c_str(), mode); } FILE* Log::openGmlogPerAccount(uint32 account) { if(m_gmlog_filename_format.empty()) return NULL; char namebuf[TRINITY_PATH_MAX]; snprintf(namebuf,TRINITY_PATH_MAX,m_gmlog_filename_format.c_str(),account); return fopen(namebuf, "a"); } void Log::outTimestamp(FILE* file) { time_t t = time(NULL); tm* aTm = localtime(&t); // YYYY year // MM month (2 digits 01-12) // DD day (2 digits 01-31) // HH hour (2 digits 00-23) // MM minutes (2 digits 00-59) // SS seconds (2 digits 00-59) fprintf(file,"%-4d-%02d-%02d %02d:%02d:%02d ",aTm->tm_year+1900,aTm->tm_mon+1,aTm->tm_mday,aTm->tm_hour,aTm->tm_min,aTm->tm_sec); } void Log::InitColors(const std::string& str) { if(str.empty()) { m_colored = false; return; } int color[4]; std::istringstream ss(str); for (uint8 i = 0; i < LogLevels; ++i) { ss >> color[i]; if(!ss) return; if(color[i] < 0 || color[i] >= Colors) return; } for (uint8 i = 0; i < LogLevels; ++i) m_colors[i] = ColorTypes(color[i]); m_colored = true; } void Log::SetColor(bool stdout_stream, ColorTypes color) { #if PLATFORM == PLATFORM_WINDOWS static WORD WinColorFG[Colors] = { 0, // BLACK FOREGROUND_RED, // RED FOREGROUND_GREEN, // GREEN FOREGROUND_RED | FOREGROUND_GREEN, // BROWN FOREGROUND_BLUE, // BLUE FOREGROUND_RED | FOREGROUND_BLUE,// MAGENTA FOREGROUND_GREEN | FOREGROUND_BLUE, // CYAN FOREGROUND_RED | FOREGROUND_GREEN | FOREGROUND_BLUE,// WHITE // YELLOW FOREGROUND_RED | FOREGROUND_GREEN | FOREGROUND_INTENSITY, // RED_BOLD FOREGROUND_RED | FOREGROUND_INTENSITY, // GREEN_BOLD FOREGROUND_GREEN | FOREGROUND_INTENSITY, FOREGROUND_BLUE | FOREGROUND_INTENSITY, // BLUE_BOLD // MAGENTA_BOLD FOREGROUND_RED | FOREGROUND_BLUE | FOREGROUND_INTENSITY, // CYAN_BOLD FOREGROUND_GREEN | FOREGROUND_BLUE | FOREGROUND_INTENSITY, // WHITE_BOLD FOREGROUND_RED | FOREGROUND_GREEN | FOREGROUND_BLUE | FOREGROUND_INTENSITY }; HANDLE hConsole = GetStdHandle(stdout_stream ? STD_OUTPUT_HANDLE : STD_ERROR_HANDLE ); SetConsoleTextAttribute(hConsole, WinColorFG[color]); #else enum ANSITextAttr { TA_NORMAL=0, TA_BOLD=1, TA_BLINK=5, TA_REVERSE=7 }; enum ANSIFgTextAttr { FG_BLACK=30, FG_RED, FG_GREEN, FG_BROWN, FG_BLUE, FG_MAGENTA, FG_CYAN, FG_WHITE, FG_YELLOW }; enum ANSIBgTextAttr { BG_BLACK=40, BG_RED, BG_GREEN, BG_BROWN, BG_BLUE, BG_MAGENTA, BG_CYAN, BG_WHITE }; static uint8 UnixColorFG[Colors] = { FG_BLACK, // BLACK FG_RED, // RED FG_GREEN, // GREEN FG_BROWN, // BROWN FG_BLUE, // BLUE FG_MAGENTA, // MAGENTA FG_CYAN, // CYAN FG_WHITE, // WHITE FG_YELLOW, // YELLOW FG_RED, // LRED FG_GREEN, // LGREEN FG_BLUE, // LBLUE FG_MAGENTA, // LMAGENTA FG_CYAN, // LCYAN FG_WHITE // LWHITE }; fprintf((stdout_stream? stdout : stderr), "\x1b[%d%sm", UnixColorFG[color], (color >= YELLOW && color < Colors ? ";1" : "")); #endif } void Log::ResetColor(bool stdout_stream) { #if PLATFORM == PLATFORM_WINDOWS HANDLE hConsole = GetStdHandle(stdout_stream ? STD_OUTPUT_HANDLE : STD_ERROR_HANDLE ); SetConsoleTextAttribute(hConsole, FOREGROUND_BLUE | FOREGROUND_GREEN | FOREGROUND_RED ); #else fprintf(( stdout_stream ? stdout : stderr ), "\x1b[0m"); #endif } std::string Log::GetTimestampStr() { time_t t = time(NULL); tm* aTm = localtime(&t); // YYYY year // MM month (2 digits 01-12) // DD day (2 digits 01-31) // HH hour (2 digits 00-23) // MM minutes (2 digits 00-59) // SS seconds (2 digits 00-59) char buf[20]; snprintf(buf,20,"%04d-%02d-%02d_%02d-%02d-%02d",aTm->tm_year+1900,aTm->tm_mon+1,aTm->tm_mday,aTm->tm_hour,aTm->tm_min,aTm->tm_sec); return std::string(buf); } void Log::outDB(LogTypes type, const char * str) { if (!str || type >= MAX_LOG_TYPES) return; std::string new_str(str); if (new_str.empty()) return; LoginDatabase.escape_string(new_str); LoginDatabase.PExecute("INSERT INTO logs (time, realm, type, string) " "VALUES (" UI64FMTD ", %u, %u, '%s');", uint64(time(0)), realm, type, new_str.c_str()); } void Log::outString(const char * str, ...) { if (!str) return; if (m_enableLogDB) { // we don't want empty strings in the DB std::string s(str); if (s.empty() || s == " ") return; va_list ap2; va_start(ap2, str); char nnew_str[MAX_QUERY_LEN]; vsnprintf(nnew_str, MAX_QUERY_LEN, str, ap2); outDB(LOG_TYPE_STRING, nnew_str); va_end(ap2); } if (m_colored) SetColor(true,m_colors[LOGL_NORMAL]); va_list ap; va_start(ap, str); vutf8printf(stdout, str, &ap); va_end(ap); if (m_colored) ResetColor(true); printf("\n"); if(logfile) { outTimestamp(logfile); va_start(ap, str); vfprintf(logfile, str, ap); fprintf(logfile, "\n"); va_end(ap); fflush(logfile); } fflush(stdout); } void Log::outString() { printf("\n"); if (logfile) { outTimestamp(logfile); fprintf(logfile, "\n"); fflush(logfile); } fflush(stdout); } void Log::outCrash(const char * err, ...) { if (!err) return; if (m_enableLogDB) { va_list ap2; va_start(ap2, err); char nnew_str[MAX_QUERY_LEN]; vsnprintf(nnew_str, MAX_QUERY_LEN, err, ap2); outDB(LOG_TYPE_CRASH, nnew_str); va_end(ap2); } if (m_colored) SetColor(false,LRED); va_list ap; va_start(ap, err); vutf8printf(stderr, err, &ap); va_end(ap); if (m_colored) ResetColor(false); fprintf(stderr, "\n"); if (logfile) { outTimestamp(logfile); fprintf(logfile, "CRASH ALERT: "); va_start(ap, err); vfprintf(logfile, err, ap); va_end(ap); fprintf(logfile, "\n"); fflush(logfile); } fflush(stderr); } void Log::outError(const char * err, ...) { if (!err) return; if (m_enableLogDB) { va_list ap2; va_start(ap2, err); char nnew_str[MAX_QUERY_LEN]; vsnprintf(nnew_str, MAX_QUERY_LEN, err, ap2); outDB(LOG_TYPE_ERROR, nnew_str); va_end(ap2); } if (m_colored) SetColor(false,LRED); va_list ap; va_start(ap, err); vutf8printf(stderr, err, &ap); va_end(ap); if (m_colored) ResetColor(false); fprintf( stderr, "\n"); if (logfile) { outTimestamp(logfile); fprintf(logfile, "ERROR: "); va_start(ap, err); vfprintf(logfile, err, ap); va_end(ap); fprintf(logfile, "\n"); fflush(logfile); } fflush(stderr); } void Log::outArena(const char * str, ...) { if (!str) return; if (arenaLogFile) { va_list ap; outTimestamp(arenaLogFile); va_start(ap, str); vfprintf(arenaLogFile, str, ap); fprintf(arenaLogFile, "\n"); va_end(ap); fflush(arenaLogFile); } } void Log::outSQLDriver(const char* str, ...) { if (!str) return; va_list ap; va_start(ap, str); vutf8printf(stdout, str, &ap); va_end(ap); printf("\n"); if (sqlLogFile) { outTimestamp(sqlLogFile); va_list ap; va_start(ap, str); vfprintf(sqlLogFile, str, ap); va_end(ap); fprintf(sqlLogFile, "\n"); fflush(sqlLogFile); } fflush(stdout); } void Log::outErrorDb(const char * err, ...) { if (!err) return; if (m_colored) SetColor(false,LRED); va_list ap; va_start(ap, err); vutf8printf(stderr, err, &ap); va_end(ap); if (m_colored) ResetColor(false); fprintf( stderr, "\n" ); if (logfile) { outTimestamp(logfile); fprintf(logfile, "ERROR: " ); va_start(ap, err); vfprintf(logfile, err, ap); va_end(ap); fprintf(logfile, "\n" ); fflush(logfile); } if (dberLogfile) { outTimestamp(dberLogfile); va_start(ap, err); vfprintf(dberLogfile, err, ap); va_end(ap); fprintf(dberLogfile, "\n" ); fflush(dberLogfile); } fflush(stderr); } void Log::outBasic(const char * str, ...) { if (!str) return; if (m_enableLogDB && m_dbLogLevel > LOGL_NORMAL) { va_list ap2; va_start(ap2, str); char nnew_str[MAX_QUERY_LEN]; vsnprintf(nnew_str, MAX_QUERY_LEN, str, ap2); outDB(LOG_TYPE_BASIC, nnew_str); va_end(ap2); } if (m_logLevel > LOGL_NORMAL) { if (m_colored) SetColor(true,m_colors[LOGL_BASIC]); va_list ap; va_start(ap, str); vutf8printf(stdout, str, &ap); va_end(ap); if (m_colored) ResetColor(true); printf("\n"); if (logfile) { outTimestamp(logfile); va_list ap; va_start(ap, str); vfprintf(logfile, str, ap); fprintf(logfile, "\n" ); va_end(ap); fflush(logfile); } } fflush(stdout); } void Log::outDetail(const char * str, ...) { if (!str) return; if (m_enableLogDB && m_dbLogLevel > LOGL_BASIC) { va_list ap2; va_start(ap2, str); char nnew_str[MAX_QUERY_LEN]; vsnprintf(nnew_str, MAX_QUERY_LEN, str, ap2); outDB(LOG_TYPE_DETAIL, nnew_str); va_end(ap2); } if (m_logLevel > LOGL_BASIC) { if (m_colored) SetColor(true,m_colors[LOGL_DETAIL]); va_list ap; va_start(ap, str); vutf8printf(stdout, str, &ap); va_end(ap); if (m_colored) ResetColor(true); printf("\n"); if (logfile) { outTimestamp(logfile); va_list ap; va_start(ap, str); vfprintf(logfile, str, ap); va_end(ap); fprintf(logfile, "\n"); fflush(logfile); } } fflush(stdout); } void Log::outDebugInLine(const char * str, ...) { if (!str) return; if (m_logLevel > LOGL_DETAIL) { va_list ap; va_start(ap, str); vutf8printf(stdout, str, &ap); va_end(ap); //if(m_colored) // ResetColor(true); if (logfile) { va_list ap; va_start(ap, str); vfprintf(logfile, str, ap); va_end(ap); } } } void Log::outDebug(const char * str, ...) { if (!str) return; if (m_enableLogDB && m_dbLogLevel > LOGL_DETAIL) { va_list ap2; va_start(ap2, str); char nnew_str[MAX_QUERY_LEN]; vsnprintf(nnew_str, MAX_QUERY_LEN, str, ap2); outDB(LOG_TYPE_DEBUG, nnew_str); va_end(ap2); } if( m_logLevel > LOGL_DETAIL ) { if (m_colored) SetColor(true,m_colors[LOGL_DEBUG]); va_list ap; va_start(ap, str); vutf8printf(stdout, str, &ap); va_end(ap); if(m_colored) ResetColor(true); printf( "\n" ); if (logfile) { outTimestamp(logfile); va_list ap; va_start(ap, str); vfprintf(logfile, str, ap); va_end(ap); fprintf(logfile, "\n" ); fflush(logfile); } } fflush(stdout); } void Log::outStaticDebug(const char * str, ...) { if (!str) return; if (m_enableLogDB && m_dbLogLevel > LOGL_DETAIL) { va_list ap2; va_start(ap2, str); char nnew_str[MAX_QUERY_LEN]; vsnprintf(nnew_str, MAX_QUERY_LEN, str, ap2); outDB(LOG_TYPE_DEBUG, nnew_str); va_end(ap2); } if( m_logLevel > LOGL_DETAIL ) { if (m_colored) SetColor(true,m_colors[LOGL_DEBUG]); va_list ap; va_start(ap, str); vutf8printf(stdout, str, &ap); va_end(ap); if(m_colored) ResetColor(true); printf( "\n" ); if (logfile) { outTimestamp(logfile); va_list ap; va_start(ap, str); vfprintf(logfile, str, ap); va_end(ap); fprintf(logfile, "\n" ); fflush(logfile); } } fflush(stdout); } void Log::outStringInLine(const char * str, ...) { if (!str) return; va_list ap; va_start(ap, str); vutf8printf(stdout, str, &ap); va_end(ap); if (logfile) { va_start(ap, str); vfprintf(logfile, str, ap); va_end(ap); } } void Log::outCommand(uint32 account, const char * str, ...) { if (!str) return; // TODO: support accountid if (m_enableLogDB && m_dbGM) { va_list ap2; va_start(ap2, str); char nnew_str[MAX_QUERY_LEN]; vsnprintf(nnew_str, MAX_QUERY_LEN, str, ap2); outDB(LOG_TYPE_GM, nnew_str); va_end(ap2); } if (m_logLevel > LOGL_NORMAL) { if (m_colored) SetColor(true,m_colors[LOGL_BASIC]); va_list ap; va_start(ap, str); vutf8printf(stdout, str, &ap); va_end(ap); if (m_colored) ResetColor(true); printf("\n"); if (logfile) { outTimestamp(logfile); va_list ap; va_start(ap, str); vfprintf(logfile, str, ap); fprintf(logfile, "\n" ); va_end(ap); fflush(logfile); } } if (m_gmlog_per_account) { if (FILE* per_file = openGmlogPerAccount (account)) { outTimestamp(per_file); va_list ap; va_start(ap, str); vfprintf(per_file, str, ap); fprintf(per_file, "\n" ); va_end(ap); fclose(per_file); } } else if (gmLogfile) { outTimestamp(gmLogfile); va_list ap; va_start(ap, str); vfprintf(gmLogfile, str, ap); fprintf(gmLogfile, "\n" ); va_end(ap); fflush(gmLogfile); } fflush(stdout); } void Log::outChar(const char * str, ...) { if (!str) return; if (m_enableLogDB && m_dbChar) { va_list ap2; va_start(ap2, str); char nnew_str[MAX_QUERY_LEN]; vsnprintf(nnew_str, MAX_QUERY_LEN, str, ap2); outDB(LOG_TYPE_CHAR, nnew_str); va_end(ap2); } if (charLogfile) { outTimestamp(charLogfile); va_list ap; va_start(ap, str); vfprintf(charLogfile, str, ap); fprintf(charLogfile, "\n" ); va_end(ap); fflush(charLogfile); } } void Log::outCharDump(const char * str, uint32 account_id, uint32 guid, const char * name) { FILE *file = NULL; if (m_charLog_Dump_Separate) { char fileName[29]; // Max length: name(12) + guid(11) + _.log (5) + \0 snprintf(fileName, 29, "%d_%s.log", guid, name); std::string sFileName(m_dumpsDir); sFileName.append(fileName); file = fopen((m_logsDir + sFileName).c_str(), "w"); } else file = charLogfile; if (file) { fprintf(file, "== START DUMP == (account: %u guid: %u name: %s )\n%s\n== END DUMP ==\n", account_id, guid, name, str); fflush(file); if (m_charLog_Dump_Separate) fclose(file); } } void Log::outRemote(const char * str, ...) { if (!str) return; if (m_enableLogDB && m_dbRA) { va_list ap2; va_start(ap2, str); char nnew_str[MAX_QUERY_LEN]; vsnprintf(nnew_str, MAX_QUERY_LEN, str, ap2); outDB(LOG_TYPE_RA, nnew_str); va_end(ap2); } if (raLogfile) { outTimestamp(raLogfile); va_list ap; va_start(ap, str); vfprintf(raLogfile, str, ap); fprintf(raLogfile, "\n" ); va_end(ap); fflush(raLogfile); } } void Log::outChat(const char * str, ...) { if (!str) return; if (m_enableLogDB && m_dbChat) { va_list ap2; va_start(ap2, str); char nnew_str[MAX_QUERY_LEN]; vsnprintf(nnew_str, MAX_QUERY_LEN, str, ap2); outDB(LOG_TYPE_CHAT, nnew_str); va_end(ap2); } if (chatLogfile) { outTimestamp(chatLogfile); va_list ap; va_start(ap, str); vfprintf(chatLogfile, str, ap); fprintf(chatLogfile, "\n" ); fflush(chatLogfile); va_end(ap); } }
milleniumcore/CactusEMU
src/server/shared/Logging/Log.cpp
C++
gpl-2.0
25,343
--- layout: default title: (unrecognied function)(FIXME!) --- [Top](../index.html) --- ### 定義場所(file name) hotspot/src/share/vm/runtime/fieldDescriptor.hpp ### 名前(function name) ``` void set_is_field_access_watched(const bool value) ``` ### 本体部(body) ``` {- ------------------------------------------- (1) value 引数の価に応じて, _access_flags の JVM_ACC_FIELD_ACCESS_WATCHED ビットを立てる(あるいはクリアする)だけ. ---------------------------------------- -} { _access_flags.set_is_field_access_watched(value); } ```
hsmemo/hsmemo.github.com
articles/no2935Pyt.md
Markdown
gpl-2.0
627
<?php use Illuminate\Database\Seeder; use Illuminate\Database\Eloquent\Model; use Illuminate\Support\Facades\DB; class lov_modules extends Seeder { /** * Run the database seeds. * * @return void */ public function run() { Model::unguard(); DB::table('lov_modules')->insert(array( array('id' => '1','module_name' => 'dashboard','icon' => 'fa-dashboard','menu_show' => '1','menu_order' => '0','status' => '1','deleted_at' => '2016-04-04 02:28:48','created_at' => '0000-00-00 00:00:00','updated_at' => '0000-00-00 00:00:00'), array('id' => '2','module_name' => 'facilities','icon' => 'fa-hospital-o','menu_show' => '1','menu_order' => '10001','status' => '1','deleted_at' => '2016-04-04 02:28:48','created_at' => '0000-00-00 00:00:00','updated_at' => '0000-00-00 00:00:00'), array('id' => '3','module_name' => 'healthcareservices','icon' => '','menu_show' => '0','menu_order' => '0','status' => '1','deleted_at' => '2016-04-04 02:28:48','created_at' => '0000-00-00 00:00:00','updated_at' => '0000-00-00 00:00:00'), array('id' => '4','module_name' => 'patients','icon' => '','menu_show' => '0','menu_order' => '0','status' => '1','deleted_at' => '2016-04-04 02:28:48','created_at' => '0000-00-00 00:00:00','updated_at' => '0000-00-00 00:00:00'), array('id' => '5','module_name' => 'records','icon' => 'fa-archive','menu_show' => '1','menu_order' => '1','status' => '1','deleted_at' => '2016-04-04 02:28:48','created_at' => '0000-00-00 00:00:00','updated_at' => '0000-00-00 00:00:00'), array('id' => '6','module_name' => 'referrals','icon' => 'fa-paper-plane-o','menu_show' => '1','menu_order' => '2','status' => '1','deleted_at' => '2016-04-04 02:28:48','created_at' => '0000-00-00 00:00:00','updated_at' => '0000-00-00 00:00:00'), array('id' => '7','module_name' => 'reminders','icon' => 'fa-calendar-check-o','menu_show' => '1','menu_order' => '3','status' => '1','deleted_at' => '2016-04-04 02:28:48','created_at' => '0000-00-00 00:00:00','updated_at' => '0000-00-00 00:00:00'), array('id' => '8','module_name' => 'reports','icon' => 'fa-clipboard','menu_show' => '1','menu_order' => '4','status' => '1','deleted_at' => '2016-04-04 02:28:48','created_at' => '0000-00-00 00:00:00','updated_at' => '0000-00-00 00:00:00'), array('id' => '9','module_name' => 'roles','icon' => 'fa-user-md','menu_show' => '0','menu_order' => '0','status' => '0','deleted_at' => '2016-04-04 02:28:48','created_at' => '0000-00-00 00:00:00','updated_at' => '0000-00-00 00:00:00'), array('id' => '10','module_name' => 'users','icon' => 'fa-group','menu_show' => '1','menu_order' => '10000','status' => '1','deleted_at' => '2016-04-04 02:28:48','created_at' => '0000-00-00 00:00:00','updated_at' => '0000-00-00 00:00:00'), array('id' => '11','module_name' => 'sync','icon' => 'fa-gears','menu_show' => '1','menu_order' => '10003','status' => '1','deleted_at' => '2016-04-11 07:44:12','created_at' => '0000-00-00 00:00:00','updated_at' => '0000-00-00 00:00:00'), array('id' => '12','module_name' => 'calendar','icon' => 'fa-calendar','menu_show' => '1','menu_order' => '11','status' => '1','deleted_at' => '2016-04-04 02:28:48','created_at' => '0000-00-00 00:00:00','updated_at' => '0000-00-00 00:00:00'), array('id' => '13','module_name' => 'extensions','icon' => 'fa-plug','menu_show' => '1','menu_order' => '10002','status' => '1','deleted_at' => '2016-04-04 02:28:48','created_at' => '0000-00-00 00:00:00','updated_at' => '0000-00-00 00:00:00'), array('id' => '14','module_name' => 'updates','icon' => 'fa-cloud-download','menu_show' => '1','menu_order' => '10004','status' => '1','deleted_at' => '2016-04-04 02:28:48','created_at' => '0000-00-00 00:00:00','updated_at' => '0000-00-00 00:00:00') )); Model::reguard(); } }
DevComSHINE/shine-os-deved
database/seeds/lov_modules.php
PHP
gpl-2.0
3,911
/* * INET An implementation of the TCP/IP protocol suite for the LINUX * operating system. INET is implemented using the BSD Socket * interface as the means of communication with the user level. * * ROUTE - implementation of the IP router. * * Authors: Ross Biro * Fred N. van Kempen, <waltje@uWalt.NL.Mugnet.ORG> * Alan Cox, <gw4pts@gw4pts.ampr.org> * Linus Torvalds, <Linus.Torvalds@helsinki.fi> * Alexey Kuznetsov, <kuznet@ms2.inr.ac.ru> * * Fixes: * Alan Cox : Verify area fixes. * Alan Cox : cli() protects routing changes * Rui Oliveira : ICMP routing table updates * (rco@di.uminho.pt) Routing table insertion and update * Linus Torvalds : Rewrote bits to be sensible * Alan Cox : Added BSD route gw semantics * Alan Cox : Super /proc >4K * Alan Cox : MTU in route table * Alan Cox : MSS actually. Also added the window * clamper. * Sam Lantinga : Fixed route matching in rt_del() * Alan Cox : Routing cache support. * Alan Cox : Removed compatibility cruft. * Alan Cox : RTF_REJECT support. * Alan Cox : TCP irtt support. * Jonathan Naylor : Added Metric support. * Miquel van Smoorenburg : BSD API fixes. * Miquel van Smoorenburg : Metrics. * Alan Cox : Use __u32 properly * Alan Cox : Aligned routing errors more closely with BSD * our system is still very different. * Alan Cox : Faster /proc handling * Alexey Kuznetsov : Massive rework to support tree based routing, * routing caches and better behaviour. * * Olaf Erb : irtt wasn't being copied right. * Bjorn Ekwall : Kerneld route support. * Alan Cox : Multicast fixed (I hope) * Pavel Krauz : Limited broadcast fixed * Mike McLagan : Routing by source * Alexey Kuznetsov : End of old history. Split to fib.c and * route.c and rewritten from scratch. * Andi Kleen : Load-limit warning messages. * Vitaly E. Lavrov : Transparent proxy revived after year coma. * Vitaly E. Lavrov : Race condition in ip_route_input_slow. * Tobias Ringstrom : Uninitialized res.type in ip_route_output_slow. * Vladimir V. Ivanov : IP rule info (flowid) is really useful. * Marc Boucher : routing by fwmark * Robert Olsson : Added rt_cache statistics * Arnaldo C. Melo : Convert proc stuff to seq_file * Eric Dumazet : hashed spinlocks and rt_check_expire() fixes. * Ilia Sotnikov : Ignore TOS on PMTUD and Redirect * Ilia Sotnikov : Removed TOS from hash calculations * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version * 2 of the License, or (at your option) any later version. */ #define pr_fmt(fmt) "IPv4: " fmt #include <linux/module.h> #include <asm/uaccess.h> #include <linux/bitops.h> #include <linux/types.h> #include <linux/kernel.h> #include <linux/mm.h> #include <linux/string.h> #include <linux/socket.h> #include <linux/sockios.h> #include <linux/errno.h> #include <linux/in.h> #include <linux/inet.h> #include <linux/netdevice.h> #include <linux/proc_fs.h> #include <linux/init.h> #include <linux/skbuff.h> #include <linux/inetdevice.h> #include <linux/igmp.h> #include <linux/pkt_sched.h> #include <linux/mroute.h> #include <linux/netfilter_ipv4.h> #include <linux/random.h> #include <linux/rcupdate.h> #include <linux/times.h> #include <linux/slab.h> #include <linux/jhash.h> #include <net/dst.h> #include <net/net_namespace.h> #include <net/protocol.h> #include <net/ip.h> #include <net/route.h> #include <net/inetpeer.h> #include <net/sock.h> #include <net/ip_fib.h> #include <net/arp.h> #include <net/tcp.h> #include <net/icmp.h> #include <net/xfrm.h> #include <net/netevent.h> #include <net/rtnetlink.h> #ifdef CONFIG_SYSCTL #include <linux/sysctl.h> #include <linux/kmemleak.h> #endif #include <net/secure_seq.h> #define RT_FL_TOS(oldflp4) \ ((oldflp4)->flowi4_tos & (IPTOS_RT_MASK | RTO_ONLINK)) #define RT_GC_TIMEOUT (300*HZ) static int ip_rt_max_size; static int ip_rt_redirect_number __read_mostly = 9; static int ip_rt_redirect_load __read_mostly = HZ / 50; static int ip_rt_redirect_silence __read_mostly = ((HZ / 50) << (9 + 1)); static int ip_rt_error_cost __read_mostly = HZ; static int ip_rt_error_burst __read_mostly = 5 * HZ; static int ip_rt_mtu_expires __read_mostly = 10 * 60 * HZ; static int ip_rt_min_pmtu __read_mostly = 512 + 20 + 20; static int ip_rt_min_advmss __read_mostly = 256; /* * Interface to generic destination cache. */ static struct dst_entry *ipv4_dst_check(struct dst_entry *dst, u32 cookie); static unsigned int ipv4_default_advmss(const struct dst_entry *dst); static unsigned int ipv4_mtu(const struct dst_entry *dst); static struct dst_entry *ipv4_negative_advice(struct dst_entry *dst); static void ipv4_link_failure(struct sk_buff *skb); static void ip_rt_update_pmtu(struct dst_entry *dst, struct sock *sk, struct sk_buff *skb, u32 mtu); static void ip_do_redirect(struct dst_entry *dst, struct sock *sk, struct sk_buff *skb); static void ipv4_dst_destroy(struct dst_entry *dst); static void ipv4_dst_ifdown(struct dst_entry *dst, struct net_device *dev, int how) { } static u32 *ipv4_cow_metrics(struct dst_entry *dst, unsigned long old) { WARN_ON(1); return NULL; } static struct neighbour *ipv4_neigh_lookup(const struct dst_entry *dst, struct sk_buff *skb, const void *daddr); static struct dst_ops ipv4_dst_ops = { .family = AF_INET, .protocol = cpu_to_be16(ETH_P_IP), .check = ipv4_dst_check, .default_advmss = ipv4_default_advmss, .mtu = ipv4_mtu, .cow_metrics = ipv4_cow_metrics, .destroy = ipv4_dst_destroy, .ifdown = ipv4_dst_ifdown, .negative_advice = ipv4_negative_advice, .link_failure = ipv4_link_failure, .update_pmtu = ip_rt_update_pmtu, .redirect = ip_do_redirect, .local_out = __ip_local_out, .neigh_lookup = ipv4_neigh_lookup, }; #define ECN_OR_COST(class) TC_PRIO_##class const __u8 ip_tos2prio[16] = { TC_PRIO_BESTEFFORT, ECN_OR_COST(BESTEFFORT), TC_PRIO_BESTEFFORT, ECN_OR_COST(BESTEFFORT), TC_PRIO_BULK, ECN_OR_COST(BULK), TC_PRIO_BULK, ECN_OR_COST(BULK), TC_PRIO_INTERACTIVE, ECN_OR_COST(INTERACTIVE), TC_PRIO_INTERACTIVE, ECN_OR_COST(INTERACTIVE), TC_PRIO_INTERACTIVE_BULK, ECN_OR_COST(INTERACTIVE_BULK), TC_PRIO_INTERACTIVE_BULK, ECN_OR_COST(INTERACTIVE_BULK) }; EXPORT_SYMBOL(ip_tos2prio); static DEFINE_PER_CPU(struct rt_cache_stat, rt_cache_stat); #define RT_CACHE_STAT_INC(field) __this_cpu_inc(rt_cache_stat.field) #ifdef CONFIG_PROC_FS static void *rt_cache_seq_start(struct seq_file *seq, loff_t *pos) { if (*pos) return NULL; return SEQ_START_TOKEN; } static void *rt_cache_seq_next(struct seq_file *seq, void *v, loff_t *pos) { ++*pos; return NULL; } static void rt_cache_seq_stop(struct seq_file *seq, void *v) { } static int rt_cache_seq_show(struct seq_file *seq, void *v) { if (v == SEQ_START_TOKEN) seq_printf(seq, "%-127s\n", "Iface\tDestination\tGateway \tFlags\t\tRefCnt\tUse\t" "Metric\tSource\t\tMTU\tWindow\tIRTT\tTOS\tHHRef\t" "HHUptod\tSpecDst"); return 0; } static const struct seq_operations rt_cache_seq_ops = { .start = rt_cache_seq_start, .next = rt_cache_seq_next, .stop = rt_cache_seq_stop, .show = rt_cache_seq_show, }; static int rt_cache_seq_open(struct inode *inode, struct file *file) { return seq_open_restrict(file, &rt_cache_seq_ops); } static const struct file_operations rt_cache_seq_fops = { .owner = THIS_MODULE, .open = rt_cache_seq_open, .read = seq_read, .llseek = seq_lseek, .release = seq_release, }; static void *rt_cpu_seq_start(struct seq_file *seq, loff_t *pos) { int cpu; if (*pos == 0) return SEQ_START_TOKEN; for (cpu = *pos-1; cpu < nr_cpu_ids; ++cpu) { if (!cpu_possible(cpu)) continue; *pos = cpu+1; return &per_cpu(rt_cache_stat, cpu); } return NULL; } static void *rt_cpu_seq_next(struct seq_file *seq, void *v, loff_t *pos) { int cpu; for (cpu = *pos; cpu < nr_cpu_ids; ++cpu) { if (!cpu_possible(cpu)) continue; *pos = cpu+1; return &per_cpu(rt_cache_stat, cpu); } return NULL; } static void rt_cpu_seq_stop(struct seq_file *seq, void *v) { } static int rt_cpu_seq_show(struct seq_file *seq, void *v) { struct rt_cache_stat *st = v; if (v == SEQ_START_TOKEN) { seq_printf(seq, "entries in_hit in_slow_tot in_slow_mc in_no_route in_brd in_martian_dst in_martian_src out_hit out_slow_tot out_slow_mc gc_total gc_ignored gc_goal_miss gc_dst_overflow in_hlist_search out_hlist_search\n"); return 0; } seq_printf(seq,"%08x %08x %08x %08x %08x %08x %08x %08x " " %08x %08x %08x %08x %08x %08x %08x %08x %08x \n", dst_entries_get_slow(&ipv4_dst_ops), 0, /* st->in_hit */ st->in_slow_tot, st->in_slow_mc, st->in_no_route, st->in_brd, st->in_martian_dst, st->in_martian_src, 0, /* st->out_hit */ st->out_slow_tot, st->out_slow_mc, 0, /* st->gc_total */ 0, /* st->gc_ignored */ 0, /* st->gc_goal_miss */ 0, /* st->gc_dst_overflow */ 0, /* st->in_hlist_search */ 0 /* st->out_hlist_search */ ); return 0; } static const struct seq_operations rt_cpu_seq_ops = { .start = rt_cpu_seq_start, .next = rt_cpu_seq_next, .stop = rt_cpu_seq_stop, .show = rt_cpu_seq_show, }; static int rt_cpu_seq_open(struct inode *inode, struct file *file) { return seq_open_restrict(file, &rt_cpu_seq_ops); } static const struct file_operations rt_cpu_seq_fops = { .owner = THIS_MODULE, .open = rt_cpu_seq_open, .read = seq_read, .llseek = seq_lseek, .release = seq_release, }; #ifdef CONFIG_IP_ROUTE_CLASSID static int rt_acct_proc_show(struct seq_file *m, void *v) { struct ip_rt_acct *dst, *src; unsigned int i, j; dst = kcalloc(256, sizeof(struct ip_rt_acct), GFP_KERNEL); if (!dst) return -ENOMEM; for_each_possible_cpu(i) { src = (struct ip_rt_acct *)per_cpu_ptr(ip_rt_acct, i); for (j = 0; j < 256; j++) { dst[j].o_bytes += src[j].o_bytes; dst[j].o_packets += src[j].o_packets; dst[j].i_bytes += src[j].i_bytes; dst[j].i_packets += src[j].i_packets; } } seq_write(m, dst, 256 * sizeof(struct ip_rt_acct)); kfree(dst); return 0; } static int rt_acct_proc_open(struct inode *inode, struct file *file) { return single_open_restrict(file, rt_acct_proc_show, NULL); } static const struct file_operations rt_acct_proc_fops = { .owner = THIS_MODULE, .open = rt_acct_proc_open, .read = seq_read, .llseek = seq_lseek, .release = single_release, }; #endif static int __net_init ip_rt_do_proc_init(struct net *net) { struct proc_dir_entry *pde; pde = proc_create("rt_cache", S_IRUGO, net->proc_net, &rt_cache_seq_fops); if (!pde) goto err1; pde = proc_create("rt_cache", S_IRUGO, net->proc_net_stat, &rt_cpu_seq_fops); if (!pde) goto err2; #ifdef CONFIG_IP_ROUTE_CLASSID pde = proc_create("rt_acct", 0, net->proc_net, &rt_acct_proc_fops); if (!pde) goto err3; #endif return 0; #ifdef CONFIG_IP_ROUTE_CLASSID err3: remove_proc_entry("rt_cache", net->proc_net_stat); #endif err2: remove_proc_entry("rt_cache", net->proc_net); err1: return -ENOMEM; } static void __net_exit ip_rt_do_proc_exit(struct net *net) { remove_proc_entry("rt_cache", net->proc_net_stat); remove_proc_entry("rt_cache", net->proc_net); #ifdef CONFIG_IP_ROUTE_CLASSID remove_proc_entry("rt_acct", net->proc_net); #endif } static struct pernet_operations ip_rt_proc_ops __net_initdata = { .init = ip_rt_do_proc_init, .exit = ip_rt_do_proc_exit, }; static int __init ip_rt_proc_init(void) { return register_pernet_subsys(&ip_rt_proc_ops); } #else static inline int ip_rt_proc_init(void) { return 0; } #endif /* CONFIG_PROC_FS */ static inline bool rt_is_expired(const struct rtable *rth) { return rth->rt_genid != rt_genid_ipv4(dev_net(rth->dst.dev)); } void rt_cache_flush(struct net *net) { rt_genid_bump_ipv4(net); } static struct neighbour *ipv4_neigh_lookup(const struct dst_entry *dst, struct sk_buff *skb, const void *daddr) { struct net_device *dev = dst->dev; const __be32 *pkey = daddr; const struct rtable *rt; struct neighbour *n; rt = (const struct rtable *) dst; if (rt->rt_gateway) pkey = (const __be32 *) &rt->rt_gateway; else if (skb) pkey = &ip_hdr(skb)->daddr; n = __ipv4_neigh_lookup(dev, *(__force u32 *)pkey); if (n) return n; return neigh_create(&arp_tbl, pkey, dev); } #define IP_IDENTS_SZ 2048u struct ip_ident_bucket { atomic_unchecked_t id; u32 stamp32; }; static struct ip_ident_bucket ip_idents[IP_IDENTS_SZ] __read_mostly; /* In order to protect privacy, we add a perturbation to identifiers * if one generator is seldom used. This makes hard for an attacker * to infer how many packets were sent between two points in time. */ u32 ip_idents_reserve(u32 hash, int segs) { struct ip_ident_bucket *bucket = ip_idents + hash % IP_IDENTS_SZ; u32 old = ACCESS_ONCE(bucket->stamp32); u32 now = (u32)jiffies; u32 delta = 0; if (old != now && cmpxchg(&bucket->stamp32, old, now) == old) delta = prandom_u32_max(now - old); return atomic_add_return_unchecked(segs + delta, &bucket->id) - segs; } EXPORT_SYMBOL(ip_idents_reserve); void __ip_select_ident(struct iphdr *iph, int segs) { static u32 ip_idents_hashrnd __read_mostly; u32 hash, id; net_get_random_once(&ip_idents_hashrnd, sizeof(ip_idents_hashrnd)); hash = jhash_3words((__force u32)iph->daddr, (__force u32)iph->saddr, iph->protocol, ip_idents_hashrnd); id = ip_idents_reserve(hash, segs); iph->id = htons(id); } EXPORT_SYMBOL(__ip_select_ident); static void __build_flow_key(struct flowi4 *fl4, const struct sock *sk, const struct iphdr *iph, int oif, u8 tos, u8 prot, u32 mark, int flow_flags) { if (sk) { const struct inet_sock *inet = inet_sk(sk); oif = sk->sk_bound_dev_if; mark = sk->sk_mark; tos = RT_CONN_FLAGS(sk); prot = inet->hdrincl ? IPPROTO_RAW : sk->sk_protocol; } flowi4_init_output(fl4, oif, mark, tos, RT_SCOPE_UNIVERSE, prot, flow_flags, iph->daddr, iph->saddr, 0, 0); } static void build_skb_flow_key(struct flowi4 *fl4, const struct sk_buff *skb, const struct sock *sk) { const struct iphdr *iph = ip_hdr(skb); int oif = skb->dev->ifindex; u8 tos = RT_TOS(iph->tos); u8 prot = iph->protocol; u32 mark = skb->mark; __build_flow_key(fl4, sk, iph, oif, tos, prot, mark, 0); } static void build_sk_flow_key(struct flowi4 *fl4, const struct sock *sk) { const struct inet_sock *inet = inet_sk(sk); const struct ip_options_rcu *inet_opt; __be32 daddr = inet->inet_daddr; rcu_read_lock(); inet_opt = rcu_dereference(inet->inet_opt); if (inet_opt && inet_opt->opt.srr) daddr = inet_opt->opt.faddr; flowi4_init_output(fl4, sk->sk_bound_dev_if, sk->sk_mark, RT_CONN_FLAGS(sk), RT_SCOPE_UNIVERSE, inet->hdrincl ? IPPROTO_RAW : sk->sk_protocol, inet_sk_flowi_flags(sk), daddr, inet->inet_saddr, 0, 0); rcu_read_unlock(); } static void ip_rt_build_flow_key(struct flowi4 *fl4, const struct sock *sk, const struct sk_buff *skb) { if (skb) build_skb_flow_key(fl4, skb, sk); else build_sk_flow_key(fl4, sk); } static inline void rt_free(struct rtable *rt) { call_rcu(&rt->dst.rcu_head, dst_rcu_free); } static DEFINE_SPINLOCK(fnhe_lock); static void fnhe_flush_routes(struct fib_nh_exception *fnhe) { struct rtable *rt; rt = rcu_dereference(fnhe->fnhe_rth_input); if (rt) { RCU_INIT_POINTER(fnhe->fnhe_rth_input, NULL); rt_free(rt); } rt = rcu_dereference(fnhe->fnhe_rth_output); if (rt) { RCU_INIT_POINTER(fnhe->fnhe_rth_output, NULL); rt_free(rt); } } static struct fib_nh_exception *fnhe_oldest(struct fnhe_hash_bucket *hash) { struct fib_nh_exception *fnhe, *oldest; oldest = rcu_dereference(hash->chain); for (fnhe = rcu_dereference(oldest->fnhe_next); fnhe; fnhe = rcu_dereference(fnhe->fnhe_next)) { if (time_before(fnhe->fnhe_stamp, oldest->fnhe_stamp)) oldest = fnhe; } fnhe_flush_routes(oldest); return oldest; } static inline u32 fnhe_hashfun(__be32 daddr) { u32 hval; hval = (__force u32) daddr; hval ^= (hval >> 11) ^ (hval >> 22); return hval & (FNHE_HASH_SIZE - 1); } static void fill_route_from_fnhe(struct rtable *rt, struct fib_nh_exception *fnhe) { rt->rt_pmtu = fnhe->fnhe_pmtu; rt->dst.expires = fnhe->fnhe_expires; if (fnhe->fnhe_gw) { rt->rt_flags |= RTCF_REDIRECTED; rt->rt_gateway = fnhe->fnhe_gw; rt->rt_uses_gateway = 1; } } static void update_or_create_fnhe(struct fib_nh *nh, __be32 daddr, __be32 gw, u32 pmtu, unsigned long expires) { struct fnhe_hash_bucket *hash; struct fib_nh_exception *fnhe; struct rtable *rt; unsigned int i; int depth; u32 hval = fnhe_hashfun(daddr); spin_lock_bh(&fnhe_lock); hash = nh->nh_exceptions; if (!hash) { hash = kzalloc(FNHE_HASH_SIZE * sizeof(*hash), GFP_ATOMIC); if (!hash) goto out_unlock; nh->nh_exceptions = hash; } hash += hval; depth = 0; for (fnhe = rcu_dereference(hash->chain); fnhe; fnhe = rcu_dereference(fnhe->fnhe_next)) { if (fnhe->fnhe_daddr == daddr) break; depth++; } if (fnhe) { if (gw) fnhe->fnhe_gw = gw; if (pmtu) { fnhe->fnhe_pmtu = pmtu; fnhe->fnhe_expires = max(1UL, expires); } /* Update all cached dsts too */ rt = rcu_dereference(fnhe->fnhe_rth_input); if (rt) fill_route_from_fnhe(rt, fnhe); rt = rcu_dereference(fnhe->fnhe_rth_output); if (rt) fill_route_from_fnhe(rt, fnhe); } else { if (depth > FNHE_RECLAIM_DEPTH) fnhe = fnhe_oldest(hash); else { fnhe = kzalloc(sizeof(*fnhe), GFP_ATOMIC); if (!fnhe) goto out_unlock; fnhe->fnhe_next = hash->chain; rcu_assign_pointer(hash->chain, fnhe); } fnhe->fnhe_genid = fnhe_genid(dev_net(nh->nh_dev)); fnhe->fnhe_daddr = daddr; fnhe->fnhe_gw = gw; fnhe->fnhe_pmtu = pmtu; fnhe->fnhe_expires = expires; /* Exception created; mark the cached routes for the nexthop * stale, so anyone caching it rechecks if this exception * applies to them. */ rt = rcu_dereference(nh->nh_rth_input); if (rt) rt->dst.obsolete = DST_OBSOLETE_KILL; for_each_possible_cpu(i) { struct rtable __rcu **prt; prt = per_cpu_ptr(nh->nh_pcpu_rth_output, i); rt = rcu_dereference(*prt); if (rt) rt->dst.obsolete = DST_OBSOLETE_KILL; } } fnhe->fnhe_stamp = jiffies; out_unlock: spin_unlock_bh(&fnhe_lock); return; } static void __ip_do_redirect(struct rtable *rt, struct sk_buff *skb, struct flowi4 *fl4, bool kill_route) { __be32 new_gw = icmp_hdr(skb)->un.gateway; __be32 old_gw = ip_hdr(skb)->saddr; struct net_device *dev = skb->dev; struct in_device *in_dev; struct fib_result res; struct neighbour *n; struct net *net; switch (icmp_hdr(skb)->code & 7) { case ICMP_REDIR_NET: case ICMP_REDIR_NETTOS: case ICMP_REDIR_HOST: case ICMP_REDIR_HOSTTOS: break; default: return; } if (rt->rt_gateway != old_gw) return; in_dev = __in_dev_get_rcu(dev); if (!in_dev) return; net = dev_net(dev); if (new_gw == old_gw || !IN_DEV_RX_REDIRECTS(in_dev) || ipv4_is_multicast(new_gw) || ipv4_is_lbcast(new_gw) || ipv4_is_zeronet(new_gw)) goto reject_redirect; if (!IN_DEV_SHARED_MEDIA(in_dev)) { if (!inet_addr_onlink(in_dev, new_gw, old_gw)) goto reject_redirect; if (IN_DEV_SEC_REDIRECTS(in_dev) && ip_fib_check_default(new_gw, dev)) goto reject_redirect; } else { if (inet_addr_type(net, new_gw) != RTN_UNICAST) goto reject_redirect; } n = ipv4_neigh_lookup(&rt->dst, NULL, &new_gw); if (n) { if (!(n->nud_state & NUD_VALID)) { neigh_event_send(n, NULL); } else { if (fib_lookup(net, fl4, &res) == 0) { struct fib_nh *nh = &FIB_RES_NH(res); update_or_create_fnhe(nh, fl4->daddr, new_gw, 0, 0); } if (kill_route) rt->dst.obsolete = DST_OBSOLETE_KILL; call_netevent_notifiers(NETEVENT_NEIGH_UPDATE, n); } neigh_release(n); } return; reject_redirect: #ifdef CONFIG_IP_ROUTE_VERBOSE if (IN_DEV_LOG_MARTIANS(in_dev)) { const struct iphdr *iph = (const struct iphdr *) skb->data; __be32 daddr = iph->daddr; __be32 saddr = iph->saddr; net_info_ratelimited("Redirect from %pI4 on %s about %pI4 ignored\n" " Advised path = %pI4 -> %pI4\n", &old_gw, dev->name, &new_gw, &saddr, &daddr); } #endif ; } static void ip_do_redirect(struct dst_entry *dst, struct sock *sk, struct sk_buff *skb) { struct rtable *rt; struct flowi4 fl4; const struct iphdr *iph = (const struct iphdr *) skb->data; int oif = skb->dev->ifindex; u8 tos = RT_TOS(iph->tos); u8 prot = iph->protocol; u32 mark = skb->mark; rt = (struct rtable *) dst; __build_flow_key(&fl4, sk, iph, oif, tos, prot, mark, 0); __ip_do_redirect(rt, skb, &fl4, true); } static struct dst_entry *ipv4_negative_advice(struct dst_entry *dst) { struct rtable *rt = (struct rtable *)dst; struct dst_entry *ret = dst; if (rt) { if (dst->obsolete > 0) { ip_rt_put(rt); ret = NULL; } else if ((rt->rt_flags & RTCF_REDIRECTED) || rt->dst.expires) { ip_rt_put(rt); ret = NULL; } } return ret; } /* * Algorithm: * 1. The first ip_rt_redirect_number redirects are sent * with exponential backoff, then we stop sending them at all, * assuming that the host ignores our redirects. * 2. If we did not see packets requiring redirects * during ip_rt_redirect_silence, we assume that the host * forgot redirected route and start to send redirects again. * * This algorithm is much cheaper and more intelligent than dumb load limiting * in icmp.c. * * NOTE. Do not forget to inhibit load limiting for redirects (redundant) * and "frag. need" (breaks PMTU discovery) in icmp.c. */ void ip_rt_send_redirect(struct sk_buff *skb) { struct rtable *rt = skb_rtable(skb); struct in_device *in_dev; struct inet_peer *peer; struct net *net; int log_martians; rcu_read_lock(); in_dev = __in_dev_get_rcu(rt->dst.dev); if (!in_dev || !IN_DEV_TX_REDIRECTS(in_dev)) { rcu_read_unlock(); return; } log_martians = IN_DEV_LOG_MARTIANS(in_dev); rcu_read_unlock(); net = dev_net(rt->dst.dev); peer = inet_getpeer_v4(net->ipv4.peers, ip_hdr(skb)->saddr, 1); if (!peer) { icmp_send(skb, ICMP_REDIRECT, ICMP_REDIR_HOST, rt_nexthop(rt, ip_hdr(skb)->daddr)); return; } /* No redirected packets during ip_rt_redirect_silence; * reset the algorithm. */ if (time_after(jiffies, peer->rate_last + ip_rt_redirect_silence)) peer->rate_tokens = 0; /* Too many ignored redirects; do not send anything * set dst.rate_last to the last seen redirected packet. */ if (peer->rate_tokens >= ip_rt_redirect_number) { peer->rate_last = jiffies; goto out_put_peer; } /* Check for load limit; set rate_last to the latest sent * redirect. */ if (peer->rate_tokens == 0 || time_after(jiffies, (peer->rate_last + (ip_rt_redirect_load << peer->rate_tokens)))) { __be32 gw = rt_nexthop(rt, ip_hdr(skb)->daddr); icmp_send(skb, ICMP_REDIRECT, ICMP_REDIR_HOST, gw); peer->rate_last = jiffies; ++peer->rate_tokens; #ifdef CONFIG_IP_ROUTE_VERBOSE if (log_martians && peer->rate_tokens == ip_rt_redirect_number) net_warn_ratelimited("host %pI4/if%d ignores redirects for %pI4 to %pI4\n", &ip_hdr(skb)->saddr, inet_iif(skb), &ip_hdr(skb)->daddr, &gw); #endif } out_put_peer: inet_putpeer(peer); } static int ip_error(struct sk_buff *skb) { struct in_device *in_dev = __in_dev_get_rcu(skb->dev); struct rtable *rt = skb_rtable(skb); struct inet_peer *peer; unsigned long now; struct net *net; bool send; int code; net = dev_net(rt->dst.dev); if (!IN_DEV_FORWARD(in_dev)) { switch (rt->dst.error) { case EHOSTUNREACH: IP_INC_STATS_BH(net, IPSTATS_MIB_INADDRERRORS); break; case ENETUNREACH: IP_INC_STATS_BH(net, IPSTATS_MIB_INNOROUTES); break; } goto out; } switch (rt->dst.error) { case EINVAL: default: goto out; case EHOSTUNREACH: code = ICMP_HOST_UNREACH; break; case ENETUNREACH: code = ICMP_NET_UNREACH; IP_INC_STATS_BH(net, IPSTATS_MIB_INNOROUTES); break; case EACCES: code = ICMP_PKT_FILTERED; break; } peer = inet_getpeer_v4(net->ipv4.peers, ip_hdr(skb)->saddr, 1); send = true; if (peer) { now = jiffies; peer->rate_tokens += now - peer->rate_last; if (peer->rate_tokens > ip_rt_error_burst) peer->rate_tokens = ip_rt_error_burst; peer->rate_last = now; if (peer->rate_tokens >= ip_rt_error_cost) peer->rate_tokens -= ip_rt_error_cost; else send = false; inet_putpeer(peer); } if (send) icmp_send(skb, ICMP_DEST_UNREACH, code, 0); out: kfree_skb(skb); return 0; } static void __ip_rt_update_pmtu(struct rtable *rt, struct flowi4 *fl4, u32 mtu) { struct dst_entry *dst = &rt->dst; struct fib_result res; if (dst_metric_locked(dst, RTAX_MTU)) return; if (dst->dev->mtu < mtu) return; if (mtu < ip_rt_min_pmtu) mtu = ip_rt_min_pmtu; if (rt->rt_pmtu == mtu && time_before(jiffies, dst->expires - ip_rt_mtu_expires / 2)) return; rcu_read_lock(); if (fib_lookup(dev_net(dst->dev), fl4, &res) == 0) { struct fib_nh *nh = &FIB_RES_NH(res); update_or_create_fnhe(nh, fl4->daddr, 0, mtu, jiffies + ip_rt_mtu_expires); } rcu_read_unlock(); } static void ip_rt_update_pmtu(struct dst_entry *dst, struct sock *sk, struct sk_buff *skb, u32 mtu) { struct rtable *rt = (struct rtable *) dst; struct flowi4 fl4; ip_rt_build_flow_key(&fl4, sk, skb); __ip_rt_update_pmtu(rt, &fl4, mtu); } void ipv4_update_pmtu(struct sk_buff *skb, struct net *net, u32 mtu, int oif, u32 mark, u8 protocol, int flow_flags) { const struct iphdr *iph = (const struct iphdr *) skb->data; struct flowi4 fl4; struct rtable *rt; __build_flow_key(&fl4, NULL, iph, oif, RT_TOS(iph->tos), protocol, mark, flow_flags); rt = __ip_route_output_key(net, &fl4); if (!IS_ERR(rt)) { __ip_rt_update_pmtu(rt, &fl4, mtu); ip_rt_put(rt); } } EXPORT_SYMBOL_GPL(ipv4_update_pmtu); static void __ipv4_sk_update_pmtu(struct sk_buff *skb, struct sock *sk, u32 mtu) { const struct iphdr *iph = (const struct iphdr *) skb->data; struct flowi4 fl4; struct rtable *rt; __build_flow_key(&fl4, sk, iph, 0, 0, 0, 0, 0); rt = __ip_route_output_key(sock_net(sk), &fl4); if (!IS_ERR(rt)) { __ip_rt_update_pmtu(rt, &fl4, mtu); ip_rt_put(rt); } } void ipv4_sk_update_pmtu(struct sk_buff *skb, struct sock *sk, u32 mtu) { const struct iphdr *iph = (const struct iphdr *) skb->data; struct flowi4 fl4; struct rtable *rt; struct dst_entry *odst = NULL; bool new = false; bh_lock_sock(sk); if (!ip_sk_accept_pmtu(sk)) goto out; odst = sk_dst_get(sk); if (sock_owned_by_user(sk) || !odst) { __ipv4_sk_update_pmtu(skb, sk, mtu); goto out; } __build_flow_key(&fl4, sk, iph, 0, 0, 0, 0, 0); rt = (struct rtable *)odst; if (odst->obsolete && odst->ops->check(odst, 0) == NULL) { rt = ip_route_output_flow(sock_net(sk), &fl4, sk); if (IS_ERR(rt)) goto out; new = true; } __ip_rt_update_pmtu((struct rtable *) rt->dst.path, &fl4, mtu); if (!dst_check(&rt->dst, 0)) { if (new) dst_release(&rt->dst); rt = ip_route_output_flow(sock_net(sk), &fl4, sk); if (IS_ERR(rt)) goto out; new = true; } if (new) sk_dst_set(sk, &rt->dst); out: bh_unlock_sock(sk); dst_release(odst); } EXPORT_SYMBOL_GPL(ipv4_sk_update_pmtu); void ipv4_redirect(struct sk_buff *skb, struct net *net, int oif, u32 mark, u8 protocol, int flow_flags) { const struct iphdr *iph = (const struct iphdr *) skb->data; struct flowi4 fl4; struct rtable *rt; __build_flow_key(&fl4, NULL, iph, oif, RT_TOS(iph->tos), protocol, mark, flow_flags); rt = __ip_route_output_key(net, &fl4); if (!IS_ERR(rt)) { __ip_do_redirect(rt, skb, &fl4, false); ip_rt_put(rt); } } EXPORT_SYMBOL_GPL(ipv4_redirect); void ipv4_sk_redirect(struct sk_buff *skb, struct sock *sk) { const struct iphdr *iph = (const struct iphdr *) skb->data; struct flowi4 fl4; struct rtable *rt; __build_flow_key(&fl4, sk, iph, 0, 0, 0, 0, 0); rt = __ip_route_output_key(sock_net(sk), &fl4); if (!IS_ERR(rt)) { __ip_do_redirect(rt, skb, &fl4, false); ip_rt_put(rt); } } EXPORT_SYMBOL_GPL(ipv4_sk_redirect); static struct dst_entry *ipv4_dst_check(struct dst_entry *dst, u32 cookie) { struct rtable *rt = (struct rtable *) dst; /* All IPV4 dsts are created with ->obsolete set to the value * DST_OBSOLETE_FORCE_CHK which forces validation calls down * into this function always. * * When a PMTU/redirect information update invalidates a route, * this is indicated by setting obsolete to DST_OBSOLETE_KILL or * DST_OBSOLETE_DEAD by dst_free(). */ if (dst->obsolete != DST_OBSOLETE_FORCE_CHK || rt_is_expired(rt)) return NULL; return dst; } static void ipv4_link_failure(struct sk_buff *skb) { struct rtable *rt; icmp_send(skb, ICMP_DEST_UNREACH, ICMP_HOST_UNREACH, 0); rt = skb_rtable(skb); if (rt) dst_set_expires(&rt->dst, 0); } static int ip_rt_bug(struct sk_buff *skb) { pr_debug("%s: %pI4 -> %pI4, %s\n", __func__, &ip_hdr(skb)->saddr, &ip_hdr(skb)->daddr, skb->dev ? skb->dev->name : "?"); kfree_skb(skb); WARN_ON(1); return 0; } /* We do not cache source address of outgoing interface, because it is used only by IP RR, TS and SRR options, so that it out of fast path. BTW remember: "addr" is allowed to be not aligned in IP options! */ void ip_rt_get_source(u8 *addr, struct sk_buff *skb, struct rtable *rt) { __be32 src; if (rt_is_output_route(rt)) src = ip_hdr(skb)->saddr; else { struct fib_result res; struct flowi4 fl4; struct iphdr *iph; iph = ip_hdr(skb); memset(&fl4, 0, sizeof(fl4)); fl4.daddr = iph->daddr; fl4.saddr = iph->saddr; fl4.flowi4_tos = RT_TOS(iph->tos); fl4.flowi4_oif = rt->dst.dev->ifindex; fl4.flowi4_iif = skb->dev->ifindex; fl4.flowi4_mark = skb->mark; rcu_read_lock(); if (fib_lookup(dev_net(rt->dst.dev), &fl4, &res) == 0) src = FIB_RES_PREFSRC(dev_net(rt->dst.dev), res); else src = inet_select_addr(rt->dst.dev, rt_nexthop(rt, iph->daddr), RT_SCOPE_UNIVERSE); rcu_read_unlock(); } memcpy(addr, &src, 4); } #ifdef CONFIG_IP_ROUTE_CLASSID static void set_class_tag(struct rtable *rt, u32 tag) { if (!(rt->dst.tclassid & 0xFFFF)) rt->dst.tclassid |= tag & 0xFFFF; if (!(rt->dst.tclassid & 0xFFFF0000)) rt->dst.tclassid |= tag & 0xFFFF0000; } #endif static unsigned int ipv4_default_advmss(const struct dst_entry *dst) { unsigned int advmss = dst_metric_raw(dst, RTAX_ADVMSS); if (advmss == 0) { advmss = max_t(unsigned int, dst->dev->mtu - 40, ip_rt_min_advmss); if (advmss > 65535 - 40) advmss = 65535 - 40; } return advmss; } static unsigned int ipv4_mtu(const struct dst_entry *dst) { const struct rtable *rt = (const struct rtable *) dst; unsigned int mtu = rt->rt_pmtu; if (!mtu || time_after_eq(jiffies, rt->dst.expires)) mtu = dst_metric_raw(dst, RTAX_MTU); if (mtu) return mtu; mtu = dst->dev->mtu; if (unlikely(dst_metric_locked(dst, RTAX_MTU))) { if (rt->rt_uses_gateway && mtu > 576) mtu = 576; } return min_t(unsigned int, mtu, IP_MAX_MTU); } static struct fib_nh_exception *find_exception(struct fib_nh *nh, __be32 daddr) { struct fnhe_hash_bucket *hash = nh->nh_exceptions; struct fib_nh_exception *fnhe; u32 hval; if (!hash) return NULL; hval = fnhe_hashfun(daddr); for (fnhe = rcu_dereference(hash[hval].chain); fnhe; fnhe = rcu_dereference(fnhe->fnhe_next)) { if (fnhe->fnhe_daddr == daddr) return fnhe; } return NULL; } static bool rt_bind_exception(struct rtable *rt, struct fib_nh_exception *fnhe, __be32 daddr) { bool ret = false; spin_lock_bh(&fnhe_lock); if (daddr == fnhe->fnhe_daddr) { struct rtable __rcu **porig; struct rtable *orig; int genid = fnhe_genid(dev_net(rt->dst.dev)); if (rt_is_input_route(rt)) porig = &fnhe->fnhe_rth_input; else porig = &fnhe->fnhe_rth_output; orig = rcu_dereference(*porig); if (fnhe->fnhe_genid != genid) { fnhe->fnhe_genid = genid; fnhe->fnhe_gw = 0; fnhe->fnhe_pmtu = 0; fnhe->fnhe_expires = 0; fnhe_flush_routes(fnhe); orig = NULL; } fill_route_from_fnhe(rt, fnhe); if (!rt->rt_gateway) rt->rt_gateway = daddr; if (!(rt->dst.flags & DST_NOCACHE)) { rcu_assign_pointer(*porig, rt); if (orig) rt_free(orig); ret = true; } fnhe->fnhe_stamp = jiffies; } spin_unlock_bh(&fnhe_lock); return ret; } static bool rt_cache_route(struct fib_nh *nh, struct rtable *rt) { struct rtable *orig, *prev, **p; bool ret = true; if (rt_is_input_route(rt)) { p = (struct rtable **)&nh->nh_rth_input; } else { p = (struct rtable **)__this_cpu_ptr(nh->nh_pcpu_rth_output); } orig = *p; prev = cmpxchg(p, orig, rt); if (prev == orig) { if (orig) rt_free(orig); } else ret = false; return ret; } static DEFINE_SPINLOCK(rt_uncached_lock); static LIST_HEAD(rt_uncached_list); static void rt_add_uncached_list(struct rtable *rt) { spin_lock_bh(&rt_uncached_lock); list_add_tail(&rt->rt_uncached, &rt_uncached_list); spin_unlock_bh(&rt_uncached_lock); } static void ipv4_dst_destroy(struct dst_entry *dst) { struct rtable *rt = (struct rtable *) dst; if (!list_empty(&rt->rt_uncached)) { spin_lock_bh(&rt_uncached_lock); list_del(&rt->rt_uncached); spin_unlock_bh(&rt_uncached_lock); } } void rt_flush_dev(struct net_device *dev) { if (!list_empty(&rt_uncached_list)) { struct net *net = dev_net(dev); struct rtable *rt; spin_lock_bh(&rt_uncached_lock); list_for_each_entry(rt, &rt_uncached_list, rt_uncached) { if (rt->dst.dev != dev) continue; rt->dst.dev = net->loopback_dev; dev_hold(rt->dst.dev); dev_put(dev); } spin_unlock_bh(&rt_uncached_lock); } } static bool rt_cache_valid(const struct rtable *rt) { return rt && rt->dst.obsolete == DST_OBSOLETE_FORCE_CHK && !rt_is_expired(rt); } static void rt_set_nexthop(struct rtable *rt, __be32 daddr, const struct fib_result *res, struct fib_nh_exception *fnhe, struct fib_info *fi, u16 type, u32 itag) { bool cached = false; if (fi) { struct fib_nh *nh = &FIB_RES_NH(*res); if (nh->nh_gw && nh->nh_scope == RT_SCOPE_LINK) { rt->rt_gateway = nh->nh_gw; rt->rt_uses_gateway = 1; } dst_init_metrics(&rt->dst, fi->fib_metrics, true); #ifdef CONFIG_IP_ROUTE_CLASSID rt->dst.tclassid = nh->nh_tclassid; #endif if (unlikely(fnhe)) cached = rt_bind_exception(rt, fnhe, daddr); else if (!(rt->dst.flags & DST_NOCACHE)) cached = rt_cache_route(nh, rt); if (unlikely(!cached)) { /* Routes we intend to cache in nexthop exception or * FIB nexthop have the DST_NOCACHE bit clear. * However, if we are unsuccessful at storing this * route into the cache we really need to set it. */ rt->dst.flags |= DST_NOCACHE; if (!rt->rt_gateway) rt->rt_gateway = daddr; rt_add_uncached_list(rt); } } else rt_add_uncached_list(rt); #ifdef CONFIG_IP_ROUTE_CLASSID #ifdef CONFIG_IP_MULTIPLE_TABLES set_class_tag(rt, res->tclassid); #endif set_class_tag(rt, itag); #endif } static struct rtable *rt_dst_alloc(struct net_device *dev, bool nopolicy, bool noxfrm, bool will_cache) { return dst_alloc(&ipv4_dst_ops, dev, 1, DST_OBSOLETE_FORCE_CHK, (will_cache ? 0 : (DST_HOST | DST_NOCACHE)) | (nopolicy ? DST_NOPOLICY : 0) | (noxfrm ? DST_NOXFRM : 0)); } /* called in rcu_read_lock() section */ static int ip_route_input_mc(struct sk_buff *skb, __be32 daddr, __be32 saddr, u8 tos, struct net_device *dev, int our) { struct rtable *rth; struct in_device *in_dev = __in_dev_get_rcu(dev); u32 itag = 0; int err; /* Primary sanity checks. */ if (in_dev == NULL) return -EINVAL; if (ipv4_is_multicast(saddr) || ipv4_is_lbcast(saddr) || skb->protocol != htons(ETH_P_IP)) goto e_inval; if (likely(!IN_DEV_ROUTE_LOCALNET(in_dev))) if (ipv4_is_loopback(saddr)) goto e_inval; if (ipv4_is_zeronet(saddr)) { if (!ipv4_is_local_multicast(daddr)) goto e_inval; } else { err = fib_validate_source(skb, saddr, 0, tos, 0, dev, in_dev, &itag); if (err < 0) goto e_err; } rth = rt_dst_alloc(dev_net(dev)->loopback_dev, IN_DEV_CONF_GET(in_dev, NOPOLICY), false, false); if (!rth) goto e_nobufs; #ifdef CONFIG_IP_ROUTE_CLASSID rth->dst.tclassid = itag; #endif rth->dst.output = ip_rt_bug; rth->rt_genid = rt_genid_ipv4(dev_net(dev)); rth->rt_flags = RTCF_MULTICAST; rth->rt_type = RTN_MULTICAST; rth->rt_is_input= 1; rth->rt_iif = 0; rth->rt_pmtu = 0; rth->rt_gateway = 0; rth->rt_uses_gateway = 0; INIT_LIST_HEAD(&rth->rt_uncached); if (our) { rth->dst.input= ip_local_deliver; rth->rt_flags |= RTCF_LOCAL; } #ifdef CONFIG_IP_MROUTE if (!ipv4_is_local_multicast(daddr) && IN_DEV_MFORWARD(in_dev)) rth->dst.input = ip_mr_input; #endif RT_CACHE_STAT_INC(in_slow_mc); skb_dst_set(skb, &rth->dst); return 0; e_nobufs: return -ENOBUFS; e_inval: return -EINVAL; e_err: return err; } static void ip_handle_martian_source(struct net_device *dev, struct in_device *in_dev, struct sk_buff *skb, __be32 daddr, __be32 saddr) { RT_CACHE_STAT_INC(in_martian_src); #ifdef CONFIG_IP_ROUTE_VERBOSE if (IN_DEV_LOG_MARTIANS(in_dev) && net_ratelimit()) { /* * RFC1812 recommendation, if source is martian, * the only hint is MAC header. */ pr_warn("martian source %pI4 from %pI4, on dev %s\n", &daddr, &saddr, dev->name); if (dev->hard_header_len && skb_mac_header_was_set(skb)) { print_hex_dump(KERN_WARNING, "ll header: ", DUMP_PREFIX_OFFSET, 16, 1, skb_mac_header(skb), dev->hard_header_len, true); } } #endif } /* called in rcu_read_lock() section */ static int __mkroute_input(struct sk_buff *skb, const struct fib_result *res, struct in_device *in_dev, __be32 daddr, __be32 saddr, u32 tos) { struct fib_nh_exception *fnhe; struct rtable *rth; int err; struct in_device *out_dev; unsigned int flags = 0; bool do_cache; u32 itag = 0; /* get a working reference to the output device */ out_dev = __in_dev_get_rcu(FIB_RES_DEV(*res)); if (out_dev == NULL) { net_crit_ratelimited("Bug in ip_route_input_slow(). Please report.\n"); return -EINVAL; } err = fib_validate_source(skb, saddr, daddr, tos, FIB_RES_OIF(*res), in_dev->dev, in_dev, &itag); if (err < 0) { ip_handle_martian_source(in_dev->dev, in_dev, skb, daddr, saddr); goto cleanup; } do_cache = res->fi && !itag; if (out_dev == in_dev && err && IN_DEV_TX_REDIRECTS(out_dev) && skb->protocol == htons(ETH_P_IP) && (IN_DEV_SHARED_MEDIA(out_dev) || inet_addr_onlink(out_dev, saddr, FIB_RES_GW(*res)))) IPCB(skb)->flags |= IPSKB_DOREDIRECT; if (skb->protocol != htons(ETH_P_IP)) { /* Not IP (i.e. ARP). Do not create route, if it is * invalid for proxy arp. DNAT routes are always valid. * * Proxy arp feature have been extended to allow, ARP * replies back to the same interface, to support * Private VLAN switch technologies. See arp.c. */ if (out_dev == in_dev && IN_DEV_PROXY_ARP_PVLAN(in_dev) == 0) { err = -EINVAL; goto cleanup; } } fnhe = find_exception(&FIB_RES_NH(*res), daddr); if (do_cache) { if (fnhe != NULL) rth = rcu_dereference(fnhe->fnhe_rth_input); else rth = rcu_dereference(FIB_RES_NH(*res).nh_rth_input); if (rt_cache_valid(rth)) { skb_dst_set_noref(skb, &rth->dst); goto out; } } rth = rt_dst_alloc(out_dev->dev, IN_DEV_CONF_GET(in_dev, NOPOLICY), IN_DEV_CONF_GET(out_dev, NOXFRM), do_cache); if (!rth) { err = -ENOBUFS; goto cleanup; } rth->rt_genid = rt_genid_ipv4(dev_net(rth->dst.dev)); rth->rt_flags = flags; rth->rt_type = res->type; rth->rt_is_input = 1; rth->rt_iif = 0; rth->rt_pmtu = 0; rth->rt_gateway = 0; rth->rt_uses_gateway = 0; INIT_LIST_HEAD(&rth->rt_uncached); RT_CACHE_STAT_INC(in_slow_tot); rth->dst.input = ip_forward; rth->dst.output = ip_output; rt_set_nexthop(rth, daddr, res, fnhe, res->fi, res->type, itag); skb_dst_set(skb, &rth->dst); out: err = 0; cleanup: return err; } static int ip_mkroute_input(struct sk_buff *skb, struct fib_result *res, const struct flowi4 *fl4, struct in_device *in_dev, __be32 daddr, __be32 saddr, u32 tos) { #ifdef CONFIG_IP_ROUTE_MULTIPATH if (res->fi && res->fi->fib_nhs > 1) fib_select_multipath(res); #endif /* create a routing cache entry */ return __mkroute_input(skb, res, in_dev, daddr, saddr, tos); } /* * NOTE. We drop all the packets that has local source * addresses, because every properly looped back packet * must have correct destination already attached by output routine. * * Such approach solves two big problems: * 1. Not simplex devices are handled properly. * 2. IP spoofing attempts are filtered with 100% of guarantee. * called with rcu_read_lock() */ static int ip_route_input_slow(struct sk_buff *skb, __be32 daddr, __be32 saddr, u8 tos, struct net_device *dev) { struct fib_result res; struct in_device *in_dev = __in_dev_get_rcu(dev); struct flowi4 fl4; unsigned int flags = 0; u32 itag = 0; struct rtable *rth; int err = -EINVAL; struct net *net = dev_net(dev); bool do_cache; /* IP on this device is disabled. */ if (!in_dev) goto out; /* Check for the most weird martians, which can be not detected by fib_lookup. */ if (ipv4_is_multicast(saddr) || ipv4_is_lbcast(saddr)) goto martian_source; res.fi = NULL; if (ipv4_is_lbcast(daddr) || (saddr == 0 && daddr == 0)) goto brd_input; /* Accept zero addresses only to limited broadcast; * I even do not know to fix it or not. Waiting for complains :-) */ if (ipv4_is_zeronet(saddr)) goto martian_source; if (ipv4_is_zeronet(daddr)) goto martian_destination; /* Following code try to avoid calling IN_DEV_NET_ROUTE_LOCALNET(), * and call it once if daddr or/and saddr are loopback addresses */ if (ipv4_is_loopback(daddr)) { if (!IN_DEV_NET_ROUTE_LOCALNET(in_dev, net)) goto martian_destination; } else if (ipv4_is_loopback(saddr)) { if (!IN_DEV_NET_ROUTE_LOCALNET(in_dev, net)) goto martian_source; } /* * Now we are ready to route packet. */ fl4.flowi4_oif = 0; fl4.flowi4_iif = dev->ifindex; fl4.flowi4_mark = skb->mark; fl4.flowi4_tos = tos; fl4.flowi4_scope = RT_SCOPE_UNIVERSE; fl4.daddr = daddr; fl4.saddr = saddr; err = fib_lookup(net, &fl4, &res); if (err != 0) { if (!IN_DEV_FORWARD(in_dev)) err = -EHOSTUNREACH; goto no_route; } if (res.type == RTN_BROADCAST) goto brd_input; if (res.type == RTN_LOCAL) { err = fib_validate_source(skb, saddr, daddr, tos, LOOPBACK_IFINDEX, dev, in_dev, &itag); if (err < 0) goto martian_source_keep_err; goto local_input; } if (!IN_DEV_FORWARD(in_dev)) { err = -EHOSTUNREACH; goto no_route; } if (res.type != RTN_UNICAST) goto martian_destination; err = ip_mkroute_input(skb, &res, &fl4, in_dev, daddr, saddr, tos); out: return err; brd_input: if (skb->protocol != htons(ETH_P_IP)) goto e_inval; if (!ipv4_is_zeronet(saddr)) { err = fib_validate_source(skb, saddr, 0, tos, 0, dev, in_dev, &itag); if (err < 0) goto martian_source_keep_err; } flags |= RTCF_BROADCAST; res.type = RTN_BROADCAST; RT_CACHE_STAT_INC(in_brd); local_input: do_cache = false; if (res.fi) { if (!itag) { rth = rcu_dereference(FIB_RES_NH(res).nh_rth_input); if (rt_cache_valid(rth)) { skb_dst_set_noref(skb, &rth->dst); err = 0; goto out; } do_cache = true; } } rth = rt_dst_alloc(net->loopback_dev, IN_DEV_CONF_GET(in_dev, NOPOLICY), false, do_cache); if (!rth) goto e_nobufs; rth->dst.input= ip_local_deliver; rth->dst.output= ip_rt_bug; #ifdef CONFIG_IP_ROUTE_CLASSID rth->dst.tclassid = itag; #endif rth->rt_genid = rt_genid_ipv4(net); rth->rt_flags = flags|RTCF_LOCAL; rth->rt_type = res.type; rth->rt_is_input = 1; rth->rt_iif = 0; rth->rt_pmtu = 0; rth->rt_gateway = 0; rth->rt_uses_gateway = 0; INIT_LIST_HEAD(&rth->rt_uncached); RT_CACHE_STAT_INC(in_slow_tot); if (res.type == RTN_UNREACHABLE) { rth->dst.input= ip_error; rth->dst.error= -err; rth->rt_flags &= ~RTCF_LOCAL; } if (do_cache) { if (unlikely(!rt_cache_route(&FIB_RES_NH(res), rth))) { rth->dst.flags |= DST_NOCACHE; rt_add_uncached_list(rth); } } skb_dst_set(skb, &rth->dst); err = 0; goto out; no_route: RT_CACHE_STAT_INC(in_no_route); res.type = RTN_UNREACHABLE; if (err == -ESRCH) err = -ENETUNREACH; goto local_input; /* * Do not cache martian addresses: they should be logged (RFC1812) */ martian_destination: RT_CACHE_STAT_INC(in_martian_dst); #ifdef CONFIG_IP_ROUTE_VERBOSE if (IN_DEV_LOG_MARTIANS(in_dev)) net_warn_ratelimited("martian destination %pI4 from %pI4, dev %s\n", &daddr, &saddr, dev->name); #endif e_inval: err = -EINVAL; goto out; e_nobufs: err = -ENOBUFS; goto out; martian_source: err = -EINVAL; martian_source_keep_err: ip_handle_martian_source(dev, in_dev, skb, daddr, saddr); goto out; } int ip_route_input_noref(struct sk_buff *skb, __be32 daddr, __be32 saddr, u8 tos, struct net_device *dev) { int res; rcu_read_lock(); /* Multicast recognition logic is moved from route cache to here. The problem was that too many Ethernet cards have broken/missing hardware multicast filters :-( As result the host on multicasting network acquires a lot of useless route cache entries, sort of SDR messages from all the world. Now we try to get rid of them. Really, provided software IP multicast filter is organized reasonably (at least, hashed), it does not result in a slowdown comparing with route cache reject entries. Note, that multicast routers are not affected, because route cache entry is created eventually. */ if (ipv4_is_multicast(daddr)) { struct in_device *in_dev = __in_dev_get_rcu(dev); if (in_dev) { int our = ip_check_mc_rcu(in_dev, daddr, saddr, ip_hdr(skb)->protocol); if (our #ifdef CONFIG_IP_MROUTE || (!ipv4_is_local_multicast(daddr) && IN_DEV_MFORWARD(in_dev)) #endif ) { int res = ip_route_input_mc(skb, daddr, saddr, tos, dev, our); rcu_read_unlock(); return res; } } rcu_read_unlock(); return -EINVAL; } res = ip_route_input_slow(skb, daddr, saddr, tos, dev); rcu_read_unlock(); return res; } EXPORT_SYMBOL(ip_route_input_noref); /* called with rcu_read_lock() */ static struct rtable *__mkroute_output(const struct fib_result *res, const struct flowi4 *fl4, int orig_oif, struct net_device *dev_out, unsigned int flags) { struct fib_info *fi = res->fi; struct fib_nh_exception *fnhe; struct in_device *in_dev; u16 type = res->type; struct rtable *rth; bool do_cache; in_dev = __in_dev_get_rcu(dev_out); if (!in_dev) return ERR_PTR(-EINVAL); if (likely(!IN_DEV_ROUTE_LOCALNET(in_dev))) if (ipv4_is_loopback(fl4->saddr) && !(dev_out->flags & IFF_LOOPBACK)) return ERR_PTR(-EINVAL); if (ipv4_is_lbcast(fl4->daddr)) type = RTN_BROADCAST; else if (ipv4_is_multicast(fl4->daddr)) type = RTN_MULTICAST; else if (ipv4_is_zeronet(fl4->daddr)) return ERR_PTR(-EINVAL); if (dev_out->flags & IFF_LOOPBACK) flags |= RTCF_LOCAL; do_cache = true; if (type == RTN_BROADCAST) { flags |= RTCF_BROADCAST | RTCF_LOCAL; fi = NULL; } else if (type == RTN_MULTICAST) { flags |= RTCF_MULTICAST | RTCF_LOCAL; if (!ip_check_mc_rcu(in_dev, fl4->daddr, fl4->saddr, fl4->flowi4_proto)) flags &= ~RTCF_LOCAL; else do_cache = false; /* If multicast route do not exist use * default one, but do not gateway in this case. * Yes, it is hack. */ if (fi && res->prefixlen < 4) fi = NULL; } fnhe = NULL; do_cache &= fi != NULL; if (do_cache) { struct rtable __rcu **prth; struct fib_nh *nh = &FIB_RES_NH(*res); fnhe = find_exception(nh, fl4->daddr); if (fnhe) prth = &fnhe->fnhe_rth_output; else { if (unlikely(fl4->flowi4_flags & FLOWI_FLAG_KNOWN_NH && !(nh->nh_gw && nh->nh_scope == RT_SCOPE_LINK))) { do_cache = false; goto add; } prth = __this_cpu_ptr(nh->nh_pcpu_rth_output); } rth = rcu_dereference(*prth); if (rt_cache_valid(rth)) { dst_hold(&rth->dst); return rth; } } add: rth = rt_dst_alloc(dev_out, IN_DEV_CONF_GET(in_dev, NOPOLICY), IN_DEV_CONF_GET(in_dev, NOXFRM), do_cache); if (!rth) return ERR_PTR(-ENOBUFS); rth->dst.output = ip_output; rth->rt_genid = rt_genid_ipv4(dev_net(dev_out)); rth->rt_flags = flags; rth->rt_type = type; rth->rt_is_input = 0; rth->rt_iif = orig_oif ? : 0; rth->rt_pmtu = 0; rth->rt_gateway = 0; rth->rt_uses_gateway = 0; INIT_LIST_HEAD(&rth->rt_uncached); RT_CACHE_STAT_INC(out_slow_tot); if (flags & RTCF_LOCAL) rth->dst.input = ip_local_deliver; if (flags & (RTCF_BROADCAST | RTCF_MULTICAST)) { if (flags & RTCF_LOCAL && !(dev_out->flags & IFF_LOOPBACK)) { rth->dst.output = ip_mc_output; RT_CACHE_STAT_INC(out_slow_mc); } #ifdef CONFIG_IP_MROUTE if (type == RTN_MULTICAST) { if (IN_DEV_MFORWARD(in_dev) && !ipv4_is_local_multicast(fl4->daddr)) { rth->dst.input = ip_mr_input; rth->dst.output = ip_mc_output; } } #endif } rt_set_nexthop(rth, fl4->daddr, res, fnhe, fi, type, 0); return rth; } /* * Major route resolver routine. */ struct rtable *__ip_route_output_key(struct net *net, struct flowi4 *fl4) { struct net_device *dev_out = NULL; __u8 tos = RT_FL_TOS(fl4); unsigned int flags = 0; struct fib_result res; struct rtable *rth; int orig_oif; res.tclassid = 0; res.fi = NULL; res.table = NULL; orig_oif = fl4->flowi4_oif; fl4->flowi4_iif = LOOPBACK_IFINDEX; fl4->flowi4_tos = tos & IPTOS_RT_MASK; fl4->flowi4_scope = ((tos & RTO_ONLINK) ? RT_SCOPE_LINK : RT_SCOPE_UNIVERSE); rcu_read_lock(); if (fl4->saddr) { rth = ERR_PTR(-EINVAL); if (ipv4_is_multicast(fl4->saddr) || ipv4_is_lbcast(fl4->saddr) || ipv4_is_zeronet(fl4->saddr)) goto out; /* I removed check for oif == dev_out->oif here. It was wrong for two reasons: 1. ip_dev_find(net, saddr) can return wrong iface, if saddr is assigned to multiple interfaces. 2. Moreover, we are allowed to send packets with saddr of another iface. --ANK */ if (fl4->flowi4_oif == 0 && (ipv4_is_multicast(fl4->daddr) || ipv4_is_lbcast(fl4->daddr))) { /* It is equivalent to inet_addr_type(saddr) == RTN_LOCAL */ dev_out = __ip_dev_find(net, fl4->saddr, false); if (dev_out == NULL) goto out; /* Special hack: user can direct multicasts and limited broadcast via necessary interface without fiddling with IP_MULTICAST_IF or IP_PKTINFO. This hack is not just for fun, it allows vic,vat and friends to work. They bind socket to loopback, set ttl to zero and expect that it will work. From the viewpoint of routing cache they are broken, because we are not allowed to build multicast path with loopback source addr (look, routing cache cannot know, that ttl is zero, so that packet will not leave this host and route is valid). Luckily, this hack is good workaround. */ fl4->flowi4_oif = dev_out->ifindex; goto make_route; } if (!(fl4->flowi4_flags & FLOWI_FLAG_ANYSRC)) { /* It is equivalent to inet_addr_type(saddr) == RTN_LOCAL */ if (!__ip_dev_find(net, fl4->saddr, false)) goto out; } } if (fl4->flowi4_oif) { dev_out = dev_get_by_index_rcu(net, fl4->flowi4_oif); rth = ERR_PTR(-ENODEV); if (dev_out == NULL) goto out; /* RACE: Check return value of inet_select_addr instead. */ if (!(dev_out->flags & IFF_UP) || !__in_dev_get_rcu(dev_out)) { rth = ERR_PTR(-ENETUNREACH); goto out; } if (ipv4_is_local_multicast(fl4->daddr) || ipv4_is_lbcast(fl4->daddr)) { if (!fl4->saddr) fl4->saddr = inet_select_addr(dev_out, 0, RT_SCOPE_LINK); goto make_route; } if (!fl4->saddr) { if (ipv4_is_multicast(fl4->daddr)) fl4->saddr = inet_select_addr(dev_out, 0, fl4->flowi4_scope); else if (!fl4->daddr) fl4->saddr = inet_select_addr(dev_out, 0, RT_SCOPE_HOST); } } if (!fl4->daddr) { fl4->daddr = fl4->saddr; if (!fl4->daddr) fl4->daddr = fl4->saddr = htonl(INADDR_LOOPBACK); dev_out = net->loopback_dev; fl4->flowi4_oif = LOOPBACK_IFINDEX; res.type = RTN_LOCAL; flags |= RTCF_LOCAL; goto make_route; } if (fib_lookup(net, fl4, &res)) { res.fi = NULL; res.table = NULL; if (fl4->flowi4_oif) { /* Apparently, routing tables are wrong. Assume, that the destination is on link. WHY? DW. Because we are allowed to send to iface even if it has NO routes and NO assigned addresses. When oif is specified, routing tables are looked up with only one purpose: to catch if destination is gatewayed, rather than direct. Moreover, if MSG_DONTROUTE is set, we send packet, ignoring both routing tables and ifaddr state. --ANK We could make it even if oif is unknown, likely IPv6, but we do not. */ if (fl4->saddr == 0) fl4->saddr = inet_select_addr(dev_out, 0, RT_SCOPE_LINK); res.type = RTN_UNICAST; goto make_route; } rth = ERR_PTR(-ENETUNREACH); goto out; } if (res.type == RTN_LOCAL) { if (!fl4->saddr) { if (res.fi->fib_prefsrc) fl4->saddr = res.fi->fib_prefsrc; else fl4->saddr = fl4->daddr; } dev_out = net->loopback_dev; fl4->flowi4_oif = dev_out->ifindex; flags |= RTCF_LOCAL; goto make_route; } #ifdef CONFIG_IP_ROUTE_MULTIPATH if (res.fi->fib_nhs > 1 && fl4->flowi4_oif == 0) fib_select_multipath(&res); else #endif if (!res.prefixlen && res.table->tb_num_default > 1 && res.type == RTN_UNICAST && !fl4->flowi4_oif) fib_select_default(&res); if (!fl4->saddr) fl4->saddr = FIB_RES_PREFSRC(net, res); dev_out = FIB_RES_DEV(res); fl4->flowi4_oif = dev_out->ifindex; make_route: rth = __mkroute_output(&res, fl4, orig_oif, dev_out, flags); out: rcu_read_unlock(); return rth; } EXPORT_SYMBOL_GPL(__ip_route_output_key); static struct dst_entry *ipv4_blackhole_dst_check(struct dst_entry *dst, u32 cookie) { return NULL; } static unsigned int ipv4_blackhole_mtu(const struct dst_entry *dst) { unsigned int mtu = dst_metric_raw(dst, RTAX_MTU); return mtu ? : dst->dev->mtu; } static void ipv4_rt_blackhole_update_pmtu(struct dst_entry *dst, struct sock *sk, struct sk_buff *skb, u32 mtu) { } static void ipv4_rt_blackhole_redirect(struct dst_entry *dst, struct sock *sk, struct sk_buff *skb) { } static u32 *ipv4_rt_blackhole_cow_metrics(struct dst_entry *dst, unsigned long old) { return NULL; } static struct dst_ops ipv4_dst_blackhole_ops = { .family = AF_INET, .protocol = cpu_to_be16(ETH_P_IP), .check = ipv4_blackhole_dst_check, .mtu = ipv4_blackhole_mtu, .default_advmss = ipv4_default_advmss, .update_pmtu = ipv4_rt_blackhole_update_pmtu, .redirect = ipv4_rt_blackhole_redirect, .cow_metrics = ipv4_rt_blackhole_cow_metrics, .neigh_lookup = ipv4_neigh_lookup, }; struct dst_entry *ipv4_blackhole_route(struct net *net, struct dst_entry *dst_orig) { struct rtable *ort = (struct rtable *) dst_orig; struct rtable *rt; rt = dst_alloc(&ipv4_dst_blackhole_ops, NULL, 1, DST_OBSOLETE_NONE, 0); if (rt) { struct dst_entry *new = &rt->dst; new->__use = 1; new->input = dst_discard; new->output = dst_discard; new->dev = ort->dst.dev; if (new->dev) dev_hold(new->dev); rt->rt_is_input = ort->rt_is_input; rt->rt_iif = ort->rt_iif; rt->rt_pmtu = ort->rt_pmtu; rt->rt_genid = rt_genid_ipv4(net); rt->rt_flags = ort->rt_flags; rt->rt_type = ort->rt_type; rt->rt_gateway = ort->rt_gateway; rt->rt_uses_gateway = ort->rt_uses_gateway; INIT_LIST_HEAD(&rt->rt_uncached); dst_free(new); } dst_release(dst_orig); return rt ? &rt->dst : ERR_PTR(-ENOMEM); } struct rtable *ip_route_output_flow(struct net *net, struct flowi4 *flp4, struct sock *sk) { struct rtable *rt = __ip_route_output_key(net, flp4); if (IS_ERR(rt)) return rt; if (flp4->flowi4_proto) rt = (struct rtable *)xfrm_lookup_route(net, &rt->dst, flowi4_to_flowi(flp4), sk, 0); return rt; } EXPORT_SYMBOL_GPL(ip_route_output_flow); static int rt_fill_info(struct net *net, __be32 dst, __be32 src, struct flowi4 *fl4, struct sk_buff *skb, u32 portid, u32 seq, int event, int nowait, unsigned int flags) { struct rtable *rt = skb_rtable(skb); struct rtmsg *r; struct nlmsghdr *nlh; unsigned long expires = 0; u32 error; u32 metrics[RTAX_MAX]; nlh = nlmsg_put(skb, portid, seq, event, sizeof(*r), flags); if (nlh == NULL) return -EMSGSIZE; r = nlmsg_data(nlh); r->rtm_family = AF_INET; r->rtm_dst_len = 32; r->rtm_src_len = 0; r->rtm_tos = fl4->flowi4_tos; r->rtm_table = RT_TABLE_MAIN; if (nla_put_u32(skb, RTA_TABLE, RT_TABLE_MAIN)) goto nla_put_failure; r->rtm_type = rt->rt_type; r->rtm_scope = RT_SCOPE_UNIVERSE; r->rtm_protocol = RTPROT_UNSPEC; r->rtm_flags = (rt->rt_flags & ~0xFFFF) | RTM_F_CLONED; if (rt->rt_flags & RTCF_NOTIFY) r->rtm_flags |= RTM_F_NOTIFY; if (IPCB(skb)->flags & IPSKB_DOREDIRECT) r->rtm_flags |= RTCF_DOREDIRECT; if (nla_put_be32(skb, RTA_DST, dst)) goto nla_put_failure; if (src) { r->rtm_src_len = 32; if (nla_put_be32(skb, RTA_SRC, src)) goto nla_put_failure; } if (rt->dst.dev && nla_put_u32(skb, RTA_OIF, rt->dst.dev->ifindex)) goto nla_put_failure; #ifdef CONFIG_IP_ROUTE_CLASSID if (rt->dst.tclassid && nla_put_u32(skb, RTA_FLOW, rt->dst.tclassid)) goto nla_put_failure; #endif if (!rt_is_input_route(rt) && fl4->saddr != src) { if (nla_put_be32(skb, RTA_PREFSRC, fl4->saddr)) goto nla_put_failure; } if (rt->rt_uses_gateway && nla_put_be32(skb, RTA_GATEWAY, rt->rt_gateway)) goto nla_put_failure; expires = rt->dst.expires; if (expires) { unsigned long now = jiffies; if (time_before(now, expires)) expires -= now; else expires = 0; } memcpy(metrics, dst_metrics_ptr(&rt->dst), sizeof(metrics)); if (rt->rt_pmtu && expires) metrics[RTAX_MTU - 1] = rt->rt_pmtu; if (rtnetlink_put_metrics(skb, metrics) < 0) goto nla_put_failure; if (fl4->flowi4_mark && nla_put_u32(skb, RTA_MARK, fl4->flowi4_mark)) goto nla_put_failure; error = rt->dst.error; if (rt_is_input_route(rt)) { #ifdef CONFIG_IP_MROUTE if (ipv4_is_multicast(dst) && !ipv4_is_local_multicast(dst) && IPV4_DEVCONF_ALL(net, MC_FORWARDING)) { int err = ipmr_get_route(net, skb, fl4->saddr, fl4->daddr, r, nowait); if (err <= 0) { if (!nowait) { if (err == 0) return 0; goto nla_put_failure; } else { if (err == -EMSGSIZE) goto nla_put_failure; error = err; } } } else #endif if (nla_put_u32(skb, RTA_IIF, skb->dev->ifindex)) goto nla_put_failure; } if (rtnl_put_cacheinfo(skb, &rt->dst, 0, expires, error) < 0) goto nla_put_failure; return nlmsg_end(skb, nlh); nla_put_failure: nlmsg_cancel(skb, nlh); return -EMSGSIZE; } static int inet_rtm_getroute(struct sk_buff *in_skb, struct nlmsghdr *nlh) { struct net *net = sock_net(in_skb->sk); struct rtmsg *rtm; struct nlattr *tb[RTA_MAX+1]; struct rtable *rt = NULL; struct flowi4 fl4; __be32 dst = 0; __be32 src = 0; u32 iif; int err; int mark; struct sk_buff *skb; err = nlmsg_parse(nlh, sizeof(*rtm), tb, RTA_MAX, rtm_ipv4_policy); if (err < 0) goto errout; rtm = nlmsg_data(nlh); skb = alloc_skb(NLMSG_GOODSIZE, GFP_KERNEL); if (skb == NULL) { err = -ENOBUFS; goto errout; } /* Reserve room for dummy headers, this skb can pass through good chunk of routing engine. */ skb_reset_mac_header(skb); skb_reset_network_header(skb); /* Bugfix: need to give ip_route_input enough of an IP header to not gag. */ ip_hdr(skb)->protocol = IPPROTO_ICMP; skb_reserve(skb, MAX_HEADER + sizeof(struct iphdr)); src = tb[RTA_SRC] ? nla_get_be32(tb[RTA_SRC]) : 0; dst = tb[RTA_DST] ? nla_get_be32(tb[RTA_DST]) : 0; iif = tb[RTA_IIF] ? nla_get_u32(tb[RTA_IIF]) : 0; mark = tb[RTA_MARK] ? nla_get_u32(tb[RTA_MARK]) : 0; memset(&fl4, 0, sizeof(fl4)); fl4.daddr = dst; fl4.saddr = src; fl4.flowi4_tos = rtm->rtm_tos; fl4.flowi4_oif = tb[RTA_OIF] ? nla_get_u32(tb[RTA_OIF]) : 0; fl4.flowi4_mark = mark; if (iif) { struct net_device *dev; dev = __dev_get_by_index(net, iif); if (dev == NULL) { err = -ENODEV; goto errout_free; } skb->protocol = htons(ETH_P_IP); skb->dev = dev; skb->mark = mark; local_bh_disable(); err = ip_route_input(skb, dst, src, rtm->rtm_tos, dev); local_bh_enable(); rt = skb_rtable(skb); if (err == 0 && rt->dst.error) err = -rt->dst.error; } else { rt = ip_route_output_key(net, &fl4); err = 0; if (IS_ERR(rt)) err = PTR_ERR(rt); } if (err) goto errout_free; skb_dst_set(skb, &rt->dst); if (rtm->rtm_flags & RTM_F_NOTIFY) rt->rt_flags |= RTCF_NOTIFY; err = rt_fill_info(net, dst, src, &fl4, skb, NETLINK_CB(in_skb).portid, nlh->nlmsg_seq, RTM_NEWROUTE, 0, 0); if (err <= 0) goto errout_free; err = rtnl_unicast(skb, net, NETLINK_CB(in_skb).portid); errout: return err; errout_free: kfree_skb(skb); goto errout; } int ip_rt_dump(struct sk_buff *skb, struct netlink_callback *cb) { return skb->len; } void ip_rt_multicast_event(struct in_device *in_dev) { rt_cache_flush(dev_net(in_dev->dev)); } #ifdef CONFIG_SYSCTL static int ip_rt_gc_timeout __read_mostly = RT_GC_TIMEOUT; static int ip_rt_gc_interval __read_mostly = 60 * HZ; static int ip_rt_gc_min_interval __read_mostly = HZ / 2; static int ip_rt_gc_elasticity __read_mostly = 8; static int ipv4_sysctl_rtcache_flush(struct ctl_table *__ctl, int write, void __user *buffer, size_t *lenp, loff_t *ppos) { struct net *net = (struct net *)__ctl->extra1; if (write) { rt_cache_flush(net); fnhe_genid_bump(net); return 0; } return -EINVAL; } static struct ctl_table ipv4_route_table[] = { { .procname = "gc_thresh", .data = &ipv4_dst_ops.gc_thresh, .maxlen = sizeof(int), .mode = 0644, .proc_handler = proc_dointvec, }, { .procname = "max_size", .data = &ip_rt_max_size, .maxlen = sizeof(int), .mode = 0644, .proc_handler = proc_dointvec, }, { /* Deprecated. Use gc_min_interval_ms */ .procname = "gc_min_interval", .data = &ip_rt_gc_min_interval, .maxlen = sizeof(int), .mode = 0644, .proc_handler = proc_dointvec_jiffies, }, { .procname = "gc_min_interval_ms", .data = &ip_rt_gc_min_interval, .maxlen = sizeof(int), .mode = 0644, .proc_handler = proc_dointvec_ms_jiffies, }, { .procname = "gc_timeout", .data = &ip_rt_gc_timeout, .maxlen = sizeof(int), .mode = 0644, .proc_handler = proc_dointvec_jiffies, }, { .procname = "gc_interval", .data = &ip_rt_gc_interval, .maxlen = sizeof(int), .mode = 0644, .proc_handler = proc_dointvec_jiffies, }, { .procname = "redirect_load", .data = &ip_rt_redirect_load, .maxlen = sizeof(int), .mode = 0644, .proc_handler = proc_dointvec, }, { .procname = "redirect_number", .data = &ip_rt_redirect_number, .maxlen = sizeof(int), .mode = 0644, .proc_handler = proc_dointvec, }, { .procname = "redirect_silence", .data = &ip_rt_redirect_silence, .maxlen = sizeof(int), .mode = 0644, .proc_handler = proc_dointvec, }, { .procname = "error_cost", .data = &ip_rt_error_cost, .maxlen = sizeof(int), .mode = 0644, .proc_handler = proc_dointvec, }, { .procname = "error_burst", .data = &ip_rt_error_burst, .maxlen = sizeof(int), .mode = 0644, .proc_handler = proc_dointvec, }, { .procname = "gc_elasticity", .data = &ip_rt_gc_elasticity, .maxlen = sizeof(int), .mode = 0644, .proc_handler = proc_dointvec, }, { .procname = "mtu_expires", .data = &ip_rt_mtu_expires, .maxlen = sizeof(int), .mode = 0644, .proc_handler = proc_dointvec_jiffies, }, { .procname = "min_pmtu", .data = &ip_rt_min_pmtu, .maxlen = sizeof(int), .mode = 0644, .proc_handler = proc_dointvec, }, { .procname = "min_adv_mss", .data = &ip_rt_min_advmss, .maxlen = sizeof(int), .mode = 0644, .proc_handler = proc_dointvec, }, { } }; static struct ctl_table ipv4_route_flush_table[] = { { .procname = "flush", .maxlen = sizeof(int), .mode = 0200, .proc_handler = ipv4_sysctl_rtcache_flush, .extra1 = &init_net, }, { }, }; static __net_init int sysctl_route_net_init(struct net *net) { ctl_table_no_const *tbl = NULL; if (!net_eq(net, &init_net)) { tbl = kmemdup(ipv4_route_flush_table, sizeof(ipv4_route_flush_table), GFP_KERNEL); if (tbl == NULL) goto err_dup; /* Don't export sysctls to unprivileged users */ if (net->user_ns != &init_user_ns) tbl[0].procname = NULL; tbl[0].extra1 = net; net->ipv4.route_hdr = register_net_sysctl(net, "net/ipv4/route", tbl); } else net->ipv4.route_hdr = register_net_sysctl(net, "net/ipv4/route", ipv4_route_flush_table); if (net->ipv4.route_hdr == NULL) goto err_reg; return 0; err_reg: kfree(tbl); err_dup: return -ENOMEM; } static __net_exit void sysctl_route_net_exit(struct net *net) { struct ctl_table *tbl; tbl = net->ipv4.route_hdr->ctl_table_arg; unregister_net_sysctl_table(net->ipv4.route_hdr); BUG_ON(tbl == ipv4_route_flush_table); kfree(tbl); } static __net_initdata struct pernet_operations sysctl_route_ops = { .init = sysctl_route_net_init, .exit = sysctl_route_net_exit, }; #endif static __net_init int rt_genid_init(struct net *net) { atomic_set_unchecked(&net->ipv4.rt_genid, 0); atomic_set_unchecked(&net->fnhe_genid, 0); get_random_bytes(&net->ipv4.dev_addr_genid, sizeof(net->ipv4.dev_addr_genid)); return 0; } static __net_initdata struct pernet_operations rt_genid_ops = { .init = rt_genid_init, }; static int __net_init ipv4_inetpeer_init(struct net *net) { struct inet_peer_base *bp = kmalloc(sizeof(*bp), GFP_KERNEL); if (!bp) return -ENOMEM; inet_peer_base_init(bp); net->ipv4.peers = bp; return 0; } static void __net_exit ipv4_inetpeer_exit(struct net *net) { struct inet_peer_base *bp = net->ipv4.peers; net->ipv4.peers = NULL; inetpeer_invalidate_tree(bp); kfree(bp); } static __net_initdata struct pernet_operations ipv4_inetpeer_ops = { .init = ipv4_inetpeer_init, .exit = ipv4_inetpeer_exit, }; #ifdef CONFIG_IP_ROUTE_CLASSID struct ip_rt_acct __percpu *ip_rt_acct __read_mostly; #endif /* CONFIG_IP_ROUTE_CLASSID */ int __init ip_rt_init(void) { int rc = 0; prandom_bytes(ip_idents, sizeof(ip_idents)); #ifdef CONFIG_IP_ROUTE_CLASSID ip_rt_acct = __alloc_percpu(256 * sizeof(struct ip_rt_acct), __alignof__(struct ip_rt_acct)); if (!ip_rt_acct) panic("IP: failed to allocate ip_rt_acct\n"); #endif ipv4_dst_ops.kmem_cachep = kmem_cache_create("ip_dst_cache", sizeof(struct rtable), 0, SLAB_HWCACHE_ALIGN|SLAB_PANIC, NULL); ipv4_dst_blackhole_ops.kmem_cachep = ipv4_dst_ops.kmem_cachep; if (dst_entries_init(&ipv4_dst_ops) < 0) panic("IP: failed to allocate ipv4_dst_ops counter\n"); if (dst_entries_init(&ipv4_dst_blackhole_ops) < 0) panic("IP: failed to allocate ipv4_dst_blackhole_ops counter\n"); ipv4_dst_ops.gc_thresh = ~0; ip_rt_max_size = INT_MAX; devinet_init(); ip_fib_init(); if (ip_rt_proc_init()) pr_err("Unable to create route proc files\n"); #ifdef CONFIG_XFRM xfrm_init(); xfrm4_init(); #endif rtnl_register(PF_INET, RTM_GETROUTE, inet_rtm_getroute, NULL, NULL); #ifdef CONFIG_SYSCTL register_pernet_subsys(&sysctl_route_ops); #endif register_pernet_subsys(&rt_genid_ops); register_pernet_subsys(&ipv4_inetpeer_ops); return rc; } #ifdef CONFIG_SYSCTL /* * We really need to sanitize the damn ipv4 init order, then all * this nonsense will go away. */ void __init ip_static_sysctl_init(void) { register_net_sysctl(&init_net, "net/ipv4/route", ipv4_route_table); } #endif
AdaLovelance/lxcGrsecKernels
linux-3.14.37/net/ipv4/route.c
C
gpl-2.0
68,343
<?php /** * @copyright 2009-2019 Vanilla Forums Inc. * @license GPL-2.0-only */ namespace Vanilla\Theme\Asset; use Vanilla\Theme\ThemeAssetFactory; /** * Style theme asset. */ class JavascriptThemeAsset extends ThemeAsset { /** @var bool */ protected $canMerge = true; /** @var string Javascript content of this asset. */ private $data; /** * Configure the JSON asset. * * @param string $data * @param string $url */ public function __construct(string $data, string $url) { $this->data = $data; $this->url = $url; } /** * @inheritdoc */ public function getDefaultType(): string { return ThemeAssetFactory::ASSET_TYPE_JS; } /** * @inheritdoc */ public function getContentType(): string { return "application/javascript"; } /** * @inheritdoc */ public function getValue() { return $this->data; } /** * @inheritdoc */ public function __toString(): string { return $this->data; } }
vanilla/vanilla
library/Vanilla/Theme/Asset/JavascriptThemeAsset.php
PHP
gpl-2.0
1,082
/* * drivers/input/touchscreen/doubletap2wake.c * * * Copyright (c) 2013, Dennis Rassmann <showp1984@gmail.com> * Copyright (c) 2015, Stanley "AngSanley"<me@angsanley.com> * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #include <linux/kernel.h> #include <linux/module.h> #include <linux/types.h> #include <linux/delay.h> #include <linux/init.h> #include <linux/err.h> #include <linux/input/doubletap2wake.h> #include <linux/slab.h> #include <linux/workqueue.h> #include <linux/input.h> #ifndef CONFIG_HAS_EARLYSUSPEND #include <linux/lcd_notify.h> #else #include <linux/earlysuspend.h> #endif #include <linux/hrtimer.h> #include <asm-generic/cputime.h> /* uncomment since no touchscreen defines android touch, do that here */ //#define ANDROID_TOUCH_DECLARED /* if Sweep2Wake is compiled it will already have taken care of this */ #ifdef CONFIG_TOUCHSCREEN_SWEEP2WAKE #define ANDROID_TOUCH_DECLARED #endif /* Version, author, desc, etc */ #define DRIVER_AUTHOR "Dennis Rassmann <showp1984@gmail.com>" #define DRIVER_DESCRIPTION "Doubletap2wake for almost any device" #define DRIVER_VERSION "1.0" #define LOGTAG "[doubletap2wake]: " MODULE_AUTHOR(DRIVER_AUTHOR); MODULE_DESCRIPTION(DRIVER_DESCRIPTION); MODULE_VERSION(DRIVER_VERSION); MODULE_LICENSE("GPLv2"); /* Tuneables */ #define DT2W_DEBUG 0 #define DT2W_DEFAULT 0 #define DT2W_PWRKEY_DUR 60 #define DT2W_FEATHER 200 #define DT2W_TIME 700 /* Resources */ int dt2w_switch = DT2W_DEFAULT; static cputime64_t tap_time_pre = 0; static int touch_x = 0, touch_y = 0, touch_nr = 0, x_pre = 0, y_pre = 0; static bool touch_x_called = false, touch_y_called = false, touch_cnt = true; static bool scr_suspended = false, exec_count = true; #ifndef CONFIG_HAS_EARLYSUSPEND static struct notifier_block dt2w_lcd_notif; #endif static struct input_dev * doubletap2wake_pwrdev; static DEFINE_MUTEX(pwrkeyworklock); static struct workqueue_struct *dt2w_input_wq; static struct work_struct dt2w_input_work; /* Read cmdline for dt2w */ static int __init read_dt2w_cmdline(char *dt2w) { if (strcmp(dt2w, "1") == 0) { pr_info("[cmdline_dt2w]: DoubleTap2Wake enabled. | dt2w='%s'\n", dt2w); dt2w_switch = 1; } else if (strcmp(dt2w, "0") == 0) { pr_info("[cmdline_dt2w]: DoubleTap2Wake disabled. | dt2w='%s'\n", dt2w); dt2w_switch = 0; } else { pr_info("[cmdline_dt2w]: No valid input found. Going with default: | dt2w='%u'\n", dt2w_switch); } return 1; } __setup("dt2w=", read_dt2w_cmdline); /* reset on finger release */ static void doubletap2wake_reset(void) { exec_count = true; touch_nr = 0; tap_time_pre = 0; x_pre = 0; y_pre = 0; } /* PowerKey work func */ static void doubletap2wake_presspwr(struct work_struct * doubletap2wake_presspwr_work) { if (!mutex_trylock(&pwrkeyworklock)) return; input_event(doubletap2wake_pwrdev, EV_KEY, KEY_POWER, 1); input_event(doubletap2wake_pwrdev, EV_SYN, 0, 0); msleep(DT2W_PWRKEY_DUR); input_event(doubletap2wake_pwrdev, EV_KEY, KEY_POWER, 0); input_event(doubletap2wake_pwrdev, EV_SYN, 0, 0); msleep(DT2W_PWRKEY_DUR); mutex_unlock(&pwrkeyworklock); return; } static DECLARE_WORK(doubletap2wake_presspwr_work, doubletap2wake_presspwr); /* PowerKey trigger */ static void doubletap2wake_pwrtrigger(void) { schedule_work(&doubletap2wake_presspwr_work); return; } /* unsigned */ static unsigned int calc_feather(int coord, int prev_coord) { int calc_coord = 0; calc_coord = coord-prev_coord; if (calc_coord < 0) calc_coord = calc_coord * (-1); return calc_coord; } /* init a new touch */ static void new_touch(int x, int y) { tap_time_pre = ktime_to_ms(ktime_get()); x_pre = x; y_pre = y; touch_nr++; } /* Doubletap2wake main function */ static void detect_doubletap2wake(int x, int y, bool st) { bool single_touch = st; #if DT2W_DEBUG pr_info(LOGTAG"x,y(%4d,%4d) single:%s\n", x, y, (single_touch) ? "true" : "false"); #endif if ((single_touch) && (dt2w_switch > 0) && (exec_count) && (touch_cnt)) { touch_cnt = false; if (touch_nr == 0) { new_touch(x, y); } else if (touch_nr == 1) { if ((calc_feather(x, x_pre) < DT2W_FEATHER) && (calc_feather(y, y_pre) < DT2W_FEATHER) && ((ktime_to_ms(ktime_get())-tap_time_pre) < DT2W_TIME)) touch_nr++; else { doubletap2wake_reset(); new_touch(x, y); } } else { doubletap2wake_reset(); new_touch(x, y); } if ((touch_nr > 1)) { pr_info(LOGTAG"ON\n"); exec_count = false; doubletap2wake_pwrtrigger(); doubletap2wake_reset(); } } } static void dt2w_input_callback(struct work_struct *unused) { detect_doubletap2wake(touch_x, touch_y, true); return; } static void dt2w_input_event(struct input_handle *handle, unsigned int type, unsigned int code, int value) { #if DT2W_DEBUG pr_info("doubletap2wake: code: %s|%u, val: %i\n", ((code==ABS_MT_POSITION_X) ? "X" : (code==ABS_MT_POSITION_Y) ? "Y" : (code==ABS_MT_TRACKING_ID) ? "ID" : "undef"), code, value); #endif if (!scr_suspended) return; if (code == ABS_MT_SLOT) { doubletap2wake_reset(); return; } if (code == ABS_MT_TRACKING_ID && value == -1) { touch_cnt = true; return; } if (code == ABS_MT_POSITION_X) { touch_x = value; touch_x_called = true; } if (code == ABS_MT_POSITION_Y) { touch_y = value; touch_y_called = true; } if (touch_x_called || touch_y_called) { touch_x_called = false; touch_y_called = false; queue_work_on(0, dt2w_input_wq, &dt2w_input_work); } } static int input_dev_filter(struct input_dev *dev) { if (strstr(dev->name, "touch") || strstr(dev->name, "ft5x06")) { return 0; } else { return 1; } } static int dt2w_input_connect(struct input_handler *handler, struct input_dev *dev, const struct input_device_id *id) { struct input_handle *handle; int error; if (input_dev_filter(dev)) return -ENODEV; handle = kzalloc(sizeof(struct input_handle), GFP_KERNEL); if (!handle) return -ENOMEM; handle->dev = dev; handle->handler = handler; handle->name = "dt2w"; error = input_register_handle(handle); if (error) goto err2; error = input_open_device(handle); if (error) goto err1; return 0; err1: input_unregister_handle(handle); err2: kfree(handle); return error; } static void dt2w_input_disconnect(struct input_handle *handle) { input_close_device(handle); input_unregister_handle(handle); kfree(handle); } static const struct input_device_id dt2w_ids[] = { { .driver_info = 1 }, { }, }; static struct input_handler dt2w_input_handler = { .event = dt2w_input_event, .connect = dt2w_input_connect, .disconnect = dt2w_input_disconnect, .name = "dt2w_inputreq", .id_table = dt2w_ids, }; #ifndef CONFIG_HAS_EARLYSUSPEND static int lcd_notifier_callback(struct notifier_block *this, unsigned long event, void *data) { switch (event) { case LCD_EVENT_ON_END: scr_suspended = false; break; case LCD_EVENT_OFF_END: scr_suspended = true; break; default: break; } return 0; } #else static void dt2w_early_suspend(struct early_suspend *h) { scr_suspended = true; } static void dt2w_late_resume(struct early_suspend *h) { scr_suspended = false; } static struct early_suspend dt2w_early_suspend_handler = { .level = EARLY_SUSPEND_LEVEL_BLANK_SCREEN, .suspend = dt2w_early_suspend, .resume = dt2w_late_resume, }; #endif /* * SYSFS stuff below here */ static ssize_t dt2w_doubletap2wake_show(struct device *dev, struct device_attribute *attr, char *buf) { size_t count = 0; count += sprintf(buf, "%d\n", dt2w_switch); return count; } static ssize_t dt2w_doubletap2wake_dump(struct device *dev, struct device_attribute *attr, const char *buf, size_t count) { if (buf[0] >= '0' && buf[0] <= '2' && buf[1] == '\n') if (dt2w_switch != buf[0] - '0') dt2w_switch = buf[0] - '0'; return count; } static DEVICE_ATTR(doubletap2wake, (S_IWUSR|S_IRUGO), dt2w_doubletap2wake_show, dt2w_doubletap2wake_dump); static ssize_t dt2w_version_show(struct device *dev, struct device_attribute *attr, char *buf) { size_t count = 0; count += sprintf(buf, "%s\n", DRIVER_VERSION); return count; } static ssize_t dt2w_version_dump(struct device *dev, struct device_attribute *attr, const char *buf, size_t count) { return count; } static DEVICE_ATTR(doubletap2wake_version, (S_IWUSR|S_IRUGO), dt2w_version_show, dt2w_version_dump); /* * INIT / EXIT stuff below here */ #ifdef ANDROID_TOUCH_DECLARED extern struct kobject *android_touch_kobj; #else struct kobject *android_touch_kobj; EXPORT_SYMBOL_GPL(android_touch_kobj); #endif static int __init doubletap2wake_init(void) { int rc = 0; doubletap2wake_pwrdev = input_allocate_device(); if (!doubletap2wake_pwrdev) { pr_err("Can't allocate suspend autotest power button\n"); goto err_alloc_dev; } input_set_capability(doubletap2wake_pwrdev, EV_KEY, KEY_POWER); doubletap2wake_pwrdev->name = "dt2w_pwrkey"; doubletap2wake_pwrdev->phys = "dt2w_pwrkey/input0"; rc = input_register_device(doubletap2wake_pwrdev); if (rc) { pr_err("%s: input_register_device err=%d\n", __func__, rc); goto err_input_dev; } dt2w_input_wq = create_workqueue("dt2wiwq"); if (!dt2w_input_wq) { pr_err("%s: Failed to create dt2wiwq workqueue\n", __func__); return -EFAULT; } INIT_WORK(&dt2w_input_work, dt2w_input_callback); rc = input_register_handler(&dt2w_input_handler); if (rc) pr_err("%s: Failed to register dt2w_input_handler\n", __func__); #ifndef CONFIG_HAS_EARLYSUSPEND dt2w_lcd_notif.notifier_call = lcd_notifier_callback; if (lcd_register_client(&dt2w_lcd_notif) != 0) { pr_err("%s: Failed to register lcd callback\n", __func__); } #else register_early_suspend(&dt2w_early_suspend_handler); #endif #ifndef ANDROID_TOUCH_DECLARED android_touch_kobj = kobject_create_and_add("android_touch", NULL) ; if (android_touch_kobj == NULL) { pr_warn("%s: android_touch_kobj create_and_add failed\n", __func__); } #endif rc = sysfs_create_file(android_touch_kobj, &dev_attr_doubletap2wake.attr); if (rc) { pr_warn("%s: sysfs_create_file failed for doubletap2wake\n", __func__); } rc = sysfs_create_file(android_touch_kobj, &dev_attr_doubletap2wake_version.attr); if (rc) { pr_warn("%s: sysfs_create_file failed for doubletap2wake_version\n", __func__); } err_input_dev: input_free_device(doubletap2wake_pwrdev); err_alloc_dev: pr_info(LOGTAG"%s done\n", __func__); return 0; } static void __exit doubletap2wake_exit(void) { #ifndef ANDROID_TOUCH_DECLARED kobject_del(android_touch_kobj); #endif #ifndef CONFIG_HAS_EARLYSUSPEND lcd_unregister_client(&dt2w_lcd_notif); #endif input_unregister_handler(&dt2w_input_handler); destroy_workqueue(dt2w_input_wq); input_unregister_device(doubletap2wake_pwrdev); input_free_device(doubletap2wake_pwrdev); return; } module_init(doubletap2wake_init); module_exit(doubletap2wake_exit);
AngSanley/AngsaKernel_armani
drivers/input/touchscreen/doubletap2wake.c
C
gpl-2.0
11,558
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html><head><meta http-equiv="Content-Type" content="text/html;charset=UTF-8"> <title>Member List</title> <link href="doxygen.css" rel="stylesheet" type="text/css"> <link href="tabs.css" rel="stylesheet" type="text/css"> </head><body> <img src="xmp_tagline_small.jpg" width="125" height="50" border="0"><p> <!-- Generated by Doxygen 1.8.11 --> <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="classes.html"><span>Class&#160;Index</span></a></li> <li><a href="hierarchy.html"><span>Class&#160;Hierarchy</span></a></li> <li><a href="functions.html"><span>Class&#160;Members</span></a></li> </ul> </div> </div><!-- top --> <div id="side-nav" class="ui-resizable side-nav-resizable"> <div id="nav-tree"> <div id="nav-tree-contents"> <div id="nav-sync" class="sync"></div> </div> </div> <div id="splitbar" style="-moz-user-select:none;" class="ui-resizable-handle"> </div> </div> <script type="text/javascript"> $(document).ready(function(){initNavTree('classAdobeXMPCore_1_1INameSpacePrefixMap__v1.html','');}); </script> <div id="doc-content"> <div class="header"> <div class="headertitle"> <div class="title">AdobeXMPCore::INameSpacePrefixMap_v1 Member List</div> </div> </div><!--header--> <div class="contents"> <p>This is the complete list of members for <a class="el" href="classAdobeXMPCore_1_1INameSpacePrefixMap__v1.html">AdobeXMPCore::INameSpacePrefixMap_v1</a>, including all inherited members.</p> <table class="directory"> <tr class="even"><td class="entry"><a class="el" href="classAdobeXMPCommon_1_1ISharedObject.html#ab90d4ec1fcd975a7ac62dcb866335cdc">Acquire</a>() const __NOTHROW__=0</td><td class="entry"><a class="el" href="classAdobeXMPCommon_1_1ISharedObject.html">AdobeXMPCommon::ISharedObject</a></td><td class="entry"><span class="mlabel">pure virtual</span></td></tr> <tr><td class="entry"><a class="el" href="classAdobeXMPCore_1_1INameSpacePrefixMap__v1.html#a6ed5fd946dfad6406539562178b3caeb">Clear</a>() __NOTHROW__=0</td><td class="entry"><a class="el" href="classAdobeXMPCore_1_1INameSpacePrefixMap__v1.html">AdobeXMPCore::INameSpacePrefixMap_v1</a></td><td class="entry"><span class="mlabel">pure virtual</span></td></tr> <tr class="even"><td class="entry"><a class="el" href="classAdobeXMPCore_1_1INameSpacePrefixMap__v1.html#ae30d56519a24afe9c22ae353fedbd8f7">Clone</a>() const =0</td><td class="entry"><a class="el" href="classAdobeXMPCore_1_1INameSpacePrefixMap__v1.html">AdobeXMPCore::INameSpacePrefixMap_v1</a></td><td class="entry"><span class="mlabel">pure virtual</span></td></tr> <tr><td class="entry"><a class="el" href="classAdobeXMPCore_1_1INameSpacePrefixMap__v1.html#a722b12c77879087c26990650d99d3339">CreateNameSpacePrefixMap</a>()</td><td class="entry"><a class="el" href="classAdobeXMPCore_1_1INameSpacePrefixMap__v1.html">AdobeXMPCore::INameSpacePrefixMap_v1</a></td><td class="entry"><span class="mlabel">static</span></td></tr> <tr class="even"><td class="entry"><a class="el" href="classAdobeXMPCommon_1_1IThreadSafe.html#a214bb1b5840dbd5576e764dd2220b261">DisableThreadSafety</a>() const __NOTHROW__=0</td><td class="entry"><a class="el" href="classAdobeXMPCommon_1_1IThreadSafe.html">AdobeXMPCommon::IThreadSafe</a></td><td class="entry"><span class="mlabel">pure virtual</span></td></tr> <tr><td class="entry"><a class="el" href="classAdobeXMPCommon_1_1IThreadSafe.html#afe35614cb88e2bdb32996cf4ac15b211">EnableThreadSafety</a>() const __NOTHROW__=0</td><td class="entry"><a class="el" href="classAdobeXMPCommon_1_1IThreadSafe.html">AdobeXMPCommon::IThreadSafe</a></td><td class="entry"><span class="mlabel">pure virtual</span></td></tr> <tr class="even"><td class="entry"><a class="el" href="classAdobeXMPCore_1_1INameSpacePrefixMap__v1.html#a16669cda8f88d9af18a248919103df22">GetDefaultNameSpacePrefixMap</a>()</td><td class="entry"><a class="el" href="classAdobeXMPCore_1_1INameSpacePrefixMap__v1.html">AdobeXMPCore::INameSpacePrefixMap_v1</a></td><td class="entry"><span class="mlabel">static</span></td></tr> <tr><td class="entry"><a class="el" href="classAdobeXMPCommon_1_1IVersionable.html#ad6539461695decfaea8a44798db51e54">GetInterfacePointer</a>()</td><td class="entry"><a class="el" href="classAdobeXMPCommon_1_1IVersionable.html">AdobeXMPCommon::IVersionable</a></td><td class="entry"><span class="mlabel">inline</span></td></tr> <tr class="even"><td class="entry"><a class="el" href="classAdobeXMPCommon_1_1IVersionable.html#ab93a940e2946c14a76ebbd9552cab070">GetInterfacePointer</a>() const </td><td class="entry"><a class="el" href="classAdobeXMPCommon_1_1IVersionable.html">AdobeXMPCommon::IVersionable</a></td><td class="entry"><span class="mlabel">inline</span></td></tr> <tr><td class="entry"><a class="el" href="classAdobeXMPCore_1_1INameSpacePrefixMap__v1.html#a57a2ef1d7b5f9fb2429220becad03413">GetNameSpace</a>(const char *prefix, sizet prefixLength) const =0</td><td class="entry"><a class="el" href="classAdobeXMPCore_1_1INameSpacePrefixMap__v1.html">AdobeXMPCore::INameSpacePrefixMap_v1</a></td><td class="entry"><span class="mlabel">pure virtual</span></td></tr> <tr class="even"><td class="entry"><a class="el" href="classAdobeXMPCore_1_1INameSpacePrefixMap__v1.html#a5a6915e1bdfa1059f4ad690bcf14a342">GetPrefix</a>(const char *nameSpace, sizet nameSpaceLength) const =0</td><td class="entry"><a class="el" href="classAdobeXMPCore_1_1INameSpacePrefixMap__v1.html">AdobeXMPCore::INameSpacePrefixMap_v1</a></td><td class="entry"><span class="mlabel">pure virtual</span></td></tr> <tr><td class="entry"><a class="el" href="classAdobeXMPCore_1_1INameSpacePrefixMap__v1.html#a1cff14bbc35fabd9fff60706ebfe23e8">Insert</a>(const char *prefix, sizet prefixLength, const char *nameSpace, sizet nameSpaceLength)=0</td><td class="entry"><a class="el" href="classAdobeXMPCore_1_1INameSpacePrefixMap__v1.html">AdobeXMPCore::INameSpacePrefixMap_v1</a></td><td class="entry"><span class="mlabel">pure virtual</span></td></tr> <tr class="even"><td class="entry"><a class="el" href="classAdobeXMPCore_1_1INameSpacePrefixMap__v1.html#a4ba4127d58b778c0148f853d7a60b8fe">IsEmpty</a>() const __NOTHROW__</td><td class="entry"><a class="el" href="classAdobeXMPCore_1_1INameSpacePrefixMap__v1.html">AdobeXMPCore::INameSpacePrefixMap_v1</a></td><td class="entry"></td></tr> <tr><td class="entry"><a class="el" href="classAdobeXMPCore_1_1INameSpacePrefixMap__v1.html#ab6fe5421aa97518a85e87bba9f4bc3a6">IsNameSpacePresent</a>(const char *nameSpace, sizet nameSpaceLength) const =0</td><td class="entry"><a class="el" href="classAdobeXMPCore_1_1INameSpacePrefixMap__v1.html">AdobeXMPCore::INameSpacePrefixMap_v1</a></td><td class="entry"><span class="mlabel">pure virtual</span></td></tr> <tr class="even"><td class="entry"><a class="el" href="classAdobeXMPCore_1_1INameSpacePrefixMap__v1.html#a10caae18d32483ff4a5737c448f4f7c3">IsPrefixPresent</a>(const char *prefix, sizet prefixLength) const =0</td><td class="entry"><a class="el" href="classAdobeXMPCore_1_1INameSpacePrefixMap__v1.html">AdobeXMPCore::INameSpacePrefixMap_v1</a></td><td class="entry"><span class="mlabel">pure virtual</span></td></tr> <tr><td class="entry"><a class="el" href="classAdobeXMPCommon_1_1IThreadSafe.html#a261e2f6af96b75015e5f8318f32be7f9">IsThreadSafe</a>() const =0</td><td class="entry"><a class="el" href="classAdobeXMPCommon_1_1IThreadSafe.html">AdobeXMPCommon::IThreadSafe</a></td><td class="entry"><span class="mlabel">pure virtual</span></td></tr> <tr class="even"><td class="entry"><a class="el" href="classAdobeXMPCommon_1_1ISharedObject.html#abf5a54e09f87366170ea19c618f68bc3">Release</a>() const __NOTHROW__=0</td><td class="entry"><a class="el" href="classAdobeXMPCommon_1_1ISharedObject.html">AdobeXMPCommon::ISharedObject</a></td><td class="entry"><span class="mlabel">pure virtual</span></td></tr> <tr><td class="entry"><a class="el" href="classAdobeXMPCore_1_1INameSpacePrefixMap__v1.html#ab030c648e112799541eb3433967207c7">RemoveNameSpace</a>(const char *nameSpace, sizet nameSpaceLength)=0</td><td class="entry"><a class="el" href="classAdobeXMPCore_1_1INameSpacePrefixMap__v1.html">AdobeXMPCore::INameSpacePrefixMap_v1</a></td><td class="entry"><span class="mlabel">pure virtual</span></td></tr> <tr class="even"><td class="entry"><a class="el" href="classAdobeXMPCore_1_1INameSpacePrefixMap__v1.html#aa4575950788bfa70dee5fad2d851230e">RemovePrefix</a>(const char *prefix, sizet prefixLength)=0</td><td class="entry"><a class="el" href="classAdobeXMPCore_1_1INameSpacePrefixMap__v1.html">AdobeXMPCore::INameSpacePrefixMap_v1</a></td><td class="entry"><span class="mlabel">pure virtual</span></td></tr> <tr><td class="entry"><a class="el" href="classAdobeXMPCommon_1_1ISharedObject.html#afcb42109aed83c3b0c133bc413388037">AdobeXMPCommon::REQ_FRIEND_CLASS_DECLARATION</a>()</td><td class="entry"><a class="el" href="classAdobeXMPCommon_1_1ISharedObject.html">AdobeXMPCommon::ISharedObject</a></td><td class="entry"><span class="mlabel">protected</span></td></tr> <tr class="even"><td class="entry"><a class="el" href="classAdobeXMPCommon_1_1IVersionable.html#ac619a81b428c88cfce50feaa91a2479f">AdobeXMPCommon::IVersionable::REQ_FRIEND_CLASS_DECLARATION</a>()</td><td class="entry"><a class="el" href="classAdobeXMPCommon_1_1IVersionable.html">AdobeXMPCommon::IVersionable</a></td><td class="entry"><span class="mlabel">protected</span></td></tr> <tr><td class="entry"><a class="el" href="classAdobeXMPCommon_1_1IThreadSafe.html#a0f31eb9677c4af06288319e363c21ebc">AdobeXMPCommon::IThreadSafe::REQ_FRIEND_CLASS_DECLARATION</a>()</td><td class="entry"><a class="el" href="classAdobeXMPCommon_1_1IThreadSafe.html">AdobeXMPCommon::IThreadSafe</a></td><td class="entry"><span class="mlabel">protected</span></td></tr> <tr class="even"><td class="entry"><a class="el" href="classAdobeXMPCore_1_1INameSpacePrefixMap__v1.html#a3dfd0d265952656c9b6641d8ce523e40">Size</a>() const __NOTHROW__=0</td><td class="entry"><a class="el" href="classAdobeXMPCore_1_1INameSpacePrefixMap__v1.html">AdobeXMPCore::INameSpacePrefixMap_v1</a></td><td class="entry"><span class="mlabel">pure virtual</span></td></tr> <tr><td class="entry"><a class="el" href="classAdobeXMPCore_1_1INameSpacePrefixMap__v1.html#aabfdffd2a782e83a627bbe1c687a922b">~INameSpacePrefixMap_v1</a>() __NOTHROW__</td><td class="entry"><a class="el" href="classAdobeXMPCore_1_1INameSpacePrefixMap__v1.html">AdobeXMPCore::INameSpacePrefixMap_v1</a></td><td class="entry"><span class="mlabel">inline</span><span class="mlabel">protected</span><span class="mlabel">virtual</span></td></tr> <tr class="even"><td class="entry"><a class="el" href="classAdobeXMPCommon_1_1ISharedObject.html#a5869ff89d0b7dd0a7b525401a1d57b31">~ISharedObject</a>() __NOTHROW__=0</td><td class="entry"><a class="el" href="classAdobeXMPCommon_1_1ISharedObject.html">AdobeXMPCommon::ISharedObject</a></td><td class="entry"><span class="mlabel">inline</span><span class="mlabel">protected</span><span class="mlabel">pure virtual</span></td></tr> <tr><td class="entry"><a class="el" href="classAdobeXMPCommon_1_1IVersionable.html#a3ccd9a1bdf7008906e094fb4e7f69826">~IVersionable</a>()</td><td class="entry"><a class="el" href="classAdobeXMPCommon_1_1IVersionable.html">AdobeXMPCommon::IVersionable</a></td><td class="entry"><span class="mlabel">inline</span><span class="mlabel">protected</span><span class="mlabel">virtual</span></td></tr> </table></div><!-- contents --> </div><!-- doc-content --> <hr size="1"><address style="text-align: right;"><small> XMPToolkit documentation generated by&nbsp;<a href="http://www.doxygen.org/index.html">doxygen</a> 1.8.11</small></address> </body> </html>
yanburman/sjcam_raw2dng
xmp_sdk/docs/API/classAdobeXMPCore_1_1INameSpacePrefixMap__v1-members.html
HTML
gpl-2.0
12,198
#ifndef PAGEDATA_HPP #define PAGEDATA_HPP /* Copyright (c) 2009-10 Qtrac Ltd. All rights reserved. This program or module 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. It is provided for educational purposes and is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. */ #include <QList> #include <QObject> #include <QString> #include <QStringList> #include <QTextTableCell> class QFont; class QPainter; class QPrinter; class QRect; class QTextCharFormat; class QTextCursor; class QTextDocument; struct OnePage { QString title; QStringList filenames; QStringList captions; QString descriptionHtml; }; class PageData : public QObject { Q_OBJECT public: explicit PageData(); public slots: void paintPages(QPrinter *printer, bool noUserInteraction=true); public: void paintPage(QPainter *painter, int page); void populateDocumentUsingHtml(QTextDocument *document); QString pageAsHtml(int page=0, bool selfContained=true); void populateDocumentUsingQTextCursor(QTextDocument *document); void addPageToDocument(QTextCursor *cursor, int page=0); private: int paintTitle(QPainter *painter, const QString &title); int paintItems(QPainter *painter, int y, const OnePage &thePage); void paintItem(QPainter *painter, const QRect &rect, const QString &filename, const QString &caption); int paintHtmlParagraph(QPainter *painter, int y, const QString &html); int paintWord(QPainter *painter, int x, int y, const QString &word, const QFont &paragraphFont, const QTextCharFormat &format); void paintFooter(QPainter *painter, const QString &footer); QString itemsAsHtmlTable(const OnePage &thePage); void addTitleToDocument(QTextCursor *cursor, const QString &title); void addItemsToDocument(QTextCursor *cursor, const OnePage &thePage); QTextTableFormat tableFormat(); void populateTableCell(QTextTableCell tableCell, const OnePage &thePage, int index); void addRuleToDocument(QTextCursor *cursor); QList<OnePage> pages; }; #endif // PAGEDATA_HPP
paradiseOffice/Bash_and_Cplus-plus
CPP/full_examples/aqp/outputsampler/pagedata.hpp
C++
gpl-2.0
2,566
#!/usr/bin/env python import sys, os sys.path.append(os.path.join(os.path.dirname(os.path.abspath(__file__)), '../../../master')) sys.path.append(os.path.join(os.path.dirname(os.path.abspath(__file__)), '../../../master/wkpf')) print os.path.join(os.path.dirname(os.path.abspath(__file__)), '../../../master/wkpf') from wkpf.pynvc import * from wkpf.wkpfcomm import * comm = getComm() print "node ids", comm.getNodeIds() comm.setFeature(2, WKPF_FEATURE_LIGHT_SENSOR, 0) comm.setFeature(2, WKPF_FEATURE_LIGHT_ACTUATOR, 1) comm.setFeature(2, WKPF_FEATURE_NUMERIC_CONTROLLER, 0) comm.setFeature(2, WKPF_FEATURE_NATIVE_THRESHOLD, 0) comm.setLocation(2, "WuKong") comm.setFeature(7, WKPF_FEATURE_LIGHT_SENSOR, 1) comm.setFeature(7, WKPF_FEATURE_LIGHT_ACTUATOR, 1) comm.setFeature(7, WKPF_FEATURE_NUMERIC_CONTROLLER, 0) comm.setFeature(7, WKPF_FEATURE_NATIVE_THRESHOLD, 0) comm.setLocation(7, "WuKong") comm.setFeature(4, WKPF_FEATURE_LIGHT_SENSOR, 1) comm.setFeature(4, WKPF_FEATURE_LIGHT_ACTUATOR, 0) comm.setFeature(4, WKPF_FEATURE_NUMERIC_CONTROLLER, 1) comm.setFeature(4, WKPF_FEATURE_NATIVE_THRESHOLD, 1) comm.setLocation(4, "WuKong") comm.setFeature(5, WKPF_FEATURE_LIGHT_SENSOR, 0) comm.setFeature(5, WKPF_FEATURE_LIGHT_ACTUATOR, 1) comm.setFeature(5, WKPF_FEATURE_NUMERIC_CONTROLLER, 0) comm.setFeature(5, WKPF_FEATURE_NATIVE_THRESHOLD, 0) comm.setLocation(5, "WuKong") comm.setFeature(6, WKPF_FEATURE_LIGHT_SENSOR, 0) comm.setFeature(6, WKPF_FEATURE_LIGHT_ACTUATOR, 1) comm.setFeature(6, WKPF_FEATURE_NUMERIC_CONTROLLER, 0) comm.setFeature(6, WKPF_FEATURE_NATIVE_THRESHOLD, 0) comm.setLocation(6, "WuKong") comm.setFeature(13, WKPF_FEATURE_LIGHT_SENSOR, 0) comm.setFeature(13, WKPF_FEATURE_LIGHT_ACTUATOR, 1) comm.setFeature(13, WKPF_FEATURE_NUMERIC_CONTROLLER, 0) comm.setFeature(13, WKPF_FEATURE_NATIVE_THRESHOLD, 0) comm.setLocation(13, "WuKong") comm.setFeature(14, WKPF_FEATURE_LIGHT_SENSOR, 0) comm.setFeature(14, WKPF_FEATURE_LIGHT_ACTUATOR, 1) comm.setFeature(14, WKPF_FEATURE_NUMERIC_CONTROLLER, 0) comm.setFeature(14, WKPF_FEATURE_NATIVE_THRESHOLD, 0) comm.setLocation(14, "WuKong") comm.setFeature(15, WKPF_FEATURE_LIGHT_SENSOR, 0) comm.setFeature(15, WKPF_FEATURE_LIGHT_ACTUATOR, 1) comm.setFeature(15, WKPF_FEATURE_NUMERIC_CONTROLLER, 0) comm.setFeature(15, WKPF_FEATURE_NATIVE_THRESHOLD, 0) comm.setLocation(15, "WuKong") comm.setFeature(10, WKPF_FEATURE_LIGHT_SENSOR, 0) comm.setFeature(10, WKPF_FEATURE_LIGHT_ACTUATOR, 1) comm.setFeature(10, WKPF_FEATURE_NUMERIC_CONTROLLER, 0) comm.setFeature(10, WKPF_FEATURE_NATIVE_THRESHOLD, 0) comm.setLocation(10, "WuKong") comm.setFeature(12, WKPF_FEATURE_LIGHT_SENSOR, 0) comm.setFeature(12, WKPF_FEATURE_LIGHT_ACTUATOR, 1) comm.setFeature(12, WKPF_FEATURE_NUMERIC_CONTROLLER, 0) comm.setFeature(12, WKPF_FEATURE_NATIVE_THRESHOLD, 0) comm.setLocation(12, "WuKong")
wukong-m2m/NanoKong
tools/python/scripts/installer.py
Python
gpl-2.0
2,839
module.exports = function(gulp, plugins, paths){ return plugins.shell.task("node "+paths.build+"/index.js --production"); };
ericholiveira/data-provider
gulp/run-release.js
JavaScript
gpl-2.0
125
/* * Copyright 2003-2004 Sun Microsystems, Inc. All Rights Reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * - Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * - Neither the name of Sun Microsystems nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ /* This file contains support for handling frames, or (method,location) pairs. */ #include "hprof.h" /* * Frames map 1-to-1 to (methodID,location) pairs. * When no line number is known, -1 should be used. * * Frames are mostly used in traces (see hprof_trace.c) and will be marked * with their status flag as they are written out to the hprof output file. * */ enum LinenoState { LINENUM_UNINITIALIZED = 0, LINENUM_AVAILABLE = 1, LINENUM_UNAVAILABLE = 2 }; typedef struct FrameKey { jmethodID method; jlocation location; } FrameKey; typedef struct FrameInfo { unsigned short lineno; unsigned char lineno_state; /* LinenoState */ unsigned char status; SerialNumber serial_num; } FrameInfo; static FrameKey* get_pkey(FrameIndex index) { void *key_ptr; int key_len; table_get_key(gdata->frame_table, index, &key_ptr, &key_len); HPROF_ASSERT(key_len==sizeof(FrameKey)); HPROF_ASSERT(key_ptr!=NULL); return (FrameKey*)key_ptr; } static FrameInfo * get_info(FrameIndex index) { FrameInfo *info; info = (FrameInfo*)table_get_info(gdata->frame_table, index); return info; } static void list_item(TableIndex i, void *key_ptr, int key_len, void *info_ptr, void *arg) { FrameKey key; FrameInfo *info; HPROF_ASSERT(key_ptr!=NULL); HPROF_ASSERT(key_len==sizeof(FrameKey)); HPROF_ASSERT(info_ptr!=NULL); key = *((FrameKey*)key_ptr); info = (FrameInfo*)info_ptr; debug_message( "Frame 0x%08x: method=%p, location=%d, lineno=%d(%d), status=%d \n", i, (void*)key.method, (jint)key.location, info->lineno, info->lineno_state, info->status); } void frame_init(void) { gdata->frame_table = table_initialize("Frame", 1024, 1024, 1023, (int)sizeof(FrameInfo)); } FrameIndex frame_find_or_create(jmethodID method, jlocation location) { FrameIndex index; static FrameKey empty_key; FrameKey key; jboolean new_one; key = empty_key; key.method = method; key.location = location; new_one = JNI_FALSE; index = table_find_or_create_entry(gdata->frame_table, &key, (int)sizeof(key), &new_one, NULL); if ( new_one ) { FrameInfo *info; info = get_info(index); info->lineno_state = LINENUM_UNINITIALIZED; if ( location < 0 ) { info->lineno_state = LINENUM_UNAVAILABLE; } info->serial_num = gdata->frame_serial_number_counter++; } return index; } void frame_list(void) { debug_message( "--------------------- Frame Table ------------------------\n"); table_walk_items(gdata->frame_table, &list_item, NULL); debug_message( "----------------------------------------------------------\n"); } void frame_cleanup(void) { table_cleanup(gdata->frame_table, NULL, NULL); gdata->frame_table = NULL; } void frame_set_status(FrameIndex index, jint status) { FrameInfo *info; info = get_info(index); info->status = (unsigned char)status; } void frame_get_location(FrameIndex index, SerialNumber *pserial_num, jmethodID *pmethod, jlocation *plocation, jint *plineno) { FrameKey *pkey; FrameInfo *info; jint lineno; pkey = get_pkey(index); *pmethod = pkey->method; *plocation = pkey->location; info = get_info(index); lineno = (jint)info->lineno; if ( info->lineno_state == LINENUM_UNINITIALIZED ) { info->lineno_state = LINENUM_UNAVAILABLE; if ( gdata->lineno_in_traces ) { if ( pkey->location >= 0 && !isMethodNative(pkey->method) ) { lineno = getLineNumber(pkey->method, pkey->location); if ( lineno >= 0 ) { info->lineno = (unsigned short)lineno; /* save it */ info->lineno_state = LINENUM_AVAILABLE; } } } } if ( info->lineno_state == LINENUM_UNAVAILABLE ) { lineno = -1; } *plineno = lineno; *pserial_num = info->serial_num; } jint frame_get_status(FrameIndex index) { FrameInfo *info; info = get_info(index); return (jint)info->status; }
TheTypoMaster/Scaper
openjdk/jdk/src/share/demo/jvmti/hprof/hprof_frame.c
C
gpl-2.0
5,904
/** * $Id: sites/all/libraries/tinymce/jscripts/tiny_mce/utils/editable_selects.js 1.3 2010/02/18 14:49:08EST Linda M. Williams (WILLIAMSLM) Production $ * * Makes select boxes editable. * * @author Moxiecode * @copyright Copyright © 2004-2008, Moxiecode Systems AB, All rights reserved. */ var TinyMCE_EditableSelects = { editSelectElm : null, init : function() { var nl = document.getElementsByTagName("select"), i, d = document, o; for (i=0; i<nl.length; i++) { if (nl[i].className.indexOf('mceEditableSelect') != -1) { o = new Option('(value)', '__mce_add_custom__'); o.className = 'mceAddSelectValue'; nl[i].options[nl[i].options.length] = o; nl[i].onchange = TinyMCE_EditableSelects.onChangeEditableSelect; } } }, onChangeEditableSelect : function(e) { var d = document, ne, se = window.event ? window.event.srcElement : e.target; if (se.options[se.selectedIndex].value == '__mce_add_custom__') { ne = d.createElement("input"); ne.id = se.id + "_custom"; ne.name = se.name + "_custom"; ne.type = "text"; ne.style.width = se.offsetWidth + 'px'; se.parentNode.insertBefore(ne, se); se.style.display = 'none'; ne.focus(); ne.onblur = TinyMCE_EditableSelects.onBlurEditableSelectInput; ne.onkeydown = TinyMCE_EditableSelects.onKeyDown; TinyMCE_EditableSelects.editSelectElm = se; } }, onBlurEditableSelectInput : function() { var se = TinyMCE_EditableSelects.editSelectElm; if (se) { if (se.previousSibling.value != '') { addSelectValue(document.forms[0], se.id, se.previousSibling.value, se.previousSibling.value); selectByValue(document.forms[0], se.id, se.previousSibling.value); } else selectByValue(document.forms[0], se.id, ''); se.style.display = 'inline'; se.parentNode.removeChild(se.previousSibling); TinyMCE_EditableSelects.editSelectElm = null; } }, onKeyDown : function(e) { e = e || window.event; if (e.keyCode == 13) TinyMCE_EditableSelects.onBlurEditableSelectInput(); } };
WPMedia/wp-postfun-drupal-prod
sites/all/libraries/tinymce/jscripts/tiny_mce/utils/editable_selects.js
JavaScript
gpl-2.0
2,098
<?php /******************************************************************************* Copyright 2013 Whole Foods Co-op This file is part of Fannie. IT CORE is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. IT CORE 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 in the file license.txt along with IT CORE; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA *********************************************************************************/ /** @class EfsnetResponseModel */ class EfsnetResponseModel extends BasicModel { protected $name = "efsnetResponse"; protected $preferred_db = 'trans'; protected $columns = array( 'date' => array('type'=>'INT'), 'cashierNo' => array('type'=>'INT'), 'laneNo' => array('type'=>'INT'), 'transNo' => array('type'=>'INT'), 'transID' => array('type'=>'INT'), 'datetime' => array('type'=>'DATETIME'), 'refNum' => array('type'=>'VARCHAR(50)'), 'seconds' => array('type'=>'FLOAT'), 'commErr' => array('type'=>'INT'), 'httpCode' => array('type'=>'INT'), 'validResponse' => array('type'=>'SMALLINT'), 'xResponseCode' => array('type'=>'VARCHAR(4)'), 'xResultCode' => array('type'=>'VARCHAR(8)'), 'xResultMessage' => array('type'=>'VARCHAR(100)'), 'xTransactionID' => array('type'=>'VARCHAR(12)'), 'xApprovalNumber' => array('type'=>'VARCHAR(20)'), ); /* START ACCESSOR FUNCTIONS */ public function date() { if(func_num_args() == 0) { if(isset($this->instance["date"])) { return $this->instance["date"]; } elseif(isset($this->columns["date"]["default"])) { return $this->columns["date"]["default"]; } else { return null; } } else { $this->instance["date"] = func_get_arg(0); } } public function cashierNo() { if(func_num_args() == 0) { if(isset($this->instance["cashierNo"])) { return $this->instance["cashierNo"]; } elseif(isset($this->columns["cashierNo"]["default"])) { return $this->columns["cashierNo"]["default"]; } else { return null; } } else { $this->instance["cashierNo"] = func_get_arg(0); } } public function laneNo() { if(func_num_args() == 0) { if(isset($this->instance["laneNo"])) { return $this->instance["laneNo"]; } elseif(isset($this->columns["laneNo"]["default"])) { return $this->columns["laneNo"]["default"]; } else { return null; } } else { $this->instance["laneNo"] = func_get_arg(0); } } public function transNo() { if(func_num_args() == 0) { if(isset($this->instance["transNo"])) { return $this->instance["transNo"]; } elseif(isset($this->columns["transNo"]["default"])) { return $this->columns["transNo"]["default"]; } else { return null; } } else { $this->instance["transNo"] = func_get_arg(0); } } public function transID() { if(func_num_args() == 0) { if(isset($this->instance["transID"])) { return $this->instance["transID"]; } elseif(isset($this->columns["transID"]["default"])) { return $this->columns["transID"]["default"]; } else { return null; } } else { $this->instance["transID"] = func_get_arg(0); } } public function datetime() { if(func_num_args() == 0) { if(isset($this->instance["datetime"])) { return $this->instance["datetime"]; } elseif(isset($this->columns["datetime"]["default"])) { return $this->columns["datetime"]["default"]; } else { return null; } } else { $this->instance["datetime"] = func_get_arg(0); } } public function refNum() { if(func_num_args() == 0) { if(isset($this->instance["refNum"])) { return $this->instance["refNum"]; } elseif(isset($this->columns["refNum"]["default"])) { return $this->columns["refNum"]["default"]; } else { return null; } } else { $this->instance["refNum"] = func_get_arg(0); } } public function seconds() { if(func_num_args() == 0) { if(isset($this->instance["seconds"])) { return $this->instance["seconds"]; } elseif(isset($this->columns["seconds"]["default"])) { return $this->columns["seconds"]["default"]; } else { return null; } } else { $this->instance["seconds"] = func_get_arg(0); } } public function commErr() { if(func_num_args() == 0) { if(isset($this->instance["commErr"])) { return $this->instance["commErr"]; } elseif(isset($this->columns["commErr"]["default"])) { return $this->columns["commErr"]["default"]; } else { return null; } } else { $this->instance["commErr"] = func_get_arg(0); } } public function httpCode() { if(func_num_args() == 0) { if(isset($this->instance["httpCode"])) { return $this->instance["httpCode"]; } elseif(isset($this->columns["httpCode"]["default"])) { return $this->columns["httpCode"]["default"]; } else { return null; } } else { $this->instance["httpCode"] = func_get_arg(0); } } public function validResponse() { if(func_num_args() == 0) { if(isset($this->instance["validResponse"])) { return $this->instance["validResponse"]; } elseif(isset($this->columns["validResponse"]["default"])) { return $this->columns["validResponse"]["default"]; } else { return null; } } else { $this->instance["validResponse"] = func_get_arg(0); } } public function xResponseCode() { if(func_num_args() == 0) { if(isset($this->instance["xResponseCode"])) { return $this->instance["xResponseCode"]; } elseif(isset($this->columns["xResponseCode"]["default"])) { return $this->columns["xResponseCode"]["default"]; } else { return null; } } else { $this->instance["xResponseCode"] = func_get_arg(0); } } public function xResultCode() { if(func_num_args() == 0) { if(isset($this->instance["xResultCode"])) { return $this->instance["xResultCode"]; } elseif(isset($this->columns["xResultCode"]["default"])) { return $this->columns["xResultCode"]["default"]; } else { return null; } } else { $this->instance["xResultCode"] = func_get_arg(0); } } public function xResultMessage() { if(func_num_args() == 0) { if(isset($this->instance["xResultMessage"])) { return $this->instance["xResultMessage"]; } elseif(isset($this->columns["xResultMessage"]["default"])) { return $this->columns["xResultMessage"]["default"]; } else { return null; } } else { $this->instance["xResultMessage"] = func_get_arg(0); } } public function xTransactionID() { if(func_num_args() == 0) { if(isset($this->instance["xTransactionID"])) { return $this->instance["xTransactionID"]; } elseif(isset($this->columns["xTransactionID"]["default"])) { return $this->columns["xTransactionID"]["default"]; } else { return null; } } else { $this->instance["xTransactionID"] = func_get_arg(0); } } public function xApprovalNumber() { if(func_num_args() == 0) { if(isset($this->instance["xApprovalNumber"])) { return $this->instance["xApprovalNumber"]; } elseif(isset($this->columns["xApprovalNumber"]["default"])) { return $this->columns["xApprovalNumber"]["default"]; } else { return null; } } else { $this->instance["xApprovalNumber"] = func_get_arg(0); } } /* END ACCESSOR FUNCTIONS */ }
joelbrock/PFC_CORE
pos/is4c-nf/lib/models/trans/EfsnetResponseModel.php
PHP
gpl-2.0
9,533
// Copyright (C) 2009,2010,2011,2012 GlavSoft LLC. // All rights reserved. // //------------------------------------------------------------------------- // This file is part of the TightVNC software. Please visit our Web site: // // http://www.tightvnc.com/ // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License along // with this program; if not, write to the Free Software Foundation, Inc., // 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. //------------------------------------------------------------------------- // #include "CurrentConsoleProcess.h" #include "win-system/WinStaLibrary.h" #include "win-system/Environment.h" #include "win-system/SystemException.h" #include "win-system/Workstation.h" #include "win-system/WTS.h" CurrentConsoleProcess::CurrentConsoleProcess(LogWriter *log, const TCHAR *path, const TCHAR *args) : Process(path, args), m_log(log) { } CurrentConsoleProcess::~CurrentConsoleProcess() { } void CurrentConsoleProcess::start() { cleanup(); DWORD sessionId = WTS::getActiveConsoleSessionId(m_log); DWORD uiAccess = 1; // Nonzero enables UI control m_log->info(_T("Try to start \"%s %s\" process as current user at %d session"), m_path.getString(), m_args.getString(), sessionId); PROCESS_INFORMATION pi; STARTUPINFO sti; getStartupInfo(&sti); m_log->debug(_T("sti: cb = %d, hStdError = %p, hStdInput = %p,") _T(" hStdOutput = %p, dwFlags = %u"), (unsigned int)sti.cb, (void *)sti.hStdError, (void *)sti.hStdInput, (void *)sti.hStdOutput, (unsigned int)sti.dwFlags); HANDLE procHandle = GetCurrentProcess(); HANDLE token, userToken; try { m_log->debug(_T("Try OpenProcessToken(%p, , )"), (void *)procHandle); if (OpenProcessToken(procHandle, TOKEN_DUPLICATE, &token) == 0) { throw SystemException(); } m_log->debug(_T("Try DuplicateTokenEx(%p, , , , , )"), (void *)token); if (DuplicateTokenEx(token, MAXIMUM_ALLOWED, 0, SecurityImpersonation, TokenPrimary, &userToken) == 0) { throw SystemException(); } m_log->debug(_T("Try SetTokenInformation(%p, , , )"), (void *)userToken); if (SetTokenInformation(userToken, (TOKEN_INFORMATION_CLASS) TokenSessionId, &sessionId, sizeof(sessionId)) == 0) { throw SystemException(); } // Fix Windows 8/8.1 UIAccess restrictions (Alt-Tab) for server as service // http://stackoverflow.com/questions/13972165/pressing-winx-alt-tab-programatically // For application we need to set /uiAccess='true' in linker manifest, sign binary // and run from "Program Files/" m_log->debug(_T("Try SetTokenInformation(%p, , , ) with UIAccess=1"), (void *)userToken); if (SetTokenInformation(userToken, (TOKEN_INFORMATION_CLASS) TokenUIAccess, &uiAccess, sizeof(uiAccess)) == 0) { m_log->info(_T("Can't set UIAccess=1, ignore it"), (void *)userToken); } StringStorage commandLine = getCommandLineString(); m_log->debug(_T("Try CreateProcessAsUser(%p, 0, %s, 0, 0, %d, NORMAL_PRIORITY_CLASS, 0, 0,") _T(" sti, pi)"), (void *)userToken, commandLine.getString(), (int)m_handlesIsInherited); if (CreateProcessAsUser(userToken, 0, (LPTSTR) commandLine.getString(), 0, 0, m_handlesIsInherited, NORMAL_PRIORITY_CLASS, 0, 0, &sti, &pi) == 0) { throw SystemException(); } m_log->info(_T("Created \"%s\" process at %d windows session"), commandLine.getString(), sessionId); } catch (SystemException &sysEx) { m_log->error(_T("Failed to start process with %d error"), sysEx.getErrorCode()); throw; } // // FIXME: Leak. // CloseHandle(userToken); CloseHandle(token); m_hThread = pi.hThread; m_hProcess = pi.hProcess; }
netassist-ua/tightvnc-gpl-ipv6
win-system/CurrentConsoleProcess.cpp
C++
gpl-2.0
4,674
{% load i18n %} <div class="row" id="group-multiple-selection"> <div class="col-md-12"> <div class="btn-group disabled"> <button type="button" id="multiple-selection-action" class="btn btn-info dropdown-toggle" aria-expanded="false" disabled data-toggle="dropdown">{% trans 'Multiple selection action' %} <span class="caret"></span> <span class="sr-only">Toggle Dropdown</span> </button> <ul class="dropdown-menu" role="menu"> <li><a id="remove-{{ obj_class }}" href="#"><span class="glyphicon glyphicon-remove" aria-hidden="true"></span> {% trans 'Remove' %}</a></li> <li class="divider"></li> <li><a id="print-members-cards" href="#"><span class="glyphicon glyphicon-print" aria-hidden="true"></span> {% trans 'Print ID Cards' %}</a></li> </ul> </div> </div> </div>
jonatascastro12/barnabe
templates/includes/group-multiple-selection.html
HTML
gpl-2.0
892
#include "sgfreader.hpp" #include "game.hpp" #include <sstream> #include <QDebug> QDebug operator<<(QDebug dbg, const std::string& str) { dbg.nospace() << QString::fromStdString(str); return dbg.space(); } const SGFReader::Dispatch SGFReader::s_dispatch; SGFReader::Dispatch::Dispatch() { s_map.insert(make_pair("GC", &SGFReader::parseGC)); s_map.insert(make_pair("GN", &SGFReader::parseGN)); s_map.insert(make_pair("HA", &SGFReader::parseHA)); s_map.insert(make_pair("KM", &SGFReader::parseKM)); s_map.insert(make_pair("TB", &SGFReader::parseTB)); s_map.insert(make_pair("TW", &SGFReader::parseTW)); s_map.insert(make_pair("DT", &SGFReader::parseDT)); s_map.insert(make_pair("PB", &SGFReader::parsePB)); s_map.insert(make_pair("PW", &SGFReader::parsePW)); s_map.insert(make_pair("BR", &SGFReader::parseBR)); s_map.insert(make_pair("WR", &SGFReader::parseWR)); s_map.insert(make_pair("OT", &SGFReader::parseOT)); s_map.insert(make_pair("CP", &SGFReader::parseCP)); s_map.insert(make_pair("EV", &SGFReader::parseEV)); s_map.insert(make_pair("SZ", &SGFReader::parseSZ)); s_map.insert(make_pair("RU", &SGFReader::parseRU)); s_map.insert(make_pair("FF", &SGFReader::parseFF)); s_map.insert(make_pair("GM", &SGFReader::parseGM)); s_map.insert(make_pair("PC", &SGFReader::parsePC)); s_map.insert(make_pair("B", &SGFReader::parseB)); s_map.insert(make_pair("W", &SGFReader::parseW)); s_map.insert(make_pair("AP", &SGFReader::parseAP)); s_map.insert(make_pair("US", &SGFReader::parseUS)); s_map.insert(make_pair("RE", &SGFReader::parseRE)); s_map.insert(make_pair("TM", &SGFReader::parseTM)); } const SGFReader::Dispatch::type_map& SGFReader::Dispatch::map() const { return s_map; } SGFReader::InvalidLine::InvalidLine(const std::string& line): std::invalid_argument("Invalid line: "+line) {} SGFReader::UnreckognizedCommand::UnreckognizedCommand(const std::string& line): std::invalid_argument("Unreckognized command: "+line) {} Game SGFReader::parse(const std::list<std::string>& lst) { Game res; std::for_each(lst.begin(), lst.end(), [&](const std::string& line) { SGFReader::parseLine(res, line); }); return res; } void SGFReader::parseLine(Game& game, std::string line) { while(!line.empty() && (isspace(line.front()) || line.front() == ';')) line.erase(0, 1); if(line.empty()) return; if(line == "(") { game.startAlternativePath(); return; } else if(line == ")") { game.endAlternativePath(); return; } for(Dispatch::type_map::const_iterator i = s_dispatch.map().begin(); i != s_dispatch.map().end(); ++i) { std::size_t pos_bracket = line.find('['); if(pos_bracket == std::string::npos) throw InvalidLine(line); if(line.substr(0, pos_bracket) != i->first) continue; line.erase(0, i->first.size()); if(line.size() < 2 || *line.begin() != '[' || *(--line.end()) != ']') throw InvalidLine(line); line.erase(0, 1); line.pop_back(); pos_bracket = line.find(']'); if(pos_bracket != std::string::npos) //several instructions on a single line!! { std::string leftOver = line.substr(pos_bracket + 1) + ']'; line = line.substr(0, pos_bracket); i->second(game, line); parseLine(game, leftOver); } else i->second(game, line); return; } throw UnreckognizedCommand(line); } void SGFReader::parseGC(Game& game, std::string line) { game.m_information = line; } void SGFReader::parseGN(Game& game, std::string line) { game.m_name = line; } void SGFReader::parseHA(Game& game, std::string line) { game.m_nbHandicapStones = parseUInt8(line); } void SGFReader::parseKM(Game& game, std::string line) { game.m_komi = parseDouble(line); } void SGFReader::parseTB(Game& game, std::string line) { qDebug() << "TB => " << line; } void SGFReader::parseTW(Game& game, std::string line) { qDebug() << "TW => " << line; } void SGFReader::parseDT(Game& game, std::string line) { game.m_date = line; } void SGFReader::parsePB(Game& game, std::string line) { game.setBlackName(line); } void SGFReader::parsePW(Game& game, std::string line) { game.setWhiteName(line); } void SGFReader::parseBR(Game& game, std::string line) { game.setBlackRank(line); } void SGFReader::parseWR(Game& game, std::string line) { game.setWhiteRank(line); } void SGFReader::parseOT(Game& game, std::string line) { game.m_overtimeSystem = line; } void SGFReader::parseCP(Game& game, std::string line) { game.m_copyright = line; } void SGFReader::parseEV(Game& game, std::string line) { game.m_eventName = line; } void SGFReader::parseSZ(Game& game, std::string line) { game.m_boardSize = parseUInt8(line); } void SGFReader::parseRU(Game& game, std::string line) { game.m_ruleSet = line; } void SGFReader::parseFF(Game& /*game*/, std::string line) { if(line != "4") throw InvalidLine("SGF" + line + " not supported"); } void SGFReader::parseGM(Game& /*game*/, std::string line) { if(line != "1") throw InvalidLine("Impossible to parsing anything other than a game of go."); } void SGFReader::parsePC(Game& game, std::string line) { game.m_gamePlace = line; } void SGFReader::parseB(Game& game, std::string line) { Point p = parsePoint(line); game.addMove(p, QGo::BLACK); } void SGFReader::parseW(Game& game, std::string line) { Point p = parsePoint(line); game.addMove(p, QGo::WHITE); } void SGFReader::parseAP(Game& game, std::string line) { game.m_application = line; } void SGFReader::parseUS(Game& game, std::string line) { game.m_user = line; } void SGFReader::parseRE(Game& game, std::string line) { game.m_result = line; } void SGFReader::parseTM(Game& game, std::string line) { game.m_timeLimit = line; } uint8_t SGFReader::parseUInt8(const std::string& line) { std::istringstream iss(line); unsigned int n; iss >> n; return (uint8_t)n; } double SGFReader::parseDouble(const std::string& line) { std::istringstream iss(line); double d; iss >> d; return d; } Point SGFReader::parsePoint(const std::string& line) throw(InvalidLine) { if(line.size() != 2) throw InvalidLine(line + " isn't a valid position for a move"); return Point(parsePosition(line.front()), parsePosition(line.back())); } uint8_t SGFReader::parsePosition(char c) throw(InvalidLine) { if(c >= 'a' && c < 'z') { return (uint8_t)(c - 'a'); } if(c >= 'A' && c < 'Z') { return (uint8_t)(c - 'A' + 27); } std::ostringstream oss; oss << c << " isn't a valid position"; throw InvalidLine(oss.str()); return -1; }
julienlopez/QGo
src/sgfreader.cpp
C++
gpl-2.0
6,879
/** @file system_ADUCRF101.h @brief: CMSIS Cortex-M3 Device Peripheral Access Layer Header File for the ADuCRF101 @version v0.2 @author PAD CSE group @date March 09th 2012 @section disclaimer Disclaimer THIS SOFTWARE IS PROVIDED BY ANALOG DEVICES INC. ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, OR NON-INFRINGEMENT, ARE DISCLAIMED. IN NO EVENT SHALL ANALOG DEVICES INC. BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. YOU ASSUME ANY AND ALL RISK FROM THE USE OF THIS CODE OR SUPPORT FILE. IT IS THE RESPONSIBILITY OF THE PERSON INTEGRATING THIS CODE INTO AN APPLICATION TO ENSURE THAT THE RESULTING APPLICATION PERFORMS AS REQUIRED AND IS SAFE. **/ /** @addtogroup CMSIS * @{ */ /** @addtogroup aducrf101_system * @{ */ #ifndef __SYSTEM_ADUCRF101_H__ #define __SYSTEM_ADUCRF101_H__ #ifdef __cplusplus extern "C" { #endif /** * @brief Initialize the system * * @param none * @return none * * Setup the microcontroller system. * Initialize the System and update the SystemCoreClock variable. */ extern void SystemInit (void); /** * @brief Update internal SystemCoreClock variable * * @param none * @return none * * Updates the internal SystemCoreClock with current core * Clock retrieved from cpu registers. */ extern void SystemCoreClockUpdate (void); /** * @brief Sets the system external clock frequency * * @param ExtClkFreq External clock frequency in Hz * @return none * * Sets the clock frequency of the source connected to P0.5 clock input source */ extern void SetSystemExtClkFreq (uint32_t ExtClkFreq); /** * @brief Gets the system external clock frequency * * @return External Clock frequency * * Gets the clock frequency of the source connected to P0.5 clock input source */ extern uint32_t GetSystemExtClkFreq (void); #ifdef __cplusplus } #endif #endif /* __SYSTEM_ADUCRF101_H__ */ /** * @} */ /** * @} */
petersoltys/Time-multiplex-ADuC-rf101_v2
src/include/Common/system_ADUCRF101.h
C
gpl-2.0
2,187
<?php /** * @package Joomla.Site * @subpackage com_content * * @copyright Copyright (C) 2005 - 2017 Open Source Matters, Inc. All rights reserved. * @license GNU General Public License version 2 or later; see LICENSE.txt */ namespace Joomla\Component\Content\Site\Model; defined('_JEXEC') or die; use Joomla\CMS\MVC\Model\ListModel; use Joomla\Registry\Registry; /** * This models supports retrieving lists of article categories. * * @since 1.6 */ class Categories extends ListModel { /** * Model context string. * * @var string */ public $_context = 'com_content.categories'; /** * The category context (allows other extensions to derived from this model). * * @var string */ protected $_extension = 'com_content'; private $_parent = null; /** * Method to auto-populate the model state. * * Note. Calling getState in this method will result in recursion. * * @param string $ordering The field to order on. * @param string $direction The direction to order on. * * @return void * * @since 1.6 */ protected function populateState($ordering = null, $direction = null) { $app = \JFactory::getApplication(); $this->setState('filter.extension', $this->_extension); // Get the parent id if defined. $parentId = $app->input->getInt('id'); $this->setState('filter.parentId', $parentId); $params = $app->getParams(); $this->setState('params', $params); $this->setState('filter.published', 1); $this->setState('filter.access', true); } /** * Method to get a store id based on model configuration state. * * This is necessary because the model is used by the component and * different modules that might need different sets of data or different * ordering requirements. * * @param string $id A prefix for the store id. * * @return string A store id. */ protected function getStoreId($id = '') { // Compile the store id. $id .= ':' . $this->getState('filter.extension'); $id .= ':' . $this->getState('filter.published'); $id .= ':' . $this->getState('filter.access'); $id .= ':' . $this->getState('filter.parentId'); return parent::getStoreId($id); } /** * Redefine the function an add some properties to make the styling more easy * * @param bool $recursive True if you want to return children recursively. * * @return mixed An array of data items on success, false on failure. * * @since 1.6 */ public function getItems($recursive = false) { $store = $this->getStoreId(); if (!isset($this->cache[$store])) { $app = \JFactory::getApplication(); $menu = $app->getMenu(); $active = $menu->getActive(); $params = new Registry; if ($active) { $params->loadString($active->params); } $options = array(); $options['countItems'] = $params->get('show_cat_num_articles_cat', 1) || !$params->get('show_empty_categories_cat', 0); $categories = \JCategories::getInstance('Content', $options); $this->_parent = $categories->get($this->getState('filter.parentId', 'root')); if (is_object($this->_parent)) { $this->cache[$store] = $this->_parent->getChildren($recursive); } else { $this->cache[$store] = false; } } return $this->cache[$store]; } /** * Get the parent. * * @return object An array of data items on success, false on failure. * * @since 1.6 */ public function getParent() { if (!is_object($this->_parent)) { $this->getItems(); } return $this->_parent; } }
Supun94/gsoc17_js_tests
components/com_content/Model/Categories.php
PHP
gpl-2.0
3,538
#include "lolevel.h" #include "platform.h" #include "core.h" static long *nrflag = (long*)0x61F4; #include "../../../generic/capt_seq.c" void __attribute__((naked,noinline)) sub_FF963344_my(long p) { #if 1 asm volatile ( "STMFD SP!, {R4-R6,LR}\n" "LDR R3, =0x6F3BC\n" "LDR R5, =0x61F0\n" "SUB SP, SP, #4\n" "MVN R1, #0\n" "STR R0, [R5]\n" "LDR R0, [R3]\n" "BL sub_FF81FF04\n" "LDR R3, =0x99EC0\n" "LDR R0, [R3,#0x7C]\n" "BL sub_FF89EFF0\n" "BL sub_FF963298\n" "BL wait_until_remote_button_is_released\n" "BL capt_seq_hook_set_nr\n" "LDR R3, =0x61F8\n" "LDR R0, [R3]\n" "BL sub_FF89F4B0\n" "B sub_FF963380\n" ); #endif } void __attribute__((naked,noinline)) sub_FF95FEA0_my(long p) { asm volatile ( "STMFD SP!, {R4,LR}\n" "LDR R4, [R0,#0xC]\n" "BL sub_FF968658\n" "CMP R0, #0\n" "BNE loc_FF95FEB8\n" "BL sub_FF968664\n" "loc_FF95FEB8:\n" "LDR R3, =0x99EC0\n" "LDR R2, [R3,#0x24]\n" "CMP R2, #0\n" "BNE loc_FF95FEEC\n" "MOV R0, #0xC\n" "BL sub_FF968678\n" "TST R0, #1\n" "BEQ loc_FF95FEEC\n" "MOV R0, #1\n" "loc_FF95FEDC:\n" "MOV R2, R4\n" "MOV R1, #1\n" "LDMFD SP!, {R4,LR}\n" "B sub_FF95E574\n" "loc_FF95FEEC:\n" "LDR R3, =0x99EC0\n" "LDR R2, [R3,#0x24]\n" "CMP R2, #0\n" "BNE loc_FF95FF3C\n" "MOV R0, R4\n" "BL sub_FF962100\n" "TST R0, #1\n" "BNE loc_FF95FEDC\n" "BL sub_FF9A15A8\n" "BL sub_FF824ADC\n" "LDR R2, =0x99E04\n" "ADD R3, R4, R4,LSL#1\n" "STR R0, [R2,R3,LSL#5]\n" "MOV R0, R4\n" "BL sub_FF963AB0\n" "BL sub_FF962604\n" "BL sub_FF9625A0\n" "MOV R0, R4\n" "BL sub_FF963344_my\n" //-------------> "BL capt_seq_hook_raw_here\n" "B loc_FF95FF50\n" "loc_FF95FF3C:\n" "LDR R3, =0x61E0\n" "LDR R2, [R3]\n" "CMP R2, #0\n" "MOVNE R0, #0x1D\n" "MOVEQ R0, #0\n" "loc_FF95FF50:\n" "MOV R2, R4\n" "MOV R1, #1\n" "BL sub_FF95E574\n" "LDMFD SP!, {R4,LR}\n" "B sub_FF96353C\n" ); } void __attribute__((naked,noinline)) capt_seq_task() { asm volatile( "STMFD SP!, {R4,LR}\n" "SUB SP, SP, #4\n" "MOV R4, SP\n" "B loc_FF96048C\n" "loc_FF960324:\n" "LDR R2, [SP]\n" "LDR R3, [R2]\n" "MOV R0, R2\n" "CMP R3, #0x14\n" "LDRLS PC, [PC,R3,LSL#2]\n" "B loc_FF960460\n" ".long loc_FF960390\n" ".long loc_FF9603B0\n" ".long loc_FF9603C4\n" ".long loc_FF9603D4\n" ".long loc_FF9603CC\n" ".long loc_FF9603DC\n" ".long loc_FF9603E4\n" ".long loc_FF9603F0\n" ".long loc_FF9603F8\n" ".long loc_FF960404\n" ".long loc_FF96040C\n" ".long loc_FF960414\n" ".long loc_FF96041C\n" ".long loc_FF960424\n" ".long loc_FF96042C\n" ".long loc_FF960438\n" ".long loc_FF960440\n" ".long loc_FF960448\n" ".long loc_FF960450\n" ".long loc_FF960458\n" ".long loc_FF960474\n" "loc_FF960390:\n" "BL sub_FF961D60\n" "BL shooting_expo_param_override\n" // + "BL sub_FF95E090\n" "LDR R3, =0x99EC0\n" "LDR R2, [R3,#0x24]\n" "CMP R2, #0\n" "BEQ loc_FF960470\n" "BL sub_FF95FF70\n" "B loc_FF960470\n" "loc_FF9603B0:\n" "BL sub_FF95FEA0_my\n" //-------------> "loc_FF9603B4:\n" "LDR R2, =0x99EC0\n" "MOV R3, #0\n" "STR R3, [R2,#0x24]\n" "B loc_FF960470\n" "loc_FF9603C4:\n" "BL sub_FF9620F0\n" "B loc_FF960470\n" "loc_FF9603CC:\n" "BL sub_FF960F60\n" "B loc_FF9603B4\n" "loc_FF9603D4:\n" "BL sub_FF9612FC\n" "B loc_FF9603B4\n" "loc_FF9603DC:\n" "BL sub_FF96130C\n" "B loc_FF960470\n" "loc_FF9603E4:\n" "BL sub_FF961E44\n" "BL sub_FF95E090\n" "B loc_FF960470\n" "loc_FF9603F0:\n" "BL sub_FF960044\n" "B loc_FF960470\n" "loc_FF9603F8:\n" "BL sub_FF961EAC\n" "BL sub_FF95E090\n" "B loc_FF960470\n" "loc_FF960404:\n" "BL sub_FF9612FC\n" "B loc_FF960470\n" "loc_FF96040C:\n" "BL sub_FF962644\n" "B loc_FF960470\n" "loc_FF960414:\n" "BL sub_FF962988\n" "B loc_FF960470\n" "loc_FF96041C:\n" "BL sub_FF962A0C\n" "B loc_FF960470\n" "loc_FF960424:\n" "BL sub_FF962AFC\n" "B loc_FF960470\n" "loc_FF96042C:\n" "MOV R0, #0\n" "BL sub_FF962BC4\n" "B loc_FF960470\n" "loc_FF960438:\n" "BL sub_FF962D30\n" "B loc_FF960470\n" "loc_FF960440:\n" "BL sub_FF962DC4\n" "B loc_FF960470\n" "loc_FF960448:\n" "BL sub_FF962E80\n" "B loc_FF960470\n" "loc_FF960450:\n" "BL sub_FF962F6C\n" "B loc_FF960470\n" "loc_FF960458:\n" "BL sub_FF962FC0\n" "B loc_FF960470\n" "loc_FF960460:\n" "MOV R1, #0x36C\n" "LDR R0, =0xFF95FC2C\n" "ADD R1, R1, #1\n" "BL sub_FF813B80\n" "loc_FF960470:\n" "LDR R2, [SP]\n" "loc_FF960474:\n" "LDR R3, =0x6F344\n" "LDR R1, [R2,#4]\n" "LDR R0, [R3]\n" "BL sub_FF81FD68\n" "LDR R0, [SP]\n" "BL sub_FF95FCA8\n" "loc_FF96048C:\n" "LDR R3, =0x6F348\n" "MOV R1, R4\n" "LDR R0, [R3]\n" "MOV R2, #0\n" "BL sub_FF820480\n" "TST R0, #1\n" "BEQ loc_FF960324\n" "MOV R1, #0x2A4\n" "LDR R0, =0xFF95FC2C\n" "ADD R1, R1, #3\n" "BL sub_FF813B80\n" "BL sub_FF8219DC\n" "ADD SP, SP, #4\n" "LDMFD SP!, {R4,PC}\n" ); }
boyska/chdkripto
platform/ixus65_sd630/sub/100a/capt_seq.c
C
gpl-2.0
8,281
<?php /** * @package languageDefines * @copyright Copyright 2003-2019 Zen Cart Development Team * @copyright Portions Copyright 2003 osCommerce * @license http://www.zen-cart.com/license/2_0.txt GNU Public License V2.0 * @version $Id: Scott C Wilson 2019 Feb 14 Modified in v1.5.6b $ */ define('TEXT_INFORMATION', 'You may proceed with your purchase by clicking the Checkout button below. Shipping and Taxes and Discounts will be handled on subsequent pages.'); define('NAVBAR_TITLE', 'The Shopping Cart'); define('HEADING_TITLE', 'Your Shopping Cart Contents'); define('HEADING_TITLE_EMPTY', 'Your Shopping Cart'); define('TABLE_HEADING_REMOVE', 'Remove'); define('TABLE_HEADING_PRICE','Unit'); define('TEXT_CART_EMPTY', 'Your Shopping Cart is empty.'); define('SUB_TITLE_SUB_TOTAL', 'Sub-Total:'); define('SUB_TITLE_TOTAL', 'Total:'); define('TEXT_TOTAL_ITEMS', 'Total Items: '); define('TEXT_TOTAL_WEIGHT', '&nbsp;&nbsp;Weight: '); define('TEXT_TOTAL_AMOUNT', '&nbsp;&nbsp;Amount: '); define('TEXT_CART_HELP', '<a href="javascript:session_win();">[help (?)]</a>'); define('TEXT_VISITORS_CART', TEXT_CART_HELP); // legacy define
zencart/zc-v1-series
includes/languages/english/shopping_cart.php
PHP
gpl-2.0
1,141
local mType = Game.createMonsterType("Zulazza The Corruptor") local monster = {} monster.description = "Zulazza The Corruptor" monster.experience = 10000 monster.outfit = { lookType = 334, lookHead = 0, lookBody = 0, lookLegs = 0, lookFeet = 0, lookAddons = 0, lookMount = 0 } monster.health = 46500 monster.maxHealth = 46500 monster.race = "blood" monster.corpse = 10190 monster.speed = 290 monster.manaCost = 0 monster.changeTarget = { interval = 2000, chance = 10 } monster.strategiesTarget = { nearest = 70, health = 10, damage = 10, random = 10, } monster.flags = { summonable = false, attackable = true, hostile = true, convinceable = false, pushable = false, rewardBoss = true, illusionable = false, canPushItems = true, canPushCreatures = true, staticAttackChance = 80, targetDistance = 1, runHealth = 1500, healthHidden = false, isBlockable = false, canWalkOnEnergy = false, canWalkOnFire = false, canWalkOnPoison = false } monster.light = { level = 0, color = 0 } monster.voices = { interval = 5000, chance = 10, {text = "I'm Zulazza, and you won't forget me that fazzt.", yell = false}, {text = "Zzaion is our last zztand! I will not leave wizzout a fight!", yell = false}, {text = "Behind zze Great Gate liezz your doom!", yell = false}, {text = "Oh, HE will take revenge on zzizz azzault when you zztep in front of HIZZ fazze!", yell = false} } monster.loot = { {id = 239, chance = 30500}, {id = 3035, chance = 41325, maxCount = 30}, {id = 3031, chance = 49650, maxCount = 100}, {id = 8894, chance = 50500}, {id = 9058, chance = 33000, maxCount = 4}, {id = 3041, chance = 30500}, {id = 3038, chance = 20500}, {id = 7643, chance = 10500}, {id = 10201, chance = 5500}, {id = 5944, chance = 19250, maxCount = 4}, {id = 3428, chance = 15500}, {id = 7366, chance = 8100, maxCount = 67}, {id = 281, chance = 28000, maxCount = 2}, {id = 3037, chance = 15500}, {id = 3039, chance = 10500}, {id = 7440, chance = 10500}, {id = 3036, chance = 25500}, {id = 238, chance = 20500}, {id = 8054, chance = 5500}, {id = 3414, chance = 5500}, {id = 3010, chance = 10500}, {id = 8063, chance = 5500}, {id = 3415, chance = 5500} } monster.attacks = { {name ="melee", interval = 2000, chance = 100, skill = 200, attack = 200}, {name ="combat", interval = 2000, chance = 40, type = COMBAT_PHYSICALDAMAGE, minDamage = -500, maxDamage = -800, length = 8, spread = 3, effect = CONST_ME_MORTAREA, target = false}, {name ="combat", interval = 2000, chance = 30, type = COMBAT_EARTHDAMAGE, minDamage = -300, maxDamage = -800, radius = 3, effect = CONST_ME_POISONAREA, target = false}, {name ="combat", interval = 2000, chance = 25, type = COMBAT_MANADRAIN, minDamage = -50, maxDamage = -130, range = 7, effect = CONST_ME_MAGIC_GREEN, target = true}, {name ="speed", interval = 2000, chance = 20, speedChange = -500, range = 7, effect = CONST_ME_MAGIC_RED, target = false, duration = 20000} } monster.defenses = { defense = 119, armor = 96, {name ="combat", interval = 2000, chance = 20, type = COMBAT_HEALING, minDamage = 2000, maxDamage = 3000, effect = CONST_ME_MAGIC_BLUE, target = false} } monster.elements = { {type = COMBAT_PHYSICALDAMAGE, percent = 0}, {type = COMBAT_ENERGYDAMAGE, percent = 100}, {type = COMBAT_EARTHDAMAGE, percent = 70}, {type = COMBAT_FIREDAMAGE, percent = 0}, {type = COMBAT_LIFEDRAIN, percent = 0}, {type = COMBAT_MANADRAIN, percent = 0}, {type = COMBAT_DROWNDAMAGE, percent = 0}, {type = COMBAT_ICEDAMAGE, percent = 20}, {type = COMBAT_HOLYDAMAGE , percent = 20}, {type = COMBAT_DEATHDAMAGE , percent = 30} } monster.immunities = { {type = "paralyze", condition = true}, {type = "outfit", condition = false}, {type = "invisible", condition = true}, {type = "bleed", condition = false} } mType.onThink = function(monster, interval) end mType.onAppear = function(monster, creature) if monster:getType():isRewardBoss() then monster:setReward(true) end end mType.onDisappear = function(monster, creature) end mType.onMove = function(monster, creature, fromPosition, toPosition) end mType.onSay = function(monster, creature, type, message) end mType:register(monster)
mattyx14/otxserver
data/monster/raids/zulazza_the_corruptor.lua
Lua
gpl-2.0
4,183
<!DOCTYPE html> <html ng-app="BrowsePassApp" ng-csp style="overflow-y: scroll"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" href="bootstrap/3.2.0/css/bootstrap.min.css"> <link rel="stylesheet" href="bootstrap/3.2.0/css/bootstrap-theme.min.css"> <link rel="shortcut icon" href="favicon.ico"/> <title>BrowsePass</title> <style> body { -webkit-user-select: text; } .nav, .pagination, .carousel, .panel-title a { cursor: pointer; } .panel-group { margin-bottom: 5px; } .panel-body { padding-right: 0px; margin-right: -1px;} .btn-file { position: relative; overflow: hidden; } .btn-file input[type=file] { position: absolute; top: 0; left: 0; opacity: 0; } .input-group-btn label { width: 100px; } .footer { clear: both; padding-top: 10px; } .footer li { display: inline; } .bp-field-value { white-space: pre-wrap; } </style> <!-- KDBX libraries --> <script src="cryptojs/components/core-min.js" type="text/javascript"></script> <script src="cryptojs/components/cipher-core-min.js" type="text/javascript"></script> <script src="cryptojs/components/mode-ecb-min.js" type="text/javascript"></script> <script src="cryptojs/components/aes-min.js" type="text/javascript"></script> <script src="cryptojs/components/pad-nopadding-min.js" type="text/javascript"></script> <script src="cryptojs/components/sha256-min.js" type="text/javascript"></script> <script src="inflate.js" type="text/javascript"></script> <script src="jdataview.js" type="text/javascript"></script> <script src="salsa20.js" type="text/javascript"></script> <script src="kdbx.js" type="text/javascript"></script> <script src="mimetype.js" type="text/javascript"></script> <!-- BrowsePass components --> <script src="angularjs/1.2.21/angular.min.js" type="text/javascript"></script> <script src="ui-bootstrap/ui-bootstrap-tpls-0.11.0.min.js" type="text/javascript"></script> <script src="app.js" type="text/javascript"></script> <script src="app-controller.js" type="text/javascript"></script> <script src="components/gdrive/gdrive-service.js" type="text/javascript"></script> <script src="components/gdrive/gdrive-controller.js" type="text/javascript"></script> <script src="components/dropbox/dropbox-service.js" type="text/javascript"></script> <script src="components/vault/vault-service.js" type="text/javascript"></script> <script src="components/dialog/dialog-service.js" type="text/javascript"></script> <script src="components/file-input/dropzone-directive.js" type="text/javascript"></script> <script src="components/file-input/receiver-directive.js" type="text/javascript"></script> <script src="components/hotkey/hotkey-directive.js" type="text/javascript"></script> <script src="components/open/open-controller.js" type="text/javascript"></script> <script src="components/group/group-controller.js" type="text/javascript"></script> <script src="components/entry/entry-controller.js" type="text/javascript"></script> <script src="components/field/field-directive.js" type="text/javascript"></script> <!-- Google Drive & Google Picker --> <script src="gapi-chrome-apps.js" type="text/javascript"></script> <!-- Dropbox Chooser Drop-in --> <script type="text/javascript" src="https://www.dropbox.com/static/api/2/dropins.js" id="dropboxjs" data-app-key="qe83tqslyje9xt3"></script> </head> <body ng-controller="AppController"> <div class="text-center center-block"> <h1><img src="icon-48.png" /> BrowsePass</h1> </div> <div ng-controller="OpenController" ng-include="'components/open/open-template.html'"></div> <div ng-if="isLoaded()" class="input-group well-sm"> <span class="input-group-btn"> <button class="btn btn-default" btn-checkbox ng-model="appConfig.showGroups">Show Groups</button> </span> <input type="text" class="form-control" placeholder="Filter" ng-model="appConfig.filter" hotkey="{ctrlKey: true, keyCode: 'F'.charCodeAt(0)}" /> <span class="input-group-btn"> <button class="btn" ng-class="{'btn-info': appConfig.filter, 'btn-default': !appConfig.filter}" ng-disabled="!appConfig.filter" ng-click="appConfig.filter=''"> <i class="glyphicon glyphicon-filter"></i> </button> </span> </div> <div ng-controller="GroupController"> <div ng-repeat="group in groups" ng-include="'components/group/group-template.html'"></div> </div> <div class="footer text-muted"> <ul> <li>Licensed under GNU Public License version 2 <i class="glyphicon glyphicon-question-sign" popover-placement="right" popover="with compatible or public domain components AngularJS (MIT License), Bootstrap (MIT License), CryptoJS (New BSD License), gapi-chrome-apps (Apache v2), jDataView (wtfpl License), UI-Bootstrap (MIT License) and unknown components salsa20.js, inflate.js."></i></li> <li>&middot;</li> <li><a href="https://github.com/chkuendig/browsepass" target="_blank">Project page</a></li> <li>&middot;</li> <li><a href="https://github.com/chkuendig/browsepass/issues" target="_blank">Feedback</a></li> </ul> </div> </body> </html>
chkuendig/browsepass
index.html
HTML
gpl-2.0
5,465
/* * PS3 Media Server, for streaming any medias to your PS3. * Copyright (C) 2008 A.Brochard * * 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; version 2 * of the License only. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package net.pms.encoders; import java.io.IOException; import javax.swing.JComponent; import net.pms.configuration.DeviceConfiguration; import net.pms.configuration.PmsConfiguration; import net.pms.dlna.DLNAMediaInfo; import net.pms.dlna.DLNAResource; import net.pms.formats.Format; import net.pms.io.OutputParams; import net.pms.io.PipeProcess; import net.pms.io.ProcessWrapper; import net.pms.io.ProcessWrapperImpl; import net.pms.util.PlayerUtil; public class MEncoderWebVideo extends Player { public static final String ID = "mencoderwebvideo"; @Override public JComponent config() { return null; } @Override public String id() { return ID; } @Override public int purpose() { return VIDEO_WEBSTREAM_PLAYER; } @Override public boolean isTimeSeekable() { return false; } @Override public String mimeType() { return "video/mpeg"; } protected String[] getDefaultArgs() { int nThreads = configuration.getMencoderMaxThreads(); String acodec = configuration.isMencoderAc3Fixed() ? "ac3_fixed" : "ac3"; return new String[]{ "-msglevel", "all=2", "-quiet", "-prefer-ipv4", "-cache", "16384", "-oac", "lavc", "-of", "lavf", "-lavfopts", "format=dvd", "-ovc", "lavc", "-lavcopts", "vcodec=mpeg2video:vbitrate=4096:threads=" + nThreads + ":acodec=" + acodec + ":abitrate=128", "-vf", "harddup", "-ofps", "25" }; } @Deprecated public MEncoderWebVideo(PmsConfiguration configuration) { this(); } public MEncoderWebVideo() { } @Override public ProcessWrapper launchTranscode( DLNAResource dlna, DLNAMediaInfo media, OutputParams params) throws IOException { // Use device-specific pms conf PmsConfiguration prev = configuration; configuration = (DeviceConfiguration) params.mediaRenderer; params.minBufferSize = params.minFileSize; params.secondread_minsize = 100000; PipeProcess pipe = new PipeProcess("mencoder" + System.currentTimeMillis()); params.input_pipes[0] = pipe; String cmdArray[] = new String[args().length + 4]; cmdArray[0] = executable(); final String filename = dlna.getFileName(); cmdArray[1] = filename; System.arraycopy(args(), 0, cmdArray, 2, args().length); cmdArray[cmdArray.length - 2] = "-o"; cmdArray[cmdArray.length - 1] = pipe.getInputPipe(); ProcessWrapper mkfifo_process = pipe.getPipeProcess(); cmdArray = finalizeTranscoderArgs( filename, dlna, media, params, cmdArray ); ProcessWrapperImpl pw = new ProcessWrapperImpl(cmdArray, params); pw.attachProcess(mkfifo_process); /** * It can take a long time for Windows to create a named pipe (and * mkfifo can be slow if /tmp isn't memory-mapped), so run this in * the current thread. */ mkfifo_process.runInSameThread(); pipe.deleteLater(); pw.runInNewThread(); // Not sure what good this 50ms wait will do for the calling method. try { Thread.sleep(50); } catch (InterruptedException e) { } configuration = prev; return pw; } @Override public boolean avisynth() { return false; } @Override public String name() { return "MEncoder Web"; } @Override public String[] args() { return getDefaultArgs(); } @Override public String executable() { return configuration.getMencoderPath(); } @Override public int type() { return Format.VIDEO; } /** * {@inheritDoc} */ @Override public boolean isCompatible(DLNAResource resource) { return PlayerUtil.isWebVideo(resource); } }
Sami32/UniversalMediaServer
src/main/java/net/pms/encoders/MEncoderWebVideo.java
Java
gpl-2.0
4,257
/*************************************************************************** qgsvectorlayerdiagramprovider.h -------------------------------------- Date : September 2015 Copyright : (C) 2015 by Martin Dobias Email : wonder dot sk at gmail dot com *************************************************************************** * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 2 of the License, or * * (at your option) any later version. * * * ***************************************************************************/ #ifndef QGSVECTORLAYERDIAGRAMPROVIDER_H #define QGSVECTORLAYERDIAGRAMPROVIDER_H #define SIP_NO_FILE #include "qgis_core.h" #include "qgslabelingengine.h" #include "qgslabelfeature.h" #include "qgsdiagramrenderer.h" /** * \ingroup core * Class that adds extra information to QgsLabelFeature for labeling of diagrams * * \note this class is not a part of public API yet. See notes in QgsLabelingEngine * \note not available in Python bindings */ class QgsDiagramLabelFeature : public QgsLabelFeature { public: //! Create label feature, takes ownership of the geometry instance QgsDiagramLabelFeature( QgsFeatureId id, geos::unique_ptr geometry, QSizeF size ) : QgsLabelFeature( id, std::move( geometry ), size ) {} //! Store feature's attributes - used for rendering of diagrams void setAttributes( const QgsAttributes &attrs ) { mAttributes = attrs; } //! Gets feature's attributes - used for rendering of diagrams const QgsAttributes &attributes() { return mAttributes; } protected: //! Stores attribute values for diagram rendering QgsAttributes mAttributes; }; class QgsAbstractFeatureSource; /** * \ingroup core * \brief The QgsVectorLayerDiagramProvider class implements support for diagrams within * the labeling engine. Parameters for the diagrams are taken from the layer settings. * * \note this class is not a part of public API yet. See notes in QgsLabelingEngine * \note not available in Python bindings * \since QGIS 2.12 */ class CORE_EXPORT QgsVectorLayerDiagramProvider : public QgsAbstractLabelProvider { public: //! Convenience constructor to initialize the provider from given vector layer explicit QgsVectorLayerDiagramProvider( QgsVectorLayer *layer, bool ownFeatureLoop = true ); //! Clean up ~QgsVectorLayerDiagramProvider() override; QList<QgsLabelFeature *> labelFeatures( QgsRenderContext &context ) override; void drawLabel( QgsRenderContext &context, pal::LabelPosition *label ) const override; // new virtual methods /** * Prepare for registration of features. Must be called after provider has been added to engine (uses its map settings) * \param context render context. * \param attributeNames list of attribute names to which additional required attributes shall be added * \returns Whether the preparation was successful - if not, the provider shall not be used */ virtual bool prepare( const QgsRenderContext &context, QSet<QString> &attributeNames ); /** * Register a feature for labeling as one or more QgsLabelFeature objects stored into mFeatures * * \param feature feature for diagram * \param context render context. The QgsExpressionContext contained within the render context * must have already had the feature and fields sets prior to calling this method. * \param obstacleGeometry optional obstacle geometry, if a different geometry to the feature's geometry * should be used as an obstacle for labels (e.g., if the feature has been rendered with an offset point * symbol, the obstacle geometry should represent the bounds of the offset symbol). If not set, * the feature's original geometry will be used as an obstacle for labels. Ownership of obstacleGeometry * is transferred. */ virtual void registerFeature( QgsFeature &feature, QgsRenderContext &context, const QgsGeometry &obstacleGeometry = QgsGeometry() ); protected: //! initialization method - called from constructors void init(); //! helper method to register one diagram feautre QgsLabelFeature *registerDiagram( QgsFeature &feat, QgsRenderContext &context, const QgsGeometry &obstacleGeometry = QgsGeometry() ); protected: //! Diagram layer settings QgsDiagramLayerSettings mSettings; //! Diagram renderer instance (owned by mSettings) QgsDiagramRenderer *mDiagRenderer = nullptr; // these are needed only if using own renderer loop //! Layer's fields QgsFields mFields; //! Layer's CRS QgsCoordinateReferenceSystem mLayerCrs; //! Layer's feature source QgsAbstractFeatureSource *mSource = nullptr; //! Whether layer's feature source is owned bool mOwnsSource; //! List of generated label features (owned by the provider) QList<QgsLabelFeature *> mFeatures; }; #endif // QGSVECTORLAYERDIAGRAMPROVIDER_H
dgoedkoop/QGIS
src/core/qgsvectorlayerdiagramprovider.h
C
gpl-2.0
5,314
/* * Copyright (C) 2011-2012 ArkCORE2 <http://www.arkania.net/> * Copyright (C) 2010-2012 Project SkyFire <http://www.projectskyfire.org/> * Copyright (C) 2008-2012 TrinityCore <http://www.trinitycore.org/> * Copyright (C) 2006-2012 ScriptDev2 <https://scriptdev2.svn.sourceforge.net/> * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License as published by the * Free Software Foundation; either version 2 of the License, or (at your * option) any later version. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * more details. * * You should have received a copy of the GNU General Public License along * with this program. If not, see <http://www.gnu.org/licenses/>. */ /* ScriptData SDName: Boss_Razorgore SD%Complete: 50 SDComment: Needs additional review. Phase 1 NYI (Grethok the Controller) SDCategory: Blackwing Lair EndScriptData */ #include "ScriptPCH.h" //Razorgore Phase 2 Script enum Say { SAY_EGGS_BROKEN1 = -1469022, SAY_EGGS_BROKEN2 = -1469023, SAY_EGGS_BROKEN3 = -1469024, SAY_DEATH = -1469025 }; enum Spells { SPELL_CLEAVE = 22540, SPELL_WARSTOMP = 24375, SPELL_FIREBALLVOLLEY = 22425, SPELL_CONFLAGRATION = 23023 }; class boss_razorgore : public CreatureScript { public: boss_razorgore() : CreatureScript("boss_razorgore") { } CreatureAI* GetAI(Creature* creature) const { return new boss_razorgoreAI (creature); } struct boss_razorgoreAI : public ScriptedAI { boss_razorgoreAI(Creature* creature) : ScriptedAI(creature) {} uint32 Cleave_Timer; uint32 WarStomp_Timer; uint32 FireballVolley_Timer; uint32 Conflagration_Timer; void Reset() { Cleave_Timer = 15000; //These times are probably wrong WarStomp_Timer = 35000; FireballVolley_Timer = 7000; Conflagration_Timer = 12000; } void EnterCombat(Unit* /*who*/) { DoZoneInCombat(); } void JustDied(Unit* /*Killer*/) { DoScriptText(SAY_DEATH, me); } void UpdateAI(const uint32 diff) { if (!UpdateVictim()) return; //Cleave_Timer if (Cleave_Timer <= diff) { DoCast(me->getVictim(), SPELL_CLEAVE); Cleave_Timer = urand(7000, 10000); } else Cleave_Timer -= diff; //WarStomp_Timer if (WarStomp_Timer <= diff) { DoCast(me->getVictim(), SPELL_WARSTOMP); WarStomp_Timer = urand(15000, 25000); } else WarStomp_Timer -= diff; //FireballVolley_Timer if (FireballVolley_Timer <= diff) { DoCast(me->getVictim(), SPELL_FIREBALLVOLLEY); FireballVolley_Timer = urand(12000, 15000); } else FireballVolley_Timer -= diff; //Conflagration_Timer if (Conflagration_Timer <= diff) { DoCast(me->getVictim(), SPELL_CONFLAGRATION); //We will remove this threat reduction and add an aura check. //if (DoGetThreat(me->getVictim())) //DoModifyThreatPercent(me->getVictim(), -50); Conflagration_Timer = 12000; } else Conflagration_Timer -= diff; // Aura Check. If the gamer is affected by confliguration we attack a random gamer. if (me->getVictim() && me->getVictim()->HasAura(SPELL_CONFLAGRATION)) if (Unit* target = SelectTarget(SELECT_TARGET_RANDOM, 1, 100, true)) me->TauntApply(target); DoMeleeAttackIfReady(); } }; }; void AddSC_boss_razorgore() { new boss_razorgore(); }
alideny/ChgMangos_CTM
src/server/scripts/EasternKingdoms/BlackwingLair/boss_razorgore.cpp
C++
gpl-2.0
4,148
package org.hl7.v3; import java.util.ArrayList; import java.util.List; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlAttribute; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlType; /** * <p>Java class for MFMI_MT700711UV01.PriorRegisteredAct complex type. * * <p>The following schema fragment specifies the expected content contained within this class. * * <pre> * &lt;complexType name="MFMI_MT700711UV01.PriorRegisteredAct"> * &lt;complexContent> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * &lt;sequence> * &lt;group ref="{urn:hl7-org:v3}InfrastructureRootElements"/> * &lt;element name="id" type="{urn:hl7-org:v3}II" maxOccurs="unbounded"/> * &lt;/sequence> * &lt;attGroup ref="{urn:hl7-org:v3}InfrastructureRootAttributes"/> * &lt;attribute name="nullFlavor" type="{urn:hl7-org:v3}NullFlavor" /> * &lt;attribute name="classCode" use="required" type="{urn:hl7-org:v3}ActClassRoot" /> * &lt;attribute name="moodCode" use="required" type="{urn:hl7-org:v3}ActMoodCompletionTrack" /> * &lt;/restriction> * &lt;/complexContent> * &lt;/complexType> * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "MFMI_MT700711UV01.PriorRegisteredAct", propOrder = { "realmCode", "typeId", "templateId", "id" }) public class MFMIMT700711UV01PriorRegisteredAct { protected List<CS> realmCode; protected II typeId; protected List<II> templateId; @XmlElement(required = true) protected List<II> id; @XmlAttribute(name = "nullFlavor") protected List<String> nullFlavor; @XmlAttribute(name = "classCode", required = true) protected List<String> classCode; @XmlAttribute(name = "moodCode", required = true) protected List<String> moodCode; /** * Gets the value of the realmCode property. * * <p> * This accessor method returns a reference to the live list, * not a snapshot. Therefore any modification you make to the * returned list will be present inside the JAXB object. * This is why there is not a <CODE>set</CODE> method for the realmCode property. * * <p> * For example, to add a new item, do as follows: * <pre> * getRealmCode().add(newItem); * </pre> * * * <p> * Objects of the following type(s) are allowed in the list * {@link CS } * * */ public List<CS> getRealmCode() { if (realmCode == null) { realmCode = new ArrayList<CS>(); } return this.realmCode; } /** * Gets the value of the typeId property. * * @return * possible object is * {@link II } * */ public II getTypeId() { return typeId; } /** * Sets the value of the typeId property. * * @param value * allowed object is * {@link II } * */ public void setTypeId(II value) { this.typeId = value; } /** * Gets the value of the templateId property. * * <p> * This accessor method returns a reference to the live list, * not a snapshot. Therefore any modification you make to the * returned list will be present inside the JAXB object. * This is why there is not a <CODE>set</CODE> method for the templateId property. * * <p> * For example, to add a new item, do as follows: * <pre> * getTemplateId().add(newItem); * </pre> * * * <p> * Objects of the following type(s) are allowed in the list * {@link II } * * */ public List<II> getTemplateId() { if (templateId == null) { templateId = new ArrayList<II>(); } return this.templateId; } /** * Gets the value of the id property. * * <p> * This accessor method returns a reference to the live list, * not a snapshot. Therefore any modification you make to the * returned list will be present inside the JAXB object. * This is why there is not a <CODE>set</CODE> method for the id property. * * <p> * For example, to add a new item, do as follows: * <pre> * getId().add(newItem); * </pre> * * * <p> * Objects of the following type(s) are allowed in the list * {@link II } * * */ public List<II> getId() { if (id == null) { id = new ArrayList<II>(); } return this.id; } /** * Gets the value of the nullFlavor property. * * <p> * This accessor method returns a reference to the live list, * not a snapshot. Therefore any modification you make to the * returned list will be present inside the JAXB object. * This is why there is not a <CODE>set</CODE> method for the nullFlavor property. * * <p> * For example, to add a new item, do as follows: * <pre> * getNullFlavor().add(newItem); * </pre> * * * <p> * Objects of the following type(s) are allowed in the list * {@link String } * * */ public List<String> getNullFlavor() { if (nullFlavor == null) { nullFlavor = new ArrayList<String>(); } return this.nullFlavor; } /** * Gets the value of the classCode property. * * <p> * This accessor method returns a reference to the live list, * not a snapshot. Therefore any modification you make to the * returned list will be present inside the JAXB object. * This is why there is not a <CODE>set</CODE> method for the classCode property. * * <p> * For example, to add a new item, do as follows: * <pre> * getClassCode().add(newItem); * </pre> * * * <p> * Objects of the following type(s) are allowed in the list * {@link String } * * */ public List<String> getClassCode() { if (classCode == null) { classCode = new ArrayList<String>(); } return this.classCode; } /** * Gets the value of the moodCode property. * * <p> * This accessor method returns a reference to the live list, * not a snapshot. Therefore any modification you make to the * returned list will be present inside the JAXB object. * This is why there is not a <CODE>set</CODE> method for the moodCode property. * * <p> * For example, to add a new item, do as follows: * <pre> * getMoodCode().add(newItem); * </pre> * * * <p> * Objects of the following type(s) are allowed in the list * {@link String } * * */ public List<String> getMoodCode() { if (moodCode == null) { moodCode = new ArrayList<String>(); } return this.moodCode; } }
flaviociaware/cwEnsaiosWeb
cwCADSUS/src/main/java/org/hl7/v3/MFMIMT700711UV01PriorRegisteredAct.java
Java
gpl-2.0
7,119
/* randompool.c (P)RNG, relies on system /dev/random to get the data. Copyright: Copyright (c) 2002, 2003 SFNT Finland Oy. All rights reserved. */ #include "sshincludes.h" #include "sshcrypt.h" #include "sshcrypt_i.h" #include "sshrandom_i.h" #define SSH_DEBUG_MODULE "SshRandomPool" typedef struct SshRandomPoolStateRec { /* Pool buffer, allocated memory */ unsigned char *pool; /* Current read offset to pool */ size_t pool_offset; /* Length of the pool true data. (offset + len) is the end of valid data, where offset is the start of valid data - thus between add_entropy (offset + len) is a constant.*/ size_t pool_len; /* Size of the pool */ size_t pool_size; } *SshRandomPoolState, SshRandomPoolStateStruct; static SshCryptoStatus ssh_random_pool_get_bytes(void *context, unsigned char *buf, size_t buflen) { SshRandomPoolState state = (SshRandomPoolState) context; SSH_DEBUG(5, ("Reading, offset=%d len=%d size=%d buflen=%d", state->pool_offset, state->pool_len, state->pool_size, buflen)); /* See if we can satisfy `buflen' bytes from the pool */ if (state->pool_len < buflen) return SSH_CRYPTO_DATA_TOO_LONG; SSH_ASSERT(state->pool_len >= buflen); memcpy(buf, state->pool + state->pool_offset, buflen); state->pool_len -= buflen; state->pool_offset += buflen; SSH_ASSERT(state->pool_offset + state->pool_len <= state->pool_size); /* Request more random noise when the pool length is less than 1/4 of the pool size. */ if (4 * state->pool_len <= state->pool_size) ssh_crypto_library_request_noise(); return SSH_CRYPTO_OK; } static SshCryptoStatus ssh_random_pool_add_entropy(void *context, const unsigned char *buf, size_t buflen, size_t estimated_entropy_bits) { SshRandomPoolState state = (SshRandomPoolState) context; SSH_DEBUG(5, ("Adding entropy, offset=%d len=%d size=%d buflen=%d", state->pool_offset, state->pool_len, state->pool_size, buflen)); /* Check if we can put `buflen' bytes into end of current pool */ if (state->pool_size - (state->pool_offset + state->pool_len) < buflen) { size_t new_size; unsigned char *new_pool; /* No - do two things: allocate compact buffer */ new_size = state->pool_len + buflen; if ((new_pool = ssh_malloc(new_size)) == NULL) return SSH_CRYPTO_NO_MEMORY; memcpy(new_pool, state->pool + state->pool_offset, state->pool_len); ssh_free(state->pool); state->pool = new_pool; state->pool_offset = 0; state->pool_size = new_size; } SSH_ASSERT(state->pool_size - state->pool_len >= buflen); /* Yeah, we have enough space at the end */ memcpy(state->pool + state->pool_len, buf, buflen); state->pool_len += buflen; SSH_ASSERT((state->pool_offset + state->pool_len) <= state->pool_size); return SSH_CRYPTO_OK; } static SshCryptoStatus ssh_random_pool_init(void **context_ret) { SshRandomPoolState state; if (!(state = ssh_calloc(1, sizeof(*state)))) return SSH_CRYPTO_NO_MEMORY; state->pool_offset = state->pool_len = state->pool_size = 0; state->pool = NULL; *context_ret = state; return SSH_CRYPTO_OK; } static void ssh_random_pool_uninit(void *context) { SshRandomPoolState state = (SshRandomPoolState) context; ssh_free(state->pool); ssh_free(state); } const SshRandomDefStruct ssh_random_pool = { "pool", 0, ssh_random_pool_init, ssh_random_pool_uninit, ssh_random_pool_add_entropy, ssh_random_pool_get_bytes }; /* Internal (but not static) function */ SshCryptoStatus ssh_random_pool_get_length(SshRandom handle, size_t *size_ret) { SshRandomPoolState state; SshRandomObject random; if (!(random = SSH_CRYPTO_HANDLE_TO_RANDOM(handle))) return SSH_CRYPTO_HANDLE_INVALID; if (random->ops != &ssh_random_pool) return SSH_CRYPTO_UNSUPPORTED; state = (SshRandomPoolState) random->context; *size_ret = state->pool_len; return SSH_CRYPTO_OK; }
invisiblek/kernel_808l
drivers/net/eip93_drivers/quickSec/src/lib/sshcrypto/sshrandom/randompool.c
C
gpl-2.0
4,055
#ifndef __CUSTOM_HEURISTIC_H_ #define __CUSTOM_HEURISTIC_H_ int apply_custom_fit(void); #endif
ankitC/RK-kernel
include/linux/custom_heuristic.h
C
gpl-2.0
98
/** * $Id: sites/all/libraries/tinymce/jscripts/tiny_mce/plugins/visualchars/editor_plugin_src.js 1.3 2010/02/18 14:48:59EST Linda M. Williams (WILLIAMSLM) Production $ * * @author Moxiecode * @copyright Copyright © 2004-2008, Moxiecode Systems AB, All rights reserved. */ (function() { tinymce.create('tinymce.plugins.VisualChars', { init : function(ed, url) { var t = this; t.editor = ed; // Register commands ed.addCommand('mceVisualChars', t._toggleVisualChars, t); // Register buttons ed.addButton('visualchars', {title : 'visualchars.desc', cmd : 'mceVisualChars'}); ed.onBeforeGetContent.add(function(ed, o) { if (t.state) { t.state = true; t._toggleVisualChars(); } }); }, getInfo : function() { return { longname : 'Visual characters', author : 'Moxiecode Systems AB', authorurl : 'http://tinymce.moxiecode.com', infourl : 'http://wiki.moxiecode.com/index.php/TinyMCE:Plugins/visualchars', version : tinymce.majorVersion + "." + tinymce.minorVersion }; }, // Private methods _toggleVisualChars : function() { var t = this, ed = t.editor, nl, i, h, d = ed.getDoc(), b = ed.getBody(), nv, s = ed.selection, bo; t.state = !t.state; ed.controlManager.setActive('visualchars', t.state); if (t.state) { nl = []; tinymce.walk(b, function(n) { if (n.nodeType == 3 && n.nodeValue && n.nodeValue.indexOf('\u00a0') != -1) nl.push(n); }, 'childNodes'); for (i=0; i<nl.length; i++) { nv = nl[i].nodeValue; nv = nv.replace(/(\u00a0+)/g, '<span class="mceItemHidden mceVisualNbsp">$1</span>'); nv = nv.replace(/\u00a0/g, '\u00b7'); ed.dom.setOuterHTML(nl[i], nv, d); } } else { nl = tinymce.grep(ed.dom.select('span', b), function(n) { return ed.dom.hasClass(n, 'mceVisualNbsp'); }); for (i=0; i<nl.length; i++) ed.dom.setOuterHTML(nl[i], nl[i].innerHTML.replace(/(&middot;|\u00b7)/g, '&nbsp;'), d); } } }); // Register plugin tinymce.PluginManager.add('visualchars', tinymce.plugins.VisualChars); })();
WPMedia/wp-postfun-drupal-prod
sites/all/libraries/tinymce/jscripts/tiny_mce/plugins/visualchars/editor_plugin_src.js
JavaScript
gpl-2.0
2,165
<html lang="en"> <head> <title>ARM-Specific Protocol Details - Debugging with GDB</title> <meta http-equiv="Content-Type" content="text/html"> <meta name="description" content="Debugging with GDB"> <meta name="generator" content="makeinfo 4.8"> <link title="Top" rel="start" href="index.html#Top"> <link rel="up" href="Architecture_002dSpecific-Protocol-Details.html#Architecture_002dSpecific-Protocol-Details" title="Architecture-Specific Protocol Details"> <link rel="next" href="MIPS_002dSpecific-Protocol-Details.html#MIPS_002dSpecific-Protocol-Details" title="MIPS-Specific Protocol Details"> <link href="http://www.gnu.org/software/texinfo/" rel="generator-home" title="Texinfo Homepage"> <!-- Copyright (C) 1988-2018 Free Software Foundation, Inc. Permission is granted to copy, distribute and/or modify this document under the terms of the GNU Free Documentation License, Version 1.3 or any later version published by the Free Software Foundation; with the Invariant Sections being ``Free Software'' and ``Free Software Needs Free Documentation'', with the Front-Cover Texts being ``A GNU Manual,'' and with the Back-Cover Texts as in (a) below. (a) The FSF's Back-Cover Text is: ``You are free to copy and modify this GNU Manual. Buying copies from GNU Press supports the FSF in developing GNU and promoting software freedom.'' --> <meta http-equiv="Content-Style-Type" content="text/css"> <style type="text/css"><!-- pre.display { font-family:inherit } pre.format { font-family:inherit } pre.smalldisplay { font-family:inherit; font-size:smaller } pre.smallformat { font-family:inherit; font-size:smaller } pre.smallexample { font-size:smaller } pre.smalllisp { font-size:smaller } span.sc { font-variant:small-caps } span.roman { font-family:serif; font-weight:normal; } span.sansserif { font-family:sans-serif; font-weight:normal; } --></style> </head> <body> <div class="node"> <p> <a name="ARM-Specific-Protocol-Details"></a> <a name="ARM_002dSpecific-Protocol-Details"></a> Next:&nbsp;<a rel="next" accesskey="n" href="MIPS_002dSpecific-Protocol-Details.html#MIPS_002dSpecific-Protocol-Details">MIPS-Specific Protocol Details</a>, Up:&nbsp;<a rel="up" accesskey="u" href="Architecture_002dSpecific-Protocol-Details.html#Architecture_002dSpecific-Protocol-Details">Architecture-Specific Protocol Details</a> <hr> </div> <h4 class="subsection">E.5.1 <acronym>ARM</acronym>-specific Protocol Details</h4> <ul class="menu"> <li><a accesskey="1" href="ARM-Breakpoint-Kinds.html#ARM-Breakpoint-Kinds">ARM Breakpoint Kinds</a> </ul> </body></html>
jocelynmass/nrf51
toolchain/arm_cm0/share/doc/gcc-arm-none-eabi/html/gdb/ARM_002dSpecific-Protocol-Details.html
HTML
gpl-2.0
2,591
lwt === Light-Weighted Thread Library version 0.2 alpha * Modified run_queue and wait_queue + Added sync/bounded-async channel support between lwt threads + Added grouped waiting on a number of channels tonylxc 11/20/2013
cooniur/lwt
README.md
Markdown
gpl-2.0
227
import os import sys print help(sys) print help(os)
pybursa/homeworks
e_tverdokhleboff/hw3/3.4.py
Python
gpl-2.0
52
<?php /** * @copyright Copyright (C) 2005 - 2012 Open Source Matters, Inc. All rights reserved. * @license GNU General Public License version 2 or later; see LICENSE.txt */ defined('JPATH_BASE') or die; /** * Supports a modal article picker. * * @package Joomla.Administrator * @subpackage com_ntrip * @since 1.6 */ class JFormFieldCustomItem extends JFormField { /** * The form field type. * * @var string * @since 1.6 */ protected $type = 'CustomItem'; /** * Method to get the field input markup. * * @return string The field input markup. * @since 1.6 */ protected function getInput() { // Load the modal behavior script. JHtml::_('behavior.modal', 'a.modal'); // Build the script. $script = array(); $script[] = ' function jSelect_'.$this->id.'(id, title, catid, object) {'; $script[] = ' document.id("'.$this->id.'_id").value = id;'; $script[] = ' document.id("'.$this->id.'_name").value = title;'; $script[] = ' SqueezeBox.close();'; $script[] = ' }'; // Add the script to the document head. JFactory::getDocument()->addScriptDeclaration(implode("\n", $script)); // Setup variables for display. $html = array(); $link = 'index.php?option=com_ntrip&amp;layout=modal&amp;tmpl=component&amp;function=jSelect_'.$this->id; $db = JFactory::getDBO(); $id = JRequest::getInt('id', 0); $type = 'hotels'; if ($id) { $query = $db->getQuery(true); $query->select('item_type')->from('#__ntrip_promotions')->where('id = ' . $id); $db->setQuery($query); $type = $db->loadResult(); if (!$type) $type = 'hotels'; } $db->setQuery( 'SELECT name' . ' FROM #__ntrip_' . $type . ' WHERE id = '.(int) $this->value ); $title = $db->loadResult(); if ($error = $db->getErrorMsg()) { JError::raiseWarning(500, $error); } if (empty($title)) { $title = JText::_('Select Item'); } $title = htmlspecialchars($title, ENT_QUOTES, 'UTF-8'); // The current user display field. $html[] = '<div class="fltlft">'; $html[] = ' <input type="text" id="'.$this->id.'_name" value="'.$title.'" disabled="disabled" size="35" />'; $html[] = '</div>'; // The user select button. $html[] = '<div class="button2-left">'; $html[] = ' <div class="blank">'; $html[] = ' <a class="modal select-item" title="'.JText::_('Select Item').'" href="'.$link.'&amp;'.JSession::getFormToken().'=1" rel="{handler: \'iframe\', size: {x: 800, y: 450}}">'.JText::_('Select Item').'</a>'; $html[] = ' </div>'; $html[] = '</div>'; // The active article id field. if (0 == (int)$this->value) { $value = ''; } else { $value = (int)$this->value; } // class='required' for client side validation $class = ''; if ($this->required) { $class = ' class="required modal-value"'; } $html[] = '<input type="hidden" id="'.$this->id.'_id"'.$class.' name="'.$this->name.'" value="'.$value.'" />'; return implode("\n", $html); } }
ngxuanmui/9trip.vn
administrator/components/com_ntrip/models/fields/customitem.php
PHP
gpl-2.0
2,980
package com.numhero.client.widget.submenu; public class EstimatesSubmenuEstimatesSubmenuUiBinderImplGenMessages_en implements com.numhero.client.widget.submenu.EstimatesSubmenuEstimatesSubmenuUiBinderImplGenMessages { public java.lang.String message3() { return "View Archived Estimates"; } public java.lang.String message4() { return "View Estimate History"; } public java.lang.String message2() { return "View Most Recent Estimates"; } public java.lang.String message1() { return "Create An Estimate"; } }
midaboghetich/netnumero
gen/com/numhero/client/widget/submenu/EstimatesSubmenuEstimatesSubmenuUiBinderImplGenMessages_en.java
Java
gpl-2.0
555
\hypertarget{util_8h_source}{\section{\-Process/util.h} } \begin{DoxyCode} 00001 \textcolor{preprocessor}{#include <iostream>} 00002 \textcolor{preprocessor}{#include <cstring>} \textcolor{comment}{//strcpy} 00003 std::string utilGetName(std::string percorso); 00004 \textcolor{keywordtype}{char} * toChar(std::string Stringa); 00005 \textcolor{keywordtype}{int} toInt(std::string Stringa); 00006 \textcolor{keywordtype}{char} * FromIntToChar(\textcolor{keywordtype}{int} num); \end{DoxyCode}
devintaietta/Remote-Player-Audio
doxygen/docs/latex/util_8h_source.tex
TeX
gpl-2.0
494
/* ResidualVM - A 3D game interpreter * * ResidualVM is the legal property of its developers, whose names * are too numerous to list here. Please refer to the COPYRIGHT * file distributed with this source distribution. * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. * */ #ifndef BACKENDS_GRAPHICS_SURFACESDL_GRAPHICS_H #define BACKENDS_GRAPHICS_SURFACESDL_GRAPHICS_H #include "backends/graphics/sdl/resvm-sdl-graphics.h" /** * SDL Surface based graphics manager * * Used when rendering the launcher, or games with TinyGL */ class SurfaceSdlGraphicsManager : public ResVmSdlGraphicsManager { public: SurfaceSdlGraphicsManager(SdlEventSource *sdlEventSource, SdlWindow *window, const Capabilities &capabilities); virtual ~SurfaceSdlGraphicsManager(); // GraphicsManager API - Features virtual bool hasFeature(OSystem::Feature f) override; // GraphicsManager API - Graphics mode virtual void setupScreen(uint gameWidth, uint gameHeight, bool fullscreen, bool accel3d) override; virtual Graphics::PixelBuffer getScreenPixelBuffer() override; virtual int16 getHeight() override; virtual int16 getWidth() override; // GraphicsManager API - Draw methods virtual void updateScreen() override; // GraphicsManager API - Overlay virtual void showOverlay() override; virtual void hideOverlay() override; virtual void clearOverlay() override; virtual void grabOverlay(void *buf, int pitch) override; virtual void copyRectToOverlay(const void *buf, int pitch, int x, int y, int w, int h) override; /* Render the passed Surfaces besides the game texture. * This is used for widescreen support in the Grim engine. * Note: we must copy the Surfaces, as they are free()d after this call. */ virtual void suggestSideTextures(Graphics::Surface *left, Graphics::Surface *right) override; // GraphicsManager API - Mouse virtual void warpMouse(int x, int y) override; // SdlGraphicsManager API virtual void transformMouseCoordinates(Common::Point &point) override; protected: #if SDL_VERSION_ATLEAST(2, 0, 0) SDL_Renderer *_renderer; SDL_Texture *_screenTexture; void deinitializeRenderer(); SDL_Surface *SDL_SetVideoMode(int width, int height, int bpp, Uint32 flags); #endif SDL_Surface *_screen; SDL_Surface *_subScreen; SDL_Surface *_overlayscreen; bool _overlayDirty; Math::Rect2d _gameRect; SDL_Surface *_sideSurfaces[2]; void drawOverlay(); void drawSideTextures(); void closeOverlay(); }; #endif
firesock/residualvm
backends/graphics/surfacesdl/surfacesdl-graphics.h
C
gpl-2.0
3,123
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.ComponentModel; using DotNetNuke.Common.Utilities; using DotNetNuke.Data; using DotNetNuke.Services.Log.EventLog; using DotNetNuke.Services.Exceptions; using SetimBasico; namespace SetimBasico { ///<summary> ///Controladores para los procedimientos de asoPeriodoCuota ///</summary> [DataObjectAttribute()] public partial class asoPeriodoCuotaControl { LogEventos _eventos = new LogEventos(); [DataObjectMethodAttribute(DataObjectMethodType.Select, true)] public IList<asoPeriodoCuota> _0SelByasoPrestamo_Id(Int32 p_asoPrestamo_Id) { return CBO.FillCollection<asoPeriodoCuota>(DataProvider.Instance().ExecuteReader( "sp_asoPeriodoCuota_0SelByasoPrestamo_Id" , p_asoPrestamo_Id )); } [DataObjectMethodAttribute(DataObjectMethodType.Select, true)] public IList<asoPeriodoCuota> _0Sel() { return CBO.FillCollection<asoPeriodoCuota>(DataProvider.Instance().ExecuteReader( "sp_asoPeriodoCuota_0Sel" )); } [DataObjectMethodAttribute(DataObjectMethodType.Select, true)] public IList<asoPeriodoCuota> _0SelByasoSocio_Id(Int32 p_asoSocio_Id, Int32 p_asoPeriodo_Id) { return CBO.FillCollection<asoPeriodoCuota>(DataProvider.Instance().ExecuteReader( "sp_asoPeriodoCuota_0SelByasoSocio_Id" , p_asoSocio_Id, p_asoPeriodo_Id )); } [DataObjectMethodAttribute(DataObjectMethodType.Select, true)] public IList<asoPeriodoCuota> _0SelByAll(Int32? asoPeriodo_Id = null, Int32? asoPrestamo_Id = null, Decimal? Valor_Capital = null, Decimal? Valor_Interes = null, String Estado = null, String Descripcion = null, String asoSocio_Nombre = null, DateTime? asoPeriodo_Fecha = null, Decimal? Valor_Suma = null, Int32? asoSocio_Id = null, Int32? No_Cuotas = null, Int32? No_Cuotas_PEN = null, Int32? No_Cuotas_COB = null, String Desc_Cuotas = null, Int32 PageIndex = 0, Int32 PageSize = 10, String SortField = "Id", String SortDirection = "ASC") { return CBO.FillCollection<asoPeriodoCuota>(DataProvider.Instance().ExecuteReader( "sp_asoPeriodoCuota_0SelByAll" , asoPeriodo_Id, asoPrestamo_Id, Valor_Capital, Valor_Interes, Estado, Descripcion, asoSocio_Nombre, asoPeriodo_Fecha, Valor_Suma, asoSocio_Id, No_Cuotas, No_Cuotas_PEN, No_Cuotas_COB, Desc_Cuotas, PageIndex, PageSize, SortField, SortDirection )); } [DataObjectMethodAttribute(DataObjectMethodType.Select, true)] public asoPeriodoCuota _1SelById(Int32 Id) { return CBO.FillObject<asoPeriodoCuota>(DataProvider.Instance().ExecuteReader( "sp_asoPeriodoCuota_1SelById" , Id )); } [DataObjectMethodAttribute(DataObjectMethodType.Delete, true)] public int _4Del(asoPeriodoCuota o) { try { return DataProvider.Instance().ExecuteScalar<int>( "sp_asoPeriodoCuota_4Del" , o.Id ); } catch (Exception exc) { Exceptions.LogException(exc); string mensaje = string.Format("Error en: asoPeriodoCuota, operacion: sp_asoPeriodoCuota_4Del, registro {0}.", o.Id); throw new Exception(mensaje, exc); } } [DataObjectMethodAttribute(DataObjectMethodType.Insert, true)] public int _2Ins(asoPeriodoCuota o) { try { return DataProvider.Instance().ExecuteScalar<int>( "sp_asoPeriodoCuota_2Ins" , o.asoPeriodo_Id, o.asoPrestamo_Id, o.Valor_Capital, o.Valor_Interes, o.Estado, o.Descripcion ); } catch (Exception exc) { Exceptions.LogException(exc); string mensaje = string.Format("Error en: asoPeriodoCuota, operacion: sp_asoPeriodoCuota_2Ins, registro {0}.", o.Id); throw new Exception(mensaje, exc); } } [DataObjectMethodAttribute(DataObjectMethodType.Update, true)] public int _3Upd(asoPeriodoCuota o) { try { return DataProvider.Instance().ExecuteScalar<int>( "sp_asoPeriodoCuota_3Upd" , o.Id, o.asoPeriodo_Id, o.asoPrestamo_Id, o.Valor_Capital, o.Valor_Interes, o.Estado, o.Descripcion ); } catch (Exception exc) { Exceptions.LogException(exc); string mensaje = string.Format("Error en: asoPeriodoCuota, operacion: sp_asoPeriodoCuota_3Upd, registro {0}.", o.Id); throw new Exception(mensaje, exc); } } } }
vmejiaec/SetimSiAso
SetimADL/asoPeriodoCuotaControl.cs
C#
gpl-2.0
5,075
const St = imports.gi.St; const Lang = imports.lang; const Pango = imports.gi.Pango; const Params = imports.misc.params; const Main = imports.ui.main; const Soup = imports.gi.Soup; const Gio = imports.gi.Gio; const ExtensionUtils = imports.misc.extensionUtils; const Me = ExtensionUtils.getCurrentExtension(); const Utils = Me.imports.utils; const PrefsKeys = Me.imports.prefs_keys; const NotePreviewerContentView = Me.imports.note_previewer_content_view; const GnoteNote = Me.imports.gnote_note; const SCALE_FACTOR = St.ThemeContext.get_for_stage(global.stage).scale_factor; const LinkPreviewerBase = new Lang.Class({ Name: 'LinkPreviewerBase', _init: function(uri, params) { let monitor = Main.layoutManager.primaryMonitor; this.params = Params.parse(params, { max_width: Math.floor(monitor.width / 2), max_height: Math.floor(monitor.height / 2) }); this.uri = uri; this.actor = new St.BoxLayout(); }, load: function(on_loaded) { throw new Error('not implemented'); }, destroy: function() { this.actor.destroy(); } }); const NotePreviewer = new Lang.Class({ Name: 'NotePreviewer', Extends: LinkPreviewerBase, _init: function(uri, params) { this.parent(uri, params); this._content_view = new NotePreviewerContentView.NotePreviewerContentView(); this.actor.add_child(this._content_view.actor); this.actor.connect('notify::mapped', Lang.bind(this, function() { if(!this.actor.mapped) return; if(this.actor.width > this.params.max_width) { this.actor.width = this.params.max_width; } if(this.actor.height > this.params.max_height) { this.actor.height = this.params.max_height; } })) }, load: function(on_loaded) { let note = new GnoteNote.GnoteNote(this.uri); note.connect( 'notify::parsed', Lang.bind(this, function() { this._content_view.set_note(note); this._content_view.show(); on_loaded(true); }) ); note.start_parsing(); }, destroy: function() { this._content_view.destroy(); this.parent(); } }); const ImagePreviewer = new Lang.Class({ Name: 'ImagePreviewView', Extends: LinkPreviewerBase, _init: function(uri, params) { this.parent(uri, params); }, load: function(on_loaded) { let image_file = Gio.file_new_for_uri(this.uri); let texture_cache = St.TextureCache.get_default(); let image = texture_cache.load_file_async( image_file, this.params.max_width, this.params.max_height, SCALE_FACTOR ); image.connect("size-change", Lang.bind(this, function() { on_loaded(true); }) ); this.actor.add_child(image); } }); const WebpagePreviewerView = new Lang.Class({ Name: 'WebpagePreviewerView', _init: function(webpage_data) { if(this._is_empty_data(webpage_data)) { throw new Error('WebpagePreviewerView:_init(): empty webpage_data'); } this._image_max_width = 350; this._image_max_height = 200; this._max_string_length = 50; this.actor = new St.BoxLayout({ vertical: true, style_class: 'dialog-note-view-box dialog-note-view-contents' }); this.actor.connect('destroy', Lang.bind(this, this.destroy)); if(webpage_data.title !== null) { let title = new St.Label({ text: Utils.wordwrap( webpage_data.title, this._max_string_length, '\n' ), style: 'font-weight: bold; font-size: 17px;' }); title.clutter_text.set_single_line_mode(false); title.clutter_text.set_activatable(false); this.actor.add_child(title); } if(webpage_data.images.length > 0) { let image_info = webpage_data.images[0]; let image_dummy = new St.Icon({ icon_name: "camera-photo-symbolic", icon_size: 120 }); this.actor.add_child(image_dummy); let image_file = Gio.file_new_for_uri(image_file.url); let texture_cache = St.TextureCache.get_default(); let image = texture_cache.load_file_async( image_file, this._image_max_width, this._image_max_height, SCALE_FACTOR ); image.connect("size-change", Lang.bind(this, function(o, e) { image_dummy.destroy(); }) ); this.actor.add(image, { x_expand: false, x_fill: false, y_expand: false, y_fill: false }); } if(webpage_data.description !== null) { let description = new St.Label({ text: Utils.wordwrap( webpage_data.description, this._max_string_length, '\n' ) }); description.clutter_text.set_single_line_mode(false); description.clutter_text.set_activatable(false); this.actor.add_child(description); } }, _is_empty_data: function(data) { return data.images.length === 0 && data.title === null && data.description === null; }, destroy: function() { this.actor.destroy(); } }); const WebpagePreviewer = new Lang.Class({ Name: 'WebpagePreviewer', Extends: LinkPreviewerBase, _init: function(uri, params) { this.parent(uri, params); this._http_session = new Soup.SessionAsync(); Soup.Session.prototype.add_feature.call( this._http_session, new Soup.ProxyResolverDefault() ); this._http_session.user_agent = 'GNOME Shell - Gnote/Tomboy Integration'; this._http_session.timeout = 10; }, load: function(on_loaded) { let api_key = Utils.SETTINGS.get_string(PrefsKeys.EMBEDLY_API_KEY_KEY); let api_url = Utils.SETTINGS.get_string(PrefsKeys.EMBEDLY_API_URL_KEY); if(Utils.is_blank(api_key) || Utils.is_blank(api_url)) { on_loaded(false); return; } let url ='%s?key=%s&url=%s'.format(api_url, api_key, this.uri); let request = Soup.Message.new('GET', url); this._http_session.queue_message(request, Lang.bind(this, function(http_session, message) { if(message.status_code !== 200) { log('WebpagePreviewer:load():Response code %s'.format( message.status_code) ); on_loaded(false); return; } try { let result = JSON.parse(request.response_body.data); let view = new WebpagePreviewerView(result); this.actor.add_child(view.actor); on_loaded(true); } catch(e) { log('WebpagePreviewer:load():%s'.format(e)); on_loaded(false); return; } }) ); } }); const MessagePreviewer = new Lang.Class({ Name: 'MessagePreviewer', Extends: LinkPreviewerBase, _init: function(message, params) { this.parent(null, params); this._message = message; }, load: function(on_loaded) { let label = new St.Label({ text: this._message }); this.actor.add_child(label); on_loaded(true); } });
awamper/gnote-integration
link_previewers.js
JavaScript
gpl-2.0
8,027
/* ** FamiTracker - NES/Famicom sound tracker ** Copyright (C) 2005-2014 Jonathan Liss ** ** This program is free software; you can redistribute it and/or modify ** it under the terms of the GNU General Public License as published by ** the Free Software Foundation; either version 2 of the License, or ** (at your option) any later version. ** ** This program is distributed in the hope that it will be useful, ** but WITHOUT ANY WARRANTY; without even the implied warranty of ** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU ** Library General Public License for more details. To obtain a ** copy of the GNU Library General Public License, write to the Free ** Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. ** ** Any permitted reproduction of these routines, in whole or in part, ** must bear this legend. */ #pragma once // // Text chunk renderer // class CChunkRenderText; typedef void (CChunkRenderText::*renderFunc_t)(CChunk *pChunk, CFile *pFile); struct stChunkRenderFunc { chunk_type_t type; renderFunc_t function; }; class CChunkRenderText { public: CChunkRenderText(CFile *pFile); void StoreChunks(const std::vector<CChunk*> &Chunks); // // // private: static const stChunkRenderFunc RENDER_FUNCTIONS[]; private: void DumpStrings(const CStringA &preStr, const CStringA &postStr, CStringArray &stringArray, CFile *pFile) const; void WriteFileString(const CStringA &str, CFile *pFile) const; void StoreByteString(const char *pData, int Len, CStringA &str, int LineBreak) const; void StoreByteString(const CChunk *pChunk, CStringA &str, int LineBreak) const; private: void StoreHeaderChunk(CChunk *pChunk, CFile *pFile); void StoreInstrumentListChunk(CChunk *pChunk, CFile *pFile); void StoreInstrumentChunk(CChunk *pChunk, CFile *pFile); void StoreSequenceChunk(CChunk *pChunk, CFile *pFile); // // // void StoreSongListChunk(CChunk *pChunk, CFile *pFile); void StoreSongChunk(CChunk *pChunk, CFile *pFile); void StoreFrameListChunk(CChunk *pChunk, CFile *pFile); void StoreFrameChunk(CChunk *pChunk, CFile *pFile); void StorePatternChunk(CChunk *pChunk, CFile *pFile); // // // private: CStringArray m_headerStrings; CStringArray m_instrumentListStrings; CStringArray m_instrumentStrings; CStringArray m_sequenceStrings; // // // CStringArray m_songListStrings; CStringArray m_songStrings; CStringArray m_songDataStrings; // // // CFile *m_pFile; };
HertzDevil/SnevenTracker
Source/ChunkRenderText.h
C
gpl-2.0
2,526
<?php /** * The template for displaying search results pages. * * @package Goatpress * @subpackage Twenty_Fifteen * @since Twenty Fifteen 1.0 */ get_header(); ?> <section id="primary" class="content-area"> <main id="main" class="site-main" role="main"> <?php if ( have_posts() ) : ?> <header class="page-header"> <h1 class="page-title"><?php printf( __( 'Search Results for: %s', 'twentyfifteen' ), get_search_query() ); ?></h1> </header><!-- .page-header --> <?php // Start the loop. while ( have_posts() ) : the_post(); ?> <?php /* * Run the loop for the search to output the results. * If you want to overload this in a child theme then include a file * called content-search.php and that will be used instead. */ get_template_part( 'content', 'search' ); // End the loop. endwhile; // Previous/next page navigation. the_posts_pagination( array( 'prev_text' => __( 'Previous page', 'twentyfifteen' ), 'next_text' => __( 'Next page', 'twentyfifteen' ), 'before_page_number' => '<span class="meta-nav screen-reader-text">' . __( 'Page', 'twentyfifteen' ) . ' </span>', ) ); // If no content, include the "No posts found" template. else : get_template_part( 'content', 'none' ); endif; ?> </main><!-- .site-main --> </section><!-- .content-area --> <?php get_footer(); ?>
NikV/GoatpressCMS
gp-content/themes/twentyfifteen/search.php
PHP
gpl-2.0
1,405
var app = require('../../app'); var boards = require('../controllers/boards'); app.get('/api/boards', boards.get);
artursgirons/beyondpad
api/routers/boards.js
JavaScript
gpl-2.0
118
#!/usr/bin/env python try: from io import StringIO except ImportError: try: from cStringIO import StringIO except ImportError: from StringIO import StringIO import bs4 as BeautifulSoup import logging from thug.DOM.W3C.Element import Element from thug.DOM.W3C.Style.CSS.ElementCSSInlineStyle import ElementCSSInlineStyle from .attr_property import attr_property log = logging.getLogger("Thug") class HTMLElement(Element, ElementCSSInlineStyle): id = attr_property("id") title = attr_property("title") lang = attr_property("lang") dir = attr_property("dir") className = attr_property("class", default = "") def __init__(self, doc, tag): Element.__init__(self, doc, tag) ElementCSSInlineStyle.__init__(self, doc, tag) def getInnerHTML(self): if not self.hasChildNodes(): return "" html = StringIO() for tag in self.tag.contents: html.write(unicode(tag)) return html.getvalue() def setInnerHTML(self, html): self.tag.clear() soup = BeautifulSoup.BeautifulSoup(html, "html5lib") for node in list(soup.head.descendants): self.tag.append(node) name = getattr(node, 'name', None) if name is None: continue handler = getattr(log.DFT, 'handle_%s' % (name, ), None) if handler: handler(node) for node in list(soup.body.children): self.tag.append(node) name = getattr(node, 'name', None) if name is None: continue handler = getattr(log.DFT, 'handle_%s' % (name, ), None) if handler: handler(node) # soup.head.unwrap() # soup.body.unwrap() # soup.html.wrap(self.tag) # self.tag.html.unwrap() for node in self.tag.descendants: name = getattr(node, 'name', None) if not name: continue p = getattr(self.doc.window.doc.DFT, 'handle_%s' % (name, ), None) if p is None: p = getattr(log.DFT, 'handle_%s' % (name, ), None) if p: p(node) innerHTML = property(getInnerHTML, setInnerHTML) # WARNING: NOT DEFINED IN W3C SPECS! def focus(self): pass @property def sourceIndex(self): return None
tweemeterjop/thug
thug/DOM/W3C/HTML/HTMLElement.py
Python
gpl-2.0
2,479
//===- DAGISelMatcherEmitter.cpp - Matcher Emitter ------------------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file contains code to generate C++ code a matcher. // //===----------------------------------------------------------------------===// #include "DAGISelMatcher.h" #include "CodeGenDAGPatterns.h" #include "Record.h" #include "llvm/ADT/DenseMap.h" #include "llvm/ADT/SmallString.h" #include "llvm/ADT/StringMap.h" #include "llvm/Support/CommandLine.h" #include "llvm/Support/FormattedStream.h" using namespace llvm; enum { CommentIndent = 30 }; // To reduce generated source code size. static cl::opt<bool> OmitComments("omit-comments", cl::desc("Do not generate comments"), cl::init(false)); namespace { class MatcherTableEmitter { StringMap<unsigned> NodePredicateMap, PatternPredicateMap; std::vector<std::string> NodePredicates, PatternPredicates; DenseMap<const ComplexPattern*, unsigned> ComplexPatternMap; std::vector<const ComplexPattern*> ComplexPatterns; DenseMap<Record*, unsigned> NodeXFormMap; std::vector<Record*> NodeXForms; public: MatcherTableEmitter() {} unsigned EmitMatcherList(const Matcher *N, unsigned Indent, unsigned StartIdx, formatted_raw_ostream &OS); void EmitPredicateFunctions(const CodeGenDAGPatterns &CGP, formatted_raw_ostream &OS); void EmitHistogram(const Matcher *N, formatted_raw_ostream &OS); private: unsigned EmitMatcher(const Matcher *N, unsigned Indent, unsigned CurrentIdx, formatted_raw_ostream &OS); unsigned getNodePredicate(StringRef PredName) { unsigned &Entry = NodePredicateMap[PredName]; if (Entry == 0) { NodePredicates.push_back(PredName.str()); Entry = NodePredicates.size(); } return Entry-1; } unsigned getPatternPredicate(StringRef PredName) { unsigned &Entry = PatternPredicateMap[PredName]; if (Entry == 0) { PatternPredicates.push_back(PredName.str()); Entry = PatternPredicates.size(); } return Entry-1; } unsigned getComplexPat(const ComplexPattern &P) { unsigned &Entry = ComplexPatternMap[&P]; if (Entry == 0) { ComplexPatterns.push_back(&P); Entry = ComplexPatterns.size(); } return Entry-1; } unsigned getNodeXFormID(Record *Rec) { unsigned &Entry = NodeXFormMap[Rec]; if (Entry == 0) { NodeXForms.push_back(Rec); Entry = NodeXForms.size(); } return Entry-1; } }; } // end anonymous namespace. static unsigned GetVBRSize(unsigned Val) { if (Val <= 127) return 1; unsigned NumBytes = 0; while (Val >= 128) { Val >>= 7; ++NumBytes; } return NumBytes+1; } /// EmitVBRValue - Emit the specified value as a VBR, returning the number of /// bytes emitted. static uint64_t EmitVBRValue(uint64_t Val, raw_ostream &OS) { if (Val <= 127) { OS << Val << ", "; return 1; } uint64_t InVal = Val; unsigned NumBytes = 0; while (Val >= 128) { OS << (Val&127) << "|128,"; Val >>= 7; ++NumBytes; } OS << Val; if (!OmitComments) OS << "/*" << InVal << "*/"; OS << ", "; return NumBytes+1; } /// EmitMatcherOpcodes - Emit bytes for the specified matcher and return /// the number of bytes emitted. unsigned MatcherTableEmitter:: EmitMatcher(const Matcher *N, unsigned Indent, unsigned CurrentIdx, formatted_raw_ostream &OS) { OS.PadToColumn(Indent*2); switch (N->getKind()) { case Matcher::Scope: { const ScopeMatcher *SM = cast<ScopeMatcher>(N); assert(SM->getNext() == 0 && "Shouldn't have next after scope"); unsigned StartIdx = CurrentIdx; // Emit all of the children. for (unsigned i = 0, e = SM->getNumChildren(); i != e; ++i) { if (i == 0) { OS << "OPC_Scope, "; ++CurrentIdx; } else { if (!OmitComments) { OS << "/*" << CurrentIdx << "*/"; OS.PadToColumn(Indent*2) << "/*Scope*/ "; } else OS.PadToColumn(Indent*2); } // We need to encode the child and the offset of the failure code before // emitting either of them. Handle this by buffering the output into a // string while we get the size. Unfortunately, the offset of the // children depends on the VBR size of the child, so for large children we // have to iterate a bit. SmallString<128> TmpBuf; unsigned ChildSize = 0; unsigned VBRSize = 0; do { VBRSize = GetVBRSize(ChildSize); TmpBuf.clear(); raw_svector_ostream OS(TmpBuf); formatted_raw_ostream FOS(OS); ChildSize = EmitMatcherList(SM->getChild(i), Indent+1, CurrentIdx+VBRSize, FOS); } while (GetVBRSize(ChildSize) != VBRSize); assert(ChildSize != 0 && "Should not have a zero-sized child!"); CurrentIdx += EmitVBRValue(ChildSize, OS); if (!OmitComments) { OS << "/*->" << CurrentIdx+ChildSize << "*/"; if (i == 0) OS.PadToColumn(CommentIndent) << "// " << SM->getNumChildren() << " children in Scope"; } OS << '\n' << TmpBuf.str(); CurrentIdx += ChildSize; } // Emit a zero as a sentinel indicating end of 'Scope'. if (!OmitComments) OS << "/*" << CurrentIdx << "*/"; OS.PadToColumn(Indent*2) << "0, "; if (!OmitComments) OS << "/*End of Scope*/"; OS << '\n'; return CurrentIdx - StartIdx + 1; } case Matcher::RecordNode: OS << "OPC_RecordNode,"; if (!OmitComments) OS.PadToColumn(CommentIndent) << "// #" << cast<RecordMatcher>(N)->getResultNo() << " = " << cast<RecordMatcher>(N)->getWhatFor(); OS << '\n'; return 1; case Matcher::RecordChild: OS << "OPC_RecordChild" << cast<RecordChildMatcher>(N)->getChildNo() << ','; if (!OmitComments) OS.PadToColumn(CommentIndent) << "// #" << cast<RecordChildMatcher>(N)->getResultNo() << " = " << cast<RecordChildMatcher>(N)->getWhatFor(); OS << '\n'; return 1; case Matcher::RecordMemRef: OS << "OPC_RecordMemRef,\n"; return 1; case Matcher::CaptureFlagInput: OS << "OPC_CaptureFlagInput,\n"; return 1; case Matcher::MoveChild: OS << "OPC_MoveChild, " << cast<MoveChildMatcher>(N)->getChildNo() << ",\n"; return 2; case Matcher::MoveParent: OS << "OPC_MoveParent,\n"; return 1; case Matcher::CheckSame: OS << "OPC_CheckSame, " << cast<CheckSameMatcher>(N)->getMatchNumber() << ",\n"; return 2; case Matcher::CheckPatternPredicate: { StringRef Pred = cast<CheckPatternPredicateMatcher>(N)->getPredicate(); OS << "OPC_CheckPatternPredicate, " << getPatternPredicate(Pred) << ','; if (!OmitComments) OS.PadToColumn(CommentIndent) << "// " << Pred; OS << '\n'; return 2; } case Matcher::CheckPredicate: { StringRef Pred = cast<CheckPredicateMatcher>(N)->getPredicateName(); OS << "OPC_CheckPredicate, " << getNodePredicate(Pred) << ','; if (!OmitComments) OS.PadToColumn(CommentIndent) << "// " << Pred; OS << '\n'; return 2; } case Matcher::CheckOpcode: OS << "OPC_CheckOpcode, TARGET_OPCODE(" << cast<CheckOpcodeMatcher>(N)->getOpcode().getEnumName() << "),\n"; return 3; case Matcher::SwitchOpcode: case Matcher::SwitchType: { unsigned StartIdx = CurrentIdx; unsigned NumCases; if (const SwitchOpcodeMatcher *SOM = dyn_cast<SwitchOpcodeMatcher>(N)) { OS << "OPC_SwitchOpcode "; NumCases = SOM->getNumCases(); } else { OS << "OPC_SwitchType "; NumCases = cast<SwitchTypeMatcher>(N)->getNumCases(); } if (!OmitComments) OS << "/*" << NumCases << " cases */"; OS << ", "; ++CurrentIdx; // For each case we emit the size, then the opcode, then the matcher. for (unsigned i = 0, e = NumCases; i != e; ++i) { const Matcher *Child; unsigned IdxSize; if (const SwitchOpcodeMatcher *SOM = dyn_cast<SwitchOpcodeMatcher>(N)) { Child = SOM->getCaseMatcher(i); IdxSize = 2; // size of opcode in table is 2 bytes. } else { Child = cast<SwitchTypeMatcher>(N)->getCaseMatcher(i); IdxSize = 1; // size of type in table is 1 byte. } // We need to encode the opcode and the offset of the case code before // emitting the case code. Handle this by buffering the output into a // string while we get the size. Unfortunately, the offset of the // children depends on the VBR size of the child, so for large children we // have to iterate a bit. SmallString<128> TmpBuf; unsigned ChildSize = 0; unsigned VBRSize = 0; do { VBRSize = GetVBRSize(ChildSize); TmpBuf.clear(); raw_svector_ostream OS(TmpBuf); formatted_raw_ostream FOS(OS); ChildSize = EmitMatcherList(Child, Indent+1, CurrentIdx+VBRSize+IdxSize, FOS); } while (GetVBRSize(ChildSize) != VBRSize); assert(ChildSize != 0 && "Should not have a zero-sized child!"); if (i != 0) { OS.PadToColumn(Indent*2); if (!OmitComments) OS << (isa<SwitchOpcodeMatcher>(N) ? "/*SwitchOpcode*/ " : "/*SwitchType*/ "); } // Emit the VBR. CurrentIdx += EmitVBRValue(ChildSize, OS); OS << ' '; if (const SwitchOpcodeMatcher *SOM = dyn_cast<SwitchOpcodeMatcher>(N)) OS << "TARGET_OPCODE(" << SOM->getCaseOpcode(i).getEnumName() << "),"; else OS << getEnumName(cast<SwitchTypeMatcher>(N)->getCaseType(i)) << ','; CurrentIdx += IdxSize; if (!OmitComments) OS << "// ->" << CurrentIdx+ChildSize; OS << '\n'; OS << TmpBuf.str(); CurrentIdx += ChildSize; } // Emit the final zero to terminate the switch. OS.PadToColumn(Indent*2) << "0, "; if (!OmitComments) OS << (isa<SwitchOpcodeMatcher>(N) ? "// EndSwitchOpcode" : "// EndSwitchType"); OS << '\n'; ++CurrentIdx; return CurrentIdx-StartIdx; } case Matcher::CheckType: OS << "OPC_CheckType, " << getEnumName(cast<CheckTypeMatcher>(N)->getType()) << ",\n"; return 2; case Matcher::CheckChildType: OS << "OPC_CheckChild" << cast<CheckChildTypeMatcher>(N)->getChildNo() << "Type, " << getEnumName(cast<CheckChildTypeMatcher>(N)->getType()) << ",\n"; return 2; case Matcher::CheckInteger: { OS << "OPC_CheckInteger, "; unsigned Bytes=1+EmitVBRValue(cast<CheckIntegerMatcher>(N)->getValue(), OS); OS << '\n'; return Bytes; } case Matcher::CheckCondCode: OS << "OPC_CheckCondCode, ISD::" << cast<CheckCondCodeMatcher>(N)->getCondCodeName() << ",\n"; return 2; case Matcher::CheckValueType: OS << "OPC_CheckValueType, MVT::" << cast<CheckValueTypeMatcher>(N)->getTypeName() << ",\n"; return 2; case Matcher::CheckComplexPat: { const CheckComplexPatMatcher *CCPM = cast<CheckComplexPatMatcher>(N); const ComplexPattern &Pattern = CCPM->getPattern(); OS << "OPC_CheckComplexPat, /*CP*/" << getComplexPat(Pattern) << ", /*#*/" << CCPM->getMatchNumber() << ','; if (!OmitComments) { OS.PadToColumn(CommentIndent) << "// " << Pattern.getSelectFunc(); OS << ":$" << CCPM->getName(); for (unsigned i = 0, e = Pattern.getNumOperands(); i != e; ++i) OS << " #" << CCPM->getFirstResult()+i; if (Pattern.hasProperty(SDNPHasChain)) OS << " + chain result"; } OS << '\n'; return 3; } case Matcher::CheckAndImm: { OS << "OPC_CheckAndImm, "; unsigned Bytes=1+EmitVBRValue(cast<CheckAndImmMatcher>(N)->getValue(), OS); OS << '\n'; return Bytes; } case Matcher::CheckOrImm: { OS << "OPC_CheckOrImm, "; unsigned Bytes = 1+EmitVBRValue(cast<CheckOrImmMatcher>(N)->getValue(), OS); OS << '\n'; return Bytes; } case Matcher::CheckFoldableChainNode: OS << "OPC_CheckFoldableChainNode,\n"; return 1; case Matcher::EmitInteger: { int64_t Val = cast<EmitIntegerMatcher>(N)->getValue(); OS << "OPC_EmitInteger, " << getEnumName(cast<EmitIntegerMatcher>(N)->getVT()) << ", "; unsigned Bytes = 2+EmitVBRValue(Val, OS); OS << '\n'; return Bytes; } case Matcher::EmitStringInteger: { const std::string &Val = cast<EmitStringIntegerMatcher>(N)->getValue(); // These should always fit into one byte. OS << "OPC_EmitInteger, " << getEnumName(cast<EmitStringIntegerMatcher>(N)->getVT()) << ", " << Val << ",\n"; return 3; } case Matcher::EmitRegister: OS << "OPC_EmitRegister, " << getEnumName(cast<EmitRegisterMatcher>(N)->getVT()) << ", "; if (Record *R = cast<EmitRegisterMatcher>(N)->getReg()) OS << getQualifiedName(R) << ",\n"; else { OS << "0 "; if (!OmitComments) OS << "/*zero_reg*/"; OS << ",\n"; } return 3; case Matcher::EmitConvertToTarget: OS << "OPC_EmitConvertToTarget, " << cast<EmitConvertToTargetMatcher>(N)->getSlot() << ",\n"; return 2; case Matcher::EmitMergeInputChains: { const EmitMergeInputChainsMatcher *MN = cast<EmitMergeInputChainsMatcher>(N); OS << "OPC_EmitMergeInputChains, " << MN->getNumNodes() << ", "; for (unsigned i = 0, e = MN->getNumNodes(); i != e; ++i) OS << MN->getNode(i) << ", "; OS << '\n'; return 2+MN->getNumNodes(); } case Matcher::EmitCopyToReg: OS << "OPC_EmitCopyToReg, " << cast<EmitCopyToRegMatcher>(N)->getSrcSlot() << ", " << getQualifiedName(cast<EmitCopyToRegMatcher>(N)->getDestPhysReg()) << ",\n"; return 3; case Matcher::EmitNodeXForm: { const EmitNodeXFormMatcher *XF = cast<EmitNodeXFormMatcher>(N); OS << "OPC_EmitNodeXForm, " << getNodeXFormID(XF->getNodeXForm()) << ", " << XF->getSlot() << ','; if (!OmitComments) OS.PadToColumn(CommentIndent) << "// "<<XF->getNodeXForm()->getName(); OS <<'\n'; return 3; } case Matcher::EmitNode: case Matcher::MorphNodeTo: { const EmitNodeMatcherCommon *EN = cast<EmitNodeMatcherCommon>(N); OS << (isa<EmitNodeMatcher>(EN) ? "OPC_EmitNode" : "OPC_MorphNodeTo"); OS << ", TARGET_OPCODE(" << EN->getOpcodeName() << "), 0"; if (EN->hasChain()) OS << "|OPFL_Chain"; if (EN->hasInFlag()) OS << "|OPFL_FlagInput"; if (EN->hasOutFlag()) OS << "|OPFL_FlagOutput"; if (EN->hasMemRefs()) OS << "|OPFL_MemRefs"; if (EN->getNumFixedArityOperands() != -1) OS << "|OPFL_Variadic" << EN->getNumFixedArityOperands(); OS << ",\n"; OS.PadToColumn(Indent*2+4) << EN->getNumVTs(); if (!OmitComments) OS << "/*#VTs*/"; OS << ", "; for (unsigned i = 0, e = EN->getNumVTs(); i != e; ++i) OS << getEnumName(EN->getVT(i)) << ", "; OS << EN->getNumOperands(); if (!OmitComments) OS << "/*#Ops*/"; OS << ", "; unsigned NumOperandBytes = 0; for (unsigned i = 0, e = EN->getNumOperands(); i != e; ++i) NumOperandBytes += EmitVBRValue(EN->getOperand(i), OS); if (!OmitComments) { // Print the result #'s for EmitNode. if (const EmitNodeMatcher *E = dyn_cast<EmitNodeMatcher>(EN)) { if (unsigned NumResults = EN->getNumVTs()) { OS.PadToColumn(CommentIndent) << "// Results = "; unsigned First = E->getFirstResultSlot(); for (unsigned i = 0; i != NumResults; ++i) OS << "#" << First+i << " "; } } OS << '\n'; if (const MorphNodeToMatcher *SNT = dyn_cast<MorphNodeToMatcher>(N)) { OS.PadToColumn(Indent*2) << "// Src: " << *SNT->getPattern().getSrcPattern() << '\n'; OS.PadToColumn(Indent*2) << "// Dst: " << *SNT->getPattern().getDstPattern() << '\n'; } } else OS << '\n'; return 6+EN->getNumVTs()+NumOperandBytes; } case Matcher::MarkFlagResults: { const MarkFlagResultsMatcher *CFR = cast<MarkFlagResultsMatcher>(N); OS << "OPC_MarkFlagResults, " << CFR->getNumNodes() << ", "; unsigned NumOperandBytes = 0; for (unsigned i = 0, e = CFR->getNumNodes(); i != e; ++i) NumOperandBytes += EmitVBRValue(CFR->getNode(i), OS); OS << '\n'; return 2+NumOperandBytes; } case Matcher::CompleteMatch: { const CompleteMatchMatcher *CM = cast<CompleteMatchMatcher>(N); OS << "OPC_CompleteMatch, " << CM->getNumResults() << ", "; unsigned NumResultBytes = 0; for (unsigned i = 0, e = CM->getNumResults(); i != e; ++i) NumResultBytes += EmitVBRValue(CM->getResult(i), OS); OS << '\n'; if (!OmitComments) { OS.PadToColumn(Indent*2) << "// Src: " << *CM->getPattern().getSrcPattern() << '\n'; OS.PadToColumn(Indent*2) << "// Dst: " << *CM->getPattern().getDstPattern(); } OS << '\n'; return 2 + NumResultBytes; } } assert(0 && "Unreachable"); return 0; } /// EmitMatcherList - Emit the bytes for the specified matcher subtree. unsigned MatcherTableEmitter:: EmitMatcherList(const Matcher *N, unsigned Indent, unsigned CurrentIdx, formatted_raw_ostream &OS) { unsigned Size = 0; while (N) { if (!OmitComments) OS << "/*" << CurrentIdx << "*/"; unsigned MatcherSize = EmitMatcher(N, Indent, CurrentIdx, OS); Size += MatcherSize; CurrentIdx += MatcherSize; // If there are other nodes in this list, iterate to them, otherwise we're // done. N = N->getNext(); } return Size; } void MatcherTableEmitter::EmitPredicateFunctions(const CodeGenDAGPatterns &CGP, formatted_raw_ostream &OS) { // Emit pattern predicates. if (!PatternPredicates.empty()) { OS << "bool CheckPatternPredicate(unsigned PredNo) const {\n"; OS << " switch (PredNo) {\n"; OS << " default: assert(0 && \"Invalid predicate in table?\");\n"; for (unsigned i = 0, e = PatternPredicates.size(); i != e; ++i) OS << " case " << i << ": return " << PatternPredicates[i] << ";\n"; OS << " }\n"; OS << "}\n\n"; } // Emit Node predicates. // FIXME: Annoyingly, these are stored by name, which we never even emit. Yay? StringMap<TreePattern*> PFsByName; for (CodeGenDAGPatterns::pf_iterator I = CGP.pf_begin(), E = CGP.pf_end(); I != E; ++I) PFsByName[I->first->getName()] = I->second; if (!NodePredicates.empty()) { OS << "bool CheckNodePredicate(SDNode *Node, unsigned PredNo) const {\n"; OS << " switch (PredNo) {\n"; OS << " default: assert(0 && \"Invalid predicate in table?\");\n"; for (unsigned i = 0, e = NodePredicates.size(); i != e; ++i) { // FIXME: Storing this by name is horrible. TreePattern *P =PFsByName[NodePredicates[i].substr(strlen("Predicate_"))]; assert(P && "Unknown name?"); // Emit the predicate code corresponding to this pattern. std::string Code = P->getRecord()->getValueAsCode("Predicate"); assert(!Code.empty() && "No code in this predicate"); OS << " case " << i << ": { // " << NodePredicates[i] << '\n'; std::string ClassName; if (P->getOnlyTree()->isLeaf()) ClassName = "SDNode"; else ClassName = CGP.getSDNodeInfo(P->getOnlyTree()->getOperator()).getSDClassName(); if (ClassName == "SDNode") OS << " SDNode *N = Node;\n"; else OS << " " << ClassName << "*N = cast<" << ClassName << ">(Node);\n"; OS << Code << "\n }\n"; } OS << " }\n"; OS << "}\n\n"; } // Emit CompletePattern matchers. // FIXME: This should be const. if (!ComplexPatterns.empty()) { OS << "bool CheckComplexPattern(SDNode *Root, SDValue N,\n"; OS << " unsigned PatternNo, SmallVectorImpl<SDValue> &Result) {\n"; OS << " switch (PatternNo) {\n"; OS << " default: assert(0 && \"Invalid pattern # in table?\");\n"; for (unsigned i = 0, e = ComplexPatterns.size(); i != e; ++i) { const ComplexPattern &P = *ComplexPatterns[i]; unsigned NumOps = P.getNumOperands(); if (P.hasProperty(SDNPHasChain)) ++NumOps; // Get the chained node too. OS << " case " << i << ":\n"; OS << " Result.resize(Result.size()+" << NumOps << ");\n"; OS << " return " << P.getSelectFunc(); OS << "(Root, N"; for (unsigned i = 0; i != NumOps; ++i) OS << ", Result[Result.size()-" << (NumOps-i) << ']'; OS << ");\n"; } OS << " }\n"; OS << "}\n\n"; } // Emit SDNodeXForm handlers. // FIXME: This should be const. if (!NodeXForms.empty()) { OS << "SDValue RunSDNodeXForm(SDValue V, unsigned XFormNo) {\n"; OS << " switch (XFormNo) {\n"; OS << " default: assert(0 && \"Invalid xform # in table?\");\n"; // FIXME: The node xform could take SDValue's instead of SDNode*'s. for (unsigned i = 0, e = NodeXForms.size(); i != e; ++i) { const CodeGenDAGPatterns::NodeXForm &Entry = CGP.getSDNodeTransform(NodeXForms[i]); Record *SDNode = Entry.first; const std::string &Code = Entry.second; OS << " case " << i << ": { "; if (!OmitComments) OS << "// " << NodeXForms[i]->getName(); OS << '\n'; std::string ClassName = CGP.getSDNodeInfo(SDNode).getSDClassName(); if (ClassName == "SDNode") OS << " SDNode *N = V.getNode();\n"; else OS << " " << ClassName << " *N = cast<" << ClassName << ">(V.getNode());\n"; OS << Code << "\n }\n"; } OS << " }\n"; OS << "}\n\n"; } } static void BuildHistogram(const Matcher *M, std::vector<unsigned> &OpcodeFreq){ for (; M != 0; M = M->getNext()) { // Count this node. if (unsigned(M->getKind()) >= OpcodeFreq.size()) OpcodeFreq.resize(M->getKind()+1); OpcodeFreq[M->getKind()]++; // Handle recursive nodes. if (const ScopeMatcher *SM = dyn_cast<ScopeMatcher>(M)) { for (unsigned i = 0, e = SM->getNumChildren(); i != e; ++i) BuildHistogram(SM->getChild(i), OpcodeFreq); } else if (const SwitchOpcodeMatcher *SOM = dyn_cast<SwitchOpcodeMatcher>(M)) { for (unsigned i = 0, e = SOM->getNumCases(); i != e; ++i) BuildHistogram(SOM->getCaseMatcher(i), OpcodeFreq); } else if (const SwitchTypeMatcher *STM = dyn_cast<SwitchTypeMatcher>(M)) { for (unsigned i = 0, e = STM->getNumCases(); i != e; ++i) BuildHistogram(STM->getCaseMatcher(i), OpcodeFreq); } } } void MatcherTableEmitter::EmitHistogram(const Matcher *M, formatted_raw_ostream &OS) { if (OmitComments) return; std::vector<unsigned> OpcodeFreq; BuildHistogram(M, OpcodeFreq); OS << " // Opcode Histogram:\n"; for (unsigned i = 0, e = OpcodeFreq.size(); i != e; ++i) { OS << " // #"; switch ((Matcher::KindTy)i) { case Matcher::Scope: OS << "OPC_Scope"; break; case Matcher::RecordNode: OS << "OPC_RecordNode"; break; case Matcher::RecordChild: OS << "OPC_RecordChild"; break; case Matcher::RecordMemRef: OS << "OPC_RecordMemRef"; break; case Matcher::CaptureFlagInput: OS << "OPC_CaptureFlagInput"; break; case Matcher::MoveChild: OS << "OPC_MoveChild"; break; case Matcher::MoveParent: OS << "OPC_MoveParent"; break; case Matcher::CheckSame: OS << "OPC_CheckSame"; break; case Matcher::CheckPatternPredicate: OS << "OPC_CheckPatternPredicate"; break; case Matcher::CheckPredicate: OS << "OPC_CheckPredicate"; break; case Matcher::CheckOpcode: OS << "OPC_CheckOpcode"; break; case Matcher::SwitchOpcode: OS << "OPC_SwitchOpcode"; break; case Matcher::CheckType: OS << "OPC_CheckType"; break; case Matcher::SwitchType: OS << "OPC_SwitchType"; break; case Matcher::CheckChildType: OS << "OPC_CheckChildType"; break; case Matcher::CheckInteger: OS << "OPC_CheckInteger"; break; case Matcher::CheckCondCode: OS << "OPC_CheckCondCode"; break; case Matcher::CheckValueType: OS << "OPC_CheckValueType"; break; case Matcher::CheckComplexPat: OS << "OPC_CheckComplexPat"; break; case Matcher::CheckAndImm: OS << "OPC_CheckAndImm"; break; case Matcher::CheckOrImm: OS << "OPC_CheckOrImm"; break; case Matcher::CheckFoldableChainNode: OS << "OPC_CheckFoldableChainNode"; break; case Matcher::EmitInteger: OS << "OPC_EmitInteger"; break; case Matcher::EmitStringInteger: OS << "OPC_EmitStringInteger"; break; case Matcher::EmitRegister: OS << "OPC_EmitRegister"; break; case Matcher::EmitConvertToTarget: OS << "OPC_EmitConvertToTarget"; break; case Matcher::EmitMergeInputChains: OS << "OPC_EmitMergeInputChains"; break; case Matcher::EmitCopyToReg: OS << "OPC_EmitCopyToReg"; break; case Matcher::EmitNode: OS << "OPC_EmitNode"; break; case Matcher::MorphNodeTo: OS << "OPC_MorphNodeTo"; break; case Matcher::EmitNodeXForm: OS << "OPC_EmitNodeXForm"; break; case Matcher::MarkFlagResults: OS << "OPC_MarkFlagResults"; break; case Matcher::CompleteMatch: OS << "OPC_CompleteMatch"; break; } OS.PadToColumn(40) << " = " << OpcodeFreq[i] << '\n'; } OS << '\n'; } void llvm::EmitMatcherTable(const Matcher *TheMatcher, const CodeGenDAGPatterns &CGP, raw_ostream &O) { formatted_raw_ostream OS(O); OS << "// The main instruction selector code.\n"; OS << "SDNode *SelectCode(SDNode *N) {\n"; MatcherTableEmitter MatcherEmitter; OS << " // Opcodes are emitted as 2 bytes, TARGET_OPCODE handles this.\n"; OS << " #define TARGET_OPCODE(X) X & 255, unsigned(X) >> 8\n"; OS << " static const unsigned char MatcherTable[] = {\n"; unsigned TotalSize = MatcherEmitter.EmitMatcherList(TheMatcher, 5, 0, OS); OS << " 0\n }; // Total Array size is " << (TotalSize+1) << " bytes\n\n"; MatcherEmitter.EmitHistogram(TheMatcher, OS); OS << " #undef TARGET_OPCODE\n"; OS << " return SelectCodeCommon(N, MatcherTable,sizeof(MatcherTable));\n}\n"; OS << '\n'; // Next up, emit the function for node and pattern predicates: MatcherEmitter.EmitPredicateFunctions(CGP, OS); }
unofficial-opensource-apple/llvmgcc42
llvmCore/utils/TableGen/DAGISelMatcherEmitter.cpp
C++
gpl-2.0
26,816
![Google Maps](https://maps.gstatic.com/tactile/settings/logo_maps-2x.png) # Google Maps Markers Updated "Visual Refresh" version of the Google Maps Marker Icons. Google's new marker icons look great, but they never bothered to provide us with matching PNG versions of them when we need custom colors and labels. I went ahead and created my own set using ImageMagick and my [ImageMagick.vbs](https://github.com/Concept211/Google-Maps-Markers/blob/master/source/ImageMagick.vbs) VBScript file. You can also link to the [pre-generated](#usage-premade) images I created instead of creating your own. --- ## Table of Contents * [Installation](#installation) * [Usage (Custom)](#usage-custom) * [Usage (Premade)](#usage-premade) * [Examples](#examples) ## <a name="installation"></a>Installation 1. Download and install **ImageMagick** from: http://www.imagemagick.org/script/binary-releases.php#windows 2. Download the **ImageMagick.vbs** file and a base image from the **source** folder: https://github.com/Concept211/Google-Maps-Markers/tree/master/source ## <a name="usage-custom"></a>Usage (Custom) 1. Open the **ImageMagick.vbs** file and edit the settings block to configure the base image file name, font family/style, characters/letters/numbers to generate, directory to save to, etc. 2. Run the VBS file. ## <a name="usage-premade"></a>Usage (Premade) Use the following format when linking to the GitHub-hosted image files: ``` https://raw.githubusercontent.com/Concept211/Google-Maps-Markers/master/images/marker_[color][character].png ``` | Placeholder | Possible Values | | --- | --- | | color | red, black, blue, green, grey, orange, purple, white, yellow | | character | A-Z, 1-100, !, @, $, +, -, =, (%23 = #), (%25 = %), (%26 = &), (blank = &bull;) | ## <a name="examples"></a>Examples | Old | New | | --- | --- | | ![Old Red Dot](http://maps.google.com/mapfiles/marker.png) | ![New Red Dot](https://raw.githubusercontent.com/Concept211/Google-Maps-Markers/master/images/marker_red.png) | | ![Old Green A](http://maps.google.com/mapfiles/marker_greenA.png) | ![New Green A](https://raw.githubusercontent.com/Concept211/Google-Maps-Markers/master/images/marker_greenA.png) | | N/A | ![New Purple 1](https://raw.githubusercontent.com/Concept211/Google-Maps-Markers/master/images/marker_purple1.png) | | N/A | ![New Orange @](https://raw.githubusercontent.com/Concept211/Google-Maps-Markers/master/images/marker_orange@.png) | | N/A | ![New White 99](https://raw.githubusercontent.com/Concept211/Google-Maps-Markers/master/images/marker_white99.png) | | N/A | ![New Blue #](https://raw.githubusercontent.com/Concept211/Google-Maps-Markers/master/images/marker_blue%23.png) | | N/A | ![New Yellow +](https://raw.githubusercontent.com/Concept211/Google-Maps-Markers/master/images/marker_yellow+.png) | | N/A | ![New Black Z](https://raw.githubusercontent.com/Concept211/Google-Maps-Markers/master/images/marker_blackZ.png) |
Concept211/Google-Maps-Markers
README.md
Markdown
gpl-2.0
2,940
/* * fptools.c, some helper functions for getcgi.c and uu(en|de)view * * Distributed under the terms of the GNU General Public License. * Use and be happy. */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #ifdef SYSTEM_WINDLL #include <windows.h> #endif #ifdef SYSTEM_OS2 #include <os2.h> #endif /* * This file provides replacements for some handy functions that aren't * available on all systems, like most of the <string.h> functions. They * should behave exactly as their counterparts. There are also extensions * that aren't portable at all (like strirstr etc.). * The proper behaviour in a configure script is as follows: * AC_CHECK_FUNC(strrchr,AC_DEFINE(strrchr,_FP_strrchr)) * This way, the (probably less efficient) replacements will only be used * where it is not provided by the default libraries. Be aware that this * does not work with replacements that just shadow wrong behaviour (like * _FP_free) or provide extended functionality (_FP_gets). * The above is not used in the uuenview/uudeview configuration script, * since both only use the replacement functions in non-performance-cri- * tical sections (except for _FP_tempnam and _FP_strerror, where some * functionality of the original would be lost). */ #include <stdio.h> #include <ctype.h> #ifdef STDC_HEADERS #include <stdlib.h> #include <string.h> #endif #ifdef HAVE_MALLOC_H #include <malloc.h> #endif #ifdef HAVE_UNISTD_H #include <unistd.h> #endif #ifdef HAVE_MEMORY_H #include <memory.h> #endif #include <fptools.h> #if 0 #ifdef SYSTEM_WINDLL BOOL _export WINAPI DllEntryPoint (HINSTANCE hInstance, DWORD seginfo, LPVOID lpCmdLine) { /* Don't do anything, so just return true */ return TRUE; } #endif #endif char * fptools_id = "$Id: fptools.c,v 1.8 2004/02/24 00:05:32 fp Exp $"; /* * some versions of free can't handle a NULL pointer properly * (ANSI says, free ignores a NULL pointer, but some machines * prefer to SIGSEGV on it) */ void TOOLEXPORT _FP_free (void *ptr) { if (ptr) free (ptr); } /* * This is non-standard, so I'm defining my own */ char * TOOLEXPORT _FP_strdup (char *string) { char *result; if (string == NULL) return NULL; if ((result = (char *) malloc (strlen (string) + 1)) == NULL) return NULL; strcpy (result, string); return result; } /* * limited-length string copy. this function behaves differently from * the original in that the dest string is always terminated with a * NULL character. */ char * TOOLEXPORT _FP_strncpy (char *dest, char *src, int length) { char *odest=dest; if (src == NULL || dest == NULL || length-- <= 0) return dest; while (length-- && *src) *dest++ = *src++; *dest++ = '\0'; return odest; } /* * duplicate a memory area */ void * TOOLEXPORT _FP_memdup (void *ptr, int len) { void *result; if (ptr == NULL) return NULL; if ((result = malloc (len)) == NULL) return NULL; memcpy (result, ptr, len); return result; } /* * case-insensitive compare */ int TOOLEXPORT _FP_stricmp (char *str1, char *str2) { if (str1==NULL || str2==NULL) return -1; while (*str1) { if (tolower(*str1) != tolower(*str2)) break; str1++; str2++; } return (tolower (*str1) - tolower (*str2)); } int TOOLEXPORT _FP_strnicmp (char *str1, char *str2, int count) { if (str1==NULL || str2==NULL) return -1; while (*str1 && count) { if (tolower(*str1) != tolower(*str2)) break; str1++; str2++; count--; } return count ? (tolower (*str1) - tolower (*str2)) : 0; } /* * autoconf says this function might be a compatibility problem */ char * TOOLEXPORT _FP_strstr (char *str1, char *str2) { char *ptr1, *ptr2; if (str1==NULL) return NULL; if (str2==NULL) return str1; while (*(ptr1=str1)) { for (ptr2=str2; *ptr1 && *ptr2 && *ptr1==*ptr2; ptr1++, ptr2++) /* empty loop */ ; if (*ptr2 == '\0') return str1; str1++; } return NULL; } char * TOOLEXPORT _FP_strpbrk (char *str, char *accept) { char *ptr; if (str == NULL) return NULL; if (accept == NULL || *accept == '\0') return str; for (; *str; str++) for (ptr=accept; *ptr; ptr++) if (*str == *ptr) return str; return NULL; } /* * autoconf also complains about this one */ char * TOOLEXPORT _FP_strtok (char *str1, char *str2) { static char *optr; char *ptr; if (str2 == NULL) return NULL; if (str1) { optr = str1; } else { if (*optr == '\0') return NULL; } while (*optr && strchr (str2, *optr)) /* look for beginning of token */ optr++; if (*optr == '\0') /* no token found */ return NULL; ptr = optr; while (*optr && strchr (str2, *optr) == NULL) /* look for end of token */ optr++; if (*optr) { *optr++ = '\0'; } return ptr; } /* * case insensitive strstr. */ char * TOOLEXPORT _FP_stristr (char *str1, char *str2) { char *ptr1, *ptr2; if (str1==NULL) return NULL; if (str2==NULL) return str1; while (*(ptr1=str1)) { for (ptr2=str2; *ptr1 && *ptr2 && tolower(*ptr1)==tolower(*ptr2); ptr1++, ptr2++) /* empty loop */ ; if (*ptr2 == '\0') return str1; str1++; } return NULL; } /* * Nice fake of the real (non-standard) one */ char * TOOLEXPORT _FP_strrstr (char *ptr, char *str) { char *found=NULL, *new, *iter=ptr; if (ptr==NULL || str==NULL) return NULL; if (*str == '\0') return ptr; while ((new = _FP_strstr (iter, str)) != NULL) { found = new; iter = new + 1; } return found; } char * TOOLEXPORT _FP_strirstr (char *ptr, char *str) { char *found=NULL, *iter=ptr, *new; if (ptr==NULL || str==NULL) return NULL; if (*str == '\0') return ptr; while ((new = _FP_stristr (iter, str)) != NULL) { found = new; iter = new + 1; } return found; } /* * convert whole string to case */ char * TOOLEXPORT _FP_stoupper (char *input) { char *iter = input; if (input == NULL) return NULL; while (*iter) { *iter = toupper (*iter); iter++; } return input; } char * TOOLEXPORT _FP_stolower (char *input) { char *iter = input; if (input == NULL) return NULL; while (*iter) { *iter = tolower (*iter); iter++; } return input; } /* * string matching with wildcards */ int TOOLEXPORT _FP_strmatch (char *string, char *pattern) { char *p1 = string, *p2 = pattern; if (pattern==NULL || string==NULL) return 0; while (*p1 && *p2) { if (*p2 == '?') { p1++; p2++; } else if (*p2 == '*') { if (*++p2 == '\0') return 1; while (*p1 && *p1 != *p2) p1++; } else if (*p1 == *p2) { p1++; p2++; } else return 0; } if (*p1 || *p2) return 0; return 1; } char * TOOLEXPORT _FP_strrchr (char *string, int tc) { char *ptr; if (string == NULL || !*string) return NULL; ptr = string + strlen (string) - 1; while (ptr != string && *ptr != tc) ptr--; if (*ptr == tc) return ptr; return NULL; } /* * strip directory information from a filename. Works only on DOS and * Unix systems so far ... */ char * TOOLEXPORT _FP_cutdir (char *filename) { char *ptr; if (filename == NULL) return NULL; if ((ptr = _FP_strrchr (filename, '/')) != NULL) ptr++; else if ((ptr = _FP_strrchr (filename, '\\')) != NULL) ptr++; else ptr = filename; return ptr; } /* * My own fgets function. It handles all kinds of line terminators * properly: LF (Unix), CRLF (DOS) and CR (Mac). In all cases, the * terminator is replaced by a single LF */ char * TOOLEXPORT _FP_fgets (char *buf, int n, FILE *stream) { char *obp = buf; int c; if (feof (stream)) return NULL; while (--n && !feof (stream)) { if ((c = fgetc (stream)) == EOF) { if (ferror (stream)) return NULL; else { if (obp == buf) return NULL; *buf = '\0'; return obp; } } if (c == '\015') { /* CR */ /* * Peek next character. If it's no LF, push it back. * ungetc(EOF, stream) is handled correctly according * to the manual page */ if ((c = fgetc (stream)) != '\012') if (!feof (stream)) ungetc (c, stream); *buf++ = '\012'; *buf = '\0'; return obp; } else if (c == '\012') { /* LF */ *buf++ = '\012'; *buf = '\0'; return obp; } /* * just another standard character */ *buf++ = c; } /* * n-1 characters already transferred */ *buf = '\0'; /* * If a line break is coming up, read it */ if (!feof (stream)) { if ((c = fgetc (stream)) == '\015' && !feof (stream)) { if ((c = fgetc (stream)) != '\012' && !feof (stream)) { ungetc (c, stream); } } else if (c != '\012' && !feof (stream)) { ungetc (c, stream); } } return obp; } /* * A replacement strerror function that just returns the error code */ char * TOOLEXPORT _FP_strerror (int errcode) { static char number[8]; sprintf (number, "%03d", errcode); return number; } /* * tempnam is not ANSI, but tmpnam is. Ignore the prefix here. */ char * TOOLEXPORT _FP_tempnam (char *dir, char *pfx) { return _FP_strdup (tmpnam (NULL)); }
Distrotech/uudeview
uulib/fptools.c
C
gpl-2.0
9,260
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace hitchbot_secure_api.Helpers.Location { public static class GoogleMapsHelper { public static void BuildLocationJS(int HitchBotID) { using (var db = new Dal.DatabaseContext()) { var locations = db.Locations.Where(l => l.HitchBotId == HitchBotID).OrderBy(l => l.TakenTime).ToList(); var slimmedLocations = LocationHelper.SlimLocations(locations); string builder = "var flightPlanCoordinates = [ "; foreach (Models.Location myLocation in slimmedLocations) { builder += "\n new google.maps.LatLng(" + myLocation.Latitude + "," + myLocation.Longitude + "),"; } builder += @" ]; var flightPath = new google.maps.Polyline({ path: flightPlanCoordinates, geodesic: true, strokeColor: '#E57373', //taken from material design by google strokeOpacity: 1.0, strokeWeight: 2 }); function AddPolyFill(map){ flightPath.setMap(map); }"; System.IO.File.WriteAllText(Helpers.PathHelper.GetJsBuildPath() + Helpers.AzureBlobHelper.JS_LOCATION_FILE_NAME + Helpers.AzureBlobHelper.JS_FILE_EXTENSION, builder); } } private static string GenInfoWindow(Models.Location myLocation) { string returnString = @"function AddInfoWindow(map){ var myLatLong = new google.maps.LatLng(" + myLocation.Latitude + "," + myLocation.Longitude + @"); var contentString = '<div id=""content"">'+ '<div id=""siteNotice"">'+ '</div>'+ '<h1 id=""firstHeading"" class=""firstHeading"">Manitoulin Island</h1>'+ '<div id=""bodyContent"">'+ '<p>Canada’s most famous hitchhiking robot spent part of its holiday weekend taking part in a Pow Wow with the Wikwemikong First Nation on Manitoulin Island, picking up an honourary name in the process.'+ '<p>Attribution: National Post, <a href=""http://news.nationalpost.com/2014/08/04/hitchbot-update-canadas-hitchhiking-robot-picks-up-an-honourary-name-on-manitoulin-island/"">'+ 'See the article here.</p>'+ '</div>'+ '</div>'; var infowindow = new google.maps.InfoWindow({ content: contentString }); var marker = new google.maps.Marker({ position: myLatLong, map: map, title: 'hitchBOT on Manitoulin Island' }); google.maps.event.addListener(marker, 'click', function() { infowindow.open(map,marker); }); return infowindow;}"; return returnString; } } }
macGRID-SRN/hitchBOT
server/hitchbot-secure-api/hitchbot-secure-api/Helpers/Location/GoogleMapsHelper.cs
C#
gpl-2.0
3,119
<HTML> <HEAD> <TITLE>vrehash - reorganize users directory</TITLE> <LINK REV="made" HREF="mailto:root@porky.devel.redhat.com"> </HEAD> <BODY> <!-- INDEX BEGIN --> <!-- <UL> <LI><A HREF="#NAME">NAME</A> <LI><A HREF="#SYNOPSIS">SYNOPSIS</A> <LI><A HREF="#DESCRIPTION">DESCRIPTION</A> <LI><A HREF="#RETURN_VALUE">RETURN VALUE</A> <LI><A HREF="#NOTES">NOTES</A> <LI><A HREF="#WARNINGS">WARNINGS</A> <LI><A HREF="#AUTHOR">AUTHOR</A> </UL> --> <!-- INDEX END --> <P> <H1><A NAME="NAME">NAME</A></H1> <P> vrehash - reorganize users directory <P> <HR> <H1><A NAME="SYNOPSIS">SYNOPSIS</A></H1> <P> <STRONG>vrehash</STRONG> <P> <HR> <H1><A NAME="DESCRIPTION">DESCRIPTION</A></H1> <P> This program is designed to be run after the sysadmin has changed the <CODE>user-dir-bits</CODE> or <CODE>user-dir-slices</CODE> configuration variables. It creates a new users directory called <CODE>new.users</CODE>, where <CODE>users</CODE> is the configured name of the user directory. It then traverses the password table, creates a new user directory name for each user, and moves the user's mail directory to the new directory name, creating any necessary directories as it goes. Any alias entries in the password table are copied as-is. <P> <HR> <H1><A NAME="RETURN_VALUE">RETURN VALUE</A></H1> <P> Returns 1 if any part of the process fails; 0 otherwise. <P> <HR> <H1><A NAME="NOTES">NOTES</A></H1> <P> When the process is completed, a the old users directory will have been moved to <CODE>backup.users</CODE>. If no errors occurred, you should be able to safely delete this directory and all its subdirectories. Check this directory first, though, to ensure that no important files remain. <P> <HR> <H1><A NAME="WARNINGS">WARNINGS</A></H1> <P> This program is not particularly careful to clean up after itself if an error occurs. If an error occurs, you will have to check the status of the current directory, the virtual password file, and all the virtual users subdirectories in both <CODE>users</CODE> and <CODE>new.users</CODE>. <P> <HR> <H1><A NAME="AUTHOR">AUTHOR</A></H1> <P> Bruce Guenter &lt;<A HREF="mailto:bruceg@em.ca">bruceg@em.ca</A>&gt; </BODY> </HTML>
hetznerZApackages/vmailmgr
doc/vrehash.html
HTML
gpl-2.0
2,171
/* * Copyright (C) 2011 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ //#define LOG_NDEBUG 0 #define LOG_TAG "JitterTool" #include <utils/Log.h> #include <cassert> #include <math.h> #include <media/stagefright/foundation/ALooper.h> #include "include/jittertool.h" namespace android { JitterTool::JitterTool(uint32_t nTicks) :mInitCheck(NO_INIT), pTicks(NULL), nLastTime(0), nTicksMax(nTicks), nTickCount(0), nHightestJitter(0), bShow(false) { assert(nTicks > 0); pTicks = new uint64_t[nTicks]; if (!pTicks) { return; } mInitCheck = OK; LOGV("%s[%d] out \n", __FUNCTION__, __LINE__); } JitterTool::~JitterTool() { if (pTicks) delete[] pTicks; LOGV("%s[%d] out \n", __FUNCTION__, __LINE__); } status_t JitterTool::initCheck() const { LOGV("%s[%d] mInitCheck %d out \n", __FUNCTION__, __LINE__, mInitCheck); return mInitCheck; } void JitterTool::AddPoint(uint64_t ts) { uint64_t now = ts; if (nLastTime == 0) { nLastTime = now; return; } pTicks[nTickCount] = now - nLastTime; nLastTime = now; nTickCount++; if (nTickCount < nTicksMax) return; AddEntry(); nTickCount = 0; } void JitterTool::AddPoint() { uint64_t now = 0; now = ALooper::GetNowUs(); if (nLastTime == 0) { nLastTime = now; return; } pTicks[nTickCount] = now - nLastTime; nLastTime = now; nTickCount++; if (nTickCount < nTicksMax) return; AddEntry(); nTickCount = 0; } void JitterTool::AddEntry() { double localAvg = 0; double localStdDev = 0; uint32_t i; for (i = 0; i < nTicksMax; i++) localAvg += pTicks[i]; localAvg /= nTicksMax; for (i = 0; i < nTicksMax; i++) localStdDev += (localAvg - pTicks[i]) * (localAvg - pTicks[i]); localStdDev = sqrt(localStdDev / nTicksMax); if (bShow) LOGV("Mean time between frames: %.2f standard deviation: %.2f\n", localAvg, localStdDev); fAvg.push(localAvg); fStdDev.push(localStdDev); if (nHightestJitter < localStdDev) { nHightestJitter = localStdDev; } } void JitterTool::SetShow(bool bShowTrace) { bShow = bShowTrace; } void JitterTool::GetAvgs(double *pStdDev, double *pAvg, double *pHighest) { assert(pStdDev); assert(pAvg); assert(pHighest); uint32_t count = 0; *pStdDev = 0; *pAvg = 0; *pHighest = 0; *pHighest = nHightestJitter; count = fAvg.getItemSize() - 1; for (uint32_t i = 0; i < count; i++) { *pAvg += fAvg.top(); fAvg.pop(); } for (uint32_t i = 0; i < count; i++) { *pStdDev += fStdDev.top(); fStdDev.pop(); } *pAvg = *pAvg / count; *pStdDev = *pStdDev /count; if (!fAvg.isEmpty()) { fAvg.clear(); } if (!fStdDev.isEmpty()) { fStdDev.clear(); } LOGV("%s[%d] stddev %.2f avg %.2f highest %.2f \n", __FUNCTION__, __LINE__, *pStdDev, *pAvg, *pHighest); } } // namespace android
DmitryADP/diff_qc750
frameworks/av/media/libstagefright/jittertool.cpp
C++
gpl-2.0
3,701
<?php // First page for import $form = $this->newObject('form', 'htmlelements'); $radio = $this->newObject('radio', 'htmlelements'); $table = $this->newObject('htmltable', 'htmlelements'); $button = $this->newObject('button', 'htmlelements'); $form->name = 'import_one'; $form->id = 'import_one'; $form->setAction($this->uri(array('action' => 'import_type'))); $form->setDisplayType(2); $this->objH = $this->getObject('htmlheading', 'htmlelements'); $this->objH->type=1; $this->objH->str=$this->objLanguage->languageText('mod_contextadmin_importcontent','contextadmin'); $radio->name = 'itype'; $radio->setBreakSpace('<br>'); $radio->addOption('1',$this->objLanguage->languageText("mod_contextadmin_importdeletecontent",'contextadmin')); $radio->addOption('0',$this->objLanguage->languageText("mod_contextadmin_importintonode",'contextadmin')); $radio->setSelected('1') ; $table->width = "100%"; $table->startRow(); $table->addCell($radio->show()); $table->startRow(); $table->startRow(); $button->setToSubmit(); $button->setValue($this->objLanguage->languageText("mod_context_next",'contextadmin')); $table->addCell('<br>'.$button->show(),'','','center'); $table->endRow(); $form->addToForm($this->objH); $form->addToForm($table); echo $form->show(); ?>
chisimba/modules
kngimport/templates/content/importone_tpl.php
PHP
gpl-2.0
1,431
#undef CONFIG_SENSORS_SIS5595
vickylinuxer/at91sam9263-kernel
include/3g/config/sensors/sis5595.h
C
gpl-2.0
30
<?php /************************************************************** * This file is part of Remository * Copyright (c) 2006 Martin Brampton * Issued as open source under GNU/GPL * For support and other information, visit http://remository.com * To contact Martin Brampton, write to martin@remository.com * * Remository started life as the psx-dude script by psx-dude@psx-dude.net * It was enhanced by Matt Smith up to version 2.10 * Since then development has been primarily by Martin Brampton, * with contributions from other people gratefully accepted */ class remositoryDownloadAgreeHTML extends remositoryCustomUserHTML { public function downloadAgreeHTML( &$file ) { $formurl = remositoryRepository::getInstance()->RemositoryBasicFunctionURL ('finishdown', $file->id); $file->showCMSPathway(); echo $this->pathwayHTML($file->getContainer()); $chk = $this->repository->makeCheck($file->id,'finishdown'); $licence = $file->licenseagree ? $file->license : $this->repository->Default_Licence; $licence = $this->translateDefinitions($licence); ?> <script type='text/javascript'> function enabledl () { document.forms['agreeform'].elements['remositorydlbutton'].disabled=false } </script> <h2><?php echo _DOWN_LICENSE_AGREE; ?></h2> <form id='agreeform' method='post' action='<?php echo $formurl; ?>'> <p> <?php echo $licence; ?> </p> <div id='remositorylicenseagree'> <input name='agreecheck' type='checkbox' onclick='enabledl()' /><strong><?php echo _DOWN_LICENSE_CHECKBOX; ?></strong> <input class="button" id='remositorydlbutton' type="submit" value="<?php echo _DOWNLOAD; ?>" /> <input type="hidden" name="da" value="<?php echo $chk; ?>" /> </div> </form> <script type='text/javascript'> document.forms['agreeform'].elements['remositorydlbutton'].disabled=true </script> <?php } }
atweb-project/in-case-of.com
components/com_remository/v-classes/remositoryDownloadAgreeHTML.php
PHP
gpl-2.0
1,855
/* linux/arch/arm/mach-s3c2440/mach-mini2440.c * * Copyright (c) 2008 Ramax Lo <ramaxlo@gmail.com> * Based on mach-anubis.c by Ben Dooks <ben@simtec.co.uk> * and modifications by SBZ <sbz@spgui.org> and * Weibing <http://weibing.blogbus.com> and * Michel Pollet <buserror@gmail.com> * * For product information, visit http://code.google.com/p/mini2440/ * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 as * published by the Free Software Foundation. */ #include <linux/kernel.h> #include <linux/types.h> #include <linux/interrupt.h> #include <linux/list.h> #include <linux/timer.h> #include <linux/init.h> #include <linux/gpio.h> #include <linux/input.h> #include <linux/io.h> #include <linux/serial_core.h> #include <linux/dm9000.h> #include <linux/i2c/at24.h> #include <linux/platform_device.h> #include <linux/gpio_keys.h> #include <linux/i2c.h> #include <linux/mmc/host.h> #include <asm/mach/arch.h> #include <asm/mach/map.h> #include <mach/hardware.h> #include <mach/fb.h> #include <asm/mach-types.h> #include <plat/regs-serial.h> #include <mach/regs-gpio.h> #include <linux/platform_data/leds-s3c24xx.h> #include <mach/regs-lcd.h> #include <mach/irqs.h> #include <linux/platform_data/mtd-nand-s3c2410.h> #include <linux/platform_data/i2c-s3c2410.h> #include <linux/platform_data/mmc-s3cmci.h> #include <linux/platform_data/usb-s3c2410_udc.h> #include <linux/mtd/mtd.h> #include <linux/mtd/nand.h> #include <linux/mtd/nand_ecc.h> #include <linux/mtd/partitions.h> #include <plat/gpio-cfg.h> #include <plat/clock.h> #include <plat/devs.h> #include <plat/cpu.h> #include <plat/samsung-time.h> #include <sound/s3c24xx_uda134x.h> #include "common.h" #define MACH_MINI2440_DM9K_BASE (S3C2410_CS4 + 0x300) static struct map_desc mini2440_iodesc[] __initdata = { /* nothing to declare, move along */ }; #define UCON S3C2410_UCON_DEFAULT #define ULCON S3C2410_LCON_CS8 | S3C2410_LCON_PNONE | S3C2410_LCON_STOPB #define UFCON S3C2410_UFCON_RXTRIG8 | S3C2410_UFCON_FIFOMODE static struct s3c2410_uartcfg mini2440_uartcfgs[] __initdata = { [0] = { .hwport = 0, .flags = 0, .ucon = UCON, .ulcon = ULCON, .ufcon = UFCON, }, [1] = { .hwport = 1, .flags = 0, .ucon = UCON, .ulcon = ULCON, .ufcon = UFCON, }, [2] = { .hwport = 2, .flags = 0, .ucon = UCON, .ulcon = ULCON, .ufcon = UFCON, }, }; /* USB device UDC support */ static struct s3c2410_udc_mach_info mini2440_udc_cfg __initdata = { .pullup_pin = S3C2410_GPC(5), }; /* LCD timing and setup */ /* * This macro simplifies the table bellow */ #define _LCD_DECLARE(_clock,_xres,margin_left,margin_right,hsync, \ _yres,margin_top,margin_bottom,vsync, refresh) \ .width = _xres, \ .xres = _xres, \ .height = _yres, \ .yres = _yres, \ .left_margin = margin_left, \ .right_margin = margin_right, \ .upper_margin = margin_top, \ .lower_margin = margin_bottom, \ .hsync_len = hsync, \ .vsync_len = vsync, \ .pixclock = ((_clock*100000000000LL) / \ ((refresh) * \ (hsync + margin_left + _xres + margin_right) * \ (vsync + margin_top + _yres + margin_bottom))), \ .bpp = 16,\ .type = (S3C2410_LCDCON1_TFT16BPP |\ S3C2410_LCDCON1_TFT) static struct s3c2410fb_display mini2440_lcd_cfg[] __initdata = { [0] = { /* mini2440 + 3.5" TFT + touchscreen */ _LCD_DECLARE( 7, /* The 3.5 is quite fast */ 240, 21, 38, 6, /* x timing */ 320, 4, 4, 2, /* y timing */ 60), /* refresh rate */ .lcdcon5 = (S3C2410_LCDCON5_FRM565 | S3C2410_LCDCON5_INVVLINE | S3C2410_LCDCON5_INVVFRAME | S3C2410_LCDCON5_INVVDEN | S3C2410_LCDCON5_PWREN), }, [1] = { /* mini2440 + 7" TFT + touchscreen */ _LCD_DECLARE( 10, /* the 7" runs slower */ 800, 40, 40, 48, /* x timing */ 480, 29, 3, 3, /* y timing */ 50), /* refresh rate */ .lcdcon5 = (S3C2410_LCDCON5_FRM565 | S3C2410_LCDCON5_INVVLINE | S3C2410_LCDCON5_INVVFRAME | S3C2410_LCDCON5_PWREN), }, /* The VGA shield can outout at several resolutions. All share * the same timings, however, anything smaller than 1024x768 * will only be displayed in the top left corner of a 1024x768 * XGA output unless you add optional dip switches to the shield. * Therefore timings for other resolutions have been omitted here. */ [2] = { _LCD_DECLARE( 10, 1024, 1, 2, 2, /* y timing */ 768, 200, 16, 16, /* x timing */ 24), /* refresh rate, maximum stable, tested with the FPGA shield */ .lcdcon5 = (S3C2410_LCDCON5_FRM565 | S3C2410_LCDCON5_HWSWP), }, /* mini2440 + 3.5" TFT (LCD-W35i, LQ035Q1DG06 type) + touchscreen*/ [3] = { _LCD_DECLARE( /* clock */ 7, /* xres, margin_right, margin_left, hsync */ 320, 68, 66, 4, /* yres, margin_top, margin_bottom, vsync */ 240, 4, 4, 9, /* refresh rate */ 60), .lcdcon5 = (S3C2410_LCDCON5_FRM565 | S3C2410_LCDCON5_INVVDEN | S3C2410_LCDCON5_INVVFRAME | S3C2410_LCDCON5_INVVLINE | S3C2410_LCDCON5_INVVCLK | S3C2410_LCDCON5_HWSWP), }, }; /* todo - put into gpio header */ #define S3C2410_GPCCON_MASK(x) (3 << ((x) * 2)) #define S3C2410_GPDCON_MASK(x) (3 << ((x) * 2)) static struct s3c2410fb_mach_info mini2440_fb_info __initdata = { .displays = &mini2440_lcd_cfg[0], /* not constant! see init */ .num_displays = 1, .default_display = 0, /* Enable VD[2..7], VD[10..15], VD[18..23] and VCLK, syncs, VDEN * and disable the pull down resistors on pins we are using for LCD * data. */ .gpcup = (0xf << 1) | (0x3f << 10), .gpccon = (S3C2410_GPC1_VCLK | S3C2410_GPC2_VLINE | S3C2410_GPC3_VFRAME | S3C2410_GPC4_VM | S3C2410_GPC10_VD2 | S3C2410_GPC11_VD3 | S3C2410_GPC12_VD4 | S3C2410_GPC13_VD5 | S3C2410_GPC14_VD6 | S3C2410_GPC15_VD7), .gpccon_mask = (S3C2410_GPCCON_MASK(1) | S3C2410_GPCCON_MASK(2) | S3C2410_GPCCON_MASK(3) | S3C2410_GPCCON_MASK(4) | S3C2410_GPCCON_MASK(10) | S3C2410_GPCCON_MASK(11) | S3C2410_GPCCON_MASK(12) | S3C2410_GPCCON_MASK(13) | S3C2410_GPCCON_MASK(14) | S3C2410_GPCCON_MASK(15)), .gpdup = (0x3f << 2) | (0x3f << 10), .gpdcon = (S3C2410_GPD2_VD10 | S3C2410_GPD3_VD11 | S3C2410_GPD4_VD12 | S3C2410_GPD5_VD13 | S3C2410_GPD6_VD14 | S3C2410_GPD7_VD15 | S3C2410_GPD10_VD18 | S3C2410_GPD11_VD19 | S3C2410_GPD12_VD20 | S3C2410_GPD13_VD21 | S3C2410_GPD14_VD22 | S3C2410_GPD15_VD23), .gpdcon_mask = (S3C2410_GPDCON_MASK(2) | S3C2410_GPDCON_MASK(3) | S3C2410_GPDCON_MASK(4) | S3C2410_GPDCON_MASK(5) | S3C2410_GPDCON_MASK(6) | S3C2410_GPDCON_MASK(7) | S3C2410_GPDCON_MASK(10) | S3C2410_GPDCON_MASK(11)| S3C2410_GPDCON_MASK(12) | S3C2410_GPDCON_MASK(13)| S3C2410_GPDCON_MASK(14) | S3C2410_GPDCON_MASK(15)), }; /* MMC/SD */ static struct s3c24xx_mci_pdata mini2440_mmc_cfg __initdata = { .gpio_detect = S3C2410_GPG(8), .gpio_wprotect = S3C2410_GPH(8), .set_power = NULL, .ocr_avail = MMC_VDD_32_33|MMC_VDD_33_34, }; /* NAND Flash on MINI2440 board */ static struct mtd_partition mini2440_default_nand_part[] __initdata = { [0] = { .name = "supervivi", .size = 0x00060000, .offset = 0, }, [1] = { .name = "Kernel", .offset = 0x00060000, .size = 0x00200000, }, [2] = { .name = "root", .offset = 0x00260000, .size = 1024 * 1024 * 1024, //64U * 1024 * 1024 - 0x00260000, }, [3] = { .name = "nand", .offset = 0x00000000, .size = 1024 * 1024 * 1024, //64U * 1024 * 1024 - 0x00260000, } }; static struct s3c2410_nand_set mini2440_nand_sets[] __initdata = { [0] = { .name = "nand", .nr_chips = 1, .nr_partitions = ARRAY_SIZE(mini2440_default_nand_part), .partitions = mini2440_default_nand_part, .flash_bbt = 1, /* we use u-boot to create a BBT */ }, }; static struct s3c2410_platform_nand mini2440_nand_info __initdata = { .tacls = 0, .twrph0 = 25, .twrph1 = 15, .nr_sets = ARRAY_SIZE(mini2440_nand_sets), .sets = mini2440_nand_sets, .ignore_unset_ecc = 1, }; /* DM9000AEP 10/100 ethernet controller */ static struct resource mini2440_dm9k_resource[] = { [0] = DEFINE_RES_MEM(MACH_MINI2440_DM9K_BASE, 4), [1] = DEFINE_RES_MEM(MACH_MINI2440_DM9K_BASE + 4, 4), [2] = DEFINE_RES_NAMED(IRQ_EINT7, 1, NULL, IORESOURCE_IRQ \ | IORESOURCE_IRQ_HIGHEDGE), }; /* * The DM9000 has no eeprom, and it's MAC address is set by * the bootloader before starting the kernel. */ static struct dm9000_plat_data mini2440_dm9k_pdata = { .flags = (DM9000_PLATF_16BITONLY | DM9000_PLATF_NO_EEPROM), }; static struct platform_device mini2440_device_eth = { .name = "dm9000", .id = -1, .num_resources = ARRAY_SIZE(mini2440_dm9k_resource), .resource = mini2440_dm9k_resource, .dev = { .platform_data = &mini2440_dm9k_pdata, }, }; /* CON5 * +--+ /-----\ * | | | | * | | | BAT | * | | \_____/ * | | * | | +----+ +----+ * | | | K5 | | K1 | * | | +----+ +----+ * | | +----+ +----+ * | | | K4 | | K2 | * | | +----+ +----+ * | | +----+ +----+ * | | | K6 | | K3 | * | | +----+ +----+ * ..... */ static struct gpio_keys_button mini2440_buttons[] = { { .gpio = S3C2410_GPG(0), /* K1 */ .code = KEY_F1, .desc = "Button 1", .active_low = 1, }, { .gpio = S3C2410_GPG(3), /* K2 */ .code = KEY_F2, .desc = "Button 2", .active_low = 1, }, { .gpio = S3C2410_GPG(5), /* K3 */ .code = KEY_F3, .desc = "Button 3", .active_low = 1, }, { .gpio = S3C2410_GPG(6), /* K4 */ .code = KEY_POWER, .desc = "Power", .active_low = 1, }, { .gpio = S3C2410_GPG(7), /* K5 */ .code = KEY_F5, .desc = "Button 5", .active_low = 1, }, #if 0 /* this pin is also known as TCLK1 and seems to already * marked as "in use" somehow in the kernel -- possibly wrongly */ { .gpio = S3C2410_GPG(11), /* K6 */ .code = KEY_F6, .desc = "Button 6", .active_low = 1, }, #endif }; static struct gpio_keys_platform_data mini2440_button_data = { .buttons = mini2440_buttons, .nbuttons = ARRAY_SIZE(mini2440_buttons), }; static struct platform_device mini2440_button_device = { .name = "gpio-keys", .id = -1, .dev = { .platform_data = &mini2440_button_data, } }; /* LEDS */ static struct s3c24xx_led_platdata mini2440_led1_pdata = { .name = "led1", .gpio = S3C2410_GPB(5), .flags = S3C24XX_LEDF_ACTLOW | S3C24XX_LEDF_TRISTATE, .def_trigger = "heartbeat", }; static struct s3c24xx_led_platdata mini2440_led2_pdata = { .name = "led2", .gpio = S3C2410_GPB(6), .flags = S3C24XX_LEDF_ACTLOW | S3C24XX_LEDF_TRISTATE, .def_trigger = "nand-disk", }; static struct s3c24xx_led_platdata mini2440_led3_pdata = { .name = "led3", .gpio = S3C2410_GPB(7), .flags = S3C24XX_LEDF_ACTLOW | S3C24XX_LEDF_TRISTATE, .def_trigger = "mmc0", }; static struct s3c24xx_led_platdata mini2440_led4_pdata = { .name = "led4", .gpio = S3C2410_GPB(8), .flags = S3C24XX_LEDF_ACTLOW | S3C24XX_LEDF_TRISTATE, .def_trigger = "", }; static struct s3c24xx_led_platdata mini2440_led_backlight_pdata = { .name = "backlight", .gpio = S3C2410_GPG(4), .def_trigger = "backlight", }; static struct platform_device mini2440_led1 = { .name = "s3c24xx_led", .id = 1, .dev = { .platform_data = &mini2440_led1_pdata, }, }; static struct platform_device mini2440_led2 = { .name = "s3c24xx_led", .id = 2, .dev = { .platform_data = &mini2440_led2_pdata, }, }; static struct platform_device mini2440_led3 = { .name = "s3c24xx_led", .id = 3, .dev = { .platform_data = &mini2440_led3_pdata, }, }; static struct platform_device mini2440_led4 = { .name = "s3c24xx_led", .id = 4, .dev = { .platform_data = &mini2440_led4_pdata, }, }; static struct platform_device mini2440_led_backlight = { .name = "s3c24xx_led", .id = 5, .dev = { .platform_data = &mini2440_led_backlight_pdata, }, }; /* AUDIO */ static struct s3c24xx_uda134x_platform_data mini2440_audio_pins = { .l3_clk = S3C2410_GPB(4), .l3_mode = S3C2410_GPB(2), .l3_data = S3C2410_GPB(3), .model = UDA134X_UDA1341 }; static struct platform_device mini2440_audio = { .name = "s3c24xx_uda134x", .id = 0, .dev = { .platform_data = &mini2440_audio_pins, }, }; /* * I2C devices */ static struct at24_platform_data at24c08 = { .byte_len = SZ_8K / 8, .page_size = 16, }; static struct i2c_board_info mini2440_i2c_devs[] __initdata = { { I2C_BOARD_INFO("24c08", 0x50), .platform_data = &at24c08, }, }; static struct platform_device uda1340_codec = { .name = "uda134x-codec", .id = -1, }; static struct platform_device *mini2440_devices[] __initdata = { &s3c_device_ohci, &s3c_device_wdt, &s3c_device_i2c0, &s3c_device_rtc, &s3c_device_usbgadget, &mini2440_device_eth, &mini2440_led1, &mini2440_led2, &mini2440_led3, &mini2440_led4, &mini2440_button_device, &s3c_device_nand, &s3c_device_sdi, &s3c_device_iis, &uda1340_codec, &mini2440_audio, }; static void __init mini2440_map_io(void) { s3c24xx_init_io(mini2440_iodesc, ARRAY_SIZE(mini2440_iodesc)); s3c24xx_init_clocks(12000000); s3c24xx_init_uarts(mini2440_uartcfgs, ARRAY_SIZE(mini2440_uartcfgs)); samsung_set_timer_source(SAMSUNG_PWM3, SAMSUNG_PWM4); } /* * mini2440_features string * * t = Touchscreen present * b = backlight control * c = camera [TODO] * 0-9 LCD configuration * */ static char mini2440_features_str[12] __initdata = "0tb"; static int __init mini2440_features_setup(char *str) { if (str) strlcpy(mini2440_features_str, str, sizeof(mini2440_features_str)); return 1; } __setup("mini2440=", mini2440_features_setup); #define FEATURE_SCREEN (1 << 0) #define FEATURE_BACKLIGHT (1 << 1) #define FEATURE_TOUCH (1 << 2) #define FEATURE_CAMERA (1 << 3) struct mini2440_features_t { int count; int done; int lcd_index; struct platform_device *optional[8]; }; static void __init mini2440_parse_features( struct mini2440_features_t * features, const char * features_str ) { const char * fp = features_str; features->count = 0; features->done = 0; features->lcd_index = -1; while (*fp) { char f = *fp++; switch (f) { case '0'...'9': /* tft screen */ if (features->done & FEATURE_SCREEN) { printk(KERN_INFO "MINI2440: '%c' ignored, " "screen type already set\n", f); } else { int li = f - '0'; if (li >= ARRAY_SIZE(mini2440_lcd_cfg)) printk(KERN_INFO "MINI2440: " "'%c' out of range LCD mode\n", f); else { features->optional[features->count++] = &s3c_device_lcd; features->lcd_index = li; } } features->done |= FEATURE_SCREEN; break; case 'b': if (features->done & FEATURE_BACKLIGHT) printk(KERN_INFO "MINI2440: '%c' ignored, " "backlight already set\n", f); else { features->optional[features->count++] = &mini2440_led_backlight; } features->done |= FEATURE_BACKLIGHT; break; case 't': printk(KERN_INFO "MINI2440: '%c' ignored, " "touchscreen not compiled in\n", f); break; case 'c': if (features->done & FEATURE_CAMERA) printk(KERN_INFO "MINI2440: '%c' ignored, " "camera already registered\n", f); else features->optional[features->count++] = &s3c_device_camif; features->done |= FEATURE_CAMERA; break; } } } static void __init mini2440_init(void) { struct mini2440_features_t features = { 0 }; int i; printk(KERN_INFO "MINI2440: Option string mini2440=%s\n", mini2440_features_str); /* Parse the feature string */ mini2440_parse_features(&features, mini2440_features_str); /* turn LCD on */ s3c_gpio_cfgpin(S3C2410_GPC(0), S3C2410_GPC0_LEND); /* Turn the backlight early on */ WARN_ON(gpio_request_one(S3C2410_GPG(4), GPIOF_OUT_INIT_HIGH, NULL)); gpio_free(S3C2410_GPG(4)); /* remove pullup on optional PWM backlight -- unused on 3.5 and 7"s */ gpio_request_one(S3C2410_GPB(1), GPIOF_IN, NULL); s3c_gpio_setpull(S3C2410_GPB(1), S3C_GPIO_PULL_UP); gpio_free(S3C2410_GPB(1)); /* mark the key as input, without pullups (there is one on the board) */ for (i = 0; i < ARRAY_SIZE(mini2440_buttons); i++) { s3c_gpio_setpull(mini2440_buttons[i].gpio, S3C_GPIO_PULL_UP); s3c_gpio_cfgpin(mini2440_buttons[i].gpio, S3C2410_GPIO_INPUT); } if (features.lcd_index != -1) { int li; mini2440_fb_info.displays = &mini2440_lcd_cfg[features.lcd_index]; printk(KERN_INFO "MINI2440: LCD"); for (li = 0; li < ARRAY_SIZE(mini2440_lcd_cfg); li++) if (li == features.lcd_index) printk(" [%d:%dx%d]", li, mini2440_lcd_cfg[li].width, mini2440_lcd_cfg[li].height); else printk(" %d:%dx%d", li, mini2440_lcd_cfg[li].width, mini2440_lcd_cfg[li].height); printk("\n"); s3c24xx_fb_set_platdata(&mini2440_fb_info); } s3c24xx_udc_set_platdata(&mini2440_udc_cfg); s3c24xx_mci_set_platdata(&mini2440_mmc_cfg); s3c_nand_set_platdata(&mini2440_nand_info); s3c_i2c0_set_platdata(NULL); i2c_register_board_info(0, mini2440_i2c_devs, ARRAY_SIZE(mini2440_i2c_devs)); platform_add_devices(mini2440_devices, ARRAY_SIZE(mini2440_devices)); if (features.count) /* the optional features */ platform_add_devices(features.optional, features.count); } MACHINE_START(MINI2440, "MINI2440") /* Maintainer: Michel Pollet <buserror@gmail.com> */ .atag_offset = 0x100, .map_io = mini2440_map_io, .init_machine = mini2440_init, .init_irq = s3c2440_init_irq, .init_time = samsung_timer_init, .restart = s3c244x_restart, MACHINE_END
zhaoxianpeng/s3c2440
linux-3.10.71/arch/arm/mach-s3c24xx/mach-mini2440.c
C
gpl-2.0
17,725
/* * Copyright (C) 2005-2008 MaNGOS <http://www.mangosproject.org/> * * Copyright (C) 2008 Trinity <http://www.trinitycore.org/> * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ #ifndef TRANSPORTS_H #define TRANSPORTS_H #include "GameObject.h" #include <map> #include <set> #include <string> class TransportPath { public: struct PathNode { uint32 mapid; float x,y,z; uint32 actionFlag; uint32 delay; }; void SetLength(const unsigned int sz) { i_nodes.resize(sz); } unsigned int Size(void) const { return i_nodes.size(); } bool Empty(void) const { return i_nodes.empty(); } void Resize(unsigned int sz) { i_nodes.resize(sz); } void Clear(void) { i_nodes.clear(); } PathNode* GetNodes(void) { return static_cast<PathNode *>(&i_nodes[0]); } PathNode& operator[](const unsigned int idx) { return i_nodes[idx]; } const PathNode& operator()(const unsigned int idx) const { return i_nodes[idx]; } protected: std::vector<PathNode> i_nodes; }; class Transport : private GameObject { public: explicit Transport(); // prevent using Transports as normal GO, but allow call some inherited functions using GameObject::IsTransport; using GameObject::GetEntry; using GameObject::GetGUID; using GameObject::GetGUIDLow; using GameObject::GetMapId; using GameObject::GetPositionX; using GameObject::GetPositionY; using GameObject::GetPositionZ; using GameObject::BuildCreateUpdateBlockForPlayer; using GameObject::BuildOutOfRangeUpdateBlock; bool Create(uint32 guidlow, uint32 mapid, float x, float y, float z, float ang, uint32 animprogress, uint32 dynflags); bool GenerateWaypoints(uint32 pathid, std::set<uint32> &mapids); void Update(uint32 p_time); bool AddPassenger(Player* passenger); bool RemovePassenger(Player* passenger); void CheckForEvent(uint32 entry, uint32 wp_id); typedef std::set<Player*> PlayerSet; PlayerSet const& GetPassengers() const { return m_passengers; } std::string m_name; private: struct WayPoint { WayPoint() : mapid(0), x(0), y(0), z(0), teleport(false), id(0) {} WayPoint(uint32 _mapid, float _x, float _y, float _z, bool _teleport, uint32 _id) : mapid(_mapid), x(_x), y(_y), z(_z), teleport(_teleport), id(_id) {} uint32 mapid; float x; float y; float z; bool teleport; uint32 id; }; typedef std::map<uint32, WayPoint> WayPointMap; WayPointMap::iterator m_curr; WayPointMap::iterator m_next; uint32 m_pathTime; uint32 m_timer; PlayerSet m_passengers; public: WayPointMap m_WayPoints; uint32 m_nextNodeTime; uint32 m_period; private: void TeleportTransport(uint32 newMapid, float x, float y, float z); WayPointMap::iterator GetNextWayPoint(); }; #endif
skyne/NeoCore
src/game/Transports.h
C
gpl-2.0
3,841
/** * Copyright (C) 2002-2015 The FreeCol Team * * This file is part of FreeCol. * * FreeCol is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 2 of the License, or * (at your option) any later version. * * FreeCol 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 FreeCol. If not, see <http://www.gnu.org/licenses/>. */ package net.sf.freecol.server.model; import java.util.List; import java.util.logging.Logger; import net.sf.freecol.common.model.Goods; import net.sf.freecol.common.model.Unit; import net.sf.freecol.server.control.ChangeSet; /** * A type of session to handle looting of cargo. */ public class LootSession extends TransactionSession { private static final Logger logger = Logger.getLogger(LootSession.class.getName()); /** The goods that are available to be captured. */ private final List<Goods> capture; public LootSession(Unit winner, Unit loser, List<Goods> capture) { super(makeSessionKey(LootSession.class, winner, loser)); this.capture = capture; } @Override public void complete(ChangeSet cs) { super.complete(cs); } public List<Goods> getCapture() { return capture; } }
edijman/SOEN_6431_Colonization_Game
src/net/sf/freecol/server/model/LootSession.java
Java
gpl-2.0
1,599
/* * module.h Interface to the RADIUS module system. * * Version: $Id$ * */ #ifndef RADIUS_MODULES_H #define RADIUS_MODULES_H #include <freeradius-devel/ident.h> RCSIDH(modules_h, "$Id$") #include <freeradius-devel/conffile.h> #ifdef __cplusplus extern "C" { #endif typedef int (*packetmethod)(void *instance, REQUEST *request); typedef enum rlm_components { RLM_COMPONENT_AUTH = 0, RLM_COMPONENT_AUTZ, /* 1 */ RLM_COMPONENT_PREACCT, /* 2 */ RLM_COMPONENT_ACCT, /* 3 */ RLM_COMPONENT_SESS, /* 4 */ RLM_COMPONENT_PRE_PROXY, /* 5 */ RLM_COMPONENT_POST_PROXY, /* 6 */ RLM_COMPONENT_POST_AUTH, /* 7 */ #ifdef WITH_COA RLM_COMPONENT_RECV_COA, /* 8 */ RLM_COMPONENT_SEND_COA, /* 9 */ #endif RLM_COMPONENT_COUNT /* 8 / 10: How many components are there */ } rlm_components_t; typedef struct section_type_value_t { const char *section; const char *typename; int attr; } section_type_value_t; extern const section_type_value_t section_type_value[]; #define RLM_TYPE_THREAD_SAFE (0 << 0) #define RLM_TYPE_THREAD_UNSAFE (1 << 0) #define RLM_TYPE_CHECK_CONFIG_SAFE (1 << 1) #define RLM_TYPE_HUP_SAFE (1 << 2) #define RLM_MODULE_MAGIC_NUMBER ((uint32_t) (0xf4ee4ad3)) #define RLM_MODULE_INIT RLM_MODULE_MAGIC_NUMBER typedef struct module_t { uint32_t magic; /* may later be opaque struct */ const char *name; int type; int (*instantiate)(CONF_SECTION *mod_cs, void **instance); int (*detach)(void *instance); packetmethod methods[RLM_COMPONENT_COUNT]; } module_t; typedef enum rlm_rcodes { RLM_MODULE_REJECT, /* immediately reject the request */ RLM_MODULE_FAIL, /* module failed, don't reply */ RLM_MODULE_OK, /* the module is OK, continue */ RLM_MODULE_HANDLED, /* the module handled the request, so stop. */ RLM_MODULE_INVALID, /* the module considers the request invalid. */ RLM_MODULE_USERLOCK, /* reject the request (user is locked out) */ RLM_MODULE_NOTFOUND, /* user not found */ RLM_MODULE_NOOP, /* module succeeded without doing anything */ RLM_MODULE_UPDATED, /* OK (pairs modified) */ RLM_MODULE_NUMCODES /* How many return codes there are */ } rlm_rcodes_t; int setup_modules(int, CONF_SECTION *); int detach_modules(void); int module_hup(CONF_SECTION *modules); int module_authorize(int type, REQUEST *request); int module_authenticate(int type, REQUEST *request); int module_preacct(REQUEST *request); int module_accounting(int type, REQUEST *request); int module_checksimul(int type, REQUEST *request, int maxsimul); int module_pre_proxy(int type, REQUEST *request); int module_post_proxy(int type, REQUEST *request); int module_post_auth(int type, REQUEST *request); #ifdef WITH_COA int module_recv_coa(int type, REQUEST *request); int module_send_coa(int type, REQUEST *request); #define MODULE_NULL_COA_FUNCS ,NULL,NULL #else #define MODULE_NULL_COA_FUNCS #endif int indexed_modcall(int comp, int idx, REQUEST *request); /* * For now, these are strongly tied together. */ int virtual_servers_load(CONF_SECTION *config); void virtual_servers_free(time_t when); #ifdef __cplusplus } #endif #endif /* RADIUS_MODULES_H */
gentoo/freeradius-server
src/include/modules.h
C
gpl-2.0
3,143
<?php switch($cpo_role) { case "administrator": $user_role_permission = "manage_options"; break; case "editor": $user_role_permission = "publish_pages"; break; case "author": $user_role_permission = "publish_posts"; break; } if (!current_user_can($user_role_permission)) { return; } else { ?> <div class="custom-message green" style="display: block;margin-top:30px;max-width:963px;"> <div style="padding: 4px 0;"> <p style="font:12px/1.0em Arial !important;font-weight:bold;">If you have any Feature Request which you would like to have in your plugin, please fill in the below form. We assure you that soon this will be taken care off!</p> </div> </div> <form id="frm_feedback" class="layout-form" style = "max-width:1000px;"> <div class="fluid-layout"> <div class="layout-span12"> <div class="widget-layout"> <div class="widget-layout-title"> <h4> <?php _e("Feature Requests", cleanup_optimizer); ?> </h4> </div> <div class="widget-layout-body"> <a class="btn btn-inverse" href="admin.php?page=cpo_dashboard"><?php _e("Back to Dashboard", cleanup_optimizer); ?></a> <div class="separator-doubled" style="margin-top:20px;"></div> <div class="fluid-layout"> <div class="layout-span12 responsive"> <div class="widget-layout"> <div class="widget-layout-title"> <h4><?php _e("Feature Requests / Suggestions", cleanup_optimizer); ?></h4> </div> <div class="widget-layout-body"> <div class="layout-control-group"> <label class="layout-control-label"><?php _e("Name", cleanup_optimizer); ?> : <span class="error">*</span></label> <div class="layout-controls"> <input type="text" class="layout-span12" name="ux_name" id="ux_name" placeholder="<?php _e("Enter your Name", cleanup_optimizer); ?>"/> </div> </div> <div class="layout-control-group"> <label class="layout-control-label"><?php _e("Email Id", cleanup_optimizer); ?> : <span class="error">*</span></label> <div class="layout-controls"> <input type="text" class="layout-span12" name="ux_email" id="ux_email" placeholder="<?php _e("Enter your Email Address", cleanup_optimizer); ?>"/> </div> </div> <div class="layout-control-group"> <label class="layout-control-label"><?php _e("Feature Requests / Suggestions", cleanup_optimizer); ?> : <span class="error">*</span></label> <div class="layout-controls"> <textarea rows="5" class="layout-span12" name="ux_suggestion" id="ux_suggestion" placeholder="<?php _e("Enter your Feature Requests / Suggestions", cleanup_optimizer); ?>"></textarea> </div> </div> <div class="layout-control-group"> <div class="layout-controls"> <button type="submit" class="btn btn-danger"><?php _e("Send", cleanup_optimizer); ?></button> </div> </div> </div> </div> </div> </div> </div> </div> </div> </div> </form> <script type="text/javascript"> var url = "<?php echo get_option("tech-banker-updation-check-url");?>"; var suggestion_array = []; jQuery("#frm_feedback").validate ({ rules: { ux_name : { required: true }, ux_email: { required: true, email: true }, ux_suggestion: { required: true } }, submitHandler: function() { var overlay_opacity = jQuery("<div class=\"opacity_overlay\"></div>"); jQuery("body").append(overlay_opacity); var overlay = jQuery("<div class=\"loader_opacity\"><div class=\"processing_overlay\"></div></div>"); jQuery("body").append(overlay); suggestion_array.push(jQuery("#ux_name").val()); suggestion_array.push(jQuery("#ux_email").val()); suggestion_array.push(jQuery("#ux_suggestion").val()); jQuery.post(url, { data : JSON.stringify(suggestion_array), param: "cleanup_feedbacks", action: "feedbacks" }, function (data) { setTimeout(function () { jQuery(".loader_opacity").remove(); jQuery(".opacity_overlay").remove(); window.location.href = "admin.php?page=cpo_feedback"; }, 2000); }); } }); </script> <?php } ?>
SayenkoDesign/selectahead
wp-content/plugins/wp-clean-up-optimizer/views/cleanup-feedback.php
PHP
gpl-2.0
4,344
import sys import pygame from pygame.locals import * pygame.init() screen = pygame.display.set_mode((600, 500)) pygame.display.set_caption("Drawing Lines") screen.fill((0, 80, 0)) # draw the line color = 100, 255, 200 width = 8 pygame.draw.line(screen, color, (100, 100), (500, 400), width) pygame.display.update() while True: for event in pygame.event.get(): if event.type in (QUIT, KEYDOWN): sys.exit()
PoisonBOx/PyGames
2.Pie/drawLine.py
Python
gpl-2.0
453
#pragma once #include "CCreatureHandler.h" #include "VCMI_Lib.h" #include "HeroBonus.h" #include "CCreatureSet.h" #include "ConstTransitivePtr.h" #include "IGameCallback.h" #include "ResourceSet.h" #include "int3.h" #include "CRandomGenerator.h" #include "CGameStateFwd.h" #include "CPathfinder.h" /* * CGameState.h, part of VCMI engine * * Authors: listed in file AUTHORS in main folder * * License: GNU General Public License v2.0 or later * Full text of license available in license.txt file, in main folder * */ class CTown; class CCallback; class IGameCallback; class CCreatureSet; class CStack; class CQuest; class CGHeroInstance; class CGTownInstance; class CArmedInstance; class CGDwelling; class CObjectScript; class CGObjectInstance; class CCreature; class CMap; struct StartInfo; struct SDL_Surface; class CMapHandler; struct SetObjectProperty; struct MetaString; struct CPack; class CSpell; struct TerrainTile; class CHeroClass; class CCampaign; class CCampaignState; class IModableArt; class CGGarrison; class CGameInfo; struct QuestInfo; class CQuest; class CCampaignScenario; struct EventCondition; class CScenarioTravel; namespace boost { class shared_mutex; } struct DLL_LINKAGE SThievesGuildInfo { std::vector<PlayerColor> playerColors; //colors of players that are in-game std::vector< std::vector< PlayerColor > > numOfTowns, numOfHeroes, gold, woodOre, mercSulfCrystGems, obelisks, artifacts, army, income; // [place] -> [colours of players] std::map<PlayerColor, InfoAboutHero> colorToBestHero; //maps player's color to his best heros' std::map<PlayerColor, EAiTactic::EAiTactic> personality; // color to personality // ai tactic std::map<PlayerColor, si32> bestCreature; // color to ID // id or -1 if not known // template <typename Handler> void serialize(Handler &h, const int version) // { // h & playerColors & numOfTowns & numOfHeroes & gold & woodOre & mercSulfCrystGems & obelisks & artifacts & army & income; // h & colorToBestHero & personality & bestCreature; // } }; struct DLL_LINKAGE RumorState { enum ERumorType : ui8 { TYPE_NONE = 0, TYPE_RAND, TYPE_SPECIAL, TYPE_MAP }; enum ERumorTypeSpecial : ui8 { RUMOR_OBELISKS = 208, RUMOR_ARTIFACTS = 209, RUMOR_ARMY = 210, RUMOR_INCOME = 211, RUMOR_GRAIL = 212 }; ERumorType type; std::map<ERumorType, std::pair<int, int>> last; RumorState(){type = TYPE_NONE;}; bool update(int id, int extra); template <typename Handler> void serialize(Handler &h, const int version) { h & type & last; } }; struct UpgradeInfo { CreatureID oldID; //creature to be upgraded std::vector<CreatureID> newID; //possible upgrades std::vector<TResources> cost; // cost[upgrade_serial] -> set of pairs<resource_ID,resource_amount>; cost is for single unit (not entire stack) UpgradeInfo(){oldID = CreatureID::NONE;}; }; struct DLL_EXPORT DuelParameters { ETerrainType terType; BFieldType bfieldType; struct DLL_EXPORT SideSettings { struct DLL_EXPORT StackSettings { CreatureID type; si32 count; template <typename Handler> void serialize(Handler &h, const int version) { h & type & count; } StackSettings(); StackSettings(CreatureID Type, si32 Count); } stacks[GameConstants::ARMY_SIZE]; si32 heroId; //-1 if none std::vector<si32> heroPrimSkills; //may be empty std::map<si32, CArtifactInstance*> artifacts; std::vector<std::pair<si32, si8> > heroSecSkills; //may be empty; pairs <id, level>, level [0-3] std::set<SpellID> spells; SideSettings(); template <typename Handler> void serialize(Handler &h, const int version) { h & stacks & heroId & heroPrimSkills & artifacts & heroSecSkills & spells; } } sides[2]; std::vector<std::shared_ptr<CObstacleInstance> > obstacles; static DuelParameters fromJSON(const std::string &fname); struct CusomCreature { int id; int attack, defense, dmg, HP, speed, shoots; CusomCreature() { id = attack = defense = dmg = HP = speed = shoots = -1; } template <typename Handler> void serialize(Handler &h, const int version) { h & id & attack & defense & dmg & HP & speed & shoots; } }; std::vector<CusomCreature> creatures; DuelParameters(); template <typename Handler> void serialize(Handler &h, const int version) { h & terType & bfieldType & sides & obstacles & creatures; } }; struct BattleInfo; DLL_LINKAGE std::ostream & operator<<(std::ostream & os, const EVictoryLossCheckResult & victoryLossCheckResult); class DLL_LINKAGE CGameState : public CNonConstInfoCallback { public: struct DLL_LINKAGE HeroesPool { std::map<ui32, ConstTransitivePtr<CGHeroInstance> > heroesPool; //[subID] - heroes available to buy; nullptr if not available std::map<ui32,ui8> pavailable; // [subid] -> which players can recruit hero (binary flags) CGHeroInstance * pickHeroFor(bool native, PlayerColor player, const CTown *town, std::map<ui32, ConstTransitivePtr<CGHeroInstance> > &available, CRandomGenerator & rand, const CHeroClass *bannedClass = nullptr) const; template <typename Handler> void serialize(Handler &h, const int version) { h & heroesPool & pavailable; } } hpool; //we have here all heroes available on this map that are not hired CGameState(); virtual ~CGameState(); void init(StartInfo * si); ConstTransitivePtr<StartInfo> scenarioOps, initialOpts; //second one is a copy of settings received from pregame (not randomized) PlayerColor currentPlayer; //ID of player currently having turn ConstTransitivePtr<BattleInfo> curB; //current battle ui32 day; //total number of days in game ConstTransitivePtr<CMap> map; std::map<PlayerColor, PlayerState> players; std::map<TeamID, TeamState> teams; CBonusSystemNode globalEffects; RumorState rumor; boost::shared_mutex *mx; void giveHeroArtifact(CGHeroInstance *h, ArtifactID aid); void apply(CPack *pack); BFieldType battleGetBattlefieldType(int3 tile); UpgradeInfo getUpgradeInfo(const CStackInstance &stack); PlayerRelations::PlayerRelations getPlayerRelations(PlayerColor color1, PlayerColor color2); bool checkForVisitableDir(const int3 & src, const int3 & dst) const; //check if src tile is visitable from dst tile void calculatePaths(const CGHeroInstance *hero, CPathsInfo &out); //calculates possible paths for hero, by default uses current hero position and movement left; returns pointer to newly allocated CPath or nullptr if path does not exists int3 guardingCreaturePosition (int3 pos) const; std::vector<CGObjectInstance*> guardingCreatures (int3 pos) const; void updateRumor(); // ----- victory, loss condition checks ----- EVictoryLossCheckResult checkForVictoryAndLoss(PlayerColor player) const; bool checkForVictory(PlayerColor player, const EventCondition & condition) const; //checks if given player is winner PlayerColor checkForStandardWin() const; //returns color of player that accomplished standard victory conditions or 255 (NEUTRAL) if no winner bool checkForStandardLoss(PlayerColor player) const; //checks if given player lost the game void obtainPlayersStats(SThievesGuildInfo & tgi, int level); //fills tgi with info about other players that is available at given level of thieves' guild std::map<ui32, ConstTransitivePtr<CGHeroInstance> > unusedHeroesFromPool(); //heroes pool without heroes that are available in taverns BattleInfo * setupBattle(int3 tile, const CArmedInstance *armies[2], const CGHeroInstance * heroes[2], bool creatureBank, const CGTownInstance *town); bool isVisible(int3 pos, PlayerColor player); bool isVisible(const CGObjectInstance *obj, boost::optional<PlayerColor> player); int getDate(Date::EDateType mode=Date::DAY) const; //mode=0 - total days in game, mode=1 - day of week, mode=2 - current week, mode=3 - current month // ----- getters, setters ----- CRandomGenerator & getRandomGenerator(); template <typename Handler> void serialize(Handler &h, const int version) { h & scenarioOps & initialOpts & currentPlayer & day & map & players & teams & hpool & globalEffects & rand; if(version >= 755) //save format backward compatibility { h & rumor; } else if(!h.saving) rumor = RumorState(); BONUS_TREE_DESERIALIZATION_FIX } private: struct CrossoverHeroesList { std::vector<CGHeroInstance *> heroesFromPreviousScenario, heroesFromAnyPreviousScenarios; void addHeroToBothLists(CGHeroInstance * hero); void removeHeroFromBothLists(CGHeroInstance * hero); }; struct CampaignHeroReplacement { CampaignHeroReplacement(CGHeroInstance * hero, ObjectInstanceID heroPlaceholderId); CGHeroInstance * hero; ObjectInstanceID heroPlaceholderId; }; // ----- initialization ----- void initNewGame(); void initCampaign(); void initDuel(); void checkMapChecksum(); void initGrailPosition(); void initRandomFactionsForPlayers(); void randomizeMapObjects(); void randomizeObject(CGObjectInstance *cur); void initPlayerStates(); void placeCampaignHeroes(); CrossoverHeroesList getCrossoverHeroesFromPreviousScenarios() const; /// returns heroes and placeholders in where heroes will be put std::vector<CampaignHeroReplacement> generateCampaignHeroesToReplace(CrossoverHeroesList & crossoverHeroes); /// gets prepared and copied hero instances with crossover heroes from prev. scenario and travel options from current scenario void prepareCrossoverHeroes(std::vector<CampaignHeroReplacement> & campaignHeroReplacements, const CScenarioTravel & travelOptions) const; void replaceHeroesPlaceholders(const std::vector<CampaignHeroReplacement> & campaignHeroReplacements); void placeStartingHeroes(); void placeStartingHero(PlayerColor playerColor, HeroTypeID heroTypeId, int3 townPos); void initStartingResources(); void initHeroes(); void giveCampaignBonusToHero(CGHeroInstance * hero); void initFogOfWar(); void initStartingBonus(); void initTowns(); void initMapObjects(); void initVisitingAndGarrisonedHeroes(); // ----- bonus system handling ----- void buildBonusSystemTree(); void attachArmedObjects(); void buildGlobalTeamPlayerTree(); void deserializationFix(); // ---- misc helpers ----- CGHeroInstance * getUsedHero(HeroTypeID hid) const; bool isUsedHero(HeroTypeID hid) const; //looks in heroes and prisons std::set<HeroTypeID> getUnusedAllowedHeroes(bool alsoIncludeNotAllowed = false) const; std::pair<Obj,int> pickObject(CGObjectInstance *obj); //chooses type of object to be randomized, returns <type, subtype> int pickUnusedHeroTypeRandomly(PlayerColor owner); // picks a unused hero type randomly int pickNextHeroType(PlayerColor owner); // picks next free hero type of the H3 hero init sequence -> chosen starting hero, then unused hero type randomly // ---- data ----- CRandomGenerator rand; friend class CCallback; friend class CClient; friend class IGameCallback; friend class CMapHandler; friend class CGameHandler; };
edeksumo/vcmi
lib/CGameState.h
C
gpl-2.0
11,195
/////////////////////////////////////////////////////////////////////////////////////// // Copyright (C) 2006-2019 Esper Team. All rights reserved. / // http://esper.codehaus.org / // ---------------------------------------------------------------------------------- / // The software in this package is published under the terms of the GPL license / // a copy of which has been included with this distribution in the license.txt file. / /////////////////////////////////////////////////////////////////////////////////////// using System; using System.Collections.Generic; using com.espertech.esper.common.client; using com.espertech.esper.common.@internal.bytecodemodel.@base; using com.espertech.esper.common.@internal.bytecodemodel.model.expression; using com.espertech.esper.common.@internal.epl.expression.codegen; using com.espertech.esper.common.@internal.epl.expression.core; using com.espertech.esper.common.@internal.util; using com.espertech.esper.compat.collections; using com.espertech.esper.compat.magic; using static com.espertech.esper.common.@internal.bytecodemodel.model.expression.CodegenExpressionBuilder; namespace com.espertech.esper.common.@internal.epl.expression.ops { public class ExprEqualsAllAnyNodeForgeEvalAllWColl : ExprEvaluator { private readonly ExprEvaluator[] _evaluators; private readonly ExprEqualsAllAnyNodeForge _forge; public ExprEqualsAllAnyNodeForgeEvalAllWColl( ExprEqualsAllAnyNodeForge forge, ExprEvaluator[] evaluators) { this._forge = forge; this._evaluators = evaluators; } public object Evaluate( EventBean[] eventsPerStream, bool isNewData, ExprEvaluatorContext exprEvaluatorContext) { return EvaluateInternal(eventsPerStream, isNewData, exprEvaluatorContext); } private object EvaluateInternal( EventBean[] eventsPerStream, bool isNewData, ExprEvaluatorContext exprEvaluatorContext) { var leftResult = _evaluators[0].Evaluate(eventsPerStream, isNewData, exprEvaluatorContext); // coerce early if testing without collections if (_forge.IsMustCoerce && leftResult != null) { leftResult = _forge.Coercer.CoerceBoxed(leftResult); } return CompareAll( _forge.ForgeRenderable.IsNot, leftResult, eventsPerStream, isNewData, exprEvaluatorContext); } private object CompareAll( bool isNot, object leftResult, EventBean[] eventsPerStream, bool isNewData, ExprEvaluatorContext exprEvaluatorContext) { var len = _forge.ForgeRenderable.ChildNodes.Length - 1; var hasNonNullRow = false; var hasNullRow = false; for (var i = 1; i <= len; i++) { var rightResult = _evaluators[i].Evaluate(eventsPerStream, isNewData, exprEvaluatorContext); if (rightResult == null) { hasNullRow = true; } else if (rightResult is Array array) { var arrayLength = array.Length; for (var index = 0; index < arrayLength; index++) { object item = array.GetValue(index); if (item == null) { hasNullRow = true; continue; } if (leftResult == null) { return null; } hasNonNullRow = true; if (!_forge.IsMustCoerce) { if (!isNot && !leftResult.Equals(item) || isNot && leftResult.Equals(item)) { return false; } } else { if (!(item.IsNumber())) { continue; } var left = _forge.Coercer.CoerceBoxed(leftResult); var right = _forge.Coercer.CoerceBoxed(item); if (!isNot && !left.Equals(right) || isNot && left.Equals(right)) { return false; } } } } else if (rightResult.GetType().IsGenericDictionary()) { if (leftResult == null) { return null; } hasNonNullRow = true; var coll = rightResult.UnwrapDictionary(MagicMarker.SingletonInstance); if (!isNot && !coll.ContainsKey(leftResult) || isNot && coll.ContainsKey(leftResult)) { return false; } } else if (rightResult.GetType().IsGenericCollection()) { if (leftResult == null) { return null; } hasNonNullRow = true; var coll = rightResult.Unwrap<object>(); if (!isNot && !coll.Contains(leftResult) || isNot && coll.Contains(leftResult)) { return false; } } else { if (leftResult == null) { return null; } if (!_forge.IsMustCoerce) { if (!isNot && !leftResult.Equals(rightResult) || isNot && leftResult.Equals(rightResult)) { return false; } } else { var left = _forge.Coercer.CoerceBoxed(leftResult); var right = _forge.Coercer.CoerceBoxed(rightResult); if (!isNot && !left.Equals(right) || isNot && left.Equals(right)) { return false; } } } } if (!hasNonNullRow || hasNullRow) { return null; } return true; } public static CodegenExpression Codegen( ExprEqualsAllAnyNodeForge forge, CodegenMethodScope codegenMethodScope, ExprForgeCodegenSymbol exprSymbol, CodegenClassScope codegenClassScope) { var forges = ExprNodeUtilityQuery.GetForges(forge.ForgeRenderable.ChildNodes); var isNot = forge.ForgeRenderable.IsNot; var methodNode = codegenMethodScope.MakeChild( typeof(bool?), typeof(ExprEqualsAllAnyNodeForgeEvalAllWColl), codegenClassScope); var block = methodNode.Block; var leftTypeUncoerced = forges[0].EvaluationType; block.DeclareVar( leftTypeUncoerced, "left", forges[0].EvaluateCodegen(leftTypeUncoerced, methodNode, exprSymbol, codegenClassScope)); block.DeclareVar( forge.CoercionTypeBoxed, "leftCoerced", !forge.IsMustCoerce ? Ref("left") : forge.Coercer.CoerceCodegenMayNullBoxed( Ref("left"), leftTypeUncoerced, methodNode, codegenClassScope)); block.DeclareVar<bool>("hasNonNullRow", ConstantFalse()); block.DeclareVar<bool>("hasNullRow", ConstantFalse()); for (var i = 1; i < forges.Length; i++) { var refforge = forges[i]; var refname = "r" + i; var reftype = forges[i].EvaluationType; if (reftype.IsArray) { var arrayBlock = block.IfRefNullReturnNull("left") .DeclareVar( reftype, refname, refforge.EvaluateCodegen(reftype, methodNode, exprSymbol, codegenClassScope)) .IfCondition(EqualsNull(Ref(refname))) .AssignRef("hasNullRow", ConstantTrue()) .IfElse(); var forLoop = arrayBlock.ForLoopIntSimple("i", ArrayLength(Ref(refname))); var arrayAtIndex = ArrayAtIndex(Ref(refname), Ref("i")); forLoop.DeclareVar( forge.CoercionTypeBoxed, "item", forge.Coercer == null ? arrayAtIndex : forge.Coercer.CoerceCodegenMayNullBoxed( arrayAtIndex, reftype.GetElementType(), methodNode, codegenClassScope)); var forLoopElse = forLoop.IfCondition(EqualsNull(Ref("item"))) .AssignRef("hasNullRow", ConstantTrue()) .IfElse(); forLoopElse.AssignRef("hasNonNullRow", ConstantTrue()); forLoopElse.IfCondition( NotOptional(!isNot, StaticMethod<object>("Equals", Ref("leftCoerced"), Ref("item")))) .BlockReturn(ConstantFalse()); } else if (reftype.IsGenericDictionary()) { var dictionaryType = typeof(IDictionary<,>) .MakeGenericType( reftype.GetGenericArguments()[0], reftype.GetGenericArguments()[1]); var leftWithBoxing = ExprEqualsAllAnyNodeForgeHelper.ItemToCollectionUnboxing( Ref("left"), leftTypeUncoerced, reftype.GetDictionaryKeyType()); block.IfRefNullReturnNull("left") .DeclareVar( dictionaryType, refname, refforge.EvaluateCodegen( dictionaryType, methodNode, exprSymbol, codegenClassScope)) .IfCondition(EqualsNull(Ref(refname))) .AssignRef("hasNullRow", ConstantTrue()) .IfElse() .AssignRef("hasNonNullRow", ConstantTrue()) .IfCondition(NotOptional(!isNot, ExprDotMethod(Ref(refname), "CheckedContainsKey", leftWithBoxing))) .BlockReturn(ConstantFalse()); } else if (reftype.IsGenericCollection()) { var collectionType = typeof(ICollection<>) .MakeGenericType(reftype.GetGenericArguments()[0]); var leftWithBoxing = ExprEqualsAllAnyNodeForgeHelper.ItemToCollectionUnboxing( Ref("left"), leftTypeUncoerced, reftype.GetCollectionItemType()); block.IfRefNullReturnNull("left") .DeclareVar( collectionType, refname, refforge.EvaluateCodegen( collectionType, methodNode, exprSymbol, codegenClassScope)) .IfCondition(EqualsNull(Ref(refname))) .AssignRef("hasNullRow", ConstantTrue()) .IfElse() .AssignRef("hasNonNullRow", ConstantTrue()) .IfCondition(NotOptional(!isNot, ExprDotMethod(Ref(refname), "CheckedContains", leftWithBoxing))) .BlockReturn(ConstantFalse()); } else { block.IfRefNullReturnNull("leftCoerced"); block.DeclareVar( forge.CoercionTypeBoxed, refname, forge.Coercer == null ? refforge.EvaluateCodegen( forge.CoercionTypeBoxed, methodNode, exprSymbol, codegenClassScope) : forge.Coercer.CoerceCodegenMayNullBoxed( refforge.EvaluateCodegen( forge.CoercionTypeBoxed, methodNode, exprSymbol, codegenClassScope), reftype, methodNode, codegenClassScope)); var ifRightNotNull = block.IfRefNotNull(refname); { ifRightNotNull.AssignRef("hasNonNullRow", ConstantTrue()); ifRightNotNull .IfCondition(NotOptional(!isNot, StaticMethod<object>("Equals", Ref("leftCoerced"), Ref(refname)))) .BlockReturn(ConstantFalse()); } ifRightNotNull.IfElse() .AssignRef("hasNullRow", ConstantTrue()); } } block.IfCondition(Or(Not(Ref("hasNonNullRow")), Ref("hasNullRow"))).BlockReturn(ConstantNull()); block.MethodReturn(ConstantTrue()); return LocalMethod(methodNode); } } } // end of namespace
espertechinc/nesper
src/NEsper.Common/common/internal/epl/expression/ops/ExprEqualsAllAnyNodeForgeEvalAllWColl.cs
C#
gpl-2.0
14,493
#ifndef ARTERY_NETWORKINTERFACETABLE_H_ #define ARTERY_NETWORKINTERFACETABLE_H_ #include "artery/application/NetworkInterface.h" #include "artery/utility/Channel.h" #include <memory> #include <unordered_set> namespace artery { /** * NetworkInterfaceTable maintains NetworkInterfaces registered at a Middleware */ class NetworkInterfaceTable { public: using TableContainer = std::unordered_set<std::shared_ptr<NetworkInterface>>; /** * Select the first NetworkInterfaces operating on a particular channel. * * \param ch NetworkInterface shall operate on this channel * \return shared pointer to found NetworkInterface (might be empty) */ std::shared_ptr<NetworkInterface> select(ChannelNumber ch) const; /** * Get all managed NetworkInterfaces. */ const TableContainer& all() const; /** * Insert a NetworkInterface * * \param ifc NetworkInterface instance */ void insert(std::shared_ptr<NetworkInterface> ifc); private: TableContainer mInterfaces; }; } // namespace artery #endif
riebl/artery
src/artery/application/NetworkInterfaceTable.h
C
gpl-2.0
1,161
/* * Copyright (C) 2008-2012 TrinityCore <http://www.trinitycore.org/> * Copyright (C) 2005-2009 MaNGOS <http://getmangos.com/> * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License as published by the * Free Software Foundation; either version 2 of the License, or (at your * option) any later version. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * more details. * * You should have received a copy of the GNU General Public License along * with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "Common.h" #include "DatabaseEnv.h" #include "Log.h" #include "ObjectAccessor.h" #include "Opcodes.h" #include "Player.h" #include "Pet.h" #include "UpdateMask.h" #include "WorldPacket.h" #include "WorldSession.h" void WorldSession::HandleLearnTalentOpcode(WorldPacket & recvData) { uint32 talent_id, requested_rank; recvData >> talent_id >> requested_rank; _player->LearnTalent(talent_id, requested_rank); _player->SendTalentsInfoData(false); } void WorldSession::HandleLearnPreviewTalents(WorldPacket& recvPacket) { sLog->outDebug(LOG_FILTER_NETWORKIO, "CMSG_LEARN_PREVIEW_TALENTS"); uint32 talentsCount; recvPacket >> talentsCount; uint32 talentId, talentRank; for (uint32 i = 0; i < talentsCount; ++i) { recvPacket >> talentId >> talentRank; _player->LearnTalent(talentId, talentRank); } _player->SendTalentsInfoData(false); } void WorldSession::HandleTalentWipeConfirmOpcode(WorldPacket & recvData) { sLog->outDebug(LOG_FILTER_NETWORKIO, "MSG_TALENT_WIPE_CONFIRM"); uint64 guid; recvData >> guid; Creature* unit = GetPlayer()->GetNPCIfCanInteractWith(guid, UNIT_NPC_FLAG_TRAINER); if (!unit) { sLog->outDebug(LOG_FILTER_NETWORKIO, "WORLD: HandleTalentWipeConfirmOpcode - Unit (GUID: %u) not found or you can't interact with him.", uint32(GUID_LOPART(guid))); return; } // remove fake death if (GetPlayer()->HasUnitState(UNIT_STATE_DIED)) GetPlayer()->RemoveAurasByType(SPELL_AURA_FEIGN_DEATH); if (!(_player->resetTalents())) { WorldPacket data(MSG_TALENT_WIPE_CONFIRM, 8+4); //you have not any talent data << uint64(0); data << uint32(0); SendPacket(&data); return; } _player->SendTalentsInfoData(false); unit->CastSpell(_player, 14867, true); //spell: "Untalent Visual Effect" } void WorldSession::HandleUnlearnSkillOpcode(WorldPacket& recvData) { uint32 skillId; recvData >> skillId; if (!IsPrimaryProfessionSkill(skillId)) return; GetPlayer()->SetSkill(skillId, 0, 0, 0); }
Dokman/DetoTesting
src/server/game/Handlers/SkillHandler.cpp
C++
gpl-2.0
2,918
/* This file is part of the KDE project Copyright (C) 2002 Peter Simonsson <psn@linux.se> Copyright (C) 2004, 2006 Jarosław Staniek <staniek@kde.org> This program is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Library General Public License for more details. You should have received a copy of the GNU Library General Public License along with this program; see the file COPYING. If not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, * Boston, MA 02110-1301, USA. */ #include "kexiblobtableedit.h" #include <stdlib.h> #include <QDataStream> #include <QFile> #include <QLayout> #include <QStatusBar> #include <QLabel> #include <QPixmap> #include <QImage> #include <QPainter> #include <QApplication> #include <QClipboard> #include <QBuffer> #include <QCache> #include <kdebug.h> #include <ktemporaryfile.h> #include <kmimetype.h> #include <kservice.h> #include <klocale.h> #include <kfiledialog.h> #include <kio/job.h> #include <kglobal.h> #include <kiconloader.h> #include <kmenu.h> #include <kstdaccel.h> #include <kexiutils/utils.h> #include <widget/utils/kexidropdownbutton.h> #include <widget/utils/kexicontextmenuutils.h> struct PixmapAndPos { QPixmap pixmap; QPoint pos; }; //! @internal class KexiBlobTableEdit::Private { public: Private() : menu(0) , readOnly(false) , setValueInternalEnabled(true) { } QByteArray value; KexiDropDownButton *button; QSize totalSize; KexiImageContextMenu *menu; bool readOnly; //!< cached for slotUpdateActionsAvailabilityRequested() bool setValueInternalEnabled; //!< used to disable KexiBlobTableEdit::setValueInternal() QCache<qulonglong, PixmapAndPos> cachedPixmaps; }; //====================================================== KexiBlobTableEdit::KexiBlobTableEdit(KexiDB::TableViewColumn &column, QWidget *parent) : KexiTableEdit(column, parent) , d(new Private()) { // m_proc = 0; // m_content = 0; KexiDataItemInterface::setHasFocusableWidget(false); d->button = new KexiDropDownButton(parentWidget() /*usually a viewport*/); d->button->hide(); d->button->setToolTip(i18n("Click to show available actions for this cell")); d->menu = new KexiImageContextMenu(this); d->menu->installEventFilter(this); if (column.columnInfo()) KexiImageContextMenu::updateTitle(d->menu, column.columnInfo()->captionOrAliasOrName(), //! @todo pixmaplabel icon is hardcoded... "pixmaplabel"); d->button->setMenu(d->menu); //force edit requested to start editing... (this will call slotUpdateActionsAvailabilityRequested()) //connect(d->menu, SIGNAL(aboutToShow()), this, SIGNAL(editRequested())); connect(d->menu, SIGNAL(updateActionsAvailabilityRequested(bool&,bool&)), this, SLOT(slotUpdateActionsAvailabilityRequested(bool&,bool&))); connect(d->menu, SIGNAL(insertFromFileRequested(KUrl)), this, SLOT(handleInsertFromFileAction(KUrl))); connect(d->menu, SIGNAL(saveAsRequested(QString)), this, SLOT(handleSaveAsAction(QString))); connect(d->menu, SIGNAL(cutRequested()), this, SLOT(handleCutAction())); connect(d->menu, SIGNAL(copyRequested()), this, SLOT(handleCopyAction())); connect(d->menu, SIGNAL(pasteRequested()), this, SLOT(handlePasteAction())); connect(d->menu, SIGNAL(clearRequested()), this, SLOT(clear())); connect(d->menu, SIGNAL(showPropertiesRequested()), this, SLOT(handleShowPropertiesAction())); } KexiBlobTableEdit::~KexiBlobTableEdit() { delete d; #if 0 kDebug() << "Cleaning up..."; if (m_tempFile) { m_tempFile->unlink(); //todo } delete m_proc; m_proc = 0; kDebug() << "Ready."; #endif } //! initializes this editor with \a add value void KexiBlobTableEdit::setValueInternal(const QVariant& add, bool removeOld) { if (!d->setValueInternalEnabled) return; if (removeOld) d->value = add.toByteArray(); else //do not add "m_origValue" to "add" as this is QByteArray d->value = KexiDataItemInterface::originalValue().toByteArray(); #if 0 //todo? QByteArray val = m_origValue.toByteArray(); kDebug() << "Size of BLOB: " << val.size(); m_tempFile = new KTemporaryFile(); m_tempFile->open(); kDebug() << "Creating temporary file: " << m_tempFile->fileName(); QDataStream stream(m_tempFile); stream->writeRawBytes(val.data(), val.size()); delete m_tempFile; m_tempFile = 0; KMimeMagicResult* mmr = KMimeMagic::self()->findFileType(m_tempFile->fileName()); kDebug() << "Mimetype = " << mmr->mimeType(); setViewWidget(new QWidget(this)); #endif } bool KexiBlobTableEdit::valueIsNull() { //TODO d->value.size(); return d->value.isEmpty(); } bool KexiBlobTableEdit::valueIsEmpty() { //TODO return d->value.isEmpty(); } QVariant KexiBlobTableEdit::value() { return d->value; #if 0 //todo // ok = true; if (m_content && m_content->isModified()) { return QVariant(m_content->text()); } QByteArray value; QFile f(m_tempFile->fileName()); f.open(QIODevice::ReadOnly); QDataStream stream(&f); char* data = (char*) malloc(f.size()); value.resize(f.size()); stream.readRawBytes(data, f.size()); value.duplicate(data, f.size()); free(data); kDebug() << "Size of BLOB: " << value.size(); return QVariant(value); #endif } void KexiBlobTableEdit::paintFocusBorders(QPainter *p, QVariant &, int x, int y, int w, int h) { // d->currentEditorWidth = w; /*2.x if (!d->readOnly && w > d->button->width()) w -= d->button->width();*/ p->drawRect(x, y, w, h); } void KexiBlobTableEdit::setupContents(QPainter *p, bool focused, const QVariant& val, QString &txt, int &align, int &x, int &y_offset, int &w, int &h) { Q_UNUSED(focused); Q_UNUSED(txt); Q_UNUSED(align); QPoint pos; PixmapAndPos *pp = 0; x = 0; w -= 1; //a place for border h -= 1; //a place for border if (p) { const QByteArray array(val.toByteArray()); //! @todo optimize: keep this checksum in context of data //! @todo optimize: for now 100 items are cached; set proper cache size, e.g. based on the number of blob items visible on screen // the key is unique for this tuple: (checksum, w, h) qulonglong sum((((qulonglong(qChecksum(array.constData(), array.length())) << 32) + w) << 16) + h); pp = d->cachedPixmaps.object(sum); if (!pp) { QPixmap pixmap; if (val.canConvert(QVariant::ByteArray) && pixmap.loadFromData(val.toByteArray())) { #if 0 KexiUtils::drawPixmap(*p, KexiUtils::WidgetMargins()/*lineWidth*/, QRect(x, y_offset, w, h), pixmap, Qt::AlignCenter, true/*scaledContents*/, true/*keepAspectRatio*/); #endif QPoint pos; pixmap = KexiUtils::scaledPixmap(KexiUtils::WidgetMargins()/*lineWidth*/, QRect(x, y_offset, w, h), pixmap, pos, Qt::AlignCenter, true/*scaledContents*/, true/*keepAspectRatio*/, Qt::SmoothTransformation); if (!pixmap.isNull()) { pp = new PixmapAndPos; pp->pixmap = pixmap; pp->pos = pos; d->cachedPixmaps.insert(sum, pp); } } } if (pp) { p->drawPixmap(pp->pos, pp->pixmap); } } } bool KexiBlobTableEdit::cursorAtStart() { return true; } bool KexiBlobTableEdit::cursorAtEnd() { return true; } void KexiBlobTableEdit::handleInsertFromFileAction(const KUrl& url) { if (isReadOnly()) return; QString fileName(url.isLocalFile() ? url.toLocalFile() : url.prettyUrl()); //! @todo download the file if remote, then set fileName properly QFile f(fileName); if (!f.open(IO_ReadOnly)) { //! @todo err msg return; } QByteArray ba = f.readAll(); if (f.error() != QFile::NoError) { //! @todo err msg f.close(); return; } f.close(); // m_valueMimeType = KImageIO::mimeType( fileName ); setValueInternal(ba, true); signalEditRequested(); //emit acceptRequested(); } void KexiBlobTableEdit::handleAboutToSaveAsAction(QString& origFilename, QString& fileExtension, bool& dataIsEmpty) { Q_UNUSED(origFilename); Q_UNUSED(fileExtension); dataIsEmpty = valueIsEmpty(); //! @todo no fname stored for now } void KexiBlobTableEdit::handleSaveAsAction(const QString& fileName) { QFile f(fileName); if (!f.open(IO_WriteOnly)) { //! @todo err msg return; } f.write(d->value); if (f.error() != QFile::NoError) { //! @todo err msg f.close(); return; } f.close(); } void KexiBlobTableEdit::handleCutAction() { if (isReadOnly()) return; handleCopyAction(); clear(); } void KexiBlobTableEdit::handleCopyAction() { executeCopyAction(d->value); } void KexiBlobTableEdit::executeCopyAction(const QByteArray& data) { QPixmap pixmap; if (!pixmap.loadFromData(data)) return; qApp->clipboard()->setPixmap(pixmap, QClipboard::Clipboard); } void KexiBlobTableEdit::handlePasteAction() { if (isReadOnly()) return; QPixmap pm(qApp->clipboard()->pixmap(QClipboard::Clipboard)); QByteArray ba; QBuffer buffer(&ba); buffer.open(QIODevice::WriteOnly); if (pm.save(&buffer, "PNG")) { // write pixmap into ba in PNG format setValueInternal(ba, true); } else { setValueInternal(QByteArray(), true); } signalEditRequested(); //emit acceptRequested(); repaintRelatedCell(); } void KexiBlobTableEdit::clear() { setValueInternal(QByteArray(), true); signalEditRequested(); //emit acceptRequested(); repaintRelatedCell(); } void KexiBlobTableEdit::handleShowPropertiesAction() { //! @todo } void KexiBlobTableEdit::showFocus(const QRect& r, bool readOnly) { d->readOnly = readOnly; //cache for slotUpdateActionsAvailabilityRequested() // d->button->move( pos().x()+ width(), pos().y() ); updateFocus(r); // d->button->setEnabled(!readOnly); if (d->readOnly) d->button->hide(); else d->button->show(); } void KexiBlobTableEdit::resize(int w, int h) { d->totalSize = QSize(w, h); const int addWidth = d->readOnly ? 0 : d->button->width(); QWidget::resize(w - addWidth, h); if (!d->readOnly) d->button->resize(h, h); m_rightMarginWhenFocused = m_rightMargin + addWidth; QRect r(pos().x(), pos().y(), w + 1, h + 1); r.translate(m_scrollView->contentsX(), m_scrollView->contentsY()); updateFocus(r); //todo if (d->menu) { //todo d->menu->updateSize(); //todo } } void KexiBlobTableEdit::updateFocus(const QRect& r) { if (!d->readOnly) { if (d->button->width() > r.width()) moveChild(d->button, r.right() + 1, r.top()); else moveChild(d->button, r.right() - d->button->width(), r.top()); } } void KexiBlobTableEdit::hideFocus() { d->button->hide(); } QSize KexiBlobTableEdit::totalSize() const { return d->totalSize; } void KexiBlobTableEdit::slotUpdateActionsAvailabilityRequested(bool& valueIsNull, bool& valueIsReadOnly) { emit editRequested(); valueIsNull = this->valueIsNull(); valueIsReadOnly = d->readOnly || isReadOnly(); } void KexiBlobTableEdit::signalEditRequested() { d->setValueInternalEnabled = false; emit editRequested(); d->setValueInternalEnabled = true; } bool KexiBlobTableEdit::handleKeyPress(QKeyEvent* ke, bool editorActive) { Q_UNUSED(editorActive); const int k = ke->key(); if (!d->readOnly) { if ((ke->modifiers() == Qt::NoButton && k == Qt::Key_F4) || (ke->modifiers() == Qt::AltButton && k == Qt::Key_Down)) { d->button->animateClick(); QMouseEvent me(QEvent::MouseButtonPress, QPoint(2, 2), Qt::LeftButton, Qt::NoButton, Qt::NoModifier); QApplication::sendEvent(d->button, &me); } else if (ke->modifiers() == Qt::NoButton && (k == Qt::Key_F2 || k == Qt::Key_Space || k == Qt::Key_Enter || k == Qt::Key_Return)) { d->menu->insertFromFile(); } else return false; } else return false; return true; } bool KexiBlobTableEdit::handleDoubleClick() { d->menu->insertFromFile(); return true; } void KexiBlobTableEdit::handleCopyAction(const QVariant& value, const QVariant& visibleValue) { Q_UNUSED(visibleValue); executeCopyAction(value.toByteArray()); } void KexiBlobTableEdit::handleAction(const QString& actionName) { if (actionName == "edit_paste") { d->menu->paste(); } else if (actionName == "edit_cut") { emit editRequested(); d->menu->cut(); } } bool KexiBlobTableEdit::eventFilter(QObject *o, QEvent *e) { if (o == d->menu && e->type() == QEvent::KeyPress) { QKeyEvent* ke = static_cast<QKeyEvent*>(e); const int mods = ke->modifiers(); const int k = ke->key(); if ((mods == Qt::NoButton && (k == Qt::Key_Tab || k == Qt::Key_Left || k == Qt::Key_Right)) || (mods == Qt::ShiftButton && k == Qt::Key_Backtab) ) { d->menu->hide(); QApplication::sendEvent(this, ke); //re-send to move cursor return true; } } return false; } KEXI_CELLEDITOR_FACTORY_ITEM_IMPL(KexiBlobEditorFactoryItem, KexiBlobTableEdit) //======================= // KexiKIconTableEdit class is temporarily here: //! @internal class KexiKIconTableEdit::Private { public: Private() : pixmapCache(17) { } //! We've no editor widget that would store current value, so we do this here QVariant currentValue; QCache<QString, QPixmap> pixmapCache; }; KexiKIconTableEdit::KexiKIconTableEdit(KexiDB::TableViewColumn &column, QWidget *parent) : KexiTableEdit(column, parent) , d(new Private()) { init(); } KexiKIconTableEdit::~KexiKIconTableEdit() { delete d; } void KexiKIconTableEdit::init() { KexiDataItemInterface::setHasFocusableWidget(false); } void KexiKIconTableEdit::setValueInternal(const QVariant& /*add*/, bool /*removeOld*/) { d->currentValue = KexiDataItemInterface::originalValue(); } bool KexiKIconTableEdit::valueIsNull() { return d->currentValue.isNull(); } bool KexiKIconTableEdit::valueIsEmpty() { return d->currentValue.isNull(); } QVariant KexiKIconTableEdit::value() { return d->currentValue; } void KexiKIconTableEdit::clear() { d->currentValue = QVariant(); } bool KexiKIconTableEdit::cursorAtStart() { return true; } bool KexiKIconTableEdit::cursorAtEnd() { return true; } void KexiKIconTableEdit::setupContents(QPainter *p, bool /*focused*/, const QVariant& val, QString &/*txt*/, int &/*align*/, int &/*x*/, int &y_offset, int &w, int &h) { Q_UNUSED(y_offset); #if 0 #ifdef Q_WS_WIN y_offset = -1; #else y_offset = 0; #endif int s = qMax(h - 5, 12); s = qMin(h - 3, s); s = qMin(w - 3, s);//avoid too large box QRect r(qMax(w / 2 - s / 2, 0) , h / 2 - s / 2 /*- 1*/, s, s); p->setPen(QPen(colorGroup().text(), 1)); p->drawRect(r); if (val.asBool()) { p->drawLine(r.x(), r.y(), r.right(), r.bottom()); p->drawLine(r.x(), r.bottom(), r.right(), r.y()); } #endif QString key(val.toString()); QPixmap pm; if (!key.isEmpty()) { QPixmap *cached = d->pixmapCache[ key ]; if (cached) pm = *cached; if (pm.isNull()) { //cache pixmap pm = KIconLoader::global()->loadIcon(key, KIconLoader::Small, 0, KIconLoader::DefaultState , QStringList() , 0L, true/*canReturnNull*/); if (!pm.isNull()) d->pixmapCache.insert(key, new QPixmap(pm)); } } if (p && !pm.isNull()) p->drawPixmap((w - pm.width()) / 2, (h - pm.height()) / 2, pm); } void KexiKIconTableEdit::handleCopyAction(const QVariant& value, const QVariant& visibleValue) { Q_UNUSED(value); Q_UNUSED(visibleValue); } KEXI_CELLEDITOR_FACTORY_ITEM_IMPL(KexiKIconTableEditorFactoryItem, KexiKIconTableEdit) #include "kexiblobtableedit.moc"
yxl/emscripten-calligra-mobile
kexi/widget/tableview/kexiblobtableedit.cpp
C++
gpl-2.0
17,025
<?php /* Plugin Name: SB Popular Posts Tabbed Widget Plugin URI: http://designbyscott.wpengine.com/ Description: A lightweight, responsive, uncluttered widget to display popular posts, recent posts, and categories with tabs. Version: 1.0 Author: Scott Bolinger Author URI: http://designbyscott.wpengine.com/ License: GPL2 */ /* Includes --------------------------------------------------- */ include_once ('includes/scripts.php'); /* Create & Display Widget --------------------------------------------------- */ class sb_tabbed_widget extends WP_Widget { /** constructor */ function sb_tabbed_widget() { parent::WP_Widget(false, $name = 'SB Popular Posts Tabbed Widget'); } /** @see WP_Widget::widget */ function widget($args, $instance) { extract( $args ); $number = $instance['number']; // Number of posts to show $checkbox = $instance['checkbox']; // Show post thumbnails $checkbox2 = $instance['checkbox2']; // Show post meta ?> <?php echo $before_widget; ?> <div class="sb_tabbed"> <!-- The tabs --> <ul class="sb_tabs"> <li class="t1"><a class="t1 tab" title="Tab 1"><?php _e('Popular') ?></a></li> <li class="t2"><a class="t2 tab" title="Tab 2"><?php _e('Recent') ?></a></li> <li class="t3"><a class="t3 tab" title="Tab 3"><?php _e('Categories') ?></a></li> </ul> <!-- tab 1 --> <div class="tab-content t1"> <ul> <?php $sb_pop_posts_query = new WP_Query( array ( 'orderby' => 'comment_count', 'order' => 'DESC', 'posts_per_page' => $number, 'post__not_in' => get_option( 'sticky_posts' ) ) ); if($sb_pop_posts_query->have_posts()): while($sb_pop_posts_query->have_posts()): $sb_pop_posts_query->the_post(); ?> <li> <a href="<?php the_permalink(); ?>" title="<?php the_title(); ?>"> <?php if ( has_post_thumbnail() && $checkbox == true ) { the_post_thumbnail( array(50,50), array('class' => 'alignleft') ); } elseif ( !has_post_thumbnail() && $checkbox == true ) { ?> <img src="<?php echo plugin_dir_url(__FILE__); ?>includes/images/default-thumb.png" alt="<?php the_title(); ?>" class="alignleft" width="50" height="50" /> <?php } ?> <?php echo get_the_title(); ?> </a> <?php if ( $checkbox2 == true ) { ?> <span class="sb-comment-meta"><?php echo comments_number( '', '1 Comment', '% Comments' ); ?></span> <?php } ?> </li> <?php endwhile; endif; /* Restore original Post Data */ wp_reset_postdata(); ?> </ul> </div> <!-- tab 2 --> <div class="tab-content t2"> <ul> <?php $sb_recent_posts_query = new WP_Query( array ( 'posts_per_page' => $number ) ); if($sb_recent_posts_query->have_posts()): while($sb_recent_posts_query->have_posts()): $sb_recent_posts_query->the_post(); ?> <li> <a href="<?php the_permalink(); ?>" title="<?php the_title(); ?>"> <?php if ( has_post_thumbnail() && $checkbox == true ) { the_post_thumbnail( array(50,50), array('class' => 'alignleft') ); } elseif ( !has_post_thumbnail() && $checkbox == true ) { ?> <img src="<?php echo plugin_dir_url(__FILE__); ?>includes/images/default-thumb.png" alt="<?php the_title(); ?>" class="alignleft" width="50" height="50" /> <?php } ?> <?php the_title(); ?> </a> <?php if ( $checkbox2 == true ) { ?> <span class="sb-date-meta"><?php the_date(); ?></span> <?php } ?> </li> <?php endwhile; endif; /* Restore original Post Data */ wp_reset_postdata(); ?> </ul> </div> <!-- tab 3 --> <div class="tab-content t3"> <ul> <?php $cat_args=array( 'orderby' => 'name', 'order' => 'ASC', 'number' => $number ); $categories=get_categories($cat_args); foreach($categories as $category) { echo '<li><a href="' . get_category_link( $category->term_id ) . '" title="' . sprintf( __( "View all posts in %s" ), $category->name ) . '" ' . '>' . $category->name.'</a>'; if ( $checkbox2 == true ) { echo '<span class="sb-cat-meta"> (' . $category->count . ')</span></li>'; } else { echo '</li>'; } } ?> </ul> </div> </div><!-- tabbed --> <?php echo $after_widget; ?> <?php } /* Update @see WP_Widget::update --------------------------------------------------- */ function update($new_instance, $old_instance) { $instance = $old_instance; $instance['number'] = wp_kses_data($new_instance['number']); $instance['checkbox'] = strip_tags($new_instance['checkbox']); $instance['checkbox2'] = strip_tags($new_instance['checkbox2']); return $instance; } /* Widget Options @see WP_Widget::form --------------------------------------------------- */ function form($instance) { $defaults = array( 'number' => 5, 'checkbox' => true, 'checkbox2' => true, ); extract( wp_parse_args( $instance, $defaults ) ); ?> <p> <label for="<?php echo $this->get_field_id('number'); ?>"><?php _e('Number of posts to display:'); ?></label> <input size="2" id="<?php echo $this->get_field_id('number'); ?>" name="<?php echo $this->get_field_name('number'); ?>" type="text" value="<?php echo esc_attr( $number ); ?>" /> </p> <p> <input id="<?php echo $this->get_field_id('checkbox'); ?>" name="<?php echo $this->get_field_name('checkbox'); ?>" type="checkbox" value="1" <?php checked( '1', $checkbox ); ?>/> <label for="<?php echo $this->get_field_id('checkbox'); ?>"><?php _e('Display thumbnails'); ?></label> </p> <p> <input id="<?php echo $this->get_field_id('checkbox2'); ?>" name="<?php echo $this->get_field_name('checkbox2'); ?>" type="checkbox" value="1" <?php checked( '1', $checkbox2 ); ?>/> <label for="<?php echo $this->get_field_id('checkbox2'); ?>"><?php _e('Display meta (date, comments)'); ?></label> </p> <?php } } add_action('widgets_init', create_function('', 'return register_widget("sb_tabbed_widget");'));
zhed/wpatomneto
wp-content/plugins/sb-popular-posts-tabbed-widget/sb-pop-posts-widget.php
PHP
gpl-2.0
6,403
/* * jQuery FlexSlider v1.5 * http://flex.madebymufffin.com * * Copyright 2011, Tyler Smith * Free to use under the MIT license. * http://www.opensource.org/licenses/mit-license.php */ /* FlexSlider Necessary Styles *********************************/ .flexslider {width: 100%; margin: 0; padding: 0;} .flexslider .slides li {display: none;} /* Hide the slides before the JS is loaded. Avoids image jumping */ .flexslider .slides img {max-width: 100%; display: block;} /* Browser Resets */ .flexslider a {outline: none;} .slides, .flex-control-nav, .flex-direction-nav {margin: 0; padding: 0; list-style: none;} /* No JavaScript Fallback */ /* If you are not using another script, such as Modernizr, make sure you * include js that eliminates this class on page load */ .no-js .slides li:first-child {display: block;} /* FlexSlider Default Theme *********************************/ .flexslider {background: #fff; border: 4px solid #fff; position: relative; -webkit-border-radius: 5px; -moz-border-radius: 5px; -o-border-radius: 5px; border-radius: 5px;} .flexslider .slides li {position: relative;} /* Suggested container for "Slide" animation setups. Can replace this with your own, if you wish */ .flexslider-container {position: relative;} /* Caption style */ .flex-caption {width: 96%; padding: 2%; position: absolute; left: 0; bottom: 0; background: rgba(0,0,0,.3); color: #fff; text-shadow: 0 -1px 0 rgba(0,0,0,.3); font-size: 14px; line-height: 18px;} /* Direction Nav */ .flex-direction-nav li a {width: 52px; height: 52px; margin: -13px 0 0; display: block; background: url(../images/bg_direction_nav.png) no-repeat 0 0; position: absolute; top: 50%; cursor: pointer; text-indent: -9999px;} /* set negative margin-top equal to half the height on the directional-nav for perfect vertical centering */ .flex-direction-nav li a.next {background-position: -52px 0; right: -21px;} .flex-direction-nav li a.prev {background-position: 0 0; left: -20px;} /* Control Nav */ .flex-control-nav {width: 100%; position: absolute; bottom: -30px; text-align: center;} .flex-control-nav li {margin: 0 0 0 5px; display: inline-block; zoom: 1; *display: inline;} .flex-control-nav li:first-child {margin: 0;} .flex-control-nav li a {width: 13px; height: 13px; display: block; background: url(../images/bg_control_nav.png) no-repeat 0 0; cursor: pointer; text-indent: -9999px;} .flex-control-nav li a:hover {background-position: 0 -13px;} .flex-control-nav li a.active {background-position: 0 -26px; cursor: default;}
Sapian/Bowkerlaw
wp-content/plugins/flexslider/js/flexslider.css
CSS
gpl-2.0
2,524
<head> <!-- you.html --> </head> <template name="you"> <tt class="x">you.html {{$.Config.you.version}}</tt> <div class="row"> <div class="large-12 columns"> <div class="you dashboard at"> <h3>Account settings, etc</h3> {{#each widgets 'you'}} <a href="{{ path }}" target="{{#if $exists target}}{{ target }}{{/if}}" id="{{ id }}" class="ldc-icon" title="{{ title }}"> <div>{{! table-row}} <div class="{{ icon }}"></div> </div> <div>{{! table-row}} <h4>{{{ name }}}</h4> </div> </a> {{/each}} </div> </div> </div> </template>
loopdotcoop/looptopia
you/you.html
HTML
gpl-2.0
662
<?php get_header(); ?> <section id="main"> <section id="main_content"> <?php if (have_posts()) : ?> <?php $post = $posts[0]; ?> <?php if (is_category()) { ?> <h2><?php echo single_cat_title(); ?></h2> <?php } elseif( is_tag() ) { ?> <h2>Posts Tagged: <?php single_tag_title(); ?></h2> <?php }elseif (is_day()) { ?> <h2>Archive for <?php the_time('F jS, Y'); ?></h2> <?php }elseif (is_month()) { ?> <h2>Archive for <?php the_time('F, Y'); ?></h2> <?php }elseif (is_year()) { ?> <h2>Archive for <?php the_time('Y'); ?></h2> <?php } elseif (is_search()) { ?> <h2>Search Results</h2> <?php } elseif (is_author()) { ?> <h2>Author Archive</h2> <?php }elseif (isset($_GET['paged']) && !empty($_GET['paged'])) { ?> <h2>Blog Archives</h2> <?php } ?> <?php while (have_posts()) : the_post(); ?> <article id="post-<?php the_ID(); ?>" <?php post_class(); ?>> <h2><a href="<?php the_permalink() ?>" rel="bookmark"><?php the_title(); ?></a></h2> <?php post_meta(); ?> <?php custom_excerpt(100, "More Info"); ?> </article> <?php endwhile; else: ?> <p>Sorry, seems like there aren't any posts.</p> <?php endif; ?> </section> <?php get_sidebar(); ?> <?php get_footer(); ?>
rigelstpierre/Everlovin-Press
wp-content/themes/everlovin/archive.php
PHP
gpl-2.0
1,319
#if defined(__GNUC__) #ident "University of Edinburgh $Id$" #else static char _WarperSourceViewer_h[] = "University of Edinburgh $Id$"; #endif /*! * \file WarperSourceViewer.h * \author Zsolt Husz * \date October 2008 * \version $Id$ * \par * Address: * MRC Human Genetics Unit, * MRC Institute of Genetics and Molecular Medicine, * University of Edinburgh, * Western General Hospital, * Edinburgh, EH4 2XU, UK. * \par * Copyright (C), [2014], * The University Court of the University of Edinburgh, * Old College, Edinburgh, UK. * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be * useful but WITHOUT ANY WARRANTY; without even the implied * warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR * PURPOSE. See the GNU General Public License for more * details. * * You should have received a copy of the GNU General Public * License along with this program; if not, write to the Free * Software Foundation, Inc., 51 Franklin Street, Fifth Floor, * Boston, MA 02110-1301, USA. * \brief Viewer displaying source objects * \ingroup UI */ #ifndef WARPERSOURCEVIEWER_H #define WARPERSOURCEVIEWER_H #include "WarperViewer.h" class QXmlStreamWriter; /*! * \brief Warping source object viewer class. * Viewer class displaying source objects. It has feature * point views. * * \ingroup UI */ class WarperSourceViewer : public WarperViewer { Q_OBJECT public: /*! * \ingroup UI * \brief Constructor * \param objectViewerModel model managing the viewer * \param is3D if viewer is for 3D objects * \param fPointModel landmark model * \param AddAction pointer referring add landmark action * Qt event * \param DeleteAction pointer referring delete landmark * action Qt event * \param MoveAction pointer referring move landmark action * Qt event * \param RemovelElemAction pointer referring remove element * action Qt event * */ WarperSourceViewer (ObjectViewerModel *objectViewerModel, bool is3D, LandmarkController* fPointModel, QAction * AddAction, QAction * DeleteAction, QAction * MoveAction, QAction * RemovelElemAction); /*! * \ingroup UI * \brief Checks if viewer accepts object. * \return true if viewer object is a source object */ virtual bool accepting(WoolzObject * object ); /*! * \ingroup UI * \brief Returns the default object transparency. * \return 0, all source objects are visible */ virtual int initialTransparency(WoolzObject * ) {return 0;} /*! * \ingroup UI * \brief Configures the view * */ virtual void init(); /*! * \ingroup Control * \brief Saves model in xml format. * \param xmlWriter output xml stream * \param header true of header should be written * \return true if succeded, false if not */ virtual bool saveAsXml(QXmlStreamWriter *xmlWriter); protected: /*! * \ingroup UI * \brief Returns the background colour of the viewer * Reimplemented form ObjectViewer * \return colour */ virtual QColor getBackgroundColour(); /*! * \ingroup UI * \brief Processes the signal of landmark addition * It forwards the signal to the appropiate source model. * \param point point to add */ virtual void addLandmark(const WlzDVertex3 point); public: static const char * xmlTag; /*!< xml section tag string */ }; #endif // WARPERSOURCEVIEWER_H
ma-tech/WlzQtApps
WlzWarp/WarperSourceViewer.h
C
gpl-2.0
3,904
/******************************************************************************* Este arquivo é parte do programa figNG figNG é um software livre; você pode redistribui-lo e/ou modifica-lo dentro dos termos da Licença Pública Geral GNU como publicada pela Fundação do Software Livre (FSF); na versão 2 da Licença, ou (na sua opnião) qualquer versão. Este programa é distribuido na esperança que possa ser util, mas SEM NENHUMA GARANTIA; sem uma garantia implicita de ADEQUAÇÂO a qualquer MERCADO ou APLICAÇÃO EM PARTICULAR. Veja a Licença Pública Geral GNU para maiores detalhes. Você deve ter recebido uma cópia da Licença Pública Geral GNU junto com este programa, se não, escreva para a Fundação do Software Livre(FSF) Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA *****************************************************************************/ #include <QtGui/QApplication> #include "mainwindow.h" int main(int argc, char *argv[]) { QApplication a(argc, argv); MainWindow w; w.show(); return a.exec(); }
helderc/figNG
main.cpp
C++
gpl-2.0
1,122
<?php /** * @copyright Copyright (C) 2005 - 2012 Open Source Matters, Inc. All rights reserved. * @license GNU General Public License version 2 or later; see LICENSE.txt */ // No direct access defined('_JEXEC') or die; jimport('joomla.base.tree'); /** * @package Joomla.Administrator * @subpackage mod_menu */ class JAdminCssMenu extends JTree { /** * CSS string to add to document head * @var string */ protected $_css = null; function __construct() { $this->_root = new JMenuNode('ROOT'); $this->_current = $this->_root; } function addSeparator() { $this->addChild(new JMenuNode(null, null, 'separator', false)); } function renderMenu($id = 'menu', $class = '') { $depth = 1; if (!empty($id)) { $id='id="'.$id.'"'; } if (!empty($class)) { $class='class="'.$class.'"'; } /* * Recurse through children if they exist */ while ($this->_current->hasChildren()) { echo "<ul ".$id." ".$class.">\n"; foreach ($this->_current->getChildren() as $child) { $this->_current = & $child; $this->renderLevel($depth++); } echo "</ul>\n"; } if ($this->_css) { // Add style to document head $doc = JFactory::getDocument(); $doc->addStyleDeclaration($this->_css); } } function renderLevel($depth) { /* * Build the CSS class suffix */ $class = ''; if ($this->_current->hasChildren()) { $class = ' class="node"'; } if ($this->_current->class == 'separator') { $class = ' class="separator"'; } if ($this->_current->class == 'disabled') { $class = ' class="disabled"'; } /* * Print the item */ echo "<li".$class.">"; /* * Print a link if it exists */ $linkClass = ''; if ($this->_current->link != null) { $linkClass = $this->getIconClass($this->_current->class); if (!empty($linkClass)) { $linkClass = ' class="'.$linkClass.'"'; } } if ($this->_current->link != null && $this->_current->target != null) { echo "<a".$linkClass." href=\"".$this->_current->link."\" target=\"".$this->_current->target."\" >".$this->_current->title."</a>"; } elseif ($this->_current->link != null && $this->_current->target == null) { echo "<a".$linkClass." href=\"".$this->_current->link."\">".$this->_current->title."</a>"; } elseif ($this->_current->title != null) { echo "<a>".$this->_current->title."</a>\n"; } else { echo "<span></span>"; } /* * Recurse through children if they exist */ while ($this->_current->hasChildren()) { if ($this->_current->class) { $id = ''; if (!empty($this->_current->id)) { $id = ' id="menu-'.strtolower($this->_current->id).'"'; } echo '<ul'.$id.' class="menu-component">'."\n"; } else { echo '<ul>'."\n"; } foreach ($this->_current->getChildren() as $child) { $this->_current = & $child; $this->renderLevel($depth++); } echo "</ul>\n"; } echo "</li>\n"; } /** * Method to get the CSS class name for an icon identifier or create one if * a custom image path is passed as the identifier * * @access public * @param string $identifier Icon identification string * @return string CSS class name * @since 1.5 */ function getIconClass($identifier) { static $classes; // Initialise the known classes array if it does not exist if (!is_array($classes)) { $classes = array(); } /* * If we don't already know about the class... build it and mark it * known so we don't have to build it again */ if (!isset($classes[$identifier])) { if (substr($identifier, 0, 6) == 'class:') { // We were passed a class name $class = substr($identifier, 6); $classes[$identifier] = "icon-16-$class"; } else { if ($identifier == null) { return null; } // Build the CSS class for the icon $class = preg_replace('#\.[^.]*$#', '', basename($identifier)); $class = preg_replace('#\.\.[^A-Za-z0-9\.\_\- ]#', '', $class); $this->_css .= "\n.icon-16-$class {\n" . "\tbackground: url($identifier) no-repeat;\n" . "}\n"; $classes[$identifier] = "icon-16-$class"; } } return $classes[$identifier]; } } /** * @package Joomla.Administrator * @subpackage mod_menu */ class JMenuNode extends JNode { /** * Node Title */ public $title = null; /** * Node Id */ public $id = null; /** * Node Link */ public $link = null; /** * Link Target */ public $target = null; /** * CSS Class for node */ public $class = null; /** * Active Node? */ public $active = false; public function __construct($title, $link = null, $class = null, $active = false, $target = null, $titleicon = null) { $this->title = $titleicon ? $title.$titleicon : $title; $this->link = JFilterOutput::ampReplace($link); $this->class = $class; $this->active = $active; $this->id = null; if (!empty($link) && $link !== '#') { $uri = new JURI($link); $params = $uri->getQuery(true); $parts = array(); foreach ($params as $name => $value) { $parts[] = str_replace(array('.', '_'), '-', $value); } $this->id = implode('-', $parts); } $this->target = $target; } }
portalgas/site
administrator/templates/modules/mod_menu/menu.php
PHP
gpl-2.0
5,166
/* This file is part of cpp-ethereum. cpp-ethereum 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. cpp-ethereum 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 cpp-ethereum. If not, see <http://www.gnu.org/licenses/>. */ /** @file Common.h * @author Gav Wood <i@gavwood.com> * @date 2014 * * Very common stuff (i.e. that every other header needs except vector_ref.h). */ #pragma once // way too many unsigned to size_t warnings in 32 bit build #ifdef _M_IX86 #pragma warning(disable:4244) #endif #if _MSC_VER && _MSC_VER < 1900 #define _ALLOW_KEYWORD_MACROS #define noexcept throw() #endif #ifdef __INTEL_COMPILER #pragma warning(disable:3682) //call through incomplete class #endif #include <map> #include <unordered_map> #include <vector> #include <set> #include <unordered_set> #include <functional> #include <string> #include <chrono> #pragma warning(push) #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Wunused-parameter" #include <boost/multiprecision/cpp_int.hpp> #pragma warning(pop) #pragma GCC diagnostic pop #include "vector_ref.h" // CryptoPP defines byte in the global namespace, so must we. using byte = uint8_t; // Quote a given token stream to turn it into a string. #define DEV_QUOTED_HELPER(s) #s #define DEV_QUOTED(s) DEV_QUOTED_HELPER(s) #define DEV_IGNORE_EXCEPTIONS(X) try { X; } catch (...) {} #define DEV_IF_THROWS(X) try{X;}catch(...) namespace dev { extern char const* Version; static const std::string EmptyString; // Binary data types. using bytes = std::vector<byte>; using bytesRef = vector_ref<byte>; using bytesConstRef = vector_ref<byte const>; template <class T> class secure_vector { public: secure_vector() {} secure_vector(secure_vector<T> const& /*_c*/) = default; // See https://github.com/ethereum/libweb3core/pull/44 explicit secure_vector(size_t _size): m_data(_size) {} explicit secure_vector(size_t _size, T _item): m_data(_size, _item) {} explicit secure_vector(std::vector<T> const& _c): m_data(_c) {} explicit secure_vector(vector_ref<T> _c): m_data(_c.data(), _c.data() + _c.size()) {} explicit secure_vector(vector_ref<const T> _c): m_data(_c.data(), _c.data() + _c.size()) {} ~secure_vector() { ref().cleanse(); } secure_vector<T>& operator=(secure_vector<T> const& _c) { if (&_c == this) return *this; ref().cleanse(); m_data = _c.m_data; return *this; } std::vector<T>& writable() { clear(); return m_data; } std::vector<T> const& makeInsecure() const { return m_data; } void clear() { ref().cleanse(); } vector_ref<T> ref() { return vector_ref<T>(&m_data); } vector_ref<T const> ref() const { return vector_ref<T const>(&m_data); } size_t size() const { return m_data.size(); } bool empty() const { return m_data.empty(); } void swap(secure_vector<T>& io_other) { m_data.swap(io_other.m_data); } private: std::vector<T> m_data; }; using bytesSec = secure_vector<byte>; // Numeric types. using bigint = boost::multiprecision::number<boost::multiprecision::cpp_int_backend<>>; using u64 = boost::multiprecision::number<boost::multiprecision::cpp_int_backend<64, 64, boost::multiprecision::unsigned_magnitude, boost::multiprecision::unchecked, void>>; using u128 = boost::multiprecision::number<boost::multiprecision::cpp_int_backend<128, 128, boost::multiprecision::unsigned_magnitude, boost::multiprecision::unchecked, void>>; using u256 = boost::multiprecision::number<boost::multiprecision::cpp_int_backend<256, 256, boost::multiprecision::unsigned_magnitude, boost::multiprecision::unchecked, void>>; using s256 = boost::multiprecision::number<boost::multiprecision::cpp_int_backend<256, 256, boost::multiprecision::signed_magnitude, boost::multiprecision::unchecked, void>>; using u160 = boost::multiprecision::number<boost::multiprecision::cpp_int_backend<160, 160, boost::multiprecision::unsigned_magnitude, boost::multiprecision::unchecked, void>>; using s160 = boost::multiprecision::number<boost::multiprecision::cpp_int_backend<160, 160, boost::multiprecision::signed_magnitude, boost::multiprecision::unchecked, void>>; using u512 = boost::multiprecision::number<boost::multiprecision::cpp_int_backend<512, 512, boost::multiprecision::unsigned_magnitude, boost::multiprecision::unchecked, void>>; using s512 = boost::multiprecision::number<boost::multiprecision::cpp_int_backend<512, 512, boost::multiprecision::signed_magnitude, boost::multiprecision::unchecked, void>>; using u256s = std::vector<u256>; using u160s = std::vector<u160>; using u256Set = std::set<u256>; using u160Set = std::set<u160>; // Map types. using StringMap = std::map<std::string, std::string>; using BytesMap = std::map<bytes, bytes>; using u256Map = std::map<u256, u256>; using HexMap = std::map<bytes, bytes>; // Hash types. using StringHashMap = std::unordered_map<std::string, std::string>; using u256HashMap = std::unordered_map<u256, u256>; // String types. using strings = std::vector<std::string>; // Fixed-length string types. using string32 = std::array<char, 32>; static const string32 ZeroString32 = {{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }}; // Null/Invalid values for convenience. static const bytes NullBytes; static const std::map<u256, u256> EmptyMapU256U256; extern const u256 Invalid256; /// Interprets @a _u as a two's complement signed number and returns the resulting s256. inline s256 u2s(u256 _u) { static const bigint c_end = bigint(1) << 256; if (boost::multiprecision::bit_test(_u, 255)) return s256(-(c_end - _u)); else return s256(_u); } /// @returns the two's complement signed representation of the signed number _u. inline u256 s2u(s256 _u) { static const bigint c_end = bigint(1) << 256; if (_u >= 0) return u256(_u); else return u256(c_end + _u); } /// Converts given int to a string and appends one of a series of units according to its size. std::string inUnits(bigint const& _b, strings const& _units); /// @returns the smallest n >= 0 such that (1 << n) >= _x inline unsigned int toLog2(u256 _x) { unsigned ret; for (ret = 0; _x >>= 1; ++ret) {} return ret; } template <size_t n> inline u256 exp10() { return exp10<n - 1>() * u256(10); } template <> inline u256 exp10<0>() { return u256(1); } /// @returns the absolute distance between _a and _b. template <class N> inline N diff(N const& _a, N const& _b) { return std::max(_a, _b) - std::min(_a, _b); } /// RAII utility class whose destructor calls a given function. class ScopeGuard { public: ScopeGuard(std::function<void(void)> _f): m_f(_f) {} ~ScopeGuard() { m_f(); } private: std::function<void(void)> m_f; }; /// Inheritable for classes that have invariants. class HasInvariants { public: /// Reimplement to specify the invariants. virtual bool invariants() const = 0; }; /// RAII checker for invariant assertions. class InvariantChecker { public: InvariantChecker(HasInvariants* _this, char const* _fn, char const* _file, int _line): m_this(_this), m_function(_fn), m_file(_file), m_line(_line) { checkInvariants(_this, _fn , _file, _line, true); } ~InvariantChecker() { checkInvariants(m_this, m_function, m_file, m_line, false); } /// Check invariants are met, throw if not. static void checkInvariants(HasInvariants const* _this, char const* _fn, char const* _file, int line, bool _pre); private: HasInvariants const* m_this; char const* m_function; char const* m_file; int m_line; }; /// Scope guard for invariant check in a class derived from HasInvariants. #if ETH_DEBUG #define DEV_INVARIANT_CHECK ::dev::InvariantChecker __dev_invariantCheck(this, BOOST_CURRENT_FUNCTION, __FILE__, __LINE__) #define DEV_INVARIANT_CHECK_HERE ::dev::InvariantChecker::checkInvariants(this, BOOST_CURRENT_FUNCTION, __FILE__, __LINE__, true) #else #define DEV_INVARIANT_CHECK (void)0; #define DEV_INVARIANT_CHECK_HERE (void)0; #endif /// Simple scope-based timer helper. class TimerHelper { public: TimerHelper(std::string const& _id, unsigned _msReportWhenGreater = 0): m_t(std::chrono::high_resolution_clock::now()), m_id(_id), m_ms(_msReportWhenGreater) {} ~TimerHelper(); private: std::chrono::high_resolution_clock::time_point m_t; std::string m_id; unsigned m_ms; }; class Timer { public: Timer() { restart(); } std::chrono::high_resolution_clock::duration duration() const { return std::chrono::high_resolution_clock::now() - m_t; } double elapsed() const { return std::chrono::duration_cast<std::chrono::microseconds>(duration()).count() / 1000000.0; } void restart() { m_t = std::chrono::high_resolution_clock::now(); } private: std::chrono::high_resolution_clock::time_point m_t; }; #define DEV_TIMED(S) for (::std::pair<::dev::TimerHelper, bool> __eth_t(S, true); __eth_t.second; __eth_t.second = false) #define DEV_TIMED_SCOPE(S) ::dev::TimerHelper __eth_t(S) #if defined(_WIN32) #define DEV_TIMED_FUNCTION DEV_TIMED_SCOPE(__FUNCSIG__) #else #define DEV_TIMED_FUNCTION DEV_TIMED_SCOPE(__PRETTY_FUNCTION__) #endif #define DEV_TIMED_ABOVE(S, MS) for (::std::pair<::dev::TimerHelper, bool> __eth_t(::dev::TimerHelper(S, MS), true); __eth_t.second; __eth_t.second = false) #define DEV_TIMED_SCOPE_ABOVE(S, MS) ::dev::TimerHelper __eth_t(S, MS) #if defined(_WIN32) #define DEV_TIMED_FUNCTION_ABOVE(MS) DEV_TIMED_SCOPE_ABOVE(__FUNCSIG__, MS) #else #define DEV_TIMED_FUNCTION_ABOVE(MS) DEV_TIMED_SCOPE_ABOVE(__PRETTY_FUNCTION__, MS) #endif #ifdef _MSC_VER // TODO. #define DEV_UNUSED #else #define DEV_UNUSED __attribute__((unused)) #endif enum class WithExisting: int { Trust = 0, Verify, Rescue, Kill }; /// Get the current time in seconds since the epoch in UTC uint64_t utcTime(); } namespace std { inline dev::WithExisting max(dev::WithExisting _a, dev::WithExisting _b) { return static_cast<dev::WithExisting>(max(static_cast<int>(_a), static_cast<int>(_b))); } template <> struct hash<dev::u256> { size_t operator()(dev::u256 const& _a) const { unsigned size = _a.backend().size(); auto limbs = _a.backend().limbs(); return boost::hash_range(limbs, limbs + size); } }; }
ZiberLTD/windows
microsip/blockchain/libdevcore/Common.h
C
gpl-2.0
10,487
<?php /** * @version 1.0.0 * @package com_somosmaestros * @copyright Copyright (C) 2015. Todos los derechos reservados. * @license Licencia Pública General GNU versión 2 o posterior. Consulte LICENSE.txt * @author Daniel Gustavo Álvarez Gaitán <info@danielalvarez.com.co> - http://danielalvarez.com.co */ // No direct access defined('_JEXEC') or die; /** * blog Table class */ class SomosmaestrosTableblog extends JTable { /** * Constructor * * @param JDatabase A database connector object */ public function __construct(&$db) { parent::__construct('#__somosmaestros_blogs', 'id', $db); } /** * Overloaded bind function to pre-process the params. * * @param array Named array * * @return null|string null is operation was satisfactory, otherwise returns an error * @see JTable:bind * @since 1.5 */ public function bind($array, $ignore = '') { $input = JFactory::getApplication()->input; $task = $input->getString('task', ''); if(($task == 'save' || $task == 'apply') && (!JFactory::getUser()->authorise('core.edit.state','com_somosmaestros') && $array['state'] == 1)){ $array['state'] = 0; } if($array['id'] == 0){ $array['created_by'] = JFactory::getUser()->id; } //Support for multiple or not foreign key field: categoria if(!empty($array['categoria'])){ if(is_array($array['categoria'])){ $array['categoria'] = implode(',',$array['categoria']); } else if(strrpos($array['categoria'], ',') != false){ $array['categoria'] = explode(',',$array['categoria']); } } else { $array['categoria'] = ''; } if (isset($array['params']) && is_array($array['params'])) { $registry = new JRegistry(); $registry->loadArray($array['params']); $array['params'] = (string) $registry; } if (isset($array['metadata']) && is_array($array['metadata'])) { $registry = new JRegistry(); $registry->loadArray($array['metadata']); $array['metadata'] = (string) $registry; } if (!JFactory::getUser()->authorise('core.admin', 'com_somosmaestros.blog.' . $array['id'])) { $actions = JFactory::getACL()->getActions('com_somosmaestros', 'blog'); $default_actions = JFactory::getACL()->getAssetRules('com_somosmaestros.blog.' . $array['id'])->getData(); $array_jaccess = array(); foreach ($actions as $action) { $array_jaccess[$action->name] = $default_actions[$action->name]; } $array['rules'] = $this->JAccessRulestoArray($array_jaccess); } //Bind the rules for ACL where supported. if (isset($array['rules']) && is_array($array['rules'])) { $this->setRules($array['rules']); } return parent::bind($array, $ignore); } /** * This function convert an array of JAccessRule objects into an rules array. * * @param type $jaccessrules an arrao of JAccessRule objects. */ private function JAccessRulestoArray($jaccessrules) { $rules = array(); foreach ($jaccessrules as $action => $jaccess) { $actions = array(); foreach ($jaccess->getData() as $group => $allow) { $actions[$group] = ((bool) $allow); } $rules[$action] = $actions; } return $rules; } /** * Overloaded check function */ public function check() { //If there is an ordering column and this is a new row then get the next ordering value if (property_exists($this, 'ordering') && $this->id == 0) { $this->ordering = self::getNextOrder(); } return parent::check(); } /** * Method to set the publishing state for a row or list of rows in the database * table. The method respects checked out rows by other users and will attempt * to checkin rows that it can after adjustments are made. * * @param mixed An optional array of primary key values to update. If not * set the instance property value is used. * @param integer The publishing state. eg. [0 = unpublished, 1 = published] * @param integer The user id of the user performing the operation. * * @return boolean True on success. * @since 1.0.4 */ public function publish($pks = null, $state = 1, $userId = 0) { // Initialise variables. $k = $this->_tbl_key; // Sanitize input. JArrayHelper::toInteger($pks); $userId = (int) $userId; $state = (int) $state; // If there are no primary keys set check to see if the instance key is set. if (empty($pks)) { if ($this->$k) { $pks = array($this->$k); } // Nothing to set publishing state on, return false. else { $this->setError(JText::_('JLIB_DATABASE_ERROR_NO_ROWS_SELECTED')); return false; } } // Build the WHERE clause for the primary keys. $where = $k . '=' . implode(' OR ' . $k . '=', $pks); // Determine if there is checkin support for the table. if (!property_exists($this, 'checked_out') || !property_exists($this, 'checked_out_time')) { $checkin = ''; } else { $checkin = ' AND (checked_out = 0 OR checked_out = ' . (int) $userId . ')'; } // Update the publishing state for rows with the given primary keys. $this->_db->setQuery( 'UPDATE `' . $this->_tbl . '`' . ' SET `state` = ' . (int) $state . ' WHERE (' . $where . ')' . $checkin ); $this->_db->execute(); // If checkin is supported and all rows were adjusted, check them in. if ($checkin && (count($pks) == $this->_db->getAffectedRows())) { // Checkin each row. foreach ($pks as $pk) { $this->checkin($pk); } } // If the JTable instance value is in the list of primary keys that were set, set the instance. if (in_array($this->$k, $pks)) { $this->state = $state; } $this->setError(''); return true; } /** * Define a namespaced asset name for inclusion in the #__assets table * @return string The asset name * * @see JTable::_getAssetName */ protected function _getAssetName() { $k = $this->_tbl_key; return 'com_somosmaestros.blog.' . (int) $this->$k; } /** * Returns the parent asset's id. If you have a tree structure, retrieve the parent's id using the external key field * * @see JTable::_getAssetParentId */ protected function _getAssetParentId(JTable $table = null, $id = null) { // We will retrieve the parent-asset from the Asset-table $assetParent = JTable::getInstance('Asset'); // Default: if no asset-parent can be found we take the global asset $assetParentId = $assetParent->getRootId(); // The item has the component as asset-parent $assetParent->loadByName('com_somosmaestros'); // Return the found asset-parent-id if ($assetParent->id) { $assetParentId = $assetParent->id; } return $assetParentId; } public function delete($pk = null) { $this->load($pk); $result = parent::delete($pk); if ($result) { } return $result; } }
emeraldstudio/somosmaestros
administrator/components/com_somosmaestros/tables/blog.php
PHP
gpl-2.0
6,849
""" Function-like objects that creates cubic clusters. """ import numpy as np from ase.data import reference_states as _refstate from ase.cluster.factory import ClusterFactory class SimpleCubicFactory(ClusterFactory): spacegroup = 221 xtal_name = 'sc' def get_lattice_constant(self): "Get the lattice constant of an element with cubic crystal structure." symmetry = _refstate[self.atomic_numbers[0]]['symmetry'] if symmetry != self.xtal_name: raise ValueError, ("Cannot guess the %s " % (self.xtal_name,) + "lattice constant of an element with crystal " + "structure %s." % (symmetry,)) return _refstate[self.atomic_numbers[0]]['a'] def set_basis(self): a = self.lattice_constant if not isinstance(a, (int, float)): raise ValueError("Improper lattice constant for %s crystal." % (self.xtal_name,)) self.lattice_basis = np.array([[a, 0., 0.], [0., a, 0.], [0., 0., a]]) self.resiproc_basis = self.get_resiproc_basis(self.lattice_basis) SimpleCubic = SimpleCubicFactory() class BodyCenteredCubicFactory(SimpleCubicFactory): xtal_name = 'bcc' atomic_basis = np.array([[0., 0., 0.], [.5, .5, .5]]) BodyCenteredCubic = BodyCenteredCubicFactory() class FaceCenteredCubicFactory(SimpleCubicFactory): xtal_name = 'fcc' atomic_basis = np.array([[0., 0., 0.], [0., .5, .5], [.5, 0., .5], [.5, .5, 0.]]) FaceCenteredCubic = FaceCenteredCubicFactory()
JConwayAWT/PGSS14CC
lib/python/multimetallics/ase/cluster/cubic.py
Python
gpl-2.0
1,732
<div <?php if(!isMobile()) { ?> id="sidebar" <? } ?>> <ul> <?php echo "<li id=search-2 class=widget widget_search>"; if(function_exists('webonary_searchform')) { webonary_searchform(); } echo "</li>"; //if(is_page() && is_active_sidebar('sidebar-pages')) : dynamic_sidebar('sidebar-pages'); if(is_active_sidebar('sidebar-pages')) : dynamic_sidebar('sidebar-pages'); //elseif(is_active_sidebar('sidebar-blog')) : dynamic_sidebar('sidebar-blog'); endif; ?> </ul> </div>
rick-maclean/webonaryLinuxCopy
wp-content/themes/webonary-zeedisplay/sidebar.php
PHP
gpl-2.0
486
/* This file is part of the KDE libraries Copyright (C) 2004-2005 Anders Lund <anders@alweb.dk> Copyright (C) 2002 John Firebaugh <jfirebaugh@kde.org> Copyright (C) 2001-2004 Christoph Cullmann <cullmann@kde.org> Copyright (C) 2001 Joseph Wenninger <jowenn@kde.org> Copyright (C) 1999 Jochen Wilhelmy <digisnap@cs.tu-berlin.de> This library is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License version 2 as published by the Free Software Foundation. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Library General Public License for more details. You should have received a copy of the GNU Library General Public License along with this library; see the file COPYING.LIB. If not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #ifndef __KATE_SPELL_H__ #define __KATE_SPELL_H__ #include "katecursor.h" class KateView; class KAction; class KSpell; class KateSpell : public QObject { Q_OBJECT public: KateSpell(KateView *); ~KateSpell(); void createActions(KActionCollection *); void updateActions(); // spellcheck from cursor, selection private slots: void spellcheckFromCursor(); // defined here in anticipation of pr view selections ;) void spellcheckSelection(); void spellcheck(); /** * Spellcheck a defined portion of the text. * * @param from Where to start the check * @param to Where to end. If this is (0,0), it will be set to the end of the document. */ void spellcheck(const KateTextCursor &from, const KateTextCursor &to = KateTextCursor()); void ready(KSpell *); void misspelling(const QString &, const QStringList &, unsigned int); void corrected(const QString &, const QString &, unsigned int); void spellResult(const QString &); void spellCleanDone(); void locatePosition(uint pos, uint &line, uint &col); private: KateView *m_view; KAction *m_spellcheckSelection; KSpell *m_kspell; // define the part of the text to check KateTextCursor m_spellStart, m_spellEnd; // keep track of where we are. KateTextCursor m_spellPosCursor; uint m_spellLastPos; }; #endif // kate: space-indent on; indent-width 2; replace-tabs on;
serghei/kde3-kdelibs
kate/part/katespell.h
C
gpl-2.0
2,499
<?php namespace Whisper\Tests\ScalarMerge; use Whisper\Tests\Common\BaseTest; use Whisper\DoctrineEntityMerger\Merger; class RelationMergeTest extends BaseTest { const RELATION_MERGE_ENTITY = 'Whisper\Tests\Entity\Family'; protected $fixtureFile = 'LoadFamilyData'; public function testFamilySurnameMerge() { $families = $this->entityManager ->getRepository(self::RELATION_MERGE_ENTITY) ->findBy(['surname' => 'Schmidt']); // it should be 3 Schmidts at first time $this->assertCount(3, $families); $merger = new Merger(); $merger->setEntityManager($this->entityManager); $merger->merge(self::RELATION_MERGE_ENTITY, 'surname'); $mergedFamilies = $this->entityManager ->getRepository(self::RELATION_MERGE_ENTITY) ->findBy(['surname' => 'Schmidt']); // now there should be only 1 John with merged info from 2 records $this->assertCount(1, $mergedFamilies); $this->assertCount(4, $mergedFamilies[0]->getPeople()); $this->assertSame('green', $mergedFamilies[0]->getColour()->getName()); $this->assertCount(2, $mergedFamilies[0]->getTags()); $this->assertSame('cool', $mergedFamilies[0]->getTags()[0]->getName()); $this->assertSame('great', $mergedFamilies[0]->getTags()[1]->getName()); } }
davidvartanian/DoctrineEntityMerger
src/Tests/RelationMerge/RelationMergeTest.php
PHP
gpl-2.0
1,378
/* * Created on 16-May-2004 * Created by Paul Gardner * Copyright (C) 2004, 2005, 2006 Aelitis, All Rights Reserved. * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. * * AELITIS, SAS au capital de 46,603.30 euros * 8 Allee Lenotre, La Grille Royale, 78600 Le Mesnil le Roi, France. * */ package org.gudy.azureus2.pluginsimpl.local.update; /** * @author parg * */ import com.aelitis.azureus.core.update.AzureusRestarter; import com.aelitis.azureus.core.update.AzureusRestarterFactory; import org.gudy.azureus2.core3.internat.MessageText; import org.gudy.azureus2.core3.logging.LogAlert; import org.gudy.azureus2.core3.logging.Logger; import org.gudy.azureus2.core3.util.*; import org.gudy.azureus2.platform.PlatformManager; import org.gudy.azureus2.platform.PlatformManagerCapabilities; import org.gudy.azureus2.platform.PlatformManagerFactory; import org.gudy.azureus2.plugins.update.UpdateException; import org.gudy.azureus2.plugins.update.UpdateInstaller; import org.gudy.azureus2.plugins.update.UpdateInstallerListener; import java.io.*; public class UpdateInstallerImpl implements UpdateInstaller { // change these and you'll need to change the Updater!!!! protected static final String UPDATE_DIR = "updates"; protected static final String ACTIONS_LEGACY = "install.act"; protected static final String ACTIONS_UTF8 = "install.act.utf8"; protected static AEMonitor class_mon = new AEMonitor( "UpdateInstaller:class" ); private UpdateManagerImpl manager; private File install_dir; protected static void checkForFailedInstalls( UpdateManagerImpl manager ) { try{ File update_dir = new File( manager.getUserDir() + File.separator + UPDATE_DIR ); File[] dirs = update_dir.listFiles(); if ( dirs != null ){ boolean found_failure = false; String files = ""; for (int i=0;i<dirs.length;i++){ File dir = dirs[i]; if ( dir.isDirectory()){ // if somethings here then the install failed found_failure = true; File[] x = dir.listFiles(); if ( x != null ){ for (int j=0;j<x.length;j++){ files += (files.length()==0?"":",") + x[j].getName(); } } FileUtil.recursiveDelete( dir ); } } if ( found_failure ){ Logger.log(new LogAlert(LogAlert.UNREPEATABLE, LogAlert.AT_ERROR, MessageText.getString("Alert.failed.update", new String[]{ files }))); } } }catch( Throwable e ){ Debug.printStackTrace( e ); } } protected UpdateInstallerImpl( UpdateManagerImpl _manager ) throws UpdateException { manager = _manager; try{ class_mon.enter(); // updates are in general user-specific (e.g. plugin updates) so store here // obviously core ones will affect all users String update_dir = getUserDir() + File.separator + UPDATE_DIR; for (int i=1;i<1024;i++){ File try_dir = new File( update_dir + File.separator + "inst_" + i ); if ( !try_dir.exists()){ if ( !FileUtil.mkdirs(try_dir)){ throw( new UpdateException( "Failed to create a temporary installation dir")); } install_dir = try_dir; break; } } if ( install_dir == null ){ throw( new UpdateException( "Failed to find a temporary installation dir")); } }finally{ class_mon.exit(); } } public void addResource( String resource_name, InputStream is ) throws UpdateException { addResource(resource_name,is,true); } public void addResource( String resource_name, InputStream is, boolean closeInputStream) throws UpdateException { try{ File target_file = new File(install_dir, resource_name ); FileUtil.copyFile( is, new FileOutputStream( target_file ),closeInputStream); }catch( Throwable e ){ throw( new UpdateException( "UpdateInstaller: resource addition fails", e )); } } public String getInstallDir() { return( manager.getInstallDir()); } public String getUserDir() { return( manager.getUserDir()); } public void addMoveAction( String from_file_or_resource, String to_file ) throws UpdateException { // System.out.println( "move action:" + from_file_or_resource + " -> " + to_file ); if ( from_file_or_resource.indexOf(File.separator) == -1 ){ from_file_or_resource = install_dir.toString() + File.separator + from_file_or_resource; } try{ // see if this action has a chance of succeeding File to_f = new File( to_file ); File parent = to_f.getParentFile(); if ( parent != null && !parent.exists()){ parent.mkdirs(); } boolean log_perm_set_fail = true; if ( parent != null ){ // we're going to need write access to the parent, let's try if ( !parent.canWrite()){ log_perm_set_fail = false; // Vista install process goes through permissions elevation process // so don't warn about lack of write permissions if ( !Constants.isWindowsVistaOrHigher ){ Logger.log(new LogAlert(LogAlert.UNREPEATABLE, LogAlert.AT_WARNING, "The location '" + parent.toString() + "' isn't writable, this update will probably fail." + " Check permissions and retry the update")); } } } try{ PlatformManager pm = PlatformManagerFactory.getPlatformManager(); if ( pm.hasCapability( PlatformManagerCapabilities.CopyFilePermissions )){ String parent_str = parent.getAbsolutePath(); PlatformManagerFactory.getPlatformManager().copyFilePermissions( parent_str, from_file_or_resource ); } }catch( Throwable e ){ if ( log_perm_set_fail ){ if ( !Constants.isWindowsVistaOrHigher ){ Debug.out( e ); } } } }catch( Throwable e ){ } from_file_or_resource = escapeFile( from_file_or_resource ); to_file = escapeFile( to_file ); appendAction( "move," + from_file_or_resource + "," + to_file ); } public void addChangeRightsAction( String rights, String to_file ) throws UpdateException { to_file = escapeFile( to_file ); appendAction( "chmod," + rights + "," + to_file ); } public void addRemoveAction( String file ) throws UpdateException { file = escapeFile( file ); appendAction( "remove," + file ); } private String escapeFile( String file ) { if ( file.contains( "," )){ // needs support in Updater... to fix :( Debug.out( "Installation is going to fail for '" + file + "' as ',' in name not supported" ); } return( file ); } protected void appendAction( String data ) throws UpdateException { PrintWriter pw_legacy = null; try{ pw_legacy = new PrintWriter(new FileWriter( install_dir.toString() + File.separator + ACTIONS_LEGACY, true )); pw_legacy.println( data ); }catch( Throwable e ){ throw( new UpdateException( "Failed to write actions file", e )); }finally{ if ( pw_legacy != null ){ try{ pw_legacy.close(); }catch( Throwable e ){ throw( new UpdateException( "Failed to write actions file", e )); } } } PrintWriter pw_utf8 = null; try{ pw_utf8 = new PrintWriter( new OutputStreamWriter( new FileOutputStream( install_dir.toString() + File.separator + ACTIONS_UTF8, true ), "UTF-8" )); pw_utf8.println( data ); }catch( Throwable e ){ throw( new UpdateException( "Failed to write actions file", e )); }finally{ if ( pw_utf8 != null ){ try{ pw_utf8.close(); }catch( Throwable e ){ throw( new UpdateException( "Failed to write actions file", e )); } } } } public void installNow( final UpdateInstallerListener listener ) throws UpdateException { try{ UpdateInstaller[] installers = manager.getInstallers(); if ( installers.length != 1 || installers[0] != this ){ throw( new UpdateException( "Other installers exist - aborting" )); } listener.reportProgress( "Update starts" ); AzureusRestarter ar = AzureusRestarterFactory.create( manager.getCore()); ar.updateNow(); new AEThread2( "installNow:waiter", true ) { public void run() { try{ long start = SystemTime.getMonotonousTime(); UpdateException pending_error = null; while( true ){ Thread.sleep( 1000 ); listener.reportProgress( "Checking progress" ); if ( !install_dir.exists()){ break; } File fail_file = new File( install_dir, "install.fail" ); if ( fail_file.exists()){ try{ String error = FileUtil.readFileAsString( fail_file, 1024 ); throw( new UpdateException( error )); }catch( Throwable e ){ if ( e instanceof UpdateException ){ throw( e ); } if ( pending_error != null ){ throw( pending_error ); } pending_error = new UpdateException( "Install failed, reason unknown" ); } } if ( SystemTime.getMonotonousTime() - start >= 5*60*1000 ){ listener.reportProgress( "Timeout" ); throw( new UpdateException( "Timeout waiting for update to apply" )); } } listener.reportProgress( "Complete" ); listener.complete(); }catch( Throwable e ){ UpdateException fail; if ( e instanceof UpdateException ){ fail = (UpdateException)e; }else{ fail = new UpdateException( "install failed", e ); } listener.reportProgress( fail.getMessage()); listener.failed( fail ); }finally{ deleteInstaller(); } } }.start(); }catch( Throwable e ){ deleteInstaller(); UpdateException fail; if ( e instanceof UpdateException ){ fail = (UpdateException)e; }else{ fail = new UpdateException( "install failed", e ); } listener.reportProgress( fail.getMessage()); listener.failed( fail ); throw( fail ); } } public void destroy() { deleteInstaller(); } private void deleteInstaller() { manager.removeInstaller( this ); if ( install_dir.exists()){ FileUtil.recursiveDelete( install_dir ); } } }
thangbn/Direct-File-Downloader
src/src/org/gudy/azureus2/pluginsimpl/local/update/UpdateInstallerImpl.java
Java
gpl-2.0
11,382
<?php /* Template Name: Blog Posts */ ?> <?php get_header(); ?> <div id="content"> <div id="inner-content"> <main id="main" class="m-all t-2of3 cf" role="main" itemscope itemprop="mainContentOfPage" itemtype="http://schema.org/Blog"> <?php if (have_posts()) : while (have_posts()) : the_post(); ?> <div class="block-alt"> <a href="<?php the_permalink() ?>" rel="bookmark" title="<?php the_title_attribute(); ?>"> <h3><?php the_title(); ?></h3> <?php if ( has_post_thumbnail() ) { the_post_thumbnail('full'); } else { the_excerpt(); } ?> </a> </div> <?php endwhile; ?> <?php bones_page_navi(); ?> <?php else : ?> <article id="post-<?php the_ID(); ?>" <?php post_class( 'cf' ); ?> role="article" itemscope itemtype="http://schema.org/BlogPosting"> <section class="entry-content cf" itemprop="articleBody"> <br><br><br> <div class="center block fancy" style="width: 60%; font-size: 120%"> <div class="block-content"> <strong>No content found.</strong> <p>Please check back soon!</p> </div> </div> </article> <?php endif; ?> </main> <?php get_sidebar(); ?> </div> </div> <?php get_footer(); ?>
lintseed/pourvous
wp-content/themes/pourvous/blog.php
PHP
gpl-2.0
1,459
#pragma once #include <valuelib/debug/demangle.hpp> #include <typeinfo> #include <typeindex> namespace value { namespace debug { template<> struct printer<demangled_string> { decltype(auto) operator()(std::ostream& os, demangled_string const& s) const { return os << std::quoted(std::string(s)); } }; template<> struct printer<std::type_info> { decltype(auto) operator()(std::ostream& os, std::type_info const& ti) const { return os << std::quoted(std::string(demangle(ti))); } }; template<> struct printer<std::type_index> { decltype(auto) operator()(std::ostream& os, std::type_index const& ti) const { return os << std::quoted(std::string(demangle(ti))); } }; }}
madmongo1/valuelib
debug/include/valuelib/debug/typeinfo.hpp
C++
gpl-2.0
836
#!/usr/bin/python3 import math import random def finding_prime(number): num=abs(number) if num<4: return True for x in range(2,num): if num%x == 0: return False return True def finding_prime_sqrt(number): num=abs(number) if num<4: return True for x in range(2,int(math.sqrt(num))+1): if number%x == 0: return False return True def finding_prime_fermat(number): if number<=102: for a in range(2,number): if pow(a,number-1,number)!=1: return False return True else: for i in range(100): a=random.randint(2,number-1) if pow(a,number-1,number)!=1: return False return True def test_finding_prime(): number1=17 number2=20 assert(finding_prime(number1)==True) assert(finding_prime(number2)==False) assert(finding_prime_sqrt(number1)==True) assert(finding_prime_sqrt(number2)==False) assert(finding_prime_fermat(number1)==True) assert(finding_prime_fermat(number2)==False) print('Tests passed!') if __name__=='__main__': test_finding_prime()
Urinx/SomeCodes
Python/others/practice/finding_if_prime.py
Python
gpl-2.0
995
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>numpy.dtype.newbyteorder &mdash; NumPy v1.10 Manual</title> <link rel="stylesheet" type="text/css" href="../../static_/css/spc-bootstrap.css"> <link rel="stylesheet" type="text/css" href="../../static_/css/spc-extend.css"> <link rel="stylesheet" href="../../static_/scipy.css" type="text/css" > <link rel="stylesheet" href="../../static_/pygments.css" type="text/css" > <script type="text/javascript"> var DOCUMENTATION_OPTIONS = { URL_ROOT: '../../', VERSION: '1.10.1', COLLAPSE_INDEX: false, FILE_SUFFIX: '.html', HAS_SOURCE: false }; </script> <script type="text/javascript" src="../../static_/jquery.js"></script> <script type="text/javascript" src="../../static_/underscore.js"></script> <script type="text/javascript" src="../../static_/doctools.js"></script> <script type="text/javascript" src="../../static_/js/copybutton.js"></script> <link rel="author" title="About these documents" href="../../about.html" > <link rel="top" title="NumPy v1.10 Manual" href="../../index.html" > <link rel="up" title="numpy.dtype" href="numpy.dtype.html" > <link rel="next" title="numpy.format_parser" href="numpy.format_parser.html" > <link rel="prev" title="numpy.dtype.subdtype" href="numpy.dtype.subdtype.html" > </head> <body> <div class="container"> <div class="header"> </div> </div> <div class="container"> <div class="main"> <div class="row-fluid"> <div class="span12"> <div class="spc-navbar"> <ul class="nav nav-pills pull-left"> <li class="active"><a href="../../index.html">NumPy v1.10 Manual</a></li> <li class="active"><a href="../index.html" >NumPy Reference</a></li> <li class="active"><a href="../routines.html" >Routines</a></li> <li class="active"><a href="../routines.dtype.html" >Data type routines</a></li> <li class="active"><a href="numpy.dtype.html" accesskey="U">numpy.dtype</a></li> </ul> <ul class="nav nav-pills pull-right"> <li class="active"> <a href="../../genindex.html" title="General Index" accesskey="I">index</a> </li> <li class="active"> <a href="numpy.format_parser.html" title="numpy.format_parser" accesskey="N">next</a> </li> <li class="active"> <a href="numpy.dtype.subdtype.html" title="numpy.dtype.subdtype" accesskey="P">previous</a> </li> </ul> </div> </div> </div> <div class="row-fluid"> <div class="spc-rightsidebar span3"> <div class="sphinxsidebarwrapper"> <h4>Previous topic</h4> <p class="topless"><a href="numpy.dtype.subdtype.html" title="previous chapter">numpy.dtype.subdtype</a></p> <h4>Next topic</h4> <p class="topless"><a href="numpy.format_parser.html" title="next chapter">numpy.format_parser</a></p> </div> </div> <div class="span9"> <div class="bodywrapper"> <div class="body" id="spc-section-body"> <div class="section" id="numpy-dtype-newbyteorder"> <h1>numpy.dtype.newbyteorder<a class="headerlink" href="#numpy-dtype-newbyteorder" title="Permalink to this headline">¶</a></h1> <dl class="method"> <dt id="numpy.dtype.newbyteorder"> <tt class="descclassname">dtype.</tt><tt class="descname">newbyteorder</tt><big>(</big><em>new_order='S'</em><big>)</big><a class="headerlink" href="#numpy.dtype.newbyteorder" title="Permalink to this definition">¶</a></dt> <dd><p>Return a new dtype with a different byte order.</p> <p>Changes are also made in all fields and sub-arrays of the data type.</p> <table class="docutils field-list" frame="void" rules="none"> <col class="field-name" /> <col class="field-body" /> <tbody valign="top"> <tr class="field-odd field"><th class="field-name">Parameters:</th><td class="field-body"><p class="first"><strong>new_order</strong> : string, optional</p> <blockquote> <div><p>Byte order to force; a value from the byte order specifications below. The default value (&#8216;S&#8217;) results in swapping the current byte order. <em class="xref py py-obj">new_order</em> codes can be any of:</p> <div class="highlight-python"><div class="highlight"><pre>* &#39;S&#39; - swap dtype from current to opposite endian * {&#39;&lt;&#39;, &#39;L&#39;} - little endian * {&#39;&gt;&#39;, &#39;B&#39;} - big endian * {&#39;=&#39;, &#39;N&#39;} - native order * {&#39;|&#39;, &#39;I&#39;} - ignore (no change to byte order) </pre></div> </div> <p>The code does a case-insensitive check on the first letter of <em class="xref py py-obj">new_order</em> for these alternatives. For example, any of &#8216;&gt;&#8217; or &#8216;B&#8217; or &#8216;b&#8217; or &#8216;brian&#8217; are valid to specify big-endian.</p> </div></blockquote> </td> </tr> <tr class="field-even field"><th class="field-name">Returns:</th><td class="field-body"><p class="first"><strong>new_dtype</strong> : dtype</p> <blockquote class="last"> <div><p>New dtype object with the given change to the byte order.</p> </div></blockquote> </td> </tr> </tbody> </table> <p class="rubric">Notes</p> <p>Changes are also made in all fields and sub-arrays of the data type.</p> <p class="rubric">Examples</p> <div class="highlight-python"><div class="highlight"><pre><span class="gp">&gt;&gt;&gt; </span><span class="kn">import</span> <span class="nn">sys</span> <span class="gp">&gt;&gt;&gt; </span><span class="n">sys_is_le</span> <span class="o">=</span> <span class="n">sys</span><span class="o">.</span><span class="n">byteorder</span> <span class="o">==</span> <span class="s">&#39;little&#39;</span> <span class="gp">&gt;&gt;&gt; </span><span class="n">native_code</span> <span class="o">=</span> <span class="n">sys_is_le</span> <span class="ow">and</span> <span class="s">&#39;&lt;&#39;</span> <span class="ow">or</span> <span class="s">&#39;&gt;&#39;</span> <span class="gp">&gt;&gt;&gt; </span><span class="n">swapped_code</span> <span class="o">=</span> <span class="n">sys_is_le</span> <span class="ow">and</span> <span class="s">&#39;&gt;&#39;</span> <span class="ow">or</span> <span class="s">&#39;&lt;&#39;</span> <span class="gp">&gt;&gt;&gt; </span><span class="n">native_dt</span> <span class="o">=</span> <span class="n">np</span><span class="o">.</span><span class="n">dtype</span><span class="p">(</span><span class="n">native_code</span><span class="o">+</span><span class="s">&#39;i2&#39;</span><span class="p">)</span> <span class="gp">&gt;&gt;&gt; </span><span class="n">swapped_dt</span> <span class="o">=</span> <span class="n">np</span><span class="o">.</span><span class="n">dtype</span><span class="p">(</span><span class="n">swapped_code</span><span class="o">+</span><span class="s">&#39;i2&#39;</span><span class="p">)</span> <span class="gp">&gt;&gt;&gt; </span><span class="n">native_dt</span><span class="o">.</span><span class="n">newbyteorder</span><span class="p">(</span><span class="s">&#39;S&#39;</span><span class="p">)</span> <span class="o">==</span> <span class="n">swapped_dt</span> <span class="go">True</span> <span class="gp">&gt;&gt;&gt; </span><span class="n">native_dt</span><span class="o">.</span><span class="n">newbyteorder</span><span class="p">()</span> <span class="o">==</span> <span class="n">swapped_dt</span> <span class="go">True</span> <span class="gp">&gt;&gt;&gt; </span><span class="n">native_dt</span> <span class="o">==</span> <span class="n">swapped_dt</span><span class="o">.</span><span class="n">newbyteorder</span><span class="p">(</span><span class="s">&#39;S&#39;</span><span class="p">)</span> <span class="go">True</span> <span class="gp">&gt;&gt;&gt; </span><span class="n">native_dt</span> <span class="o">==</span> <span class="n">swapped_dt</span><span class="o">.</span><span class="n">newbyteorder</span><span class="p">(</span><span class="s">&#39;=&#39;</span><span class="p">)</span> <span class="go">True</span> <span class="gp">&gt;&gt;&gt; </span><span class="n">native_dt</span> <span class="o">==</span> <span class="n">swapped_dt</span><span class="o">.</span><span class="n">newbyteorder</span><span class="p">(</span><span class="s">&#39;N&#39;</span><span class="p">)</span> <span class="go">True</span> <span class="gp">&gt;&gt;&gt; </span><span class="n">native_dt</span> <span class="o">==</span> <span class="n">native_dt</span><span class="o">.</span><span class="n">newbyteorder</span><span class="p">(</span><span class="s">&#39;|&#39;</span><span class="p">)</span> <span class="go">True</span> <span class="gp">&gt;&gt;&gt; </span><span class="n">np</span><span class="o">.</span><span class="n">dtype</span><span class="p">(</span><span class="s">&#39;&lt;i2&#39;</span><span class="p">)</span> <span class="o">==</span> <span class="n">native_dt</span><span class="o">.</span><span class="n">newbyteorder</span><span class="p">(</span><span class="s">&#39;&lt;&#39;</span><span class="p">)</span> <span class="go">True</span> <span class="gp">&gt;&gt;&gt; </span><span class="n">np</span><span class="o">.</span><span class="n">dtype</span><span class="p">(</span><span class="s">&#39;&lt;i2&#39;</span><span class="p">)</span> <span class="o">==</span> <span class="n">native_dt</span><span class="o">.</span><span class="n">newbyteorder</span><span class="p">(</span><span class="s">&#39;L&#39;</span><span class="p">)</span> <span class="go">True</span> <span class="gp">&gt;&gt;&gt; </span><span class="n">np</span><span class="o">.</span><span class="n">dtype</span><span class="p">(</span><span class="s">&#39;&gt;i2&#39;</span><span class="p">)</span> <span class="o">==</span> <span class="n">native_dt</span><span class="o">.</span><span class="n">newbyteorder</span><span class="p">(</span><span class="s">&#39;&gt;&#39;</span><span class="p">)</span> <span class="go">True</span> <span class="gp">&gt;&gt;&gt; </span><span class="n">np</span><span class="o">.</span><span class="n">dtype</span><span class="p">(</span><span class="s">&#39;&gt;i2&#39;</span><span class="p">)</span> <span class="o">==</span> <span class="n">native_dt</span><span class="o">.</span><span class="n">newbyteorder</span><span class="p">(</span><span class="s">&#39;B&#39;</span><span class="p">)</span> <span class="go">True</span> </pre></div> </div> </dd></dl> </div> </div> </div> </div> </div> </div> </div> <div class="container container-navbar-bottom"> <div class="spc-navbar"> </div> </div> <div class="container"> <div class="footer"> <div class="row-fluid"> <ul class="inline pull-left"> <li> &copy; Copyright 2008-2009, The Scipy community. </li> <li> Last updated on Oct 18, 2015. </li> <li> Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 1.2.1. </li> </ul> </div> </div> </div> </body> </html>
platinhom/ManualHom
Coding/Python/numpy-html-1.10.1/reference/generated/numpy.dtype.newbyteorder.html
HTML
gpl-2.0
11,186
--- title: Server-side CSV Export --- # CSV Export in server-side code This project shows how to export the Kendo UI Grid data as a CSV (comma separated value) file. [CSV Export Server-side](https://github.com/telerik/ui-for-aspnet-mvc-examples/tree/master/grid/csv-export-server-side)
cuongnd/test_pro
media/kendo-ui-core-master/docs/aspnet-mvc/helpers/grid/how-to/csv-export-server-side.md
Markdown
gpl-2.0
289
#include "MaterialNode.hpp" #include "NodeVisitor.hpp" bool MaterialNode::accept(NodeVisitor& visitor) { if(visitor.visit(*this)) { for(std::list<SceneNode*>::iterator i = lstChildren.begin(); i != lstChildren.end(); i++) { if(!(*i)->accept(visitor)) { std::cerr << "Error in traversel of: " << *this << std::endl; break; } } } return true; }
eulcey/Wumpus-OGL
deps/scenegraph/MaterialNode.cpp
C++
gpl-2.0
376
using System; namespace HerhangiOT.ServerLibrary.Utility { public class Rsa { protected static BigInteger N; protected static BigInteger D; protected static BigInteger Me = new BigInteger("65537", 10); public static bool SetKey(string p, string q) { Logger.LogOperationStart("Setting up RSA encyption"); BigInteger mP, mQ; try { mP = new BigInteger(p, 10); mQ = new BigInteger(q, 10); } catch (Exception) { Logger.LogOperationFailed("P,Q value could not be parsed!"); return false; } N = mP * mQ; BigInteger mod = (mP - 1)*(mQ - 1); D = Me.ModInverse(mod); Logger.LogOperationDone(); return true; } public static void Encrypt(ref byte[] buffer, int index) { byte[] temp = new byte[128]; Array.Copy(buffer, index, temp, 0, 128); BigInteger input = new BigInteger(temp); BigInteger output = input.modPow(Me, N); Array.Copy(GetPaddedValue(output), 0, buffer, index, 128); } public static void Decrypt(ref byte[] buffer, int index) { byte[] temp = new byte[128]; Array.Copy(buffer, index, temp, 0, 128); BigInteger input = new BigInteger(temp); BigInteger output = input.modPow(D, N); Array.Copy(GetPaddedValue(output), 0, buffer, index, 128); } private static byte[] GetPaddedValue(BigInteger value) { byte[] result = value.getBytes(); const int length = (1024 >> 3); if (result.Length >= length) return result; // left-pad 0x00 value on the result (same integer, correct length) byte[] padded = new byte[length]; Buffer.BlockCopy(result, 0, padded, (length - result.Length), result.Length); // temporary result may contain decrypted (plaintext) data, clear it Array.Clear(result, 0, result.Length); return padded; } } }
Herhangi/HerhangiOT
ServerLibrary/Utility/Rsa.cs
C#
gpl-2.0
2,267
Rails.application.routes.draw do root 'main#home' get 'about' => 'main#about' get 'contact' => 'main#contact' get 'dashboard' => 'main#dashboard' resources :users get 'signup' => 'users#new' get 'login' => 'sessions#new' post 'login' => 'sessions#create' delete 'logout' => 'sessions#destroy' resources :account_activations, only: [:edit] get 'sessions/new' get 'resend_activation_email' => 'users#resend_activation_email' resources :password_resets, only: [:new, :create, :edit, :update] get 'password_resets/new' get 'password_resets/edit' # The priority is based upon order of creation: first created -> highest priority. # See how all your routes lay out with "rake routes". # Example of regular route: # get 'products/:id' => 'catalog#view' # Example of named route that can be invoked with purchase_url(id: product.id) # get 'products/:id/purchase' => 'catalog#purchase', as: :purchase # Example resource route (maps HTTP verbs to controller actions automatically): # resources :products # Example resource route with options: # resources :products do # member do # get 'short' # post 'toggle' # end # # collection do # get 'sold' # end # end # Example resource route with sub-resources: # resources :products do # resources :comments, :sales # resource :seller # end # Example resource route with more complex sub-resources: # resources :products do # resources :comments # resources :sales do # get 'recent', on: :collection # end # end # Example resource route with concerns: # concern :toggleable do # post 'toggle' # end # resources :posts, concerns: :toggleable # resources :photos, concerns: :toggleable # Example resource route within a namespace: # namespace :admin do # # Directs /admin/products/* to Admin::ProductsController # # (app/controllers/admin/products_controller.rb) # resources :products # end end
ebelter/userauth
config/routes.rb
Ruby
gpl-2.0
2,076
/* GeneratorListener: callbacks for GeneratorStream. $Id: GeneratorListener.java,v 1.2 2003/07/20 04:26:13 rsdio Exp $ Copyright (C) 2003 Casey Marshall <rsdio@metastatic.org> This file is a part of Jarsync. Jarsync is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. Jarsync 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 Jarsync; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA Linking Jarsync statically or dynamically with other modules is making a combined work based on Jarsync. Thus, the terms and conditions of the GNU General Public License cover the whole combination. As a special exception, the copyright holders of Jarsync give you permission to link Jarsync with independent modules to produce an executable, regardless of the license terms of these independent modules, and to copy and distribute the resulting executable under terms of your choice, provided that you also meet, for each linked independent module, the terms and conditions of the license of that module. An independent module is a module which is not derived from or based on Jarsync. If you modify Jarsync, you may extend this exception to your version of it, but you are not obligated to do so. If you do not wish to do so, delete this exception statement from your version. */ package org.metastatic.rsync; import java.util.EventListener; /** * Standard interface for the checksum generator callback, called by * {@link GeneratorStream} when new checksum pairs are ready. * * @version $Revision: 1.2 $ */ public interface GeneratorListener extends EventListener { /** * Update with a single, new checksum pair. * * @param event The event containing the next checksum pair. */ void update(GeneratorEvent event) throws ListenerException; }
Tongbupan/Jarsync
source/org/metastatic/rsync/GeneratorListener.java
Java
gpl-2.0
2,362
/*- * APT - Analysis of Petri Nets and labeled Transition systems * Copyright (C) 2015 vsp * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ package uniol.apt.analysis.homogeneous; import uniol.apt.adt.pn.Flow; import uniol.apt.adt.pn.PetriNet; import uniol.apt.module.AbstractModule; import uniol.apt.module.AptModule; import uniol.apt.module.Category; import uniol.apt.module.InterruptibleModule; import uniol.apt.module.ModuleInput; import uniol.apt.module.ModuleInputSpec; import uniol.apt.module.ModuleOutput; import uniol.apt.module.ModuleOutputSpec; import uniol.apt.module.exception.ModuleException; import uniol.apt.util.Pair; /** * Checks whether a given plain Petri net is an homogeneous net. * @author vsp */ @AptModule public class HomogeneousModule extends AbstractModule implements InterruptibleModule { @Override public String getName() { return "homogeneous"; } @Override public void require(ModuleInputSpec inputSpec) { inputSpec.addParameter("net", PetriNet.class, "The Petri net that should be examined"); } @Override public void provide(ModuleOutputSpec outputSpec) { outputSpec.addReturnValue("homogeneous", Boolean.class, ModuleOutputSpec.PROPERTY_SUCCESS); outputSpec.addReturnValue("witness1", Flow.class); outputSpec.addReturnValue("witness2", Flow.class); } @Override public void run(ModuleInput input, ModuleOutput output) throws ModuleException { PetriNet pn = input.getParameter("net", PetriNet.class); Homogeneous homogeneous = new Homogeneous(); Pair<Flow, Flow> counterexample = homogeneous.check(pn); output.setReturnValue("homogeneous", Boolean.class, counterexample == null); if (counterexample != null) { output.setReturnValue("witness1", Flow.class, counterexample.getFirst()); output.setReturnValue("witness2", Flow.class, counterexample.getSecond()); } } @Override public String getTitle() { return "Homogeneous"; } @Override public String getShortDescription() { return "Check if a Petri net is homogeneous"; } @Override public String getLongDescription() { return getShortDescription() + ".\n\nA Petri net is an homogeneous net if " + "∀p∈P:∀t₁,t₂∈p°: F(p,t₁)=F(p,t₂)"; } @Override public Category[] getCategories() { return new Category[]{Category.PN}; } } // vim: ft=java:noet:sw=8:sts=8:ts=8:tw=120
CvO-Theory/apt
src/module/uniol/apt/analysis/homogeneous/HomogeneousModule.java
Java
gpl-2.0
3,020
# encoding: utf-8 # module _dbus_bindings # from /usr/lib/python2.7/dist-packages/_dbus_bindings.so # by generator 1.135 """ Low-level Python bindings for libdbus. Don't use this module directly - the public API is provided by the `dbus`, `dbus.service`, `dbus.mainloop` and `dbus.mainloop.glib` modules, with a lower-level API provided by the `dbus.lowlevel` module. """ # imports import dbus.lowlevel as __dbus_lowlevel from _LongBase import _LongBase class UInt64(_LongBase): """ An unsigned 64-bit integer between 0 and 0xFFFF FFFF FFFF FFFF, represented as a subtype of `long`. This type only exists on platforms where the C compiler has suitable 64-bit types, such as C99 ``unsigned long long``. Constructor:: dbus.UInt64(value: long[, variant_level: int]) -> UInt64 ``value`` must be within the allowed range, or `OverflowError` will be raised. ``variant_level`` must be non-negative; the default is 0. :IVariables: `variant_level` : int Indicates how many nested Variant containers this object is contained in: if a message's wire format has a variant containing a variant containing a uint64, this is represented in Python by a UInt64 with variant_level==2. """ def __init__(self, value, variant_level=None): # real signature unknown; restored from __doc__ pass @staticmethod # known case of __new__ def __new__(S, *more): # real signature unknown; restored from __doc__ """ T.__new__(S, ...) -> a new object with type S, a subtype of T """ pass
ProfessorX/Config
.PyCharm30/system/python_stubs/-1247972723/_dbus_bindings/UInt64.py
Python
gpl-2.0
1,618
/* * Copyright 2010 Red Hat Inc. * * Permission is hereby granted, free of charge, to any person obtaining a * copy of this software and associated documentation files (the "Software"), * to deal in the Software without restriction, including without limitation * the rights to use, copy, modify, merge, publish, distribute, sublicense, * and/or sell copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL * THE COPYRIGHT HOLDER(S) OR AUTHOR(S) BE LIABLE FOR ANY CLAIM, DAMAGES OR * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR * OTHER DEALINGS IN THE SOFTWARE. * * Authors: Ben Skeggs */ #include "drmP.h" #include "nouveau_drv.h" #include "nouveau_mm.h" static void nvc0_fifo_isr(struct drm_device *); struct nvc0_fifo_priv { struct nouveau_gpuobj *playlist[2]; int cur_playlist; struct nouveau_vma user_vma; int spoon_nr; }; struct nvc0_fifo_chan { struct nouveau_gpuobj *user; struct nouveau_gpuobj *ramfc; }; static void nvc0_fifo_playlist_update(struct drm_device *dev) { struct drm_nouveau_private *dev_priv = dev->dev_private; struct nouveau_instmem_engine *pinstmem = &dev_priv->engine.instmem; struct nouveau_fifo_engine *pfifo = &dev_priv->engine.fifo; struct nvc0_fifo_priv *priv = pfifo->priv; struct nouveau_gpuobj *cur; int i, p; cur = priv->playlist[priv->cur_playlist]; priv->cur_playlist = !priv->cur_playlist; for (i = 0, p = 0; i < 128; i++) { if (!(nv_rd32(dev, 0x3004 + (i * 8)) & 1)) continue; nv_wo32(cur, p + 0, i); nv_wo32(cur, p + 4, 0x00000004); p += 8; } pinstmem->flush(dev); nv_wr32(dev, 0x002270, cur->vinst >> 12); nv_wr32(dev, 0x002274, 0x01f00000 | (p >> 3)); if (!nv_wait(dev, 0x00227c, 0x00100000, 0x00000000)) NV_ERROR(dev, "PFIFO - playlist update failed\n"); } void nvc0_fifo_disable(struct drm_device *dev) { } void nvc0_fifo_enable(struct drm_device *dev) { } bool nvc0_fifo_reassign(struct drm_device *dev, bool enable) { return false; } bool nvc0_fifo_cache_pull(struct drm_device *dev, bool enable) { return false; } int nvc0_fifo_channel_id(struct drm_device *dev) { return 127; } int nvc0_fifo_create_context(struct nouveau_channel *chan) { struct drm_device *dev = chan->dev; struct drm_nouveau_private *dev_priv = dev->dev_private; struct nouveau_instmem_engine *pinstmem = &dev_priv->engine.instmem; struct nouveau_fifo_engine *pfifo = &dev_priv->engine.fifo; struct nvc0_fifo_priv *priv = pfifo->priv; struct nvc0_fifo_chan *fifoch; u64 ib_virt = chan->pushbuf_base + chan->dma.ib_base * 4; int ret; chan->fifo_priv = kzalloc(sizeof(*fifoch), GFP_KERNEL); if (!chan->fifo_priv) return -ENOMEM; fifoch = chan->fifo_priv; /* allocate vram for control regs, map into polling area */ ret = nouveau_gpuobj_new(dev, NULL, 0x1000, 0x1000, NVOBJ_FLAG_ZERO_ALLOC, &fifoch->user); if (ret) goto error; nouveau_vm_map_at(&priv->user_vma, chan->id * 0x1000, *(struct nouveau_mem **)fifoch->user->node); chan->user = ioremap_wc(pci_resource_start(dev->pdev, 1) + priv->user_vma.offset + (chan->id * 0x1000), PAGE_SIZE); if (!chan->user) { ret = -ENOMEM; goto error; } /* ramfc */ ret = nouveau_gpuobj_new_fake(dev, chan->ramin->pinst, chan->ramin->vinst, 0x100, NVOBJ_FLAG_ZERO_ALLOC, &fifoch->ramfc); if (ret) goto error; nv_wo32(fifoch->ramfc, 0x08, lower_32_bits(fifoch->user->vinst)); nv_wo32(fifoch->ramfc, 0x0c, upper_32_bits(fifoch->user->vinst)); nv_wo32(fifoch->ramfc, 0x10, 0x0000face); nv_wo32(fifoch->ramfc, 0x30, 0xfffff902); nv_wo32(fifoch->ramfc, 0x48, lower_32_bits(ib_virt)); nv_wo32(fifoch->ramfc, 0x4c, drm_order(chan->dma.ib_max + 1) << 16 | upper_32_bits(ib_virt)); nv_wo32(fifoch->ramfc, 0x54, 0x00000002); nv_wo32(fifoch->ramfc, 0x84, 0x20400000); nv_wo32(fifoch->ramfc, 0x94, 0x30000001); nv_wo32(fifoch->ramfc, 0x9c, 0x00000100); nv_wo32(fifoch->ramfc, 0xa4, 0x1f1f1f1f); nv_wo32(fifoch->ramfc, 0xa8, 0x1f1f1f1f); nv_wo32(fifoch->ramfc, 0xac, 0x0000001f); nv_wo32(fifoch->ramfc, 0xb8, 0xf8000000); nv_wo32(fifoch->ramfc, 0xf8, 0x10003080); /* 0x002310 */ nv_wo32(fifoch->ramfc, 0xfc, 0x10000010); /* 0x002350 */ pinstmem->flush(dev); nv_wr32(dev, 0x003000 + (chan->id * 8), 0xc0000000 | (chan->ramin->vinst >> 12)); nv_wr32(dev, 0x003004 + (chan->id * 8), 0x001f0001); nvc0_fifo_playlist_update(dev); return 0; error: pfifo->destroy_context(chan); return ret; } void nvc0_fifo_destroy_context(struct nouveau_channel *chan) { struct drm_device *dev = chan->dev; struct nvc0_fifo_chan *fifoch; nv_mask(dev, 0x003004 + (chan->id * 8), 0x00000001, 0x00000000); nv_wr32(dev, 0x002634, chan->id); if (!nv_wait(dev, 0x0002634, 0xffffffff, chan->id)) NV_WARN(dev, "0x2634 != chid: 0x%08x\n", nv_rd32(dev, 0x2634)); nvc0_fifo_playlist_update(dev); nv_wr32(dev, 0x003000 + (chan->id * 8), 0x00000000); if (chan->user) { iounmap(chan->user); chan->user = NULL; } fifoch = chan->fifo_priv; chan->fifo_priv = NULL; if (!fifoch) return; nouveau_gpuobj_ref(NULL, &fifoch->ramfc); nouveau_gpuobj_ref(NULL, &fifoch->user); kfree(fifoch); } int nvc0_fifo_load_context(struct nouveau_channel *chan) { return 0; } int nvc0_fifo_unload_context(struct drm_device *dev) { int i; for (i = 0; i < 128; i++) { if (!(nv_rd32(dev, 0x003004 + (i * 8)) & 1)) continue; nv_mask(dev, 0x003004 + (i * 8), 0x00000001, 0x00000000); nv_wr32(dev, 0x002634, i); if (!nv_wait(dev, 0x002634, 0xffffffff, i)) { NV_INFO(dev, "PFIFO: kick ch %d failed: 0x%08x\n", i, nv_rd32(dev, 0x002634)); return -EBUSY; } } return 0; } static void nvc0_fifo_destroy(struct drm_device *dev) { struct drm_nouveau_private *dev_priv = dev->dev_private; struct nouveau_fifo_engine *pfifo = &dev_priv->engine.fifo; struct nvc0_fifo_priv *priv; priv = pfifo->priv; if (!priv) return; nouveau_vm_put(&priv->user_vma); nouveau_gpuobj_ref(NULL, &priv->playlist[1]); nouveau_gpuobj_ref(NULL, &priv->playlist[0]); kfree(priv); } void nvc0_fifo_takedown(struct drm_device *dev) { nv_wr32(dev, 0x002140, 0x00000000); nvc0_fifo_destroy(dev); } static int nvc0_fifo_create(struct drm_device *dev) { struct drm_nouveau_private *dev_priv = dev->dev_private; struct nouveau_fifo_engine *pfifo = &dev_priv->engine.fifo; struct nvc0_fifo_priv *priv; int ret; priv = kzalloc(sizeof(*priv), GFP_KERNEL); if (!priv) return -ENOMEM; pfifo->priv = priv; ret = nouveau_gpuobj_new(dev, NULL, 0x1000, 0x1000, 0, &priv->playlist[0]); if (ret) goto error; ret = nouveau_gpuobj_new(dev, NULL, 0x1000, 0x1000, 0, &priv->playlist[1]); if (ret) goto error; ret = nouveau_vm_get(dev_priv->bar1_vm, pfifo->channels * 0x1000, 12, NV_MEM_ACCESS_RW, &priv->user_vma); if (ret) goto error; nouveau_irq_register(dev, 8, nvc0_fifo_isr); NVOBJ_CLASS(dev, 0x506e, SW); /* nvsw */ return 0; error: nvc0_fifo_destroy(dev); return ret; } int nvc0_fifo_init(struct drm_device *dev) { struct drm_nouveau_private *dev_priv = dev->dev_private; struct nouveau_fifo_engine *pfifo = &dev_priv->engine.fifo; struct nouveau_channel *chan; struct nvc0_fifo_priv *priv; int ret, i; if (!pfifo->priv) { ret = nvc0_fifo_create(dev); if (ret) return ret; } priv = pfifo->priv; /* reset PFIFO, enable all available PSUBFIFO areas */ nv_mask(dev, 0x000200, 0x00000100, 0x00000000); nv_mask(dev, 0x000200, 0x00000100, 0x00000100); nv_wr32(dev, 0x000204, 0xffffffff); nv_wr32(dev, 0x002204, 0xffffffff); priv->spoon_nr = hweight32(nv_rd32(dev, 0x002204)); NV_DEBUG(dev, "PFIFO: %d subfifo(s)\n", priv->spoon_nr); /* assign engines to subfifos */ if (priv->spoon_nr >= 3) { nv_wr32(dev, 0x002208, ~(1 << 0)); /* PGRAPH */ nv_wr32(dev, 0x00220c, ~(1 << 1)); /* PVP */ nv_wr32(dev, 0x002210, ~(1 << 1)); /* PPP */ nv_wr32(dev, 0x002214, ~(1 << 1)); /* PBSP */ nv_wr32(dev, 0x002218, ~(1 << 2)); /* PCE0 */ nv_wr32(dev, 0x00221c, ~(1 << 1)); /* PCE1 */ } /* PSUBFIFO[n] */ for (i = 0; i < priv->spoon_nr; i++) { nv_mask(dev, 0x04013c + (i * 0x2000), 0x10000100, 0x00000000); nv_wr32(dev, 0x040108 + (i * 0x2000), 0xffffffff); /* INTR */ nv_wr32(dev, 0x04010c + (i * 0x2000), 0xfffffeff); /* INTR_EN */ } nv_mask(dev, 0x002200, 0x00000001, 0x00000001); nv_wr32(dev, 0x002254, 0x10000000 | priv->user_vma.offset >> 12); nv_wr32(dev, 0x002a00, 0xffffffff); /* clears PFIFO.INTR bit 30 */ nv_wr32(dev, 0x002100, 0xffffffff); nv_wr32(dev, 0x002140, 0xbfffffff); /* restore PFIFO context table */ for (i = 0; i < 128; i++) { chan = dev_priv->channels.ptr[i]; if (!chan || !chan->fifo_priv) continue; nv_wr32(dev, 0x003000 + (i * 8), 0xc0000000 | (chan->ramin->vinst >> 12)); nv_wr32(dev, 0x003004 + (i * 8), 0x001f0001); } nvc0_fifo_playlist_update(dev); return 0; } struct nouveau_enum nvc0_fifo_fault_unit[] = { { 0x00, "PGRAPH" }, { 0x03, "PEEPHOLE" }, { 0x04, "BAR1" }, { 0x05, "BAR3" }, { 0x07, "PFIFO" }, { 0x10, "PBSP" }, { 0x11, "PPPP" }, { 0x13, "PCOUNTER" }, { 0x14, "PVP" }, { 0x15, "PCOPY0" }, { 0x16, "PCOPY1" }, { 0x17, "PDAEMON" }, {} }; struct nouveau_enum nvc0_fifo_fault_reason[] = { { 0x00, "PT_NOT_PRESENT" }, { 0x01, "PT_TOO_SHORT" }, { 0x02, "PAGE_NOT_PRESENT" }, { 0x03, "VM_LIMIT_EXCEEDED" }, { 0x04, "NO_CHANNEL" }, { 0x05, "PAGE_SYSTEM_ONLY" }, { 0x06, "PAGE_READ_ONLY" }, { 0x0a, "COMPRESSED_SYSRAM" }, { 0x0c, "INVALID_STORAGE_TYPE" }, {} }; struct nouveau_enum nvc0_fifo_fault_hubclient[] = { { 0x01, "PCOPY0" }, { 0x02, "PCOPY1" }, { 0x04, "DISPATCH" }, { 0x05, "CTXCTL" }, { 0x06, "PFIFO" }, { 0x07, "BAR_READ" }, { 0x08, "BAR_WRITE" }, { 0x0b, "PVP" }, { 0x0c, "PPPP" }, { 0x0d, "PBSP" }, { 0x11, "PCOUNTER" }, { 0x12, "PDAEMON" }, { 0x14, "CCACHE" }, { 0x15, "CCACHE_POST" }, {} }; struct nouveau_enum nvc0_fifo_fault_gpcclient[] = { { 0x01, "TEX" }, { 0x0c, "ESETUP" }, { 0x0e, "CTXCTL" }, { 0x0f, "PROP" }, {} }; struct nouveau_bitfield nvc0_fifo_subfifo_intr[] = { /* { 0x00008000, "" } seen with null ib push */ { 0x00200000, "ILLEGAL_MTHD" }, { 0x00800000, "EMPTY_SUBC" }, {} }; static void nvc0_fifo_isr_vm_fault(struct drm_device *dev, int unit) { u32 inst = nv_rd32(dev, 0x2800 + (unit * 0x10)); u32 valo = nv_rd32(dev, 0x2804 + (unit * 0x10)); u32 vahi = nv_rd32(dev, 0x2808 + (unit * 0x10)); u32 stat = nv_rd32(dev, 0x280c + (unit * 0x10)); u32 client = (stat & 0x00001f00) >> 8; NV_INFO(dev, "PFIFO: %s fault at 0x%010llx [", (stat & 0x00000080) ? "write" : "read", (u64)vahi << 32 | valo); nouveau_enum_print(nvc0_fifo_fault_reason, stat & 0x0000000f); printk("] from "); nouveau_enum_print(nvc0_fifo_fault_unit, unit); if (stat & 0x00000040) { printk("/"); nouveau_enum_print(nvc0_fifo_fault_hubclient, client); } else { printk("/GPC%d/", (stat & 0x1f000000) >> 24); nouveau_enum_print(nvc0_fifo_fault_gpcclient, client); } printk(" on channel 0x%010llx\n", (u64)inst << 12); } static int nvc0_fifo_page_flip(struct drm_device *dev, u32 chid) { struct drm_nouveau_private *dev_priv = dev->dev_private; struct nouveau_channel *chan = NULL; unsigned long flags; int ret = -EINVAL; spin_lock_irqsave(&dev_priv->channels.lock, flags); if (likely(chid >= 0 && chid < dev_priv->engine.fifo.channels)) { chan = dev_priv->channels.ptr[chid]; if (likely(chan)) ret = nouveau_finish_page_flip(chan, NULL); } spin_unlock_irqrestore(&dev_priv->channels.lock, flags); return ret; } static void nvc0_fifo_isr_subfifo_intr(struct drm_device *dev, int unit) { u32 stat = nv_rd32(dev, 0x040108 + (unit * 0x2000)); u32 addr = nv_rd32(dev, 0x0400c0 + (unit * 0x2000)); u32 data = nv_rd32(dev, 0x0400c4 + (unit * 0x2000)); u32 chid = nv_rd32(dev, 0x040120 + (unit * 0x2000)) & 0x7f; u32 subc = (addr & 0x00070000); u32 mthd = (addr & 0x00003ffc); u32 show = stat; if (stat & 0x00200000) { if (mthd == 0x0054) { if (!nvc0_fifo_page_flip(dev, chid)) show &= ~0x00200000; } } if (show) { NV_INFO(dev, "PFIFO%d:", unit); nouveau_bitfield_print(nvc0_fifo_subfifo_intr, show); NV_INFO(dev, "PFIFO%d: ch %d subc %d mthd 0x%04x data 0x%08x\n", unit, chid, subc, mthd, data); } nv_wr32(dev, 0x0400c0 + (unit * 0x2000), 0x80600008); nv_wr32(dev, 0x040108 + (unit * 0x2000), stat); } static void nvc0_fifo_isr(struct drm_device *dev) { u32 stat = nv_rd32(dev, 0x002100); if (stat & 0x00000100) { NV_INFO(dev, "PFIFO: unknown status 0x00000100\n"); nv_wr32(dev, 0x002100, 0x00000100); stat &= ~0x00000100; } if (stat & 0x10000000) { u32 units = nv_rd32(dev, 0x00259c); u32 u = units; while (u) { int i = ffs(u) - 1; nvc0_fifo_isr_vm_fault(dev, i); u &= ~(1 << i); } nv_wr32(dev, 0x00259c, units); stat &= ~0x10000000; } if (stat & 0x20000000) { u32 units = nv_rd32(dev, 0x0025a0); u32 u = units; while (u) { int i = ffs(u) - 1; nvc0_fifo_isr_subfifo_intr(dev, i); u &= ~(1 << i); } nv_wr32(dev, 0x0025a0, units); stat &= ~0x20000000; } if (stat & 0x40000000) { NV_INFO(dev, "PFIFO: unknown status 0x40000000\n"); nv_mask(dev, 0x002a00, 0x00000000, 0x00000000); stat &= ~0x40000000; } if (stat) { NV_INFO(dev, "PFIFO: unhandled status 0x%08x\n", stat); nv_wr32(dev, 0x002100, stat); nv_wr32(dev, 0x002140, 0); } }
Jackeagle/android_kernel_sony_c2305
drivers/gpu/drm/nouveau/nvc0_fifo.c
C
gpl-2.0
14,346
/* * Copyright 2009-2015 Contributors (see credits.txt) * * This file is part of jEveAssets. * * jEveAssets is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * jEveAssets 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 jEveAssets; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. * */ package net.nikr.eve.jeveasset.gui.tabs.routing; import java.util.ArrayList; import java.util.List; import net.nikr.eve.jeveasset.gui.tabs.routing.mocks.FakeRoutingTab; import net.nikr.eve.jeveasset.gui.tabs.routing.mocks.RoutingMockProgram; import net.nikr.eve.jeveasset.tests.mocks.FakeProgress; import org.apache.log4j.Level; import org.apache.log4j.Logger; import org.junit.AfterClass; import static org.junit.Assert.assertEquals; import org.junit.BeforeClass; import org.junit.Test; import uk.me.candle.eve.graph.Node; import uk.me.candle.eve.routing.BruteForce; import uk.me.candle.eve.routing.NearestNeighbour; import uk.me.candle.eve.routing.RoutingAlgorithm; /** * * @author Candle */ public class TestRouting { @BeforeClass public static void setUpClass() throws Exception { Logger.getRootLogger().setLevel(Level.OFF); } @AfterClass public static void tearDownClass() throws Exception { Logger.getRootLogger().setLevel(Level.INFO); } @Test public void empty() { } private List<String> getErentaList() { /* * Erenta * Haajinen * Kakakela * Kiskoken * Oipo * Torrinos * Umokka */ List<String> waypointNames = new ArrayList<String>(); waypointNames.add("Erenta"); waypointNames.add("Haajinen"); waypointNames.add("Kakakela"); waypointNames.add("Kiskoken"); waypointNames.add("Oipo"); waypointNames.add("Torrinos"); waypointNames.add("Umokka"); return waypointNames; } @Test public void testErentaBF() { testRoute(getErentaList(), new BruteForce(), 40); } @Test public void testErentaNN() { testRoute(getErentaList(), new NearestNeighbour(), 42); } private void testRoute(final List<String> waypointNames, final RoutingAlgorithm ra, final int exptectedDistance) { FakeRoutingTab frd = new FakeRoutingTab(new RoutingMockProgram(), null, ra); frd.buildTestGraph(); List<Node> initial = frd.getNodesFromNames(waypointNames); List<Node> routeBF = ra.execute(new FakeProgress(), frd.getGraph(), new ArrayList<Node>(initial)); for (int i = 0; i < initial.size(); ++i) { System.out.println(i + " " + initial.get(i)); } short[][] distances = ra.getLastDistanceMatrix(); for (int i = 0; i < distances.length; ++i) { System.out.print("" + i + ":"); for (int j = 0; j < distances[i].length && j <= i; ++j) { String id = "" + distances[i][j]; switch (id.length()) { // HAAAAAX. case 1: id = " " + id; break; case 2: id = " " + id; break; case 3: id = "" + id; break; } System.out.print(" " + id); } System.out.println(); } for (Node n : routeBF) { System.out.println(n + "(" + initial.indexOf(n) + ")"); } System.out.println("Length: " + ra.getLastDistance()); assertEquals(exptectedDistance, ra.getLastDistance()); } // @Test - skipped 'cause it takes too long. public void testArtisineBF() { testRoute(getArtisineList(), new BruteForce(), 61); } @Test public void testArtisineNN() { testRoute(getArtisineList(), new NearestNeighbour(), 63); } private List<String> getArtisineList() { /* * Artisine * Deltole * Jolia * Doussivitte * Misneden * Bawilan * Ney * Stegette * Odette * Inghenges * Sileperer */ List<String> waypointNames = new ArrayList<String>(); waypointNames.add("Artisine"); waypointNames.add("Deltole"); waypointNames.add("Jolia"); waypointNames.add("Doussivitte"); waypointNames.add("Misneden"); waypointNames.add("Bawilan"); waypointNames.add("Ney"); waypointNames.add("Stegette"); waypointNames.add("Odette"); waypointNames.add("Inghenges"); waypointNames.add("Sileperer"); return waypointNames; } }
stiez/jeveassets
src/test/java/net/nikr/eve/jeveasset/gui/tabs/routing/TestRouting.java
Java
gpl-2.0
4,482
<?php defined( '_VALID_MOS' ) or die( 'Direct Access to this location is not allowed.' ); /** * * @version $Id: coupon.coupon_field.php 617 2007-01-04 19:43:08Z soeren_nb $ * @package VirtueMart * @subpackage html * @copyright Copyright (C) 2004-2005 Soeren Eberhardt. All rights reserved. * @license http://www.gnu.org/copyleft/gpl.html GNU/GPL, see LICENSE.php * VirtueMart is free software. This version may have been modified pursuant * to the GNU General Public License, and as distributed it includes or * is derivative of works licensed under the GNU General Public License or * other free or open source software licenses. * See /administrator/components/com_virtuemart/COPYRIGHT.php for copyright notices and details. * @author Erich Vinson * http://virtuemart.net */ mm_showMyFileName( __FILE__ ); global $page, $sess; echo "<table width=\"100%\"><tr class=\"sectiontableentry1\"><td width=\"100%\">"; if (@$_SESSION['invalid_coupon'] == true) { echo "<strong>" . $VM_LANG->_PHPSHOP_COUPON_CODE_INVALID . "</strong><br />"; } if( !empty($_REQUEST['coupon_error']) ) { echo mosGetParam($_REQUEST, 'coupon_error', '')."<br />"; } echo $VM_LANG->_PHPSHOP_COUPON_ENTER_HERE . "<br /> <form action=\"".$mm_action_url . "index.php\" method=\"post\"> <input type=\"text\" name=\"coupon_code\" width=\"10\" maxlength=\"30\" class=\"inputbox\" /> <input type=\"hidden\" name=\"Itemid\" value=\"".$sess->getShopItemid()."\" /> <input type=\"hidden\" name=\"do_coupon\" value=\"yes\" /> <input type=\"hidden\" name=\"option\" value=\"$option\" /> <input type=\"hidden\" name=\"page\" value=\"".$page."\" /> <input type=\"submit\" value=\"" . $PHPSHOP_LANG->_PHPSHOP_COUPON_SUBMIT_BUTTON . "\" class=\"button\" /> </form> </td> </tr></table>"; ?>
foresitegroup/sherwin
administrator/components/com_virtuemart/html/coupon.coupon_field.php
PHP
gpl-2.0
1,780