text
stringlengths
2
1.04M
meta
dict
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <!-- NewPage --> <html lang="en"> <head> <!-- Generated by javadoc (version 1.7.0_21) on Sun Jul 28 12:47:49 EDT 2013 --> <meta http-equiv="Content-Type" content="text/html" charset="UTF-8"> <title>Uses of Interface com.thinkaurelius.titan.graphdb.transaction.addedrelations.AddedRelationsContainer (Titan-Site: Static Webpages and Docs 0.3.2 API)</title> <meta name="date" content="2013-07-28"> <link rel="stylesheet" type="text/css" href="../../../../../../../stylesheet.css" title="Style"> </head> <body> <script type="text/javascript"><!-- if (location.href.indexOf('is-external=true') == -1) { parent.document.title="Uses of Interface com.thinkaurelius.titan.graphdb.transaction.addedrelations.AddedRelationsContainer (Titan-Site: Static Webpages and Docs 0.3.2 API)"; } //--> </script> <noscript> <div>JavaScript is disabled on your browser.</div> </noscript> <!-- ========= START OF TOP NAVBAR ======= --> <div class="topNav"><a name="navbar_top"> <!-- --> </a><a href="#skip-navbar_top" title="Skip navigation links"></a><a name="navbar_top_firstrow"> <!-- --> </a> <ul class="navList" title="Navigation"> <li><a href="../../../../../../../overview-summary.html">Overview</a></li> <li><a href="../package-summary.html">Package</a></li> <li><a href="../../../../../../../com/thinkaurelius/titan/graphdb/transaction/addedrelations/AddedRelationsContainer.html" title="interface in com.thinkaurelius.titan.graphdb.transaction.addedrelations">Class</a></li> <li class="navBarCell1Rev">Use</li> <li><a href="../package-tree.html">Tree</a></li> <li><a href="../../../../../../../deprecated-list.html">Deprecated</a></li> <li><a href="../../../../../../../index-all.html">Index</a></li> <li><a href="../../../../../../../help-doc.html">Help</a></li> </ul> </div> <div class="subNav"> <ul class="navList"> <li>Prev</li> <li>Next</li> </ul> <ul class="navList"> <li><a href="../../../../../../../index.html?com/thinkaurelius/titan/graphdb/transaction/addedrelations/class-use/AddedRelationsContainer.html" target="_top">Frames</a></li> <li><a href="AddedRelationsContainer.html" target="_top">No Frames</a></li> </ul> <ul class="navList" id="allclasses_navbar_top"> <li><a href="../../../../../../../allclasses-noframe.html">All Classes</a></li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_top"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } //--> </script> </div> <a name="skip-navbar_top"> <!-- --> </a></div> <!-- ========= END OF TOP NAVBAR ========= --> <div class="header"> <h2 title="Uses of Interface com.thinkaurelius.titan.graphdb.transaction.addedrelations.AddedRelationsContainer" class="title">Uses of Interface<br>com.thinkaurelius.titan.graphdb.transaction.addedrelations.AddedRelationsContainer</h2> </div> <div class="classUseContainer"> <ul class="blockList"> <li class="blockList"> <table border="0" cellpadding="3" cellspacing="0" summary="Use table, listing packages, and an explanation"> <caption><span>Packages that use <a href="../../../../../../../com/thinkaurelius/titan/graphdb/transaction/addedrelations/AddedRelationsContainer.html" title="interface in com.thinkaurelius.titan.graphdb.transaction.addedrelations">AddedRelationsContainer</a></span><span class="tabEnd">&nbsp;</span></caption> <tr> <th class="colFirst" scope="col">Package</th> <th class="colLast" scope="col">Description</th> </tr> <tbody> <tr class="altColor"> <td class="colFirst"><a href="#com.thinkaurelius.titan.graphdb.transaction.addedrelations">com.thinkaurelius.titan.graphdb.transaction.addedrelations</a></td> <td class="colLast">&nbsp;</td> </tr> </tbody> </table> </li> <li class="blockList"> <ul class="blockList"> <li class="blockList"><a name="com.thinkaurelius.titan.graphdb.transaction.addedrelations"> <!-- --> </a> <h3>Uses of <a href="../../../../../../../com/thinkaurelius/titan/graphdb/transaction/addedrelations/AddedRelationsContainer.html" title="interface in com.thinkaurelius.titan.graphdb.transaction.addedrelations">AddedRelationsContainer</a> in <a href="../../../../../../../com/thinkaurelius/titan/graphdb/transaction/addedrelations/package-summary.html">com.thinkaurelius.titan.graphdb.transaction.addedrelations</a></h3> <table border="0" cellpadding="3" cellspacing="0" summary="Use table, listing classes, and an explanation"> <caption><span>Classes in <a href="../../../../../../../com/thinkaurelius/titan/graphdb/transaction/addedrelations/package-summary.html">com.thinkaurelius.titan.graphdb.transaction.addedrelations</a> that implement <a href="../../../../../../../com/thinkaurelius/titan/graphdb/transaction/addedrelations/AddedRelationsContainer.html" title="interface in com.thinkaurelius.titan.graphdb.transaction.addedrelations">AddedRelationsContainer</a></span><span class="tabEnd">&nbsp;</span></caption> <tr> <th class="colFirst" scope="col">Modifier and Type</th> <th class="colLast" scope="col">Class and Description</th> </tr> <tbody> <tr class="altColor"> <td class="colFirst"><code>class&nbsp;</code></td> <td class="colLast"><code><strong><a href="../../../../../../../com/thinkaurelius/titan/graphdb/transaction/addedrelations/ConcurrentAddedRelations.html" title="class in com.thinkaurelius.titan.graphdb.transaction.addedrelations">ConcurrentAddedRelations</a></strong></code>&nbsp;</td> </tr> <tr class="rowColor"> <td class="colFirst"><code>class&nbsp;</code></td> <td class="colLast"><code><strong><a href="../../../../../../../com/thinkaurelius/titan/graphdb/transaction/addedrelations/ConcurrentBufferAddedRelations.html" title="class in com.thinkaurelius.titan.graphdb.transaction.addedrelations">ConcurrentBufferAddedRelations</a></strong></code>&nbsp;</td> </tr> <tr class="altColor"> <td class="colFirst"><code>class&nbsp;</code></td> <td class="colLast"><code><strong><a href="../../../../../../../com/thinkaurelius/titan/graphdb/transaction/addedrelations/SimpleAddedRelations.html" title="class in com.thinkaurelius.titan.graphdb.transaction.addedrelations">SimpleAddedRelations</a></strong></code>&nbsp;</td> </tr> <tr class="rowColor"> <td class="colFirst"><code>class&nbsp;</code></td> <td class="colLast"><code><strong><a href="../../../../../../../com/thinkaurelius/titan/graphdb/transaction/addedrelations/SimpleBufferAddedRelations.html" title="class in com.thinkaurelius.titan.graphdb.transaction.addedrelations">SimpleBufferAddedRelations</a></strong></code>&nbsp;</td> </tr> </tbody> </table> <table border="0" cellpadding="3" cellspacing="0" summary="Use table, listing fields, and an explanation"> <caption><span>Fields in <a href="../../../../../../../com/thinkaurelius/titan/graphdb/transaction/addedrelations/package-summary.html">com.thinkaurelius.titan.graphdb.transaction.addedrelations</a> declared as <a href="../../../../../../../com/thinkaurelius/titan/graphdb/transaction/addedrelations/AddedRelationsContainer.html" title="interface in com.thinkaurelius.titan.graphdb.transaction.addedrelations">AddedRelationsContainer</a></span><span class="tabEnd">&nbsp;</span></caption> <tr> <th class="colFirst" scope="col">Modifier and Type</th> <th class="colLast" scope="col">Field and Description</th> </tr> <tbody> <tr class="altColor"> <td class="colFirst"><code>static <a href="../../../../../../../com/thinkaurelius/titan/graphdb/transaction/addedrelations/AddedRelationsContainer.html" title="interface in com.thinkaurelius.titan.graphdb.transaction.addedrelations">AddedRelationsContainer</a></code></td> <td class="colLast"><span class="strong">AddedRelationsContainer.</span><code><strong><a href="../../../../../../../com/thinkaurelius/titan/graphdb/transaction/addedrelations/AddedRelationsContainer.html#EMPTY">EMPTY</a></strong></code>&nbsp;</td> </tr> </tbody> </table> </li> </ul> </li> </ul> </div> <!-- ======= START OF BOTTOM NAVBAR ====== --> <div class="bottomNav"><a name="navbar_bottom"> <!-- --> </a><a href="#skip-navbar_bottom" title="Skip navigation links"></a><a name="navbar_bottom_firstrow"> <!-- --> </a> <ul class="navList" title="Navigation"> <li><a href="../../../../../../../overview-summary.html">Overview</a></li> <li><a href="../package-summary.html">Package</a></li> <li><a href="../../../../../../../com/thinkaurelius/titan/graphdb/transaction/addedrelations/AddedRelationsContainer.html" title="interface in com.thinkaurelius.titan.graphdb.transaction.addedrelations">Class</a></li> <li class="navBarCell1Rev">Use</li> <li><a href="../package-tree.html">Tree</a></li> <li><a href="../../../../../../../deprecated-list.html">Deprecated</a></li> <li><a href="../../../../../../../index-all.html">Index</a></li> <li><a href="../../../../../../../help-doc.html">Help</a></li> </ul> </div> <div class="subNav"> <ul class="navList"> <li>Prev</li> <li>Next</li> </ul> <ul class="navList"> <li><a href="../../../../../../../index.html?com/thinkaurelius/titan/graphdb/transaction/addedrelations/class-use/AddedRelationsContainer.html" target="_top">Frames</a></li> <li><a href="AddedRelationsContainer.html" target="_top">No Frames</a></li> </ul> <ul class="navList" id="allclasses_navbar_bottom"> <li><a href="../../../../../../../allclasses-noframe.html">All Classes</a></li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_bottom"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } //--> </script> </div> <a name="skip-navbar_bottom"> <!-- --> </a></div> <!-- ======== END OF BOTTOM NAVBAR ======= --> <p class="legalCopy"><small>Copyright &#169; 2012&#x2013;2013. All rights reserved.</small></p> </body> </html>
{ "content_hash": "4a54cb9f0a86cfdc153e69b7a7211f28", "timestamp": "", "source": "github", "line_count": 182, "max_line_length": 492, "avg_line_length": 54.12637362637363, "alnum_prop": 0.686427773830068, "repo_name": "greghill/TitanFork", "id": "70b5101e4fbe0cbc373906db0048c8e023891060", "size": "9851", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "doc/javadoc/com/thinkaurelius/titan/graphdb/transaction/addedrelations/class-use/AddedRelationsContainer.html", "mode": "33188", "license": "apache-2.0", "language": [], "symlink_target": "" }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Collections; using System.Data.Common; namespace GlobalcachingApplication.Plugins.IgnoreGeocaches { public class IgnoreService { private static IgnoreService _uniqueInstance = null; private static object _lockObject = new object(); public enum FilterField { GeocacheCode, GeocacheName, GeocacheOwner, } private Hashtable _filterFields = null; private Framework.Interfaces.ICore _core = null; public class FilterFieldPoco { public string field { get; set; } public string filter { get; set; } } private IgnoreService(Framework.Interfaces.ICore core) { _filterFields = new Hashtable(); _core = core; foreach (string s in Enum.GetNames(typeof(FilterField))) { _filterFields.Add(s, new Hashtable()); } try { InitDatabase(core); lock (core.SettingsProvider) { List<FilterFieldPoco> pocos = core.SettingsProvider.Database.Fetch<FilterFieldPoco>(string.Format("select * from {0}", core.SettingsProvider.GetFullTableName("filterfields"))); foreach (var poco in pocos) { Hashtable ht = _filterFields[poco.field] as Hashtable; if (ht != null) { ht.Add(poco.filter, true); } } } } catch { } } public string[] GetFilters(FilterField field) { Hashtable ht = _filterFields[field.ToString()] as Hashtable; if (ht != null) { ArrayList al = new ArrayList(ht.Keys); return ((string[])al.ToArray(typeof(string))); } else { return new string[0]; } } public void Clear() { try { foreach (Hashtable ht in _filterFields.Values) { ht.Clear(); } lock (_core.SettingsProvider) { _core.SettingsProvider.Database.Execute(string.Format("delete from {0}", _core.SettingsProvider.GetFullTableName("filterfields"))); } } catch { } } public void RemoveFilter(FilterField field, string filter) { try { Hashtable ht = _filterFields[field.ToString()] as Hashtable; if (ht != null) { if (ht[filter]!=null) { ht.Remove(filter); lock (_core.SettingsProvider) { _core.SettingsProvider.Database.Execute(string.Format("delete from {2} where field = '{0}' and filter = '{1}'", field.ToString(), filter.Replace("'", "''"), _core.SettingsProvider.GetFullTableName("filterfields"))); } } } } catch { } } public void AddFilter(FilterField field, string filter) { try { Hashtable ht = _filterFields[field.ToString()] as Hashtable; if (ht != null) { if (ht[filter]==null) { ht.Add(filter, true); lock (_core.SettingsProvider) { _core.SettingsProvider.Database.Execute(string.Format("insert into {2} (field, filter) values ('{0}', '{1}')", field.ToString(), filter.Replace("'", "''"), _core.SettingsProvider.GetFullTableName("filterfields"))); } } } } catch { } } public void AddCode(string code) { AddFilter(FilterField.GeocacheCode, code.ToUpper()); } public void AddCodes(List<string> codes) { try { lock (_core.SettingsProvider) { Hashtable ht = _filterFields[FilterField.GeocacheCode.ToString()] as Hashtable; if (ht != null) { foreach (string filter in codes) { if (ht[filter.ToUpper()]==null) { ht.Add(filter.ToUpper(), true); _core.SettingsProvider.Database.Execute(string.Format("insert into {2} (field, filter) values ('{0}', '{1}')", FilterField.GeocacheCode.ToString(), filter.ToUpper().Replace("'", "''"), _core.SettingsProvider.GetFullTableName("filterfields"))); } } } } } catch { } } private void InitDatabase(Framework.Interfaces.ICore core) { try { lock (core.SettingsProvider) { if (!core.SettingsProvider.TableExists(core.SettingsProvider.GetFullTableName("filterfields"))) { core.SettingsProvider.Database.Execute(string.Format("create table '{0}' (field text, filter text)", core.SettingsProvider.GetFullTableName("filterfields"))); } } } catch { } } public static IgnoreService Instance(Framework.Interfaces.ICore core) { if (_uniqueInstance == null) { lock (_lockObject) { if (_uniqueInstance == null) { _uniqueInstance = new IgnoreService(core); } } } return _uniqueInstance; } public bool IgnoreGeocache(string code) { return (_filterFields[FilterField.GeocacheCode.ToString()] as Hashtable)[code] != null; } public bool IgnoreGeocache(Framework.Data.Geocache gc) { bool result = false; if ((_filterFields[FilterField.GeocacheCode.ToString()] as Hashtable)[gc.Code]!=null) { result = true; } else { if (!string.IsNullOrEmpty(gc.Name)) { foreach (string s in (_filterFields[FilterField.GeocacheName.ToString()] as Hashtable).Keys) { if (gc.Name.IndexOf(s, StringComparison.InvariantCultureIgnoreCase) >= 0) { result = true; break; } } } if (!result && !string.IsNullOrEmpty(gc.Owner)) { foreach (string s in (_filterFields[FilterField.GeocacheOwner.ToString()] as Hashtable).Keys) { if (string.Compare(gc.Owner, s, true) == 0) { result = true; break; } } } } return result; } public List<string> FilterGeocaches(List<string> codes) { if (codes != null) { int index = 0; Hashtable ht = _filterFields[FilterField.GeocacheCode.ToString()] as Hashtable; while (index < codes.Count) { if (ht[codes[index]]!=null) { codes.RemoveAt(index); } else { index++; } } } return codes; } } }
{ "content_hash": "e01311509d1547771e68cb2b5ec57a65", "timestamp": "", "source": "github", "line_count": 262, "max_line_length": 275, "avg_line_length": 32.70992366412214, "alnum_prop": 0.4221703617269545, "repo_name": "GlobalcachingEU/GAPP", "id": "7198d520641285e6f033b188bcabb6b1b01ca248", "size": "8572", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "DefaultPlugins/GlobalcachingApplication.Plugins.IgnoreGeocaches/IgnoreService.cs", "mode": "33188", "license": "mit", "language": [ { "name": "Batchfile", "bytes": "356" }, { "name": "C#", "bytes": "28736830" }, { "name": "HTML", "bytes": "1084895" }, { "name": "JavaScript", "bytes": "32372" } ], "symlink_target": "" }
package io.pivotal.pa.simplejms; import java.io.IOException; import java.io.PrintWriter; import javax.inject.Inject; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; @WebServlet(name = "senderServlet", urlPatterns = { "/send-topic-message" }) public class SendTopicServlet extends HttpServlet { private static final long serialVersionUID = 2638127270022516617L; @Inject private Sender sender; protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String retVal = "Sender"; if(sender == null) { retVal = "Sender was null."; sender = new Sender(); } retVal += sender.doSend(); PrintWriter out = response.getWriter(); out.println("Sending message: "+retVal); out.close(); } }
{ "content_hash": "f4bed16d68825dcf973e78878d278c2e", "timestamp": "", "source": "github", "line_count": 38, "max_line_length": 79, "avg_line_length": 24.894736842105264, "alnum_prop": 0.758985200845666, "repo_name": "sdeeg-pivotal/rabbitmq-jms-samples", "id": "a3bdb83caba86ab4891c74a0bae3f60dacd075e0", "size": "946", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "rabbitmq-jms-simple-webapp/src/main/java/io/pivotal/pa/simplejms/SendTopicServlet.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "54438" }, { "name": "Shell", "bytes": "253" } ], "symlink_target": "" }
<?xml version="1.0" ?><!DOCTYPE TS><TS language="it" version="2.1"> <context> <name>AboutDialog</name> <message> <location filename="../forms/aboutdialog.ui" line="+14"/> <source>About Demonic</source> <translation type="unfinished"/> </message> <message> <location line="+39"/> <source>&lt;b&gt;Demonic&lt;/b&gt; version</source> <translation type="unfinished"/> </message> <message> <location line="+41"/> <source>Copyright © 2009-2014 The Bitcoin developers Copyright © 2012-2014 The NovaCoin developers Copyright © 2014 The Demonic developers</source> <translation type="unfinished"/> </message> <message> <location line="+15"/> <source> This is experimental software. Distributed under the MIT/X11 software license, see the accompanying file COPYING or &lt;a href=&quot;http://www.opensource.org/licenses/mit-license.php&quot;&gt;http://www.opensource.org/licenses/mit-license.php&lt;/a&gt;. This product includes software developed by the OpenSSL Project for use in the OpenSSL Toolkit (&lt;a href=&quot;https://www.openssl.org/&quot;&gt;https://www.openssl.org/&lt;/a&gt;) and cryptographic software written by Eric Young (&lt;a href=&quot;mailto:eay@cryptsoft.com&quot;&gt;eay@cryptsoft.com&lt;/a&gt;) and UPnP software written by Thomas Bernard.</source> <translation type="unfinished"/> </message> </context> <context> <name>AddressBookPage</name> <message> <location filename="../forms/addressbookpage.ui" line="+14"/> <source>Address Book</source> <translation type="unfinished"/> </message> <message> <location line="+22"/> <source>Double-click to edit address or label</source> <translation>Fai doppio click per modificare o cancellare l&apos;etichetta</translation> </message> <message> <location line="+24"/> <source>Create a new address</source> <translation>Crea un nuovo indirizzo</translation> </message> <message> <location line="+10"/> <source>Copy the currently selected address to the system clipboard</source> <translation>Copia l&apos;indirizzo attualmente selezionato nella clipboard</translation> </message> <message> <location line="-7"/> <source>&amp;New Address</source> <translation type="unfinished"/> </message> <message> <location line="-43"/> <source>These are your Demonic addresses for receiving payments. You may want to give a different one to each sender so you can keep track of who is paying you.</source> <translation type="unfinished"/> </message> <message> <location line="+53"/> <source>&amp;Copy Address</source> <translation>&amp;Copia l&apos;indirizzo</translation> </message> <message> <location line="+7"/> <source>Show &amp;QR Code</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>Sign a message to prove you own a Demonic address</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Sign &amp;Message</source> <translation type="unfinished"/> </message> <message> <location line="+17"/> <source>Delete the currently selected address from the list</source> <translation>Cancella l&apos;indirizzo attualmente selezionato dalla lista</translation> </message> <message> <location line="-10"/> <source>Verify a message to ensure it was signed with a specified Demonic address</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>&amp;Verify Message</source> <translation type="unfinished"/> </message> <message> <location line="+10"/> <source>&amp;Delete</source> <translation>&amp;Cancella</translation> </message> <message> <location filename="../addressbookpage.cpp" line="+65"/> <source>Copy &amp;Label</source> <translation>Copia &amp;l&apos;etichetta</translation> </message> <message> <location line="+2"/> <source>&amp;Edit</source> <translation>&amp;Modifica</translation> </message> <message> <location line="+250"/> <source>Export Address Book Data</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Comma separated file (*.csv)</source> <translation>Testo CSV (*.csv)</translation> </message> <message> <location line="+13"/> <source>Error exporting</source> <translation type="unfinished"/> </message> <message> <location line="+0"/> <source>Could not write to file %1.</source> <translation type="unfinished"/> </message> </context> <context> <name>AddressTableModel</name> <message> <location filename="../addresstablemodel.cpp" line="+145"/> <source>Label</source> <translation>Etichetta</translation> </message> <message> <location line="+0"/> <source>Address</source> <translation>Indirizzo</translation> </message> <message> <location line="+36"/> <source>(no label)</source> <translation>(nessuna etichetta)</translation> </message> </context> <context> <name>AskPassphraseDialog</name> <message> <location filename="../forms/askpassphrasedialog.ui" line="+26"/> <source>Passphrase Dialog</source> <translation>Finestra passphrase</translation> </message> <message> <location line="+21"/> <source>Enter passphrase</source> <translation>Inserisci la passphrase</translation> </message> <message> <location line="+14"/> <source>New passphrase</source> <translation>Nuova passphrase</translation> </message> <message> <location line="+14"/> <source>Repeat new passphrase</source> <translation>Ripeti la passphrase</translation> </message> <message> <location line="+33"/> <source>Serves to disable the trivial sendmoney when OS account compromised. Provides no real security.</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>For staking only</source> <translation type="unfinished"/> </message> <message> <location filename="../askpassphrasedialog.cpp" line="+38"/> <source>Encrypt wallet</source> <translation>Cifra il portamonete</translation> </message> <message> <location line="+7"/> <source>This operation needs your wallet passphrase to unlock the wallet.</source> <translation>Quest&apos;operazione necessita della passphrase per sbloccare il portamonete.</translation> </message> <message> <location line="+5"/> <source>Unlock wallet</source> <translation>Sblocca il portamonete</translation> </message> <message> <location line="+3"/> <source>This operation needs your wallet passphrase to decrypt the wallet.</source> <translation>Quest&apos;operazione necessita della passphrase per decifrare il portamonete,</translation> </message> <message> <location line="+5"/> <source>Decrypt wallet</source> <translation>Decifra il portamonete</translation> </message> <message> <location line="+3"/> <source>Change passphrase</source> <translation>Cambia la passphrase</translation> </message> <message> <location line="+1"/> <source>Enter the old and new passphrase to the wallet.</source> <translation>Inserisci la vecchia e la nuova passphrase per il portamonete.</translation> </message> <message> <location line="+45"/> <source>Confirm wallet encryption</source> <translation>Conferma la cifratura del portamonete</translation> </message> <message> <location line="+1"/> <source>Warning: If you encrypt your wallet and lose your passphrase, you will &lt;b&gt;LOSE ALL OF YOUR COINS&lt;/b&gt;!</source> <translation type="unfinished"/> </message> <message> <location line="+0"/> <source>Are you sure you wish to encrypt your wallet?</source> <translation>Si è sicuri di voler cifrare il portamonete?</translation> </message> <message> <location line="+15"/> <source>IMPORTANT: Any previous backups you have made of your wallet file should be replaced with the newly generated, encrypted wallet file. For security reasons, previous backups of the unencrypted wallet file will become useless as soon as you start using the new, encrypted wallet.</source> <translation>IMPORTANTE: qualsiasi backup del portafoglio effettuato precedentemente dovrebbe essere sostituito con il file del portafoglio criptato appena generato. Per ragioni di sicurezza, i backup precedenti del file del portafoglio non criptato diventeranno inservibili non appena si inizi ad usare il nuovo portafoglio criptato.</translation> </message> <message> <location line="+103"/> <location line="+24"/> <source>Warning: The Caps Lock key is on!</source> <translation>Attenzione: tasto Blocco maiuscole attivo.</translation> </message> <message> <location line="-133"/> <location line="+60"/> <source>Wallet encrypted</source> <translation>Portamonete cifrato</translation> </message> <message> <location line="-140"/> <source>Enter the new passphrase to the wallet.&lt;br/&gt;Please use a passphrase of &lt;b&gt;ten or more random characters&lt;/b&gt;, or &lt;b&gt;eight or more words&lt;/b&gt;.</source> <translation type="unfinished"/> </message> <message> <location line="+82"/> <source>Demonic will close now to finish the encryption process. Remember that encrypting your wallet cannot fully protect your coins from being stolen by malware infecting your computer.</source> <translation type="unfinished"/> </message> <message> <location line="+13"/> <location line="+7"/> <location line="+44"/> <location line="+6"/> <source>Wallet encryption failed</source> <translation>Cifratura del portamonete fallita</translation> </message> <message> <location line="-56"/> <source>Wallet encryption failed due to an internal error. Your wallet was not encrypted.</source> <translation>Cifratura del portamonete fallita a causa di un errore interno. Il portamonete non è stato cifrato.</translation> </message> <message> <location line="+7"/> <location line="+50"/> <source>The supplied passphrases do not match.</source> <translation>Le passphrase inserite non corrispondono.</translation> </message> <message> <location line="-38"/> <source>Wallet unlock failed</source> <translation>Sblocco del portamonete fallito</translation> </message> <message> <location line="+1"/> <location line="+12"/> <location line="+19"/> <source>The passphrase entered for the wallet decryption was incorrect.</source> <translation>La passphrase inserita per la decifrazione del portamonete è errata.</translation> </message> <message> <location line="-20"/> <source>Wallet decryption failed</source> <translation>Decifrazione del portamonete fallita</translation> </message> <message> <location line="+14"/> <source>Wallet passphrase was successfully changed.</source> <translation>Passphrase del portamonete modificata con successo.</translation> </message> </context> <context> <name>BitcoinGUI</name> <message> <location filename="../bitcoingui.cpp" line="+297"/> <source>Sign &amp;message...</source> <translation>Firma il &amp;messaggio...</translation> </message> <message> <location line="-64"/> <source>Show general overview of wallet</source> <translation>Mostra lo stato generale del portamonete</translation> </message> <message> <location line="+17"/> <source>&amp;Transactions</source> <translation>&amp;Transazioni</translation> </message> <message> <location line="+1"/> <source>Browse transaction history</source> <translation>Cerca nelle transazioni</translation> </message> <message> <location line="+5"/> <source>&amp;Address Book</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Edit the list of stored addresses and labels</source> <translation type="unfinished"/> </message> <message> <location line="-18"/> <source>Show the list of addresses for receiving payments</source> <translation type="unfinished"/> </message> <message> <location line="+34"/> <source>E&amp;xit</source> <translation>&amp;Esci</translation> </message> <message> <location line="+1"/> <source>Quit application</source> <translation>Chiudi applicazione</translation> </message> <message> <location line="+4"/> <source>Show information about Demonic</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>About &amp;Qt</source> <translation>Informazioni su &amp;Qt</translation> </message> <message> <location line="+1"/> <source>Show information about Qt</source> <translation>Mostra informazioni su Qt</translation> </message> <message> <location line="+2"/> <source>&amp;Options...</source> <translation>&amp;Opzioni...</translation> </message> <message> <location line="+4"/> <source>&amp;Encrypt Wallet...</source> <translation>&amp;Cifra il portamonete...</translation> </message> <message> <location line="+2"/> <source>&amp;Backup Wallet...</source> <translation>&amp;Backup Portamonete...</translation> </message> <message> <location line="+2"/> <source>&amp;Change Passphrase...</source> <translation>&amp;Cambia la passphrase...</translation> </message> <message> <location line="+9"/> <source>&amp;Export...</source> <translation type="unfinished"/> </message> <message> <location line="-55"/> <source>Send coins to a Demonic address</source> <translation type="unfinished"/> </message> <message> <location line="+39"/> <source>Modify configuration options for Demonic</source> <translation type="unfinished"/> </message> <message> <location line="+17"/> <source>Export the data in the current tab to a file</source> <translation type="unfinished"/> </message> <message> <location line="-13"/> <source>Encrypt or decrypt wallet</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Backup wallet to another location</source> <translation>Backup portamonete in un&apos;altra locazione</translation> </message> <message> <location line="+2"/> <source>Change the passphrase used for wallet encryption</source> <translation>Cambia la passphrase per la cifratura del portamonete</translation> </message> <message> <location line="+10"/> <source>&amp;Debug window</source> <translation>Finestra &amp;Debug</translation> </message> <message> <location line="+1"/> <source>Open debugging and diagnostic console</source> <translation>Apri la console di degugging e diagnostica</translation> </message> <message> <location line="-5"/> <source>&amp;Verify message...</source> <translation>&amp;Verifica messaggio...</translation> </message> <message> <location line="-214"/> <location line="+555"/> <source>Demonic</source> <translation type="unfinished"/> </message> <message> <location line="-555"/> <source>Wallet</source> <translation>Portamonete</translation> </message> <message> <location line="+193"/> <source>&amp;About Demonic</source> <translation type="unfinished"/> </message> <message> <location line="+9"/> <source>&amp;Show / Hide</source> <translation>&amp;Mostra/Nascondi</translation> </message> <message> <location line="+8"/> <source>Unlock wallet</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>&amp;Lock Wallet</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Lock wallet</source> <translation type="unfinished"/> </message> <message> <location line="+32"/> <source>&amp;File</source> <translation>&amp;File</translation> </message> <message> <location line="+8"/> <source>&amp;Settings</source> <translation>&amp;Impostazioni</translation> </message> <message> <location line="+8"/> <source>&amp;Help</source> <translation>&amp;Aiuto</translation> </message> <message> <location line="+17"/> <source>Tabs toolbar</source> <translation>Barra degli strumenti &quot;Tabs&quot;</translation> </message> <message> <location line="+46"/> <location line="+9"/> <source>[testnet]</source> <translation>[testnet]</translation> </message> <message> <location line="+0"/> <location line="+58"/> <source>Demonic client</source> <translation type="unfinished"/> </message> <message numerus="yes"> <location line="+70"/> <source>%n active connection(s) to Demonic network</source> <translation type="unfinished"><numerusform></numerusform><numerusform></numerusform></translation> </message> <message> <location line="+488"/> <source>Staking.&lt;br&gt;Your weight is %1&lt;br&gt;Network weight is %2&lt;br&gt;Expected time to earn reward is %3</source> <translation type="unfinished"/> </message> <message> <location line="+6"/> <source>Not staking because wallet is locked</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Not staking because wallet is offline</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Not staking because wallet is syncing</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Not staking because you don&apos;t have mature coins</source> <translation type="unfinished"/> </message> <message> <location line="-812"/> <source>&amp;Dashboard</source> <translation type="unfinished"/> </message> <message> <location line="+6"/> <source>&amp;Receive</source> <translation type="unfinished"/> </message> <message> <location line="+6"/> <source>&amp;Send</source> <translation type="unfinished"/> </message> <message> <location line="+49"/> <source>&amp;Unlock Wallet...</source> <translation type="unfinished"/> </message> <message> <location line="+277"/> <source>Up to date</source> <translation>Aggiornato</translation> </message> <message> <location line="+43"/> <source>Catching up...</source> <translation>In aggiornamento...</translation> </message> <message> <location line="+113"/> <source>Confirm transaction fee</source> <translation type="unfinished"/> </message> <message> <location line="+27"/> <source>Sent transaction</source> <translation>Transazione inviata</translation> </message> <message> <location line="+1"/> <source>Incoming transaction</source> <translation>Transazione ricevuta</translation> </message> <message> <location line="+1"/> <source>Date: %1 Amount: %2 Type: %3 Address: %4 </source> <translation>Data: %1 Quantità: %2 Tipo: %3 Indirizzo: %4 </translation> </message> <message> <location line="+100"/> <location line="+15"/> <source>URI handling</source> <translation type="unfinished"/> </message> <message> <location line="-15"/> <location line="+15"/> <source>URI can not be parsed! This can be caused by an invalid Demonic address or malformed URI parameters.</source> <translation type="unfinished"/> </message> <message> <location line="+9"/> <source>Wallet is &lt;b&gt;not encrypted&lt;/b&gt;</source> <translation type="unfinished"/> </message> <message> <location line="+8"/> <source>Wallet is &lt;b&gt;encrypted&lt;/b&gt; and currently &lt;b&gt;unlocked&lt;/b&gt;</source> <translation>Il portamonete è &lt;b&gt;cifrato&lt;/b&gt; e attualmente &lt;b&gt;sbloccato&lt;/b&gt;</translation> </message> <message> <location line="+8"/> <source>Wallet is &lt;b&gt;encrypted&lt;/b&gt; and currently &lt;b&gt;locked&lt;/b&gt;</source> <translation>Il portamonete è &lt;b&gt;cifrato&lt;/b&gt; e attualmente &lt;b&gt;bloccato&lt;/b&gt;</translation> </message> <message> <location line="+24"/> <source>Backup Wallet</source> <translation type="unfinished"/> </message> <message> <location line="+0"/> <source>Wallet Data (*.dat)</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Backup Failed</source> <translation type="unfinished"/> </message> <message> <location line="+0"/> <source>There was an error trying to save the wallet data to the new location.</source> <translation type="unfinished"/> </message> <message numerus="yes"> <location line="+91"/> <source>%n second(s)</source> <translation type="unfinished"><numerusform></numerusform><numerusform></numerusform></translation> </message> <message numerus="yes"> <location line="+4"/> <source>%n minute(s)</source> <translation type="unfinished"><numerusform></numerusform><numerusform></numerusform></translation> </message> <message numerus="yes"> <location line="-429"/> <location line="+433"/> <source>%n hour(s)</source> <translation><numerusform>%n ora</numerusform><numerusform>%n ore</numerusform></translation> </message> <message> <location line="-456"/> <source>Processed %1 blocks of transaction history.</source> <translation type="unfinished"/> </message> <message numerus="yes"> <location line="+27"/> <location line="+433"/> <source>%n day(s)</source> <translation><numerusform>%n giorno</numerusform><numerusform>%n giorni</numerusform></translation> </message> <message numerus="yes"> <location line="-429"/> <location line="+6"/> <source>%n week(s)</source> <translation type="unfinished"><numerusform></numerusform><numerusform></numerusform></translation> </message> <message> <location line="+0"/> <source>%1 and %2</source> <translation type="unfinished"/> </message> <message numerus="yes"> <location line="+0"/> <source>%n year(s)</source> <translation type="unfinished"><numerusform></numerusform><numerusform></numerusform></translation> </message> <message> <location line="+5"/> <source>%1 behind</source> <translation type="unfinished"/> </message> <message> <location line="+15"/> <source>Last received block was generated %1 ago.</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Transactions after this will not yet be visible.</source> <translation type="unfinished"/> </message> <message> <location line="+23"/> <source>Error</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Warning</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Information</source> <translation type="unfinished"/> </message> <message> <location line="+69"/> <source>This transaction is over the size limit. You can still send it for a fee of %1, which goes to the nodes that process your transaction and helps to support the network. Do you want to pay the fee?</source> <translation type="unfinished"/> </message> <message> <location line="+324"/> <source>Not staking</source> <translation type="unfinished"/> </message> <message> <location filename="../bitcoin.cpp" line="+104"/> <source>A fatal error occurred. Demonic can no longer continue safely and will quit.</source> <translation type="unfinished"/> </message> </context> <context> <name>ClientModel</name> <message> <location filename="../clientmodel.cpp" line="+110"/> <source>Network Alert</source> <translation>Avviso di rete</translation> </message> </context> <context> <name>CoinControlDialog</name> <message> <location filename="../forms/coincontroldialog.ui" line="+14"/> <source>Coin Control</source> <translation type="unfinished"/> </message> <message> <location line="+31"/> <source>Quantity:</source> <translation>Quantità:</translation> </message> <message> <location line="+32"/> <source>Bytes:</source> <translation>Byte:</translation> </message> <message> <location line="+48"/> <source>Amount:</source> <translation>Importo:</translation> </message> <message> <location line="+32"/> <source>Priority:</source> <translation>Priorità:</translation> </message> <message> <location line="+48"/> <source>Fee:</source> <translation>Commissione:</translation> </message> <message> <location line="+35"/> <source>Low Output:</source> <translation>Low Output:</translation> </message> <message> <location filename="../coincontroldialog.cpp" line="+537"/> <source>no</source> <translation>no</translation> </message> <message> <location filename="../forms/coincontroldialog.ui" line="+51"/> <source>After Fee:</source> <translation>Dopo Commissione:</translation> </message> <message> <location line="+35"/> <source>Change:</source> <translation>Resto:</translation> </message> <message> <location line="+69"/> <source>(un)select all</source> <translation>(de)seleziona tutto</translation> </message> <message> <location line="+13"/> <source>Tree mode</source> <translation>Modalità Albero</translation> </message> <message> <location line="+16"/> <source>List mode</source> <translation>Modalità Lista</translation> </message> <message> <location line="+45"/> <source>Amount</source> <translation>Importo</translation> </message> <message> <location line="+5"/> <source>Label</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <source>Address</source> <translation>Indirizzo</translation> </message> <message> <location line="+5"/> <source>Date</source> <translation>Data</translation> </message> <message> <location line="+5"/> <source>Confirmations</source> <translation>Conferme:</translation> </message> <message> <location line="+3"/> <source>Confirmed</source> <translation>Confermato</translation> </message> <message> <location line="+5"/> <source>Priority</source> <translation>Priorità</translation> </message> <message> <location filename="../coincontroldialog.cpp" line="-500"/> <source>Copy address</source> <translation>Copia l&apos;indirizzo</translation> </message> <message> <location line="+1"/> <source>Copy label</source> <translation>Copia l&apos;etichetta</translation> </message> <message> <location line="+1"/> <location line="+26"/> <source>Copy amount</source> <translation>Copia l&apos;importo</translation> </message> <message> <location line="-25"/> <source>Copy transaction ID</source> <translation>Copia l&apos;ID transazione</translation> </message> <message> <location line="+24"/> <source>Copy quantity</source> <translation>Copia quantità</translation> </message> <message> <location line="+2"/> <source>Copy fee</source> <translation>Copia commissione</translation> </message> <message> <location line="+1"/> <source>Copy after fee</source> <translation>Copia dopo commissione</translation> </message> <message> <location line="+1"/> <source>Copy bytes</source> <translation>Copia byte</translation> </message> <message> <location line="+1"/> <source>Copy priority</source> <translation>Copia priorità</translation> </message> <message> <location line="+1"/> <source>Copy low output</source> <translation>Copia low output</translation> </message> <message> <location line="+1"/> <source>Copy change</source> <translation>Copia resto</translation> </message> <message> <location line="+317"/> <source>highest</source> <translation>massima</translation> </message> <message> <location line="+1"/> <source>high</source> <translation>alta</translation> </message> <message> <location line="+1"/> <source>medium-high</source> <translation>medio-alta</translation> </message> <message> <location line="+1"/> <source>medium</source> <translation>media</translation> </message> <message> <location line="+4"/> <source>low-medium</source> <translation>medio-bassa</translation> </message> <message> <location line="+1"/> <source>low</source> <translation>bassa</translation> </message> <message> <location line="+1"/> <source>lowest</source> <translation>infima</translation> </message> <message> <location line="+140"/> <source>DUST</source> <translation type="unfinished"/> </message> <message> <location line="+0"/> <source>yes</source> <translation>si</translation> </message> <message> <location line="+10"/> <source>This label turns red, if the transaction size is bigger than 10000 bytes. This means a fee of at least %1 per kb is required. Can vary +/- 1 Byte per input.</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Transactions with higher priority get more likely into a block. This label turns red, if the priority is smaller than &quot;medium&quot;. This means a fee of at least %1 per kb is required.</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>This label turns red, if any recipient receives an amount smaller than %1. This means a fee of at least %2 is required. Amounts below 0.546 times the minimum relay fee are shown as DUST.</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>This label turns red, if the change is smaller than %1. This means a fee of at least %2 is required.</source> <translation type="unfinished"/> </message> <message> <location line="+36"/> <location line="+66"/> <source>(no label)</source> <translation>(nessuna etichetta)</translation> </message> <message> <location line="-9"/> <source>change from %1 (%2)</source> <translation>resto da %1 (%2)</translation> </message> <message> <location line="+1"/> <source>(change)</source> <translation>(resto)</translation> </message> </context> <context> <name>EditAddressDialog</name> <message> <location filename="../forms/editaddressdialog.ui" line="+14"/> <source>Edit Address</source> <translation>Modifica l&apos;indirizzo</translation> </message> <message> <location line="+11"/> <source>&amp;Label</source> <translation>&amp;Etichetta</translation> </message> <message> <location line="+10"/> <source>The label associated with this address book entry</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>&amp;Address</source> <translation>&amp;Indirizzo</translation> </message> <message> <location line="+10"/> <source>The address associated with this address book entry. This can only be modified for sending addresses.</source> <translation type="unfinished"/> </message> <message> <location filename="../editaddressdialog.cpp" line="+21"/> <source>New receiving address</source> <translation>Nuovo indirizzo di ricezione</translation> </message> <message> <location line="+4"/> <source>New sending address</source> <translation>Nuovo indirizzo d&apos;invio</translation> </message> <message> <location line="+3"/> <source>Edit receiving address</source> <translation>Modifica indirizzo di ricezione</translation> </message> <message> <location line="+4"/> <source>Edit sending address</source> <translation>Modifica indirizzo d&apos;invio</translation> </message> <message> <location line="+76"/> <source>The entered address &quot;%1&quot; is already in the address book.</source> <translation>L&apos;indirizzo inserito &quot;%1&quot; è già in rubrica.</translation> </message> <message> <location line="-5"/> <source>The entered address &quot;%1&quot; is not a valid Demonic address.</source> <translation type="unfinished"/> </message> <message> <location line="+10"/> <source>Could not unlock wallet.</source> <translation>Impossibile sbloccare il portamonete.</translation> </message> <message> <location line="+5"/> <source>New key generation failed.</source> <translation>Generazione della nuova chiave non riuscita.</translation> </message> </context> <context> <name>GUIUtil::HelpMessageBox</name> <message> <location filename="../guiutil.cpp" line="+426"/> <location line="+12"/> <source>Demonic-Qt</source> <translation type="unfinished"/> </message> <message> <location line="-12"/> <source>version</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Usage:</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>command-line options</source> <translation type="unfinished"/> </message> <message> <location line="+4"/> <source>UI options</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Set language, for example &quot;de_DE&quot; (default: system locale)</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Start minimized</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Show splash screen on startup (default: 1)</source> <translation type="unfinished"/> </message> </context> <context> <name>OptionsDialog</name> <message> <location filename="../forms/optionsdialog.ui" line="+14"/> <source>Options</source> <translation>Opzioni</translation> </message> <message> <location line="+16"/> <source>&amp;Main</source> <translation>&amp;Principale</translation> </message> <message> <location line="+6"/> <source>Optional transaction fee per kB that helps make sure your transactions are processed quickly. Most transactions are 1 kB. Fee 0.01 recommended.</source> <translation type="unfinished"/> </message> <message> <location line="+15"/> <source>Pay transaction &amp;fee</source> <translation>Paga la &amp;commissione</translation> </message> <message> <location line="+31"/> <source>Reserved amount does not participate in staking and is therefore spendable at any time.</source> <translation type="unfinished"/> </message> <message> <location line="+15"/> <source>Reserve</source> <translation type="unfinished"/> </message> <message> <location line="+31"/> <source>Automatically start Demonic after logging in to the system.</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>&amp;Start Demonic on system login</source> <translation type="unfinished"/> </message> <message> <location line="+21"/> <source>&amp;Network</source> <translation>Rete</translation> </message> <message> <location line="+6"/> <source>Automatically open the Demonic client port on the router. This only works when your router supports UPnP and it is enabled.</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Map port using &amp;UPnP</source> <translation>Mappa le porte tramite l&apos;&amp;UPnP</translation> </message> <message> <location line="+19"/> <source>Proxy &amp;IP:</source> <translation>&amp;IP del proxy:</translation> </message> <message> <location line="+19"/> <source>IP address of the proxy (e.g. 127.0.0.1)</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>&amp;Port:</source> <translation>&amp;Porta:</translation> </message> <message> <location line="+19"/> <source>Port of the proxy (e.g. 9050)</source> <translation>Porta del proxy (es. 9050)</translation> </message> <message> <location line="-57"/> <source>Connect to the Demonic network through a SOCKS5 proxy (e.g. when connecting through Tor).</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>&amp;Connect through SOCKS5 proxy:</source> <translation type="unfinished"/> </message> <message> <location line="+90"/> <source>&amp;Window</source> <translation>&amp;Finestra</translation> </message> <message> <location line="+6"/> <source>Show only a tray icon after minimizing the window.</source> <translation>Mostra solo un&apos;icona nel tray quando si minimizza la finestra</translation> </message> <message> <location line="+3"/> <source>&amp;Minimize to the tray instead of the taskbar</source> <translation>&amp;Minimizza sul tray invece che sulla barra delle applicazioni</translation> </message> <message> <location line="+7"/> <source>Minimize instead of exit the application when the window is closed. When this option is enabled, the application will be closed only after selecting Quit in the menu.</source> <translation>Riduci ad icona, invece di uscire dall&apos;applicazione quando la finestra viene chiusa. Quando questa opzione è attivata, l&apos;applicazione verrà chiusa solo dopo aver selezionato Esci nel menu.</translation> </message> <message> <location line="+3"/> <source>M&amp;inimize on close</source> <translation>M&amp;inimizza alla chiusura</translation> </message> <message> <location line="+21"/> <source>&amp;Display</source> <translation>&amp;Mostra</translation> </message> <message> <location line="+8"/> <source>User Interface &amp;language:</source> <translation>&amp;Lingua Interfaccia Utente:</translation> </message> <message> <location line="+13"/> <source>The user interface language can be set here. This setting will take effect after restarting Demonic.</source> <translation type="unfinished"/> </message> <message> <location line="+11"/> <source>&amp;Unit to show amounts in:</source> <translation>&amp;Unità di misura degli importi in:</translation> </message> <message> <location line="+13"/> <source>Choose the default subdivision unit to show in the interface and when sending coins.</source> <translation>Scegli l&apos;unità di suddivisione predefinita per l&apos;interfaccia e per l&apos;invio di monete</translation> </message> <message> <location line="+9"/> <source>Whether to show coin control features or not.</source> <translation>Mostrare/non mostrare le funzionalita&apos; di controllo della moneta.</translation> </message> <message> <location line="+3"/> <source>Display coin &amp;control features (experts only!)</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>Whether to select the coin outputs randomly or with minimal coin age.</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Minimize weight consumption (experimental)</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>Use black visual theme (requires restart)</source> <translation type="unfinished"/> </message> <message> <location line="+71"/> <source>&amp;OK</source> <translation>&amp;OK</translation> </message> <message> <location line="+7"/> <source>&amp;Cancel</source> <translation>&amp;Cancella</translation> </message> <message> <location line="+10"/> <source>&amp;Apply</source> <translation type="unfinished"/> </message> <message> <location filename="../optionsdialog.cpp" line="+47"/> <source>default</source> <translation>predefinito</translation> </message> <message> <location line="+148"/> <location line="+9"/> <source>Warning</source> <translation type="unfinished"/> </message> <message> <location line="-9"/> <location line="+9"/> <source>This setting will take effect after restarting Demonic.</source> <translation type="unfinished"/> </message> <message> <location line="+29"/> <source>The supplied proxy address is invalid.</source> <translation>L&apos;indirizzo proxy che hai fornito è invalido.</translation> </message> </context> <context> <name>OverviewPage</name> <message> <location filename="../forms/overviewpage.ui" line="+14"/> <source>Form</source> <translation>Modulo</translation> </message> <message> <location line="+46"/> <location line="+247"/> <source>The displayed information may be out of date. Your wallet automatically synchronizes with the Demonic network after a connection is established, but this process has not completed yet.</source> <translation type="unfinished"/> </message> <message> <location line="-173"/> <source>Stake:</source> <translation type="unfinished"/> </message> <message> <location line="+32"/> <source>Unconfirmed:</source> <translation type="unfinished"/> </message> <message> <location line="-113"/> <source>Wallet</source> <translation>Portamonete</translation> </message> <message> <location line="+49"/> <source>Spendable:</source> <translation type="unfinished"/> </message> <message> <location line="+16"/> <source>Your current spendable balance</source> <translation>Saldo spendibile attuale</translation> </message> <message> <location line="+80"/> <source>Immature:</source> <translation>Immaturo:</translation> </message> <message> <location line="+13"/> <source>Mined balance that has not yet matured</source> <translation>Importo scavato che non è ancora maturato</translation> </message> <message> <location line="+23"/> <source>Total:</source> <translation>Totale:</translation> </message> <message> <location line="+16"/> <source>Your current total balance</source> <translation>Saldo totale attuale</translation> </message> <message> <location line="+50"/> <source>&lt;b&gt;Recent transactions&lt;/b&gt;</source> <translation>&lt;b&gt;Transazioni recenti&lt;/b&gt;</translation> </message> <message> <location line="-118"/> <source>Total of transactions that have yet to be confirmed, and do not yet count toward the current balance</source> <translation type="unfinished"/> </message> <message> <location line="-32"/> <source>Total of coins that was staked, and do not yet count toward the current balance</source> <translation type="unfinished"/> </message> <message> <location filename="../overviewpage.cpp" line="+116"/> <location line="+1"/> <source>out of sync</source> <translation>fuori sincrono</translation> </message> </context> <context> <name>PaymentServer</name> <message> <location filename="../paymentserver.cpp" line="+107"/> <source>Cannot start demonic: click-to-pay handler</source> <translation type="unfinished"/> </message> </context> <context> <name>QRCodeDialog</name> <message> <location filename="../forms/qrcodedialog.ui" line="+14"/> <source>QR Code Dialog</source> <translation type="unfinished"/> </message> <message> <location line="+59"/> <source>Request Payment</source> <translation type="unfinished"/> </message> <message> <location line="+56"/> <source>Amount:</source> <translation type="unfinished"/> </message> <message> <location line="-44"/> <source>Label:</source> <translation type="unfinished"/> </message> <message> <location line="+19"/> <source>Message:</source> <translation type="unfinished"/> </message> <message> <location line="+71"/> <source>&amp;Save As...</source> <translation type="unfinished"/> </message> <message> <location filename="../qrcodedialog.cpp" line="+62"/> <source>Error encoding URI into QR Code.</source> <translation type="unfinished"/> </message> <message> <location line="+40"/> <source>The entered amount is invalid, please check.</source> <translation type="unfinished"/> </message> <message> <location line="+23"/> <source>Resulting URI too long, try to reduce the text for label / message.</source> <translation type="unfinished"/> </message> <message> <location line="+25"/> <source>Save QR Code</source> <translation type="unfinished"/> </message> <message> <location line="+0"/> <source>PNG Images (*.png)</source> <translation type="unfinished"/> </message> </context> <context> <name>RPCConsole</name> <message> <location filename="../forms/rpcconsole.ui" line="+46"/> <source>Client name</source> <translation>Nome del client</translation> </message> <message> <location line="+10"/> <location line="+23"/> <location line="+26"/> <location line="+23"/> <location line="+23"/> <location line="+36"/> <location line="+53"/> <location line="+23"/> <source>N/A</source> <translation>N/D</translation> </message> <message> <location line="-194"/> <source>Client version</source> <translation>Versione client</translation> </message> <message> <location line="-45"/> <source>&amp;Information</source> <translation>&amp;Informazione</translation> </message> <message> <location line="+68"/> <source>Using OpenSSL version</source> <translation>Versione OpenSSL in uso</translation> </message> <message> <location line="+49"/> <source>Startup time</source> <translation>Tempo di avvio</translation> </message> <message> <location line="+29"/> <source>Network</source> <translation>Rete</translation> </message> <message> <location line="+7"/> <source>Number of connections</source> <translation>Numero connessioni</translation> </message> <message> <location line="+23"/> <source>On testnet</source> <translation type="unfinished"/> </message> <message> <location line="+23"/> <source>Block chain</source> <translation>Block chain</translation> </message> <message> <location line="+7"/> <source>Current number of blocks</source> <translation>Numero attuale di blocchi</translation> </message> <message> <location line="+197"/> <source>&amp;Network Traffic</source> <translation type="unfinished"/> </message> <message> <location line="+52"/> <source>&amp;Clear</source> <translation type="unfinished"/> </message> <message> <location line="+13"/> <source>Totals</source> <translation type="unfinished"/> </message> <message> <location line="+64"/> <source>In:</source> <translation type="unfinished"/> </message> <message> <location line="+80"/> <source>Out:</source> <translation type="unfinished"/> </message> <message> <location line="-383"/> <source>Last block time</source> <translation>Ora dell blocco piu recente</translation> </message> <message> <location line="+52"/> <source>&amp;Open</source> <translation>&amp;Apri</translation> </message> <message> <location line="+16"/> <source>Command-line options</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>Show the Demonic-Qt help message to get a list with possible Demonic command-line options.</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>&amp;Show</source> <translation type="unfinished"/> </message> <message> <location line="+24"/> <source>&amp;Console</source> <translation>&amp;Console</translation> </message> <message> <location line="-237"/> <source>Build date</source> <translation>Data di creazione</translation> </message> <message> <location line="-104"/> <source>Demonic - Debug window</source> <translation type="unfinished"/> </message> <message> <location line="+25"/> <source>Demonic Core</source> <translation type="unfinished"/> </message> <message> <location line="+256"/> <source>Debug log file</source> <translation>File log del Debug</translation> </message> <message> <location line="+7"/> <source>Open the Demonic debug log file from the current data directory. This can take a few seconds for large log files.</source> <translation type="unfinished"/> </message> <message> <location line="+102"/> <source>Clear console</source> <translation>Svuota console</translation> </message> <message> <location filename="../rpcconsole.cpp" line="+325"/> <source>Welcome to the Demonic RPC console.</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Use up and down arrows to navigate history, and &lt;b&gt;Ctrl-L&lt;/b&gt; to clear screen.</source> <translation>Usa le frecce direzionali per navigare la cronologia, and &lt;b&gt;Ctrl-L&lt;/b&gt; per cancellarla.</translation> </message> <message> <location line="+1"/> <source>Type &lt;b&gt;help&lt;/b&gt; for an overview of available commands.</source> <translation>Scrivi &lt;b&gt;help&lt;/b&gt; per un riassunto dei comandi disponibili</translation> </message> <message> <location line="+127"/> <source>%1 B</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>%1 KB</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>%1 MB</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>%1 GB</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>%1 m</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <source>%1 h</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>%1 h %2 m</source> <translation type="unfinished"/> </message> </context> <context> <name>SendCoinsDialog</name> <message> <location filename="../forms/sendcoinsdialog.ui" line="+14"/> <location filename="../sendcoinsdialog.cpp" line="+182"/> <location line="+5"/> <location line="+5"/> <location line="+5"/> <location line="+6"/> <location line="+5"/> <location line="+5"/> <source>Send Coins</source> <translation>Spedisci Bitcoin</translation> </message> <message> <location line="+76"/> <source>Coin Control Features</source> <translation>Funzionalità di Coin Control</translation> </message> <message> <location line="+20"/> <source>Inputs...</source> <translation>Input...</translation> </message> <message> <location line="+7"/> <source>automatically selected</source> <translation>selezionato automaticamente</translation> </message> <message> <location line="+19"/> <source>Insufficient funds!</source> <translation>Fondi insufficienti!</translation> </message> <message> <location line="+77"/> <source>Quantity:</source> <translation>Quantità:</translation> </message> <message> <location line="+22"/> <location line="+35"/> <source>0</source> <translation type="unfinished"/> </message> <message> <location line="-19"/> <source>Bytes:</source> <translation>Byte:</translation> </message> <message> <location line="+51"/> <source>Amount:</source> <translation>Importo:</translation> </message> <message> <location line="+35"/> <source>Priority:</source> <translation>Priorità:</translation> </message> <message> <location line="+19"/> <source>medium</source> <translation type="unfinished"/> </message> <message> <location line="+32"/> <source>Fee:</source> <translation>Commissione:</translation> </message> <message> <location line="+35"/> <source>Low Output:</source> <translation>Low Output:</translation> </message> <message> <location line="+19"/> <source>no</source> <translation type="unfinished"/> </message> <message> <location line="+32"/> <source>After Fee:</source> <translation>Dopo Commissione:</translation> </message> <message> <location line="+35"/> <source>Change</source> <translation type="unfinished"/> </message> <message> <location line="+50"/> <source>custom change address</source> <translation type="unfinished"/> </message> <message> <location line="+106"/> <source>Send to multiple recipients at once</source> <translation>Spedisci a diversi beneficiari in una volta sola</translation> </message> <message> <location line="+3"/> <source>Add &amp;Recipient</source> <translation>&amp;Aggiungi beneficiario</translation> </message> <message> <location line="+16"/> <source>Remove all transaction fields</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Clear &amp;All</source> <translation>Cancella &amp;tutto</translation> </message> <message> <location line="+24"/> <source>Balance:</source> <translation>Saldo:</translation> </message> <message> <location line="+47"/> <source>Confirm the send action</source> <translation>Conferma la spedizione</translation> </message> <message> <location line="+3"/> <source>S&amp;end</source> <translation>&amp;Spedisci</translation> </message> <message> <location filename="../sendcoinsdialog.cpp" line="-174"/> <source>Enter a Demonic address (e.g. btK1jUZ2SEe7hxMA4tvDWxpBigJyekXPgZ)</source> <translation type="unfinished"/> </message> <message> <location line="+15"/> <source>Copy quantity</source> <translation>Copia quantità</translation> </message> <message> <location line="+1"/> <source>Copy amount</source> <translation>Copia l&apos;importo</translation> </message> <message> <location line="+1"/> <source>Copy fee</source> <translation>Copia commissione</translation> </message> <message> <location line="+1"/> <source>Copy after fee</source> <translation>Copia dopo commissione</translation> </message> <message> <location line="+1"/> <source>Copy bytes</source> <translation>Copia byte</translation> </message> <message> <location line="+1"/> <source>Copy priority</source> <translation>Copia priorità</translation> </message> <message> <location line="+1"/> <source>Copy low output</source> <translation>Copia low output</translation> </message> <message> <location line="+1"/> <source>Copy change</source> <translation>Copia resto</translation> </message> <message> <location line="+87"/> <source>&lt;b&gt;%1&lt;/b&gt; to %2 (%3)</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <source>Confirm send coins</source> <translation>Conferma la spedizione di bitcoin</translation> </message> <message> <location line="+1"/> <source>Are you sure you want to send %1?</source> <translation type="unfinished"/> </message> <message> <location line="+0"/> <source> and </source> <translation type="unfinished"/> </message> <message> <location line="+29"/> <source>The recipient address is not valid, please recheck.</source> <translation>L&apos;indirizzo del beneficiario non è valido, per cortesia controlla.</translation> </message> <message> <location line="+5"/> <source>The amount to pay must be larger than 0.</source> <translation>L&apos;importo da pagare dev&apos;essere maggiore di 0.</translation> </message> <message> <location line="+5"/> <source>The amount exceeds your balance.</source> <translation>L&apos;importo è superiore al saldo attuale</translation> </message> <message> <location line="+5"/> <source>The total exceeds your balance when the %1 transaction fee is included.</source> <translation>Il totale è superiore al saldo attuale includendo la commissione %1.</translation> </message> <message> <location line="+6"/> <source>Duplicate address found, can only send to each address once per send operation.</source> <translation>Trovato un indirizzo doppio, si può spedire solo una volta a ciascun indirizzo in una singola operazione.</translation> </message> <message> <location line="+5"/> <source>Error: Transaction creation failed!</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <source>Error: The transaction was rejected. This might happen if some of the coins in your wallet were already spent, such as if you used a copy of wallet.dat and coins were spent in the copy but not marked as spent here.</source> <translation type="unfinished"/> </message> <message> <location line="+247"/> <source>WARNING: Invalid Demonic address</source> <translation type="unfinished"/> </message> <message> <location line="+13"/> <source>(no label)</source> <translation>(nessuna etichetta)</translation> </message> <message> <location line="+4"/> <source>WARNING: unknown change address</source> <translation type="unfinished"/> </message> </context> <context> <name>SendCoinsEntry</name> <message> <location filename="../forms/sendcoinsentry.ui" line="+14"/> <source>Form</source> <translation type="unfinished"/> </message> <message> <location line="+15"/> <source>A&amp;mount:</source> <translation>&amp;Importo:</translation> </message> <message> <location line="+13"/> <source>Pay &amp;To:</source> <translation>Paga &amp;a:</translation> </message> <message> <location line="+34"/> <source>The address to send the payment to (e.g. btK1jUZ2SEe7hxMA4tvDWxpBigJyekXPgZ)</source> <translation type="unfinished"/> </message> <message> <location line="+60"/> <location filename="../sendcoinsentry.cpp" line="+26"/> <source>Enter a label for this address to add it to your address book</source> <translation>Inserisci un&apos;etichetta per questo indirizzo, per aggiungerlo nella rubrica</translation> </message> <message> <location line="-78"/> <source>&amp;Label:</source> <translation>&amp;Etichetta</translation> </message> <message> <location line="+28"/> <source>Choose address from address book</source> <translation type="unfinished"/> </message> <message> <location line="+10"/> <source>Alt+A</source> <translation>Alt+A</translation> </message> <message> <location line="+7"/> <source>Paste address from clipboard</source> <translation>Incollare l&apos;indirizzo dagli appunti</translation> </message> <message> <location line="+10"/> <source>Alt+P</source> <translation>Alt+P</translation> </message> <message> <location line="+7"/> <source>Remove this recipient</source> <translation type="unfinished"/> </message> <message> <location filename="../sendcoinsentry.cpp" line="+1"/> <source>Enter a Demonic address (e.g. btK1jUZ2SEe7hxMA4tvDWxpBigJyekXPgZ)</source> <translation type="unfinished"/> </message> </context> <context> <name>SignVerifyMessageDialog</name> <message> <location filename="../forms/signverifymessagedialog.ui" line="+14"/> <source>Signatures - Sign / Verify a Message</source> <translation>Firme - Firma / Verifica un messaggio</translation> </message> <message> <location line="+13"/> <location line="+124"/> <source>&amp;Sign Message</source> <translation>&amp;Firma il messaggio</translation> </message> <message> <location line="-118"/> <source>You can sign messages with your addresses to prove you own them. Be careful not to sign anything vague, as phishing attacks may try to trick you into signing your identity over to them. Only sign fully-detailed statements you agree to.</source> <translation>Puoi firmare messeggi con i tuoi indirizzi per dimostrare che sono tuoi. Fai attenzione a non firmare niente di vago, visto che gli attacchi di phishing potrebbero cercare di spingerti a mettere la tua firma su di loro. Firma solo dichiarazioni completamente dettagliate con cui sei d&apos;accordo.</translation> </message> <message> <location line="+18"/> <source>The address to sign the message with (e.g. btK1jUZ2SEe7hxMA4tvDWxpBigJyekXPgZ)</source> <translation type="unfinished"/> </message> <message> <location line="+10"/> <location line="+203"/> <source>Choose an address from the address book</source> <translation type="unfinished"/> </message> <message> <location line="-193"/> <location line="+203"/> <source>Alt+A</source> <translation>Alt+A</translation> </message> <message> <location line="-193"/> <source>Paste address from clipboard</source> <translation>Incollare l&apos;indirizzo dagli appunti</translation> </message> <message> <location line="+10"/> <source>Alt+P</source> <translation>Alt+P</translation> </message> <message> <location line="+12"/> <source>Enter the message you want to sign here</source> <translation>Inserisci qui il messaggio che vuoi firmare</translation> </message> <message> <location line="+24"/> <source>Copy the current signature to the system clipboard</source> <translation>Copia la firma corrente nella clipboard</translation> </message> <message> <location line="+21"/> <source>Sign the message to prove you own this Demonic address</source> <translation type="unfinished"/> </message> <message> <location line="+17"/> <source>Reset all sign message fields</source> <translation>Reimposta tutti i campi della firma</translation> </message> <message> <location line="+3"/> <location line="+146"/> <source>Clear &amp;All</source> <translation>Cancella &amp;tutto</translation> </message> <message> <location line="-87"/> <location line="+70"/> <source>&amp;Verify Message</source> <translation>&amp;Verifica Messaggio</translation> </message> <message> <location line="-64"/> <source>Enter the signing address, message (ensure you copy line breaks, spaces, tabs, etc. exactly) and signature below to verify the message. Be careful not to read more into the signature than what is in the signed message itself, to avoid being tricked by a man-in-the-middle attack.</source> <translation>Inserisci l&apos;indirizzo per la firma, il messaggio (verifica di copiare esattamente anche i ritorni a capo, gli spazi, le tabulazioni, etc) e la firma qui sotto, per verificare il messaggio. Verifica che il contenuto della firma non sia più grande di quello del messaggio per evitare attacchi di tipo man-in-the-middle.</translation> </message> <message> <location line="+21"/> <source>The address the message was signed with (e.g. btK1jUZ2SEe7hxMA4tvDWxpBigJyekXPgZ)</source> <translation type="unfinished"/> </message> <message> <location line="+40"/> <source>Verify the message to ensure it was signed with the specified Demonic address</source> <translation type="unfinished"/> </message> <message> <location line="+17"/> <source>Reset all verify message fields</source> <translation>Reimposta tutti i campi della verifica messaggio</translation> </message> <message> <location filename="../signverifymessagedialog.cpp" line="+27"/> <location line="+3"/> <source>Enter a Demonic address (e.g. btK1jUZ2SEe7hxMA4tvDWxpBigJyekXPgZ)</source> <translation type="unfinished"/> </message> <message> <location line="-2"/> <source>Click &quot;Sign Message&quot; to generate signature</source> <translation>Clicca &quot;Firma il messaggio&quot; per ottenere la firma</translation> </message> <message> <location line="+3"/> <source>Enter Demonic signature</source> <translation type="unfinished"/> </message> <message> <location line="+85"/> <location line="+81"/> <source>The entered address is invalid.</source> <translation>L&apos;indirizzo inserito non è valido.</translation> </message> <message> <location line="-81"/> <location line="+8"/> <location line="+73"/> <location line="+8"/> <source>Please check the address and try again.</source> <translation>Per favore controlla l&apos;indirizzo e prova ancora</translation> </message> <message> <location line="-81"/> <location line="+81"/> <source>The entered address does not refer to a key.</source> <translation>L&apos;indirizzo bitcoin inserito non è associato a nessuna chiave.</translation> </message> <message> <location line="-73"/> <source>Wallet unlock was cancelled.</source> <translation>Sblocco del portafoglio annullato.</translation> </message> <message> <location line="+8"/> <source>Private key for the entered address is not available.</source> <translation>La chiave privata per l&apos;indirizzo inserito non è disponibile.</translation> </message> <message> <location line="+12"/> <source>Message signing failed.</source> <translation>Firma messaggio fallita.</translation> </message> <message> <location line="+5"/> <source>Message signed.</source> <translation>Messaggio firmato.</translation> </message> <message> <location line="+59"/> <source>The signature could not be decoded.</source> <translation>Non è stato possibile decodificare la firma.</translation> </message> <message> <location line="+0"/> <location line="+13"/> <source>Please check the signature and try again.</source> <translation>Per favore controlla la firma e prova ancora.</translation> </message> <message> <location line="+0"/> <source>The signature did not match the message digest.</source> <translation>La firma non corrisponde al sunto del messaggio.</translation> </message> <message> <location line="+7"/> <source>Message verification failed.</source> <translation>Verifica messaggio fallita.</translation> </message> <message> <location line="+5"/> <source>Message verified.</source> <translation>Messaggio verificato.</translation> </message> </context> <context> <name>TrafficGraphWidget</name> <message> <location filename="../trafficgraphwidget.cpp" line="+75"/> <source>KB/s</source> <translation type="unfinished"/> </message> </context> <context> <name>TransactionDesc</name> <message> <location filename="../transactiondesc.cpp" line="+25"/> <source>Open until %1</source> <translation>Aperto fino a %1</translation> </message> <message> <location line="+6"/> <source>conflicted</source> <translation>in conflitto</translation> </message> <message> <location line="+2"/> <source>%1/offline</source> <translation>%1/offline</translation> </message> <message> <location line="+2"/> <source>%1/unconfirmed</source> <translation>%1/non confermato</translation> </message> <message> <location line="+2"/> <source>%1 confirmations</source> <translation>%1 conferme</translation> </message> <message> <location line="+17"/> <source>Status</source> <translation>Stato</translation> </message> <message numerus="yes"> <location line="+7"/> <source>, broadcast through %n node(s)</source> <translation><numerusform>, trasmesso attraverso %n nodo</numerusform><numerusform>, trasmesso attraverso %n nodi</numerusform></translation> </message> <message> <location line="+4"/> <source>Date</source> <translation>Data</translation> </message> <message> <location line="+7"/> <source>Source</source> <translation>Sorgente</translation> </message> <message> <location line="+0"/> <source>Generated</source> <translation>Generato</translation> </message> <message> <location line="+5"/> <location line="+13"/> <source>From</source> <translation>Da</translation> </message> <message> <location line="+1"/> <location line="+19"/> <location line="+58"/> <source>To</source> <translation>A</translation> </message> <message> <location line="-74"/> <location line="+2"/> <source>own address</source> <translation>proprio indirizzo</translation> </message> <message> <location line="-2"/> <source>label</source> <translation>etichetta</translation> </message> <message> <location line="+34"/> <location line="+12"/> <location line="+45"/> <location line="+17"/> <location line="+30"/> <source>Credit</source> <translation>Credito</translation> </message> <message numerus="yes"> <location line="-102"/> <source>matures in %n more block(s)</source> <translation><numerusform>matura in %n ulteriore blocco</numerusform><numerusform>matura in altri %n blocchi</numerusform></translation> </message> <message> <location line="+2"/> <source>not accepted</source> <translation>non accettate</translation> </message> <message> <location line="+44"/> <location line="+8"/> <location line="+15"/> <location line="+30"/> <source>Debit</source> <translation>Debito</translation> </message> <message> <location line="-39"/> <source>Transaction fee</source> <translation>Commissione transazione</translation> </message> <message> <location line="+16"/> <source>Net amount</source> <translation>Importo netto</translation> </message> <message> <location line="+6"/> <source>Message</source> <translation>Messaggio</translation> </message> <message> <location line="+2"/> <source>Comment</source> <translation>Commento</translation> </message> <message> <location line="+2"/> <source>Transaction ID</source> <translation>ID della transazione</translation> </message> <message> <location line="+3"/> <source>Generated coins must mature 510 blocks before they can be spent. When you generated this block, it was broadcast to the network to be added to the block chain. If it fails to get into the chain, its state will change to &quot;not accepted&quot; and it won&apos;t be spendable. This may occasionally happen if another node generates a block within a few seconds of yours.</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>Debug information</source> <translation>Informazione di debug</translation> </message> <message> <location line="+8"/> <source>Transaction</source> <translation>Transazione</translation> </message> <message> <location line="+5"/> <source>Inputs</source> <translation>Input</translation> </message> <message> <location line="+21"/> <source>Amount</source> <translation>Importo</translation> </message> <message> <location line="+1"/> <source>true</source> <translation>vero</translation> </message> <message> <location line="+0"/> <source>false</source> <translation>falso</translation> </message> <message> <location line="-202"/> <source>, has not been successfully broadcast yet</source> <translation>, non è stato ancora trasmesso con successo</translation> </message> <message numerus="yes"> <location line="-36"/> <source>Open for %n more block(s)</source> <translation type="unfinished"><numerusform></numerusform><numerusform></numerusform></translation> </message> <message> <location line="+67"/> <source>unknown</source> <translation>sconosciuto</translation> </message> </context> <context> <name>TransactionDescDialog</name> <message> <location filename="../forms/transactiondescdialog.ui" line="+14"/> <source>Transaction details</source> <translation>Dettagli sulla transazione</translation> </message> <message> <location line="+6"/> <source>This pane shows a detailed description of the transaction</source> <translation>Questo pannello mostra una descrizione dettagliata della transazione</translation> </message> </context> <context> <name>TransactionTableModel</name> <message> <location filename="../transactiontablemodel.cpp" line="+231"/> <source>Date</source> <translation>Data</translation> </message> <message> <location line="+0"/> <source>Type</source> <translation>Tipo</translation> </message> <message> <location line="+0"/> <source>Address</source> <translation>Indirizzo</translation> </message> <message> <location line="+0"/> <source>Amount</source> <translation>Importo</translation> </message> <message> <location line="+52"/> <source>Open until %1</source> <translation>Aperto fino a %1</translation> </message> <message> <location line="+12"/> <source>Confirmed (%1 confirmations)</source> <translation>Confermato (%1 conferme)</translation> </message> <message numerus="yes"> <location line="-15"/> <source>Open for %n more block(s)</source> <translation><numerusform>Aperto per %n altro blocco</numerusform><numerusform>Aperto per altri %n blocchi</numerusform></translation> </message> <message> <location line="+6"/> <source>Offline</source> <translation>Offline</translation> </message> <message> <location line="+3"/> <source>Unconfirmed</source> <translation>Non confermato:</translation> </message> <message> <location line="+3"/> <source>Confirming (%1 of %2 recommended confirmations)</source> <translation>In conferma (%1 di %2 conferme raccomandate)</translation> </message> <message> <location line="+6"/> <source>Conflicted</source> <translation>In conflitto</translation> </message> <message> <location line="+3"/> <source>Immature (%1 confirmations, will be available after %2)</source> <translation>Immaturo (%1 conferme, sarà disponibile fra %2)</translation> </message> <message> <location line="+3"/> <source>This block was not received by any other nodes and will probably not be accepted!</source> <translation>Questo blocco non è stato ricevuto da altri nodi e probabilmente non sarà accettato!</translation> </message> <message> <location line="+3"/> <source>Generated but not accepted</source> <translation>Generati, ma non accettati</translation> </message> <message> <location line="+42"/> <source>Received with</source> <translation>Ricevuto tramite</translation> </message> <message> <location line="+2"/> <source>Received from</source> <translation>Ricevuto da</translation> </message> <message> <location line="+3"/> <source>Sent to</source> <translation>Spedito a</translation> </message> <message> <location line="+2"/> <source>Payment to yourself</source> <translation>Pagamento a te stesso</translation> </message> <message> <location line="+2"/> <source>Mined</source> <translation>Ottenuto dal mining</translation> </message> <message> <location line="+38"/> <source>(n/a)</source> <translation>(N / a)</translation> </message> <message> <location line="+194"/> <source>Transaction status. Hover over this field to show number of confirmations.</source> <translation>Stato della transazione. Passare con il mouse su questo campo per vedere il numero di conferme.</translation> </message> <message> <location line="+2"/> <source>Date and time that the transaction was received.</source> <translation>Data e ora in cui la transazione è stata ricevuta.</translation> </message> <message> <location line="+2"/> <source>Type of transaction.</source> <translation>Tipo di transazione.</translation> </message> <message> <location line="+2"/> <source>Destination address of transaction.</source> <translation>Indirizzo di destinazione della transazione.</translation> </message> <message> <location line="+2"/> <source>Amount removed from or added to balance.</source> <translation>Importo rimosso o aggiunto al saldo.</translation> </message> </context> <context> <name>TransactionView</name> <message> <location filename="../transactionview.cpp" line="+54"/> <location line="+17"/> <source>All</source> <translation>Tutti</translation> </message> <message> <location line="-16"/> <source>Today</source> <translation>Oggi</translation> </message> <message> <location line="+1"/> <source>This week</source> <translation>Questa settimana</translation> </message> <message> <location line="+1"/> <source>This month</source> <translation>Questo mese</translation> </message> <message> <location line="+1"/> <source>Last month</source> <translation>Il mese scorso</translation> </message> <message> <location line="+1"/> <source>This year</source> <translation>Quest&apos;anno</translation> </message> <message> <location line="+1"/> <source>Range...</source> <translation>Intervallo...</translation> </message> <message> <location line="+12"/> <source>Received with</source> <translation>Ricevuto tramite</translation> </message> <message> <location line="+2"/> <source>Sent to</source> <translation>Spedito a</translation> </message> <message> <location line="+2"/> <source>To yourself</source> <translation>A te</translation> </message> <message> <location line="+1"/> <source>Mined</source> <translation>Ottenuto dal mining</translation> </message> <message> <location line="+1"/> <source>Other</source> <translation>Altro</translation> </message> <message> <location line="+7"/> <source>Enter address or label to search</source> <translation>Inserisci un indirizzo o un&apos;etichetta da cercare</translation> </message> <message> <location line="+7"/> <source>Min amount</source> <translation>Importo minimo</translation> </message> <message> <location line="+34"/> <source>Copy address</source> <translation>Copia l&apos;indirizzo</translation> </message> <message> <location line="+1"/> <source>Copy label</source> <translation>Copia l&apos;etichetta</translation> </message> <message> <location line="+1"/> <source>Copy amount</source> <translation>Copia l&apos;importo</translation> </message> <message> <location line="+1"/> <source>Copy transaction ID</source> <translation>Copia l&apos;ID transazione</translation> </message> <message> <location line="+1"/> <source>Edit label</source> <translation>Modifica l&apos;etichetta</translation> </message> <message> <location line="+1"/> <source>Show transaction details</source> <translation>Mostra i dettagli della transazione</translation> </message> <message> <location line="+138"/> <source>Export Transaction Data</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Comma separated file (*.csv)</source> <translation>Testo CSV (*.csv)</translation> </message> <message> <location line="+8"/> <source>Confirmed</source> <translation>Confermato</translation> </message> <message> <location line="+1"/> <source>Date</source> <translation>Data</translation> </message> <message> <location line="+1"/> <source>Type</source> <translation>Tipo</translation> </message> <message> <location line="+1"/> <source>Label</source> <translation>Etichetta</translation> </message> <message> <location line="+1"/> <source>Address</source> <translation>Indirizzo</translation> </message> <message> <location line="+1"/> <source>Amount</source> <translation>Importo</translation> </message> <message> <location line="+1"/> <source>ID</source> <translation>ID</translation> </message> <message> <location line="+4"/> <source>Error exporting</source> <translation type="unfinished"/> </message> <message> <location line="+0"/> <source>Could not write to file %1.</source> <translation type="unfinished"/> </message> <message> <location line="+100"/> <source>Range:</source> <translation>Intervallo:</translation> </message> <message> <location line="+8"/> <source>to</source> <translation>a</translation> </message> </context> <context> <name>WalletModel</name> <message> <location filename="../walletmodel.cpp" line="+208"/> <source>Sending...</source> <translation type="unfinished"/> </message> </context> <context> <name>bitcoin-core</name> <message> <location filename="../bitcoinstrings.cpp" line="+173"/> <source>Demonic version</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Usage:</source> <translation>Utilizzo:</translation> </message> <message> <location line="+1"/> <source>Send command to -server or demonicd</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>List commands</source> <translation>Lista comandi </translation> </message> <message> <location line="+1"/> <source>Get help for a command</source> <translation>Aiuto su un comando </translation> </message> <message> <location line="-147"/> <source>Options:</source> <translation>Opzioni: </translation> </message> <message> <location line="+2"/> <source>Specify configuration file (default: demonic.conf)</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Specify pid file (default: demonicd.pid)</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Specify wallet file (within data directory)</source> <translation>Specifica il file portafoglio (nella cartella dati)</translation> </message> <message> <location line="-1"/> <source>Specify data directory</source> <translation>Specifica la cartella dati </translation> </message> <message> <location line="-25"/> <source>%s, you must set a rpcpassword in the configuration file: %s It is recommended you use the following random password: rpcuser=demonicrpc rpcpassword=%s (you do not need to remember this password) The username and password MUST NOT be the same. If the file does not exist, create it with owner-readable-only file permissions. It is also recommended to set alertnotify so you are notified of problems; for example: alertnotify=echo %%s | mail -s &quot;Demonic Alert&quot; admin@foo.com </source> <translation type="unfinished"/> </message> <message> <location line="+27"/> <source>Set database cache size in megabytes (default: 25)</source> <translation>Imposta la dimensione cache del database in megabyte (predefinita: 25)</translation> </message> <message> <location line="+1"/> <source>Set database disk log size in megabytes (default: 100)</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <source>Listen for connections on &lt;port&gt; (default: 15714 or testnet: 25714)</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Maintain at most &lt;n&gt; connections to peers (default: 125)</source> <translation>Mantieni al massimo &lt;n&gt; connessioni ai peer (predefinite: 125)</translation> </message> <message> <location line="+3"/> <source>Connect to a node to retrieve peer addresses, and disconnect</source> <translation>Connessione ad un nodo per ricevere l&apos;indirizzo del peer, e disconnessione</translation> </message> <message> <location line="+1"/> <source>Specify your own public address</source> <translation>Specifica il tuo indirizzo pubblico</translation> </message> <message> <location line="+4"/> <source>Bind to given address. Use [host]:port notation for IPv6</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Query for peer addresses via DNS lookup, if low on addresses (default: 1 unless -connect)</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Always query for peer addresses via DNS lookup (default: 0)</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <source>Threshold for disconnecting misbehaving peers (default: 100)</source> <translation>Soglia di disconnessione dei peer di cattiva qualità (predefinita: 100)</translation> </message> <message> <location line="+1"/> <source>Number of seconds to keep misbehaving peers from reconnecting (default: 86400)</source> <translation>Numero di secondi di sospensione che i peer di cattiva qualità devono trascorrere prima di riconnettersi (predefiniti: 86400)</translation> </message> <message> <location line="-36"/> <source>An error occurred while setting up the RPC port %u for listening on IPv4: %s</source> <translation>Errore riscontrato durante l&apos;impostazione della porta RPC %u per l&apos;ascolto su IPv4: %s</translation> </message> <message> <location line="+63"/> <source>Listen for JSON-RPC connections on &lt;port&gt; (default: 15715 or testnet: 25715)</source> <translation type="unfinished"/> </message> <message> <location line="-16"/> <source>Accept command line and JSON-RPC commands</source> <translation>Accetta da linea di comando e da comandi JSON-RPC </translation> </message> <message> <location line="+1"/> <source>Run in the background as a daemon and accept commands</source> <translation>Esegui in background come demone e accetta i comandi </translation> </message> <message> <location line="+1"/> <source>Use the test network</source> <translation>Utilizza la rete di prova </translation> </message> <message> <location line="-24"/> <source>Accept connections from outside (default: 1 if no -proxy or -connect)</source> <translation>Accetta connessioni dall&apos;esterno (predefinito: 1 se no -proxy o -connect)</translation> </message> <message> <location line="-28"/> <source>An error occurred while setting up the RPC port %u for listening on IPv6, falling back to IPv4: %s</source> <translation>Errore riscontrato durante l&apos;impostazione della porta RPC %u per l&apos;ascolto su IPv6, tornando su IPv4: %s</translation> </message> <message> <location line="+94"/> <source>Set maximum size of high-priority/low-fee transactions in bytes (default: 27000)</source> <translation type="unfinished"/> </message> <message> <location line="+15"/> <source>Warning: -paytxfee is set very high! This is the transaction fee you will pay if you send a transaction.</source> <translation>Attenzione: -paytxfee è molto alta. Questa è la commissione che si paga quando si invia una transazione.</translation> </message> <message> <location line="-104"/> <source>Warning: Please check that your computer&apos;s date and time are correct! If your clock is wrong Demonic will not work properly.</source> <translation type="unfinished"/> </message> <message> <location line="+132"/> <source>Warning: error reading wallet.dat! All keys read correctly, but transaction data or address book entries might be missing or incorrect.</source> <translation>Attenzione: errore di lettura di wallet.dat! Tutte le chiave lette correttamente, ma i dati delle transazioni o le voci in rubrica potrebbero mancare o non essere corretti.</translation> </message> <message> <location line="-17"/> <source>Warning: wallet.dat corrupt, data salvaged! Original wallet.dat saved as wallet.{timestamp}.bak in %s; if your balance or transactions are incorrect you should restore from a backup.</source> <translation>Attenzione: wallet.dat corrotto, dati salvati! Il wallet.dat originale salvato come wallet.{timestamp}.bak in %s; se il tuo bilancio o le transazioni non sono corrette dovresti ripristinare da un backup.</translation> </message> <message> <location line="-34"/> <source>Attempt to recover private keys from a corrupt wallet.dat</source> <translation>Tenta di recuperare le chiavi private da un wallet.dat corrotto</translation> </message> <message> <location line="+5"/> <source>Block creation options:</source> <translation>Opzioni creazione blocco:</translation> </message> <message> <location line="-68"/> <source>Connect only to the specified node(s)</source> <translation>Connetti solo al nodo specificato</translation> </message> <message> <location line="+4"/> <source>Discover own IP address (default: 1 when listening and no -externalip)</source> <translation>Scopri proprio indirizzo IP (predefinito: 1 se in ascolto e no -externalip)</translation> </message> <message> <location line="+102"/> <source>Failed to listen on any port. Use -listen=0 if you want this.</source> <translation>Impossibile mettersi in ascolto su una porta. Usa -listen=0 se vuoi usare questa opzione.</translation> </message> <message> <location line="-92"/> <source>Sync checkpoints policy (default: strict)</source> <translation type="unfinished"/> </message> <message> <location line="+90"/> <source>Invalid -tor address: &apos;%s&apos;</source> <translation type="unfinished"/> </message> <message> <location line="+4"/> <source>Invalid amount for -reservebalance=&lt;amount&gt;</source> <translation type="unfinished"/> </message> <message> <location line="-89"/> <source>Maximum per-connection receive buffer, &lt;n&gt;*1000 bytes (default: 5000)</source> <translation>Buffer di ricezione massimo per connessione, &lt;n&gt;*1000 byte (predefinito: 5000)</translation> </message> <message> <location line="+1"/> <source>Maximum per-connection send buffer, &lt;n&gt;*1000 bytes (default: 1000)</source> <translation>Buffer di invio massimo per connessione, &lt;n&gt;*1000 byte (predefinito: 1000)</translation> </message> <message> <location line="-17"/> <source>Only connect to nodes in network &lt;net&gt; (IPv4, IPv6 or Tor)</source> <translation>Connetti solo a nodi nella rete &lt;net&gt; (IPv4, IPv6 o Tor)</translation> </message> <message> <location line="+31"/> <source>Prepend debug output with timestamp</source> <translation type="unfinished"/> </message> <message> <location line="+40"/> <source>SSL options: (see the Bitcoin Wiki for SSL setup instructions)</source> <translation>Opzioni SSL: (vedi il wiki di Bitcoin per le istruzioni di configurazione SSL)</translation> </message> <message> <location line="-38"/> <source>Send trace/debug info to console instead of debug.log file</source> <translation>Invia le informazioni di trace/debug alla console invece che al file debug.log</translation> </message> <message> <location line="+34"/> <source>Set maximum block size in bytes (default: 250000)</source> <translation type="unfinished"/> </message> <message> <location line="-1"/> <source>Set minimum block size in bytes (default: 0)</source> <translation>Imposta dimensione minima del blocco in bytes (predefinita: 0)</translation> </message> <message> <location line="-34"/> <source>Shrink debug.log file on client startup (default: 1 when no -debug)</source> <translation>Riduci il file debug.log all&apos;avvio del client (predefinito: 1 se non impostato -debug)</translation> </message> <message> <location line="-42"/> <source>Specify connection timeout in milliseconds (default: 5000)</source> <translation>Specifica il timeout di connessione in millisecondi (predefinito: 5000)</translation> </message> <message> <location line="+116"/> <source>Unable to sign checkpoint, wrong checkpointkey? </source> <translation type="unfinished"/> </message> <message> <location line="-87"/> <source>Use UPnP to map the listening port (default: 0)</source> <translation>Usa UPnP per mappare la porta in ascolto (predefinito: 0)</translation> </message> <message> <location line="-1"/> <source>Use UPnP to map the listening port (default: 1 when listening)</source> <translation>Usa UPnP per mappare la porta in ascolto (predefinito: 1 when listening)</translation> </message> <message> <location line="-26"/> <source>Use proxy to reach tor hidden services (default: same as -proxy)</source> <translation type="unfinished"/> </message> <message> <location line="+46"/> <source>Username for JSON-RPC connections</source> <translation>Nome utente per connessioni JSON-RPC </translation> </message> <message> <location line="+54"/> <source>Verifying database integrity...</source> <translation type="unfinished"/> </message> <message> <location line="+43"/> <source>Error: Wallet locked, unable to create transaction!</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Error: This transaction requires a transaction fee of at least %s because of its amount, complexity, or use of recently received funds!</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Error: Transaction creation failed!</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Error: The transaction was rejected! This might happen if some of the coins in your wallet were already spent, such as if you used a copy of wallet.dat and coins were spent in the copy but not marked as spent here.</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>Warning</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Information</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>WARNING: syncronized checkpoint violation detected, but skipped!</source> <translation type="unfinished"/> </message> <message> <location line="-1"/> <source>Warning: This version is obsolete, upgrade required!</source> <translation>Attenzione: questa versione è obsoleta, aggiornamento necessario!</translation> </message> <message> <location line="-53"/> <source>wallet.dat corrupt, salvage failed</source> <translation>wallet.dat corrotto, salvataggio fallito</translation> </message> <message> <location line="-59"/> <source>Password for JSON-RPC connections</source> <translation>Password per connessioni JSON-RPC </translation> </message> <message> <location line="-48"/> <source>Connect through SOCKS5 proxy</source> <translation type="unfinished"/> </message> <message> <location line="+17"/> <source>Sync time with other nodes. Disable if time on your system is precise e.g. syncing with NTP (default: 1)</source> <translation type="unfinished"/> </message> <message> <location line="+13"/> <source>When creating transactions, ignore inputs with value less than this (default: 0.01)</source> <translation type="unfinished"/> </message> <message> <location line="+6"/> <source>Output debugging information (default: 0, supplying &lt;category&gt; is optional)</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>If &lt;category&gt; is not supplied, output all debugging information.</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>&lt;category&gt; can be:</source> <translation type="unfinished"/> </message> <message> <location line="+4"/> <source>Enter regression test mode, which uses a special chain in which blocks can be solved instantly. This is intended for regression testing tools and app development.</source> <translation type="unfinished"/> </message> <message> <location line="+8"/> <source>Allow JSON-RPC connections from specified IP address</source> <translation>Consenti connessioni JSON-RPC dall&apos;indirizzo IP specificato </translation> </message> <message> <location line="+1"/> <source>Send commands to node running on &lt;ip&gt; (default: 127.0.0.1)</source> <translation>Inviare comandi al nodo in esecuzione su &lt;ip&gt; (predefinito: 127.0.0.1)</translation> </message> <message> <location line="+1"/> <source>Wait for RPC server to start</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Set the number of threads to service RPC calls (default: 4)</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Execute command when the best block changes (%s in cmd is replaced by block hash)</source> <translation>Esegui il comando quando il miglior block cambia(%s nel cmd è sostituito dall&apos;hash del blocco)</translation> </message> <message> <location line="+3"/> <source>Execute command when a wallet transaction changes (%s in cmd is replaced by TxID)</source> <translation>Esegui comando quando una transazione del portafoglio cambia (%s in cmd è sostituito da TxID)</translation> </message> <message> <location line="+3"/> <source>Require a confirmations for change (default: 0)</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Execute command when a relevant alert is received (%s in cmd is replaced by message)</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Upgrade wallet to latest format</source> <translation>Aggiorna il wallet all&apos;ultimo formato</translation> </message> <message> <location line="+1"/> <source>Set key pool size to &lt;n&gt; (default: 100)</source> <translation>Impostare la quantità di chiavi di riserva a &lt;n&gt; (predefinita: 100)</translation> </message> <message> <location line="+1"/> <source>Rescan the block chain for missing wallet transactions</source> <translation>Ripeti analisi della catena dei blocchi per cercare le transazioni mancanti dal portamonete </translation> </message> <message> <location line="+3"/> <source>How thorough the block verification is (0-6, default: 1)</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Imports blocks from external blk000?.dat file</source> <translation type="unfinished"/> </message> <message> <location line="+9"/> <source>Use OpenSSL (https) for JSON-RPC connections</source> <translation>Utilizzare OpenSSL (https) per le connessioni JSON-RPC </translation> </message> <message> <location line="+1"/> <source>Server certificate file (default: server.cert)</source> <translation>File certificato del server (predefinito: server.cert)</translation> </message> <message> <location line="+1"/> <source>Server private key (default: server.pem)</source> <translation>Chiave privata del server (predefinito: server.pem)</translation> </message> <message> <location line="+5"/> <source>Error: Unsupported argument -socks found. Setting SOCKS version isn&apos;t possible anymore, only SOCKS5 proxies are supported.</source> <translation type="unfinished"/> </message> <message> <location line="+8"/> <source>Initialization sanity check failed. Demonic is shutting down.</source> <translation type="unfinished"/> </message> <message> <location line="+21"/> <source>Error loading block database</source> <translation type="unfinished"/> </message> <message> <location line="+28"/> <source>Error: Wallet unlocked for staking only, unable to create transaction.</source> <translation type="unfinished"/> </message> <message> <location line="+17"/> <source>Error: Disk space is low!</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>This is a pre-release test build - use at your own risk - do not use for mining or merchant applications</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>WARNING: Invalid checkpoint found! Displayed transactions may not be correct! You may need to upgrade, or notify developers.</source> <translation type="unfinished"/> </message> <message> <location line="-174"/> <source>This help message</source> <translation>Questo messaggio di aiuto </translation> </message> <message> <location line="+105"/> <source>Wallet %s resides outside data directory %s.</source> <translation type="unfinished"/> </message> <message> <location line="+36"/> <source>Unable to bind to %s on this computer (bind returned error %d, %s)</source> <translation>Impossibile collegarsi alla %s su questo computer (bind returned error %d, %s)</translation> </message> <message> <location line="-131"/> <source>Allow DNS lookups for -addnode, -seednode and -connect</source> <translation>Consenti ricerche DNS per aggiungere nodi e collegare </translation> </message> <message> <location line="+127"/> <source>Loading addresses...</source> <translation>Caricamento indirizzi...</translation> </message> <message> <location line="-10"/> <source>Error loading wallet.dat: Wallet corrupted</source> <translation>Errore caricamento wallet.dat: Wallet corrotto</translation> </message> <message> <location line="+4"/> <source>Error loading wallet.dat: Wallet requires newer version of Demonic</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Wallet needed to be rewritten: restart Demonic to complete</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Error loading wallet.dat</source> <translation>Errore caricamento wallet.dat</translation> </message> <message> <location line="-16"/> <source>Invalid -proxy address: &apos;%s&apos;</source> <translation>Indirizzo -proxy non valido: &apos;%s&apos;</translation> </message> <message> <location line="-1"/> <source>Unknown network specified in -onlynet: &apos;%s&apos;</source> <translation>Rete sconosciuta specificata in -onlynet: &apos;%s&apos;</translation> </message> <message> <location line="+3"/> <source>Cannot resolve -bind address: &apos;%s&apos;</source> <translation>Impossibile risolvere -bind address: &apos;%s&apos;</translation> </message> <message> <location line="+2"/> <source>Cannot resolve -externalip address: &apos;%s&apos;</source> <translation>Impossibile risolvere indirizzo -externalip: &apos;%s&apos;</translation> </message> <message> <location line="-22"/> <source>Invalid amount for -paytxfee=&lt;amount&gt;: &apos;%s&apos;</source> <translation>Importo non valido per -paytxfee=&lt;amount&gt;: &apos;%s&apos;</translation> </message> <message> <location line="+59"/> <source>Sending...</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <source>Invalid amount</source> <translation>Importo non valido</translation> </message> <message> <location line="+1"/> <source>Insufficient funds</source> <translation>Fondi insufficienti</translation> </message> <message> <location line="-40"/> <source>Loading block index...</source> <translation>Caricamento dell&apos;indice del blocco...</translation> </message> <message> <location line="-111"/> <source>Add a node to connect to and attempt to keep the connection open</source> <translation>Elérendő csomópont megadása and attempt to keep the connection open</translation> </message> <message> <location line="+126"/> <source>Unable to bind to %s on this computer. Demonic is probably already running.</source> <translation type="unfinished"/> </message> <message> <location line="-102"/> <source>Fee per KB to add to transactions you send</source> <translation type="unfinished"/> </message> <message> <location line="+33"/> <source>Minimize weight consumption (experimental) (default: 0)</source> <translation type="unfinished"/> </message> <message> <location line="+8"/> <source>How many blocks to check at startup (default: 500, 0 = all)</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Keep at most &lt;n&gt; unconnectable blocks in memory (default: %u)</source> <translation type="unfinished"/> </message> <message> <location line="+11"/> <source>Acceptable ciphers (default: TLSv1.2+HIGH:TLSv1+HIGH:!SSLv2:!aNULL:!eNULL:!3DES:@STRENGTH)</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Warning: Deprecated argument -debugnet ignored, use -debug=net</source> <translation type="unfinished"/> </message> <message> <location line="+8"/> <source>Invalid amount for -mininput=&lt;amount&gt;: &apos;%s&apos;</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Cannot obtain a lock on data directory %s. Demonic is probably already running.</source> <translation type="unfinished"/> </message> <message> <location line="+4"/> <source>Error initializing wallet database environment %s!</source> <translation type="unfinished"/> </message> <message> <location line="+16"/> <source>Loading wallet...</source> <translation>Caricamento portamonete...</translation> </message> <message> <location line="+8"/> <source>Cannot downgrade wallet</source> <translation>Non è possibile retrocedere il wallet</translation> </message> <message> <location line="+1"/> <source>Cannot write default address</source> <translation>Non è possibile scrivere l&apos;indirizzo predefinito</translation> </message> <message> <location line="+1"/> <source>Rescanning...</source> <translation>Ripetere la scansione...</translation> </message> <message> <location line="+2"/> <source>Done loading</source> <translation>Caricamento completato</translation> </message> <message> <location line="-161"/> <source>To use the %s option</source> <translation>Per usare la opzione %s</translation> </message> <message> <location line="+188"/> <source>Error</source> <translation>Errore</translation> </message> <message> <location line="-18"/> <source>You must set rpcpassword=&lt;password&gt; in the configuration file: %s If the file does not exist, create it with owner-readable-only file permissions.</source> <translation>Devi settare rpcpassword=&lt;password&gt; nel file di configurazione: %s Se il file non esiste, crealo con i permessi di amministratore</translation> </message> </context> </TS>
{ "content_hash": "8b80665b0362a8593719c8081d672d37", "timestamp": "", "source": "github", "line_count": 3349, "max_line_length": 395, "avg_line_length": 35.77157360406091, "alnum_prop": 0.609721283149275, "repo_name": "CryptoDemonic/demonic", "id": "520ad4a2f32c73828a4c7e53dfc73b16772a4cdd", "size": "119856", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/qt/locale/bitcoin_it.ts", "mode": "33188", "license": "mit", "language": [ { "name": "Assembly", "bytes": "51312" }, { "name": "C", "bytes": "465529" }, { "name": "C++", "bytes": "2533501" }, { "name": "CSS", "bytes": "1127" }, { "name": "HTML", "bytes": "50620" }, { "name": "Makefile", "bytes": "12088" }, { "name": "NSIS", "bytes": "5914" }, { "name": "Objective-C", "bytes": "858" }, { "name": "Objective-C++", "bytes": "6899" }, { "name": "Python", "bytes": "54355" }, { "name": "QMake", "bytes": "14146" }, { "name": "Shell", "bytes": "8509" } ], "symlink_target": "" }
from pathlib import Path from typing import List def insert_documentation(file_path: Path, content: List[str], header: str, footer: str): text = file_path.read_text().splitlines(keepends=True) replacing = False result: List[str] = [] for line in text: if line.startswith(header): replacing = True result.append(line) result.extend(content) if line.startswith(footer): replacing = False if not replacing: result.append(line) file_path.write_text("".join(result))
{ "content_hash": "95efd67826d6a4b804639b2428b98382", "timestamp": "", "source": "github", "line_count": 18, "max_line_length": 88, "avg_line_length": 31.555555555555557, "alnum_prop": 0.6197183098591549, "repo_name": "lyft/incubator-airflow", "id": "871aee3672ffa5e212533ca961b0965d1925aab1", "size": "1354", "binary": false, "copies": "1", "ref": "refs/heads/main", "path": "scripts/ci/pre_commit/common_precommit_utils.py", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "13715" }, { "name": "Dockerfile", "bytes": "17280" }, { "name": "HTML", "bytes": "161328" }, { "name": "JavaScript", "bytes": "25360" }, { "name": "Jinja", "bytes": "8565" }, { "name": "Jupyter Notebook", "bytes": "2933" }, { "name": "Mako", "bytes": "1339" }, { "name": "Python", "bytes": "10019710" }, { "name": "Shell", "bytes": "220780" } ], "symlink_target": "" }
using System; using System.Data; using System.Collections; using MbUnit.Framework; using MbUnit.Core.Framework; namespace TestFu.Tests.Data.Generators { using TestFu.Data; using TestFu.Data.Generators; public class AllDataGeneratorFactory { private Random rnd =new Random((int)System.DateTime.Now.Ticks); private DataTable table=new DataTable("AllTypes"); private Hashtable generators = new Hashtable(); public AllDataGeneratorFactory() { // filling table columns and generators this.addGenerator(typeof(byte[])); this.addGenerator(typeof(bool)); this.addGenerator(typeof(byte)); this.addGenerator(typeof(DateTime)); this.addGenerator(typeof(decimal)); this.addGenerator(typeof(double)); this.addGenerator(typeof(Guid)); this.addGenerator(typeof(Int16)); this.addGenerator(typeof(Int32)); this.addGenerator(typeof(Int64)); this.addGenerator(typeof(Single)); this.addGenerator(typeof(String)); this.addGenerator("UserFirstName", typeof(string)); DataColumn col = table.Columns.Add("LoremIpsum", typeof(string)); IDataGenerator gen = new LoremIpsumStringGenerator(col); this.generators.Add(gen.GetType(), gen); } private void addGenerator(string columnName, Type type) { DataColumn col = table.Columns.Add(columnName, type); IDataGenerator gen = DataGeneratorConverter.FromColumn(col); this.generators.Add(gen.GetType(), gen); } private void addGenerator(Type type) { addGenerator(type.Name, type); } public DataTable Table { get { return this.table; } } public ICollection Generators { get { return this.generators.Values; } } [Factory] public BinaryGeneratorBase Binary { get { return (BinaryGeneratorBase)this.generators[typeof(BinaryGeneratorBase)]; } } [Factory] public BooleanGenerator Boolean { get { return (BooleanGenerator)this.generators[typeof(BooleanGenerator)]; } } [Factory] public ByteGenerator Byte { get { return (ByteGenerator)this.generators[typeof(ByteGenerator)]; } } [Factory] public NowDateTimeGenerator DateTime { get { return (NowDateTimeGenerator)this.generators[typeof(NowDateTimeGenerator)]; } } [Factory] public DecimalGenerator Decimal { get { return (DecimalGenerator)this.generators[typeof(DecimalGenerator)]; } } [Factory] public DoubleGenerator Double { get { return (DoubleGenerator)this.generators[typeof(DoubleGenerator)]; } } [Factory] public GuidGenerator Guid { get { return (GuidGenerator)this.generators[typeof(GuidGenerator)]; } } [Factory] public Int16Generator Int16 { get { return (Int16Generator)this.generators[typeof(Int16Generator)]; } } [Factory] public Int32Generator Int32 { get { return (Int32Generator)this.generators[typeof(Int32Generator)]; } } [Factory] public Int64Generator Int64 { get { return (Int64Generator)this.generators[typeof(Int64Generator)]; } } [Factory] public SingleGenerator Single { get { return (SingleGenerator)this.generators[typeof(SingleGenerator)]; } } [Factory] public RangeStringGenerator RangeString { get { return (RangeStringGenerator)this.generators[typeof(RangeStringGenerator)]; } } [Factory] public NameStringGenerator NameString { get { return (NameStringGenerator)this.generators[typeof(NameStringGenerator)]; } } [Factory] public LoremIpsumStringGenerator LoremIpsum { get { return (LoremIpsumStringGenerator)this.generators[typeof(LoremIpsumStringGenerator)]; } } } }
{ "content_hash": "8bdf592b12517be248c4f43f2d0218e2", "timestamp": "", "source": "github", "line_count": 190, "max_line_length": 101, "avg_line_length": 24.2, "alnum_prop": 0.5628534145280557, "repo_name": "Gallio/mbunit-v2", "id": "8ce86238497293793bb7f22bb3f72f342d44e948", "size": "4598", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/mbunit/TestFu.Tests/Data/Generators/AllDataGeneratorFactory.cs", "mode": "33188", "license": "apache-2.0", "language": [], "symlink_target": "" }
<?xml version="1.0" encoding="utf-8"?> <!DOCTYPE TS> <TS version="2.1" language="hi_IN"> <context> <name>ColorDialog</name> <message> <location filename="../ColorDialog.ui" line="14"/> <source>Customize Colors</source> <translation type="unfinished"></translation> </message> <message> <location filename="../ColorDialog.ui" line="24"/> <source>Item Type</source> <translation type="unfinished"></translation> </message> <message> <location filename="../ColorDialog.ui" line="29"/> <source>Color</source> <translation type="unfinished"></translation> </message> <message> <location filename="../ColorDialog.ui" line="34"/> <source>Sample</source> <translation type="unfinished"></translation> </message> <message> <location filename="../ColorDialog.ui" line="44"/> <location filename="../ColorDialog.cpp" line="55"/> <source>Select Color</source> <translation type="unfinished"></translation> </message> <message> <location filename="../ColorDialog.ui" line="64"/> <source>Cancel</source> <translation type="unfinished"></translation> </message> <message> <location filename="../ColorDialog.ui" line="71"/> <source>Apply</source> <translation type="unfinished"></translation> </message> </context> <context> <name>DnDTabBar</name> <message> <location filename="../DnDTabBar.h" line="43"/> <source>Detach Tab</source> <translation type="unfinished"></translation> </message> </context> <context> <name>MainUI</name> <message> <location filename="../MainUI.ui" line="63"/> <source>Find the previous match</source> <translation type="unfinished"></translation> </message> <message> <location filename="../MainUI.ui" line="66"/> <location filename="../MainUI.ui" line="79"/> <location filename="../MainUI.ui" line="130"/> <location filename="../MainUI.ui" line="143"/> <location filename="../MainUI.ui" line="155"/> <source>...</source> <translation type="unfinished"></translation> </message> <message> <location filename="../MainUI.ui" line="76"/> <source>Find the next match</source> <translation type="unfinished"></translation> </message> <message> <location filename="../MainUI.ui" line="86"/> <source>Replace:</source> <translation type="unfinished"></translation> </message> <message> <location filename="../MainUI.ui" line="105"/> <source>Match case</source> <translation type="unfinished"></translation> </message> <message> <location filename="../MainUI.ui" line="127"/> <source>Replace next match</source> <translation type="unfinished"></translation> </message> <message> <location filename="../MainUI.ui" line="140"/> <source>Replace all matches (to end of document)</source> <translation type="unfinished"></translation> </message> <message> <location filename="../MainUI.ui" line="152"/> <source>Hide the find/replace options</source> <translation type="unfinished"></translation> </message> <message> <location filename="../MainUI.ui" line="165"/> <source>Find:</source> <translation type="unfinished"></translation> </message> <message> <location filename="../MainUI.ui" line="211"/> <source>Syntax Highlighting</source> <translation type="unfinished"></translation> </message> <message> <location filename="../MainUI.ui" line="218"/> <source>Tabs Location</source> <translation type="unfinished"></translation> </message> <message> <location filename="../MainUI.ui" line="193"/> <source>&amp;File</source> <translation type="unfinished"></translation> </message> <message> <location filename="../MainUI.ui" line="207"/> <source>&amp;View</source> <translation type="unfinished"></translation> </message> <message> <location filename="../MainUI.ui" line="236"/> <source>&amp;Edit</source> <translation type="unfinished"></translation> </message> <message> <location filename="../MainUI.ui" line="274"/> <source>Show Line Numbers</source> <translation type="unfinished"></translation> </message> <message> <location filename="../MainUI.ui" line="279"/> <source>None</source> <translation type="unfinished"></translation> </message> <message> <location filename="../MainUI.ui" line="284"/> <location filename="../MainUI.cpp" line="219"/> <source>New File</source> <translation type="unfinished"></translation> </message> <message> <location filename="../MainUI.ui" line="287"/> <source>Ctrl+N</source> <translation type="unfinished"></translation> </message> <message> <location filename="../MainUI.ui" line="295"/> <source>Open File</source> <translation type="unfinished"></translation> </message> <message> <location filename="../MainUI.ui" line="298"/> <source>Ctrl+O</source> <translation type="unfinished"></translation> </message> <message> <location filename="../MainUI.ui" line="306"/> <source>Save File</source> <translation type="unfinished"></translation> </message> <message> <location filename="../MainUI.ui" line="309"/> <source>Ctrl+S</source> <translation type="unfinished"></translation> </message> <message> <location filename="../MainUI.ui" line="317"/> <source>Save File As</source> <translation type="unfinished"></translation> </message> <message> <location filename="../MainUI.ui" line="322"/> <source>Close</source> <translation type="unfinished"></translation> </message> <message> <location filename="../MainUI.ui" line="325"/> <source>Ctrl+Q</source> <translation type="unfinished"></translation> </message> <message> <location filename="../MainUI.ui" line="333"/> <source>Close File</source> <translation type="unfinished"></translation> </message> <message> <location filename="../MainUI.ui" line="336"/> <source>Ctrl+W</source> <translation type="unfinished"></translation> </message> <message> <location filename="../MainUI.ui" line="344"/> <source>Customize Colors</source> <translation type="unfinished"></translation> </message> <message> <location filename="../MainUI.ui" line="355"/> <source>Wrap Lines</source> <translation type="unfinished"></translation> </message> <message> <location filename="../MainUI.ui" line="360"/> <source>Find</source> <translation type="unfinished"></translation> </message> <message> <location filename="../MainUI.ui" line="363"/> <source>Ctrl+F</source> <translation type="unfinished"></translation> </message> <message> <location filename="../MainUI.ui" line="371"/> <source>Replace</source> <translation type="unfinished"></translation> </message> <message> <location filename="../MainUI.ui" line="374"/> <source>Ctrl+R</source> <translation type="unfinished"></translation> </message> <message> <location filename="../MainUI.ui" line="388"/> <source>Show Popup Warnings</source> <translation type="unfinished"></translation> </message> <message> <location filename="../MainUI.ui" line="391"/> <location filename="../MainUI.ui" line="394"/> <source>Show warnings about unsaved changes</source> <translation type="unfinished"></translation> </message> <message> <location filename="../MainUI.ui" line="405"/> <source>Top</source> <translation type="unfinished"></translation> </message> <message> <location filename="../MainUI.ui" line="413"/> <source>Bottom</source> <translation type="unfinished"></translation> </message> <message> <location filename="../MainUI.ui" line="421"/> <source>Left</source> <translation type="unfinished"></translation> </message> <message> <location filename="../MainUI.ui" line="429"/> <source>Right</source> <translation type="unfinished"></translation> </message> <message> <location filename="../MainUI.ui" line="434"/> <source>Print</source> <translation type="unfinished"></translation> </message> <message> <location filename="../MainUI.ui" line="437"/> <source>Ctrl+P</source> <translation type="unfinished"></translation> </message> <message> <location filename="../MainUI.ui" line="448"/> <source>Show Toolbar</source> <translation type="unfinished"></translation> </message> <message> <location filename="../MainUI.cpp" line="34"/> <source>Read-Only File</source> <translation type="unfinished"></translation> </message> <message> <location filename="../MainUI.cpp" line="75"/> <source>Text Editor</source> <translation type="unfinished"></translation> </message> <message> <location filename="../MainUI.cpp" line="226"/> <source>Open File(s)</source> <translation type="unfinished"></translation> </message> <message> <location filename="../MainUI.cpp" line="226"/> <source>Text Files (*)</source> <translation type="unfinished"></translation> </message> <message> <location filename="../MainUI.cpp" line="290"/> <source>Print Content</source> <translation type="unfinished"></translation> </message> <message> <location filename="../MainUI.cpp" line="428"/> <location filename="../MainUI.cpp" line="439"/> <source>Lose Unsaved Changes?</source> <translation type="unfinished"></translation> </message> <message> <location filename="../MainUI.cpp" line="428"/> <location filename="../MainUI.cpp" line="439"/> <source>This file has unsaved changes. Do you want to close it anyway? %1</source> <translation type="unfinished"></translation> </message> <message> <location filename="../MainUI.cpp" line="546"/> <source>Save Changes before closing?</source> <translation type="unfinished"></translation> </message> <message> <location filename="../MainUI.cpp" line="547"/> <source>There are unsaved changes. Do you want save them before you close the editor? %1</source> <translation type="unfinished"></translation> </message> </context> <context> <name>PlainTextEditor</name> <message> <location filename="../PlainTextEditor.cpp" line="127"/> <source>Save File</source> <translation type="unfinished"></translation> </message> <message> <location filename="../PlainTextEditor.cpp" line="127"/> <source>Text File (*)</source> <translation type="unfinished"></translation> </message> <message> <location filename="../PlainTextEditor.cpp" line="346"/> <source>Row Number: %1, Column Number: %2</source> <translation type="unfinished"></translation> </message> <message> <location filename="../PlainTextEditor.cpp" line="355"/> <source>The following file has been changed by some other utility. Do you want to re-load it?</source> <translation type="unfinished"></translation> </message> <message> <location filename="../PlainTextEditor.cpp" line="357"/> <source>(Note: You will lose all currently-unsaved changes)</source> <translation type="unfinished"></translation> </message> <message> <location filename="../PlainTextEditor.cpp" line="361"/> <source>File Modified</source> <translation type="unfinished"></translation> </message> </context> <context> <name>XDGDesktopList</name> <message> <location filename="../../../core/libLumina/LuminaXDG.cpp" line="608"/> <source>Multimedia</source> <translation type="unfinished"></translation> </message> <message> <location filename="../../../core/libLumina/LuminaXDG.cpp" line="609"/> <source>Development</source> <translation type="unfinished"></translation> </message> <message> <location filename="../../../core/libLumina/LuminaXDG.cpp" line="610"/> <source>Education</source> <translation type="unfinished"></translation> </message> <message> <location filename="../../../core/libLumina/LuminaXDG.cpp" line="611"/> <source>Games</source> <translation type="unfinished"></translation> </message> <message> <location filename="../../../core/libLumina/LuminaXDG.cpp" line="612"/> <source>Graphics</source> <translation type="unfinished"></translation> </message> <message> <location filename="../../../core/libLumina/LuminaXDG.cpp" line="613"/> <source>Network</source> <translation type="unfinished"></translation> </message> <message> <location filename="../../../core/libLumina/LuminaXDG.cpp" line="614"/> <source>Office</source> <translation type="unfinished"></translation> </message> <message> <location filename="../../../core/libLumina/LuminaXDG.cpp" line="615"/> <source>Science</source> <translation type="unfinished"></translation> </message> <message> <location filename="../../../core/libLumina/LuminaXDG.cpp" line="616"/> <source>Settings</source> <translation type="unfinished"></translation> </message> <message> <location filename="../../../core/libLumina/LuminaXDG.cpp" line="617"/> <source>System</source> <translation type="unfinished"></translation> </message> <message> <location filename="../../../core/libLumina/LuminaXDG.cpp" line="618"/> <source>Utility</source> <translation type="unfinished"></translation> </message> <message> <location filename="../../../core/libLumina/LuminaXDG.cpp" line="619"/> <source>Wine</source> <translation type="unfinished"></translation> </message> <message> <location filename="../../../core/libLumina/LuminaXDG.cpp" line="620"/> <source>Unsorted</source> <translation type="unfinished"></translation> </message> </context> </TS>
{ "content_hash": "cf225acab64f09173d327bcc89407510", "timestamp": "", "source": "github", "line_count": 424, "max_line_length": 110, "avg_line_length": 35.72405660377358, "alnum_prop": 0.5945731828084769, "repo_name": "cpforbes/lumina", "id": "f04595d4e3efcd0360e6d85740aa7d36c241d263", "size": "15147", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src-qt5/desktop-utils/lumina-textedit/i18n/l-te_hi.ts", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "C", "bytes": "3471" }, { "name": "C++", "bytes": "2481709" }, { "name": "Go", "bytes": "4594" }, { "name": "HTML", "bytes": "355" }, { "name": "JavaScript", "bytes": "1112" }, { "name": "Makefile", "bytes": "10768" }, { "name": "PHP", "bytes": "6718" }, { "name": "Prolog", "bytes": "323" }, { "name": "Python", "bytes": "338" }, { "name": "QML", "bytes": "51215" }, { "name": "QMake", "bytes": "94535" }, { "name": "Roff", "bytes": "18338" }, { "name": "Shell", "bytes": "7983" } ], "symlink_target": "" }
package factorio.window; import factorio.calculator.AssemblerSettings; import factorio.data.Technology; public class TechnologyProductListRow extends ProductListRow { private static final long serialVersionUID = 4792177846559773999L; public TechnologyProductListRow(final Technology tech) { super(tech); } @Override protected String[] getOptions() { return new String[] {"seconds to finish", "max cap. labs"}; } @Override public double getRate() { if (Double.isNaN(this.getValue())) return 0; switch (this.getSelectedOption()) { case "max cap. labs": return 1 / (this.getValue() * this.getAssemblerSettings().getSpeed() * this.recipe.time); default: return 1 / this.getValue(); } } @Override public AssemblerSettings configure() { // TODO return null; } }
{ "content_hash": "68714d03afd02a17e58b677e52c26213", "timestamp": "", "source": "github", "line_count": 37, "max_line_length": 93, "avg_line_length": 22.756756756756758, "alnum_prop": 0.6888361045130641, "repo_name": "ricky3350/Factorio-Calculator", "id": "ec6f04761e80f61aa1bcfafc3654c17b0462ae50", "size": "842", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/factorio/window/TechnologyProductListRow.java", "mode": "33188", "license": "mit", "language": [ { "name": "Java", "bytes": "155717" }, { "name": "Lua", "bytes": "2479" } ], "symlink_target": "" }
{% extends "templates/layout.html" %} {% block page_title %} NHS Medicines alpha {% endblock %} {% block content %} <main id="content" role="main"> <div class="grid-row"> <div class="column-two-thirds"> <h1 class="heading-xlarge"><a href="/paracetamol" class="link-no-style">Paracetamol</a></h1> <h2>When will I feel better?</h2> <ul> <li><a href="/paracetamol/when-will-i-feel-better/when-will-i-feel-better-KB">Option A <span class="print">- When will I feel better KB</span></a> </ul> <nav role="navigation" class="pagination"> <div class="previous-page"> <a href="/paracetamol"> <span class="prefix">Previous page:</span> <span class="title">Paracetamol topics</span> </a> </div> </nav> </div> </div> </main> {% endblock %}
{ "content_hash": "d85b53b5de18ed0f7c8f734386ae9ab3", "timestamp": "", "source": "github", "line_count": 31, "max_line_length": 154, "avg_line_length": 27.483870967741936, "alnum_prop": 0.5786384976525821, "repo_name": "NHSChoices/medicines-alpha", "id": "cd7f46d1f3906c429356d5ec045a26820081c9cf", "size": "852", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "app/views/paracetamol/when-will-i-feel-better/index.html", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "67457" }, { "name": "HTML", "bytes": "1956816" }, { "name": "JavaScript", "bytes": "58684" }, { "name": "Shell", "bytes": "649" } ], "symlink_target": "" }
package org.cloudfoundry.client.v2.spaces; import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import org.cloudfoundry.client.v2.PaginatedResponse; import org.cloudfoundry.client.v2.users.UserResource; import org.immutables.value.Value; /** * The response payload for the List all Managers for the Space operation */ @JsonDeserialize @Value.Immutable abstract class _ListSpaceManagersResponse extends PaginatedResponse<UserResource> { }
{ "content_hash": "18ddb4729bd299a7c232aad756a74138", "timestamp": "", "source": "github", "line_count": 17, "max_line_length": 83, "avg_line_length": 26.941176470588236, "alnum_prop": 0.8231441048034934, "repo_name": "alexander071/cf-java-client", "id": "c67c2fb167e2200d6c01804078aaaccd45302036", "size": "1078", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "cloudfoundry-client/src/main/java/org/cloudfoundry/client/v2/spaces/_ListSpaceManagersResponse.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Batchfile", "bytes": "5043" }, { "name": "Java", "bytes": "4410753" }, { "name": "Shell", "bytes": "8834" } ], "symlink_target": "" }
<?php namespace spec\LdapTools\AttributeConverter; use PhpSpec\ObjectBehavior; class ConvertWindowsTimeSpec extends ObjectBehavior { protected $timestamp = "130660331300000000"; protected $genTime = "20150118053850"; function it_is_initializable() { $this->shouldHaveType('LdapTools\AttributeConverter\ConvertWindowsTime'); } function it_should_implement_AttributeConverterInterface() { $this->shouldImplement('\LdapTools\AttributeConverter\AttributeConverterInterface'); } function it_should_return_a_DateTime_object_with_the_correct_time_when_calling_fromLdap() { $this->fromLdap($this->timestamp)->shouldBeLike(new \DateTime($this->genTime, new \DateTimeZone('UTC'))); } function it_should_return_a_windows_timestamp_when_calling_toLdap() { $this->toLdap(new \DateTime($this->genTime, new \DateTimeZone('UTC')))->shouldBeEqualTo($this->timestamp); } function it_should_error_when_the_value_going_to_ldap_is_not_a_datetime_object() { $this->shouldThrow('\LdapTools\Exception\AttributeConverterException')->duringToLdap('foo'); } }
{ "content_hash": "58cdd6b1842b4c89af5a3c65eb398c20", "timestamp": "", "source": "github", "line_count": 38, "max_line_length": 114, "avg_line_length": 30.289473684210527, "alnum_prop": 0.7106863596872285, "repo_name": "ldaptools/ldaptools", "id": "351c025cff737187d648a42751c917393d64afb7", "size": "1383", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "spec/LdapTools/AttributeConverter/ConvertWindowsTimeSpec.php", "mode": "33188", "license": "mit", "language": [ { "name": "PHP", "bytes": "1542334" } ], "symlink_target": "" }
package org.uberfire.ext.wires.core.client.util; /** * Useful geometry functions taken from Java's Line2D class */ public class GeometryUtil { /** * Returns the square of the distance from a point to a line segment. * The distance measured is the distance between the specified * point and the closest point between the specified end points. * If the specified point intersects the line segment in between the * end points, this method returns 0.0. * <p> * See http://docs.oracle.com/javase/6/docs/api/java/awt/geom/Line2D.html#ptSegDist%28double,%20double,%20double,%20double,%20double,%20double%29 * @param x1 the X coordinate of the start point of the * specified line segment * @param y1 the Y coordinate of the start point of the * specified line segment * @param x2 the X coordinate of the end point of the * specified line segment * @param y2 the Y coordinate of the end point of the * specified line segment * @param px the X coordinate of the specified point being * measured against the specified line segment * @param py the Y coordinate of the specified point being * measured against the specified line segment * @return a double value that is the square of the distance from the * specified point to the specified line segment. */ public static double ptSegDistSq(double x1, double y1, double x2, double y2, double px, double py) { // Adjust vectors relative to x1,y1 // x2,y2 becomes relative vector from x1,y1 to end of segment x2 -= x1; y2 -= y1; // px,py becomes relative vector from x1,y1 to test point px -= x1; py -= y1; double dotprod = px * x2 + py * y2; double projlenSq; if (dotprod <= 0.0) { // px,py is on the side of x1,y1 away from x2,y2 // distance to segment is length of px,py vector // "length of its (clipped) projection" is now 0.0 projlenSq = 0.0; } else { // switch to backwards vectors relative to x2,y2 // x2,y2 are already the negative of x1,y1=>x2,y2 // to get px,py to be the negative of px,py=>x2,y2 // the dot product of two negated vectors is the same // as the dot product of the two normal vectors px = x2 - px; py = y2 - py; dotprod = px * x2 + py * y2; if (dotprod <= 0.0) { // px,py is on the side of x2,y2 away from x1,y1 // distance to segment is length of (backwards) px,py vector // "length of its (clipped) projection" is now 0.0 projlenSq = 0.0; } else { // px,py is between x1,y1 and x2,y2 // dotprod is the length of the px,py vector // projected on the x2,y2=>x1,y1 vector times the // length of the x2,y2=>x1,y1 vector projlenSq = dotprod * dotprod / (x2 * x2 + y2 * y2); } } // Distance to line is now the length of the relative point // vector minus the length of its projection onto the line // (which is zero if the projection falls outside the range // of the line segment). double lenSq = px * px + py * py - projlenSq; if (lenSq < 0) { lenSq = 0; } return lenSq; } }
{ "content_hash": "4f26a7c75f5c38342b52efab64e4ba27", "timestamp": "", "source": "github", "line_count": 84, "max_line_length": 149, "avg_line_length": 43.36904761904762, "alnum_prop": 0.5618995333516332, "repo_name": "ederign/uberfire", "id": "6e60e1437f692d4bb4ed6bf235b7c3e641babfaa", "size": "4250", "binary": false, "copies": "4", "ref": "refs/heads/master", "path": "uberfire-extensions/uberfire-wires/uberfire-wires-core/uberfire-wires-core-client/src/main/java/org/uberfire/ext/wires/core/client/util/GeometryUtil.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "72237" }, { "name": "FreeMarker", "bytes": "45767" }, { "name": "HTML", "bytes": "86224" }, { "name": "Java", "bytes": "12507156" }, { "name": "JavaScript", "bytes": "85658" }, { "name": "Shell", "bytes": "13146" } ], "symlink_target": "" }
[![Build Status](https://travis-ci.org/jkuri/angular-rollup-starter.svg?branch=master)](https://travis-ci.org/jkuri/angular-rollup-starter) [![Build status](https://ci.appveyor.com/api/projects/status/u6b3i8c8fnrh4dmb?svg=true)](https://ci.appveyor.com/project/jkuri/angular-rollup-starter) Angular2 starter seed based on Rollup. Production builds including AoT steps. Starter also comes with Universal support built-in. ## Start First, clone this repository. ```sh git clone https://github.com/jkuri/angular-rollup-starter.git --depth 1 ``` Move into cloned directory and run ```sh npm install ``` ## Usage ### Serve ```sh npm start ``` ***Note*** Initial load takes some time so vendor files are generated. Then it runs like a charm with cached builds which happens to be really fast. This serves your app with live-reload enabled. ### Production Build Production builds automatically includes AoT (Ahead of Time) compilation steps. ```sh npm run roll ``` ### Universal (Isomorphic) Production Build ```sh npm run roll:prerender ``` Routes stored in `config.json` as `universalRoutes` will be prerendered into `dist/` directory. For example ```json { "externalPackages": { }, "styles": ["css/app.css"], "universalRoutes": ["/", "/docs", "/docs/child"] } ``` will generate prerendered content in `dist/index.html` `dist/docs.html` and `dist/docs/child.html`. To properly serve prerendered content use below `nginx` configuration. ```nginx server { listen 80; server_name subdomain.example.com example.com; root /path/to/dist; location / { try_files $uri.html $uri $uri/ /index.html; } } ``` ### Licence MIT
{ "content_hash": "80bb88c9405dcb0b4a5ba8aaca4c4564", "timestamp": "", "source": "github", "line_count": 77, "max_line_length": 150, "avg_line_length": 21.506493506493506, "alnum_prop": 0.7179951690821256, "repo_name": "jkuri/angular2-rollup-starter", "id": "11c6730e5b6532496e99d87e6931e85c0e531b72", "size": "1680", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "README.md", "mode": "33188", "license": "mit", "language": [ { "name": "HTML", "bytes": "511" }, { "name": "JavaScript", "bytes": "13747" }, { "name": "TypeScript", "bytes": "24197" } ], "symlink_target": "" }
<?php namespace ndxbn\DateTime; interface DateRangeInterface { public function __construct(\DateTimeInterface $start, \DateTimeInterface $end); public function getStart(): \DateTimeImmutable; public function getEnd(): \DateTimeImmutable; public function interval(): \DateInterval; }
{ "content_hash": "56c18a2e95729a5958e8c00950ff8213", "timestamp": "", "source": "github", "line_count": 14, "max_line_length": 84, "avg_line_length": 21.642857142857142, "alnum_prop": 0.7491749174917491, "repo_name": "ndxbn/arstia", "id": "df259e1135dd5634b876f59b5e67b14651890771", "size": "303", "binary": false, "copies": "1", "ref": "refs/heads/develop", "path": "src/ndxbn/DateTime/DateRangeInterface.php", "mode": "33188", "license": "mit", "language": [ { "name": "PHP", "bytes": "6481" } ], "symlink_target": "" }
package flow import ( "encoding/json" "github.com/qiniu/qshell/v2/iqshell/common/data" "github.com/qiniu/qshell/v2/iqshell/common/recorder" ) func NewDBRecordOverseer(dbPath string, blankWorkRecordBuilder func() *WorkRecord) (Overseer, *data.CodeError) { if r, err := recorder.CreateDBRecorder(dbPath); err != nil { return nil, err } else { return &localDBRecordOverseer{ Recorder: r, BlankWorkRecordBuilder: blankWorkRecordBuilder, }, nil } } type localDBRecordOverseer struct { Recorder recorder.Recorder BlankWorkRecordBuilder func() *WorkRecord } func (l *localDBRecordOverseer) WillWork(work *WorkInfo) { if l == nil || l.Recorder == nil { return } status := &workStatus{ WorkRecord: &WorkRecord{ WorkInfo: work, }, Status: workStatusDoing, } l.setWorkStatus(work, status) } func (l *localDBRecordOverseer) WorkDone(record *WorkRecord) { if l == nil || l.Recorder == nil { return } status := &workStatus{ WorkRecord: record, } if record.Err != nil { status.Status = workStatusError } else { status.Status = workStatusSuccess } l.setWorkStatus(record.WorkInfo, status) } func (l *localDBRecordOverseer) GetWorkRecordIfHasDone(work *WorkInfo) (hasDone bool, record *WorkRecord) { if l == nil || l.Recorder == nil { return false, nil } if status := l.getWorkStatus(work); status != nil && (status.Status == workStatusSuccess || status.Status == workStatusError) { return true, status.WorkRecord } else { return false, nil } } func (l *localDBRecordOverseer) getWorkStatus(work *WorkInfo) *workStatus { if l == nil || l.Recorder == nil || work == nil || work.Work == nil || l.BlankWorkRecordBuilder == nil { return nil } workId := work.Work.WorkId() if len(workId) == 0 { return nil } value, err := l.Recorder.Get(workId) if len(value) == 0 || err != nil { return nil } status := &workStatus{ WorkRecord: l.BlankWorkRecordBuilder(), Status: workStatusPrepare, } if status.WorkRecord.Err == nil { status.WorkRecord.Err = data.NewEmptyError() } if e := unmarshalWorkStatus(value, status); e != nil { return nil } else { if status.Status == workStatusSuccess { status.WorkRecord.Err = nil } return status } } func (l *localDBRecordOverseer) setWorkStatus(work *WorkInfo, status *workStatus) { if l == nil || l.Recorder == nil || work == nil || work.Work == nil || status == nil { return } workId := work.Work.WorkId() if len(workId) == 0 { return } value, err := status.toData() if err != nil { return } _ = l.Recorder.Put(workId, value) } var ( workStatusPrepare = 0 workStatusDoing = 1 workStatusSuccess = 2 workStatusError = 3 ) func unmarshalWorkStatus(d string, s *workStatus) *data.CodeError { err := json.Unmarshal([]byte(d), s) return data.ConvertError(err) } type workStatus struct { *WorkRecord Status int `json:"status"` } func (s *workStatus) toData() (string, *data.CodeError) { d, err := json.Marshal(s) return string(d), data.ConvertError(err) }
{ "content_hash": "6d0d739a95ac3167694d02a5d7ff6409", "timestamp": "", "source": "github", "line_count": 136, "max_line_length": 112, "avg_line_length": 22.36764705882353, "alnum_prop": 0.6771860618014465, "repo_name": "qiniu/qshell", "id": "ff49901b44fdfe250638d8e13200b19efb042ec4", "size": "3042", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "iqshell/common/flow/overseer_local_db.go", "mode": "33188", "license": "mit", "language": [ { "name": "Go", "bytes": "702642" }, { "name": "Makefile", "bytes": "1811" } ], "symlink_target": "" }
package repo import ( "encoding/json" "errors" "fmt" "strings" "time" "github.com/Unknwon/com" "github.com/pecastro/gogs/models" "github.com/pecastro/gogs/modules/auth" "github.com/pecastro/gogs/modules/base" "github.com/pecastro/gogs/modules/git" "github.com/pecastro/gogs/modules/log" "github.com/pecastro/gogs/modules/mailer" "github.com/pecastro/gogs/modules/middleware" "github.com/pecastro/gogs/modules/setting" ) const ( SETTINGS_OPTIONS base.TplName = "repo/settings/options" COLLABORATION base.TplName = "repo/settings/collaboration" HOOKS base.TplName = "repo/settings/hooks" HOOK_NEW base.TplName = "repo/settings/hook_new" ORG_HOOK_NEW base.TplName = "org/settings/hook_new" GITHOOKS base.TplName = "repo/settings/githooks" GITHOOK_EDIT base.TplName = "repo/settings/githook_edit" DEPLOY_KEYS base.TplName = "repo/settings/deploy_keys" ) func Settings(ctx *middleware.Context) { ctx.Data["Title"] = ctx.Tr("repo.settings") ctx.Data["PageIsSettingsOptions"] = true ctx.HTML(200, SETTINGS_OPTIONS) } func SettingsPost(ctx *middleware.Context, form auth.RepoSettingForm) { ctx.Data["Title"] = ctx.Tr("repo.settings") ctx.Data["PageIsSettingsOptions"] = true repo := ctx.Repo.Repository switch ctx.Query("action") { case "update": if ctx.HasError() { ctx.HTML(200, SETTINGS_OPTIONS) return } isNameChanged := false oldRepoName := repo.Name newRepoName := form.RepoName // Check if repository name has been changed. if repo.LowerName != strings.ToLower(newRepoName) { isNameChanged = true if err := models.ChangeRepositoryName(ctx.Repo.Owner, repo.Name, newRepoName); err != nil { ctx.Data["Err_RepoName"] = true switch { case models.IsErrRepoAlreadyExist(err): ctx.RenderWithErr(ctx.Tr("form.repo_name_been_taken"), SETTINGS_OPTIONS, &form) case models.IsErrNameReserved(err): ctx.RenderWithErr(ctx.Tr("repo.form.name_reserved", err.(models.ErrNameReserved).Name), SETTINGS_OPTIONS, &form) case models.IsErrNamePatternNotAllowed(err): ctx.RenderWithErr(ctx.Tr("repo.form.name_pattern_not_allowed", err.(models.ErrNamePatternNotAllowed).Pattern), SETTINGS_OPTIONS, &form) default: ctx.Handle(500, "ChangeRepositoryName", err) } return } log.Trace("Repository name changed: %s/%s -> %s", ctx.Repo.Owner.Name, repo.Name, newRepoName) } // In case it's just a case change. repo.Name = newRepoName repo.LowerName = strings.ToLower(newRepoName) if ctx.Repo.GitRepo.IsBranchExist(form.Branch) { repo.DefaultBranch = form.Branch } repo.Description = form.Description repo.Website = form.Website visibilityChanged := repo.IsPrivate != form.Private repo.IsPrivate = form.Private if err := models.UpdateRepository(repo, visibilityChanged); err != nil { ctx.Handle(500, "UpdateRepository", err) return } log.Trace("Repository updated: %s/%s", ctx.Repo.Owner.Name, repo.Name) if isNameChanged { if err := models.RenameRepoAction(ctx.User, oldRepoName, repo); err != nil { log.Error(4, "RenameRepoAction: %v", err) } } if repo.IsMirror { if form.Interval > 0 { ctx.Repo.Mirror.Interval = form.Interval ctx.Repo.Mirror.NextUpdate = time.Now().Add(time.Duration(form.Interval) * time.Hour) if err := models.UpdateMirror(ctx.Repo.Mirror); err != nil { log.Error(4, "UpdateMirror: %v", err) } } } ctx.Flash.Success(ctx.Tr("repo.settings.update_settings_success")) ctx.Redirect(fmt.Sprintf("%s/%s/%s/settings", setting.AppSubUrl, ctx.Repo.Owner.Name, repo.Name)) case "transfer": if repo.Name != form.RepoName { ctx.RenderWithErr(ctx.Tr("form.enterred_invalid_repo_name"), SETTINGS_OPTIONS, nil) return } if ctx.Repo.Owner.IsOrganization() { if !ctx.Repo.Owner.IsOwnedBy(ctx.User.Id) { ctx.Error(404) return } } newOwner := ctx.Query("new_owner_name") isExist, err := models.IsUserExist(0, newOwner) if err != nil { ctx.Handle(500, "IsUserExist", err) return } else if !isExist { ctx.RenderWithErr(ctx.Tr("form.enterred_invalid_owner_name"), SETTINGS_OPTIONS, nil) return } if err = models.TransferOwnership(ctx.User, newOwner, repo); err != nil { if models.IsErrRepoAlreadyExist(err) { ctx.RenderWithErr(ctx.Tr("repo.settings.new_owner_has_same_repo"), SETTINGS_OPTIONS, nil) } else { ctx.Handle(500, "TransferOwnership", err) } return } log.Trace("Repository transfered: %s/%s -> %s", ctx.Repo.Owner.Name, repo.Name, newOwner) ctx.Flash.Success(ctx.Tr("repo.settings.transfer_succeed")) ctx.Redirect(setting.AppSubUrl + "/" + newOwner + "/" + repo.Name) case "delete": if repo.Name != form.RepoName { ctx.RenderWithErr(ctx.Tr("form.enterred_invalid_repo_name"), SETTINGS_OPTIONS, nil) return } if ctx.Repo.Owner.IsOrganization() { if !ctx.Repo.Owner.IsOwnedBy(ctx.User.Id) { ctx.Error(404) return } } if err := models.DeleteRepository(ctx.Repo.Owner.Id, repo.ID); err != nil { ctx.Handle(500, "DeleteRepository", err) return } log.Trace("Repository deleted: %s/%s", ctx.Repo.Owner.Name, repo.Name) ctx.Redirect(ctx.Repo.Owner.DashboardLink()) } } func Collaboration(ctx *middleware.Context) { ctx.Data["Title"] = ctx.Tr("repo.settings") ctx.Data["PageIsSettingsCollaboration"] = true if ctx.Req.Method == "POST" { name := strings.ToLower(ctx.Query("collaborator")) if len(name) == 0 || ctx.Repo.Owner.LowerName == name { ctx.Redirect(setting.AppSubUrl + ctx.Req.URL.Path) return } u, err := models.GetUserByName(name) if err != nil { if models.IsErrUserNotExist(err) { ctx.Flash.Error(ctx.Tr("form.user_not_exist")) ctx.Redirect(setting.AppSubUrl + ctx.Req.URL.Path) } else { ctx.Handle(500, "GetUserByName", err) } return } // Check if user is organization member. if ctx.Repo.Owner.IsOrganization() && ctx.Repo.Owner.IsOrgMember(u.Id) { ctx.Flash.Info(ctx.Tr("repo.settings.user_is_org_member")) ctx.Redirect(ctx.Repo.RepoLink + "/settings/collaboration") return } if err = ctx.Repo.Repository.AddCollaborator(u); err != nil { ctx.Handle(500, "AddCollaborator", err) return } if setting.Service.EnableNotifyMail { if err = mailer.SendCollaboratorMail(ctx.Render, u, ctx.User, ctx.Repo.Repository); err != nil { ctx.Handle(500, "SendCollaboratorMail", err) return } } ctx.Flash.Success(ctx.Tr("repo.settings.add_collaborator_success")) ctx.Redirect(setting.AppSubUrl + ctx.Req.URL.Path) return } // Delete collaborator. remove := strings.ToLower(ctx.Query("remove")) if len(remove) > 0 && remove != ctx.Repo.Owner.LowerName { u, err := models.GetUserByName(remove) if err != nil { ctx.Handle(500, "GetUserByName", err) return } if err := ctx.Repo.Repository.DeleteCollaborator(u); err != nil { ctx.Handle(500, "DeleteCollaborator", err) return } ctx.Flash.Success(ctx.Tr("repo.settings.remove_collaborator_success")) ctx.Redirect(ctx.Repo.RepoLink + "/settings/collaboration") return } users, err := ctx.Repo.Repository.GetCollaborators() if err != nil { ctx.Handle(500, "GetCollaborators", err) return } ctx.Data["Collaborators"] = users ctx.HTML(200, COLLABORATION) } func Webhooks(ctx *middleware.Context) { ctx.Data["Title"] = ctx.Tr("repo.settings.hooks") ctx.Data["PageIsSettingsHooks"] = true ctx.Data["BaseLink"] = ctx.Repo.RepoLink ctx.Data["Description"] = ctx.Tr("repo.settings.hooks_desc", "http://gogs.io/docs/features/webhook.html") ws, err := models.GetWebhooksByRepoId(ctx.Repo.Repository.ID) if err != nil { ctx.Handle(500, "GetWebhooksByRepoId", err) return } ctx.Data["Webhooks"] = ws ctx.HTML(200, HOOKS) } type OrgRepoCtx struct { OrgID int64 RepoID int64 Link string NewTemplate base.TplName } // getOrgRepoCtx determines whether this is a repo context or organization context. func getOrgRepoCtx(ctx *middleware.Context) (*OrgRepoCtx, error) { if len(ctx.Repo.RepoLink) > 0 { return &OrgRepoCtx{ RepoID: ctx.Repo.Repository.ID, Link: ctx.Repo.RepoLink, NewTemplate: HOOK_NEW, }, nil } if len(ctx.Org.OrgLink) > 0 { return &OrgRepoCtx{ OrgID: ctx.Org.Organization.Id, Link: ctx.Org.OrgLink, NewTemplate: ORG_HOOK_NEW, }, nil } return nil, errors.New("Unable to set OrgRepo context") } func checkHookType(ctx *middleware.Context) string { hookType := strings.ToLower(ctx.Params(":type")) if !com.IsSliceContainsStr(setting.Webhook.Types, hookType) { ctx.Handle(404, "checkHookType", nil) return "" } return hookType } func WebhooksNew(ctx *middleware.Context) { ctx.Data["Title"] = ctx.Tr("repo.settings.add_webhook") ctx.Data["PageIsSettingsHooks"] = true ctx.Data["PageIsSettingsHooksNew"] = true ctx.Data["Webhook"] = models.Webhook{HookEvent: &models.HookEvent{}} orCtx, err := getOrgRepoCtx(ctx) if err != nil { ctx.Handle(500, "getOrgRepoCtx", err) return } ctx.Data["HookType"] = checkHookType(ctx) if ctx.Written() { return } ctx.Data["BaseLink"] = orCtx.Link ctx.HTML(200, orCtx.NewTemplate) } func ParseHookEvent(form auth.WebhookForm) *models.HookEvent { return &models.HookEvent{ PushOnly: form.PushOnly(), SendEverything: form.SendEverything(), ChooseEvents: form.ChooseEvents(), HookEvents: models.HookEvents{ Create: form.Create, Push: form.Push, }, } } func WebHooksNewPost(ctx *middleware.Context, form auth.NewWebhookForm) { ctx.Data["Title"] = ctx.Tr("repo.settings.add_webhook") ctx.Data["PageIsSettingsHooks"] = true ctx.Data["PageIsSettingsHooksNew"] = true ctx.Data["Webhook"] = models.Webhook{HookEvent: &models.HookEvent{}} ctx.Data["HookType"] = "gogs" orCtx, err := getOrgRepoCtx(ctx) if err != nil { ctx.Handle(500, "getOrgRepoCtx", err) return } ctx.Data["BaseLink"] = orCtx.Link if ctx.HasError() { ctx.HTML(200, orCtx.NewTemplate) return } contentType := models.JSON if models.HookContentType(form.ContentType) == models.FORM { contentType = models.FORM } w := &models.Webhook{ RepoID: orCtx.RepoID, URL: form.PayloadURL, ContentType: contentType, Secret: form.Secret, HookEvent: ParseHookEvent(form.WebhookForm), IsActive: form.Active, HookTaskType: models.GOGS, OrgID: orCtx.OrgID, } if err := w.UpdateEvent(); err != nil { ctx.Handle(500, "UpdateEvent", err) return } else if err := models.CreateWebhook(w); err != nil { ctx.Handle(500, "CreateWebhook", err) return } ctx.Flash.Success(ctx.Tr("repo.settings.add_hook_success")) ctx.Redirect(orCtx.Link + "/settings/hooks") } func SlackHooksNewPost(ctx *middleware.Context, form auth.NewSlackHookForm) { ctx.Data["Title"] = ctx.Tr("repo.settings") ctx.Data["PageIsSettingsHooks"] = true ctx.Data["PageIsSettingsHooksNew"] = true ctx.Data["Webhook"] = models.Webhook{HookEvent: &models.HookEvent{}} orCtx, err := getOrgRepoCtx(ctx) if err != nil { ctx.Handle(500, "getOrgRepoCtx", err) return } if ctx.HasError() { ctx.HTML(200, orCtx.NewTemplate) return } meta, err := json.Marshal(&models.SlackMeta{ Channel: form.Channel, Username: form.Username, IconURL: form.IconURL, Color: form.Color, }) if err != nil { ctx.Handle(500, "Marshal", err) return } w := &models.Webhook{ RepoID: orCtx.RepoID, URL: form.PayloadURL, ContentType: models.JSON, HookEvent: ParseHookEvent(form.WebhookForm), IsActive: form.Active, HookTaskType: models.SLACK, Meta: string(meta), OrgID: orCtx.OrgID, } if err := w.UpdateEvent(); err != nil { ctx.Handle(500, "UpdateEvent", err) return } else if err := models.CreateWebhook(w); err != nil { ctx.Handle(500, "CreateWebhook", err) return } ctx.Flash.Success(ctx.Tr("repo.settings.add_hook_success")) ctx.Redirect(orCtx.Link + "/settings/hooks") } func checkWebhook(ctx *middleware.Context) (*OrgRepoCtx, *models.Webhook) { ctx.Data["RequireHighlightJS"] = true orCtx, err := getOrgRepoCtx(ctx) if err != nil { ctx.Handle(500, "getOrgRepoCtx", err) return nil, nil } ctx.Data["BaseLink"] = orCtx.Link w, err := models.GetWebhookByID(ctx.ParamsInt64(":id")) if err != nil { if models.IsErrWebhookNotExist(err) { ctx.Handle(404, "GetWebhookByID", nil) } else { ctx.Handle(500, "GetWebhookByID", err) } return nil, nil } switch w.HookTaskType { case models.SLACK: ctx.Data["SlackHook"] = w.GetSlackHook() ctx.Data["HookType"] = "slack" default: ctx.Data["HookType"] = "gogs" } ctx.Data["History"], err = w.History(1) if err != nil { ctx.Handle(500, "History", err) } return orCtx, w } func WebHooksEdit(ctx *middleware.Context) { ctx.Data["Title"] = ctx.Tr("repo.settings.update_webhook") ctx.Data["PageIsSettingsHooks"] = true ctx.Data["PageIsSettingsHooksEdit"] = true orCtx, w := checkWebhook(ctx) if ctx.Written() { return } ctx.Data["Webhook"] = w ctx.HTML(200, orCtx.NewTemplate) } func WebHooksEditPost(ctx *middleware.Context, form auth.NewWebhookForm) { ctx.Data["Title"] = ctx.Tr("repo.settings.update_webhook") ctx.Data["PageIsSettingsHooks"] = true ctx.Data["PageIsSettingsHooksEdit"] = true orCtx, w := checkWebhook(ctx) if ctx.Written() { return } ctx.Data["Webhook"] = w if ctx.HasError() { ctx.HTML(200, orCtx.NewTemplate) return } contentType := models.JSON if models.HookContentType(form.ContentType) == models.FORM { contentType = models.FORM } w.URL = form.PayloadURL w.ContentType = contentType w.Secret = form.Secret w.HookEvent = ParseHookEvent(form.WebhookForm) w.IsActive = form.Active if err := w.UpdateEvent(); err != nil { ctx.Handle(500, "UpdateEvent", err) return } else if err := models.UpdateWebhook(w); err != nil { ctx.Handle(500, "WebHooksEditPost", err) return } ctx.Flash.Success(ctx.Tr("repo.settings.update_hook_success")) ctx.Redirect(fmt.Sprintf("%s/settings/hooks/%d", orCtx.Link, w.ID)) } func SlackHooksEditPost(ctx *middleware.Context, form auth.NewSlackHookForm) { ctx.Data["Title"] = ctx.Tr("repo.settings") ctx.Data["PageIsSettingsHooks"] = true ctx.Data["PageIsSettingsHooksEdit"] = true orCtx, w := checkWebhook(ctx) if ctx.Written() { return } ctx.Data["Webhook"] = w if ctx.HasError() { ctx.HTML(200, orCtx.NewTemplate) return } meta, err := json.Marshal(&models.SlackMeta{ Channel: form.Channel, Username: form.Username, IconURL: form.IconURL, Color: form.Color, }) if err != nil { ctx.Handle(500, "Marshal", err) return } w.URL = form.PayloadURL w.Meta = string(meta) w.HookEvent = ParseHookEvent(form.WebhookForm) w.IsActive = form.Active if err := w.UpdateEvent(); err != nil { ctx.Handle(500, "UpdateEvent", err) return } else if err := models.UpdateWebhook(w); err != nil { ctx.Handle(500, "UpdateWebhook", err) return } ctx.Flash.Success(ctx.Tr("repo.settings.update_hook_success")) ctx.Redirect(fmt.Sprintf("%s/settings/hooks/%d", orCtx.Link, w.ID)) } func DeleteWebhook(ctx *middleware.Context) { if err := models.DeleteWebhook(ctx.QueryInt64("id")); err != nil { ctx.Flash.Error("DeleteWebhook: " + err.Error()) } else { ctx.Flash.Success(ctx.Tr("repo.settings.webhook_deletion_success")) } ctx.JSON(200, map[string]interface{}{ "redirect": ctx.Repo.RepoLink + "/settings/hooks", }) } func TriggerHook(ctx *middleware.Context) { u, err := models.GetUserByName(ctx.Params(":username")) if err != nil { if models.IsErrUserNotExist(err) { ctx.Handle(404, "GetUserByName", err) } else { ctx.Handle(500, "GetUserByName", err) } return } repo, err := models.GetRepositoryByName(u.Id, ctx.Params(":reponame")) if err != nil { if models.IsErrRepoNotExist(err) { ctx.Handle(404, "GetRepositoryByName", err) } else { ctx.Handle(500, "GetRepositoryByName", err) } return } models.HookQueue.AddRepoID(repo.ID) ctx.Status(200) } func GitHooks(ctx *middleware.Context) { ctx.Data["Title"] = ctx.Tr("repo.settings.githooks") ctx.Data["PageIsSettingsGitHooks"] = true hooks, err := ctx.Repo.GitRepo.Hooks() if err != nil { ctx.Handle(500, "Hooks", err) return } ctx.Data["Hooks"] = hooks ctx.HTML(200, GITHOOKS) } func GitHooksEdit(ctx *middleware.Context) { ctx.Data["Title"] = ctx.Tr("repo.settings.githooks") ctx.Data["PageIsSettingsGitHooks"] = true name := ctx.Params(":name") hook, err := ctx.Repo.GitRepo.GetHook(name) if err != nil { if err == git.ErrNotValidHook { ctx.Handle(404, "GetHook", err) } else { ctx.Handle(500, "GetHook", err) } return } ctx.Data["Hook"] = hook ctx.HTML(200, GITHOOK_EDIT) } func GitHooksEditPost(ctx *middleware.Context) { name := ctx.Params(":name") hook, err := ctx.Repo.GitRepo.GetHook(name) if err != nil { if err == git.ErrNotValidHook { ctx.Handle(404, "GetHook", err) } else { ctx.Handle(500, "GetHook", err) } return } hook.Content = ctx.Query("content") if err = hook.Update(); err != nil { ctx.Handle(500, "hook.Update", err) return } ctx.Redirect(ctx.Repo.RepoLink + "/settings/hooks/git") } func DeployKeys(ctx *middleware.Context) { ctx.Data["Title"] = ctx.Tr("repo.settings.deploy_keys") ctx.Data["PageIsSettingsKeys"] = true keys, err := models.ListDeployKeys(ctx.Repo.Repository.ID) if err != nil { ctx.Handle(500, "ListDeployKeys", err) return } ctx.Data["Deploykeys"] = keys ctx.HTML(200, DEPLOY_KEYS) } func DeployKeysPost(ctx *middleware.Context, form auth.AddSSHKeyForm) { ctx.Data["Title"] = ctx.Tr("repo.settings.deploy_keys") ctx.Data["PageIsSettingsKeys"] = true keys, err := models.ListDeployKeys(ctx.Repo.Repository.ID) if err != nil { ctx.Handle(500, "ListDeployKeys", err) return } ctx.Data["Deploykeys"] = keys if ctx.HasError() { ctx.HTML(200, DEPLOY_KEYS) return } content, err := models.CheckPublicKeyString(form.Content) if err != nil { if err == models.ErrKeyUnableVerify { ctx.Flash.Info(ctx.Tr("form.unable_verify_ssh_key")) } else { ctx.Data["HasError"] = true ctx.Data["Err_Content"] = true ctx.Flash.Error(ctx.Tr("form.invalid_ssh_key", err.Error())) ctx.Redirect(ctx.Repo.RepoLink + "/settings/keys") return } } if err = models.AddDeployKey(ctx.Repo.Repository.ID, form.Title, content); err != nil { ctx.Data["HasError"] = true switch { case models.IsErrKeyAlreadyExist(err): ctx.Data["Err_Content"] = true ctx.RenderWithErr(ctx.Tr("repo.settings.key_been_used"), DEPLOY_KEYS, &form) case models.IsErrKeyNameAlreadyUsed(err): ctx.Data["Err_Title"] = true ctx.RenderWithErr(ctx.Tr("repo.settings.key_name_used"), DEPLOY_KEYS, &form) default: ctx.Handle(500, "AddDeployKey", err) } return } log.Trace("Deploy key added: %d", ctx.Repo.Repository.ID) ctx.Flash.Success(ctx.Tr("repo.settings.add_key_success", form.Title)) ctx.Redirect(ctx.Repo.RepoLink + "/settings/keys") } func DeleteDeployKey(ctx *middleware.Context) { if err := models.DeleteDeployKey(ctx.QueryInt64("id")); err != nil { ctx.Flash.Error("DeleteDeployKey: " + err.Error()) } else { ctx.Flash.Success(ctx.Tr("repo.settings.deploy_key_deletion_success")) } ctx.JSON(200, map[string]interface{}{ "redirect": ctx.Repo.RepoLink + "/settings/keys", }) }
{ "content_hash": "a3b60edbf0391dce5646365c2a8a7457", "timestamp": "", "source": "github", "line_count": 711, "max_line_length": 140, "avg_line_length": 27.20815752461322, "alnum_prop": 0.6850865856810545, "repo_name": "pecastro/gogs", "id": "403fb3b3220c4f1cb9d1dc06ef72e283366be9af", "size": "19507", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "routers/repo/setting.go", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "265999" }, { "name": "Go", "bytes": "853015" }, { "name": "Groff", "bytes": "131138" }, { "name": "JavaScript", "bytes": "207988" }, { "name": "Makefile", "bytes": "273" }, { "name": "Shell", "bytes": "9925" } ], "symlink_target": "" }
"use strict"; const pygments_data = require("../generated/pygments_data.json"); const render_settings_admin_auth_methods_list = require("../templates/settings/admin_auth_methods_list.hbs"); const render_settings_admin_realm_domains_list = require("../templates/settings/admin_realm_domains_list.hbs"); const settings_config = require("./settings_config"); const meta = { loaded: false, }; exports.reset = function () { meta.loaded = false; }; exports.maybe_disable_widgets = function () { if (page_params.is_owner) { return; } $(".organization-box [data-name='auth-methods']") .find("input, button, select, checked") .prop("disabled", true); if (page_params.is_admin) { $("#deactivate_realm_button").prop("disabled", true); $("#org-message-retention").find("input, select").prop("disabled", true); return; } $(".organization-box [data-name='organization-profile']") .find("input, textarea, button, select") .prop("disabled", true); $(".organization-box [data-name='organization-settings']") .find("input, textarea, button, select") .prop("disabled", true); $(".organization-box [data-name='organization-settings']") .find(".control-label-disabled") .addClass("enabled"); $(".organization-box [data-name='organization-permissions']") .find("input, textarea, button, select") .prop("disabled", true); $(".organization-box [data-name='organization-permissions']") .find(".control-label-disabled") .addClass("enabled"); }; exports.get_sorted_options_list = function (option_values_object) { const options_list = Object.keys(option_values_object).map((key) => ({ ...option_values_object[key], key, })); let comparator = (x, y) => x.order - y.order; if (!options_list[0].order) { comparator = (x, y) => { const key_x = x.key.toUpperCase(); const key_y = y.key.toUpperCase(); if (key_x < key_y) { return -1; } if (key_x > key_y) { return 1; } return 0; }; } options_list.sort(comparator); return options_list; }; exports.get_organization_settings_options = () => { const options = {}; options.create_stream_policy_values = exports.get_sorted_options_list( settings_config.create_stream_policy_values, ); options.invite_to_stream_policy_values = exports.get_sorted_options_list( settings_config.invite_to_stream_policy_values, ); options.user_group_edit_policy_values = exports.get_sorted_options_list( settings_config.user_group_edit_policy_values, ); options.private_message_policy_values = exports.get_sorted_options_list( settings_config.private_message_policy_values, ); options.wildcard_mention_policy_values = exports.get_sorted_options_list( settings_config.wildcard_mention_policy_values, ); return options; }; exports.get_realm_time_limits_in_minutes = function (property) { let val = (page_params[property] / 60).toFixed(1); if (Number.parseFloat(val, 10) === Number.parseInt(val, 10)) { val = Number.parseInt(val, 10); } return val.toString(); }; function get_property_value(property_name) { if (property_name === "realm_message_content_edit_limit_minutes") { return exports.get_realm_time_limits_in_minutes("realm_message_content_edit_limit_seconds"); } if (property_name === "realm_message_content_delete_limit_minutes") { return exports.get_realm_time_limits_in_minutes( "realm_message_content_delete_limit_seconds", ); } if (property_name === "realm_waiting_period_setting") { if (page_params.realm_waiting_period_threshold === 0) { return "none"; } if (page_params.realm_waiting_period_threshold === 3) { return "three_days"; } return "custom_days"; } if (property_name === "realm_add_emoji_by_admins_only") { if (page_params.realm_add_emoji_by_admins_only) { return "by_admins_only"; } return "by_anyone"; } if (property_name === "realm_msg_edit_limit_setting") { if (!page_params.realm_allow_message_editing) { return "never"; } for (const [value, elem] of settings_config.msg_edit_limit_dropdown_values) { if (elem.seconds === page_params.realm_message_content_edit_limit_seconds) { return value; } } return "custom_limit"; } if (property_name === "realm_message_retention_setting") { if (page_params.realm_message_retention_days === settings_config.retain_message_forever) { return "retain_forever"; } return "retain_for_period"; } if (property_name === "realm_msg_delete_limit_setting") { if (!page_params.realm_allow_message_deleting) { return "never"; } for (const [value, elem] of settings_config.msg_delete_limit_dropdown_values) { if (elem.seconds === page_params.realm_message_content_delete_limit_seconds) { return value; } } return "custom_limit"; } if (property_name === "realm_org_join_restrictions") { if (page_params.realm_emails_restricted_to_domains) { return "only_selected_domain"; } if (page_params.realm_disallow_disposable_email_addresses) { return "no_disposable_email"; } return "no_restriction"; } if (property_name === "realm_user_invite_restriction") { if (!page_params.realm_invite_required) { if (page_params.realm_invite_by_admins_only) { return "no_invite_required_by_admins_only"; } return "no_invite_required"; } if (page_params.realm_invite_by_admins_only) { return "by_admins_only"; } return "by_anyone"; } if (property_name === "realm_default_twenty_four_hour_time") { return JSON.stringify(page_params[property_name]); } return page_params[property_name]; } exports.extract_property_name = function (elem) { return elem.attr("id").split("-").join("_").replace("id_", ""); }; function get_subsection_property_elements(element) { const subsection = $(element).closest(".org-subsection-parent"); return Array.from(subsection.find(".prop-element")); } const simple_dropdown_properties = [ "realm_create_stream_policy", "realm_invite_to_stream_policy", "realm_user_group_edit_policy", "realm_private_message_policy", "realm_add_emoji_by_admins_only", "realm_user_invite_restriction", "realm_wildcard_mention_policy", ]; function set_property_dropdown_value(property_name) { $("#id_" + property_name).val(get_property_value(property_name)); } function change_element_block_display_property(elem_id, show_element) { const elem = $("#" + elem_id); if (show_element) { elem.parent().show(); } else { elem.parent().hide(); } } function set_realm_waiting_period_dropdown() { const value = get_property_value("realm_waiting_period_setting"); $("#id_realm_waiting_period_setting").val(value); change_element_block_display_property( "id_realm_waiting_period_threshold", value === "custom_days", ); } function set_video_chat_provider_dropdown() { const chat_provider_id = page_params.realm_video_chat_provider; $("#id_realm_video_chat_provider").val(chat_provider_id); } function set_msg_edit_limit_dropdown() { const value = get_property_value("realm_msg_edit_limit_setting"); $("#id_realm_msg_edit_limit_setting").val(value); change_element_block_display_property( "id_realm_message_content_edit_limit_minutes", value === "custom_limit", ); settings_ui.disable_sub_setting_onchange( value !== "never", "id_realm_allow_community_topic_editing", true, ); } function set_msg_delete_limit_dropdown() { const value = get_property_value("realm_msg_delete_limit_setting"); $("#id_realm_msg_delete_limit_setting").val(value); change_element_block_display_property( "id_realm_message_content_delete_limit_minutes", value === "custom_limit", ); } function set_message_retention_setting_dropdown() { const value = get_property_value("realm_message_retention_setting"); $("#id_realm_message_retention_setting").val(value); change_element_block_display_property( "id_realm_message_retention_days", value === "retain_for_period", ); if ( get_property_value("realm_message_retention_days") === settings_config.retain_message_forever ) { $("#id_realm_message_retention_days").val(""); } } function set_org_join_restrictions_dropdown() { const value = get_property_value("realm_org_join_restrictions"); $("#id_realm_org_join_restrictions").val(value); change_element_block_display_property( "allowed_domains_label", value === "only_selected_domain", ); } function set_message_content_in_email_notifications_visiblity() { change_element_block_display_property( "message_content_in_email_notifications_label", page_params.realm_message_content_allowed_in_email_notifications, ); } function set_digest_emails_weekday_visibility() { change_element_block_display_property( "id_realm_digest_weekday", page_params.realm_digest_emails_enabled, ); } exports.populate_realm_domains = function (realm_domains) { if (!meta.loaded) { return; } const domains_list = realm_domains.map((realm_domain) => realm_domain.allow_subdomains ? "*." + realm_domain.domain : realm_domain.domain, ); let domains = domains_list.join(", "); if (domains.length === 0) { domains = i18n.t("None"); } $("#allowed_domains_label").text(i18n.t("Allowed domains: __domains__", {domains})); const realm_domains_table_body = $("#realm_domains_table tbody").expectOne(); realm_domains_table_body.find("tr").remove(); for (const realm_domain of realm_domains) { realm_domains_table_body.append( render_settings_admin_realm_domains_list({ realm_domain, }), ); } }; function sort_object_by_key(obj) { const keys = Object.keys(obj).sort(); const new_obj = {}; for (const key of keys) { new_obj[key] = obj[key]; } return new_obj; } exports.populate_auth_methods = function (auth_methods) { if (!meta.loaded) { return; } const auth_methods_table = $("#id_realm_authentication_methods").expectOne(); auth_methods = sort_object_by_key(auth_methods); let rendered_auth_method_rows = ""; for (const [auth_method, value] of Object.entries(auth_methods)) { rendered_auth_method_rows += render_settings_admin_auth_methods_list({ method: auth_method, enabled: value, is_owner: page_params.is_owner, }); } auth_methods_table.html(rendered_auth_method_rows); }; function update_dependent_subsettings(property_name) { if (simple_dropdown_properties.includes(property_name)) { set_property_dropdown_value(property_name); } else if (property_name === "realm_waiting_period_threshold") { set_realm_waiting_period_dropdown(); } else if ( property_name === "realm_video_chat_provider" || property_name.startsWith("realm_zoom") ) { set_video_chat_provider_dropdown(); } else if ( property_name === "realm_msg_edit_limit_setting" || property_name === "realm_message_content_edit_limit_minutes" ) { set_msg_edit_limit_dropdown(); } else if (property_name === "realm_message_retention_days") { set_message_retention_setting_dropdown(); } else if ( property_name === "realm_msg_delete_limit_setting" || property_name === "realm_message_content_delete_limit_minutes" ) { set_msg_delete_limit_dropdown(); } else if (property_name === "realm_org_join_restrictions") { set_org_join_restrictions_dropdown(); } else if (property_name === "realm_message_content_allowed_in_email_notifications") { set_message_content_in_email_notifications_visiblity(); } else if (property_name === "realm_digest_emails_enabled") { settings_notifications.set_enable_digest_emails_visibility(); set_digest_emails_weekday_visibility(); } } function discard_property_element_changes(elem) { elem = $(elem); const property_name = exports.extract_property_name(elem); const property_value = get_property_value(property_name); if (property_name === "realm_authentication_methods") { exports.populate_auth_methods(property_value); } else if (property_name === "realm_notifications_stream_id") { exports.notifications_stream_widget.render(property_value); } else if (property_name === "realm_signup_notifications_stream_id") { exports.signup_notifications_stream_widget.render(property_value); } else if (property_name === "realm_default_code_block_language") { exports.default_code_language_widget.render(property_value); } else if (property_value !== undefined) { exports.set_input_element_value(elem, property_value); } else { blueslip.error("Element refers to unknown property " + property_name); } update_dependent_subsettings(property_name); } exports.sync_realm_settings = function (property) { if (!overlays.settings_open()) { return; } const value = page_params[`realm_${property}`]; if (property === "notifications_stream_id") { exports.notifications_stream_widget.render(value); } else if (property === "signup_notifications_stream_id") { exports.signup_notifications_stream_widget.render(value); } else if (property === "default_code_block_language") { exports.default_code_language_widget.render(value); } if (property === "message_content_edit_limit_seconds") { property = "message_content_edit_limit_minutes"; } else if (property === "allow_message_editing") { property = "msg_edit_limit_setting"; } else if ( property === "emails_restricted_to_domains" || property === "disallow_disposable_email_addresses" ) { property = "org_join_restrictions"; } else if (property === "message_content_delete_limit_seconds") { property = "message_content_delete_limit_minutes"; } else if (property === "allow_message_deleting") { property = "msg_delete_limit_setting"; } else if (property === "invite_required" || property === "invite_by_admins_only") { property = "user_invite_restriction"; } const element = $("#id_realm_" + property); if (element.length) { discard_property_element_changes(element); } }; exports.change_save_button_state = function ($element, state) { function show_hide_element($element, show, fadeout_delay) { if (show) { $element.removeClass("hide").addClass(".show").fadeIn(300); return; } setTimeout(() => { $element.fadeOut(300); }, fadeout_delay); } const $saveBtn = $element.find(".save-button"); const $textEl = $saveBtn.find(".save-discard-widget-button-text"); if (state !== "saving") { $saveBtn.removeClass("saving"); } if (state === "discarded") { show_hide_element($element, false, 0); return; } let button_text; let data_status; let is_show; if (state === "unsaved") { button_text = i18n.t("Save changes"); data_status = "unsaved"; is_show = true; $element.find(".discard-button").show(); } else if (state === "saved") { button_text = i18n.t("Save changes"); data_status = ""; is_show = false; } else if (state === "saving") { button_text = i18n.t("Saving"); data_status = "saving"; is_show = true; $element.find(".discard-button").hide(); $saveBtn.addClass("saving"); } else if (state === "failed") { button_text = i18n.t("Save changes"); data_status = "failed"; is_show = true; } else if (state === "succeeded") { button_text = i18n.t("Saved"); data_status = "saved"; is_show = false; } $textEl.text(button_text); $saveBtn.attr("data-status", data_status); show_hide_element($element, is_show, 800); }; function get_input_type(input_elem, input_type) { if (["boolean", "string", "number"].includes(input_type)) { return input_type; } return input_elem.data("setting-widget-type"); } exports.get_input_element_value = function (input_elem, input_type) { input_elem = $(input_elem); input_type = get_input_type(input_elem, input_type); if (input_type) { if (input_type === "boolean") { return input_elem.prop("checked"); } if (input_type === "string") { return input_elem.val().trim(); } if (input_type === "number") { return Number.parseInt(input_elem.val().trim(), 10); } } return undefined; }; exports.set_input_element_value = function (input_elem, value) { const input_type = get_input_type(input_elem, typeof value); if (input_type) { if (input_type === "boolean") { return input_elem.prop("checked", value); } if (input_type === "string" || input_type === "number") { return input_elem.val(value); } } blueslip.error(`Failed to set value of property ${exports.extract_property_name(input_elem)}`); return undefined; }; exports.set_up = function () { exports.build_page(); exports.maybe_disable_widgets(); }; function get_auth_method_table_data() { const new_auth_methods = {}; const auth_method_rows = $("#id_realm_authentication_methods").find("tr.method_row"); for (const method_row of auth_method_rows) { new_auth_methods[$(method_row).data("method")] = $(method_row) .find("input") .prop("checked"); } return new_auth_methods; } function check_property_changed(elem) { elem = $(elem); const property_name = exports.extract_property_name(elem); let current_val = get_property_value(property_name); let changed_val; if (property_name === "realm_authentication_methods") { current_val = sort_object_by_key(current_val); current_val = JSON.stringify(current_val); changed_val = get_auth_method_table_data(); changed_val = JSON.stringify(changed_val); } else if (property_name === "realm_notifications_stream_id") { changed_val = Number.parseInt(exports.notifications_stream_widget.value(), 10); } else if (property_name === "realm_signup_notifications_stream_id") { changed_val = Number.parseInt(exports.signup_notifications_stream_widget.value(), 10); } else if (property_name === "realm_default_code_block_language") { changed_val = exports.default_code_language_widget.value(); } else if (current_val !== undefined) { changed_val = exports.get_input_element_value(elem, typeof current_val); } else { blueslip.error("Element refers to unknown property " + property_name); } return current_val !== changed_val; } exports.save_discard_widget_status_handler = (subsection) => { subsection.find(".subsection-failed-status p").hide(); subsection.find(".save-button").show(); const properties_elements = get_subsection_property_elements(subsection); const show_change_process_button = properties_elements.some(check_property_changed); const save_btn_controls = subsection.find(".subsection-header .save-button-controls"); const button_state = show_change_process_button ? "unsaved" : "discarded"; exports.change_save_button_state(save_btn_controls, button_state); }; exports.default_code_language_widget = null; exports.notifications_stream_widget = null; exports.signup_notifications_stream_widget = null; exports.init_dropdown_widgets = () => { const streams = stream_data.get_streams_for_settings_page(); const notification_stream_options = { data: streams.map((x) => { const item = { name: x.name, value: x.stream_id.toString(), }; return item; }), on_update: () => { exports.save_discard_widget_status_handler($("#org-notifications")); }, default_text: i18n.t("Disabled"), render_text: (x) => `#${x}`, null_value: -1, }; exports.notifications_stream_widget = dropdown_list_widget( Object.assign( { widget_name: "realm_notifications_stream_id", value: page_params.realm_notifications_stream_id, }, notification_stream_options, ), ); exports.signup_notifications_stream_widget = dropdown_list_widget( Object.assign( { widget_name: "realm_signup_notifications_stream_id", value: page_params.realm_signup_notifications_stream_id, }, notification_stream_options, ), ); exports.default_code_language_widget = dropdown_list_widget({ widget_name: "realm_default_code_block_language", data: Object.keys(pygments_data.langs).map((x) => ({ name: x, value: x, })), value: page_params.realm_default_code_block_language, on_update: () => { exports.save_discard_widget_status_handler($("#org-other-settings")); }, default_text: i18n.t("No language set"), }); }; exports.build_page = function () { meta.loaded = true; loading.make_indicator($("#admin_page_auth_methods_loading_indicator")); // Initialize all the dropdown list widgets. exports.init_dropdown_widgets(); // Populate realm domains exports.populate_realm_domains(page_params.realm_domains); // Populate authentication methods table exports.populate_auth_methods(page_params.realm_authentication_methods); simple_dropdown_properties.forEach(set_property_dropdown_value); set_realm_waiting_period_dropdown(); set_video_chat_provider_dropdown(); set_msg_edit_limit_dropdown(); set_msg_delete_limit_dropdown(); set_message_retention_setting_dropdown(); set_org_join_restrictions_dropdown(); set_message_content_in_email_notifications_visiblity(); set_digest_emails_weekday_visibility(); $(".admin-realm-form").on("change input", "input, select, textarea", (e) => { e.preventDefault(); e.stopPropagation(); // This event handler detects whether after these input // changes, any fields have different values from the current // official values stored in the database and page_params. If // they do, we transition to the "unsaved" state showing the // save/discard widget; otherwise, we hide that widget (the // "discarded" state). if ($(e.target).hasClass("no-input-change-detection")) { // This is to prevent input changes detection in elements // within a subsection whose changes should not affect the // visibility of the discard button return false; } const subsection = $(e.target).closest(".org-subsection-parent"); exports.save_discard_widget_status_handler(subsection); return undefined; }); $(".organization").on( "click", ".subsection-header .subsection-changes-discard .button", (e) => { e.preventDefault(); e.stopPropagation(); get_subsection_property_elements(e.target).forEach(discard_property_element_changes); const save_btn_controls = $(e.target).closest(".save-button-controls"); exports.change_save_button_state(save_btn_controls, "discarded"); }, ); exports.save_organization_settings = function (data, save_button) { const subsection_parent = save_button.closest(".org-subsection-parent"); const save_btn_container = subsection_parent.find(".save-button-controls"); const failed_alert_elem = subsection_parent.find(".subsection-failed-status p"); exports.change_save_button_state(save_btn_container, "saving"); channel.patch({ url: "/json/realm", data, success() { failed_alert_elem.hide(); exports.change_save_button_state(save_btn_container, "succeeded"); }, error(xhr) { exports.change_save_button_state(save_btn_container, "failed"); save_button.hide(); ui_report.error(i18n.t("Save failed"), xhr, failed_alert_elem); }, }); }; exports.parse_time_limit = function parse_time_limit(elem) { return Math.floor(Number.parseFloat(elem.val(), 10).toFixed(1) * 60); }; function get_complete_data_for_subsection(subsection) { let data = {}; if (subsection === "msg_editing") { const edit_limit_setting_value = $("#id_realm_msg_edit_limit_setting").val(); if (edit_limit_setting_value === "never") { data.allow_message_editing = false; } else if (edit_limit_setting_value === "custom_limit") { data.message_content_edit_limit_seconds = exports.parse_time_limit( $("#id_realm_message_content_edit_limit_minutes"), ); // Disable editing if the parsed time limit is 0 seconds data.allow_message_editing = Boolean(data.message_content_edit_limit_seconds); } else { data.allow_message_editing = true; data.message_content_edit_limit_seconds = settings_config.msg_edit_limit_dropdown_values.get( edit_limit_setting_value, ).seconds; } const delete_limit_setting_value = $("#id_realm_msg_delete_limit_setting").val(); if (delete_limit_setting_value === "never") { data.allow_message_deleting = false; } else if (delete_limit_setting_value === "custom_limit") { data.message_content_delete_limit_seconds = exports.parse_time_limit( $("#id_realm_message_content_delete_limit_minutes"), ); // Disable deleting if the parsed time limit is 0 seconds data.allow_message_deleting = Boolean(data.message_content_delete_limit_seconds); } else { data.allow_message_deleting = true; data.message_content_delete_limit_seconds = settings_config.msg_delete_limit_dropdown_values.get( delete_limit_setting_value, ).seconds; } } else if (subsection === "notifications") { data.notifications_stream_id = JSON.stringify( Number.parseInt(exports.notifications_stream_widget.value(), 10), ); data.signup_notifications_stream_id = JSON.stringify( Number.parseInt(exports.signup_notifications_stream_widget.value(), 10), ); } else if (subsection === "message_retention") { const message_retention_setting_value = $("#id_realm_message_retention_setting").val(); if (message_retention_setting_value === "retain_forever") { data.message_retention_days = JSON.stringify("forever"); } else { data.message_retention_days = JSON.stringify( exports.get_input_element_value($("#id_realm_message_retention_days")), ); } } else if (subsection === "other_settings") { const code_block_language_value = exports.default_code_language_widget.value(); data.default_code_block_language = JSON.stringify(code_block_language_value); } else if (subsection === "other_permissions") { const add_emoji_permission = $("#id_realm_add_emoji_by_admins_only").val(); if (add_emoji_permission === "by_admins_only") { data.add_emoji_by_admins_only = true; } else if (add_emoji_permission === "by_anyone") { data.add_emoji_by_admins_only = false; } } else if (subsection === "org_join") { const org_join_restrictions = $("#id_realm_org_join_restrictions").val(); if (org_join_restrictions === "only_selected_domain") { data.emails_restricted_to_domains = true; data.disallow_disposable_email_addresses = false; } else if (org_join_restrictions === "no_disposable_email") { data.emails_restricted_to_domains = false; data.disallow_disposable_email_addresses = true; } else if (org_join_restrictions === "no_restriction") { data.disallow_disposable_email_addresses = false; data.emails_restricted_to_domains = false; } const user_invite_restriction = $("#id_realm_user_invite_restriction").val(); if (user_invite_restriction === "no_invite_required") { data.invite_required = false; data.invite_by_admins_only = false; } else if (user_invite_restriction === "no_invite_required_by_admins_only") { data.invite_required = false; data.invite_by_admins_only = true; } else if (user_invite_restriction === "by_admins_only") { data.invite_required = true; data.invite_by_admins_only = true; } else { data.invite_required = true; data.invite_by_admins_only = false; } const waiting_period_threshold = $("#id_realm_waiting_period_setting").val(); if (waiting_period_threshold === "none") { data.waiting_period_threshold = 0; } else if (waiting_period_threshold === "three_days") { data.waiting_period_threshold = 3; } else if (waiting_period_threshold === "custom_days") { data.waiting_period_threshold = $("#id_realm_waiting_period_threshold").val(); } } else if (subsection === "auth_settings") { data = {}; data.authentication_methods = JSON.stringify(get_auth_method_table_data()); } else if (subsection === "user_defaults") { const realm_default_twenty_four_hour_time = $( "#id_realm_default_twenty_four_hour_time", ).val(); data.default_twenty_four_hour_time = realm_default_twenty_four_hour_time; } return data; } function populate_data_for_request(subsection) { const data = {}; const properties_elements = get_subsection_property_elements(subsection); for (let input_elem of properties_elements) { input_elem = $(input_elem); if (check_property_changed(input_elem)) { const input_value = exports.get_input_element_value(input_elem); if (input_value !== undefined) { const property_name = input_elem.attr("id").replace("id_realm_", ""); data[property_name] = JSON.stringify(input_value); } } } return data; } $(".organization").on("click", ".subsection-header .subsection-changes-save .button", (e) => { e.preventDefault(); e.stopPropagation(); const save_button = $(e.currentTarget); const subsection_id = save_button.attr("id").replace("org-submit-", ""); const subsection = subsection_id.split("-").join("_"); const subsection_elem = save_button.closest(".org-subsection-parent"); const data = { ...populate_data_for_request(subsection_elem), ...get_complete_data_for_subsection(subsection), }; exports.save_organization_settings(data, save_button); }); $(".org-subsection-parent").on("keydown", "input", (e) => { e.stopPropagation(); if (e.keyCode === 13) { e.preventDefault(); $(e.target) .closest(".org-subsection-parent") .find(".subsection-changes-save button") .trigger("click"); } }); $("#id_realm_msg_edit_limit_setting").on("change", (e) => { const msg_edit_limit_dropdown_value = e.target.value; change_element_block_display_property( "id_realm_message_content_edit_limit_minutes", msg_edit_limit_dropdown_value === "custom_limit", ); }); $("#id_realm_msg_delete_limit_setting").on("change", (e) => { const msg_delete_limit_dropdown_value = e.target.value; change_element_block_display_property( "id_realm_message_content_delete_limit_minutes", msg_delete_limit_dropdown_value === "custom_limit", ); }); $("#id_realm_message_retention_setting").on("change", (e) => { const message_retention_setting_dropdown_value = e.target.value; change_element_block_display_property( "id_realm_message_retention_days", message_retention_setting_dropdown_value === "retain_for_period", ); }); $("#id_realm_waiting_period_setting").on("change", function () { const waiting_period_threshold = this.value; change_element_block_display_property( "id_realm_waiting_period_threshold", waiting_period_threshold === "custom_days", ); }); $("#id_realm_org_join_restrictions").on("change", (e) => { const org_join_restrictions = e.target.value; const node = $("#allowed_domains_label").parent(); if (org_join_restrictions === "only_selected_domain") { node.show(); if (page_params.realm_domains.length === 0) { overlays.open_modal("#realm_domains_modal"); } } else { node.hide(); } }); $("#id_realm_org_join_restrictions").on("click", (e) => { // This prevents the disappearance of modal when there are // no allowed domains otherwise it gets closed due to // the click event handler attached to `#settings_overlay_container` e.stopPropagation(); }); function fade_status_element(elem) { setTimeout(() => { elem.fadeOut(500); }, 1000); } $("#realm_domains_table").on("click", ".delete_realm_domain", function () { const domain = $(this).parents("tr").find(".domain").text(); const url = "/json/realm/domains/" + domain; const realm_domains_info = $(".realm_domains_info"); channel.del({ url, success() { ui_report.success(i18n.t("Deleted successfully!"), realm_domains_info); fade_status_element(realm_domains_info); }, error(xhr) { ui_report.error(i18n.t("Failed"), xhr, realm_domains_info); fade_status_element(realm_domains_info); }, }); }); $("#submit-add-realm-domain").on("click", () => { const realm_domains_info = $(".realm_domains_info"); const widget = $("#add-realm-domain-widget"); const domain = widget.find(".new-realm-domain").val(); const allow_subdomains = widget.find(".new-realm-domain-allow-subdomains").prop("checked"); const data = { domain: JSON.stringify(domain), allow_subdomains: JSON.stringify(allow_subdomains), }; channel.post({ url: "/json/realm/domains", data, success() { $("#add-realm-domain-widget .new-realm-domain").val(""); $("#add-realm-domain-widget .new-realm-domain-allow-subdomains").prop( "checked", false, ); ui_report.success(i18n.t("Added successfully!"), realm_domains_info); fade_status_element(realm_domains_info); }, error(xhr) { ui_report.error(i18n.t("Failed"), xhr, realm_domains_info); fade_status_element(realm_domains_info); }, }); }); $("#realm_domains_table").on("change", ".allow-subdomains", function (e) { e.stopPropagation(); const realm_domains_info = $(".realm_domains_info"); const domain = $(this).parents("tr").find(".domain").text(); const allow_subdomains = $(this).prop("checked"); const url = "/json/realm/domains/" + domain; const data = { allow_subdomains: JSON.stringify(allow_subdomains), }; channel.patch({ url, data, success() { if (allow_subdomains) { ui_report.success( i18n.t("Update successful: Subdomains allowed for __domain__", { domain, }), realm_domains_info, ); } else { ui_report.success( i18n.t("Update successful: Subdomains no longer allowed for __domain__", { domain, }), realm_domains_info, ); } fade_status_element(realm_domains_info); }, error(xhr) { ui_report.error(i18n.t("Failed"), xhr, realm_domains_info); fade_status_element(realm_domains_info); }, }); }); function realm_icon_logo_upload_complete(spinner, upload_text, delete_button) { spinner.css({visibility: "hidden"}); upload_text.show(); delete_button.show(); } function realm_icon_logo_upload_start(spinner, upload_text, delete_button) { spinner.css({visibility: "visible"}); upload_text.hide(); delete_button.hide(); } function upload_realm_logo_or_icon(file_input, night, icon) { const form_data = new FormData(); let widget; let url; form_data.append("csrfmiddlewaretoken", csrf_token); for (const [i, file] of Array.prototype.entries.call(file_input[0].files)) { form_data.append("file-" + i, file); } if (icon) { url = "/json/realm/icon"; widget = "#realm-icon-upload-widget"; } else { if (night) { widget = "#realm-night-logo-upload-widget"; } else { widget = "#realm-day-logo-upload-widget"; } url = "/json/realm/logo"; form_data.append("night", JSON.stringify(night)); } const spinner = $(`${widget} .upload-spinner-background`).expectOne(); const upload_text = $(`${widget} .image-upload-text`).expectOne(); const delete_button = $(`${widget} .image-delete-button`).expectOne(); const error_field = $(`${widget} .image_file_input_error`).expectOne(); realm_icon_logo_upload_start(spinner, upload_text, delete_button); error_field.hide(); channel.post({ url, data: form_data, cache: false, processData: false, contentType: false, success() { realm_icon_logo_upload_complete(spinner, upload_text, delete_button); }, error(xhr) { realm_icon_logo_upload_complete(spinner, upload_text, delete_button); ui_report.error("", xhr, error_field); }, }); } realm_icon.build_realm_icon_widget(upload_realm_logo_or_icon, null, true); if (page_params.zulip_plan_is_not_limited) { realm_logo.build_realm_logo_widget(upload_realm_logo_or_icon, false); realm_logo.build_realm_logo_widget(upload_realm_logo_or_icon, true); } $("#deactivate_realm_button").on("click", (e) => { if (!overlays.is_modal_open()) { e.preventDefault(); e.stopPropagation(); overlays.open_modal("#deactivate-realm-modal"); } }); $("#do_deactivate_realm_button").on("click", () => { if (overlays.is_modal_open()) { overlays.close_modal("#deactivate-realm-modal"); } channel.post({ url: "/json/realm/deactivate", error(xhr) { ui_report.error( i18n.t("Failed"), xhr, $("#admin-realm-deactivation-status").expectOne(), ); }, }); }); }; window.settings_org = exports;
{ "content_hash": "1297a942fc9a00c17a57e1b618fd11d7", "timestamp": "", "source": "github", "line_count": 1110, "max_line_length": 113, "avg_line_length": 37.457657657657656, "alnum_prop": 0.58393862138631, "repo_name": "showell/zulip", "id": "79f33df64619d518f9ecaa277e6bb4e830e4ce58", "size": "41578", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "static/js/settings_org.js", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "433235" }, { "name": "Dockerfile", "bytes": "2941" }, { "name": "Emacs Lisp", "bytes": "157" }, { "name": "HTML", "bytes": "634357" }, { "name": "Handlebars", "bytes": "235334" }, { "name": "JavaScript", "bytes": "3341135" }, { "name": "Perl", "bytes": "8594" }, { "name": "Puppet", "bytes": "79720" }, { "name": "Python", "bytes": "8120030" }, { "name": "Ruby", "bytes": "8480" }, { "name": "Shell", "bytes": "133132" }, { "name": "TypeScript", "bytes": "20603" } ], "symlink_target": "" }
%VREP V-REP simulator communications object % % A VREP object holds all information related to the state of a connection % to an instance of the V-REP simulator running on this or a networked % computer. Allows the creation of references to other objects/models in % V-REP which can be manipulated in MATLAB. % % This class handles the interface to the simulator and low-level object % handle operations. % % Methods throw exception if an error occurs. % % Methods:: % % gethandle get handle to named object % getchildren get children belonging to handle % getobjname get names of objects %- % object return a VREP_obj object for named object % arm return a VREP_arm object for named robot % camera return a VREP_camera object for named vosion sensor % hokuyo return a VREP_hokuyo object for named Hokuyo scanner %- % getpos return position of object given handle % setpos set position of object given handle % getorient return orientation of object given handle % setorient set orientation of object given handle % getpose return pose of object given handle % setpose set pose of object given handle %- % setobjparam_bool set object boolean parameter % setobjparam_int set object integer parameter % setobjparam_float set object float parameter % getobjparam_bool get object boolean parameter % getobjparam_int get object integer parameter % getobjparam_float get object float parameter %- % signal_int send named integer signal % signal_float send named float signal % signal_str send named string signal %- % setparam_bool set simulator boolean parameter % setparam_int set simulator integer parameter % setparam_str set simulator string parameter % setparam_float set simulator float parameter % getparam_bool get simulator boolean parameter % getparam_int get simulator integer parameter % getparam_str get simulator string parameter % getparam_float get simulator float parameter %- % delete shutdown the connection and cleanup %- % simstart start the simulator running % simstop stop the simulator running % simpause pause the simulator % getversion get V-REP version number % checkcomms return status of connection % pausecomms pause the comms %- % loadscene load a scene file % clearscene clear the current scene % loadmodel load a model into current scene %- % display print the link parameters in human readable form % char convert to string % % See also VREP_obj, VREP_arm, VREP_camera, VREP_hokuyo. % Copyright (C) 1993-2015, by Peter I. Corke % % This file is part of The Robotics Toolbox for MATLAB (RTB). % % RTB is free software: you can redistribute it and/or modify % it under the terms of the GNU Lesser General Public License as published by % the Free Software Foundation, either version 3 of the License, or % (at your option) any later version. % % RTB is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU Lesser General Public License for more details. % % You should have received a copy of the GNU Leser General Public License % along with RTB. If not, see <http://www.gnu.org/licenses/>. % % http://www.petercorke.com classdef VREP < handle properties(GetAccess=public, SetAccess=protected) vrep % the remApi object client % the comms handle path % path to V-REP root mode % the communications mode libpath % list of libraries added to path version % the version as given by user 304, 311 etc. end methods function obj = VREP(varargin) %VREP.VREP VREP object constructor % % v = VREP(OPTIONS) create a connection to an instance of the V-REP % simulator. % % Options:: % 'timeout',T Timeout T in ms (default 2000) % 'cycle',C Cycle time C in ms (default 5) % 'port',P Override communications port % 'reconnect' Reconnect on error (default noreconnect) % 'path',P The path to VREP install directory % % Notes:: % - The default path is taken from the environment variable VREP opt.timeout = 2000; opt.cycle = 5; opt.port = 19997; opt.reconnect = false; opt.path = getenv('VREP'); [opt,args] = tb_optparse(opt, varargin); % setup paths if isempty(opt.path) error('RTB:VREP:badargs', 'no VREP path specified'); end if ~exist(opt.path, 'dir') error('RTB:VREP:badargs', 'Root VREP folder %s does not exist', opt.path); end obj.path = opt.path; % % for 3.0.4 % libpath = { fullfile(path, 'programming', 'remoteApi') % fullfile(path, 'programming', 'Matlab') % fullfile(path, 'programming', 'remoteApiSharedLib') % }; % port = 19998; % for 3.1.x libpath = { fullfile(opt.path, 'programming', 'remoteApi') fullfile(opt.path, 'programming', 'remoteApiBindings', 'matlab', 'matlab') fullfile(opt.path, 'programming', 'remoteApiBindings', 'lib', 'lib') }; addpath( libpath{:} ); obj.libpath = libpath; obj.vrep = remApi('remoteApi','extApi.h'); % IP address and port % wait until connected % do not attempt to reconnect % timeout is 2000ms % comms cycle time is 5ms % establish the connection obj.client = obj.vrep.simxStart('127.0.0.1', opt.port, true, ... ~opt.reconnect, opt.timeout, opt.cycle); if obj.client < 0 error('RTB:VREP:noconnect', 'Can''t connect to V-REP simulator'); end obj.mode = obj.vrep.simx_opmode_oneshot_wait; % get actual version number as a string vint = obj.getversion(); v = ''; for i=1:3 v = [num2str(rem(vint,100)) v]; vint = floor(vint/100); if i < 3 v = ['.' v]; end end obj.version = v; end function display(v) %VREP.display Display parameters % % V.display() displays the VREP parameters in compact format. % % Notes:: % - This method is invoked implicitly at the command line when the result % of an expression is a VREP object and the command has no trailing % semicolon. % % See also VREP.char. loose = strcmp( get(0, 'FormatSpacing'), 'loose'); if loose disp(' '); end disp([inputname(1), ' = ']) disp( char(v) ); end % display() function s = char(obj) %VREP.char Convert to string % % V.char() is a string representation the VREP parameters in human % readable foramt. % % See also VREP.display. s = sprintf('V-REP robotic simulator interface (active=%d)', obj.checkcomms() ); s = strvcat(s, sprintf('path: %s (ver %s)', obj.path, obj.version)); switch obj.mode case obj.vrep.simx_opmode_oneshot s = strvcat(s, 'mode: simx_opmode_oneshot (non-blocking)'); case obj.vrep.simx_opmode_oneshot_wait s = strvcat(s, 'mode: simx_opmode_oneshot_wait (blocking)'); case obj.vrep.simx_opmode_streaming s = strvcat(s, 'mode: simx_opmode_streaming (non-blocking)'); end end function delete(obj) %VREP.delete VREP object destructor % % delete(v) closes the connection to the V-REP simulator disp('--VREP destructor called'); obj.vrep.simxFinish(obj.client); obj.vrep.delete(); % explicitly call the destructor! obj.vrep = []; rmpath( obj.libpath{:} ); end %---- wrapper functions for getting object handles function [h,s] = gethandle(obj, fmt, varargin) %VREP.gethandle Return handle to VREP object % % H = V.gethandle(NAME) is an integer handle for named V-REP object. % % H = V.gethandle(FMT, ARGLIST) as above but the name is formed % from sprintf(FMT, ARGLIST). % % See also sprintf. [s,h] = obj.vrep.simxGetObjectHandle(obj.client, sprintf(fmt, varargin{:}), obj.mode); end function children = getchildren(obj, h) %VREP.getchildren Find children of object % % C = V.getchildren(H) is a vector of integer handles for the children of % the V-REP object denoted by the integer handle H. i = 0; while true [s,ch] = obj.vrep.simxGetObjectChild(obj.client, h, i, obj.mode); if s < 0 break end i = i+1; children(i) = ch; end end function out = getobjname(obj, h) %VREP.getname Find names of objects % % V.getobjname() will display the names and object handle (integers) for % all objects in the current scene. % % NAME = V.getobjname(H) will return the name of the object with handle H. [s,handles,~,~,strd] = obj.vrep.simxGetObjectGroupData(obj.client, obj.vrep.sim_appobj_object_type, 0, obj.mode); if s ~= 0 throw( obj.except(s) ); end if nargin < 2 name = strd(:,1); else name = strd{handles == h,1}; end if (nargout == 0) && (nargin < 2) for i=1:length(name) fprintf('%3d: %s\n', handles(i), strd{i}); return end end out = name; end % HOW DO I GET OBJECT TYPE FROM V-REP?? % % Scene object types % sim_object_shape_type =0; % sim_object_joint_type =1; % sim_object_graph_type =2; % sim_object_camera_type =3; % sim_object_dummy_type =4; % sim_object_proximitysensor_type =5; % sim_object_reserved1 =6; % sim_object_reserved2 =7; % sim_object_path_type =8; % sim_object_visionsensor_type =9; % sim_object_volume_type =10; % sim_object_mill_type =11; % sim_object_forcesensor_type =12; % sim_object_light_type =13; % sim_object_mirror_type =14; %---- simulation control function simstart(obj) %VREP.simstart Start V-REP simulation % % V.simstart() starts the V-REP simulation engine. % % See also VREP.simstop, VREP.simpause. s = obj.vrep.simxStartSimulation(obj.client, obj.mode); end function simstop(obj) %VREP.simstop Stop V-REP simulation % % V.simstop() stops the V-REP simulation engine. % % See also VREP.simstart. s = obj.vrep.simxStopSimulation(obj.client, obj.mode); end function simpause(obj) %VREP.pause Pause V-REP simulation % % V.simpause() pauses the V-REP simulation engine. Use % V.simstart() to resume the simulation. % % See also VREP.simstart. s = obj.vrep.simxPauseSimulation(obj.client, obj.mode); end function v = getversion(obj) %VREP.getversion Get version of the V-REP simulator % % V.getversion() is the version of the V-REP simulator % server as an integer MNNNN where M is the major version % number and NNNN is the minor version number. [s,v] = obj.vrep.simxGetIntegerParameter(obj.client, obj.vrep.sim_intparam_program_version, obj.mode); end function s = checkcomms(obj) %VREP.checkcomms Check communications to V-REP simulator % % V.checkcomms() is true if a valid connection to the V-REP simulator exists. s = obj.vrep.simxGetConnectionId(obj.client); end function pausecomms(obj, onoff) %VREP.pausecomms Pause communcations to the V-REP simulator % % V.pausecomms(P) pauses communications to the V-REP simulation engine if P is true % else resumes it. Useful to ensure an atomic update of % simulator state. s = obj.vrep.simxPauseCommunication(obj.client, onoff, obj.mode); if s ~= 0 throw( obj.except(s) ); end end function loadscene(obj, name, varargin) %VREP.loadscene Load a scene into the V-REP simulator % % V.loadscene(FILE, OPTIONS) loads the scene file FILE with extension .ttt % into the simulator. % % Options:: % 'local' The file is loaded relative to the MATLAB client's current % folder, otherwise from the V-REP root folder. % % Example:: % vrep.loadscene('2IndustrialRobots'); % % Notes:: % - If a relative filename is given in non-local (server) mode it is % relative to the V-REP scenes folder. % % See also VREP.clearscene. opt.local = false; opt = tb_optparse(opt, varargin); if ~opt.local if name(1) ~= '/' % its a relative path, add in full path name = fullfile(obj.path, 'scenes', [name '.ttt']); end end s = obj.vrep.simxLoadScene(obj.client, name, opt.local, obj.mode); if s ~= 0 throw( obj.except(s) ); end end function clearscene(obj, name, varargin) %VREP.clearscene Clear current scene in the V-REP simulator % % V.clearscene() clears the current scene and switches to another open % scene, if none, a new (default) scene is created. % % See also VREP.loadscene. s = obj.vrep.simxCloseScene(obj.client, obj.mode); if s ~= 0 throw( obj.except(s) ); end end function m = loadmodel(obj, model, varargin) %VREP.loadmodel Load a model into the V-REP simulator % % M = V.loadmodel(FILE, OPTIONS) loads the model file FILE with extension .ttm % into the simulator and returns a VREP_obj object that mirrors it in % MATLAB. % % Options:: % 'local' The file is loaded relative to the MATLAB client's current % folder, otherwise from the V-REP root folder. % % Example:: % vrep.loadmodel('people/Walking Bill'); % % Notes:: % - If a relative filename is given in non-local (server) mode it is % relative to the V-REP models folder. % % See also VREP.arm, VREP.camera, VREP.object. opt.local = false; opt.name = []; opt = tb_optparse(opt, varargin); if ~opt.local if model(1) ~= '/' % its a relative path, add in full path model = fullfile(obj.path, 'models', [model '.ttm']); end end [s,bh] = obj.vrep.simxLoadModel(obj.client, model, opt.local, obj.mode); if s ~= 0 throw( obj.except(s) ); end m = obj.object(bh, varargin{:}); pause(0.5); end %---- signals function signal_int(obj, name, val) %VREP.signal_int Send an integer signal to the V-REP simulator % % V.signal_int(NAME, VAL) send an integer signal with name NAME % and value VAL to the V-REP simulation engine. s = obj.vrep.simxSetIntegerSignal(obj.client, name, val, obj.mode); if s ~= 0 throw( obj.except(s) ); end end function signal_float(obj, name, val) %VREP.signal_float Send a float signal to the V-REP simulator % % V.signal_float(NAME, VAL) send a float signal with name NAME % and value VAL to the V-REP simulation engine. s = obj.vrep.simxSetFloatSignal(obj.client, name, val, obj.mode); if s ~= 0 throw( obj.except(s) ); end end function signal_str(obj, name, val) %VREP.signal_str Send a string signal to the V-REP simulator % % V.signal_str(NAME, VAL) send a string signal with name NAME % and value VAL to the V-REP simulation engine. s = obj.vrep.simxSetStringSignal(obj.client, name, val, obj.mode); if s ~= 0 throw( obj.except(s) ); end end %---- set/get simulator parameters function setparam_bool(obj, paramid, val) %VREP.setparam_bool Set boolean parameter of the V-REP simulator % % V.setparam_bool(NAME, VAL) sets the boolean parameter with name NAME % to value VAL within the V-REP simulation engine. % % See also VREP.getparam_bool. if isstr(paramid) paramid = eval(['obj.vrep.' paramid]); end s = obj.vrep.simxSetBooleanParameter(obj.client, paramid, val, obj.mode); if s ~= 0 throw( obj.except(s) ); end end function setparam_int(obj, paramid, val) %VREP.setparam_int Set integer parameter of the V-REP simulator % % V.setparam_int(NAME, VAL) sets the integer parameter with name NAME % to value VAL within the V-REP simulation engine. % % See also VREP.getparam_int. if isstr(paramid) paramid = eval(['obj.vrep.' paramid]); end s = obj.vrep.simxSetIntegerParameter(obj.client, paramid, val, obj.mode); if s ~= 0 throw( obj.except(s) ); end end function setparam_str(obj, paramid, val) %VREP.setparam_str Set string parameter of the V-REP simulator % % V.setparam_str(NAME, VAL) sets the integer parameter with name NAME % to value VAL within the V-REP simulation engine. % % See also VREP.getparam_str. if isstr(paramid) paramid = eval(['obj.vrep.' paramid]); end s = obj.vrep.simxSetStringParameter(obj.client, paramid, val, obj.mode); if s ~= 0 throw( obj.except(s) ); end end function setparam_float(obj, paramid, val) %VREP.setparam_float Set float parameter of the V-REP simulator % % V.setparam_float(NAME, VAL) sets the float parameter with name NAME % to value VAL within the V-REP simulation engine. % % See also VREP.getparam_float. if isstr(paramid) paramid = eval(['obj.vrep.' paramid]); end s = obj.vrep.simxSetFloatingParameter(obj.client, paramid, val, obj.mode); if s ~= 0 throw( obj.except(s) ); end end function v = getparam_bool(obj, paramid) %VREP.getparam_bool Get boolean parameter of the V-REP simulator % % V.getparam_bool(NAME) is the boolean parameter with name NAME % from the V-REP simulation engine. % % Example:: % v = VREP(); % v.getparam_bool('sim_boolparam_mirrors_enabled') % % See also VREP.setparam_bool. if isstr(paramid) paramid = eval(['obj.vrep.' paramid]); end [s,v] = obj.vrep.simxGetBooleanParameter(obj.client, paramid, obj.mode); if s ~= 0 throw( obj.except(s) ); end end function v = getparam_int(obj, paramid) %VREP.getparam_int Get integer parameter of the V-REP simulator % % V.getparam_int(NAME) is the integer parameter with name NAME % from the V-REP simulation engine. % % Example:: % v = VREP(); % v.getparam_int('sim_intparam_settings') % % See also VREP.setparam_int. if isstr(paramid) paramid = eval(['obj.vrep.' paramid]); end [s,v] = obj.vrep.simxGetIntegerParameter(obj.client, paramid, obj.mode); if s ~= 0 throw( obj.except(s) ); end end function v = getparam_str(obj, paramid) %VREP.getparam_str Get string parameter of the V-REP simulator % % V.getparam_str(NAME) is the string parameter with name NAME % from the V-REP simulation engine. % % Example:: % v = VREP(); % v.getparam_str('sim_stringparam_application_path') % % See also VREP.setparam_str. if isstr(paramid) paramid = eval(['obj.vrep.' paramid]); end [s,v] = obj.vrep.simxGetStringParameter(obj.client, paramid, obj.mode); if s ~= 0 throw( obj.except(s) ); end end function v = getparam_float(obj, paramid) %VREP.getparam_float Get float parameter of the V-REP simulator % % V.getparam_float(NAME) gets the float parameter with name NAME % from the V-REP simulation engine. % % Example:: % v = VREP(); % v.getparam_float('sim_floatparam_simulation_time_step') % % See also VREP.setparam_float. if isstr(paramid) paramid = eval(['obj.vrep.' paramid]); end [s,v] = obj.vrep.simxGetFloatingParameter(obj.client, paramid, obj.mode); if s ~= 0 throw( obj.except(s) ); end end %---- set/get object parameters function setobjparam_bool(obj, h, paramid, val) %VREP.setobjparam_bool Set boolean parameter of a V-REP object % % V.setobjparam_bool(H, PARAM, VAL) sets the boolean parameter % with identifier PARAM of object H to value VAL. s = obj.vrep.simxSetObjectIntParameter(obj.client, h, paramid, val, obj.mode); if s ~= 0 throw( obj.except(s) ); end end function setobjparam_int(obj, h, paramid, val) %VREP.setobjparam_int Set Integer parameter of a V-REP object % % V.setobjparam_int(H, PARAM, VAL) sets the integer parameter % with identifier PARAM of object H to value VAL. s = obj.vrep.simxSetObjectIntParameter(obj.client, h, paramid, val, obj.mode); if s ~= 0 throw( obj.except(s) ); end end function setobjparam_float(obj, h, paramid, val) %VREP.setobjparam_float Set float parameter of a V-REP object % % V.setobjparam_float(H, PARAM, VAL) sets the float parameter % with identifier PARAM of object H to value VAL. s = obj.vrep.simxSetObjectFloatParameter(obj.client, h, paramid, val, obj.mode); if s ~= 0 throw( obj.except(s) ); end end function val = getobjparam_bool(obj, h, paramid) %VREP.getobjparam_bool Get boolean parameter of a V-REP object % % V.getobjparam_bool(H, PARAM) gets the boolean parameter % with identifier PARAM of object with integer handle H. [s,val] = obj.vrep.simxGetObjectIntParameter(obj.client, h, paramid, obj.mode); if s ~= 0 throw( obj.except(s) ); end end function val = getobjparam_int(obj, h, paramid) %VREP.getobjparam_int Get integer parameter of a V-REP object % % V.getobjparam_int(H, PARAM) gets the integer parameter % with identifier PARAM of object with integer handle H. [s,val] = obj.vrep.simxGetObjectIntParameter(obj.client, h, paramid, obj.mode); if s ~= 0 throw( obj.except(s) ); end end function val = getobjparam_float(obj, h, paramid) %VREP.getobjparam_float Get float parameter of a V-REP object % % V.getobjparam_float(H, PARAM) gets the float parameter % with identifier PARAM of object with integer handle H. [s,val] = obj.vrep.simxGetObjectFloatParameter(obj.client, h, paramid, obj.mode); if s ~= 0 throw( obj.except(s) ); end end %---- wrapper functions for using joint objects function setjoint(obj, h, q) %VREP.setjoint Set value of V-REP joint object % % V.setjoint(H, Q) sets the position of joint object with integer handle H % to the value Q. s = obj.vrep.simxSetJointPosition(obj.client, h, q, obj.mode); end function q = getjoint(obj, h) %VREP.getjoint Get value of V-REP joint object % % V.getjoint(H, Q) is the position of joint object with integer handle H. [s,q] = obj.vrep.simxGetJointPosition(obj.client, h, obj.mode); if s ~= 0 throw( obj.except(s) ); end end function setjointtarget(obj, h, q) %VREP.setjointtarget Set target value of V-REP joint object % % V.setjointtarget(H, Q) sets the target position of joint object with integer handle H % to the value Q. s = obj.vrep.simxSetJointTargetPosition(obj.client, h, q, obj.mode); if s ~= 0 throw( obj.except(s) ); end end function setjointvel(obj, h, qd) %VREP.setjointvel Set velocity of V-REP joint object % % V.setjointvel(H, QD) sets the target velocity of joint object with integer handle H % to the value QD. s = obj.vrep.simxSetJointTargetVelocity(obj.client, h, qd, obj.mode); if s ~= 0 throw( obj.except(s) ); end end %---- wrapper functions for position of objects function setpos(obj, h, t, relto) %VREP.setpos Set position of V-REP object % % V.setpos(H, T) sets the position of V-REP object with integer % handle H to T (1x3). % % V.setpos(H, T, HR) as above but position is set relative to the % position of object with integer handle HR. % % See also VREP.getpos, VREP.setpose, VREP.setorient. if nargin < 4 relto = -1; end s = obj.vrep.simxSetObjectPosition(obj.client, h, relto, t, obj.mode); if s ~= 0 throw( obj.except(s) ); end end function t = getpos(obj, h, relto) %VREP.getpos Get position of V-REP object % % V.getpos(H) is the position (1x3) of the V-REP object with integer % handle H. % % V.getpos(H, HR) as above but position is relative to the % position of object with integer handle HR. % % See also VREP.setpose, VREP.getpose, VREP.getorient. if nargin < 4 relto = -1; end [s,t] = obj.vrep.simxGetObjectPosition(obj.client, h, relto, obj.mode); if s ~= 0 throw( obj.except(s) ); end end %---- wrapper functions for pose of objects function setpose(obj, h, T, relto) %VREP.setpose Set pose of V-REP object % % V.setpos(H, T) sets the pose of V-REP object with integer % handle H according to homogeneous transform T (4x4). % % V.setpos(H, T, HR) as above but pose is set relative to the % pose of object with integer handle HR. % % See also VREP.getpose, VREP.setpos, VREP.setorient. if nargin < 4 relto = -1; elseif isa(relto, 'VREP_base') relto = relto.h; end pos = transl(T); eul = tr2eul(T, 'deg'); s = obj.vrep.simxSetObjectPosition(obj.client, h, relto, pos, obj.mode); if s ~= 0 throw( obj.except(s) ); end s = obj.vrep.simxSetObjectOrientation(obj.client, h, relto, eul, obj.mode); if s < 0 throw( obj.except(s) ); end end function T = getpose(obj, h, relto) %VREP.getpose Get pose of V-REP object % % T = V.getpose(H) is the pose of the V-REP object with integer % handle H as a homogeneous transformation matrix (4x4). % % T = V.getpose(H, HR) as above but pose is relative to the % pose of object with integer handle R. % % See also VREP.setpose, VREP.getpos, VREP.getorient. if nargin < 4 relto = -1; elseif isa(relto, 'VREP_base') relto = relto.h; end [s,pos] = obj.vrep.simxGetObjectPosition(obj.client, h, relto, obj.mode); if s ~= 0 throw( obj.except(s) ); end [s,eul] = obj.vrep.simxGetObjectOrientation(obj.client, h, relto, obj.mode); if s ~= 0 throw( obj.except(s) ); end T = transl(pos) * eul2tr(eul, 'deg'); end %---- wrapper functions for orientation of objects function setorient(obj, h, R, relto) %VREP.setorient Set orientation of V-REP object % % V.setorient(H, R) sets the orientation of V-REP object with integer % handle H to that given by rotation matrix R (3x3). % % V.setorient(H, T) sets the orientation of V-REP object with integer % handle H to rotational component of homogeneous transformation matrix % T (4x4). % % V.setorient(H, E) sets the orientation of V-REP object with integer % handle H to ZYZ Euler angles (1x3). % % V.setorient(H, X, HR) as above but orientation is set relative to the % orientation of object with integer handle HR. % % See also VREP.getorient, VREP.setpos, VREP.setpose. if nargin < 4 relto = -1; elseif isa(relto, 'VREP_base') relto = relto.h; end if isrot(R) || ishomog(R) eul = tr2eul(R); elseif isvec(R, 3) eul = R; end s = obj.vrep.simxSetObjectOrientation(obj.client, h, relto, eul, obj.mode); if s ~= 0 throw( obj.except(s) ); end end function R = getorient(obj, h, relto, varargin) %VREP.getorient Get orientation of V-REP object % % R = V.getorient(H) is the orientation of the V-REP object with integer % handle H as a rotation matrix (3x3). % % EUL = V.getorient(H, 'euler', OPTIONS) as above but returns ZYZ Euler % angles. % % V.getorient(H, HRR) as above but orientation is relative to the % position of object with integer handle HR. % % V.getorient(H, HRR, 'euler', OPTIONS) as above but returns ZYZ Euler % angles. % % Options:: % See tr2eul. % % See also VREP.setorient, VREP.getpos, VREP.getpose. if nargin < 4 relto = -1; elseif isa(relto, 'VREP_base') relto = relto.h; end opt.euler = false; [opt,args] = tb_optparse(opt, varargin); [s,eul] = obj.vrep.simxGetObjectOrientation(obj.client, h, relto, obj.mode); if s ~= 0 throw( obj.except(s) ); end if opt.euler R = eul; else R = eul2tr(eul, args{:}); end end %---- factory methods to create instances of specific objects that mirror VREP objects function a = arm(obj, name) %VREP.arm Return VREP_arm object % % V.arm(name) is a factory method that returns a VREP_arm object for the V-REP robot % object named NAME. % % Example:: % vrep.arm('IRB 140'); % % See also VREP_arm. if isa(name, 'VREP_obj') h = name.h; name = name.getname(); end a = VREP_arm(obj, name); end function o = object(obj, varargin) %VREP.arm Return VREP_obj object % % V.objet(name) is a factory method that returns a VREP_obj object for the V-REP % object or model named NAME. % Example:: % vrep.obj('Walking Bill'); % % See also VREP_obj. o = VREP_obj(obj, varargin{:}); end function m = mobile(obj, name) %VREP.mobile Return VREP_mobile object % % V.mobile(name) is a factory method that returns a % VREP_mobile object for the V-REP mobile base object named NAME. % % See also VREP_mobile. m = VREP_mobile(obj, name); end function m = camera(obj, name) %VREP.camera Return VREP_camera object % % V.camera(name) is a factory method that returns a VREP_camera object for the V-REP vision % sensor object named NAME. % % See also VREP_camera. m = VREP_camera(obj, name); end function m = hokuyo(obj, name) %VREP.hokuyo Return VREP_hokuyo object % % V.hokuyo(name) is a factory method that returns a VREP_hokuyo % object for the V-REP Hokuyo laser scanner object named NAME. % % See also VREP_hokuyo. m = VREP_mobile(obj, name); end function m = youbot(obj, name) %VREP.youbot Return VREP_youbot object % % V.youbot(name) is a factory method that returns a VREP_youbot % object for the V-REP YouBot object named NAME. % % See also VREP_youbot. m = VREP_youbot(obj, name); end end methods(Access=private) function e = except(obj, s) switch (s) case obj.vrep.simx_return_novalue_flag %1 msgid = 'VREP:noreply'; err = 'No command reply in the input buffer'; case obj.vrep.simx_return_timeout_flag %2 msgid = 'VREP:timedout'; err = 'function timed out (probably the network is down or too slow)'; case obj.vrep.simx_return_illegal_opmode_flag %4 msgid = 'VREP:notsupported'; err = 'The specified operation mode is not supported for the given function'; case obj.vrep.simx_return_remote_error_flag %8 msgid = 'VREP:serversideerrror'; err = 'function caused an error on the server side (e.g. an invalid handle was specified)'; case obj.vrep.simx_return_split_progress_flag %16 msgid = 'VREP:busy'; err = 'The communication thread is still processing previous split command of the same type'; case obj.vrep.simx_return_local_error_flag %32 msgid = 'VREP:clientsideerror'; err = 'The function caused an error on the client side'; case obj.vrep.simx_return_initialize_error_flag %64 msgid = 'VREP:nostarted'; err = 'simxStart was not yet called' end e = MException(msgid, err); end end end
{ "content_hash": "6a7b8fca2d314b2d574c6004a0714ae9", "timestamp": "", "source": "github", "line_count": 1035, "max_line_length": 125, "avg_line_length": 37.854106280193236, "alnum_prop": 0.5119834605273234, "repo_name": "alfkjartan/khmatlab", "id": "7cda27a316aea6254ecfb22dea8a25ade555154b", "size": "39179", "binary": false, "copies": "10", "ref": "refs/heads/master", "path": "thirdpart/rvctools/robot/interfaces/VREP/VREP.m", "mode": "33188", "license": "mit", "language": [ { "name": "C", "bytes": "54863" }, { "name": "C++", "bytes": "56933" }, { "name": "HTML", "bytes": "812491" }, { "name": "Java", "bytes": "36102" }, { "name": "M", "bytes": "1241" }, { "name": "Makefile", "bytes": "552" }, { "name": "Mathematica", "bytes": "1184" }, { "name": "Matlab", "bytes": "4218872" }, { "name": "Mercury", "bytes": "201" }, { "name": "Objective-C", "bytes": "465" }, { "name": "TeX", "bytes": "243545" } ], "symlink_target": "" }
#include <iostream> #include <HFO.hpp> #include <glog/logging.h> #include <gflags/gflags.h> #include "dqn.hpp" #include "hfo_game.hpp" #include <boost/filesystem.hpp> #include <thread> #include <mutex> #include <algorithm> #include <chrono> #include <limits> #include <stdlib.h> using namespace boost::filesystem; using namespace hfo; DEFINE_bool(gpu, true, "Use GPU to brew Caffe"); DEFINE_bool(benchmark, false, "Benchmark the network and exit"); DEFINE_bool(learn_offline, false, "Just do updates on a fixed replaymemory."); // Load/Save Args DEFINE_string(save, "", "Prefix for saving snapshots"); DEFINE_string(resume, "", "Prefix for resuming from. Default=save_path"); DEFINE_string(actor_weights, "", "The actor pretrained weights load (*.caffemodel)."); DEFINE_string(critic_weights, "", "The critic pretrained weights load (*.caffemodel)."); DEFINE_string(actor_snapshot, "", "The actor solver state to load (*.solverstate)."); DEFINE_string(critic_snapshot, "", "The critic solver state to load (*.solverstate)."); DEFINE_string(memory_snapshot, "", "The replay memory to load (*.replaymemory)."); // Solver Args DEFINE_string(solver, "Adam", "Solver Type."); DEFINE_double(momentum, .95, "Solver momentum."); DEFINE_double(momentum2, .999, "Solver momentum2."); DEFINE_double(actor_lr, .00001, "Solver learning rate."); DEFINE_double(critic_lr, .001, "Solver learning rate."); DEFINE_double(clip_grad, 10, "Clip gradients."); DEFINE_string(lr_policy, "fixed", "LR Policy."); DEFINE_int32(max_iter, 10000000, "Custom max iter."); // Epsilon-Greedy Args DEFINE_int32(explore, 10000, "Iterations for epsilon to reach given value."); DEFINE_double(epsilon, .1, "Value of epsilon after explore iterations."); DEFINE_double(evaluate_with_epsilon, 0, "Epsilon value to be used in evaluation mode"); // Evaluation Args DEFINE_bool(evaluate, false, "Evaluation mode: only playing a game, no updates"); DEFINE_int32(evaluate_freq, 10000, "Frequency (steps) between evaluations"); DEFINE_int32(repeat_games, 100, "Number of games played in evaluation mode"); // Misc Args DEFINE_double(update_ratio, 0.1, "Ratio of new experiences to updates."); // Sharing DEFINE_int32(share_actor_layers, 0, "Share layers between actor networks."); DEFINE_int32(share_critic_layers, 0, "Share layers between critic networks."); DEFINE_bool(share_replay_memory, false, "Shares replay memory between agents."); // Game configuration DEFINE_int32(offense_agents, 1, "Number of agents playing offense"); DEFINE_int32(offense_npcs, 0, "Number of npcs playing offense"); DEFINE_int32(defense_agents, 0, "Number of agents playing defense"); DEFINE_int32(defense_npcs, 0, "Number of npcs playing defense"); DEFINE_int32(offense_dummies, 0, "Number of dummy npcs playing offense"); DEFINE_int32(defense_dummies, 0, "Number of dummy npcs playing defense"); DEFINE_int32(defense_chasers, 0, "Number of chasers playing defense"); // Global Variables Shared Between Threads dqn::DQN* DQNS[12]; // Pointers to all DQNs. We will never have >12 players std::mutex MTX; double CalculateEpsilon(const int iter) { if (iter < FLAGS_explore) { return 1.0 - (1.0 - FLAGS_epsilon) * (static_cast<double>(iter) / FLAGS_explore); } else { return FLAGS_epsilon; } } std::string GetArg(std::string input, int indx) { std::istringstream ss(input); std::string token; int i = 0; while(std::getline(ss, token, ',')) { if (i++ == indx) { return token; } } return ""; } // Busy sleep while suggesting that other threads run for a small amount of time void little_sleep(std::chrono::microseconds us) { auto start = std::chrono::high_resolution_clock::now(); auto end = start + us; do { std::this_thread::yield(); } while (std::chrono::high_resolution_clock::now() < end); } /** * Play one episode and return the total score and number of steps */ std::tuple<double, int, status_t, double> PlayOneEpisode(HFOEnvironment& hfo, dqn::DQN& dqn, const double epsilon, const bool update, const int tid) { std::vector<dqn::Transition> episode; HFOGameState game(dqn.unum()); hfo.act(DASH, 0, 0); game.update(hfo); CHECK(!game.episode_over) << "Episode should not be over at beginning!"; std::deque<dqn::StateDataSp> past_states; while (!game.episode_over) { const std::vector<float>& current_state = hfo.getState(); CHECK_EQ(current_state.size(), dqn.state_size()); dqn::StateDataSp current_state_sp = std::make_shared<dqn::StateData>(dqn.state_size()); std::copy(current_state.begin(), current_state.end(), current_state_sp->begin()); past_states.push_back(current_state_sp); if (past_states.size() < dqn::kStateInputCount) { hfo.act(DASH, 0, 0); } else { while (past_states.size() > dqn::kStateInputCount) { past_states.pop_front(); } dqn::InputStates input_states; std::copy(past_states.begin(), past_states.end(), input_states.begin()); dqn::ActorOutput actor_output = dqn.SelectAction(input_states, epsilon); VLOG(1) << "Step " << game.steps; VLOG(1) << "Actor_output: " << dqn::PrintActorOutput(actor_output); Action action = dqn::GetAction(actor_output); VLOG(1) << "q_value: " << dqn.EvaluateAction(input_states, actor_output) << " Action: " << hfo::ActionToString(action.action); hfo.act(action.action, action.arg1, action.arg2); game.update(hfo); float reward = game.reward(); if (update) { const std::vector<float>& next_state = hfo.getState(); CHECK_EQ(next_state.size(), dqn.state_size()); dqn::StateDataSp next_state_sp = std::make_shared<dqn::StateData>(dqn.state_size()); std::copy(next_state.begin(), next_state.end(), next_state_sp->begin()); const auto transition = (game.status == IN_GAME) ? dqn::Transition(input_states, actor_output, reward, 0, next_state_sp): dqn::Transition(input_states, actor_output, reward, 0, boost::none); episode.push_back(transition); } } } if (update) { if (FLAGS_share_replay_memory) { MTX.lock(); } dqn.LabelTransitions(episode); dqn.AddTransitions(episode); if (FLAGS_share_replay_memory) { MTX.unlock(); } } return std::make_tuple(game.total_reward, game.steps, game.status, game.extrinsic_reward); } template <class T> std::pair<double,double> get_avg_std(std::vector<T> data) { double sum = 0; for (int i = 0; i < data.size(); ++i) { sum += data[i]; } double avg = sum / static_cast<double>(data.size()); double std = 0; for (int i = 0; i < data.size(); ++i) { std += (data[i] - avg) * (data[i] - avg); } std = sqrt(std / static_cast<double>(data.size() - 1)); return std::make_pair(avg, std); } double Evaluate(HFOEnvironment& hfo, dqn::DQN& dqn, int tid) { LOG(INFO) << "[Agent" << tid << "] Evaluating for " << FLAGS_repeat_games << " episodes with epsilon = " << FLAGS_evaluate_with_epsilon; std::vector<double> scores; std::vector<int> steps; std::vector<int> successful_trial_steps; int goals = 0; for (int i = 0; i < FLAGS_repeat_games; ++i) { auto result = PlayOneEpisode(hfo, dqn, FLAGS_evaluate_with_epsilon, false, tid); double trial_reward = std::get<0>(result); int trial_steps = std::get<1>(result); status_t trial_status = std::get<2>(result); scores.push_back(trial_reward); steps.push_back(trial_steps); if (trial_status == GOAL) { goals++; successful_trial_steps.push_back(trial_steps); } } std::pair<double, double> score_dist = get_avg_std(scores); std::pair<double, double> steps_dist = get_avg_std(steps); std::pair<double, double> succ_steps_dist = get_avg_std(successful_trial_steps); float goal_percent = goals / float(FLAGS_repeat_games); LOG(INFO) << "[Agent" << tid << "] Evaluation: " << "actor_iter = " << dqn.actor_iter() << ", avg_reward = " << score_dist.first << ", reward_std = " << score_dist.second << ", avg_steps = " << steps_dist.first << ", steps_std = " << steps_dist.second << ", success_steps = " << succ_steps_dist.first << ", success_std = " << succ_steps_dist.second << ", goal_perc = " << goal_percent; return goal_percent; } void KeepPlayingGames(int tid, std::string save_prefix, int port) { LOG(INFO) << "Thread " << tid << ", port=" << port << ", save_prefix=" << save_prefix; if (FLAGS_gpu) { caffe::Caffe::set_mode(caffe::Caffe::GPU); } else { caffe::Caffe::set_mode(caffe::Caffe::CPU); } // Look for a recent snapshot to resume std::string resume_path = FLAGS_resume.empty() ? save_prefix : FLAGS_resume; std::string last_actor_snapshot, last_critic_snapshot, last_memory_snapshot; dqn::FindLatestSnapshot(resume_path, last_actor_snapshot, last_critic_snapshot, last_memory_snapshot); LOG(INFO) << "Found Resumable(s): [" << resume_path << "] " << last_actor_snapshot << ", " << last_critic_snapshot << ", " << last_memory_snapshot; CHECK((FLAGS_critic_snapshot.empty() || FLAGS_critic_weights.empty()) && (FLAGS_actor_snapshot.empty() || FLAGS_actor_weights.empty())) << "Give a snapshot or weights but not both."; int num_players = FLAGS_offense_agents + FLAGS_offense_npcs + FLAGS_offense_dummies + FLAGS_defense_agents + FLAGS_defense_npcs + FLAGS_defense_dummies + FLAGS_defense_chasers; int num_features = NumStateFeatures(num_players); // Construct the solver caffe::SolverParameter actor_solver_param; caffe::SolverParameter critic_solver_param; caffe::NetParameter* actor_net_param = actor_solver_param.mutable_net_param(); std::string actor_net_filename = save_prefix + "_actor.prototxt"; if (boost::filesystem::is_regular_file(actor_net_filename)) { caffe::ReadProtoFromTextFileOrDie(actor_net_filename.c_str(), actor_net_param); } else { actor_net_param->CopyFrom(dqn::CreateActorNet(num_features)); WriteProtoToTextFile(*actor_net_param, actor_net_filename.c_str()); } caffe::NetParameter* critic_net_param = critic_solver_param.mutable_net_param(); std::string critic_net_filename = save_prefix + "_critic.prototxt"; if (boost::filesystem::is_regular_file(critic_net_filename)) { caffe::ReadProtoFromTextFileOrDie(critic_net_filename.c_str(), critic_net_param); } else { critic_net_param->CopyFrom(dqn::CreateCriticNet(num_features)); WriteProtoToTextFile(*critic_net_param, critic_net_filename.c_str()); } actor_solver_param.set_snapshot_prefix((save_prefix + "_actor").c_str()); critic_solver_param.set_snapshot_prefix((save_prefix + "_critic").c_str()); actor_solver_param.set_max_iter(FLAGS_max_iter); critic_solver_param.set_max_iter(FLAGS_max_iter); actor_solver_param.set_type(FLAGS_solver); critic_solver_param.set_type(FLAGS_solver); actor_solver_param.set_base_lr(FLAGS_actor_lr); critic_solver_param.set_base_lr(FLAGS_critic_lr); actor_solver_param.set_lr_policy(FLAGS_lr_policy); critic_solver_param.set_lr_policy(FLAGS_lr_policy); actor_solver_param.set_momentum(FLAGS_momentum); critic_solver_param.set_momentum(FLAGS_momentum); actor_solver_param.set_momentum2(FLAGS_momentum2); critic_solver_param.set_momentum2(FLAGS_momentum2); actor_solver_param.set_clip_gradients(FLAGS_clip_grad); critic_solver_param.set_clip_gradients(FLAGS_clip_grad); dqn::DQN* dqn = new dqn::DQN(actor_solver_param, critic_solver_param, save_prefix, num_features, tid); // Load actor/critic/memory. Try to load from resumables // first. Otherwise load from the args. if (!last_actor_snapshot.empty()) { dqn->RestoreActorSolver(last_actor_snapshot); } else if (!GetArg(FLAGS_actor_snapshot, tid).empty()) { dqn->RestoreActorSolver(GetArg(FLAGS_actor_snapshot, tid)); } else if (!GetArg(FLAGS_actor_weights, tid).empty()) { dqn->LoadActorWeights(GetArg(FLAGS_actor_weights, tid)); } if (!last_critic_snapshot.empty()) { dqn->RestoreCriticSolver(last_critic_snapshot); } else if (!GetArg(FLAGS_critic_snapshot, tid).empty()) { dqn->RestoreCriticSolver(GetArg(FLAGS_critic_snapshot, tid)); } else if (!GetArg(FLAGS_critic_weights, tid).empty()) { dqn->LoadCriticWeights(GetArg(FLAGS_critic_weights, 0)); } if (!last_memory_snapshot.empty()) { dqn->LoadReplayMemory(last_memory_snapshot); } else if (!GetArg(FLAGS_memory_snapshot, tid).empty()) { dqn->LoadReplayMemory(GetArg(FLAGS_memory_snapshot, tid)); } HFOEnvironment env; ConnectToServer(env, port); dqn->set_unum(env.getUnum()); // Wait for all DQNs to connect and be ready DQNS[tid] = dqn; int target_id = tid == 0 ? 1 : 0; bool all_dqns_ready = false; while (!all_dqns_ready) { little_sleep(std::chrono::microseconds(100)); all_dqns_ready = true; for (int i=0; i<FLAGS_offense_agents; ++i) { if (DQNS[i] == NULL) { all_dqns_ready = false; } } } // TID 0 is the Master and will do the sharing if (tid == 0) { if (FLAGS_share_actor_layers > 0 || FLAGS_share_critic_layers > 0) { for (int i=1; i<FLAGS_offense_agents; ++i) { dqn::DQN* teammate = DQNS[i]; CHECK_NOTNULL(teammate); dqn->ShareParameters(*teammate, FLAGS_share_actor_layers, FLAGS_share_critic_layers); } } if (FLAGS_share_replay_memory) { for (int i=1; i<FLAGS_offense_agents; ++i) { dqn::DQN* teammate = DQNS[i]; CHECK_NOTNULL(teammate); dqn->ShareReplayMemory(*teammate); } } } if (FLAGS_evaluate) { Evaluate(env, *dqn, tid); delete dqn; env.act(QUIT); env.step(); return; } if (FLAGS_benchmark) { PlayOneEpisode(env, *dqn, FLAGS_evaluate_with_epsilon, true, tid); dqn->Benchmark(1000); delete dqn; env.act(QUIT); env.step(); return; } if (FLAGS_learn_offline) { while (dqn->max_iter() < FLAGS_max_iter) { dqn->Update(); } dqn->Snapshot(); delete dqn; env.act(QUIT); env.step(); return; } int last_eval_iter = dqn->max_iter(); double best_score = std::numeric_limits<double>::min(); for (int episode = 0; dqn->max_iter() < FLAGS_max_iter; ++episode) { double epsilon = CalculateEpsilon(dqn->max_iter()); auto result = PlayOneEpisode(env, *dqn, epsilon, true, tid); LOG(INFO) << "[Agent" << tid <<"] Episode " << episode << " reward = " << std::get<0>(result); int steps = std::get<1>(result); int n_updates = int(steps * FLAGS_update_ratio); if (FLAGS_share_replay_memory) { MTX.lock(); } for (int i=0; i<n_updates; ++i) { dqn->Update(); } if (FLAGS_share_replay_memory) { MTX.unlock(); } if (dqn->actor_iter() >= last_eval_iter + FLAGS_evaluate_freq) { double avg_score = Evaluate(env, *dqn, tid); if (avg_score > best_score) { LOG(INFO) << "[Agent " << tid << "] New High Score: " << avg_score << ", actor_iter = " << dqn->actor_iter() << ", critic_iter = " << dqn->critic_iter(); best_score = avg_score; dqn::RemoveFilesMatchingRegexp(dqn->save_path() + "_HiScore.*"); std::string fname = dqn->save_path() + "_HiScore" + std::to_string(avg_score); dqn->Snapshot(fname, false, false); } last_eval_iter = dqn->actor_iter(); } } dqn->Snapshot(); delete dqn; env.act(QUIT); env.step(); } void SystemExecute(std::string cmd) { CHECK_EQ(system(cmd.c_str()), 0) << "Unable to execute command"; } int main(int argc, char** argv) { std::string usage(argv[0]); usage.append(" -[evaluate|save [path]]"); gflags::SetUsageMessage(usage); gflags::SetVersionString("0.1"); gflags::ParseCommandLineFlags(&argc, &argv, true); google::InitGoogleLogging(argv[0]); google::InstallFailureSignalHandler(); fLI::FLAGS_logbuflevel = -1; if (FLAGS_evaluate) { google::LogToStderr(); } if (FLAGS_save.empty() && !FLAGS_evaluate) { LOG(ERROR) << "Save path (or evaluate) required but not set."; LOG(ERROR) << "Usage: " << gflags::ProgramUsage(); exit(1); } path save_path(FLAGS_save); google::SetLogDestination(google::GLOG_INFO, (save_path.native() + "_INFO_").c_str()); google::SetLogDestination(google::GLOG_WARNING, (save_path.native() + "_WARNING_").c_str()); google::SetLogDestination(google::GLOG_ERROR, (save_path.native() + "_ERROR_").c_str()); google::SetLogDestination(google::GLOG_FATAL, (save_path.native() + "_FATAL_").c_str()); for (int i=0; i<12; ++i) { // Make the global pointers all null DQNS[i] = NULL; } srand(std::hash<std::string>()(save_path.native())); int port = rand() % 40000 + 20000; std::thread server_thread( StartHFOServer, port, FLAGS_offense_agents + FLAGS_offense_dummies, FLAGS_offense_npcs, FLAGS_defense_agents + FLAGS_defense_dummies + FLAGS_defense_chasers, FLAGS_defense_npcs); std::thread player_threads[10]; int threadNum = 0; for (int i=0; i<FLAGS_offense_agents; ++i) { std::string save_prefix = save_path.native() + "_agent" + std::to_string(i); player_threads[threadNum++] = std::thread(KeepPlayingGames, i, save_prefix, port); sleep(10); } for (int i=0; i<FLAGS_offense_dummies; ++i) { player_threads[threadNum++] = std::thread(StartDummyTeammate, port); } for (int i=0; i<FLAGS_defense_dummies; ++i) { player_threads[threadNum++] = std::thread(StartDummyGoalie, port); } for (int i=0; i<FLAGS_defense_chasers; ++i) { player_threads[threadNum++] = std::thread(StartChaser, port, "base_right", i == 0 ? 1 : 0); } for (int i = 0; i < threadNum; ++i) { player_threads[i].join(); } // StopHFOServer(); server_thread.join(); };
{ "content_hash": "463c2ed28d4eec2eb23704bdba7e896a", "timestamp": "", "source": "github", "line_count": 442, "max_line_length": 94, "avg_line_length": 41.12217194570136, "alnum_prop": 0.6381492077464789, "repo_name": "mhauskn/dqn-hfo", "id": "942036d6feaec88725bd7731365cb5023f267a81", "size": "18176", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/dqn_main.cpp", "mode": "33188", "license": "mit", "language": [ { "name": "C++", "bytes": "93542" }, { "name": "CMake", "bytes": "6810" }, { "name": "Shell", "bytes": "22861" } ], "symlink_target": "" }
package com.dremio.dac.resource; import static javax.ws.rs.core.Response.Status.UNAUTHORIZED; import javax.inject.Inject; import javax.servlet.http.HttpServletRequest; import javax.ws.rs.Consumes; import javax.ws.rs.DELETE; import javax.ws.rs.GET; import javax.ws.rs.HeaderParam; import javax.ws.rs.POST; import javax.ws.rs.Path; import javax.ws.rs.Produces; import javax.ws.rs.core.Context; import javax.ws.rs.core.HttpHeaders; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import javax.ws.rs.core.Response.Status; import com.dremio.common.util.DremioVersionInfo; import com.dremio.config.DremioConfig; import com.dremio.dac.annotations.RestResource; import com.dremio.dac.annotations.Secured; import com.dremio.dac.model.usergroup.SessionPermissions; import com.dremio.dac.model.usergroup.UserLogin; import com.dremio.dac.model.usergroup.UserLoginSession; import com.dremio.dac.model.usergroup.UserName; import com.dremio.dac.server.GenericErrorMessage; import com.dremio.dac.server.tokens.TokenUtils; import com.dremio.dac.service.catalog.CatalogServiceHelper; import com.dremio.dac.support.SupportService; import com.dremio.exec.server.SabotContext; import com.dremio.exec.server.options.ProjectOptionManager; import com.dremio.options.OptionManager; import com.dremio.service.namespace.NamespaceException; import com.dremio.service.namespace.NamespaceService; import com.dremio.service.tokens.TokenDetails; import com.dremio.service.tokens.TokenManager; import com.dremio.service.users.SystemUser; import com.dremio.service.users.User; import com.dremio.service.users.UserLoginException; import com.dremio.service.users.UserNotFoundException; import com.dremio.service.users.UserService; import com.google.common.base.Strings; /** * API for user log in and log out. */ @RestResource @Path("/login") @Produces(MediaType.APPLICATION_JSON) @Consumes(MediaType.APPLICATION_JSON) public class LogInLogOutResource { private static final org.slf4j.Logger logger = org.slf4j.LoggerFactory.getLogger(LogInLogOutResource.class); private final DremioConfig dremioConfig; private final SabotContext dContext; private final UserService userService; private final SupportService support; private final TokenManager tokenManager; private final OptionManager projectOptionManager; @Inject public LogInLogOutResource( DremioConfig dremioConfig, SabotContext dContext, UserService userService, SupportService support, TokenManager tokenManager, ProjectOptionManager projectOptionManager ) { this.dremioConfig = dremioConfig; this.dContext = dContext; this.userService = userService; this.support = support; this.tokenManager = tokenManager; this.projectOptionManager = projectOptionManager; } @POST public Response login(UserLogin userLogin, @Context HttpServletRequest request) { try { if (userLogin == null || Strings.isNullOrEmpty(userLogin.getUserName()) || Strings.isNullOrEmpty(userLogin.getPassword())) { throw new IllegalArgumentException("user name or password cannot be null or empty"); } final UserName userName = new UserName(userLogin.getUserName()); // Authenticate the user using the credentials provided userService.authenticate(userName.getName(), userLogin.getPassword()); final User userConfig = userService.getUser(userName.getName()); final String clientAddress = request.getRemoteAddr(); // Get a token for this session final TokenDetails tokenDetails = tokenManager.createToken(userLogin.getUserName(), clientAddress); // Make sure the logged-in user has a home space. If not create one. try { final NamespaceService ns = dContext.getNamespaceService(SystemUser.SYSTEM_USERNAME); CatalogServiceHelper.ensureUserHasHomespace(ns, userConfig.getUserName()); } catch (NamespaceException ex) { logger.error("Failed to make sure the user has home space setup.", ex); return Response.status(Status.INTERNAL_SERVER_ERROR).entity(new GenericErrorMessage(ex.getMessage())).build(); } SessionPermissions perms = new SessionPermissions( projectOptionManager.getOption(SupportService.USERS_UPLOAD), projectOptionManager.getOption(SupportService.USERS_DOWNLOAD), projectOptionManager.getOption(SupportService.USERS_EMAIL), projectOptionManager.getOption(SupportService.USERS_CHAT), true, true, true, true, true, true, true, true, true, true ); return Response.ok( new UserLoginSession( tokenDetails.token, userLogin.getUserName(), userConfig.getFirstName(), userConfig.getLastName(), tokenDetails.expiresAt, userConfig.getEmail(), userConfig.getUID().getId(), true, userConfig.getCreatedAt(), support.getClusterId().getIdentity(), support.getClusterId().getCreated(), DremioVersionInfo.getVersion(), perms ) ).build(); } catch (IllegalArgumentException | UserLoginException | UserNotFoundException e) { logger.error("Encountered an issue while authenticating {}", userLogin.getUserName(), e); return Response.status(UNAUTHORIZED).entity(new GenericErrorMessage(e.getMessage())).build(); } } @DELETE public void logout(@HeaderParam(HttpHeaders.AUTHORIZATION) String authHeader) { tokenManager.invalidateToken(TokenUtils.getToken(authHeader)); } @GET @Secured /** * This method serves for following purposes: * 1) Check if current user is still authenticated * 2) If any user exists. See {@link com.dremio.dac.server.NoUserFilter} */ public boolean isUserAuthorized() { return true; } }
{ "content_hash": "88f699af99b2ac8de7116b5c3d193d8e", "timestamp": "", "source": "github", "line_count": 162, "max_line_length": 130, "avg_line_length": 36.629629629629626, "alnum_prop": 0.731041456016178, "repo_name": "dremio/dremio-oss", "id": "5c6006bb9d3bdcfde66d2c4c171d00e3cfad4206", "size": "6544", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "dac/backend/src/main/java/com/dremio/dac/resource/LogInLogOutResource.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "47376" }, { "name": "Dockerfile", "bytes": "1668" }, { "name": "FreeMarker", "bytes": "132156" }, { "name": "GAP", "bytes": "15936" }, { "name": "HTML", "bytes": "6544" }, { "name": "Java", "bytes": "39679012" }, { "name": "JavaScript", "bytes": "5439822" }, { "name": "Less", "bytes": "547002" }, { "name": "SCSS", "bytes": "95688" }, { "name": "Shell", "bytes": "16063" }, { "name": "TypeScript", "bytes": "887739" } ], "symlink_target": "" }
namespace Hotcakes.Shipping.FedEx { public enum DropOffType { REGULARPICKUP = 1, REQUESTCOURIER = 2, DROPBOX = 3, BUSINESSSERVICECENTER = 4, STATION = 5 } }
{ "content_hash": "2178a69f963bd0ff8ac62b18ed3da167", "timestamp": "", "source": "github", "line_count": 11, "max_line_length": 34, "avg_line_length": 18.90909090909091, "alnum_prop": 0.5673076923076923, "repo_name": "HotcakesCommerce/core", "id": "09c3e29cad4f06f03a163280cc7befaa55f9a931", "size": "1470", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "Libraries/Hotcakes.Shipping.FedEx/DropOffType.cs", "mode": "33188", "license": "mit", "language": [ { "name": "ASP", "bytes": "2267142" }, { "name": "Batchfile", "bytes": "373" }, { "name": "C#", "bytes": "11194618" }, { "name": "CSS", "bytes": "1952419" }, { "name": "HTML", "bytes": "873593" }, { "name": "JavaScript", "bytes": "4896110" }, { "name": "Smalltalk", "bytes": "2410" }, { "name": "Visual Basic", "bytes": "16681" }, { "name": "XSLT", "bytes": "10409" } ], "symlink_target": "" }
<?php namespace Structr\Tree\Scalar; use Structr\Tree\Base\Node; class AnyNode extends Node { }
{ "content_hash": "fb04f2b2d88db2dd9d298fa25dab701a", "timestamp": "", "source": "github", "line_count": 10, "max_line_length": 30, "avg_line_length": 10, "alnum_prop": 0.74, "repo_name": "Yellitech/Structr", "id": "b77425e42885c4464e3523e4d5347a1c2ace1af0", "size": "270", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/Structr/Tree/Scalar/AnyNode.php", "mode": "33261", "license": "mit", "language": [ { "name": "PHP", "bytes": "98828" } ], "symlink_target": "" }
using System; using System.Collections; using Server.Network; using Server.Items; using Server.Targeting; using Server.Mobiles; namespace Server.Spells.Necromancy { public class VengefulSpiritSpell : NecromancerSpell { private static SpellInfo m_Info = new SpellInfo( "Vengeful Spirit", "Kal Xen Bal Beh", 203, 9031, Reagent.BatWing, Reagent.GraveDust, Reagent.PigIron ); public override TimeSpan CastDelayBase { get { return TimeSpan.FromSeconds( 2.0 ); } } public override double RequiredSkill{ get{ return 80.0; } } public override int RequiredMana{ get{ return 41; } } public VengefulSpiritSpell( Mobile caster, Item scroll ) : base( caster, scroll, m_Info ) { } public override void OnCast() { Caster.Target = new InternalTarget( this ); } public override bool CheckCast() { if ( !base.CheckCast() ) return false; if ( (Caster.Followers + 3) > Caster.FollowersMax ) { Caster.SendLocalizedMessage( 1049645 ); // You have too many followers to summon that creature. return false; } return true; } public void Target( Mobile m ) { if ( Caster == m ) { Caster.SendLocalizedMessage( 1061832 ); // You cannot exact vengeance on yourself. } else if ( CheckHSequence( m ) ) { SpellHelper.Turn( Caster, m ); /* Summons a Revenant which haunts the target until either the target or the Revenant is dead. * Revenants have the ability to track down their targets wherever they may travel. * A Revenant's strength is determined by the Necromancy and Spirit Speak skills of the Caster. * The effect lasts for ((Spirit Speak skill level * 80) / 120) + 10 seconds. */ TimeSpan duration = TimeSpan.FromSeconds( ((GetDamageSkill( Caster ) * 80) / 120) + 10 ); Revenant rev = new Revenant( Caster, m, duration ); if ( BaseCreature.Summon( rev, false, Caster, m.Location, 0x81, TimeSpan.FromSeconds( duration.TotalSeconds + 2.0 ) ) ) rev.FixedParticles( 0x373A, 1, 15, 9909, EffectLayer.Waist ); } FinishSequence(); } private class InternalTarget : Target { private VengefulSpiritSpell m_Owner; public InternalTarget( VengefulSpiritSpell owner ) : base( Core.ML ? 10 : 12, false, TargetFlags.Harmful ) { m_Owner = owner; } protected override void OnTarget( Mobile from, object o ) { if ( o is Mobile ) m_Owner.Target( (Mobile) o ); } protected override void OnTargetFinish( Mobile from ) { m_Owner.FinishSequence(); } } } }
{ "content_hash": "de1735e44916ab82003560be148c3b5a", "timestamp": "", "source": "github", "line_count": 97, "max_line_length": 123, "avg_line_length": 26.195876288659793, "alnum_prop": 0.6745375836284927, "repo_name": "ggobbe/vivre-uo", "id": "f59b855b731ff59913841613f789afebc9596efe", "size": "2541", "binary": false, "copies": "8", "ref": "refs/heads/master", "path": "Scripts/Spells/Necromancy/VengefulSpirit.cs", "mode": "33188", "license": "bsd-2-clause", "language": [ { "name": "C#", "bytes": "19852349" }, { "name": "CSS", "bytes": "699" }, { "name": "HTML", "bytes": "3008" } ], "symlink_target": "" }
/// <reference path="../../includes.ts"/> /// <reference path="kubernetesHelpers.ts"/> /// <reference path="kubernetesPlugin.ts"/> module Kubernetes { export var BuildConfigEditController = _module.controller("Kubernetes.BuildConfigEditController", ($scope, $element, KubernetesModel:Kubernetes.KubernetesModelService, KubernetesState, KubernetesSchema, $templateCache:ng.ITemplateCacheService, $location:ng.ILocationService, $routeParams, $http, $timeout, KubernetesApiURL, K8SClientFactory, SchemaRegistry:HawtioForms.SchemaRegistry) => { $scope.kubernetes = KubernetesState; $scope.model = KubernetesModel; $scope.id = $routeParams["project"] || $routeParams["id"]; $scope.schema = KubernetesSchema; var mode = $scope.$eval('mode') || 'edit'; log.debug("Mode: ", mode); var specConfig = SchemaRegistry.getSchema('io.fabric8.openshift.api.model.BuildConfigSpec'); var gitBuildSource = SchemaRegistry.getSchema('io.fabric8.openshift.api.model.GitBuildSource'); var buildSource = SchemaRegistry.getSchema('io.fabric8.openshift.api.model.BuildSource'); var buildOutput = SchemaRegistry.getSchema('io.fabric8.openshift.api.model.BuildOutput'); var resources = SchemaRegistry.getSchema('io.fabric8.kubernetes.api.model.ResourceRequirements'); var revision = SchemaRegistry.getSchema('io.fabric8.openshift.api.model.SourceRevision'); var strategy = SchemaRegistry.getSchema('io.fabric8.openshift.api.model.BuildStrategy'); var customStrategy = SchemaRegistry.getSchema('io.fabric8.openshift.api.model.CustomBuildStrategy'); var buildTriggerPolicy = SchemaRegistry.getSchema('io.fabric8.openshift.api.model.BuildTriggerPolicy'); var getSecrets = () => { return $scope.secrets; }; var secretSchemaType = "fabric8_SecretReference"; var secretSchemaRef = "#/definitions/" + secretSchemaType; var secretSchemaJavaType = "io.fabric8.console.SecretReference"; var secretNameElement = <HawtioForms.FormElement> { "type": "string", "enum": getSecrets, required: true }; var secretSchema: HawtioForms.FormConfiguration = <any> { "type": "object", properties: { "name": secretNameElement }, javaType: secretSchemaJavaType }; SchemaRegistry.addSchema(secretSchemaType, secretSchema); // lets switch to the new secrets types: var sourceSecretProperty = Core.pathGet(buildSource, ["properties", "sourceSecret"]); angular.forEach([ Core.pathGet(customStrategy, ["properties", "pullSecret"]), sourceSecretProperty, ], (schemaType) => { if (schemaType) { schemaType["type"] = secretSchemaType; schemaType["$ref"] = secretSchemaRef; schemaType["javaType"] = secretSchemaJavaType; } }); // lets try make the buildSource's sourceSecret mandatory //schemaSetRequired(customStrategy, 'pullSecret'); schemaSetRequired(buildSource, 'sourceSecret'); if (sourceSecretProperty) { Core.pathSet(sourceSecretProperty, ['properties', 'required'], true); Core.pathSet(sourceSecretProperty, ['properties', 'input-attributes', 'required'], true); } $scope.customStrategy = customStrategy; $scope.buildSource = buildSource; $scope.secrets = []; // $scope.config = KubernetesSchema.definitions.os_build_BuildConfig; //$scope.specConfig = KubernetesSchema.definitions.os_build_BuildConfigSpec; // specConfig.style = HawtioForms.FormStyle.STANDARD; specConfig.properties['triggers']['label-attributes'] = { style: 'display: none;' }; gitBuildSource.controls = ['uri', 'ref', '*']; buildSource.properties['type'].type = 'hidden'; buildSource.properties['type']['default'] = 'Git'; buildSource.controls = ['git', 'contextDir', 'sourceSecret', '*']; gitBuildSource['hideLegend'] = true; buildSource['hideLegend'] = true; buildOutput['hideLegend'] = true; resources['hideLegend'] = true; revision['hideLegend'] = true; strategy['hideLegend'] = true; strategy.controls = ['type', '*']; strategy.properties['type'] = { type: 'text', enum: [{ 'value': 'Custom', 'label': 'Custom' }, { 'value': 'Docker', 'label': 'Docker' }, { 'value': 'Source', 'label': 'Source' }] }; customStrategy['control-group-attributes'] = { 'ng-show': "entity.type == 'Custom'" }; strategy.properties['dockerStrategy']['control-group-attributes'] = { 'ng-show': "entity.type == 'Docker'" }; strategy.properties['sourceStrategy']['control-group-attributes'] = { 'ng-show': "entity.type == 'Source'" }; buildTriggerPolicy.controls = ['type', '*']; buildTriggerPolicy.properties['type'] = { type: 'string', enum: [{ 'value': 'Github', 'label': 'Github' }, { 'value': 'ImageChange', 'label': 'Image Change' }, { 'value': 'Generic', 'label': 'Generic' }] }; buildTriggerPolicy.properties['generic']['control-group-attributes'] = { 'ng-show': "entity.type == 'Generic'" }; buildTriggerPolicy.properties['github']['control-group-attributes'] = { 'ng-show': "entity.type == 'Github'" }; buildTriggerPolicy.properties['imageChange']['control-group-attributes'] = { 'ng-show': "entity.type == 'ImageChange'" }; // re-arranging the controls //specConfig.controls = ['source', '*']; // tabs specConfig.tabs = { "Source": ["source"], "Revision": ["revision"], "Output": ["output"], "Resources": ["resources"], "Strategy": ["strategy"], "Triggers": ["triggers"], "Service Account": ["serviceAccount"] }; /* * wizard, needs an 'onFinish' function in the scope specConfig.wizard = <any>{ pages: { Source: { controls: ["source"] }, Revision: { controls: ["revision"] }, Output: { controls: ["output"] }, Resources: { controls: ["resources"] }, Strategy: { controls: ["strategy"] }, Triggers: { controls: ["triggers"] }, "Service Account": { controls: ["serviceAccount"] } } }; */ $scope.entity = { "apiVersion": "v1", "kind": "BuildConfig", "metadata": { "name": "", "labels": { } }, "spec": { "source": { "type": "Git" }, "strategy": { "type": "Custom", "customStrategy": { "from": { "kind": "DockerImage", "name": "fabric8/openshift-s2i-jenkins-trigger" }, "env": [ { "name": "BASE_URI", "value": jenkinsUrl }, { "name": "JOB_NAME", "value": jobName } ] } } } }; $scope.$watch('entity.spec.source.git.uri', (val) => { if (!val) { return; } var lastBit = val.match(/[^\/]+$/)[0]; if (lastBit) { var name = lastBit.replace(/\.git$/, ''); log.debug("name: ", name); if (!Core.isBlank(name) && Core.isBlank(Core.pathGet($scope.entity, ['metadata', 'name']))) { Core.pathSet($scope.entity, ['metadata', 'name'], name); } } }); Kubernetes.initShared($scope, $location, $http, $timeout, $routeParams, KubernetesModel, KubernetesState, KubernetesApiURL); $scope.breadcrumbConfig = Developer.createProjectSettingsBreadcrumbs($scope.projectId); $scope.subTabConfig = Developer.createProjectSubNavBars($scope.projectId); $scope.tabs = Developer.createProjectSettingsSubNavBars($scope.projectId); watch($scope, $element, "secrets", $scope.namespace, onSecrets); $scope.buildConfigClient = K8SClientFactory.create("buildconfigs", $scope.namespace); $element.on('$destroy', () => { $scope.$destroy(); }); $scope.$on('$destroy', () => { K8SClientFactory.destroy($scope.buildConfigClient); }); /* $scope.$on('kubernetesModelUpdated', function () { updateData(); }); */ $scope.$on('$routeUpdate', ($event) => { updateData(); }); $scope.save = () => { log.info("Saving!"); var entity = $scope.entity; var spec = (entity || {}).spec || {}; // TODO update the jenkins job name! // lets delete lots of cruft var strategy = spec.strategy || {}; delete strategy["dockerStrategy"]; delete strategy["sourceStrategy"]; delete spec["revision"]; delete spec["output"]; delete spec["resources"]; var strategyPullSecretName = Core.pathGet(spec, ["strategy", "customStrategy", "pullSecret", "name"]); var sourceSecretName = Core.pathGet(spec, ["source", "sourceSecret", "name"]); log.info("sourceSecretName: " + sourceSecretName); log.info("strategyPullSecretName: " + strategyPullSecretName); if (!strategyPullSecretName && sourceSecretName) { Core.pathSet(spec, ["strategy", "customStrategy", "pullSecret", "name"], sourceSecretName); } /* // TODO hack until the put deals with updates var metadata = entity.metadata; if (metadata) { delete metadata["resourceVersion"]; } */ log.info(angular.toJson(entity, true)); $scope.buildConfigClient.put(entity, (obj) => { log.info("build config created!"); var link = Developer.projectSecretsLink($scope.namespace, getName(entity)); if (link) { Kubernetes.goToPath($location, link); } else { log.warn("Could not find the edit pipeline link!"); } }) }; updateData(); var jenkinsUrl = Developer.jenkinsLink(); var jobName = ""; function updateData() { $scope.item = null; if ($scope.id) { var url = buildConfigRestUrl($scope.id); $http.get(url). success(function (data, status, headers, config) { if (data) { $scope.entity = data; var buildConfig = angular.copy(data); var sortedBuilds = null; Kubernetes.enrichBuildConfig(buildConfig, sortedBuilds); $scope.buildConfig = buildConfig; } $scope.spec = ($scope.entity || {}).spec || {}; $scope.fetched = true; // lets update the tabs $scope.subTabConfig = Developer.createProjectSubNavBars($scope.projectId, null, $scope); Core.$apply($scope); }). error(function (data, status, headers, config) { log.warn("Failed to load " + url + " " + data + " " + status); }); } else { $scope.fetched = true; $scope.spec = $scope.entity.spec; Core.$apply($scope); } } function onSecrets(secrets) { var array = []; angular.forEach(secrets, (secret) => { var name = getName(secret); if (name) { array.push({ label: name, value: name, "attributes": { "title": name }, $secret: secret }); } }); $scope.secrets = _.sortBy(array, "label"); var specSourceSecretNamePath = ['spec', 'source', 'sourceSecret', 'name']; if ($scope.entity && !Core.pathGet($scope.entity, specSourceSecretNamePath)) { var defaultSecretName = findDefaultImportSecretName(secrets); Core.pathSet($scope.entity, specSourceSecretNamePath, defaultSecretName); } } function findDefaultImportSecretName(secrets) { var answer = null; angular.forEach(secrets, (secret) => { var name = getName(secret); if (!answer && name && name.startsWith("jenkins-login")) { answer = name; } }); if (!answer) { angular.forEach(secrets, (secret) => { var name = getName(secret); if (!answer && name && name.startsWith("jenkins-token")) { answer = name; } }); } return answer; } switch (mode) { case 'create': delete specConfig.tabs; _.forIn(buildSource.properties, (property:any, name:string) => { if (name !== 'git') { log.info("Hiding property: ", name); property.hidden = true; } }); _.forIn(gitBuildSource.properties, (property:any, name:string) => { if (name !== 'uri') { log.info("Hiding property: ", name); property.hidden = true; } else { property.label = "Git URL"; property['input-attributes'] = { 'required': true } } }); _.forIn(specConfig.properties, (property:any, name:string) => { if (name !== 'source') { log.info("Hiding property: ", name); property.hidden = true; } }); break; case 'edit': default: } $scope.specConfig = specConfig; }); }
{ "content_hash": "4c6df4b732fc37dc09973f3e42132e42", "timestamp": "", "source": "github", "line_count": 428, "max_line_length": 391, "avg_line_length": 34.768691588785046, "alnum_prop": 0.5117263624756401, "repo_name": "hawtio/hawtio-kubernetes", "id": "fd799ccea487fe9cca4ea28bb328b5040f292e18", "size": "14881", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "plugins/kubernetes/ts/buildConfigEdit.ts", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "13724" }, { "name": "HTML", "bytes": "188298" }, { "name": "JavaScript", "bytes": "11026" }, { "name": "TypeScript", "bytes": "706055" } ], "symlink_target": "" }
require "rails_helper" describe "fields/url/_index", type: :view do let(:product) do build(:product, image_url: "https://thoughtbot.com/image.jpg") end it "renders url" do url = instance_double( "Administrate::Field::Url", data: product.image_url, html_options: {}, ) render( partial: "fields/url/index", locals: { field: url, namespace: :admin }, ) expect(rendered).to have_css( %{a[href="#{product.image_url}"]}, text: product.image_url, ) end it "renders html options" do url = instance_double( "Administrate::Field::Url", data: product.image_url, html_options: { referrerpolicy: "no-referrer" }, ) render( partial: "fields/url/show", locals: { field: url, namespace: :admin }, ) expect(rendered).to have_css( %{a[href="#{product.image_url}"][referrerpolicy="no-referrer"]}, text: product.image_url, ) end end
{ "content_hash": "e7010b3fd3ad1ea6b066357f8b06ce39", "timestamp": "", "source": "github", "line_count": 43, "max_line_length": 70, "avg_line_length": 22.511627906976745, "alnum_prop": 0.5898760330578512, "repo_name": "thoughtbot/administrate", "id": "e5719ae2159875abdb19301e744473ecc128f0c3", "size": "968", "binary": false, "copies": "1", "ref": "refs/heads/main", "path": "spec/administrate/views/fields/url/_index_spec.rb", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "686" }, { "name": "HTML", "bytes": "59733" }, { "name": "JavaScript", "bytes": "1719" }, { "name": "Procfile", "bytes": "57" }, { "name": "Ruby", "bytes": "344059" }, { "name": "SCSS", "bytes": "21308" }, { "name": "Shell", "bytes": "2200" } ], "symlink_target": "" }
#define NPY_NO_DEPRECATED_API NPY_API_VERSION #define _MULTIARRAYMODULE #define PY_SSIZE_T_CLEAN #include <Python.h> #include "numpy/arrayobject.h" #include "numpyos.h" #include "npy_config.h" #include "npy_pycompat.h" #include "common.h" #include "numpy/arrayscalars.h" #include "_datetime.h" #include "datetime_strings.h" #include "convert_datatype.h" #include "array_method.h" #include "dtypemeta.h" #include "usertypes.h" #include "dtype_transfer.h" #include "lowlevel_strided_loops.h" #include <datetime.h> #include <time.h> /* * Computes the python `ret, d = divmod(d, unit)`. * * Note that GCC is smart enough at -O2 to eliminate the `if(*d < 0)` branch * for subsequent calls to this command - it is able to deduce that `*d >= 0`. */ static inline npy_int64 extract_unit_64(npy_int64 *d, npy_int64 unit) { assert(unit > 0); npy_int64 div = *d / unit; npy_int64 mod = *d % unit; if (mod < 0) { mod += unit; div -= 1; } assert(mod >= 0); *d = mod; return div; } static inline npy_int32 extract_unit_32(npy_int32 *d, npy_int32 unit) { assert(unit > 0); npy_int32 div = *d / unit; npy_int32 mod = *d % unit; if (mod < 0) { mod += unit; div -= 1; } assert(mod >= 0); *d = mod; return div; } /* * Imports the PyDateTime functions so we can create these objects. * This is called during module initialization */ NPY_NO_EXPORT void numpy_pydatetime_import(void) { PyDateTime_IMPORT; } /* Exported as DATETIMEUNITS in multiarraymodule.c */ NPY_NO_EXPORT char const *_datetime_strings[NPY_DATETIME_NUMUNITS] = { "Y", "M", "W", "<invalid>", "D", "h", "m", "s", "ms", "us", "ns", "ps", "fs", "as", "generic" }; /* Days per month, regular year and leap year */ NPY_NO_EXPORT int _days_per_month_table[2][12] = { { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 }, { 31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 } }; /* * Returns 1 if the given year is a leap year, 0 otherwise. */ NPY_NO_EXPORT int is_leapyear(npy_int64 year) { return (year & 0x3) == 0 && /* year % 4 == 0 */ ((year % 100) != 0 || (year % 400) == 0); } /* * Calculates the days offset from the 1970 epoch. */ NPY_NO_EXPORT npy_int64 get_datetimestruct_days(const npy_datetimestruct *dts) { int i, month; npy_int64 year, days = 0; int *month_lengths; year = dts->year - 1970; days = year * 365; /* Adjust for leap years */ if (days >= 0) { /* * 1968 is the closest leap year before 1970. * Exclude the current year, so add 1. */ year += 1; /* Add one day for each 4 years */ days += year / 4; /* 1900 is the closest previous year divisible by 100 */ year += 68; /* Subtract one day for each 100 years */ days -= year / 100; /* 1600 is the closest previous year divisible by 400 */ year += 300; /* Add one day for each 400 years */ days += year / 400; } else { /* * 1972 is the closest later year after 1970. * Include the current year, so subtract 2. */ year -= 2; /* Subtract one day for each 4 years */ days += year / 4; /* 2000 is the closest later year divisible by 100 */ year -= 28; /* Add one day for each 100 years */ days -= year / 100; /* 2000 is also the closest later year divisible by 400 */ /* Subtract one day for each 400 years */ days += year / 400; } month_lengths = _days_per_month_table[is_leapyear(dts->year)]; month = dts->month - 1; /* Add the months */ for (i = 0; i < month; ++i) { days += month_lengths[i]; } /* Add the days */ days += dts->day - 1; return days; } /* * Calculates the minutes offset from the 1970 epoch. */ NPY_NO_EXPORT npy_int64 get_datetimestruct_minutes(const npy_datetimestruct *dts) { npy_int64 days = get_datetimestruct_days(dts) * 24 * 60; days += dts->hour * 60; days += dts->min; return days; } /* * Modifies '*days_' to be the day offset within the year, * and returns the year. */ static npy_int64 days_to_yearsdays(npy_int64 *days_) { const npy_int64 days_per_400years = (400*365 + 100 - 4 + 1); /* Adjust so it's relative to the year 2000 (divisible by 400) */ npy_int64 days = (*days_) - (365*30 + 7); npy_int64 year; /* Break down the 400 year cycle to get the year and day within the year */ year = 400 * extract_unit_64(&days, days_per_400years); /* Work out the year/day within the 400 year cycle */ if (days >= 366) { year += 100 * ((days-1) / (100*365 + 25 - 1)); days = (days-1) % (100*365 + 25 - 1); if (days >= 365) { year += 4 * ((days+1) / (4*365 + 1)); days = (days+1) % (4*365 + 1); if (days >= 366) { year += (days-1) / 365; days = (days-1) % 365; } } } *days_ = days; return year + 2000; } /* Extracts the month number from a 'datetime64[D]' value */ NPY_NO_EXPORT int days_to_month_number(npy_datetime days) { npy_int64 year; int *month_lengths, i; year = days_to_yearsdays(&days); month_lengths = _days_per_month_table[is_leapyear(year)]; for (i = 0; i < 12; ++i) { if (days < month_lengths[i]) { return i + 1; } else { days -= month_lengths[i]; } } /* Should never get here */ return 1; } /* * Fills in the year, month, day in 'dts' based on the days * offset from 1970. */ static void set_datetimestruct_days(npy_int64 days, npy_datetimestruct *dts) { int *month_lengths, i; dts->year = days_to_yearsdays(&days); month_lengths = _days_per_month_table[is_leapyear(dts->year)]; for (i = 0; i < 12; ++i) { if (days < month_lengths[i]) { dts->month = i + 1; dts->day = (int)days + 1; return; } else { days -= month_lengths[i]; } } } /* * Converts a datetime from a datetimestruct to a datetime based * on some metadata. The date is assumed to be valid. * * TODO: If meta->num is really big, there could be overflow * * Returns 0 on success, -1 on failure. */ NPY_NO_EXPORT int convert_datetimestruct_to_datetime(PyArray_DatetimeMetaData *meta, const npy_datetimestruct *dts, npy_datetime *out) { npy_datetime ret; NPY_DATETIMEUNIT base = meta->base; /* If the datetimestruct is NaT, return NaT */ if (dts->year == NPY_DATETIME_NAT) { *out = NPY_DATETIME_NAT; return 0; } /* Cannot instantiate a datetime with generic units */ if (meta->base == NPY_FR_GENERIC) { PyErr_SetString(PyExc_ValueError, "Cannot create a NumPy datetime other than NaT " "with generic units"); return -1; } if (base == NPY_FR_Y) { /* Truncate to the year */ ret = dts->year - 1970; } else if (base == NPY_FR_M) { /* Truncate to the month */ ret = 12 * (dts->year - 1970) + (dts->month - 1); } else { /* Otherwise calculate the number of days to start */ npy_int64 days = get_datetimestruct_days(dts); switch (base) { case NPY_FR_W: /* Truncate to weeks */ if (days >= 0) { ret = days / 7; } else { ret = (days - 6) / 7; } break; case NPY_FR_D: ret = days; break; case NPY_FR_h: ret = days * 24 + dts->hour; break; case NPY_FR_m: ret = (days * 24 + dts->hour) * 60 + dts->min; break; case NPY_FR_s: ret = ((days * 24 + dts->hour) * 60 + dts->min) * 60 + dts->sec; break; case NPY_FR_ms: ret = (((days * 24 + dts->hour) * 60 + dts->min) * 60 + dts->sec) * 1000 + dts->us / 1000; break; case NPY_FR_us: ret = (((days * 24 + dts->hour) * 60 + dts->min) * 60 + dts->sec) * 1000000 + dts->us; break; case NPY_FR_ns: ret = ((((days * 24 + dts->hour) * 60 + dts->min) * 60 + dts->sec) * 1000000 + dts->us) * 1000 + dts->ps / 1000; break; case NPY_FR_ps: ret = ((((days * 24 + dts->hour) * 60 + dts->min) * 60 + dts->sec) * 1000000 + dts->us) * 1000000 + dts->ps; break; case NPY_FR_fs: /* only 2.6 hours */ ret = (((((days * 24 + dts->hour) * 60 + dts->min) * 60 + dts->sec) * 1000000 + dts->us) * 1000000 + dts->ps) * 1000 + dts->as / 1000; break; case NPY_FR_as: /* only 9.2 secs */ ret = (((((days * 24 + dts->hour) * 60 + dts->min) * 60 + dts->sec) * 1000000 + dts->us) * 1000000 + dts->ps) * 1000000 + dts->as; break; default: /* Something got corrupted */ PyErr_SetString(PyExc_ValueError, "NumPy datetime metadata with corrupt unit value"); return -1; } } /* Divide by the multiplier */ if (meta->num > 1) { if (ret >= 0) { ret /= meta->num; } else { ret = (ret - meta->num + 1) / meta->num; } } *out = ret; return 0; } /*NUMPY_API * Create a datetime value from a filled datetime struct and resolution unit. * * TO BE REMOVED - NOT USED INTERNALLY. */ NPY_NO_EXPORT npy_datetime PyArray_DatetimeStructToDatetime( NPY_DATETIMEUNIT NPY_UNUSED(fr), npy_datetimestruct *NPY_UNUSED(d)) { PyErr_SetString(PyExc_RuntimeError, "The NumPy PyArray_DatetimeStructToDatetime function has " "been removed"); return -1; } /*NUMPY_API * Create a timedelta value from a filled timedelta struct and resolution unit. * * TO BE REMOVED - NOT USED INTERNALLY. */ NPY_NO_EXPORT npy_datetime PyArray_TimedeltaStructToTimedelta( NPY_DATETIMEUNIT NPY_UNUSED(fr), npy_timedeltastruct *NPY_UNUSED(d)) { PyErr_SetString(PyExc_RuntimeError, "The NumPy PyArray_TimedeltaStructToTimedelta function has " "been removed"); return -1; } /* * Converts a datetime based on the given metadata into a datetimestruct */ NPY_NO_EXPORT int convert_datetime_to_datetimestruct(PyArray_DatetimeMetaData *meta, npy_datetime dt, npy_datetimestruct *out) { npy_int64 days; /* Initialize the output to all zeros */ memset(out, 0, sizeof(npy_datetimestruct)); out->year = 1970; out->month = 1; out->day = 1; /* NaT is signaled in the year */ if (dt == NPY_DATETIME_NAT) { out->year = NPY_DATETIME_NAT; return 0; } /* Datetimes can't be in generic units */ if (meta->base == NPY_FR_GENERIC) { PyErr_SetString(PyExc_ValueError, "Cannot convert a NumPy datetime value other than NaT " "with generic units"); return -1; } /* TODO: Change to a mechanism that avoids the potential overflow */ dt *= meta->num; /* * Note that care must be taken with the / and % operators * for negative values. */ switch (meta->base) { case NPY_FR_Y: out->year = 1970 + dt; break; case NPY_FR_M: out->year = 1970 + extract_unit_64(&dt, 12); out->month = dt + 1; break; case NPY_FR_W: /* A week is 7 days */ set_datetimestruct_days(dt * 7, out); break; case NPY_FR_D: set_datetimestruct_days(dt, out); break; case NPY_FR_h: days = extract_unit_64(&dt, 24LL); set_datetimestruct_days(days, out); out->hour = (int)dt; break; case NPY_FR_m: days = extract_unit_64(&dt, 60LL*24); set_datetimestruct_days(days, out); out->hour = (int)extract_unit_64(&dt, 60LL); out->min = (int)dt; break; case NPY_FR_s: days = extract_unit_64(&dt, 60LL*60*24); set_datetimestruct_days(days, out); out->hour = (int)extract_unit_64(&dt, 60LL*60); out->min = (int)extract_unit_64(&dt, 60LL); out->sec = (int)dt; break; case NPY_FR_ms: days = extract_unit_64(&dt, 1000LL*60*60*24); set_datetimestruct_days(days, out); out->hour = (int)extract_unit_64(&dt, 1000LL*60*60); out->min = (int)extract_unit_64(&dt, 1000LL*60); out->sec = (int)extract_unit_64(&dt, 1000LL); out->us = (int)(dt * 1000); break; case NPY_FR_us: days = extract_unit_64(&dt, 1000LL*1000*60*60*24); set_datetimestruct_days(days, out); out->hour = (int)extract_unit_64(&dt, 1000LL*1000*60*60); out->min = (int)extract_unit_64(&dt, 1000LL*1000*60); out->sec = (int)extract_unit_64(&dt, 1000LL*1000); out->us = (int)dt; break; case NPY_FR_ns: days = extract_unit_64(&dt, 1000LL*1000*1000*60*60*24); set_datetimestruct_days(days, out); out->hour = (int)extract_unit_64(&dt, 1000LL*1000*1000*60*60); out->min = (int)extract_unit_64(&dt, 1000LL*1000*1000*60); out->sec = (int)extract_unit_64(&dt, 1000LL*1000*1000); out->us = (int)extract_unit_64(&dt, 1000LL); out->ps = (int)(dt * 1000); break; case NPY_FR_ps: days = extract_unit_64(&dt, 1000LL*1000*1000*1000*60*60*24); set_datetimestruct_days(days, out); out->hour = (int)extract_unit_64(&dt, 1000LL*1000*1000*1000*60*60); out->min = (int)extract_unit_64(&dt, 1000LL*1000*1000*1000*60); out->sec = (int)extract_unit_64(&dt, 1000LL*1000*1000*1000); out->us = (int)extract_unit_64(&dt, 1000LL*1000); out->ps = (int)(dt); break; case NPY_FR_fs: /* entire range is only +- 2.6 hours */ out->hour = (int)extract_unit_64(&dt, 1000LL*1000*1000*1000*1000*60*60); if (out->hour < 0) { out->year = 1969; out->month = 12; out->day = 31; out->hour += 24; assert(out->hour >= 0); } out->min = (int)extract_unit_64(&dt, 1000LL*1000*1000*1000*1000*60); out->sec = (int)extract_unit_64(&dt, 1000LL*1000*1000*1000*1000); out->us = (int)extract_unit_64(&dt, 1000LL*1000*1000); out->ps = (int)extract_unit_64(&dt, 1000LL); out->as = (int)(dt * 1000); break; case NPY_FR_as: /* entire range is only +- 9.2 seconds */ out->sec = (int)extract_unit_64(&dt, 1000LL*1000*1000*1000*1000*1000); if (out->sec < 0) { out->year = 1969; out->month = 12; out->day = 31; out->hour = 23; out->min = 59; out->sec += 60; assert(out->sec >= 0); } out->us = (int)extract_unit_64(&dt, 1000LL*1000*1000*1000); out->ps = (int)extract_unit_64(&dt, 1000LL*1000); out->as = (int)dt; break; default: PyErr_SetString(PyExc_RuntimeError, "NumPy datetime metadata is corrupted with invalid " "base unit"); return -1; } return 0; } /*NUMPY_API * Fill the datetime struct from the value and resolution unit. * * TO BE REMOVED - NOT USED INTERNALLY. */ NPY_NO_EXPORT void PyArray_DatetimeToDatetimeStruct( npy_datetime NPY_UNUSED(val), NPY_DATETIMEUNIT NPY_UNUSED(fr), npy_datetimestruct *result) { PyErr_SetString(PyExc_RuntimeError, "The NumPy PyArray_DatetimeToDatetimeStruct function has " "been removed"); memset(result, -1, sizeof(npy_datetimestruct)); } /* * FIXME: Overflow is not handled at all * To convert from Years or Months, * multiplication by the average is done */ /*NUMPY_API * Fill the timedelta struct from the timedelta value and resolution unit. * * TO BE REMOVED - NOT USED INTERNALLY. */ NPY_NO_EXPORT void PyArray_TimedeltaToTimedeltaStruct( npy_timedelta NPY_UNUSED(val), NPY_DATETIMEUNIT NPY_UNUSED(fr), npy_timedeltastruct *result) { PyErr_SetString(PyExc_RuntimeError, "The NumPy PyArray_TimedeltaToTimedeltaStruct function has " "been removed"); memset(result, -1, sizeof(npy_timedeltastruct)); } /* * Creates a datetime or timedelta dtype using a copy of the provided metadata. */ NPY_NO_EXPORT PyArray_Descr * create_datetime_dtype(int type_num, PyArray_DatetimeMetaData *meta) { PyArray_Descr *dtype = NULL; PyArray_DatetimeMetaData *dt_data; /* Create a default datetime or timedelta */ if (type_num == NPY_DATETIME || type_num == NPY_TIMEDELTA) { dtype = PyArray_DescrNewFromType(type_num); } else { PyErr_SetString(PyExc_RuntimeError, "Asked to create a datetime type with a non-datetime " "type number"); return NULL; } if (dtype == NULL) { return NULL; } dt_data = &(((PyArray_DatetimeDTypeMetaData *)dtype->c_metadata)->meta); /* Copy the metadata */ *dt_data = *meta; return dtype; } /* * Creates a datetime or timedelta dtype using the given unit. */ NPY_NO_EXPORT PyArray_Descr * create_datetime_dtype_with_unit(int type_num, NPY_DATETIMEUNIT unit) { PyArray_DatetimeMetaData meta; meta.base = unit; meta.num = 1; return create_datetime_dtype(type_num, &meta); } /* * This function returns a pointer to the DateTimeMetaData * contained within the provided datetime dtype. */ NPY_NO_EXPORT PyArray_DatetimeMetaData * get_datetime_metadata_from_dtype(PyArray_Descr *dtype) { if (!PyDataType_ISDATETIME(dtype)) { PyErr_SetString(PyExc_TypeError, "cannot get datetime metadata from non-datetime type"); return NULL; } return &(((PyArray_DatetimeDTypeMetaData *)dtype->c_metadata)->meta); } /* strtol does not know whether to put a const qualifier on endptr, wrap * it so we can put this cast in one place. */ NPY_NO_EXPORT long int strtol_const(char const *str, char const **endptr, int base) { return strtol(str, (char**)endptr, base); } /* * Converts a substring given by 'str' and 'len' into * a date time unit multiplier + enum value, which are populated * into out_meta. Other metadata is left along. * * 'metastr' is only used in the error message, and may be NULL. * * Returns 0 on success, -1 on failure. */ NPY_NO_EXPORT int parse_datetime_extended_unit_from_string(char const *str, Py_ssize_t len, char const *metastr, PyArray_DatetimeMetaData *out_meta) { char const *substr = str, *substrend = NULL; int den = 1; npy_longlong true_meta_val; /* First comes an optional integer multiplier */ out_meta->num = (int)strtol_const(substr, &substrend, 10); if (substr == substrend) { out_meta->num = 1; } else { // check for 32-bit integer overflow char *endptr = NULL; true_meta_val = NumPyOS_strtoll(substr, &endptr, 10); if (true_meta_val > INT_MAX || true_meta_val < 0) { goto bad_input; } } substr = substrend; /* Next comes the unit itself, followed by either '/' or the string end */ substrend = substr; while (substrend-str < len && *substrend != '/') { ++substrend; } if (substr == substrend) { goto bad_input; } out_meta->base = parse_datetime_unit_from_string(substr, substrend - substr, metastr); if (out_meta->base == NPY_FR_ERROR ) { return -1; } substr = substrend; /* Next comes an optional integer denominator */ if (substr-str < len && *substr == '/') { substr++; den = (int)strtol_const(substr, &substrend, 10); /* If the '/' exists, there must be a number followed by ']' */ if (substr == substrend || *substrend != ']') { goto bad_input; } substr = substrend + 1; } else if (substr-str != len) { goto bad_input; } if (den != 1) { if (convert_datetime_divisor_to_multiple( out_meta, den, metastr) < 0) { return -1; } } return 0; bad_input: if (metastr != NULL) { PyErr_Format(PyExc_TypeError, "Invalid datetime metadata string \"%s\" at position %zd", metastr, substr-metastr); } else { PyErr_Format(PyExc_TypeError, "Invalid datetime metadata string \"%s\"", str); } return -1; } /* * Parses the metadata string into the metadata C structure. * * Returns 0 on success, -1 on failure. */ NPY_NO_EXPORT int parse_datetime_metadata_from_metastr(char const *metastr, Py_ssize_t len, PyArray_DatetimeMetaData *out_meta) { char const *substr = metastr, *substrend = NULL; /* Treat the empty string as generic units */ if (len == 0) { out_meta->base = NPY_FR_GENERIC; out_meta->num = 1; return 0; } /* The metadata string must start with a '[' */ if (len < 3 || *substr++ != '[') { goto bad_input; } substrend = substr; while (substrend - metastr < len && *substrend != ']') { ++substrend; } if (substrend - metastr == len || substr == substrend) { substr = substrend; goto bad_input; } /* Parse the extended unit inside the [] */ if (parse_datetime_extended_unit_from_string(substr, substrend-substr, metastr, out_meta) < 0) { return -1; } substr = substrend+1; if (substr - metastr != len) { goto bad_input; } return 0; bad_input: if (substr != metastr) { PyErr_Format(PyExc_TypeError, "Invalid datetime metadata string \"%s\" at position %zd", metastr, substr - metastr); } else { PyErr_Format(PyExc_TypeError, "Invalid datetime metadata string \"%s\"", metastr); } return -1; } /* * Converts a datetype dtype string into a dtype descr object. * The "type" string should be NULL-terminated. */ NPY_NO_EXPORT PyArray_Descr * parse_dtype_from_datetime_typestr(char const *typestr, Py_ssize_t len) { PyArray_DatetimeMetaData meta; char const *metastr = NULL; int is_timedelta = 0; Py_ssize_t metalen = 0; if (len < 2) { PyErr_Format(PyExc_TypeError, "Invalid datetime typestr \"%s\"", typestr); return NULL; } /* * First validate that the root is correct, * and get the metadata string address */ if (typestr[0] == 'm' && typestr[1] == '8') { is_timedelta = 1; metastr = typestr + 2; metalen = len - 2; } else if (typestr[0] == 'M' && typestr[1] == '8') { is_timedelta = 0; metastr = typestr + 2; metalen = len - 2; } else if (len >= 11 && strncmp(typestr, "timedelta64", 11) == 0) { is_timedelta = 1; metastr = typestr + 11; metalen = len - 11; } else if (len >= 10 && strncmp(typestr, "datetime64", 10) == 0) { is_timedelta = 0; metastr = typestr + 10; metalen = len - 10; } else { PyErr_Format(PyExc_TypeError, "Invalid datetime typestr \"%s\"", typestr); return NULL; } /* Parse the metadata string into a metadata struct */ if (parse_datetime_metadata_from_metastr(metastr, metalen, &meta) < 0) { return NULL; } return create_datetime_dtype(is_timedelta ? NPY_TIMEDELTA : NPY_DATETIME, &meta); } static NPY_DATETIMEUNIT _multiples_table[16][4] = { {12, 52, 365}, /* NPY_FR_Y */ {NPY_FR_M, NPY_FR_W, NPY_FR_D}, {4, 30, 720}, /* NPY_FR_M */ {NPY_FR_W, NPY_FR_D, NPY_FR_h}, {7, 168, 10080}, /* NPY_FR_W */ {NPY_FR_D, NPY_FR_h, NPY_FR_m}, {0}, /* Gap for removed NPY_FR_B */ {0}, {24, 1440, 86400}, /* NPY_FR_D */ {NPY_FR_h, NPY_FR_m, NPY_FR_s}, {60, 3600}, /* NPY_FR_h */ {NPY_FR_m, NPY_FR_s}, {60, 60000}, /* NPY_FR_m */ {NPY_FR_s, NPY_FR_ms}, {1000, 1000000}, /* >=NPY_FR_s */ {0, 0} }; /* * Translate divisors into multiples of smaller units. * 'metastr' is used for the error message if the divisor doesn't work, * and can be NULL if the metadata didn't come from a string. * * This function only affects the 'base' and 'num' values in the metadata. * * Returns 0 on success, -1 on failure. */ NPY_NO_EXPORT int convert_datetime_divisor_to_multiple(PyArray_DatetimeMetaData *meta, int den, char const *metastr) { int i, num, ind; NPY_DATETIMEUNIT *totry; NPY_DATETIMEUNIT *baseunit; int q, r; if (meta->base == NPY_FR_GENERIC) { PyErr_SetString(PyExc_ValueError, "Can't use 'den' divisor with generic units"); return -1; } num = 3; if (meta->base == NPY_FR_W) { num = 4; } else if (meta->base > NPY_FR_D) { num = 2; } if (meta->base >= NPY_FR_s) { /* _multiplies_table only has entries up to NPY_FR_s */ ind = ((int)NPY_FR_s - (int)NPY_FR_Y)*2; totry = _multiples_table[ind]; baseunit = _multiples_table[ind + 1]; baseunit[0] = meta->base + 1; baseunit[1] = meta->base + 2; if (meta->base == NPY_FR_as - 1) { num = 1; } if (meta->base == NPY_FR_as) { num = 0; } } else { ind = ((int)meta->base - (int)NPY_FR_Y)*2; totry = _multiples_table[ind]; baseunit = _multiples_table[ind + 1]; } for (i = 0; i < num; i++) { q = totry[i] / den; r = totry[i] % den; if (r == 0) { break; } } if (i == num) { if (metastr == NULL) { PyErr_Format(PyExc_ValueError, "divisor (%d) is not a multiple of a lower-unit " "in datetime metadata", den); } else { PyErr_Format(PyExc_ValueError, "divisor (%d) is not a multiple of a lower-unit " "in datetime metadata \"%s\"", den, metastr); } return -1; } meta->base = baseunit[i]; meta->num *= q; return 0; } /* * Lookup table for factors between datetime units, except * for years and months. */ static npy_uint32 _datetime_factors[] = { 1, /* Years - not used */ 1, /* Months - not used */ 7, /* Weeks -> Days */ 1, /* Business Days - was removed but a gap still exists in the enum */ 24, /* Days -> Hours */ 60, /* Hours -> Minutes */ 60, /* Minutes -> Seconds */ 1000, 1000, 1000, 1000, 1000, 1000, 1, /* Attoseconds are the smallest base unit */ 0 /* Generic units don't have a conversion */ }; /* * Returns the scale factor between the units. Does not validate * that bigbase represents larger units than littlebase, or that * the units are not generic. * * Returns 0 if there is an overflow. */ static npy_uint64 get_datetime_units_factor(NPY_DATETIMEUNIT bigbase, NPY_DATETIMEUNIT littlebase) { npy_uint64 factor = 1; NPY_DATETIMEUNIT unit = bigbase; while (unit < littlebase) { factor *= _datetime_factors[unit]; /* * Detect overflow by disallowing the top 16 bits to be 1. * That allows a margin of error much bigger than any of * the datetime factors. */ if (factor&0xff00000000000000ULL) { return 0; } ++unit; } return factor; } /* Euclidean algorithm on two positive numbers */ static npy_uint64 _uint64_euclidean_gcd(npy_uint64 x, npy_uint64 y) { npy_uint64 tmp; if (x > y) { tmp = x; x = y; y = tmp; } while (x != y && y != 0) { tmp = x % y; x = y; y = tmp; } return x; } /* * Computes the conversion factor to convert data with 'src_meta' metadata * into data with 'dst_meta' metadata. * * If overflow occurs, both out_num and out_denom are set to 0, but * no error is set. */ NPY_NO_EXPORT void get_datetime_conversion_factor(PyArray_DatetimeMetaData *src_meta, PyArray_DatetimeMetaData *dst_meta, npy_int64 *out_num, npy_int64 *out_denom) { int src_base, dst_base, swapped; npy_uint64 num = 1, denom = 1, tmp, gcd; /* Generic units change to the destination with no conversion factor */ if (src_meta->base == NPY_FR_GENERIC) { *out_num = 1; *out_denom = 1; return; } /* * Converting to a generic unit from something other than a generic * unit is an error. */ else if (dst_meta->base == NPY_FR_GENERIC) { PyErr_SetString(PyExc_ValueError, "Cannot convert from specific units to generic " "units in NumPy datetimes or timedeltas"); *out_num = 0; *out_denom = 0; return; } if (src_meta->base <= dst_meta->base) { src_base = src_meta->base; dst_base = dst_meta->base; swapped = 0; } else { src_base = dst_meta->base; dst_base = src_meta->base; swapped = 1; } if (src_base != dst_base) { /* * Conversions between years/months and other units use * the factor averaged over the 400 year leap year cycle. */ if (src_base == NPY_FR_Y) { if (dst_base == NPY_FR_M) { num *= 12; } else if (dst_base == NPY_FR_W) { num *= (97 + 400*365); denom *= 400*7; } else { /* Year -> Day */ num *= (97 + 400*365); denom *= 400; /* Day -> dst_base */ num *= get_datetime_units_factor(NPY_FR_D, dst_base); } } else if (src_base == NPY_FR_M) { if (dst_base == NPY_FR_W) { num *= (97 + 400*365); denom *= 400*12*7; } else { /* Month -> Day */ num *= (97 + 400*365); denom *= 400*12; /* Day -> dst_base */ num *= get_datetime_units_factor(NPY_FR_D, dst_base); } } else { num *= get_datetime_units_factor(src_base, dst_base); } } /* If something overflowed, make both num and denom 0 */ if (num == 0) { PyErr_Format(PyExc_OverflowError, "Integer overflow while computing the conversion " "factor between NumPy datetime units %s and %s", _datetime_strings[src_base], _datetime_strings[dst_base]); *out_num = 0; *out_denom = 0; return; } /* Swap the numerator and denominator if necessary */ if (swapped) { tmp = num; num = denom; denom = tmp; } num *= src_meta->num; denom *= dst_meta->num; /* Return as a fraction in reduced form */ gcd = _uint64_euclidean_gcd(num, denom); *out_num = (npy_int64)(num / gcd); *out_denom = (npy_int64)(denom / gcd); } /* * Determines whether the 'divisor' metadata divides evenly into * the 'dividend' metadata. */ NPY_NO_EXPORT npy_bool datetime_metadata_divides( PyArray_DatetimeMetaData *dividend, PyArray_DatetimeMetaData *divisor, int strict_with_nonlinear_units) { npy_uint64 num1, num2; /* * Any unit can always divide into generic units. In other words, we * should be able to convert generic units into any more specific unit. */ if (dividend->base == NPY_FR_GENERIC) { return 1; } /* * However, generic units cannot always divide into more specific units. * We cannot safely convert datetimes with units back into generic units. */ else if (divisor->base == NPY_FR_GENERIC) { return 0; } num1 = (npy_uint64)dividend->num; num2 = (npy_uint64)divisor->num; /* If the bases are different, factor in a conversion */ if (dividend->base != divisor->base) { /* * Years and Months are incompatible with * all other units (except years and months are compatible * with each other). */ if (dividend->base == NPY_FR_Y) { if (divisor->base == NPY_FR_M) { num1 *= 12; } else if (strict_with_nonlinear_units) { return 0; } else { /* Could do something complicated here */ return 1; } } else if (divisor->base == NPY_FR_Y) { if (dividend->base == NPY_FR_M) { num2 *= 12; } else if (strict_with_nonlinear_units) { return 0; } else { /* Could do something complicated here */ return 1; } } else if (dividend->base == NPY_FR_M || divisor->base == NPY_FR_M) { if (strict_with_nonlinear_units) { return 0; } else { /* Could do something complicated here */ return 1; } } /* Take the greater base (unit sizes are decreasing in enum) */ if (dividend->base > divisor->base) { num2 *= get_datetime_units_factor(divisor->base, dividend->base); if (num2 == 0) { return 0; } } else { num1 *= get_datetime_units_factor(dividend->base, divisor->base); if (num1 == 0) { return 0; } } } /* Crude, incomplete check for overflow */ if (num1&0xff00000000000000LL || num2&0xff00000000000000LL ) { return 0; } return (num1 % num2) == 0; } /* * This provides the casting rules for the DATETIME data type units. */ NPY_NO_EXPORT npy_bool can_cast_datetime64_units(NPY_DATETIMEUNIT src_unit, NPY_DATETIMEUNIT dst_unit, NPY_CASTING casting) { switch (casting) { /* Allow anything with unsafe casting */ case NPY_UNSAFE_CASTING: return 1; /* * Can cast between all units with 'same_kind' casting. */ case NPY_SAME_KIND_CASTING: if (src_unit == NPY_FR_GENERIC || dst_unit == NPY_FR_GENERIC) { return src_unit == NPY_FR_GENERIC; } else { return 1; } /* * Casting is only allowed towards more precise units with 'safe' * casting. */ case NPY_SAFE_CASTING: if (src_unit == NPY_FR_GENERIC || dst_unit == NPY_FR_GENERIC) { return src_unit == NPY_FR_GENERIC; } else { return (src_unit <= dst_unit); } /* Enforce equality with 'no' or 'equiv' casting */ default: return src_unit == dst_unit; } } /* * This provides the casting rules for the TIMEDELTA data type units. * * Notably, there is a barrier between the nonlinear years and * months units, and all the other units. */ NPY_NO_EXPORT npy_bool can_cast_timedelta64_units(NPY_DATETIMEUNIT src_unit, NPY_DATETIMEUNIT dst_unit, NPY_CASTING casting) { switch (casting) { /* Allow anything with unsafe casting */ case NPY_UNSAFE_CASTING: return 1; /* * Only enforce the 'date units' vs 'time units' barrier with * 'same_kind' casting. */ case NPY_SAME_KIND_CASTING: if (src_unit == NPY_FR_GENERIC || dst_unit == NPY_FR_GENERIC) { return src_unit == NPY_FR_GENERIC; } else { return (src_unit <= NPY_FR_M && dst_unit <= NPY_FR_M) || (src_unit > NPY_FR_M && dst_unit > NPY_FR_M); } /* * Enforce the 'date units' vs 'time units' barrier and that * casting is only allowed towards more precise units with * 'safe' casting. */ case NPY_SAFE_CASTING: if (src_unit == NPY_FR_GENERIC || dst_unit == NPY_FR_GENERIC) { return src_unit == NPY_FR_GENERIC; } else { return (src_unit <= dst_unit) && ((src_unit <= NPY_FR_M && dst_unit <= NPY_FR_M) || (src_unit > NPY_FR_M && dst_unit > NPY_FR_M)); } /* Enforce equality with 'no' or 'equiv' casting */ default: return src_unit == dst_unit; } } /* * This provides the casting rules for the DATETIME data type metadata. */ NPY_NO_EXPORT npy_bool can_cast_datetime64_metadata(PyArray_DatetimeMetaData *src_meta, PyArray_DatetimeMetaData *dst_meta, NPY_CASTING casting) { switch (casting) { case NPY_UNSAFE_CASTING: return 1; case NPY_SAME_KIND_CASTING: return can_cast_datetime64_units(src_meta->base, dst_meta->base, casting); case NPY_SAFE_CASTING: return can_cast_datetime64_units(src_meta->base, dst_meta->base, casting) && datetime_metadata_divides(src_meta, dst_meta, 0); default: return src_meta->base == dst_meta->base && src_meta->num == dst_meta->num; } } /* * This provides the casting rules for the TIMEDELTA data type metadata. */ NPY_NO_EXPORT npy_bool can_cast_timedelta64_metadata(PyArray_DatetimeMetaData *src_meta, PyArray_DatetimeMetaData *dst_meta, NPY_CASTING casting) { switch (casting) { case NPY_UNSAFE_CASTING: return 1; case NPY_SAME_KIND_CASTING: return can_cast_timedelta64_units(src_meta->base, dst_meta->base, casting); case NPY_SAFE_CASTING: return can_cast_timedelta64_units(src_meta->base, dst_meta->base, casting) && datetime_metadata_divides(src_meta, dst_meta, 1); default: return src_meta->base == dst_meta->base && src_meta->num == dst_meta->num; } } /* * Tests whether a datetime64 can be cast from the source metadata * to the destination metadata according to the specified casting rule. * * Returns -1 if an exception was raised, 0 otherwise. */ NPY_NO_EXPORT int raise_if_datetime64_metadata_cast_error(char *object_type, PyArray_DatetimeMetaData *src_meta, PyArray_DatetimeMetaData *dst_meta, NPY_CASTING casting) { if (can_cast_datetime64_metadata(src_meta, dst_meta, casting)) { return 0; } else { PyObject *src = metastr_to_unicode(src_meta, 0); if (src == NULL) { return -1; } PyObject *dst = metastr_to_unicode(dst_meta, 0); if (dst == NULL) { Py_DECREF(src); return -1; } PyErr_Format(PyExc_TypeError, "Cannot cast %s from metadata %S to %S according to the rule %s", object_type, src, dst, npy_casting_to_string(casting)); Py_DECREF(src); Py_DECREF(dst); return -1; } } /* * Tests whether a timedelta64 can be cast from the source metadata * to the destination metadata according to the specified casting rule. * * Returns -1 if an exception was raised, 0 otherwise. */ NPY_NO_EXPORT int raise_if_timedelta64_metadata_cast_error(char *object_type, PyArray_DatetimeMetaData *src_meta, PyArray_DatetimeMetaData *dst_meta, NPY_CASTING casting) { if (can_cast_timedelta64_metadata(src_meta, dst_meta, casting)) { return 0; } else { PyObject *src = metastr_to_unicode(src_meta, 0); if (src == NULL) { return -1; } PyObject *dst = metastr_to_unicode(dst_meta, 0); if (dst == NULL) { Py_DECREF(src); return -1; } PyErr_Format(PyExc_TypeError, "Cannot cast %s from metadata %S to %S according to the rule %s", object_type, src, dst, npy_casting_to_string(casting)); Py_DECREF(src); Py_DECREF(dst); return -1; } } /* * Computes the GCD of the two date-time metadata values. Raises * an exception if there is no reasonable GCD, such as with * years and days. * * The result is placed in 'out_meta'. * * Returns 0 on success, -1 on failure. */ NPY_NO_EXPORT int compute_datetime_metadata_greatest_common_divisor( PyArray_DatetimeMetaData *meta1, PyArray_DatetimeMetaData *meta2, PyArray_DatetimeMetaData *out_meta, int strict_with_nonlinear_units1, int strict_with_nonlinear_units2) { NPY_DATETIMEUNIT base; npy_uint64 num1, num2, num; /* If either unit is generic, adopt the metadata from the other one */ if (meta1->base == NPY_FR_GENERIC) { *out_meta = *meta2; return 0; } else if (meta2->base == NPY_FR_GENERIC) { *out_meta = *meta1; return 0; } num1 = (npy_uint64)meta1->num; num2 = (npy_uint64)meta2->num; /* First validate that the units have a reasonable GCD */ if (meta1->base == meta2->base) { base = meta1->base; } else { /* * Years and Months are incompatible with * all other units (except years and months are compatible * with each other). */ if (meta1->base == NPY_FR_Y) { if (meta2->base == NPY_FR_M) { base = NPY_FR_M; num1 *= 12; } else if (strict_with_nonlinear_units1) { goto incompatible_units; } else { base = meta2->base; /* Don't multiply num1 since there is no even factor */ } } else if (meta2->base == NPY_FR_Y) { if (meta1->base == NPY_FR_M) { base = NPY_FR_M; num2 *= 12; } else if (strict_with_nonlinear_units2) { goto incompatible_units; } else { base = meta1->base; /* Don't multiply num2 since there is no even factor */ } } else if (meta1->base == NPY_FR_M) { if (strict_with_nonlinear_units1) { goto incompatible_units; } else { base = meta2->base; /* Don't multiply num1 since there is no even factor */ } } else if (meta2->base == NPY_FR_M) { if (strict_with_nonlinear_units2) { goto incompatible_units; } else { base = meta1->base; /* Don't multiply num2 since there is no even factor */ } } /* Take the greater base (unit sizes are decreasing in enum) */ if (meta1->base > meta2->base) { base = meta1->base; num2 *= get_datetime_units_factor(meta2->base, meta1->base); if (num2 == 0) { goto units_overflow; } } else { base = meta2->base; num1 *= get_datetime_units_factor(meta1->base, meta2->base); if (num1 == 0) { goto units_overflow; } } } /* Compute the GCD of the resulting multipliers */ num = _uint64_euclidean_gcd(num1, num2); /* Fill the 'out_meta' values */ out_meta->base = base; out_meta->num = (int)num; if (out_meta->num <= 0 || num != (npy_uint64)out_meta->num) { goto units_overflow; } return 0; incompatible_units: { PyObject *umeta1 = metastr_to_unicode(meta1, 0); if (umeta1 == NULL) { return -1; } PyObject *umeta2 = metastr_to_unicode(meta2, 0); if (umeta2 == NULL) { Py_DECREF(umeta1); return -1; } PyErr_Format(PyExc_TypeError, "Cannot get a common metadata divisor for Numpy datetime " "metadata %S and %S because they have incompatible nonlinear " "base time units.", umeta1, umeta2); Py_DECREF(umeta1); Py_DECREF(umeta2); return -1; } units_overflow: { PyObject *umeta1 = metastr_to_unicode(meta1, 0); if (umeta1 == NULL) { return -1; } PyObject *umeta2 = metastr_to_unicode(meta2, 0); if (umeta2 == NULL) { Py_DECREF(umeta1); return -1; } PyErr_Format(PyExc_OverflowError, "Integer overflow getting a common metadata divisor for " "NumPy datetime metadata %S and %S.", umeta1, umeta2); Py_DECREF(umeta1); Py_DECREF(umeta2); return -1; } } /* * Both type1 and type2 must be either NPY_DATETIME or NPY_TIMEDELTA. * Applies the type promotion rules between the two types, returning * the promoted type. */ NPY_NO_EXPORT PyArray_Descr * datetime_type_promotion(PyArray_Descr *type1, PyArray_Descr *type2) { int type_num1, type_num2; PyArray_Descr *dtype; int is_datetime; type_num1 = type1->type_num; type_num2 = type2->type_num; is_datetime = (type_num1 == NPY_DATETIME || type_num2 == NPY_DATETIME); /* Create a DATETIME or TIMEDELTA dtype */ dtype = PyArray_DescrNewFromType(is_datetime ? NPY_DATETIME : NPY_TIMEDELTA); if (dtype == NULL) { return NULL; } /* * Get the metadata GCD, being strict about nonlinear units for * timedelta and relaxed for datetime. */ if (compute_datetime_metadata_greatest_common_divisor( get_datetime_metadata_from_dtype(type1), get_datetime_metadata_from_dtype(type2), get_datetime_metadata_from_dtype(dtype), type_num1 == NPY_TIMEDELTA, type_num2 == NPY_TIMEDELTA) < 0) { Py_DECREF(dtype); return NULL; } return dtype; } /* * Converts a substring given by 'str' and 'len' into * a date time unit enum value. The 'metastr' parameter * is used for error messages, and may be NULL. * * Returns NPY_DATETIMEUNIT on success, NPY_FR_ERROR on failure. */ NPY_NO_EXPORT NPY_DATETIMEUNIT parse_datetime_unit_from_string(char const *str, Py_ssize_t len, char const *metastr) { /* Use switch statements so the compiler can make it fast */ if (len == 1) { switch (str[0]) { case 'Y': return NPY_FR_Y; case 'M': return NPY_FR_M; case 'W': return NPY_FR_W; case 'D': return NPY_FR_D; case 'h': return NPY_FR_h; case 'm': return NPY_FR_m; case 's': return NPY_FR_s; } } /* All the two-letter units are variants of seconds */ else if (len == 2 && str[1] == 's') { switch (str[0]) { case 'm': return NPY_FR_ms; case 'u': return NPY_FR_us; case 'n': return NPY_FR_ns; case 'p': return NPY_FR_ps; case 'f': return NPY_FR_fs; case 'a': return NPY_FR_as; } } else if (len == 3 && !strncmp(str, "\xce\xbcs", 3)) { /* greek small letter mu, utf8-encoded */ return NPY_FR_us; } else if (len == 7 && !strncmp(str, "generic", 7)) { return NPY_FR_GENERIC; } /* If nothing matched, it's an error */ if (metastr == NULL) { PyErr_Format(PyExc_TypeError, "Invalid datetime unit \"%s\" in metadata", str); } else { PyErr_Format(PyExc_TypeError, "Invalid datetime unit in metadata string \"%s\"", metastr); } return NPY_FR_ERROR; } NPY_NO_EXPORT PyObject * convert_datetime_metadata_to_tuple(PyArray_DatetimeMetaData *meta) { PyObject *dt_tuple; dt_tuple = PyTuple_New(2); if (dt_tuple == NULL) { return NULL; } PyTuple_SET_ITEM(dt_tuple, 0, PyUnicode_FromString(_datetime_strings[meta->base])); PyTuple_SET_ITEM(dt_tuple, 1, PyLong_FromLong(meta->num)); return dt_tuple; } /* * Converts a metadata tuple into a datetime metadata C struct. * * Returns 0 on success, -1 on failure. */ NPY_NO_EXPORT int convert_datetime_metadata_tuple_to_datetime_metadata(PyObject *tuple, PyArray_DatetimeMetaData *out_meta, npy_bool from_pickle) { int den = 1; if (!PyTuple_Check(tuple)) { PyErr_Format(PyExc_TypeError, "Require tuple for tuple to NumPy " "datetime metadata conversion, not %R", tuple); return -1; } Py_ssize_t tuple_size = PyTuple_GET_SIZE(tuple); if (tuple_size < 2 || tuple_size > 4) { PyErr_SetString(PyExc_TypeError, "Require tuple of size 2 to 4 for " "tuple to NumPy datetime metadata conversion"); return -1; } PyObject *unit_str = PyTuple_GET_ITEM(tuple, 0); if (PyBytes_Check(unit_str)) { /* Allow bytes format strings: convert to unicode */ PyObject *tmp = PyUnicode_FromEncodedObject(unit_str, NULL, NULL); if (tmp == NULL) { return -1; } unit_str = tmp; } else { Py_INCREF(unit_str); } Py_ssize_t len; char const *basestr = PyUnicode_AsUTF8AndSize(unit_str, &len); if (basestr == NULL) { Py_DECREF(unit_str); return -1; } out_meta->base = parse_datetime_unit_from_string(basestr, len, NULL); if (out_meta->base == NPY_FR_ERROR) { Py_DECREF(unit_str); return -1; } Py_DECREF(unit_str); /* Convert the values to longs */ out_meta->num = PyLong_AsLong(PyTuple_GET_ITEM(tuple, 1)); if (error_converting(out_meta->num)) { return -1; } /* * The event metadata was removed way back in numpy 1.7 (cb4545), but was * not deprecated at the time. */ /* (unit, num, event) */ if (tuple_size == 3) { /* Numpy 1.14, 2017-08-11 */ if (DEPRECATE( "When passing a 3-tuple as (unit, num, event), the event " "is ignored (since 1.7) - use (unit, num) instead") < 0) { return -1; } } /* (unit, num, den, event) */ else if (tuple_size == 4) { PyObject *event = PyTuple_GET_ITEM(tuple, 3); if (from_pickle) { /* if (event == 1) */ PyObject *one = PyLong_FromLong(1); if (one == NULL) { return -1; } int equal_one = PyObject_RichCompareBool(event, one, Py_EQ); Py_DECREF(one); if (equal_one == -1) { return -1; } /* if the event data is not 1, it had semantics different to how * datetime types now behave, which are no longer respected. */ if (!equal_one) { if (PyErr_WarnEx(PyExc_UserWarning, "Loaded pickle file contains non-default event data " "for a datetime type, which has been ignored since 1.7", 1) < 0) { return -1; } } } else if (event != Py_None) { /* Numpy 1.14, 2017-08-11 */ if (DEPRECATE( "When passing a 4-tuple as (unit, num, den, event), the " "event argument is ignored (since 1.7), so should be None" ) < 0) { return -1; } } den = PyLong_AsLong(PyTuple_GET_ITEM(tuple, 2)); if (error_converting(den)) { return -1; } } if (out_meta->num <= 0 || den <= 0) { PyErr_SetString(PyExc_TypeError, "Invalid tuple values for " "tuple to NumPy datetime metadata conversion"); return -1; } if (den != 1) { if (convert_datetime_divisor_to_multiple(out_meta, den, NULL) < 0) { return -1; } } return 0; } /* * Converts an input object into datetime metadata. The input * may be either a string or a tuple. * * Returns 0 on success, -1 on failure. */ NPY_NO_EXPORT int convert_pyobject_to_datetime_metadata(PyObject *obj, PyArray_DatetimeMetaData *out_meta) { if (PyTuple_Check(obj)) { return convert_datetime_metadata_tuple_to_datetime_metadata( obj, out_meta, NPY_FALSE); } /* Get a UTF8 string */ PyObject *utf8 = NULL; if (PyBytes_Check(obj)) { /* Allow bytes format strings: convert to unicode */ utf8 = PyUnicode_FromEncodedObject(obj, NULL, NULL); if (utf8 == NULL) { return -1; } } else if (PyUnicode_Check(obj)) { utf8 = obj; Py_INCREF(utf8); } else { PyErr_SetString(PyExc_TypeError, "Invalid object for specifying NumPy datetime metadata"); return -1; } Py_ssize_t len = 0; char const *str = PyUnicode_AsUTF8AndSize(utf8, &len); if (str == NULL) { Py_DECREF(utf8); return -1; } if (len > 0 && str[0] == '[') { int r = parse_datetime_metadata_from_metastr(str, len, out_meta); Py_DECREF(utf8); return r; } else { if (parse_datetime_extended_unit_from_string(str, len, NULL, out_meta) < 0) { Py_DECREF(utf8); return -1; } Py_DECREF(utf8); return 0; } } /* * Return the datetime metadata as a Unicode object. * * Returns new reference, NULL on error. * * If 'skip_brackets' is true, skips the '[]'. * */ NPY_NO_EXPORT PyObject * metastr_to_unicode(PyArray_DatetimeMetaData *meta, int skip_brackets) { int num; char const *basestr; if (meta->base == NPY_FR_GENERIC) { /* Without brackets, give a string "generic" */ if (skip_brackets) { return PyUnicode_FromString("generic"); } /* But with brackets, return nothing */ else { return PyUnicode_FromString(""); } } num = meta->num; if (meta->base >= 0 && meta->base < NPY_DATETIME_NUMUNITS) { basestr = _datetime_strings[meta->base]; } else { PyErr_SetString(PyExc_RuntimeError, "NumPy datetime metadata is corrupted"); return NULL; } if (num == 1) { if (skip_brackets) { return PyUnicode_FromFormat("%s", basestr); } else { return PyUnicode_FromFormat("[%s]", basestr); } } else { if (skip_brackets) { return PyUnicode_FromFormat("%d%s", num, basestr); } else { return PyUnicode_FromFormat("[%d%s]", num, basestr); } } } /* * Adjusts a datetimestruct based on a seconds offset. Assumes * the current values are valid. */ NPY_NO_EXPORT void add_seconds_to_datetimestruct(npy_datetimestruct *dts, int seconds) { int minutes; dts->sec += seconds; minutes = extract_unit_32(&dts->sec, 60); add_minutes_to_datetimestruct(dts, minutes); } /* * Adjusts a datetimestruct based on a minutes offset. Assumes * the current values are valid. */ NPY_NO_EXPORT void add_minutes_to_datetimestruct(npy_datetimestruct *dts, int minutes) { int isleap; dts->min += minutes; /* propagate invalid minutes into hour and day changes */ dts->hour += extract_unit_32(&dts->min, 60); dts->day += extract_unit_32(&dts->hour, 24); /* propagate invalid days into month and year changes */ if (dts->day < 1) { dts->month--; if (dts->month < 1) { dts->year--; dts->month = 12; } isleap = is_leapyear(dts->year); dts->day += _days_per_month_table[isleap][dts->month-1]; } else if (dts->day > 28) { isleap = is_leapyear(dts->year); if (dts->day > _days_per_month_table[isleap][dts->month-1]) { dts->day -= _days_per_month_table[isleap][dts->month-1]; dts->month++; if (dts->month > 12) { dts->year++; dts->month = 1; } } } } /* * Tests for and converts a Python datetime.datetime or datetime.date * object into a NumPy npy_datetimestruct. * * While the C API has PyDate_* and PyDateTime_* functions, the following * implementation just asks for attributes, and thus supports * datetime duck typing. The tzinfo time zone conversion would require * this style of access anyway. * * 'out_bestunit' gives a suggested unit based on whether the object * was a datetime.date or datetime.datetime object. * * If 'apply_tzinfo' is 1, this function uses the tzinfo to convert * to UTC time, otherwise it returns the struct with the local time. * * Returns -1 on error, 0 on success, and 1 (with no error set) * if obj doesn't have the needed date or datetime attributes. */ NPY_NO_EXPORT int convert_pydatetime_to_datetimestruct(PyObject *obj, npy_datetimestruct *out, NPY_DATETIMEUNIT *out_bestunit, int apply_tzinfo) { PyObject *tmp; int isleap; /* Initialize the output to all zeros */ memset(out, 0, sizeof(npy_datetimestruct)); out->month = 1; out->day = 1; /* Need at least year/month/day attributes */ if (!PyObject_HasAttrString(obj, "year") || !PyObject_HasAttrString(obj, "month") || !PyObject_HasAttrString(obj, "day")) { return 1; } /* Get the year */ tmp = PyObject_GetAttrString(obj, "year"); if (tmp == NULL) { return -1; } out->year = PyLong_AsLong(tmp); if (error_converting(out->year)) { Py_DECREF(tmp); return -1; } Py_DECREF(tmp); /* Get the month */ tmp = PyObject_GetAttrString(obj, "month"); if (tmp == NULL) { return -1; } out->month = PyLong_AsLong(tmp); if (error_converting(out->month)) { Py_DECREF(tmp); return -1; } Py_DECREF(tmp); /* Get the day */ tmp = PyObject_GetAttrString(obj, "day"); if (tmp == NULL) { return -1; } out->day = PyLong_AsLong(tmp); if (error_converting(out->day)) { Py_DECREF(tmp); return -1; } Py_DECREF(tmp); /* Validate that the month and day are valid for the year */ if (out->month < 1 || out->month > 12) { goto invalid_date; } isleap = is_leapyear(out->year); if (out->day < 1 || out->day > _days_per_month_table[isleap][out->month-1]) { goto invalid_date; } /* Check for time attributes (if not there, return success as a date) */ if (!PyObject_HasAttrString(obj, "hour") || !PyObject_HasAttrString(obj, "minute") || !PyObject_HasAttrString(obj, "second") || !PyObject_HasAttrString(obj, "microsecond")) { /* The best unit for date is 'D' */ if (out_bestunit != NULL) { *out_bestunit = NPY_FR_D; } return 0; } /* Get the hour */ tmp = PyObject_GetAttrString(obj, "hour"); if (tmp == NULL) { return -1; } out->hour = PyLong_AsLong(tmp); if (error_converting(out->hour)) { Py_DECREF(tmp); return -1; } Py_DECREF(tmp); /* Get the minute */ tmp = PyObject_GetAttrString(obj, "minute"); if (tmp == NULL) { return -1; } out->min = PyLong_AsLong(tmp); if (error_converting(out->min)) { Py_DECREF(tmp); return -1; } Py_DECREF(tmp); /* Get the second */ tmp = PyObject_GetAttrString(obj, "second"); if (tmp == NULL) { return -1; } out->sec = PyLong_AsLong(tmp); if (error_converting(out->sec)) { Py_DECREF(tmp); return -1; } Py_DECREF(tmp); /* Get the microsecond */ tmp = PyObject_GetAttrString(obj, "microsecond"); if (tmp == NULL) { return -1; } out->us = PyLong_AsLong(tmp); if (error_converting(out->us)) { Py_DECREF(tmp); return -1; } Py_DECREF(tmp); if (out->hour < 0 || out->hour >= 24 || out->min < 0 || out->min >= 60 || out->sec < 0 || out->sec >= 60 || out->us < 0 || out->us >= 1000000) { goto invalid_time; } /* Apply the time zone offset if it exists */ if (apply_tzinfo && PyObject_HasAttrString(obj, "tzinfo")) { tmp = PyObject_GetAttrString(obj, "tzinfo"); if (tmp == NULL) { return -1; } if (tmp == Py_None) { Py_DECREF(tmp); } else { PyObject *offset; int seconds_offset, minutes_offset; /* 2016-01-14, 1.11 */ PyErr_Clear(); if (DEPRECATE( "parsing timezone aware datetimes is deprecated; " "this will raise an error in the future") < 0) { Py_DECREF(tmp); return -1; } /* The utcoffset function should return a timedelta */ offset = PyObject_CallMethod(tmp, "utcoffset", "O", obj); if (offset == NULL) { Py_DECREF(tmp); return -1; } Py_DECREF(tmp); /* * The timedelta should have a function "total_seconds" * which contains the value we want. */ tmp = PyObject_CallMethod(offset, "total_seconds", ""); Py_DECREF(offset); if (tmp == NULL) { return -1; } /* Rounding here is no worse than the integer division below. * Only whole minute offsets are supported by numpy anyway. */ seconds_offset = (int)PyFloat_AsDouble(tmp); if (error_converting(seconds_offset)) { Py_DECREF(tmp); return -1; } Py_DECREF(tmp); /* Convert to a minutes offset and apply it */ minutes_offset = seconds_offset / 60; add_minutes_to_datetimestruct(out, -minutes_offset); } } /* The resolution of Python's datetime is 'us' */ if (out_bestunit != NULL) { *out_bestunit = NPY_FR_us; } return 0; invalid_date: PyErr_Format(PyExc_ValueError, "Invalid date (%" NPY_INT64_FMT ",%" NPY_INT32_FMT ",%" NPY_INT32_FMT ") when converting to NumPy datetime", out->year, out->month, out->day); return -1; invalid_time: PyErr_Format(PyExc_ValueError, "Invalid time (%" NPY_INT32_FMT ",%" NPY_INT32_FMT ",%" NPY_INT32_FMT ",%" NPY_INT32_FMT ") when converting " "to NumPy datetime", out->hour, out->min, out->sec, out->us); return -1; } /* * Gets a tzoffset in minutes by calling the fromutc() function on * the Python datetime.tzinfo object. */ NPY_NO_EXPORT int get_tzoffset_from_pytzinfo(PyObject *timezone_obj, npy_datetimestruct *dts) { PyObject *dt, *loc_dt; npy_datetimestruct loc_dts; /* Create a Python datetime to give to the timezone object */ dt = PyDateTime_FromDateAndTime((int)dts->year, dts->month, dts->day, dts->hour, dts->min, 0, 0); if (dt == NULL) { return -1; } /* Convert the datetime from UTC to local time */ loc_dt = PyObject_CallMethod(timezone_obj, "fromutc", "O", dt); Py_DECREF(dt); if (loc_dt == NULL) { return -1; } /* Convert the local datetime into a datetimestruct */ if (convert_pydatetime_to_datetimestruct(loc_dt, &loc_dts, NULL, 0) < 0) { Py_DECREF(loc_dt); return -1; } Py_DECREF(loc_dt); /* Calculate the tzoffset as the difference between the datetimes */ return (int)(get_datetimestruct_minutes(&loc_dts) - get_datetimestruct_minutes(dts)); } /* * Converts a PyObject * into a datetime, in any of the forms supported. * * If the units metadata isn't known ahead of time, set meta->base * to -1, and this function will populate meta with either default * values or values from the input object. * * The 'casting' parameter is used to control what kinds of inputs * are accepted, and what happens. For example, with 'unsafe' casting, * unrecognized inputs are converted to 'NaT' instead of throwing an error, * while with 'safe' casting an error will be thrown if any precision * from the input will be thrown away. * * Returns -1 on error, 0 on success. */ NPY_NO_EXPORT int convert_pyobject_to_datetime(PyArray_DatetimeMetaData *meta, PyObject *obj, NPY_CASTING casting, npy_datetime *out) { if (PyBytes_Check(obj) || PyUnicode_Check(obj)) { PyObject *utf8 = NULL; /* Convert to an UTF8 string for the date parser */ if (PyBytes_Check(obj)) { utf8 = PyUnicode_FromEncodedObject(obj, NULL, NULL); if (utf8 == NULL) { return -1; } } else { utf8 = obj; Py_INCREF(utf8); } Py_ssize_t len = 0; char const *str = PyUnicode_AsUTF8AndSize(utf8, &len); if (str == NULL) { Py_DECREF(utf8); return -1; } /* Parse the ISO date */ npy_datetimestruct dts; NPY_DATETIMEUNIT bestunit = NPY_FR_ERROR; if (parse_iso_8601_datetime(str, len, meta->base, casting, &dts, &bestunit, NULL) < 0) { Py_DECREF(utf8); return -1; } /* Use the detected unit if none was specified */ if (meta->base == NPY_FR_ERROR) { meta->base = bestunit; meta->num = 1; } if (convert_datetimestruct_to_datetime(meta, &dts, out) < 0) { Py_DECREF(utf8); return -1; } Py_DECREF(utf8); return 0; } /* Do no conversion on raw integers */ else if (PyLong_Check(obj)) { /* Don't allow conversion from an integer without specifying a unit */ if (meta->base == NPY_FR_ERROR || meta->base == NPY_FR_GENERIC) { PyErr_SetString(PyExc_ValueError, "Converting an integer to a " "NumPy datetime requires a specified unit"); return -1; } *out = PyLong_AsLongLong(obj); if (error_converting(*out)) { return -1; } return 0; } /* Datetime scalar */ else if (PyArray_IsScalar(obj, Datetime)) { PyDatetimeScalarObject *dts = (PyDatetimeScalarObject *)obj; /* Copy the scalar directly if units weren't specified */ if (meta->base == NPY_FR_ERROR) { *meta = dts->obmeta; *out = dts->obval; return 0; } /* Otherwise do a casting transformation */ else { /* Allow NaT (not-a-time) values to slip through any rule */ if (dts->obval != NPY_DATETIME_NAT && raise_if_datetime64_metadata_cast_error( "NumPy timedelta64 scalar", &dts->obmeta, meta, casting) < 0) { return -1; } else { return cast_datetime_to_datetime(&dts->obmeta, meta, dts->obval, out); } } } /* Datetime zero-dimensional array */ else if (PyArray_Check(obj) && PyArray_NDIM((PyArrayObject *)obj) == 0 && PyArray_DESCR((PyArrayObject *)obj)->type_num == NPY_DATETIME) { PyArrayObject *arr = (PyArrayObject *)obj; PyArray_DatetimeMetaData *arr_meta; npy_datetime dt = 0; arr_meta = get_datetime_metadata_from_dtype(PyArray_DESCR(arr)); if (arr_meta == NULL) { return -1; } PyArray_DESCR(arr)->f->copyswap(&dt, PyArray_DATA(arr), PyArray_ISBYTESWAPPED(arr), obj); /* Copy the value directly if units weren't specified */ if (meta->base == NPY_FR_ERROR) { *meta = *arr_meta; *out = dt; return 0; } /* Otherwise do a casting transformation */ else { /* Allow NaT (not-a-time) values to slip through any rule */ if (dt != NPY_DATETIME_NAT && raise_if_datetime64_metadata_cast_error( "NumPy timedelta64 scalar", arr_meta, meta, casting) < 0) { return -1; } else { return cast_datetime_to_datetime(arr_meta, meta, dt, out); } } } /* Convert from a Python date or datetime object */ else { int code; npy_datetimestruct dts; NPY_DATETIMEUNIT bestunit = NPY_FR_ERROR; code = convert_pydatetime_to_datetimestruct(obj, &dts, &bestunit, 1); if (code == -1) { return -1; } else if (code == 0) { /* Use the detected unit if none was specified */ if (meta->base == NPY_FR_ERROR) { meta->base = bestunit; meta->num = 1; } else { PyArray_DatetimeMetaData obj_meta; obj_meta.base = bestunit; obj_meta.num = 1; if (raise_if_datetime64_metadata_cast_error( bestunit == NPY_FR_D ? "datetime.date object" : "datetime.datetime object", &obj_meta, meta, casting) < 0) { return -1; } } return convert_datetimestruct_to_datetime(meta, &dts, out); } } /* * With unsafe casting, convert unrecognized objects into NaT * and with same_kind casting, convert None into NaT */ if (casting == NPY_UNSAFE_CASTING || (obj == Py_None && casting == NPY_SAME_KIND_CASTING)) { if (meta->base == NPY_FR_ERROR) { meta->base = NPY_FR_GENERIC; meta->num = 1; } *out = NPY_DATETIME_NAT; return 0; } else { PyErr_SetString(PyExc_ValueError, "Could not convert object to NumPy datetime"); return -1; } } /* * Converts a PyObject * into a timedelta, in any of the forms supported * * If the units metadata isn't known ahead of time, set meta->base * to -1, and this function will populate meta with either default * values or values from the input object. * * The 'casting' parameter is used to control what kinds of inputs * are accepted, and what happens. For example, with 'unsafe' casting, * unrecognized inputs are converted to 'NaT' instead of throwing an error, * while with 'safe' casting an error will be thrown if any precision * from the input will be thrown away. * * Returns -1 on error, 0 on success. */ NPY_NO_EXPORT int convert_pyobject_to_timedelta(PyArray_DatetimeMetaData *meta, PyObject *obj, NPY_CASTING casting, npy_timedelta *out) { if (PyBytes_Check(obj) || PyUnicode_Check(obj)) { PyObject *utf8 = NULL; int succeeded = 0; /* Convert to an UTF8 string for the date parser */ if (PyBytes_Check(obj)) { utf8 = PyUnicode_FromEncodedObject(obj, NULL, NULL); if (utf8 == NULL) { return -1; } } else { utf8 = obj; Py_INCREF(utf8); } Py_ssize_t len = 0; char const *str = PyUnicode_AsUTF8AndSize(utf8, &len); if (str == NULL) { Py_DECREF(utf8); return -1; } /* Check for a NaT string */ if (len <= 0 || (len == 3 && tolower(str[0]) == 'n' && tolower(str[1]) == 'a' && tolower(str[2]) == 't')) { *out = NPY_DATETIME_NAT; succeeded = 1; } /* Parse as an integer */ else { char *strend = NULL; *out = strtol(str, &strend, 10); if (strend - str == len) { succeeded = 1; } } Py_DECREF(utf8); if (succeeded) { /* Use generic units if none was specified */ if (meta->base == NPY_FR_ERROR) { meta->base = NPY_FR_GENERIC; meta->num = 1; } return 0; } } /* Do no conversion on raw integers */ else if (PyLong_Check(obj)) { /* Use the default unit if none was specified */ if (meta->base == NPY_FR_ERROR) { meta->base = NPY_DATETIME_DEFAULTUNIT; meta->num = 1; } *out = PyLong_AsLongLong(obj); if (error_converting(*out)) { return -1; } return 0; } /* Timedelta scalar */ else if (PyArray_IsScalar(obj, Timedelta)) { PyTimedeltaScalarObject *dts = (PyTimedeltaScalarObject *)obj; /* Copy the scalar directly if units weren't specified */ if (meta->base == NPY_FR_ERROR) { *meta = dts->obmeta; *out = dts->obval; return 0; } /* Otherwise do a casting transformation */ else { /* Allow NaT (not-a-time) values to slip through any rule */ if (dts->obval != NPY_DATETIME_NAT && raise_if_timedelta64_metadata_cast_error( "NumPy timedelta64 scalar", &dts->obmeta, meta, casting) < 0) { return -1; } else { return cast_timedelta_to_timedelta(&dts->obmeta, meta, dts->obval, out); } } } /* Timedelta zero-dimensional array */ else if (PyArray_Check(obj) && PyArray_NDIM((PyArrayObject *)obj) == 0 && PyArray_DESCR((PyArrayObject *)obj)->type_num == NPY_TIMEDELTA) { PyArrayObject *arr = (PyArrayObject *)obj; PyArray_DatetimeMetaData *arr_meta; npy_timedelta dt = 0; arr_meta = get_datetime_metadata_from_dtype(PyArray_DESCR(arr)); if (arr_meta == NULL) { return -1; } PyArray_DESCR(arr)->f->copyswap(&dt, PyArray_DATA(arr), PyArray_ISBYTESWAPPED(arr), obj); /* Copy the value directly if units weren't specified */ if (meta->base == NPY_FR_ERROR) { *meta = *arr_meta; *out = dt; return 0; } /* Otherwise do a casting transformation */ else { /* Allow NaT (not-a-time) values to slip through any rule */ if (dt != NPY_DATETIME_NAT && raise_if_timedelta64_metadata_cast_error( "NumPy timedelta64 scalar", arr_meta, meta, casting) < 0) { return -1; } else { return cast_timedelta_to_timedelta(arr_meta, meta, dt, out); } } } /* Convert from a Python timedelta object */ else if (PyObject_HasAttrString(obj, "days") && PyObject_HasAttrString(obj, "seconds") && PyObject_HasAttrString(obj, "microseconds")) { PyObject *tmp; PyArray_DatetimeMetaData us_meta; npy_timedelta td; npy_int64 days; int seconds = 0, useconds = 0; /* Get the days */ tmp = PyObject_GetAttrString(obj, "days"); if (tmp == NULL) { return -1; } days = PyLong_AsLongLong(tmp); if (error_converting(days)) { Py_DECREF(tmp); return -1; } Py_DECREF(tmp); /* Get the seconds */ tmp = PyObject_GetAttrString(obj, "seconds"); if (tmp == NULL) { return -1; } seconds = PyLong_AsLong(tmp); if (error_converting(seconds)) { Py_DECREF(tmp); return -1; } Py_DECREF(tmp); /* Get the microseconds */ tmp = PyObject_GetAttrString(obj, "microseconds"); if (tmp == NULL) { return -1; } useconds = PyLong_AsLong(tmp); if (error_converting(useconds)) { Py_DECREF(tmp); return -1; } Py_DECREF(tmp); td = days*(24*60*60*1000000LL) + seconds*1000000LL + useconds; /* Use microseconds if none was specified */ if (meta->base == NPY_FR_ERROR) { meta->base = NPY_FR_us; meta->num = 1; *out = td; return 0; } else { /* * Detect the largest unit where every value after is zero, * to allow safe casting to seconds if microseconds is zero, * for instance. */ if (td % 1000LL != 0) { us_meta.base = NPY_FR_us; } else if (td % 1000000LL != 0) { us_meta.base = NPY_FR_ms; } else if (td % (60*1000000LL) != 0) { us_meta.base = NPY_FR_s; } else if (td % (60*60*1000000LL) != 0) { us_meta.base = NPY_FR_m; } else if (td % (24*60*60*1000000LL) != 0) { us_meta.base = NPY_FR_h; } else if (td % (7*24*60*60*1000000LL) != 0) { us_meta.base = NPY_FR_D; } else { us_meta.base = NPY_FR_W; } us_meta.num = 1; if (raise_if_timedelta64_metadata_cast_error( "datetime.timedelta object", &us_meta, meta, casting) < 0) { return -1; } else { /* Switch back to microseconds for the casting operation */ us_meta.base = NPY_FR_us; return cast_timedelta_to_timedelta(&us_meta, meta, td, out); } } } /* * With unsafe casting, convert unrecognized objects into NaT * and with same_kind casting, convert None into NaT */ if (casting == NPY_UNSAFE_CASTING || (obj == Py_None && casting == NPY_SAME_KIND_CASTING)) { if (meta->base == NPY_FR_ERROR) { meta->base = NPY_FR_GENERIC; meta->num = 1; } *out = NPY_DATETIME_NAT; return 0; } else if (PyArray_IsScalar(obj, Integer)) { /* Use the default unit if none was specified */ if (meta->base == NPY_FR_ERROR) { meta->base = NPY_DATETIME_DEFAULTUNIT; meta->num = 1; } *out = PyLong_AsLongLong(obj); if (error_converting(*out)) { return -1; } return 0; } else { PyErr_SetString(PyExc_ValueError, "Could not convert object to NumPy timedelta"); return -1; } } /* * Converts a datetime into a PyObject *. * * Not-a-time is returned as the string "NaT". * For days or coarser, returns a datetime.date. * For microseconds or coarser, returns a datetime.datetime. * For units finer than microseconds, returns an integer. */ NPY_NO_EXPORT PyObject * convert_datetime_to_pyobject(npy_datetime dt, PyArray_DatetimeMetaData *meta) { PyObject *ret = NULL; npy_datetimestruct dts; /* * Convert NaT (not-a-time) and any value with generic units * into None. */ if (dt == NPY_DATETIME_NAT || meta->base == NPY_FR_GENERIC) { Py_RETURN_NONE; } /* If the type's precision is greater than microseconds, return an int */ if (meta->base > NPY_FR_us) { return PyLong_FromLongLong(dt); } /* Convert to a datetimestruct */ if (convert_datetime_to_datetimestruct(meta, dt, &dts) < 0) { return NULL; } /* * If the year is outside the range of years supported by Python's * datetime, or the datetime64 falls on a leap second, * return a raw int. */ if (dts.year < 1 || dts.year > 9999 || dts.sec == 60) { return PyLong_FromLongLong(dt); } /* If the type's precision is greater than days, return a datetime */ if (meta->base > NPY_FR_D) { ret = PyDateTime_FromDateAndTime(dts.year, dts.month, dts.day, dts.hour, dts.min, dts.sec, dts.us); } /* Otherwise return a date */ else { ret = PyDate_FromDate(dts.year, dts.month, dts.day); } return ret; } /* * Converts a timedelta into a PyObject *. * * Not-a-time is returned as the string "NaT". * For microseconds or coarser, returns a datetime.timedelta. * For units finer than microseconds, returns an integer. */ NPY_NO_EXPORT PyObject * convert_timedelta_to_pyobject(npy_timedelta td, PyArray_DatetimeMetaData *meta) { npy_timedelta value; int days = 0, seconds = 0, useconds = 0; /* * Convert NaT (not-a-time) into None. */ if (td == NPY_DATETIME_NAT) { Py_RETURN_NONE; } /* * If the type's precision is greater than microseconds, is * Y/M/B (nonlinear units), or is generic units, return an int */ if (meta->base > NPY_FR_us || meta->base == NPY_FR_Y || meta->base == NPY_FR_M || meta->base == NPY_FR_GENERIC) { return PyLong_FromLongLong(td); } value = td; /* Apply the unit multiplier (TODO: overflow treatment...) */ value *= meta->num; /* Convert to days/seconds/useconds */ switch (meta->base) { case NPY_FR_W: days = value * 7; break; case NPY_FR_D: days = value; break; case NPY_FR_h: days = extract_unit_64(&value, 24ULL); seconds = value*60*60; break; case NPY_FR_m: days = extract_unit_64(&value, 60ULL*24); seconds = value*60; break; case NPY_FR_s: days = extract_unit_64(&value, 60ULL*60*24); seconds = value; break; case NPY_FR_ms: days = extract_unit_64(&value, 1000ULL*60*60*24); seconds = extract_unit_64(&value, 1000ULL); useconds = value*1000; break; case NPY_FR_us: days = extract_unit_64(&value, 1000ULL*1000*60*60*24); seconds = extract_unit_64(&value, 1000ULL*1000); useconds = value; break; default: // unreachable, handled by the `if` above assert(NPY_FALSE); break; } /* * If it would overflow the datetime.timedelta days, return a raw int */ if (days < -999999999 || days > 999999999) { return PyLong_FromLongLong(td); } else { return PyDelta_FromDSU(days, seconds, useconds); } } /* * Returns true if the datetime metadata matches */ NPY_NO_EXPORT npy_bool has_equivalent_datetime_metadata(PyArray_Descr *type1, PyArray_Descr *type2) { PyArray_DatetimeMetaData *meta1, *meta2; if ((type1->type_num != NPY_DATETIME && type1->type_num != NPY_TIMEDELTA) || (type2->type_num != NPY_DATETIME && type2->type_num != NPY_TIMEDELTA)) { return 0; } meta1 = get_datetime_metadata_from_dtype(type1); if (meta1 == NULL) { PyErr_Clear(); return 0; } meta2 = get_datetime_metadata_from_dtype(type2); if (meta2 == NULL) { PyErr_Clear(); return 0; } /* For generic units, the num is ignored */ if (meta1->base == NPY_FR_GENERIC && meta2->base == NPY_FR_GENERIC) { return 1; } return meta1->base == meta2->base && meta1->num == meta2->num; } /* * Casts a single datetime from having src_meta metadata into * dst_meta metadata. * * Returns 0 on success, -1 on failure. */ NPY_NO_EXPORT int cast_datetime_to_datetime(PyArray_DatetimeMetaData *src_meta, PyArray_DatetimeMetaData *dst_meta, npy_datetime src_dt, npy_datetime *dst_dt) { npy_datetimestruct dts; /* If the metadata is the same, short-circuit the conversion */ if (src_meta->base == dst_meta->base && src_meta->num == dst_meta->num) { *dst_dt = src_dt; return 0; } /* Otherwise convert through a datetimestruct */ if (convert_datetime_to_datetimestruct(src_meta, src_dt, &dts) < 0) { *dst_dt = NPY_DATETIME_NAT; return -1; } if (convert_datetimestruct_to_datetime(dst_meta, &dts, dst_dt) < 0) { *dst_dt = NPY_DATETIME_NAT; return -1; } return 0; } /* * Casts a single timedelta from having src_meta metadata into * dst_meta metadata. * * Returns 0 on success, -1 on failure. */ NPY_NO_EXPORT int cast_timedelta_to_timedelta(PyArray_DatetimeMetaData *src_meta, PyArray_DatetimeMetaData *dst_meta, npy_timedelta src_dt, npy_timedelta *dst_dt) { npy_int64 num = 0, denom = 0; /* If the metadata is the same, short-circuit the conversion */ if (src_meta->base == dst_meta->base && src_meta->num == dst_meta->num) { *dst_dt = src_dt; return 0; } /* Get the conversion factor */ get_datetime_conversion_factor(src_meta, dst_meta, &num, &denom); if (num == 0) { return -1; } /* Apply the scaling */ if (src_dt < 0) { *dst_dt = (src_dt * num - (denom - 1)) / denom; } else { *dst_dt = src_dt * num / denom; } return 0; } /* * Returns true if the object is something that is best considered * a Datetime, false otherwise. */ static NPY_GCC_NONNULL(1) npy_bool is_any_numpy_datetime(PyObject *obj) { return (PyArray_IsScalar(obj, Datetime) || (PyArray_Check(obj) && ( PyArray_DESCR((PyArrayObject *)obj)->type_num == NPY_DATETIME)) || PyDate_Check(obj) || PyDateTime_Check(obj)); } /* * Returns true if the object is something that is best considered * a Timedelta, false otherwise. */ static npy_bool is_any_numpy_timedelta(PyObject *obj) { return (PyArray_IsScalar(obj, Timedelta) || (PyArray_Check(obj) && ( PyArray_DESCR((PyArrayObject *)obj)->type_num == NPY_TIMEDELTA)) || PyDelta_Check(obj)); } /* * Returns true if the object is something that is best considered * a Datetime or Timedelta, false otherwise. */ NPY_NO_EXPORT npy_bool is_any_numpy_datetime_or_timedelta(PyObject *obj) { return obj != NULL && (is_any_numpy_datetime(obj) || is_any_numpy_timedelta(obj)); } /* * Converts an array of PyObject * into datetimes and/or timedeltas, * based on the values in type_nums. * * If inout_meta->base is -1, uses GCDs to calculate the metadata, filling * in 'inout_meta' with the resulting metadata. Otherwise uses the provided * 'inout_meta' for all the conversions. * * When obj[i] is NULL, out_value[i] will be set to NPY_DATETIME_NAT. * * Returns 0 on success, -1 on failure. */ NPY_NO_EXPORT int convert_pyobjects_to_datetimes(int count, PyObject **objs, const int *type_nums, NPY_CASTING casting, npy_int64 *out_values, PyArray_DatetimeMetaData *inout_meta) { int i, is_out_strict; PyArray_DatetimeMetaData *meta; /* No values trivially succeeds */ if (count == 0) { return 0; } /* Use the inputs to resolve the unit metadata if requested */ if (inout_meta->base == NPY_FR_ERROR) { /* Allocate an array of metadata corresponding to the objects */ meta = PyArray_malloc(count * sizeof(PyArray_DatetimeMetaData)); if (meta == NULL) { PyErr_NoMemory(); return -1; } /* Convert all the objects into timedeltas or datetimes */ for (i = 0; i < count; ++i) { meta[i].base = NPY_FR_ERROR; meta[i].num = 1; /* NULL -> NaT */ if (objs[i] == NULL) { out_values[i] = NPY_DATETIME_NAT; meta[i].base = NPY_FR_GENERIC; } else if (type_nums[i] == NPY_DATETIME) { if (convert_pyobject_to_datetime(&meta[i], objs[i], casting, &out_values[i]) < 0) { PyArray_free(meta); return -1; } } else if (type_nums[i] == NPY_TIMEDELTA) { if (convert_pyobject_to_timedelta(&meta[i], objs[i], casting, &out_values[i]) < 0) { PyArray_free(meta); return -1; } } else { PyErr_SetString(PyExc_ValueError, "convert_pyobjects_to_datetimes requires that " "all the type_nums provided be datetime or timedelta"); PyArray_free(meta); return -1; } } /* Merge all the metadatas, starting with the first one */ *inout_meta = meta[0]; is_out_strict = (type_nums[0] == NPY_TIMEDELTA); for (i = 1; i < count; ++i) { if (compute_datetime_metadata_greatest_common_divisor( &meta[i], inout_meta, inout_meta, type_nums[i] == NPY_TIMEDELTA, is_out_strict) < 0) { PyArray_free(meta); return -1; } is_out_strict = is_out_strict || (type_nums[i] == NPY_TIMEDELTA); } /* Convert all the values into the resolved unit metadata */ for (i = 0; i < count; ++i) { if (type_nums[i] == NPY_DATETIME) { if (cast_datetime_to_datetime(&meta[i], inout_meta, out_values[i], &out_values[i]) < 0) { PyArray_free(meta); return -1; } } else if (type_nums[i] == NPY_TIMEDELTA) { if (cast_timedelta_to_timedelta(&meta[i], inout_meta, out_values[i], &out_values[i]) < 0) { PyArray_free(meta); return -1; } } } PyArray_free(meta); } /* Otherwise convert to the provided unit metadata */ else { /* Convert all the objects into timedeltas or datetimes */ for (i = 0; i < count; ++i) { /* NULL -> NaT */ if (objs[i] == NULL) { out_values[i] = NPY_DATETIME_NAT; } else if (type_nums[i] == NPY_DATETIME) { if (convert_pyobject_to_datetime(inout_meta, objs[i], casting, &out_values[i]) < 0) { return -1; } } else if (type_nums[i] == NPY_TIMEDELTA) { if (convert_pyobject_to_timedelta(inout_meta, objs[i], casting, &out_values[i]) < 0) { return -1; } } else { PyErr_SetString(PyExc_ValueError, "convert_pyobjects_to_datetimes requires that " "all the type_nums provided be datetime or timedelta"); return -1; } } } return 0; } NPY_NO_EXPORT PyArrayObject * datetime_arange(PyObject *start, PyObject *stop, PyObject *step, PyArray_Descr *dtype) { /* * First normalize the input parameters so there is no Py_None, * and start is moved to stop if stop is unspecified. */ if (step == Py_None) { step = NULL; } if (stop == NULL || stop == Py_None) { stop = start; start = NULL; /* If start was NULL or None, raise an exception */ if (stop == NULL || stop == Py_None) { PyErr_SetString(PyExc_ValueError, "arange needs at least a stopping value"); return NULL; } } if (start == Py_None) { start = NULL; } /* Step must not be a Datetime */ if (step != NULL && is_any_numpy_datetime(step)) { PyErr_SetString(PyExc_ValueError, "cannot use a datetime as a step in arange"); return NULL; } /* Check if the units of the given dtype are generic, in which * case we use the code path that detects the units */ int type_nums[3]; PyArray_DatetimeMetaData meta; if (dtype != NULL) { PyArray_DatetimeMetaData *meta_tmp; type_nums[0] = dtype->type_num; if (type_nums[0] != NPY_DATETIME && type_nums[0] != NPY_TIMEDELTA) { PyErr_SetString(PyExc_ValueError, "datetime_arange was given a non-datetime dtype"); return NULL; } meta_tmp = get_datetime_metadata_from_dtype(dtype); if (meta_tmp == NULL) { return NULL; } /* * If the dtype specified is in generic units, detect the * units from the input parameters. */ if (meta_tmp->base == NPY_FR_GENERIC) { dtype = NULL; meta.base = NPY_FR_ERROR; } /* Otherwise use the provided metadata */ else { meta = *meta_tmp; } } else { if ((start && is_any_numpy_datetime(start)) || is_any_numpy_datetime(stop)) { type_nums[0] = NPY_DATETIME; } else { type_nums[0] = NPY_TIMEDELTA; } meta.base = NPY_FR_ERROR; } if (type_nums[0] == NPY_DATETIME && start == NULL) { PyErr_SetString(PyExc_ValueError, "arange requires both a start and a stop for " "NumPy datetime64 ranges"); return NULL; } /* Set up to convert the objects to a common datetime unit metadata */ PyObject *objs[3]; objs[0] = start; objs[1] = stop; objs[2] = step; if (type_nums[0] == NPY_TIMEDELTA) { type_nums[1] = NPY_TIMEDELTA; type_nums[2] = NPY_TIMEDELTA; } else { if (PyLong_Check(objs[1]) || PyArray_IsScalar(objs[1], Integer) || is_any_numpy_timedelta(objs[1])) { type_nums[1] = NPY_TIMEDELTA; } else { type_nums[1] = NPY_DATETIME; } type_nums[2] = NPY_TIMEDELTA; } /* Convert all the arguments * * Both datetime and timedelta are stored as int64, so they can * share value variables. */ npy_int64 values[3]; if (convert_pyobjects_to_datetimes(3, objs, type_nums, NPY_SAME_KIND_CASTING, values, &meta) < 0) { return NULL; } /* If no start was provided, default to 0 */ if (start == NULL) { /* enforced above */ assert(type_nums[0] == NPY_TIMEDELTA); values[0] = 0; } /* If no step was provided, default to 1 */ if (step == NULL) { values[2] = 1; } /* * In the case of arange(datetime, timedelta), convert * the timedelta into a datetime by adding the start datetime. */ if (type_nums[0] == NPY_DATETIME && type_nums[1] == NPY_TIMEDELTA) { values[1] += values[0]; } /* Now start, stop, and step have their values and matching metadata */ if (values[0] == NPY_DATETIME_NAT || values[1] == NPY_DATETIME_NAT || values[2] == NPY_DATETIME_NAT) { PyErr_SetString(PyExc_ValueError, "arange: cannot use NaT (not-a-time) datetime values"); return NULL; } /* Calculate the array length */ npy_intp length; if (values[2] > 0 && values[1] > values[0]) { length = (values[1] - values[0] + (values[2] - 1)) / values[2]; } else if (values[2] < 0 && values[1] < values[0]) { length = (values[1] - values[0] + (values[2] + 1)) / values[2]; } else if (values[2] != 0) { length = 0; } else { PyErr_SetString(PyExc_ValueError, "arange: step cannot be zero"); return NULL; } /* Create the dtype of the result */ if (dtype != NULL) { Py_INCREF(dtype); } else { dtype = create_datetime_dtype(type_nums[0], &meta); if (dtype == NULL) { return NULL; } } /* Create the result array */ PyArrayObject *ret = (PyArrayObject *)PyArray_NewFromDescr( &PyArray_Type, dtype, 1, &length, NULL, NULL, 0, NULL); if (ret == NULL) { return NULL; } if (length > 0) { /* Extract the data pointer */ npy_int64 *ret_data = (npy_int64 *)PyArray_DATA(ret); /* Create the timedeltas or datetimes */ for (npy_intp i = 0; i < length; ++i) { *ret_data = values[0]; values[0] += values[2]; ret_data++; } } return ret; } /* * Examines all the strings in the given string array, and parses them * to find the right metadata. * * Returns 0 on success, -1 on failure. */ NPY_NO_EXPORT int find_string_array_datetime64_type(PyArrayObject *arr, PyArray_DatetimeMetaData *meta) { NpyIter* iter; NpyIter_IterNextFunc *iternext; char **dataptr; npy_intp *strideptr, *innersizeptr; PyArray_Descr *string_dtype; int maxlen; char *tmp_buffer = NULL; npy_datetimestruct dts; PyArray_DatetimeMetaData tmp_meta; /* Handle zero-sized arrays specially */ if (PyArray_SIZE(arr) == 0) { return 0; } string_dtype = PyArray_DescrFromType(NPY_STRING); if (string_dtype == NULL) { return -1; } /* Use unsafe casting to allow unicode -> ascii string */ iter = NpyIter_New((PyArrayObject *)arr, NPY_ITER_READONLY| NPY_ITER_EXTERNAL_LOOP| NPY_ITER_BUFFERED, NPY_KEEPORDER, NPY_UNSAFE_CASTING, string_dtype); Py_DECREF(string_dtype); if (iter == NULL) { return -1; } iternext = NpyIter_GetIterNext(iter, NULL); if (iternext == NULL) { NpyIter_Deallocate(iter); return -1; } dataptr = NpyIter_GetDataPtrArray(iter); strideptr = NpyIter_GetInnerStrideArray(iter); innersizeptr = NpyIter_GetInnerLoopSizePtr(iter); /* Get the resulting string length */ maxlen = NpyIter_GetDescrArray(iter)[0]->elsize; /* Allocate a buffer for strings which fill the buffer completely */ tmp_buffer = PyArray_malloc(maxlen+1); if (tmp_buffer == NULL) { PyErr_NoMemory(); NpyIter_Deallocate(iter); return -1; } /* The iteration loop */ do { /* Get the inner loop data/stride/count values */ char* data = *dataptr; npy_intp stride = *strideptr; npy_intp count = *innersizeptr; char *tmp; /* The inner loop */ while (count--) { /* Replicating strnlen with memchr, because Mac OS X lacks it */ tmp = memchr(data, '\0', maxlen); /* If the string is all full, use the buffer */ if (tmp == NULL) { memcpy(tmp_buffer, data, maxlen); tmp_buffer[maxlen] = '\0'; tmp_meta.base = NPY_FR_ERROR; if (parse_iso_8601_datetime(tmp_buffer, maxlen, -1, NPY_UNSAFE_CASTING, &dts, &tmp_meta.base, NULL) < 0) { goto fail; } } /* Otherwise parse the data in place */ else { tmp_meta.base = NPY_FR_ERROR; if (parse_iso_8601_datetime(data, tmp - data, -1, NPY_UNSAFE_CASTING, &dts, &tmp_meta.base, NULL) < 0) { goto fail; } } tmp_meta.num = 1; /* Combine it with 'meta' */ if (compute_datetime_metadata_greatest_common_divisor(meta, &tmp_meta, meta, 0, 0) < 0) { goto fail; } data += stride; } } while(iternext(iter)); PyArray_free(tmp_buffer); NpyIter_Deallocate(iter); return 0; fail: PyArray_free(tmp_buffer); NpyIter_Deallocate(iter); return -1; } /* * Recursively determines the metadata for an NPY_DATETIME dtype. * * Returns 0 on success, -1 on failure. */ static int find_object_datetime64_meta(PyObject *obj, PyArray_DatetimeMetaData *meta) { if (PyArray_IsScalar(obj, Datetime)) { PyDatetimeScalarObject *dts = (PyDatetimeScalarObject *)obj; /* Combine it with 'meta' */ if (compute_datetime_metadata_greatest_common_divisor(meta, &dts->obmeta, meta, 0, 0) < 0) { return -1; } return 0; } /* String -> parse it to find out */ else if (PyBytes_Check(obj) || PyUnicode_Check(obj)) { npy_datetime tmp = 0; PyArray_DatetimeMetaData tmp_meta; tmp_meta.base = NPY_FR_ERROR; tmp_meta.num = 1; if (convert_pyobject_to_datetime(&tmp_meta, obj, NPY_UNSAFE_CASTING, &tmp) < 0) { /* If it's a value error, clear the error */ if (PyErr_Occurred() && PyErr_GivenExceptionMatches(PyErr_Occurred(), PyExc_ValueError)) { PyErr_Clear(); return 0; } /* Otherwise propagate the error */ else { return -1; } } /* Combine it with 'meta' */ if (compute_datetime_metadata_greatest_common_divisor(meta, &tmp_meta, meta, 0, 0) < 0) { return -1; } return 0; } /* Python datetime object -> 'us' */ else if (PyDateTime_Check(obj)) { PyArray_DatetimeMetaData tmp_meta; tmp_meta.base = NPY_FR_us; tmp_meta.num = 1; /* Combine it with 'meta' */ if (compute_datetime_metadata_greatest_common_divisor(meta, &tmp_meta, meta, 0, 0) < 0) { return -1; } return 0; } /* Python date object -> 'D' */ else if (PyDate_Check(obj)) { PyArray_DatetimeMetaData tmp_meta; tmp_meta.base = NPY_FR_D; tmp_meta.num = 1; /* Combine it with 'meta' */ if (compute_datetime_metadata_greatest_common_divisor(meta, &tmp_meta, meta, 0, 0) < 0) { return -1; } return 0; } /* Otherwise ignore it */ else { return 0; } } /* * handler function for PyDelta values * which may also be in a 0 dimensional * NumPy array */ static int delta_checker(PyArray_DatetimeMetaData *meta) { PyArray_DatetimeMetaData tmp_meta; tmp_meta.base = NPY_FR_us; tmp_meta.num = 1; /* Combine it with 'meta' */ if (compute_datetime_metadata_greatest_common_divisor( meta, &tmp_meta, meta, 0, 0) < 0) { return -1; } return 0; } /* * Recursively determines the metadata for an NPY_TIMEDELTA dtype. * * Returns 0 on success, -1 on failure. */ static int find_object_timedelta64_meta(PyObject *obj, PyArray_DatetimeMetaData *meta) { /* Datetime scalar -> use its metadata */ if (PyArray_IsScalar(obj, Timedelta)) { PyTimedeltaScalarObject *dts = (PyTimedeltaScalarObject *)obj; /* Combine it with 'meta' */ if (compute_datetime_metadata_greatest_common_divisor(meta, &dts->obmeta, meta, 1, 1) < 0) { return -1; } return 0; } /* String -> parse it to find out */ else if (PyBytes_Check(obj) || PyUnicode_Check(obj)) { /* No timedelta parser yet */ return 0; } /* Python timedelta object -> 'us' */ else if (PyDelta_Check(obj)) { return delta_checker(meta); } /* Otherwise ignore it */ else { return 0; } } /* * Examines all the objects in the given Python object by * recursively descending the sequence structure. Returns a * datetime or timedelta type with metadata based on the data. */ NPY_NO_EXPORT PyArray_Descr * find_object_datetime_type(PyObject *obj, int type_num) { PyArray_DatetimeMetaData meta; meta.base = NPY_FR_GENERIC; meta.num = 1; if (type_num == NPY_DATETIME) { if (find_object_datetime64_meta(obj, &meta) < 0) { return NULL; } else { return create_datetime_dtype(type_num, &meta); } } else if (type_num == NPY_TIMEDELTA) { if (find_object_timedelta64_meta(obj, &meta) < 0) { return NULL; } else { return create_datetime_dtype(type_num, &meta); } } else { PyErr_SetString(PyExc_ValueError, "find_object_datetime_type needs a datetime or " "timedelta type number"); return NULL; } } /* * Describes casting within datetimes or timedelta */ static NPY_CASTING time_to_time_resolve_descriptors( PyArrayMethodObject *NPY_UNUSED(self), PyArray_DTypeMeta *NPY_UNUSED(dtypes[2]), PyArray_Descr *given_descrs[2], PyArray_Descr *loop_descrs[2], npy_intp *view_offset) { /* This is a within-dtype cast, which currently must handle byteswapping */ Py_INCREF(given_descrs[0]); loop_descrs[0] = given_descrs[0]; if (given_descrs[1] == NULL) { loop_descrs[1] = NPY_DT_CALL_ensure_canonical(given_descrs[0]); } else { Py_INCREF(given_descrs[1]); loop_descrs[1] = given_descrs[1]; } int is_timedelta = given_descrs[0]->type_num == NPY_TIMEDELTA; if (given_descrs[0] == given_descrs[1]) { *view_offset = 0; return NPY_NO_CASTING; } npy_bool byteorder_may_allow_view = ( PyDataType_ISNOTSWAPPED(loop_descrs[0]) == PyDataType_ISNOTSWAPPED(loop_descrs[1])); PyArray_DatetimeMetaData *meta1, *meta2; meta1 = get_datetime_metadata_from_dtype(loop_descrs[0]); assert(meta1 != NULL); meta2 = get_datetime_metadata_from_dtype(loop_descrs[1]); assert(meta2 != NULL); if ((meta1->base == meta2->base && meta1->num == meta2->num) || // handle some common metric prefix conversions // 1000 fold conversions ((meta2->base >= 7) && (meta1->base - meta2->base == 1) && ((meta1->num / meta2->num) == 1000)) || // 10^6 fold conversions ((meta2->base >= 7) && (meta1->base - meta2->base == 2) && ((meta1->num / meta2->num) == 1000000)) || // 10^9 fold conversions ((meta2->base >= 7) && (meta1->base - meta2->base == 3) && ((meta1->num / meta2->num) == 1000000000))) { if (byteorder_may_allow_view) { *view_offset = 0; return NPY_NO_CASTING; } return NPY_EQUIV_CASTING; } else if (meta1->base == NPY_FR_GENERIC) { if (byteorder_may_allow_view) { *view_offset = 0; } return NPY_SAFE_CASTING ; } else if (meta2->base == NPY_FR_GENERIC) { /* TODO: This is actually an invalid cast (casting will error) */ return NPY_UNSAFE_CASTING; } else if (is_timedelta && ( /* jump between time units and date units is unsafe for timedelta */ (meta1->base <= NPY_FR_M && meta2->base > NPY_FR_M) || (meta1->base > NPY_FR_M && meta2->base <= NPY_FR_M))) { return NPY_UNSAFE_CASTING; } else if (meta1->base <= meta2->base) { /* Casting to a more precise unit is currently considered safe */ if (datetime_metadata_divides(meta1, meta2, is_timedelta)) { /* If it divides, we consider it to be a safe cast */ return NPY_SAFE_CASTING; } else { return NPY_SAME_KIND_CASTING; } } return NPY_SAME_KIND_CASTING; } static int time_to_time_get_loop( PyArrayMethod_Context *context, int aligned, int NPY_UNUSED(move_references), npy_intp *strides, PyArrayMethod_StridedLoop **out_loop, NpyAuxData **out_transferdata, NPY_ARRAYMETHOD_FLAGS *flags) { int requires_wrap = 0; int inner_aligned = aligned; PyArray_Descr **descrs = context->descriptors; *flags = NPY_METH_NO_FLOATINGPOINT_ERRORS; PyArray_DatetimeMetaData *meta1 = get_datetime_metadata_from_dtype(descrs[0]); PyArray_DatetimeMetaData *meta2 = get_datetime_metadata_from_dtype(descrs[1]); if (meta1->base == meta2->base && meta1->num == meta2->num) { /* * If the metadata matches, use the low-level copy or copy-swap * functions. (If they do not match, but swapping is necessary this * path is hit recursively.) */ if (PyDataType_ISNOTSWAPPED(descrs[0]) == PyDataType_ISNOTSWAPPED(descrs[1])) { *out_loop = PyArray_GetStridedCopyFn( aligned, strides[0], strides[1], NPY_SIZEOF_DATETIME); } else { *out_loop = PyArray_GetStridedCopySwapFn( aligned, strides[0], strides[1], NPY_SIZEOF_DATETIME); } return 0; } if (!PyDataType_ISNOTSWAPPED(descrs[0]) || !PyDataType_ISNOTSWAPPED(descrs[1])) { inner_aligned = 1; requires_wrap = 1; } if (get_nbo_cast_datetime_transfer_function( inner_aligned, descrs[0], descrs[1], out_loop, out_transferdata) == NPY_FAIL) { return -1; } if (!requires_wrap) { return 0; } PyArray_Descr *src_wrapped_dtype = NPY_DT_CALL_ensure_canonical(descrs[0]); PyArray_Descr *dst_wrapped_dtype = NPY_DT_CALL_ensure_canonical(descrs[1]); int needs_api = 0; int res = wrap_aligned_transferfunction( aligned, 0, strides[0], strides[1], descrs[0], descrs[1], src_wrapped_dtype, dst_wrapped_dtype, out_loop, out_transferdata, &needs_api); Py_DECREF(src_wrapped_dtype); Py_DECREF(dst_wrapped_dtype); assert(needs_api == 0); return res; } /* Handles datetime<->timedelta type resolution (both directions) */ static NPY_CASTING datetime_to_timedelta_resolve_descriptors( PyArrayMethodObject *NPY_UNUSED(self), PyArray_DTypeMeta *dtypes[2], PyArray_Descr *given_descrs[2], PyArray_Descr *loop_descrs[2], npy_intp *NPY_UNUSED(view_offset)) { loop_descrs[0] = NPY_DT_CALL_ensure_canonical(given_descrs[0]); if (loop_descrs[0] == NULL) { return -1; } if (given_descrs[1] == NULL) { PyArray_DatetimeMetaData *meta = get_datetime_metadata_from_dtype(given_descrs[0]); assert(meta != NULL); loop_descrs[1] = create_datetime_dtype(dtypes[1]->type_num, meta); } else { loop_descrs[1] = NPY_DT_CALL_ensure_canonical(given_descrs[1]); } if (loop_descrs[1] == NULL) { Py_DECREF(loop_descrs[0]); return -1; } /* * Mostly NPY_UNSAFE_CASTING is not true, the cast will fail. * TODO: Once ufuncs use dtype specific promotion rules, * this is likely unnecessary */ return NPY_UNSAFE_CASTING; } /* In the current setup both strings and unicode casts support all outputs */ static NPY_CASTING time_to_string_resolve_descriptors( PyArrayMethodObject *NPY_UNUSED(self), PyArray_DTypeMeta *dtypes[2], PyArray_Descr **given_descrs, PyArray_Descr **loop_descrs, npy_intp *NPY_UNUSED(view_offset)) { if (given_descrs[1] != NULL && dtypes[0]->type_num == NPY_DATETIME) { /* * At the time of writing, NumPy does not check the length here, * but will error if filling fails. */ Py_INCREF(given_descrs[1]); loop_descrs[1] = given_descrs[1]; } else { /* Find the correct string length, possibly based on the unit */ int size; if (given_descrs[0]->type_num == NPY_DATETIME) { PyArray_DatetimeMetaData *meta = get_datetime_metadata_from_dtype(given_descrs[0]); assert(meta != NULL); size = get_datetime_iso_8601_strlen(0, meta->base); } else { /* * This is arguably missing space for the unit, e.g. for: * `np.timedelta64(1231234342124, 'ms')` */ size = 21; } if (dtypes[1]->type_num == NPY_UNICODE) { size *= 4; } loop_descrs[1] = PyArray_DescrNewFromType(dtypes[1]->type_num); if (loop_descrs[1] == NULL) { return -1; } loop_descrs[1]->elsize = size; } loop_descrs[0] = NPY_DT_CALL_ensure_canonical(given_descrs[0]); if (loop_descrs[0] == NULL) { Py_DECREF(loop_descrs[1]); return -1; } return NPY_UNSAFE_CASTING; } static int datetime_to_string_get_loop( PyArrayMethod_Context *context, int aligned, int NPY_UNUSED(move_references), npy_intp *strides, PyArrayMethod_StridedLoop **out_loop, NpyAuxData **out_transferdata, NPY_ARRAYMETHOD_FLAGS *flags) { PyArray_Descr **descrs = context->descriptors; *flags = context->method->flags & NPY_METH_RUNTIME_FLAGS; if (descrs[1]->type_num == NPY_STRING) { if (get_nbo_datetime_to_string_transfer_function( descrs[0], descrs[1], out_loop, out_transferdata) == NPY_FAIL) { return -1; } } else { assert(descrs[1]->type_num == NPY_UNICODE); int out_needs_api; if (get_datetime_to_unicode_transfer_function( aligned, strides[0], strides[1], descrs[0], descrs[1], out_loop, out_transferdata, &out_needs_api) == NPY_FAIL) { return -1; } } return 0; } static NPY_CASTING string_to_datetime_cast_resolve_descriptors( PyArrayMethodObject *NPY_UNUSED(self), PyArray_DTypeMeta *dtypes[2], PyArray_Descr *given_descrs[2], PyArray_Descr *loop_descrs[2], npy_intp *NPY_UNUSED(view_offset)) { if (given_descrs[1] == NULL) { /* NOTE: This doesn't actually work, and will error during the cast */ loop_descrs[1] = NPY_DT_CALL_default_descr(dtypes[1]); if (loop_descrs[1] == NULL) { return -1; } } else { loop_descrs[1] = NPY_DT_CALL_ensure_canonical(given_descrs[1]); if (loop_descrs[1] == NULL) { return -1; } } /* We currently support byte-swapping, so any (unicode) string is OK */ Py_INCREF(given_descrs[0]); loop_descrs[0] = given_descrs[0]; return NPY_UNSAFE_CASTING; } static int string_to_datetime_cast_get_loop( PyArrayMethod_Context *context, int aligned, int NPY_UNUSED(move_references), npy_intp *strides, PyArrayMethod_StridedLoop **out_loop, NpyAuxData **out_transferdata, NPY_ARRAYMETHOD_FLAGS *flags) { PyArray_Descr **descrs = context->descriptors; *flags = context->method->flags & NPY_METH_RUNTIME_FLAGS; if (descrs[0]->type_num == NPY_STRING) { if (get_nbo_string_to_datetime_transfer_function( descrs[0], descrs[1], out_loop, out_transferdata) == NPY_FAIL) { return -1; } } else { assert(descrs[0]->type_num == NPY_UNICODE); int out_needs_api; if (get_unicode_to_datetime_transfer_function( aligned, strides[0], strides[1], descrs[0], descrs[1], out_loop, out_transferdata, &out_needs_api) == NPY_FAIL) { return -1; } } return 0; } /* * This registers the castingimpl for all datetime related casts. */ NPY_NO_EXPORT int PyArray_InitializeDatetimeCasts() { int result = -1; PyType_Slot slots[3]; PyArray_DTypeMeta *dtypes[2]; PyArrayMethod_Spec spec = { .name = "datetime_casts", .nin = 1, .nout = 1, .casting = NPY_UNSAFE_CASTING, .flags = NPY_METH_SUPPORTS_UNALIGNED, .dtypes = dtypes, .slots = slots, }; slots[0].slot = NPY_METH_resolve_descriptors; slots[0].pfunc = &time_to_time_resolve_descriptors; slots[1].slot = NPY_METH_get_loop; slots[1].pfunc = &time_to_time_get_loop; slots[2].slot = 0; slots[2].pfunc = NULL; PyArray_DTypeMeta *datetime = PyArray_DTypeFromTypeNum(NPY_DATETIME); PyArray_DTypeMeta *timedelta = PyArray_DTypeFromTypeNum(NPY_TIMEDELTA); PyArray_DTypeMeta *string = PyArray_DTypeFromTypeNum(NPY_STRING); PyArray_DTypeMeta *unicode = PyArray_DTypeFromTypeNum(NPY_UNICODE); PyArray_DTypeMeta *tmp = NULL; dtypes[0] = datetime; dtypes[1] = datetime; if (PyArray_AddCastingImplementation_FromSpec(&spec, 1) < 0) { goto fail; } dtypes[0] = timedelta; dtypes[1] = timedelta; if (PyArray_AddCastingImplementation_FromSpec(&spec, 1) < 0) { goto fail; } /* * Casting between timedelta and datetime uses legacy casting loops, but * custom dtype resolution (to handle copying of the time unit). */ spec.flags = NPY_METH_REQUIRES_PYAPI; slots[0].slot = NPY_METH_resolve_descriptors; slots[0].pfunc = &datetime_to_timedelta_resolve_descriptors; slots[1].slot = NPY_METH_get_loop; slots[1].pfunc = &legacy_cast_get_strided_loop; slots[2].slot = 0; slots[2].pfunc = NULL; spec.name = "timedelta_and_datetime_cast"; dtypes[0] = timedelta; dtypes[1] = datetime; if (PyArray_AddCastingImplementation_FromSpec(&spec, 1) < 0) { goto fail; } spec.name = "datetime_to_timedelta_cast"; dtypes[0] = datetime; dtypes[1] = timedelta; if (PyArray_AddCastingImplementation_FromSpec(&spec, 1) < 0) { goto fail; } /* * Cast from numeric types to times. These use the cast functions * as stored on the datatype, which should be replaced at some point. * Some of these casts can fail (casting to unitless datetime), but these * are rather special. */ for (int num = 0; num < NPY_NTYPES; num++) { if (!PyTypeNum_ISNUMBER(num) && num != NPY_BOOL) { continue; } Py_XSETREF(tmp, PyArray_DTypeFromTypeNum(num)); if (PyArray_AddLegacyWrapping_CastingImpl( tmp, datetime, NPY_UNSAFE_CASTING) < 0) { goto fail; } if (PyArray_AddLegacyWrapping_CastingImpl( datetime, tmp, NPY_UNSAFE_CASTING) < 0) { goto fail; } NPY_CASTING to_timedelta_casting = NPY_UNSAFE_CASTING; if (PyTypeNum_ISINTEGER(num) || num == NPY_BOOL) { /* timedelta casts like int64 right now... */ if (PyTypeNum_ISUNSIGNED(num) && tmp->singleton->elsize == 8) { to_timedelta_casting = NPY_SAME_KIND_CASTING; } else { to_timedelta_casting = NPY_SAFE_CASTING; } } if (PyArray_AddLegacyWrapping_CastingImpl( tmp, timedelta, to_timedelta_casting) < 0) { goto fail; } if (PyArray_AddLegacyWrapping_CastingImpl( timedelta, tmp, NPY_UNSAFE_CASTING) < 0) { goto fail; } } /* * Cast times to string and unicode */ spec.casting = NPY_UNSAFE_CASTING; /* * Casts can error and need API (unicodes needs it for string->unicode). * Unicode handling is currently implemented via a legacy cast. * Datetime->string has its own fast cast while timedelta->string uses * the legacy fallback. */ slots[0].slot = NPY_METH_resolve_descriptors; slots[0].pfunc = &time_to_string_resolve_descriptors; /* Strided loop differs for the two */ slots[1].slot = NPY_METH_get_loop; slots[2].slot = 0; slots[2].pfunc = NULL; dtypes[0] = datetime; for (int num = NPY_DATETIME; num <= NPY_TIMEDELTA; num++) { if (num == NPY_DATETIME) { dtypes[0] = datetime; spec.flags = NPY_METH_SUPPORTS_UNALIGNED | NPY_METH_REQUIRES_PYAPI; slots[1].pfunc = &datetime_to_string_get_loop; } else { dtypes[0] = timedelta; spec.flags = NPY_METH_REQUIRES_PYAPI; slots[1].pfunc = &legacy_cast_get_strided_loop; } for (int str = NPY_STRING; str <= NPY_UNICODE; str++) { dtypes[1] = PyArray_DTypeFromTypeNum(str); int res = PyArray_AddCastingImplementation_FromSpec(&spec, 1); Py_SETREF(dtypes[1], NULL); if (res < 0) { goto fail; } } } /* * Cast strings to timedelta are currently only legacy casts */ if (PyArray_AddLegacyWrapping_CastingImpl( string, timedelta, NPY_UNSAFE_CASTING) < 0) { goto fail; } if (PyArray_AddLegacyWrapping_CastingImpl( unicode, timedelta, NPY_UNSAFE_CASTING) < 0) { goto fail; } /* * Cast strings to datetime */ dtypes[1] = datetime; spec.casting = NPY_UNSAFE_CASTING; /* The default type resolution should work fine. */ slots[0].slot = NPY_METH_resolve_descriptors; slots[0].pfunc = &string_to_datetime_cast_resolve_descriptors; slots[1].slot = NPY_METH_get_loop; slots[1].pfunc = &string_to_datetime_cast_get_loop; slots[2].slot = 0; slots[2].pfunc = NULL; dtypes[0] = string; spec.flags = NPY_METH_SUPPORTS_UNALIGNED; if (PyArray_AddCastingImplementation_FromSpec(&spec, 1) < 0) { goto fail; } dtypes[0] = unicode; /* * Unicode handling is currently implemented via a legacy cast, which * requires the Python API. */ spec.flags = NPY_METH_SUPPORTS_UNALIGNED | NPY_METH_REQUIRES_PYAPI; if (PyArray_AddCastingImplementation_FromSpec(&spec, 1) < 0) { goto fail; } result = 0; fail: Py_DECREF(datetime); Py_DECREF(timedelta); Py_DECREF(string); Py_DECREF(unicode); Py_XDECREF(tmp); return result; }
{ "content_hash": "2cdd7e7b5419738983c8e4ea7a1204ad", "timestamp": "", "source": "github", "line_count": 4272, "max_line_length": 121, "avg_line_length": 29.925327715355806, "alnum_prop": 0.5203651410736775, "repo_name": "numpy/numpy", "id": "2abd68ca23f97c1784a5ee98604c7f509ae06c4f", "size": "128038", "binary": false, "copies": "2", "ref": "refs/heads/main", "path": "numpy/core/src/multiarray/datetime.c", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "C", "bytes": "5997418" }, { "name": "C++", "bytes": "212906" }, { "name": "Cython", "bytes": "146258" }, { "name": "D", "bytes": "19" }, { "name": "Dockerfile", "bytes": "5266" }, { "name": "Forth", "bytes": "3787" }, { "name": "Fortran", "bytes": "24695" }, { "name": "Makefile", "bytes": "1697" }, { "name": "Python", "bytes": "10567678" }, { "name": "Shell", "bytes": "26767" }, { "name": "Smarty", "bytes": "4104" }, { "name": "sed", "bytes": "5741" } ], "symlink_target": "" }
// ---------------------------------------------------------------------------------- // Copyright Microsoft Corporation // 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. // ---------------------------------------------------------------------------------- namespace DurableTask.Samples.Replat { using System; using System.Threading.Tasks; public interface IManagementSqlOrchestrationTasks { Task<Application[]> GetApplicationNames(string subscriptionId); Task<bool> UpsertSubscriptionLock(string subscriptionId, bool isLocked); } public class ManagementSqlOrchestrationTasks : IManagementSqlOrchestrationTasks { public Task<Application[]> GetApplicationNames(string subscriptionId) { var applications = new[] { new Application { Name = "App1", SiteName = "App1", Platform = RuntimePlatform.Node, Region = "West US" }, new Application { Name = "App2", SiteName = "App2", Platform = RuntimePlatform.Node, Region = "West US" }, new Application { Name = "App3", SiteName = "App3", Platform = RuntimePlatform.Node, Region = "West US" }, new Application { Name = "App4", SiteName = "App4", Platform = RuntimePlatform.Node, Region = "West US" }, new Application { Name = "App5", SiteName = "App5", Platform = RuntimePlatform.Node, Region = "West US" }, new Application { Name = "App6", SiteName = "App6", Platform = RuntimePlatform.Node, Region = "West US" }, new Application { Name = "App7", SiteName = "App7", Platform = RuntimePlatform.Node, Region = "West US" }, new Application { Name = "App8", SiteName = "App8", Platform = RuntimePlatform.Node, Region = "West US" }, new Application { Name = "App9", SiteName = "App9", Platform = RuntimePlatform.Node, Region = "West US" }, new Application { Name = "App10", SiteName = "App10", Platform = RuntimePlatform.Node, Region = "West US" }, new Application { Name = "App11", SiteName = "App11", Platform = RuntimePlatform.Node, Region = "West US" }, new Application { Name = "App12", SiteName = "App12", Platform = RuntimePlatform.Node, Region = "West US" }, new Application { Name = "App13", SiteName = "App13", Platform = RuntimePlatform.Node, Region = "West US" }, new Application { Name = "App14", SiteName = "App14", Platform = RuntimePlatform.Node, Region = "West US" }, new Application { Name = "App15", SiteName = "App15", Platform = RuntimePlatform.Node, Region = "West US" }, new Application { Name = "App16", SiteName = "App16", Platform = RuntimePlatform.Node, Region = "West US" }, new Application { Name = "App17", SiteName = "App17", Platform = RuntimePlatform.Node, Region = "West US" }, new Application { Name = "App18", SiteName = "App18", Platform = RuntimePlatform.Node, Region = "West US" }, new Application { Name = "App19", SiteName = "App19", Platform = RuntimePlatform.Node, Region = "West US" }, new Application { Name = "App20", SiteName = "App20", Platform = RuntimePlatform.Node, Region = "West US" }, }; return Task.FromResult(applications); } public Task<bool> UpsertSubscriptionLock(string subscriptionId, bool isLocked) { Console.WriteLine($"Upsert Subscription Lock called for SubId '{subscriptionId}' with value '{isLocked}'"); return Task.FromResult(true); } } }
{ "content_hash": "74f00650417209256dad918f9d133885", "timestamp": "", "source": "github", "line_count": 64, "max_line_length": 124, "avg_line_length": 64.765625, "alnum_prop": 0.6074788902291918, "repo_name": "Azure/durabletask", "id": "4d0ea6027ee37fb4d787cc2f5c79bd4239991d08", "size": "4147", "binary": false, "copies": "2", "ref": "refs/heads/main", "path": "samples/DurableTask.Samples/Replat/ManagementSqlOrchestrationTasks.cs", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "C#", "bytes": "3219344" }, { "name": "PowerShell", "bytes": "8880" } ], "symlink_target": "" }
class UniqueLogin < ActiveRecord::Migration def self.up add_index(:users, :login, :unique => true) end def self.down remove_index(:users, :login) end end
{ "content_hash": "e79338bf2f3e5602f2388e7ac8cda928", "timestamp": "", "source": "github", "line_count": 9, "max_line_length": 45, "avg_line_length": 18.77777777777778, "alnum_prop": 0.6804733727810651, "repo_name": "birdstack/birdstack", "id": "1b2789ebcfd623ab2b402260254296ba99c11fba", "size": "169", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "db/migrate/011_unique_login.rb", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "JavaScript", "bytes": "1751" }, { "name": "Perl", "bytes": "387" }, { "name": "Ruby", "bytes": "623204" }, { "name": "Shell", "bytes": "7256" } ], "symlink_target": "" }
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <!-- NewPage --> <html lang="en"> <head> <!-- Generated by javadoc (1.8.0_131) on Tue Aug 01 18:04:58 MSK 2017 --> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>ProgressCallback (GLMap 0.8.13)</title> <meta name="date" content="2017-08-01"> <link rel="stylesheet" type="text/css" href="../../stylesheet.css" title="Style"> <script type="text/javascript" src="../../script.js"></script> </head> <body> <script type="text/javascript"><!-- try { if (location.href.indexOf('is-external=true') == -1) { parent.document.title="ProgressCallback (GLMap 0.8.13)"; } } catch(err) { } //--> var methods = {"i0":6}; var tabs = {65535:["t0","All Methods"],2:["t2","Instance Methods"],4:["t3","Abstract Methods"]}; var altColor = "altColor"; var rowColor = "rowColor"; var tableTab = "tableTab"; var activeTableTab = "activeTableTab"; </script> <noscript> <div>JavaScript is disabled on your browser.</div> </noscript> <!-- ========= START OF TOP NAVBAR ======= --> <div class="topNav"><a name="navbar.top"> <!-- --> </a> <div class="skipNav"><a href="#skip.navbar.top" title="Skip navigation links">Skip navigation links</a></div> <a name="navbar.top.firstrow"> <!-- --> </a> <ul class="navList" title="Navigation"> <li><a href="../../com/glmapview/package-summary.html">Package</a></li> <li class="navBarCell1Rev">Class</li> <li><a href="package-tree.html">Tree</a></li> <li><a href="../../deprecated-list.html">Deprecated</a></li> <li><a href="../../index-all.html">Index</a></li> <li><a href="../../help-doc.html">Help</a></li> </ul> </div> <div class="subNav"> <ul class="navList"> <li><a href="../../com/glmapview/MapPoint.html" title="class in com.glmapview"><span class="typeNameLink">Prev&nbsp;Class</span></a></li> <li>Next&nbsp;Class</li> </ul> <ul class="navList"> <li><a href="../../index.html?com/glmapview/ProgressCallback.html" target="_top">Frames</a></li> <li><a href="ProgressCallback.html" target="_top">No&nbsp;Frames</a></li> </ul> <ul class="navList" id="allclasses_navbar_top"> <li><a href="../../allclasses-noframe.html">All&nbsp;Classes</a></li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_top"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } //--> </script> </div> <div> <ul class="subNavList"> <li>Summary:&nbsp;</li> <li>Nested&nbsp;|&nbsp;</li> <li>Field&nbsp;|&nbsp;</li> <li>Constr&nbsp;|&nbsp;</li> <li><a href="#method.summary">Method</a></li> </ul> <ul class="subNavList"> <li>Detail:&nbsp;</li> <li>Field&nbsp;|&nbsp;</li> <li>Constr&nbsp;|&nbsp;</li> <li><a href="#method.detail">Method</a></li> </ul> </div> <a name="skip.navbar.top"> <!-- --> </a></div> <!-- ========= END OF TOP NAVBAR ========= --> <!-- ======== START OF CLASS DATA ======== --> <div class="header"> <div class="subTitle">com.glmapview</div> <h2 title="Interface ProgressCallback" class="title">Interface ProgressCallback</h2> </div> <div class="contentContainer"> <div class="description"> <ul class="blockList"> <li class="blockList"> <hr> <br> <pre>public interface <span class="typeNameLabel">ProgressCallback</span></pre> <div class="block">Called to notify about GLMapManager initialization progress updates</div> </li> </ul> </div> <div class="summary"> <ul class="blockList"> <li class="blockList"> <!-- ========== METHOD SUMMARY =========== --> <ul class="blockList"> <li class="blockList"><a name="method.summary"> <!-- --> </a> <h3>Method Summary</h3> <table class="memberSummary" border="0" cellpadding="3" cellspacing="0" summary="Method Summary table, listing methods, and an explanation"> <caption><span id="t0" class="activeTableTab"><span>All Methods</span><span class="tabEnd">&nbsp;</span></span><span id="t2" class="tableTab"><span><a href="javascript:show(2);">Instance Methods</a></span><span class="tabEnd">&nbsp;</span></span><span id="t3" class="tableTab"><span><a href="javascript:show(4);">Abstract Methods</a></span><span class="tabEnd">&nbsp;</span></span></caption> <tr> <th class="colFirst" scope="col">Modifier and Type</th> <th class="colLast" scope="col">Method and Description</th> </tr> <tr id="i0" class="altColor"> <td class="colFirst"><code>void</code></td> <td class="colLast"><code><span class="memberNameLink"><a href="../../com/glmapview/ProgressCallback.html#progress-double-">progress</a></span>(double&nbsp;k)</code>&nbsp;</td> </tr> </table> </li> </ul> </li> </ul> </div> <div class="details"> <ul class="blockList"> <li class="blockList"> <!-- ============ METHOD DETAIL ========== --> <ul class="blockList"> <li class="blockList"><a name="method.detail"> <!-- --> </a> <h3>Method Detail</h3> <a name="progress-double-"> <!-- --> </a> <ul class="blockListLast"> <li class="blockList"> <h4>progress</h4> <pre>void&nbsp;progress(double&nbsp;k)</pre> </li> </ul> </li> </ul> </li> </ul> </div> </div> <!-- ========= END OF CLASS DATA ========= --> <!-- ======= START OF BOTTOM NAVBAR ====== --> <div class="bottomNav"><a name="navbar.bottom"> <!-- --> </a> <div class="skipNav"><a href="#skip.navbar.bottom" title="Skip navigation links">Skip navigation links</a></div> <a name="navbar.bottom.firstrow"> <!-- --> </a> <ul class="navList" title="Navigation"> <li><a href="../../com/glmapview/package-summary.html">Package</a></li> <li class="navBarCell1Rev">Class</li> <li><a href="package-tree.html">Tree</a></li> <li><a href="../../deprecated-list.html">Deprecated</a></li> <li><a href="../../index-all.html">Index</a></li> <li><a href="../../help-doc.html">Help</a></li> </ul> </div> <div class="subNav"> <ul class="navList"> <li><a href="../../com/glmapview/MapPoint.html" title="class in com.glmapview"><span class="typeNameLink">Prev&nbsp;Class</span></a></li> <li>Next&nbsp;Class</li> </ul> <ul class="navList"> <li><a href="../../index.html?com/glmapview/ProgressCallback.html" target="_top">Frames</a></li> <li><a href="ProgressCallback.html" target="_top">No&nbsp;Frames</a></li> </ul> <ul class="navList" id="allclasses_navbar_bottom"> <li><a href="../../allclasses-noframe.html">All&nbsp;Classes</a></li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_bottom"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } //--> </script> </div> <div> <ul class="subNavList"> <li>Summary:&nbsp;</li> <li>Nested&nbsp;|&nbsp;</li> <li>Field&nbsp;|&nbsp;</li> <li>Constr&nbsp;|&nbsp;</li> <li><a href="#method.summary">Method</a></li> </ul> <ul class="subNavList"> <li>Detail:&nbsp;</li> <li>Field&nbsp;|&nbsp;</li> <li>Constr&nbsp;|&nbsp;</li> <li><a href="#method.detail">Method</a></li> </ul> </div> <a name="skip.navbar.bottom"> <!-- --> </a></div> <!-- ======== END OF BOTTOM NAVBAR ======= --> <p class="legalCopy"><small><i>Copyright &#169; 2017 GetYourMap. All Rights Reserved.</i></small></p> </body> </html>
{ "content_hash": "1fda95855c49311e785e684ab51a6e65", "timestamp": "", "source": "github", "line_count": 220, "max_line_length": 391, "avg_line_length": 32.42727272727273, "alnum_prop": 0.6323240818615082, "repo_name": "charlenni/Xam-GLMap-Android", "id": "082d81998730a53ed17d80420e71af416a9bf648", "size": "7134", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "Xam-GLMap-Android/JavaDoc/glmap-0.8.12/com/glmapview/ProgressCallback.html", "mode": "33188", "license": "mit", "language": [ { "name": "C#", "bytes": "67297" }, { "name": "CSS", "bytes": "12842" }, { "name": "HTML", "bytes": "849016" }, { "name": "JavaScript", "bytes": "827" } ], "symlink_target": "" }
using System; using System.Collections.Generic; using System.IO; namespace HackerRank { // https://www.hackerrank.com/challenges/insertionsort1 public class Solution2 { static void Main(String[] args) { int _ar_size; _ar_size = Convert.ToInt32(Console.ReadLine()); int[] _ar = new int[_ar_size]; String elements = Console.ReadLine(); String[] split_elements = elements.Split(' '); for (int _ar_i = 0; _ar_i < _ar_size; _ar_i++) { _ar[_ar_i] = Convert.ToInt32(split_elements[_ar_i]); } insertionSort(_ar); } public static int NumberOfSwaps { get; set; } //challenge for running time public static void insertionSort(int[] ar) { TestableInsertionSort(ar); } public static int[] TestableInsertionSort(int[] ar) { NumberOfSwaps = 0; for (int i = 0; i < ar.Length; i++) { ar = SwapToLeftUntilSorted(i, ar); } Console.WriteLine(NumberOfSwaps.ToString()); //challenge for running time return ar; } public static int[] SwapToLeftUntilSorted(int index, int[] input) { if (index == 0) { return input; } var currentNumber = input[index]; var sortedArray = input; for (int i = index; i > 0; i--) { var numberToLeft = sortedArray[i - 1]; if (currentNumber < numberToLeft) { //swap sortedArray[i - 1] = currentNumber; sortedArray[i] = numberToLeft; NumberOfSwaps++; } else if (currentNumber >= numberToLeft) { //break break; } } //Console.WriteLine(string.Join(" ", sortedArray)); return sortedArray; } } }
{ "content_hash": "ee87c1262dbe06ef4ada673286fee40c", "timestamp": "", "source": "github", "line_count": 76, "max_line_length": 76, "avg_line_length": 20.82894736842105, "alnum_prop": 0.6216045483259633, "repo_name": "blong145/HackerRank-Practice", "id": "948d1a858e7e8da2c7c60193e5badca4d59da6c6", "size": "1585", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "HackerRank/InsertionSortPart2/InsertionSortPart2.cs", "mode": "33188", "license": "mit", "language": [ { "name": "C#", "bytes": "8787" } ], "symlink_target": "" }
package dk.netdesign.common.osgi.config.wicket.fragment; import dk.netdesign.common.osgi.config.Attribute; import org.apache.wicket.Component; import org.apache.wicket.MarkupContainer; import org.apache.wicket.markup.html.form.TextField; import org.apache.wicket.model.IModel; /** * * @author mnn */ public class TextFieldFragment extends InputFragment<String>{ public TextFieldFragment(String id, String markupId, MarkupContainer markupProvider, Attribute attribute, String panelFormInputID, String panelSmallLabelID, IModel<String> model) { super(id, markupId, markupProvider, attribute, panelFormInputID, panelSmallLabelID, model); } @Override protected Component getFormInput(String wicketID, IModel<String> model) { return new TextField(wicketID, model); } }
{ "content_hash": "2c422085cf44aebfd9476a2fe6fb5e8f", "timestamp": "", "source": "github", "line_count": 27, "max_line_length": 184, "avg_line_length": 30.48148148148148, "alnum_prop": 0.7594167679222357, "repo_name": "TDC-Netdesign/ManagedProperties", "id": "be4222c84c52cfeb61fc066baae4903a8d5161ce", "size": "1411", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "managedproperties-wicket/src/main/java/dk/netdesign/common/osgi/config/wicket/fragment/TextFieldFragment.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "HTML", "bytes": "4208" }, { "name": "Java", "bytes": "318128" } ], "symlink_target": "" }
namespace cc { BitmapContentLayerUpdater::Resource::Resource(BitmapContentLayerUpdater* updater, scoped_ptr<PrioritizedTexture> texture) : LayerUpdater::Resource(texture.Pass()) , m_updater(updater) { } BitmapContentLayerUpdater::Resource::~Resource() { } void BitmapContentLayerUpdater::Resource::update(ResourceUpdateQueue& queue, const IntRect& sourceRect, const IntSize& destOffset, bool partialUpdate, RenderingStats&) { updater()->updateTexture(queue, texture(), sourceRect, destOffset, partialUpdate); } scoped_refptr<BitmapContentLayerUpdater> BitmapContentLayerUpdater::create(scoped_ptr<LayerPainter> painter) { return make_scoped_refptr(new BitmapContentLayerUpdater(painter.Pass())); } BitmapContentLayerUpdater::BitmapContentLayerUpdater(scoped_ptr<LayerPainter> painter) : ContentLayerUpdater(painter.Pass()) , m_opaque(false) { } BitmapContentLayerUpdater::~BitmapContentLayerUpdater() { } scoped_ptr<LayerUpdater::Resource> BitmapContentLayerUpdater::createResource(PrioritizedTextureManager* manager) { return scoped_ptr<LayerUpdater::Resource>(new Resource(this, PrioritizedTexture::create(manager))); } void BitmapContentLayerUpdater::prepareToUpdate(const IntRect& contentRect, const IntSize& tileSize, float contentsWidthScale, float contentsHeightScale, IntRect& resultingOpaqueRect, RenderingStats& stats) { if (m_canvasSize != contentRect.size()) { m_canvasSize = contentRect.size(); m_canvas = make_scoped_ptr(skia::CreateBitmapCanvas(m_canvasSize.width(), m_canvasSize.height(), m_opaque)); } paintContents(m_canvas.get(), contentRect, contentsWidthScale, contentsHeightScale, resultingOpaqueRect, stats); } void BitmapContentLayerUpdater::updateTexture(ResourceUpdateQueue& queue, PrioritizedTexture* texture, const IntRect& sourceRect, const IntSize& destOffset, bool partialUpdate) { ResourceUpdate upload = ResourceUpdate::Create( texture, &m_canvas->getDevice()->accessBitmap(false), contentRect(), sourceRect, destOffset); if (partialUpdate) queue.appendPartialUpload(upload); else queue.appendFullUpload(upload); } void BitmapContentLayerUpdater::setOpaque(bool opaque) { if (opaque != m_opaque) { m_canvas.reset(); m_canvasSize = IntSize(); } m_opaque = opaque; } } // namespace cc
{ "content_hash": "a66cec5bb9f97fa039b106a57c358508", "timestamp": "", "source": "github", "line_count": 71, "max_line_length": 206, "avg_line_length": 33.521126760563384, "alnum_prop": 0.7504201680672269, "repo_name": "junmin-zhu/chromium-rivertrail", "id": "66828ff772fad1d0ba5450020dcf0238e16d97a3", "size": "2752", "binary": false, "copies": "1", "ref": "refs/heads/v8-binding", "path": "cc/bitmap_content_layer_updater.cc", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "ASP", "bytes": "853" }, { "name": "AppleScript", "bytes": "6973" }, { "name": "Arduino", "bytes": "464" }, { "name": "Assembly", "bytes": "1172794" }, { "name": "Awk", "bytes": "9519" }, { "name": "C", "bytes": "75806807" }, { "name": "C#", "bytes": "1132" }, { "name": "C++", "bytes": "145161929" }, { "name": "DOT", "bytes": "1559" }, { "name": "F#", "bytes": "381" }, { "name": "Java", "bytes": "1546515" }, { "name": "JavaScript", "bytes": "18675242" }, { "name": "Logos", "bytes": "4517" }, { "name": "Matlab", "bytes": "5234" }, { "name": "Objective-C", "bytes": "6981387" }, { "name": "PHP", "bytes": "97817" }, { "name": "Perl", "bytes": "926245" }, { "name": "Python", "bytes": "8088373" }, { "name": "R", "bytes": "262" }, { "name": "Ragel in Ruby Host", "bytes": "3239" }, { "name": "Shell", "bytes": "1513486" }, { "name": "Tcl", "bytes": "277077" }, { "name": "XML", "bytes": "13493" } ], "symlink_target": "" }
package main import "fmt" import "time" import "crypto/cipher" import "crypto/aes" import sslAES "github.com/shanemhansen/gossl/crypto/aes" func bench_aes128(h *cipher.Block, msg string) { bufsize := 102400 iterations := 10000 src := make([]byte, bufsize) dst := make([]byte, bufsize) t := time.Now() for i := 0; i < iterations; i++ { (*h).Encrypt(src, dst) (*h).Encrypt(dst, src) } fmt.Printf("%s took %s to process %d mb\n", msg, time.Since(t), bufsize*iterations/1024/1024) } func main() { fmt.Println("This program benchmarks crypto/aes and aes/aes implementations") k := []byte("1234567890123456") h, _ := aes.NewCipher(k) bench_aes128(&h, "crypto/aes") ssl, _ := sslAES.NewCipher(k) bench_aes128(&ssl, "ssl/aes") }
{ "content_hash": "5f5c270854cb2b6bdf4e297d7cfaa1b8", "timestamp": "", "source": "github", "line_count": 29, "max_line_length": 94, "avg_line_length": 25.586206896551722, "alnum_prop": 0.6684636118598383, "repo_name": "shanemhansen/gossl", "id": "68c3ee6cab5a41e3d1df63faeee76a37f4ccff9f", "size": "742", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "examples/bench_aes128/bench_aes128.go", "mode": "33188", "license": "mit", "language": [ { "name": "C", "bytes": "10898" }, { "name": "Go", "bytes": "175464" } ], "symlink_target": "" }
package com.hauldata.dbpa.task.expression; import com.hauldata.dbpa.expression.Expression; import com.hauldata.dbpa.file.FileHandler; import com.hauldata.dbpa.file.FileIdentifier; import com.hauldata.dbpa.file.PageIdentifier; import com.hauldata.dbpa.process.Context; public class FileIdentifierExpression extends PhysicalPageIdentifierExpression { public FileIdentifierExpression(FileHandler handler, Expression<String> filePath) { super(handler, filePath); } @Override public PageIdentifier evaluate(Context context, boolean writeNotRead) { return new FileIdentifier(handler, context.getDataPath(getEvaluatedFilePath(), writeNotRead)); } }
{ "content_hash": "b341638964ae054ddf2e47f005d1c558", "timestamp": "", "source": "github", "line_count": 21, "max_line_length": 96, "avg_line_length": 31.285714285714285, "alnum_prop": 0.8234398782343988, "repo_name": "rdesantis/hauldata", "id": "b9e00709c10a3028d621d8c1c7606567f941360e", "size": "1263", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "dbpa/src/main/java/com/hauldata/dbpa/task/expression/FileIdentifierExpression.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Batchfile", "bytes": "89" }, { "name": "Java", "bytes": "1514300" } ], "symlink_target": "" }
本期周报内容来自: [新宁](https://github.com/SSSSSSnail), [桉远](https://github.com/AnYuan)。 周报汇总 [地址](https://github.com/BaiduHiDeviOS/iOS-Tech-Weekly) 周报博客 [地址](http://baiduhidevios.github.io/) ### swift: [Swift Programming Language Evolution: Proposal Status](http://apple.github.io/swift-evolution/): 查看proposals的状态 [Writing High-Performance Swift Code](https://github.com/apple/swift/blob/master/docs/OptimizationTips.rst) [Migrating to swift 3](http://www.jessesquires.com/migrating-to-swift-3/) [Swift 3 Grand Central Dispatch](https://medium.com/swift-and-ios-writing/a-quick-look-at-gcd-and-swift-3-732bef6e1838#.bhqrecmpq): Swift 3中GCD的变化 ### 单测 [Asynchronous Testing](https://medium.com/swift-programming/asynchronous-testing-e52db1b9b1fb#.ezgeue1i3) ### Xcode新特性 [xcode visual memory debugger](http://useyourloaf.com/blog/xcode-visual-memory-debugger/) ### iOS新特性 [iOS 10 适配](https://github.com/ChenYilong/iOS10AdaptationTips) ### 技术实践 [理解iOS的内存管理](http://blog.devtang.com/2016/07/30/ios-memory-management/) ### 开源代码: [RMPZoomTransitionAnimator](https://github.com/recruit-mp/RMPZoomTransitionAnimator): A custom zooming transition animation for UIViewController [Translucid](https://github.com/Ekhoo/Translucid): Lightweight library to set an Image as text background. Written in swift. [Zip](https://github.com/marmelroy/Zip): Swift framework for zipping and unzipping files. [AspectFillFaceAware](https://github.com/BeauNouvelle/AspectFillFaceAware): An extension that gives UIImageView the ability to focus on faces within an image when using AspectFill. [LTMorphingLabel](https://github.com/lexrus/LTMorphingLabel): Graceful morphing effects for UILabel written in Swift. [objc2swift](https://github.com/yahoojapan/objc2swift): Open Source Obj-C to Swift Converter. http://objc2swift.yahoo-labs.jp ### 工具 [dSYMTools](https://github.com/answer-huang/dSYMTools): 开源的 dSYM 文件分析工具,可帮助开发者快速定位报错函数 [hirundo](https://stylemac.com/hirundo/): Hirundo (Latin for 'Swift') is a convenient way to browse and follow the discussions in the Swift mailing lists like Swift-Evolution or Swift-Dev. You can even bookmark messages of threads because they contain important information ### 程序员的自我修养 [A DIY COMPUTER SCIENCE EDUCATION](http://bradfieldcs.com/diy/): 应当如何自学计算机科学(CS),本文基于众多专业工程师自学的教育经验给出了一个简短的指南。 [How to be a programmer](https://github.com/braydie/HowToBeAProgrammer): A guide on how to be a Programmer - originally published by Robert L Read https://braydie.gitbooks.io/how-to-be-a-programmer/content/ ### 博客 [iOS insight](http://www.iosinsight.com/)
{ "content_hash": "6c795185f1f3e3ba5d2f82c19681ce8a", "timestamp": "", "source": "github", "line_count": 63, "max_line_length": 273, "avg_line_length": 40.98412698412698, "alnum_prop": 0.7765298218435321, "repo_name": "BaiduHiDeviOS/iOS-Tech-Weekly", "id": "63f46e47e770112d8d16c398b3433292bd41acf6", "size": "2886", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "往期周报/20160807.md", "mode": "33188", "license": "mit", "language": [ { "name": "EJS", "bytes": "13970" }, { "name": "JavaScript", "bytes": "4687" }, { "name": "Stylus", "bytes": "22960" } ], "symlink_target": "" }
<?xml version="1.0" encoding="utf-8" standalone="yes"?> <rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom"> <channel> <title>Reaper: Easy Repair Management for Apache Cassandra</title> <link>http://cassandra-reaper.io/docs/download/</link> <description>Recent content on Reaper: Easy Repair Management for Apache Cassandra</description> <generator>Hugo -- gohugo.io</generator> <language>en-us</language> <atom:link href="http://cassandra-reaper.io/docs/download/index.xml" rel="self" type="application/rss+xml" /> <item> <title></title> <link>http://cassandra-reaper.io/docs/download/building/</link> <pubDate>Mon, 01 Jan 0001 00:00:00 +0000</pubDate> <guid>http://cassandra-reaper.io/docs/download/building/</guid> <description>Building Install Packages Debian packages and RPMs can be built from this project using Make, for example: make deb make rpm Building JARs from source To build use the following command: mvn clean package Building Docker Image from source See the Docker section for more details. Building Using Docker To simplify the build toolchain it&amp;rsquo;s possible to build everything using Docker itself. This is the process used to build the release binary artifacts from jar files to debian packages.</description> </item> <item> <title></title> <link>http://cassandra-reaper.io/docs/download/docker/</link> <pubDate>Mon, 01 Jan 0001 00:00:00 +0000</pubDate> <guid>http://cassandra-reaper.io/docs/download/docker/</guid> <description>Docker Docker and Docker Compose will need to be installed in order to use the commands in this section. Building Reaper Docker Image Prerequisite The generation of the Docker image requires that the JAR file be built and placed in the src/packages directory. If the JAR package is missing from the directory then it can built using either the steps in the Docker package build section (above), or in the Building from Source section.</description> </item> <item> <title></title> <link>http://cassandra-reaper.io/docs/download/install/</link> <pubDate>Mon, 01 Jan 0001 00:00:00 +0000</pubDate> <guid>http://cassandra-reaper.io/docs/download/install/</guid> <description>Running Reaper After modifying the resource/cassandra-reaper.yaml config file, Reaper can be started using the following command line : java -jar target/cassandra-reaper-X.X.X.jar server resource/cassandra-reaper.yaml Once started, the UI can be accessed through : http://127.0.0.1:8080/webui/ Reaper can also be accessed using the REST API exposed on port 8080, or using the command line tool bin/spreaper Installing and Running as a Service We provide prebuilt packages for reaper on Cloudsmith. RPM Install (CentOS, Fedora, RHEK) Grab the RPM from GitHub and install using the rpm command:</description> </item> </channel> </rss>
{ "content_hash": "388693489285b6cc05ca3fa087ddbea6", "timestamp": "", "source": "github", "line_count": 49, "max_line_length": 343, "avg_line_length": 60.42857142857143, "alnum_prop": 0.7284701114488349, "repo_name": "thelastpickle/cassandra-reaper", "id": "92a91d4bc5ef62d0de32cd3347fc504fcc276a3d", "size": "2961", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "docs/docs/download/index.xml", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Dockerfile", "bytes": "9753" }, { "name": "EJS", "bytes": "1984" }, { "name": "Gherkin", "bytes": "40941" }, { "name": "HTML", "bytes": "1182" }, { "name": "Java", "bytes": "1634745" }, { "name": "JavaScript", "bytes": "400172" }, { "name": "Less", "bytes": "276331" }, { "name": "Makefile", "bytes": "3669" }, { "name": "Python", "bytes": "44180" }, { "name": "SCSS", "bytes": "3775" }, { "name": "Shell", "bytes": "53455" } ], "symlink_target": "" }
<?xml version="1.0"?> <package> <name>ur10_demo_descartes</name> <version>0.0.0</version> <description>The ur10_demo_descartes package</description> <maintainer email="jnicho@swri.org">Jorge Nicho</maintainer> <license>Apache2.0</license> <url type="website">https://github.com/ros-industrial/industrial_training</url> <author email="jnicho@swri.org">Jorge Nicho</author> <buildtool_depend>catkin</buildtool_depend> <build_depend>descartes_core</build_depend> <build_depend>descartes_moveit</build_depend> <build_depend>pluginlib</build_depend> <build_depend>moveit_core</build_depend> <build_depend>liblapack-dev</build_depend> <build_depend>roscpp</build_depend> <build_depend>tf_conversions</build_depend> <build_depend>ur_kinematics</build_depend> <run_depend>descartes_core</run_depend> <run_depend>descartes_moveit</run_depend> <run_depend>pluginlib</run_depend> <run_depend>moveit_core</run_depend> <run_depend>liblapack-dev</run_depend> <run_depend>roscpp</run_depend> <run_depend>tf_conversions</run_depend> <run_depend>ur_kinematics</run_depend> <export> <descartes_core plugin="${prefix}/ur10_demo_descartes_plugins.xml"/> </export> </package>
{ "content_hash": "d9f856870285b5ae0fb180ab0ede0777", "timestamp": "", "source": "github", "line_count": 35, "max_line_length": 81, "avg_line_length": 34.74285714285714, "alnum_prop": 0.7310855263157895, "repo_name": "Levi-Armstrong/industrial_training", "id": "abb8351e205c3ffa0fc332ff97954c56754cde55", "size": "1216", "binary": false, "copies": "1", "ref": "refs/heads/kinetic", "path": "exercises/5.0/src/ur10_demo_descartes/package.xml", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "C++", "bytes": "1033540" }, { "name": "CMake", "bytes": "236074" }, { "name": "CSS", "bytes": "804" }, { "name": "HTML", "bytes": "20499" }, { "name": "Makefile", "bytes": "164" }, { "name": "Python", "bytes": "30576" }, { "name": "Shell", "bytes": "5269" } ], "symlink_target": "" }
package stroom.job.impl; import stroom.test.AbstractCoreIntegrationTest; import org.junit.jupiter.api.Test; import javax.inject.Inject; class TestJobBootstrap extends AbstractCoreIntegrationTest { @Inject private JobBootstrap jobBootstrap; @Test void testStartup() { jobBootstrap.startup(); } }
{ "content_hash": "7f317206308da801307e35f86e15279a", "timestamp": "", "source": "github", "line_count": 21, "max_line_length": 60, "avg_line_length": 15.80952380952381, "alnum_prop": 0.7349397590361446, "repo_name": "gchq/stroom", "id": "edf2056062d6626e8bbb2d7d1c80ede2fdaa29c1", "size": "933", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "stroom-app/src/test/java/stroom/job/impl/TestJobBootstrap.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "272243" }, { "name": "Dockerfile", "bytes": "21009" }, { "name": "HTML", "bytes": "14114" }, { "name": "Java", "bytes": "22782925" }, { "name": "JavaScript", "bytes": "14516557" }, { "name": "Makefile", "bytes": "661" }, { "name": "Python", "bytes": "3176" }, { "name": "SCSS", "bytes": "158667" }, { "name": "Shell", "bytes": "166531" }, { "name": "TypeScript", "bytes": "2009517" }, { "name": "XSLT", "bytes": "174226" } ], "symlink_target": "" }
package vektah.rust.psi; import java.util.List; import org.jetbrains.annotations.*; import com.intellij.psi.PsiElement; public interface RustFnArgs extends PsiElement { @NotNull RustLetArgs getLetArgs(); }
{ "content_hash": "4b08e477f022b2dbec321cd1bbbf9c28", "timestamp": "", "source": "github", "line_count": 12, "max_line_length": 48, "avg_line_length": 17.833333333333332, "alnum_prop": 0.780373831775701, "repo_name": "consulo/consulo-rust", "id": "c5bc6ac0742299f269135e0e7392b3b0695db5d4", "size": "276", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "gen/vektah/rust/psi/RustFnArgs.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "672163" }, { "name": "Lex", "bytes": "11918" }, { "name": "Rust", "bytes": "9453" } ], "symlink_target": "" }
import {Services} from '#service'; import {applyFillContent, isLayoutSizeDefined} from '#core/dom/layout'; import {dashToUnderline} from '#core/types/string'; import {getData, listen} from '../../../src/event-helper'; import {getIframe, preloadBootstrap} from '../../../src/3p-frame'; import {isObject} from '#core/types'; import {listenFor} from '../../../src/iframe-helper'; import {removeElement} from '#core/dom'; import {tryParseJson} from '#core/types/object/json'; const TYPE = 'facebook'; class AmpFacebookLike extends AMP.BaseElement { /** @param {!AmpElement} element */ constructor(element) { super(element); /** @private {?HTMLIFrameElement} */ this.iframe_ = null; /** @private @const {string} */ this.dataLocale_ = element.hasAttribute('data-locale') ? element.getAttribute('data-locale') : dashToUnderline(window.navigator.language); /** @private {?Function} */ this.unlistenMessage_ = null; } /** @override */ renderOutsideViewport() { // We are conservative about loading heavy embeds. // This will still start loading before they become visible, but it // won't typically load a large number of embeds. return 0.75; } /** * @param {boolean=} opt_onLayout * @override */ preconnectCallback(opt_onLayout) { const preconnect = Services.preconnectFor(this.win); preconnect.url(this.getAmpDoc(), 'https://facebook.com', opt_onLayout); // Hosts the facebook SDK. preconnect.preload( this.getAmpDoc(), 'https://connect.facebook.net/' + this.dataLocale_ + '/sdk.js', 'script' ); preloadBootstrap(this.win, TYPE, this.getAmpDoc(), preconnect); } /** @override */ isLayoutSupported(layout) { return isLayoutSizeDefined(layout); } /** @override */ layoutCallback() { this.element.setAttribute('data-embed-as', 'like'); const iframe = getIframe(this.win, this.element, TYPE); iframe.title = this.element.title || 'Facebook like button'; applyFillContent(iframe); // Triggered by context.updateDimensions() inside the iframe. listenFor( iframe, 'embed-size', (data) => { this.attemptChangeHeight(data['height']).catch(() => { /* ignore failures */ }); }, /* opt_is3P */ true ); this.unlistenMessage_ = listen( this.win, 'message', this.handleFacebookMessages_.bind(this) ); this.toggleLoading(true); this.element.appendChild(iframe); this.iframe_ = iframe; return this.loadPromise(iframe); } /** * @param {!Event} event * @private */ handleFacebookMessages_(event) { if (this.iframe_ && event.source != this.iframe_.contentWindow) { return; } const eventData = getData(event); if (!eventData) { return; } const parsedEventData = isObject(eventData) ? eventData : tryParseJson(eventData); if (!parsedEventData) { return; } if (eventData['action'] == 'ready') { this.toggleLoading(false); } } /** @override */ unlayoutCallback() { if (this.iframe_) { removeElement(this.iframe_); this.iframe_ = null; } if (this.unlistenMessage_) { this.unlistenMessage_(); } return true; } } AMP.extension('amp-facebook-like', '0.1', (AMP) => { AMP.registerElement('amp-facebook-like', AmpFacebookLike); });
{ "content_hash": "bb4f6c28c4ebe844773069dddbbb772b", "timestamp": "", "source": "github", "line_count": 128, "max_line_length": 75, "avg_line_length": 26.671875, "alnum_prop": 0.6265377855887522, "repo_name": "rsimha-amp/amphtml", "id": "cae1d80b777a7cf620eaa12597b19d6f7ec59623", "size": "4041", "binary": false, "copies": "1", "ref": "refs/heads/2021-06-29-CrossBrowserTests", "path": "extensions/amp-facebook-like/0.1/amp-facebook-like.js", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "195514" }, { "name": "Go", "bytes": "15254" }, { "name": "HTML", "bytes": "1018438" }, { "name": "Java", "bytes": "36670" }, { "name": "JavaScript", "bytes": "9464137" }, { "name": "Python", "bytes": "80044" }, { "name": "Ruby", "bytes": "14445" }, { "name": "Shell", "bytes": "12162" }, { "name": "Yacc", "bytes": "22292" } ], "symlink_target": "" }
<?xml version="1.0" encoding="UTF-8"?> <!-- see: https://gist.github.com/bjornharrtell/3054462 --> <module xmlns="urn:jboss:module:1.0" name="org.postgresql"> <resources> <resource-root path="postgresql-${postgresql.version}.jar"/> <resource-root path="postgis-jdbc-${postgis.version}.jar"/> </resources> <dependencies> <module name="javax.api"/> <module name="javax.transaction.api"/> </dependencies> </module>
{ "content_hash": "1bf60d7c48b9c5f16dae57aab8d84e0e", "timestamp": "", "source": "github", "line_count": 12, "max_line_length": 68, "avg_line_length": 38.25, "alnum_prop": 0.6405228758169934, "repo_name": "dzolo/wildfly-arquillian-hibernate-spatial-postgis", "id": "3206f776533fab96e0ff35e777e5b0c531b7a0c3", "size": "459", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/test/resources-wildfly-configuration/modules/org/postgresql/main/module.xml", "mode": "33188", "license": "mit", "language": [ { "name": "Java", "bytes": "7347" } ], "symlink_target": "" }
import os os.environ.setdefault("DJANGO_SETTINGS_MODULE", "crowdsource.settings") import requests import json from crowdsource.settings import BASE_DIR, STATIC_URL, bl_image_root, web_server_start, recorded_image_root, \ resized_start, web_server_start_resized from random import randint from django.core import serializers from lost_visions import models, wordnet from django.core.exceptions import ObjectDoesNotExist import logging logger = logging.getLogger('lost_visions') import nltk from nltk.corpus import wordnet as wn, WordNetCorpusReader __author__ = 'ubuntu' def get_next_image_id(): image_id = None try: # min_view_count = models.Image.objects.aggregate(Min('user_count')) # min_viewed_image = models.Image.objects.get(user_count=min_view_count['user_count__min']) number_of_images = models.Image.objects.count() rand_image_pk = randint(1, number_of_images) # flickr_id=10998459416 min_viewed_image = models.Image.objects.get(pk=rand_image_pk) # data = serializers.serialize("json", [min_viewed_image, ]) # print data # image_id = str(min_viewed_image.identifier) image_id = str(min_viewed_image.flickr_id) except ObjectDoesNotExist as e34423: print 'get_next_image_id', str(e34423), type(e34423) pass if image_id is None or len(image_id) == 0: return get_next_image_id() else: return image_id def get_info_from_image_model(image_model): try: image_json = serializers.serialize("json", [image_model, ]) image_object = json.loads(image_json) image_info = image_object[0]['fields'] image_info['flickr_url'] = image_model.flickr_medium_source image_info['flickr_original'] = image_model.flickr_original_source if image_info['flickr_url'] == '': image_info['flickr_url'] = image_model.flickr_original_source try: image_info['location'] = image_model.location # print 'IMAGE HAS A LOCATION???' except Exception as e78942: print 'image_model.location', str(e78942), type(e78942) except Exception as e7682: print 'get_info_from_image_model', str(e7682), type(e7682) return image_info def get_thumbnail_image(image_info): # book_id = image_info['book_identifier'] # volume = image_info['volume'] # page = image_info['page'] # index = image_info['image_idx'] try: # found_image = models.Image.objects.get(book_identifier=book_id, volume=volume, page=page, image_idx=index) # image_location = models.ImageLocation.objects.get(image=found_image) # image_location = models.ImageLocation.objects.filter(book_id=book_id, # volume=volume, # page=page, # idx=index) image_path = image_info.location if image_path is None: raise Exception('Location from DB is None') image_path = image_path.replace(recorded_image_root, resized_start) + '.thumb.jpg' image_web_path = image_path.replace(resized_start, web_server_start_resized) if not os.access(image_path, os.R_OK): raise Exception('thumbnail image unavailable in arcca ' + image_path + ' ' + image_web_path) return image_web_path except Exception as e4: # print e4 raise def find_image(image_info): # book_id = image_info['book_identifier'] # volume = image_info['volume'] # page = image_info['page'] # index = image_info['image_idx'] try: # found_image = models.Image.objects.get(book_identifier=book_id, volume=volume, page=page, image_idx=index) # image_location = models.ImageLocation.objects.get(image=found_image) # image_location = models.ImageLocation.objects.filter(book_id=book_id, # volume=volume, # page=page, # idx=index) # # image_path = image_location[0].location image_path = image_info['location'] if image_path is None: raise Exception('Location from DB is None') else: # scratch_start = '/scratch/lost-visions/images-found/' image_path = image_path.replace(recorded_image_root, bl_image_root) if not os.access(image_path, os.R_OK): raise Exception('image unavailable in arcca') return image_path.replace(bl_image_root, web_server_start) except Exception as e: # print 'e3423232' + str(e) pass try: # print image_info # web_folder = os.path.join('', 'static') web_folder = os.path.join('', 'media') web_folder = os.path.join(web_folder, 'images') web_folder = os.path.join(web_folder, 'scans') medium_folder = os.path.join(web_folder, 'medium') medium_folder = os.path.join(medium_folder, image_info['date'].strip()) root_folder = os.path.join(BASE_DIR, 'lost_visions') root_folder = os.path.join(root_folder, 'static') root_folder = os.path.join(root_folder, medium_folder) for a_file in os.listdir(root_folder): try: # image_for_id = models.Image.objects.get(flickr_id=a_file.split('_')[0]) # if image_for_id: # print 'found' + a_file full_path = os.path.join(root_folder, a_file) filename_split = a_file.split('_') if os.path.isfile(full_path) and filename_split[0] == image_info['book_identifier']: if filename_split[1] == image_info['volume']: # print '**' + full_path # print filename_split[2] # print image_info['page'] if filename_split[2].lstrip('0') == image_info['page'].lstrip('0'): if filename_split[3] == image_info['image_idx']: image_root_url = os.path.join(STATIC_URL, medium_folder) file_url = os.path.join(image_root_url, a_file) # print file_url return file_url # return STATIC_URL + 'bl_images/' + a_file except Exception as e890234: print 'full_path', str(e890234), type(e890234) pass scan_folder = os.path.join(web_folder, 'plates') scan_folder = os.path.join(scan_folder, image_info['date'].strip()) root_folder = os.path.join(BASE_DIR, 'lost_visions') root_folder = os.path.join(root_folder, 'static') root_folder = os.path.join(root_folder, scan_folder) for a_file in os.listdir(root_folder): try: # image_for_id = models.Image.objects.get(flickr_id=a_file.split('_')[0]) # if image_for_id: # print 'found' + a_file full_path = os.path.join(root_folder, a_file) filename_split = a_file.split('_') if os.path.isfile(full_path) and filename_split[0] == image_info['book_identifier']: if filename_split[1] == image_info['volume']: # print full_path # print filename_split[2] # print image_info['page'] if filename_split[2].lstrip('0') == image_info['page'].lstrip('0'): if filename_split[3] == image_info['image_idx']: image_root_url = os.path.join(STATIC_URL, scan_folder) file_url = os.path.join(image_root_url, a_file) # print file_url return file_url except Exception as e: # print e pass scan_folder = os.path.join(web_folder, 'covers') scan_folder = os.path.join(scan_folder, image_info['date'].strip()) root_folder = os.path.join(BASE_DIR, 'lost_visions') root_folder = os.path.join(root_folder, 'static') root_folder = os.path.join(root_folder, scan_folder) for a_file in os.listdir(root_folder): try: # image_for_id = models.Image.objects.get(flickr_id=a_file.split('_')[0]) # if image_for_id: # print 'found' + a_file full_path = os.path.join(root_folder, a_file) filename_split = a_file.split('_') if os.path.isfile(full_path) and filename_split[0] == image_info['book_identifier']: if filename_split[1] == image_info['volume']: # print full_path # print filename_split[2] # print image_info['page'] if filename_split[2].lstrip('0') == image_info['page'].lstrip('0'): if filename_split[3] == image_info['image_idx']: image_root_url = os.path.join(STATIC_URL, scan_folder) file_url = os.path.join(image_root_url, a_file) # print file_url return file_url except Exception as e: # print e pass scan_folder = os.path.join(web_folder, 'embellishments') scan_folder = os.path.join(scan_folder, image_info['date'].strip()) root_folder = os.path.join(BASE_DIR, 'lost_visions') root_folder = os.path.join(root_folder, 'static') root_folder = os.path.join(root_folder, scan_folder) for a_file in os.listdir(root_folder): try: # image_for_id = models.Image.objects.get(flickr_id=a_file.split('_')[0]) # if image_for_id: # print 'found' + a_file full_path = os.path.join(root_folder, a_file) filename_split = a_file.split('_') if os.path.isfile(full_path) and filename_split[0] == image_info['book_identifier']: if filename_split[1] == image_info['volume']: # print full_path # print filename_split[2] # print image_info['page'] if filename_split[2].lstrip('0') == image_info['page'].lstrip('0'): if filename_split[3] == image_info['image_idx']: image_root_url = os.path.join(STATIC_URL, scan_folder) file_url = os.path.join(image_root_url, a_file) # print file_url return file_url except Exception as e: # print e pass except: pass return None def get_image_info(image_model): try: # image_for_id = models.Image.objects.get(flickr_id=image_id) image_info = get_info_from_image_model(image_model) try: arcca_image = find_image(image_info) except Exception as e7863257: print 'error db.find_image', str(e7863257), type(e7863257) arcca_image == None image_info['arcca_url'] = '' if arcca_image: image_info['arcca_url'] = arcca_image image_model.views_begun += 1 image_model.save() return image_info except Exception as e84: print 'get_info_from_image_model', str(e84), type(e84) return None def get_tested_azure_url(image_info): try: # tk = TimeKeeper() # tk.time_now(image_info['flickr_id'] + '_azure_start', print_out=True) azure_url_part = u"http://blmc.blob.core.windows.net/{0[date]}/{0[book_identifier]}_{0[volume]}_{0[page]}_{0[image_idx]}_{0[date]}_imagesize.jpg".format(image_info) azure_url_part = azure_url_part.replace('imagesize', 'embellishments') r = requests.head(azure_url_part, stream=True, timeout=0.3) # tk.time_now(image_info['flickr_id'] + '_azure_embellishments', print_out=True) if r.status_code is requests.codes.ok: return azure_url_part else: azure_url_part = azure_url_part.replace('embellishments', 'medium') r = requests.head(azure_url_part, stream=True, timeout=0.3) # tk.time_now(image_info['flickr_id'] + '_azure_medium', print_out=True) if r.status_code is requests.codes.ok: return azure_url_part else: azure_url_part = azure_url_part.replace('medium', 'plates') r = requests.head(azure_url_part, stream=True, timeout=0.3) # tk.time_now(image_info['flickr_id'] + '_azure_medium', print_out=True) if r.status_code is requests.codes.ok: return azure_url_part else: return None except: return None def read_tsv_file(filename, line_number): with open(filename) as f: for i, line in enumerate(f): if i == line_number: words = line.split('\t') image = dict() image['volume'] = words[0] image['publisher'] = words[1] image['title'] = words[2] image['first_author'] = words[3] image['BL_DLS_ID'] = words[4] image['pubplace'] = words[5] image['book_identifier'] = words[6] image['ARK_id_of_book'] = words[7] image['date'] = words[8] image['flickr_url'] = words[9] image['image_idx'] = words[10] image['page'] = words[11] image['flickr_id'] = words[12] image['flickr_small_source'] = words[13] image['flickr_small_height'] = words[14] image['flickr_small_width'] = words[15] image['flickr_medium_source'] = words[16] image['flickr_medium_height'] = words[17] image['flickr_medium_width'] = words[18] image['flickr_large_source'] = words[19] image['flickr_large_height'] = words[20] image['flickr_large_width'] = words[21] image['flickr_original_source'] = words[22] image['flickr_original_height'] = words[23] image['flickr_original_width'] = words[24] f.close() return image # Reached end of file without hitting line number # Close it and return None f.close() return None def save_books_from_images(): image_set = models.Image.objects.all() for image in image_set: try: models.Book.objects.get(book_identifier=image.book_identifier, volume=image.volume) print 'Already have book ' + image.book_identifier + ' vol ' + image.volume except ObjectDoesNotExist: new_book = models.Book() new_book.volume = image.volume new_book.publisher = image.publisher new_book.title = image.title new_book.first_author = image.first_author new_book.BL_DLS_ID = image.BL_DLS_ID new_book.book_identifier = image.book_identifier new_book.ARK_id_of_book = image.ARK_id_of_book new_book.date = image.date print 'Saving book ' + image.book_identifier + ' vol ' + image.volume new_book.save() # image_set = models.Image.objects.exclude(volume=0) # # for image in image_set: # print image.date + ' : ' + image.flickr_id # print image.flickr_url # print image.book_identifier # # print '*****' # print len(image_set) # print '\n***********\n' # image_set = models.Image.objects.filter(book_identifier='') # for image in image_set: # print image.id # print image # # print '*****' # print len(image_set) def tests(): print '' def backup_db(): data = serializers.serialize("json", models.LostVisionUser.objects.all()) out = open("lostvisionsuser.json", "w") out.write(data) out.close() data = serializers.serialize("json", models.Tag.objects.all()) out = open("tag.json", "w") out.write(data) out.close() data = serializers.serialize("json", models.GeoTag.objects.all()) out = open("geotag.json", "w") out.write(data) out.close() data = serializers.serialize("json", models.ImageText.objects.all()) out = open("imagetext.json", "w") out.write(data) out.close() data = serializers.serialize("json", models.SavedImages.objects.all()) out = open("savedimages.json", "w") out.write(data) out.close() data = serializers.serialize("json", models.SearchQuery.objects.all()) out = open("searchquery.json", "w") out.write(data) out.close() data = serializers.serialize("json", models.User.objects.all()) out = open("tag.json", "w") out.write(data) out.close() # # SELECT lemma, definition FROM words LEFT JOIN senses s USING (wordid) # LEFT JOIN synsets USING (synsetid) where lemma like '%churc%' order by pos limit 30 # def search_wordnet(searchword, limit=30): query = "SELECT wordid, lemma, definition, synsetid, pos, sensenum FROM words LEFT JOIN senses s USING (wordid) " \ "LEFT JOIN synsets USING (synsetid) where lemma like %s " \ "order by length(lemma), sensenum ASC limit %s" # COLLATE NOCASE removed from above query results = wordnet.Words.objects.db_manager('default').raw(query, [searchword + '%', limit]) print '\n', results.query, '\n' # for word in results: # # print type(word) # word_dict = word.__dict__ # # for key in word_dict: # print key # print word.__dict__.get(key) return results def wordnet_formatted(word): word = word.lower() words = search_wordnet(word) response_data = [] for found_word in words: word_data = dict() word_data['label'] = found_word.lemma word_data['desc'] = str(found_word.definition) word_data['sensenum'] = found_word.sensenum response_data.append(word_data) synsetid = found_word.lemma + '.' + str(found_word.pos) + '.' + str(found_word.sensenum) word_data['synset'] = synsetid stem = wn.morphy(word) if stem is not None and stem is not word: # print '*' + str(stem) + '*' word_stem_words = search_wordnet(stem) for found_word in word_stem_words: word_data = dict() word_data['label'] = found_word.lemma word_data['desc'] = str(found_word.definition) word_data['sensenum'] = found_word.sensenum response_data.append(word_data) synsetid = found_word.lemma + '.' + str(found_word.pos) + '.' + str(found_word.sensenum) word_data['synset'] = synsetid return response_data # TODO we can speed this up, # use the search_word code to grab synsets instead # currently uses the nltk wordnet package which is slooooow def list_wordnet_links(tag_synset_id): initial_list = [] loop = 1 try: word_synset = wn.synset(tag_synset_id) # print 'attributes: ' + str(word_synset.__dict__) # print 'synset: ' + pprint.pformat(word_synset.__dict__) for index, lemma in enumerate(word_synset.lemmas): # print '\n' + lemma.name # print wn.lemma_from_key(lemma.key) # print 'no way: ' + str(wn._synset_from_pos_and_offset(lemma.synset.pos, lemma.synset.offset)) # print 'lemma dict synset: ' + pprint.pformat(lemma.__dict__) # print 'lemma dict synset: ' + pprint.pformat(lemma.synset.__dict__) if lemma.name != tag_synset_id.split('.')[0]: # print lemma.name + ':' + tag_synset_id.split('.')[0] initial_list.append([lemma.name, [loop, index], lemma.synset.name]) loop += 1 synset, synset_list = get_hypernyms(word_synset, initial_list, loop) return synset_list except Exception as e2432: logger.debug(e2432) logger.debug(('list_wordnet_links: ', tag_synset_id, str(e2432), type(e2432))) print 'list_wordnet_links: ', tag_synset_id, str(e2432), type(e2432) return initial_list # we stop looking upwards for parent words once we reach these pretty useless tags useless_words = ['artifact', 'being', 'abstraction', 'state', 'part', 'thing', 'entity', 'event', 'device', 'stuff', 'physical entity', 'physical object', 'object', 'creation', 'homo', 'representational process', 'percept', 'organism', 'representation', 'picture', 'image'] def get_hypernyms(synset, synset_list, loop=0): # print '\nlist so far: ' + str(synset_list) try: # print 'hypernyms: ' + str(synset.hypernyms()) for word in synset.hypernyms(): # print '\nlemmas: ' + str(word.lemmas) for index, lemma in enumerate(word.lemmas[0:2]): # print '\nfull lemma ' + str(lemma.__dict__) # print 'full lemma synset ' + str(lemma.synset.__dict__) word_string = str(lemma.name) # print 'word_string: ' + word_string if word_string in useless_words: # print 'synset_list_a ' + str(synset_list) return (word, synset_list, loop), synset_list else: # print 'synset_list_b ' + str(synset_list) synset_list.append([word_string.replace('_', ' '), [loop, index], lemma.synset.name]) loop += 1 if loop > 4: # print 'synset_list_c ' + str(synset_list) return (word, synset_list, loop), synset_list else: return get_hypernyms(word, synset_list, loop), synset_list except Exception as e45: logger.debug(e45) print 'get_hypernyms: ', str(e45), type(e45) return ('', synset_list, loop), synset_list
{ "content_hash": "a18fe8e6c7a2c6cb401ec7490ef68a15", "timestamp": "", "source": "github", "line_count": 563, "max_line_length": 172, "avg_line_length": 40.44404973357016, "alnum_prop": 0.5455862977602108, "repo_name": "CSCSI/Lost-Visions", "id": "d6dfde4101cd192c432402f62107695692500807", "size": "22770", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "lost_visions/utils/db_tools.py", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "341754" }, { "name": "HTML", "bytes": "785300" }, { "name": "JavaScript", "bytes": "608226" }, { "name": "Python", "bytes": "383528" }, { "name": "Ruby", "bytes": "58036" }, { "name": "Shell", "bytes": "93" } ], "symlink_target": "" }
Cluster telegram bot
{ "content_hash": "72346dcb269c1043cb86a0147e49b2e0", "timestamp": "", "source": "github", "line_count": 1, "max_line_length": 20, "avg_line_length": 21, "alnum_prop": 0.8571428571428571, "repo_name": "vssanya/cluster_bot", "id": "fb75b805b72fb9b692141b65dd7de94a831e0fad", "size": "35", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "README.md", "mode": "33188", "license": "mit", "language": [ { "name": "Python", "bytes": "11015" } ], "symlink_target": "" }
package fr.sysf.sample import org.assertj.core.api.Assertions import org.junit.Test import org.junit.runner.RunWith import org.springframework.beans.factory.annotation.Autowired import org.springframework.boot.test.context.SpringBootTest import org.springframework.boot.test.context.SpringBootTest.WebEnvironment import org.springframework.boot.test.web.client.TestRestTemplate import org.springframework.http.HttpStatus import org.springframework.test.context.junit4.SpringJUnit4ClassRunner /** * Created by florent on 21/02/2016. */ @RunWith(classOf[SpringJUnit4ClassRunner]) @SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT, classes = Array(classOf[Application])) class ApplicationTest { @Autowired private val restTemplate: TestRestTemplate = null @Test def getHello() { // getAll before insert val response = restTemplate.getForEntity("/api/customers/0000-AAAA", classOf[String]) Assertions.assertThat(response.getStatusCodeValue).isEqualTo(HttpStatus.OK.value()) //Assertions.assertThat(response.getBody.getContent).isEmpty } }
{ "content_hash": "113b0b68ad5af7935dfcd8de591aef24", "timestamp": "", "source": "github", "line_count": 33, "max_line_length": 99, "avg_line_length": 32.78787878787879, "alnum_prop": 0.8059149722735675, "repo_name": "fpeyron/sample-scala-camel", "id": "0b6cebd523d41d6af3120e7b983bd9cd21bb22ba", "size": "1082", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/test/scala/fr/sysf/sample/ApplicationTest.scala", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "96337" }, { "name": "HTML", "bytes": "6554" }, { "name": "JavaScript", "bytes": "2779985" }, { "name": "Scala", "bytes": "14077" } ], "symlink_target": "" }
ig.module( 'game.entities.spawner-libraried' ) .requires( 'plusplus.abstractities.spawner', /* particles */ 'plusplus.entities.particle-color', 'plusplus.entities.particle-debris', 'plusplus.entities.effect-electricity' ) .defines(function () { "use strict"; /** * Spawner that requires all spawnable non-character entities for easy reusability of generic spawner entity. * This is intended for use in the level editor so that we don't need to define a new spawner for each spawnable entity. * If you're generating a spawner programatically, use ig.Spawner instead and simply require the spawnable entity. * @class * @extends ig.Spawner * @memberof ig * @author Collin Hover - collinhover.com **/ ig.EntitySpawnerLibraried = ig.global.EntitySpawnerLibraried = ig.Spawner.extend({ // nothing }); });
{ "content_hash": "b5c906a5f25d1b03ada304a294f5772d", "timestamp": "", "source": "github", "line_count": 30, "max_line_length": 128, "avg_line_length": 32.93333333333333, "alnum_prop": 0.6194331983805668, "repo_name": "Tempus35/impactJSChocolate", "id": "6a3eac7841c79dee0f5beecb76ca3a2794fe45e7", "size": "988", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "examples/supercollider/lib/game/entities/spawner-libraried.js", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "34498" }, { "name": "JavaScript", "bytes": "1653482" }, { "name": "PHP", "bytes": "2486" } ], "symlink_target": "" }
require 'xml/xml_utils' require 'scanning_operations_mixin' module ScanningMixin extend ActiveSupport::Concern include ScanningOperationsMixin module ClassMethods def default_scan_categories_no_profile default_scan_categories - ["profiles"] end def default_scan_categories %w(vmconfig accounts software services system profiles) end # Stash metadata before sync. # Called from Queue def save_metadata(target_id, data_array) xml_file, data_type = Marshal.load(data_array) target = base_class.find_by(:id => target_id) xml_file = MIQEncode.decode(xml_file) if data_type.include?('b64,zlib') begin doc = MiqXml.load(xml_file) rescue REXML::ParseException n = MiqXml.load(xml_file, :nokogiri) xml_file = n.to_s doc = MiqXml.load(xml_file) end taskid = doc.root.attributes["taskid"] _log.info("TaskId = [#{taskid}]") unless taskid.blank? name = begin File.basename(doc.root.elements[1].elements[1].attributes["original_filename"], ".*") rescue "vmscan" end job = Job.find_by(:guid => taskid) raise _("Unable to process data for job with id <%{number}>. Job not found.") % {:number => taskid} if job.nil? begin job.signal(:data, xml_file) rescue => err _log.error("Processing xml for [#{name}] [#{err}]") _log.error("Processing xml for [#{name}] #{err.backtrace.join("\n")}") end end case doc.root.name.downcase when "summary" _log.info("Summary XML received. [#{doc.root.to_s[0..100]}]") when "vmmetadata" # TODO: - should be "metadata" # doc being sent up has a some extra header elements we need to remove (<vmmetadata>, and <item>) begin # Reset the root of the xml document to match the expected starting point doc.root = doc.root.elements[1].elements[1] rescue => err _log.error "Invalid xml error [#{err}] for xml:[#{doc}]" end target.add_elements(doc) target.save! when "vmevents" # TODO: - should be "events" target.add_elements(doc) target.save! else target.add_elements(doc) target.save! end end end # ClassMethods # Process XML documents from VM scans def add_elements(xml_node) return if xml_node.nil? _log.info("Adding XML elements for [#{id}] from [#{xml_node.root.name}]") updated = false # Find out what XML file document we are being passed. case xml_node.root.name when "miq" for element_class in [OperatingSystem, Account, SystemService, GuestApplication, Patch, Network] begin element_class.add_elements(self, xml_node) updated = true rescue Exception => err _log.log_backtrace(err) end end when "scan_profiles" ScanItem.add_elements(self, xml_node) updated = true when "vm_configuration" # TODO: should be "configuration"? Hardware.add_elements(self, xml_node) updated = true when "vmevents" # TODO: should be "events"? # Record vm operational and configuration events MiqEvent.add_elements(self, xml_node) end # Update the last sync time if we did something self.last_sync_on = Time.at(xml_node.root.attributes["created_on"].to_i).utc if updated == true && xml_node.root.attributes["created_on"] save hardware.save if self.respond_to?(:hardware) && !hardware.nil? end def scan_queue(userid = "system", options = {}) MiqQueue.submit_job( :class_name => self.class.base_class.name, :instance_id => id, :method_name => "scan", :args => [userid, options] ) end # Do the SyncMetadata operation through the server smart proxy def sync_metadata(category, options = {}) _log.debug "category=[#{category}] [#{category.class}]" options = { "category" => category.join(","), "from_time" => nil, # TODO: is this still needed?: last_drift_state_timestamp.try(:to_i), "taskid" => nil, "target_id" => id, "target_type" => self.class.base_class.name }.merge(options) host = options.delete("host") options = { "args" => [path_arg], "method_name" => "sync_metadata", "vm_guid" => guid # TODO: target_guid }.merge(options) ost = OpenStruct.new(options) host.queue_call(ost) rescue => err _log.log_backtrace(err) end # Do the ScanMetadata operation through the server smart proxy def scan_metadata(category, options = {}) _log.info "category=[#{category}] [#{category.class}]" options = { "category" => category.join(","), "taskid" => nil, "target_id" => id, "target_type" => self.class.base_class.name }.merge(options) host = options.delete("host") # If the options hash has an "args" element, remove it and add it to the "args" element with self.path miqhost_args = Array(options.delete("args")) options = { "args" => [path_arg] + miqhost_args, "method_name" => "scan_metadata", "vm_guid" => guid # TODO: target_guid }.merge(options) ost = OpenStruct.new(options) host.queue_call(ost) rescue => err _log.log_backtrace(err) end def path_arg return path if self.respond_to?(:path) return name if self.respond_to?(:name) nil end private :path_arg def scan_profile_list ScanItem.get_default_profiles end def scan_profile_categories(scan_profiles) cat_scan_list = [] begin # Loop over all profiles and add category scan items to the array scan_profiles.to_miq_a.each do |p| p["definition"].each do |d| if d["item_type"] == "category" d["definition"]["content"].to_miq_a.each { |item| cat_scan_list << item["target"] } else cat_scan_list |= ["profiles"] end end end rescue end # If we get through the profile check and do not have anything pass the default list cat_scan_list.uniq! cat_scan_list = self.class.default_scan_categories_no_profile if cat_scan_list.empty? cat_scan_list end def scan_on_registered_host_only? false end def scan_via_miq_vm(miqVm, ost) # Initialize stat collection variables ost.scanTime = Time.now.utc unless ost.scanTime status = "OK" status_code = 0 scan_message = "OK" categories_processed = 0 ost.xml_class = XmlHash::Document _log.debug "Scanning - Initializing scan" update_job_message(ost, "Initializing scan") bb, last_err = nil xml_summary = ost.xml_class.createDoc(:summary) xml_node = xml_node_scan = xml_summary.root.add_element("scanmetadata") xml_node_scan.add_attributes("start_time" => ost.scanTime.iso8601) xml_summary.root.add_attributes("taskid" => ost.taskid) data_dir = File.join(File.expand_path(Rails.root), "data/metadata") _log.debug "creating #{data_dir}" begin Dir.mkdir(data_dir) rescue Errno::EEXIST # Ignore if the directory was created by another thread. end unless File.exist?(data_dir) ost.skipConfig = true ost.config = OpenStruct.new( :dataDir => data_dir, :forceFleeceDefault => false ) begin require 'metadata/MIQExtract/MIQExtract' _log.debug "instantiating MIQExtract" extractor = MIQExtract.new(miqVm, ost) _log.debug "instantiated MIQExtract" require 'blackbox/VmBlackBox' _log.debug "instantiating BlackBox" bb = Manageiq::BlackBox.new(guid, ost) # TODO: target must have GUID _log.debug "instantiated BlackBox" _log.debug "Checking for file systems..." raise extractor.systemFsMsg unless extractor.systemFs categories = extractor.categories _log.debug "categories = [ #{categories.join(', ')} ]" categories.each do |c| update_job_message(ost, "Scanning #{c}") _log.info "Scanning [#{c}] information. TaskId:[#{ost.taskid}] VM:[#{name}]" st = Time.now xml = extractor.extract(c) { |scan_data| update_job_message(ost, scan_data[:msg]) } categories_processed += 1 _log.info "Scanning [#{c}] information ran for [#{Time.now - st}] seconds. TaskId:[#{ost.taskid}] VM:[#{name}]" if xml xml.root.add_attributes("created_on" => ost.scanTime.to_i, "display_time" => ost.scanTime.iso8601) _log.debug "Writing scanned data to XML for [#{c}] to blackbox." bb.saveXmlData(xml, c) _log.debug "writing xml complete." category_node = xml_summary.class.load(xml.root.shallow_copy.to_xml.to_s).root category_node.add_attributes("start_time" => st.utc.iso8601, "end_time" => Time.now.utc.iso8601) xml_node << category_node else # Handle categories that we do not expect to return data. # Otherwise, log an error if we do not get data back. unless c == "vmevents" _log.error "Error: No XML returned for category [#{c}] TaskId:[#{ost.taskid}] VM:[#{name}]" end end end rescue NoMethodError => scanErr last_err = scanErr _log.error "Scanmetadata Error - [#{scanErr}]" _log.error "Scanmetadata Error - [#{scanErr.backtrace.join("\n")}]" rescue Timeout::Error, StandardError => scanErr last_err = scanErr ensure bb.close if bb update_job_message(ost, "Scanning completed.") # If we are sent a TaskId transfer a end of job summary xml. _log.info "Starting: Sending scan summary to server. TaskId:[#{ost.taskid}] VM:[#{name}]" if last_err status = "Error" status_code = 8 status_code = 16 if categories_processed.zero? scan_message = last_err.to_s _log.error "ScanMetadata error status:[#{status_code}]: message:[#{last_err}]" _log.debug { last_err.backtrace.join("\n") } end xml_node_scan.add_attributes( "end_time" => Time.now.utc.iso8601, "status" => status, "status_code" => status_code.to_s, "message" => scan_message ) save_metadata_op(MIQEncode.encode(xml_summary.to_xml.to_s), "b64,zlib,xml", ost.taskid) _log.info "Completed: Sending scan summary to server. TaskId:[#{ost.taskid}] target:[#{name}]" end end def sync_stashed_metadata(ost) _log.info "from #{self.class.name}" xml_summary = nil begin raise _("No synchronize category specified") if ost.category.nil? categories = ost.category.split(",") ost.scanTime = Time.now.utc ost.compress = true # Request that data returned from the blackbox is compressed ost.xml_class = REXML::Document # TODO: if from_time is not a string (see sync_metadata() above), loadXmlData fails. # Just clear it for now, until we figure out the right thing to do. ost.from_time = nil bb = nil xml_summary = ost.xml_class.createDoc("<summary/>") _log.debug "xml_summary1 = #{xml_summary.class.name}" xml_node = xml_summary.root.add_element("syncmetadata") xml_summary.root.add_attributes("scan_time" => ost.scanTime, "taskid" => ost.taskid) ost.skipConfig = true data_dir = File.join(File.expand_path(Rails.root), "data/metadata") ost.config = OpenStruct.new( :dataDir => data_dir, :forceFleeceDefault => false ) require 'blackbox/VmBlackBox' bb = Manageiq::BlackBox.new(guid, ost) update_job_message(ost, "Synchronization in progress") categories.each do |c| c.delete!("\"") c.strip! # Grab data out of the bb. (results may be limited by parms in ost like "from_time") ret = bb.loadXmlData(c, ost) xml_node << ost.xml_class.load(ret.xml.root.shallow_copy.to_xml.to_s).root items_total = ret.xml.root.attributes["items_total"].to_i items_selected = ret.xml.root.attributes["items_selected"].to_i data = MIQEncode.encode(ret.xml.to_s) # Verify that we have data to send if !items_selected.zero? _log.info "Starting: Sending target data for [#{c}] to server. Size:[#{data.length}] TaskId:[#{ost.taskid}] target:[#{name}]" save_metadata_op(data, "b64,zlib,xml", ost.taskid) _log.info "Completed: Sending target data for [#{c}] to server. Size:[#{data.length}] TaskId:[#{ost.taskid}] target:[#{name}]" else # Do not send empty XMLs. Warn if there is not data at all, or just not items selected. if items_total.zero? _log.warn "Synchronize: No data found for [#{c}]. Items:Total[#{items_total}] Selected[#{items_selected}] TaskId:[#{ost.taskid}] VM:[#{name}]" else _log.warn "Synchronize: No data selected for [#{c}]. Items:Total[#{items_total}] Selected[#{items_selected}] TaskId:[#{ost.taskid}] VM:[#{name}]" end end end rescue => syncErr _log.error syncErr.to_s _log.debug { syncErr.backtrace.join("\n") } ensure if bb bb.postSync bb.close end _log.info "Starting: Sending target summary to server. TaskId:[#{ost.taskid}] target:[#{name}]" _log.debug "xml_summary2 = #{xml_summary.class.name}" save_metadata_op(MIQEncode.encode(xml_summary.to_s), "b64,zlib,xml", ost.taskid) _log.info "Completed: Sending target summary to server. TaskId:[#{ost.taskid}] target:[#{name}]" update_job_message(ost, "Synchronization complete") raise syncErr if syncErr end ost.value = "OK\n" end def update_job_message(ost, message) ost.message = message if ost.taskid.present? MiqQueue.submit_job( :service => "smartstate", :class_name => "Job", :method_name => "update_message", :args => [ost.taskid, message], :task_id => "job_message_#{Time.now.to_i}", ) end end end
{ "content_hash": "e7979bd2e87eba4adc6a403e8b09648b", "timestamp": "", "source": "github", "line_count": 388, "max_line_length": 160, "avg_line_length": 36.649484536082475, "alnum_prop": 0.6078762306610408, "repo_name": "mfeifer/manageiq", "id": "05ad29858e4f3e0a227479d00b95eaf0c1ef8ee6", "size": "14416", "binary": false, "copies": "6", "ref": "refs/heads/master", "path": "app/models/mixins/scanning_mixin.rb", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "HTML", "bytes": "2167" }, { "name": "JavaScript", "bytes": "183" }, { "name": "Ruby", "bytes": "8252036" }, { "name": "Shell", "bytes": "2696" } ], "symlink_target": "" }
import os from django.core.wsgi import get_wsgi_application os.environ.setdefault("DJANGO_SETTINGS_MODULE", "bot.settings") application = get_wsgi_application()
{ "content_hash": "2503ae43332a1a8384073cd638bb4431", "timestamp": "", "source": "github", "line_count": 7, "max_line_length": 63, "avg_line_length": 23.428571428571427, "alnum_prop": 0.7865853658536586, "repo_name": "sergei-maertens/discord-bot", "id": "46e11bb7142c7150de7b8f01e6e0e386e60e8d2e", "size": "164", "binary": false, "copies": "1", "ref": "refs/heads/develop", "path": "bot/wsgi.py", "mode": "33188", "license": "mit", "language": [ { "name": "Dockerfile", "bytes": "1069" }, { "name": "HTML", "bytes": "165" }, { "name": "Python", "bytes": "87711" }, { "name": "Shell", "bytes": "896" } ], "symlink_target": "" }
namespace Resources { const Core::CRTTI& CSkinInfoLoaderSKN::GetResultType() const { return Render::CSkinInfo::RTTI; } //--------------------------------------------------------------------- Core::PObject CSkinInfoLoaderSKN::CreateResource(CStrID UID) { const char* pOutSubId; IO::PStream Stream = _ResMgr.CreateResourceStream(UID.CStr(), pOutSubId, IO::SAP_SEQUENTIAL); if (!Stream || !Stream->IsOpened()) return nullptr; IO::CBinaryReader Reader(*Stream); U32 Magic; if (!Reader.Read(Magic) || Magic != 'SKIN') return nullptr; U32 FormatVersion; if (!Reader.Read(FormatVersion)) return nullptr; U32 BoneCount; if (!Reader.Read(BoneCount)) return nullptr; // Skip padding Reader.Read<U32>(); Render::PSkinInfo SkinInfo = n_new(Render::CSkinInfo); SkinInfo->Create(BoneCount); //!!!may use MMF for bind pose matrices! their offset in a file is aligned-16! Stream->Read(SkinInfo->pInvBindPose, BoneCount * sizeof(matrix44)); for (auto& BoneInfo : SkinInfo->Bones) { U16 ParentIndex; if (!Reader.Read(ParentIndex)) return nullptr; BoneInfo.ParentIndex = (ParentIndex == static_cast<U16>(-1)) ? INVALID_INDEX : ParentIndex; if (!Reader.Read(BoneInfo.ID)) return nullptr; } return SkinInfo.Get(); } //--------------------------------------------------------------------- }
{ "content_hash": "40c0ec068d5a3dd6cc271279b284ce69", "timestamp": "", "source": "github", "line_count": 48, "max_line_length": 94, "avg_line_length": 27.291666666666668, "alnum_prop": 0.6412213740458015, "repo_name": "niello/deusexmachina", "id": "7319077486c40e8a380be8654a20d6fac3fac60b", "size": "1440", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "DEM/Low/src/Render/SkinInfoLoaderSKN.cpp", "mode": "33188", "license": "mit", "language": [ { "name": "Assembly", "bytes": "122533" }, { "name": "Awk", "bytes": "688" }, { "name": "Batchfile", "bytes": "7513" }, { "name": "C", "bytes": "16388375" }, { "name": "C#", "bytes": "398813" }, { "name": "C++", "bytes": "36890379" }, { "name": "CMake", "bytes": "561047" }, { "name": "CSS", "bytes": "10638" }, { "name": "Fortran", "bytes": "87" }, { "name": "FreeBasic", "bytes": "3789" }, { "name": "HTML", "bytes": "1351597" }, { "name": "Lua", "bytes": "135757" }, { "name": "M4", "bytes": "52785" }, { "name": "Makefile", "bytes": "52318" }, { "name": "Mathematica", "bytes": "4491" }, { "name": "NSIS", "bytes": "4683" }, { "name": "Objective-C", "bytes": "55376" }, { "name": "Pascal", "bytes": "29093" }, { "name": "Perl", "bytes": "39592" }, { "name": "PowerShell", "bytes": "7410" }, { "name": "Python", "bytes": "160966" }, { "name": "Roff", "bytes": "5263" }, { "name": "Ruby", "bytes": "39" }, { "name": "SWIG", "bytes": "11981" }, { "name": "Shell", "bytes": "7830" }, { "name": "TeX", "bytes": "149544" }, { "name": "VBA", "bytes": "41547" }, { "name": "Visual Basic .NET", "bytes": "8505" } ], "symlink_target": "" }
set(XPREFIX PC_RAYLIB) if (raylib_USE_STATIC_LIBS) set(XPREFIX ${XPREFIX}_STATIC) endif() find_package(PkgConfig QUIET) pkg_check_modules(${XPREFIX} QUIET raylib) set(raylib_DEFINITIONS ${${XPREFIX}_CFLAGS}) find_path(raylib_INCLUDE_DIR NAMES raylib.h HINTS ${${XPREFIX}_INCLUDE_DIRS} ) if (raylib_USE_STATIC_LIBS) find_library(raylib_LIBRARY NAMES raylib_static HINTS ${${XPREFIX}_LIBRARY_DIRS} ) else () find_library(raylib_LIBRARY NAMES raylib HINTS ${${XPREFIX}_LIBRARY_DIRS} ) endif () set(raylib_LIBRARIES ${raylib_LIBRARY}) set(raylib_LIBRARY_DIRS ${${XPREFIX}_LIBRARY_DIRS}) set(raylib_LIBRARY_DIR ${raylib_LIBRARY_DIRS}) set(raylib_INCLUDE_DIRS ${raylib_INCLUDE_DIR}) set(raylib_LDFLAGS ${${XPREFIX}_LDFLAGS}) include(FindPackageHandleStandardArgs) find_package_handle_standard_args(raylib DEFAULT_MSG raylib_LIBRARY raylib_INCLUDE_DIR ) mark_as_advanced(raylib_LIBRARY raylib_INCLUDE_DIR) if (raylib_USE_STATIC_LIBS) add_library(raylib STATIC IMPORTED GLOBAL) else() add_library(raylib SHARED IMPORTED GLOBAL) endif() string (REPLACE ";" " " raylib_LDFLAGS "${raylib_LDFLAGS}") set_target_properties(raylib PROPERTIES IMPORTED_LOCATION "${raylib_LIBRARIES}" INTERFACE_INCLUDE_DIRECTORIES "${raylib_INCLUDE_DIRS}" INTERFACE_LINK_LIBRARIES "${raylib_LDFLAGS}" INTERFACE_COMPILE_OPTIONS "${raylib_DEFINITIONS}" ) if (raylib_VERBOSE) message(STATUS "raylib_FOUND: ${raylib_FOUND}") message(STATUS "raylib_INCLUDE_DIRS: ${raylib_INCLUDE_DIRS}") message(STATUS "raylib_LIBRARIES: ${raylib_LIBRARIES}") message(STATUS "raylib_LDFLAGS: ${raylib_LDFLAGS}") message(STATUS "raylib_DEFINITIONS: ${raylib_DEFINITIONS}") endif()
{ "content_hash": "9ba0955e19e3f80669f94a46d3b8abdf", "timestamp": "", "source": "github", "line_count": 62, "max_line_length": 63, "avg_line_length": 28.338709677419356, "alnum_prop": 0.7114399544678429, "repo_name": "ring-lang/ring", "id": "5ad55b1698123b8b728edcb9d9148bdd203d2e95", "size": "2308", "binary": false, "copies": "3", "ref": "refs/heads/master", "path": "extensions/libdepwin/raylib2.5/lib/cmake/raylib/raylib-config.cmake", "mode": "33188", "license": "mit", "language": [ { "name": "Ada", "bytes": "89080" }, { "name": "Assembly", "bytes": "296081" }, { "name": "Awk", "bytes": "46636" }, { "name": "Batchfile", "bytes": "101663" }, { "name": "C", "bytes": "71469704" }, { "name": "C#", "bytes": "80097" }, { "name": "C++", "bytes": "20961776" }, { "name": "CLIPS", "bytes": "5291" }, { "name": "CMake", "bytes": "67747" }, { "name": "CSS", "bytes": "82643" }, { "name": "DIGITAL Command Language", "bytes": "110604" }, { "name": "Emacs Lisp", "bytes": "7096" }, { "name": "Java", "bytes": "60236" }, { "name": "JavaScript", "bytes": "77844" }, { "name": "Less", "bytes": "246" }, { "name": "M4", "bytes": "493435" }, { "name": "Makefile", "bytes": "3116661" }, { "name": "Module Management System", "bytes": "17479" }, { "name": "Objective-C", "bytes": "376958" }, { "name": "Pascal", "bytes": "72283" }, { "name": "Perl", "bytes": "85778" }, { "name": "Python", "bytes": "263263" }, { "name": "QML", "bytes": "1152" }, { "name": "QMake", "bytes": "36639" }, { "name": "Rebol", "bytes": "6496" }, { "name": "Ring", "bytes": "45850703" }, { "name": "Roff", "bytes": "677912" }, { "name": "SAS", "bytes": "16030" }, { "name": "SWIG", "bytes": "13206" }, { "name": "Shell", "bytes": "5483160" }, { "name": "Smalltalk", "bytes": "5908" }, { "name": "StringTemplate", "bytes": "4184" }, { "name": "TeX", "bytes": "352002" }, { "name": "WebAssembly", "bytes": "13987" }, { "name": "sed", "bytes": "236" } ], "symlink_target": "" }
package ru.job4j.tracker; import org.junit.Test; import static org.hamcrest.core.Is.is; import static org.junit.Assert.*; /** * Test. * * @author Kseniya Shustova (shustovakv@mail.ru) * @version $Id$ * @since 0.1 */ public class TrackerTest { /** * Test add. */ @Test public void whenAddNewItemThenTrackerHasSameItem() { Tracker tracker = new Tracker(); Item item = new Item("test1", "testDescription", 123L); tracker.add(item); assertThat(tracker.findAll().get(0), is(item)); } /** * Test update. */ @Test public void whenUpdateNameThenReturnNewName() { Tracker tracker = new Tracker(); Item previous = new Item("test1", "testDescription", 123L); tracker.add(previous); Item next = new Item("test2", "testDescription2", 1234L); next.setId(previous.getId()); tracker.replace(next.getId(), next); assertThat(tracker.findById(previous.getId()).getName(), is("test2")); } /** * Test delete. */ @Test public void whenDeleteItemThenTrackerHasSameItem() { Tracker tracker = new Tracker(); Item previous = new Item("test1", "testDescription", 123L); tracker.add(previous); tracker.delete(previous.getId()); Item[] result = {}; assertThat(tracker.findAll().toArray(), is(result)); } /** * Test findAll. */ @Test public void whenFindAllItemsThenReturnAllItems() { Tracker tracker = new Tracker(); Item first = new Item("test1", "testDescription1", 123L); tracker.add(first); Item[] result = {first}; assertThat(tracker.findAll().toArray(), is(result)); } /** * Test findByName. */ @Test public void whenFindItemsByNameThenReturnItems() { Tracker tracker = new Tracker(); Item first = new Item("test1", "testDescription1", 123L); tracker.add(first); Item[] result = {first}; assertThat(tracker.findByName("test1").toArray(), is(result)); } /** * Тест findById. */ @Test public void whenFindItemByIdThenReturnItem() { Tracker tracker = new Tracker(); Item first = new Item("test1", "testDescription1", 123L); tracker.add(first); assertThat(tracker.findById(first.getId()).getName(), is("test1")); } }
{ "content_hash": "e4f0b9679dfa41fd168586d83506e560", "timestamp": "", "source": "github", "line_count": 83, "max_line_length": 78, "avg_line_length": 28.951807228915662, "alnum_prop": 0.5938410320432792, "repo_name": "Spirka/shustovakv", "id": "c3a29fc62958497f98098e536ac091db64fe4212", "size": "2407", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "chapter_002/src/test/java/ru/job4j/tracker/TrackerTest.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "HTML", "bytes": "247188" }, { "name": "Java", "bytes": "292434" }, { "name": "Shell", "bytes": "14" }, { "name": "XSLT", "bytes": "575" } ], "symlink_target": "" }
module.exports = function(grunt) { 'use strict'; var chalk = require('chalk'), PJV = require('package-json-validator').PJV; grunt.registerTask('npm-validate', 'Opinionated package.json validator.', function() { var options = this.options({ file: grunt.config('pkgFile') || 'package.json', force: false, strict: false }); grunt.log.write('Validating ' + options.file + '...'); var results = PJV.validate(grunt.file.read(options.file)); var fail = results.errors || options.strict && results.warnings; if (fail) { grunt.log.error(); } else { grunt.log.ok(); } if ((results.errors || []).length > 0) { grunt.log.subhead(chalk.red('Errors:')); results.errors.forEach(function(error) { grunt.log.error(error); }); } if ((results.warnings || []).length > 0) { grunt.log.subhead(chalk.yellow('Warnings:')); results.warnings.forEach(function(warning) { grunt.log.warn(warning); }); } if ((results.recommendations || []).length > 0) { grunt.log.subhead(chalk.green('Recommendations:')); results.recommendations.forEach(function(recommendation) { grunt.log.warn(recommendation); }); } return options.force || !fail; }); };
{ "content_hash": "e374ead0ec281425758f080a6f63c19d", "timestamp": "", "source": "github", "line_count": 49, "max_line_length": 90, "avg_line_length": 30.26530612244898, "alnum_prop": 0.5232636547538773, "repo_name": "joshuaspence/grunt-npm-validate", "id": "eb947f4249d4c79db1cd86b3844025f2d87d8222", "size": "1640", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "tasks/npm-validate.js", "mode": "33188", "license": "mit", "language": [ { "name": "JavaScript", "bytes": "5359" } ], "symlink_target": "" }
import React, { Component } from 'react'; import { Redirect } from 'react-router-dom'; import Section from 'shared/components/section/section'; import FormButton from 'shared/components/form/formButton/formButton'; import { patchBackend } from 'shared/utils/apiHelper'; import Identifier from './formComponents/identifier'; import Interests from './formComponents/interests'; import WorkInfo from './formComponents/workInfo'; import SchoolInfo from './formComponents/schoolInfo'; import MilitaryInfo from './formComponents/militaryInfo'; import styles from './informationForm.css'; class SignupInformation extends Component { constructor(props) { super(props); this.onIdentifierStatusChange = this.onIdentifierStatusChange.bind(this); this.onCheckBoxChange = this.onCheckBoxChange.bind(this); this.previousPage = this.previousPage.bind(this); this.onCheckboxLoad = this.onCheckboxLoad.bind(this); this.state = { error: false, isValid: true, isDescriptionValid: true, success: false, identifier: 'false', interests: new Set(), step: 0 }; } onCheckboxLoad = () => { // Clear the interests once we get to the interests page if (this.state.interests.size) { const interests = new Set(this.state.interests); interests.clear(); this.setState({ interests }); } } // On-Change handler dynamically creates state named after the // ID of the changing event, with a value captured by the event itself. // Ex. If a form select with ID 'hello' selects value 'greeted' // Then state will be updated with key of 'hello' and value of 'greeted' onIdentifierStatusChange = (e, value) => { this.setState({ [e.target.id]: value }); } // Adds values from checkboxes to a set, eliminating possible repeat values onCheckBoxChange = (e) => { const interests = new Set(this.state.interests); const { value } = e.target; if (e.target.checked) { interests.add(value); } else { interests.delete(value); } this.setState({ interests }); } // make sure isDescriptionValid is false on initialization onIdentifierInit = () => { this.setState({ isDescriptionValid: false }); } // check if an option was selected: volunteer / veteran validateDescription = (value) => { const isDescriptionValid = Boolean(value.length); this.setState({ isDescriptionValid }); return isDescriptionValid; } // Reduces 'step' value by 1, going back one page in the form // Unless you are at the first page previousPage = () => { if (this.state.step < 1) { return; } this.setState({ step: this.state.step -= 1 }); } isFormValid = () => { let valid = true; if (!this.state.isDescriptionValid) { valid = false; } this.setState({ error: !valid }); return valid; } // Patches whatever values that have been captured so far to the DB // Then adds 1 to step to progress to the next page. saveAndContinue = () => { // check if the form is valid before submitting if (!this.isFormValid()) { return; } patchBackend('users', { user: { education_level: this.state.schoolLevel, mentor: this.state.mentor, scholarship_info: this.state.scholarships, employment_status: this.state.workInfo, company_name: this.state.company, company_role: this.state.role, // Convert string to boolean for DB volunteer: this.state.identifier === 'true', branch_of_service: this.state.branch, // Necessary to convert Set to Array for storage in DB interests: Array.from(this.state.interests) }, }) .then(() => { this.setState({ step: this.state.step += 1 }); }).catch(() => { this.setState({ error: true }); }); } // Showstep renders each consecutive 'page' (component) based on user input // The form splits based on identifier, which determines whether or not // You are military or civillian. If miltitary, it's false. If civillian, true // 'Step' state is combined with 'identifier' to determine which component to // Serve to the user. The default case, or STEP ONE is the Identifier form. showStep = () => { const step = this.state.step + this.state.identifier; switch (step) { // Military STEP 2 case '1false': return ( <MilitaryInfo update={this.onIdentifierStatusChange} percent="20" /> ); // Civillian STEP 2 case '1true': return ( <WorkInfo role={this.state.role} company={this.state.company} update={this.onIdentifierStatusChange} percent="33" identifier={this.state.identifier} /> ); // Civillian STEP 3 case '2true': return ( <Interests update={this.onCheckBoxChange} percent="66" onLoad={this.onCheckboxLoad} /> ); // Civillian COMPLETE case '3true': return ( <Redirect to="/profile" /> ); // Military STEP 3 case '2false': return ( <WorkInfo role={this.state.role} company={this.state.company} update={this.onIdentifierStatusChange} percent="40" /> ); // Military STEP 4 case '3false': return ( <SchoolInfo update={this.onIdentifierStatusChange} percent="60" /> ); // Military STEP 5 case '4false': return ( <Interests update={this.onCheckBoxChange} percent="80" /> ); // Military COMPLETE case '5false': return ( <Redirect to="/profile" /> ); // STEP ONE default: return ( <Identifier update={this.onIdentifierStatusChange} validationFunc={e => this.validateDescription(e.target.value)} validationErrorMessage="You have to select a value" isValid={this.state.isDescriptionValid} init={this.onIdentifierInit} /> ); } } render() { const showStep = this.showStep(); return ( <Section title="More Info"> <p>At Op-Code, we are dedicated to helping our community thrive. In order to do so, we need to collect some information to better serve you. Please take a minute to complete these steps and help us on our mission to code the future. We will never sell or distribute your information.</p> {showStep} <div className={styles.buttonContainer}> <FormButton text="Go Back" onClick={this.previousPage} theme="blue" /> <FormButton text="Save and Continue" onClick={this.saveAndContinue} theme="red" /> {this.state.error ? <ul className={styles.errorList}>There was an error saving your information, please try again. </ul> : null } </div> </Section> ); } } export default SignupInformation;
{ "content_hash": "beebc9a4b1df26e6dc06e6e6a9403262", "timestamp": "", "source": "github", "line_count": 225, "max_line_length": 295, "avg_line_length": 31.897777777777776, "alnum_prop": 0.6084715062003623, "repo_name": "miaket/operationcode_frontend", "id": "a65e53c9b685a405d21da16b05d25d1394850315", "size": "7177", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/scenes/home/informationForm/informationForm.js", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "58706" }, { "name": "HTML", "bytes": "4695" }, { "name": "JavaScript", "bytes": "284865" }, { "name": "Makefile", "bytes": "361" }, { "name": "Shell", "bytes": "2436" } ], "symlink_target": "" }
import moment from 'moment'; import filtersReducer from '../../reducers/filters'; test('should setup default filter values', () => { // params: current state, action object (redux dispatches @@INIT first) const state = filtersReducer(undefined, { type: '@@INIT' }); expect(state).toEqual({ text: '', sortBy: 'date', startDate: moment().startOf('month'), endDate: moment().endOf('month') }); }); // ======== test('should set sortBy to amount', () => { const state = filtersReducer(undefined, { type: 'SORT_BY_AMOUNT' }); expect(state.sortBy).toBe('amount'); }); test('should set sortBy to date', () => { const currentState = { text: '', startDate: undefined, endDate: undefined, sortBy: 'amount' }; const action = { type: 'SORT_BY_DATE' }; const state = filtersReducer(currentState, action); expect(state.sortBy).toBe('date'); }); // ======== test('should set text filter', () => { const text = 'This is my filter'; const action = { type: 'SET_TEXT_FILTER', text }; const state = filtersReducer(undefined, action); expect(state.text).toBe(text); }); // ======== test('should set startDate filter', () => { const startDate = moment(); const action = { type: 'SET_START_DATE', startDate }; const state = filtersReducer(undefined, action); expect(state.startDate).toEqual(startDate); }); test('should set endDate filter', () => { const endDate = moment(); const action = { type: 'SET_END_DATE', endDate }; const state = filtersReducer(undefined, action); expect(state.endDate).toEqual(endDate); });
{ "content_hash": "bfbac11bb4dfb7c761b79f0014bfaa61", "timestamp": "", "source": "github", "line_count": 67, "max_line_length": 73, "avg_line_length": 24.074626865671643, "alnum_prop": 0.6230626162430254, "repo_name": "VeeShostak/Expense-Manager", "id": "ca8ed9064402725f9004f97de8188c3cf9cfee2d", "size": "1613", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "expense-manager-app/src/tests/reducers/filters.test.js", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "4564" }, { "name": "HTML", "bytes": "385" }, { "name": "JavaScript", "bytes": "71426" } ], "symlink_target": "" }
@interface SlidingThing () @end @implementation SlidingThing - (instancetype)initWithFrame:(CGRect)frame { self = [super initWithFrame:frame]; if (self) { [self configure]; } return self; } - (id)initWithCoder:(NSCoder *)aDecoder { self = [super initWithCoder:aDecoder]; if (self) { [self configure]; } return self; } - (void)configure { self.actualYPosition = 10.0f; self.targetYPosition = 20.0f; } - (void)drawRect:(CGRect)rect { [super drawRect:rect]; CGContextRef context = UIGraphicsGetCurrentContext(); CGContextSetLineWidth(context, 2.0); CGContextSetStrokeColorWithColor(context, [Theme colourMain].CGColor); CGContextMoveToPoint(context, rect.size.width, rect.origin.y); CGContextAddLineToPoint(context, rect.size.width, rect.size.height); CGFloat x1 = rect.size.width - 20.0f; CGFloat x2 = rect.size.width; // Middle CGContextMoveToPoint(context, x1, self.actualYPosition); CGContextAddLineToPoint(context, x2, self.actualYPosition); // Actual CGContextMoveToPoint(context, x1, self.targetYPosition); CGContextAddLineToPoint(context, x2, self.targetYPosition); CGContextStrokePath(context); } @end
{ "content_hash": "fa945318d73a3424fd8b17681cceddba", "timestamp": "", "source": "github", "line_count": 60, "max_line_length": 74, "avg_line_length": 20.683333333333334, "alnum_prop": 0.693795326349718, "repo_name": "jdunwoody/DateMaths", "id": "e4756e5ed3a352b1d47f07f8b635719b6b852d42", "size": "1376", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "DateMaths/ResultsSlider/SlidingThing.m", "mode": "33188", "license": "mit", "language": [ { "name": "Objective-C", "bytes": "96656" }, { "name": "Ruby", "bytes": "2615" } ], "symlink_target": "" }
layout: default title: ICCSTE'16 - PayPal Payment Successful --- <div class="unit unit-s-1 unit-m-1-4-1 unit-l-1-4-1"> <div class="unit-spacer content"> <p class="body">Your payment has been successful!</p> <p align="body">We thank you very much for registering for ICCSTE'16. An email has been sent to you confirming your payment to ICCSTE'16. Please keep this email for your reference.</p> <p align="body">Please make sure you <strong>fill out and submit the registration form</strong>. Failing to fill out this form will result in the elimination of your registration.</p> <p align="body">You may find the registration form by following the link below:</p> <center><a href="../registration" class="body-link">www.iccste.com/registration</a></center> <p class="body">Should you have any concerns, questions or comments, please do not hesitate to contact us at:</p> <center><a href="mailto:registration@iccste.com" class="body-link">registration@iccste.com</a></p> <p class="body">We are looking forward to seeing you at ICCSTE'16!</p> </div> </div>
{ "content_hash": "52771ac650f9daf741c0cb50408b429c", "timestamp": "", "source": "github", "line_count": 23, "max_line_length": 188, "avg_line_length": 47.608695652173914, "alnum_prop": 0.7123287671232876, "repo_name": "intaset/iccste", "id": "b1a9c3f93e48b7c6299b1ef508e649ebc990d724", "size": "1099", "binary": false, "copies": "1", "ref": "refs/heads/gh-pages", "path": "payment_successful.html", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "90407" }, { "name": "HTML", "bytes": "410646" }, { "name": "JavaScript", "bytes": "338038" }, { "name": "PHP", "bytes": "42570" } ], "symlink_target": "" }
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical"> <android.support.design.widget.TabLayout android:id="@+id/sliding_tabs" android:layout_width="match_parent" android:layout_height="wrap_content" app:tabMode="scrollable" /> <android.support.v4.view.ViewPager android:id="@+id/viewpager" android:layout_width="match_parent" android:layout_height="0px" android:layout_weight="1" android:background="@android:color/white" /> </LinearLayout> <!-- <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" tools:context="com.baquiax.marvelsuperheroes.MainActivity"> <fragment android:id="@+id/searchFragment" android:name="com.baquiax.marvelsuperheroes.fragments.SearchFragment" android:layout_width="match_parent" android:layout_height="wrap_content" tools:layout="@layout/fragment_search"></fragment> <fragment android:id="@+id/resultSearchContainer" android:name="com.baquiax.marvelsuperheroes.fragments.ResultSearchFragment" android:layout_width="match_parent" android:layout_height="wrap_content" tools:layout="@layout/fragment_result_search"></fragment> </LinearLayout> -->
{ "content_hash": "2be134bc905d031ef9c1f44b0f37a0e4", "timestamp": "", "source": "github", "line_count": 45, "max_line_length": 83, "avg_line_length": 37.08888888888889, "alnum_prop": 0.6908328340323547, "repo_name": "baquiax/MarvelSuperHeroes", "id": "0e8113a06e2335d81c881624200be93b32a573e9", "size": "1669", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "app/src/main/res/layout/activity_main.xml", "mode": "33188", "license": "mit", "language": [ { "name": "Java", "bytes": "20101" } ], "symlink_target": "" }
// Copyright (c) 2016-2019 The Bitcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #ifndef BITCOIN_SUPPORT_LOCKEDPOOL_H #define BITCOIN_SUPPORT_LOCKEDPOOL_H #include <stdint.h> #include <list> #include <map> #include <mutex> #include <memory> #include <unordered_map> /** * OS-dependent allocation and deallocation of locked/pinned memory pages. * Abstract base class. */ class LockedPageAllocator { public: virtual ~LockedPageAllocator() {} /** Allocate and lock memory pages. * If len is not a multiple of the system page size, it is rounded up. * Returns nullptr in case of allocation failure. * * If locking the memory pages could not be accomplished it will still * return the memory, however the lockingSuccess flag will be false. * lockingSuccess is undefined if the allocation fails. */ virtual void* AllocateLocked(size_t len, bool *lockingSuccess) = 0; /** Unlock and free memory pages. * Clear the memory before unlocking. */ virtual void FreeLocked(void* addr, size_t len) = 0; /** Get the total limit on the amount of memory that may be locked by this * process, in bytes. Return size_t max if there is no limit or the limit * is unknown. Return 0 if no memory can be locked at all. */ virtual size_t GetLimit() = 0; }; /* An arena manages a contiguous region of memory by dividing it into * chunks. */ class Arena { public: Arena(void *base, size_t size, size_t alignment); virtual ~Arena(); Arena(const Arena& other) = delete; // non construction-copyable Arena& operator=(const Arena&) = delete; // non copyable /** Memory statistics. */ struct Stats { size_t used; size_t free; size_t total; size_t chunks_used; size_t chunks_free; }; /** Allocate size bytes from this arena. * Returns pointer on success, or 0 if memory is full or * the application tried to allocate 0 bytes. */ void* alloc(size_t size); /** Free a previously allocated chunk of memory. * Freeing the zero pointer has no effect. * Raises std::runtime_error in case of error. */ void free(void *ptr); /** Get arena usage statistics */ Stats stats() const; #ifdef ARENA_DEBUG void walk() const; #endif /** Return whether a pointer points inside this arena. * This returns base <= ptr < (base+size) so only use it for (inclusive) * chunk starting addresses. */ bool addressInArena(void *ptr) const { return ptr >= base && ptr < end; } private: typedef std::multimap<size_t, char*> SizeToChunkSortedMap; /** Map to enable O(log(n)) best-fit allocation, as it's sorted by size */ SizeToChunkSortedMap size_to_free_chunk; typedef std::unordered_map<char*, SizeToChunkSortedMap::const_iterator> ChunkToSizeMap; /** Map from begin of free chunk to its node in size_to_free_chunk */ ChunkToSizeMap chunks_free; /** Map from end of free chunk to its node in size_to_free_chunk */ ChunkToSizeMap chunks_free_end; /** Map from begin of used chunk to its size */ std::unordered_map<char*, size_t> chunks_used; /** Base address of arena */ char* base; /** End address of arena */ char* end; /** Minimum chunk alignment */ size_t alignment; }; /** Pool for locked memory chunks. * * To avoid sensitive key data from being swapped to disk, the memory in this pool * is locked/pinned. * * An arena manages a contiguous region of memory. The pool starts out with one arena * but can grow to multiple arenas if the need arises. * * Unlike a normal C heap, the administrative structures are separate from the managed * memory. This has been done as the sizes and bases of objects are not in themselves sensitive * information, as to conserve precious locked memory. In some operating systems * the amount of memory that can be locked is small. */ class LockedPool { public: /** Size of one arena of locked memory. This is a compromise. * Do not set this too low, as managing many arenas will increase * allocation and deallocation overhead. Setting it too high allocates * more locked memory from the OS than strictly necessary. */ static const size_t ARENA_SIZE = 256*1024; /** Chunk alignment. Another compromise. Setting this too high will waste * memory, setting it too low will facilitate fragmentation. */ static const size_t ARENA_ALIGN = 16; /** Callback when allocation succeeds but locking fails. */ typedef bool (*LockingFailed_Callback)(); /** Memory statistics. */ struct Stats { size_t used; size_t free; size_t total; size_t locked; size_t chunks_used; size_t chunks_free; }; /** Create a new LockedPool. This takes ownership of the MemoryPageLocker, * you can only instantiate this with LockedPool(std::move(...)). * * The second argument is an optional callback when locking a newly allocated arena failed. * If this callback is provided and returns false, the allocation fails (hard fail), if * it returns true the allocation proceeds, but it could warn. */ explicit LockedPool(std::unique_ptr<LockedPageAllocator> allocator, LockingFailed_Callback lf_cb_in = nullptr); ~LockedPool(); LockedPool(const LockedPool& other) = delete; // non construction-copyable LockedPool& operator=(const LockedPool&) = delete; // non copyable /** Allocate size bytes from this arena. * Returns pointer on success, or 0 if memory is full or * the application tried to allocate 0 bytes. */ void* alloc(size_t size); /** Free a previously allocated chunk of memory. * Freeing the zero pointer has no effect. * Raises std::runtime_error in case of error. */ void free(void *ptr); /** Get pool usage statistics */ Stats stats() const; private: std::unique_ptr<LockedPageAllocator> allocator; /** Create an arena from locked pages */ class LockedPageArena: public Arena { public: LockedPageArena(LockedPageAllocator *alloc_in, void *base_in, size_t size, size_t align); ~LockedPageArena(); private: void *base; size_t size; LockedPageAllocator *allocator; }; bool new_arena(size_t size, size_t align); std::list<LockedPageArena> arenas; LockingFailed_Callback lf_cb; size_t cumulative_bytes_locked; /** Mutex protects access to this pool's data structures, including arenas. */ mutable std::mutex mutex; }; /** * Singleton class to keep track of locked (ie, non-swappable) memory, for use in * std::allocator templates. * * Some implementations of the STL allocate memory in some constructors (i.e., see * MSVC's vector<T> implementation where it allocates 1 byte of memory in the allocator.) * Due to the unpredictable order of static initializers, we have to make sure the * LockedPoolManager instance exists before any other STL-based objects that use * secure_allocator are created. So instead of having LockedPoolManager also be * static-initialized, it is created on demand. */ class LockedPoolManager : public LockedPool { public: /** Return the current instance, or create it once */ static LockedPoolManager& Instance() { static std::once_flag init_flag; std::call_once(init_flag, LockedPoolManager::CreateInstance); return *LockedPoolManager::_instance; } private: explicit LockedPoolManager(std::unique_ptr<LockedPageAllocator> allocator); /** Create a new LockedPoolManager specialized to the OS */ static void CreateInstance(); /** Called when locking fails, warn the user here */ static bool LockingFailed(); static LockedPoolManager* _instance; }; #endif // BITCOIN_SUPPORT_LOCKEDPOOL_H
{ "content_hash": "6b1052b510add072882c2178a2a5077c", "timestamp": "", "source": "github", "line_count": 240, "max_line_length": 115, "avg_line_length": 33.44166666666667, "alnum_prop": 0.6814104161475205, "repo_name": "litecoin-project/litecoin", "id": "b9e2e99d1aba27b44f7dec7f890902fbf433b98f", "size": "8026", "binary": false, "copies": "5", "ref": "refs/heads/master", "path": "src/support/lockedpool.h", "mode": "33188", "license": "mit", "language": [ { "name": "Assembly", "bytes": "898000" }, { "name": "C", "bytes": "1594708" }, { "name": "C++", "bytes": "8860047" }, { "name": "CMake", "bytes": "29310" }, { "name": "HTML", "bytes": "21833" }, { "name": "Java", "bytes": "30291" }, { "name": "M4", "bytes": "226003" }, { "name": "Makefile", "bytes": "123607" }, { "name": "Objective-C++", "bytes": "5489" }, { "name": "Python", "bytes": "2267056" }, { "name": "QMake", "bytes": "798" }, { "name": "Sage", "bytes": "31382" }, { "name": "Scheme", "bytes": "7554" }, { "name": "Shell", "bytes": "150309" } ], "symlink_target": "" }
require 'hrt_bus' require 'factory_girl' require 'ap' require 'forgery' require 'support/vcr_setup' require 'tempfile' RSpec.configure do |config| config.treat_symbols_as_metadata_keys_with_true_values = true config.run_all_when_everything_filtered = true config.filter_run :focus end
{ "content_hash": "d9247706902d29132c4285693838fcc7", "timestamp": "", "source": "github", "line_count": 12, "max_line_length": 63, "avg_line_length": 24.333333333333332, "alnum_prop": 0.7671232876712328, "repo_name": "bds/hrt_bus", "id": "84676f296e0a2289e4e824fbf31c69d6e50c8655", "size": "292", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "spec/spec_helper.rb", "mode": "33188", "license": "mit", "language": [ { "name": "Ruby", "bytes": "20000" } ], "symlink_target": "" }
package es.dlacalle.pfg.servicios; import android.app.Notification; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.os.Bundle; import android.service.notification.NotificationListenerService; import android.service.notification.StatusBarNotification; public class ServicioNotificaciones extends NotificationListenerService { private NLServiceReceiver nlservicereciver; @Override public void onCreate() { super.onCreate(); nlservicereciver = new NLServiceReceiver(); IntentFilter filter = new IntentFilter(); filter.addAction("es.dlacalle.pfg.servicios.NOTIFICATION_LISTENER_SERVICE_EXAMPLE"); registerReceiver(nlservicereciver, filter); } @Override public void onDestroy() { super.onDestroy(); unregisterReceiver(nlservicereciver); } @Override public void onNotificationPosted(StatusBarNotification sbn) { Intent i = new Intent("es.dlacalle.pfg.servicios.NOTIFICATION_LISTENER_EXAMPLE"); Bundle extras = sbn.getNotification().extras; String title = extras.getString("android.title"); String text = ""; CharSequence[] multiline; if (extras.getCharSequence(Notification.EXTRA_TEXT) == null) { multiline = extras.getCharSequenceArray(Notification.EXTRA_TEXT_LINES); //text = (String) extras.getCharSequence("android.textLines");//.toString(); for (CharSequence line : multiline) { text += line.toString() + "\n"; } } else { text = extras.getCharSequence(Notification.EXTRA_TEXT).toString(); } //i.putExtra("notification_event","onNotificationPosted :" + sbn.getPackageName() + "\n"); i.putExtra("notification_event", title + ": " + text); i.putExtra("notification_paquete", sbn.getPackageName()); sendBroadcast(i); } @Override public void onNotificationRemoved(StatusBarNotification sbn) { Intent i = new Intent("es.dlacalle.pfg.servicios.NOTIFICATION_LISTENER_EXAMPLE"); i.putExtra("notification_event", "onNotificationRemoved :" + sbn.getPackageName() + "\n"); //i.putExtra("notification_paquete", sbn.getPackageName()); sendBroadcast(i); } class NLServiceReceiver extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { if (intent.getStringExtra("command").equals("clearall")) { ServicioNotificaciones.this.cancelAllNotifications(); } else if (intent.getStringExtra("command").equals("list")) { Intent i1 = new Intent("es.dlacalle.pfg.servicios.NOTIFICATION_LISTENER_EXAMPLE"); i1.putExtra("notification_event", "========================"); i1.putExtra("notification_paquete", "Separador"); sendBroadcast(i1); int i = 1; for (StatusBarNotification sbn : ServicioNotificaciones.this.getActiveNotifications()) { Intent i2 = new Intent("es.dlacalle.pfg.servicios.NOTIFICATION_LISTENER_EXAMPLE"); Bundle extras = sbn.getNotification().extras; String title = extras.getString(Notification.EXTRA_TITLE); String text = ""; CharSequence[] multiline; if (extras.getCharSequence(Notification.EXTRA_TEXT) == null) { multiline = extras.getCharSequenceArray(Notification.EXTRA_TEXT_LINES); for (CharSequence line : multiline) { text += line.toString() + "\n"; } } else { text = extras.getCharSequence(Notification.EXTRA_TEXT).toString(); } i2.putExtra("notification_event", i + " - " + title + ": " + text + ""); i2.putExtra("notification_paquete", sbn.getPackageName()); sendBroadcast(i2); i++; } Intent i3 = new Intent("es.dlacalle.pfg.servicios.NOTIFICATION_LISTENER_EXAMPLE"); i3.putExtra("notification_event", "===== Notification List ===="); i3.putExtra("notification_paquete", "Separador"); sendBroadcast(i3); } } } }
{ "content_hash": "7f8bf5f3b6ca07a88f35e65825119114", "timestamp": "", "source": "github", "line_count": 116, "max_line_length": 104, "avg_line_length": 39.43103448275862, "alnum_prop": 0.5975076519457805, "repo_name": "kraventh/PFG", "id": "dd6ffc85d3e526bd60a6ca0add2f4fcf9027ac3c", "size": "4574", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "Application/src/main/java/es/dlacalle/pfg/servicios/ServicioNotificaciones.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "163199" } ], "symlink_target": "" }
<?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd" > <mapper namespace="com.appleframework.qos.server.statistics.dao.DayStatMethodDao"> <resultMap id="baseResultMap" type="com.appleframework.qos.server.core.entity.DayStatMethod"> <id column="id" property="id" jdbcType="BIGINT" /> <result column="provider_app_id" property="providerAppId" jdbcType="BIGINT" /> <result column="provider_app_name" property="providerAppName" jdbcType="VARCHAR" /> <result column="consumer_app_id" property="consumerAppId" jdbcType="BIGINT" /> <result column="consumer_app_name" property="consumerAppName" jdbcType="VARCHAR" /> <result column="service" property="service" jdbcType="VARCHAR" /> <result column="method" property="method" jdbcType="VARCHAR" /> <result column="stat_date" property="statDate" jdbcType="TIMESTAMP" /> <result column="create_time" property="createTime" jdbcType="TIMESTAMP" /> <result column="update_time" property="updateTime" jdbcType="TIMESTAMP" /> <result column="fail_sum_number" property="failSumNumber" jdbcType="BIGINT" /> <result column="fail_avg_elapsed" property="failAvgElapsed" jdbcType="BIGINT" /> <result column="fail_max_elapsed" property="succMaxElapsed" jdbcType="BIGINT" /> <result column="succ_sum_number" property="succSumNumber" jdbcType="BIGINT" /> <result column="succ_avg_elapsed" property="succAvgElapsed" jdbcType="BIGINT" /> <result column="succ_max_elapsed" property="succMaxElapsed" jdbcType="BIGINT" /> <result column="total_sum_number" property="totalSumNumber" jdbcType="BIGINT" /> <result column="total_avg_elapsed" property="totalAvgElapsed" jdbcType="BIGINT" /> <result column="total_succ_per" property="totalSuccPer" jdbcType="DOUBLE" /> </resultMap> <sql id="baseColumnList"> id, provider_app_id, provider_app_name, consumer_app_id, consumer_app_name, service, method, stat_date, create_time, update_time, fail_sum_number, fail_avg_elapsed, fail_max_elapsed, succ_sum_number, succ_avg_elapsed, succ_max_elapsed, total_sum_number, total_avg_elapsed, total_succ_per </sql> <insert id="insert" parameterType="com.appleframework.qos.server.core.entity.DayStatMethod"> insert into qos_stat_day_method ( provider_app_id, provider_app_name, consumer_app_id, consumer_app_name, service, method, fail_sum_number, fail_avg_elapsed, fail_max_elapsed, succ_sum_number, succ_avg_elapsed, succ_max_elapsed, total_sum_number, total_avg_elapsed, total_succ_per, stat_date, create_time ) values ( #{providerAppId, jdbcType=INTEGER}, #{providerAppName, jdbcType=VARCHAR}, #{consumerAppId, jdbcType=INTEGER}, #{consumerAppName, jdbcType=VARCHAR}, #{service, jdbcType=VARCHAR}, #{method, jdbcType=VARCHAR}, #{failSumNumber, jdbcType=BIGINT}, #{failAvgElapsed, jdbcType=BIGINT}, #{failMaxElapsed, jdbcType=BIGINT}, #{succSumNumber, jdbcType=BIGINT}, #{succAvgElapsed, jdbcType=BIGINT}, #{succMaxElapsed, jdbcType=BIGINT}, #{totalSumNumber, jdbcType=BIGINT}, #{totalAvgElapsed, jdbcType=BIGINT}, #{totalSuccPer, jdbcType=DOUBLE}, #{statDate, jdbcType=TIMESTAMP}, #{createTime, jdbcType=TIMESTAMP} ) </insert> <update id="update" parameterType="com.appleframework.qos.server.core.entity.DayStatMethod"> update qos_stat_day_method set fail_sum_number = ${failSumNumber}, fail_avg_elapsed = ${failAvgElapsed}, fail_max_elapsed = ${failMaxElapsed}, succ_sum_number = ${succSumNumber}, succ_avg_elapsed = ${succAvgElapsed}, succ_max_elapsed = ${succMaxElapsed}, total_sum_number = ${totalSumNumber}, total_avg_elapsed = ${totalAvgElapsed}, total_succ_per = ${totalSuccPer}, update_time = #{updateTime, jdbcType=TIMESTAMP} where id = #{id, jdbcType=BIGINT} </update> <select id="getByDate" resultMap="baseResultMap" parameterType="com.appleframework.qos.core.orm.MapQuery"> select <include refid="baseColumnList" /> from qos_stat_day_method where provider_app_id = ${providerAppId} and consumer_app_id = ${consumerAppId} and service = '${service}' and method = '${method}' and stat_date = #{statDate, jdbcType=TIMESTAMP} limit 1 </select> <select id="findPageByAppAndDay" resultMap="baseResultMap" parameterType="com.appleframework.qos.core.orm.PageQuery"> select <include refid="baseColumnList" /> from qos_stat_day_method <trim prefix="where" prefixOverrides="and"> <if test="startDate!=null"> stat_date >= #{startDate, jdbcType=TIMESTAMP} </if> <if test="endDate!=null"> stat_date &lt;= #{endDate, jdbcType=TIMESTAMP} </if> <if test="consumerAppName!=null"> and consumer_app_name like '%${consumerAppName}%' </if> <if test="providerAppName!=null"> and provider_app_name like '%${providerAppName}%' </if> <if test="service!=null"> and service like '%${service}%' </if> <if test="method!=null"> and method like '%${method}%' </if> </trim> order by stat_date desc, total_sum_number desc </select> <update id="createTable"> CREATE TABLE IF NOT EXISTS qos_stat_day_method ( id int(11) NOT NULL AUTO_INCREMENT, stat_date date DEFAULT NULL COMMENT '统计时间', provider_app_id int(11) DEFAULT NULL COMMENT '服务提供方应用ID', provider_app_name varchar(64) CHARACTER SET utf8 DEFAULT NULL COMMENT '服务提供方名称', consumer_app_id int(11) DEFAULT NULL COMMENT '服务消费方应用ID', consumer_app_name varchar(64) CHARACTER SET utf8 DEFAULT NULL COMMENT '服务消费方名称', service varchar(255) COLLATE utf8_bin DEFAULT NULL COMMENT '服务名称', method varchar(64) CHARACTER SET utf8 DEFAULT NULL COMMENT '方法', fail_sum_number bigint(20) DEFAULT NULL COMMENT '调用失败总数', fail_avg_elapsed bigint(20) DEFAULT NULL COMMENT '调用失败平均耗时', fail_max_elapsed bigint(20) DEFAULT NULL COMMENT '调用失败最大耗时', succ_sum_number bigint(20) DEFAULT NULL COMMENT '调用成功总数', succ_avg_elapsed bigint(20) DEFAULT NULL COMMENT '调用成功平均耗时', succ_max_elapsed bigint(20) DEFAULT NULL COMMENT '调用成功最大耗时', total_sum_number bigint(20) DEFAULT NULL COMMENT '调用总次数', total_avg_elapsed bigint(20) DEFAULT NULL COMMENT '调用总平均耗时', total_succ_per double DEFAULT NULL COMMENT '调用成功比率', create_time timestamp NULL DEFAULT NULL COMMENT '信息入库时间', update_time timestamp NULL DEFAULT NULL ON UPDATE CURRENT_TIMESTAMP COMMENT '信息更新时间', PRIMARY KEY (id) ) ENGINE=InnoDB AUTO_INCREMENT=1000 DEFAULT CHARSET=utf8; </update> </mapper>
{ "content_hash": "f46a16e8073812d909b0b00523abaa5a", "timestamp": "", "source": "github", "line_count": 183, "max_line_length": 118, "avg_line_length": 38.09289617486339, "alnum_prop": 0.6693444269114904, "repo_name": "yungoo/apple-qos", "id": "939779603d91aa9e60ec7dd357e56249809bdbff", "size": "7195", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "apple-qos-server/apple-qos-server-statistics/target/classes/mapper/DayStatMethodMapper.xml", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "ActionScript", "bytes": "141792" }, { "name": "Batchfile", "bytes": "226" }, { "name": "CSS", "bytes": "152194" }, { "name": "Java", "bytes": "408012" }, { "name": "JavaScript", "bytes": "624704" }, { "name": "Shell", "bytes": "1251" } ], "symlink_target": "" }
def make_parent(parent: str) -> str: # Sample function parameter parent in list_data_labeling_jobs_sample parent = parent return parent
{ "content_hash": "60b3f2d51718613d7e831bafbbd6b1f3", "timestamp": "", "source": "github", "line_count": 6, "max_line_length": 72, "avg_line_length": 25, "alnum_prop": 0.7066666666666667, "repo_name": "sasha-gitg/python-aiplatform", "id": "262b8ef6e9b2416f5782950a801a8fcc6aec8ac9", "size": "727", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": ".sample_configs/param_handlers/list_data_labeling_jobs_sample.py", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Dockerfile", "bytes": "1700" }, { "name": "Python", "bytes": "11216304" }, { "name": "Shell", "bytes": "30838" } ], "symlink_target": "" }
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <!-- NewPage --> <html lang="en"> <head> <!-- Generated by javadoc (1.8.0_92) on Wed Jul 27 21:27:47 CEST 2016 --> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>net.sourceforge.pmd.cpd Class Hierarchy (PMD Ruby 5.5.1 Test API)</title> <meta name="date" content="2016-07-27"> <link rel="stylesheet" type="text/css" href="../../../../stylesheet.css" title="Style"> <script type="text/javascript" src="../../../../script.js"></script> </head> <body> <script type="text/javascript"><!-- try { if (location.href.indexOf('is-external=true') == -1) { parent.document.title="net.sourceforge.pmd.cpd Class Hierarchy (PMD Ruby 5.5.1 Test API)"; } } catch(err) { } //--> </script> <noscript> <div>JavaScript is disabled on your browser.</div> </noscript> <!-- ========= START OF TOP NAVBAR ======= --> <div class="topNav"><a name="navbar.top"> <!-- --> </a> <div class="skipNav"><a href="#skip.navbar.top" title="Skip navigation links">Skip navigation links</a></div> <a name="navbar.top.firstrow"> <!-- --> </a> <ul class="navList" title="Navigation"> <li><a href="../../../../overview-summary.html">Overview</a></li> <li><a href="package-summary.html">Package</a></li> <li>Class</li> <li>Use</li> <li class="navBarCell1Rev">Tree</li> <li><a href="../../../../deprecated-list.html">Deprecated</a></li> <li><a href="../../../../index-all.html">Index</a></li> <li><a href="../../../../help-doc.html">Help</a></li> </ul> </div> <div class="subNav"> <ul class="navList"> <li><a href="../../../../net/sourceforge/pmd/package-tree.html">Prev</a></li> <li>Next</li> </ul> <ul class="navList"> <li><a href="../../../../index.html?net/sourceforge/pmd/cpd/package-tree.html" target="_top">Frames</a></li> <li><a href="package-tree.html" target="_top">No&nbsp;Frames</a></li> </ul> <ul class="navList" id="allclasses_navbar_top"> <li><a href="../../../../allclasses-noframe.html">All&nbsp;Classes</a></li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_top"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } //--> </script> </div> <a name="skip.navbar.top"> <!-- --> </a></div> <!-- ========= END OF TOP NAVBAR ========= --> <div class="header"> <h1 class="title">Hierarchy For Package net.sourceforge.pmd.cpd</h1> <span class="packageHierarchyLabel">Package Hierarchies:</span> <ul class="horizontal"> <li><a href="../../../../overview-tree.html">All Packages</a></li> </ul> </div> <div class="contentContainer"> <h2 title="Class Hierarchy">Class Hierarchy</h2> <ul> <li type="circle">java.lang.<a href="http://docs.oracle.com/javase/8/docs/api/java/lang/Object.html?is-external=true" title="class or interface in java.lang"><span class="typeNameLink">Object</span></a> <ul> <li type="circle">net.sourceforge.pmd.testframework.<a href="http://pmd.sourceforge.net/pmd-core/apidocs/net/sourceforge/pmd/testframework.AbstractTokenizerTest.html?is-external=true" title="class or interface in net.sourceforge.pmd"><span class="typeNameLink">AbstractTokenizerTest</span></a> <ul> <li type="circle">net.sourceforge.pmd.cpd.<a href="../../../../net/sourceforge/pmd/cpd/RubyTokenizerTest.html" title="class in net.sourceforge.pmd.cpd"><span class="typeNameLink">RubyTokenizerTest</span></a></li> </ul> </li> </ul> </li> </ul> </div> <!-- ======= START OF BOTTOM NAVBAR ====== --> <div class="bottomNav"><a name="navbar.bottom"> <!-- --> </a> <div class="skipNav"><a href="#skip.navbar.bottom" title="Skip navigation links">Skip navigation links</a></div> <a name="navbar.bottom.firstrow"> <!-- --> </a> <ul class="navList" title="Navigation"> <li><a href="../../../../overview-summary.html">Overview</a></li> <li><a href="package-summary.html">Package</a></li> <li>Class</li> <li>Use</li> <li class="navBarCell1Rev">Tree</li> <li><a href="../../../../deprecated-list.html">Deprecated</a></li> <li><a href="../../../../index-all.html">Index</a></li> <li><a href="../../../../help-doc.html">Help</a></li> </ul> </div> <div class="subNav"> <ul class="navList"> <li><a href="../../../../net/sourceforge/pmd/package-tree.html">Prev</a></li> <li>Next</li> </ul> <ul class="navList"> <li><a href="../../../../index.html?net/sourceforge/pmd/cpd/package-tree.html" target="_top">Frames</a></li> <li><a href="package-tree.html" target="_top">No&nbsp;Frames</a></li> </ul> <ul class="navList" id="allclasses_navbar_bottom"> <li><a href="../../../../allclasses-noframe.html">All&nbsp;Classes</a></li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_bottom"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } //--> </script> </div> <a name="skip.navbar.bottom"> <!-- --> </a></div> <!-- ======== END OF BOTTOM NAVBAR ======= --> <p class="legalCopy"><small>Copyright &#169; 2002&#x2013;2016 <a href="http://pmd.sourceforge.net/">InfoEther</a>. All rights reserved.</small></p> </body> </html>
{ "content_hash": "6602cafd330acc8643b05837074d1e0c", "timestamp": "", "source": "github", "line_count": 143, "max_line_length": 293, "avg_line_length": 36.49650349650349, "alnum_prop": 0.6319218241042345, "repo_name": "jasonwee/videoOnCloud", "id": "ad6a94fb7a10bf94dca088c9e45a22ac68a1c45e", "size": "5219", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "pmd/pmd-doc-5.5.1/pmd-ruby/testapidocs/net/sourceforge/pmd/cpd/package-tree.html", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Batchfile", "bytes": "116270" }, { "name": "C", "bytes": "2209717" }, { "name": "C++", "bytes": "375267" }, { "name": "CSS", "bytes": "1134648" }, { "name": "Dockerfile", "bytes": "1656" }, { "name": "HTML", "bytes": "306558398" }, { "name": "Java", "bytes": "1465506" }, { "name": "JavaScript", "bytes": "9028509" }, { "name": "Jupyter Notebook", "bytes": "30907" }, { "name": "Less", "bytes": "107003" }, { "name": "PHP", "bytes": "856" }, { "name": "PowerShell", "bytes": "77807" }, { "name": "Pug", "bytes": "2968" }, { "name": "Python", "bytes": "1001861" }, { "name": "R", "bytes": "7390" }, { "name": "Roff", "bytes": "3553" }, { "name": "Shell", "bytes": "206191" }, { "name": "Thrift", "bytes": "80564" }, { "name": "XSLT", "bytes": "4740" } ], "symlink_target": "" }
import {AccessClientAdapter} from '../../amp-access/0.1/amp-access-client'; import {CSS} from '../../../build/amp-access-scroll-0.1.css'; import {PROTOCOL_VERSION} from './scroll-protocol'; import {ReadDepthTracker} from './read-depth-tracker.js'; import {Relay} from './scroll-relay'; import {ScrollBar} from './scroll-bar'; import {Services} from '../../../src/services'; import {Sheet} from './scroll-sheet'; import {createElementWithAttributes} from '../../../src/dom'; import {dict} from '../../../src/utils/object'; import {getMode} from '../../../src/mode'; import {installStylesForDoc} from '../../../src/style-installer'; import {parseQueryString} from '../../../src/url'; const TAG = 'amp-access-scroll-elt'; /** * @param {string} baseUrl * @return {!JsonObject} */ const accessConfig = (baseUrl) => { /** @const {!JsonObject} */ const ACCESS_CONFIG = /** @type {!JsonObject} */ ({ 'authorization': `${baseUrl}/amp/access` + '?rid=READER_ID' + '&cid=CLIENT_ID(scroll1)' + '&c=CANONICAL_URL' + '&o=AMPDOC_URL' + '&x=QUERY_PARAM(scrollx)' + `&p=${PROTOCOL_VERSION}`, 'pingback': `${baseUrl}/amp/pingback` + '?rid=READER_ID' + '&cid=CLIENT_ID(scroll1)' + '&c=CANONICAL_URL' + '&o=AMPDOC_URL' + '&r=DOCUMENT_REFERRER' + '&x=QUERY_PARAM(scrollx)' + '&d=AUTHDATA(scroll)' + '&v=AUTHDATA(visitId)' + `&p=${PROTOCOL_VERSION}`, 'namespace': 'scroll', }); return ACCESS_CONFIG; }; /** * @param {string} baseUrl * @return {!JsonObject} */ const analyticsConfig = (baseUrl) => { const ANALYTICS_CONFIG = /** @type {!JsonObject} */ ({ 'requests': { 'scroll': `${baseUrl}/amp/analytics` + '?rid=ACCESS_READER_ID' + '&cid=CLIENT_ID(scroll1)' + '&c=CANONICAL_URL' + '&o=AMPDOC_URL' + '&r=DOCUMENT_REFERRER' + '&x=QUERY_PARAM(scrollx)' + '&d=AUTHDATA(scroll.scroll)' + '&v=AUTHDATA(scroll.visitId)' + '&h=SOURCE_HOSTNAME' + '&s=${totalEngagedTime}' + `&p=${PROTOCOL_VERSION}`, }, 'triggers': { 'trackInterval': { 'on': 'timer', 'timerSpec': { 'interval': 15, 'maxTimerLength': 7200, }, 'request': 'scroll', }, }, }); return ANALYTICS_CONFIG; }; /** * The eTLD for scroll URLs in development mode. * * Enables amp-access-scroll to work with dev/staging environments. * * @param {!JsonObject} config * @return {string} */ const devEtld = (config) => { return getMode().development && config['etld'] ? config['etld'] : ''; }; /** * The connect server hostname. * * @param {!JsonObject} config * @return {string} */ const connectHostname = (config) => { return `https://connect${devEtld(config) || '.scroll.com'}`; }; /** * amp-access vendor that authenticates against the scroll.com service. * If the user is authenticated, also adds a fixed position iframe * to the page. * * A little gross, but avoid some duplicate code by inheriting * from ClientAdapter. * @implements {../../amp-access/0.1/access-vendor.AccessVendor} */ export class ScrollAccessVendor extends AccessClientAdapter { /** * @param {!../../../src/service/ampdoc-impl.AmpDoc} ampdoc * @param {!../../amp-access/0.1/amp-access-source.AccessSource} accessSource */ constructor(ampdoc, accessSource) { const scrollConfig = accessSource.getAdapterConfig(); const baseUrl = connectHostname(scrollConfig); super(ampdoc, accessConfig(baseUrl), { buildUrl: accessSource.buildUrl.bind(accessSource), collectUrlVars: accessSource.collectUrlVars.bind(accessSource), }); // Install styles installStylesForDoc(ampdoc, CSS, () => {}, false, TAG); /** @private {!../../amp-access/0.1/amp-access-source.AccessSource} */ this.accessSource_ = accessSource; /** @private */ this.baseUrl_ = baseUrl; } /** @override */ authorize() { // TODO(dbow): Handle timeout? return super.authorize().then((response) => { const isStory = this.ampdoc .getRootNode() .querySelector('amp-story[standalone]'); if (response && response['scroll']) { if (!isStory) { // Display Scrollbar and set up features const bar = new ScrollBar( this.ampdoc, this.accessSource_, this.baseUrl_ ); const sheet = new Sheet(this.ampdoc); const relay = new Relay(this.baseUrl_); relay.register(sheet.window, (message) => { if (message['_scramp'] === 'au' || message['_scramp'] === 'st') { sheet.update(message); } }); relay.register(bar.window, (message) => { if (message['_scramp'] === 'st') { sheet.update(message); bar.update(message); } }); const config = this.accessSource_.getAdapterConfig(); addAnalytics(this.ampdoc, config); if (response['features'] && response['features']['d']) { new ReadDepthTracker( this.ampdoc, this.accessSource_, connectHostname(config) ); } } } else { if ( response && response['blocker'] && ScrollContentBlocker.shouldCheck(this.ampdoc) ) { new ScrollContentBlocker(this.ampdoc, this.accessSource_).check(); } } return response; }); } } /** * Coordinate with the Scroll App's Content Blocker on Safari browsers. */ class ScrollContentBlocker { /** * @param {!../../../src/service/ampdoc-impl.AmpDoc} ampdoc * @return {boolean} * @static */ static shouldCheck(ampdoc) { const queryParams = parseQueryString(ampdoc.win.location.search); return !queryParams['scrollnoblockerrefresh']; } /** * @param {!../../../src/service/ampdoc-impl.AmpDoc} ampdoc * @param {!../../amp-access/0.1/amp-access-source.AccessSource} accessSource */ constructor(ampdoc, accessSource) { /** @const @private {!../../../src/service/ampdoc-impl.AmpDoc} */ this.ampdoc_ = ampdoc; /** @const @private {!../../amp-access/0.1/amp-access-source.AccessSource} */ this.accessSource_ = accessSource; } /** * Check if the Scroll App blocks the resource request. */ check() { Services.xhrFor(this.ampdoc_.win) .fetchJson('https://block.scroll.com/check.json') .then( () => false, (e) => this.blockedByScrollApp_(e.message) ) .then((blockedByScrollApp) => { if (blockedByScrollApp === true) { // TODO(dbow): Ideally we would automatically redirect to the page // here, but for now we are adding a button so we redirect on user // action. const baseUrl = connectHostname( this.accessSource_.getAdapterConfig() ); const bar = new ScrollBar(this.ampdoc_, this.accessSource_, baseUrl); const relay = new Relay(baseUrl); relay.register(bar.window, (message) => { if (message['_scramp'] === 'st') { bar.update(message); } }); } }); } /** * Whether the given error message indicates the Scroll App blocked the * request. * * @param {string} message * @return {boolean} * @private */ blockedByScrollApp_(message) { return ( message.indexOf( 'XHR Failed fetching (https://block.scroll.com/...): ' + 'Resource blocked by content blocker' ) === 0 ); } } /** * Add analytics for Scroll to page. * @param {!../../../src/service/ampdoc-impl.AmpDoc} ampdoc * @param {!JsonObject} vendorConfig */ function addAnalytics(ampdoc, vendorConfig) { if (vendorConfig['disableAnalytics']) { return; } // Create analytics element const doc = /** @type {!Document} */ (ampdoc.win.document); const attributes = dict({'trigger': 'immediate'}); if (vendorConfig['dataConsentId']) { attributes['data-block-on-consent'] = ''; } const analyticsElem = createElementWithAttributes( doc, 'amp-analytics', attributes ); const scriptElem = createElementWithAttributes( doc, 'script', dict({ 'type': 'application/json', }) ); const ANALYTICS_CONFIG = analyticsConfig(connectHostname(vendorConfig)); scriptElem.textContent = JSON.stringify(ANALYTICS_CONFIG); analyticsElem.appendChild(scriptElem); analyticsElem.CONFIG = ANALYTICS_CONFIG; // Get extensions service and force load analytics extension const extensions = Services.extensionsFor(ampdoc.win); extensions./*OK*/ installExtensionForDoc(ampdoc, 'amp-analytics'); // Append ampdoc.getBody().appendChild(analyticsElem); }
{ "content_hash": "49ee5aa297c850e7f399f97090828988", "timestamp": "", "source": "github", "line_count": 304, "max_line_length": 81, "avg_line_length": 29.154605263157894, "alnum_prop": 0.5891910188423785, "repo_name": "adup-tech/amphtml", "id": "7a9ce1d43e85376514570922f12c6efefb990036", "size": "9490", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "extensions/amp-access-scroll/0.1/scroll-impl.js", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "71752" }, { "name": "Go", "bytes": "7459" }, { "name": "HTML", "bytes": "506690" }, { "name": "Java", "bytes": "36355" }, { "name": "JavaScript", "bytes": "5661528" }, { "name": "Protocol Buffer", "bytes": "25410" }, { "name": "Python", "bytes": "68440" }, { "name": "Shell", "bytes": "4731" } ], "symlink_target": "" }
<script type="text/javascript"> $(document).ready(function(){ // $('#cambios').hide(); // var x = document.getElementsByClassName("active"); // console.log(x[0].id); // if (x[0].id != "agregar"){ // $('#busqueda').show(); // }else { // $('#busqueda').hide(); // } }); </script> <html ng-app="myApp"> <body> <!-- <ul class="nav nav-tabs nav-justified"> <li role="presentation"><a href="#">Disabled link</a></li> <li role="presentation"><a href="#">Disabled link</a></li> </ul> --> <!--navbar code --> <!-- <nav class="navbar navbar-inverse"> <div class="container-fluid"> --> <!-- Brand and toggle get grouped for better mobile display --> <!-- <div class="navbar-header"> <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1" aria-expanded="false"> <span class="sr-only">Toggle navigation</span> <span class="icon-bar"></span> <span class="icon-bar"></span> <span class="icon-bar"></span> </button> <a class="navbar-brand" href="#">Arribos</a> </div> --> <!-- Collect the nav links, forms, and other content for toggling --> <!-- <div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1"> <ul class="nav navbar-nav"> <li id="realizados" class="active"><a ui-sref="estudios.tabla">Realizados </a></li> <li id="pendientes" ><a href="estudios.">Pendientes</a></li> <li id="agregar" ><a href="#">Agregar</a></li> </ul> <form id="busqueda" class="navbar-form navbar-right"> <div class="form-group"> <input type="text" class="form-control" placeholder="Search"> </div> --> <!-- <button type="submit" class="btn btn-default">Submit</button> --> <!-- </form> --> <!-- </div> --><!-- /.navbar-collapse --> <!-- </div>--><!-- /.container-fluid --> <!-- </nav> --> <!--end navbar code --> <!--result table code --> <div ui-view="table"></div> <!--result table code --> </body> </html>
{ "content_hash": "c11a28cca1950672eb77674936e63390", "timestamp": "", "source": "github", "line_count": 55, "max_line_length": 155, "avg_line_length": 41.4, "alnum_prop": 0.510320597277119, "repo_name": "iglesiasdan/SAO", "id": "c32fcd112128d537ab99e1c957580e413e4fcfec", "size": "2277", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "Views/Pages/navbar_estudios.php", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "1360953" }, { "name": "HTML", "bytes": "3409792" }, { "name": "JavaScript", "bytes": "3170166" }, { "name": "PHP", "bytes": "3782618" } ], "symlink_target": "" }
zdk-marked ========== zdk-marked is a markdown web component based on the (polymer)[http://www.polymer-project.org] framework.
{ "content_hash": "8b14f9b0a423a13b2742143ec0e38bea", "timestamp": "", "source": "github", "line_count": 4, "max_line_length": 104, "avg_line_length": 32, "alnum_prop": 0.7109375, "repo_name": "zedesk/zdk-marked", "id": "d015e554bc5166a29ba40df4713f47234457c157", "size": "128", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "README.md", "mode": "33188", "license": "mit", "language": [ { "name": "JavaScript", "bytes": "36434" } ], "symlink_target": "" }
<!DOCTYPE html> <html ng-app="TestApp" lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <script src="angular.min.js"></script> </body> </html>
{ "content_hash": "726e6c91a2b9ebdf5be509b767b88e93", "timestamp": "", "source": "github", "line_count": 10, "max_line_length": 38, "avg_line_length": 17.8, "alnum_prop": 0.6179775280898876, "repo_name": "Avislux/avislux.github.io", "id": "ff481e6fa4c641b4b7bc65b5d4e483cc2b5362ac", "size": "178", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "coursera/test/2/index.html", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "27113" }, { "name": "HTML", "bytes": "81276" }, { "name": "JavaScript", "bytes": "148856" }, { "name": "Ruby", "bytes": "87" } ], "symlink_target": "" }
[![NPM](https://nodei.co/npm/aws-sdk.svg?downloads=true&downloadRank=true&stars=true)](https://nodei.co/npm/aws-sdk/) [![Gitter chat](https://badges.gitter.im/gitterHQ/gitter.svg)](https://gitter.im/aws/aws-sdk-js) [![Version](https://badge.fury.io/js/aws-sdk.svg)](http://badge.fury.io/js/aws-sdk) [![Build Status](https://travis-ci.org/aws/aws-sdk-js.svg?branch=master)](https://travis-ci.org/aws/aws-sdk-js) [![Coverage Status](https://coveralls.io/repos/aws/aws-sdk-js/badge.svg?branch=master)](https://coveralls.io/r/aws/aws-sdk-js?branch=master) The official AWS SDK for JavaScript, available for browsers and mobile devices, or Node.js backends Release notes can be found at http://aws.amazon.com/releasenotes/SDK/JavaScript <p class="note"> If you are upgrading from 1.x to 2.0 of the SDK, please see the {file:UPGRADING.md} notes for information on how to migrate existing code to work with the new major version. </p> ## Installing ### In the Browser To use the SDK in the browser, simply add the following script tag to your HTML pages: <script src="https://sdk.amazonaws.com/js/aws-sdk-2.4.11.min.js"></script> You can also build a custom browser SDK with your specified set of AWS services. This can allow you to reduce the SDK's size, specify different API versions of services, or use AWS services that don't currently support CORS if you are working in an environment that does not enforce CORS. To get started: http://docs.aws.amazon.com/AWSJavaScriptSDK/guide/browser-building.html The AWS SDK is also compatible with [browserify](http://browserify.org). ### In Node.js The preferred way to install the AWS SDK for Node.js is to use the [npm](http://npmjs.org) package manager for Node.js. Simply type the following into a terminal window: ```sh npm install aws-sdk ``` ### Using Bower You can also use [Bower](http://bower.io) to install the SDK by typing the following into a terminal window: ```sh bower install aws-sdk-js ``` ## Usage and Getting Started You can find a getting started guide at: http://docs.aws.amazon.com/AWSJavaScriptSDK/guide/ ## Supported Services <p class="note"><strong>Note</strong>: Although all services are supported in the browser version of the SDK, not all of the services are available in the default hosted build (using the script tag provided above). A list of services in the hosted build are provided in the "<a href="http://docs.aws.amazon.com/AWSJavaScriptSDK/guide/browser-services.html">Working With Services</a>" section of the browser SDK guide, including instructions on how to build a custom version of the SDK with extra services. </p> The SDK currently supports the following services: <table> <thead> <th>Service Name</th> <th>Class Name</th> <th>API Version</th> </thead> <tbody> <tr><td>Amazon API Gateway</td><td>AWS.APIGateway</td><td>2015-07-09</td></tr> <tr><td>Amazon CloudFront</td><td>AWS.CloudFront</td><td>2014-10-21</td></tr> <tr><td>Amazon CloudHSM</td><td>AWS.CloudHSM</td><td>2014-05-30</td></tr> <tr><td>Amazon CloudSearch</td><td>AWS.CloudSearch</td><td>2013-01-01</td></tr> <tr><td>Amazon CloudSearch Domain</td><td>AWS.CloudSearchDomain</td><td>2013-01-01</td></tr> <tr><td>Amazon CloudWatch</td><td>AWS.CloudWatch</td><td>2010-08-01</td></tr> <tr><td>Amazon CloudWatch Events</td><td>AWS.CloudWatchLogs</td><td>2015-10-07</td></tr> <tr><td>Amazon CloudWatch Logs</td><td>AWS.CloudWatchLogs</td><td>2014-03-28</td></tr> <tr><td>Amazon Cognito Identity</td><td>AWS.CognitoIdentity</td><td>2014-06-30</td></tr> <tr><td>Amazon Cognito Sync</td><td>AWS.CognitoSync</td><td>2014-06-30</td></tr> <tr><td>Amazon DynamoDB</td><td>AWS.DynamoDB</td><td>2012-08-10</td></tr> <tr><td>Amazon DynamoDB Streams</td><td>AWS.DynamoDBStreams</td><td>2012-08-10</td></tr> <tr><td>Amazon EC2 Container Registry</td><td>AWS.ECR</td><td>2015-09-21</td></tr> <tr><td>Amazon EC2 Container Service</td><td>AWS.ECS</td><td>2014-11-13</td></tr> <tr><td>Amazon Elastic Compute Cloud</td><td>AWS.EC2</td><td>2014-10-01</td></tr> <tr><td>Amazon Elastic File System</td><td>AWS.EFS</td><td>2015-02-01</td></tr> <tr><td>Amazon Elastic MapReduce</td><td>AWS.EMR</td><td>2009-03-31</td></tr> <tr><td>Amazon Elastic Transcoder</td><td>AWS.ElasticTranscoder</td><td>2012-09-25</td></tr> <tr><td>Amazon ElastiCache</td><td>AWS.ElastiCache</td><td>2014-09-30</td></tr> <tr><td>Amazon Elasticsearch Service</td><td>AWS.ES</td><td>2015-01-01</td></tr> <tr><td>Amazon GameLift</td><td>AWS.GameLift</td><td>2015-10-01</td></tr> <tr><td>Amazon Glacier</td><td>AWS.Glacier</td><td>2012-06-01</td></tr> <tr><td>Amazon Inspector</td><td>AWS.Inspector</td><td>2016-02-16</td></tr> <tr><td>Amazon Kinesis</td><td>AWS.Kinesis</td><td>2013-12-02</td></tr> <tr><td>Amazon Kinesis Firehose</td><td>AWS.Firehose</td><td>2015-08-04</td></tr> <tr><td>Amazon Machine Learning</td><td>AWS.MachineLearning</td><td>2014-12-12</td></tr> <tr><td>Amazon Mobile Analytics</td><td>AWS.MobileAnalytics</td><td>2014-06-05</td></tr> <tr><td>Amazon Redshift</td><td>AWS.Redshift</td><td>2012-12-01</td></tr> <tr><td>Amazon Relational Database Service</td><td>AWS.RDS</td><td>2014-09-01</td></tr> <tr><td>Amazon Route 53</td><td>AWS.Route53</td><td>2013-04-01</td></tr> <tr><td>Amazon Route 53 Domains</td><td>AWS.Route53Domains</td><td>2014-05-15</td></tr> <tr><td>Amazon Simple Email Service</td><td>AWS.SES</td><td>2010-12-01</td></tr> <tr><td>Amazon Simple Notification Service</td><td>AWS.SNS</td><td>2010-03-31</td></tr> <tr><td>Amazon Simple Queue Service</td><td>AWS.SQS</td><td>2012-11-05</td></tr> <tr><td>Amazon Simple Storage Service</td><td>AWS.S3</td><td>2006-03-01</td></tr> <tr><td>Amazon Simple Systems Management Service</td><td>AWS.SSM</td><td>2014-11-06</td></tr> <tr><td>Amazon Simple Workflow Service</td><td>AWS.SWF</td><td>2012-01-25</td></tr> <tr><td>Amazon SimpleDB</td><td>AWS.SimpleDB</td><td>2009-04-15</td></tr> <tr><td>Amazon WorkSpaces</td><td>AWS.WorkSpaces</td><td>2015-04-08</td></tr> <tr><td>Auto Scaling</td><td>AWS.AutoScaling</td><td>2011-01-01</td></tr> <tr><td>AWS Certificate Manager</td><td>AWS.ACM</td><td>2015-12-08</td></tr> <tr><td>AWS CloudFormation</td><td>AWS.CloudFormation</td><td>2010-05-15</td></tr> <tr><td>AWS CloudTrail</td><td>AWS.CloudTrail</td><td>2013-11-01</td></tr> <tr><td>AWS CodeCommit</td><td>AWS.CodeCommit</td><td>2015-04-13</td></tr> <tr><td>AWS CodeDeploy</td><td>AWS.CodeDeploy</td><td>2014-10-06</td></tr> <tr><td>AWS CodePipeline</td><td>AWS.CodePipeline</td><td>2015-07-09</td></tr> <tr><td>AWS Config</td><td>AWS.ConfigService</td><td>2014-11-12</td></tr> <tr><td>AWS Data Pipeline</td><td>AWS.DataPipeline</td><td>2012-10-29</td></tr> <tr><td>AWS Database Migration Service</td><td>AWS.DMS</td><td>2016-01-01</td></tr> <tr><td>AWS Device Farm</td><td>AWS.DeviceFarm</td><td>2015-06-23</td></tr> <tr><td>AWS Direct Connect</td><td>AWS.DirectConnect</td><td>2012-10-25</td></tr> <tr><td>AWS Directory Service</td><td>AWS.DirectoryService</td><td>2015-04-16</td></tr> <tr><td>AWS Elastic Beanstalk</td><td>AWS.ElasticBeanstalk</td><td>2010-12-01</td></tr> <tr><td>AWS Identity and Access Management</td><td>AWS.IAM</td><td>2010-05-08</td></tr> <tr><td>AWS Import/Export</td><td>AWS.ImportExport</td><td>2010-06-01</td></tr> <tr><td>AWS IoT</td><td>AWS.Iot</td><td>2015-05-28</td></tr> <tr><td>AWS IoT Data Plane</td><td>AWS.IotData</td><td>2015-05-28</td></tr> <tr><td>AWS Key Management Service</td><td>AWS.KMS</td><td>2014-11-01</td></tr> <tr><td>AWS Lambda</td><td>AWS.Lambda</td><td>2015-03-31</td></tr> <tr><td>AWS Marketplace Commerce Analytics</td><td>AWS.MarketplaceCommerceAnalytics</td><td>2015-07-01</td></tr> <tr><td>AWS Marketplace Metering</td><td>AWS.MarketplaceMetering</td><td>2016-01-14</td></tr> <tr><td>AWS OpsWorks</td><td>AWS.OpsWorks</td><td>2013-02-18</td></tr> <tr><td>AWS Security Token Service</td><td>AWS.STS</td><td>2011-06-15</td></tr> <tr><td>AWS Storage Gateway</td><td>AWS.StorageGateway</td><td>2013-06-30</td></tr> <tr><td>AWS Support</td><td>AWS.Support</td><td>2013-04-15</td></tr> <tr><td>AWS WAF</td><td>AWS.WAF</td><td>2015-08-24</td></tr> <tr><td>Elastic Load Balancing</td><td>AWS.ELB</td><td>2012-06-01</td></tr> </tbody> </table> ## License This SDK is distributed under the [Apache License, Version 2.0](http://www.apache.org/licenses/LICENSE-2.0), see LICENSE.txt and NOTICE.txt for more information.
{ "content_hash": "fa9643d35f2c820d661f8b08d83b222d", "timestamp": "", "source": "github", "line_count": 155, "max_line_length": 336, "avg_line_length": 55.85806451612903, "alnum_prop": 0.68006468006468, "repo_name": "allankv/bdq-framework-slides", "id": "a0a34876357f0204e99d1cd29817c6c6e5108375", "size": "8684", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "node_modules/aws-sdk/README.md", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "198654" }, { "name": "HTML", "bytes": "84799" }, { "name": "JavaScript", "bytes": "415272" } ], "symlink_target": "" }
/*19. Permutations of set Description Write a program that reads a number N and generates and prints all the permutations of the numbers [1 … N]. Sample tests N result 3 {1, 2, 3} {1, 3, 2} {2, 1, 3} {2, 3, 1} {3, 1, 2} {3, 2, 1} Submission You do not have to submit anything for this problem */ namespace PermutationsOfSet { class PermutOfSet { static void Main() { } } }
{ "content_hash": "2ca57baaa81664e2e4119a2f454772de", "timestamp": "", "source": "github", "line_count": 26, "max_line_length": 107, "avg_line_length": 16.115384615384617, "alnum_prop": 0.6157517899761337, "repo_name": "Nayaata/CSharp-part-2", "id": "97b9b95e80866c303b4cb657a09f819785166438", "size": "423", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "Arrays/PermutationsOfSet/PermutOfSet.cs", "mode": "33188", "license": "mit", "language": [ { "name": "C#", "bytes": "116530" } ], "symlink_target": "" }
Template.usermanagement.helpers({ //Find the database entries for today, or create them if they don't exist userManager: function() { return Meteor.users.find({}, { sort: { 'roles': 1, 'profile.name': 1 } }); }, });
{ "content_hash": "33f8ecf3f4aa5a79d55883a1970a609c", "timestamp": "", "source": "github", "line_count": 11, "max_line_length": 77, "avg_line_length": 27.181818181818183, "alnum_prop": 0.49498327759197325, "repo_name": "Noamyoungerm/kiosk-point-of-sale", "id": "cc92c7358d348c2679df5b9498efed4d938e4df0", "size": "299", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "client/usermanagement/usermanagement.js", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "260" }, { "name": "HTML", "bytes": "10902" }, { "name": "JavaScript", "bytes": "23439" } ], "symlink_target": "" }
require 'tush/helpers/association_helpers' require "set" module Tush # This holds the collection of models that will be exported. class ModelStore attr_accessor :model_wrappers, :blacklisted_models, :copy_only_models, :model_instances def initialize(opts={}) self.blacklisted_models = Set.new(opts[:blacklisted_models] || []) self.copy_only_models = Set.new(opts[:copy_only_models] || []) self.model_wrappers = Set.new self.model_instances = Set.new end def push_array(model_array) model_array.each { |model_instance| self.push(model_instance) } end def push(model_instance, parent_wrapper=nil) return if self.object_in_stack?(model_instance) return if self.blacklisted_models.include?(model_instance.class) if model_instance.respond_to?(:copy_with_tush?) return unless model_instance.copy_with_tush? end model_wrapper = ModelWrapper.new(:model => model_instance) model_wrapper.model_blacklist = blacklisted_models unless Tush.disable_model_trace if parent_wrapper and parent_wrapper.model_trace.any? model_wrapper.add_model_trace_list(parent_wrapper.model_trace) model_wrapper.add_model_trace(parent_wrapper) elsif parent_wrapper model_wrapper.add_model_trace(parent_wrapper) end end model_wrappers << model_wrapper model_instances << [model_wrapper.model_class, model_wrapper.model_attributes["id"]] return if self.copy_only_models.include?(model_instance.class) model_wrapper.association_objects.each do |object| self.push(object, model_wrapper) end end def object_in_stack?(model_instance) model_instances.include?([model_instance.class, model_instance.attributes["id"]]) end def export { :model_wrappers => self.model_wrappers.map { |model_wrapper| model_wrapper.export } } end end end
{ "content_hash": "1aab0f713c3d0a5d05802858046682d4", "timestamp": "", "source": "github", "line_count": 62, "max_line_length": 93, "avg_line_length": 31.403225806451612, "alnum_prop": 0.6810477657935285, "repo_name": "3dna/tush", "id": "d5cc083223dcf522640cf855107f4aa6f9148a7b", "size": "1947", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "lib/tush/model_store.rb", "mode": "33188", "license": "mit", "language": [ { "name": "Ruby", "bytes": "41717" } ], "symlink_target": "" }
package com.opengamma.id; import static org.testng.Assert.assertEquals; import static org.testng.Assert.assertFalse; import static org.testng.Assert.assertTrue; import java.util.Arrays; import java.util.Collections; import java.util.LinkedHashMap; import java.util.Map; import org.testng.annotations.Test; import com.google.common.collect.ImmutableMap; import com.opengamma.test.Assert; import com.opengamma.util.test.TestGroup; /** * Test {@link UniqueIdSchemeDelegator}. */ @Test(groups = TestGroup.UNIT) public class UniqueIdSchemeDelegatorTest { /** * Constructs a delegator with only the default set. */ @Test public void testConstructorDefaultOnly() { final UniqueIdSchemeDelegator<String> test = new UniqueIdSchemeDelegator<>("default"); assertEquals(test.chooseDelegate("A"), "default"); assertEquals(test.chooseDelegate("B"), "default"); assertEquals(test.getDefaultDelegate(), "default"); assertEquals(test.getDelegates(), Collections.emptyMap()); } /** * Tests that the default cannot be null. */ @Test(expectedExceptions = IllegalArgumentException.class) public void testConstructorDefaultOnlyNullDefault() { new UniqueIdSchemeDelegator<String>(null); } //------------------------------------------------------------------------- /** * Constructs a delegator from a map. */ @Test public void testConstructorDefaultAndMap() { final Map<String, String> map = new LinkedHashMap<>(); map.put("A", "adapt"); map.put("B", "bootup"); map.put("C", "curve"); final UniqueIdSchemeDelegator<String> test = new UniqueIdSchemeDelegator<>("default", map); assertEquals(test.chooseDelegate("A"), "adapt"); assertEquals(test.chooseDelegate("B"), "bootup"); assertEquals(test.chooseDelegate("C"), "curve"); assertEquals(test.chooseDelegate("D"), "default"); assertEquals(test.getDefaultDelegate(), "default"); assertEquals(test.getDelegates(), map); Assert.assertEqualsNoOrder(test.getAllDelegates(), Arrays.asList("default", "adapt", "bootup", "curve")); } /** * Tests that the register of delegates is immutable. */ @Test(expectedExceptions = UnsupportedOperationException.class) public void testImmutableDelegateRegister() { final Map<String, String> map = ImmutableMap.of("A", "adapt", "B", "bootup", "C", "curve"); final UniqueIdSchemeDelegator<String> test = new UniqueIdSchemeDelegator<>("default", map); test.getDelegates().clear(); } /** * Tests that the default cannot be null. */ @Test(expectedExceptions = IllegalArgumentException.class) public void testConstructorDefaultAndMapNullDefault() { final Map<String, String> map = ImmutableMap.of("A", "adapt", "B", "bootup", "C", "curve"); new UniqueIdSchemeDelegator<>(null, map); } /** * Tests that the map of delegates cannot be null. */ @Test(expectedExceptions = IllegalArgumentException.class) public void testConstructorDefaultAndMapNullMap() { new UniqueIdSchemeDelegator<>("default", null); } //------------------------------------------------------------------------- /** * Tests the registration and removal of delegates. */ @Test public void testRegisterDelegateRemoveDelegate() { final Map<String, String> map = ImmutableMap.of("A", "adapt", "B", "bootup"); final UniqueIdSchemeDelegator<String> test = new UniqueIdSchemeDelegator<>("default", map); assertEquals(test.chooseDelegate("A"), "adapt"); assertEquals(test.chooseDelegate("B"), "bootup"); assertEquals(test.chooseDelegate("C"), "default"); assertEquals(test.chooseDelegate("D"), "default"); assertTrue(test.registerDelegate("C", "curve")); assertFalse(test.registerDelegate("C", "curve")); assertEquals(test.chooseDelegate("A"), "adapt"); assertEquals(test.chooseDelegate("B"), "bootup"); assertEquals(test.chooseDelegate("C"), "curve"); assertEquals(test.chooseDelegate("D"), "default"); test.removeDelegate("C"); assertEquals(test.chooseDelegate("A"), "adapt"); assertEquals(test.chooseDelegate("B"), "bootup"); assertEquals(test.chooseDelegate("C"), "default"); assertEquals(test.chooseDelegate("D"), "default"); } /** * Tests that the scheme cannot be null. */ @Test(expectedExceptions = IllegalArgumentException.class) public void testRegisterDelegateNullScheme() { final UniqueIdSchemeDelegator<String> test = new UniqueIdSchemeDelegator<>("default"); test.registerDelegate(null, "default"); } /** * Tests that the delegate cannot be null. */ @Test(expectedExceptions = IllegalArgumentException.class) public void testRegisterDelegateNullDelegate() { final UniqueIdSchemeDelegator<String> test = new UniqueIdSchemeDelegator<>("default"); test.registerDelegate("default", null); } /** * Tests that the null cannot be removed. */ @Test(expectedExceptions = IllegalArgumentException.class) public void testRemoveDelegateNull() { final UniqueIdSchemeDelegator<String> test = new UniqueIdSchemeDelegator<>("default"); test.removeDelegate(null); } }
{ "content_hash": "a2ff8e4f2d73d48a8bd35744db285fb9", "timestamp": "", "source": "github", "line_count": 144, "max_line_length": 109, "avg_line_length": 35.604166666666664, "alnum_prop": 0.6892919836161499, "repo_name": "McLeodMoores/starling", "id": "5584f2f9c0b49d57a3b436a4e78df6a43d228d6a", "size": "5264", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "projects/util/src/test/java/com/opengamma/id/UniqueIdSchemeDelegatorTest.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Batchfile", "bytes": "2505" }, { "name": "CSS", "bytes": "213501" }, { "name": "FreeMarker", "bytes": "310184" }, { "name": "GAP", "bytes": "1490" }, { "name": "Groovy", "bytes": "11518" }, { "name": "HTML", "bytes": "318295" }, { "name": "Java", "bytes": "79541905" }, { "name": "JavaScript", "bytes": "1511230" }, { "name": "PLSQL", "bytes": "398" }, { "name": "PLpgSQL", "bytes": "26901" }, { "name": "Shell", "bytes": "11481" }, { "name": "TSQL", "bytes": "604117" } ], "symlink_target": "" }
package com.rim.samples.device.mmsdemo; import java.io.IOException; import java.io.InputStream; import javax.microedition.io.Connection; import javax.microedition.io.Connector; import javax.wireless.messaging.MessageConnection; import javax.wireless.messaging.MessagePart; import javax.wireless.messaging.MultipartMessage; import net.rim.device.api.io.IOUtilities; import net.rim.device.api.system.Bitmap; import net.rim.device.api.ui.UiApplication; import net.rim.device.api.ui.component.Dialog; import net.rim.device.api.ui.component.EditField; import net.rim.device.api.ui.component.table.TableModel; import net.rim.device.api.ui.container.MainScreen; /** * This sample demonstrates the sending and receiving of MMS messages using the * javax.wireless.messaging APIs. Note that MMS is not supported by the * BlackBerry Smartphone simulator. */ public final class MMSDemo extends UiApplication { // The application ID that the MMS connection is opened with private static final String APP_ID = "com.rim.samples.device.mmsdemo"; private static final int CLIENT_CHOICE = 0; private static final int SERVER_CHOICE = 1; private static final String[] CHOICES = { "Send MMS", "Receive MMS", "Exit" }; static final int PICTURE = 0; static final int AUDIO = 1; // Parallel arrays containg file information private static final String[] MIME_TYPES = { "image/png", "audio/mp3" }; private static final String[] FOLDER_NAMES = { "picture", "audio" }; private static final String[] EXTENSIONS = { ".png", ".mp3" }; private Connection _sendConn; private Connection _recConn; private MMSDemoSendScreen _mmsDemoSendScreen; private MMSDemoReceiveScreen _mmsDemoReceiveScreen; private final MainScreen _blankScreen; // Vector to hold MessagePart objects private final TableModel _messageParts; /** * Creates a new MMSDemo object */ public MMSDemo() { _messageParts = new TableModel(); _blankScreen = new MainScreen(); _blankScreen.setTitle("MMS Demo"); pushScreen(_blankScreen); chooseModeDialog(); } /** * Creates a MessagePart with content of given type to be attached to * outgoing MultipartMessage * * @param type * The type of content to attach */ void attach(final int type) { boolean exists = false; // Check that content has not already been added. For this sample there // is no point in attaching the same file twice. Note that every // MessagePart contained within a MultipartMessage must have a unique // content id. for (int i = 0; i < getMessageParts().getNumberOfRows(); i++) { final MessagePart messagePart = (MessagePart) getMessageParts().getRow(i); final String contentLocation = messagePart.getContentLocation(); if (contentLocation.equals(FOLDER_NAMES[type] + '0' + EXTENSIONS[type])) { exists = true; } } if (!exists) { // Obtain content data from project resource final String filename = FOLDER_NAMES[type] + "0" + EXTENSIONS[type]; final StringBuffer path = new StringBuffer("/media/"); path.append(FOLDER_NAMES[type]); path.append("/"); path.append(filename); final InputStream inputStream = getClass().getResourceAsStream(path.toString()); try { final byte[] contentData = IOUtilities.streamToBytes(inputStream); // Create a MessagePart object with the contentData and add it // to the message parts vector final MessagePart messagePart = new MessagePart(contentData, MIME_TYPES[type], FOLDER_NAMES[type], filename, null); addMessagePart(messagePart); } catch (final IOException ioe) { errorDialog(ioe.toString()); } } } /** * Allows user to choose between client or server mode */ private void chooseModeDialog() { invokeLater(new Runnable() { public void run() { final int choice = Dialog.ask("Select Mode", CHOICES, CLIENT_CHOICE); popScreen(_blankScreen); if (choice == CLIENT_CHOICE) { _mmsDemoSendScreen = new MMSDemoSendScreen(MMSDemo.this); pushScreen(_mmsDemoSendScreen); } else if (choice == SERVER_CHOICE) { receiveMMS(); _mmsDemoReceiveScreen = new MMSDemoReceiveScreen(); pushScreen(_mmsDemoReceiveScreen); } else { System.exit(0); } } }); } /** * Retrieves a vector of MessagePart objects * * @return A vector that contains the message parts */ TableModel getMessageParts() { return _messageParts; } /** * Adds a new MessagePart object * * @param m * The MessagePart object to be added */ void addMessagePart(final MessagePart messagePart) { _messageParts.addRow(messagePart); } /** * Sends an MMS message */ void sendMMS(final EditField addressField, final EditField subjectField, final EditField messageField) { final String address = addressField.getText(); final String subject = subjectField.getText(); final String message = messageField.getText(); // Check for blank fields if (address.length() == 0) { errorDialog("Destination field cannot be blank"); addressField.setFocus(); } else if (subject.length() == 0) { errorDialog("Subject field cannot be blank"); subjectField.setFocus(); } else if (message.length() == 0) { errorDialog("Message field cannot be blank"); messageField.setFocus(); } else { MultipartMessage multipartMessage = null; try { // Open an MMS connection for sending _sendConn = Connector.open("mms://" + address + ":" + APP_ID); // Create the multipart message and set the subject multipartMessage = (MultipartMessage) ((MessageConnection) _sendConn) .newMessage(MessageConnection.MULTIPART_MESSAGE); multipartMessage.setSubject(subject); // Add the message text to the multipart message multipartMessage.addMessagePart(new MessagePart(message .getBytes(), "text/plain", "text", null, null)); // Add any attachments for (int i = 0; i < _messageParts.getNumberOfRows(); i++) { multipartMessage.addMessagePart((MessagePart) _messageParts .getRow(i)); } } catch (final IOException ioe) { errorDialog(ioe.toString() + " when creating message."); } try { ((MessageConnection) _sendConn).send(multipartMessage); invokeLater(new Runnable() { public void run() { Dialog.alert("Message sent"); } }); } catch (final IOException ioe) { errorDialog(ioe.toString() + " when sending message."); } } } /** * Listens for incoming MMS messages */ private void receiveMMS() { final Thread t = new Thread() { public void run() { try { // Open an MMS connection for receiving _recConn = Connector.open("mms://:" + APP_ID); for (;;) { // Wait for an MMS final MultipartMessage multipartMessage = (MultipartMessage) ((MessageConnection) _recConn) .receive(); // Process the MMS in an other thread so this thread can // continue to listen for messages without interruption. new ProcessMMSThread(multipartMessage).start(); } } catch (final IOException ioe) { MMSDemo.errorDialog("MessageConnection.receive() threw " + ioe.toString()); } } }; t.start(); } /** * A class to process an MMS message and update the screen */ class ProcessMMSThread extends Thread { private final MultipartMessage _multipartMessage; private String _msgText; private Bitmap _bitmap; /** * Create a new ProcessMMSThread object * * @param multipartMessage * Message to display on the screen */ ProcessMMSThread(final MultipartMessage multipartMessage) { _multipartMessage = multipartMessage; } public void run() { // Obtain the message part containing the message body final MessagePart textMsgPart = _multipartMessage.getMessagePart("text"); if (textMsgPart != null) { final byte[] bytes = textMsgPart.getContent(); _msgText = new String(bytes); } final MessagePart pictureMsgPart = _multipartMessage.getMessagePart("picture"); if (pictureMsgPart != null) { final byte[] pictureData = pictureMsgPart.getContent(); _bitmap = Bitmap.createBitmapFromBytes(pictureData, 0, -1, 1); } invokeLater(new Runnable() { public void run() { // Update the screen on the event thread _mmsDemoReceiveScreen.setStatus("Message received"); _mmsDemoReceiveScreen.setSubject(_multipartMessage .getSubject()); _mmsDemoReceiveScreen.setMessage(_msgText); _mmsDemoReceiveScreen.updateBitmapField(_bitmap); } }); } } /** * @see net.rim.device.api.ui.Screen#close() */ public void close() { try { if (_sendConn != null) { _sendConn.close(); } } catch (final Exception e) { } try { if (_recConn != null) { _recConn.close(); } } catch (final Exception e) { } } /** * Entry point for application * * @param args * Command line arguments (not used) */ public static void main(final String[] args) { // Create a new instance of the application and make the currently // running thread the application's event dispatch thread. final MMSDemo mmsDemo = new MMSDemo(); mmsDemo.enterEventDispatcher(); } /** * Presents a dialog to the user with a given message * * @param message * The text to display */ public static void errorDialog(final String message) { UiApplication.getUiApplication().invokeLater(new Runnable() { public void run() { Dialog.alert(message); } }); } }
{ "content_hash": "bb99bdfa02becd53ae07e97d237dadaa", "timestamp": "", "source": "github", "line_count": 334, "max_line_length": 81, "avg_line_length": 36.24850299401198, "alnum_prop": 0.5372098785826381, "repo_name": "blackberry/JDE-Samples", "id": "5b96d0e87513f28dc7ee207066c77637efba26ad", "size": "13312", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "com/rim/samples/device/mmsdemo/MMSDemo.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "C", "bytes": "500" }, { "name": "C++", "bytes": "24878" }, { "name": "Java", "bytes": "3544747" }, { "name": "JavaScript", "bytes": "671" }, { "name": "Shell", "bytes": "2391" } ], "symlink_target": "" }
package com.google.api.ads.adwords.jaxws.v201402.video; 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.XmlType; import com.google.api.ads.adwords.jaxws.v201402.cm.Page; /** * * Contains the set of TargetingGroupCriteria matching filtering and paging options * of the VideoTargetingGroupCriterionService.get() call. * * * <p>Java class for TargetingGroupCriterionPage complex type. * * <p>The following schema fragment specifies the expected content contained within this class. * * <pre> * &lt;complexType name="TargetingGroupCriterionPage"> * &lt;complexContent> * &lt;extension base="{https://adwords.google.com/api/adwords/cm/v201402}Page"> * &lt;sequence> * &lt;element name="entries" type="{https://adwords.google.com/api/adwords/video/v201402}TargetingGroupCriterion" maxOccurs="unbounded" minOccurs="0"/> * &lt;element name="summaryStats" type="{https://adwords.google.com/api/adwords/video/v201402}VideoEntityStats" maxOccurs="unbounded" minOccurs="0"/> * &lt;/sequence> * &lt;/extension> * &lt;/complexContent> * &lt;/complexType> * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "TargetingGroupCriterionPage", propOrder = { "entries", "summaryStats" }) public class TargetingGroupCriterionPage extends Page { protected List<TargetingGroupCriterion> entries; protected List<VideoEntityStats> summaryStats; /** * Gets the value of the entries 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 entries property. * * <p> * For example, to add a new item, do as follows: * <pre> * getEntries().add(newItem); * </pre> * * * <p> * Objects of the following type(s) are allowed in the list * {@link TargetingGroupCriterion } * * */ public List<TargetingGroupCriterion> getEntries() { if (entries == null) { entries = new ArrayList<TargetingGroupCriterion>(); } return this.entries; } /** * Gets the value of the summaryStats 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 summaryStats property. * * <p> * For example, to add a new item, do as follows: * <pre> * getSummaryStats().add(newItem); * </pre> * * * <p> * Objects of the following type(s) are allowed in the list * {@link VideoEntityStats } * * */ public List<VideoEntityStats> getSummaryStats() { if (summaryStats == null) { summaryStats = new ArrayList<VideoEntityStats>(); } return this.summaryStats; } }
{ "content_hash": "bc63e3ec725d8eebb2ed4fb61f18dda1", "timestamp": "", "source": "github", "line_count": 107, "max_line_length": 160, "avg_line_length": 30.822429906542055, "alnum_prop": 0.6440266828380837, "repo_name": "nafae/developer", "id": "c79e6960d4318bfdbce305efaf364bbc0a936aec", "size": "3298", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "modules/adwords_appengine/src/main/java/com/google/api/ads/adwords/jaxws/v201402/video/TargetingGroupCriterionPage.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "127846798" }, { "name": "Perl", "bytes": "28418" } ], "symlink_target": "" }
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>numpy.matrix.squeeze &mdash; NumPy v1.8 Manual</title> <link rel="stylesheet" href="../../_static/pythonista.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.8.0', 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> <link rel="author" title="About these documents" href="../../about.html" /> <link rel="top" title="NumPy v1.8 Manual" href="../../index.html" /> <link rel="up" title="numpy.matrix" href="numpy.matrix.html" /> <link rel="next" title="numpy.matrix.std" href="numpy.matrix.std.html" /> <link rel="prev" title="numpy.matrix.sort" href="numpy.matrix.sort.html" /> <link rel="shortcut icon" type="image/png" href="../../_static/py.png" /> <meta name = "viewport" content = "width=device-width,initial-scale=1.0,user-scalable=no;"> <script type="text/javascript"> var getTextForSample = function(i) { codeBlock = document.getElementsByClassName('highlight-python')[i]; return codeBlock.innerText; } var copySample = function (i) { window.location.href = '/__pythonista_copy__/' + encodeURI(getTextForSample(i)); } var openSample = function (i) { window.location.href = '/__pythonista_open__/' + encodeURI(getTextForSample(i)); } //Source: http://ejohn.org/blog/partial-functions-in-javascript/ Function.prototype.partial = function() { var fn = this, args = Array.prototype.slice.call(arguments); return function() { var arg = 0; for (var i = 0; i < args.length && arg < arguments.length; i++) if (args[i] === undefined) args[i] = arguments[arg++]; return fn.apply(this, args); }; }; window.onload=function() { //Add "Copy" and "Open in Editor" buttons for code samples: var inApp = navigator.userAgent.match(/AppleWebKit/i) != null && navigator.userAgent.match(/Safari/i) == null; if (inApp) { codeBlocks = document.getElementsByClassName('highlight-python'); for (var i = 0; i < codeBlocks.length; i++) { codeBlock = codeBlocks[i]; if (codeBlock.innerText.indexOf('>>>') == 0) { //Don't add header for interactive sessions continue; } var codeHeader = document.createElement('div'); codeHeader.className = 'pythonista-code-header'; var copyButton = document.createElement('button'); copyButton.className = 'pythonista-button'; copyButton.innerText = 'Copy'; copyButton.addEventListener('click', copySample.partial(i)); codeHeader.appendChild(copyButton); var openButton = document.createElement('button'); openButton.className = 'pythonista-button'; openButton.innerText = 'Open in Editor'; openButton.addEventListener('click', openSample.partial(i)); codeHeader.appendChild(openButton); codeBlock.parentElement.insertBefore(codeHeader, codeBlock); } } } </script> </head> <body ontouchstart=""> <div class="related"> <h3>Navigation</h3> <ul> <li class="right" style="margin-right: 10px"> <a href="../../genindex.html" title="General Index" accesskey="I">index</a></li> <li class="right" > <a href="numpy.matrix.std.html" title="numpy.matrix.std" accesskey="N">next</a> |</li> <li class="right" > <a href="numpy.matrix.sort.html" title="numpy.matrix.sort" accesskey="P">previous</a> |</li> <li><a href="../../index.html">NumPy v1.8 Manual</a> &raquo;</li> <li><a href="../index.html" >NumPy Reference</a> &raquo;</li> <li><a href="../arrays.html" >Array objects</a> &raquo;</li> <li><a href="../arrays.classes.html" >Standard array subclasses</a> &raquo;</li> <li><a href="numpy.matrix.html" accesskey="U">numpy.matrix</a> &raquo;</li> </ul> </div> <div class="document"> <div class="documentwrapper"> <div class="body"> <div class="section" id="numpy-matrix-squeeze"> <h1>numpy.matrix.squeeze<a class="headerlink" href="#numpy-matrix-squeeze" title="Permalink to this headline">¶</a></h1> <dl class="method"> <dt id="numpy.matrix.squeeze"> <tt class="descclassname">matrix.</tt><tt class="descname">squeeze</tt><big>(</big><em>axis=None</em><big>)</big><a class="headerlink" href="#numpy.matrix.squeeze" title="Permalink to this definition">¶</a></dt> <dd><p>Remove single-dimensional entries from the shape of <em class="xref py py-obj">a</em>.</p> <p>Refer to <a class="reference internal" href="numpy.squeeze.html#numpy.squeeze" title="numpy.squeeze"><tt class="xref py py-obj docutils literal"><span class="pre">numpy.squeeze</span></tt></a> for full documentation.</p> <div class="admonition seealso"> <p class="first admonition-title">See also</p> <dl class="last docutils"> <dt><a class="reference internal" href="numpy.squeeze.html#numpy.squeeze" title="numpy.squeeze"><tt class="xref py py-obj docutils literal"><span class="pre">numpy.squeeze</span></tt></a></dt> <dd>equivalent function</dd> </dl> </div> </dd></dl> </div> </div> </div> <div class="clearer"></div> </div> <div class="footer"> &copy; <a href="../../copyright.html">Copyright</a> 2008-2009, The Scipy community. <br /> The Python Software Foundation is a non-profit corporation. <a href="http://www.python.org/psf/donations/">Please donate.</a> <br /> Last updated on May 03, 2016. <a href="../../bugs.html">Found a bug</a>? <br /> Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 1.2.1. </div> </body> </html>
{ "content_hash": "a145f4a044e1ea04b43c4f2515c8c1c7", "timestamp": "", "source": "github", "line_count": 155, "max_line_length": 223, "avg_line_length": 43.92258064516129, "alnum_prop": 0.5788777908343126, "repo_name": "leesavide/pythonista-docs", "id": "1a3cae8521bed299989e79ded4e0fa7da873038f", "size": "6811", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "Documentation/numpy/reference/generated/numpy.matrix.squeeze.html", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "84392" }, { "name": "HTML", "bytes": "70040156" }, { "name": "JavaScript", "bytes": "89777" }, { "name": "Python", "bytes": "884325" } ], "symlink_target": "" }
/* NetHack 3.6 gnmain.c $NHDT-Date: 1432512807 2015/05/25 00:13:27 $ $NHDT-Branch: master $:$NHDT-Revision: 1.15 $ */ /* Copyright (C) 1998 by Erik Andersen <andersee@debian.org> */ /* NetHack may be freely redistributed. See license for details. */ #include "gnmain.h" #include "gnsignal.h" #include "gnbind.h" #include "gnopts.h" #include <gnome.h> #include <getopt.h> #include <gdk/gdk.h> #include <sys/time.h> #include <unistd.h> #include <signal.h> #include "hack.h" #include "date.h" static GtkWidget *mainWindow = NULL; static GtkWidget *about = NULL; static GtkWidget *hBoxFirstRow; static GtkWidget *vBoxMain; int restarted = 0; int os_x = 0, os_y = 0, os_w = 0, os_h = 0; static GnomeClient *session_id; static void ghack_quit_game(GtkWidget *widget, int button) { gtk_widget_hide(widget); if (button == 0) { gnome_exit_nhwindows(0); gtk_object_unref(GTK_OBJECT(session_id)); clearlocks(); gtk_exit(0); } } static void ghack_quit_game_cb(GtkWidget *widget, gpointer data) { GtkWidget *box; box = gnome_message_box_new( _("Do you really want to quit?"), GNOME_MESSAGE_BOX_QUESTION, GNOME_STOCK_BUTTON_YES, GNOME_STOCK_BUTTON_NO, NULL); gnome_dialog_set_default(GNOME_DIALOG(box), 1); gnome_dialog_set_parent(GNOME_DIALOG(box), GTK_WINDOW(ghack_get_main_window())); gnome_dialog_set_accelerator(GNOME_DIALOG(box), 1, 'n', 0); gnome_dialog_set_accelerator(GNOME_DIALOG(box), 0, 'y', 0); gtk_window_set_modal(GTK_WINDOW(box), TRUE); gtk_signal_connect(GTK_OBJECT(box), "clicked", (GtkSignalFunc) ghack_quit_game, NULL); gtk_widget_show(box); } static void ghack_save_game(GtkWidget *widget, int button) { gtk_widget_hide(widget); if (button == 0) { if (dosave0()) { /* make sure they see the Saving message */ display_nhwindow(WIN_MESSAGE, TRUE); gnome_exit_nhwindows("Be seeing you..."); clearlocks(); gtk_exit(0); } else (void) doredraw(); } } void ghack_save_game_cb(GtkWidget *widget, gpointer data) { GtkWidget *box; box = gnome_message_box_new( _("Quit and save the current game?"), GNOME_MESSAGE_BOX_QUESTION, GNOME_STOCK_BUTTON_YES, GNOME_STOCK_BUTTON_NO, NULL); gnome_dialog_set_default(GNOME_DIALOG(box), 1); gnome_dialog_set_parent(GNOME_DIALOG(box), GTK_WINDOW(ghack_get_main_window())); gnome_dialog_set_accelerator(GNOME_DIALOG(box), 1, 'n', 0); gnome_dialog_set_accelerator(GNOME_DIALOG(box), 0, 'y', 0); gtk_window_set_modal(GTK_WINDOW(box), TRUE); gtk_signal_connect(GTK_OBJECT(box), "clicked", (GtkSignalFunc) ghack_save_game, NULL); gtk_widget_show(box); } static void ghack_new_game(GtkWidget *widget, int button) { if (button == 0) { g_message("This feature is not yet implemented. Sorry."); } } static void ghack_new_game_cb(GtkWidget *widget, gpointer data) { GtkWidget *box; box = gnome_message_box_new( _("Start a new game?"), GNOME_MESSAGE_BOX_QUESTION, GNOME_STOCK_BUTTON_YES, GNOME_STOCK_BUTTON_NO, NULL); gnome_dialog_set_default(GNOME_DIALOG(box), 1); gnome_dialog_set_parent(GNOME_DIALOG(box), GTK_WINDOW(ghack_get_main_window())); gnome_dialog_set_accelerator(GNOME_DIALOG(box), 1, 'n', 0); gnome_dialog_set_accelerator(GNOME_DIALOG(box), 0, 'y', 0); gtk_window_set_modal(GTK_WINDOW(box), TRUE); gtk_signal_connect(GTK_OBJECT(box), "clicked", (GtkSignalFunc) ghack_new_game, NULL); gtk_widget_show(box); } static void about_destroy_callback(void) { about = NULL; } static void ghack_about_cb(GtkWidget *widget, gpointer data) { char buf[BUFSZ] = "\0"; char buf1[BUFSZ] = "\0"; const gchar *authors[] = { "Erik Andersen", "Anthony Taylor", "Jeff Garzik", "The Nethack Dev Team", NULL }; if (about) { gdk_window_raise(about->window); return; } getversionstring(buf); #if 0 /* XXX this needs further re-write to use DEVTEAM_EMAIL, DEVTEAM_URL, * sysopt.support, etc. I'm not doing it now because I can't test * it yet. (keni) */ /* out of date first cut: */ ! len = strlen(buf); ! char *str1 = _("\nSend comments and bug reports to:\n"); ! len += strlen(str1); ! len += sysopt.email; ! char *str2 = _("\nThis game is free software. See License for details."); ! len += strlen(str2); ! str = (char*)alloc(len+1); ! strcat(buf, str1); ! strcat(buf, sysopt.email); ! strcat(buf, str2); free(str) below #else strcat(buf1, VERSION_STRING); strcat(buf, _("\nSend comments and bug reports to: nethack-bugs@nethack.org\n" "This game is free software. See License for details.")); #endif about = gnome_about_new(_("Nethack"), buf1, "Copyright (C) 1985-2002 Mike Stephenson", (const char **) authors, buf, NULL); gtk_signal_connect(GTK_OBJECT(about), "destroy", (GtkSignalFunc) about_destroy_callback, NULL); gtk_widget_show(about); } static void ghack_settings_cb(GtkWidget *widget, gpointer data) { ghack_settings_dialog(); } static void ghack_accelerator_selected(GtkWidget *widget, gpointer data) { GdkEventKey event; int key = GPOINTER_TO_INT(data); /* g_message("An accelerator for \"%c\" was selected", key); */ /* stuff a key directly into the keybuffer */ event.state = 0; event.keyval = key; ghack_handle_key_press(NULL, &event, NULL); } #ifndef M #ifndef NHSTDC #define M(c) (0x80 | (c)) #else #define M(c) ((c) -128) #endif /* NHSTDC */ #endif #ifndef C #define C(c) (0x1f & (c)) #endif GnomeUIInfo game_tree[] = { { GNOME_APP_UI_ITEM, N_("_Change Settings..."), N_("Change Game Settings"), ghack_settings_cb, NULL, NULL, GNOME_APP_PIXMAP_NONE, NULL, 0, 0, NULL }, GNOMEUIINFO_SEPARATOR, { GNOME_APP_UI_ITEM, N_("Version"), NULL, ghack_accelerator_selected, GINT_TO_POINTER('v'), NULL, GNOME_APP_PIXMAP_STOCK, GNOME_STOCK_MENU_ABOUT, 'v', 0 }, { GNOME_APP_UI_ITEM, N_("History..."), NULL, ghack_accelerator_selected, GINT_TO_POINTER('V'), NULL, GNOME_APP_PIXMAP_STOCK, GNOME_STOCK_MENU_ABOUT, 'V', GDK_SHIFT_MASK }, { GNOME_APP_UI_ITEM, N_("Compilation..."), NULL, ghack_accelerator_selected, GINT_TO_POINTER(M('v')), NULL, GNOME_APP_PIXMAP_STOCK, GNOME_STOCK_MENU_ABOUT, 'v', GDK_MOD1_MASK }, { GNOME_APP_UI_ITEM, N_("Options..."), NULL, ghack_accelerator_selected, GINT_TO_POINTER('O'), NULL, GNOME_APP_PIXMAP_STOCK, GNOME_STOCK_MENU_PREF, 'O', GDK_SHIFT_MASK }, { GNOME_APP_UI_ITEM, N_("Explore Mode..."), NULL, ghack_accelerator_selected, GINT_TO_POINTER('X'), NULL, GNOME_APP_PIXMAP_STOCK, GNOME_STOCK_MENU_QUIT, 'X', GDK_SHIFT_MASK }, GNOMEUIINFO_SEPARATOR, GNOMEUIINFO_MENU_NEW_GAME_ITEM(ghack_new_game_cb, NULL), GNOMEUIINFO_MENU_SAVE_ITEM(ghack_save_game_cb, NULL), { GNOME_APP_UI_ITEM, N_("Exit"), NULL, ghack_quit_game_cb, GINT_TO_POINTER(M('Q')), NULL, GNOME_APP_PIXMAP_STOCK, GNOME_STOCK_MENU_ABOUT, 'Q', GDK_MOD1_MASK }, GNOMEUIINFO_END }; GnomeUIInfo edit_menu[] = { { GNOME_APP_UI_ITEM, N_("Inventory"), N_("Edit/View your Inventory"), ghack_accelerator_selected, GINT_TO_POINTER('i'), NULL, GNOME_APP_PIXMAP_NONE, NULL, 'i', 0 }, { GNOME_APP_UI_ITEM, N_("Discoveries"), N_("Edit/View your Discoveries"), ghack_accelerator_selected, GINT_TO_POINTER('\\'), NULL, GNOME_APP_PIXMAP_NONE, NULL, '\\', 0 }, { GNOME_APP_UI_ITEM, N_("List/reorder your spells"), N_("List/reorder your spells"), ghack_accelerator_selected, GINT_TO_POINTER('x'), NULL, GNOME_APP_PIXMAP_NONE, NULL, 'x', 0 }, { GNOME_APP_UI_ITEM, N_("Adjust letters"), N_("Adjust letter for items in your Inventory"), ghack_accelerator_selected, GINT_TO_POINTER(M('a')), NULL, GNOME_APP_PIXMAP_NONE, NULL, 'a', GDK_MOD1_MASK }, GNOMEUIINFO_SEPARATOR, { GNOME_APP_UI_ITEM, N_("Name object"), N_("Assign a name to an object"), ghack_accelerator_selected, GINT_TO_POINTER(M('n')), NULL, GNOME_APP_PIXMAP_NONE, NULL, 'n', GDK_MOD1_MASK }, { GNOME_APP_UI_ITEM, N_("Name creature"), N_("Assign a name to a creature"), ghack_accelerator_selected, GINT_TO_POINTER('C'), NULL, GNOME_APP_PIXMAP_NONE, NULL, 'C', GDK_SHIFT_MASK }, GNOMEUIINFO_SEPARATOR, { GNOME_APP_UI_ITEM, N_("Qualifications"), N_("Edit your Qualifications"), ghack_accelerator_selected, GINT_TO_POINTER(M('e')), NULL, GNOME_APP_PIXMAP_NONE, NULL, 'e', GDK_MOD1_MASK }, GNOMEUIINFO_END }; GnomeUIInfo apparel_menu[] = { { GNOME_APP_UI_ITEM, N_("Wield Weapon"), N_("Select a weapon to fight with"), ghack_accelerator_selected, GINT_TO_POINTER('w'), NULL, GNOME_APP_PIXMAP_NONE, NULL, 'w', 0 }, { GNOME_APP_UI_ITEM, N_("Remove Apparel..."), N_("Remove apparel dialog bog"), ghack_accelerator_selected, GINT_TO_POINTER('A'), NULL, GNOME_APP_PIXMAP_NONE, NULL, 'A', GDK_SHIFT_MASK }, GNOMEUIINFO_SEPARATOR, { GNOME_APP_UI_ITEM, N_("Wear Armor"), N_("Put on armor"), ghack_accelerator_selected, GINT_TO_POINTER('W'), NULL, GNOME_APP_PIXMAP_NONE, NULL, 'W', GDK_SHIFT_MASK }, { GNOME_APP_UI_ITEM, N_("Take off Armor"), N_("Take off armor you are wearing"), ghack_accelerator_selected, GINT_TO_POINTER('T'), NULL, GNOME_APP_PIXMAP_NONE, NULL, 'T', GDK_SHIFT_MASK }, GNOMEUIINFO_SEPARATOR, { GNOME_APP_UI_ITEM, N_("Put on non-armor"), N_("Put on non-armor apparel"), ghack_accelerator_selected, GINT_TO_POINTER('P'), NULL, GNOME_APP_PIXMAP_NONE, NULL, 'P', GDK_SHIFT_MASK }, { GNOME_APP_UI_ITEM, N_("Remove non-armor"), N_("Remove non-armor apparel you are wearing"), ghack_accelerator_selected, GINT_TO_POINTER('R'), NULL, GNOME_APP_PIXMAP_NONE, NULL, 'R', GDK_SHIFT_MASK }, GNOMEUIINFO_END }; GnomeUIInfo action_menu[] = { { GNOME_APP_UI_ITEM, N_("Get"), N_("Pick up things at the current location"), ghack_accelerator_selected, GINT_TO_POINTER(','), NULL, GNOME_APP_PIXMAP_NONE, NULL, ',', 0 }, { GNOME_APP_UI_ITEM, N_("Loot"), N_("loot a box on the floor"), ghack_accelerator_selected, GINT_TO_POINTER(M('l')), NULL, GNOME_APP_PIXMAP_NONE, NULL, 'l', GDK_MOD1_MASK }, { GNOME_APP_UI_ITEM, N_("Sit"), N_("sit down"), ghack_accelerator_selected, GINT_TO_POINTER(M('s')), NULL, GNOME_APP_PIXMAP_NONE, NULL, 's', GDK_MOD1_MASK }, { GNOME_APP_UI_ITEM, N_("Force"), N_("force a lock"), ghack_accelerator_selected, GINT_TO_POINTER(M('f')), NULL, GNOME_APP_PIXMAP_NONE, NULL, 'f', GDK_MOD1_MASK }, { GNOME_APP_UI_ITEM, N_("Kick"), N_("kick something (usually a door)"), ghack_accelerator_selected, GINT_TO_POINTER(C('d')), NULL, GNOME_APP_PIXMAP_NONE, NULL, 'd', GDK_CONTROL_MASK }, { GNOME_APP_UI_ITEM, N_("Jump"), N_("jump to another location"), ghack_accelerator_selected, GINT_TO_POINTER(M('j')), NULL, GNOME_APP_PIXMAP_NONE, NULL, 'j', GDK_MOD1_MASK }, { GNOME_APP_UI_ITEM, N_("Ride"), N_("Ride (or stop riding) a monster"), doride, GINT_TO_POINTER(M('r')), NULL, GNOME_APP_PIXMAP_NONE, NULL, 'R', GDK_MOD1_MASK }, { GNOME_APP_UI_ITEM, N_("Wipe face"), N_("wipe off your face"), ghack_accelerator_selected, GINT_TO_POINTER(M('w')), NULL, GNOME_APP_PIXMAP_NONE, NULL, 'w', GDK_MOD1_MASK }, { GNOME_APP_UI_ITEM, N_("Throw/Shoot"), N_("throw or shoot a weapon"), ghack_accelerator_selected, GINT_TO_POINTER('t'), NULL, GNOME_APP_PIXMAP_NONE, NULL, 't', 0 }, { GNOME_APP_UI_ITEM, N_("Quiver/Ready"), N_("ready or quiver some ammunition"), ghack_accelerator_selected, GINT_TO_POINTER('Q'), NULL, GNOME_APP_PIXMAP_NONE, NULL, 'Q', GDK_SHIFT_MASK, }, { GNOME_APP_UI_ITEM, N_("Open Door"), N_("open a door"), ghack_accelerator_selected, GINT_TO_POINTER('o'), NULL, GNOME_APP_PIXMAP_NONE, NULL, 'o', 0 }, { GNOME_APP_UI_ITEM, N_("Close Door"), N_("open a door"), ghack_accelerator_selected, GINT_TO_POINTER('c'), NULL, GNOME_APP_PIXMAP_NONE, NULL, 'c', 0 }, GNOMEUIINFO_SEPARATOR, { GNOME_APP_UI_ITEM, N_("Drop"), N_("drop an object"), ghack_accelerator_selected, GINT_TO_POINTER('d'), NULL, GNOME_APP_PIXMAP_NONE, NULL, 'd', 0 }, { GNOME_APP_UI_ITEM, N_("Drop Many"), N_("drop selected types of objects"), ghack_accelerator_selected, GINT_TO_POINTER('D'), NULL, GNOME_APP_PIXMAP_NONE, NULL, 'D', GDK_SHIFT_MASK }, { GNOME_APP_UI_ITEM, N_("Eat"), N_("eat something"), ghack_accelerator_selected, GINT_TO_POINTER('e'), NULL, GNOME_APP_PIXMAP_NONE, NULL, 'e', 0 }, { GNOME_APP_UI_ITEM, N_("Engrave"), N_("write a message in the dust on the floor"), ghack_accelerator_selected, GINT_TO_POINTER('E'), NULL, GNOME_APP_PIXMAP_NONE, NULL, 'E', GDK_SHIFT_MASK }, { GNOME_APP_UI_ITEM, N_("Apply"), N_("apply or use a tool (pick-axe, key, camera, etc.)"), ghack_accelerator_selected, GINT_TO_POINTER('a'), NULL, GNOME_APP_PIXMAP_NONE, NULL, 'a', 0 }, GNOMEUIINFO_SEPARATOR, { GNOME_APP_UI_ITEM, N_("Up"), N_("go up the stairs"), ghack_accelerator_selected, GINT_TO_POINTER('<'), NULL, GNOME_APP_PIXMAP_NONE, NULL, '<', 0 }, { GNOME_APP_UI_ITEM, N_("Down"), N_("go down the stairs"), ghack_accelerator_selected, GINT_TO_POINTER('>'), NULL, GNOME_APP_PIXMAP_NONE, NULL, '>', 0 }, { GNOME_APP_UI_ITEM, N_("Rest"), N_("wait for a moment"), ghack_accelerator_selected, GINT_TO_POINTER('.'), NULL, GNOME_APP_PIXMAP_NONE, NULL, '.', 0 }, { GNOME_APP_UI_ITEM, N_("Search"), N_("search for secret doors, hidden traps and monsters"), ghack_accelerator_selected, GINT_TO_POINTER('s'), NULL, GNOME_APP_PIXMAP_NONE, NULL, 's', 0 }, GNOMEUIINFO_SEPARATOR, { GNOME_APP_UI_ITEM, N_("Chat"), N_("talk to someone"), ghack_accelerator_selected, GINT_TO_POINTER(M('c')), NULL, GNOME_APP_PIXMAP_NONE, NULL, 'c', GDK_MOD1_MASK }, { GNOME_APP_UI_ITEM, N_("Pay"), N_("pay your bill to the shopkeeper"), ghack_accelerator_selected, GINT_TO_POINTER('p'), NULL, GNOME_APP_PIXMAP_NONE, NULL, 'p', 0 }, GNOMEUIINFO_END }; GnomeUIInfo magic_menu[] = { { GNOME_APP_UI_ITEM, N_("Quaff potion"), N_("drink a potion"), ghack_accelerator_selected, GINT_TO_POINTER('q'), NULL, GNOME_APP_PIXMAP_NONE, NULL, 'q', 0 }, { GNOME_APP_UI_ITEM, N_("Read Book/Scroll"), N_("read a spell book or a scroll"), ghack_accelerator_selected, GINT_TO_POINTER('r'), NULL, GNOME_APP_PIXMAP_NONE, NULL, 'r', 0 }, { GNOME_APP_UI_ITEM, N_("Zap Wand"), N_("zap a wand"), ghack_accelerator_selected, GINT_TO_POINTER('z'), NULL, GNOME_APP_PIXMAP_NONE, NULL, 'z', 0 }, { GNOME_APP_UI_ITEM, N_("Zap Spell"), N_("cast a spell"), ghack_accelerator_selected, GINT_TO_POINTER('Z'), NULL, GNOME_APP_PIXMAP_NONE, NULL, 'Z', GDK_SHIFT_MASK }, GNOMEUIINFO_SEPARATOR, { GNOME_APP_UI_ITEM, N_("Dip"), N_("dip an object into something"), ghack_accelerator_selected, GINT_TO_POINTER(M('d')), NULL, GNOME_APP_PIXMAP_NONE, NULL, 'd', GDK_MOD1_MASK }, { GNOME_APP_UI_ITEM, N_("Rub"), N_("Rub something (i.e. a lamp)"), ghack_accelerator_selected, GINT_TO_POINTER(M('r')), NULL, GNOME_APP_PIXMAP_NONE, NULL, 'r', GDK_MOD1_MASK }, { GNOME_APP_UI_ITEM, N_("Invoke"), N_("invoke an object's special powers"), ghack_accelerator_selected, GINT_TO_POINTER(M('i')), NULL, GNOME_APP_PIXMAP_NONE, NULL, 'i', GDK_MOD1_MASK }, GNOMEUIINFO_SEPARATOR, { GNOME_APP_UI_ITEM, N_("Offer"), N_("offer a sacrifice to the gods"), ghack_accelerator_selected, GINT_TO_POINTER(M('o')), NULL, GNOME_APP_PIXMAP_NONE, NULL, 'o', GDK_MOD1_MASK }, { GNOME_APP_UI_ITEM, N_("Pray"), N_("pray to the gods for help"), ghack_accelerator_selected, GINT_TO_POINTER(M('p')), NULL, GNOME_APP_PIXMAP_NONE, NULL, 'p', GDK_MOD1_MASK }, GNOMEUIINFO_SEPARATOR, { GNOME_APP_UI_ITEM, N_("Teleport"), N_("teleport (if you can)"), ghack_accelerator_selected, GINT_TO_POINTER(C('t')), NULL, GNOME_APP_PIXMAP_NONE, NULL, 't', GDK_CONTROL_MASK }, { GNOME_APP_UI_ITEM, N_("Monster Action"), N_("use a monster's special ability"), ghack_accelerator_selected, GINT_TO_POINTER(M('m')), NULL, GNOME_APP_PIXMAP_NONE, NULL, 'm', GDK_MOD1_MASK }, { GNOME_APP_UI_ITEM, N_("Turn Undead"), N_("turn undead"), ghack_accelerator_selected, GINT_TO_POINTER(M('t')), NULL, GNOME_APP_PIXMAP_NONE, NULL, 't', GDK_MOD1_MASK }, GNOMEUIINFO_END }; GnomeUIInfo help_menu[] = { { GNOME_APP_UI_ITEM, N_("About..."), N_("About GnomeHack"), ghack_about_cb, NULL, NULL, GNOME_APP_PIXMAP_STOCK, GNOME_STOCK_MENU_ABOUT, 0, 0, NULL }, { GNOME_APP_UI_ITEM, N_("Help"), NULL, ghack_accelerator_selected, GINT_TO_POINTER('?'), NULL, GNOME_APP_PIXMAP_STOCK, GNOME_STOCK_MENU_ABOUT, '?', 0 }, GNOMEUIINFO_SEPARATOR, { GNOME_APP_UI_ITEM, N_("What is here"), N_("Check what items occupy the current location"), ghack_accelerator_selected, GINT_TO_POINTER(':'), NULL, GNOME_APP_PIXMAP_STOCK, GNOME_STOCK_MENU_ABOUT, ':', 0 }, { GNOME_APP_UI_ITEM, N_("What is that"), N_("Identify an object"), ghack_accelerator_selected, GINT_TO_POINTER(';'), NULL, GNOME_APP_PIXMAP_STOCK, GNOME_STOCK_MENU_ABOUT, ';', 0 }, { GNOME_APP_UI_ITEM, N_("Identify a map symbol"), N_("Identify a map symbol"), ghack_accelerator_selected, GINT_TO_POINTER('/'), NULL, GNOME_APP_PIXMAP_STOCK, GNOME_STOCK_MENU_ABOUT, '/', 0 }, GNOMEUIINFO_END }; GnomeUIInfo mainmenu[] = { GNOMEUIINFO_MENU_GAME_TREE(game_tree), GNOMEUIINFO_MENU_EDIT_TREE(edit_menu), { GNOME_APP_UI_SUBTREE, N_("Apparel"), NULL, apparel_menu, NULL, NULL, 0, NULL, 0, 0, NULL }, { GNOME_APP_UI_SUBTREE, N_("Action"), NULL, action_menu, NULL, NULL, 0, NULL, 0, 0, NULL }, { GNOME_APP_UI_SUBTREE, N_("Magic"), NULL, magic_menu, NULL, NULL, 0, NULL, 0, 0, NULL }, GNOMEUIINFO_MENU_HELP_TREE(help_menu), GNOMEUIINFO_END }; static void ghack_main_window_key_press(GtkWidget *widget, GdkEventKey *event, gpointer data) { /* First, turn off the key press propogation. We've got the * key, but we don't wan't the underlying Gtk widgets to get it, * since they do the wrong thing with the arrow keys (shift focus)... */ gtk_signal_emit_stop_by_name(GTK_OBJECT(mainWindow), "key_press_event"); /* stuff the key event into the keybuffer */ ghack_handle_key_press(widget, event, data); } /* parsing args */ void parse_args(int argc, char *argv[]) { gint ch; struct option options[] = { /* Default args */ { "help", no_argument, NULL, 'h' }, { "version", no_argument, NULL, 'v' }, { NULL, 0, NULL, 0 } }; gchar *id = NULL; /* initialize getopt */ optarg = NULL; optind = 0; optopt = 0; while ((ch = getopt_long(argc, argv, "hv", options, NULL)) != EOF) { switch (ch) { case 'h': g_print( _("%s: A gnomified 'Hello World' program\n\n" "Usage: %s [--help] [--version]\n\n" "Options:\n" " --help display this help and exit\n" " --version output version information and exit\n"), argv[0], argv[0]); exit(0); break; case 'v': g_print(_("NetHack %s.\n"), VERSION_STRING); exit(0); break; case ':': case '?': g_print(_("Options error\n")); exit(0); break; } } /* SM stuff */ session_id = gnome_client_new(); #if 0 session_id = gnome_client_new ( /* callback to save the state and parameter for it */ save_state, argv[0], /* callback to die and parameter for it */ NULL, NULL, /* id from the previous session if restarted, NULL otherwise */ id); #endif /* set the program name */ gnome_client_set_program(session_id, argv[0]); g_free(id); return; } /* * [ALI] Gnome installs its own handler(s) for SIGBUS, SIGFPE and SIGSEGV. * These handlers will fork and exec a helper program. When that helper * comes to initialize GTK+, it may fail if setuid/setgid. We solve this * by dropping privileges before passing the signal along the chain. * Note: We don't need to either drop or mask the saved ID since this * will be reset when the child process performs the execve() anyway. */ static struct { int signum; void (*handler)(int); } ghack_chain[] = { { SIGBUS }, { SIGFPE }, { SIGSEGV }, { SIGILL } /* Not currently handled by Gnome */ }; static void ghack_sig_handler(int signum) { int i; uid_t uid, euid; gid_t gid, egid; uid = getuid(); euid = geteuid(); gid = getgid(); egid = getegid(); if (gid != egid) setgid(gid); if (uid != euid) setuid(uid); for (i = SIZE(ghack_chain) - 1; i >= 0; i--) if (ghack_chain[i].signum == signum) { ghack_chain[i].handler(signum); break; } if (i < 0) impossible("Unhandled ghack signal"); if (uid != euid) setuid(euid); if (gid != egid) setgid(egid); } /* initialize gnome and fir up the main window */ void ghack_init_main_window(int argc, char **argv) { int i; struct timeval tv; uid_t uid, euid; /* It seems that the authors of gnome_score_init() drop group * priveledges. We need group priveledges, so until we change the * way we save games to do things the gnome way(???), this stays * commented out. (after hours of frusteration...) * -Erik */ /* gnome_score_init("gnomehack"); */ gettimeofday(&tv, NULL); srand(tv.tv_usec); uid = getuid(); euid = geteuid(); if (uid != euid) setuid(uid); hide_privileges(TRUE); /* XXX gnome_init must print nethack options for --help, but does not */ gnome_init("nethack", VERSION_STRING, argc, argv); hide_privileges(FALSE); parse_args(argc, argv); /* Initialize the i18n stuff (not that gnomehack supperts it yet...) */ #if 0 textdomain (PACKAGE); #endif gdk_imlib_init(); /* Main window */ mainWindow = gnome_app_new((char *) "nethack", (char *) N_("Nethack for Gnome")); gtk_widget_realize(mainWindow); if (restarted) { gtk_widget_set_uposition(mainWindow, os_x, os_y); gtk_widget_set_usize(mainWindow, os_w, os_h); } gtk_window_set_default_size(GTK_WINDOW(mainWindow), 800, 600); gtk_window_set_policy(GTK_WINDOW(mainWindow), FALSE, TRUE, TRUE); gnome_app_create_menus(GNOME_APP(mainWindow), mainmenu); gtk_signal_connect(GTK_OBJECT(mainWindow), "key_press_event", GTK_SIGNAL_FUNC(ghack_main_window_key_press), NULL); gtk_signal_connect(GTK_OBJECT(mainWindow), "delete_event", GTK_SIGNAL_FUNC(ghack_quit_game_cb), NULL); /* Put some stuff into our main window */ vBoxMain = gtk_vbox_new(FALSE, 0); hBoxFirstRow = gtk_hbox_new(FALSE, 0); /* pack Boxes into other boxes to produce the right structure */ gtk_box_pack_start(GTK_BOX(vBoxMain), hBoxFirstRow, FALSE, TRUE, 0); /* pack vBoxMain which contains all our widgets into the main window. */ gnome_app_set_contents(GNOME_APP(mainWindow), vBoxMain); /* DONT show the main window yet, due to a Gtk bug that causes it * to not refresh the window when adding widgets after the window * has already been shown */ if (uid != euid) setuid(euid); for (i = 0; i < SIZE(ghack_chain); i++) ghack_chain[i].handler = signal(ghack_chain[i].signum, ghack_sig_handler); } void ghack_main_window_add_map_window(GtkWidget *win) { GtkWidget *vBox; vBox = gtk_vbox_new(TRUE, 0); gtk_box_pack_start(GTK_BOX(vBox), win, TRUE, TRUE, 2); gtk_box_pack_start(GTK_BOX(vBoxMain), vBox, TRUE, TRUE, 2); gtk_widget_show_all(vBox); /* Ok, now show the main window -- now that we have added in * all the windows (relys on nethack displaying the map window last * (This is an ugly kludge, BTW) */ gtk_widget_show_all(mainWindow); } void ghack_main_window_add_message_window(GtkWidget *win) { gtk_box_pack_start(GTK_BOX(hBoxFirstRow), win, TRUE, TRUE, 2); gtk_widget_show_all(win); } void ghack_main_window_add_status_window(GtkWidget *win) { gtk_box_pack_start(GTK_BOX(hBoxFirstRow), win, FALSE, TRUE, 2); gtk_widget_show_all(win); } void ghack_main_window_add_worn_window(GtkWidget *win) { gtk_box_pack_end(GTK_BOX(hBoxFirstRow), win, FALSE, TRUE, 2); gtk_widget_show_all(win); } void ghack_main_window_add_text_window(GtkWidget *win) { g_warning("Fixme!!! AddTextWindow is not yet implemented"); } void ghack_main_window_remove_window(GtkWidget *win) { g_warning("Fixme!!! RemoveWindow is not yet implemented"); } void ghack_main_window_update_inventory() { /* For now, do very little. Eventually we may allow the inv. window to stay active. When we do this, we'll need to implement this... g_warning("Fixme!!! updateInventory is not yet implemented"); */ gnome_display_nhwindow(WIN_WORN, FALSE); } GtkWidget * ghack_get_main_window() { return (GTK_WIDGET(mainWindow)); }
{ "content_hash": "8a2af04322205b60ffa53192ef892b42", "timestamp": "", "source": "github", "line_count": 706, "max_line_length": 118, "avg_line_length": 37.20254957507082, "alnum_prop": 0.604797258709309, "repo_name": "Nax/citizenhack", "id": "1a16cc9fe7c2f330f82ae9d929d9a40596fbe07e", "size": "26265", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "outdated/win/gnome/gnmain.c", "mode": "33188", "license": "mit", "language": [ { "name": "C", "bytes": "31332" }, { "name": "C++", "bytes": "40781" }, { "name": "CMake", "bytes": "2658" }, { "name": "Ruby", "bytes": "5120" } ], "symlink_target": "" }
{% extends "base.html" %} {% load i18n %} {% block head_title %}{% trans "Account Inactive" %}{% endblock %} {% block content %} <div class="columns is-centered"> <div class="column is-three-quarters"> <div class="content"> <h1 class="title is-3">{% trans "Account Inactive" %}</h1> <p>{% trans "This account is inactive." %}</p> </div> </div> </div> {% endblock %}
{ "content_hash": "10b96f0c381ecb4efa001faae6f236fc", "timestamp": "", "source": "github", "line_count": 17, "max_line_length": 66, "avg_line_length": 23.176470588235293, "alnum_prop": 0.5786802030456852, "repo_name": "stencila/hub", "id": "9c65b18777bfd3b9379b766f0c3257583502ac7e", "size": "394", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "manager/users/templates/account/account_inactive.html", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Dockerfile", "bytes": "5505" }, { "name": "HTML", "bytes": "274142" }, { "name": "JavaScript", "bytes": "18731" }, { "name": "Makefile", "bytes": "14959" }, { "name": "Mustache", "bytes": "1137" }, { "name": "Python", "bytes": "1262375" }, { "name": "SCSS", "bytes": "31993" }, { "name": "Shell", "bytes": "8726" }, { "name": "TypeScript", "bytes": "5270" } ], "symlink_target": "" }
if defined? Rake module Rake class Application alias original_load_imports load_imports def load_imports @pending_imports.delete_if{|fn| fn.is_a?(Class)} original_load_imports end end end end
{ "content_hash": "b1fd69e185606346a2ea130a4d1d513f", "timestamp": "", "source": "github", "line_count": 11, "max_line_length": 56, "avg_line_length": 21.636363636363637, "alnum_prop": 0.6428571428571429, "repo_name": "technohippy/rails_on_gae", "id": "3037c5956c0e5481cf5ab74a7315b7eda152939e", "size": "238", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "templates/rake_fix.rb", "mode": "33188", "license": "mit", "language": [ { "name": "Ruby", "bytes": "13615" } ], "symlink_target": "" }
class SkBitmap; namespace gfx { class Size; } namespace android_webview { // A helper that observes favicon changes for Webview. class IconHelper : public content::WebContentsObserver { public: class Listener { public: virtual bool ShouldDownloadFavicon(const GURL& icon_url) = 0; virtual void OnReceivedIcon(const GURL& icon_url, const SkBitmap& bitmap) = 0; virtual void OnReceivedTouchIconUrl(const std::string& url, const bool precomposed) = 0; protected: virtual ~Listener() {} }; explicit IconHelper(content::WebContents* web_contents); IconHelper(const IconHelper&) = delete; IconHelper& operator=(const IconHelper&) = delete; ~IconHelper() override; void SetListener(Listener* listener); // From WebContentsObserver void DidUpdateFaviconURL( content::RenderFrameHost* render_frame_host, const std::vector<blink::mojom::FaviconURLPtr>& candidates) override; void DidStartNavigation(content::NavigationHandle* navigation) override; void DownloadFaviconCallback( int id, int http_status_code, const GURL& image_url, const std::vector<SkBitmap>& bitmaps, const std::vector<gfx::Size>& original_bitmap_sizes); private: void MarkUnableToDownloadFavicon(const GURL& icon_url); bool WasUnableToDownloadFavicon(const GURL& icon_url) const; void ClearUnableToDownloadFavicons(); raw_ptr<Listener> listener_; using MissingFaviconURLHash = size_t; std::unordered_set<MissingFaviconURLHash> missing_favicon_urls_; }; } // namespace android_webview #endif // ANDROID_WEBVIEW_BROWSER_ICON_HELPER_H_
{ "content_hash": "8e033ef4f3442085e937d6bf14a27056", "timestamp": "", "source": "github", "line_count": 58, "max_line_length": 75, "avg_line_length": 28.96551724137931, "alnum_prop": 0.7047619047619048, "repo_name": "ric2b/Vivaldi-browser", "id": "b9e3bca636fc4043f859173548ef5a7ce6d46be7", "size": "2250", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "chromium/android_webview/browser/icon_helper.h", "mode": "33188", "license": "bsd-3-clause", "language": [], "symlink_target": "" }
package hotpepper4s.raw import hotpepper4s.{CodeName, Results} /** * @author ponkotuy * Date: 2014/01/04 */ case class SpecialCategoryResults( private val api_version: String, private val results_available: Int, private val results_returned: String, private val results_start: Int, private val special_category: List[SpecialCategory]) extends Results[SpecialCategory] { def apiVersion: String = api_version def resultsAvailable: Int = results_available def resultsReturned: String = results_returned def resultsStart: Int = results_start def data: List[SpecialCategory] = special_category def specialCategory = special_category } case class SpecialCategory(code: String, name: String) extends CodeName
{ "content_hash": "d3325683da6baf0a6c90704fc0f5077d", "timestamp": "", "source": "github", "line_count": 23, "max_line_length": 91, "avg_line_length": 32.17391304347826, "alnum_prop": 0.7608108108108108, "repo_name": "ponkotuy/hotpepper4s", "id": "45841cedb751a2ab92a581365383eed338c2b358", "size": "740", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/main/scala/hotpepper4s/raw/SpecialCategoryResults.scala", "mode": "33188", "license": "mit", "language": [ { "name": "Java", "bytes": "241" }, { "name": "Scala", "bytes": "24126" } ], "symlink_target": "" }
sigma.layout.dagre ======================== Plugin developed by [Sébastien Heymann](https://github.com/sheymann) for [Linkurious](https://github.com/Linkurious) and published under the [MIT](LICENSE) license. Contact: seb@linkurio.us --- This plugin implements a binding to the [dagre layout](https://github.com/cpettitt/dagre), which organises the graph using a DAG (directed acyclic graph) system, written by [Chris Pettitt](https://www.linkedin.com/in/chrismpettitt). It is especially suitable for DAGs and trees. For more information, please refer to its [Dagre's documentation](https://github.com/cpettitt/dagre/wiki). Because Dagre is a separate library, the developer must manually include [`dagre.js`](https://github.com/cpettitt/dagre/releases) in their app in order to use the layout. :warning: The time complexity of the algorithm is quadratic and is thus suitable for small graphs with less than 300 edges only. ## Recommended reading source: https://github.com/cpettitt/dagre/wiki#recommended-reading This work was produced by taking advantage of many papers and books. If you're interested in how dagre works internally here are some of the most important papers to read. The general skeleton for Dagre comes from [*Gansner, et al., "A Technique for Drawing Directed Graphs"*](http://www.graphviz.org/Documentation/TSE93.pdf), which gives both an excellent high level overview of the phases involved in layered drawing as well as diving into the details and problems of each of the phases. Besides the basic skeleton, the author specifically used the technique described in the paper to produce an acyclic graph, and the author use the network simplex algorithm for ranking. If there is one paper to start with when learning about layered graph drawing, this is it! For crossing minimization we used [*Jünger and Mutzel, "2-Layer Straightline Crossing Minimization"*](http://www.researchgate.net/profile/Petra_Mutzel/publication/30508315_2-Layer_Straightline_Crossing_Minimization_Performance_of_Exact_and_Heuristic_Algorithms/links/09e4150eabaf4cc7bd000000.pdf), which provides a comparison of the performance of various heuristics and exact algorithms for crossing minimization. For counting the number of edge crossings between two layers we use the `O(|E| log |V_small|)` algorithm described in [*Barth, et al., "Simple and Efficient Bilayer Cross Counting"*](http://jgaa.info/accepted/2004/BarthMutzelJuenger2004.8.2.pdf). For positioning (or coordinate assignment), we derived our algorithm from [*Brandes and Köpf, "Fast and Simple Horizontal Coordinate Assignment"*](http://www.inf.uni-konstanz.de/algo/publications/bk-fshca-01.pdf). The author made some adjustments to get tighter graphs when node and edges sizes vary greatly. The implementation for clustering derives extensively from Sander, [*"Layout of Compound Directed Graphs."*](http://scidok.sulb.uni-saarland.de/volltexte/2005/359/pdf/tr-A03-96.pdf) It is an excellent paper that details the impact of clustering on all phases of layout and also covers many of the associated problems. Crossing reduction with clustered graphs derives from two papers by Michael Forster, *"Applying Crossing Reduction Strategies to Layered Compound Graphs"* and *"A Fast and Simple Heuristic for Constrained Two-Level Crossing Reduction."* ## Methods **configure** Changes the layout's configuration. ```js var listener = sigma.layouts.dagre.configure(sigInst, config); ``` **start** Starts the layout. It is possible to pass a configuration if this is the first time you start the layout. ```js var listener = sigma.layouts.dagre.start(sigInst, config); ``` **isRunning** Returns whether the layout is running. ```js sigma.layouts.dagre.isRunning(sigInst); ``` ## Configuration * **nodes**: *array*: the subset of nodes to apply the layout. * **boundingBox** *object|boolean*: constrain layout bounds. Value: {minX, maxX, minY, maxY} or true (all current positions of the given nodes). *Algorithm configuration* * **directed**: *boolean* `true`: if `true`, take edge direction into account. * **multigraph**: *boolean* `true`: if `true`, allows multiple edges between the same pair of nodes. * **compound**: *boolean* `true`: if `true`, allows ompound nodes, i.e. nodes which can be the parent of other nodes. * **rankDir** *string* `TB`: direction for rank nodes. Can be `TB`, `BT`, `LR`, or `RL`, where T = top, B = bottom, L = left, and R = right. *Easing configuration* * **easing** *string*: if specified, ease the transition between nodes positions if background is `true`. The duration is specified by the Sigma settings `animationsTime`. See [sigma.utils.easing](../../src/utils/sigma.utils.js#L723) for available values. * **duration** *number*: duration of the transition for the easing method. Default value is Sigma setting `animationsTime`. ## Events The plugin dispatches the following events: - `start`: on layout start. - `interpolate`: at the beginning of the layout animation if an *easing* function is specified and the layout is ran on background. - `stop`: on layout stop, will be dispatched after `interpolate`. Example: ```js var config = { rankdir: 'TB' }; // Start the algorithm: var listener = sigma.layouts.dagre.configure(sigInst, config); // Bind all events: listener.bind('start stop interpolate', function(event) { console.log(event.type); }); sigma.layouts.dagre.start(sigInst); ```
{ "content_hash": "9a9af72edb3e32ebfc2882539f4f787e", "timestamp": "", "source": "github", "line_count": 99, "max_line_length": 593, "avg_line_length": 54.78787878787879, "alnum_prop": 0.7617994100294986, "repo_name": "kevin-who/genify", "id": "784a8cde7e951c51a34a146e7906f9a97515e8e4", "size": "5427", "binary": false, "copies": "7", "ref": "refs/heads/master", "path": "public/javascripts/linkurious/plugins/sigma.layout.dagre/README.md", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "25694" }, { "name": "HTML", "bytes": "43776" }, { "name": "JavaScript", "bytes": "1031717" }, { "name": "Ruby", "bytes": "33661" } ], "symlink_target": "" }
<?xml version="1.0" encoding="utf-8"?> <resources> <!-- From: file:/C:/github/Battleship/app/src/main/res/values-w820dp/dimens.xml --> <eat-comment/> <dimen name="activity_horizontal_margin">64dp</dimen> </resources>
{ "content_hash": "627fe6c9b04fd0cd50630f33e9814914", "timestamp": "", "source": "github", "line_count": 6, "max_line_length": 87, "avg_line_length": 38, "alnum_prop": 0.6710526315789473, "repo_name": "djmiley/BattleshipAndroid", "id": "db7beb71b6458238b8ed41f7e36bac90547b4047", "size": "228", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "app/build/intermediates/res/release/values-w820dp-v13/values.xml", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "3223" }, { "name": "HTML", "bytes": "903" }, { "name": "Java", "bytes": "1135058" } ], "symlink_target": "" }
class AddTeamsnapScans < ActiveRecord::Migration def change create_table :teamsnap_scan_accounts do |t| t.string :username t.string :password t.boolean :is_active t.timestamps end end end
{ "content_hash": "fd71f4be836a9e74c3d4da3a48d5e95b", "timestamp": "", "source": "github", "line_count": 10, "max_line_length": 48, "avg_line_length": 22.4, "alnum_prop": 0.6741071428571429, "repo_name": "BigAppleSoftball/ratingsManager", "id": "894f6517416d0bb61df06a4f35cc27655aaca070", "size": "224", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "db/migrate/20150316002236_add_teamsnap_scans.rb", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "3103703" }, { "name": "HTML", "bytes": "312828" }, { "name": "JavaScript", "bytes": "1971908" }, { "name": "Ruby", "bytes": "349531" } ], "symlink_target": "" }
<?xml version='1.0' encoding='UTF-8'?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd"> <html> <head> <title>UnknownCodecException - core 0.8.3-SNAPSHOT API - kafka.common.UnknownCodecException</title> <meta name="description" content="UnknownCodecException - core 0.8.3 - SNAPSHOT API - kafka.common.UnknownCodecException" /> <meta name="keywords" content="UnknownCodecException core 0.8.3 SNAPSHOT API kafka.common.UnknownCodecException" /> <meta http-equiv="content-type" content="text/html; charset=UTF-8" /> <link href="../../lib/template.css" media="screen" type="text/css" rel="stylesheet" /> <link href="../../lib/diagrams.css" media="screen" type="text/css" rel="stylesheet" id="diagrams-css" /> <script type="text/javascript"> if(top === self) { var url = '../../index.html'; var hash = 'kafka.common.UnknownCodecException'; var anchor = window.location.hash; var anchor_opt = ''; if (anchor.length >= 1) anchor_opt = '@' + anchor.substring(1); window.location.href = url + '#' + hash + anchor_opt; } </script> </head> <body class="type"> <div id="definition"> <img src="../../lib/class_big.png" /> <p id="owner"><a href="../package.html" class="extype" name="kafka">kafka</a>.<a href="package.html" class="extype" name="kafka.common">common</a></p> <h1>UnknownCodecException</h1> </div> <h4 id="signature" class="signature"> <span class="modifier_kind"> <span class="modifier"></span> <span class="kind">class</span> </span> <span class="symbol"> <span class="name">UnknownCodecException</span><span class="result"> extends <span class="extype" name="scala.RuntimeException">RuntimeException</span></span> </span> </h4> <div id="comment" class="fullcommenttop"><div class="comment cmt"><p>Indicates the client has requested a range no longer available on the server </p></div><div class="toggleContainer block"> <span class="toggle">Linear Supertypes</span> <div class="superTypes hiddenContent"><span class="extype" name="java.lang.RuntimeException">RuntimeException</span>, <span class="extype" name="java.lang.Exception">Exception</span>, <span class="extype" name="java.lang.Throwable">Throwable</span>, <span class="extype" name="java.io.Serializable">Serializable</span>, <span class="extype" name="scala.AnyRef">AnyRef</span>, <span class="extype" name="scala.Any">Any</span></div> </div></div> <div id="mbrsel"> <div id="textfilter"><span class="pre"></span><span class="input"><input id="mbrsel-input" type="text" accesskey="/" /></span><span class="post"></span></div> <div id="order"> <span class="filtertype">Ordering</span> <ol> <li class="alpha in"><span>Alphabetic</span></li> <li class="inherit out"><span>By inheritance</span></li> </ol> </div> <div id="ancestors"> <span class="filtertype">Inherited<br /> </span> <ol id="linearization"> <li class="in" name="kafka.common.UnknownCodecException"><span>UnknownCodecException</span></li><li class="in" name="java.lang.RuntimeException"><span>RuntimeException</span></li><li class="in" name="java.lang.Exception"><span>Exception</span></li><li class="in" name="java.lang.Throwable"><span>Throwable</span></li><li class="in" name="java.io.Serializable"><span>Serializable</span></li><li class="in" name="scala.AnyRef"><span>AnyRef</span></li><li class="in" name="scala.Any"><span>Any</span></li> </ol> </div><div id="ancestors"> <span class="filtertype"></span> <ol> <li class="hideall out"><span>Hide All</span></li> <li class="showall in"><span>Show all</span></li> </ol> <a href="http://docs.scala-lang.org/overviews/scaladoc/usage.html#members" target="_blank">Learn more about member selection</a> </div> <div id="visbl"> <span class="filtertype">Visibility</span> <ol><li class="public in"><span>Public</span></li><li class="all out"><span>All</span></li></ol> </div> </div> <div id="template"> <div id="allMembers"> <div id="constructors" class="members"> <h3>Instance Constructors</h3> <ol><li name="kafka.common.UnknownCodecException#&lt;init&gt;" visbl="pub" data-isabs="false" fullComment="no" group="Ungrouped"> <a id="&lt;init&gt;():kafka.common.UnknownCodecException"></a> <a id="&lt;init&gt;:UnknownCodecException"></a> <h4 class="signature"> <span class="modifier_kind"> <span class="modifier"></span> <span class="kind">new</span> </span> <span class="symbol"> <span class="name">UnknownCodecException</span><span class="params">()</span> </span> </h4> </li><li name="kafka.common.UnknownCodecException#&lt;init&gt;" visbl="pub" data-isabs="false" fullComment="no" group="Ungrouped"> <a id="&lt;init&gt;(message:String):kafka.common.UnknownCodecException"></a> <a id="&lt;init&gt;:UnknownCodecException"></a> <h4 class="signature"> <span class="modifier_kind"> <span class="modifier"></span> <span class="kind">new</span> </span> <span class="symbol"> <span class="name">UnknownCodecException</span><span class="params">(<span name="message">message: <span class="extype" name="scala.Predef.String">String</span></span>)</span> </span> </h4> </li></ol> </div> <div id="values" class="values members"> <h3>Value Members</h3> <ol><li name="scala.AnyRef#!=" visbl="pub" data-isabs="false" fullComment="yes" group="Ungrouped"> <a id="!=(x$1:AnyRef):Boolean"></a> <a id="!=(AnyRef):Boolean"></a> <h4 class="signature"> <span class="modifier_kind"> <span class="modifier">final </span> <span class="kind">def</span> </span> <span class="symbol"> <span title="gt4s: $bang$eq" class="name">!=</span><span class="params">(<span name="arg0">arg0: <span class="extype" name="scala.AnyRef">AnyRef</span></span>)</span><span class="result">: <span class="extype" name="scala.Boolean">Boolean</span></span> </span> </h4> <div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd>AnyRef</dd></dl></div> </li><li name="scala.Any#!=" visbl="pub" data-isabs="false" fullComment="yes" group="Ungrouped"> <a id="!=(x$1:Any):Boolean"></a> <a id="!=(Any):Boolean"></a> <h4 class="signature"> <span class="modifier_kind"> <span class="modifier">final </span> <span class="kind">def</span> </span> <span class="symbol"> <span title="gt4s: $bang$eq" class="name">!=</span><span class="params">(<span name="arg0">arg0: <span class="extype" name="scala.Any">Any</span></span>)</span><span class="result">: <span class="extype" name="scala.Boolean">Boolean</span></span> </span> </h4> <div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd>Any</dd></dl></div> </li><li name="scala.AnyRef###" visbl="pub" data-isabs="false" fullComment="yes" group="Ungrouped"> <a id="##():Int"></a> <a id="##():Int"></a> <h4 class="signature"> <span class="modifier_kind"> <span class="modifier">final </span> <span class="kind">def</span> </span> <span class="symbol"> <span title="gt4s: $hash$hash" class="name">##</span><span class="params">()</span><span class="result">: <span class="extype" name="scala.Int">Int</span></span> </span> </h4> <div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd>AnyRef → Any</dd></dl></div> </li><li name="scala.AnyRef#==" visbl="pub" data-isabs="false" fullComment="yes" group="Ungrouped"> <a id="==(x$1:AnyRef):Boolean"></a> <a id="==(AnyRef):Boolean"></a> <h4 class="signature"> <span class="modifier_kind"> <span class="modifier">final </span> <span class="kind">def</span> </span> <span class="symbol"> <span title="gt4s: $eq$eq" class="name">==</span><span class="params">(<span name="arg0">arg0: <span class="extype" name="scala.AnyRef">AnyRef</span></span>)</span><span class="result">: <span class="extype" name="scala.Boolean">Boolean</span></span> </span> </h4> <div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd>AnyRef</dd></dl></div> </li><li name="scala.Any#==" visbl="pub" data-isabs="false" fullComment="yes" group="Ungrouped"> <a id="==(x$1:Any):Boolean"></a> <a id="==(Any):Boolean"></a> <h4 class="signature"> <span class="modifier_kind"> <span class="modifier">final </span> <span class="kind">def</span> </span> <span class="symbol"> <span title="gt4s: $eq$eq" class="name">==</span><span class="params">(<span name="arg0">arg0: <span class="extype" name="scala.Any">Any</span></span>)</span><span class="result">: <span class="extype" name="scala.Boolean">Boolean</span></span> </span> </h4> <div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd>Any</dd></dl></div> </li><li name="java.lang.Throwable#addSuppressed" visbl="pub" data-isabs="false" fullComment="yes" group="Ungrouped"> <a id="addSuppressed(x$1:Throwable):Unit"></a> <a id="addSuppressed(Throwable):Unit"></a> <h4 class="signature"> <span class="modifier_kind"> <span class="modifier">final </span> <span class="kind">def</span> </span> <span class="symbol"> <span class="name">addSuppressed</span><span class="params">(<span name="arg0">arg0: <span class="extype" name="java.lang.Throwable">Throwable</span></span>)</span><span class="result">: <span class="extype" name="scala.Unit">Unit</span></span> </span> </h4> <div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd>Throwable</dd></dl></div> </li><li name="scala.Any#asInstanceOf" visbl="pub" data-isabs="false" fullComment="yes" group="Ungrouped"> <a id="asInstanceOf[T0]:T0"></a> <a id="asInstanceOf[T0]:T0"></a> <h4 class="signature"> <span class="modifier_kind"> <span class="modifier">final </span> <span class="kind">def</span> </span> <span class="symbol"> <span class="name">asInstanceOf</span><span class="tparams">[<span name="T0">T0</span>]</span><span class="result">: <span class="extype" name="scala.Any.asInstanceOf.T0">T0</span></span> </span> </h4> <div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd>Any</dd></dl></div> </li><li name="scala.AnyRef#clone" visbl="prt" data-isabs="false" fullComment="yes" group="Ungrouped"> <a id="clone():Object"></a> <a id="clone():AnyRef"></a> <h4 class="signature"> <span class="modifier_kind"> <span class="modifier"></span> <span class="kind">def</span> </span> <span class="symbol"> <span class="name">clone</span><span class="params">()</span><span class="result">: <span class="extype" name="scala.AnyRef">AnyRef</span></span> </span> </h4> <div class="fullcomment"><dl class="attributes block"> <dt>Attributes</dt><dd>protected[<a href="../../java$lang.html" class="extype" name="java.lang">java.lang</a>] </dd><dt>Definition Classes</dt><dd>AnyRef</dd><dt>Annotations</dt><dd> <span class="name">@throws</span><span class="args">(<span> <span class="defval" name="classOf[java.lang.CloneNotSupportedException]">...</span> </span>)</span> </dd></dl></div> </li><li name="scala.AnyRef#eq" visbl="pub" data-isabs="false" fullComment="yes" group="Ungrouped"> <a id="eq(x$1:AnyRef):Boolean"></a> <a id="eq(AnyRef):Boolean"></a> <h4 class="signature"> <span class="modifier_kind"> <span class="modifier">final </span> <span class="kind">def</span> </span> <span class="symbol"> <span class="name">eq</span><span class="params">(<span name="arg0">arg0: <span class="extype" name="scala.AnyRef">AnyRef</span></span>)</span><span class="result">: <span class="extype" name="scala.Boolean">Boolean</span></span> </span> </h4> <div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd>AnyRef</dd></dl></div> </li><li name="scala.AnyRef#equals" visbl="pub" data-isabs="false" fullComment="yes" group="Ungrouped"> <a id="equals(x$1:Any):Boolean"></a> <a id="equals(Any):Boolean"></a> <h4 class="signature"> <span class="modifier_kind"> <span class="modifier"></span> <span class="kind">def</span> </span> <span class="symbol"> <span class="name">equals</span><span class="params">(<span name="arg0">arg0: <span class="extype" name="scala.Any">Any</span></span>)</span><span class="result">: <span class="extype" name="scala.Boolean">Boolean</span></span> </span> </h4> <div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd>AnyRef → Any</dd></dl></div> </li><li name="java.lang.Throwable#fillInStackTrace" visbl="pub" data-isabs="false" fullComment="yes" group="Ungrouped"> <a id="fillInStackTrace():Throwable"></a> <a id="fillInStackTrace():Throwable"></a> <h4 class="signature"> <span class="modifier_kind"> <span class="modifier"></span> <span class="kind">def</span> </span> <span class="symbol"> <span class="name">fillInStackTrace</span><span class="params">()</span><span class="result">: <span class="extype" name="java.lang.Throwable">Throwable</span></span> </span> </h4> <div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd>Throwable</dd></dl></div> </li><li name="scala.AnyRef#finalize" visbl="prt" data-isabs="false" fullComment="yes" group="Ungrouped"> <a id="finalize():Unit"></a> <a id="finalize():Unit"></a> <h4 class="signature"> <span class="modifier_kind"> <span class="modifier"></span> <span class="kind">def</span> </span> <span class="symbol"> <span class="name">finalize</span><span class="params">()</span><span class="result">: <span class="extype" name="scala.Unit">Unit</span></span> </span> </h4> <div class="fullcomment"><dl class="attributes block"> <dt>Attributes</dt><dd>protected[<a href="../../java$lang.html" class="extype" name="java.lang">java.lang</a>] </dd><dt>Definition Classes</dt><dd>AnyRef</dd><dt>Annotations</dt><dd> <span class="name">@throws</span><span class="args">(<span> <span class="symbol">classOf[java.lang.Throwable]</span> </span>)</span> </dd></dl></div> </li><li name="java.lang.Throwable#getCause" visbl="pub" data-isabs="false" fullComment="yes" group="Ungrouped"> <a id="getCause():Throwable"></a> <a id="getCause():Throwable"></a> <h4 class="signature"> <span class="modifier_kind"> <span class="modifier"></span> <span class="kind">def</span> </span> <span class="symbol"> <span class="name">getCause</span><span class="params">()</span><span class="result">: <span class="extype" name="java.lang.Throwable">Throwable</span></span> </span> </h4> <div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd>Throwable</dd></dl></div> </li><li name="scala.AnyRef#getClass" visbl="pub" data-isabs="false" fullComment="yes" group="Ungrouped"> <a id="getClass():Class[_]"></a> <a id="getClass():Class[_]"></a> <h4 class="signature"> <span class="modifier_kind"> <span class="modifier">final </span> <span class="kind">def</span> </span> <span class="symbol"> <span class="name">getClass</span><span class="params">()</span><span class="result">: <span class="extype" name="java.lang.Class">Class</span>[_]</span> </span> </h4> <div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd>AnyRef → Any</dd></dl></div> </li><li name="java.lang.Throwable#getLocalizedMessage" visbl="pub" data-isabs="false" fullComment="yes" group="Ungrouped"> <a id="getLocalizedMessage():String"></a> <a id="getLocalizedMessage():String"></a> <h4 class="signature"> <span class="modifier_kind"> <span class="modifier"></span> <span class="kind">def</span> </span> <span class="symbol"> <span class="name">getLocalizedMessage</span><span class="params">()</span><span class="result">: <span class="extype" name="java.lang.String">String</span></span> </span> </h4> <div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd>Throwable</dd></dl></div> </li><li name="java.lang.Throwable#getMessage" visbl="pub" data-isabs="false" fullComment="yes" group="Ungrouped"> <a id="getMessage():String"></a> <a id="getMessage():String"></a> <h4 class="signature"> <span class="modifier_kind"> <span class="modifier"></span> <span class="kind">def</span> </span> <span class="symbol"> <span class="name">getMessage</span><span class="params">()</span><span class="result">: <span class="extype" name="java.lang.String">String</span></span> </span> </h4> <div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd>Throwable</dd></dl></div> </li><li name="java.lang.Throwable#getStackTrace" visbl="pub" data-isabs="false" fullComment="yes" group="Ungrouped"> <a id="getStackTrace():Array[StackTraceElement]"></a> <a id="getStackTrace():Array[StackTraceElement]"></a> <h4 class="signature"> <span class="modifier_kind"> <span class="modifier"></span> <span class="kind">def</span> </span> <span class="symbol"> <span class="name">getStackTrace</span><span class="params">()</span><span class="result">: <span class="extype" name="scala.Array">Array</span>[<span class="extype" name="java.lang.StackTraceElement">StackTraceElement</span>]</span> </span> </h4> <div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd>Throwable</dd></dl></div> </li><li name="java.lang.Throwable#getSuppressed" visbl="pub" data-isabs="false" fullComment="yes" group="Ungrouped"> <a id="getSuppressed():Array[Throwable]"></a> <a id="getSuppressed():Array[Throwable]"></a> <h4 class="signature"> <span class="modifier_kind"> <span class="modifier">final </span> <span class="kind">def</span> </span> <span class="symbol"> <span class="name">getSuppressed</span><span class="params">()</span><span class="result">: <span class="extype" name="scala.Array">Array</span>[<span class="extype" name="java.lang.Throwable">Throwable</span>]</span> </span> </h4> <div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd>Throwable</dd></dl></div> </li><li name="scala.AnyRef#hashCode" visbl="pub" data-isabs="false" fullComment="yes" group="Ungrouped"> <a id="hashCode():Int"></a> <a id="hashCode():Int"></a> <h4 class="signature"> <span class="modifier_kind"> <span class="modifier"></span> <span class="kind">def</span> </span> <span class="symbol"> <span class="name">hashCode</span><span class="params">()</span><span class="result">: <span class="extype" name="scala.Int">Int</span></span> </span> </h4> <div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd>AnyRef → Any</dd></dl></div> </li><li name="java.lang.Throwable#initCause" visbl="pub" data-isabs="false" fullComment="yes" group="Ungrouped"> <a id="initCause(x$1:Throwable):Throwable"></a> <a id="initCause(Throwable):Throwable"></a> <h4 class="signature"> <span class="modifier_kind"> <span class="modifier"></span> <span class="kind">def</span> </span> <span class="symbol"> <span class="name">initCause</span><span class="params">(<span name="arg0">arg0: <span class="extype" name="java.lang.Throwable">Throwable</span></span>)</span><span class="result">: <span class="extype" name="java.lang.Throwable">Throwable</span></span> </span> </h4> <div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd>Throwable</dd></dl></div> </li><li name="scala.Any#isInstanceOf" visbl="pub" data-isabs="false" fullComment="yes" group="Ungrouped"> <a id="isInstanceOf[T0]:Boolean"></a> <a id="isInstanceOf[T0]:Boolean"></a> <h4 class="signature"> <span class="modifier_kind"> <span class="modifier">final </span> <span class="kind">def</span> </span> <span class="symbol"> <span class="name">isInstanceOf</span><span class="tparams">[<span name="T0">T0</span>]</span><span class="result">: <span class="extype" name="scala.Boolean">Boolean</span></span> </span> </h4> <div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd>Any</dd></dl></div> </li><li name="scala.AnyRef#ne" visbl="pub" data-isabs="false" fullComment="yes" group="Ungrouped"> <a id="ne(x$1:AnyRef):Boolean"></a> <a id="ne(AnyRef):Boolean"></a> <h4 class="signature"> <span class="modifier_kind"> <span class="modifier">final </span> <span class="kind">def</span> </span> <span class="symbol"> <span class="name">ne</span><span class="params">(<span name="arg0">arg0: <span class="extype" name="scala.AnyRef">AnyRef</span></span>)</span><span class="result">: <span class="extype" name="scala.Boolean">Boolean</span></span> </span> </h4> <div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd>AnyRef</dd></dl></div> </li><li name="scala.AnyRef#notify" visbl="pub" data-isabs="false" fullComment="yes" group="Ungrouped"> <a id="notify():Unit"></a> <a id="notify():Unit"></a> <h4 class="signature"> <span class="modifier_kind"> <span class="modifier">final </span> <span class="kind">def</span> </span> <span class="symbol"> <span class="name">notify</span><span class="params">()</span><span class="result">: <span class="extype" name="scala.Unit">Unit</span></span> </span> </h4> <div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd>AnyRef</dd></dl></div> </li><li name="scala.AnyRef#notifyAll" visbl="pub" data-isabs="false" fullComment="yes" group="Ungrouped"> <a id="notifyAll():Unit"></a> <a id="notifyAll():Unit"></a> <h4 class="signature"> <span class="modifier_kind"> <span class="modifier">final </span> <span class="kind">def</span> </span> <span class="symbol"> <span class="name">notifyAll</span><span class="params">()</span><span class="result">: <span class="extype" name="scala.Unit">Unit</span></span> </span> </h4> <div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd>AnyRef</dd></dl></div> </li><li name="java.lang.Throwable#printStackTrace" visbl="pub" data-isabs="false" fullComment="yes" group="Ungrouped"> <a id="printStackTrace(x$1:java.io.PrintWriter):Unit"></a> <a id="printStackTrace(PrintWriter):Unit"></a> <h4 class="signature"> <span class="modifier_kind"> <span class="modifier"></span> <span class="kind">def</span> </span> <span class="symbol"> <span class="name">printStackTrace</span><span class="params">(<span name="arg0">arg0: <span class="extype" name="java.io.PrintWriter">PrintWriter</span></span>)</span><span class="result">: <span class="extype" name="scala.Unit">Unit</span></span> </span> </h4> <div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd>Throwable</dd></dl></div> </li><li name="java.lang.Throwable#printStackTrace" visbl="pub" data-isabs="false" fullComment="yes" group="Ungrouped"> <a id="printStackTrace(x$1:java.io.PrintStream):Unit"></a> <a id="printStackTrace(PrintStream):Unit"></a> <h4 class="signature"> <span class="modifier_kind"> <span class="modifier"></span> <span class="kind">def</span> </span> <span class="symbol"> <span class="name">printStackTrace</span><span class="params">(<span name="arg0">arg0: <span class="extype" name="java.io.PrintStream">PrintStream</span></span>)</span><span class="result">: <span class="extype" name="scala.Unit">Unit</span></span> </span> </h4> <div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd>Throwable</dd></dl></div> </li><li name="java.lang.Throwable#printStackTrace" visbl="pub" data-isabs="false" fullComment="yes" group="Ungrouped"> <a id="printStackTrace():Unit"></a> <a id="printStackTrace():Unit"></a> <h4 class="signature"> <span class="modifier_kind"> <span class="modifier"></span> <span class="kind">def</span> </span> <span class="symbol"> <span class="name">printStackTrace</span><span class="params">()</span><span class="result">: <span class="extype" name="scala.Unit">Unit</span></span> </span> </h4> <div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd>Throwable</dd></dl></div> </li><li name="java.lang.Throwable#setStackTrace" visbl="pub" data-isabs="false" fullComment="yes" group="Ungrouped"> <a id="setStackTrace(x$1:Array[StackTraceElement]):Unit"></a> <a id="setStackTrace(Array[StackTraceElement]):Unit"></a> <h4 class="signature"> <span class="modifier_kind"> <span class="modifier"></span> <span class="kind">def</span> </span> <span class="symbol"> <span class="name">setStackTrace</span><span class="params">(<span name="arg0">arg0: <span class="extype" name="scala.Array">Array</span>[<span class="extype" name="java.lang.StackTraceElement">StackTraceElement</span>]</span>)</span><span class="result">: <span class="extype" name="scala.Unit">Unit</span></span> </span> </h4> <div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd>Throwable</dd></dl></div> </li><li name="scala.AnyRef#synchronized" visbl="pub" data-isabs="false" fullComment="yes" group="Ungrouped"> <a id="synchronized[T0](x$1:=&gt;T0):T0"></a> <a id="synchronized[T0](⇒T0):T0"></a> <h4 class="signature"> <span class="modifier_kind"> <span class="modifier">final </span> <span class="kind">def</span> </span> <span class="symbol"> <span class="name">synchronized</span><span class="tparams">[<span name="T0">T0</span>]</span><span class="params">(<span name="arg0">arg0: ⇒ <span class="extype" name="java.lang.AnyRef.synchronized.T0">T0</span></span>)</span><span class="result">: <span class="extype" name="java.lang.AnyRef.synchronized.T0">T0</span></span> </span> </h4> <div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd>AnyRef</dd></dl></div> </li><li name="java.lang.Throwable#toString" visbl="pub" data-isabs="false" fullComment="yes" group="Ungrouped"> <a id="toString():String"></a> <a id="toString():String"></a> <h4 class="signature"> <span class="modifier_kind"> <span class="modifier"></span> <span class="kind">def</span> </span> <span class="symbol"> <span class="name">toString</span><span class="params">()</span><span class="result">: <span class="extype" name="java.lang.String">String</span></span> </span> </h4> <div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd>Throwable → AnyRef → Any</dd></dl></div> </li><li name="scala.AnyRef#wait" visbl="pub" data-isabs="false" fullComment="yes" group="Ungrouped"> <a id="wait():Unit"></a> <a id="wait():Unit"></a> <h4 class="signature"> <span class="modifier_kind"> <span class="modifier">final </span> <span class="kind">def</span> </span> <span class="symbol"> <span class="name">wait</span><span class="params">()</span><span class="result">: <span class="extype" name="scala.Unit">Unit</span></span> </span> </h4> <div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd>AnyRef</dd><dt>Annotations</dt><dd> <span class="name">@throws</span><span class="args">(<span> <span class="defval" name="classOf[java.lang.InterruptedException]">...</span> </span>)</span> </dd></dl></div> </li><li name="scala.AnyRef#wait" visbl="pub" data-isabs="false" fullComment="yes" group="Ungrouped"> <a id="wait(x$1:Long,x$2:Int):Unit"></a> <a id="wait(Long,Int):Unit"></a> <h4 class="signature"> <span class="modifier_kind"> <span class="modifier">final </span> <span class="kind">def</span> </span> <span class="symbol"> <span class="name">wait</span><span class="params">(<span name="arg0">arg0: <span class="extype" name="scala.Long">Long</span></span>, <span name="arg1">arg1: <span class="extype" name="scala.Int">Int</span></span>)</span><span class="result">: <span class="extype" name="scala.Unit">Unit</span></span> </span> </h4> <div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd>AnyRef</dd><dt>Annotations</dt><dd> <span class="name">@throws</span><span class="args">(<span> <span class="defval" name="classOf[java.lang.InterruptedException]">...</span> </span>)</span> </dd></dl></div> </li><li name="scala.AnyRef#wait" visbl="pub" data-isabs="false" fullComment="yes" group="Ungrouped"> <a id="wait(x$1:Long):Unit"></a> <a id="wait(Long):Unit"></a> <h4 class="signature"> <span class="modifier_kind"> <span class="modifier">final </span> <span class="kind">def</span> </span> <span class="symbol"> <span class="name">wait</span><span class="params">(<span name="arg0">arg0: <span class="extype" name="scala.Long">Long</span></span>)</span><span class="result">: <span class="extype" name="scala.Unit">Unit</span></span> </span> </h4> <div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd>AnyRef</dd><dt>Annotations</dt><dd> <span class="name">@throws</span><span class="args">(<span> <span class="defval" name="classOf[java.lang.InterruptedException]">...</span> </span>)</span> </dd></dl></div> </li></ol> </div> </div> <div id="inheritedMembers"> <div class="parent" name="java.lang.RuntimeException"> <h3>Inherited from <span class="extype" name="java.lang.RuntimeException">RuntimeException</span></h3> </div><div class="parent" name="java.lang.Exception"> <h3>Inherited from <span class="extype" name="java.lang.Exception">Exception</span></h3> </div><div class="parent" name="java.lang.Throwable"> <h3>Inherited from <span class="extype" name="java.lang.Throwable">Throwable</span></h3> </div><div class="parent" name="java.io.Serializable"> <h3>Inherited from <span class="extype" name="java.io.Serializable">Serializable</span></h3> </div><div class="parent" name="scala.AnyRef"> <h3>Inherited from <span class="extype" name="scala.AnyRef">AnyRef</span></h3> </div><div class="parent" name="scala.Any"> <h3>Inherited from <span class="extype" name="scala.Any">Any</span></h3> </div> </div> <div id="groupedMembers"> <div class="group" name="Ungrouped"> <h3>Ungrouped</h3> </div> </div> </div> <div id="tooltip"></div> <div id="footer"> </div> <script defer="defer" type="text/javascript" id="jquery-js" src="../../lib/jquery.js"></script><script defer="defer" type="text/javascript" id="jquery-ui-js" src="../../lib/jquery-ui.js"></script><script defer="defer" type="text/javascript" id="tools-tooltip-js" src="../../lib/tools.tooltip.js"></script><script defer="defer" type="text/javascript" id="template-js" src="../../lib/template.js"></script> </body> </html>
{ "content_hash": "d989a33a6a762e9b2f2032ee56c8da87", "timestamp": "", "source": "github", "line_count": 616, "max_line_length": 520, "avg_line_length": 54.82954545454545, "alnum_prop": 0.599259807549963, "repo_name": "richardliaw/cs286A", "id": "e0d2fd4363b5c29eaf07fce0344ac4b40ca3259d", "size": "33791", "binary": false, "copies": "3", "ref": "refs/heads/master", "path": "dataMover/kafka/core/build/docs/scaladoc/kafka/common/UnknownCodecException.html", "mode": "33188", "license": "bsd-2-clause", "language": [ { "name": "Batchfile", "bytes": "19756" }, { "name": "CSS", "bytes": "43684" }, { "name": "Groff", "bytes": "202" }, { "name": "HTML", "bytes": "22996620" }, { "name": "Java", "bytes": "2546563" }, { "name": "JavaScript", "bytes": "250136" }, { "name": "Python", "bytes": "296677" }, { "name": "Ruby", "bytes": "6258" }, { "name": "Scala", "bytes": "2222904" }, { "name": "Shell", "bytes": "97377" } ], "symlink_target": "" }
/////////////////////////////////////////////////////////////////////////////// // Copyright 2011 John Maddock. Distributed under the Boost // Software License, Version 1.0. (See accompanying file // LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) #ifndef BOOST_MATH_EXTENDED_REAL_HPP #define BOOST_MATH_EXTENDED_REAL_HPP #include <boost/cstdint.hpp> #include <boost/mpl/max.hpp> #include <boost/mpl/plus.hpp> #include <boost/mpl/or.hpp> #include <boost/mpl/find_if.hpp> #include <boost/assert.hpp> #include <boost/type_traits/remove_pointer.hpp> #include <boost/type_traits/is_signed.hpp> #include <boost/type_traits/is_unsigned.hpp> #include <boost/type_traits/is_floating_point.hpp> #include <boost/type_traits/is_integral.hpp> #include <boost/type_traits/make_unsigned.hpp> #include <boost/throw_exception.hpp> #include <boost/multiprecision/detail/generic_interconvert.hpp> #include <boost/multiprecision/detail/number_compare.hpp> #include <boost/multiprecision/traits/is_restricted_conversion.hpp> #include <istream> // stream operators #include <cstdio> // EOF #include <cctype> // isspace namespace boost{ namespace multiprecision{ #ifdef BOOST_MSVC // warning C4127: conditional expression is constant // warning C4714: function marked as __forceinline not inlined #pragma warning(push) #pragma warning(disable:4127 4714 6326) #endif template <class Backend, expression_template_option ExpressionTemplates> class number { typedef number<Backend, ExpressionTemplates> self_type; public: typedef Backend backend_type; BOOST_MP_FORCEINLINE BOOST_CONSTEXPR number() BOOST_MP_NOEXCEPT_IF(noexcept(Backend())) {} BOOST_MP_FORCEINLINE BOOST_CONSTEXPR number(const number& e) BOOST_MP_NOEXCEPT_IF(noexcept(Backend(std::declval<Backend const&>()))) : m_backend(e.m_backend){} template <class V> BOOST_MP_FORCEINLINE number(const V& v, typename boost::enable_if_c< (boost::is_arithmetic<V>::value || is_same<std::string, V>::value || is_convertible<V, const char*>::value) && !is_convertible<typename detail::canonical<V, Backend>::type, Backend>::value && !detail::is_restricted_conversion<typename detail::canonical<V, Backend>::type, Backend>::value #ifdef BOOST_HAS_FLOAT128 && !boost::is_same<V, __float128>::value #endif >::type* = 0) { m_backend = canonical_value(v); } template <class V> BOOST_MP_FORCEINLINE BOOST_CONSTEXPR number(const V& v, typename boost::enable_if_c< is_convertible<typename detail::canonical<V, Backend>::type, Backend>::value && !detail::is_restricted_conversion<typename detail::canonical<V, Backend>::type, Backend>::value >::type* = 0) #ifndef BOOST_INTEL BOOST_MP_NOEXCEPT_IF(noexcept(Backend(std::declval<typename detail::canonical<V, Backend>::type const&>()))) #endif : m_backend(canonical_value(v)) {} BOOST_MP_FORCEINLINE BOOST_CONSTEXPR number(const number& e, unsigned digits10) BOOST_MP_NOEXCEPT_IF(noexcept(Backend(std::declval<Backend const&>(), std::declval<unsigned>()))) : m_backend(e.m_backend, digits10){} template <class V> explicit BOOST_MP_FORCEINLINE number(const V& v, typename boost::enable_if_c< (boost::is_arithmetic<V>::value || is_same<std::string, V>::value || is_convertible<V, const char*>::value) && !detail::is_explicitly_convertible<typename detail::canonical<V, Backend>::type, Backend>::value && detail::is_restricted_conversion<typename detail::canonical<V, Backend>::type, Backend>::value >::type* = 0) BOOST_MP_NOEXCEPT_IF(noexcept(std::declval<Backend&>() = std::declval<typename detail::canonical<V, Backend>::type const&>())) { m_backend = canonical_value(v); } template <class V> explicit BOOST_MP_FORCEINLINE BOOST_CONSTEXPR number(const V& v, typename boost::enable_if_c< detail::is_explicitly_convertible<typename detail::canonical<V, Backend>::type, Backend>::value && (detail::is_restricted_conversion<typename detail::canonical<V, Backend>::type, Backend>::value || !is_convertible<typename detail::canonical<V, Backend>::type, Backend>::value) >::type* = 0) BOOST_MP_NOEXCEPT_IF(noexcept(Backend(std::declval<typename detail::canonical<V, Backend>::type const&>()))) : m_backend(canonical_value(v)) {} /* // // This conflicts with component based initialization (for rational and complex types) // which is arguably more useful. Disabled for now. // template <class V> number(V v, unsigned digits10, typename boost::enable_if<mpl::or_<boost::is_arithmetic<V>, is_same<std::string, V>, is_convertible<V, const char*> > >::type* dummy1 = 0) { m_backend.precision(digits10); m_backend = canonical_value(v); } */ template<expression_template_option ET> BOOST_MP_FORCEINLINE BOOST_CONSTEXPR number(const number<Backend, ET>& val) BOOST_MP_NOEXCEPT_IF(noexcept(Backend(std::declval<Backend const&>()))) : m_backend(val.backend()) {} template <class Other, expression_template_option ET> BOOST_MP_FORCEINLINE number(const number<Other, ET>& val, typename boost::enable_if_c<(boost::is_convertible<Other, Backend>::value && !detail::is_restricted_conversion<Other, Backend>::value)>::type* = 0) BOOST_MP_NOEXCEPT_IF(noexcept(Backend(std::declval<Other const&>()))) : m_backend(val.backend()) {} template <class Other, expression_template_option ET> explicit number(const number<Other, ET>& val, typename boost::enable_if_c< (!detail::is_explicitly_convertible<Other, Backend>::value) >::type* = 0) { // // Attempt a generic interconvertion: // using detail::generic_interconvert; generic_interconvert(backend(), val.backend(), number_category<Backend>(), number_category<Other>()); } template <class Other, expression_template_option ET> explicit BOOST_MP_FORCEINLINE number(const number<Other, ET>& val, typename boost::enable_if_c< (detail::is_explicitly_convertible<Other, Backend>::value && (detail::is_restricted_conversion<Other, Backend>::value || !boost::is_convertible<Other, Backend>::value)) >::type* = 0) BOOST_MP_NOEXCEPT_IF(noexcept(Backend(std::declval<Other const&>()))) : m_backend(val.backend()) {} template <class V> BOOST_MP_FORCEINLINE number(V v1, V v2, typename boost::enable_if<mpl::or_<boost::is_arithmetic<V>, is_same<std::string, V>, is_convertible<V, const char*> > >::type* = 0) { using default_ops::assign_components; assign_components(m_backend, canonical_value(v1), canonical_value(v2)); } template <class Other, expression_template_option ET> BOOST_MP_FORCEINLINE number(const number<Other, ET>& v1, const number<Other, ET>& v2, typename boost::enable_if<boost::is_convertible<Other, Backend> >::type* = 0) { using default_ops::assign_components; assign_components(m_backend, v1.backend(), v2.backend()); } template <class tag, class Arg1, class Arg2, class Arg3, class Arg4> typename boost::enable_if<is_convertible<typename detail::expression<tag, Arg1, Arg2, Arg3, Arg4>::result_type, self_type>, number&>::type operator=(const detail::expression<tag, Arg1, Arg2, Arg3, Arg4>& e) { typedef typename is_same<number, typename detail::expression<tag, Arg1, Arg2, Arg3, Arg4>::result_type>::type tag_type; do_assign(e, tag_type()); return *this; } template <class tag, class Arg1, class Arg2, class Arg3, class Arg4> number& assign(const detail::expression<tag, Arg1, Arg2, Arg3, Arg4>& e) { typedef typename is_same<number, typename detail::expression<tag, Arg1, Arg2, Arg3, Arg4>::result_type>::type tag_type; do_assign(e, tag_type()); return *this; } BOOST_MP_FORCEINLINE number& operator=(const number& e) BOOST_MP_NOEXCEPT_IF(noexcept(std::declval<Backend&>() = std::declval<Backend const&>())) { m_backend = e.m_backend; return *this; } template <class V> BOOST_MP_FORCEINLINE typename boost::enable_if<is_convertible<V, self_type>, number<Backend, ExpressionTemplates>& >::type operator=(const V& v) BOOST_MP_NOEXCEPT_IF(noexcept(std::declval<Backend&>() = std::declval<const typename detail::canonical<V, Backend>::type&>())) { m_backend = canonical_value(v); return *this; } template <class V> BOOST_MP_FORCEINLINE number<Backend, ExpressionTemplates>& assign(const V& v) BOOST_MP_NOEXCEPT_IF(noexcept(std::declval<Backend&>() = std::declval<const typename detail::canonical<V, Backend>::type&>())) { m_backend = canonical_value(v); return *this; } template <class Other, expression_template_option ET> typename boost::disable_if<boost::multiprecision::detail::is_explicitly_convertible<Other, Backend>, number<Backend, ExpressionTemplates>& >::type assign(const number<Other, ET>& v) { // // Attempt a generic interconvertion: // using detail::generic_interconvert; generic_interconvert(backend(), v.backend(), number_category<Backend>(), number_category<Other>()); return *this; } template <class tag, class Arg1, class Arg2, class Arg3, class Arg4> number(const detail::expression<tag, Arg1, Arg2, Arg3, Arg4>& e, typename boost::enable_if_c<is_convertible<typename detail::expression<tag, Arg1, Arg2, Arg3, Arg4>::result_type, self_type>::value>::type* = 0) { *this = e; } template <class tag, class Arg1, class Arg2, class Arg3, class Arg4> explicit number(const detail::expression<tag, Arg1, Arg2, Arg3, Arg4>& e, typename boost::enable_if_c<!is_convertible<typename detail::expression<tag, Arg1, Arg2, Arg3, Arg4>::result_type, self_type>::value && boost::multiprecision::detail::is_explicitly_convertible<typename detail::expression<tag, Arg1, Arg2, Arg3, Arg4>::result_type, self_type>::value>::type* = 0) { assign(e); } #ifndef BOOST_NO_CXX11_RVALUE_REFERENCES BOOST_MP_FORCEINLINE BOOST_CONSTEXPR number(number&& r) BOOST_MP_NOEXCEPT_IF(noexcept(Backend(std::declval<Backend>()))) : m_backend(static_cast<Backend&&>(r.m_backend)){} BOOST_MP_FORCEINLINE number& operator=(number&& r) BOOST_MP_NOEXCEPT_IF(noexcept(std::declval<Backend&>() = std::declval<Backend>())) { m_backend = static_cast<Backend&&>(r.m_backend); return *this; } #endif number& operator+=(const self_type& val) { do_add(detail::expression<detail::terminal, self_type>(val), detail::terminal()); return *this; } template <class tag, class Arg1, class Arg2, class Arg3, class Arg4> typename boost::enable_if<is_convertible<typename detail::expression<tag, Arg1, Arg2, Arg3, Arg4>::result_type, self_type>, number&>::type operator+=(const detail::expression<tag, Arg1, Arg2, Arg3, Arg4>& e) { // Create a copy if e contains this, but not if we're just doing a // x += x if(contains_self(e) && !is_self(e)) { self_type temp(e); do_add(detail::expression<detail::terminal, self_type>(temp), detail::terminal()); } else { do_add(e, tag()); } return *this; } template <class Arg1, class Arg2, class Arg3, class Arg4> number& operator+=(const detail::expression<detail::multiply_immediates, Arg1, Arg2, Arg3, Arg4>& e) { // // Fused multiply-add: // using default_ops::eval_multiply_add; eval_multiply_add(m_backend, canonical_value(e.left_ref()), canonical_value(e.right_ref())); return *this; } template <class V> typename boost::enable_if<boost::is_convertible<V, self_type>, number<Backend, ExpressionTemplates>& >::type operator+=(const V& v) { using default_ops::eval_add; eval_add(m_backend, canonical_value(v)); return *this; } number& operator-=(const self_type& val) { do_subtract(detail::expression<detail::terminal, self_type>(val), detail::terminal()); return *this; } template <class tag, class Arg1, class Arg2, class Arg3, class Arg4> typename boost::enable_if<is_convertible<typename detail::expression<tag, Arg1, Arg2, Arg3, Arg4>::result_type, self_type>, number&>::type operator-=(const detail::expression<tag, Arg1, Arg2, Arg3, Arg4>& e) { // Create a copy if e contains this: if(contains_self(e)) { self_type temp(e); do_subtract(detail::expression<detail::terminal, self_type>(temp), detail::terminal()); } else { do_subtract(e, typename detail::expression<tag, Arg1, Arg2, Arg3, Arg4>::tag_type()); } return *this; } template <class V> typename boost::enable_if<boost::is_convertible<V, self_type>, number<Backend, ExpressionTemplates>& >::type operator-=(const V& v) { using default_ops::eval_subtract; eval_subtract(m_backend, canonical_value(v)); return *this; } template <class Arg1, class Arg2, class Arg3, class Arg4> number& operator-=(const detail::expression<detail::multiply_immediates, Arg1, Arg2, Arg3, Arg4>& e) { // // Fused multiply-subtract: // using default_ops::eval_multiply_subtract; eval_multiply_subtract(m_backend, canonical_value(e.left_ref()), canonical_value(e.right_ref())); return *this; } number& operator *= (const self_type& e) { do_multiplies(detail::expression<detail::terminal, self_type>(e), detail::terminal()); return *this; } template <class tag, class Arg1, class Arg2, class Arg3, class Arg4> typename boost::enable_if<is_convertible<typename detail::expression<tag, Arg1, Arg2, Arg3, Arg4>::result_type, self_type>, number&>::type operator*=(const detail::expression<tag, Arg1, Arg2, Arg3, Arg4>& e) { // Create a temporary if the RHS references *this, but not // if we're just doing an x *= x; if(contains_self(e) && !is_self(e)) { self_type temp(e); do_multiplies(detail::expression<detail::terminal, self_type>(temp), detail::terminal()); } else { do_multiplies(e, typename detail::expression<tag, Arg1, Arg2, Arg3, Arg4>::tag_type()); } return *this; } template <class V> typename boost::enable_if<boost::is_convertible<V, self_type>, number<Backend, ExpressionTemplates>& >::type operator*=(const V& v) { using default_ops::eval_multiply; eval_multiply(m_backend, canonical_value(v)); return *this; } number& operator%=(const self_type& e) { BOOST_STATIC_ASSERT_MSG(number_category<Backend>::value == number_kind_integer, "The modulus operation is only valid for integer types"); do_modulus(detail::expression<detail::terminal, self_type>(e), detail::terminal()); return *this; } template <class tag, class Arg1, class Arg2, class Arg3, class Arg4> typename boost::enable_if<is_convertible<typename detail::expression<tag, Arg1, Arg2, Arg3, Arg4>::result_type, self_type>, number&>::type operator%=(const detail::expression<tag, Arg1, Arg2, Arg3, Arg4>& e) { BOOST_STATIC_ASSERT_MSG(number_category<Backend>::value == number_kind_integer, "The modulus operation is only valid for integer types"); // Create a temporary if the RHS references *this: if(contains_self(e)) { self_type temp(e); do_modulus(detail::expression<detail::terminal, self_type>(temp), detail::terminal()); } else { do_modulus(e, typename detail::expression<tag, Arg1, Arg2, Arg3, Arg4>::tag_type()); } return *this; } template <class V> typename boost::enable_if<boost::is_convertible<V, self_type>, number<Backend, ExpressionTemplates>& >::type operator%=(const V& v) { BOOST_STATIC_ASSERT_MSG(number_category<Backend>::value == number_kind_integer, "The modulus operation is only valid for integer types"); using default_ops::eval_modulus; eval_modulus(m_backend, canonical_value(v)); return *this; } // // These operators are *not* proto-ized. // The issue is that the increment/decrement must happen // even if the result of the operator *is never used*. // Possibly we could modify our expression wrapper to // execute the increment/decrement on destruction, but // correct implementation will be tricky, so defered for now... // BOOST_MP_FORCEINLINE number& operator++() { using default_ops::eval_increment; eval_increment(m_backend); return *this; } BOOST_MP_FORCEINLINE number& operator--() { using default_ops::eval_decrement; eval_decrement(m_backend); return *this; } inline number operator++(int) { using default_ops::eval_increment; self_type temp(*this); eval_increment(m_backend); return BOOST_MP_MOVE(temp); } inline number operator--(int) { using default_ops::eval_decrement; self_type temp(*this); eval_decrement(m_backend); return BOOST_MP_MOVE(temp); } template <class V> BOOST_MP_FORCEINLINE typename boost::enable_if<is_integral<V>, number&>::type operator <<= (V val) { BOOST_STATIC_ASSERT_MSG(number_category<Backend>::value == number_kind_integer, "The left-shift operation is only valid for integer types"); detail::check_shift_range(val, mpl::bool_<(sizeof(V) > sizeof(std::size_t))>(), is_signed<V>()); eval_left_shift(m_backend, static_cast<std::size_t>(canonical_value(val))); return *this; } template <class V> BOOST_MP_FORCEINLINE typename boost::enable_if<is_integral<V>, number&>::type operator >>= (V val) { BOOST_STATIC_ASSERT_MSG(number_category<Backend>::value == number_kind_integer, "The right-shift operation is only valid for integer types"); detail::check_shift_range(val, mpl::bool_<(sizeof(V) > sizeof(std::size_t))>(), is_signed<V>()); eval_right_shift(m_backend, static_cast<std::size_t>(canonical_value(val))); return *this; } BOOST_MP_FORCEINLINE number& operator /= (const self_type& e) { do_divide(detail::expression<detail::terminal, self_type>(e), detail::terminal()); return *this; } template <class tag, class Arg1, class Arg2, class Arg3, class Arg4> typename boost::enable_if<is_convertible<typename detail::expression<tag, Arg1, Arg2, Arg3, Arg4>::result_type, self_type>, number&>::type operator/=(const detail::expression<tag, Arg1, Arg2, Arg3, Arg4>& e) { // Create a temporary if the RHS references *this: if(contains_self(e)) { self_type temp(e); do_divide(detail::expression<detail::terminal, self_type>(temp), detail::terminal()); } else { do_divide(e, typename detail::expression<tag, Arg1, Arg2, Arg3, Arg4>::tag_type()); } return *this; } template <class V> BOOST_MP_FORCEINLINE typename boost::enable_if<boost::is_convertible<V, self_type>, number<Backend, ExpressionTemplates>& >::type operator/=(const V& v) { using default_ops::eval_divide; eval_divide(m_backend, canonical_value(v)); return *this; } BOOST_MP_FORCEINLINE number& operator&=(const self_type& e) { BOOST_STATIC_ASSERT_MSG(number_category<Backend>::value == number_kind_integer, "The bitwise & operation is only valid for integer types"); do_bitwise_and(detail::expression<detail::terminal, self_type>(e), detail::terminal()); return *this; } template <class tag, class Arg1, class Arg2, class Arg3, class Arg4> typename boost::enable_if<is_convertible<typename detail::expression<tag, Arg1, Arg2, Arg3, Arg4>::result_type, self_type>, number&>::type operator&=(const detail::expression<tag, Arg1, Arg2, Arg3, Arg4>& e) { BOOST_STATIC_ASSERT_MSG(number_category<Backend>::value == number_kind_integer, "The bitwise & operation is only valid for integer types"); // Create a temporary if the RHS references *this, but not // if we're just doing an x &= x; if(contains_self(e) && !is_self(e)) { self_type temp(e); do_bitwise_and(detail::expression<detail::terminal, self_type>(temp), detail::terminal()); } else { do_bitwise_and(e, typename detail::expression<tag, Arg1, Arg2, Arg3, Arg4>::tag_type()); } return *this; } template <class V> BOOST_MP_FORCEINLINE typename boost::enable_if<boost::is_convertible<V, self_type>, number<Backend, ExpressionTemplates>& >::type operator&=(const V& v) { BOOST_STATIC_ASSERT_MSG(number_category<Backend>::value == number_kind_integer, "The bitwise & operation is only valid for integer types"); using default_ops::eval_bitwise_and; eval_bitwise_and(m_backend, canonical_value(v)); return *this; } BOOST_MP_FORCEINLINE number& operator|=(const self_type& e) { BOOST_STATIC_ASSERT_MSG(number_category<Backend>::value == number_kind_integer, "The bitwise | operation is only valid for integer types"); do_bitwise_or(detail::expression<detail::terminal, self_type>(e), detail::terminal()); return *this; } template <class tag, class Arg1, class Arg2, class Arg3, class Arg4> typename boost::enable_if<is_convertible<typename detail::expression<tag, Arg1, Arg2, Arg3, Arg4>::result_type, self_type>, number&>::type operator|=(const detail::expression<tag, Arg1, Arg2, Arg3, Arg4>& e) { BOOST_STATIC_ASSERT_MSG(number_category<Backend>::value == number_kind_integer, "The bitwise | operation is only valid for integer types"); // Create a temporary if the RHS references *this, but not // if we're just doing an x |= x; if(contains_self(e) && !is_self(e)) { self_type temp(e); do_bitwise_or(detail::expression<detail::terminal, self_type>(temp), detail::terminal()); } else { do_bitwise_or(e, typename detail::expression<tag, Arg1, Arg2, Arg3, Arg4>::tag_type()); } return *this; } template <class V> BOOST_MP_FORCEINLINE typename boost::enable_if<boost::is_convertible<V, self_type>, number<Backend, ExpressionTemplates>& >::type operator|=(const V& v) { BOOST_STATIC_ASSERT_MSG(number_category<Backend>::value == number_kind_integer, "The bitwise | operation is only valid for integer types"); using default_ops::eval_bitwise_or; eval_bitwise_or(m_backend, canonical_value(v)); return *this; } BOOST_MP_FORCEINLINE number& operator^=(const self_type& e) { BOOST_STATIC_ASSERT_MSG(number_category<Backend>::value == number_kind_integer, "The bitwise ^ operation is only valid for integer types"); do_bitwise_xor(detail::expression<detail::terminal, self_type>(e), detail::terminal()); return *this; } template <class tag, class Arg1, class Arg2, class Arg3, class Arg4> typename boost::enable_if<is_convertible<typename detail::expression<tag, Arg1, Arg2, Arg3, Arg4>::result_type, self_type>, number&>::type operator^=(const detail::expression<tag, Arg1, Arg2, Arg3, Arg4>& e) { BOOST_STATIC_ASSERT_MSG(number_category<Backend>::value == number_kind_integer, "The bitwise ^ operation is only valid for integer types"); if(contains_self(e)) { self_type temp(e); do_bitwise_xor(detail::expression<detail::terminal, self_type>(temp), detail::terminal()); } else { do_bitwise_xor(e, typename detail::expression<tag, Arg1, Arg2, Arg3, Arg4>::tag_type()); } return *this; } template <class V> BOOST_MP_FORCEINLINE typename boost::enable_if<boost::is_convertible<V, self_type>, number<Backend, ExpressionTemplates>& >::type operator^=(const V& v) { BOOST_STATIC_ASSERT_MSG(number_category<Backend>::value == number_kind_integer, "The bitwise ^ operation is only valid for integer types"); using default_ops::eval_bitwise_xor; eval_bitwise_xor(m_backend, canonical_value(v)); return *this; } // // swap: // BOOST_MP_FORCEINLINE void swap(self_type& other) BOOST_MP_NOEXCEPT_IF(noexcept(std::declval<Backend>().swap(std::declval<Backend&>()))) { m_backend.swap(other.backend()); } // // Zero and sign: // BOOST_MP_FORCEINLINE bool is_zero()const { using default_ops::eval_is_zero; return eval_is_zero(m_backend); } BOOST_MP_FORCEINLINE int sign()const { using default_ops::eval_get_sign; return eval_get_sign(m_backend); } // // String conversion functions: // std::string str(std::streamsize digits = 0, std::ios_base::fmtflags f = std::ios_base::fmtflags(0))const { return m_backend.str(digits, f); } template<class Archive> void serialize(Archive & ar, const unsigned int /*version*/) { ar & m_backend; } private: template <class T> void convert_to_imp(T* result)const { using default_ops::eval_convert_to; eval_convert_to(result, m_backend); } template <class B2, expression_template_option ET> void convert_to_imp(number<B2, ET>* result)const { result->assign(*this); } void convert_to_imp(std::string* result)const { *result = this->str(); } public: template <class T> T convert_to()const { T result; convert_to_imp(&result); return result; } // // Use in boolean context, and explicit conversion operators: // #ifndef BOOST_MP_NO_CXX11_EXPLICIT_CONVERSION_OPERATORS # if (defined(__GNUC__) && (__GNUC__ == 4) && (__GNUC_MINOR__ < 7)) || (defined(BOOST_INTEL) && (BOOST_INTEL <= 1500)) // // Horrible workaround for gcc-4.6.x which always prefers the template // operator bool() rather than the non-template operator when converting to // an arithmetic type: // template <class T, typename boost::enable_if<is_same<T, bool>, int>::type = 0> explicit operator T ()const { using default_ops::eval_is_zero; return !eval_is_zero(backend()); } template <class T, typename boost::disable_if_c<is_same<T, bool>::value || is_void<T>::value, int>::type = 0> explicit operator T ()const { return this->template convert_to<T>(); } # else #if BOOST_WORKAROUND(BOOST_MSVC, < 1900) template <class T> #else template <class T, class = typename boost::disable_if_c<boost::is_constructible<T, self_type const&>::value || !boost::is_default_constructible<T>::value, T>::type> #endif explicit operator T ()const { return this->template convert_to<T>(); } BOOST_MP_FORCEINLINE explicit operator bool()const { return !is_zero(); } #if BOOST_WORKAROUND(BOOST_GCC_VERSION, < 40800) BOOST_MP_FORCEINLINE explicit operator void()const {} #endif # endif #else typedef bool (self_type::*unmentionable_type)()const; BOOST_MP_FORCEINLINE operator unmentionable_type()const { return is_zero() ? 0 : &self_type::is_zero; } #endif // // Default precision: // static unsigned default_precision() BOOST_NOEXCEPT { return Backend::default_precision(); } static void default_precision(unsigned digits10) { Backend::default_precision(digits10); } unsigned precision()const BOOST_NOEXCEPT { return m_backend.precision(); } void precision(unsigned digits10) { m_backend.precision(digits10); } // // Comparison: // BOOST_MP_FORCEINLINE int compare(const number<Backend, ExpressionTemplates>& o)const BOOST_MP_NOEXCEPT_IF(noexcept(std::declval<Backend>().compare(std::declval<Backend>()))) { return m_backend.compare(o.m_backend); } template <class V> BOOST_MP_FORCEINLINE typename boost::enable_if<is_arithmetic<V>, int>::type compare(const V& o)const { using default_ops::eval_get_sign; if(o == 0) return eval_get_sign(m_backend); return m_backend.compare(canonical_value(o)); } BOOST_MP_FORCEINLINE Backend& backend() BOOST_NOEXCEPT { return m_backend; } BOOST_MP_FORCEINLINE BOOST_CONSTEXPR const Backend& backend()const BOOST_NOEXCEPT { return m_backend; } private: template <class tag, class Arg1, class Arg2, class Arg3, class Arg4> void do_assign(const detail::expression<tag, Arg1, Arg2, Arg3, Arg4>& e, const mpl::true_&) { do_assign(e, tag()); } template <class tag, class Arg1, class Arg2, class Arg3, class Arg4> void do_assign(const detail::expression<tag, Arg1, Arg2, Arg3, Arg4>& e, const mpl::false_&) { // The result of the expression isn't the same type as this - // create a temporary result and assign it to *this: typedef typename detail::expression<tag, Arg1, Arg2, Arg3, Arg4>::result_type temp_type; temp_type t(e); this->assign(t); } template <class Exp> void do_assign(const Exp& e, const detail::add_immediates&) { using default_ops::eval_add; eval_add(m_backend, canonical_value(e.left().value()), canonical_value(e.right().value())); } template <class Exp> void do_assign(const Exp& e, const detail::subtract_immediates&) { using default_ops::eval_subtract; eval_subtract(m_backend, canonical_value(e.left().value()), canonical_value(e.right().value())); } template <class Exp> void do_assign(const Exp& e, const detail::multiply_immediates&) { using default_ops::eval_multiply; eval_multiply(m_backend, canonical_value(e.left().value()), canonical_value(e.right().value())); } template <class Exp> void do_assign(const Exp& e, const detail::multiply_add&) { using default_ops::eval_multiply_add; eval_multiply_add(m_backend, canonical_value(e.left().value()), canonical_value(e.middle().value()), canonical_value(e.right().value())); } template <class Exp> void do_assign(const Exp& e, const detail::multiply_subtract&) { using default_ops::eval_multiply_subtract; eval_multiply_subtract(m_backend, canonical_value(e.left().value()), canonical_value(e.middle().value()), canonical_value(e.right().value())); } template <class Exp> void do_assign(const Exp& e, const detail::divide_immediates&) { using default_ops::eval_divide; eval_divide(m_backend, canonical_value(e.left().value()), canonical_value(e.right().value())); } template <class Exp> void do_assign(const Exp& e, const detail::negate&) { typedef typename Exp::left_type left_type; do_assign(e.left(), typename left_type::tag_type()); m_backend.negate(); } template <class Exp> void do_assign(const Exp& e, const detail::plus&) { typedef typename Exp::left_type left_type; typedef typename Exp::right_type right_type; static int const left_depth = left_type::depth; static int const right_depth = right_type::depth; bool bl = contains_self(e.left()); bool br = contains_self(e.right()); if(bl && br) { self_type temp(e); temp.m_backend.swap(this->m_backend); } else if(bl && is_self(e.left())) { // Ignore the left node, it's *this, just add the right: do_add(e.right(), typename right_type::tag_type()); } else if(br && is_self(e.right())) { // Ignore the right node, it's *this, just add the left: do_add(e.left(), typename left_type::tag_type()); } else if(!br && (bl || (left_depth >= right_depth))) { // br is always false, but if bl is true we must take the this branch: do_assign(e.left(), typename left_type::tag_type()); do_add(e.right(), typename right_type::tag_type()); } else { do_assign(e.right(), typename right_type::tag_type()); do_add(e.left(), typename left_type::tag_type()); } } template <class Exp> void do_assign(const Exp& e, const detail::minus&) { typedef typename Exp::left_type left_type; typedef typename Exp::right_type right_type; static int const left_depth = left_type::depth; static int const right_depth = right_type::depth; bool bl = contains_self(e.left()); bool br = contains_self(e.right()); if(bl && br) { self_type temp(e); temp.m_backend.swap(this->m_backend); } else if(bl && is_self(e.left())) { // Ignore the left node, it's *this, just subtract the right: do_subtract(e.right(), typename right_type::tag_type()); } else if(br && is_self(e.right())) { // Ignore the right node, it's *this, just subtract the left and negate the result: do_subtract(e.left(), typename left_type::tag_type()); m_backend.negate(); } else if(!br && (bl || (left_depth >= right_depth))) { // br is always false, but if bl is true we must take the this branch: do_assign(e.left(), typename left_type::tag_type()); do_subtract(e.right(), typename right_type::tag_type()); } else { do_assign(e.right(), typename right_type::tag_type()); do_subtract(e.left(), typename left_type::tag_type()); m_backend.negate(); } } template <class Exp> void do_assign(const Exp& e, const detail::multiplies&) { typedef typename Exp::left_type left_type; typedef typename Exp::right_type right_type; static int const left_depth = left_type::depth; static int const right_depth = right_type::depth; bool bl = contains_self(e.left()); bool br = contains_self(e.right()); if(bl && br) { self_type temp(e); temp.m_backend.swap(this->m_backend); } else if(bl && is_self(e.left())) { // Ignore the left node, it's *this, just add the right: do_multiplies(e.right(), typename right_type::tag_type()); } else if(br && is_self(e.right())) { // Ignore the right node, it's *this, just add the left: do_multiplies(e.left(), typename left_type::tag_type()); } else if(!br && (bl || (left_depth >= right_depth))) { // br is always false, but if bl is true we must take the this branch: do_assign(e.left(), typename left_type::tag_type()); do_multiplies(e.right(), typename right_type::tag_type()); } else { do_assign(e.right(), typename right_type::tag_type()); do_multiplies(e.left(), typename left_type::tag_type()); } } template <class Exp> void do_assign(const Exp& e, const detail::divides&) { typedef typename Exp::left_type left_type; typedef typename Exp::right_type right_type; bool bl = contains_self(e.left()); bool br = contains_self(e.right()); if(bl && is_self(e.left())) { // Ignore the left node, it's *this, just add the right: do_divide(e.right(), typename right_type::tag_type()); } else if(br) { self_type temp(e); temp.m_backend.swap(this->m_backend); } else { do_assign(e.left(), typename left_type::tag_type()); do_divide(e.right(), typename right_type::tag_type()); } } template <class Exp> void do_assign(const Exp& e, const detail::modulus&) { // // This operation is only valid for integer backends: // BOOST_STATIC_ASSERT_MSG(number_category<Backend>::value == number_kind_integer, "The modulus operation is only valid for integer types"); typedef typename Exp::left_type left_type; typedef typename Exp::right_type right_type; bool bl = contains_self(e.left()); bool br = contains_self(e.right()); if(bl && is_self(e.left())) { // Ignore the left node, it's *this, just add the right: do_modulus(e.right(), typename right_type::tag_type()); } else if(br) { self_type temp(e); temp.m_backend.swap(this->m_backend); } else { do_assign(e.left(), typename left_type::tag_type()); do_modulus(e.right(), typename right_type::tag_type()); } } template <class Exp> void do_assign(const Exp& e, const detail::modulus_immediates&) { BOOST_STATIC_ASSERT_MSG(number_category<Backend>::value == number_kind_integer, "The modulus operation is only valid for integer types"); using default_ops::eval_modulus; eval_modulus(m_backend, canonical_value(e.left().value()), canonical_value(e.right().value())); } template <class Exp> void do_assign(const Exp& e, const detail::bitwise_and&) { // // This operation is only valid for integer backends: // BOOST_STATIC_ASSERT_MSG(number_category<Backend>::value == number_kind_integer, "Bitwise operations are only valid for integer types"); typedef typename Exp::left_type left_type; typedef typename Exp::right_type right_type; static int const left_depth = left_type::depth; static int const right_depth = right_type::depth; bool bl = contains_self(e.left()); bool br = contains_self(e.right()); if(bl && is_self(e.left())) { // Ignore the left node, it's *this, just add the right: do_bitwise_and(e.right(), typename right_type::tag_type()); } else if(br && is_self(e.right())) { do_bitwise_and(e.left(), typename left_type::tag_type()); } else if(!br && (bl || (left_depth >= right_depth))) { do_assign(e.left(), typename left_type::tag_type()); do_bitwise_and(e.right(), typename right_type::tag_type()); } else { do_assign(e.right(), typename right_type::tag_type()); do_bitwise_and(e.left(), typename left_type::tag_type()); } } template <class Exp> void do_assign(const Exp& e, const detail::bitwise_and_immediates&) { BOOST_STATIC_ASSERT_MSG(number_category<Backend>::value == number_kind_integer, "Bitwise operations are only valid for integer types"); using default_ops::eval_bitwise_and; eval_bitwise_and(m_backend, canonical_value(e.left().value()), canonical_value(e.right().value())); } template <class Exp> void do_assign(const Exp& e, const detail::bitwise_or&) { // // This operation is only valid for integer backends: // BOOST_STATIC_ASSERT_MSG(number_category<Backend>::value == number_kind_integer, "Bitwise operations are only valid for integer types"); typedef typename Exp::left_type left_type; typedef typename Exp::right_type right_type; static int const left_depth = left_type::depth; static int const right_depth = right_type::depth; bool bl = contains_self(e.left()); bool br = contains_self(e.right()); if(bl && is_self(e.left())) { // Ignore the left node, it's *this, just add the right: do_bitwise_or(e.right(), typename right_type::tag_type()); } else if(br && is_self(e.right())) { do_bitwise_or(e.left(), typename left_type::tag_type()); } else if(!br && (bl || (left_depth >= right_depth))) { do_assign(e.left(), typename left_type::tag_type()); do_bitwise_or(e.right(), typename right_type::tag_type()); } else { do_assign(e.right(), typename right_type::tag_type()); do_bitwise_or(e.left(), typename left_type::tag_type()); } } template <class Exp> void do_assign(const Exp& e, const detail::bitwise_or_immediates&) { BOOST_STATIC_ASSERT_MSG(number_category<Backend>::value == number_kind_integer, "Bitwise operations are only valid for integer types"); using default_ops::eval_bitwise_or; eval_bitwise_or(m_backend, canonical_value(e.left().value()), canonical_value(e.right().value())); } template <class Exp> void do_assign(const Exp& e, const detail::bitwise_xor&) { // // This operation is only valid for integer backends: // BOOST_STATIC_ASSERT_MSG(number_category<Backend>::value == number_kind_integer, "Bitwise operations are only valid for integer types"); typedef typename Exp::left_type left_type; typedef typename Exp::right_type right_type; static int const left_depth = left_type::depth; static int const right_depth = right_type::depth; bool bl = contains_self(e.left()); bool br = contains_self(e.right()); if(bl && is_self(e.left())) { // Ignore the left node, it's *this, just add the right: do_bitwise_xor(e.right(), typename right_type::tag_type()); } else if(br && is_self(e.right())) { do_bitwise_xor(e.left(), typename left_type::tag_type()); } else if(!br && (bl || (left_depth >= right_depth))) { do_assign(e.left(), typename left_type::tag_type()); do_bitwise_xor(e.right(), typename right_type::tag_type()); } else { do_assign(e.right(), typename right_type::tag_type()); do_bitwise_xor(e.left(), typename left_type::tag_type()); } } template <class Exp> void do_assign(const Exp& e, const detail::bitwise_xor_immediates&) { BOOST_STATIC_ASSERT_MSG(number_category<Backend>::value == number_kind_integer, "Bitwise operations are only valid for integer types"); using default_ops::eval_bitwise_xor; eval_bitwise_xor(m_backend, canonical_value(e.left().value()), canonical_value(e.right().value())); } template <class Exp> void do_assign(const Exp& e, const detail::terminal&) { if(!is_self(e)) { m_backend = canonical_value(e.value()); } } template <class Exp> void do_assign(const Exp& e, const detail::function&) { typedef typename Exp::arity tag_type; do_assign_function(e, tag_type()); } template <class Exp> void do_assign(const Exp& e, const detail::shift_left&) { // We can only shift by an integer value, not an arbitrary expression: typedef typename Exp::left_type left_type; typedef typename Exp::right_type right_type; typedef typename right_type::arity right_arity; BOOST_STATIC_ASSERT_MSG(right_arity::value == 0, "The left shift operator requires an integer value for the shift operand."); typedef typename right_type::result_type right_value_type; BOOST_STATIC_ASSERT_MSG(is_integral<right_value_type>::value, "The left shift operator requires an integer value for the shift operand."); typedef typename left_type::tag_type tag_type; do_assign_left_shift(e.left(), canonical_value(e.right().value()), tag_type()); } template <class Exp> void do_assign(const Exp& e, const detail::shift_right&) { // We can only shift by an integer value, not an arbitrary expression: typedef typename Exp::left_type left_type; typedef typename Exp::right_type right_type; typedef typename right_type::arity right_arity; BOOST_STATIC_ASSERT_MSG(right_arity::value == 0, "The left shift operator requires an integer value for the shift operand."); typedef typename right_type::result_type right_value_type; BOOST_STATIC_ASSERT_MSG(is_integral<right_value_type>::value, "The left shift operator requires an integer value for the shift operand."); typedef typename left_type::tag_type tag_type; do_assign_right_shift(e.left(), canonical_value(e.right().value()), tag_type()); } template <class Exp> void do_assign(const Exp& e, const detail::bitwise_complement&) { BOOST_STATIC_ASSERT_MSG(number_category<Backend>::value == number_kind_integer, "The bitwise ~ operation is only valid for integer types"); using default_ops::eval_complement; self_type temp(e.left()); eval_complement(m_backend, temp.backend()); } template <class Exp> void do_assign(const Exp& e, const detail::complement_immediates&) { BOOST_STATIC_ASSERT_MSG(number_category<Backend>::value == number_kind_integer, "The bitwise ~ operation is only valid for integer types"); using default_ops::eval_complement; eval_complement(m_backend, canonical_value(e.left().value())); } template <class Exp, class Val> void do_assign_right_shift(const Exp& e, const Val& val, const detail::terminal&) { BOOST_STATIC_ASSERT_MSG(number_category<Backend>::value == number_kind_integer, "The right shift operation is only valid for integer types"); using default_ops::eval_right_shift; detail::check_shift_range(val, mpl::bool_<(sizeof(Val) > sizeof(std::size_t))>(), is_signed<Val>()); eval_right_shift(m_backend, canonical_value(e.value()), static_cast<std::size_t>(val)); } template <class Exp, class Val> void do_assign_left_shift(const Exp& e, const Val& val, const detail::terminal&) { BOOST_STATIC_ASSERT_MSG(number_category<Backend>::value == number_kind_integer, "The left shift operation is only valid for integer types"); using default_ops::eval_left_shift; detail::check_shift_range(val, mpl::bool_<(sizeof(Val) > sizeof(std::size_t))>(), is_signed<Val>()); eval_left_shift(m_backend, canonical_value(e.value()), static_cast<std::size_t>(val)); } template <class Exp, class Val, class Tag> void do_assign_right_shift(const Exp& e, const Val& val, const Tag&) { BOOST_STATIC_ASSERT_MSG(number_category<Backend>::value == number_kind_integer, "The right shift operation is only valid for integer types"); using default_ops::eval_right_shift; self_type temp(e); detail::check_shift_range(val, mpl::bool_<(sizeof(Val) > sizeof(std::size_t))>(), is_signed<Val>()); eval_right_shift(m_backend, temp.backend(), static_cast<std::size_t>(val)); } template <class Exp, class Val, class Tag> void do_assign_left_shift(const Exp& e, const Val& val, const Tag&) { BOOST_STATIC_ASSERT_MSG(number_category<Backend>::value == number_kind_integer, "The left shift operation is only valid for integer types"); using default_ops::eval_left_shift; self_type temp(e); detail::check_shift_range(val, mpl::bool_<(sizeof(Val) > sizeof(std::size_t))>(), is_signed<Val>()); eval_left_shift(m_backend, temp.backend(), static_cast<std::size_t>(val)); } template <class Exp> void do_assign_function(const Exp& e, const mpl::int_<1>&) { e.left().value()(&m_backend); } template <class Exp> void do_assign_function(const Exp& e, const mpl::int_<2>&) { typedef typename Exp::right_type right_type; typedef typename right_type::tag_type tag_type; do_assign_function_1(e.left().value(), e.right_ref(), tag_type()); } template <class F, class Exp> void do_assign_function_1(const F& f, const Exp& val, const detail::terminal&) { f(m_backend, function_arg_value(val)); } template <class F, class Exp, class Tag> void do_assign_function_1(const F& f, const Exp& val, const Tag&) { number t(val); f(m_backend, t.backend()); } template <class Exp> void do_assign_function(const Exp& e, const mpl::int_<3>&) { typedef typename Exp::middle_type middle_type; typedef typename middle_type::tag_type tag_type; typedef typename Exp::right_type end_type; typedef typename end_type::tag_type end_tag; do_assign_function_2(e.left().value(), e.middle_ref(), e.right_ref(), tag_type(), end_tag()); } template <class F, class Exp1, class Exp2> void do_assign_function_2(const F& f, const Exp1& val1, const Exp2& val2, const detail::terminal&, const detail::terminal&) { f(m_backend, function_arg_value(val1), function_arg_value(val2)); } template <class F, class Exp1, class Exp2, class Tag1> void do_assign_function_2(const F& f, const Exp1& val1, const Exp2& val2, const Tag1&, const detail::terminal&) { self_type temp1(val1); f(m_backend, BOOST_MP_MOVE(temp1.backend()), function_arg_value(val2)); } template <class F, class Exp1, class Exp2, class Tag2> void do_assign_function_2(const F& f, const Exp1& val1, const Exp2& val2, const detail::terminal&, const Tag2&) { self_type temp2(val2); f(m_backend, function_arg_value(val1), BOOST_MP_MOVE(temp2.backend())); } template <class F, class Exp1, class Exp2, class Tag1, class Tag2> void do_assign_function_2(const F& f, const Exp1& val1, const Exp2& val2, const Tag1&, const Tag2&) { self_type temp1(val1); self_type temp2(val2); f(m_backend, BOOST_MP_MOVE(temp1.backend()), BOOST_MP_MOVE(temp2.backend())); } template <class Exp> void do_assign_function(const Exp& e, const mpl::int_<4>&) { typedef typename Exp::left_middle_type left_type; typedef typename left_type::tag_type left_tag_type; typedef typename Exp::right_middle_type middle_type; typedef typename middle_type::tag_type middle_tag_type; typedef typename Exp::right_type right_type; typedef typename right_type::tag_type right_tag_type; do_assign_function_3a(e.left().value(), e.left_middle_ref(), e.right_middle_ref(), e.right_ref(), left_tag_type(), middle_tag_type(), right_tag_type()); } template <class F, class Exp1, class Exp2, class Exp3, class Tag2, class Tag3> void do_assign_function_3a(const F& f, const Exp1& val1, const Exp2& val2, const Exp3& val3, const detail::terminal&, const Tag2& t2, const Tag3& t3) { do_assign_function_3b(f, val1, val2, val3, t2, t3); } template <class F, class Exp1, class Exp2, class Exp3, class Tag1, class Tag2, class Tag3> void do_assign_function_3a(const F& f, const Exp1& val1, const Exp2& val2, const Exp3& val3, const Tag1&, const Tag2& t2, const Tag3& t3) { number t(val1); do_assign_function_3b(f, BOOST_MP_MOVE(t), val2, val3, t2, t3); } template <class F, class Exp1, class Exp2, class Exp3, class Tag3> void do_assign_function_3b(const F& f, const Exp1& val1, const Exp2& val2, const Exp3& val3, const detail::terminal&, const Tag3& t3) { do_assign_function_3c(f, val1, val2, val3, t3); } template <class F, class Exp1, class Exp2, class Exp3, class Tag2, class Tag3> void do_assign_function_3b(const F& f, const Exp1& val1, const Exp2& val2, const Exp3& val3, const Tag2& /*t2*/, const Tag3& t3) { number t(val2); do_assign_function_3c(f, val1, BOOST_MP_MOVE(t), val3, t3); } template <class F, class Exp1, class Exp2, class Exp3> void do_assign_function_3c(const F& f, const Exp1& val1, const Exp2& val2, const Exp3& val3, const detail::terminal&) { f(m_backend, function_arg_value(val1), function_arg_value(val2), function_arg_value(val3)); } template <class F, class Exp1, class Exp2, class Exp3, class Tag3> void do_assign_function_3c(const F& f, const Exp1& val1, const Exp2& val2, const Exp3& val3, const Tag3& /*t3*/) { number t(val3); do_assign_function_3c(f, val1, val2, BOOST_MP_MOVE(t), detail::terminal()); } template <class Exp> void do_add(const Exp& e, const detail::terminal&) { using default_ops::eval_add; eval_add(m_backend, canonical_value(e.value())); } template <class Exp> void do_add(const Exp& e, const detail::negate&) { typedef typename Exp::left_type left_type; do_subtract(e.left(), typename left_type::tag_type()); } template <class Exp> void do_add(const Exp& e, const detail::plus&) { typedef typename Exp::left_type left_type; typedef typename Exp::right_type right_type; do_add(e.left(), typename left_type::tag_type()); do_add(e.right(), typename right_type::tag_type()); } template <class Exp> void do_add(const Exp& e, const detail::minus&) { typedef typename Exp::left_type left_type; typedef typename Exp::right_type right_type; do_add(e.left(), typename left_type::tag_type()); do_subtract(e.right(), typename right_type::tag_type()); } template <class Exp, class unknown> void do_add(const Exp& e, const unknown&) { self_type temp(e); do_add(detail::expression<detail::terminal, self_type>(temp), detail::terminal()); } template <class Exp> void do_add(const Exp& e, const detail::add_immediates&) { using default_ops::eval_add; eval_add(m_backend, canonical_value(e.left().value())); eval_add(m_backend, canonical_value(e.right().value())); } template <class Exp> void do_add(const Exp& e, const detail::subtract_immediates&) { using default_ops::eval_add; using default_ops::eval_subtract; eval_add(m_backend, canonical_value(e.left().value())); eval_subtract(m_backend, canonical_value(e.right().value())); } template <class Exp> void do_subtract(const Exp& e, const detail::terminal&) { using default_ops::eval_subtract; eval_subtract(m_backend, canonical_value(e.value())); } template <class Exp> void do_subtract(const Exp& e, const detail::negate&) { typedef typename Exp::left_type left_type; do_add(e.left(), typename left_type::tag_type()); } template <class Exp> void do_subtract(const Exp& e, const detail::plus&) { typedef typename Exp::left_type left_type; typedef typename Exp::right_type right_type; do_subtract(e.left(), typename left_type::tag_type()); do_subtract(e.right(), typename right_type::tag_type()); } template <class Exp> void do_subtract(const Exp& e, const detail::minus&) { typedef typename Exp::left_type left_type; typedef typename Exp::right_type right_type; do_subtract(e.left(), typename left_type::tag_type()); do_add(e.right(), typename right_type::tag_type()); } template <class Exp> void do_subtract(const Exp& e, const detail::add_immediates&) { using default_ops::eval_subtract; eval_subtract(m_backend, canonical_value(e.left().value())); eval_subtract(m_backend, canonical_value(e.right().value())); } template <class Exp> void do_subtract(const Exp& e, const detail::subtract_immediates&) { using default_ops::eval_add; using default_ops::eval_subtract; eval_subtract(m_backend, canonical_value(e.left().value())); eval_add(m_backend, canonical_value(e.right().value())); } template <class Exp, class unknown> void do_subtract(const Exp& e, const unknown&) { self_type temp(e); do_subtract(detail::expression<detail::terminal, self_type>(temp), detail::terminal()); } template <class Exp> void do_multiplies(const Exp& e, const detail::terminal&) { using default_ops::eval_multiply; eval_multiply(m_backend, canonical_value(e.value())); } template <class Exp> void do_multiplies(const Exp& e, const detail::negate&) { typedef typename Exp::left_type left_type; do_multiplies(e.left(), typename left_type::tag_type()); m_backend.negate(); } template <class Exp> void do_multiplies(const Exp& e, const detail::multiplies&) { typedef typename Exp::left_type left_type; typedef typename Exp::right_type right_type; do_multiplies(e.left(), typename left_type::tag_type()); do_multiplies(e.right(), typename right_type::tag_type()); } // // This rearrangement is disabled for integer types, the test on sizeof(Exp) is simply to make // the disable_if dependent on the template argument (the size of 1 can never occur in practice). // template <class Exp> typename boost::disable_if_c<boost::multiprecision::number_category<self_type>::value == boost::multiprecision::number_kind_integer || sizeof(Exp) == 1>::type do_multiplies(const Exp& e, const detail::divides&) { typedef typename Exp::left_type left_type; typedef typename Exp::right_type right_type; do_multiplies(e.left(), typename left_type::tag_type()); do_divide(e.right(), typename right_type::tag_type()); } template <class Exp> void do_multiplies(const Exp& e, const detail::multiply_immediates&) { using default_ops::eval_multiply; eval_multiply(m_backend, canonical_value(e.left().value())); eval_multiply(m_backend, canonical_value(e.right().value())); } // // This rearrangement is disabled for integer types, the test on sizeof(Exp) is simply to make // the disable_if dependent on the template argument (the size of 1 can never occur in practice). // template <class Exp> typename boost::disable_if_c<boost::multiprecision::number_category<self_type>::value == boost::multiprecision::number_kind_integer || sizeof(Exp) == 1>::type do_multiplies(const Exp& e, const detail::divide_immediates&) { using default_ops::eval_multiply; using default_ops::eval_divide; eval_multiply(m_backend, canonical_value(e.left().value())); eval_divide(m_backend, canonical_value(e.right().value())); } template <class Exp, class unknown> void do_multiplies(const Exp& e, const unknown&) { using default_ops::eval_multiply; self_type temp(e); eval_multiply(m_backend, temp.m_backend); } template <class Exp> void do_divide(const Exp& e, const detail::terminal&) { using default_ops::eval_divide; eval_divide(m_backend, canonical_value(e.value())); } template <class Exp> void do_divide(const Exp& e, const detail::negate&) { typedef typename Exp::left_type left_type; do_divide(e.left(), typename left_type::tag_type()); m_backend.negate(); } // // This rearrangement is disabled for integer types, the test on sizeof(Exp) is simply to make // the disable_if dependent on the template argument (the size of 1 can never occur in practice). // template <class Exp> typename boost::disable_if_c<boost::multiprecision::number_category<self_type>::value == boost::multiprecision::number_kind_integer || sizeof(Exp) == 1>::type do_divide(const Exp& e, const detail::multiplies&) { typedef typename Exp::left_type left_type; typedef typename Exp::right_type right_type; do_divide(e.left(), typename left_type::tag_type()); do_divide(e.right(), typename right_type::tag_type()); } // // This rearrangement is disabled for integer types, the test on sizeof(Exp) is simply to make // the disable_if dependent on the template argument (the size of 1 can never occur in practice). // template <class Exp> typename boost::disable_if_c<boost::multiprecision::number_category<self_type>::value == boost::multiprecision::number_kind_integer || sizeof(Exp) == 1>::type do_divide(const Exp& e, const detail::divides&) { typedef typename Exp::left_type left_type; typedef typename Exp::right_type right_type; do_divide(e.left(), typename left_type::tag_type()); do_multiplies(e.right(), typename right_type::tag_type()); } // // This rearrangement is disabled for integer types, the test on sizeof(Exp) is simply to make // the disable_if dependent on the template argument (the size of 1 can never occur in practice). // template <class Exp> typename boost::disable_if_c<boost::multiprecision::number_category<self_type>::value == boost::multiprecision::number_kind_integer || sizeof(Exp) == 1>::type do_divides(const Exp& e, const detail::multiply_immediates&) { using default_ops::eval_divide; eval_divide(m_backend, canonical_value(e.left().value())); eval_divide(m_backend, canonical_value(e.right().value())); } // // This rearrangement is disabled for integer types, the test on sizeof(Exp) is simply to make // the disable_if dependent on the template argument (the size of 1 can never occur in practice). // template <class Exp> typename boost::disable_if_c<boost::multiprecision::number_category<self_type>::value == boost::multiprecision::number_kind_integer || sizeof(Exp) == 1>::type do_divides(const Exp& e, const detail::divide_immediates&) { using default_ops::eval_multiply; using default_ops::eval_divide; eval_divide(m_backend, canonical_value(e.left().value())); mutiply(m_backend, canonical_value(e.right().value())); } template <class Exp, class unknown> void do_divide(const Exp& e, const unknown&) { using default_ops::eval_multiply; self_type temp(e); eval_divide(m_backend, temp.m_backend); } template <class Exp> void do_modulus(const Exp& e, const detail::terminal&) { BOOST_STATIC_ASSERT_MSG(number_category<Backend>::value == number_kind_integer, "The modulus operation is only valid for integer types"); using default_ops::eval_modulus; eval_modulus(m_backend, canonical_value(e.value())); } template <class Exp, class Unknown> void do_modulus(const Exp& e, const Unknown&) { BOOST_STATIC_ASSERT_MSG(number_category<Backend>::value == number_kind_integer, "The modulus operation is only valid for integer types"); using default_ops::eval_modulus; self_type temp(e); eval_modulus(m_backend, canonical_value(temp)); } template <class Exp> void do_bitwise_and(const Exp& e, const detail::terminal&) { BOOST_STATIC_ASSERT_MSG(number_category<Backend>::value == number_kind_integer, "The bitwise & operation is only valid for integer types"); using default_ops::eval_bitwise_and; eval_bitwise_and(m_backend, canonical_value(e.value())); } template <class Exp> void do_bitwise_and(const Exp& e, const detail::bitwise_and&) { BOOST_STATIC_ASSERT_MSG(number_category<Backend>::value == number_kind_integer, "The bitwise & operation is only valid for integer types"); typedef typename Exp::left_type left_type; typedef typename Exp::right_type right_type; do_bitwise_and(e.left(), typename left_type::tag_type()); do_bitwise_and(e.right(), typename right_type::tag_type()); } template <class Exp, class unknown> void do_bitwise_and(const Exp& e, const unknown&) { BOOST_STATIC_ASSERT_MSG(number_category<Backend>::value == number_kind_integer, "The bitwise & operation is only valid for integer types"); using default_ops::eval_bitwise_and; self_type temp(e); eval_bitwise_and(m_backend, temp.m_backend); } template <class Exp> void do_bitwise_or(const Exp& e, const detail::terminal&) { BOOST_STATIC_ASSERT_MSG(number_category<Backend>::value == number_kind_integer, "The bitwise | operation is only valid for integer types"); using default_ops::eval_bitwise_or; eval_bitwise_or(m_backend, canonical_value(e.value())); } template <class Exp> void do_bitwise_or(const Exp& e, const detail::bitwise_or&) { BOOST_STATIC_ASSERT_MSG(number_category<Backend>::value == number_kind_integer, "The bitwise | operation is only valid for integer types"); typedef typename Exp::left_type left_type; typedef typename Exp::right_type right_type; do_bitwise_or(e.left(), typename left_type::tag_type()); do_bitwise_or(e.right(), typename right_type::tag_type()); } template <class Exp, class unknown> void do_bitwise_or(const Exp& e, const unknown&) { BOOST_STATIC_ASSERT_MSG(number_category<Backend>::value == number_kind_integer, "The bitwise | operation is only valid for integer types"); using default_ops::eval_bitwise_or; self_type temp(e); eval_bitwise_or(m_backend, temp.m_backend); } template <class Exp> void do_bitwise_xor(const Exp& e, const detail::terminal&) { BOOST_STATIC_ASSERT_MSG(number_category<Backend>::value == number_kind_integer, "The bitwise ^ operation is only valid for integer types"); using default_ops::eval_bitwise_xor; eval_bitwise_xor(m_backend, canonical_value(e.value())); } template <class Exp> void do_bitwise_xor(const Exp& e, const detail::bitwise_xor&) { BOOST_STATIC_ASSERT_MSG(number_category<Backend>::value == number_kind_integer, "The bitwise ^ operation is only valid for integer types"); typedef typename Exp::left_type left_type; typedef typename Exp::right_type right_type; do_bitwise_xor(e.left(), typename left_type::tag_type()); do_bitwise_xor(e.right(), typename right_type::tag_type()); } template <class Exp, class unknown> void do_bitwise_xor(const Exp& e, const unknown&) { BOOST_STATIC_ASSERT_MSG(number_category<Backend>::value == number_kind_integer, "The bitwise ^ operation is only valid for integer types"); using default_ops::eval_bitwise_xor; self_type temp(e); eval_bitwise_xor(m_backend, temp.m_backend); } // Tests if the expression contains a reference to *this: template <class Exp> BOOST_MP_FORCEINLINE bool contains_self(const Exp& e)const BOOST_NOEXCEPT { return contains_self(e, typename Exp::arity()); } template <class Exp> BOOST_MP_FORCEINLINE bool contains_self(const Exp& e, mpl::int_<0> const&)const BOOST_NOEXCEPT { return is_realy_self(e.value()); } template <class Exp> BOOST_MP_FORCEINLINE bool contains_self(const Exp& e, mpl::int_<1> const&)const BOOST_NOEXCEPT { typedef typename Exp::left_type child_type; return contains_self(e.left(), typename child_type::arity()); } template <class Exp> BOOST_MP_FORCEINLINE bool contains_self(const Exp& e, mpl::int_<2> const&)const BOOST_NOEXCEPT { typedef typename Exp::left_type child0_type; typedef typename Exp::right_type child1_type; return contains_self(e.left(), typename child0_type::arity()) || contains_self(e.right(), typename child1_type::arity()); } template <class Exp> BOOST_MP_FORCEINLINE bool contains_self(const Exp& e, mpl::int_<3> const&)const BOOST_NOEXCEPT { typedef typename Exp::left_type child0_type; typedef typename Exp::middle_type child1_type; typedef typename Exp::right_type child2_type; return contains_self(e.left(), typename child0_type::arity()) || contains_self(e.middle(), typename child1_type::arity()) || contains_self(e.right(), typename child2_type::arity()); } // Test if the expression is a reference to *this: template <class Exp> BOOST_MP_FORCEINLINE BOOST_CONSTEXPR bool is_self(const Exp& e)const BOOST_NOEXCEPT { return is_self(e, typename Exp::arity()); } template <class Exp> BOOST_MP_FORCEINLINE BOOST_CONSTEXPR bool is_self(const Exp& e, mpl::int_<0> const&)const BOOST_NOEXCEPT { return is_realy_self(e.value()); } template <class Exp, int v> BOOST_MP_FORCEINLINE BOOST_CONSTEXPR bool is_self(const Exp&, mpl::int_<v> const&)const BOOST_NOEXCEPT { return false; } template <class Val> BOOST_MP_FORCEINLINE BOOST_CONSTEXPR bool is_realy_self(const Val&)const BOOST_NOEXCEPT{ return false; } BOOST_MP_FORCEINLINE BOOST_CONSTEXPR bool is_realy_self(const self_type& v)const BOOST_NOEXCEPT{ return &v == this; } static BOOST_MP_FORCEINLINE BOOST_CONSTEXPR const Backend& function_arg_value(const self_type& v) BOOST_NOEXCEPT { return v.backend(); } template <class V> static BOOST_MP_FORCEINLINE BOOST_CONSTEXPR const V& function_arg_value(const V& v) BOOST_NOEXCEPT { return v; } template <class A1, class A2, class A3, class A4> static BOOST_MP_FORCEINLINE const A1& function_arg_value(const detail::expression<detail::terminal, A1, A2, A3, A4>& exp) BOOST_NOEXCEPT { return exp.value(); } template <class A2, class A3, class A4> static BOOST_MP_FORCEINLINE BOOST_CONSTEXPR const Backend& function_arg_value(const detail::expression<detail::terminal, number<Backend>, A2, A3, A4>& exp) BOOST_NOEXCEPT { return exp.value().backend(); } Backend m_backend; public: // // These shouldn't really need to be public, or even member functions, but it makes implementing // the non-member operators way easier if they are: // static BOOST_MP_FORCEINLINE BOOST_CONSTEXPR const Backend& canonical_value(const self_type& v) BOOST_NOEXCEPT { return v.m_backend; } template <class B2, expression_template_option ET> static BOOST_MP_FORCEINLINE BOOST_CONSTEXPR const B2& canonical_value(const number<B2, ET>& v) BOOST_NOEXCEPT { return v.backend(); } template <class V> static BOOST_MP_FORCEINLINE BOOST_CONSTEXPR typename boost::disable_if<is_same<typename detail::canonical<V, Backend>::type, V>, typename detail::canonical<V, Backend>::type>::type canonical_value(const V& v) BOOST_NOEXCEPT { return static_cast<typename detail::canonical<V, Backend>::type>(v); } template <class V> static BOOST_MP_FORCEINLINE BOOST_CONSTEXPR typename boost::enable_if<is_same<typename detail::canonical<V, Backend>::type, V>, const V&>::type canonical_value(const V& v) BOOST_NOEXCEPT { return v; } static BOOST_MP_FORCEINLINE typename detail::canonical<std::string, Backend>::type canonical_value(const std::string& v) BOOST_NOEXCEPT { return v.c_str(); } }; template <class Backend, expression_template_option ExpressionTemplates> inline std::ostream& operator << (std::ostream& os, const number<Backend, ExpressionTemplates>& r) { std::streamsize d = os.precision(); std::string s = r.str(d, os.flags()); std::streamsize ss = os.width(); if(ss > static_cast<std::streamsize>(s.size())) { char fill = os.fill(); if((os.flags() & std::ios_base::left) == std::ios_base::left) s.append(static_cast<std::string::size_type>(ss - s.size()), fill); else s.insert(static_cast<std::string::size_type>(0), static_cast<std::string::size_type>(ss - s.size()), fill); } return os << s; } namespace detail{ template <class tag, class A1, class A2, class A3, class A4> inline std::ostream& operator << (std::ostream& os, const expression<tag, A1, A2, A3, A4>& r) { typedef typename expression<tag, A1, A2, A3, A4>::result_type value_type; value_type temp(r); return os << temp; } // // What follows is the input streaming code: this is not "proper" iostream code at all // but that's fiendishly hard to write when dealing with multiple backends all // with different requirements... yes we could deligate this to the backend author... // but we really want backends to be EASY to write! // For now just pull in all the characters that could possibly form the number // and let the backend's string parser make use of it. This fixes most use cases // including CSV type formats such as those used by the Random lib. // inline std::string read_string_while(std::istream& is, std::string const& permitted_chars) { std::ios_base::iostate state = std::ios_base::goodbit; const std::istream::sentry sentry_check(is); std::string result; if(sentry_check) { int c = is.rdbuf()->sgetc(); for(;; c = is.rdbuf()->snextc()) if(std::istream::traits_type::eq_int_type(std::istream::traits_type::eof(), c)) { // end of file: state |= std::ios_base::eofbit; break; } else if(permitted_chars.find_first_of(std::istream::traits_type::to_char_type(c)) == std::string::npos) { // Invalid numeric character, stop reading: //is.rdbuf()->sputbackc(static_cast<char>(c)); break; } else { result.append(1, std::istream::traits_type::to_char_type(c)); } } if(!result.size()) state |= std::ios_base::failbit; is.setstate(state); return result; } } // namespace detail template <class Backend, expression_template_option ExpressionTemplates> inline std::istream& operator >> (std::istream& is, number<Backend, ExpressionTemplates>& r) { bool hex_format = (is.flags() & std::ios_base::hex) == std::ios_base::hex; bool oct_format = (is.flags() & std::ios_base::oct) == std::ios_base::oct; std::string s; switch(boost::multiprecision::number_category<number<Backend, ExpressionTemplates> >::value) { case boost::multiprecision::number_kind_integer: if(oct_format) s = detail::read_string_while(is, "+-01234567"); else if(hex_format) s = detail::read_string_while(is, "+-xXabcdefABCDEF0123456789"); else s = detail::read_string_while(is, "+-0123456789"); break; case boost::multiprecision::number_kind_floating_point: s = detail::read_string_while(is, "+-eE.0123456789infINFnanNANinfinityINFINITY"); break; default: is >> s; } if(s.size()) { if(hex_format && (number_category<Backend>::value == number_kind_integer) && ((s[0] != '0') || (s[1] != 'x'))) s.insert(s.find_first_not_of("+-"), "0x"); if(oct_format && (number_category<Backend>::value == number_kind_integer) && (s[0] != '0')) s.insert(s.find_first_not_of("+-"), "0"); r.assign(s); } else if(!is.fail()) is.setstate(std::istream::failbit); return is; } template <class Backend, expression_template_option ExpressionTemplates> BOOST_MP_FORCEINLINE void swap(number<Backend, ExpressionTemplates>& a, number<Backend, ExpressionTemplates>& b) BOOST_MP_NOEXCEPT_IF(noexcept(std::declval<number<Backend, ExpressionTemplates>&>() = std::declval<number<Backend, ExpressionTemplates>&>())) { a.swap(b); } // // Boost.Hash support, just call hash_value for the backend, which may or may not be supported: // template <class Backend, expression_template_option ExpressionTemplates> inline std::size_t hash_value(const number<Backend, ExpressionTemplates>& val) { return hash_value(val.backend()); } } // namespace multiprecision template <class T> class rational; template <class Backend, multiprecision::expression_template_option ExpressionTemplates> inline std::istream& operator >> (std::istream& is, rational<multiprecision::number<Backend, ExpressionTemplates> >& r) { std::string s1; multiprecision::number<Backend, ExpressionTemplates> v1, v2; char c; bool have_hex = false; bool hex_format = (is.flags() & std::ios_base::hex) == std::ios_base::hex; bool oct_format = (is.flags() & std::ios_base::oct) == std::ios_base::oct; while((EOF != (c = static_cast<char>(is.peek()))) && (c == 'x' || c == 'X' || c == '-' || c == '+' || (c >= '0' && c <= '9') || (have_hex && (c >= 'a' && c <= 'f')) || (have_hex && (c >= 'A' && c <= 'F')))) { if(c == 'x' || c == 'X') have_hex = true; s1.append(1, c); is.get(); } if(hex_format && ((s1[0] != '0') || (s1[1] != 'x'))) s1.insert(static_cast<std::string::size_type>(0), "0x"); if(oct_format && (s1[0] != '0')) s1.insert(static_cast<std::string::size_type>(0), "0"); v1.assign(s1); s1.erase(); if(c == '/') { is.get(); while((EOF != (c = static_cast<char>(is.peek()))) && (c == 'x' || c == 'X' || c == '-' || c == '+' || (c >= '0' && c <= '9') || (have_hex && (c >= 'a' && c <= 'f')) || (have_hex && (c >= 'A' && c <= 'F')))) { if(c == 'x' || c == 'X') have_hex = true; s1.append(1, c); is.get(); } if(hex_format && ((s1[0] != '0') || (s1[1] != 'x'))) s1.insert(static_cast<std::string::size_type>(0), "0x"); if(oct_format && (s1[0] != '0')) s1.insert(static_cast<std::string::size_type>(0), "0"); v2.assign(s1); } else v2 = 1; r.assign(v1, v2); return is; } template <class T, multiprecision::expression_template_option ExpressionTemplates> inline multiprecision::number<T, ExpressionTemplates> numerator(const rational<multiprecision::number<T, ExpressionTemplates> >& a) { return a.numerator(); } template <class T, multiprecision::expression_template_option ExpressionTemplates> inline multiprecision::number<T, ExpressionTemplates> denominator(const rational<multiprecision::number<T, ExpressionTemplates> >& a) { return a.denominator(); } namespace multiprecision { template <class I> struct component_type<boost::rational<I> > { typedef I type; }; } #ifdef BOOST_MSVC #pragma warning(pop) #endif } // namespaces #ifndef BOOST_NO_CXX11_HDR_FUNCTIONAL #include <functional> namespace std { template <class Backend, boost::multiprecision::expression_template_option ExpressionTemplates> struct hash<boost::multiprecision::number<Backend, ExpressionTemplates> > { std::size_t operator()(const boost::multiprecision::number<Backend, ExpressionTemplates>& val)const { return hash_value(val); } }; } #endif #include <boost/multiprecision/detail/ublas_interop.hpp> #endif
{ "content_hash": "171b85c048e8634bb8cb354da8b52eb9", "timestamp": "", "source": "github", "line_count": 1913, "max_line_length": 212, "avg_line_length": 41.26502875065342, "alnum_prop": 0.6315429440081074, "repo_name": "Owldream/Ginseng", "id": "da117bcf2e06f34d7a3059f574bba7f1eb8b53aa", "size": "78940", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "include/ginseng/3rd-party/boost/multiprecision/number.hpp", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "C", "bytes": "2144" }, { "name": "C++", "bytes": "612615" }, { "name": "CMake", "bytes": "21889" }, { "name": "Objective-C++", "bytes": "398" } ], "symlink_target": "" }
package nomad import ( "crypto/tls" "fmt" "io" "math/rand" "net" "net/rpc" "strings" "time" "github.com/armon/go-metrics" "github.com/hashicorp/consul/lib" memdb "github.com/hashicorp/go-memdb" "github.com/hashicorp/net-rpc-msgpackrpc" "github.com/hashicorp/nomad/nomad/state" "github.com/hashicorp/nomad/nomad/structs" "github.com/hashicorp/raft" "github.com/hashicorp/yamux" ) type RPCType byte const ( rpcNomad RPCType = 0x01 rpcRaft = 0x02 rpcMultiplex = 0x03 rpcTLS = 0x04 ) const ( // maxQueryTime is used to bound the limit of a blocking query maxQueryTime = 300 * time.Second // defaultQueryTime is the amount of time we block waiting for a change // if no time is specified. Previously we would wait the maxQueryTime. defaultQueryTime = 300 * time.Second // jitterFraction is a the limit to the amount of jitter we apply // to a user specified MaxQueryTime. We divide the specified time by // the fraction. So 16 == 6.25% limit of jitter. This jitter is also // applied to RPCHoldTimeout. jitterFraction = 16 // Warn if the Raft command is larger than this. // If it's over 1MB something is probably being abusive. raftWarnSize = 1024 * 1024 // enqueueLimit caps how long we will wait to enqueue // a new Raft command. Something is probably wrong if this // value is ever reached. However, it prevents us from blocking // the requesting goroutine forever. enqueueLimit = 30 * time.Second ) // NewClientCodec returns a new rpc.ClientCodec to be used to make RPC calls to // the Nomad Server. func NewClientCodec(conn io.ReadWriteCloser) rpc.ClientCodec { return msgpackrpc.NewCodecFromHandle(true, true, conn, structs.HashiMsgpackHandle) } // NewServerCodec returns a new rpc.ServerCodec to be used by the Nomad Server // to handle rpcs. func NewServerCodec(conn io.ReadWriteCloser) rpc.ServerCodec { return msgpackrpc.NewCodecFromHandle(true, true, conn, structs.HashiMsgpackHandle) } // listen is used to listen for incoming RPC connections func (s *Server) listen() { for { // Accept a connection conn, err := s.rpcListener.Accept() if err != nil { if s.shutdown { return } s.logger.Printf("[ERR] nomad.rpc: failed to accept RPC conn: %v", err) continue } go s.handleConn(conn, false) metrics.IncrCounter([]string{"nomad", "rpc", "accept_conn"}, 1) } } // handleConn is used to determine if this is a Raft or // Nomad type RPC connection and invoke the correct handler func (s *Server) handleConn(conn net.Conn, isTLS bool) { // Read a single byte buf := make([]byte, 1) if _, err := conn.Read(buf); err != nil { if err != io.EOF { s.logger.Printf("[ERR] nomad.rpc: failed to read byte: %v", err) } conn.Close() return } // Enforce TLS if VerifyIncoming is set if s.config.RequireTLS && !isTLS && RPCType(buf[0]) != rpcTLS { s.logger.Printf("[WARN] nomad.rpc: Non-TLS connection attempted with RequireTLS set") conn.Close() return } // Switch on the byte switch RPCType(buf[0]) { case rpcNomad: s.handleNomadConn(conn) case rpcRaft: metrics.IncrCounter([]string{"nomad", "rpc", "raft_handoff"}, 1) s.raftLayer.Handoff(conn) case rpcMultiplex: s.handleMultiplex(conn) case rpcTLS: if s.rpcTLS == nil { s.logger.Printf("[WARN] nomad.rpc: TLS connection attempted, server not configured for TLS") conn.Close() return } conn = tls.Server(conn, s.rpcTLS) s.handleConn(conn, true) default: s.logger.Printf("[ERR] nomad.rpc: unrecognized RPC byte: %v", buf[0]) conn.Close() return } } // handleMultiplex is used to multiplex a single incoming connection // using the Yamux multiplexer func (s *Server) handleMultiplex(conn net.Conn) { defer conn.Close() conf := yamux.DefaultConfig() conf.LogOutput = s.config.LogOutput server, _ := yamux.Server(conn, conf) for { sub, err := server.Accept() if err != nil { if err != io.EOF { s.logger.Printf("[ERR] nomad.rpc: multiplex conn accept failed: %v", err) } return } go s.handleNomadConn(sub) } } // handleNomadConn is used to service a single Nomad RPC connection func (s *Server) handleNomadConn(conn net.Conn) { defer conn.Close() rpcCodec := NewServerCodec(conn) for { select { case <-s.shutdownCh: return default: } if err := s.rpcServer.ServeRequest(rpcCodec); err != nil { if err != io.EOF && !strings.Contains(err.Error(), "closed") { s.logger.Printf("[ERR] nomad.rpc: RPC error: %v (%v)", err, conn) metrics.IncrCounter([]string{"nomad", "rpc", "request_error"}, 1) } return } metrics.IncrCounter([]string{"nomad", "rpc", "request"}, 1) } } // forward is used to forward to a remote region or to forward to the local leader // Returns a bool of if forwarding was performed, as well as any error func (s *Server) forward(method string, info structs.RPCInfo, args interface{}, reply interface{}) (bool, error) { var firstCheck time.Time region := info.RequestRegion() if region == "" { return true, fmt.Errorf("missing target RPC") } // Handle region forwarding if region != s.config.Region { err := s.forwardRegion(region, method, args, reply) return true, err } // Check if we can allow a stale read if info.IsRead() && info.AllowStaleRead() { return false, nil } CHECK_LEADER: // Find the leader isLeader, remoteServer := s.getLeader() // Handle the case we are the leader if isLeader { return false, nil } // Handle the case of a known leader if remoteServer != nil { err := s.forwardLeader(remoteServer, method, args, reply) return true, err } // Gate the request until there is a leader if firstCheck.IsZero() { firstCheck = time.Now() } if time.Now().Sub(firstCheck) < s.config.RPCHoldTimeout { jitter := lib.RandomStagger(s.config.RPCHoldTimeout / jitterFraction) select { case <-time.After(jitter): goto CHECK_LEADER case <-s.shutdownCh: } } // No leader found and hold time exceeded return true, structs.ErrNoLeader } // getLeader returns if the current node is the leader, and if not // then it returns the leader which is potentially nil if the cluster // has not yet elected a leader. func (s *Server) getLeader() (bool, *serverParts) { // Check if we are the leader if s.IsLeader() { return true, nil } // Get the leader leader := s.raft.Leader() if leader == "" { return false, nil } // Lookup the server s.peerLock.RLock() server := s.localPeers[leader] s.peerLock.RUnlock() // Server could be nil return false, server } // forwardLeader is used to forward an RPC call to the leader, or fail if no leader func (s *Server) forwardLeader(server *serverParts, method string, args interface{}, reply interface{}) error { // Handle a missing server if server == nil { return structs.ErrNoLeader } return s.connPool.RPC(s.config.Region, server.Addr, server.MajorVersion, method, args, reply) } // forwardRegion is used to forward an RPC call to a remote region, or fail if no servers func (s *Server) forwardRegion(region, method string, args interface{}, reply interface{}) error { // Bail if we can't find any servers s.peerLock.RLock() servers := s.peers[region] if len(servers) == 0 { s.peerLock.RUnlock() s.logger.Printf("[WARN] nomad.rpc: RPC request for region '%s', no path found", region) return structs.ErrNoRegionPath } // Select a random addr offset := rand.Intn(len(servers)) server := servers[offset] s.peerLock.RUnlock() // Forward to remote Nomad metrics.IncrCounter([]string{"nomad", "rpc", "cross-region", region}, 1) return s.connPool.RPC(region, server.Addr, server.MajorVersion, method, args, reply) } // raftApplyFuture is used to encode a message, run it through raft, and return the Raft future. func (s *Server) raftApplyFuture(t structs.MessageType, msg interface{}) (raft.ApplyFuture, error) { buf, err := structs.Encode(t, msg) if err != nil { return nil, fmt.Errorf("Failed to encode request: %v", err) } // Warn if the command is very large if n := len(buf); n > raftWarnSize { s.logger.Printf("[WARN] nomad: Attempting to apply large raft entry (type %d) (%d bytes)", t, n) } future := s.raft.Apply(buf, enqueueLimit) return future, nil } // raftApply is used to encode a message, run it through raft, and return // the FSM response along with any errors func (s *Server) raftApply(t structs.MessageType, msg interface{}) (interface{}, uint64, error) { future, err := s.raftApplyFuture(t, msg) if err != nil { return nil, 0, err } if err := future.Error(); err != nil { return nil, 0, err } return future.Response(), future.Index(), nil } // setQueryMeta is used to populate the QueryMeta data for an RPC call func (s *Server) setQueryMeta(m *structs.QueryMeta) { if s.IsLeader() { m.LastContact = 0 m.KnownLeader = true } else { m.LastContact = time.Now().Sub(s.raft.LastContact()) m.KnownLeader = (s.raft.Leader() != "") } } // queryFn is used to perform a query operation. If a re-query is needed, the // passed-in watch set will be used to block for changes. The passed-in state // store should be used (vs. calling fsm.State()) since the given state store // will be correctly watched for changes if the state store is restored from // a snapshot. type queryFn func(memdb.WatchSet, *state.StateStore) error // blockingOptions is used to parameterize blockingRPC type blockingOptions struct { queryOpts *structs.QueryOptions queryMeta *structs.QueryMeta run queryFn } // blockingRPC is used for queries that need to wait for a // minimum index. This is used to block and wait for changes. func (s *Server) blockingRPC(opts *blockingOptions) error { var timeout *time.Timer var state *state.StateStore // Fast path non-blocking if opts.queryOpts.MinQueryIndex == 0 { goto RUN_QUERY } // Restrict the max query time, and ensure there is always one if opts.queryOpts.MaxQueryTime > maxQueryTime { opts.queryOpts.MaxQueryTime = maxQueryTime } else if opts.queryOpts.MaxQueryTime <= 0 { opts.queryOpts.MaxQueryTime = defaultQueryTime } // Apply a small amount of jitter to the request opts.queryOpts.MaxQueryTime += lib.RandomStagger(opts.queryOpts.MaxQueryTime / jitterFraction) // Setup a query timeout timeout = time.NewTimer(opts.queryOpts.MaxQueryTime) defer timeout.Stop() RUN_QUERY: // Update the query meta data s.setQueryMeta(opts.queryMeta) // Increment the rpc query counter metrics.IncrCounter([]string{"nomad", "rpc", "query"}, 1) // We capture the state store and its abandon channel but pass a snapshot to // the blocking query function. We operate on the snapshot to allow separate // calls to the state store not all wrapped within the same transaction. state = s.fsm.State() abandonCh := state.AbandonCh() snap, _ := state.Snapshot() stateSnap := &snap.StateStore // We can skip all watch tracking if this isn't a blocking query. var ws memdb.WatchSet if opts.queryOpts.MinQueryIndex > 0 { ws = memdb.NewWatchSet() // This channel will be closed if a snapshot is restored and the // whole state store is abandoned. ws.Add(abandonCh) } // Block up to the timeout if we didn't see anything fresh. err := opts.run(ws, stateSnap) // Check for minimum query time if err == nil && opts.queryOpts.MinQueryIndex > 0 && opts.queryMeta.Index <= opts.queryOpts.MinQueryIndex { if expired := ws.Watch(timeout.C); !expired { goto RUN_QUERY } } return err }
{ "content_hash": "8ed4a5dc81b1b3730716d1fa69c46792", "timestamp": "", "source": "github", "line_count": 398, "max_line_length": 114, "avg_line_length": 28.768844221105528, "alnum_prop": 0.7042794759825327, "repo_name": "chentex/maya", "id": "7aaf225c094baedfc64451c1a3cd043eb582e85c", "size": "11450", "binary": false, "copies": "4", "ref": "refs/heads/master", "path": "vendor/github.com/hashicorp/nomad/nomad/rpc.go", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Go", "bytes": "650999" }, { "name": "HCL", "bytes": "577" }, { "name": "Makefile", "bytes": "4197" }, { "name": "Shell", "bytes": "29956" } ], "symlink_target": "" }
layout: post date: '2016-08-04' title: "PAGEANT DRESSES Side Cut Outs Chiffon Prom Dress in Magenta" category: PAGEANT DRESSES tags: [PAGEANT DRESSES] --- ### PAGEANT DRESSES Side Cut Outs Chiffon Prom Dress in Magenta Just **$504.99** ### &nbsp; <a href="https://www.eudances.com/en/pageant-dresses/1540-side-cut-outs-chiffon-prom-dress-in-magenta.html"><img src="//www.eudances.com/4593-thickbox_default/side-cut-outs-chiffon-prom-dress-in-magenta.jpg" alt="Side Cut Outs Chiffon Prom Dress in Magenta" style="width:100%;" /></a> <!-- break --><a href="https://www.eudances.com/en/pageant-dresses/1540-side-cut-outs-chiffon-prom-dress-in-magenta.html"><img src="//www.eudances.com/4592-thickbox_default/side-cut-outs-chiffon-prom-dress-in-magenta.jpg" alt="Side Cut Outs Chiffon Prom Dress in Magenta" style="width:100%;" /></a> Buy it: [https://www.eudances.com/en/pageant-dresses/1540-side-cut-outs-chiffon-prom-dress-in-magenta.html](https://www.eudances.com/en/pageant-dresses/1540-side-cut-outs-chiffon-prom-dress-in-magenta.html)
{ "content_hash": "20dd6a83ee8424d8628e954f1464c2a2", "timestamp": "", "source": "github", "line_count": 15, "max_line_length": 298, "avg_line_length": 69.4, "alnum_prop": 0.7473583093179635, "repo_name": "lastgown/lastgown.github.io", "id": "5e9bb87994594e2f699a17ad21179f7dfc322ed9", "size": "1045", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "_posts/2016-08-04-PAGEANT-DRESSES-Side-Cut-Outs-Chiffon-Prom-Dress-in-Magenta.md", "mode": "33261", "license": "mit", "language": [ { "name": "CSS", "bytes": "83876" }, { "name": "HTML", "bytes": "14755" }, { "name": "Ruby", "bytes": "897" } ], "symlink_target": "" }
package com.commonsware.android.headerdetail; import android.app.ListActivity; import android.os.Bundle; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.TextView; public class HeaderDetailListDemo extends ListActivity { private static final String[][] items= { { "lorem", "ipsum", "dolor", "sit", "amet" }, { "consectetuer", "adipiscing", "elit", "morbi", "vel" }, { "ligula", "vitae", "arcu", "aliquet", "mollis" }, { "etiam", "vel", "erat", "placerat", "ante" }, { "porttitor", "sodales", "pellentesque", "augue", "purus" } }; @Override public void onCreate(Bundle state) { super.onCreate(state); setListAdapter(new IconicAdapter()); } class IconicAdapter extends BaseAdapter { @Override public int getCount() { int count=0; for (String[] batch : items) { count+=1 + batch.length; } return(count); } @Override public Object getItem(int position) { int offset=position; int batchIndex=0; for (String[] batch : items) { if (offset == 0) { return(Integer.valueOf(batchIndex)); } offset--; if (offset < batch.length) { return(batch[offset]); } offset-=batch.length; batchIndex++; } throw new IllegalArgumentException("Invalid position: " + String.valueOf(position)); } @Override public long getItemId(int position) { return(position); } @Override public int getViewTypeCount() { return(2); } @Override public int getItemViewType(int position) { if (getItem(position) instanceof Integer) { return(0); } return(1); } @Override public View getView(int position, View convertView, ViewGroup parent) { if (getItemViewType(position) == 0) { return(getHeaderView(position, convertView, parent)); } View row=convertView; if (row == null) { row=getLayoutInflater().inflate(R.layout.row, parent, false); } ViewHolder holder=(ViewHolder)row.getTag(); if (holder == null) { holder=new ViewHolder(row); row.setTag(holder); } String word=(String)getItem(position); if (word.length() > 4) { holder.icon.setImageResource(R.drawable.delete); } else { holder.icon.setImageResource(R.drawable.ok); } holder.label.setText(word); holder.size.setText(String.format(getString(R.string.size_template), word.length())); return(row); } private View getHeaderView(int position, View convertView, ViewGroup parent) { View row=convertView; if (row == null) { row=getLayoutInflater().inflate(R.layout.header, parent, false); } Integer batchIndex=(Integer)getItem(position); TextView label=(TextView)row.findViewById(R.id.label); label.setText(String.format(getString(R.string.batch), 1 + batchIndex.intValue())); return(row); } } }
{ "content_hash": "0f18c9ad657446fe86ffb895296b7538", "timestamp": "", "source": "github", "line_count": 133, "max_line_length": 75, "avg_line_length": 24.157894736842106, "alnum_prop": 0.5866791160908807, "repo_name": "alexsh/cw-omnibus", "id": "4e392b59674b5c803d8f750ce0a258c8909202bb", "size": "3916", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "Selection/HeaderDetailList/app/src/main/java/com/commonsware/android/headerdetail/HeaderDetailListDemo.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "54274" }, { "name": "Groovy", "bytes": "4601" }, { "name": "HTML", "bytes": "2293656" }, { "name": "Java", "bytes": "3404604" }, { "name": "JavaScript", "bytes": "646239" }, { "name": "Kotlin", "bytes": "7397" }, { "name": "Python", "bytes": "546" }, { "name": "Ruby", "bytes": "2071" }, { "name": "Shell", "bytes": "1020" } ], "symlink_target": "" }
// // BSJPictureShowViewController.h // PLMMPRJK // // Created by HuXuPeng on 2017/6/1. // Copyright © 2017年 GoMePrjk. All rights reserved. // #import "LMJBaseViewController.h" #import "BSJTopicViewModel.h" @interface BSJPictureShowViewController : LMJBaseViewController /** <#digest#> */ @property (nonatomic, strong) BSJTopicViewModel *topicViewModel; @end
{ "content_hash": "162ce6f596a2f47c55948729dfe61e5e", "timestamp": "", "source": "github", "line_count": 16, "max_line_length": 64, "avg_line_length": 22.875, "alnum_prop": 0.7486338797814208, "repo_name": "NJHu/PLMMPrjk", "id": "790004d0be8f546d97fe8b2a7c29b192c9498fe2", "size": "369", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "iOSProject/iOSProject/Classes/百思不得姐/Controller/BSJPictureShowViewController.h", "mode": "33188", "license": "mit", "language": [ { "name": "C", "bytes": "3884" }, { "name": "HTML", "bytes": "7741" }, { "name": "JavaScript", "bytes": "9900" }, { "name": "Objective-C", "bytes": "7221492" }, { "name": "Ruby", "bytes": "1558" }, { "name": "Shell", "bytes": "10753" }, { "name": "Swift", "bytes": "5016" } ], "symlink_target": "" }
package net.tmachq.Ported_Blocks.tileentities.blocks; import java.util.List; import net.minecraft.block.Block; import net.minecraft.block.BlockContainer; import net.minecraft.block.material.Material; import net.minecraft.client.renderer.texture.IconRegister; import net.minecraft.creativetab.CreativeTabs; import net.minecraft.entity.EntityLivingBase; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.item.ItemStack; import net.minecraft.tileentity.TileEntity; import net.minecraft.util.Icon; import net.minecraft.util.MathHelper; import net.minecraft.util.ResourceLocation; import net.minecraft.world.World; import net.tmachq.Ported_Blocks.Ported_Blocks; import net.tmachq.Ported_Blocks.tileentities.entities.*; import cpw.mods.fml.relauncher.Side; import cpw.mods.fml.relauncher.SideOnly; public class TileEntityAzuriteColumn extends BlockContainer { public TileEntityAzuriteColumn(int id) { super(id, Material.rock); this.setHardness(3.0F); this.setCreativeTab(Ported_Blocks.Ported_Blocks_Tab); this.setLightOpacity(0); this.setBlockBounds(.14F, 0F, .14F, .86F, 1F, .86F); } @Override public TileEntity createNewTileEntity(World world) { return new TileEntityAzuriteColumnEntity(); } @Override public int getRenderType() { return -1; } @Override public boolean isOpaqueCube() { return false; } public boolean renderAsNormalBlock() { return false; } public void registerIcons(IconRegister icon) { this.blockIcon = icon.registerIcon("ported_blocks:Azurite_Column"); } }
{ "content_hash": "d0c6f83e24e92b61115a7a5c237f798b", "timestamp": "", "source": "github", "line_count": 57, "max_line_length": 75, "avg_line_length": 29.57894736842105, "alnum_prop": 0.7224199288256228, "repo_name": "TMAC-Coding/Ported-Blocks", "id": "596fcd2c1e487d805e3673a218339bc7e183446e", "size": "1686", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/net/tmachq/Ported_Blocks/tileentities/blocks/TileEntityAzuriteColumn.java", "mode": "33188", "license": "mit", "language": [ { "name": "Java", "bytes": "135526" } ], "symlink_target": "" }
bool getCheckAllCombinations();
{ "content_hash": "c8bdc8f3987072d86fc197aa5c7bfc27", "timestamp": "", "source": "github", "line_count": 1, "max_line_length": 31, "avg_line_length": 31, "alnum_prop": 0.8709677419354839, "repo_name": "Harrix/HarrixClass_DataOfHarrixOptimizationTesting", "id": "b30f35ec391d3fd50ed44c9f3dc46cd5d0faaa50", "size": "31", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "source_library_onlydata/public Возвращение данных из класса/getCheckAllCombinations.h", "mode": "33188", "license": "mit", "language": [ { "name": "C", "bytes": "13218" }, { "name": "C++", "bytes": "1984780" }, { "name": "CSS", "bytes": "3189" }, { "name": "HTML", "bytes": "2065" }, { "name": "TeX", "bytes": "305427" } ], "symlink_target": "" }
<!-- Safe sample input : use proc_open to read /tmp/tainted.txt sanitize : cast via + = 0 File : use of untrusted data in a double quoted property value (CSS) --> <!--Copyright 2015 Bertrand STIVALET Permission is hereby granted, without written agreement or royalty fee, to use, copy, modify, and distribute this software and its documentation for any purpose, provided that the above copyright notice and the following three paragraphs appear in all copies of this software. IN NO EVENT SHALL AUTHORS BE LIABLE TO ANY PARTY FOR DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF AUTHORS HAVE BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. AUTHORS SPECIFICALLY DISCLAIM ANY WARRANTIES INCLUDING, BUT NOT LIMITED TO THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, AND NON-INFRINGEMENT. THE SOFTWARE IS PROVIDED ON AN "AS-IS" BASIS AND AUTHORS HAVE NO OBLIGATION TO PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.--> <!DOCTYPE html> <html> <head> <style> <?php $descriptorspec = array( 0 => array("pipe", "r"), 1 => array("pipe", "w"), 2 => array("file", "/tmp/error-output.txt", "a") ); $cwd = '/tmp'; $process = proc_open('more /tmp/tainted.txt', $descriptorspec, $pipes, $cwd, NULL); if (is_resource($process)) { fclose($pipes[0]); $tainted = stream_get_contents($pipes[1]); fclose($pipes[1]); $return_value = proc_close($process); } $tainted = $tainted + 0; echo "body { color :\"". $tainted ."\" ; }" ; ?> </style> </head> <body> <h1>Hello World!</h1> </body> </html>
{ "content_hash": "787030e89910d799dde1471a3d13b7ae", "timestamp": "", "source": "github", "line_count": 71, "max_line_length": 83, "avg_line_length": 23.253521126760564, "alnum_prop": 0.709267110841914, "repo_name": "stivalet/PHP-Vulnerability-test-suite", "id": "eb66507105860442b65336eeea5b03a28c9bc00a", "size": "1651", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "XSS/CWE_79/safe/CWE_79__proc_open__CAST-cast_int_sort_of2__Use_untrusted_data_propertyValue_CSS-double_Quoted_Property_Value.php", "mode": "33188", "license": "mit", "language": [ { "name": "PHP", "bytes": "64184004" } ], "symlink_target": "" }
There's quite a few steps to follow if you want to setup Kubuntu to work with different input methods such as Korean (Hangul). These are the steps I had to do on Kubuntu 16.04 to get it working. Hopefully this is useful to anyone else who was stuck with this :) # 1. Install packages IBus seems to be the way to go if you want to type on a non-english keyboard. First you need to install an appropriate engine. To see what's available: ```shell $ apt-cache search ibus |grep engine ibus-anthy - anthy engine for IBus ibus-anthy-dev - anthy engine for IBus, development files ibus-chewing - Chewing engine for IBus ibus-hangul - Hangul engine for IBus ibus-m17n - m17n engine for IBus ibus-sunpinyin - sunpinyin engine for ibus ibus-table - table engine for IBus ibus-table-extraphrase - Extra phrase for table engine of ibus ibus-array - Array 30 input engine for iBus ibus-kkc - Japanese Kana Kanji input engine for IBus ibus-kkc-dbg - Japanese Kana Kanji input engine for IBus - debugging symbols ibus-libthai - Thai input method engine for IBus based on LibThai ibus-mozc - Mozc engine for IBus - Client of the Mozc input method ibus-skk - SKK engine for IBus ibus-table-array30 - Array30 input method based on table engine of ibus ibus-tegaki - tegaki engine for IBus ibus-braille - Braille input engine for IBus ibus-libpinyin - Intelligent Pinyin engine based on libpinyin for IBus ibus-libzhuyin - New Zhuyin engine based on libzhuyin for IBus ibus-pinyin - Pinyin engine for IBus ``` To try out Korean support, we want the `ibus-hangul` method: ``` $ sudo apt-get install -y ibus-hangul ``` # 2. Configure KDE to start ibus-daemon We need to tell KDE to start the ibus-daemon on login ## 2.1 Load KDE settings ![settings](step2_i.png) ## 2.2 Startup and shutdown ![startup and shutdown](step2_ii.png) ## 2.3 Add ibus-daemon Click `Add Program...`, then type `ibus-daemon` and click `OK` until the system accepts the change. ![autostart ibus-daemon](step2_iii.png) When you've finished, the screen should look like this: ![finished](step2_iv.png) # 3. Configure input methods Now we need to tell the system to use `ibus`. I had a few extra options in my list because I was playing earlier ;-) ## 3.1 Run im-config ![im-config](step3_i.png) ## 3.2 Click OK ![im-config ok](step3_ii.png) ## 3.3 Click Yes ![finished](step3_iii.png) ## 3.4 Select ibus Choose `ibus` from the list and then click `OK` ![ibus mode](step3_iv.png) ## 3.5 Summary Check the summary information and click `OK` ![summary](step3_v.png) ## 3.6 Reboot Now the important part. Reboot your computer! ![reboot](step3_vi.png) # 4. Using the new input method ## 4.1 Switching input methods If it all worked, you should now have a new indicator in the panel at the bottom right of the screen. Here we are still in ENglish mode: ![switcher icon](step4_i.png) To switch languages, we can click the icon or use `Windows Key` + `Space` at the same time to switch: ![switch languages hotkey](switch_lang.jpg) The icon will change: ![switcher icon](step4_ii.png) ## 4.2 Try out Hangul mode If we type something now, we can see we are still getting English input, we need to activate Hangul (Korean) mode by pressing `Shift` + `Space` at the same time: ![hangul mode](hangul_mode.jpg) Now we can easily switch between typing in Korean and English. I used the `kate` editor to practice but you can just try this in firefox and it should work too. You can also use the icon in the bottom right panel to switch: ![demo](step4_iii.png) I have no idea what I typed but its working! # Troubleshooting If you followed the steps and it didn't work, here are some things to try: * First of all, make sure you rebooted. It seems necessary to restart the Xserver for changes to take effect * Try re-running `im-config` (Step 3) and then reboot - this seemed to fix it for me * Make sure the `ibus-daemon` process is alive
{ "content_hash": "96b5ac3e05a5f0c98ce0437f18e8787f", "timestamp": "", "source": "github", "line_count": 108, "max_line_length": 263, "avg_line_length": 36.27777777777778, "alnum_prop": 0.7450229709035222, "repo_name": "GeoffWilliams/geoffwilliams.me.uk", "id": "a85d6ada6f81fce86c3a3f176a08db2705dfe50e", "size": "3942", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "user/pages/04.blog/07.ibus_kubuntu/default.md", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "522366" }, { "name": "Dockerfile", "bytes": "901" }, { "name": "HTML", "bytes": "118727" }, { "name": "JavaScript", "bytes": "54563" }, { "name": "Logos", "bytes": "831" }, { "name": "Makefile", "bytes": "494" }, { "name": "PHP", "bytes": "1950535" }, { "name": "Shell", "bytes": "41" } ], "symlink_target": "" }
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE PolicySet [ <!ENTITY xml "http://www.w3.org/2001/XMLSchema#"> <!ENTITY rule-combine "urn:oasis:names:tc:xacml:1.0:rule-combining-algorithm:"> <!ENTITY policy-combine "urn:oasis:names:tc:xacml:1.0:policy-combining-algorithm:"> <!ENTITY function "urn:oasis:names:tc:xacml:1.0:function:"> <!ENTITY subject-category "urn:oasis:names:tc:xacml:1.0:subject-category:"> <!ENTITY subject "urn:oasis:names:tc:xacml:1.0:subject:"> <!ENTITY role "urn:oasis:names:tc:xacml:2.0:subject:role"> <!ENTITY roles "urn:oasis:names:tc:xacml:2.0:subject:role-values:"> <!ENTITY tenant "urn:oasis:names:tc:xacml:2.0:subject:tenant"> <!ENTITY tenants "urn:oasis:names:tc:xacml:2.0:subject:tenant-values:"> <!ENTITY resource "urn:oasis:names:tc:xacml:1.0:resource:"> <!ENTITY resource-tenant "urn:oasis:names:tc:xacml:2.0:resource:tenant"> <!ENTITY resource-tenants "urn:oasis:names:tc:xacml:2.0:resource:tenant-values:"> <!ENTITY action "urn:oasis:names:tc:xacml:1.0:action:"> <!ENTITY actions "urn:oasis:names:tc:xacml:2.0:actions:"> <!ENTITY environment "urn:oasis:names:tc:xacml:1.0:environment:"> <!ENTITY policyset-id "urn:oasis:names:tc:xacml:2.0:rbac:"> ]> <Request xmlns="urn:oasis:names:tc:xacml:2.0:context:schema:os" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"> <Subject> <Attribute AttributeId="&subject;subject-id" DataType="&xml;string" IncludeInResult="false"> <AttributeValue>Anne</AttributeValue> </Attribute> <Attribute AttributeId="&role;" DataType="&xml;anyURI" IncludeInResult="false"> <AttributeValue>&roles;i0849:manager</AttributeValue> </Attribute> <Attribute AttributeId="&tenant;" DataType="&xml;anyURI" IncludeInResult="false"> <AttributeValue>&tenants;i0848</AttributeValue> </Attribute> </Subject> <Resource> <Attribute AttributeId="&resource;resource-id" DataType="&xml;string" IncludeInResult="false"> <AttributeValue>purchase order</AttributeValue> </Attribute> <Attribute AttributeId="&resource-tenant;" DataType="&xml;anyURI" IncludeInResult="false"> <AttributeValue>&resource-tenants;i0849</AttributeValue> </Attribute> </Resource> <Action> <Attribute AttributeId="&action;action-id" DataType="&xml;string" IncludeInResult="false"> <AttributeValue>create</AttributeValue> </Attribute> </Action> </Request>
{ "content_hash": "3a9692c21872d0283a409237a1df25a3", "timestamp": "", "source": "github", "line_count": 55, "max_line_length": 83, "avg_line_length": 43.654545454545456, "alnum_prop": 0.7176176593086214, "repo_name": "townbull/mtaaas", "id": "f5734fa46b9863f795152afb257e1a36ba339d31", "size": "2401", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "PEPClient/testcases/MTAS0849CRequest.xml", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "1440895" }, { "name": "Shell", "bytes": "8283" } ], "symlink_target": "" }
<?php namespace Speelpenning\Workbench\Generators; use Illuminate\Config\Repository; use Illuminate\Contracts\Support\Arrayable; use Illuminate\Contracts\Support\Jsonable; use Illuminate\Filesystem\Filesystem; use Speelpenning\Workbench\Exceptions\FileNotCreated; class ComposerDotJsonGenerator { /** * @var Filesystem */ protected $filesystem; /** * ComposerDotJsonGenerator constructor. * * @param Filesystem $filesystem */ public function __construct(Filesystem $filesystem) { $this->filesystem = $filesystem; } /** * Generates the composer.json file. * * @param string $path * @param string $vendor * @param string $package * @param string $description * @param string $license * @param string $author_name * @param string $author_email * @param string $namespace * @throws FileNotCreated */ public function generate($path, $vendor, $package, $description, $license, $author_name, $author_email, $namespace) { $file = $path . DIRECTORY_SEPARATOR . 'composer.json'; $json = $this->toJson($vendor, $package, $description, $license, $author_name, $author_email, $namespace); if ( ! $this->filesystem->put($file, $json)) { throw new FileNotCreated($file); } } /** * Creates the JSON output. * * @param string $vendor * @param string $package * @param string $description * @param string $license * @param string $author_name * @param string $author_email * @param string $namespace * @return string */ protected function toJson($vendor, $package, $description, $license, $author_name, $author_email, $namespace) { return json_encode([ 'name' => $vendor . DIRECTORY_SEPARATOR . $package, 'description' => $description, 'license' => $license, 'authors' => [ ['name' => $author_name, 'email' => $author_email] ], 'autoload' => [ 'psr-4' => [ $namespace . '\\' => 'src/' ] ] ], JSON_PRETTY_PRINT|JSON_UNESCAPED_SLASHES); } }
{ "content_hash": "1f1324be56bfb9d107d160dbf195196e", "timestamp": "", "source": "github", "line_count": 80, "max_line_length": 119, "avg_line_length": 28.225, "alnum_prop": 0.5788308237378211, "repo_name": "Speelpenning-nl/laravel-workbench", "id": "af4491d045f9e2c80e8a92fc46fac3fcd1917ab1", "size": "2258", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/Generators/ComposerDotJsonGenerator.php", "mode": "33188", "license": "mit", "language": [ { "name": "PHP", "bytes": "54360" } ], "symlink_target": "" }
// Copyright 2020 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // 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. using NtApiDotNet; namespace NtObjectManager.Utils { class SecurityDescriptorTransformAttribute : BaseTransformAttribute { public SecurityDescriptorTransformAttribute() : base(typeof(SecurityDescriptor)) { } protected override object DefaultValue(object obj) { if (obj is SecurityDescriptor sd) { return sd; } return new SecurityDescriptor(); } protected override NtResult<object> Parse(string value, bool throw_on_error) { return SecurityDescriptor.Parse(value, false); } } }
{ "content_hash": "647d780553fbe5aefc31b54c2f39710f", "timestamp": "", "source": "github", "line_count": 40, "max_line_length": 84, "avg_line_length": 31.75, "alnum_prop": 0.6622047244094488, "repo_name": "googleprojectzero/sandbox-attacksurface-analysis-tools", "id": "6988c43c9ba567796a5c19b8159cf9faaeed41a3", "size": "1272", "binary": false, "copies": "1", "ref": "refs/heads/main", "path": "NtObjectManager/Utils/SecurityDescriptorTransformAttribute.cs", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "C#", "bytes": "9863556" }, { "name": "PowerShell", "bytes": "667339" }, { "name": "Smalltalk", "bytes": "108104" } ], "symlink_target": "" }
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("GoldenTicket.Tests")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("GoldenTicket.Tests")] [assembly: AssemblyCopyright("Copyright © 2014")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("38ebe42a-5b38-4c94-b0e7-d6bd582ff661")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Revision and Build Numbers // by using the '*' as shown below: [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
{ "content_hash": "80e562a8bb19fa1f1abe84a66fa7a4dd", "timestamp": "", "source": "github", "line_count": 35, "max_line_length": 84, "avg_line_length": 38.97142857142857, "alnum_prop": 0.7521994134897361, "repo_name": "codeforamerica/golden-ticket", "id": "87c675345747adc344f9953dd7cf7373e0e8d0e1", "size": "1367", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "GoldenTicket.Tests/Properties/AssemblyInfo.cs", "mode": "33188", "license": "bsd-2-clause", "language": [ { "name": "ASP", "bytes": "103" }, { "name": "C#", "bytes": "242949" }, { "name": "CSS", "bytes": "43553" }, { "name": "JavaScript", "bytes": "11266" } ], "symlink_target": "" }
/*************************************************************************/ /* godot_broad_phase_3d_bvh.cpp */ /*************************************************************************/ /* This file is part of: */ /* GODOT ENGINE */ /* https://godotengine.org */ /*************************************************************************/ /* Copyright (c) 2007-2022 Juan Linietsky, Ariel Manzur. */ /* Copyright (c) 2014-2022 Godot Engine contributors (cf. AUTHORS.md). */ /* */ /* Permission is hereby granted, free of charge, to any person obtaining */ /* a copy of this software and associated documentation files (the */ /* "Software"), to deal in the Software without restriction, including */ /* without limitation the rights to use, copy, modify, merge, publish, */ /* distribute, sublicense, and/or sell copies of the Software, and to */ /* permit persons to whom the Software is furnished to do so, subject to */ /* the following conditions: */ /* */ /* The above copyright notice and this permission notice shall be */ /* included in all copies or substantial portions of the Software. */ /* */ /* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */ /* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */ /* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/ /* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */ /* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */ /* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */ /* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ /*************************************************************************/ #include "godot_broad_phase_3d_bvh.h" #include "godot_collision_object_3d.h" GodotBroadPhase3DBVH::ID GodotBroadPhase3DBVH::create(GodotCollisionObject3D *p_object, int p_subindex, const AABB &p_aabb, bool p_static) { uint32_t tree_id = p_static ? TREE_STATIC : TREE_DYNAMIC; uint32_t tree_collision_mask = p_static ? TREE_FLAG_DYNAMIC : (TREE_FLAG_STATIC | TREE_FLAG_DYNAMIC); ID oid = bvh.create(p_object, true, tree_id, tree_collision_mask, p_aabb, p_subindex); // Pair everything, don't care? return oid + 1; } void GodotBroadPhase3DBVH::move(ID p_id, const AABB &p_aabb) { bvh.move(p_id - 1, p_aabb); } void GodotBroadPhase3DBVH::set_static(ID p_id, bool p_static) { uint32_t tree_id = p_static ? TREE_STATIC : TREE_DYNAMIC; uint32_t tree_collision_mask = p_static ? TREE_FLAG_DYNAMIC : (TREE_FLAG_STATIC | TREE_FLAG_DYNAMIC); bvh.set_tree(p_id - 1, tree_id, tree_collision_mask, false); } void GodotBroadPhase3DBVH::remove(ID p_id) { bvh.erase(p_id - 1); } GodotCollisionObject3D *GodotBroadPhase3DBVH::get_object(ID p_id) const { GodotCollisionObject3D *it = bvh.get(p_id - 1); ERR_FAIL_COND_V(!it, nullptr); return it; } bool GodotBroadPhase3DBVH::is_static(ID p_id) const { uint32_t tree_id = bvh.get_tree_id(p_id - 1); return tree_id == 0; } int GodotBroadPhase3DBVH::get_subindex(ID p_id) const { return bvh.get_subindex(p_id - 1); } int GodotBroadPhase3DBVH::cull_point(const Vector3 &p_point, GodotCollisionObject3D **p_results, int p_max_results, int *p_result_indices) { return bvh.cull_point(p_point, p_results, p_max_results, nullptr, 0xFFFFFFFF, p_result_indices); } int GodotBroadPhase3DBVH::cull_segment(const Vector3 &p_from, const Vector3 &p_to, GodotCollisionObject3D **p_results, int p_max_results, int *p_result_indices) { return bvh.cull_segment(p_from, p_to, p_results, p_max_results, nullptr, 0xFFFFFFFF, p_result_indices); } int GodotBroadPhase3DBVH::cull_aabb(const AABB &p_aabb, GodotCollisionObject3D **p_results, int p_max_results, int *p_result_indices) { return bvh.cull_aabb(p_aabb, p_results, p_max_results, nullptr, 0xFFFFFFFF, p_result_indices); } void *GodotBroadPhase3DBVH::_pair_callback(void *self, uint32_t p_A, GodotCollisionObject3D *p_object_A, int subindex_A, uint32_t p_B, GodotCollisionObject3D *p_object_B, int subindex_B) { GodotBroadPhase3DBVH *bpo = (GodotBroadPhase3DBVH *)(self); if (!bpo->pair_callback) { return nullptr; } return bpo->pair_callback(p_object_A, subindex_A, p_object_B, subindex_B, bpo->pair_userdata); } void GodotBroadPhase3DBVH::_unpair_callback(void *self, uint32_t p_A, GodotCollisionObject3D *p_object_A, int subindex_A, uint32_t p_B, GodotCollisionObject3D *p_object_B, int subindex_B, void *pairdata) { GodotBroadPhase3DBVH *bpo = (GodotBroadPhase3DBVH *)(self); if (!bpo->unpair_callback) { return; } bpo->unpair_callback(p_object_A, subindex_A, p_object_B, subindex_B, pairdata, bpo->unpair_userdata); } void GodotBroadPhase3DBVH::set_pair_callback(PairCallback p_pair_callback, void *p_userdata) { pair_callback = p_pair_callback; pair_userdata = p_userdata; } void GodotBroadPhase3DBVH::set_unpair_callback(UnpairCallback p_unpair_callback, void *p_userdata) { unpair_callback = p_unpair_callback; unpair_userdata = p_userdata; } void GodotBroadPhase3DBVH::update() { bvh.update(); } GodotBroadPhase3D *GodotBroadPhase3DBVH::_create() { return memnew(GodotBroadPhase3DBVH); } GodotBroadPhase3DBVH::GodotBroadPhase3DBVH() { bvh.set_pair_callback(_pair_callback, this); bvh.set_unpair_callback(_unpair_callback, this); }
{ "content_hash": "32f1c9ade79adec3fa841b8795fc707c", "timestamp": "", "source": "github", "line_count": 122, "max_line_length": 205, "avg_line_length": 47.27049180327869, "alnum_prop": 0.6271891798161956, "repo_name": "Faless/godot", "id": "ecdf74fd416369db72646d66beb2dac63500b5ea", "size": "5767", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "servers/physics_3d/godot_broad_phase_3d_bvh.cpp", "mode": "33188", "license": "mit", "language": [ { "name": "AIDL", "bytes": "1633" }, { "name": "C", "bytes": "820090" }, { "name": "C#", "bytes": "954253" }, { "name": "C++", "bytes": "36679303" }, { "name": "CMake", "bytes": "538" }, { "name": "GAP", "bytes": "62" }, { "name": "GDScript", "bytes": "59146" }, { "name": "GLSL", "bytes": "802565" }, { "name": "Java", "bytes": "512268" }, { "name": "JavaScript", "bytes": "184665" }, { "name": "Kotlin", "bytes": "16172" }, { "name": "Makefile", "bytes": "1421" }, { "name": "Objective-C", "bytes": "20550" }, { "name": "Objective-C++", "bytes": "315906" }, { "name": "PowerShell", "bytes": "2713" }, { "name": "Python", "bytes": "427946" }, { "name": "Shell", "bytes": "27482" } ], "symlink_target": "" }
@implementation Test2 @end
{ "content_hash": "80e4d5cea342de3b5344a83868042cec", "timestamp": "", "source": "github", "line_count": 3, "max_line_length": 21, "avg_line_length": 9.333333333333334, "alnum_prop": 0.7857142857142857, "repo_name": "wzhilong/ZLDB", "id": "07e9f563f53ffec4f1f6b46811dab789e464ac20", "size": "168", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "ZLDB/Classes/Test2.m", "mode": "33188", "license": "mit", "language": [ { "name": "Objective-C", "bytes": "6730" }, { "name": "Ruby", "bytes": "6480" } ], "symlink_target": "" }
import java.util.Random; class UnsatMultiplication04 { public static void main(String args[]) { Random r = new Random(); int i = r.nextInt(); if (i > 0) assert (i*-1 >= 0); } }
{ "content_hash": "a8203b8e9db0f68c18ad1b86607effd2", "timestamp": "", "source": "github", "line_count": 10, "max_line_length": 42, "avg_line_length": 20, "alnum_prop": 0.585, "repo_name": "jayhorn/jayhorn", "id": "bf8b615d1b4e745c94b06f8d9d9dd010129867ff", "size": "200", "binary": false, "copies": "1", "ref": "refs/heads/devel", "path": "jayhorn/src/test/resources/horn-encoding/nonlinear/UnsatMultiplication04.java", "mode": "33188", "license": "mit", "language": [ { "name": "Dockerfile", "bytes": "198" }, { "name": "Java", "bytes": "1461733" }, { "name": "Makefile", "bytes": "162" }, { "name": "Shell", "bytes": "1819" } ], "symlink_target": "" }
import unittest import frappe from frappe.utils import now_datetime from frappe.model.naming import getseries from frappe.model.naming import append_number_if_name_exists, revert_series_if_last from frappe.model.naming import determine_consecutive_week_number, parse_naming_series class TestNaming(unittest.TestCase): def setUp(self): frappe.db.delete('Note') def tearDown(self): frappe.db.rollback() def test_append_number_if_name_exists(self): ''' Append number to name based on existing values if Bottle exists Bottle -> Bottle-1 if Bottle-1 exists Bottle -> Bottle-2 ''' note = frappe.new_doc('Note') note.title = 'Test' note.insert() title2 = append_number_if_name_exists('Note', 'Test') self.assertEqual(title2, 'Test-1') title2 = append_number_if_name_exists('Note', 'Test', 'title', '_') self.assertEqual(title2, 'Test_1') def test_format_autoname(self): ''' Test if braced params are replaced in format autoname ''' doctype = 'ToDo' todo_doctype = frappe.get_doc('DocType', doctype) todo_doctype.autoname = 'format:TODO-{MM}-{status}-{##}' todo_doctype.save() description = 'Format' todo = frappe.new_doc(doctype) todo.description = description todo.insert() series = getseries('', 2) series = str(int(series)-1) if len(series) < 2: series = '0' + series self.assertEqual(todo.name, 'TODO-{month}-{status}-{series}'.format( month=now_datetime().strftime('%m'), status=todo.status, series=series)) def test_format_autoname_for_consecutive_week_number(self): ''' Test if braced params are replaced for consecutive week number in format autoname ''' doctype = 'ToDo' todo_doctype = frappe.get_doc('DocType', doctype) todo_doctype.autoname = 'format:TODO-{WW}-{##}' todo_doctype.save() description = 'Format' todo = frappe.new_doc(doctype) todo.description = description todo.insert() series = getseries('', 2) series = str(int(series)-1) if len(series) < 2: series = '0' + series week = determine_consecutive_week_number(now_datetime()) self.assertEqual(todo.name, 'TODO-{week}-{series}'.format( week=week, series=series)) def test_revert_series(self): from datetime import datetime year = datetime.now().year series = 'TEST-{}-'.format(year) key = 'TEST-.YYYY.-' name = 'TEST-{}-00001'.format(year) frappe.db.sql("""INSERT INTO `tabSeries` (name, current) values (%s, 1)""", (series,)) revert_series_if_last(key, name) current_index = frappe.db.sql("""SELECT current from `tabSeries` where name = %s""", series, as_dict=True)[0] self.assertEqual(current_index.get('current'), 0) frappe.db.delete("Series", {"name": series}) series = 'TEST-{}-'.format(year) key = 'TEST-.YYYY.-.#####' name = 'TEST-{}-00002'.format(year) frappe.db.sql("""INSERT INTO `tabSeries` (name, current) values (%s, 2)""", (series,)) revert_series_if_last(key, name) current_index = frappe.db.sql("""SELECT current from `tabSeries` where name = %s""", series, as_dict=True)[0] self.assertEqual(current_index.get('current'), 1) frappe.db.delete("Series", {"name": series}) series = 'TEST-' key = 'TEST-' name = 'TEST-00003' frappe.db.delete("Series", {"name": series}) frappe.db.sql("""INSERT INTO `tabSeries` (name, current) values (%s, 3)""", (series,)) revert_series_if_last(key, name) current_index = frappe.db.sql("""SELECT current from `tabSeries` where name = %s""", series, as_dict=True)[0] self.assertEqual(current_index.get('current'), 2) frappe.db.delete("Series", {"name": series}) series = 'TEST1-' key = 'TEST1-.#####.-2021-22' name = 'TEST1-00003-2021-22' frappe.db.delete("Series", {"name": series}) frappe.db.sql("""INSERT INTO `tabSeries` (name, current) values (%s, 3)""", (series,)) revert_series_if_last(key, name) current_index = frappe.db.sql("""SELECT current from `tabSeries` where name = %s""", series, as_dict=True)[0] self.assertEqual(current_index.get('current'), 2) frappe.db.delete("Series", {"name": series}) series = '' key = '.#####.-2021-22' name = '00003-2021-22' frappe.db.delete("Series", {"name": series}) frappe.db.sql("""INSERT INTO `tabSeries` (name, current) values (%s, 3)""", (series,)) revert_series_if_last(key, name) current_index = frappe.db.sql("""SELECT current from `tabSeries` where name = %s""", series, as_dict=True)[0] self.assertEqual(current_index.get('current'), 2) frappe.db.delete("Series", {"name": series}) def test_naming_for_cancelled_and_amended_doc(self): submittable_doctype = frappe.get_doc({ "doctype": "DocType", "module": "Core", "custom": 1, "is_submittable": 1, "permissions": [{ "role": "System Manager", "read": 1 }], "name": 'Submittable Doctype' }).insert(ignore_if_duplicate=True) doc = frappe.new_doc('Submittable Doctype') doc.save() original_name = doc.name doc.submit() doc.cancel() cancelled_name = doc.name self.assertEqual(cancelled_name, original_name) amended_doc = frappe.copy_doc(doc) amended_doc.docstatus = 0 amended_doc.amended_from = doc.name amended_doc.save() self.assertEqual(amended_doc.name, "{}-1".format(original_name)) amended_doc.submit() amended_doc.cancel() self.assertEqual(amended_doc.name, "{}-1".format(original_name)) submittable_doctype.delete() def test_determine_consecutive_week_number(self): from datetime import datetime dt = datetime.fromisoformat("2019-12-31") w = determine_consecutive_week_number(dt) self.assertEqual(w, "53") dt = datetime.fromisoformat("2020-01-01") w = determine_consecutive_week_number(dt) self.assertEqual(w, "01") dt = datetime.fromisoformat("2020-01-15") w = determine_consecutive_week_number(dt) self.assertEqual(w, "03") dt = datetime.fromisoformat("2021-01-01") w = determine_consecutive_week_number(dt) self.assertEqual(w, "00") dt = datetime.fromisoformat("2021-12-31") w = determine_consecutive_week_number(dt) self.assertEqual(w, "52") def test_naming_validations(self): # case 1: check same name as doctype # set name via prompt tag = frappe.get_doc({ 'doctype': 'Tag', '__newname': 'Tag' }) self.assertRaises(frappe.NameError, tag.insert) # set by passing set_name as ToDo self.assertRaises(frappe.NameError, make_invalid_todo) # set new name - Note note = frappe.get_doc({ 'doctype': 'Note', 'title': 'Note' }) self.assertRaises(frappe.NameError, note.insert) # case 2: set name with "New ---" tag = frappe.get_doc({ 'doctype': 'Tag', '__newname': 'New Tag' }) self.assertRaises(frappe.NameError, tag.insert) # case 3: set name with special characters tag = frappe.get_doc({ 'doctype': 'Tag', '__newname': 'Tag<>' }) self.assertRaises(frappe.NameError, tag.insert) # case 4: no name specified tag = frappe.get_doc({ 'doctype': 'Tag', '__newname': '' }) self.assertRaises(frappe.ValidationError, tag.insert) def test_autoincremented_naming(self): from frappe.core.doctype.doctype.test_doctype import new_doctype doctype = "autoinc_doctype" + frappe.generate_hash(length=5) dt = new_doctype(doctype, autoincremented=True).insert(ignore_permissions=True) for i in range(1, 20): self.assertEqual(frappe.new_doc(doctype).save(ignore_permissions=True).name, i) dt.delete(ignore_permissions=True) def make_invalid_todo(): frappe.get_doc({ 'doctype': 'ToDo', 'description': 'Test' }).insert(set_name='ToDo')
{ "content_hash": "650893b9221082446782d78c425fe6fe", "timestamp": "", "source": "github", "line_count": 261, "max_line_length": 111, "avg_line_length": 28.71264367816092, "alnum_prop": 0.6714705097411262, "repo_name": "mhbu50/frappe", "id": "0c5387ccf2c83a167d9d4187194d9b6915daacd9", "size": "7592", "binary": false, "copies": "1", "ref": "refs/heads/develop", "path": "frappe/tests/test_naming.py", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "67734" }, { "name": "HTML", "bytes": "247122" }, { "name": "JavaScript", "bytes": "2359670" }, { "name": "Less", "bytes": "25489" }, { "name": "Makefile", "bytes": "99" }, { "name": "Python", "bytes": "3464477" }, { "name": "SCSS", "bytes": "248877" }, { "name": "Shell", "bytes": "3505" }, { "name": "Vue", "bytes": "96912" } ], "symlink_target": "" }