text
stringlengths
2
1.04M
meta
dict
package org.apache.catalina.util; import java.io.Serializable; import java.net.MalformedURLException; /** * <p><strong>URL</strong> is designed to provide public APIs for parsing * and synthesizing Uniform Resource Locators as similar as possible to the * APIs of <code>java.net.URL</code>, but without the ability to open a * stream or connection. One of the consequences of this is that you can * construct URLs for protocols for which a URLStreamHandler is not * available (such as an "https" URL when JSSE is not installed).</p> * * <p><strong>WARNING</strong> - This class assumes that the string * representation of a URL conforms to the <code>spec</code> argument * as described in RFC 2396 "Uniform Resource Identifiers: Generic Syntax": * <pre> * &lt;scheme&gt;//&lt;authority&gt;&lt;path&gt;?&lt;query&gt;#&lt;fragment&gt; * </pre></p> * * <p><strong>FIXME</strong> - This class really ought to end up in a Commons * package someplace.</p> * * @author Craig R. McClanahan * */ public final class URL implements Serializable { // ----------------------------------------------------------- Constructors /** * Create a URL object from the specified String representation. * * @param spec String representation of the URL * * @exception MalformedURLException if the string representation * cannot be parsed successfully */ public URL(String spec) throws MalformedURLException { this(null, spec); } /** * Create a URL object by parsing a string representation relative * to a specified context. Based on logic from JDK 1.3.1's * <code>java.net.URL</code>. * * @param context URL against which the relative representation * is resolved * @param spec String representation of the URL (usually relative) * * @exception MalformedURLException if the string representation * cannot be parsed successfully */ public URL(URL context, String spec) throws MalformedURLException { String original = spec; int i, limit, c; int start = 0; String newProtocol = null; boolean aRef = false; try { // Eliminate leading and trailing whitespace limit = spec.length(); while ((limit > 0) && (spec.charAt(limit - 1) <= ' ')) { limit--; } while ((start < limit) && (spec.charAt(start) <= ' ')) { start++; } // If the string representation starts with "url:", skip it if (spec.regionMatches(true, start, "url:", 0, 4)) { start += 4; } // Is this a ref relative to the context URL? if ((start < spec.length()) && (spec.charAt(start) == '#')) { aRef = true; } // Parse out the new protocol for (i = start; !aRef && (i < limit) && ((c = spec.charAt(i)) != '/'); i++) { if (c == ':') { String s = spec.substring(start, i).toLowerCase(); // Assume all protocols are valid newProtocol = s; start = i + 1; break; } } // Only use our context if the protocols match protocol = newProtocol; if ((context != null) && ((newProtocol == null) || newProtocol.equalsIgnoreCase(context.getProtocol()))) { // If the context is a hierarchical URL scheme and the spec // contains a matching scheme then maintain backwards // compatibility and treat it as if the spec didn't contain // the scheme; see 5.2.3 of RFC2396 if ((context.getPath() != null) && (context.getPath().startsWith("/"))) newProtocol = null; if (newProtocol == null) { protocol = context.getProtocol(); authority = context.getAuthority(); userInfo = context.getUserInfo(); host = context.getHost(); port = context.getPort(); file = context.getFile(); int question = file.lastIndexOf("?"); if (question < 0) path = file; else path = file.substring(0, question); } } if (protocol == null) throw new MalformedURLException("no protocol: " + original); // Parse out any ref portion of the spec i = spec.indexOf('#', start); if (i >= 0) { ref = spec.substring(i + 1, limit); limit = i; } // Parse the remainder of the spec in a protocol-specific fashion parse(spec, start, limit); if (context != null) normalize(); } catch (MalformedURLException e) { throw e; } catch (Exception e) { throw new MalformedURLException(e.toString()); } } /** * Create a URL object from the specified components. The default port * number for the specified protocol will be used. * * @param protocol Name of the protocol to use * @param host Name of the host addressed by this protocol * @param file Filename on the specified host * * @exception MalformedURLException is never thrown, but present for * compatible APIs */ public URL(String protocol, String host, String file) throws MalformedURLException { this(protocol, host, -1, file); } /** * Create a URL object from the specified components. Specifying a port * number of -1 indicates that the URL should use the default port for * that protocol. Based on logic from JDK 1.3.1's * <code>java.net.URL</code>. * * @param protocol Name of the protocol to use * @param host Name of the host addressed by this protocol * @param port Port number, or -1 for the default port for this protocol * @param file Filename on the specified host * * @exception MalformedURLException is never thrown, but present for * compatible APIs */ public URL(String protocol, String host, int port, String file) throws MalformedURLException { this.protocol = protocol; this.host = host; this.port = port; int hash = file.indexOf('#'); this.file = hash < 0 ? file : file.substring(0, hash); this.ref = hash < 0 ? null : file.substring(hash + 1); int question = file.lastIndexOf('?'); if (question >= 0) { query = file.substring(question + 1); path = file.substring(0, question); } else path = file; if ((host != null) && (host.length() > 0)) authority = (port == -1) ? host : host + ":" + port; } // ----------------------------------------------------- Instance Variables /** * The authority part of the URL. */ private String authority = null; /** * The filename part of the URL. */ private String file = null; /** * The host name part of the URL. */ private String host = null; /** * The path part of the URL. */ private String path = null; /** * The port number part of the URL. */ private int port = -1; /** * The protocol name part of the URL. */ private String protocol = null; /** * The query part of the URL. */ private String query = null; /** * The reference part of the URL. */ private String ref = null; /** * The user info part of the URL. */ private String userInfo = null; // --------------------------------------------------------- Public Methods /** * Compare two URLs for equality. The result is <code>true</code> if and * only if the argument is not null, and is a <code>URL</code> object * that represents the same <code>URL</code> as this object. Two * <code>URLs</code> are equal if they have the same protocol and * reference the same host, the same port number on the host, * and the same file and anchor on the host. * * @param obj The URL to compare against */ public boolean equals(Object obj) { if (obj == null) return (false); if (!(obj instanceof URL)) return (false); URL other = (URL) obj; if (!sameFile(other)) return (false); return (compare(ref, other.getRef())); } /** * Return the authority part of the URL. */ public String getAuthority() { return (this.authority); } /** * Return the filename part of the URL. <strong>NOTE</strong> - For * compatibility with <code>java.net.URL</code>, this value includes * the query string if there was one. For just the path portion, * call <code>getPath()</code> instead. */ public String getFile() { if (file == null) return (""); return (this.file); } /** * Return the host name part of the URL. */ public String getHost() { return (this.host); } /** * Return the path part of the URL. */ public String getPath() { if (this.path == null) return (""); return (this.path); } /** * Return the port number part of the URL. */ public int getPort() { return (this.port); } /** * Return the protocol name part of the URL. */ public String getProtocol() { return (this.protocol); } /** * Return the query part of the URL. */ public String getQuery() { return (this.query); } /** * Return the reference part of the URL. */ public String getRef() { return (this.ref); } /** * Return the user info part of the URL. */ public String getUserInfo() { return (this.userInfo); } /** * Normalize the <code>path</code> (and therefore <code>file</code>) * portions of this URL. * <p> * <strong>NOTE</strong> - This method is not part of the public API * of <code>java.net.URL</code>, but is provided as a value added * service of this implementation. * * @exception MalformedURLException if a normalization error occurs, * such as trying to move about the hierarchical root */ public void normalize() throws MalformedURLException { // Special case for null path if (path == null) { if (query != null) file = "?" + query; else file = ""; return; } // Create a place for the normalized path String normalized = path; if (normalized.equals("/.")) { path = "/"; if (query != null) file = path + "?" + query; else file = path; return; } // Normalize the slashes and add leading slash if necessary if (normalized.indexOf('\\') >= 0) normalized = normalized.replace('\\', '/'); if (!normalized.startsWith("/")) normalized = "/" + normalized; // Resolve occurrences of "//" in the normalized path while (true) { int index = normalized.indexOf("//"); if (index < 0) break; normalized = normalized.substring(0, index) + normalized.substring(index + 1); } // Resolve occurrences of "/./" in the normalized path while (true) { int index = normalized.indexOf("/./"); if (index < 0) break; normalized = normalized.substring(0, index) + normalized.substring(index + 2); } // Resolve occurrences of "/../" in the normalized path while (true) { int index = normalized.indexOf("/../"); if (index < 0) break; if (index == 0) throw new MalformedURLException ("Invalid relative URL reference"); int index2 = normalized.lastIndexOf('/', index - 1); normalized = normalized.substring(0, index2) + normalized.substring(index + 3); } // Resolve occurrences of "/." at the end of the normalized path if (normalized.endsWith("/.")) normalized = normalized.substring(0, normalized.length() - 1); // Resolve occurrences of "/.." at the end of the normalized path if (normalized.endsWith("/..")) { int index = normalized.length() - 3; int index2 = normalized.lastIndexOf('/', index - 1); if (index2 < 0) throw new MalformedURLException ("Invalid relative URL reference"); normalized = normalized.substring(0, index2 + 1); } // Return the normalized path that we have completed path = normalized; if (query != null) file = path + "?" + query; else file = path; } /** * Compare two URLs, excluding the "ref" fields. Returns <code>true</code> * if this <code>URL</code> and the <code>other</code> argument both refer * to the same resource. The two <code>URLs</code> might not both contain * the same anchor. */ public boolean sameFile(URL other) { if (!compare(protocol, other.getProtocol())) return (false); if (!compare(host, other.getHost())) return (false); if (port != other.getPort()) return (false); if (!compare(file, other.getFile())) return (false); return (true); } /** * Return a string representation of this URL. This follow the rules in * RFC 2396, Section 5.2, Step 7. */ public String toExternalForm() { StringBuffer sb = new StringBuffer(); if (protocol != null) { sb.append(protocol); sb.append(":"); } if (authority != null) { sb.append("//"); sb.append(authority); } if (path != null) sb.append(path); if (query != null) { sb.append('?'); sb.append(query); } if (ref != null) { sb.append('#'); sb.append(ref); } return (sb.toString()); } /** * Return a string representation of this object. */ public String toString() { StringBuffer sb = new StringBuffer("URL["); sb.append("authority="); sb.append(authority); sb.append(", file="); sb.append(file); sb.append(", host="); sb.append(host); sb.append(", port="); sb.append(port); sb.append(", protocol="); sb.append(protocol); sb.append(", query="); sb.append(query); sb.append(", ref="); sb.append(ref); sb.append(", userInfo="); sb.append(userInfo); sb.append("]"); return (sb.toString()); // return (toExternalForm()); } // -------------------------------------------------------- Private Methods /** * Compare to String values for equality, taking appropriate care if one * or both of the values are <code>null</code>. * * @param first First string * @param second Second string */ private boolean compare(String first, String second) { if (first == null) { if (second == null) return (true); else return (false); } else { if (second == null) return (false); else return (first.equals(second)); } } /** * Parse the specified portion of the string representation of a URL, * assuming that it has a format similar to that for <code>http</code>. * * <p><strong>FIXME</strong> - This algorithm can undoubtedly be optimized * for performance. However, that needs to wait until after sufficient * unit tests are implemented to guarantee correct behavior with no * regressions.</p> * * @param spec String representation being parsed * @param start Starting offset, which will be just after the ':' (if * there is one) that determined the protocol name * @param limit Ending position, which will be the position of the '#' * (if there is one) that delimited the anchor * * @exception MalformedURLException if a parsing error occurs */ private void parse(String spec, int start, int limit) throws MalformedURLException { // Trim the query string (if any) off the tail end int question = spec.lastIndexOf('?', limit - 1); if ((question >= 0) && (question < limit)) { query = spec.substring(question + 1, limit); limit = question; } else { query = null; } // Parse the authority section if (spec.indexOf("//", start) == start) { int pathStart = spec.indexOf("/", start + 2); if ((pathStart >= 0) && (pathStart < limit)) { authority = spec.substring(start + 2, pathStart); start = pathStart; } else { authority = spec.substring(start + 2, limit); start = limit; } if (authority.length() > 0) { int at = authority.indexOf('@'); if( at >= 0 ) { userInfo = authority.substring(0,at); } int colon = authority.indexOf(':',at+1); if (colon >= 0) { try { port = Integer.parseInt(authority.substring(colon + 1)); } catch (NumberFormatException e) { throw new MalformedURLException(e.toString()); } host = authority.substring(at+1, colon); } else { host = authority.substring(at+1); port = -1; } } } // Parse the path section if (spec.indexOf("/", start) == start) { // Absolute path path = spec.substring(start, limit); if (query != null) file = path + "?" + query; else file = path; return; } // Resolve relative path against our context's file if (path == null) { if (query != null) file = "?" + query; else file = null; return; } if (!path.startsWith("/")) throw new MalformedURLException ("Base path does not start with '/'"); if (!path.endsWith("/")) path += "/../"; path += spec.substring(start, limit); if (query != null) file = path + "?" + query; else file = path; return; } }
{ "content_hash": "5a590ff76b21108102d4b52fdc4732f2", "timestamp": "", "source": "github", "line_count": 693, "max_line_length": 81, "avg_line_length": 28.382395382395384, "alnum_prop": 0.5134475570695002, "repo_name": "plumer/codana", "id": "f2bcef0264639aec6f4cf995eec7789dbdb2a15c", "size": "20473", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "tomcat_files/6.0.43/URL.java", "mode": "33188", "license": "mit", "language": [ { "name": "Java", "bytes": "101920653" }, { "name": "Python", "bytes": "58358" } ], "symlink_target": "" }
namespace net { class DrainableIOBuffer; class IOBuffer; class IOBufferWithSize; } // namespace net namespace gcm { // A helper class for interacting with a mojo consumer pipe that is receiving // protobuf encoded messages. If an error is encounters, the input stream will // store the error in |last_error_|, and GetState() will be set to CLOSED. // Typical usage: // 1. Check the GetState() of the input stream before using it. If CLOSED, the // input stream must be rebuilt (and the socket likely needs to be // reconnected as an error was encountered). // 2. If GetState() is EMPTY, call Refresh(..), passing the maximum byte size // for a message, and wait until completion. It is invalid to attempt to // Refresh an input stream or read data from the stream while a Refresh is // pending. // 3. Check GetState() again to ensure the Refresh was successful. // 4. Use a CodedInputStream to read from the ZeroCopyInputStream interface of // the SocketInputStream. Next(..) will return true until there is no data // remaining. // 5. Call RebuildBuffer when done reading, to shift any unread data to the // start of the buffer. // 6. Repeat as necessary. class GCM_EXPORT SocketInputStream : public google::protobuf::io::ZeroCopyInputStream { public: enum State { // No valid data to read. This means the buffer is either empty or all data // in the buffer has already been consumed. EMPTY, // Valid data to read. READY, // In the process of reading new data from the socket. READING, // An permanent error occurred and the stream is now closed. CLOSED, }; // |socket| should already be connected. explicit SocketInputStream(mojo::ScopedDataPipeConsumerHandle stream); ~SocketInputStream() override; // ZeroCopyInputStream implementation. bool Next(const void** data, int* size) override; void BackUp(int count) override; bool Skip(int count) override; // Not implemented. int64_t ByteCount() const override; // The remaining amount of valid data available to be read. int UnreadByteCount() const; // Reads from the socket, appending a max of |byte_limit| bytes onto the read // buffer. net::ERR_IO_PENDING is returned if the refresh can't complete // synchronously, in which case the callback is invoked upon completion. If // the refresh can complete synchronously, even in case of an error, returns // net::OK without invoking callback. // Note: GetState() (and possibly last_error()) should be checked upon // completion to determine whether the Refresh encountered an error. net::Error Refresh(base::OnceClosure callback, int byte_limit); // Rebuilds the buffer state by copying over any unread data to the beginning // of the buffer and resetting the buffer read/write positions. // Note: it is not valid to call Rebuild() if GetState() == CLOSED. The stream // must be recreated from scratch in such a scenario. void RebuildBuffer(); // Returns the last fatal error encountered. Only valid if GetState() == // CLOSED. Note that all network read errors will be reported as // net::ERR_FAILED, because mojo data pipe doesn't allow surfacing a more // specific error code. net::Error last_error() const; // Returns the current state. State GetState() const; private: // Clears the local state. void ResetInternal(); void ReadMore(MojoResult result, const mojo::HandleSignalsState& state); // Permanently closes the stream. void CloseStream(net::Error error); // Internal net components. mojo::ScopedDataPipeConsumerHandle stream_; mojo::SimpleWatcher stream_watcher_; uint32_t read_size_; const scoped_refptr<net::IOBuffer> io_buffer_; base::OnceClosure read_callback_; // IOBuffer implementation that wraps the data within |io_buffer_| that hasn't // been written to yet by Socket::Read calls. const scoped_refptr<net::DrainableIOBuffer> read_buffer_; // Starting position of the data within |io_buffer_| to consume on subsequent // Next(..) call. 0 <= next_pos_ <= read_buffer_.BytesConsumed() // Note: next_pos == read_buffer_.BytesConsumed() implies GetState() == EMPTY. int next_pos_; // If < net::ERR_IO_PENDING, the last net error received. // Note: last_error_ == net::ERR_IO_PENDING implies GetState() == READING. net::Error last_error_; base::WeakPtrFactory<SocketInputStream> weak_ptr_factory_{this}; DISALLOW_COPY_AND_ASSIGN(SocketInputStream); }; // A helper class for writing to a mojo producer handle with protobuf encoded // data. Typical usage: // 1. Check the GetState() of the output stream before using it. If CLOSED, the // output stream must be rebuilt (and the socket likely needs to be // reconnected, as an error was encountered). // 2. If EMPTY, the output stream can be written via a CodedOutputStream using // the ZeroCopyOutputStream interface. // 3. Once done writing, GetState() should be READY, so call Flush(..) to write // the buffer into the mojo producer handle. Wait for the callback to be // invoked (it's invalid to write to an output stream while it's flushing). // 4. Check the GetState() again to ensure the Flush was successful. GetState() // should be EMPTY again. // 5. Repeat. class GCM_EXPORT SocketOutputStream : public google::protobuf::io::ZeroCopyOutputStream { public: enum State { // No valid data yet. EMPTY, // Ready for flushing (some data is present). READY, // In the process of flushing into the socket. FLUSHING, // A permanent error occurred, and the stream is now closed. CLOSED, }; explicit SocketOutputStream(mojo::ScopedDataPipeProducerHandle stream); ~SocketOutputStream() override; // ZeroCopyOutputStream implementation. bool Next(void** data, int* size) override; void BackUp(int count) override; int64_t ByteCount() const override; // Writes the buffer into the Socket. net::Error Flush(base::OnceClosure callback); // Returns the last fatal error encountered. Only valid if GetState() == // CLOSED. Note that All network read errors will be reported as // net::ERR_FAILED, because mojo data pipe doesn't allow surfacing a more // specific error code. net::Error last_error() const; // Returns the current state. State GetState() const; private: void WriteMore(MojoResult result, const mojo::HandleSignalsState& state); // Internal net components. mojo::ScopedDataPipeProducerHandle stream_; mojo::SimpleWatcher stream_watcher_; base::OnceClosure write_callback_; const scoped_refptr<net::IOBufferWithSize> io_buffer_; // IOBuffer implementation that wraps the data within |io_buffer_| that hasn't // been written to the socket yet. scoped_refptr<net::DrainableIOBuffer> write_buffer_; // Starting position of the data within |io_buffer_| to consume on subsequent // Next(..) call. 0 <= write_buffer_.BytesConsumed() <= next_pos_ // Note: next_pos == 0 implies GetState() == EMPTY. int next_pos_; // If < net::ERR_IO_PENDING, the last net error received. // Note: last_error_ == net::ERR_IO_PENDING implies GetState() == FLUSHING. net::Error last_error_; base::WeakPtrFactory<SocketOutputStream> weak_ptr_factory_{this}; DISALLOW_COPY_AND_ASSIGN(SocketOutputStream); }; } // namespace gcm #endif // GOOGLE_APIS_GCM_BASE_SOCKET_STREAM_H_
{ "content_hash": "bc9c15f3126195926f74ab8d268ce13f", "timestamp": "", "source": "github", "line_count": 187, "max_line_length": 80, "avg_line_length": 39.31550802139037, "alnum_prop": 0.719804134929271, "repo_name": "endlessm/chromium-browser", "id": "109f4168d9e8455e5fde54412f87624b7ae07c6a", "size": "8190", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "google_apis/gcm/base/socket_stream.h", "mode": "33188", "license": "bsd-3-clause", "language": [], "symlink_target": "" }
/*-------------distributions.h------------------------------------------------// * * Purpose: to hold all possible distributions for SDL and OGL stuff * *-----------------------------------------------------------------------------*/ #ifndef DIST_H #define DIST_H #include "../include/GL_setup.h" // STD functions void std_key(Param &par, SDL_Keysym* Keysym, bool is_down); void std_fn(Param &par); void std_par(Param &par); void std_OGL(Param &par); // test pend functions void platformer_key(Param &par, SDL_Keysym* Keysym, bool is_down); void platformer_fn(Param &par); void platformer_par(Param &par); void platformer_OGL(Param &par); #endif
{ "content_hash": "6d1b1a022b5c1978a707fd7e9311a80f", "timestamp": "", "source": "github", "line_count": 24, "max_line_length": 80, "avg_line_length": 27.125, "alnum_prop": 0.5622119815668203, "repo_name": "leios/SciVL", "id": "f9a84cbab983407df94a96b3599a38d8893cc8d4", "size": "651", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "include/distributions.h", "mode": "33188", "license": "mit", "language": [ { "name": "C", "bytes": "7560" }, { "name": "C++", "bytes": "193088" }, { "name": "GLSL", "bytes": "333" }, { "name": "Makefile", "bytes": "989" }, { "name": "Shell", "bytes": "496" } ], "symlink_target": "" }
package com.amazonaws.services.lightsail.model; import javax.annotation.Generated; /** * */ @Generated("com.amazonaws:aws-java-sdk-code-generator") public enum MetricUnit { Seconds("Seconds"), Microseconds("Microseconds"), Milliseconds("Milliseconds"), Bytes("Bytes"), Kilobytes("Kilobytes"), Megabytes("Megabytes"), Gigabytes("Gigabytes"), Terabytes("Terabytes"), Bits("Bits"), Kilobits("Kilobits"), Megabits("Megabits"), Gigabits("Gigabits"), Terabits("Terabits"), Percent("Percent"), Count("Count"), BytesSecond("Bytes/Second"), KilobytesSecond("Kilobytes/Second"), MegabytesSecond("Megabytes/Second"), GigabytesSecond("Gigabytes/Second"), TerabytesSecond("Terabytes/Second"), BitsSecond("Bits/Second"), KilobitsSecond("Kilobits/Second"), MegabitsSecond("Megabits/Second"), GigabitsSecond("Gigabits/Second"), TerabitsSecond("Terabits/Second"), CountSecond("Count/Second"), None("None"); private String value; private MetricUnit(String value) { this.value = value; } @Override public String toString() { return this.value; } /** * Use this in place of valueOf. * * @param value * real value * @return MetricUnit corresponding to the value * * @throws IllegalArgumentException * If the specified value does not map to one of the known values in this enum. */ public static MetricUnit fromValue(String value) { if (value == null || "".equals(value)) { throw new IllegalArgumentException("Value cannot be null or empty!"); } for (MetricUnit enumEntry : MetricUnit.values()) { if (enumEntry.toString().equals(value)) { return enumEntry; } } throw new IllegalArgumentException("Cannot create enum from " + value + " value!"); } }
{ "content_hash": "eca4010f65ad04456fb2adcd60db5f1c", "timestamp": "", "source": "github", "line_count": 74, "max_line_length": 91, "avg_line_length": 26.37837837837838, "alnum_prop": 0.6239754098360656, "repo_name": "jentfoo/aws-sdk-java", "id": "912868dc4464f9e2c92fabd2128143ed6e5043f3", "size": "2532", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "aws-java-sdk-lightsail/src/main/java/com/amazonaws/services/lightsail/model/MetricUnit.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Batchfile", "bytes": "270" }, { "name": "FreeMarker", "bytes": "173637" }, { "name": "Gherkin", "bytes": "25063" }, { "name": "Java", "bytes": "356214839" }, { "name": "Scilab", "bytes": "3924" }, { "name": "Shell", "bytes": "295" } ], "symlink_target": "" }
package org.apache.commons.chain2.web.portlet; import java.util.ArrayList; import java.util.Collection; import java.util.Enumeration; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import javax.portlet.PortletContext; import org.apache.commons.chain2.web.MapEntry; /** * <p>Private implementation of <code>Map</code> for portlet context * init parameters.</p> * */ final class PortletInitParamMap implements Map<String, String> { public PortletInitParamMap(PortletContext context) { this.context = context; } private final PortletContext context; public void clear() { throw new UnsupportedOperationException(); } public boolean containsKey(Object key) { return (context.getInitParameter(key(key)) != null); } public boolean containsValue(Object value) { return values().contains(value); } public Set<Entry<String, String>> entrySet() { Set<Entry<String, String>> set = new HashSet<Entry<String, String>>(); Enumeration<String> keys = context.getInitParameterNames(); String key; while (keys.hasMoreElements()) { key = keys.nextElement(); set.add(new MapEntry<String, String>(key, context.getInitParameter(key), false)); } return (set); } @Override public boolean equals(Object o) { return (context.equals(o)); } public String get(Object key) { return (context.getInitParameter(key(key))); } @Override public int hashCode() { return (context.hashCode()); } public boolean isEmpty() { return (size() < 1); } public Set<String> keySet() { Set<String> set = new HashSet<String>(); Enumeration<String> keys = context.getInitParameterNames(); while (keys.hasMoreElements()) { set.add(keys.nextElement()); } return (set); } public String put(String key, String value) { throw new UnsupportedOperationException(); } public void putAll(Map<? extends String, ? extends String> map) { throw new UnsupportedOperationException(); } public String remove(Object key) { throw new UnsupportedOperationException(); } public int size() { int n = 0; Enumeration<String> keys = context.getInitParameterNames(); while (keys.hasMoreElements()) { keys.nextElement(); n++; } return (n); } public Collection<String> values() { List<String> list = new ArrayList<String>(); Enumeration<String> keys = context.getInitParameterNames(); while (keys.hasMoreElements()) { list.add(context.getInitParameter(keys.nextElement())); } return (list); } private String key(Object key) { if (key == null) { throw new IllegalArgumentException(); } else if (key instanceof String) { return ((String) key); } else { return (key.toString()); } } }
{ "content_hash": "9bbf5fa5746d64548f2ccb92e2da83e6", "timestamp": "", "source": "github", "line_count": 119, "max_line_length": 93, "avg_line_length": 26.15126050420168, "alnum_prop": 0.6127892030848329, "repo_name": "apache/commons-chain", "id": "165dc793b243e5bef078ad742f1065f91358be1d", "size": "3913", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "web/src/main/java/org/apache/commons/chain2/web/portlet/PortletInitParamMap.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "HTML", "bytes": "15147" }, { "name": "Java", "bytes": "655989" }, { "name": "Shell", "bytes": "157" } ], "symlink_target": "" }
<?php namespace Magento\Payment\Model\Cart\SalesModel; /** * Wrapper for \Magento\Quote\Model\Quote sales model */ class Quote implements \Magento\Payment\Model\Cart\SalesModel\SalesModelInterface { /** * Sales quote model instance * * @var \Magento\Quote\Model\Quote */ protected $_salesModel; /** * @var \Magento\Quote\Model\Quote\Address */ protected $_address; /** * @param \Magento\Quote\Model\Quote $salesModel */ public function __construct(\Magento\Quote\Model\Quote $salesModel) { $this->_salesModel = $salesModel; $this->_address = $this ->_salesModel ->getIsVirtual() ? $this ->_salesModel ->getBillingAddress() : $this ->_salesModel ->getShippingAddress(); } /** * {@inheritdoc} */ public function getAllItems() { $resultItems = []; foreach ($this->_salesModel->getAllItems() as $item) { $resultItems[] = new \Magento\Framework\DataObject( [ 'parent_item' => $item->getParentItem(), 'name' => $item->getName(), 'qty' => (int)$item->getTotalQty(), 'price' => (double)$item->getBaseCalculationPrice(), 'original_item' => $item, ] ); } return $resultItems; } /** * {@inheritdoc} */ public function getBaseSubtotal() { return $this->_salesModel->getBaseSubtotal(); } /** * {@inheritdoc} */ public function getBaseTaxAmount() { return $this->_address->getBaseTaxAmount(); } /** * {@inheritdoc} */ public function getBaseShippingAmount() { return $this->_address->getBaseShippingAmount(); } /** * {@inheritdoc} */ public function getBaseDiscountAmount() { return $this->_address->getBaseDiscountAmount(); } /** * {@inheritdoc} */ public function getDataUsingMethod($key, $args = null) { return $this->_salesModel->getDataUsingMethod($key, $args); } /** * {@inheritdoc} */ public function getTaxContainer() { return $this->_salesModel ->getIsVirtual() ? $this ->_salesModel ->getBillingAddress() : $this ->_salesModel ->getShippingAddress(); } }
{ "content_hash": "edd0358d2d12ee12f4e70e1f9b6fb0f0", "timestamp": "", "source": "github", "line_count": 111, "max_line_length": 81, "avg_line_length": 22.55855855855856, "alnum_prop": 0.5163738019169329, "repo_name": "enettolima/magento-training", "id": "03a25f838e02ce4a9762f69a47ea37b854d5882c", "size": "2602", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "magento2ce/app/code/Magento/Payment/Model/Cart/SalesModel/Quote.php", "mode": "33188", "license": "mit", "language": [ { "name": "ApacheConf", "bytes": "22648" }, { "name": "CSS", "bytes": "3382928" }, { "name": "HTML", "bytes": "8749335" }, { "name": "JavaScript", "bytes": "7355635" }, { "name": "PHP", "bytes": "58607662" }, { "name": "Perl", "bytes": "10258" }, { "name": "Shell", "bytes": "41887" }, { "name": "XSLT", "bytes": "19889" } ], "symlink_target": "" }
<?php declare(strict_types=1); namespace Doctrine\ODM\MongoDB\Tests\Mocks; use Doctrine\Common\EventSubscriber; use Doctrine\ODM\MongoDB\Event\OnFlushEventArgs; use Exception; class ExceptionThrowingListenerMock implements EventSubscriber { public function getSubscribedEvents(): array { return ['onFlush']; } public function onFlush(OnFlushEventArgs $args): void { throw new Exception('This should not happen'); } }
{ "content_hash": "88df6e4199c89ff6eb6ee3d7b83a43e3", "timestamp": "", "source": "github", "line_count": 22, "max_line_length": 62, "avg_line_length": 21, "alnum_prop": 0.7272727272727273, "repo_name": "doctrine/mongodb-odm", "id": "7b1ad70be59993845681490da742324300beb599", "size": "462", "binary": false, "copies": "1", "ref": "refs/heads/2.4.x", "path": "tests/Doctrine/ODM/MongoDB/Tests/Mocks/ExceptionThrowingListenerMock.php", "mode": "33188", "license": "mit", "language": [ { "name": "PHP", "bytes": "2557841" }, { "name": "Shell", "bytes": "4972" } ], "symlink_target": "" }
FROM balenalib/intel-nuc-debian:stretch-run ENV GO_VERSION 1.15.7 # gcc for cgo RUN apt-get update && apt-get install -y --no-install-recommends \ g++ \ gcc \ libc6-dev \ make \ pkg-config \ git \ && rm -rf /var/lib/apt/lists/* RUN set -x \ && fetchDeps=' \ curl \ ' \ && apt-get update && apt-get install -y $fetchDeps --no-install-recommends && rm -rf /var/lib/apt/lists/* \ && mkdir -p /usr/local/go \ && curl -SLO "https://storage.googleapis.com/golang/go$GO_VERSION.linux-amd64.tar.gz" \ && echo "0d142143794721bb63ce6c8a6180c4062bcf8ef4715e7d6d6609f3a8282629b3 go$GO_VERSION.linux-amd64.tar.gz" | sha256sum -c - \ && tar -xzf "go$GO_VERSION.linux-amd64.tar.gz" -C /usr/local/go --strip-components=1 \ && rm -f go$GO_VERSION.linux-amd64.tar.gz ENV GOROOT /usr/local/go ENV GOPATH /go ENV PATH $GOPATH/bin:/usr/local/go/bin:$PATH RUN mkdir -p "$GOPATH/src" "$GOPATH/bin" && chmod -R 777 "$GOPATH" WORKDIR $GOPATH CMD ["echo","'No CMD command was set in Dockerfile! Details about CMD command could be found in Dockerfile Guide section in our Docs. Here's the link: https://balena.io/docs"] RUN curl -SLO "https://raw.githubusercontent.com/balena-io-library/base-images/8accad6af708fca7271c5c65f18a86782e19f877/scripts/assets/tests/[email protected]" \ && echo "Running test-stack@golang" \ && chmod +x [email protected] \ && bash [email protected] \ && rm -rf [email protected] RUN [ ! -d /.balena/messages ] && mkdir -p /.balena/messages; echo 'Here are a few details about this Docker image (For more information please visit https://www.balena.io/docs/reference/base-images/base-images/): \nArchitecture: Intel 64-bit (x86-64) \nOS: Debian Stretch \nVariant: run variant \nDefault variable(s): UDEV=off \nThe following software stack is preinstalled: \nGo v1.15.7 \nExtra features: \n- Easy way to install packages with `install_packages <package-name>` command \n- Run anywhere with cross-build feature (for ARM only) \n- Keep the container idling with `balena-idle` command \n- Show base image details with `balena-info` command' > /.balena/messages/image-info RUN echo '#!/bin/sh.real\nbalena-info\nrm -f /bin/sh\ncp /bin/sh.real /bin/sh\n/bin/sh "$@"' > /bin/sh-shim \ && chmod +x /bin/sh-shim \ && cp /bin/sh /bin/sh.real \ && mv /bin/sh-shim /bin/sh
{ "content_hash": "c149876c9d29a9659b74178ce085e527", "timestamp": "", "source": "github", "line_count": 46, "max_line_length": 688, "avg_line_length": 50.43478260869565, "alnum_prop": 0.7047413793103449, "repo_name": "nghiant2710/base-images", "id": "f6bd08a2fe856f59bf42a43c1d76ff00871e031b", "size": "2341", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "balena-base-images/golang/intel-nuc/debian/stretch/1.15.7/run/Dockerfile", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Dockerfile", "bytes": "144558581" }, { "name": "JavaScript", "bytes": "16316" }, { "name": "Shell", "bytes": "368690" } ], "symlink_target": "" }
AV-Panels ========= Mobile Web Notification Panels Library
{ "content_hash": "9414cd1f4055c79fab00d1b89b775a7f", "timestamp": "", "source": "github", "line_count": 4, "max_line_length": 38, "avg_line_length": 15, "alnum_prop": 0.7, "repo_name": "aaronalexvargas/AVPanels.Library-codesample", "id": "497ae5cada6a067e63448aa7e2b9e5fa7e891399", "size": "60", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "README.md", "mode": "33188", "license": "mit", "language": [], "symlink_target": "" }
(function () { 'use strict'; angular.module('tf-training.core', []); })();
{ "content_hash": "73280674bb8076d343210e240007fd01", "timestamp": "", "source": "github", "line_count": 6, "max_line_length": 43, "avg_line_length": 14.166666666666666, "alnum_prop": 0.5176470588235295, "repo_name": "akarienta/taskforce-training", "id": "1542b6763131bbabea6877790e5d1aae72a015f6", "size": "85", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/core/core.module.js", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "53062" }, { "name": "HTML", "bytes": "6185" }, { "name": "JavaScript", "bytes": "9616" } ], "symlink_target": "" }
package uk.org.sljo.gigsec.domain; import java.io.Serializable; import com.fasterxml.jackson.annotation.JsonIgnore; import org.hibernate.envers.Audited; import org.springframework.data.annotation.CreatedBy; import org.springframework.data.annotation.CreatedDate; import org.springframework.data.annotation.LastModifiedBy; import org.springframework.data.annotation.LastModifiedDate; import org.springframework.data.jpa.domain.support.AuditingEntityListener; import java.time.ZonedDateTime; import javax.persistence.Column; import javax.persistence.EntityListeners; import javax.persistence.MappedSuperclass; import javax.validation.constraints.NotNull; /** * Base abstract class for entities which will hold definitions for created, last modified by and created, * last modified by date. */ @MappedSuperclass @Audited @EntityListeners(AuditingEntityListener.class) public abstract class AbstractAuditingEntity implements Serializable { private static final long serialVersionUID = 1L; @CreatedBy @NotNull @Column(name = "created_by", nullable = false, length = 50, updatable = false) @JsonIgnore private String createdBy; @CreatedDate @NotNull @Column(name = "created_date", nullable = false) @JsonIgnore private ZonedDateTime createdDate = ZonedDateTime.now(); @LastModifiedBy @Column(name = "last_modified_by", length = 50) @JsonIgnore private String lastModifiedBy; @LastModifiedDate @Column(name = "last_modified_date") @JsonIgnore private ZonedDateTime lastModifiedDate = ZonedDateTime.now(); public String getCreatedBy() { return createdBy; } public void setCreatedBy(String createdBy) { this.createdBy = createdBy; } public ZonedDateTime getCreatedDate() { return createdDate; } public void setCreatedDate(ZonedDateTime createdDate) { this.createdDate = createdDate; } public String getLastModifiedBy() { return lastModifiedBy; } public void setLastModifiedBy(String lastModifiedBy) { this.lastModifiedBy = lastModifiedBy; } public ZonedDateTime getLastModifiedDate() { return lastModifiedDate; } public void setLastModifiedDate(ZonedDateTime lastModifiedDate) { this.lastModifiedDate = lastModifiedDate; } }
{ "content_hash": "a2ab08b271f58ad57a97ebf4333a2037", "timestamp": "", "source": "github", "line_count": 83, "max_line_length": 106, "avg_line_length": 28.19277108433735, "alnum_prop": 0.7431623931623932, "repo_name": "clamped/gigsec", "id": "9cf2ef0076d631c016202783889e2cc767488885", "size": "2340", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/main/java/uk/org/sljo/gigsec/domain/AbstractAuditingEntity.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "ApacheConf", "bytes": "24139" }, { "name": "CSS", "bytes": "5388" }, { "name": "Cucumber", "bytes": "161" }, { "name": "HTML", "bytes": "141423" }, { "name": "Java", "bytes": "309618" }, { "name": "JavaScript", "bytes": "191633" }, { "name": "Scala", "bytes": "10003" } ], "symlink_target": "" }
package org.apache.camel.component.leveldb; import java.util.HashMap; import java.util.Map; import org.apache.camel.AggregationStrategy; import org.apache.camel.Exchange; import org.apache.camel.builder.RouteBuilder; import org.apache.camel.component.mock.MockEndpoint; import org.apache.camel.component.util.HeaderDto; import org.apache.camel.test.junit4.CamelTestSupport; import org.junit.Before; import org.junit.Test; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class LevelDBAggregateSerializedHeadersTest extends CamelTestSupport { private static final Logger LOG = LoggerFactory.getLogger(LevelDBAggregateSerializedHeadersTest.class); private static final int SIZE = 500; private LevelDBAggregationRepository repo; @Before @Override public void setUp() throws Exception { deleteDirectory("target/data"); repo = new LevelDBAggregationRepository("repo1", "target/data/leveldb.dat"); repo.setAllowSerializedHeaders(true); super.setUp(); } @Test public void testLoadTestLevelDBAggregate() throws Exception { MockEndpoint mock = getMockEndpoint("mock:result"); mock.expectedMinimumMessageCount(1); mock.setResultWaitTime(50 * 1000); LOG.info("Staring to send " + SIZE + " messages."); for (int i = 0; i < SIZE; i++) { final int value = 1; HeaderDto headerDto = new HeaderDto("test", "company", 1); char id = 'A'; LOG.debug("Sending {} with id {}", value, id); Map<String, Object> headers = new HashMap<>(); headers.put("id", headerDto); template.sendBodyAndHeaders("seda:start?size=" + SIZE, value, headers); } LOG.info("Sending all " + SIZE + " message done. Now waiting for aggregation to complete."); assertMockEndpointsSatisfied(); } @Override protected RouteBuilder createRouteBuilder() throws Exception { return new RouteBuilder() { @Override public void configure() throws Exception { from("seda:start?size=" + SIZE) .to("log:input?groupSize=500") .aggregate(header("id"), new MyAggregationStrategy()) .aggregationRepository(repo) .completionSize(SIZE) .to("log:output?showHeaders=true") .to("mock:result") .end(); } }; } public static class MyAggregationStrategy implements AggregationStrategy { public Exchange aggregate(Exchange oldExchange, Exchange newExchange) { if (oldExchange == null) { return newExchange; } Integer body1 = oldExchange.getIn().getBody(Integer.class); Integer body2 = newExchange.getIn().getBody(Integer.class); int sum = body1 + body2; oldExchange.getIn().setBody(sum); return oldExchange; } } }
{ "content_hash": "5d25790e41591c117f4f8b159c6b1125", "timestamp": "", "source": "github", "line_count": 89, "max_line_length": 107, "avg_line_length": 34.247191011235955, "alnum_prop": 0.6246719160104987, "repo_name": "punkhorn/camel-upstream", "id": "163f522386e770baff1763ffda4c0d830a4f25b7", "size": "3851", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "components/camel-leveldb/src/test/java/org/apache/camel/component/leveldb/LevelDBAggregateSerializedHeadersTest.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Apex", "bytes": "6519" }, { "name": "Batchfile", "bytes": "1518" }, { "name": "CSS", "bytes": "16394" }, { "name": "Elm", "bytes": "10852" }, { "name": "FreeMarker", "bytes": "11410" }, { "name": "Groovy", "bytes": "14490" }, { "name": "HTML", "bytes": "896075" }, { "name": "Java", "bytes": "70312352" }, { "name": "JavaScript", "bytes": "90399" }, { "name": "Makefile", "bytes": "513" }, { "name": "Shell", "bytes": "17108" }, { "name": "Tcl", "bytes": "4974" }, { "name": "Thrift", "bytes": "6979" }, { "name": "XQuery", "bytes": "546" }, { "name": "XSLT", "bytes": "270186" } ], "symlink_target": "" }
from __future__ import absolute_import from django.contrib import messages from django.core.urlresolvers import reverse from django.db.models import Q from django.utils.translation import ugettext_lazy as _, ugettext from sentry import roles from sentry.models import OrganizationMember, OrganizationMemberTeam, \ Team, TeamStatus from sentry.utils import auth from sentry.web.frontend.base import OrganizationView from sentry.web.forms.edit_organization_member import EditOrganizationMemberForm class OrganizationMemberSettingsView(OrganizationView): def get_form(self, request, member, all_teams, allowed_roles): return EditOrganizationMemberForm( data=request.POST or None, instance=member, all_teams=all_teams, allowed_roles=allowed_roles, initial={ 'role': member.role, 'teams': Team.objects.filter( id__in=OrganizationMemberTeam.objects.filter( organizationmember=member, ).values('team'), ), }, ) def resend_invite(self, request, organization, member, regen=False): if regen: member.update(token=member.generate_token()) messages.success( request, ugettext('A new invitation has been generated and sent to %(email)s') % { 'organization': organization.name, 'email': member.email, } ) else: messages.success( request, ugettext('An invitation to join %(organization)s has been sent to %(email)s') % { 'organization': organization.name, 'email': member.email, } ) member.send_invite_email() redirect = reverse( 'sentry-organization-member-settings', args=[organization.slug, member.id] ) return self.redirect(redirect) def view_member(self, request, organization, member, all_teams): context = { 'member': member, 'enabled_teams': set(member.teams.all()), 'all_teams': all_teams, 'role_list': roles.get_all(), } return self.respond('sentry/organization-member-details.html', context) def handle(self, request, organization, member_id): try: member = OrganizationMember.objects.get( Q(user__is_active=True) | Q(user__isnull=True), organization=organization, id=member_id, ) except OrganizationMember.DoesNotExist: return self.redirect(auth.get_login_url()) if request.POST.get('op') == 'reinvite' and member.is_pending: return self.resend_invite(request, organization, member) elif request.POST.get('op') == 'regenerate' and member.is_pending: return self.resend_invite(request, organization, member, regen=True) can_admin, allowed_roles = self.get_allowed_roles(request, organization, member) all_teams = Team.objects.filter(organization=organization, status=TeamStatus.VISIBLE) if member.user == request.user or not can_admin: return self.view_member(request, organization, member, all_teams) form = self.get_form(request, member, all_teams, allowed_roles) if form.is_valid(): member = form.save(request.user, organization, request.META['REMOTE_ADDR']) messages.add_message(request, messages.SUCCESS, _('Your changes were saved.')) redirect = reverse( 'sentry-organization-member-settings', args=[organization.slug, member.id] ) return self.redirect(redirect) context = { 'member': member, 'form': form, 'invite_link': member.get_invite_link(), 'role_list': [(r, r in allowed_roles) for r in roles.get_all()], 'all_teams': all_teams } return self.respond('sentry/organization-member-settings.html', context)
{ "content_hash": "0b75422d77d285bdc95fbf0d4620726d", "timestamp": "", "source": "github", "line_count": 114, "max_line_length": 97, "avg_line_length": 36.89473684210526, "alnum_prop": 0.5905848787446505, "repo_name": "jean/sentry", "id": "114d63e7ffbbdad0510a6ab7419cf24e9bdcaceb", "size": "4206", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/sentry/web/frontend/organization_member_settings.py", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "CSS", "bytes": "296112" }, { "name": "HTML", "bytes": "314273" }, { "name": "JavaScript", "bytes": "1293918" }, { "name": "Lua", "bytes": "57158" }, { "name": "Makefile", "bytes": "6632" }, { "name": "Python", "bytes": "24515298" }, { "name": "Ruby", "bytes": "4410" }, { "name": "Shell", "bytes": "2942" } ], "symlink_target": "" }
- AngularJS - ngRoute - angular-translate ## CSS Dependencies - Bootstrap CSS - Fontawesome
{ "content_hash": "29ccbfffe55c6ee333fe118a8fcfb496", "timestamp": "", "source": "github", "line_count": 9, "max_line_length": 19, "avg_line_length": 10.555555555555555, "alnum_prop": 0.7368421052631579, "repo_name": "mmalfertheiner/pmc-layout", "id": "85b49aa133742c6dfa4488740891dba21fba4cdf", "size": "149", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "README.md", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "6923" }, { "name": "HTML", "bytes": "5763" }, { "name": "JavaScript", "bytes": "3891" } ], "symlink_target": "" }
<?php defined('BASEPATH') OR exit('No direct script access allowed'); class Api extends CI_Controller { /** * Index Page for this controller. * * Maps to the following URL * http://example.com/index.php/welcome * - or - * http://example.com/index.php/welcome/index * - or - * Since this controller is set as the default controller in * config/routes.php, it's displayed at http://example.com/ * * So any other public methods not prefixed with an underscore will * map to /index.php/welcome/<method_name> * @see http://codeigniter.com/user_guide/general/urls.html */ public function index() { $this->config->load('bot'); $botToken = $this->config->item('botToken'); $website = "https://api.telegram.org/bot".$botToken; //$last_id = intval(file_get_contents('./lastid.txt'))+1; $last_id = 1; $update = file_get_contents($website."/getupdates?offset=$last_id"); //cuando se cambie a servidor SSL hay que poner esto //$update = file_get_contents("php://input"); //y no hace falta recorrer los mensajes porque te mandan un post por mensaje echo "<pre>"; print_r(json_decode($update)); $data = json_decode($update); /* //esto es un data de ejemplo stdClass Object ( [ok] => 1 [result] => Array ( [0] => stdClass Object ( [update_id] => 911242039 [message] => stdClass Object ( [message_id] => 63 [from] => stdClass Object ( [id] => 8908013 [first_name] => Guillermo - Killer [username] => killer415 ) [chat] => stdClass Object ( [id] => -12658615 [title] => Airsoft partidas club ) [date] => 1441465223 [text] => /crearpartida ) ) */ foreach ($data->result as $key => $msg){ echo "Analyzing message $key<br>"; //datos grupo $in_group = !isset($msg->message->chat->username); $last_update_id = $msg->update_id; //solo permitimos hablar en grupo //if (!$in_group) continue; //echo "mensaje a grupo :". intval($in_group) ."<br>"; //datos mensaje $group_id = $msg->message->chat->id; $from_id = $msg->message->from->id; $from_username = $msg->message->from->username; $text = $msg->message->text; //lista de commands disponibles $commands = array( 'crearpartida' => '/(\/crearpartida)$/', 'cancelarpartida' => '/(\/cancelarpartida)$/', 'infopartida' => '/(\/infopartida)$/', ); $matches = null; foreach ($commands as $commandkey => $commandexp){ $returnValue = preg_match($commandexp, $text, $matches); //print_r($matches); if (!empty($matches)) { switch($commandkey){ case "crearpartida": echo "command $commandkey<br>"; file_get_contents($website."/sendMessage?chat_id=$group_id&text=@$from_username: command crearpartida leído"); break; case "cancelarpartida": echo "command $commandkey<br>"; file_get_contents($website."/sendMessage?chat_id=$group_id&text=@$from_username: command cerrarpartida leído."); break; case "infopartida": echo "command $commandkey<br>"; file_get_contents($website."/sendMessage?chat_id=$group_id&text=@$from_username: command infopartida leído."); break; } } $matches = null; //$last_id = file_put_contents('./lastid.txt',$last_update_id); } } } public function customKeyboard() { $this->config->load('bot'); $params = array( $this->config->item('botToken') ); $this->load->library('Telegram', $params); $option = array( array("UNO"), array("DOS"), array("TRES"), array("CUATRO"), array("CINCO"), array("SEIS"), array("SIETE") ); $chat_id = "-24787695"; $text = "@NdeNahun cuantos testículos tienes?"; // Create custom keyboard $keyboard = $this->telegram->buildKeyBoard($option, $onetime=TRUE, $selective=TRUE); $content = array('chat_id' => $chat_id, 'reply_markup' => $keyboard, 'text' => $text); $output = $this->telegram->sendMessage($content); echo '<pre>'.print_r($output, TRUE); } public function getUpdates() { $this->load->library('migration'); $this->config->load('bot'); $params = array( $this->config->item('botToken') ); $this->load->library('Telegram', $params); $output = $this->telegram->getUpdates(); echo '<pre>'; foreach ($output['result'] as $key => $value) { echo print_r($value, TRUE); } } public function sendPhoto() { $this->config->load('bot'); $params = array( $this->config->item('botToken') ); $this->load->library('Telegram', $params); $chat_id = "8908013"; // killer $chat_id = "-28127793"; //$filename = realpath(APPPATH.'../imgs/'.'space-ship.jpg'); //require_once(APPPATH.'libraries/CURLFile.php'); //$img = new CURLFile($filename, 'image/jpg', 'space-ship.jpg'); $this->load->model('Ships'); $ship = $this->Ships->get(1); $this->load->library('Mapdrawer'); $pathimg = $this->mapdrawer->generateShipMap($ship); $img = $this->telegram->prepareImage($pathimg); // $img = 'AgADBAADqacxG3864gf8EKgg3EpKRVXNijAABMy2MMSlqhpUJGAAAgI'; // file_id $caption = 'Cache Tests'; $content = array('chat_id' => $chat_id, 'photo' => $img, 'caption' => $caption ); $output = $this->telegram->sendPhoto($content); $this->telegram->updateImage($pathimg, json_decode($output)); echo '<pre>'.print_r($output, TRUE); } public function debug() { $this->config->load('bot'); $params = array( $this->config->item('botToken') ); $this->load->library('Telegram', $params); $output = $this->telegram->getUpdates(); echo '<pre>'; foreach ($output['result'] as $key => $value) { echo print_r($value, TRUE); } echo '<script>setTimeout(function(){ window.location = window.location; }, 3000);</script>'; } public function test() { $this->load->model('Ships'); $ship = $this->Ships->get(1); $this->load->library('Mapdrawer'); log_message('error', 'TEST'); try { //$this->mapdrawer->setAsteroids($asteroids); //$this->mapdrawer->setShips($ships); //$this->mapdrawer->__random(); $this->mapdrawer->generateShipMap($ship); } catch (Exception $e) { var_dump($e); } } }
{ "content_hash": "b23b9377c55fcd19322cd8b535d2512a", "timestamp": "", "source": "github", "line_count": 250, "max_line_length": 127, "avg_line_length": 26.88, "alnum_prop": 0.5620535714285714, "repo_name": "guillermofr/interestelegram_bot", "id": "d0d9756256f845d754f02bf17f3bc995bdc4419f", "size": "6724", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "application/controllers/Api.php", "mode": "33188", "license": "mit", "language": [ { "name": "ApacheConf", "bytes": "240" }, { "name": "CSS", "bytes": "9721" }, { "name": "HTML", "bytes": "5633" }, { "name": "JavaScript", "bytes": "3809" }, { "name": "PHP", "bytes": "1991145" } ], "symlink_target": "" }
<?xml version='1.0' encoding='UTF-8'?> <widget xmlns="http://www.w3.org/ns/widgets" xmlns:intelxdk="http://xdk.intel.com/ns/v1" id="not.yet.specified" version="0.0.1"> <!--This file is generated by the Intel XDK. Do not edit this file as your edits will be lost. --> <!--To change the contents of this file, see the documentation on the intelxdk.config.additions.xml file.--> <intelxdk:version value="1.1"/> <name>barcode_project</name> <content src="index.html"/> <!--creationInfo:{"src":"","projectTypeName":"com.intel.xdk.projecttype.jsapp"}--> <preference name="debuggable" value="false"/></widget>
{ "content_hash": "835b0133d9718c661702f3a436d8e286", "timestamp": "", "source": "github", "line_count": 9, "max_line_length": 128, "avg_line_length": 68, "alnum_prop": 0.6993464052287581, "repo_name": "WWC-IoT-Fridge/barcode", "id": "15e5682c70433462140fb357895b8895a85ad8b7", "size": "612", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "intelxdk.config.chrome.xml", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "3847" }, { "name": "HTML", "bytes": "7814" }, { "name": "JavaScript", "bytes": "50856" } ], "symlink_target": "" }
import numpy as np from SimPEG import ( maps, optimization, inversion, inverse_problem, directives, data_misfit, regularization, ) def spectral_ip_mappings( mesh, indActive=None, inactive_eta=1e-4, inactive_tau=1e-4, inactive_c=1e-4, is_log_eta=True, is_log_tau=True, is_log_c=True, ): """ Generates Mappings for Spectral Induced Polarization Simulation. Three parameters are required to be input: Chargeability (eta), Time constant (tau), and Frequency dependency (c). If there is no topography (indActive is None), model (m) can be either set to m = np.r_[log(eta), log(tau), log(c)] or m = np.r_[eta, tau, c] When indActive is not None, m is m = np.r_[log(eta[indAcitve]), log(tau[indAcitve]), log(c[indAcitve])] or m = np.r_[eta[indAcitve], tau[indAcitve], c[indAcitve]] or TODO: Illustrate input and output variables """ if indActive is None: indActive = np.ones(mesh.nC, dtype=bool) actmap_eta = maps.InjectActiveCells( mesh, indActive=indActive, valInactive=inactive_eta ) actmap_tau = maps.InjectActiveCells( mesh, indActive=indActive, valInactive=inactive_tau ) actmap_c = maps.InjectActiveCells(mesh, indActive=indActive, valInactive=inactive_c) wires = maps.Wires( ("eta", indActive.sum()), ("tau", indActive.sum()), ("c", indActive.sum()) ) if is_log_eta: eta_map = actmap_eta * maps.ExpMap(nP=actmap_eta.nP) * wires.eta else: eta_map = actmap_eta * wires.eta if is_log_tau: tau_map = actmap_tau * maps.ExpMap(nP=actmap_tau.nP) * wires.tau else: tau_map = actmap_tau * wires.tau if is_log_c: c_map = actmap_c * maps.ExpMap(nP=actmap_c.nP) * wires.c else: c_map = actmap_c * wires.c return eta_map, tau_map, c_map, wires def run_inversion( m0, survey, actind, mesh, wires, std, eps, maxIter=15, beta0_ratio=1e0, coolingFactor=2, coolingRate=2, maxIterLS=20, maxIterCG=10, LSshorten=0.5, eta_lower=1e-5, eta_upper=1, tau_lower=1e-6, tau_upper=10.0, c_lower=1e-2, c_upper=1.0, is_log_tau=True, is_log_c=True, is_log_eta=True, mref=None, alpha_s=1e-4, alpha_x=1e0, alpha_y=1e0, alpha_z=1e0, ): """ Run Spectral Spectral IP inversion """ dmisfit = data_misfit.L2DataMisfit(survey) uncert = abs(survey.dobs) * std + eps dmisfit.W = 1.0 / uncert # Map for a regularization # Related to inversion # Set Upper and Lower bounds e = np.ones(actind.sum()) if np.isscalar(eta_lower): eta_lower = e * eta_lower if np.isscalar(tau_lower): tau_lower = e * tau_lower if np.isscalar(c_lower): c_lower = e * c_lower if np.isscalar(eta_upper): eta_upper = e * eta_upper if np.isscalar(tau_upper): tau_upper = e * tau_upper if np.isscalar(c_upper): c_upper = e * c_upper if is_log_eta: eta_upper = np.log(eta_upper) eta_lower = np.log(eta_lower) if is_log_tau: tau_upper = np.log(tau_upper) tau_lower = np.log(tau_lower) if is_log_c: c_upper = np.log(c_upper) c_lower = np.log(c_lower) m_upper = np.r_[eta_upper, tau_upper, c_upper] m_lower = np.r_[eta_lower, tau_lower, c_lower] # Set up regularization reg_eta = regularization.Simple(mesh, mapping=wires.eta, indActive=actind) reg_tau = regularization.Simple(mesh, mapping=wires.tau, indActive=actind) reg_c = regularization.Simple(mesh, mapping=wires.c, indActive=actind) # Todo: reg_eta.alpha_s = alpha_s reg_tau.alpha_s = 0.0 reg_c.alpha_s = 0.0 reg_eta.alpha_x = alpha_x reg_tau.alpha_x = alpha_x reg_c.alpha_x = alpha_x reg_eta.alpha_y = alpha_y reg_tau.alpha_y = alpha_y reg_c.alpha_y = alpha_y reg_eta.alpha_z = alpha_z reg_tau.alpha_z = alpha_z reg_c.alpha_z = alpha_z reg = reg_eta + reg_tau + reg_c # Use Projected Gauss Newton scheme opt = optimization.ProjectedGNCG( maxIter=maxIter, upper=m_upper, lower=m_lower, maxIterLS=maxIterLS, maxIterCG=maxIterCG, LSshorten=LSshorten, ) invProb = inverse_problem.BaseInvProblem(dmisfit, reg, opt) beta = directives.BetaSchedule(coolingFactor=coolingFactor, coolingRate=coolingRate) betaest = directives.BetaEstimate_ByEig(beta0_ratio=beta0_ratio) target = directives.TargetMisfit() directiveList = [beta, betaest, target] inv = inversion.BaseInversion(invProb, directiveList=directiveList) opt.LSshorten = 0.5 opt.remember("xc") # Run inversion mopt = inv.run(m0) return mopt, invProb.dpred
{ "content_hash": "f0e5449931759f09353f5977231072c6", "timestamp": "", "source": "github", "line_count": 191, "max_line_length": 88, "avg_line_length": 25.32460732984293, "alnum_prop": 0.6158776100888981, "repo_name": "simpeg/simpeg", "id": "18b766b3e106c5a3603a8608bd74dbe80f51af6a", "size": "4837", "binary": false, "copies": "1", "ref": "refs/heads/main", "path": "SimPEG/electromagnetics/static/spectral_induced_polarization/run.py", "mode": "33188", "license": "mit", "language": [ { "name": "Makefile", "bytes": "685" }, { "name": "Python", "bytes": "3476002" } ], "symlink_target": "" }
#pragma once #include "SVGPathSegWithContext.h" namespace WebCore { class SVGPathSegLinetoRel final : public SVGPathSegSingleCoordinate { public: static Ref<SVGPathSegLinetoRel> create(const SVGPathElement& element, SVGPathSegRole role, float x, float y) { return adoptRef(*new SVGPathSegLinetoRel(element, role, x, y)); } private: SVGPathSegLinetoRel(const SVGPathElement& element, SVGPathSegRole role, float x, float y) : SVGPathSegSingleCoordinate(element, role, x, y) { } unsigned short pathSegType() const final { return PATHSEG_LINETO_REL; } String pathSegTypeAsLetter() const final { return "l"; } }; } // namespace WebCore
{ "content_hash": "e5f118ff0242b0fc250990a42221547d", "timestamp": "", "source": "github", "line_count": 26, "max_line_length": 112, "avg_line_length": 26.423076923076923, "alnum_prop": 0.7219796215429404, "repo_name": "gubaojian/trylearn", "id": "dcdf4838ac39fa5a1c7c1a58483f07fbf9ac7e13", "size": "1670", "binary": false, "copies": "4", "ref": "refs/heads/master", "path": "WebLayoutCore/Source/WebCore/svg/SVGPathSegLinetoRel.h", "mode": "33188", "license": "mit", "language": [ { "name": "AspectJ", "bytes": "623" }, { "name": "Assembly", "bytes": "1942" }, { "name": "Batchfile", "bytes": "6632" }, { "name": "C", "bytes": "6629351" }, { "name": "C++", "bytes": "57418677" }, { "name": "CMake", "bytes": "1269316" }, { "name": "CSS", "bytes": "99559" }, { "name": "HTML", "bytes": "283332" }, { "name": "Java", "bytes": "267448" }, { "name": "JavaScript", "bytes": "282026" }, { "name": "Makefile", "bytes": "164797" }, { "name": "Objective-C", "bytes": "956074" }, { "name": "Objective-C++", "bytes": "3645713" }, { "name": "Perl", "bytes": "192119" }, { "name": "Python", "bytes": "39191" }, { "name": "Ragel", "bytes": "128173" }, { "name": "Roff", "bytes": "26536" }, { "name": "Ruby", "bytes": "32784" }, { "name": "Shell", "bytes": "7177" }, { "name": "Vue", "bytes": "1776" }, { "name": "Yacc", "bytes": "11866" } ], "symlink_target": "" }
========= ##read_grib is a WMO GRiB Edition 1 file reader for MATLAB Current Version: r4 (10 March 2013) ##NOTE RE: Grib2 files read_grib does NOT read grib2 files, and there is no chance that it will. It is much easier to do one of two things: 1. Use nctoolbox, available on GitHub at https://github.com/nctoolbox/nctoolbox.git. This is the simplest way. 2. Convert grib2 to netCDF with [wgrib2](http://www.cpc.ncep.noaa.gov/products/wesley/wgrib2/) and use MATLAB's netCDF interface to get into MATLAB. ##Summary read_grib is a WMO GRiB Edition 1 file reader for MATLAB. It uses the binary data segment decoder from Wesley Ebisusaki's [wgrib](http://www.cpc.ncep.noaa.gov/products/wesley/wgrib.html) to decode Edition 1 grib records. Details of the GRiB format can be found in [NCEP's Office Note 388](http://www.nco.ncep.noaa.gov/pmb/docs/on388/). I wrote it because I needed it; feel free to use it as-is, and with no guarantee that it will work for all possible grib records. However, for the most common model output, it seems to work well. If a particular grib record is problematic, please try to look at it with wgrib. If that doesn't work (for whatever reason), then read_grib will not work either. While all of the grib record information is read and (optionally) returned by read_grib, it is sometimes easier to use wgrib to see what is in the grib file, and then use read_grib to get data into MATLAB. ###INSTALLATION Pull the repo to your local machine, into a directory called read_grib. The files can be left here and the path to read_grib included in the startup.m file. Alternatively, get the latest zipped package [here](). ###COMPILATION There is 1 mex file, written in c, that needs to be compiled. Fire up MATLAB, cd to the read_grib/private directory and type the following: >> mex BDS_unpack_mex5.c All should go well, assuming you have a [MATLAB-supported c compiler](http://www.mathworks.com/support/compilers/R2013b/index.html). This code is known to work on Linux, DEC-alpha, IBM, SGI, and MACs. The code is standard, and should work on most other platforms. Binaries are available for some platforms, and are in the git repo. ###Usage read_grib reads WMO international exchange GRiB formatted data files into MATLAB. It has various input modes, including extraction of individial GRiB records by record number, extraction by parameter name (which is not unique), and generating an inventory of the GRiB file contents. It has been tested on the following standard model output files: AVN, ETA, RUC, ECMWF, and WAM. The default GRiB parameter table used is the NCEP Operational table. Calls to read_grib look like: >> grib_struct=read_grib(gribname,irec,p1,v1,p2,v2,...); For example: >> grib_struct=read_grib(gribname,irec,'HeaderFlag',0,'ParamTable','ECMWF128'); The first 2 arguments are required: gribname - filename containing GRiB records. irec - specifies which GRiB records to read. If irec is a vector, it specifies which GRiB records to return. If irec is a scalar, is specifies how far to read into the GRiB file. If irec==-1, read_grib reads all records(default). Irec can be a CELL ARRAY of parameter names to extract. Type read_grib('paramtable') for a list of parameter names. Irec can also be the string 'inv{entory}', so that Read_grib prints a GRiB contents list. There are a few optional arguments that control header reporting, data decoding, and which grib parameter table to use. HeaderFlag - (0|1) report only headers if==1 (default=1) no data structures are returned unless DataFlag==1. DataFlag - (0|1) return decoded BDS if==1 (default=1). The data for the parameter is stored in the .fltarray field of the structure. ScreenDiag - (0|1) control diagnostics to screen (default=1) ParamTable - ('NCEPOPER'|'NCEPREAN'|'ECMWF128'|'ECMWF160'|'ECMWF140') selects the parameter table to use for matching kpds6 number to the correct parameter name. (default='NCEPOPER') A different parameter table can be specificed by creating a file in the same format at the .tab files in the read_grib directory, and using the ParamTable option with the file's name. ###Tutorial Pretend you have a file called anl.grb containing 37 grib records from an originating center that has output the model fields onto an equidistant lat/lon grid. To inventory the file: >> gribFileName='anl.grb'; >> grib_struct=read_grib(gribFileName,'inv'); To decode (extract) the 3rd and 7th grib records: >> grib_struct=read_grib(gribFileName,[3 7]) To decode (extract) all grib records: >> grib_struct=read_grib(gribFileName,-1); Each record that is extracted is returned as a structure in the grib_struct variable. In the last case above, the grib_struct variable is of length 37 (there are 37 records in this grib file), with structure fields for all parts of the grib record. >> grib_struct grib_struct = 1x37 struct array with fields: sec1_1 lengrib edition file record description parameter layer units stime level gridtype pds gds bms bds fltarray The actual data for a decoded record is in the **fltarray** field of each structure. So, according to the inventory, the 850 mb ugrd data is in grib_struct(31).fltarray. The date for this data is grib_struct(31).stime, in this case the date is June 01, 1990. More detailed date/time is in the product description segment (pds). >> dn=datenum(grib_struct(31).pds.year,grib_struct(31).pds.month,grib_struct(31).pds.day,grib_struct(31).pds.hour,grib_struct(31).pds.min,0); >> datestr(dn,31) ans = 1990-06-01 00:00:00 ###Dealing with the horizontal grid Dealing with the horizontal (spatial) grid for grib files is usually the hardest part. The grib_struct field grid definition segment (gds) contains the description of the spatial grid parameters. Some grids (like equidistant cylinders) are easy to reconstruct. (Some grids like NCEP's lambert or gaussian grids are not easy to reconstruct; fortunately many grib originators publish the grid coordinates for these types of grids.) The grid in these gribs is an equidistant cylindrical lat/lon grid: >> grib_struct(31).gridtype ans = Equidis. Cyl. Lat/Lon According to the gds, it is a 1.25 degree global grid (note the Di, Dj, La1,Lo1, La2,Lo2 field values): >> grib_struct(31).gds ans = len: 32 NV: 0 PV: 255 DRT: 'Equidis. Cyl. Lat/Lon' Ni: 288 Nj: 145 La1: 90 Lo1: 0 rcf: 128 La2: -90 Lo2: -1.2500 Di: 1.2500 Dj: 1.2500 smf: 0 oct29to32: [4x1 double] gdsvals: [32x1 double] The spatial grid is then just >> gds=grib_struct(31).gds; >> lon=gds.Lo1:gds.Di:gds.Lo2+360; >> lat=gds.La1:-gds.Dj:gds.La2; Note that there is a bit of manipulation of the grid parameters to get the coordinate vectors to be correct (Lo2+360, -gds.Dj). Then, just reshape the fltarray vector to this size, plot it to make sure the landmasses are where they should be. If not, then there probably needs to be a transpose in the reshape. >> ThisUgrd=reshape(grib_struct(31).fltarray,gds.Ni,gds.Nj)'; >> pcolor(lon,lat,ThisUgrd) >> % draw some coastline, etc... You should get something like this: ![TestImage1](testfiles/TestImage1.png "Test") Then, just use standard interp2 to sample at specific locations, etc ... Some gribs, such as from NCEP operational model output, are on unequally spaced grids (e.g., Lambert Conformal or Gaussian). NCEP uses many different output grids; some of these grids' lat/lon coordinates are posted [here](http://ftp.emc.ncep.noaa.gov/mmb/mmbpll/gridlola.eta/).
{ "content_hash": "e70f776a810103bf78c2ebac37404559", "timestamp": "", "source": "github", "line_count": 161, "max_line_length": 537, "avg_line_length": 49.590062111801245, "alnum_prop": 0.7094188376753507, "repo_name": "MajorChina/CPOP", "id": "fe6efa5262e5c9857372c9f1be1b9554cd69d126", "size": "7996", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "util/read_grib-master/README.md", "mode": "33188", "license": "mit", "language": [ { "name": "C", "bytes": "3904" }, { "name": "Jupyter Notebook", "bytes": "427931" }, { "name": "M", "bytes": "724" }, { "name": "Mathematica", "bytes": "480433" }, { "name": "Matlab", "bytes": "174316" }, { "name": "Python", "bytes": "957" } ], "symlink_target": "" }
@interface TwoViewController : UIViewController @property (nonatomic, strong) RACSubject *delegateSignal; @end
{ "content_hash": "527a3909054a61ed07deb599d2656b03", "timestamp": "", "source": "github", "line_count": 5, "max_line_length": 57, "avg_line_length": 22.6, "alnum_prop": 0.8141592920353983, "repo_name": "qinting513/Learning-QT", "id": "a6122c665894adfd8bdab7aa0bc8c573f73526c3", "size": "296", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "2016 Plan/10月/链式编程、函数式编程/1025-ReactiveCocoa/RAC第一天备课代码/06-RAC常见类-RACSubject和RACReplaySubject/ReactiveCocoa/TwoViewController.h", "mode": "33261", "license": "apache-2.0", "language": [ { "name": "C", "bytes": "1773653" }, { "name": "C++", "bytes": "616556" }, { "name": "CSS", "bytes": "14772" }, { "name": "DTrace", "bytes": "6180" }, { "name": "HTML", "bytes": "780741" }, { "name": "JavaScript", "bytes": "60127" }, { "name": "Objective-C", "bytes": "32993916" }, { "name": "Objective-C++", "bytes": "135277" }, { "name": "Ruby", "bytes": "8377" }, { "name": "Shell", "bytes": "272766" }, { "name": "Swift", "bytes": "2330800" } ], "symlink_target": "" }
namespace MassTransit.SagaStateMachine { using System; using System.Linq; using System.Linq.Expressions; using System.Reflection; using System.Threading.Tasks; using Internals; /// <summary> /// Accesses the current state as a string property /// </summary> /// <typeparam name="TSaga">The instance type</typeparam> public class StringStateAccessor<TSaga> : IStateAccessor<TSaga> where TSaga : class, ISaga { readonly StateMachine<TSaga> _machine; readonly IStateObserver<TSaga> _observer; readonly PropertyInfo _propertyInfo; readonly IReadProperty<TSaga, string> _read; readonly IWriteProperty<TSaga, string> _write; public StringStateAccessor(StateMachine<TSaga> machine, Expression<Func<TSaga, string>> currentStateExpression, IStateObserver<TSaga> observer) { _machine = machine; _observer = observer; _propertyInfo = currentStateExpression.GetPropertyInfo(); _read = ReadPropertyCache<TSaga>.GetProperty<string>(_propertyInfo); _write = WritePropertyCache<TSaga>.GetProperty<string>(_propertyInfo); } Task<State<TSaga>> IStateAccessor<TSaga>.Get(BehaviorContext<TSaga> context) { var stateName = _read.Get(context.Saga); if (string.IsNullOrWhiteSpace(stateName)) return Task.FromResult<State<TSaga>>(null); return Task.FromResult(_machine.GetState(stateName)); } Task IStateAccessor<TSaga>.Set(BehaviorContext<TSaga> context, State<TSaga> state) { if (state == null) throw new ArgumentNullException(nameof(state)); var previous = _read.Get(context.Saga); if (state.Name.Equals(previous)) return Task.CompletedTask; _write.Set(context.Saga, state.Name); State<TSaga> previousState = null; if (previous != null) previousState = _machine.GetState(previous); return _observer.StateChanged(context, state, previousState); } public Expression<Func<TSaga, bool>> GetStateExpression(params State[] states) { if (states == null || states.Length == 0) throw new ArgumentOutOfRangeException(nameof(states), "One or more states must be specified"); var parameterExpression = Expression.Parameter(typeof(TSaga), "instance"); var statePropertyExpression = Expression.Property(parameterExpression, _propertyInfo.GetMethod); var stateExpression = states.Select(state => Expression.Equal(statePropertyExpression, Expression.Constant(state.Name))) .Aggregate((left, right) => Expression.Or(left, right)); return Expression.Lambda<Func<TSaga, bool>>(stateExpression, parameterExpression); } public void Probe(ProbeContext context) { context.Add("currentStateProperty", _propertyInfo.Name); } } }
{ "content_hash": "603235aca5d4a0521da74b3608269bad", "timestamp": "", "source": "github", "line_count": 83, "max_line_length": 151, "avg_line_length": 37.0722891566265, "alnum_prop": 0.6373090672733182, "repo_name": "phatboyg/MassTransit", "id": "7758776db051353f0874731a0d4bdadd2e8a4f9a", "size": "3077", "binary": false, "copies": "3", "ref": "refs/heads/develop", "path": "src/MassTransit/SagaStateMachine/SagaStateMachine/Accessors/StringStateAccessor.cs", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "C#", "bytes": "12646003" }, { "name": "Dockerfile", "bytes": "781" }, { "name": "PowerShell", "bytes": "3303" }, { "name": "Shell", "bytes": "907" }, { "name": "Smalltalk", "bytes": "4" } ], "symlink_target": "" }
#include <linux/kernel.h> #include <linux/module.h> #include <linux/pm.h> #include <linux/device.h> #include <linux/of_device.h> #include <linux/platform_device.h> #include <linux/libata.h> #include <linux/ahci_platform.h> #include <linux/acpi.h> #include <linux/pci_ids.h> #include "ahci.h" #define DRV_NAME "ahci" static const struct ata_port_info ahci_port_info = { .flags = AHCI_FLAG_COMMON, .pio_mask = ATA_PIO4, .udma_mask = ATA_UDMA6, .port_ops = &ahci_platform_ops, }; static struct scsi_host_template ahci_platform_sht = { AHCI_SHT(DRV_NAME), }; static int ahci_probe(struct platform_device *pdev) { struct device *dev = &pdev->dev; struct ahci_host_priv *hpriv; int rc; hpriv = ahci_platform_get_resources(pdev); if (IS_ERR(hpriv)) return PTR_ERR(hpriv); rc = ahci_platform_enable_resources(hpriv); if (rc) return rc; if (of_device_is_compatible(dev->of_node, "hisilicon,hisi-ahci")) hpriv->flags |= AHCI_HFLAG_NO_FBS | AHCI_HFLAG_NO_NCQ; rc = ahci_platform_init_host(pdev, hpriv, &ahci_port_info, &ahci_platform_sht); if (rc) goto disable_resources; return 0; disable_resources: ahci_platform_disable_resources(hpriv); return rc; } static SIMPLE_DEV_PM_OPS(ahci_pm_ops, ahci_platform_suspend, ahci_platform_resume); static const struct of_device_id ahci_of_match[] = { { .compatible = "generic-ahci", }, /* Keep the following compatibles for device tree compatibility */ { .compatible = "snps,spear-ahci", }, { .compatible = "snps,exynos5440-ahci", }, { .compatible = "ibm,476gtr-ahci", }, { .compatible = "snps,dwc-ahci", }, { .compatible = "hisilicon,hisi-ahci", }, { .compatible = "fsl,qoriq-ahci", }, {}, }; MODULE_DEVICE_TABLE(of, ahci_of_match); static const struct acpi_device_id ahci_acpi_match[] = { { ACPI_DEVICE_CLASS(PCI_CLASS_STORAGE_SATA_AHCI, 0xffffff) }, {}, }; MODULE_DEVICE_TABLE(acpi, ahci_acpi_match); static struct platform_driver ahci_driver = { .probe = ahci_probe, .remove = ata_platform_remove_one, .driver = { .name = DRV_NAME, .of_match_table = ahci_of_match, .acpi_match_table = ahci_acpi_match, .pm = &ahci_pm_ops, }, }; module_platform_driver(ahci_driver); MODULE_DESCRIPTION("AHCI SATA platform driver"); MODULE_AUTHOR("Anton Vorontsov <[email protected]>"); MODULE_LICENSE("GPL"); MODULE_ALIAS("platform:ahci");
{ "content_hash": "3e341f4565156d45fffb70bb0ba6332e", "timestamp": "", "source": "github", "line_count": 93, "max_line_length": 67, "avg_line_length": 25.172043010752688, "alnum_prop": 0.68859461768475, "repo_name": "publicloudapp/csrutil", "id": "1befb114c3844c507939fe82924d60340edce15b", "size": "2787", "binary": false, "copies": "378", "ref": "refs/heads/master", "path": "linux-4.3/drivers/ata/ahci_platform.c", "mode": "33188", "license": "mit", "language": [ { "name": "Assembly", "bytes": "3984" }, { "name": "Awk", "bytes": "29136" }, { "name": "C", "bytes": "532969471" }, { "name": "C++", "bytes": "3352303" }, { "name": "Clojure", "bytes": "1489" }, { "name": "Cucumber", "bytes": "4701" }, { "name": "Groff", "bytes": "46775" }, { "name": "Lex", "bytes": "55199" }, { "name": "Makefile", "bytes": "1576284" }, { "name": "Objective-C", "bytes": "521540" }, { "name": "Perl", "bytes": "715196" }, { "name": "Perl6", "bytes": "3783" }, { "name": "Python", "bytes": "273092" }, { "name": "Shell", "bytes": "343618" }, { "name": "SourcePawn", "bytes": "4687" }, { "name": "UnrealScript", "bytes": "12797" }, { "name": "XS", "bytes": "1239" }, { "name": "Yacc", "bytes": "114559" } ], "symlink_target": "" }
<div class="commune_descr limited"> <p> Boissières est un village localisé dans le département de Lot en Midi-Pyrénées. Elle comptait 350 habitants en 2008.</p> <p>À proximité de Boissières sont localisées les communes de <a href="{{VLROOT}}/immobilier/uchaud_30333/">Uchaud</a> située à 3&nbsp;km, 3&nbsp;799 habitants, <a href="{{VLROOT}}/immobilier/codognan_30083/">Codognan</a> située à 4&nbsp;km, 2&nbsp;492 habitants, <a href="{{VLROOT}}/immobilier/nages-et-solorgues_30186/">Nages-et-Solorgues</a> localisée à 1&nbsp;km, 1&nbsp;462 habitants, <a href="{{VLROOT}}/immobilier/saint-dionizy_30249/">Saint-Dionizy</a> à 3&nbsp;km, 818 habitants, <a href="{{VLROOT}}/immobilier/bernis_30036/">Bernis</a> située à 4&nbsp;km, 2&nbsp;975 habitants, <a href="{{VLROOT}}/immobilier/calvisson_30062/">Calvisson</a> localisée à 3&nbsp;km, 4&nbsp;213 habitants, entre autres. De plus, Boissières est située à seulement douze&nbsp;km de <a href="{{VLROOT}}/immobilier/nimes_30189/">Nîmes</a>.</p> <p>Si vous envisagez de venir habiter à Boissières, vous pourrez aisément trouver une maison à vendre. </p> <p>Le nombre de logements, à Boissières, était réparti en 2011 en six appartements et 214 maisons soit un marché plutôt équilibré.</p> </div>
{ "content_hash": "b7e0894a4274b157996d84144130aa20", "timestamp": "", "source": "github", "line_count": 17, "max_line_length": 134, "avg_line_length": 74, "alnum_prop": 0.7329093799682035, "repo_name": "donaldinou/frontend", "id": "4f47e83738cfd3e1c7cf1a355346174966fce5fd", "size": "1294", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/Viteloge/CoreBundle/Resources/descriptions/46032.html", "mode": "33188", "license": "mit", "language": [ { "name": "ApacheConf", "bytes": "3073" }, { "name": "CSS", "bytes": "111338" }, { "name": "HTML", "bytes": "58634405" }, { "name": "JavaScript", "bytes": "88564" }, { "name": "PHP", "bytes": "841919" } ], "symlink_target": "" }
The goal of this gem is to parse a crontab timing specification and produce an object that can be queried about the schedule. This gem began as an extraction of Rufus::CronLine from the [rufus-scheduler](https://github.com/jmettraux/rufus-scheduler) gem. [![Build Status](https://travis-ci.org/bwthomas/whedon.png)](https://travis-ci.org/bwthomas/whedon) ## API example ``` sch = Whedon::Schedule.new('30 * * * *') # Most Recent sch.last # Upcoming sch.next # Next after date/time argument sch.next("2020/07/01") # Given date/time matches cron string sch.matches?("2020/07/01 14:00:00") # Time.now matches cron string sch.now? # Give cron string represented as an array # [seconds minutes hours days months weekdays monthdays timezone] sch.to_a ``` ## And ... the Name? Why 'whedon' ? First, [when](http://rubygems.org/gems/when) was taken. I was considering variations on 'when do', & it occurred to me that 'whedon' (a la [Joss Whedon](http://en.wikipedia.org/wiki/Joss_Whedon)) was an obvious anagram of 'when do'. The pun regarding Whedon::Schedule being that Joss Whedon's television series tend to get pulled from the network schedule. ## License [MIT](http://opensource.org/licenses/MIT). See [LICENSE](LICENSE).
{ "content_hash": "41c58f2c53dbb3e65ea1fca062aa4145", "timestamp": "", "source": "github", "line_count": 42, "max_line_length": 128, "avg_line_length": 29.357142857142858, "alnum_prop": 0.7339821573398215, "repo_name": "bwthomas/whedon", "id": "eac11809e932dfc69dffc244fa925ce653a0477b", "size": "1266", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "README.md", "mode": "33188", "license": "mit", "language": [ { "name": "Ruby", "bytes": "25014" } ], "symlink_target": "" }
<?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd"> <modelVersion>4.0.0</modelVersion> <parent> <groupId>gov.nasa.jpl</groupId> <artifactId>cmac-pipeline</artifactId> <version>0.1-SNAPSHOT</version> <relativePath>../../pom.xml</relativePath> </parent> <name>PCS Ops Interface (Apache OODT)</name> <artifactId>cmac-pipeline-opsui</artifactId> <packaging>war</packaging> <build> <sourceDirectory>src/main/java</sourceDirectory> <testSourceDirectory>src/test</testSourceDirectory> <outputDirectory>target/classes</outputDirectory> <resources> <resource> <directory>src/main/resources</directory> </resource> <resource> <directory>src/main/java</directory> <includes> <include>**</include> </includes> <excludes> <exclude>**/*.java</exclude> </excludes> </resource> </resources> <plugins> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-war-plugin</artifactId> <version>2.1.1</version> <configuration> <overlays> <overlay> <groupId>org.apache.oodt</groupId> <artifactId>pcs-opsui</artifactId> </overlay> </overlays> </configuration> </plugin> </plugins> </build> <dependencies> <dependency> <groupId>org.apache.oodt</groupId> <artifactId>pcs-opsui</artifactId> <version>${oodt.version}</version> <type>war</type> </dependency> </dependencies> </project>
{ "content_hash": "02fa333e1fc7bef1a732441e986c766f", "timestamp": "", "source": "github", "line_count": 63, "max_line_length": 100, "avg_line_length": 28.38095238095238, "alnum_prop": 0.6112975391498882, "repo_name": "chrismattmann/apple", "id": "3f02ff2c7d5d45a56db4b886816a920e518e7ed6", "size": "1788", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "webapps/opsui/pom.xml", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "3301" }, { "name": "Java", "bytes": "52242" }, { "name": "JavaScript", "bytes": "21408" }, { "name": "Perl", "bytes": "12253" }, { "name": "Python", "bytes": "10516" }, { "name": "Shell", "bytes": "45837" }, { "name": "XSLT", "bytes": "24923" } ], "symlink_target": "" }
using System; using System.Globalization; using System.IO; using System.Net; using System.Threading.Tasks; using Newtonsoft.Json; using Newtonsoft.Json.Converters; namespace MyLife.Core { public class JsonHttpHelper : HttpHelperBase { private JsonSerializerSettings Settings { get; set; } public JsonHttpHelper() { Settings = new JsonSerializerSettings { DateParseHandling = DateParseHandling.DateTime, DateTimeZoneHandling = DateTimeZoneHandling.Utc, }; //Settings.Converters.Add(new JavaScriptDateTimeConverter()); //Settings.Converters.Add(new TickDateTimeConverter()); Settings.Converters.Add(new IsoDateTimeConverter { DateTimeFormat = "yyyy'-'MM'-'dd'T'HH':'mm':'ss.fffK", DateTimeStyles = DateTimeStyles.RoundtripKind | DateTimeStyles.AssumeUniversal }); } protected override async Task<HttpWebRequest> BuildRequest(IHttpHelperRequest request) { var httpWebRequest = await base.BuildRequest(request); httpWebRequest.Accept = null; if (request.ContentType == null) httpWebRequest.ContentType = "application/json; charset=UTF-8"; httpWebRequest.Headers["X-Accept"] = "application/json"; return httpWebRequest; } protected override void SetRequestPayload(IHttpHelperRequest request, Stream requestStream) { if (request.Data == null) return; var json = JsonConvert.SerializeObject(request.Data, Settings); var byteArray = Encoding.GetBytes(json); requestStream.Write(byteArray, 0, byteArray.Length); } protected override object ReadResponseData(IHttpHelperRequest request, Stream responseStream) { var responseData = base.ReadResponseData(request, responseStream); return responseData; } protected override T Deserialize<T>(object data) { T result; try { if (data is string) { if (typeof (T) == typeof (string)) result = (T) data; else { var json = (string)data; result = JsonConvert.DeserializeObject<T>(json, Settings); } } else { var json = JsonConvert.SerializeObject(data, Settings); result = JsonConvert.DeserializeObject<T>(json, Settings); } } catch (Exception ex) { throw; } return result; } } }
{ "content_hash": "7320044ed81525bbf9d896191393aa21", "timestamp": "", "source": "github", "line_count": 91, "max_line_length": 101, "avg_line_length": 31.714285714285715, "alnum_prop": 0.5488565488565489, "repo_name": "LazyTarget/MyLife", "id": "923e5e862497fdb0c592c7e7996a2e036f486c6d", "size": "2888", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "MyLife/MyLife/MyLife.Core/Http/JsonHttpHelper.cs", "mode": "33188", "license": "mit", "language": [ { "name": "C#", "bytes": "651998" } ], "symlink_target": "" }
CouchDB as the State Database ============================= State Database options ---------------------- The current options for the peer state database are LevelDB and CouchDB. LevelDB is the default key-value state database embedded in the peer process. CouchDB is an alternative external state database. Like the LevelDB key-value store, CouchDB can store any binary data that is modeled in chaincode (CouchDB attachments are used internally for non-JSON data). As a document object store, CouchDB allows you to store data in JSON format, issue JSON queries against your data, and use indexes to support your queries. Both LevelDB and CouchDB support core chaincode operations such as getting and setting a key (asset), and querying based on keys. Keys can be queried by range, and composite keys can be modeled to enable equivalence queries against multiple parameters. For example a composite key of ``owner,asset_id`` can be used to query all assets owned by a certain entity. These key-based queries can be used for read-only queries against the ledger, as well as in transactions that update the ledger. Modeling your data in JSON allows you to issue JSON queries against the values of your data, instead of only being able to query the keys. This makes it easier for your applications and chaincode to read the data stored on the blockchain ledger. Using CouchDB can help you meet auditing and reporting requirements for many use cases that are not supported by LevelDB. If you use CouchDB and model your data in JSON, you can also deploy indexes with your chaincode. Using indexes makes queries more flexible and efficient and enables you to query large datasets from chaincode. CouchDB runs as a separate database process alongside the peer, therefore there are additional considerations in terms of setup, management, and operations. It is a good practice to model asset data as JSON, so that you have the option to perform complex JSON queries if needed in the future. .. note:: The key for a CouchDB JSON document can only contain valid UTF-8 strings and cannot begin with an underscore ("_"). Whether you are using CouchDB or LevelDB, you should avoid using U+0000 (nil byte) in keys. JSON documents in CouchDB cannot use the following values as top level field names. These values are reserved for internal use. - ``Any field beginning with an underscore, "_"`` - ``~version`` Because of these data incompatibilities between LevelDB and CouchDB, the database choice must be finalized prior to deploying a production peer. The database cannot be converted at a later time. Using CouchDB from Chaincode ---------------------------- Reading and writing JSON data ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ When writing JSON data values to CouchDB (e.g. using ``PutState``) and reading JSON back in later chaincode requests (e.g. using ``GetState``), the format of the JSON and the order of the JSON fields are not guaranteed, based on the JSON specification. Your chaincode should therefore unmarshall the JSON before working with the data. Similarly, when marshaling JSON, utilize a library that guarantees deterministic results, so that proposed chaincode writes and responses to clients will be identical across endorsing peers (note that Go ``json.Marshal()`` does in fact sort keys deterministically, but in other languages you may need to utilize a canonical JSON library). Chaincode queries ~~~~~~~~~~~~~~~~~ Most of the `chaincode shim APIs <https://godoc.org/github.com/hyperledger/fabric-chaincode-go/shim#ChaincodeStubInterface>`__ can be utilized with either LevelDB or CouchDB state database, e.g. ``GetState``, ``PutState``, ``GetStateByRange``, ``GetStateByPartialCompositeKey``. Additionally when you utilize CouchDB as the state database and model assets as JSON in chaincode, you can perform JSON queries against the data in the state database by using the ``GetQueryResult`` API and passing a CouchDB query string. The query string follows the `CouchDB JSON query syntax <http://docs.couchdb.org/en/2.1.1/api/database/find.html>`__. The `asset transfer Fabric sample <https://github.com/hyperledger/fabric-samples/blob/main/asset-transfer-ledger-queries/chaincode-go/asset_transfer_ledger_chaincode.go>`__ demonstrates use of CouchDB queries from chaincode. It includes a ``queryAssetsByOwner()`` function that demonstrates parameterized queries by passing an owner id into chaincode. It then queries the state data for JSON documents matching the docType of "asset" and the owner id using the JSON query syntax: .. code:: bash {"selector":{"docType":"asset","owner":<OWNER_ID>}} The responses to JSON queries are useful for understanding the data on the ledger. However, there is no guarantee that the result set for a JSON query will be stable between the chaincode execution and commit time. As a result, you should not use a JSON query and update the channel ledger in a single transaction. For example, if you perform a JSON query for all assets owned by Alice and transfer them to Bob, a new asset may be assigned to Alice by another transaction between chaincode execution time and commit time. .. couchdb-pagination: CouchDB pagination ^^^^^^^^^^^^^^^^^^ Fabric supports paging of query results for JSON queries and key range based queries. APIs supporting pagination allow the use of page size and bookmarks to be used for both key range and JSON queries. To support efficient pagination, the Fabric pagination APIs must be used. Specifically, the CouchDB ``limit`` keyword will not be honored in CouchDB queries since Fabric itself manages the pagination of query results and implicitly sets the pageSize limit that is passed to CouchDB. If a pageSize is specified using the paginated query APIs (``GetStateByRangeWithPagination()``, ``GetStateByPartialCompositeKeyWithPagination()``, and ``GetQueryResultWithPagination()``), a set of results (bound by the pageSize) will be returned to the chaincode along with a bookmark. The bookmark can be returned from chaincode to invoking clients, which can use the bookmark in a follow on query to receive the next "page" of results. The pagination APIs are for use in read-only transactions only, the query results are intended to support client paging requirements. For transactions that need to read and write, use the non-paginated chaincode query APIs. Within chaincode you can iterate through result sets to your desired depth. Regardless of whether the pagination APIs are utilized, all chaincode queries are bound by ``totalQueryLimit`` (default 100000) from ``core.yaml``. This is the maximum number of results that chaincode will iterate through and return to the client, in order to avoid accidental or malicious long-running queries. .. note:: Regardless of whether chaincode uses paginated queries or not, the peer will query CouchDB in batches based on ``internalQueryLimit`` (default 1000) from ``core.yaml``. This behavior ensures reasonably sized result sets are passed between the peer and CouchDB when executing chaincode, and is transparent to chaincode and the calling client. An example using pagination is included in the :doc:`couchdb_tutorial` tutorial. CouchDB indexes ~~~~~~~~~~~~~~~ Indexes in CouchDB are required in order to make JSON queries efficient and are required for any JSON query with a sort. Indexes enable you to query data from chaincode when you have a large amount of data on your ledger. Indexes can be packaged alongside chaincode in a ``/META-INF/statedb/couchdb/indexes`` directory. Each index must be defined in its own text file with extension ``*.json`` with the index definition formatted in JSON following the `CouchDB index JSON syntax <http://docs.couchdb.org/en/stable/api/database/find.html#db-index>`__. For example, to support the above marble query, a sample index on the ``docType`` and ``owner`` fields is provided: .. code:: bash {"index":{"fields":["docType","owner"]},"ddoc":"indexOwnerDoc", "name":"indexOwner","type":"json"} The sample index can be found `here <https://github.com/hyperledger/fabric-samples/blob/main/asset-transfer-ledger-queries/chaincode-go/META-INF/statedb/couchdb/indexes/indexOwner.json>`__. Any index in the chaincode’s ``META-INF/statedb/couchdb/indexes`` directory will be packaged up with the chaincode for deployment. The index will be deployed to a peers channel and chaincode specific database when the chaincode package is installed on the peer and the chaincode definition is committed to the channel. If you install the chaincode first and then commit the chaincode definition to the channel, the index will be deployed at commit time. If the chaincode has already been defined on the channel and the chaincode package subsequently installed on a peer joined to the channel, the index will be deployed at chaincode **installation** time. Upon deployment, the index will automatically be utilized by chaincode queries. CouchDB can automatically determine which index to use based on the fields being used in a query. Alternatively, in the selector query the index can be specified using the ``use_index`` keyword. The same index may exist in subsequent versions of the chaincode that gets installed. To change the index, use the same index name but alter the index definition. Upon installation/instantiation, the index definition will get re-deployed to the peer’s state database. If you have a large volume of data already, and later install the chaincode, the index creation upon installation may take some time. Similarly, if you have a large volume of data already and commit the definition of a subsequent chaincode version, the index creation may take some time. Avoid calling chaincode functions that query the state database at these times as the chaincode query may time out while the index is getting initialized. During transaction processing, the indexes will automatically get refreshed as blocks are committed to the ledger. If the peer crashes during chaincode installation, the couchdb indexes may not get created. If this occurs, you need to reinstall the chaincode to create the indexes. CouchDB Configuration --------------------- CouchDB is enabled as the state database by changing the ``stateDatabase`` configuration option from goleveldb to CouchDB. Additionally, the ``couchDBAddress`` needs to configured to point to the CouchDB to be used by the peer. The username and password properties should be populated with an admin username and password. Additional options are provided in the ``couchDBConfig`` section and are documented in place. Changes to the *core.yaml* will be effective immediately after restarting the peer. You can also pass in docker environment variables to override core.yaml values, for example ``CORE_LEDGER_STATE_STATEDATABASE`` and ``CORE_LEDGER_STATE_COUCHDBCONFIG_COUCHDBADDRESS``. Below is the ``stateDatabase`` section from *core.yaml*: .. code:: bash state: # stateDatabase - options are "goleveldb", "CouchDB" # goleveldb - default state database stored in goleveldb. # CouchDB - store state database in CouchDB stateDatabase: goleveldb # Limit on the number of records to return per query totalQueryLimit: 10000 couchDBConfig: # It is recommended to run CouchDB on the same server as the peer, and # not map the CouchDB container port to a server port in docker-compose. # Otherwise proper security must be provided on the connection between # CouchDB client (on the peer) and server. couchDBAddress: couchdb:5984 # This username must have read and write authority on CouchDB username: # The password is recommended to pass as an environment variable # during start up (e.g. LEDGER_COUCHDBCONFIG_PASSWORD). # If it is stored here, the file must be access control protected # to prevent unintended users from discovering the password. password: # Number of retries for CouchDB errors maxRetries: 3 # Number of retries for CouchDB errors during peer startup maxRetriesOnStartup: 10 # CouchDB request timeout (unit: duration, e.g. 20s) requestTimeout: 35s # Limit on the number of records per each CouchDB query # Note that chaincode queries are only bound by totalQueryLimit. # Internally the chaincode may execute multiple CouchDB queries, # each of size internalQueryLimit. internalQueryLimit: 1000 # Limit on the number of records per CouchDB bulk update batch maxBatchUpdateSize: 1000 CouchDB hosted in docker containers supplied with Hyperledger Fabric have the capability of setting the CouchDB username and password with environment variables passed in with the ``COUCHDB_USER`` and ``COUCHDB_PASSWORD`` environment variables using Docker Compose scripting. For CouchDB installations outside of the docker images supplied with Fabric, the `local.ini file of that installation <http://docs.couchdb.org/en/stable/config/intro.html#configuration-files>`__ must be edited to set the admin username and password. Docker compose scripts only set the username and password at the creation of the container. The *local.ini* file must be edited if the username or password is to be changed after creation of the container. If you choose to map the fabric-couchdb container port to a host port, make sure you are aware of the security implications. Mapping the CouchDB container port in a development environment exposes the CouchDB REST API and allows you to visualize the database via the CouchDB web interface (Fauxton). In a production environment you should refrain from mapping the host port to restrict access to the CouchDB container. Only the peer will be able to access the CouchDB container. .. note:: CouchDB peer options are read on each peer startup. Good practices for queries -------------------------- Avoid using chaincode for queries that will result in a scan of the entire CouchDB database. Full length database scans will result in long response times and will degrade the performance of your network. You can take some of the following steps to avoid long queries: - When using JSON queries: * Be sure to create indexes in the chaincode package. * Avoid query operators such as ``$or``, ``$in`` and ``$regex``, which lead to full database scans. - For range queries, composite key queries, and JSON queries: * Utilize paging support instead of one large result set. - If you want to build a dashboard or collect aggregate data as part of your application, you can query an off-chain database that replicates the data from your blockchain network. This will allow you to query and analyze the blockchain data in a data store optimized for your needs, without degrading the performance of your network or disrupting transactions. To achieve this, applications may use block or chaincode events to write transaction data to an off-chain database or analytics engine. For each block received, the block listener application would iterate through the block transactions and build a data store using the key/value writes from each valid transaction's ``rwset``. The :doc:`peer_event_services` provide replayable events to ensure the integrity of downstream data stores. .. Licensed under Creative Commons Attribution 4.0 International License https://creativecommons.org/licenses/by/4.0/
{ "content_hash": "26b3f11589549fc45e9c733cd5320d7b", "timestamp": "", "source": "github", "line_count": 277, "max_line_length": 189, "avg_line_length": 56.1985559566787, "alnum_prop": 0.7687415687030257, "repo_name": "jimthematrix/fabric", "id": "360c0c545d2d578e73f82e8d83be3926118dab92", "size": "15571", "binary": false, "copies": "1", "ref": "refs/heads/main", "path": "docs/source/couchdb_as_state_database.rst", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Dockerfile", "bytes": "4104" }, { "name": "Go", "bytes": "11991272" }, { "name": "Makefile", "bytes": "15840" }, { "name": "Shell", "bytes": "66599" } ], "symlink_target": "" }
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE hibernate-reverse-engineering PUBLIC "-//Hibernate/Hibernate Reverse Engineering DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-reverse-engineering-3.0.dtd" > <hibernate-reverse-engineering> <table-filter match-name=".*"></table-filter> <table name="t_article" schema="public"> <primary-key> <generator class="sequence"> <param name="sequence">t_article_articleno_seq</param> </generator> <key-column name="articleno" type="int"></key-column> </primary-key> </table> <table name="t_bookcase" schema="public"> <primary-key> <generator class="sequence"> <param name="sequence">t_bookcase_bookcaseno_seq</param> </generator> <key-column name="bookcaseno" type="int"></key-column> </primary-key> </table> <table name="t_chapter" schema="public"> <primary-key> <generator class="sequence"> <param name="sequence">t_chapter_chapterno_seq</param> </generator> <key-column name="chapterno" type="int"></key-column> </primary-key> </table> <table name="t_credit_history" schema="public"> <primary-key> <generator class="sequence"> <param name="sequence">t_credit_history_credithistoryno_seq</param> </generator> <key-column name="credithistoryno" type="int"></key-column> </primary-key> </table> <table name="t_message" schema="public"> <primary-key> <generator class="sequence"> <param name="sequence">t_message_messageno_seq</param> </generator> <key-column name="messageno" type="int"></key-column> </primary-key> </table> <table name="t_review" schema="public"> <primary-key> <generator class="sequence"> <param name="sequence">t_review_reviewno_seq</param> </generator> <key-column name="reviewno" type="int"></key-column> </primary-key> </table> <table name="t_system_block" schema="public"> <primary-key> <generator class="sequence"> <param name="sequence">t_system_block_blockno_seq</param> </generator> <key-column name="blockno" type="int"></key-column> </primary-key> </table> <table name="t_user" schema="public"> <primary-key> <generator class="sequence"> <param name="sequence">t_user_userno_seq</param> </generator> <key-column name="userno" type="int"></key-column> </primary-key> </table> <table name="t_subscribe" schema="public"> <primary-key> <generator class="sequence"> <param name="sequence">t_subscribe_subscribeno_seq</param> </generator> <key-column name="subscribeno" type="int"></key-column> </primary-key> </table> </hibernate-reverse-engineering>
{ "content_hash": "cf44c0bbb4231c838306628a751bce85", "timestamp": "", "source": "github", "line_count": 91, "max_line_length": 178, "avg_line_length": 28.703296703296704, "alnum_prop": 0.6738131699846861, "repo_name": "thu0ng91/maiyeu", "id": "71a58669ffd6efce4c13ea9f64e918c2e9fa1506", "size": "2612", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "src/main/resources/hibernategenerate/hibernate.reveng.xml", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "151792" }, { "name": "HTML", "bytes": "2884" }, { "name": "Java", "bytes": "711691" }, { "name": "JavaScript", "bytes": "41505" } ], "symlink_target": "" }
declare let ExpoAppleAuthenticationButtonSignInWhite: any; declare let ExpoAppleAuthenticationButtonSignInWhiteOutline: any; declare let ExpoAppleAuthenticationButtonSignInBlack: any; declare let ExpoAppleAuthenticationButtonContinueWhite: any; declare let ExpoAppleAuthenticationButtonContinueWhiteOutline: any; declare let ExpoAppleAuthenticationButtonContinueBlack: any; declare let ExpoAppleAuthenticationButtonSignUpWhite: any; declare let ExpoAppleAuthenticationButtonSignUpWhiteOutline: any; declare let ExpoAppleAuthenticationButtonSignUpBlack: any; export { ExpoAppleAuthenticationButtonSignInWhite, ExpoAppleAuthenticationButtonSignInWhiteOutline, ExpoAppleAuthenticationButtonSignInBlack, ExpoAppleAuthenticationButtonContinueWhite, ExpoAppleAuthenticationButtonContinueWhiteOutline, ExpoAppleAuthenticationButtonContinueBlack, ExpoAppleAuthenticationButtonSignUpWhite, ExpoAppleAuthenticationButtonSignUpWhiteOutline, ExpoAppleAuthenticationButtonSignUpBlack, }; //# sourceMappingURL=ExpoAppleAuthenticationButton.d.ts.map
{ "content_hash": "db250a315db805bf1b7b262ed154160c", "timestamp": "", "source": "github", "line_count": 11, "max_line_length": 416, "avg_line_length": 94, "alnum_prop": 0.9168278529980658, "repo_name": "exponentjs/exponent", "id": "46566555a16de855de5921c3d5bdef873ec27e44", "size": "1034", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "packages/expo-apple-authentication/build/ExpoAppleAuthenticationButton.d.ts", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "Assembly", "bytes": "96902" }, { "name": "Batchfile", "bytes": "382" }, { "name": "C", "bytes": "896724" }, { "name": "C++", "bytes": "867983" }, { "name": "CSS", "bytes": "6732" }, { "name": "HTML", "bytes": "152590" }, { "name": "IDL", "bytes": "897" }, { "name": "Java", "bytes": "4588748" }, { "name": "JavaScript", "bytes": "9343259" }, { "name": "Makefile", "bytes": "8790" }, { "name": "Objective-C", "bytes": "10675806" }, { "name": "Objective-C++", "bytes": "364286" }, { "name": "Perl", "bytes": "5860" }, { "name": "Prolog", "bytes": "287" }, { "name": "Python", "bytes": "97564" }, { "name": "Ruby", "bytes": "45432" }, { "name": "Shell", "bytes": "6501" } ], "symlink_target": "" }
/** * @file cdcacm.h * * cdcacm bootloader definitions. */ #pragma once extern void usb_cinit(void *config); extern void usb_cfini(void); extern int usb_cin(void); extern void usb_cout(uint8_t *buf, unsigned len);
{ "content_hash": "40affb2a3dacce188d1e806059bff781", "timestamp": "", "source": "github", "line_count": 15, "max_line_length": 49, "avg_line_length": 14.866666666666667, "alnum_prop": 0.6905829596412556, "repo_name": "acfloria/Firmware", "id": "18175b5c685b13f1f66c689a574490f34a046aea", "size": "1959", "binary": false, "copies": "3", "ref": "refs/heads/master", "path": "platforms/nuttx/src/bootloader/common/cdcacm.h", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "C", "bytes": "3738677" }, { "name": "C++", "bytes": "9489997" }, { "name": "CMake", "bytes": "1106585" }, { "name": "EmberScript", "bytes": "93414" }, { "name": "GDB", "bytes": "41" }, { "name": "Groovy", "bytes": "66180" }, { "name": "HTML", "bytes": "5343" }, { "name": "MATLAB", "bytes": "9938" }, { "name": "Makefile", "bytes": "20040" }, { "name": "Perl", "bytes": "11401" }, { "name": "Python", "bytes": "1300486" }, { "name": "Shell", "bytes": "301338" } ], "symlink_target": "" }
@interface ____Tests : XCTestCase @end @implementation ____Tests - (void)setUp { [super setUp]; // Put setup code here. This method is called before the invocation of each test method in the class. } - (void)tearDown { // Put teardown code here. This method is called after the invocation of each test method in the class. [super tearDown]; } - (void)testExample { // This is an example of a functional test case. // Use XCTAssert and related functions to verify your tests produce the correct results. } - (void)testPerformanceExample { // This is an example of a performance test case. [self measureBlock:^{ // Put the code you want to measure the time of here. }]; } @end
{ "content_hash": "d3be705302f0497ff748c8c0b5e2a46c", "timestamp": "", "source": "github", "line_count": 29, "max_line_length": 107, "avg_line_length": 25.03448275862069, "alnum_prop": 0.6804407713498623, "repo_name": "wowiwj/Xcode", "id": "d14b7ea561347e0ab67687f1a0bfbea9f6526b31", "size": "890", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "省市联动/省市联动Tests/____Tests.m", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "HTML", "bytes": "145019" }, { "name": "Objective-C", "bytes": "397607" }, { "name": "Swift", "bytes": "5876" } ], "symlink_target": "" }
var url = 'https://sweltering-inferno-6192.firebaseio.com'; var firebaseRef = new Firebase(url); function funct1(event) { event.preventDefault(); var tweet_content = $("#user-input").val(); tweet_content = tweet_content.trim(); if (tweet_content.length > 1){ firebaseRef.push({tweet_text: tweet_content}); } } function clearInput() { $('#user-input').val(''); } //----- Event handlers -----// $('.submit').click(funct1); $('.submit').click(clearInput);
{ "content_hash": "4509c977fe90dd431ad6ad6e7df9db24", "timestamp": "", "source": "github", "line_count": 21, "max_line_length": 60, "avg_line_length": 26.047619047619047, "alnum_prop": 0.5557586837294333, "repo_name": "peanutbutternsam/peanutbutternsam.github.io", "id": "c811282c00e194fee2ef39b6db234fc286c1a951", "size": "547", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "portfolio/twooter/twitta.js", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "49985" }, { "name": "JavaScript", "bytes": "1730" } ], "symlink_target": "" }
namespace courier { absl::Status Router::Bind(absl::string_view method, std::shared_ptr<HandlerInterface> method_handler, bool is_high_priority) { if (method.empty()) { return absl::InvalidArgumentError("Bind method name must be non-empty"); } if (method_handler == nullptr) { return absl::InvalidArgumentError("Bind method handler must be non-null."); } absl::WriterMutexLock lock(&mu_); handlers_[std::string(method)] = HandlerBinding{.handler = std::move(method_handler), .is_high_priority = is_high_priority}; return absl::OkStatus(); } void Router::Unbind(absl::string_view method) { absl::WriterMutexLock lock(&mu_); handlers_.erase(std::string(method)); } absl::StatusOr<const Router::HandlerBinding> Router::Lookup( absl::string_view method_name) { absl::ReaderMutexLock lock(&mu_); auto func_it = handlers_.find(std::string(method_name)); if (func_it == handlers_.end()) { func_it = handlers_.find("*"); } if (func_it == handlers_.end()) { return absl::Status(absl::StatusCode::kNotFound, absl::StrCat("method ", method_name, " not found")); } return func_it->second; } std::vector<std::string> Router::Names() { absl::ReaderMutexLock lock(&mu_); std::vector<std::string> names; names.reserve(handlers_.size()); for (const auto& item : handlers_) { names.push_back(item.first); } return names; } } // namespace courier
{ "content_hash": "1ce0f9a7e579abd3a43f76b9481dd68e", "timestamp": "", "source": "github", "line_count": 49, "max_line_length": 79, "avg_line_length": 30.73469387755102, "alnum_prop": 0.6321381142098274, "repo_name": "deepmind/launchpad", "id": "dffa3bb4bd4a18a4c1d24a48c8826a599fc7cdc1", "size": "2492", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "courier/router.cc", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "C", "bytes": "2395" }, { "name": "C++", "bytes": "217863" }, { "name": "Dockerfile", "bytes": "4420" }, { "name": "Python", "bytes": "285547" }, { "name": "Shell", "bytes": "12821" }, { "name": "Starlark", "bytes": "51487" } ], "symlink_target": "" }
while true; do echo "Restaring cib" ./gradlew run sleep 5 done
{ "content_hash": "10f900f716e379642108bcd7ff44a944", "timestamp": "", "source": "github", "line_count": 5, "max_line_length": 24, "avg_line_length": 15, "alnum_prop": 0.6266666666666667, "repo_name": "phzfi/RIC", "id": "d5a59b4baa091e275e7022350f10a0354f0c3156", "size": "88", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "competing_product/cib_loop.sh", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "815" }, { "name": "Go", "bytes": "133817" }, { "name": "HTML", "bytes": "6435" }, { "name": "Java", "bytes": "8253" }, { "name": "JavaScript", "bytes": "3966" }, { "name": "Python", "bytes": "16517" }, { "name": "Shell", "bytes": "14415" } ], "symlink_target": "" }
<?php //! Utility class for ZIP archives class Zip extends Base { //@{ Locale-specific error/exception messages const TEXT_Required='A ZIP archive must be specified', TEXT_NotValid='File %s is not a valid ZIP archive', TEXT_UnMethod='Unsupported compression method'; //@} //@{ ZIP header signatures const LFHDR_Sig='504B0304', CDHDR_Sig='504B0102', CDEND_Sig='504B0506'; //@} const //! Read-granularity of ZIP archive BLOCK_Size=4096; private //! ZIP file name $file, //! Central directory container $cdir, //! Central directory relative offset $cofs; /** Return central directory structure @return array @public **/ function dir() { return $this->cdir; } /** Return content of specified file from ZIP archive; FALSE if compression method is not supported @return mixed @param $path string @public **/ function get($path) { if (!$path || $path[strlen($path)-1]=='/') return FALSE; $chdr=$this->cdir[$path]; // Find local file header $zip=fopen($this->file,'rb'); fseek($zip,implode('',unpack('V',substr($chdr,42,4)))); // Read local file header $fhdr=fread($zip,30+strlen($path)); $comp=self::binhex(substr($fhdr,8,2)); if ($comp!='0800' && $comp!='0000') { trigger_error(self::TEXT_UnMethod); return FALSE; } if ($len=implode(unpack('v',substr($fhdr,28,2)))) // Append extra field $fhdr.=fread($zip,$len); $len=unpack('V',substr($fhdr,22,4)); $data=''; if ($len) $data=fread($zip,implode('',$len)); fclose($zip); return hexdec($comp) && $data?gzinflate($data):$data; } /** Add or replace file in ZIP archive using specified content; Create folder if content is NULL or unspecified @param $path string @param $data string @param $time integer @public **/ function set($path,$data=NULL,$time=0) { $this->parse('set',$path,$data,$time); } /** Delete file from ZIP archive @param $path string @public **/ function clear($path) { $this->parse('clear',$path); } /** Parse ZIP archive @param $path string @param $func mixed @public **/ private function parse($action,$path,$data=NULL,$time=0) { if (!$time) $time=time(); $tfn=self::$vars['TEMP'].$_SERVER['SERVER_NAME'].'.zip.'. self::hash($path); $tmp=fopen($tfn,'wb+'); if (is_file($this->file)) { $zip=fopen($this->file,'rb'); // Copy data from ZIP archive to temporary file foreach ($this->cdir as $name=>$chdr) if ($name!=$path) { // Find local file header fseek($zip,implode('', unpack('V',substr($chdr,42,4)))); $fhdr=fread($zip,30+strlen($name)); $len=implode(unpack('v',substr($fhdr,28,2))); if ($len) // Append extra field $fhdr.=fread($zip,$len); // Update relative offset $this->cdir[$name]=substr_replace( $this->cdir[$name],pack('V',ftell($tmp)),42,4); // Copy header and compressed content $len=implode('',unpack('V',substr($fhdr,18,4))); fwrite($tmp,$fhdr.($len?fread($zip,$len):'')); } fclose($zip); } switch ($action) { case 'set': $path=self::fixslashes($path). (is_null($data) && $path[strlen($path)]!='/'?'/':''); $chdr=&$this->cdir[$path]; // Blank headers $fhdr=str_repeat(chr(0),30).$path; $chdr=str_repeat(chr(0),46).$path; // Signatures $fhdr=substr_replace( $fhdr,self::hexbin(self::LFHDR_Sig),0,4); $chdr=substr_replace( $chdr,self::hexbin(self::CDHDR_Sig),0,4); // Version needed to extract $ver=self::hexbin(is_null($data)?'0A00':'1400'); $fhdr=substr_replace($fhdr,$ver,4,2); $chdr=substr_replace($chdr,$ver,6,2); // Last modification time $mod=pack('V',self::unix2dostime($time)); $fhdr=substr_replace($fhdr,$mod,10,4); $chdr=substr_replace($chdr,$mod,12,4); // File name length $len=pack('v',strlen($path)); $fhdr=substr_replace($fhdr,$len,26,2); $chdr=substr_replace($chdr,$len,28,2); // File header relative offset $chdr=substr_replace( $chdr,pack('V',ftell($tmp)),42,4); if (!is_null($data)) { // Compress data/Fix CRC bug $comp=gzdeflate($data); // Compression method $def=self::hexbin('0800'); $fhdr=substr_replace($fhdr,$def,8,2); $chdr=substr_replace($chdr,$def,10,2); // CRC32 $crc=pack('V',crc32($data)); $fhdr=substr_replace($fhdr,$crc,14,4); $chdr=substr_replace($chdr,$crc,16,4); // Compressed size $size=pack('V',strlen($comp)); $fhdr=substr_replace($fhdr,$size,18,4); $chdr=substr_replace($chdr,$size,20,4); // Uncompressed size $size=pack('V',strlen($data)); $fhdr=substr_replace($fhdr,$size,22,4); $chdr=substr_replace($chdr,$size,24,4); // Copy header and compressed content fwrite($tmp,$fhdr.$comp); } break; case 'clear': $path=self::fixslashes($path); unset($this->cdir[$path]); break; } // Central directory relative offset $this->cofs=ftell($tmp); foreach ($this->cdir as $raw) // Copy central directory file headers fwrite($tmp,$raw); // Blank end of central directory record $cend=str_repeat(chr(0),22); // Signature $cend=substr_replace($cend,self::hexbin(self::CDEND_Sig),0,4); // Total number of central directory records $total=pack('v',count($this->cdir)); $cend=substr_replace($cend,$total,8,2); $cend=substr_replace($cend,$total,10,2); // Size of central directory $cend=substr_replace( $cend,pack('V',strlen(implode('',$this->cdir))),12,4); // Relative offset of central directory $cend=substr_replace($cend,pack('V',$this->cofs),16,4); fwrite($tmp,$cend); fclose($tmp); if (is_file($this->file)) // Delete old ZIP archive unlink($this->file); rename($tfn,$this->file); } /** Convert 4-byte DOS time to Un*x timestamp @return integer @param $time integer @public **/ static function dos2unixtime($time) { $date=$time>>16; return mktime( ($time & 0xF800)>>11, ($time & 0x07E0)>>5, ($time & 0x001F)<<1, ($date & 0x01E0)>>5, ($date & 0x001F), (($date & 0xFE00)>>9)+1980 ); } /** Convert Un*x timestamp to 4-byte DOS time @return integer @param $time integer @public **/ static function unix2dostime($time=0) { $time=$time?getdate($time):getdate(); if ($time['year']<1980) $time=array_combine( array('hours','minutes','seconds','mon','mday','year'), array(0,0,0,1,1,1980) ); return ($time['hours']<<11) | ($time['minutes']<<5) | ($time['seconds']>>1) | ($time['mon']<<21) | ($time['mday']<<16) | (($time['year']-1980)<<25); } /** Class constructor @param $path string @public **/ function __construct($path=NULL) { if (is_null($path)) { trigger_error(self::TEXT_Required); return; } $path=self::resolve($path); $this->file=$path; $this->cdir=array(); if (!is_file($path)) return; // Parse file contents $zip=fopen($path,'rb'); $found=FALSE; $cdir=''; while (!feof($zip)) { $cdir.=fread($zip,self::BLOCK_Size); if (is_bool($found)) { $found=strstr($cdir,self::hexbin(self::CDHDR_Sig)); if (is_string($found)) { // Start of central directory record $cdir=$found; $this->cofs=ftell($zip)-strlen($found); } elseif (strlen($cdir)>self::BLOCK_Size) // Conserve memory $cdir=substr($cdir,self::BLOCK_Size); } } fclose($zip); if (is_bool(strstr($cdir,self::hexbin(self::CDEND_Sig)))) { // Invalid ZIP archive trigger_error(sprintf(self::TEXT_NotValid,$path)); return; } // Save central directory record foreach (array_slice(explode(self::hexbin(self::CDHDR_Sig), strstr($cdir,self::hexbin(self::CDEND_Sig),TRUE)),1) as $raw) // Extract name and use as array key $this->cdir[substr( $raw,42,implode('',unpack('v',substr($raw,24,2))) )]=self::hexbin(self::CDHDR_Sig).$raw; } }
{ "content_hash": "1f527480ae087cb6d733b344b7814ffa", "timestamp": "", "source": "github", "line_count": 302, "max_line_length": 64, "avg_line_length": 26.129139072847682, "alnum_prop": 0.6039792168292992, "repo_name": "liosha2007/temporary-groupdocs-php-sdk", "id": "a806476d8e5233443c8aaeca3d09e448593a8c61", "size": "8323", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "examples/api-samples/FatFree_Framework/lib/zip.php", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "PHP", "bytes": "1183346" }, { "name": "Shell", "bytes": "152" } ], "symlink_target": "" }
package org.spongepowered.common.event.tracking.phase.plugin; import org.spongepowered.common.event.tracking.TrackingUtil; public class BlockWorkerPhaseState extends BasicPluginState { BlockWorkerPhaseState() { } @Override public void unwind(BasicPluginContext phaseContext) { phaseContext.getCapturedItemsSupplier().acceptAndClearIfNotEmpty(items -> { }); // TODO - Determine if we need to pass the supplier or perform some parameterized // process if not empty method on the capture object. TrackingUtil.processBlockCaptures(phaseContext); } @Override public boolean handlesOwnStateCompletion() { return true; } }
{ "content_hash": "2cb4055d17b8b15ad57b4270df3b2e40", "timestamp": "", "source": "github", "line_count": 25, "max_line_length": 89, "avg_line_length": 28.16, "alnum_prop": 0.71875, "repo_name": "SpongePowered/SpongeCommon", "id": "4bfb9af4c4d5ffe6ee1989c477716539d7de1410", "size": "1951", "binary": false, "copies": "1", "ref": "refs/heads/stable-7", "path": "src/main/java/org/spongepowered/common/event/tracking/phase/plugin/BlockWorkerPhaseState.java", "mode": "33188", "license": "mit", "language": [ { "name": "Java", "bytes": "14153592" }, { "name": "Shell", "bytes": "1072" } ], "symlink_target": "" }
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd"> <groupId>com.demo</groupId> <modelVersion>4.0.0</modelVersion> <artifactId>rest-demo</artifactId> <packaging>war</packaging> <version>0.0.1</version> <name>Spring REST Services with Basic Example</name> <url>http://github.com/vollov</url> <properties> <!-- Spring versions --> <org.springframework.version>4.0.5.RELEASE</org.springframework.version> <org.springframework.security.version>3.2.5.RELEASE</org.springframework.security.version> </properties> <dependencies> <!-- Spring --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-core</artifactId> <version>${org.springframework.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-beans</artifactId> <version>${org.springframework.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context</artifactId> <version>${org.springframework.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-web</artifactId> <version>${org.springframework.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-webmvc</artifactId> <version>${org.springframework.version}</version> </dependency> <!-- Spring Security --> <dependency> <groupId>org.springframework.security</groupId> <artifactId>spring-security-web</artifactId> <version>${org.springframework.security.version}</version> </dependency> <dependency> <groupId>org.springframework.security</groupId> <artifactId>spring-security-config</artifactId> <version>${org.springframework.security.version}</version> </dependency> <!-- JASON parser --> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-core</artifactId> <version>2.4.0</version> </dependency> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-databind</artifactId> <version>2.4.0</version> </dependency> <dependency> <groupId>log4j</groupId> <artifactId>log4j</artifactId> <version>1.2.17</version> </dependency> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.11</version> <scope>test</scope> </dependency> <!-- Added for debugging purposes --> <dependency> <groupId>javax.servlet</groupId> <artifactId>javax.servlet-api</artifactId> <version>3.1.0</version> <scope>provided</scope> </dependency> </dependencies> <build> <finalName>rest-demo</finalName> <plugins> <plugin> <groupId>org.apache.tomcat.maven</groupId> <artifactId>tomcat7-maven-plugin</artifactId> <version>2.2</version> <configuration> <url>http://localhost:8080/manager/text</url> <server>TomcatServer</server> <path>/${project.build.finalName}</path> </configuration> </plugin> </plugins> </build> </project>
{ "content_hash": "7ad6b9b6a65af446135f9408baa02d34", "timestamp": "", "source": "github", "line_count": 109, "max_line_length": 105, "avg_line_length": 33.72477064220183, "alnum_prop": 0.6139825897714908, "repo_name": "vollov/spring-lab", "id": "384b739c7b59832af9323e93ea578dbd06f22390", "size": "3676", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "rest-demo/pom.xml", "mode": "33188", "license": "mit", "language": [ { "name": "Java", "bytes": "37677" } ], "symlink_target": "" }
namespace Prometheus.Client.Tests.Mocks { public interface IDummyMetric : IMetric { void Observe(long? ts); } }
{ "content_hash": "fd1a463723ca8275a4159438eddc6bb8", "timestamp": "", "source": "github", "line_count": 7, "max_line_length": 43, "avg_line_length": 18.857142857142858, "alnum_prop": 0.6515151515151515, "repo_name": "phnx47/Prometheus.Client", "id": "6769c8dde02086bbe41e51d2649964f8721253ee", "size": "132", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "tests/Prometheus.Client.Tests/Mocks/IDummyMetric.cs", "mode": "33188", "license": "mit", "language": [ { "name": "C#", "bytes": "105624" }, { "name": "PowerShell", "bytes": "734" } ], "symlink_target": "" }
<!DOCTYPE html> <title>Reference for WebVTT rendering, ::cue(v), background properties</title> <style> html { overflow:hidden } body { margin:0 } .video { display: inline-block; width: 320px; height: 180px; position: relative; font-size: 9px; } .cue { position: absolute; bottom: 0; left: 0; right: 0; text-align: center } .cue > span { font-family: sans-serif; background: rgba(0,0,0,0.8); color: white; } .cue > span > span { background: #0f0 url('../../../media/background.gif') repeat-x top left; color: #000; } </style> <div class="video"><span class="cue"><span>This is a <span>test subtitle</span></span></span></div>
{ "content_hash": "962e186600bf66f0b249a8c3c0075014", "timestamp": "", "source": "github", "line_count": 30, "max_line_length": 99, "avg_line_length": 22.833333333333332, "alnum_prop": 0.6175182481751825, "repo_name": "chromium/chromium", "id": "c45b7a550a7c8726d6c2da31ef472e23746e07f2", "size": "685", "binary": false, "copies": "97", "ref": "refs/heads/main", "path": "third_party/blink/web_tests/external/wpt/webvtt/rendering/cues-with-video/processing-model/selectors/cue_function/voice_object/voice_background_properties-ref.html", "mode": "33188", "license": "bsd-3-clause", "language": [], "symlink_target": "" }
<?xml version="1.0" encoding="utf-8"?> <android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:fitsSystemWindows="true" tools:context="com.github.k24.prefsovensample.PrefsEditActivity"> <android.support.design.widget.AppBarLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:theme="@style/AppTheme.AppBarOverlay"> <android.support.v7.widget.Toolbar android:id="@+id/toolbar" android:layout_width="match_parent" android:layout_height="?attr/actionBarSize" android:background="?attr/colorPrimary" app:popupTheme="@style/AppTheme.PopupOverlay" /> </android.support.design.widget.AppBarLayout> <include layout="@layout/content_prefs_edit" /> <android.support.design.widget.FloatingActionButton android:id="@+id/fab" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="bottom|end" android:layout_margin="@dimen/fab_margin" android:src="@android:drawable/ic_input_add" /> </android.support.design.widget.CoordinatorLayout>
{ "content_hash": "7419ff81df2051a608b2cc9008b65ddb", "timestamp": "", "source": "github", "line_count": 34, "max_line_length": 107, "avg_line_length": 41.64705882352941, "alnum_prop": 0.6927966101694916, "repo_name": "k24/prefsoven", "id": "03c43f8a7ad4bd43ec2f32e8090833e2bdce5419", "size": "1416", "binary": false, "copies": "1", "ref": "refs/heads/develop", "path": "prefsovensample/src/main/res/layout/activity_prefs_edit.xml", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "107704" } ], "symlink_target": "" }
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>cours-de-coq: Not compatible 👼</title> <link rel="shortcut icon" type="image/png" href="../../../../../favicon.png" /> <link href="../../../../../bootstrap.min.css" rel="stylesheet"> <link href="../../../../../bootstrap-custom.css" rel="stylesheet"> <link href="//maxcdn.bootstrapcdn.com/font-awesome/4.2.0/css/font-awesome.min.css" rel="stylesheet"> <script src="../../../../../moment.min.js"></script> <!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries --> <!-- WARNING: Respond.js doesn't work if you view the page via file:// --> <!--[if lt IE 9]> <script src="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script> <script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script> <![endif]--> </head> <body> <div class="container"> <div class="navbar navbar-default" role="navigation"> <div class="container-fluid"> <div class="navbar-header"> <a class="navbar-brand" href="../../../../.."><i class="fa fa-lg fa-flag-checkered"></i> Coq bench</a> </div> <div id="navbar" class="collapse navbar-collapse"> <ul class="nav navbar-nav"> <li><a href="../..">clean / extra-dev</a></li> <li class="active"><a href="">dev / cours-de-coq - 8.8.0</a></li> </ul> </div> </div> </div> <div class="article"> <div class="row"> <div class="col-md-12"> <a href="../..">« Up</a> <h1> cours-de-coq <small> 8.8.0 <span class="label label-info">Not compatible 👼</span> </small> </h1> <p>📅 <em><script>document.write(moment("2022-05-24 01:37:32 +0000", "YYYY-MM-DD HH:mm:ss Z").fromNow());</script> (2022-05-24 01:37:32 UTC)</em><p> <h2>Context</h2> <pre># Packages matching: installed # Name # Installed # Synopsis base-bigarray base base-threads base base-unix base conf-findutils 1 Virtual package relying on findutils conf-gmp 4 Virtual package relying on a GMP lib system installation coq dev Formal proof management system dune 3.1.1 Fast, portable, and opinionated build system ocaml 4.10.2 The OCaml compiler (virtual package) ocaml-base-compiler 4.10.2 Official release 4.10.2 ocaml-config 1 OCaml Switch Configuration ocamlfind 1.9.3 A library manager for OCaml zarith 1.12 Implements arithmetic and logical operations over arbitrary-precision integers # opam file: opam-version: &quot;2.0&quot; maintainer: &quot;[email protected]&quot; homepage: &quot;https://github.com/coq-contribs/cours-de-coq&quot; license: &quot;Unknown&quot; build: [make &quot;-j%{jobs}%&quot;] install: [make &quot;install&quot;] remove: [&quot;rm&quot; &quot;-R&quot; &quot;%{lib}%/coq/user-contrib/CoursDeCoq&quot;] depends: [ &quot;ocaml&quot; &quot;coq&quot; {&gt;= &quot;8.8&quot; &amp; &lt; &quot;8.9~&quot;} ] tags: [ &quot;category: Miscellaneous/Coq Use Examples&quot; ] authors: [ &quot;Frédéric Prost&quot; &quot;Gilles Kahn&quot; ] bug-reports: &quot;https://github.com/coq-contribs/cours-de-coq/issues&quot; dev-repo: &quot;git+https://github.com/coq-contribs/cours-de-coq.git&quot; synopsis: &quot;Various examples of Coq proofs&quot; description: &quot;Various simple examples of Coq proofs&quot; flags: light-uninstall url { src: &quot;https://github.com/coq-contribs/cours-de-coq/archive/v8.8.0.tar.gz&quot; checksum: &quot;md5=1acf2cbcd7c2c0bdaed451a17696e43e&quot; } </pre> <h2>Lint</h2> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>true</code></dd> <dt>Return code</dt> <dd>0</dd> </dl> <h2>Dry install 🏜️</h2> <p>Dry install with the current Coq version:</p> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>opam install -y --show-action coq-cours-de-coq.8.8.0 coq.dev</code></dd> <dt>Return code</dt> <dd>5120</dd> <dt>Output</dt> <dd><pre>[NOTE] Package coq is already installed (current version is dev). The following dependencies couldn&#39;t be met: - coq-cours-de-coq -&gt; coq &lt; 8.9~ -&gt; ocaml &lt; 4.10 base of this switch (use `--unlock-base&#39; to force) Your request can&#39;t be satisfied: - No available version of coq satisfies the constraints No solution found, exiting </pre></dd> </dl> <p>Dry install without Coq/switch base, to test if the problem was incompatibility with the current Coq/OCaml version:</p> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>opam remove -y coq; opam install -y --show-action --unlock-base coq-cours-de-coq.8.8.0</code></dd> <dt>Return code</dt> <dd>0</dd> </dl> <h2>Install dependencies</h2> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>true</code></dd> <dt>Return code</dt> <dd>0</dd> <dt>Duration</dt> <dd>0 s</dd> </dl> <h2>Install 🚀</h2> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>true</code></dd> <dt>Return code</dt> <dd>0</dd> <dt>Duration</dt> <dd>0 s</dd> </dl> <h2>Installation size</h2> <p>No files were installed.</p> <h2>Uninstall 🧹</h2> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>true</code></dd> <dt>Return code</dt> <dd>0</dd> <dt>Missing removes</dt> <dd> none </dd> <dt>Wrong removes</dt> <dd> none </dd> </dl> </div> </div> </div> <hr/> <div class="footer"> <p class="text-center"> Sources are on <a href="https://github.com/coq-bench">GitHub</a> © Guillaume Claret 🐣 </p> </div> </div> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <script src="../../../../../bootstrap.min.js"></script> </body> </html>
{ "content_hash": "f4b14280197998fcc95f084cfcff944d", "timestamp": "", "source": "github", "line_count": 166, "max_line_length": 159, "avg_line_length": 41.066265060240966, "alnum_prop": 0.5376265219304679, "repo_name": "coq-bench/coq-bench.github.io", "id": "070b0f124e5e1311316268c8d7a189dbf031239e", "size": "6844", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "clean/Linux-x86_64-4.10.2-2.0.6/extra-dev/dev/cours-de-coq/8.8.0.html", "mode": "33188", "license": "mit", "language": [], "symlink_target": "" }
<?php namespace SituacaoResponsavelCatequizando\Controller; use Estrutura\Controller\AbstractCrudController; use Estrutura\Helpers\Cript; use Estrutura\Helpers\Data; use Zend\View\Model\ViewModel; use Zend\View\Model\JsonModel; class SituacaoResponsavelCatequizandoController extends AbstractCrudController { protected $service; protected $form; public function __construct(){ parent::init(); } public function indexAction() { return parent::index($this->service, $this->form); //http://igorrocha.com.br/tutorial-zf2-parte-9-paginacao-busca-e-listagem/4/ return new ViewModel([ 'service' => $this->service, 'form' => $this->form, 'controller' => $this->params('controller'), 'atributos' => array() ]); } public function gravarAction(){ $this->getRequest()->getPost()->set('id_catequizando', $this->getRequest()->getPost()->get('id_catequizando')); $this->getRequest()->getPost()->set('id_situacao_responsavel', $this->getRequest()->getPost()->get('id_situacao_responsavel')); parent::gravar( $this->getServiceLocator()->get('\SituacaoResponsavelCatequizando\Service\SituacaoResponsavelCatequizandoService'), new \SituacaoResponsavelCatequizando\Form\SituacaoResponsavelCatequizandoForm() ); $this->addSuccessMessage('Registro Inserido/Alterado com sucesso'); $this->redirect()->toRoute('navegacao', array('controller' => 'situacao_responsavel_catequizando-situacaoresponsavelcatequizando', 'action' => 'index')); } public function cadastroAction() { // funnção alterar return parent::cadastro($this->service, $this->form); } public function excluirAction() { return parent::excluir($this->service, $this->form); } public function indexPaginationAction() {// funcao paginacao //http://igorrocha.com.br/tutorial-zf2-parte-9-paginacao-busca-e-listagem/4/ $filter = $this->getFilterPage(); $camposFilter = [ '0' => [ 'filter' => "catequizando.nm_catequizando LIKE ?", ], '1' => [ 'filter' => "situacao_responsavel.ds_situacao_responsavel LIKE ?" , ], ]; $paginator = $this->service->getSituacaoResponsavelCatequizandoPaginator($filter, $camposFilter); $paginator->setItemCountPerPage($paginator->getTotalItemCount()); $countPerPage = $this->getCountPerPage( current(\Estrutura\Helpers\Pagination::getCountPerPage($paginator->getTotalItemCount())) ); $paginator->setItemCountPerPage($this->getCountPerPage( current(\Estrutura\Helpers\Pagination::getCountPerPage($paginator->getTotalItemCount())) ))->setCurrentPageNumber($this->getCurrentPage()); $viewModel = new ViewModel([ 'service' => $this->service, 'form' => $this->form, 'paginator' => $paginator, 'filter' => $filter, 'countPerPage' => $countPerPage, 'camposFilter' => $camposFilter, 'controller' => $this->params('controller'), 'atributos' => array() ]); return $viewModel->setTerminal(TRUE); } }
{ "content_hash": "d42a8fded27f0f951dae7d4b10d9c95d", "timestamp": "", "source": "github", "line_count": 107, "max_line_length": 223, "avg_line_length": 32.299065420560744, "alnum_prop": 0.5992476851851852, "repo_name": "alyssontkd/catequese", "id": "851391e16ddaa9a393b00aa1456aae1a50939ec1", "size": "3458", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "module/SituacaoResponsavelCatequizando/src/SituacaoResponsavelCatequizando/Controller/SituacaoResponsavelCatequizandoController.php", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "ApacheConf", "bytes": "711" }, { "name": "CSS", "bytes": "1813340" }, { "name": "HTML", "bytes": "2637778" }, { "name": "JavaScript", "bytes": "1062487" }, { "name": "PHP", "bytes": "947700" }, { "name": "SQLPL", "bytes": "24564" }, { "name": "Shell", "bytes": "151" } ], "symlink_target": "" }
namespace lasso { struct ProxGradConfig { int worker_rank = -1; int feature_start = 0; int feature_end = 0; int num_samples = 0; int num_reps = 1; }; class ProxGrad { public: ProxGrad(const ProxGradConfig& config); void ProxStep( const std::vector<petuum::ml::SparseFeature<float>*>& X_cols, const petuum::ml::DenseFeature<float>& y, float lr, int my_clock); float EvalSqLoss( const petuum::ml::DenseFeature<float>& y); float EvalL1Penalty() const; // Cound # of non-zeros in beta (sharded to workers). int EvalBetaNNZ() const; int GetSampleSize() const { return num_feature_samples_; } private: void SoftThreshold(float threshold, petuum::ml::DenseFeature<float>* x); private: int worker_rank_; int num_workers_; int num_samples_; int feature_start_; int feature_end_; int num_features_; // # features in this worker. // stochastic version uses only this many coordinates in each step int num_feature_samples_; int num_reps_; petuum::ml::DenseFeature<float> beta_; // [num_features_ x 1] petuum::ml::DenseFeature<float> r_; // [num_samples_ x 1] //petuum::ml::DenseFeature<float> delta_; // [num_features_ x 1] petuum::Table<float> w_table_; petuum::Table<float> unused_table_; petuum::Table<int64_t> staleness_table_; std::random_device r; std::seed_seq seed2{r(), r(), r(), r(), r(), r(), r(), r()}; std::mt19937 rand_eng{seed2}; std::uniform_real_distribution<float> uniform_dist{0, 1}; }; } // namespace lasso
{ "content_hash": "781a08f3ecb735fd26a2539048ce18b4", "timestamp": "", "source": "github", "line_count": 58, "max_line_length": 68, "avg_line_length": 26.551724137931036, "alnum_prop": 0.6538961038961039, "repo_name": "daiwei89/wdai_petuum_public", "id": "af6865b70dca6d51f0e12fc6ac104705796886d2", "size": "1670", "binary": false, "copies": "1", "ref": "refs/heads/dev_1.0", "path": "apps/stochastic_lasso/src/prox_grad.hpp", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "C", "bytes": "114881" }, { "name": "C++", "bytes": "8153288" }, { "name": "CMake", "bytes": "18261" }, { "name": "Cuda", "bytes": "19654" }, { "name": "Logos", "bytes": "76" }, { "name": "Makefile", "bytes": "46087" }, { "name": "Protocol Buffer", "bytes": "34712" }, { "name": "Python", "bytes": "305319" }, { "name": "Shell", "bytes": "113572" }, { "name": "Yacc", "bytes": "20" } ], "symlink_target": "" }
PermissionsEx can be configured in-game using its set of commands: ## Argument types - *subject type*: a type of subject - *subject*: A compound argument of subject type and identifier - *context*: A `<context-type>=<context-value>` - *rank-ladder*: The name of a currently existing rank ladder - *permission*: A permission string - *option*: An option string - *permission value*: a number, boolean, or `none`, `null`, or `unset` ## Common flags These flags can be specified after any permissions modification command to control the specific areas permissions are updated in: - `--transient`: If the data should be stored transiently (i.e. only for the current session) - `--context <context>`: A context to restrict a permission to, such as a world ## The actual commands ### `/pex|permissionsex` **Description:** Provides simple information about PermissionsEx. ### `/pex|permissionsex help [command]` **Description:** Provide help about PermissionsEx commands **Permission:** `permissionsex.help` Provides an in-game help viewer for information on PermissionsEx commands ### `/pex|permissionsex debug|d [filter]` **Description:** Toggle whether all permissions checks are logged to console **Permission:** `permissionsex.debug` When enabled, any check executed through PermissionsEx will be logged to console. If the `filter` regular expression is provided, only permissions, objects, and parent names that match the pattern will be logged. ### `/pex|permissionsex import [source data store]` **Description:** Import data from another data store **Permission:** `permissionsex.import` Import permissions data from a configured backend, or automatically configured conversion provider. If no data store is specified, a list of available sources will be provided. This import will fully replace any subject in the active data store that is also present in the source data store ### `/pex|permissionsex ranking|rank [ladder]` **Description:** Print the contents of a rank ladder **Permission:** `permissionsex.rank.view.<ladder>` Clickable buttons are added to ease working with rank ladders. ### `/pex|permissionsex ranking|rank <ladder> add|+ <subject> [position] [-r|--relative]` **Description:** Add a subject to the rank ladder **Permission:** `permissionsex.rank.add.<ladder>` Adds a subject to the rank ladder, by default at the end of the ladder. If a position is specified, the rank will be inserted at that position. If the rank is already on the ladder and the `--relative` flag is provided, the rank will be moved by the specified number of positions. ### `/pex|permissionsex ranking|rank <ladder> remove|rem|- <subject>` **Description:** Remove a subject from a rank ladder. **Permission:** `permissionsex.rank.remove.<ladder>` Remove a subject from a rank ladder. ### `/pex|permissionsex reload|rel` **Description:** Reload all PermissionsEx configuration **Permission:** `permissionsex.reload` Reloads all permissions data. The reload is performed asynchronously, and new data will only be applied if the reload is successful. ### `/pex|permissionsex version [--verbose|-v]` **Description**: Provide information on the current PermissionsEx version. **Permission:** `permissionsex.version` Print detailed information on the version of PermissionsEx that is currently running. If the `verbose` option is provided, more detailed information on base directories will be printed. ### `/pex|permissions <type> list` **Description:** List all subjects of a certain type **Permission:** `permissionsex.list.<type>` ### `/pex|permissionsex <type> <subject> delete [--transient|-t]` **Description:**: Delete all data for a subject **Permission:** `permissionsex.delete.<type>.<subject>` ### `/pex|permissionsex <type> <subject> info` **Description:**: Print all known information for a certain subject. **Permission:** `permissionsex.info.<type>.<subject>` All information will be printed for the subject ### `/pex|permissionsex <type> <subject> option|options|opt|o|meta <key> [value] [--transient|-t] [--context key=value]` **Description:**: Sets or unsets an option for the subject **Permission:** `permissionsex.option.set.<type>.<subject>` Sets (if `value` is provided) or unset (if not provided) a certain option on the subject. ### `/pex|permissionsex <type> <subject> parents|parent|par|p add|a|+ <type> <subject> [--transient|t] [--context key=value]` **Description:**: Adds a parent to the subject **Permission:** `permissionsex.parent.add.<type>.<subject>` The parent will be added at the first position to the subject, meaning it will take priority over other parents. ### `/pex|permissionsex <type> <subject> parents|parent|par|p remove|rem|delete|del|- <type> <subject> [--transient|t] [--context key=value]` **Description:**: Adds a parent to the subject **Permission:** `permissionsex.parent.remove.<type>.<subject>` Remove the specified parent from the subject. ### `/pex|permissionsex <type> <subject> parents|parent|par|p remove|rem|delete|del|- <type> <subject> [--transient|t] [--context key=value...]` **Description:**: Replace all parents of the subject with one parent. **Permission:** `permissionsex.parent.set.<type>.<subject>` Remove all parents from the subject and replace them with the one provided subject. ### `/pex|permissionsex <type> <subject> permission|permissions|perm|perms|p <permission> <value> [--transient|t] [--context key=value...]` **Description:**: Set the permission for a subject **Permission:** `permissionsex.permission.set.<type>.<subject>` Set a permission on the subject. Permission values can be a true or false value to explicitly set the permission, `none`, `null`, or `unset` to clear the permission, or a number to assign a weight to the permission. - Prefixing a permission with `#` means that its value will only be applicable to a subject and its direct parents. - Glob syntax will be evaluated for permissions: - `permissionsex.{permission,parent}.set` will evaluate to both `permissionsex.permission.set` and `permissionsex.parent.set` - `some.permission[a-z]` will match `some.permissiona`, `some.permissionb`, and so on, all the way through until `some.permissionz` ### `/pex|permissionsex <type> <subject> permission-default|perms-def|permsdef|pdef|pd|default|def <value> [--transient|t] [--context key=value...]` **Description:**: Set the fallback permission value for a subject **Permission:** `permissionsex.permission.set-default.<type>.<subject>` Set the default permissions value for a subject. This is the result that is returned for a subject when no more specific node matches. This value is roughly equivalent to the `*` permission formerly used, but will not override permissions specifically set to `false`. ### `/promote` ### `/demote`
{ "content_hash": "fec00026dbd8c506aee788e1dc76384a", "timestamp": "", "source": "github", "line_count": 182, "max_line_length": 148, "avg_line_length": 37.44505494505494, "alnum_prop": 0.742626559060895, "repo_name": "PEXPlugins/PermissionsEx", "id": "3390e189aef3d84080d16937ef339050b3d0e4f9", "size": "6827", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "doc/components-in-detail/command.md", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "ANTLR", "bytes": "439" }, { "name": "Java", "bytes": "1202591" }, { "name": "Kotlin", "bytes": "151748" }, { "name": "Nix", "bytes": "571" }, { "name": "Shell", "bytes": "405" } ], "symlink_target": "" }
class Admin::NamespacesController < Admin::BaseController def index @special_namespaces = Namespace.where(global: true) @namespaces = Namespace.not_portus .where(global: false) .order("created_at ASC") .page(params[:page]) end end
{ "content_hash": "ddef05bdd931d924ce8294a2c91e84f5", "timestamp": "", "source": "github", "line_count": 9, "max_line_length": 57, "avg_line_length": 36, "alnum_prop": 0.5524691358024691, "repo_name": "angry-tony/Portus-20170827", "id": "465321e3b22fcd12057902a7db524cb34daf9129", "size": "324", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "app/controllers/admin/namespaces_controller.rb", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "18345" }, { "name": "HTML", "bytes": "139412" }, { "name": "JavaScript", "bytes": "53896" }, { "name": "Roff", "bytes": "18369" }, { "name": "Ruby", "bytes": "728063" }, { "name": "Shell", "bytes": "10400" }, { "name": "Vue", "bytes": "8387" } ], "symlink_target": "" }
FROM balenalib/up-core-plus-ubuntu:cosmic-run # remove several traces of debian python RUN apt-get purge -y python.* # http://bugs.python.org/issue19846 # > At the moment, setting "LANG=C" on a Linux system *fundamentally breaks Python 3*, and that's not OK. ENV LANG C.UTF-8 # install python dependencies RUN apt-get update && apt-get install -y --no-install-recommends \ ca-certificates \ netbase \ && rm -rf /var/lib/apt/lists/* # key 63C7CC90: public key "Simon McVittie <[email protected]>" imported # key 3372DCFA: public key "Donald Stufft (dstufft) <[email protected]>" imported RUN gpg --keyserver keyring.debian.org --recv-keys 4DE8FF2A63C7CC90 \ && gpg --keyserver keyserver.ubuntu.com --recv-key 6E3CBCE93372DCFA \ && gpg --keyserver keyserver.ubuntu.com --recv-keys 0x52a43a1e4b77b059 ENV PYTHON_VERSION 3.9.4 # if this is called "PIP_VERSION", pip explodes with "ValueError: invalid truth value '<VERSION>'" ENV PYTHON_PIP_VERSION 21.0.1 ENV SETUPTOOLS_VERSION 56.0.0 RUN set -x \ && buildDeps=' \ curl \ ' \ && apt-get update && apt-get install -y $buildDeps --no-install-recommends && rm -rf /var/lib/apt/lists/* \ && curl -SLO "http://resin-packages.s3.amazonaws.com/python/v$PYTHON_VERSION/Python-$PYTHON_VERSION.linux-amd64-openssl1.1.tar.gz" \ && echo "3cfb071eb95dcc80c29339ae8c534cd5072ab687d2c1c36d7a5a432bf35c9039 Python-$PYTHON_VERSION.linux-amd64-openssl1.1.tar.gz" | sha256sum -c - \ && tar -xzf "Python-$PYTHON_VERSION.linux-amd64-openssl1.1.tar.gz" --strip-components=1 \ && rm -rf "Python-$PYTHON_VERSION.linux-amd64-openssl1.1.tar.gz" \ && ldconfig \ && if [ ! -e /usr/local/bin/pip3 ]; then : \ && curl -SLO "https://raw.githubusercontent.com/pypa/get-pip/430ba37776ae2ad89f794c7a43b90dc23bac334c/get-pip.py" \ && echo "19dae841a150c86e2a09d475b5eb0602861f2a5b7761ec268049a662dbd2bd0c get-pip.py" | sha256sum -c - \ && python3 get-pip.py \ && rm get-pip.py \ ; fi \ && pip3 install --no-cache-dir --upgrade --force-reinstall pip=="$PYTHON_PIP_VERSION" setuptools=="$SETUPTOOLS_VERSION" \ && find /usr/local \ \( -type d -a -name test -o -name tests \) \ -o \( -type f -a -name '*.pyc' -o -name '*.pyo' \) \ -exec rm -rf '{}' + \ && cd / \ && rm -rf /usr/src/python ~/.cache # make some useful symlinks that are expected to exist RUN cd /usr/local/bin \ && ln -sf pip3 pip \ && { [ -e easy_install ] || ln -s easy_install-* easy_install; } \ && ln -sf idle3 idle \ && ln -sf pydoc3 pydoc \ && ln -sf python3 python \ && ln -sf python3-config python-config # set PYTHONPATH to point to dist-packages ENV PYTHONPATH /usr/lib/python3/dist-packages:$PYTHONPATH CMD ["echo","'No CMD command was set in Dockerfile! Details about CMD command could be found in Dockerfile Guide section in our Docs. Here's the link: https://balena.io/docs"] RUN curl -SLO "https://raw.githubusercontent.com/balena-io-library/base-images/8accad6af708fca7271c5c65f18a86782e19f877/scripts/assets/tests/[email protected]" \ && echo "Running test-stack@python" \ && chmod +x [email protected] \ && bash [email protected] \ && rm -rf [email protected] RUN [ ! -d /.balena/messages ] && mkdir -p /.balena/messages; echo 'Here are a few details about this Docker image (For more information please visit https://www.balena.io/docs/reference/base-images/base-images/): \nArchitecture: Intel 64-bit (x86-64) \nOS: Ubuntu cosmic \nVariant: run variant \nDefault variable(s): UDEV=off \nThe following software stack is preinstalled: \nPython v3.9.4, Pip v21.0.1, Setuptools v56.0.0 \nExtra features: \n- Easy way to install packages with `install_packages <package-name>` command \n- Run anywhere with cross-build feature (for ARM only) \n- Keep the container idling with `balena-idle` command \n- Show base image details with `balena-info` command' > /.balena/messages/image-info RUN echo '#!/bin/sh.real\nbalena-info\nrm -f /bin/sh\ncp /bin/sh.real /bin/sh\n/bin/sh "$@"' > /bin/sh-shim \ && chmod +x /bin/sh-shim \ && cp /bin/sh /bin/sh.real \ && mv /bin/sh-shim /bin/sh
{ "content_hash": "801db76a1d957316a1bb1e2690afaa72", "timestamp": "", "source": "github", "line_count": 78, "max_line_length": 723, "avg_line_length": 52.01282051282051, "alnum_prop": 0.7071727877742174, "repo_name": "nghiant2710/base-images", "id": "6d18a4befd8529bb66973ac009627750d13e7f59", "size": "4078", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "balena-base-images/python/up-core-plus/ubuntu/cosmic/3.9.4/run/Dockerfile", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Dockerfile", "bytes": "144558581" }, { "name": "JavaScript", "bytes": "16316" }, { "name": "Shell", "bytes": "368690" } ], "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> <title>Uses of Class org.apache.poi.hssf.record.IndexRecord (POI API Documentation)</title> <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 Class org.apache.poi.hssf.record.IndexRecord (POI API Documentation)"; } //--> </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="../../../../../../org/apache/poi/hssf/record/IndexRecord.html" title="class in org.apache.poi.hssf.record">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?org/apache/poi/hssf/record/class-use/IndexRecord.html" target="_top">Frames</a></li> <li><a href="IndexRecord.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 Class org.apache.poi.hssf.record.IndexRecord" class="title">Uses of Class<br>org.apache.poi.hssf.record.IndexRecord</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="../../../../../../org/apache/poi/hssf/record/IndexRecord.html" title="class in org.apache.poi.hssf.record">IndexRecord</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="#org.apache.poi.hssf.record.aggregates">org.apache.poi.hssf.record.aggregates</a></td> <td class="colLast"> <div class="block">record aggregates are not real "records" but collections of records that act as a single record.</div> </td> </tr> </tbody> </table> </li> <li class="blockList"> <ul class="blockList"> <li class="blockList"><a name="org.apache.poi.hssf.record.aggregates"> <!-- --> </a> <h3>Uses of <a href="../../../../../../org/apache/poi/hssf/record/IndexRecord.html" title="class in org.apache.poi.hssf.record">IndexRecord</a> in <a href="../../../../../../org/apache/poi/hssf/record/aggregates/package-summary.html">org.apache.poi.hssf.record.aggregates</a></h3> <table border="0" cellpadding="3" cellspacing="0" summary="Use table, listing methods, and an explanation"> <caption><span>Methods in <a href="../../../../../../org/apache/poi/hssf/record/aggregates/package-summary.html">org.apache.poi.hssf.record.aggregates</a> that return <a href="../../../../../../org/apache/poi/hssf/record/IndexRecord.html" title="class in org.apache.poi.hssf.record">IndexRecord</a></span><span class="tabEnd">&nbsp;</span></caption> <tr> <th class="colFirst" scope="col">Modifier and Type</th> <th class="colLast" scope="col">Method and Description</th> </tr> <tbody> <tr class="altColor"> <td class="colFirst"><code><a href="../../../../../../org/apache/poi/hssf/record/IndexRecord.html" title="class in org.apache.poi.hssf.record">IndexRecord</a></code></td> <td class="colLast"><span class="strong">RowRecordsAggregate.</span><code><strong><a href="../../../../../../org/apache/poi/hssf/record/aggregates/RowRecordsAggregate.html#createIndexRecord(int,%20int)">createIndexRecord</a></strong>(int&nbsp;indexRecordOffset, int&nbsp;sizeOfInitialSheetRecords)</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="../../../../../../org/apache/poi/hssf/record/IndexRecord.html" title="class in org.apache.poi.hssf.record">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?org/apache/poi/hssf/record/class-use/IndexRecord.html" target="_top">Frames</a></li> <li><a href="IndexRecord.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> <i>Copyright 2015 The Apache Software Foundation or its licensors, as applicable.</i> </small></p> </body> </html>
{ "content_hash": "61d7b344c55b1f1c0cb619be0d2678a4", "timestamp": "", "source": "github", "line_count": 160, "max_line_length": 349, "avg_line_length": 42.31875, "alnum_prop": 0.6166002067641412, "repo_name": "lunheur/JiraSorting", "id": "6c5b1127f99e287b7d32bd7fe31e639627b65c3c", "size": "6771", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "JiraSorting/lib/poi-3.12/docs/apidocs/org/apache/poi/hssf/record/class-use/IndexRecord.html", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "26462" }, { "name": "HTML", "bytes": "78171707" }, { "name": "Java", "bytes": "9424" } ], "symlink_target": "" }
<!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en"> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/> <link rel="SHORTCUT ICON" href="../../../../../img/clover.ico" /> <link rel="stylesheet" href="../../../../../aui/css/aui.min.css" media="all"/> <link rel="stylesheet" href="../../../../../aui/css/aui-experimental.min.css" media="all"/> <!--[if IE 9]><link rel="stylesheet" href="../../../../../aui/css/aui-ie9.min.css" media="all"/><![endif]--> <style type="text/css" media="all"> @import url('../../../../../style.css'); @import url('../../../../../tree.css'); </style> <script src="../../../../../jquery-1.8.3.min.js" type="text/javascript"></script> <script src="../../../../../aui/js/aui.min.js" type="text/javascript"></script> <script src="../../../../../aui/js/aui-experimental.min.js" type="text/javascript"></script> <script src="../../../../../aui/js/aui-soy.min.js" type="text/javascript"></script> <script src="../../../../../package-nodes-tree.js" type="text/javascript"></script> <script src="../../../../../clover-tree.js" type="text/javascript"></script> <script src="../../../../../clover.js" type="text/javascript"></script> <script src="../../../../../clover-descriptions.js" type="text/javascript"></script> <script src="../../../../../cloud.js" type="text/javascript"></script> <title>ABA Route Transit Number Validator 1.0.1-SNAPSHOT</title> </head> <body> <div id="page"> <header id="header" role="banner"> <nav class="aui-header aui-dropdown2-trigger-group" role="navigation"> <div class="aui-header-inner"> <div class="aui-header-primary"> <h1 id="logo" class="aui-header-logo aui-header-logo-clover"> <a href="http://openclover.org" title="Visit OpenClover home page"><span class="aui-header-logo-device">OpenClover</span></a> </h1> </div> <div class="aui-header-secondary"> <ul class="aui-nav"> <li id="system-help-menu"> <a class="aui-nav-link" title="Open online documentation" target="_blank" href="http://openclover.org/documentation"> <span class="aui-icon aui-icon-small aui-iconfont-help">&#160;Help</span> </a> </li> </ul> </div> </div> </nav> </header> <div class="aui-page-panel"> <div class="aui-page-panel-inner"> <div class="aui-page-panel-nav aui-page-panel-nav-clover"> <div class="aui-page-header-inner" style="margin-bottom: 20px;"> <div class="aui-page-header-image"> <a href="http://cardatechnologies.com" target="_top"> <div class="aui-avatar aui-avatar-large aui-avatar-project"> <div class="aui-avatar-inner"> <img src="../../../../../img/clover_logo_large.png" alt="Clover icon"/> </div> </div> </a> </div> <div class="aui-page-header-main" > <h1> <a href="http://cardatechnologies.com" target="_top"> ABA Route Transit Number Validator 1.0.1-SNAPSHOT </a> </h1> </div> </div> <nav class="aui-navgroup aui-navgroup-vertical"> <div class="aui-navgroup-inner"> <ul class="aui-nav"> <li class=""> <a href="../../../../../dashboard.html">Project overview</a> </li> </ul> <div class="aui-nav-heading packages-nav-heading"> <strong>Packages</strong> </div> <div class="aui-nav project-packages"> <form method="get" action="#" class="aui package-filter-container"> <input type="text" autocomplete="off" class="package-filter text" placeholder="Type to filter packages..." name="package-filter" id="package-filter" title="Start typing package name (or part of the name) to search through the tree. Use arrow keys and the Enter key to navigate."/> </form> <p class="package-filter-no-results-message hidden"> <small>No results found.</small> </p> <div class="packages-tree-wrapper" data-root-relative="../../../../../" data-package-name="com.cardatechnologies.utils.validators.abaroutevalidator"> <div class="packages-tree-container"></div> <div class="clover-packages-lozenges"></div> </div> </div> </div> </nav> </div> <section class="aui-page-panel-content"> <div class="aui-page-panel-content-clover"> <div class="aui-page-header-main"><ol class="aui-nav aui-nav-breadcrumbs"> <li><a href="../../../../../dashboard.html"> Project Clover database Sat Aug 7 2021 12:29:33 MDT</a></li> <li><a href="test-pkg-summary.html">Package com.cardatechnologies.utils.validators.abaroutevalidator</a></li> <li><a href="test-Test_AbaRouteValidator_13b.html">Class Test_AbaRouteValidator_13b</a></li> </ol></div> <h1 class="aui-h2-clover"> Test testAbaNumberCheck_28965_good </h1> <table class="aui"> <thead> <tr> <th>Test</th> <th><label title="The test result. Either a Pass, Fail or Error.">Status</label></th> <th><label title="When the test execution was started">Start time</label></th> <th><label title="The total time in seconds taken to run this test.">Time (seconds)</label></th> <th><label title="A failure or error message if the test is not successful.">Message</label></th> </tr> </thead> <tbody> <tr> <td> <a href="../../../../../com/cardatechnologies/utils/validators/abaroutevalidator/Test_AbaRouteValidator_13b.html?line=42424#src-42424" >testAbaNumberCheck_28965_good</a> </td> <td> <span class="sortValue">1</span><span class="aui-lozenge aui-lozenge-success">PASS</span> </td> <td> 7 Aug 12:43:07 </td> <td> 0.0 </td> <td> <div></div> <div class="errorMessage"></div> </td> </tr> </tbody> </table> <div>&#160;</div> <table class="aui aui-table-sortable"> <thead> <tr> <th style="white-space:nowrap;"><label title="A class that was directly hit by this test.">Target Class</label></th> <th colspan="4"><label title="The percentage of coverage contributed by each single test.">Coverage contributed by</label> testAbaNumberCheck_28965_good</th> </tr> </thead> <tbody> <tr> <td> <span class="sortValue">com.cardatechnologies.utils.validators.abaroutevalidator.AbaRouteValidator</span> &#160;&#160;<a href="../../../../../com/cardatechnologies/utils/validators/abaroutevalidator/AbaRouteValidator.html?id=32352#AbaRouteValidator" title="AbaRouteValidator" name="sl-47">com.cardatechnologies.utils.validators.abaroutevalidator.AbaRouteValidator</a> </td> <td> <span class="sortValue">0.7352941</span>73.5% </td> <td class="align-middle" style="width: 100%" colspan="3"> <div> <div title="73.5% Covered" style="min-width:40px;" class="barNegative contribBarNegative contribBarNegative"><div class="barPositive contribBarPositive contribBarPositive" style="width:73.5%"></div></div></div> </td> </tr> </tbody> </table> </div> <!-- class="aui-page-panel-content-clover" --> <footer id="footer" role="contentinfo"> <section class="footer-body"> <ul> <li> Report generated by <a target="_new" href="http://openclover.org">OpenClover</a> v 4.4.1 on Sat Aug 7 2021 12:49:26 MDT using coverage data from Sat Aug 7 2021 12:47:23 MDT. </li> </ul> <ul> <li>OpenClover is free and open-source software. </li> </ul> </section> </footer> </section> <!-- class="aui-page-panel-content" --> </div> <!-- class="aui-page-panel-inner" --> </div> <!-- class="aui-page-panel" --> </div> <!-- id="page" --> </body> </html>
{ "content_hash": "367da35727e7c1772fea2e4072d8b08b", "timestamp": "", "source": "github", "line_count": 209, "max_line_length": 297, "avg_line_length": 43.942583732057415, "alnum_prop": 0.5099085365853658, "repo_name": "dcarda/aba.route.validator", "id": "8454296b604ae162a173f21f3ae4543367579d51", "size": "9184", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "target13/site/clover/com/cardatechnologies/utils/validators/abaroutevalidator/Test_AbaRouteValidator_13b_testAbaNumberCheck_28965_good_oyo.html", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "18715254" } ], "symlink_target": "" }
/// <reference path="../_references.ts"/> module powerbitests.customVisuals { import VisualClass = powerbi.visuals.samples.Histogram; import ValueByAgeData = powerbitests.customVisuals.sampleDataViews.ValueByAgeData; import assertColorsMatch = powerbitests.helpers.assertColorsMatch; describe("HistogramChart", () => { let visualBuilder: HistogramChartBuilder; let defaultDataViewBuilder: ValueByAgeData; let dataView: powerbi.DataView; beforeEach(() => { visualBuilder = new HistogramChartBuilder(1000,500); defaultDataViewBuilder = new ValueByAgeData(); dataView = defaultDataViewBuilder.getDataView(); }); describe("capabilities", () => { it("registered capabilities", () => expect(VisualClass.capabilities).toBeDefined()); }); describe("DOM tests", () => { it("svg element created", () => expect(visualBuilder.mainElement[0]).toBeInDOM()); it("update", (done) => { visualBuilder.updateRenderTimeout(dataView, () => { let binsNumber = d3.layout.histogram().frequency(true)(dataView.categorical.categories[0].values).length; expect(visualBuilder.mainElement.find(".column").length).toBe(binsNumber); done(); }); }); }); describe("property pane changes", () => { it("Validate data point color change", (done) => { dataView.metadata.objects = { dataPoint: { fill: { solid: { color: "#ff0000" } } } }; visualBuilder.updateRenderTimeout(dataView, () => { let elements = visualBuilder.mainElement.find(".column"); elements.each((index, elem) => { assertColorsMatch($(elem).css("fill"), "#ff0000"); }); done(); }); }); it("Validate bins count change", (done) => { dataView.metadata.objects = { general: { bins: 3 } }; visualBuilder.updateRenderTimeout(dataView, () => { let binsCount = visualBuilder.mainElement.find(".column").length; dataView.metadata.objects = { general: { bins: 6 } }; visualBuilder.updateRenderTimeout(dataView, () => { let binsAfterUpdate = visualBuilder.mainElement.find(".column").length; expect(binsCount).toBe(3); expect(binsAfterUpdate).toBeGreaterThan(binsCount); expect(binsAfterUpdate).toBe(6); done(); }); }); }); it("Validate start bigger than end at y axis", (done) => { dataView.metadata.objects = { yAxis: { start: 65, end:33 } }; visualBuilder.updateRenderTimeout(dataView, () => { let firstY = parseInt(visualBuilder.mainElement.find(".axis:last .tick:first text").text(),10); expect(firstY).toBe(0); done(); }); }); it('Validate position right y axis', (done) => { dataView.metadata.objects = { yAxis: { position: "Right" } }; visualBuilder.update(dataView); setTimeout(() => { var firstY = parseInt(visualBuilder.mainElement.find('.axis:last').attr("transform").split(',')[0].split('(')[1], 10); var lastX = parseInt(visualBuilder.mainElement.find('.axis:first .tick:last').attr("transform").split(',')[0].split('(')[1], 10); expect(firstY).toBe(lastX); done(); }, DefaultWaitForRender); }); it('Validate Data Label', (done) => { dataView.metadata.objects = { labels: { show: true } }; visualBuilder.updateRenderTimeout(dataView, () => { let columns = (visualBuilder.mainElement.find(".columns rect")).length; let dataLabels = (visualBuilder.mainElement.find(".labels text")).length; expect(columns).toBe(dataLabels); done(); }); }); it('Validate title disabled', (done) => { dataView.metadata.objects = { yAxis: { title: false } }; visualBuilder.update(dataView); setTimeout(() => { var title = visualBuilder.mainElement.find('.legends text:last').attr("style").indexOf("display: none") > -1; expect(title).toBe(true); done(); }, DefaultWaitForRender); }); }); }); class HistogramChartBuilder extends VisualBuilderBase<VisualClass> { constructor(width: number, height: number, isMinervaVisualPlugin: boolean = false) { super(width, height, isMinervaVisualPlugin); } protected build() { return new VisualClass(); } public get mainElement() { return this.element.children("svg"); } } }
{ "content_hash": "ac393df04855219a7a0eaa9a1e47f738", "timestamp": "", "source": "github", "line_count": 155, "max_line_length": 149, "avg_line_length": 37.10322580645161, "alnum_prop": 0.47713441140671187, "repo_name": "sagarvadodaria/PowerBI-visuals", "id": "50c0f8ecb74f702fe81edb571b8920efa762016b", "size": "6973", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/Clients/PowerBIVisualsTests/customVisuals/histogramChartTests.ts", "mode": "33188", "license": "mit", "language": [ { "name": "Batchfile", "bytes": "78" }, { "name": "CSS", "bytes": "835857" }, { "name": "HTML", "bytes": "12571" }, { "name": "JavaScript", "bytes": "18471108" }, { "name": "TypeScript", "bytes": "10045267" } ], "symlink_target": "" }
<?php namespace GDAPI; class Type { private $clientId; public function __construct($clientId,$schema) { $this->clientId = $clientId; $this->schema = $schema; } public function getById($id) { $url = $this->getUrl($id); $client = $this->getClient(); return $client->request('GET', $url); } public function query($filters=array(), $sort=array(), $pagination=array(), $include=array()) { $options = array( 'filters' => $filters, 'sort' => $sort, 'pagination' => $pagination, 'include' => $include, ); $url = static::listHref($this->getUrl(), $options); $client = $this->getClient(); return $client->request('GET', $url); } public function create($obj) { $data = ( $obj instanceof Resource ? $obj->getMeta() : $obj ); $url = $this->getUrl(); $client = $this->getClient(); return $client->request('POST', $url, array(), $data, Client::MIME_TYPE_JSON); } public function remove($id_or_obj) { $id = ( $id_or_obj instanceof Resource ? $id_or_obj->getId() : $id_or_obj ); $url = $this->getUrl($id); $client = $this->getClient(); return $client->request('DELETE', $url); } public function schema() { return $this->schema; } public function resourceField($name) { if ( $this->schema->metaIsSet('resourceFields') ) $fields = $this->schema->getResourceFields(); else $fields = $this->schema->getFields(); if ( isset($fields->{$name}) ) { return $fields->{$name}; } return null; } public function collectionField($name) { $fields = $this->schema->getCollectionFields(); if ( isset($fields->{$name}) ) { return $fields->{$name}; } return null; } protected function getUrl($id=false) { return $this->schema->getLink('collection') . ($id === false ? '' : '/'.urlencode($id) ); } public static function listHref($url, $opt) { $opt = static::arrayify($opt); $qs = parse_url($url,PHP_URL_QUERY); # Filters if ( isset($opt['filters']) && count($opt['filters']) ) { // 'filters' is a hash of field names => filter or array(filters) // Each filter value can be: // - A simple literal like 'blah', ("name equals blah") // - A hash with modifier and/or value: array('modifier' => 'ne', value => 'blah') ("name is not equal to blah") // - An array of one or more of the above: array('blah', array('modifier' => 'notnull') ("name is equal to blah AND name is not null") // Loop over the hash of each field name foreach ( $opt['filters'] as $fieldName => $list ) { // Turn whatever the input was into an aray of individual filters to check if ( !is_array($list) ) { // Simple value $list = array($list); } else if ( isset($list['value']) || isset($list['modifier']) ) { // It's an "array", but really a hash like array('modifier' => 'blah', 'value' => blah') $list = array($list); } else { // Already an array of individual filters, do nothing } // Loop over each individual filter for this field foreach ( $list as $filter ) { // This is a filter like array('modifier' => 'blah', 'value' => blah') if ( is_array($filter) && ( isset($filter['value']) || isset($filter['modifier']) ) ) { $name = $fieldName; if ( isset($filter['modifier']) && $filter['modifier'] != '' && $filter['modifier'] != 'eq' ) $name .= '_' . $filter['modifier']; $value = null; if ( isset($filter['value']) ) { $value = $filter['value']; } } else { // This is a simple literal name=value literal $name = $fieldName; $value = $filter; } $qs .= '&' . urlencode($name); // Only add value if it's meaningful // (Note: A filter with value => null is invalid, use array('modifier' => 'null') to say that a field is null) if ( $value !== null ) $qs .= '='. urlencode($value); } } } # Sorting if ( isset($opt['sort']) && count($opt['sort']) ) { if ( is_array($opt['sort']) ) { $qs .= '&sort=' . urlencode($opt['sort']['name']); if ( isset($opt['sort']['order']) && strtolower($opt['sort']['order']) == 'desc' ) { $qs .= '&order=desc'; } } } # Pagination if ( isset($opt['pagination']) && count($opt['pagination']) ) { $qs .= '&limit=' . intval($opt['pagination']['limit']); if ( isset($opt['pagination']['marker']) ) { $qs .= '&marker=' . urlencode($opt['pagination']['marker']); } } # Include if ( isset($opt['include']) && count($opt['include']) ) { foreach ( $opt['include'] as $link ) { $qs .= '&include=' . urlencode($link); } } $base_url = preg_replace("/\?.*/","",$url); $out = $base_url; if ( $qs ) { // If the initial URL query string was empty, there will be an extra & at the beginning $out .= '?' . preg_replace("/^&/","",$qs); } return $out; } static function arrayify($obj) { if ( is_object($obj) ) $ary = get_object_vars($obj); else $ary = $obj; foreach ( $ary as $k => $v ) { if ( is_array($v) || is_object($v) ) { $v = static::arrayify($v); $ary[$k] = $v; } } return $ary; } protected function &getClient() { return Client::get($this->clientId); } } ?>
{ "content_hash": "b56699ee697f3974de8dff60697723d9", "timestamp": "", "source": "github", "line_count": 225, "max_line_length": 140, "avg_line_length": 25.77777777777778, "alnum_prop": 0.5044827586206897, "repo_name": "godaddy/gdapi-php", "id": "6c9cab4bcb8b128e045c4bf776bb7e7ce7648698", "size": "6935", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "class/Type.php", "mode": "33188", "license": "mit", "language": [ { "name": "PHP", "bytes": "61856" } ], "symlink_target": "" }
<?php namespace Services\Event; use Services\IBaseService; //Each repository class would implement its own interface class which //extends the IBaseService: interface IEventService extends IBaseService { }
{ "content_hash": "316c327756cd5d8fe5802412877dd1d6", "timestamp": "", "source": "github", "line_count": 12, "max_line_length": 72, "avg_line_length": 19.333333333333332, "alnum_prop": 0.728448275862069, "repo_name": "RowlandOti/SlimeApi", "id": "2c37e2117a70de7db86f63e31eb123f11ece4098", "size": "232", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "app/models/services/event/IEventService.php", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "PHP", "bytes": "123845" } ], "symlink_target": "" }
import React from 'react'; import {FilePair} from './CodeDiff'; import {PerceptualDiffMode} from './DiffView'; import {isSameSizeImagePair} from './utils'; // XXX should this just be a component? /** * Returns a React.DIV which boxes the changed parts of the image pair. * scaleDown is in [0, 1], with 1 being full-size */ export function makePerceptualBoxDiv( pdiffMode: PerceptualDiffMode, filePair: FilePair, scaleDown: number, ) { if (pdiffMode === 'off' || !isSameSizeImagePair(filePair)) { return null; } else if (pdiffMode === 'bbox') { var padding = 5; // try not to obscure anything inside the box if (filePair.diffData && filePair.diffData.diffBounds) { const bbox = filePair.diffData.diffBounds; const {top, left, right, bottom, width, height} = bbox; if (width === 0 || height === 0) return null; const styles = { top: Math.floor(scaleDown * (top - padding)) + 'px', left: Math.floor(scaleDown * (left - padding)) + 'px', width: Math.ceil(scaleDown * (right - left + 2 * padding)) + 'px', height: Math.ceil(scaleDown * (bottom - top + 2 * padding)) + 'px', }; return <div className="perceptual-diff bbox" style={styles} />; } else { return null; } } else if (pdiffMode === 'pixels') { const styles = {top: 0, left: 0}; const width = filePair.image_a.width * scaleDown; const height = filePair.image_a.height * scaleDown; const src = `/pdiff/${filePair.idx}`; return ( <img className="perceptual-diff pixels" style={styles} width={width} height={height} src={src} /> ); } }
{ "content_hash": "7b82bf87361b3d0659aa4c3ca1f81ba9", "timestamp": "", "source": "github", "line_count": 50, "max_line_length": 75, "avg_line_length": 33.48, "alnum_prop": 0.6129032258064516, "repo_name": "danvk/webdiff", "id": "f8957e106963291d9ea4a3b5ff7054509267e0af", "size": "1674", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "ts/image_utils.tsx", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "9392" }, { "name": "HTML", "bytes": "2775" }, { "name": "JavaScript", "bytes": "34314" }, { "name": "Python", "bytes": "34994" }, { "name": "Shell", "bytes": "212" }, { "name": "TypeScript", "bytes": "31438" } ], "symlink_target": "" }
""" <Program> transition_canonical_to_twopercent.py <Purpose> The purpose of this program is to transition nodes from the canonical state to the twopercent state by bypassing through the movingto_twopercent state. <Started> November 10, 2010 <Author> Monzur Muhammad [email protected] <Usage> Ensure that clearinghouse and seattle are in the PYTHONPATH. Ensure that the database is setup properly and django settings are set correctly. python transition_canonical_to_twopercent.py """ import os import node_transition_lib # The full path to the onepercentmanyevents.resources file, including the filename. RESOURCES_TEMPLATE_FILE_PATH = os.path.join(os.path.dirname(__file__), "resource_files", "twopercent.resources") def main(): """ <Purpose> The main function that calls the process_nodes_and_change_state() function in the node_transition_lib passing in the process and error functions. <Arguments> None <Exceptions> None <Side Effects> None """ # Open and read the resource file that is necessary for twopercent vessels. # This will determine how the vessels will be split and how much resource # will be allocated to each vessel. twopercent_resource_fd = file(RESOURCES_TEMPLATE_FILE_PATH) twopercent_resourcetemplate = twopercent_resource_fd.read() twopercent_resource_fd.close() # We are going to transition all the nodes that are in the canonical state # to the twopercent state. We are going to do this in three different # state. First we are going to transition all the canonical state nodes # to the movingto_twopercent state with a no-op function. The reason for # this is, so if anything goes wrong, we can revert back. # In the second step we are going to attempt to move all the nodes in the # movingto_twopercent state to the twopercent state. The way to do this, is # we are going to split the vessels by giving each vessel the resources # that are described in the resource template. # Next we are going to try to transition all the nodes in the # movingto_twopercent state to the canonical state. Any nodes that failed # to go to the twopercent are still stuck in the movingto_twopercent state, # and we want to move them back to the canonical state. # Variables that determine weather to mark a node inactive or not. mark_node_inactive = False mark_node_active = True state_function_arg_tuplelist = [ ("canonical", "movingto_twopercent", node_transition_lib.noop, node_transition_lib.noop, mark_node_inactive), ("movingto_twopercent", "twopercent", node_transition_lib.split_vessels, node_transition_lib.noop, mark_node_active, twopercent_resourcetemplate), ("movingto_twopercent", "canonical", node_transition_lib.combine_vessels, node_transition_lib.noop, mark_node_inactive)] sleeptime = 10 process_name = "canonical_to_twopercent" parallel_instances = 10 #call process_nodes_and_change_state() to start the node state transition node_transition_lib.process_nodes_and_change_state(state_function_arg_tuplelist, process_name, sleeptime, parallel_instances) if __name__ == '__main__': main()
{ "content_hash": "74ccbbe4d0ee3c13fe67f66454699c35", "timestamp": "", "source": "github", "line_count": 105, "max_line_length": 128, "avg_line_length": 30.6, "alnum_prop": 0.7379396202925614, "repo_name": "SensibilityTestbed/clearinghouse", "id": "ed38d068c71c8980b2b20239b6a2cd4932491e33", "size": "3213", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "node_state_transitions/transition_canonical_to_twopercent.py", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "23149" }, { "name": "HTML", "bytes": "73669" }, { "name": "JavaScript", "bytes": "30670" }, { "name": "Python", "bytes": "947344" }, { "name": "Shell", "bytes": "13984" } ], "symlink_target": "" }
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>angles: 31 s 🏆</title> <link rel="shortcut icon" type="image/png" href="../../../../../favicon.png" /> <link href="../../../../../bootstrap.min.css" rel="stylesheet"> <link href="../../../../../bootstrap-custom.css" rel="stylesheet"> <link href="//maxcdn.bootstrapcdn.com/font-awesome/4.2.0/css/font-awesome.min.css" rel="stylesheet"> <script src="../../../../../moment.min.js"></script> <!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries --> <!-- WARNING: Respond.js doesn't work if you view the page via file:// --> <!--[if lt IE 9]> <script src="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script> <script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script> <![endif]--> </head> <body> <div class="container"> <div class="navbar navbar-default" role="navigation"> <div class="container-fluid"> <div class="navbar-header"> <a class="navbar-brand" href="../../../../.."><i class="fa fa-lg fa-flag-checkered"></i> Coq bench</a> </div> <div id="navbar" class="collapse navbar-collapse"> <ul class="nav navbar-nav"> <li><a href="../..">clean / extra-dev</a></li> <li class="active"><a href="">dev / angles - dev</a></li> </ul> </div> </div> </div> <div class="article"> <div class="row"> <div class="col-md-12"> <a href="../..">« Up</a> <h1> angles <small> dev <span class="label label-success">31 s 🏆</span> </small> </h1> <p>📅 <em><script>document.write(moment("2022-03-29 02:01:24 +0000", "YYYY-MM-DD HH:mm:ss Z").fromNow());</script> (2022-03-29 02:01:24 UTC)</em><p> <h2>Context</h2> <pre># Packages matching: installed # Name # Installed # Synopsis base-bigarray base base-threads base base-unix base conf-findutils 1 Virtual package relying on findutils conf-gmp 4 Virtual package relying on a GMP lib system installation coq dev Formal proof management system dune 3.0.3 Fast, portable, and opinionated build system ocaml 4.11.2 The OCaml compiler (virtual package) ocaml-base-compiler 4.11.2 Official release 4.11.2 ocaml-config 1 OCaml Switch Configuration ocamlfind 1.9.3 A library manager for OCaml zarith 1.12 Implements arithmetic and logical operations over arbitrary-precision integers # opam file: opam-version: &quot;2.0&quot; maintainer: &quot;[email protected]&quot; homepage: &quot;https://github.com/coq-contribs/angles&quot; license: &quot;Proprietary&quot; build: [ [&quot;coq_makefile&quot; &quot;-f&quot; &quot;Make&quot; &quot;-o&quot; &quot;Makefile&quot;] [make &quot;-j%{jobs}%&quot;] ] install: [make &quot;install&quot;] remove: [&quot;rm&quot; &quot;-R&quot; &quot;%{lib}%/coq/user-contrib/Angles&quot;] depends: [ &quot;ocaml&quot; &quot;coq&quot; {= &quot;dev&quot;} ] tags: [ &quot;keyword:pcoq&quot; &quot;keyword:geometry&quot; &quot;keyword:plane geometry&quot; &quot;keyword:oriented angles&quot; &quot;category:Mathematics/Geometry/General&quot; &quot;date:2002-01-15&quot; ] authors: [ &quot;Frédérique Guilhot &lt;[email protected]&gt;&quot; ] synopsis: &quot;Formalization of the oriented angles theory.&quot; description: &quot;&quot;&quot; The basis of the contribution is a formalization of the theory of oriented angles of non-zero vectors. Then, we prove some classical plane geometry theorems: the theorem which gives a necessary and sufficient condition so that four points are cocyclic, the one which shows that the reflected points with respect to the sides of a triangle orthocenter are on its circumscribed circle, the Simson&#39;s theorem and the Napoleon&#39;s theorem. The reader can refer to the associated research report (http://www-sop.inria.fr/lemme/FGRR.ps) and the README file of the contribution.&quot;&quot;&quot; flags: light-uninstall url { src: &quot;git+https://github.com/coq-contribs/angles.git#master&quot; } </pre> <h2>Lint</h2> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>true</code></dd> <dt>Return code</dt> <dd>0</dd> </dl> <h2>Dry install 🏜️</h2> <p>Dry install with the current Coq version:</p> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>opam install -y --show-action coq-angles.dev coq.dev</code></dd> <dt>Return code</dt> <dd>0</dd> </dl> <p>Dry install without Coq/switch base, to test if the problem was incompatibility with the current Coq/OCaml version:</p> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>true</code></dd> <dt>Return code</dt> <dd>0</dd> </dl> <h2>Install dependencies</h2> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>opam list; echo; ulimit -Sv 4000000; timeout 4h opam install -y --deps-only coq-angles.dev coq.dev</code></dd> <dt>Return code</dt> <dd>0</dd> <dt>Duration</dt> <dd>11 s</dd> </dl> <h2>Install 🚀</h2> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>opam list; echo; ulimit -Sv 16000000; timeout 4h opam install -y coq-angles.dev coq.dev</code></dd> <dt>Return code</dt> <dd>0</dd> <dt>Duration</dt> <dd>31 s</dd> </dl> <h2>Installation size</h2> <p>Total: 907 K</p> <ul> <li>200 K <code>../ocaml-base-compiler.4.11.2/lib/coq/user-contrib/Angles/point_tangente.glob</code></li> <li>192 K <code>../ocaml-base-compiler.4.11.2/lib/coq/user-contrib/Angles/point_cocyclicite.glob</code></li> <li>111 K <code>../ocaml-base-compiler.4.11.2/lib/coq/user-contrib/Angles/point_napoleon.glob</code></li> <li>111 K <code>../ocaml-base-compiler.4.11.2/lib/coq/user-contrib/Angles/point_angle.glob</code></li> <li>36 K <code>../ocaml-base-compiler.4.11.2/lib/coq/user-contrib/Angles/point_Simson.glob</code></li> <li>31 K <code>../ocaml-base-compiler.4.11.2/lib/coq/user-contrib/Angles/point_napoleon.vo</code></li> <li>30 K <code>../ocaml-base-compiler.4.11.2/lib/coq/user-contrib/Angles/point_tangente.v</code></li> <li>29 K <code>../ocaml-base-compiler.4.11.2/lib/coq/user-contrib/Angles/point_cocyclicite.vo</code></li> <li>29 K <code>../ocaml-base-compiler.4.11.2/lib/coq/user-contrib/Angles/point_cocyclicite.v</code></li> <li>28 K <code>../ocaml-base-compiler.4.11.2/lib/coq/user-contrib/Angles/point_tangente.vo</code></li> <li>27 K <code>../ocaml-base-compiler.4.11.2/lib/coq/user-contrib/Angles/point_angle.vo</code></li> <li>21 K <code>../ocaml-base-compiler.4.11.2/lib/coq/user-contrib/Angles/point_orthocentre.glob</code></li> <li>19 K <code>../ocaml-base-compiler.4.11.2/lib/coq/user-contrib/Angles/point_napoleon.v</code></li> <li>18 K <code>../ocaml-base-compiler.4.11.2/lib/coq/user-contrib/Angles/point_angle.v</code></li> <li>10 K <code>../ocaml-base-compiler.4.11.2/lib/coq/user-contrib/Angles/point_Simson.vo</code></li> <li>6 K <code>../ocaml-base-compiler.4.11.2/lib/coq/user-contrib/Angles/point_Simson.v</code></li> <li>5 K <code>../ocaml-base-compiler.4.11.2/lib/coq/user-contrib/Angles/point_orthocentre.vo</code></li> <li>2 K <code>../ocaml-base-compiler.4.11.2/lib/coq/user-contrib/Angles/point_orthocentre.v</code></li> </ul> <h2>Uninstall 🧹</h2> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>opam remove -y coq-angles.dev</code></dd> <dt>Return code</dt> <dd>0</dd> <dt>Missing removes</dt> <dd> none </dd> <dt>Wrong removes</dt> <dd> none </dd> </dl> </div> </div> </div> <hr/> <div class="footer"> <p class="text-center"> Sources are on <a href="https://github.com/coq-bench">GitHub</a> © Guillaume Claret 🐣 </p> </div> </div> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <script src="../../../../../bootstrap.min.js"></script> </body> </html>
{ "content_hash": "91cb47171bd2061a3e6d9049d043ede4", "timestamp": "", "source": "github", "line_count": 184, "max_line_length": 212, "avg_line_length": 49.90217391304348, "alnum_prop": 0.571335221084731, "repo_name": "coq-bench/coq-bench.github.io", "id": "84a285bc4122c149106bc7ddf5cbe7c5257df803", "size": "9209", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "clean/Linux-x86_64-4.11.2-2.0.7/extra-dev/dev/angles/dev.html", "mode": "33188", "license": "mit", "language": [], "symlink_target": "" }
import '../../index'; import { Reference } from '../../src/api/Reference'; import { Query } from '../../src/api/Query'; import { RepoInfo } from '../../src/core/RepoInfo'; export declare const TEST_PROJECT: any; /** * Fake Firebase App Authentication functions for testing. * @param {!FirebaseApp} app * @return {!FirebaseApp} */ export declare function patchFakeAuthFunctions(app: any): any; /** * Gets or creates a root node to the test namespace. All calls sharing the * value of opt_i will share an app context. * @param {number=} i * @param {string=} ref * @return {Reference} */ export declare function getRootNode(i?: number, ref?: string): any; /** * Create multiple refs to the same top level * push key - each on it's own Firebase.Context. * @param {int=} numNodes * @return {Reference|Array<Reference>} */ export declare function getRandomNode(numNodes?: any): Reference | Array<Reference>; export declare function getQueryValue(query: Query): Promise<any>; export declare function pause(milliseconds: number): Promise<{}>; export declare function getPath(query: Query): string; export declare function shuffle(arr: any, randFn?: () => number): void; export declare function testAuthTokenProvider(app: any): { setToken: (token: any) => Promise<void>; setNextToken: (token: any) => void; }; export declare function getFreshRepo(url: any, path?: any): any; export declare function getFreshRepoFromReference(ref: any): any; export declare function getSnap(path: any): any; export declare function getVal(path: any): any; export declare function canCreateExtraConnections(): boolean; export declare function buildObjFromKey(key: any): {}; export declare function testRepoInfo(url: any): RepoInfo;
{ "content_hash": "695dd645aa8f3372245a27913f3ffd37", "timestamp": "", "source": "github", "line_count": 41, "max_line_length": 84, "avg_line_length": 43.1219512195122, "alnum_prop": 0.709841628959276, "repo_name": "tipographo/tipographo.github.io", "id": "4cfecf2f4fc0a90e397d9666e78140bf7b35a3e7", "size": "1768", "binary": false, "copies": "6", "ref": "refs/heads/master", "path": "node_modules/@firebase/database/dist/packages/database/test/helpers/util.d.ts", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "21077" }, { "name": "HTML", "bytes": "225781" }, { "name": "JavaScript", "bytes": "43710" }, { "name": "PHP", "bytes": "1218" } ], "symlink_target": "" }
MAKEFLAGS=-r # The source directory tree. srcdir := .. abs_srcdir := $(abspath $(srcdir)) # The name of the builddir. builddir_name ?= . # The V=1 flag on command line makes us verbosely print command lines. ifdef V quiet= else quiet=quiet_ endif # Specify BUILDTYPE=Release on the command line for a release build. BUILDTYPE ?= Release # Directory all our build output goes into. # Note that this must be two directories beneath src/ for unit tests to pass, # as they reach into the src/ directory for data with relative paths. builddir ?= $(builddir_name)/$(BUILDTYPE) abs_builddir := $(abspath $(builddir)) depsdir := $(builddir)/.deps # Object output directory. obj := $(builddir)/obj abs_obj := $(abspath $(obj)) # We build up a list of every single one of the targets so we can slurp in the # generated dependency rule Makefiles in one pass. all_deps := CC.target ?= $(CC) CFLAGS.target ?= $(CFLAGS) CXX.target ?= $(CXX) CXXFLAGS.target ?= $(CXXFLAGS) LINK.target ?= $(LINK) LDFLAGS.target ?= $(LDFLAGS) AR.target ?= $(AR) # C++ apps need to be linked with g++. # # Note: flock is used to seralize linking. Linking is a memory-intensive # process so running parallel links can often lead to thrashing. To disable # the serialization, override LINK via an envrionment variable as follows: # # export LINK=g++ # # This will allow make to invoke N linker processes as specified in -jN. LINK ?= ./gyp-mac-tool flock $(builddir)/linker.lock $(CXX.target) # TODO(evan): move all cross-compilation logic to gyp-time so we don't need # to replicate this environment fallback in make as well. CC.host ?= gcc CFLAGS.host ?= CXX.host ?= g++ CXXFLAGS.host ?= LINK.host ?= $(CXX.host) LDFLAGS.host ?= AR.host ?= ar # Define a dir function that can handle spaces. # http://www.gnu.org/software/make/manual/make.html#Syntax-of-Functions # "leading spaces cannot appear in the text of the first argument as written. # These characters can be put into the argument value by variable substitution." empty := space := $(empty) $(empty) # http://stackoverflow.com/questions/1189781/using-make-dir-or-notdir-on-a-path-with-spaces replace_spaces = $(subst $(space),?,$1) unreplace_spaces = $(subst ?,$(space),$1) dirx = $(call unreplace_spaces,$(dir $(call replace_spaces,$1))) # Flags to make gcc output dependency info. Note that you need to be # careful here to use the flags that ccache and distcc can understand. # We write to a dep file on the side first and then rename at the end # so we can't end up with a broken dep file. depfile = $(depsdir)/$(call replace_spaces,$@).d DEPFLAGS = -MMD -MF $(depfile).raw # We have to fixup the deps output in a few ways. # (1) the file output should mention the proper .o file. # ccache or distcc lose the path to the target, so we convert a rule of # the form: # foobar.o: DEP1 DEP2 # into # path/to/foobar.o: DEP1 DEP2 # (2) we want missing files not to cause us to fail to build. # We want to rewrite # foobar.o: DEP1 DEP2 \ # DEP3 # to # DEP1: # DEP2: # DEP3: # so if the files are missing, they're just considered phony rules. # We have to do some pretty insane escaping to get those backslashes # and dollar signs past make, the shell, and sed at the same time. # Doesn't work with spaces, but that's fine: .d files have spaces in # their names replaced with other characters. define fixup_dep # The depfile may not exist if the input file didn't have any #includes. touch $(depfile).raw # Fixup path as in (1). sed -e "s|^$(notdir $@)|$@|" $(depfile).raw >> $(depfile) # Add extra rules as in (2). # We remove slashes and replace spaces with new lines; # remove blank lines; # delete the first line and append a colon to the remaining lines. sed -e 's|\\||' -e 'y| |\n|' $(depfile).raw |\ grep -v '^$$' |\ sed -e 1d -e 's|$$|:|' \ >> $(depfile) rm $(depfile).raw endef # Command definitions: # - cmd_foo is the actual command to run; # - quiet_cmd_foo is the brief-output summary of the command. quiet_cmd_cc = CC($(TOOLSET)) $@ cmd_cc = $(CC.$(TOOLSET)) $(GYP_CFLAGS) $(DEPFLAGS) $(CFLAGS.$(TOOLSET)) -c -o $@ $< quiet_cmd_cxx = CXX($(TOOLSET)) $@ cmd_cxx = $(CXX.$(TOOLSET)) $(GYP_CXXFLAGS) $(DEPFLAGS) $(CXXFLAGS.$(TOOLSET)) -c -o $@ $< quiet_cmd_objc = CXX($(TOOLSET)) $@ cmd_objc = $(CC.$(TOOLSET)) $(GYP_OBJCFLAGS) $(DEPFLAGS) -c -o $@ $< quiet_cmd_objcxx = CXX($(TOOLSET)) $@ cmd_objcxx = $(CXX.$(TOOLSET)) $(GYP_OBJCXXFLAGS) $(DEPFLAGS) -c -o $@ $< # Commands for precompiled header files. quiet_cmd_pch_c = CXX($(TOOLSET)) $@ cmd_pch_c = $(CC.$(TOOLSET)) $(GYP_PCH_CFLAGS) $(DEPFLAGS) $(CXXFLAGS.$(TOOLSET)) -c -o $@ $< quiet_cmd_pch_cc = CXX($(TOOLSET)) $@ cmd_pch_cc = $(CC.$(TOOLSET)) $(GYP_PCH_CXXFLAGS) $(DEPFLAGS) $(CXXFLAGS.$(TOOLSET)) -c -o $@ $< quiet_cmd_pch_m = CXX($(TOOLSET)) $@ cmd_pch_m = $(CC.$(TOOLSET)) $(GYP_PCH_OBJCFLAGS) $(DEPFLAGS) -c -o $@ $< quiet_cmd_pch_mm = CXX($(TOOLSET)) $@ cmd_pch_mm = $(CC.$(TOOLSET)) $(GYP_PCH_OBJCXXFLAGS) $(DEPFLAGS) -c -o $@ $< # gyp-mac-tool is written next to the root Makefile by gyp. # Use $(4) for the command, since $(2) and $(3) are used as flag by do_cmd # already. quiet_cmd_mac_tool = MACTOOL $(4) $< cmd_mac_tool = ./gyp-mac-tool $(4) $< "$@" quiet_cmd_mac_package_framework = PACKAGE FRAMEWORK $@ cmd_mac_package_framework = ./gyp-mac-tool package-framework "$@" $(4) quiet_cmd_infoplist = INFOPLIST $@ cmd_infoplist = $(CC.$(TOOLSET)) -E -P -Wno-trigraphs -x c $(INFOPLIST_DEFINES) "$<" -o "$@" quiet_cmd_touch = TOUCH $@ cmd_touch = touch $@ quiet_cmd_copy = COPY $@ # send stderr to /dev/null to ignore messages when linking directories. cmd_copy = rm -rf "$@" && cp -af "$<" "$@" quiet_cmd_alink = LIBTOOL-STATIC $@ cmd_alink = rm -f $@ && ./gyp-mac-tool filter-libtool libtool $(GYP_LIBTOOLFLAGS) -static -o $@ $(filter %.o,$^) quiet_cmd_link = LINK($(TOOLSET)) $@ cmd_link = $(LINK.$(TOOLSET)) $(GYP_LDFLAGS) $(LDFLAGS.$(TOOLSET)) -o "$@" $(LD_INPUTS) $(LIBS) quiet_cmd_solink = SOLINK($(TOOLSET)) $@ cmd_solink = $(LINK.$(TOOLSET)) -shared $(GYP_LDFLAGS) $(LDFLAGS.$(TOOLSET)) -o "$@" $(LD_INPUTS) $(LIBS) quiet_cmd_solink_module = SOLINK_MODULE($(TOOLSET)) $@ cmd_solink_module = $(LINK.$(TOOLSET)) -bundle $(GYP_LDFLAGS) $(LDFLAGS.$(TOOLSET)) -o $@ $(filter-out FORCE_DO_CMD, $^) $(LIBS) # Define an escape_quotes function to escape single quotes. # This allows us to handle quotes properly as long as we always use # use single quotes and escape_quotes. escape_quotes = $(subst ','\'',$(1)) # This comment is here just to include a ' to unconfuse syntax highlighting. # Define an escape_vars function to escape '$' variable syntax. # This allows us to read/write command lines with shell variables (e.g. # $LD_LIBRARY_PATH), without triggering make substitution. escape_vars = $(subst $$,$$$$,$(1)) # Helper that expands to a shell command to echo a string exactly as it is in # make. This uses printf instead of echo because printf's behaviour with respect # to escape sequences is more portable than echo's across different shells # (e.g., dash, bash). exact_echo = printf '%s\n' '$(call escape_quotes,$(1))' # Helper to compare the command we're about to run against the command # we logged the last time we ran the command. Produces an empty # string (false) when the commands match. # Tricky point: Make has no string-equality test function. # The kernel uses the following, but it seems like it would have false # positives, where one string reordered its arguments. # arg_check = $(strip $(filter-out $(cmd_$(1)), $(cmd_$@)) \ # $(filter-out $(cmd_$@), $(cmd_$(1)))) # We instead substitute each for the empty string into the other, and # say they're equal if both substitutions produce the empty string. # .d files contain ? instead of spaces, take that into account. command_changed = $(or $(subst $(cmd_$(1)),,$(cmd_$(call replace_spaces,$@))),\ $(subst $(cmd_$(call replace_spaces,$@)),,$(cmd_$(1)))) # Helper that is non-empty when a prerequisite changes. # Normally make does this implicitly, but we force rules to always run # so we can check their command lines. # $? -- new prerequisites # $| -- order-only dependencies prereq_changed = $(filter-out FORCE_DO_CMD,$(filter-out $|,$?)) # Helper that executes all postbuilds until one fails. define do_postbuilds @E=0;\ for p in $(POSTBUILDS); do\ eval $$p;\ E=$$?;\ if [ $$E -ne 0 ]; then\ break;\ fi;\ done;\ if [ $$E -ne 0 ]; then\ rm -rf "$@";\ exit $$E;\ fi endef # do_cmd: run a command via the above cmd_foo names, if necessary. # Should always run for a given target to handle command-line changes. # Second argument, if non-zero, makes it do asm/C/C++ dependency munging. # Third argument, if non-zero, makes it do POSTBUILDS processing. # Note: We intentionally do NOT call dirx for depfile, since it contains ? for # spaces already and dirx strips the ? characters. define do_cmd $(if $(or $(command_changed),$(prereq_changed)), @$(call exact_echo, $($(quiet)cmd_$(1))) @mkdir -p "$(call dirx,$@)" "$(dir $(depfile))" $(if $(findstring flock,$(word 2,$(cmd_$1))), @$(cmd_$(1)) @echo " $(quiet_cmd_$(1)): Finished", @$(cmd_$(1)) ) @$(call exact_echo,$(call escape_vars,cmd_$(call replace_spaces,$@) := $(cmd_$(1)))) > $(depfile) @$(if $(2),$(fixup_dep)) $(if $(and $(3), $(POSTBUILDS)), $(call do_postbuilds) ) ) endef # Declare the "all" target first so it is the default, # even though we don't have the deps yet. .PHONY: all all: # make looks for ways to re-generate included makefiles, but in our case, we # don't have a direct way. Explicitly telling make that it has nothing to do # for them makes it go faster. %.d: ; # Use FORCE_DO_CMD to force a target to run. Should be coupled with # do_cmd. .PHONY: FORCE_DO_CMD FORCE_DO_CMD: TOOLSET := target # Suffix rules, putting all outputs into $(obj). $(obj).$(TOOLSET)/%.o: $(srcdir)/%.c FORCE_DO_CMD @$(call do_cmd,cc,1) $(obj).$(TOOLSET)/%.o: $(srcdir)/%.cc FORCE_DO_CMD @$(call do_cmd,cxx,1) $(obj).$(TOOLSET)/%.o: $(srcdir)/%.cpp FORCE_DO_CMD @$(call do_cmd,cxx,1) $(obj).$(TOOLSET)/%.o: $(srcdir)/%.cxx FORCE_DO_CMD @$(call do_cmd,cxx,1) $(obj).$(TOOLSET)/%.o: $(srcdir)/%.m FORCE_DO_CMD @$(call do_cmd,objc,1) $(obj).$(TOOLSET)/%.o: $(srcdir)/%.mm FORCE_DO_CMD @$(call do_cmd,objcxx,1) $(obj).$(TOOLSET)/%.o: $(srcdir)/%.S FORCE_DO_CMD @$(call do_cmd,cc,1) $(obj).$(TOOLSET)/%.o: $(srcdir)/%.s FORCE_DO_CMD @$(call do_cmd,cc,1) # Try building from generated source, too. $(obj).$(TOOLSET)/%.o: $(obj).$(TOOLSET)/%.c FORCE_DO_CMD @$(call do_cmd,cc,1) $(obj).$(TOOLSET)/%.o: $(obj).$(TOOLSET)/%.cc FORCE_DO_CMD @$(call do_cmd,cxx,1) $(obj).$(TOOLSET)/%.o: $(obj).$(TOOLSET)/%.cpp FORCE_DO_CMD @$(call do_cmd,cxx,1) $(obj).$(TOOLSET)/%.o: $(obj).$(TOOLSET)/%.cxx FORCE_DO_CMD @$(call do_cmd,cxx,1) $(obj).$(TOOLSET)/%.o: $(obj).$(TOOLSET)/%.m FORCE_DO_CMD @$(call do_cmd,objc,1) $(obj).$(TOOLSET)/%.o: $(obj).$(TOOLSET)/%.mm FORCE_DO_CMD @$(call do_cmd,objcxx,1) $(obj).$(TOOLSET)/%.o: $(obj).$(TOOLSET)/%.S FORCE_DO_CMD @$(call do_cmd,cc,1) $(obj).$(TOOLSET)/%.o: $(obj).$(TOOLSET)/%.s FORCE_DO_CMD @$(call do_cmd,cc,1) $(obj).$(TOOLSET)/%.o: $(obj)/%.c FORCE_DO_CMD @$(call do_cmd,cc,1) $(obj).$(TOOLSET)/%.o: $(obj)/%.cc FORCE_DO_CMD @$(call do_cmd,cxx,1) $(obj).$(TOOLSET)/%.o: $(obj)/%.cpp FORCE_DO_CMD @$(call do_cmd,cxx,1) $(obj).$(TOOLSET)/%.o: $(obj)/%.cxx FORCE_DO_CMD @$(call do_cmd,cxx,1) $(obj).$(TOOLSET)/%.o: $(obj)/%.m FORCE_DO_CMD @$(call do_cmd,objc,1) $(obj).$(TOOLSET)/%.o: $(obj)/%.mm FORCE_DO_CMD @$(call do_cmd,objcxx,1) $(obj).$(TOOLSET)/%.o: $(obj)/%.S FORCE_DO_CMD @$(call do_cmd,cc,1) $(obj).$(TOOLSET)/%.o: $(obj)/%.s FORCE_DO_CMD @$(call do_cmd,cc,1) ifeq ($(strip $(foreach prefix,$(NO_LOAD),\ $(findstring $(join ^,$(prefix)),\ $(join ^,kerberos.target.mk)))),) include kerberos.target.mk endif quiet_cmd_regen_makefile = ACTION Regenerating $@ cmd_regen_makefile = cd $(srcdir); /usr/local/lib/node_modules/npm/node_modules/node-gyp/gyp/gyp_main.py -fmake --ignore-environment "--toplevel-dir=." -I/Users/kielan/Documents/Programming/TheGraduate/node_modules/mongoose/node_modules/mongodb/node_modules/kerberos/build/config.gypi -I/usr/local/lib/node_modules/npm/node_modules/node-gyp/addon.gypi -I/Users/kielan/.node-gyp/0.12.0/common.gypi "--depth=." "-Goutput_dir=." "--generator-output=build" "-Dlibrary=shared_library" "-Dvisibility=default" "-Dnode_root_dir=/Users/kielan/.node-gyp/0.12.0" "-Dmodule_root_dir=/Users/kielan/Documents/Programming/TheGraduate/node_modules/mongoose/node_modules/mongodb/node_modules/kerberos" binding.gyp Makefile: $(srcdir)/../../../../../../../../../../../usr/local/lib/node_modules/npm/node_modules/node-gyp/addon.gypi $(srcdir)/build/config.gypi $(srcdir)/binding.gyp $(srcdir)/../../../../../../../../../.node-gyp/0.12.0/common.gypi $(call do_cmd,regen_makefile) # "all" is a concatenation of the "all" targets from all the included # sub-makefiles. This is just here to clarify. all: # Add in dependency-tracking rules. $(all_deps) is the list of every single # target in our tree. Only consider the ones with .d (dependency) info: d_files := $(wildcard $(foreach f,$(all_deps),$(depsdir)/$(f).d)) ifneq ($(d_files),) include $(d_files) endif
{ "content_hash": "ca4b905e6ed9af95b47bc28862d085d4", "timestamp": "", "source": "github", "line_count": 344, "max_line_length": 696, "avg_line_length": 38.906976744186046, "alnum_prop": 0.6535415421398685, "repo_name": "Kielan/graduation", "id": "f58b5595b40c8fe0f0c2cb9f0dae473f821287e3", "size": "13714", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "node_modules/mongoose/node_modules/mongodb/node_modules/kerberos/build/Makefile", "mode": "33188", "license": "mit", "language": [ { "name": "HTML", "bytes": "7146" }, { "name": "Handlebars", "bytes": "2265" }, { "name": "JavaScript", "bytes": "14513" } ], "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:19:24 CEST 2016 --> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>Uses of Class net.sourceforge.pmd.lang.vm.ast.ASTGENode (PMD 5.5.1 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="Uses of Class net.sourceforge.pmd.lang.vm.ast.ASTGENode (PMD 5.5.1 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><a href="../../../../../../../net/sourceforge/pmd/lang/vm/ast/ASTGENode.html" title="class in net.sourceforge.pmd.lang.vm.ast">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?net/sourceforge/pmd/lang/vm/ast/class-use/ASTGENode.html" target="_top">Frames</a></li> <li><a href="ASTGENode.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"> <h2 title="Uses of Class net.sourceforge.pmd.lang.vm.ast.ASTGENode" class="title">Uses of Class<br>net.sourceforge.pmd.lang.vm.ast.ASTGENode</h2> </div> <div class="classUseContainer"> <ul class="blockList"> <li class="blockList"> <table class="useSummary" border="0" cellpadding="3" cellspacing="0" summary="Use table, listing packages, and an explanation"> <caption><span>Packages that use <a href="../../../../../../../net/sourceforge/pmd/lang/vm/ast/ASTGENode.html" title="class in net.sourceforge.pmd.lang.vm.ast">ASTGENode</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="#net.sourceforge.pmd.lang.vm.ast">net.sourceforge.pmd.lang.vm.ast</a></td> <td class="colLast">&nbsp;</td> </tr> <tr class="rowColor"> <td class="colFirst"><a href="#net.sourceforge.pmd.lang.vm.rule">net.sourceforge.pmd.lang.vm.rule</a></td> <td class="colLast">&nbsp;</td> </tr> </tbody> </table> </li> <li class="blockList"> <ul class="blockList"> <li class="blockList"><a name="net.sourceforge.pmd.lang.vm.ast"> <!-- --> </a> <h3>Uses of <a href="../../../../../../../net/sourceforge/pmd/lang/vm/ast/ASTGENode.html" title="class in net.sourceforge.pmd.lang.vm.ast">ASTGENode</a> in <a href="../../../../../../../net/sourceforge/pmd/lang/vm/ast/package-summary.html">net.sourceforge.pmd.lang.vm.ast</a></h3> <table class="useSummary" border="0" cellpadding="3" cellspacing="0" summary="Use table, listing methods, and an explanation"> <caption><span>Methods in <a href="../../../../../../../net/sourceforge/pmd/lang/vm/ast/package-summary.html">net.sourceforge.pmd.lang.vm.ast</a> with parameters of type <a href="../../../../../../../net/sourceforge/pmd/lang/vm/ast/ASTGENode.html" title="class in net.sourceforge.pmd.lang.vm.ast">ASTGENode</a></span><span class="tabEnd">&nbsp;</span></caption> <tr> <th class="colFirst" scope="col">Modifier and Type</th> <th class="colLast" scope="col">Method and Description</th> </tr> <tbody> <tr class="altColor"> <td class="colFirst"><code><a href="http://docs.oracle.com/javase/8/docs/api/java/lang/Object.html?is-external=true" title="class or interface in java.lang">Object</a></code></td> <td class="colLast"><span class="typeNameLabel">VmParserVisitor.</span><code><span class="memberNameLink"><a href="../../../../../../../net/sourceforge/pmd/lang/vm/ast/VmParserVisitor.html#visit-net.sourceforge.pmd.lang.vm.ast.ASTGENode-java.lang.Object-">visit</a></span>(<a href="../../../../../../../net/sourceforge/pmd/lang/vm/ast/ASTGENode.html" title="class in net.sourceforge.pmd.lang.vm.ast">ASTGENode</a>&nbsp;node, <a href="http://docs.oracle.com/javase/8/docs/api/java/lang/Object.html?is-external=true" title="class or interface in java.lang">Object</a>&nbsp;data)</code>&nbsp;</td> </tr> <tr class="rowColor"> <td class="colFirst"><code><a href="http://docs.oracle.com/javase/8/docs/api/java/lang/Object.html?is-external=true" title="class or interface in java.lang">Object</a></code></td> <td class="colLast"><span class="typeNameLabel">VmParserVisitorAdapter.</span><code><span class="memberNameLink"><a href="../../../../../../../net/sourceforge/pmd/lang/vm/ast/VmParserVisitorAdapter.html#visit-net.sourceforge.pmd.lang.vm.ast.ASTGENode-java.lang.Object-">visit</a></span>(<a href="../../../../../../../net/sourceforge/pmd/lang/vm/ast/ASTGENode.html" title="class in net.sourceforge.pmd.lang.vm.ast">ASTGENode</a>&nbsp;node, <a href="http://docs.oracle.com/javase/8/docs/api/java/lang/Object.html?is-external=true" title="class or interface in java.lang">Object</a>&nbsp;data)</code>&nbsp;</td> </tr> </tbody> </table> </li> <li class="blockList"><a name="net.sourceforge.pmd.lang.vm.rule"> <!-- --> </a> <h3>Uses of <a href="../../../../../../../net/sourceforge/pmd/lang/vm/ast/ASTGENode.html" title="class in net.sourceforge.pmd.lang.vm.ast">ASTGENode</a> in <a href="../../../../../../../net/sourceforge/pmd/lang/vm/rule/package-summary.html">net.sourceforge.pmd.lang.vm.rule</a></h3> <table class="useSummary" border="0" cellpadding="3" cellspacing="0" summary="Use table, listing methods, and an explanation"> <caption><span>Methods in <a href="../../../../../../../net/sourceforge/pmd/lang/vm/rule/package-summary.html">net.sourceforge.pmd.lang.vm.rule</a> with parameters of type <a href="../../../../../../../net/sourceforge/pmd/lang/vm/ast/ASTGENode.html" title="class in net.sourceforge.pmd.lang.vm.ast">ASTGENode</a></span><span class="tabEnd">&nbsp;</span></caption> <tr> <th class="colFirst" scope="col">Modifier and Type</th> <th class="colLast" scope="col">Method and Description</th> </tr> <tbody> <tr class="altColor"> <td class="colFirst"><code><a href="http://docs.oracle.com/javase/8/docs/api/java/lang/Object.html?is-external=true" title="class or interface in java.lang">Object</a></code></td> <td class="colLast"><span class="typeNameLabel">AbstractVmRule.</span><code><span class="memberNameLink"><a href="../../../../../../../net/sourceforge/pmd/lang/vm/rule/AbstractVmRule.html#visit-net.sourceforge.pmd.lang.vm.ast.ASTGENode-java.lang.Object-">visit</a></span>(<a href="../../../../../../../net/sourceforge/pmd/lang/vm/ast/ASTGENode.html" title="class in net.sourceforge.pmd.lang.vm.ast">ASTGENode</a>&nbsp;node, <a href="http://docs.oracle.com/javase/8/docs/api/java/lang/Object.html?is-external=true" title="class or interface in java.lang">Object</a>&nbsp;data)</code>&nbsp;</td> </tr> </tbody> </table> </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><a href="../../../../../../../net/sourceforge/pmd/lang/vm/ast/ASTGENode.html" title="class in net.sourceforge.pmd.lang.vm.ast">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?net/sourceforge/pmd/lang/vm/ast/class-use/ASTGENode.html" target="_top">Frames</a></li> <li><a href="ASTGENode.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": "2b50fd6236c0f8fc456297a407a0087c", "timestamp": "", "source": "github", "line_count": 195, "max_line_length": 438, "avg_line_length": 51.78974358974359, "alnum_prop": 0.6447172987424498, "repo_name": "jasonwee/videoOnCloud", "id": "c65ec352929c97f04d35a01cf72dfb1bc86df9cd", "size": "10099", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "pmd/pmd-doc-5.5.1/apidocs/net/sourceforge/pmd/lang/vm/ast/class-use/ASTGENode.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": "" }
package com.amazonaws.services.iot.model.transform; import static com.amazonaws.util.StringUtils.UTF8; import static com.amazonaws.util.StringUtils.COMMA_SEPARATOR; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.OutputStreamWriter; import java.io.StringWriter; import java.io.Writer; import java.util.Collections; import java.util.HashMap; import java.util.Map; import java.util.List; import java.util.regex.Pattern; import com.amazonaws.AmazonClientException; import com.amazonaws.Request; import com.amazonaws.DefaultRequest; import com.amazonaws.http.HttpMethodName; import com.amazonaws.services.iot.model.*; import com.amazonaws.transform.Marshaller; import com.amazonaws.util.BinaryUtils; import com.amazonaws.util.StringUtils; import com.amazonaws.util.IdempotentUtils; import com.amazonaws.util.StringInputStream; import com.amazonaws.util.SdkHttpUtils; import com.amazonaws.protocol.json.*; /** * RegisterCertificateRequest Marshaller */ public class RegisterCertificateRequestMarshaller implements Marshaller<Request<RegisterCertificateRequest>, RegisterCertificateRequest> { private static final String DEFAULT_CONTENT_TYPE = "application/x-amz-json-1.1"; private final SdkJsonProtocolFactory protocolFactory; public RegisterCertificateRequestMarshaller( SdkJsonProtocolFactory protocolFactory) { this.protocolFactory = protocolFactory; } public Request<RegisterCertificateRequest> marshall( RegisterCertificateRequest registerCertificateRequest) { if (registerCertificateRequest == null) { throw new AmazonClientException( "Invalid argument passed to marshall(...)"); } Request<RegisterCertificateRequest> request = new DefaultRequest<RegisterCertificateRequest>( registerCertificateRequest, "AWSIot"); request.setHttpMethod(HttpMethodName.POST); String uriResourcePath = "/certificate/register"; request.setResourcePath(uriResourcePath); if (registerCertificateRequest.getSetAsActive() != null) { request.addParameter("setAsActive", StringUtils .fromBoolean(registerCertificateRequest.getSetAsActive())); } try { final StructuredJsonGenerator jsonGenerator = protocolFactory .createGenerator(); jsonGenerator.writeStartObject(); if (registerCertificateRequest.getCertificatePem() != null) { jsonGenerator.writeFieldName("certificatePem").writeValue( registerCertificateRequest.getCertificatePem()); } if (registerCertificateRequest.getCaCertificatePem() != null) { jsonGenerator.writeFieldName("caCertificatePem").writeValue( registerCertificateRequest.getCaCertificatePem()); } jsonGenerator.writeEndObject(); byte[] content = jsonGenerator.getBytes(); request.setContent(new ByteArrayInputStream(content)); request.addHeader("Content-Length", Integer.toString(content.length)); if (!request.getHeaders().containsKey("Content-Type")) { request.addHeader("Content-Type", DEFAULT_CONTENT_TYPE); } } catch (Throwable t) { throw new AmazonClientException( "Unable to marshall request to JSON: " + t.getMessage(), t); } return request; } }
{ "content_hash": "5b6405173f23ab69aa6c26e8a92896fb", "timestamp": "", "source": "github", "line_count": 100, "max_line_length": 101, "avg_line_length": 35.75, "alnum_prop": 0.693986013986014, "repo_name": "nterry/aws-sdk-java", "id": "80bae43eec62d644e5d1ebae77ecf8ed276ec9b5", "size": "4162", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "aws-java-sdk-iot/src/main/java/com/amazonaws/services/iot/model/transform/RegisterCertificateRequestMarshaller.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "FreeMarker", "bytes": "126417" }, { "name": "Java", "bytes": "113994954" }, { "name": "Scilab", "bytes": "3561" } ], "symlink_target": "" }
ActiveAdmin.register SubjectMatter do menu false permit_params :name, :description, :order, :is_active, :course_id, lesson_attributes: [:_destroy, :id, :name, :order, :is_approved] remove_filter :lesson controller do def scoped_collection super.includes :course, :lesson end end # sidebar "Course Material", only: [:show, :edit] do # ul do # li link_to "Courses", admin_courses_path(q: { id_eq: subject_matter.course_id}) # li link_to "Lessons", admin_lessons_path(q: { subject_matter_id_eq: subject_matter.id}) # end # end index do selectable_column column :name column :description column :order column :is_active column :course_id column "" do |subject_matter| link_to "View Lessons", admin_lessons_path(q: { subject_matter_id_eq: subject_matter.id}) end actions end show do columns do column max_width: "35%" do panel subject_matter.name do attributes_table_for subject_matter do row :name row :description row :order row :is_active row :course_id end end end column max_width: "35%" do panel "Lessons" do table_for subject_matter.lesson do column "Name" do |l| li link_to l.name, admin_lesson_path(l) end end end end end end form do |f| f.semantic_errors *f.object.errors.keys tabs do if !f.object.new_record? tab "Subject Details" do f.inputs do f.input :name f.input :description f.input :order f.input :is_active end end tab "Lessons" do f.has_many :lesson, heading: false, allow_destroy: true, new_record: true do |lt| lt.input :name lt.input :order lt.input :is_approved end end else tab "Subject Details" do f.inputs end end end f.actions end end
{ "content_hash": "ff3c9e125c7842e3ee209ad277d8c92c", "timestamp": "", "source": "github", "line_count": 90, "max_line_length": 101, "avg_line_length": 29.377777777777776, "alnum_prop": 0.43872919818456885, "repo_name": "empowerhack/SoulMedicine", "id": "96c14d74b956c76c23c83107bb267c0d10b7c148", "size": "2644", "binary": false, "copies": "1", "ref": "refs/heads/staging", "path": "app/admin/subject_matter.rb", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "1665791" }, { "name": "CoffeeScript", "bytes": "633" }, { "name": "HTML", "bytes": "36303" }, { "name": "JavaScript", "bytes": "1677157" }, { "name": "Ruby", "bytes": "139057" } ], "symlink_target": "" }
using System; using System.Reactive.Linq; using System.Windows.Forms; using System.Reactive.Disposables; namespace Excercise4 { class Program { static void Main() { var txt = new TextBox(); var frm = new Form() { Controls = { txt } }; var moves = from evt in Observable.FromEventPattern<MouseEventArgs>(frm, "MouseMove") select evt.EventArgs.Location; var input = from evt in Observable.FromEventPattern(txt, "TextChanged") select ((TextBox)evt.Sender).Text; var overFirstBisector = from pos in moves where pos.X == pos.Y select pos; var movesSubscription = overFirstBisector.Subscribe(pos => Console.WriteLine("Mouse at: " + pos)); var inputSubscription = input.Subscribe(inp => Console.WriteLine("User wrote: " + inp)); using (new CompositeDisposable(movesSubscription, inputSubscription)) { Application.Run(frm); } } } }
{ "content_hash": "7fb5ac28710a77f5b26edcb37ebf53ec", "timestamp": "", "source": "github", "line_count": 38, "max_line_length": 110, "avg_line_length": 30.94736842105263, "alnum_prop": 0.5306122448979592, "repo_name": "airbreather/RandomFireplace", "id": "337e545b91ce0860d1318af237dbb807be61e627", "size": "1178", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "External/Rx/Rx.NET/Samples/HOL/CS/Excercise4/Step04/Program.cs", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "C#", "bytes": "10894888" }, { "name": "PowerShell", "bytes": "5066" }, { "name": "Shell", "bytes": "979" }, { "name": "Smalltalk", "bytes": "383113" } ], "symlink_target": "" }
/* TEMPLATE GENERATED TESTCASE FILE Filename: CWE126_Buffer_Overread__new_wchar_t_memcpy_11.cpp Label Definition File: CWE126_Buffer_Overread__new.label.xml Template File: sources-sink-11.tmpl.cpp */ /* * @description * CWE: 126 Buffer Over-read * BadSource: Use a small buffer * GoodSource: Use a large buffer * Sink: memcpy * BadSink : Copy data to string using memcpy * Flow Variant: 11 Control flow: if(globalReturnsTrue()) and if(globalReturnsFalse()) * * */ #include "std_testcase.h" #include <wchar.h> namespace CWE126_Buffer_Overread__new_wchar_t_memcpy_11 { #ifndef OMITBAD void bad() { wchar_t * data; data = NULL; if(globalReturnsTrue()) { /* FLAW: Use a small buffer */ data = new wchar_t[50]; wmemset(data, L'A', 50-1); /* fill with 'A's */ data[50-1] = L'\0'; /* null terminate */ } { wchar_t dest[100]; wmemset(dest, L'C', 100-1); dest[100-1] = L'\0'; /* null terminate */ /* POTENTIAL FLAW: using memcpy with the length of the dest where data * could be smaller than dest causing buffer overread */ memcpy(dest, data, wcslen(dest)*sizeof(wchar_t)); dest[100-1] = L'\0'; printWLine(dest); delete [] data; } } #endif /* OMITBAD */ #ifndef OMITGOOD /* goodG2B1() - use goodsource and badsink by changing the globalReturnsTrue() to globalReturnsFalse() */ static void goodG2B1() { wchar_t * data; data = NULL; if(globalReturnsFalse()) { /* INCIDENTAL: CWE 561 Dead Code, the code below will never run */ printLine("Benign, fixed string"); } else { /* FIX: Use a large buffer */ data = new wchar_t[100]; wmemset(data, L'A', 100-1); /* fill with 'A's */ data[100-1] = L'\0'; /* null terminate */ } { wchar_t dest[100]; wmemset(dest, L'C', 100-1); dest[100-1] = L'\0'; /* null terminate */ /* POTENTIAL FLAW: using memcpy with the length of the dest where data * could be smaller than dest causing buffer overread */ memcpy(dest, data, wcslen(dest)*sizeof(wchar_t)); dest[100-1] = L'\0'; printWLine(dest); delete [] data; } } /* goodG2B2() - use goodsource and badsink by reversing the blocks in the if statement */ static void goodG2B2() { wchar_t * data; data = NULL; if(globalReturnsTrue()) { /* FIX: Use a large buffer */ data = new wchar_t[100]; wmemset(data, L'A', 100-1); /* fill with 'A's */ data[100-1] = L'\0'; /* null terminate */ } { wchar_t dest[100]; wmemset(dest, L'C', 100-1); dest[100-1] = L'\0'; /* null terminate */ /* POTENTIAL FLAW: using memcpy with the length of the dest where data * could be smaller than dest causing buffer overread */ memcpy(dest, data, wcslen(dest)*sizeof(wchar_t)); dest[100-1] = L'\0'; printWLine(dest); delete [] data; } } void good() { goodG2B1(); goodG2B2(); } #endif /* OMITGOOD */ } /* close namespace */ /* Below is the main(). It is only used when building this testcase on its own for testing or for building a binary to use in testing binary analysis tools. It is not used when compiling all the testcases as one application, which is how source code analysis tools are tested. */ #ifdef INCLUDEMAIN using namespace CWE126_Buffer_Overread__new_wchar_t_memcpy_11; /* so that we can use good and bad easily */ int main(int argc, char * argv[]) { /* seed randomness */ srand( (unsigned)time(NULL) ); #ifndef OMITGOOD printLine("Calling good()..."); good(); printLine("Finished good()"); #endif /* OMITGOOD */ #ifndef OMITBAD printLine("Calling bad()..."); bad(); printLine("Finished bad()"); #endif /* OMITBAD */ return 0; } #endif
{ "content_hash": "b734af44ab915c37df680d527f5affbf", "timestamp": "", "source": "github", "line_count": 145, "max_line_length": 107, "avg_line_length": 27.924137931034483, "alnum_prop": 0.5764386268214374, "repo_name": "JianpingZeng/xcc", "id": "f60047be941860503c96f674d63274e7de067860", "size": "4049", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "xcc/test/juliet/testcases/CWE126_Buffer_Overread/s02/CWE126_Buffer_Overread__new_wchar_t_memcpy_11.cpp", "mode": "33188", "license": "bsd-3-clause", "language": [], "symlink_target": "" }
import { regexAddress } from 'lbry-redux'; type DraftTxValues = { address: string, // amount: number }; export const validateSendTx = (formValues: DraftTxValues) => { const { address } = formValues; const errors = {}; // All we need to check is if the address is valid // If values are missing, users wont' be able to submit the form if (!process.env.NO_ADDRESS_VALIDATION && !regexAddress.test(address)) { errors.address = __('Not a valid LBRY address'); } return errors; };
{ "content_hash": "804b2489df8611a22144de8c723c3ba1", "timestamp": "", "source": "github", "line_count": 19, "max_line_length": 74, "avg_line_length": 26.42105263157895, "alnum_prop": 0.6733067729083665, "repo_name": "lbryio/lbry-electron", "id": "a697155adb7a2a958b8d934f71d9e0a84c52e815", "size": "511", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "ui/util/form-validation.js", "mode": "33188", "license": "mit", "language": [ { "name": "JavaScript", "bytes": "4033" }, { "name": "PowerShell", "bytes": "698" }, { "name": "Python", "bytes": "8616" }, { "name": "Shell", "bytes": "3646" } ], "symlink_target": "" }
package com.rodrigodev.xgen4j.model.common.template.model; import com.rodrigodev.xgen4j.model.common.clazz.ClassDefinition; import com.rodrigodev.xgen4j.service.time.TimeService; import lombok.Getter; import lombok.NonNull; import lombok.Setter; import lombok.experimental.Accessors; import javax.inject.Inject; import java.time.format.DateTimeFormatter; import java.time.format.FormatStyle; /** * Created by Rodrigo Quesada on 20/06/15. */ @Getter public class ClassTemplateModel { private static final DateTimeFormatter DATE_TIME_FORMATTER = DateTimeFormatter.ofLocalizedDate(FormatStyle.LONG); public static class InjectedFields { @Inject TimeService timeService; @Inject public InjectedFields() { } } @NonNull private InjectedFields inj; @NonNull final private String name; @NonNull final private String packagePath; final private TypeTemplateModel parent; private String currentDate; private ClassTemplateModel( @NonNull InjectedFields injectedFields, @NonNull String name, @NonNull String packagePath, ClassDefinition parentClassDefinition ) { this.inj = injectedFields; this.name = name; this.packagePath = packagePath; this.parent = parentClassDefinition != null ? new TypeTemplateModel(parentClassDefinition.name(), parentClassDefinition.fullyQualifiedName()) : null; this.currentDate = DATE_TIME_FORMATTER.format(inj.timeService.now()); } protected ClassTemplateModel(@NonNull ClassTemplateModelBuilder builder) { this(builder.injectedFields, builder.name, builder.packagePath, builder.parent); } @Setter @Accessors(fluent = true) public static abstract class ClassTemplateModelBuilder<M extends ClassTemplateModel, B extends ClassTemplateModelBuilder<M, B>> { private InjectedFields injectedFields; private String name; private String packagePath; private ClassDefinition parent; public abstract M build(); } }
{ "content_hash": "7411ebd0a0acb7b351f1d84f258642f0", "timestamp": "", "source": "github", "line_count": 69, "max_line_length": 133, "avg_line_length": 30.536231884057973, "alnum_prop": 0.7138111058376839, "repo_name": "RodrigoQuesadaDev/XGen4J", "id": "59dbd0e70483952193093d494bcecf91ef7dfd6d", "size": "3285", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "xgen4j/src/main/java/com/rodrigodev/xgen4j/model/common/template/model/ClassTemplateModel.java", "mode": "33188", "license": "mit", "language": [ { "name": "Java", "bytes": "1981849" } ], "symlink_target": "" }
layout: post comments: true title: MultiISO LiveDVD category : Linux tags : [iso] --- ![EmErgE's MultiISO LiveDVD](/images/multiiso-livedvd-2.0.png "EmErgE's MultiISO LiveDVD") >MultiISO LiveDVD is an integrated Live DVD technology which combines some of the very popular Live CD ISOs already available on the internet. It can be used for security reconnaissance, vulnerability identification, penetration testing, system rescue, media center and multimedia, system recovery, etc. It's a all-in-one multipurpose LiveDVD put together. There's something in it for everyone. I hope you enjoy it. Recently, after months of testing, I have released version 2.0 of MultiISO LiveDVD which can be [directly downloaded here](http://binarybum.com/MultiISO-2.0-final.iso). *BSDGurl* and *duder* have been kind enough as always and helping me out with testing. **MultiISO LiveDVD 2.0 consists of following distros:** - Backtrack 4 - GeeXBoX - Damn Small Linux - Clonezilla - Offline NT Password & Registry Editor - FreeDOS - Damn Vulnerable Linux - Trinity Rescue Kit - Tiny Core Linux - Helix 3 - Puppy Linux - Byzantine OS - Pentoo Linux - Dban - boot.kernel.org (bko) [Direct Download Link](http://binarybum.com/MultiISO-2.0-final.iso)
{ "content_hash": "9c53c4622d0da1af4ed28620931e8d79", "timestamp": "", "source": "github", "line_count": 33, "max_line_length": 415, "avg_line_length": 38.42424242424242, "alnum_prop": 0.75, "repo_name": "em3rg3/em3rg3.github.io", "id": "219ca7b4ad0c1b559e3f0ee87c31ec2270521795", "size": "1272", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "_posts/2010-01-04-emerge-multiiso-livedvd.md", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "10133" }, { "name": "HTML", "bytes": "14092" }, { "name": "JavaScript", "bytes": "18" }, { "name": "Python", "bytes": "748" }, { "name": "Shell", "bytes": "6266" } ], "symlink_target": "" }
// this file was created by SCC 2019 and is largely a derived work from the // original java class/interface package org.orekit.python; import org.orekit.frames.Frame; import org.orekit.orbits.OrbitType; import org.orekit.orbits.PositionAngle; import org.orekit.propagation.Propagator; import org.orekit.propagation.conversion.PropagatorBuilder; import org.orekit.time.AbsoluteDate; import org.orekit.utils.ParameterDriversList; public class PythonPropagatorBuilder implements PropagatorBuilder { /** Part of JCC Python interface to object */ private long pythonObject; /** Part of JCC Python interface to object */ public void pythonExtension(long pythonObject) { this.pythonObject = pythonObject; } /** Part of JCC Python interface to object */ public long pythonExtension() { return this.pythonObject; } /** Part of JCC Python interface to object */ public void finalize() throws Throwable { pythonDecRef(); } /** Part of JCC Python interface to object */ public native void pythonDecRef(); /** * Build a propagator. * * @param normalizedParameters normalized values for the selected parameters * @return an initialized propagator */ @Override public native Propagator buildPropagator(double[] normalizedParameters); /** * Get the current value of selected normalized parameters. * * @return current value of selected normalized parameters */ @Override public native double[] getSelectedNormalizedParameters(); /** * Get the orbit type expected for the 6 first parameters in * {@link #buildPropagator(double[])}. * * @return orbit type to use in {@link #buildPropagator(double[])} * @see #buildPropagator(double[]) * @see #getPositionAngle() * @since 7.1 */ @Override public native OrbitType getOrbitType(); /** * Get the position angle type expected for the 6 first parameters in * {@link #buildPropagator(double[])}. * * @return position angle type to use in {@link #buildPropagator(double[])} * @see #buildPropagator(double[]) * @see #getOrbitType() * @since 7.1 */ @Override public native PositionAngle getPositionAngle(); /** * Get the date of the initial orbit. * * @return date of the initial orbit */ @Override public native AbsoluteDate getInitialOrbitDate(); /** * Get the frame in which the orbit is propagated. * * @return frame in which the orbit is propagated */ @Override public native Frame getFrame(); /** * Get the drivers for the configurable orbital parameters. * * @return drivers for the configurable orbital parameters * @since 8.0 */ @Override public native ParameterDriversList getOrbitalParametersDrivers(); /** * Get the drivers for the configurable propagation parameters. * <p> * The parameters typically correspond to force models. * </p> * * @return drivers for the configurable propagation parameters * @since 8.0 */ @Override public native ParameterDriversList getPropagationParametersDrivers(); }
{ "content_hash": "242198d8be3f54b46a19573a4815beb8", "timestamp": "", "source": "github", "line_count": 119, "max_line_length": 80, "avg_line_length": 27.537815126050422, "alnum_prop": 0.6640219713152273, "repo_name": "petrushy/Orekit", "id": "fa1aa95f56f74ad081504616ede306d621874bd6", "size": "4113", "binary": false, "copies": "1", "ref": "refs/heads/develop", "path": "src/main/java/org/orekit/python/PythonPropagatorBuilder.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Fortran", "bytes": "7408" }, { "name": "HTML", "bytes": "19607" }, { "name": "Java", "bytes": "23105843" }, { "name": "Roff", "bytes": "31072" } ], "symlink_target": "" }
https://pubchem.ncbi.nlm.nih.gov/summary/summary.cgi?cid=46941307
{ "content_hash": "f15cb35460920c1268bbbd231f32abf7", "timestamp": "", "source": "github", "line_count": 1, "max_line_length": 65, "avg_line_length": 66, "alnum_prop": 0.803030303030303, "repo_name": "andrewdefries/ToxCast", "id": "74583c27f36e18ef02d79f58a844bd5b2bbb25e1", "size": "66", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "Figure4/Tox21_PCIDs/PCID_46941307.html", "mode": "33188", "license": "mit", "language": [ { "name": "Objective-C++", "bytes": "3350" }, { "name": "R", "bytes": "51115" }, { "name": "Shell", "bytes": "7248" } ], "symlink_target": "" }
<html> <head> <link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous"> <title>test</title> <link rel="icon" type="image/png" sizes="96x96" href="favicon2.jpg"> <link rel="stylesheet" type="text/css" href="test.css"> </head> <body> <div class="container"> <div class="row10"> <div><input id="idInput" class="text-center" type="text"></div> <div class="col-xs-6 btn btn-danger" id="prodById">Product by ID</div> <div class="col-xs-6 btn btn-danger" id="allProd">All Products</div> <div class="col-xs-6 btn btn-danger" id="catById">Category by ID</div> <div class="col-xs-6 btn btn-danger" id="allCat">All Categories</div> </div> </div> <!-- jQuery --> <script src="https://code.jquery.com/jquery-3.1.1.min.js" integrity="sha256-hVVnYaiADRTO2PzUGmuLJr8BLUSjGIZsDYGmIJLv2b8=" crossorigin="anonymous"></script> <!-- bootstrap.js --> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa" crossorigin="anonymous"></script> <!-- Custom JS --> <script type="text/javascript" src="test.js"></script> </body> </html>
{ "content_hash": "32e385909bb8fe76731689e66f5487d3", "timestamp": "", "source": "github", "line_count": 36, "max_line_length": 216, "avg_line_length": 43.583333333333336, "alnum_prop": 0.5952836201402167, "repo_name": "1701-jan09-java/ims", "id": "2613f276a4e18cbe427177155731b559455a226e", "size": "1569", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/main/webapp/static/test.html", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "3855" }, { "name": "HTML", "bytes": "15205" }, { "name": "Java", "bytes": "92056" }, { "name": "JavaScript", "bytes": "46943" } ], "symlink_target": "" }
class SecureRequestPropagationMiddleware(object): """ When running on AWS Elastic Beanstalk, we suffer an issue where HTTPS requests arriving at the load balancer are propagated to the individual hosts as HTTP requests. If the host issues a redirect it issues it using the same scheme as its incoming request (HTTP) when it should use HTTPS. This issue isn't unique to AWS EB, it's discussed in the context of WebFaction hosting in this Django ticket: https://code.djangoproject.com/ticket/12043 This middleware addresses the problem, by using the value of the X-Forwarded-Proto header to manually set the wsgi.url_scheme header. """ def process_request(self, request): if 'HTTP_X_FORWARDED_PROTO' in request.META: request.META['wsgi.url_scheme'] = request.META['HTTP_X_FORWARDED_PROTO'] return None
{ "content_hash": "f17ea6d1c1d37c99c91a3515ae82d526", "timestamp": "", "source": "github", "line_count": 24, "max_line_length": 84, "avg_line_length": 37.375, "alnum_prop": 0.7090301003344481, "repo_name": "rtucker-mozilla/WhistlePig", "id": "5156063255fd009a22d707d74ac3e3f079b5ba03", "size": "897", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "whistlepig/middleware/securerequestpropogationmiddleware.py", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "CSS", "bytes": "231184" }, { "name": "JavaScript", "bytes": "252043" }, { "name": "Makefile", "bytes": "4594" }, { "name": "Puppet", "bytes": "6677" }, { "name": "Python", "bytes": "740066" }, { "name": "Shell", "bytes": "3065" } ], "symlink_target": "" }
\hypertarget{instruction__decoder_8hpp}{}\section{include/mips/decoder/instruction\+\_\+decoder.hpp File Reference} \label{instruction__decoder_8hpp}\index{include/mips/decoder/instruction\+\_\+decoder.\+hpp@{include/mips/decoder/instruction\+\_\+decoder.\+hpp}} {\ttfamily \#include $<$mips/core.\+hpp$>$}\\* {\ttfamily \#include $<$mips/instructions/instruction.\+hpp$>$}\\* {\ttfamily \#include $<$mips/memory/register\+\_\+bank.\+hpp$>$}\\* \subsection*{Classes} \begin{DoxyCompactItemize} \item class \hyperlink{classMIPS_1_1InstructionDecoder}{M\+I\+P\+S\+::\+Instruction\+Decoder} \end{DoxyCompactItemize} \subsection{Detailed Description} Arquivo contendo um decodificador de instruções para a arquitetura M\+I\+PS de 16 bits.
{ "content_hash": "272ee36111d46cb40f32481cd0226b3e", "timestamp": "", "source": "github", "line_count": 14, "max_line_length": 146, "avg_line_length": 52.714285714285715, "alnum_prop": 0.7344173441734417, "repo_name": "mathnogueira/mips", "id": "d003370ae99b702b55897d92e808506e3a0e20de", "size": "740", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "docs/latex/instruction__decoder_8hpp.tex", "mode": "33188", "license": "mit", "language": [ { "name": "Assembly", "bytes": "8872" }, { "name": "C", "bytes": "17067" }, { "name": "C++", "bytes": "3231444" }, { "name": "CMake", "bytes": "32594" }, { "name": "M4", "bytes": "19093" }, { "name": "Makefile", "bytes": "14479" }, { "name": "Objective-C", "bytes": "6286" }, { "name": "Python", "bytes": "254657" }, { "name": "Shell", "bytes": "15224" } ], "symlink_target": "" }
package main type Action interface { Run() error }
{ "content_hash": "479a81fdac0d9f04c87a644d5307fe0c", "timestamp": "", "source": "github", "line_count": 5, "max_line_length": 23, "avg_line_length": 10.6, "alnum_prop": 0.7169811320754716, "repo_name": "wuub/roj", "id": "49c226221c56496aafe9c281c92bb72475824312", "size": "53", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "action.go", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Go", "bytes": "14036" }, { "name": "Shell", "bytes": "140" } ], "symlink_target": "" }
/** * This loader is needed to add additional exports and is a workaround for a Webpack bug that doesn't * allow exports from multiple files in the same entry. * @see https://github.com/webpack/webpack/issues/15936. */ export default function (this: import('webpack').LoaderContext<{}>, content: string, map: Parameters<import('webpack').LoaderDefinitionFunction>[1]): void;
{ "content_hash": "aebf8c82be6f1956fad087205e278230", "timestamp": "", "source": "github", "line_count": 7, "max_line_length": 155, "avg_line_length": 54.285714285714285, "alnum_prop": 0.7473684210526316, "repo_name": "angular/angular-devkit-build-angular-builds", "id": "c57506949cfaef27655353e61486d300589b7cc4", "size": "581", "binary": false, "copies": "1", "ref": "refs/heads/main", "path": "src/builders/server/platform-server-exports-loader.d.ts", "mode": "33188", "license": "mit", "language": [ { "name": "HTML", "bytes": "3462" }, { "name": "JavaScript", "bytes": "890" } ], "symlink_target": "" }
package main import ( "flag" "github.com/golang/glog" rad "github.com/radanalyticsio/oshinko-cli/pkg/client/clientset/versioned" informers "github.com/radanalyticsio/oshinko-cli/pkg/client/informers/externalversions" "github.com/radanalyticsio/oshinko-cli/pkg/crd/controller" "github.com/radanalyticsio/oshinko-cli/pkg/signals" "github.com/radanalyticsio/oshinko-cli/version" kubeinformers "k8s.io/client-go/informers" "k8s.io/client-go/kubernetes" "k8s.io/client-go/tools/clientcmd" "os" "os/signal" "time" //"fmt" ) var ( configPath string masterURL string namespace string ) func init() { const ( MY_NAMESPACE = "MY_NAMESPACE" ) // flags flag.StringVar(&configPath, "kubeconfig", os.Getenv("KUBECONFIG"), "(Optional) Overrides $KUBECONFIG") flag.StringVar(&masterURL, "server", "", "(Optional) URL address of a remote api server. Do not set for local clusters.") flag.StringVar(&namespace, "ns", "", "(Optional) URL address of a remote api server. Do not set for local clusters.") flag.Parse() // env variables namespace = os.Getenv(MY_NAMESPACE) if namespace == "" { glog.Infof("usage: oshinko-crd --kubeconfig=$HOME.kube/config --logtostderr") glog.Fatalf("init: crd's namespace was not passed in env variable %q", MY_NAMESPACE) } glog.Infof("%s %s Default spark image: %s\n", version.GetAppName(), version.GetVersion(), version.GetSparkImage()) glog.Infof("init complete: Oshinko crd version %q starting...\n", version.GetVersion()) } func main() { stopCh := signals.SetupSignalHandler() cfg, err := clientcmd.BuildConfigFromFlags(masterURL, configPath) if err != nil { glog.Fatalf("Error getting kube config: %v\n", err) } kubeClient, err := kubernetes.NewForConfig(cfg) if err != nil { glog.Fatalf("Error building kubernetes clientset: %s", err.Error()) } radClient, err := rad.NewForConfig(cfg) if err != nil { glog.Fatalf("Error building example clientset: %v", err) } kubeInformerFactory := kubeinformers.NewSharedInformerFactory(kubeClient, time.Second*30) sparkInformerFactory := informers.NewSharedInformerFactory(radClient, time.Second*30) controller := controller.NewController(kubeClient, radClient, kubeInformerFactory, sparkInformerFactory) go kubeInformerFactory.Start(stopCh) go sparkInformerFactory.Start(stopCh) if err = controller.Run(1, stopCh); err != nil { glog.Fatalf("Error running crd: %s", err.Error()) } /* working code */ //list, err := radClient.RadanalyticsV1().SparkClusters(namespace).List(metav1.ListOptions{}) //if err != nil { // glog.Fatalf("Error listing all databases: %v", err) //} // //for _, s := range list.Items { // fmt.Printf("database %s with user %q\n", s.ConfigName, s.Spec.ConfigName) //} /* working code */ } // Shutdown gracefully on system signals func handleSignals() <-chan struct{} { sigCh := make(chan os.Signal) stopCh := make(chan struct{}) go func() { signal.Notify(sigCh) <-sigCh close(stopCh) os.Exit(1) }() return stopCh }
{ "content_hash": "ff45964e034d5bcee82b8ac0431deb61", "timestamp": "", "source": "github", "line_count": 102, "max_line_length": 123, "avg_line_length": 29.38235294117647, "alnum_prop": 0.7157157157157157, "repo_name": "radanalyticsio/oshinko-cli", "id": "067d0334d14d6c520ffd658eb2d54b65bf2be0f6", "size": "2997", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "cmd/crd/crd-controller.go", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Awk", "bytes": "921" }, { "name": "Dockerfile", "bytes": "422" }, { "name": "Go", "bytes": "442529" }, { "name": "Makefile", "bytes": "869" }, { "name": "Python", "bytes": "2181" }, { "name": "Shell", "bytes": "237203" } ], "symlink_target": "" }
"""Tests for the fetch_worker module.""" import Queue import logging import sys import time import unittest # Local Libraries import gflags FLAGS = gflags.FLAGS # Local modules from dpxdt.client import fetch_worker class FetchWorkerTest(unittest.TestCase): """Tests for the FetchWorker.""" def setUp(self): """Sets up the test harness.""" self.input_queue = Queue.Queue() self.output_queue = Queue.Queue() self.worker = fetch_worker.FetchThread(self.input_queue, self.output_queue) def testForbiddenScheme(self): """Tests that some schemes are not allowed.""" self.worker.start() self.input_queue.put(fetch_worker.FetchItem('file:///etc/passwd')) time.sleep(0.1) result = self.output_queue.get() self.assertEquals(403, result.status_code) def main(argv): logging.getLogger().setLevel(logging.DEBUG) argv = FLAGS(argv) unittest.main(argv=argv) if __name__ == '__main__': main(sys.argv)
{ "content_hash": "ac1f54f788b897a8df925242499ab6f7", "timestamp": "", "source": "github", "line_count": 42, "max_line_length": 83, "avg_line_length": 23.904761904761905, "alnum_prop": 0.6633466135458167, "repo_name": "bslatkin/dpxdt", "id": "a21eb947184c2b1ef12092ed1546af89a8208106", "size": "1603", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "tests/fetch_worker_test.py", "mode": "33261", "license": "apache-2.0", "language": [ { "name": "Batchfile", "bytes": "541" }, { "name": "CSS", "bytes": "5284" }, { "name": "HTML", "bytes": "70284" }, { "name": "JavaScript", "bytes": "31309" }, { "name": "Makefile", "bytes": "171" }, { "name": "Mako", "bytes": "412" }, { "name": "Python", "bytes": "299772" }, { "name": "Shell", "bytes": "1754" } ], "symlink_target": "" }
package main import ( "fmt" "net" "strings" "github.com/hashicorp/terraform/helper/schema" ) func resourceDNS() *schema.Resource { return &schema.Resource{ Create: resourceDNSCreate, Read: resourceDNSRead, Update: resourceDNSUpdate, Delete: resourceDNSDelete, Schema: map[string]*schema.Schema{ "host": &schema.Schema{ Type: schema.TypeString, Required: true, }, "ip_address": &schema.Schema{ Type: schema.TypeString, Computed: true, }, "ip_address_csv": &schema.Schema{ Type: schema.TypeString, Computed: true, }, }, } } func resourceDNSCreate(d *schema.ResourceData, m interface{}) error { err := resourceDNSRead(d, m) if err != nil { return err } d.SetId(d.Get("host").(string)) return nil } func resourceDNSRead(d *schema.ResourceData, m interface{}) error { ips, err := getIPs(d.Get("host").(string)) if err != nil { return err } if len(ips) == 0 { return fmt.Errorf("No IP addresses found for %s", d.Get("host")) } d.Set("ip_address", ips[0]) d.Set("ip_address_csv", strings.Join(ips, ",")) return nil } func resourceDNSUpdate(d *schema.ResourceData, m interface{}) error { return nil } func resourceDNSDelete(d *schema.ResourceData, m interface{}) error { return nil } func getIPs(host string) ([]string, error) { ips := []string{} adds, err := net.LookupIP(host) if err != nil { return ips, err } for _, v := range adds { ips = append(ips, v.String()) } return ips, nil }
{ "content_hash": "a0e61fa1a6c70e37feb5139a8c7477ec", "timestamp": "", "source": "github", "line_count": 84, "max_line_length": 69, "avg_line_length": 17.904761904761905, "alnum_prop": 0.6456117021276596, "repo_name": "mattwilmott/terraform-foreman", "id": "dc0e94620a7982c520abb47522d49c68f736d1af", "size": "1504", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "resource_dns.go", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Go", "bytes": "30688" } ], "symlink_target": "" }
package com.amazonaws.services.lightsail.model.transform; import java.util.List; import javax.annotation.Generated; import com.amazonaws.SdkClientException; import com.amazonaws.services.lightsail.model.*; import com.amazonaws.protocol.*; import com.amazonaws.annotation.SdkInternalApi; /** * DiskMarshaller */ @Generated("com.amazonaws:aws-java-sdk-code-generator") @SdkInternalApi public class DiskMarshaller { private static final MarshallingInfo<String> NAME_BINDING = MarshallingInfo.builder(MarshallingType.STRING).marshallLocation(MarshallLocation.PAYLOAD) .marshallLocationName("name").build(); private static final MarshallingInfo<String> ARN_BINDING = MarshallingInfo.builder(MarshallingType.STRING).marshallLocation(MarshallLocation.PAYLOAD) .marshallLocationName("arn").build(); private static final MarshallingInfo<String> SUPPORTCODE_BINDING = MarshallingInfo.builder(MarshallingType.STRING) .marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("supportCode").build(); private static final MarshallingInfo<java.util.Date> CREATEDAT_BINDING = MarshallingInfo.builder(MarshallingType.DATE) .marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("createdAt").timestampFormat("unixTimestamp").build(); private static final MarshallingInfo<StructuredPojo> LOCATION_BINDING = MarshallingInfo.builder(MarshallingType.STRUCTURED) .marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("location").build(); private static final MarshallingInfo<String> RESOURCETYPE_BINDING = MarshallingInfo.builder(MarshallingType.STRING) .marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("resourceType").build(); private static final MarshallingInfo<List> TAGS_BINDING = MarshallingInfo.builder(MarshallingType.LIST).marshallLocation(MarshallLocation.PAYLOAD) .marshallLocationName("tags").build(); private static final MarshallingInfo<List> ADDONS_BINDING = MarshallingInfo.builder(MarshallingType.LIST).marshallLocation(MarshallLocation.PAYLOAD) .marshallLocationName("addOns").build(); private static final MarshallingInfo<Integer> SIZEINGB_BINDING = MarshallingInfo.builder(MarshallingType.INTEGER) .marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("sizeInGb").build(); private static final MarshallingInfo<Boolean> ISSYSTEMDISK_BINDING = MarshallingInfo.builder(MarshallingType.BOOLEAN) .marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("isSystemDisk").build(); private static final MarshallingInfo<Integer> IOPS_BINDING = MarshallingInfo.builder(MarshallingType.INTEGER).marshallLocation(MarshallLocation.PAYLOAD) .marshallLocationName("iops").build(); private static final MarshallingInfo<String> PATH_BINDING = MarshallingInfo.builder(MarshallingType.STRING).marshallLocation(MarshallLocation.PAYLOAD) .marshallLocationName("path").build(); private static final MarshallingInfo<String> STATE_BINDING = MarshallingInfo.builder(MarshallingType.STRING).marshallLocation(MarshallLocation.PAYLOAD) .marshallLocationName("state").build(); private static final MarshallingInfo<String> ATTACHEDTO_BINDING = MarshallingInfo.builder(MarshallingType.STRING) .marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("attachedTo").build(); private static final MarshallingInfo<Boolean> ISATTACHED_BINDING = MarshallingInfo.builder(MarshallingType.BOOLEAN) .marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("isAttached").build(); private static final MarshallingInfo<String> ATTACHMENTSTATE_BINDING = MarshallingInfo.builder(MarshallingType.STRING) .marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("attachmentState").build(); private static final MarshallingInfo<Integer> GBINUSE_BINDING = MarshallingInfo.builder(MarshallingType.INTEGER).marshallLocation(MarshallLocation.PAYLOAD) .marshallLocationName("gbInUse").build(); private static final DiskMarshaller instance = new DiskMarshaller(); public static DiskMarshaller getInstance() { return instance; } /** * Marshall the given parameter object. */ public void marshall(Disk disk, ProtocolMarshaller protocolMarshaller) { if (disk == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { protocolMarshaller.marshall(disk.getName(), NAME_BINDING); protocolMarshaller.marshall(disk.getArn(), ARN_BINDING); protocolMarshaller.marshall(disk.getSupportCode(), SUPPORTCODE_BINDING); protocolMarshaller.marshall(disk.getCreatedAt(), CREATEDAT_BINDING); protocolMarshaller.marshall(disk.getLocation(), LOCATION_BINDING); protocolMarshaller.marshall(disk.getResourceType(), RESOURCETYPE_BINDING); protocolMarshaller.marshall(disk.getTags(), TAGS_BINDING); protocolMarshaller.marshall(disk.getAddOns(), ADDONS_BINDING); protocolMarshaller.marshall(disk.getSizeInGb(), SIZEINGB_BINDING); protocolMarshaller.marshall(disk.getIsSystemDisk(), ISSYSTEMDISK_BINDING); protocolMarshaller.marshall(disk.getIops(), IOPS_BINDING); protocolMarshaller.marshall(disk.getPath(), PATH_BINDING); protocolMarshaller.marshall(disk.getState(), STATE_BINDING); protocolMarshaller.marshall(disk.getAttachedTo(), ATTACHEDTO_BINDING); protocolMarshaller.marshall(disk.getIsAttached(), ISATTACHED_BINDING); protocolMarshaller.marshall(disk.getAttachmentState(), ATTACHMENTSTATE_BINDING); protocolMarshaller.marshall(disk.getGbInUse(), GBINUSE_BINDING); } catch (Exception e) { throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e); } } }
{ "content_hash": "7ebd588673244d21e4aec8f534ce3fed", "timestamp": "", "source": "github", "line_count": 93, "max_line_length": 159, "avg_line_length": 64.78494623655914, "alnum_prop": 0.7546887966804979, "repo_name": "aws/aws-sdk-java", "id": "dfb4acd3048461f38c8afa5ce1abd70bdc1acd29", "size": "6605", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "aws-java-sdk-lightsail/src/main/java/com/amazonaws/services/lightsail/model/transform/DiskMarshaller.java", "mode": "33188", "license": "apache-2.0", "language": [], "symlink_target": "" }
Package bit provides a bit array implementation and some utility functions. ## Installation ```sh go get github.com/robskie/bit ``` ## Example A bit array can be used to compactly store integer values in exchange for slower operations. For example, suppose you have an input that varies from 0 to 1000, and you want to store it in an array without wasting too much bits. You can use an array of ```uint16``` to store it, but if you use a bit array, you will save more than one third of those precious bit space. Here's how: ```go import "github.com/robskie/bit" bitsize := 10 array := bit.NewArray(0) // Store the input to a bit array for _, v := range input { array.Add(v, bitsize) } // Iterate through the array numElem := array.Len() / bitsize for i := 0; i < numElem; i++ { value := array.Get(i*bitsize, bitsize) // Do something useful with value } ``` ## API Reference Godoc documentation can be found [here](https://godoc.org/github.com/robskie/bit). ## Benchmarks I used a Core i5 running at 2.3GHz for these benchmarks. I used different bit sizes in measuring the running time for bit array Add and Get methods as shown in BenchmarkAddXX and BenchmarkGetXX where XX is the bit size. BenchmarkAddRand and BenchmarkGetRand uses random bit sizes. Both BenchmarkGetXX and BenchmarkGetRand measures the running time of Get using consecutive indices while BenchmarkGetRandIdx measures the running time of Get using random indices and bit sizes. Here are the results by running ```go test github.com/robskie/bit -bench=.*``` from terminal. ``` BenchmarkAdd7 100000000 12.2 ns/op BenchmarkAdd15 100000000 14.6 ns/op BenchmarkAdd31 100000000 19.7 ns/op BenchmarkAdd63 50000000 24.7 ns/op BenchmarkAddRand 100000000 25.8 ns/op BenchmarkInsertRandIdx 20000000 63.1 ns/op BenchmarkGet7 100000000 22.5 ns/op BenchmarkGet15 100000000 23.4 ns/op BenchmarkGet31 50000000 24.3 ns/op BenchmarkGet63 50000000 24.7 ns/op BenchmarkGetRand 50000000 29.2 ns/op BenchmarkGetRandIdx 30000000 53.1 ns/op BenchmarkMSBIndex 300000000 4.96 ns/op BenchmarkPopCount 500000000 3.51 ns/op BenchmarkRank 200000000 6.69 ns/op BenchmarkSelect 100000000 13.3 ns/op ```
{ "content_hash": "cdc0cd4b1b98ddcdf9c62ac1c6993017", "timestamp": "", "source": "github", "line_count": 70, "max_line_length": 82, "avg_line_length": 35.02857142857143, "alnum_prop": 0.6794453507340946, "repo_name": "robskie/bit", "id": "c84973411401c0791c7fa08cb7e96de5f50a63e8", "size": "2459", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "README.md", "mode": "33188", "license": "mit", "language": [ { "name": "Go", "bytes": "20037" } ], "symlink_target": "" }
package ru.job4j.listspeed; import org.junit.Ignore; import org.junit.Test; import static org.hamcrest.core.Is.is; import static org.junit.Assert.assertThat; /** * Класс тестов класса Speed. */ public class SpeedTest { /** * Объект класса Speed. */ private final Speed test = new Speed(); /** * Стартовый размер коллекций. */ private final int collectionSize = 200000; /** * Количество добавляемых или удаляемых эл-тов. */ private final int amount = 50000; /** Мешает при сборке из-за долгого тестирования. * Тестируем добавление эл-тов в коллекции. * При стартовом размере коллекции 1000000 при добавлении более 280000 эл-тов тест проваливается. * Т.е. LinkedList быстрее до 280000. */ @Test @Ignore public void whenAddNewElementsToCollectionsThanCompareTime() { test.generateLists(collectionSize); long arrT = test.add(test.getArrayList(), amount); System.out.println(String.format("Add to ArrayList size %s, %s new elements in %s ", collectionSize, amount, arrT)); long linT = test.add(test.getLinkedList(), amount); System.out.println(String.format("Add to LinkedList size %s, %s new elements in %s ", collectionSize, amount, linT)); long treT = test.add(test.getTreeSet(), amount); System.out.println(String.format("Add to TreeSet size %s, %s new elements in %s ", collectionSize, amount, treT)); assertThat(linT < arrT, is(false)); assertThat(arrT < treT, is(false)); } /** * Тестируем удаление. */ @Test @Ignore public void whenDeleteNElementsFromCollectionsThanCompareTime() { test.generateLists(collectionSize); long arrT = test.delete(test.getArrayList(), amount); System.out.println(String.format("Remove from ArrayList size %s, %s first elements in %s ", collectionSize, amount, arrT)); long linT = test.delete(test.getLinkedList(), amount); System.out.println(String.format("Remove from LinkedList size %s, %s first elements in %s ", collectionSize, amount, linT)); long treT = test.delete(test.getTreeSet(), amount); System.out.println(String.format("Remove from TreeSet size %s, %s first elements in %s ", collectionSize, amount, treT)); assertThat(linT < treT, is(true)); assertThat(treT < arrT, is(true)); } }
{ "content_hash": "1ce79a0a3d9c290533cf50aeebcea04d", "timestamp": "", "source": "github", "line_count": 64, "max_line_length": 132, "avg_line_length": 37.578125, "alnum_prop": 0.6632016632016632, "repo_name": "yaegorko/Egor-Kuznetcov", "id": "a8fb619d4466a60234f22b2d8dff6bbe4712562d", "size": "2664", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "chapter_003/src/test/java/ru/job4j/listspeed/SpeedTest.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "278260" } ], "symlink_target": "" }
package cn.haoyunbang.haocommon.widget.qrcode.utils; import android.annotation.SuppressLint; import android.app.Activity; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.os.AsyncTask; import android.os.BatteryManager; import android.os.Build; import android.util.Log; import cn.haoyunbang.common.widget.log.LogUtil; /** * Finishes an activity after a period of inactivity if the device is on battery * power. */ public class InactivityTimer { private static final String TAG = InactivityTimer.class.getSimpleName(); private static final long INACTIVITY_DELAY_MS = 5 * 60 * 1000L; private Activity activity; private BroadcastReceiver powerStatusReceiver; private boolean registered; private AsyncTask<Object, Object, Object> inactivityTask; public InactivityTimer(Activity activity) { this.activity = activity; powerStatusReceiver = new PowerStatusReceiver(); registered = false; onActivity(); } @SuppressLint("NewApi") public synchronized void onActivity() { cancel(); inactivityTask = new InactivityAsyncTask(); if (Build.VERSION.SDK_INT >= 11) { inactivityTask.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR); } else { inactivityTask.execute(); } } public synchronized void onPause() { cancel(); if (registered) { activity.unregisterReceiver(powerStatusReceiver); registered = false; } else { LogUtil.w(TAG, "PowerStatusReceiver was never registered?"); } } public synchronized void onResume() { if (registered) { LogUtil.w(TAG, "PowerStatusReceiver was already registered?"); } else { activity.registerReceiver(powerStatusReceiver, new IntentFilter(Intent.ACTION_BATTERY_CHANGED)); registered = true; } onActivity(); } private synchronized void cancel() { AsyncTask<?, ?, ?> task = inactivityTask; if (task != null) { task.cancel(true); inactivityTask = null; } } public void shutdown() { cancel(); } private class PowerStatusReceiver extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { if (Intent.ACTION_BATTERY_CHANGED.equals(intent.getAction())) { // 0 indicates that we're on battery boolean onBatteryNow = intent.getIntExtra(BatteryManager.EXTRA_PLUGGED, -1) <= 0; if (onBatteryNow) { InactivityTimer.this.onActivity(); } else { InactivityTimer.this.cancel(); } } } } private class InactivityAsyncTask extends AsyncTask<Object, Object, Object> { @Override protected Object doInBackground(Object... objects) { try { Thread.sleep(INACTIVITY_DELAY_MS); LogUtil.i(TAG, "Finishing activity due to inactivity"); activity.finish(); } catch (InterruptedException e) { // continue without killing } return null; } } }
{ "content_hash": "22ddb481a8df988d57f0cb1265f3b150", "timestamp": "", "source": "github", "line_count": 112, "max_line_length": 99, "avg_line_length": 25.544642857142858, "alnum_prop": 0.7287661656763369, "repo_name": "haoyunbang/HaoCommon", "id": "fe561ce6392914ed137a3d658930a6162d61a0cf", "size": "3490", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "HaoCommon/app/src/main/java/cn/haoyunbang/haocommon/widget/qrcode/utils/InactivityTimer.java", "mode": "33261", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "600683" } ], "symlink_target": "" }
package uk.joshiejack.penguinlib.client.scripting.wrappers; import net.minecraft.client.renderer.GlStateManager; import net.minecraft.item.ItemStack; import net.minecraft.util.NonNullList; import uk.joshiejack.penguinlib.client.gui.CyclingStack; import uk.joshiejack.penguinlib.client.gui.book.label.LabelBook; import uk.joshiejack.penguinlib.scripting.wrappers.ItemStackJS; public class BookLabelJS extends GuiJS<LabelBook> { public BookLabelJS(LabelBook label) { super(label); } public void drawStack(ItemStackJS stack, int x, int y, float scale) { penguinScriptingObject.drawStack(stack.penguinScriptingObject, x, y, scale); } public void drawCyclingStack(CyclingStack stack, int x, int y, float scale) { penguinScriptingObject.drawStack(stack.getStack(0), x, y, scale); } public void drawGold(long gold, int x, int y) { /* LabelBook object = penguinScriptingObject; boolean unicode = object.gui.mc.fontRenderer.getUnicodeFlag(); object.gui.mc.fontRenderer.setUnicodeFlag(true); GlStateManager.color(1F, 1F, 1F); String text = NumberFormat.getNumberInstance(Locale.ENGLISH).format(gold); object.gui.mc.getTextureManager().bindTexture(GuiShop.EXTRA); object.drawTexturedModalRect(object.x + x, object.y + y, 244, 244, 12, 12); object.gui.mc.fontRenderer.drawString(TextFormatting.BOLD + text, object.x + x + 15, object.y + y + 2, 0x857754); object.gui.mc.fontRenderer.setUnicodeFlag(unicode); */ } public void drawLeftArrow(int x, int y) { LabelBook object = penguinScriptingObject; GlStateManager.color(1F, 1F, 1F); //Fix colours object.gui.mc.getTextureManager().bindTexture(object.gui.left); object.drawTexturedModalRect(object.x + x, object.y + y, 16, 235, 15, 10); } public void drawRightArrow(int x, int y) { LabelBook object = penguinScriptingObject; GlStateManager.color(1F, 1F, 1F); //Fix colours object.gui.mc.getTextureManager().bindTexture(object.gui.left); object.drawTexturedModalRect(object.x + x, object.y + y, 0, 235, 15, 10); } public CyclingStack createCyclingStack(NonNullList<ItemStackJS> stacks) { NonNullList<ItemStack> list = NonNullList.withSize(stacks.size(), ItemStack.EMPTY); for (int i = 0; i < stacks.size(); i++) { list.set(i, stacks.get(i).penguinScriptingObject); } return new CyclingStack(list); } }
{ "content_hash": "70b8955af9b263a1a1af4580f1fe50ed", "timestamp": "", "source": "github", "line_count": 58, "max_line_length": 121, "avg_line_length": 43.327586206896555, "alnum_prop": 0.6951850378034222, "repo_name": "joshiejack/Harvest-Festival", "id": "f49abe1410447c2c62a4fffb6c586faec5b64f65", "size": "2513", "binary": false, "copies": "1", "ref": "refs/heads/1.12.2", "path": "src/main/java/uk/joshiejack/penguinlib/client/scripting/wrappers/BookLabelJS.java", "mode": "33188", "license": "mit", "language": [ { "name": "Java", "bytes": "1131422" } ], "symlink_target": "" }
// MIT License // // Copyright (c) 2019 Remy Noulin // // 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. #pragma once // Class smallBytes typedef struct smallBytes smallBytest; /** * help text for this class * It is public declaration so that child classes can add their help text easily: * ret "Child help text \n\n" helpTextSmallBytes; */ #define helpTextSmallBytes "TODO smallBytes help brief, class description /*, definitions,*/ methods, examples" // for object inheriting smallBytes, cast to smallBytes to be able to use this class functions and generics #define cBy(self) ( (smallBytest*) self ) typedef void (*freeSmallBytesFt) (smallBytest *self); typedef void (*terminateSmallBytesFt) (smallBytest **self); typedef char* (*toStringSmallBytesFt) (smallBytest *self); typedef smallBytest* (*duplicateSmallBytesFt) (smallBytest *self); /** * free container */ typedef void (*finishSmallBytesFt)(smallBytest **self); typedef const char* (*helpSmallBytesFt) (smallBytest *self); /** * get buffer in object */ typedef void* (*getSmallBytesFt) (smallBytest *self); /** * push char to object * * \param * data char to push */ typedef smallBytest* (*pushSmallBytesFt) (smallBytest *self, char data); /** * push data buffer to object * * \param * bytes small bytes * data buffer to push * size size of buffer */ typedef smallBytest* (*pushBufferSmallBytesFt) (smallBytest *self, void *data, uint32_t size); /** * get char at index * * \param * index * \return * char at index */ typedef char (*getAtSmallBytesFt) (smallBytest *self, uint32_t index); /** * return buffer size in bytes * * \return * size in bytes * 0 when smallBytes is NULL */ typedef size_t (*lenSmallBytesFt) (smallBytest *self); /** * read file to self * * \param * filePath: path to file * \return * 0 data in file * -1 an error occured */ typedef smallBytest* (*readFileSmallBytesFt)(smallBytest *self, const char *filePath); typedef smallBytest* (*readFileSmallJsonSmallBytesFt)(smallBytest *self, smallJsont *filePath); typedef smallBytest* (*readFileSmallStringSmallBytesFt)(smallBytest *self, smallStringt *filePath); typedef smallBytest* (*readStreamSmallBytesFt)(smallBytest *self, FILE *fp); /** * write self to file * * \param * filePath path to file * \return * 1 success * 0 error */ typedef int (*writeFileSmallBytesFt)(smallBytest *self, const char *filePath); typedef int (*writeFileSmallJsonSmallBytesFt)(smallBytest *self, smallJsont *filePath); typedef int (*writeFileSmallStringSmallBytesFt)(smallBytest *self, smallStringt *filePath); typedef int (*writeStreamSmallBytesFt)(smallBytest *self, FILE *fp); /** * append self to filePath * * \param * filePath * list * \return * true success * false failed, filePath or smallBytes are NULL */ typedef int (*appendFileSmallBytesFt)(smallBytest *self, const char *filePath); typedef int (*appendFileSmallStringSmallBytesFt)(smallBytest *self, smallStringt *filePath); /** * equal * compare self to value * * \param * value to compare * \return * true self and value have identical content * false they differ */ typedef bool (*equalSmallBytesFt)(smallBytest *self, smallBytest *value); typedef bool (*equalSmallBytesBoolFt)(smallBytest *self, bool value); typedef bool (*equalSmallBytesDoubleFt)(smallBytest *self, double value); typedef bool (*equalSmallBytesInt64Ft)(smallBytest *self, int64_t value); typedef bool (*equalSmallBytesInt32Ft)(smallBytest *self, int32_t value); typedef bool (*equalSmallBytesUint32Ft)(smallBytest *self, uint32_t value); typedef bool (*equalSmallBytesUint64Ft)(smallBytest *self, uint64_t value); typedef bool (*equalSmallBytesSmallBoolFt)(smallBytest *self, smallBoolt *value); typedef bool (*equalSmallBytesSmallDoubleFt)(smallBytest *self, smallDoublet *value); typedef bool (*equalSmallBytesSmallIntFt)(smallBytest *self, smallIntt *value); typedef bool (*equalSmallBytesCharFt)(smallBytest *self, const char *value); typedef bool (*equalSmallBytesSmallStringFt)(smallBytest *self, smallStringt *value); typedef bool (*equalSmallBytesBaseFt)(smallBytest *self, baset *value); /* * * class functions * allocated once for all objects * * freed with finalizeSmallBytes or finalizeLibsheepy */ /** * use this define in child classes and add the new function after this class functions * * in this define, add the methods after <finishClassTemplateFt finish;> * * Example: * #define RINGFUNCTIONST \ * CLASSTEMPLATEFUNCTIONST; \ * setSizeRingFt setSize */ #define SMALLBYTESFUNCTIONST \ helpSmallBytesFt help;\ getSmallBytesFt get;\ /*set-*/\ pushSmallBytesFt push;\ pushBufferSmallBytesFt pushBuffer;\ getAtSmallBytesFt getAt;\ /*setAt*/\ lenSmallBytesFt len;\ readFileSmallBytesFt readFile;\ readFileSmallJsonSmallBytesFt readFileSmallJson;\ readFileSmallStringSmallBytesFt readFileSmallString;\ readStreamSmallBytesFt readStream;\ writeFileSmallBytesFt writeFile;\ writeFileSmallJsonSmallBytesFt writeFileSmallJson;\ writeFileSmallStringSmallBytesFt writeFileSmallString;\ writeStreamSmallBytesFt writeStream;\ appendFileSmallBytesFt appendFile;\ appendFileSmallStringSmallBytesFt appendFileSmallString;\ equalSmallBytesFt equal;\ equalSmallBytesBoolFt equalBool;\ equalSmallBytesDoubleFt equalDouble;\ equalSmallBytesInt64Ft equalInt64;\ equalSmallBytesInt32Ft equalInt32;\ equalSmallBytesUint32Ft equalUint32;\ equalSmallBytesUint64Ft equalUint64;\ equalSmallBytesSmallBoolFt equalSmallBool;\ equalSmallBytesSmallDoubleFt equalSmallDouble;\ equalSmallBytesSmallIntFt equalSmallInt;\ equalSmallBytesCharFt equalS;\ equalSmallBytesSmallStringFt equalSmallString;\ equalSmallBytesBaseFt equalBase typedef struct { freeSmallBytesFt free; terminateSmallBytesFt terminate; toStringSmallBytesFt toString; duplicateSmallBytesFt duplicate; finishSmallBytesFt smash; finishSmallBytesFt finish; SMALLBYTESFUNCTIONST; } smallBytesFunctionst; /** * class */ struct smallBytes { const char *type; smallBytesFunctionst *f; // internal sBytest *B; }; // smallBytes #define createSmallBytes(obj) ;smallBytest obj; initiateSmallBytes(&obj) #define createAllocateSmallBytes(obj) ;smallBytest *obj; initiateAllocateSmallBytes(&obj) void initiateSmallBytes(smallBytest *self); void initiateAllocateSmallBytes(smallBytest **self); void finalizeRecycleSmallBytes(void *arg UNUSED); void finalizeSmallBytes(void); // initialize class methods, call registerMethodsSmallBytes from classes inheriting this class void registerMethodsSmallBytes(smallBytesFunctionst *f); smallBytest* allocSmallBytes(void *data, uint32_t size); smallBytest* duplicateSmallBytesG (smallBytest *self); void freeSmallBytesG (smallBytest *self); char getAtSmallBytesG(smallBytest *self, char retType UNUSED, uint32_t index); smallBytest* pushSmallBytesG (smallBytest *self, char data); size_t lenSmallBytesG(smallBytest *self); smallBytest* readFileSmallJsonSmallBytesG(smallBytest *self, smallJsont *filePath); smallBytest* readFileSmallStringSmallBytesG(smallBytest *self, smallStringt *filePath); smallBytest* readFileSmallBytesG(smallBytest *self, const char *filePath); smallBytest* readStreamSmallBytesG(smallBytest *self, FILE *fp); int writeFileSmallBytesG(smallBytest *self, const char *filePath); int writeFileSmallJsonSmallBytesG(smallBytest *self, smallJsont *filePath); int writeFileSmallStringSmallBytesG(smallBytest *self, smallStringt *filePath); int writeStreamSmallBytesG(smallBytest *self, FILE *fp); int appendFileSmallBytesG(smallBytest *self, const char *filePath); int appendFileSmallStringSmallBytesG(smallBytest *self, smallStringt *filePath); bool equalSmallBytesG(smallBytest *self, smallBytest *value); bool equalSmallBytesBoolG(smallBytest *self, bool value); bool equalSmallBytesDoubleG(smallBytest *self, double value); bool equalSmallBytesInt64G(smallBytest *self, int64_t value); bool equalSmallBytesInt32G(smallBytest *self, int32_t value); bool equalSmallBytesUint32G(smallBytest *self, uint32_t value); bool equalSmallBytesUint64G(smallBytest *self, uint64_t value); bool equalSmallBytesSmallBoolG(smallBytest *self, smallBoolt *value); bool equalSmallBytesSmallDoubleG(smallBytest *self, smallDoublet *value); bool equalSmallBytesSmallIntG(smallBytest *self, smallIntt *value); bool equalSmallBytesCharG(smallBytest *self, const char *value); bool equalSmallBytesSmallStringG(smallBytest *self, smallStringt *value); bool equalSmallBytesBaseG(smallBytest *self, baset *value); // end class smallBytes
{ "content_hash": "d799f132e819487d206c9bdcbbee4845", "timestamp": "", "source": "github", "line_count": 273, "max_line_length": 111, "avg_line_length": 36.00366300366301, "alnum_prop": 0.7609115881574932, "repo_name": "RemyNoulin/libsheepy", "id": "a2b408f78e2fb77746111dd1fd55fdf43dba1fac", "size": "9829", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "release/json/libsheepyCSmallBytes.h", "mode": "33188", "license": "mit", "language": [ { "name": "C", "bytes": "26830060" }, { "name": "C++", "bytes": "438645" }, { "name": "Makefile", "bytes": "3570" }, { "name": "Shell", "bytes": "4642" } ], "symlink_target": "" }
import django.db.models.deletion from django.conf import settings from django.db import IntegrityError, migrations, models def _populate_hq_oauth_application(apps, schema_editor): HQOauthApplication = apps.get_model('hqwebapp', 'HQOauthApplication') Application = apps.get_model(settings.OAUTH2_PROVIDER_APPLICATION_MODEL) for app in Application.objects.all(): try: HQOauthApplication.objects.create( pkce_required=False, application=app, ) except IntegrityError: pass class Migration(migrations.Migration): dependencies = [ migrations.swappable_dependency(settings.OAUTH2_PROVIDER_APPLICATION_MODEL), ('hqwebapp', '0007_user_access_agent'), ] operations = [ migrations.CreateModel( name='HQOauthApplication', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('pkce_required', models.BooleanField(default=True)), ( 'application', models.OneToOneField( on_delete=django.db.models.deletion.CASCADE, related_name='hq_application', to=settings.OAUTH2_PROVIDER_APPLICATION_MODEL ) ), ], ), migrations.RunPython(_populate_hq_oauth_application, migrations.RunPython.noop), ]
{ "content_hash": "ea0339f1b342892ce1fd3ac79d510891", "timestamp": "", "source": "github", "line_count": 43, "max_line_length": 114, "avg_line_length": 35.27906976744186, "alnum_prop": 0.5899802241265656, "repo_name": "dimagi/commcare-hq", "id": "60c188f997b6050a652f84424e40aed244c4862d", "size": "1567", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "corehq/apps/hqwebapp/migrations/0008_hqoauthapplication.py", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "CSS", "bytes": "82928" }, { "name": "Dockerfile", "bytes": "2341" }, { "name": "HTML", "bytes": "2589268" }, { "name": "JavaScript", "bytes": "5889543" }, { "name": "Jinja", "bytes": "3693" }, { "name": "Less", "bytes": "176180" }, { "name": "Makefile", "bytes": "1622" }, { "name": "PHP", "bytes": "2232" }, { "name": "PLpgSQL", "bytes": "66704" }, { "name": "Python", "bytes": "21779773" }, { "name": "Roff", "bytes": "150" }, { "name": "Shell", "bytes": "67473" } ], "symlink_target": "" }
package com.beirtipol.svnmergeutils; import java.util.function.Predicate; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.tmatesoft.svn.core.SVNLogEntry; /** * * @author [email protected] * */ public class QuietTimeMergeCheckerPredicate implements Predicate<SVNLogEntry> { private static final Logger LOGGER = LoggerFactory.getLogger(QuietTimeMergeCheckerPredicate.class); private final long quietTimeInMillis; private boolean verbose; public QuietTimeMergeCheckerPredicate(long quietTimeInMillis, boolean verbose) { this.quietTimeInMillis = quietTimeInMillis; this.verbose = verbose; } @Override public boolean test(SVNLogEntry entry) { boolean result = System.currentTimeMillis() - entry.getDate().getTime() > quietTimeInMillis; if (!result && verbose) { LOGGER.info(String.format("Skipping Log Entry for revision %s as it has been committed within the quiet time window of %sms", entry.getRevision(), quietTimeInMillis)); } return result; } }
{ "content_hash": "8494923e9d8a72a92a511fb61db1291b", "timestamp": "", "source": "github", "line_count": 33, "max_line_length": 170, "avg_line_length": 31.454545454545453, "alnum_prop": 0.7514450867052023, "repo_name": "beirtipol/svn-merge-utils", "id": "5b79cd7bb8e7d7d8497aed480967ed355b21b215", "size": "2202", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/main/java/com/beirtipol/svnmergeutils/QuietTimeMergeCheckerPredicate.java", "mode": "33188", "license": "mit", "language": [ { "name": "Java", "bytes": "46665" }, { "name": "XSLT", "bytes": "4033" } ], "symlink_target": "" }
SYNONYM #### According to The Catalogue of Life, 3rd January 2011 #### Published in J. Coll. agric. , Hokkaido Imp. Univ. 45: 222 (1941) #### Original name Trichoglossum hirsutum f. variabile E.J. Durand, 1908 ### Remarks null
{ "content_hash": "b9976e9a3fb93e2d18c96bdb0a22f9cf", "timestamp": "", "source": "github", "line_count": 13, "max_line_length": 53, "avg_line_length": 17.692307692307693, "alnum_prop": 0.7, "repo_name": "mdoering/backbone", "id": "202edd2b2c953d5f07b39a0a5deb53601cc00301", "size": "319", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "life/Fungi/Ascomycota/Leotiomycetes/Helotiales/Geoglossaceae/Trichoglossum/Trichoglossum variabile/ Syn. Trichoglossum hirsutum variabile/README.md", "mode": "33188", "license": "apache-2.0", "language": [], "symlink_target": "" }
<!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta charset="utf-8" /> <title>What’s new in Statsmodels &#8212; statsmodels v0.10.1 documentation</title> <link rel="stylesheet" href="../_static/nature.css" type="text/css" /> <link rel="stylesheet" href="../_static/pygments.css" type="text/css" /> <link rel="stylesheet" type="text/css" href="../_static/graphviz.css" /> <script type="text/javascript" id="documentation_options" data-url_root="../" src="../_static/documentation_options.js"></script> <script type="text/javascript" src="../_static/jquery.js"></script> <script type="text/javascript" src="../_static/underscore.js"></script> <script type="text/javascript" src="../_static/doctools.js"></script> <script type="text/javascript" src="../_static/language_data.js"></script> <script async="async" type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/mathjax/2.7.5/latest.js?config=TeX-AMS-MML_HTMLorMML"></script> <link rel="shortcut icon" href="../_static/statsmodels_hybi_favico.ico"/> <link rel="author" title="About these documents" href="../about.html" /> <link rel="index" title="Index" href="../genindex.html" /> <link rel="search" title="Search" href="../search.html" /> <link rel="next" title="Release 0.10.1" href="version0.10.1.html" /> <link rel="prev" title="Welcome to Statsmodels’s Documentation" href="../index.html" /> <link rel="stylesheet" href="../_static/examples.css" type="text/css" /> <link rel="stylesheet" href="../_static/facebox.css" type="text/css" /> <script type="text/javascript" src="../_static/scripts.js"> </script> <script type="text/javascript" src="../_static/facebox.js"> </script> <script type="text/javascript"> $.facebox.settings.closeImage = "../_static/closelabel.png" $.facebox.settings.loadingImage = "../_static/loading.gif" </script> <script> $(document).ready(function() { $.getJSON("../../versions.json", function(versions) { var dropdown = document.createElement("div"); dropdown.className = "dropdown"; var button = document.createElement("button"); button.className = "dropbtn"; button.innerHTML = "Other Versions"; var content = document.createElement("div"); content.className = "dropdown-content"; dropdown.appendChild(button); dropdown.appendChild(content); $(".header").prepend(dropdown); for (var i = 0; i < versions.length; i++) { if (versions[i].substring(0, 1) == "v") { versions[i] = [versions[i], versions[i].substring(1)]; } else { versions[i] = [versions[i], versions[i]]; }; }; for (var i = 0; i < versions.length; i++) { var a = document.createElement("a"); a.innerHTML = versions[i][1]; a.href = "../../" + versions[i][0] + "/index.html"; a.title = versions[i][1]; $(".dropdown-content").append(a); }; }); }); </script> </head><body> <div class="headerwrap"> <div class = "header"> <a href = "../index.html"> <img src="../_static/statsmodels_hybi_banner.png" alt="Logo" style="padding-left: 15px"/></a> </div> </div> <div class="related" role="navigation" aria-label="related navigation"> <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="../py-modindex.html" title="Python Module Index" >modules</a> |</li> <li class="right" > <a href="version0.10.1.html" title="Release 0.10.1" accesskey="N">next</a> |</li> <li class="right" > <a href="../index.html" title="Welcome to Statsmodels’s Documentation" accesskey="P">previous</a> |</li> <li><a href ="../install.html">Install</a></li> &nbsp;|&nbsp; <li><a href="https://groups.google.com/forum/?hl=en#!forum/pystatsmodels">Support</a></li> &nbsp;|&nbsp; <li><a href="https://github.com/statsmodels/statsmodels/issues">Bugs</a></li> &nbsp;|&nbsp; <li><a href="../dev/index.html">Develop</a></li> &nbsp;|&nbsp; <li><a href="../examples/index.html">Examples</a></li> &nbsp;|&nbsp; <li><a href="../faq.html">FAQ</a></li> &nbsp;|&nbsp; </ul> </div> <div class="document"> <div class="documentwrapper"> <div class="bodywrapper"> <div class="body" role="main"> <div class="section" id="what-s-new-in-statsmodels"> <span id="whatsnew-index"></span><h1>What’s new in Statsmodels<a class="headerlink" href="#what-s-new-in-statsmodels" title="Permalink to this headline">¶</a></h1> <div class="toctree-wrapper compound"> <ul> <li class="toctree-l1"><a class="reference internal" href="version0.10.1.html">Release 0.10.1</a></li> <li class="toctree-l1"><a class="reference internal" href="version0.10.html">Release 0.10.0</a></li> <li class="toctree-l1"><a class="reference internal" href="version0.9.html">Release 0.9.0</a></li> <li class="toctree-l1"><a class="reference internal" href="version0.8.html">Release 0.8.0</a></li> <li class="toctree-l1"><a class="reference internal" href="version0.7.html">Release 0.7.0</a></li> <li class="toctree-l1"><a class="reference internal" href="version0.6.html">Release 0.6.1</a></li> <li class="toctree-l1"><a class="reference internal" href="version0.6.html#release-0-6-0">Release 0.6.0</a></li> <li class="toctree-l1"><a class="reference internal" href="version0.5.html">Release 0.5.0</a></li> </ul> </div> <p>For an overview of changes that occured previous to the 0.5.0 release see <a class="reference internal" href="old_changes.html#old-changes"><span class="std std-ref">Pre 0.5.0 Release History</span></a>.</p> </div> </div> </div> </div> <div class="sphinxsidebar" role="navigation" aria-label="main navigation"> <div class="sphinxsidebarwrapper"> <h4>Previous topic</h4> <p class="topless"><a href="../index.html" title="previous chapter">Welcome to Statsmodels’s Documentation</a></p> <h4>Next topic</h4> <p class="topless"><a href="version0.10.1.html" title="next chapter">Release 0.10.1</a></p> <div role="note" aria-label="source link"> <h3>This Page</h3> <ul class="this-page-menu"> <li><a href="../_sources/release/index.rst.txt" rel="nofollow">Show Source</a></li> </ul> </div> <div id="searchbox" style="display: none" role="search"> <h3 id="searchlabel">Quick search</h3> <div class="searchformwrapper"> <form class="search" action="../search.html" method="get"> <input type="text" name="q" aria-labelledby="searchlabel" /> <input type="submit" value="Go" /> </form> </div> </div> <script type="text/javascript">$('#searchbox').show(0);</script> </div> </div> <div class="clearer"></div> </div> <div class="footer" role="contentinfo"> &#169; Copyright 2009-2018, Josef Perktold, Skipper Seabold, Jonathan Taylor, statsmodels-developers. Created using <a href="http://sphinx-doc.org/">Sphinx</a> 2.1.2. </div> </body> </html>
{ "content_hash": "210825f00a6a179f0c04ab5804d2bc74", "timestamp": "", "source": "github", "line_count": 168, "max_line_length": 210, "avg_line_length": 42.970238095238095, "alnum_prop": 0.6212771852057072, "repo_name": "statsmodels/statsmodels.github.io", "id": "dea0baff0348970a5b8e01484c9259b72eacf5ec", "size": "7232", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "v0.10.1/release/index.html", "mode": "33188", "license": "bsd-3-clause", "language": [], "symlink_target": "" }
package org.apache.nutch.urlfilter.api; // JDK imports import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; import java.io.Reader; import java.util.ArrayList; import java.util.List; import org.junit.Assert; import org.slf4j.Logger; import org.slf4j.LoggerFactory; // Nutch imports import org.apache.nutch.net.URLFilter; /** * JUnit based test of class <code>RegexURLFilterBase</code>. * * @author J&eacute;r&ocirc;me Charron */ public abstract class RegexURLFilterBaseTest { /** My logger */ protected static final Logger LOG = LoggerFactory .getLogger(RegexURLFilterBaseTest.class); private final static String SEPARATOR = System.getProperty("file.separator"); private final static String SAMPLES = System.getProperty("test.data", "."); protected abstract URLFilter getURLFilter(Reader rules); protected void bench(int loops, String file) { try { bench(loops, new FileReader(SAMPLES + SEPARATOR + file + ".rules"), new FileReader(SAMPLES + SEPARATOR + file + ".urls")); } catch (Exception e) { Assert.fail(e.toString()); } } protected void bench(int loops, Reader rules, Reader urls) { long start = System.currentTimeMillis(); try { URLFilter filter = getURLFilter(rules); FilteredURL[] expected = readURLFile(urls); for (int i = 0; i < loops; i++) { test(filter, expected); } } catch (Exception e) { Assert.fail(e.toString()); } LOG.info("bench time (" + loops + ") " + (System.currentTimeMillis() - start) + "ms"); } protected void test(String file) { try { test(new FileReader(SAMPLES + SEPARATOR + file + ".rules"), new FileReader(SAMPLES + SEPARATOR + file + ".urls")); } catch (Exception e) { Assert.fail(e.toString()); } } protected void test(Reader rules, Reader urls) { try { test(getURLFilter(rules), readURLFile(urls)); } catch (Exception e) { Assert.fail(e.toString()); } } protected void test(URLFilter filter, FilteredURL[] expected) { for (int i = 0; i < expected.length; i++) { String result = filter.filter(expected[i].url); if (result != null) { Assert.assertTrue(expected[i].url, expected[i].sign); } else { Assert.assertFalse(expected[i].url, expected[i].sign); } } } private static FilteredURL[] readURLFile(Reader reader) throws IOException { BufferedReader in = new BufferedReader(reader); List<FilteredURL> list = new ArrayList<FilteredURL>(); String line; while ((line = in.readLine()) != null) { if (line.length() != 0) { list.add(new FilteredURL(line)); } } return (FilteredURL[]) list.toArray(new FilteredURL[list.size()]); } private static class FilteredURL { boolean sign; String url; FilteredURL(String line) { switch (line.charAt(0)) { case '+': sign = true; break; case '-': sign = false; break; default: // Simply ignore... } url = line.substring(1); } } }
{ "content_hash": "67b52da8309072c93f3dab7b478c8cda", "timestamp": "", "source": "github", "line_count": 119, "max_line_length": 79, "avg_line_length": 26.33613445378151, "alnum_prop": 0.6273133375877473, "repo_name": "nhahv/apache-nutch-1.x", "id": "0b582318e355d9c6d547206ccad0ef730aeae4c2", "size": "3936", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "src/plugin/lib-regex-filter/src/test/org/apache/nutch/urlfilter/api/RegexURLFilterBaseTest.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "HTML", "bytes": "56042" }, { "name": "Java", "bytes": "2288304" }, { "name": "Shell", "bytes": "18445" }, { "name": "XSLT", "bytes": "1822" } ], "symlink_target": "" }
(function(window, $){ 'use strict'; /** * @fileOverview Contains the awesome plug-in code. * @version 1.0.1 * @author Hyyoon &amp;lt;[email protected] */ /** * See (http://jquery.com/) * @name jQuery * @class * See the jQuery Library (http://jquery.com/) for full details. This just * documents the function and classes that are added to jQuery by this plug-in. */ /** * See (http://jquery.com/) * @name fn * @class * See the jQuery Library (http://jquery.com/) for full details. This just * documents the function and classes that are added to jQuery by this plug-in. * @memberOf jQuery */ /** * imageSliderNavigation Plugin - image slide sub module for navigation. * * @class imageSliderNavigation * @membarOf jQuery.fn */ $.fn.imageSliderNavigation = function navigation(options){ var len = $(this).find('.slide').find('li').length; var $a = ''; for(var i = 1; i <= len ;i++){ $a = $a + '<a href="#page=' + i +'" data-index="' + i + '" class="'+ (i === 1 ? 'active' : '') +'"><span class="bland">' + i + '</span></a>'; } var $slideNav = $(this).find('.slide-nav'); // if(options.theme){ // $slideNav.css('margin-left', options.width / 2 + 'px'); // } $slideNav.html($a); }; })(window, jQuery);
{ "content_hash": "315cd3810f706ba3b30822f4088372cc", "timestamp": "", "source": "github", "line_count": 45, "max_line_length": 147, "avg_line_length": 29.08888888888889, "alnum_prop": 0.5805958747135218, "repo_name": "sorita114/imageSlider", "id": "28098a9afa3ee5c92e6999925b2d47595a4e759c", "size": "1309", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "lib/jquery-plugin/jquery-imageSliderNavigation.js", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "16154" }, { "name": "JavaScript", "bytes": "4827" } ], "symlink_target": "" }
<application> <component name="CodeInsightSettings"> <option name="AUTO_POPUP_JAVADOC_INFO" value="true" /> <option name="SELECT_AUTOPOPUP_SUGGESTIONS_BY_CHARS" value="true" /> <option name="SHOW_FULL_SIGNATURES_IN_PARAMETER_INFO" value="true" /> <option name="SURROUND_SELECTION_ON_QUOTE_TYPED" value="true" /> <option name="ADD_IMPORTS_ON_PASTE" value="1" /> <option name="OPTIMIZE_IMPORTS_ON_THE_FLY" value="true" /> <option name="ADD_UNAMBIGIOUS_IMPORTS_ON_THE_FLY" value="true" /> </component> </application>
{ "content_hash": "44db1d53aee247c3e37d170758aa6b69", "timestamp": "", "source": "github", "line_count": 11, "max_line_length": 73, "avg_line_length": 49.54545454545455, "alnum_prop": 0.691743119266055, "repo_name": "jackmiras/intellij-idea-config", "id": "03cb076047a2ee7eab8a5d7ec576ddd52d636ff6", "size": "545", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "options/editor.codeinsight.xml", "mode": "33261", "license": "mit", "language": [ { "name": "Batchfile", "bytes": "4437" }, { "name": "Shell", "bytes": "8095" } ], "symlink_target": "" }
package com.zheng.cms.web.schedule; import com.taobao.pamirs.schedule.IScheduleTaskDealSingle; import com.taobao.pamirs.schedule.TaskItemDefine; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.ArrayList; import java.util.Comparator; import java.util.List; /** * 测试任务 * Created by zhangshuzheng on 2016/11/14. */ public class LongSchedule implements IScheduleTaskDealSingle<Long> { private static final Logger LOGGER = LoggerFactory.getLogger(LongSchedule.class); /** * 执行单个任务 * @param item Object * @param ownSign 当前环境名称 * @throws Exception */ @Override public boolean execute(Long item, String ownSign) throws Exception { LOGGER.info("执行任务:{}", item); return true; } /** * 根据条件,查询当前调度服务器可处理的任务 * @param taskParameter 任务的自定义参数 * @param ownSign 当前环境名称 * @param taskItemNum 当前任务类型的任务队列数量 * @param taskItemList 当前调度服务器,分配到的可处理队列 * @param eachFetchDataNum 每次获取数据的数量 * @return * @throws Exception */ @Override public List<Long> selectTasks(String taskParameter, String ownSign, int taskItemNum, List<TaskItemDefine> taskItemList, int eachFetchDataNum) throws Exception { List<Long> allDrawList = new ArrayList<>(); allDrawList.add(System.currentTimeMillis()); return allDrawList; } /** * 获取任务的比较器,只有在NotSleep模式下需要用到 * @return */ @Override public Comparator<Long> getComparator() { return new Comparator<Long>() { @Override public int compare(Long o1, Long o2) { return o1.compareTo(o2); } }; } }
{ "content_hash": "e805ebc318ae5c0432db0e329d3bed9f", "timestamp": "", "source": "github", "line_count": 63, "max_line_length": 164, "avg_line_length": 26.555555555555557, "alnum_prop": 0.6586969515839809, "repo_name": "shuzheng/zheng", "id": "2fbf3829ed67777b7c6ebcd6d696b45ddb17e606", "size": "1897", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "zheng-cms/zheng-cms-web/src/main/java/com/zheng/cms/web/schedule/LongSchedule.java", "mode": "33188", "license": "mit", "language": [ { "name": "Batchfile", "bytes": "7085" }, { "name": "CSS", "bytes": "233037" }, { "name": "HTML", "bytes": "188395" }, { "name": "Java", "bytes": "1605082" }, { "name": "JavaScript", "bytes": "223554" }, { "name": "Shell", "bytes": "39516" } ], "symlink_target": "" }
"""Tests for BERT trainer network.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function from absl.testing import parameterized import tensorflow as tf from tensorflow.python.keras import keras_parameterized # pylint: disable=g-direct-tensorflow-import from official.nlp.modeling import networks from official.nlp.modeling.models import bert_classifier # This decorator runs the test in V1, V2-Eager, and V2-Functional mode. It # guarantees forward compatibility of this code for the V2 switchover. @keras_parameterized.run_all_keras_modes class BertClassifierTest(keras_parameterized.TestCase): @parameterized.parameters(1, 3) def test_bert_trainer(self, num_classes): """Validate that the Keras object can be created.""" # Build a transformer network to use within the BERT trainer. vocab_size = 100 sequence_length = 512 test_network = networks.TransformerEncoder( vocab_size=vocab_size, num_layers=2, sequence_length=sequence_length) # Create a BERT trainer with the created network. bert_trainer_model = bert_classifier.BertClassifier( test_network, num_classes=num_classes) # Create a set of 2-dimensional inputs (the first dimension is implicit). word_ids = tf.keras.Input(shape=(sequence_length,), dtype=tf.int32) mask = tf.keras.Input(shape=(sequence_length,), dtype=tf.int32) type_ids = tf.keras.Input(shape=(sequence_length,), dtype=tf.int32) # Invoke the trainer model on the inputs. This causes the layer to be built. cls_outs = bert_trainer_model([word_ids, mask, type_ids]) # Validate that the outputs are of the expected shape. expected_classification_shape = [None, num_classes] self.assertAllEqual(expected_classification_shape, cls_outs.shape.as_list()) @parameterized.parameters(1, 2) def test_bert_trainer_tensor_call(self, num_classes): """Validate that the Keras object can be invoked.""" # Build a transformer network to use within the BERT trainer. (Here, we use # a short sequence_length for convenience.) test_network = networks.TransformerEncoder( vocab_size=100, num_layers=2, sequence_length=2) # Create a BERT trainer with the created network. bert_trainer_model = bert_classifier.BertClassifier( test_network, num_classes=num_classes) # Create a set of 2-dimensional data tensors to feed into the model. word_ids = tf.constant([[1, 1], [2, 2]], dtype=tf.int32) mask = tf.constant([[1, 1], [1, 0]], dtype=tf.int32) type_ids = tf.constant([[1, 1], [2, 2]], dtype=tf.int32) # Invoke the trainer model on the tensors. In Eager mode, this does the # actual calculation. (We can't validate the outputs, since the network is # too complex: this simply ensures we're not hitting runtime errors.) _ = bert_trainer_model([word_ids, mask, type_ids]) def test_serialize_deserialize(self): """Validate that the BERT trainer can be serialized and deserialized.""" # Build a transformer network to use within the BERT trainer. (Here, we use # a short sequence_length for convenience.) test_network = networks.TransformerEncoder( vocab_size=100, num_layers=2, sequence_length=5) # Create a BERT trainer with the created network. (Note that all the args # are different, so we can catch any serialization mismatches.) bert_trainer_model = bert_classifier.BertClassifier( test_network, num_classes=4, initializer='zeros') # Create another BERT trainer via serialization and deserialization. config = bert_trainer_model.get_config() new_bert_trainer_model = bert_classifier.BertClassifier.from_config(config) # Validate that the config can be forced to JSON. _ = new_bert_trainer_model.to_json() # If the serialization was successful, the new config should match the old. self.assertAllEqual(bert_trainer_model.get_config(), new_bert_trainer_model.get_config()) if __name__ == '__main__': tf.test.main()
{ "content_hash": "bff819a9a99f39fe277657b848aad268", "timestamp": "", "source": "github", "line_count": 92, "max_line_length": 101, "avg_line_length": 44.09782608695652, "alnum_prop": 0.7160463396598472, "repo_name": "tombstone/models", "id": "8e00c0313c61e1d8b1c4075933efee6eddcefd58", "size": "4746", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "official/nlp/modeling/models/bert_classifier_test.py", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "C++", "bytes": "1365199" }, { "name": "GLSL", "bytes": "976" }, { "name": "HTML", "bytes": "147010" }, { "name": "JavaScript", "bytes": "33208" }, { "name": "Jupyter Notebook", "bytes": "1858048" }, { "name": "Makefile", "bytes": "4763" }, { "name": "Python", "bytes": "7241242" }, { "name": "Shell", "bytes": "102270" }, { "name": "TypeScript", "bytes": "6515" } ], "symlink_target": "" }
"use strict"; var __extends = (this && this.__extends) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; var SearchMailboxesResult_1 = require("../../MailboxSearch/SearchMailboxesResult"); var XmlElementNames_1 = require("../XmlElementNames"); var ServiceResponse_1 = require("./ServiceResponse"); /** * Represents the SearchMailboxes response. * * @sealed */ var SearchMailboxesResponse = (function (_super) { __extends(SearchMailboxesResponse, _super); /** * @internal Initializes a new instance of the **SearchMailboxesResponse** class. */ function SearchMailboxesResponse() { _super.call(this); this.searchResult = null; } Object.defineProperty(SearchMailboxesResponse.prototype, "SearchResult", { /** * Search mailboxes result */ get: function () { return this.searchResult; }, /**@internal set*/ set: function (value) { this.searchResult = value; }, enumerable: true, configurable: true }); /** * @internal Reads response elements from Xml JsObject. * * @param {any} jsObject The response object. * @param {ExchangeService} service The service. */ SearchMailboxesResponse.prototype.ReadElementsFromXmlJsObject = function (jsObject, service) { //super.ReadElementsFromXmlJsObject(jsObject, service); if (jsObject[XmlElementNames_1.XmlElementNames.SearchMailboxesResult]) { this.searchResult = SearchMailboxesResult_1.SearchMailboxesResult.LoadFromXmlJsObject(jsObject[XmlElementNames_1.XmlElementNames.SearchMailboxesResult], service); } }; return SearchMailboxesResponse; }(ServiceResponse_1.ServiceResponse)); exports.SearchMailboxesResponse = SearchMailboxesResponse;
{ "content_hash": "abffcfd8e26d973c0d8b5f649c9448b5", "timestamp": "", "source": "github", "line_count": 52, "max_line_length": 174, "avg_line_length": 38.55769230769231, "alnum_prop": 0.6488778054862843, "repo_name": "eino-makitalo/ews-javascript-npmbuild", "id": "7625bf2faa04bb16a2a7dd54d92c08980031b67d", "size": "2005", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "js/Core/Responses/SearchMailboxesResponse.js", "mode": "33188", "license": "mit", "language": [ { "name": "JavaScript", "bytes": "3299999" } ], "symlink_target": "" }
<?php /** * Created by IntelliJ IDEA. * User: brlamore * Date: 7/18/14 * Time: 4:57 PM */ namespace RockIT\TechgamesBundle\Model; class TeamManager{ private $_items = array(); private $_profileManager; public function __construct() { $this->_profileManager = new ProfileManager(); $this->_items[1] = new Team(1, "3rd-degree"); $this->_items[2] = new Team(2, "Zoom Zoom"); $this->_items[3] = new Team(3, "UATSpeedie"); $this->_items[4] = new Team(4, "Artyletes"); $this->_items[5] = new Team(5, "MCC TShooters"); $this->_items[6] = new Team(6, "We Do Windows"); $this->_items[7] = new Team(7, "ITT West Phoenix #2"); $this->_items[8] = new Team(8, "Let's Go CGCC"); $this->_items[9] = new Team(9, "Winning Team"); $this->_items[10] = new Team(10, "Team Blue"); $this->_items[11] = new Team(11, "Team Earth"); $this->_items[12] = new Team(12, "Team Red"); $this->_items[13] = new Team(13, "Team Tucson"); $this->_items[14] = new Team(14, "Team Wildcat"); $this->_items[15] = new Team(15, "Team AZ"); $this->_items[16] = new Team(16, "Team Dinamo"); $this->_items[17] = new Team(17, "Team Grey"); $this->_items[18] = new Team(18, "Team Rise"); $this->_items[19] = new Team(19, "Team TSA"); $this->_items[20] = new Team(20, "UA"); $this->_items[21] = new Team(21, "U of A"); $this->_items[22] = new Team(22, "Wildcat"); $this->_items[23] = new Team(23, "AZ"); $this->_items[24] = new Team(24, "Arizona"); $this->_items[25] = new Team(25, "Northern Arizona"); $this->_items[26] = new Team(26, "NS 3"); $this->_items[27] = new Team(27, "PVCC Business/Computer Club"); $this->_items[28] = new Team(28, "Team170"); $this->_items[29] = new Team(29, "Team Five"); $this->_items[30] = new Team(30, "MCCSSD"); $this->_items[31] = new Team(31, "UAT Ladies 1st!"); $this->_items[32] = new Team(32, "PVCC Computer CLub #2"); $this->_items[33] = new Team(33, "ITT West Phoenix #3"); $this->_items[34] = new Team(34, "ITT West Phoenix #5"); // 3rd-degree $members = array(); array_push($members, $this->_profileManager->getProfile(2)); array_push($members, $this->_profileManager->getProfile(3)); array_push($members, $this->_profileManager->getProfile(4)); $this->_items[1]->setMembers($members); // UATSpeedie $members = array(); array_push($members, $this->_profileManager->getProfile(5)); $this->_items[3]->setMembers($members); // Let's Go CGCC $members = array(); array_push($members, new TeamMember($this->_profileManager->getProfile(7), False, False)); array_push($members, new TeamMember($this->_profileManager->getProfile(8), False, False)); array_push($members, new TeamMember($this->_profileManager->getProfile(9), False, False)); array_push($members, new TeamMember($this->_profileManager->getProfile(10), False, False)); array_push($members, new TeamMember($this->_profileManager->getProfile(11), True, True)); $this->_items[8]->setMembers($members); $this->_items[8]->setSchool("Chandler-Gilbert Community College"); // Zoom Zoom $members = array(); array_push($members, new TeamMember($this->_profileManager->getProfile(13), False, False)); array_push($members, new TeamMember($this->_profileManager->getProfile(14), False, False)); array_push($members, new TeamMember($this->_profileManager->getProfile(15), False, False)); array_push($members, new TeamMember($this->_profileManager->getProfile(11), True, True)); $this->_items[8]->setMembers($members); $this->_items[8]->setSchool("Chandler-Gilbert Community College"); } public function getTeam($teamId) { return $this->_items[$teamId]; } public function getMyTeams($profileId) { $myTeams = array(); array_push($myTeams, $this->_items[3]); return $myTeams; } public function getAllTeams() { return $this->_items; } }
{ "content_hash": "f71378b68ddaa1eefb697cfe64d8c868", "timestamp": "", "source": "github", "line_count": 115, "max_line_length": 99, "avg_line_length": 37.31304347826087, "alnum_prop": 0.5697972500582614, "repo_name": "briglx/techgames", "id": "4d3d2b08fd4d0d1d667e60c524b3dd24eeeb0e57", "size": "4291", "binary": false, "copies": "1", "ref": "refs/heads/teams", "path": "src/RockIT/TechgamesBundle/Model/TeamManager.php", "mode": "33188", "license": "mit", "language": [ { "name": "ApacheConf", "bytes": "2647" }, { "name": "CSS", "bytes": "122399" }, { "name": "HTML", "bytes": "120757" }, { "name": "JavaScript", "bytes": "94904" }, { "name": "PHP", "bytes": "176788" }, { "name": "Ruby", "bytes": "5110" } ], "symlink_target": "" }
#import "YapDatabaseTransaction.h" #import "YapDatabasePrivate.h" #import "YapDatabaseExtensionPrivate.h" #import "YapDatabaseString.h" #import "YapDatabaseLogging.h" #import "YapCache.h" #import "YapCollectionKey.h" #import "YapTouch.h" #import "YapNull.h" #import <objc/runtime.h> #if ! __has_feature(objc_arc) #warning This file must be compiled with ARC. Use -fobjc-arc flag (or convert project to ARC). #endif /** * Define log level for this file: OFF, ERROR, WARN, INFO, VERBOSE * See YapDatabaseLogging.h for more information. **/ #if DEBUG static const int ydbLogLevel = YDB_LOG_LEVEL_INFO; #else static const int ydbLogLevel = YDB_LOG_LEVEL_WARN; #endif #pragma unused(ydbLogLevel) @implementation YapDatabaseReadTransaction + (void)load { static BOOL loaded = NO; if (!loaded) { // Method swizzle: // Both extension: and ext: are designed to be the same method (with ext: shorthand for extension:). // So swap out the ext: method to point to extension:. Method extMethod = class_getInstanceMethod([self class], @selector(ext:)); IMP extensionIMP = class_getMethodImplementation([self class], @selector(extension:)); method_setImplementation(extMethod, extensionIMP); loaded = YES; } } - (id)initWithConnection:(YapDatabaseConnection *)aConnection isReadWriteTransaction:(BOOL)flag { if ((self = [super init])) { connection = aConnection; isReadWriteTransaction = flag; } return self; } @synthesize connection = connection; @synthesize userInfo = _external_userInfo; //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// #pragma mark Transaction States //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// - (void)beginTransaction { sqlite3_stmt *statement = [connection beginTransactionStatement]; if (statement == NULL) return; // BEGIN TRANSACTION; int status = sqlite3_step(statement); if (status != SQLITE_DONE) { YDBLogError(@"Couldn't begin transaction: %d %s", status, sqlite3_errmsg(connection->db)); } sqlite3_reset(statement); } - (void)preCommitReadWriteTransaction { // Step 1: // // Allow extensions to flush changes to the main database table. // This is different from flushing changes to their own private tables. // We're referring here to the main collection/key/value table (database2) that's public. __block BOOL restart; __block BOOL prevExtModifiesMainDatabaseTable; do { isMutated = NO; restart = NO; prevExtModifiesMainDatabaseTable = NO; [extensions enumerateKeysAndObjectsUsingBlock:^(id __unused extNameObj, id extTransactionObj, BOOL *stop) { BOOL extModifiesMainDatabaseTable = [(YapDatabaseExtensionTransaction *)extTransactionObj flushPendingChangesToMainDatabaseTable]; if (extModifiesMainDatabaseTable) { if (!isMutated) { prevExtModifiesMainDatabaseTable = YES; } else { if (prevExtModifiesMainDatabaseTable) { restart = YES; *stop = YES; } else { prevExtModifiesMainDatabaseTable = YES; } } } }]; } while (restart); // Step 2: // // Allow extensions to flush changes to their own tables, // and perform any needed "cleanup" code needed before the changeset is requested. [extensions enumerateKeysAndObjectsUsingBlock:^(id __unused extNameObj, id extTransactionObj, BOOL __unused *stop) { [(YapDatabaseExtensionTransaction *)extTransactionObj flushPendingChangesToExtensionTables]; }]; [yapMemoryTableTransaction commit]; } - (void)commitTransaction { sqlite3_stmt *statement = [connection commitTransactionStatement]; if (statement) { // COMMIT TRANSACTION; int status = sqlite3_step(statement); if (status != SQLITE_DONE) { YDBLogError(@"Couldn't commit transaction: %d %s", status, sqlite3_errmsg(connection->db)); } sqlite3_reset(statement); } if (isReadWriteTransaction) { [extensions enumerateKeysAndObjectsUsingBlock:^(id __unused extNameObj, id extTransactionObj, BOOL __unused *stop) { [(YapDatabaseExtensionTransaction *)extTransactionObj didCommitTransaction]; }]; } } - (void)rollbackTransaction { sqlite3_stmt *statement = [connection rollbackTransactionStatement]; if (statement) { // ROLLBACK TRANSACTION; int status = sqlite3_step(statement); if (status != SQLITE_DONE) { YDBLogError(@"Couldn't rollback transaction: %d %s", status, sqlite3_errmsg(connection->db)); } sqlite3_reset(statement); } [extensions enumerateKeysAndObjectsUsingBlock:^(id __unused extNameObj, id extTransactionObj, BOOL __unused *stop) { [(YapDatabaseExtensionTransaction *)extTransactionObj didRollbackTransaction]; }]; [yapMemoryTableTransaction rollback]; } //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// #pragma mark Count //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// - (NSUInteger)numberOfCollections { sqlite3_stmt *statement = [connection getCollectionCountStatement]; if (statement == NULL) return 0; // SELECT COUNT(DISTINCT collection) AS NumberOfRows FROM "database2"; NSUInteger result = 0; int status = sqlite3_step(statement); if (status == SQLITE_ROW) { if (connection->needsMarkSqlLevelSharedReadLock) [connection markSqlLevelSharedReadLockAcquired]; result = (NSUInteger)sqlite3_column_int64(statement, SQLITE_COLUMN_START); } else if (status == SQLITE_ERROR) { YDBLogError(@"Error executing 'getCollectionCountStatement': %d %s", status, sqlite3_errmsg(connection->db)); } sqlite3_reset(statement); return result; } - (NSUInteger)numberOfKeysInCollection:(NSString *)collection { if (collection == nil) collection = @""; sqlite3_stmt *statement = [connection getKeyCountForCollectionStatement]; if (statement == NULL) return 0; // SELECT COUNT(*) AS NumberOfRows FROM "database2" WHERE "collection" = ?; int const column_idx_result = SQLITE_COLUMN_START; int const bind_idx_collection = SQLITE_BIND_START; YapDatabaseString _collection; MakeYapDatabaseString(&_collection, collection); sqlite3_bind_text(statement, bind_idx_collection, _collection.str, _collection.length, SQLITE_STATIC); NSUInteger result = 0; int status = sqlite3_step(statement); if (status == SQLITE_ROW) { if (connection->needsMarkSqlLevelSharedReadLock) [connection markSqlLevelSharedReadLockAcquired]; result = (NSUInteger)sqlite3_column_int64(statement, column_idx_result); } else if (status == SQLITE_ERROR) { YDBLogError(@"Error executing 'getKeyCountForCollectionStatement': %d %s", status, sqlite3_errmsg(connection->db)); } sqlite3_clear_bindings(statement); sqlite3_reset(statement); FreeYapDatabaseString(&_collection); return result; } - (NSUInteger)numberOfKeysInAllCollections { sqlite3_stmt *statement = [connection getKeyCountForAllStatement]; if (statement == NULL) return 0; // SELECT COUNT(*) AS NumberOfRows FROM "database2"; NSUInteger result = 0; int status = sqlite3_step(statement); if (status == SQLITE_ROW) { if (connection->needsMarkSqlLevelSharedReadLock) [connection markSqlLevelSharedReadLockAcquired]; result = (NSUInteger)sqlite3_column_int64(statement, SQLITE_COLUMN_START); } else if (status == SQLITE_ERROR) { YDBLogError(@"Error executing 'getKeyCountForAllStatement': %d %s", status, sqlite3_errmsg(connection->db)); } sqlite3_reset(statement); return result; } //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// #pragma mark List //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// - (NSArray *)allCollections { sqlite3_stmt *statement = [connection enumerateCollectionsStatement]; if (statement == NULL) return nil; // SELECT DISTINCT "collection" FROM "database2";"; NSMutableArray *result = [NSMutableArray array]; int status = sqlite3_step(statement); if (status == SQLITE_ROW) { if (connection->needsMarkSqlLevelSharedReadLock) [connection markSqlLevelSharedReadLockAcquired]; do { const unsigned char *text = sqlite3_column_text(statement, SQLITE_COLUMN_START); int textSize = sqlite3_column_bytes(statement, SQLITE_COLUMN_START); NSString *collection = [[NSString alloc] initWithBytes:text length:textSize encoding:NSUTF8StringEncoding]; [result addObject:collection]; } while ((status = sqlite3_step(statement)) == SQLITE_ROW); } sqlite3_reset(statement); return result; } - (NSArray *)allKeysInCollection:(NSString *)collection { NSUInteger count = [self numberOfKeysInCollection:collection]; NSMutableArray *result = [NSMutableArray arrayWithCapacity:count]; [self _enumerateKeysInCollection:collection usingBlock:^(int64_t __unused rowid, NSString *key, BOOL __unused *stop) { [result addObject:key]; }]; return result; } //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// #pragma mark Internal (using rowid) //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// - (BOOL)getRowid:(int64_t *)rowidPtr forKey:(NSString *)key inCollection:(NSString *)collection { if (key == nil) { if (rowidPtr) *rowidPtr = 0; return NO; } if (collection == nil) collection = @""; sqlite3_stmt *statement = [connection getRowidForKeyStatement]; if (statement == NULL) { if (rowidPtr) *rowidPtr = 0; return NO; } // SELECT "rowid" FROM "database2" WHERE "collection" = ? AND "key" = ?; int const column_idx_result = SQLITE_COLUMN_START; int const bind_idx_collection = SQLITE_BIND_START + 0; int const bind_idx_key = SQLITE_BIND_START + 1; YapDatabaseString _collection; MakeYapDatabaseString(&_collection, collection); sqlite3_bind_text(statement, bind_idx_collection, _collection.str, _collection.length, SQLITE_STATIC); YapDatabaseString _key; MakeYapDatabaseString(&_key, key); sqlite3_bind_text(statement, bind_idx_key, _key.str, _key.length, SQLITE_STATIC); int64_t rowid = 0; BOOL result = NO; int status = sqlite3_step(statement); if (status == SQLITE_ROW) { if (connection->needsMarkSqlLevelSharedReadLock) [connection markSqlLevelSharedReadLockAcquired]; rowid = sqlite3_column_int64(statement, column_idx_result); result = YES; } else if (status == SQLITE_ERROR) { YDBLogError(@"Error executing 'getRowidForKeyStatement': %d %s", status, sqlite3_errmsg(connection->db)); } sqlite3_clear_bindings(statement); sqlite3_reset(statement); FreeYapDatabaseString(&_collection); FreeYapDatabaseString(&_key); if (rowidPtr) *rowidPtr = rowid; return result; } - (YapCollectionKey *)collectionKeyForRowid:(int64_t)rowid { NSNumber *rowidNumber = @(rowid); YapCollectionKey *collectionKey = [connection->keyCache objectForKey:rowidNumber]; if (collectionKey) { return collectionKey; } sqlite3_stmt *statement = [connection getKeyForRowidStatement]; if (statement == NULL) { return nil; } // SELECT "collection", "key" FROM "database2" WHERE "rowid" = ?; int const column_idx_collection = SQLITE_COLUMN_START + 0; int const column_idx_key = SQLITE_COLUMN_START + 1; int const bind_idx_rowid = SQLITE_BIND_START; sqlite3_bind_int64(statement, bind_idx_rowid, rowid); int status = sqlite3_step(statement); if (status == SQLITE_ROW) { if (connection->needsMarkSqlLevelSharedReadLock) [connection markSqlLevelSharedReadLockAcquired]; const unsigned char *text0 = sqlite3_column_text(statement, column_idx_collection); int textSize0 = sqlite3_column_bytes(statement, column_idx_collection); const unsigned char *text1 = sqlite3_column_text(statement, column_idx_key); int textSize1 = sqlite3_column_bytes(statement, column_idx_key); NSString *collection = [[NSString alloc] initWithBytes:text0 length:textSize0 encoding:NSUTF8StringEncoding]; NSString *key = [[NSString alloc] initWithBytes:text1 length:textSize1 encoding:NSUTF8StringEncoding]; collectionKey = [[YapCollectionKey alloc] initWithCollection:collection key:key]; [connection->keyCache setObject:collectionKey forKey:rowidNumber]; } else if (status == SQLITE_ERROR) { YDBLogError(@"Error executing 'getKeyForRowidStatement': %d %s", status, sqlite3_errmsg(connection->db)); } sqlite3_clear_bindings(statement); sqlite3_reset(statement); return collectionKey; } - (BOOL)getCollectionKey:(YapCollectionKey **)collectionKeyPtr object:(id *)objectPtr forRowid:(int64_t)rowid { YapCollectionKey *collectionKey = [self collectionKeyForRowid:rowid]; if (collectionKey) { id object = [self objectForCollectionKey:collectionKey withRowid:rowid]; if (collectionKeyPtr) *collectionKeyPtr = collectionKey; if (objectPtr) *objectPtr = object; return YES; } else { if (collectionKeyPtr) *collectionKeyPtr = nil; if (objectPtr) *objectPtr = nil; return NO; } } - (BOOL)getCollectionKey:(YapCollectionKey **)collectionKeyPtr metadata:(id *)metadataPtr forRowid:(int64_t)rowid { YapCollectionKey *collectionKey = [self collectionKeyForRowid:rowid]; if (collectionKey) { id metadata = [self metadataForCollectionKey:collectionKey withRowid:rowid]; if (collectionKeyPtr) *collectionKeyPtr = collectionKey; if (metadataPtr) *metadataPtr = metadata; return YES; } else { if (collectionKeyPtr) *collectionKeyPtr = nil; if (metadataPtr) *metadataPtr = nil; return NO; } } - (BOOL)getCollectionKey:(YapCollectionKey **)collectionKeyPtr object:(id *)objectPtr metadata:(id *)metadataPtr forRowid:(int64_t)rowid { YapCollectionKey *collectionKey = [self collectionKeyForRowid:rowid]; if (collectionKey == nil) { if (collectionKeyPtr) *collectionKeyPtr = nil; if (objectPtr) *objectPtr = nil; if (metadataPtr) *metadataPtr = nil; return NO; } if ([self getObject:objectPtr metadata:metadataPtr forCollectionKey:collectionKey withRowid:rowid]) { if (collectionKeyPtr) *collectionKeyPtr = collectionKey; return YES; } else { if (collectionKeyPtr) *collectionKeyPtr = nil; return NO; } } - (BOOL)hasRowid:(int64_t)rowid { sqlite3_stmt *statement = [connection getCountForRowidStatement]; if (statement == NULL) return NO; // SELECT COUNT(*) AS NumberOfRows FROM "database2" WHERE "rowid" = ?; int const column_idx_result = SQLITE_COLUMN_START; int const bind_idx_rowid = SQLITE_BIND_START; sqlite3_bind_int64(statement, bind_idx_rowid, rowid); BOOL result = NO; int status = sqlite3_step(statement); if (status == SQLITE_ROW) { if (connection->needsMarkSqlLevelSharedReadLock) [connection markSqlLevelSharedReadLockAcquired]; result = (sqlite3_column_int64(statement, column_idx_result) > 0); } else if (status == SQLITE_ERROR) { YDBLogError(@"Error executing 'getCountForRowidStatement': %d %s", status, sqlite3_errmsg(connection->db)); } sqlite3_clear_bindings(statement); sqlite3_reset(statement); return result; } - (id)objectForKey:(NSString *)key inCollection:(NSString *)collection withRowid:(int64_t)rowid { YapCollectionKey *cacheKey = [[YapCollectionKey alloc] initWithCollection:collection key:key]; return [self objectForCollectionKey:cacheKey withRowid:rowid]; } - (id)objectForCollectionKey:(YapCollectionKey *)cacheKey withRowid:(int64_t)rowid { if (cacheKey == nil) return nil; id object = [connection->objectCache objectForKey:cacheKey]; if (object) return object; sqlite3_stmt *statement = [connection getDataForRowidStatement]; if (statement == NULL) return nil; // SELECT "data" FROM "database2" WHERE "rowid" = ?; int const column_idx_data = SQLITE_COLUMN_START; int const bind_idx_rowid = SQLITE_BIND_START; sqlite3_bind_int64(statement, bind_idx_rowid, rowid); int status = sqlite3_step(statement); if (status == SQLITE_ROW) { if (connection->needsMarkSqlLevelSharedReadLock) [connection markSqlLevelSharedReadLockAcquired]; const void *blob = sqlite3_column_blob(statement, column_idx_data); int blobSize = sqlite3_column_bytes(statement, column_idx_data); // Performance tuning: // Use dataWithBytesNoCopy to avoid an extra allocation and memcpy. NSData *data = [NSData dataWithBytesNoCopy:(void *)blob length:blobSize freeWhenDone:NO]; object = connection->database->objectDeserializer(cacheKey.collection, cacheKey.key, data); if (object) [connection->objectCache setObject:object forKey:cacheKey]; } else if (status == SQLITE_ERROR) { YDBLogError(@"Error executing 'getDataForRowidStatement': %d %s", status, sqlite3_errmsg(connection->db)); } sqlite3_clear_bindings(statement); sqlite3_reset(statement); return object; } - (id)metadataForKey:(NSString *)key inCollection:(NSString *)collection withRowid:(int64_t)rowid { YapCollectionKey *cacheKey = [[YapCollectionKey alloc] initWithCollection:collection key:key]; return [self metadataForCollectionKey:cacheKey withRowid:rowid]; } - (id)metadataForCollectionKey:(YapCollectionKey *)cacheKey withRowid:(int64_t)rowid { if (cacheKey == nil) return nil; id metadata = [connection->metadataCache objectForKey:cacheKey]; if (metadata) return metadata; sqlite3_stmt *statement = [connection getMetadataForRowidStatement]; if (statement == NULL) return nil; // SELECT "metadata" FROM "database2" WHERE "rowid" = ?; int const column_idx_metadata = SQLITE_COLUMN_START; int const bind_idx_rowid = SQLITE_BIND_START; sqlite3_bind_int64(statement, bind_idx_rowid, rowid); int status = sqlite3_step(statement); if (status == SQLITE_ROW) { if (connection->needsMarkSqlLevelSharedReadLock) [connection markSqlLevelSharedReadLockAcquired]; const void *blob = sqlite3_column_blob(statement, column_idx_metadata); int blobSize = sqlite3_column_bytes(statement, column_idx_metadata); // Performance tuning: // Use dataWithBytesNoCopy to avoid an extra allocation and memcpy. NSData *data = [NSData dataWithBytesNoCopy:(void *)blob length:blobSize freeWhenDone:NO]; metadata = connection->database->metadataDeserializer(cacheKey.collection, cacheKey.key, data); if (metadata) [connection->metadataCache setObject:metadata forKey:cacheKey]; } else if (status == SQLITE_ERROR) { YDBLogError(@"Error executing 'getMetadataForRowidStatement': %d %s", status, sqlite3_errmsg(connection->db)); } sqlite3_clear_bindings(statement); sqlite3_reset(statement); return metadata; } - (BOOL)getObject:(id *)objectPtr metadata:(id *)metadataPtr forCollectionKey:(YapCollectionKey *)collectionKey withRowid:(int64_t)rowid { id object = [connection->objectCache objectForKey:collectionKey]; id metadata = [connection->metadataCache objectForKey:collectionKey]; if (object || metadata) { if (object == nil) { object = [self objectForCollectionKey:collectionKey withRowid:rowid]; } else if (metadata == nil) { metadata = [self metadataForCollectionKey:collectionKey withRowid:rowid]; } if (objectPtr) *objectPtr = object; if (metadataPtr) *metadataPtr = metadata; return YES; } sqlite3_stmt *statement = [connection getAllForRowidStatement]; if (statement == NULL) { if (objectPtr) *objectPtr = nil; if (metadataPtr) *metadataPtr = nil; return NO; } // SELECT "data", "metadata" FROM "database2" WHERE "rowid" = ?; int const column_idx_data = SQLITE_COLUMN_START + 0; int const column_idx_metadata = SQLITE_COLUMN_START + 1; int const bind_idx_rowid = SQLITE_BIND_START; sqlite3_bind_int64(statement, bind_idx_rowid, rowid); int status = sqlite3_step(statement); if (status == SQLITE_ROW) { if (connection->needsMarkSqlLevelSharedReadLock) [connection markSqlLevelSharedReadLockAcquired]; const void *blob = sqlite3_column_blob(statement, column_idx_data); int blobSize = sqlite3_column_bytes(statement, column_idx_data); // Performance tuning: // Use dataWithBytesNoCopy to avoid an extra allocation and memcpy. NSData *data = [NSData dataWithBytesNoCopy:(void *)blob length:blobSize freeWhenDone:NO]; object = connection->database->objectDeserializer(collectionKey.collection, collectionKey.key, data); if (object) [connection->objectCache setObject:object forKey:collectionKey]; const void *mBlob = sqlite3_column_blob(statement, column_idx_metadata); int mBlobSize = sqlite3_column_bytes(statement, column_idx_metadata); if (mBlobSize > 0) { // Performance tuning: // Use dataWithBytesNoCopy to avoid an extra allocation and memcpy. NSData *mData = [NSData dataWithBytesNoCopy:(void *)mBlob length:mBlobSize freeWhenDone:NO]; metadata = connection->database->metadataDeserializer(collectionKey.collection, collectionKey.key, mData); } if (metadata) [connection->metadataCache setObject:metadata forKey:collectionKey]; else [connection->metadataCache setObject:[YapNull null] forKey:collectionKey]; } else if (status == SQLITE_ERROR) { YDBLogError(@"Error executing 'getKeyForRowidStatement': %d %s", status, sqlite3_errmsg(connection->db)); } sqlite3_clear_bindings(statement); sqlite3_reset(statement); if (objectPtr) *objectPtr = object; if (metadataPtr) *metadataPtr = metadata; return YES; } //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// #pragma mark Object & Metadata //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// - (id)objectForKey:(NSString *)key inCollection:(NSString *)collection { if (key == nil) return nil; if (collection == nil) collection = @""; YapCollectionKey *cacheKey = [[YapCollectionKey alloc] initWithCollection:collection key:key]; id object = [connection->objectCache objectForKey:cacheKey]; if (object) return object; sqlite3_stmt *statement = [connection getDataForKeyStatement]; if (statement == NULL) return nil; // SELECT "data" FROM "database2" WHERE "collection" = ? AND "key" = ?; int const column_idx_data = SQLITE_COLUMN_START; int const bind_idx_collection = SQLITE_BIND_START + 0; int const bind_idx_key = SQLITE_BIND_START + 1; YapDatabaseString _collection; MakeYapDatabaseString(&_collection, collection); sqlite3_bind_text(statement, bind_idx_collection, _collection.str, _collection.length, SQLITE_STATIC); YapDatabaseString _key; MakeYapDatabaseString(&_key, key); sqlite3_bind_text(statement, bind_idx_key, _key.str, _key.length, SQLITE_STATIC); int status = sqlite3_step(statement); if (status == SQLITE_ROW) { if (connection->needsMarkSqlLevelSharedReadLock) [connection markSqlLevelSharedReadLockAcquired]; const void *blob = sqlite3_column_blob(statement, column_idx_data); int blobSize = sqlite3_column_bytes(statement, column_idx_data); // Performance tuning: // Use dataWithBytesNoCopy to avoid an extra allocation and memcpy. // Be sure not to call sqlite3_reset until we're done with the data. NSData *data = [NSData dataWithBytesNoCopy:(void *)blob length:blobSize freeWhenDone:NO]; object = connection->database->objectDeserializer(collection, key, data); } else if (status == SQLITE_ERROR) { YDBLogError(@"Error executing 'getDataForKeyStatement': %d %s, key(%@)", status, sqlite3_errmsg(connection->db), key); } sqlite3_clear_bindings(statement); sqlite3_reset(statement); FreeYapDatabaseString(&_collection); FreeYapDatabaseString(&_key); if (object) [connection->objectCache setObject:object forKey:cacheKey]; return object; } - (BOOL)hasObjectForKey:(NSString *)key inCollection:(NSString *)collection { if (key == nil) return NO; if (collection == nil) collection = @""; // Shortcut: // We may not need to query the database if we have the key in any of our caches. YapCollectionKey *cacheKey = [[YapCollectionKey alloc] initWithCollection:collection key:key]; if ([connection->objectCache objectForKey:cacheKey]) return YES; if ([connection->metadataCache objectForKey:cacheKey]) return YES; // The normal SQL way return [self getRowid:NULL forKey:key inCollection:collection]; } - (BOOL)getObject:(id *)objectPtr metadata:(id *)metadataPtr forKey:(NSString *)key inCollection:(NSString *)collection { if (key == nil) { if (objectPtr) *objectPtr = nil; if (metadataPtr) *metadataPtr = nil; return NO; } if (collection == nil) collection = @""; YapCollectionKey *cacheKey = [[YapCollectionKey alloc] initWithCollection:collection key:key]; id object = [connection->objectCache objectForKey:cacheKey]; id metadata = [connection->metadataCache objectForKey:cacheKey]; BOOL found = NO; if (object && metadata) { // Both object and metadata were in cache. found = YES; // Need to check for empty metadata placeholder from cache. if (metadata == [YapNull null]) metadata = nil; } else if (!object && metadata) { // Metadata was in cache. found = YES; // Need to check for empty metadata placeholder from cache. if (metadata == [YapNull null]) metadata = nil; // Missing object. Fetch individually if requested. if (objectPtr) object = [self objectForKey:key inCollection:collection]; } else if (object && !metadata) { // Object was in cache. found = YES; // Missing metadata. Fetch individually if requested. if (metadataPtr) metadata = [self metadataForKey:key inCollection:collection]; } else // (!object && !metadata) { // Both object and metadata are missing. // Fetch via query. sqlite3_stmt *statement = [connection getAllForKeyStatement]; if (statement) { // SELECT "data", "metadata" FROM "database2" WHERE "collection" = ? AND "key" = ? ; int const column_idx_data = SQLITE_COLUMN_START + 0; int const column_idx_metadata = SQLITE_COLUMN_START + 1; int const bind_idx_collection = SQLITE_BIND_START + 0; int const bind_idx_key = SQLITE_BIND_START + 1; YapDatabaseString _collection; MakeYapDatabaseString(&_collection, collection); sqlite3_bind_text(statement, bind_idx_collection, _collection.str, _collection.length, SQLITE_STATIC); YapDatabaseString _key; MakeYapDatabaseString(&_key, key); sqlite3_bind_text(statement, bind_idx_key, _key.str, _key.length, SQLITE_STATIC); int status = sqlite3_step(statement); if (status == SQLITE_ROW) { if (connection->needsMarkSqlLevelSharedReadLock) [connection markSqlLevelSharedReadLockAcquired]; const void *oBlob = sqlite3_column_blob(statement, column_idx_data); int oBlobSize = sqlite3_column_bytes(statement, column_idx_data); const void *mBlob = sqlite3_column_blob(statement, column_idx_metadata); int mBlobSize = sqlite3_column_bytes(statement, column_idx_metadata); if (objectPtr) { NSData *oData = [NSData dataWithBytesNoCopy:(void *)oBlob length:oBlobSize freeWhenDone:NO]; object = connection->database->objectDeserializer(collection, key, oData); } if (metadataPtr && mBlobSize > 0) { NSData *mData = [NSData dataWithBytesNoCopy:(void *)mBlob length:mBlobSize freeWhenDone:NO]; metadata = connection->database->metadataDeserializer(collection, key, mData); } found = YES; } else if (status == SQLITE_ERROR) { YDBLogError(@"Error executing 'getAllForKeyStatement': %d %s", status, sqlite3_errmsg(connection->db)); } if (object) { [connection->objectCache setObject:object forKey:cacheKey]; if (metadata) [connection->metadataCache setObject:metadata forKey:cacheKey]; else [connection->metadataCache setObject:[YapNull null] forKey:cacheKey]; } sqlite3_clear_bindings(statement); sqlite3_reset(statement); FreeYapDatabaseString(&_collection); FreeYapDatabaseString(&_key); } } if (objectPtr) *objectPtr = object; if (metadataPtr) *metadataPtr = metadata; return found; } - (id)metadataForKey:(NSString *)key inCollection:(NSString *)collection { if (key == nil) return nil; if (collection == nil) collection = @""; YapCollectionKey *cacheKey = [[YapCollectionKey alloc] initWithCollection:collection key:key]; id metadata = [connection->metadataCache objectForKey:cacheKey]; if (metadata) { if (metadata == [YapNull null]) return nil; else return metadata; } sqlite3_stmt *statement = [connection getMetadataForKeyStatement]; if (statement == NULL) return nil; // SELECT "metadata" FROM "database2" WHERE "collection" = ? AND "key" = ? ; int const column_idx_metadata = SQLITE_COLUMN_START; int const bind_idx_collection = SQLITE_BIND_START + 0; int const bind_idx_key = SQLITE_BIND_START + 1; YapDatabaseString _collection; MakeYapDatabaseString(&_collection, collection); sqlite3_bind_text(statement, bind_idx_collection, _collection.str, _collection.length, SQLITE_STATIC); YapDatabaseString _key; MakeYapDatabaseString(&_key, key); sqlite3_bind_text(statement, bind_idx_key, _key.str, _key.length, SQLITE_STATIC); BOOL found = NO; NSData *metadataData = nil; int status = sqlite3_step(statement); if (status == SQLITE_ROW) { if (connection->needsMarkSqlLevelSharedReadLock) [connection markSqlLevelSharedReadLockAcquired]; found = YES; const void *blob = sqlite3_column_blob(statement, column_idx_metadata); int blobSize = sqlite3_column_bytes(statement, column_idx_metadata); // Performance tuning: // // Use dataWithBytesNoCopy to avoid an extra allocation and memcpy. // But be sure not to call sqlite3_reset until we're done with the data. if (blobSize > 0) metadataData = [NSData dataWithBytesNoCopy:(void *)blob length:blobSize freeWhenDone:NO]; } else if (status == SQLITE_ERROR) { YDBLogError(@"Error executing 'getMetadataForKeyStatement': %d %s", status, sqlite3_errmsg(connection->db)); } if (found) { if (metadataData) metadata = connection->database->metadataDeserializer(collection, key, metadataData); if (metadata) [connection->metadataCache setObject:metadata forKey:cacheKey]; else [connection->metadataCache setObject:[YapNull null] forKey:cacheKey]; } sqlite3_clear_bindings(statement); sqlite3_reset(statement); FreeYapDatabaseString(&_collection); FreeYapDatabaseString(&_key); return metadata; } //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// #pragma mark Primitive //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// /** * Primitive access. * This method is available in-case you have a need to fetch the raw serializedObject from the database. * * This method is slower than objectForKey:inCollection:, since that method makes use of the objectCache. * In contrast, this method always fetches the raw data from disk. * * @see objectForKey:inCollection: **/ - (NSData *)serializedObjectForKey:(NSString *)key inCollection:(NSString *)collection { if (key == nil) return nil; if (collection == nil) collection = @""; sqlite3_stmt *statement = [connection getDataForKeyStatement]; if (statement == NULL) return nil; NSData *result = nil; // SELECT "data" FROM "database2" WHERE "collection" = ? AND "key" = ?; int const column_idx_data = SQLITE_COLUMN_START; int const bind_idx_collection = SQLITE_BIND_START + 0; int const bind_idx_key = SQLITE_BIND_START + 1; YapDatabaseString _collection; MakeYapDatabaseString(&_collection, collection); sqlite3_bind_text(statement, bind_idx_collection, _collection.str, _collection.length, SQLITE_STATIC); YapDatabaseString _key; MakeYapDatabaseString(&_key, key); sqlite3_bind_text(statement, bind_idx_key, _key.str, _key.length, SQLITE_STATIC); int status = sqlite3_step(statement); if (status == SQLITE_ROW) { if (connection->needsMarkSqlLevelSharedReadLock) [connection markSqlLevelSharedReadLockAcquired]; const void *blob = sqlite3_column_blob(statement, column_idx_data); int blobSize = sqlite3_column_bytes(statement, column_idx_data); result = [[NSData alloc] initWithBytes:blob length:blobSize]; } else if (status == SQLITE_ERROR) { YDBLogError(@"Error executing 'getDataForKeyStatement': %d %s, key(%@)", status, sqlite3_errmsg(connection->db), key); } sqlite3_clear_bindings(statement); sqlite3_reset(statement); FreeYapDatabaseString(&_collection); FreeYapDatabaseString(&_key); return result; } /** * Primitive access. * This method is available in-case you have a need to fetch the raw serializedMetadata from the database. * * This method is slower than metadataForKey:inCollection:, since that method makes use of the metadataCache. * In contrast, this method always fetches the raw data from disk. * * @see metadataForKey:inCollection: **/ - (NSData *)serializedMetadataForKey:(NSString *)key inCollection:(NSString *)collection { if (key == nil) return nil; if (collection == nil) collection = @""; sqlite3_stmt *statement = [connection getMetadataForKeyStatement]; if (statement == NULL) return nil; // SELECT "metadata" FROM "database2" WHERE "collection" = ? AND "key" = ? ; int const column_idx_metadata = SQLITE_COLUMN_START; int const bind_idx_collection = SQLITE_BIND_START + 0; int const bind_idx_key = SQLITE_BIND_START + 1; YapDatabaseString _collection; MakeYapDatabaseString(&_collection, collection); sqlite3_bind_text(statement, bind_idx_collection, _collection.str, _collection.length, SQLITE_STATIC); YapDatabaseString _key; MakeYapDatabaseString(&_key, key); sqlite3_bind_text(statement, bind_idx_key, _key.str, _key.length, SQLITE_STATIC); NSData *result = nil; int status = sqlite3_step(statement); if (status == SQLITE_ROW) { if (connection->needsMarkSqlLevelSharedReadLock) [connection markSqlLevelSharedReadLockAcquired]; const void *blob = sqlite3_column_blob(statement, column_idx_metadata); int blobSize = sqlite3_column_bytes(statement, column_idx_metadata); result = [[NSData alloc] initWithBytes:blob length:blobSize]; } else if (status == SQLITE_ERROR) { YDBLogError(@"Error executing 'getDataForKeyStatement': %d %s, key(%@)", status, sqlite3_errmsg(connection->db), key); } sqlite3_clear_bindings(statement); sqlite3_reset(statement); FreeYapDatabaseString(&_collection); FreeYapDatabaseString(&_key); return result; } /** * Primitive access. * This method is available in-case you have a need to fetch the raw serialized forms from the database. * * This method is slower than getObject:metadata:forKey:inCollection:, since that method makes use of the caches. * In contrast, this method always fetches the raw data from disk. * * @see getObject:metadata:forKey:inCollection: **/ - (BOOL)getSerializedObject:(NSData **)serializedObjectPtr serializedMetadata:(NSData **)serializedMetadataPtr forKey:(NSString *)key inCollection:(NSString *)collection { if (key == nil) { if (serializedObjectPtr) *serializedObjectPtr = nil; if (serializedMetadataPtr) *serializedMetadataPtr = nil; return NO; } if (collection == nil) collection = @""; sqlite3_stmt *statement = [connection getAllForKeyStatement]; if (statement == NULL) { if (serializedObjectPtr) *serializedObjectPtr = nil; if (serializedMetadataPtr) *serializedMetadataPtr = nil; return NO; } NSData *serializedObject = nil; NSData *serializedMetadata = nil; BOOL found = NO; // SELECT "data", "metadata" FROM "database2" WHERE "collection" = ? AND "key" = ? ; int const column_idx_data = SQLITE_COLUMN_START + 0; int const column_idx_metadata = SQLITE_COLUMN_START + 1; int const bind_idx_collection = SQLITE_BIND_START + 0; int const bind_idx_key = SQLITE_BIND_START + 1; YapDatabaseString _collection; MakeYapDatabaseString(&_collection, collection); sqlite3_bind_text(statement, bind_idx_collection, _collection.str, _collection.length, SQLITE_STATIC); YapDatabaseString _key; MakeYapDatabaseString(&_key, key); sqlite3_bind_text(statement, bind_idx_key, _key.str, _key.length, SQLITE_STATIC); int status = sqlite3_step(statement); if (status == SQLITE_ROW) { if (connection->needsMarkSqlLevelSharedReadLock) [connection markSqlLevelSharedReadLockAcquired]; const void *oBlob = sqlite3_column_blob(statement, column_idx_data); int oBlobSize = sqlite3_column_bytes(statement, column_idx_data); const void *mBlob = sqlite3_column_blob(statement, column_idx_metadata); int mBlobSize = sqlite3_column_bytes(statement, column_idx_metadata); if (serializedObjectPtr) { serializedObject = [NSData dataWithBytes:(void *)oBlob length:oBlobSize]; } if (serializedMetadataPtr) { serializedMetadata = [NSData dataWithBytes:(void *)mBlob length:mBlobSize]; } found = YES; } else if (status == SQLITE_ERROR) { YDBLogError(@"Error executing 'getAllForKeyStatement': %d %s", status, sqlite3_errmsg(connection->db)); } sqlite3_clear_bindings(statement); sqlite3_reset(statement); FreeYapDatabaseString(&_collection); FreeYapDatabaseString(&_key); if (serializedObjectPtr) *serializedObjectPtr = serializedObject; if (serializedMetadataPtr) *serializedMetadataPtr = serializedMetadata; return found; } //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// #pragma mark Enumerate //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// /** * Fast enumeration over all the collections in the database. * * This uses a "SELECT collection FROM database" operation, * and then steps over the results invoking the given block handler. **/ - (void)enumerateCollectionsUsingBlock:(void (^)(NSString *collection, BOOL *stop))block { if (block == NULL) return; sqlite3_stmt *statement = [connection enumerateCollectionsStatement]; if (statement == NULL) return; isMutated = NO; // mutation during enumeration protection BOOL stop = NO; // SELECT DISTINCT "collection" FROM "database2"; int const column_idx_collection = SQLITE_COLUMN_START; int status = sqlite3_step(statement); if (status == SQLITE_ROW) { if (connection->needsMarkSqlLevelSharedReadLock) [connection markSqlLevelSharedReadLockAcquired]; do { const unsigned char *text = sqlite3_column_text(statement, column_idx_collection); int textSize = sqlite3_column_bytes(statement, column_idx_collection); NSString *collection = [[NSString alloc] initWithBytes:text length:textSize encoding:NSUTF8StringEncoding]; block(collection, &stop); if (stop || isMutated) break; } while ((status = sqlite3_step(statement)) == SQLITE_ROW); } if ((status != SQLITE_DONE) && !stop && !isMutated) { YDBLogError(@"%@ - sqlite_step error: %d %s", THIS_METHOD, status, sqlite3_errmsg(connection->db)); } sqlite3_reset(statement); if (isMutated && !stop) { @throw [self mutationDuringEnumerationException]; } } /** * This method is rarely needed, but may be helpful in certain situations. * * This method may be used if you have the key, but not the collection for a particular item. * Please note that this is not the ideal situation. * * Since there may be numerous collections for a given key, this method enumerates all possible collections. **/ - (void)enumerateCollectionsForKey:(NSString *)key usingBlock:(void (^)(NSString *collection, BOOL *stop))block { if (key == nil) return; if (block == NULL) return; sqlite3_stmt *statement = [connection enumerateCollectionsForKeyStatement]; if (statement == NULL) return; isMutated = NO; // mutation during enumeration protection BOOL stop = NO; // SELECT "collection" FROM "database2" WHERE "key" = ?; int const column_idx_collection = SQLITE_COLUMN_START; int const bind_idx_key = SQLITE_BIND_START; YapDatabaseString _key; MakeYapDatabaseString(&_key, key); sqlite3_bind_text(statement, bind_idx_key, _key.str, _key.length, SQLITE_STATIC); int status = sqlite3_step(statement); if (status == SQLITE_ROW) { if (connection->needsMarkSqlLevelSharedReadLock) [connection markSqlLevelSharedReadLockAcquired]; do { const unsigned char *text = sqlite3_column_text(statement, column_idx_collection); int textSize = sqlite3_column_bytes(statement, column_idx_collection); NSString *collection = [[NSString alloc] initWithBytes:text length:textSize encoding:NSUTF8StringEncoding]; block(collection, &stop); if (stop || isMutated) break; } while ((status = sqlite3_step(statement)) == SQLITE_ROW); } if ((status != SQLITE_DONE) && !stop && !isMutated) { YDBLogError(@"%@ - sqlite_step error: %d %s", THIS_METHOD, status, sqlite3_errmsg(connection->db)); } sqlite3_clear_bindings(statement); sqlite3_reset(statement); FreeYapDatabaseString(&_key); if (isMutated && !stop) { @throw [self mutationDuringEnumerationException]; } } /** * Fast enumeration over all keys in the given collection. * * This uses a "SELECT key FROM database WHERE collection = ?" operation, * and then steps over the results invoking the given block handler. **/ - (void)enumerateKeysInCollection:(NSString *)collection usingBlock:(void (^)(NSString *key, BOOL *stop))block { if (block == NULL) return; [self _enumerateKeysInCollection:collection usingBlock:^(int64_t __unused rowid, NSString *key, BOOL *stop) { block(key, stop); }]; } /** * Fast enumeration over all keys in the given collection. * * This uses a "SELECT collection, key FROM database" operation, * and then steps over the results invoking the given block handler. **/ - (void)enumerateKeysInAllCollectionsUsingBlock:(void (^)(NSString *collection, NSString *key, BOOL *stop))block { if (block == NULL) return; [self _enumerateKeysInAllCollectionsUsingBlock:^(int64_t __unused rowid, NSString *collection, NSString *key, BOOL *stop) { block(collection, key, stop); }]; } /** * Fast enumeration over all keys and associated metadata in the given collection. * * This uses a "SELECT key, metadata FROM database WHERE collection = ?" operation and steps over the results. * * If you only need to enumerate over certain items (e.g. keys with a particular prefix), * consider using the alternative version below which provides a filter, * allowing you to skip the deserialization step for those items you're not interested in. * * Keep in mind that you cannot modify the collection mid-enumeration (just like any other kind of enumeration). **/ - (void)enumerateKeysAndMetadataInCollection:(NSString *)collection usingBlock:(void (^)(NSString *key, id metadata, BOOL *stop))block { [self enumerateKeysAndMetadataInCollection:collection usingBlock:block withFilter:NULL]; } /** * Fast enumeration over all keys and associated metadata in the given collection. * * From the filter block, simply return YES if you'd like the block handler to be invoked for the given key. * If the filter block returns NO, then the block handler is skipped for the given key, * which avoids the cost associated with deserializing the object. * * Keep in mind that you cannot modify the collection mid-enumeration (just like any other kind of enumeration). **/ - (void)enumerateKeysAndMetadataInCollection:(NSString *)collection usingBlock:(void (^)(NSString *key, id metadata, BOOL *stop))block withFilter:(BOOL (^)(NSString *key))filter { if (block == NULL) return; if (filter) { [self _enumerateKeysAndMetadataInCollection:collection usingBlock:^(int64_t __unused rowid, NSString *key, id metadata, BOOL *stop) { block(key, metadata, stop); } withFilter:^BOOL(int64_t __unused rowid, NSString *key) { return filter(key); }]; } else { [self _enumerateKeysAndMetadataInCollection:collection usingBlock:^(int64_t __unused rowid, NSString *key, id metadata, BOOL *stop) { block(key, metadata, stop); } withFilter:NULL]; } } /** * Fast enumeration over all key/metadata pairs in all collections. * * This uses a "SELECT metadata FROM database ORDER BY collection ASC" operation, and steps over the results. * * If you only need to enumerate over certain objects (e.g. keys with a particular prefix), * consider using the alternative version below which provides a filter, * allowing you to skip the deserialization step for those objects you're not interested in. * * Keep in mind that you cannot modify the database mid-enumeration (just like any other kind of enumeration). **/ - (void)enumerateKeysAndMetadataInAllCollectionsUsingBlock: (void (^)(NSString *collection, NSString *key, id metadata, BOOL *stop))block { [self enumerateKeysAndMetadataInAllCollectionsUsingBlock:block withFilter:NULL]; } /** * Fast enumeration over all key/metadata pairs in all collections. * * This uses a "SELECT metadata FROM database ORDER BY collection ASC" operation and steps over the results. * * From the filter block, simply return YES if you'd like the block handler to be invoked for the given key. * If the filter block returns NO, then the block handler is skipped for the given key, * which avoids the cost associated with deserializing the object. * * Keep in mind that you cannot modify the database mid-enumeration (just like any other kind of enumeration). **/ - (void)enumerateKeysAndMetadataInAllCollectionsUsingBlock: (void (^)(NSString *collection, NSString *key, id metadata, BOOL *stop))block withFilter:(BOOL (^)(NSString *collection, NSString *key))filter { if (block == NULL) return; if (filter) { [self _enumerateKeysAndMetadataInAllCollectionsUsingBlock: ^(int64_t __unused rowid, NSString *collection, NSString *key, id metadata, BOOL *stop) { block(collection, key, metadata, stop); } withFilter:^BOOL(int64_t __unused rowid, NSString *collection, NSString *key) { return filter(collection, key); }]; } else { [self _enumerateKeysAndMetadataInAllCollectionsUsingBlock: ^(int64_t __unused rowid, NSString *collection, NSString *key, id metadata, BOOL *stop) { block(collection, key, metadata, stop); } withFilter:NULL]; } } /** * Fast enumeration over all objects in the database. * * This uses a "SELECT key, object from database WHERE collection = ?" operation, and then steps over the results, * deserializing each object, and then invoking the given block handler. * * If you only need to enumerate over certain objects (e.g. keys with a particular prefix), * consider using the alternative version below which provides a filter, * allowing you to skip the serialization step for those objects you're not interested in. **/ - (void)enumerateKeysAndObjectsInCollection:(NSString *)collection usingBlock:(void (^)(NSString *key, id object, BOOL *stop))block { [self enumerateKeysAndObjectsInCollection:collection usingBlock:block withFilter:NULL]; } /** * Fast enumeration over objects in the database for which you're interested in. * The filter block allows you to decide which objects you're interested in. * * From the filter block, simply return YES if you'd like the block handler to be invoked for the given key. * If the filter block returns NO, then the block handler is skipped for the given key, * which avoids the cost associated with deserializing the object. **/ - (void)enumerateKeysAndObjectsInCollection:(NSString *)collection usingBlock:(void (^)(NSString *key, id object, BOOL *stop))block withFilter:(BOOL (^)(NSString *key))filter { if (block == NULL) return; if (filter) { [self _enumerateKeysAndObjectsInCollection:collection usingBlock:^(int64_t __unused rowid, NSString *key, id object, BOOL *stop) { block(key, object, stop); } withFilter:^BOOL(int64_t __unused rowid, NSString *key) { return filter(key); }]; } else { [self _enumerateKeysAndObjectsInCollection:collection usingBlock:^(int64_t __unused rowid, NSString *key, id object, BOOL *stop) { block(key, object, stop); } withFilter:NULL]; } } /** * Enumerates all key/object pairs in all collections. * * The enumeration is sorted by collection. That is, it will enumerate fully over a single collection * before moving onto another collection. * * If you only need to enumerate over certain objects (e.g. subset of collections, or keys with a particular prefix), * consider using the alternative version below which provides a filter, * allowing you to skip the serialization step for those objects you're not interested in. **/ - (void)enumerateKeysAndObjectsInAllCollectionsUsingBlock: (void (^)(NSString *collection, NSString *key, id object, BOOL *stop))block { [self enumerateKeysAndObjectsInAllCollectionsUsingBlock:block withFilter:NULL]; } /** * Enumerates all key/object pairs in all collections. * The filter block allows you to decide which objects you're interested in. * * The enumeration is sorted by collection. That is, it will enumerate fully over a single collection * before moving onto another collection. * * From the filter block, simply return YES if you'd like the block handler to be invoked for the given * collection/key pair. If the filter block returns NO, then the block handler is skipped for the given pair, * which avoids the cost associated with deserializing the object. **/ - (void)enumerateKeysAndObjectsInAllCollectionsUsingBlock: (void (^)(NSString *collection, NSString *key, id object, BOOL *stop))block withFilter:(BOOL (^)(NSString *collection, NSString *key))filter { if (block == NULL) return; if (filter) { [self _enumerateKeysAndObjectsInAllCollectionsUsingBlock: ^(int64_t __unused rowid, NSString *collection, NSString *key, id object, BOOL *stop) { block(collection, key, object, stop); } withFilter:^BOOL(int64_t __unused rowid, NSString *collection, NSString *key) { return filter(collection, key); }]; } else { [self _enumerateKeysAndObjectsInAllCollectionsUsingBlock: ^(int64_t __unused rowid, NSString *collection, NSString *key, id object, BOOL *stop) { block(collection, key, object, stop); } withFilter:NULL]; } } /** * Fast enumeration over all rows in the database. * * This uses a "SELECT key, data, metadata from database WHERE collection = ?" operation, * and then steps over the results, deserializing each object & metadata, and then invoking the given block handler. * * If you only need to enumerate over certain rows (e.g. keys with a particular prefix), * consider using the alternative version below which provides a filter, * allowing you to skip the serialization step for those rows you're not interested in. **/ - (void)enumerateRowsInCollection:(NSString *)collection usingBlock:(void (^)(NSString *key, id object, id metadata, BOOL *stop))block { [self enumerateRowsInCollection:collection usingBlock:block withFilter:NULL]; } /** * Fast enumeration over rows in the database for which you're interested in. * The filter block allows you to decide which rows you're interested in. * * From the filter block, simply return YES if you'd like the block handler to be invoked for the given key. * If the filter block returns NO, then the block handler is skipped for the given key, * which avoids the cost associated with deserializing the object & metadata. **/ - (void)enumerateRowsInCollection:(NSString *)collection usingBlock:(void (^)(NSString *key, id object, id metadata, BOOL *stop))block withFilter:(BOOL (^)(NSString *key))filter { if (block == NULL) return; if (filter) { [self _enumerateRowsInCollection:collection usingBlock:^(int64_t __unused rowid, NSString *key, id object, id metadata, BOOL *stop) { block(key, object, metadata, stop); } withFilter:^BOOL(int64_t __unused rowid, NSString *key) { return filter(key); }]; } else { [self _enumerateRowsInCollection:collection usingBlock:^(int64_t __unused rowid, NSString *key, id object, id metadata, BOOL *stop) { block(key, object, metadata, stop); } withFilter:NULL]; } } /** * Enumerates all rows in all collections. * * The enumeration is sorted by collection. That is, it will enumerate fully over a single collection * before moving onto another collection. * * If you only need to enumerate over certain rows (e.g. subset of collections, or keys with a particular prefix), * consider using the alternative version below which provides a filter, * allowing you to skip the serialization step for those objects you're not interested in. **/ - (void)enumerateRowsInAllCollectionsUsingBlock: (void (^)(NSString *collection, NSString *key, id object, id metadata, BOOL *stop))block { [self enumerateRowsInAllCollectionsUsingBlock:block withFilter:NULL]; } /** * Enumerates all rows in all collections. * The filter block allows you to decide which objects you're interested in. * * The enumeration is sorted by collection. That is, it will enumerate fully over a single collection * before moving onto another collection. * * From the filter block, simply return YES if you'd like the block handler to be invoked for the given * collection/key pair. If the filter block returns NO, then the block handler is skipped for the given pair, * which avoids the cost associated with deserializing the object. **/ - (void)enumerateRowsInAllCollectionsUsingBlock: (void (^)(NSString *collection, NSString *key, id object, id metadata, BOOL *stop))block withFilter:(BOOL (^)(NSString *collection, NSString *key))filter { if (block == NULL) return; if (filter) { [self _enumerateRowsInAllCollectionsUsingBlock: ^(int64_t __unused rowid, NSString *collection, NSString *key, id object, id metadata, BOOL *stop) { block(collection, key, object, metadata, stop); } withFilter:^BOOL(int64_t __unused rowid, NSString *collection, NSString *key) { return filter(collection, key); }]; } else { [self _enumerateRowsInAllCollectionsUsingBlock: ^(int64_t __unused rowid, NSString *collection, NSString *key, id object, id metadata, BOOL *stop) { block(collection, key, object, metadata, stop); } withFilter:NULL]; } } /** * Enumerates over the given list of keys (unordered). * * This method is faster than fetching individual items as it optimizes cache access. * That is, it will first enumerate over items in the cache and then fetch items from the database, * thus optimizing the cache and reducing query size. * * If any keys are missing from the database, the 'metadata' parameter will be nil. * * IMPORTANT: * Due to cache optimizations, the items may not be enumerated in the same order as the 'keys' parameter. **/ - (void)enumerateMetadataForKeys:(NSArray *)keys inCollection:(NSString *)collection unorderedUsingBlock:(void (^)(NSUInteger keyIndex, id metadata, BOOL *stop))block { if (block == NULL) return; if ([keys count] == 0) return; if (collection == nil) collection = @""; isMutated = NO; // mutation during enumeration protection BOOL stop = NO; // Check the cache first (to optimize cache) NSMutableArray *missingIndexes = [NSMutableArray arrayWithCapacity:[keys count]]; NSUInteger keyIndex = 0; for (NSString *key in keys) { YapCollectionKey *cacheKey = [[YapCollectionKey alloc] initWithCollection:collection key:key]; id metadata = [connection->metadataCache objectForKey:cacheKey]; if (metadata) { if (metadata == [YapNull null]) block(keyIndex, nil, &stop); else block(keyIndex, metadata, &stop); if (stop || isMutated) break; } else { [missingIndexes addObject:@(keyIndex)]; } keyIndex++; } if (stop) { return; } if (isMutated) { @throw [self mutationDuringEnumerationException]; return; } if ([missingIndexes count] == 0) { return; } // Go to database for any missing keys (if needed) // Sqlite has an upper bound on the number of host parameters that may be used in a single query. // We need to watch out for this in case a large array of keys is passed. NSUInteger maxHostParams = (NSUInteger) sqlite3_limit(connection->db, SQLITE_LIMIT_VARIABLE_NUMBER, -1); YapDatabaseString _collection; MakeYapDatabaseString(&_collection, collection); do { // Determine how many parameters to use in the query NSUInteger numKeyParams = MIN([missingIndexes count], (maxHostParams-1)); // minus 1 for collection param // Create the SQL query: // // SELECT "key", "metadata" FROM "database2" WHERE "collection" = ? AND key IN (?, ?, ...); int const column_idx_key = SQLITE_COLUMN_START + 0; int const column_idx_metadata = SQLITE_COLUMN_START + 1; NSUInteger capacity = 80 + (numKeyParams * 3); NSMutableString *query = [NSMutableString stringWithCapacity:capacity]; [query appendString:@"SELECT \"key\", \"metadata\" FROM \"database2\""]; [query appendString:@" WHERE \"collection\" = ? AND \"key\" IN ("]; NSUInteger i; for (i = 0; i < numKeyParams; i++) { if (i == 0) [query appendString:@"?"]; else [query appendString:@", ?"]; } [query appendString:@");"]; sqlite3_stmt *statement; int status = sqlite3_prepare_v2(connection->db, [query UTF8String], -1, &statement, NULL); if (status != SQLITE_OK) { YDBLogError(@"Error creating 'metadataForKeys' statement: %d %s", status, sqlite3_errmsg(connection->db)); break; // Break from do/while. Still need to free _collection. } // Bind parameters. // And move objects from the missingIndexes array into keyIndexDict. NSMutableDictionary *keyIndexDict = [NSMutableDictionary dictionaryWithCapacity:numKeyParams]; sqlite3_bind_text(statement, SQLITE_BIND_START, _collection.str, _collection.length, SQLITE_STATIC); for (i = 0; i < numKeyParams; i++) { NSNumber *keyIndexNumber = [missingIndexes objectAtIndex:i]; NSString *key = [keys objectAtIndex:[keyIndexNumber unsignedIntegerValue]]; [keyIndexDict setObject:keyIndexNumber forKey:key]; sqlite3_bind_text(statement, (int)(SQLITE_BIND_START + 1 + i), [key UTF8String], -1, SQLITE_TRANSIENT); } [missingIndexes removeObjectsInRange:NSMakeRange(0, numKeyParams)]; // Execute the query and step over the results status = sqlite3_step(statement); if (status == SQLITE_ROW) { if (connection->needsMarkSqlLevelSharedReadLock) [connection markSqlLevelSharedReadLockAcquired]; do { const unsigned char *text = sqlite3_column_text(statement, column_idx_key); int textSize = sqlite3_column_bytes(statement, column_idx_key); const void *blob = sqlite3_column_blob(statement, column_idx_metadata); int blobSize = sqlite3_column_bytes(statement, column_idx_metadata); NSString *key = [[NSString alloc] initWithBytes:text length:textSize encoding:NSUTF8StringEncoding]; keyIndex = [[keyIndexDict objectForKey:key] unsignedIntegerValue]; NSData *data = [NSData dataWithBytesNoCopy:(void *)blob length:blobSize freeWhenDone:NO]; id metadata = data ? connection->database->metadataDeserializer(collection, key, data) : nil; if (metadata) { YapCollectionKey *cacheKey = [[YapCollectionKey alloc] initWithCollection:collection key:key]; [connection->metadataCache setObject:metadata forKey:cacheKey]; } block(keyIndex, metadata, &stop); [keyIndexDict removeObjectForKey:key]; if (stop || isMutated) break; } while ((status = sqlite3_step(statement)) == SQLITE_ROW); } if ((status != SQLITE_DONE) && !stop && !isMutated) { YDBLogError(@"%@ - sqlite_step error: %d %s", THIS_METHOD, status, sqlite3_errmsg(connection->db)); } sqlite3_finalize(statement); statement = NULL; if (stop) { FreeYapDatabaseString(&_collection); return; } if (isMutated) { FreeYapDatabaseString(&_collection); @throw [self mutationDuringEnumerationException]; return; } // If there are any remaining items in the keyIndexDict, // then those items didn't exist in the database. for (NSNumber *keyIndexNumber in [keyIndexDict objectEnumerator]) { block([keyIndexNumber unsignedIntegerValue], nil, &stop); // Do NOT add keys to the cache that don't exist in the database. if (stop || isMutated) break; } if (stop) { FreeYapDatabaseString(&_collection); return; } if (isMutated) { FreeYapDatabaseString(&_collection); @throw [self mutationDuringEnumerationException]; return; } } while ([missingIndexes count] > 0); FreeYapDatabaseString(&_collection); } /** * Enumerates over the given list of keys (unordered). * * This method is faster than fetching individual items as it optimizes cache access. * That is, it will first enumerate over items in the cache and then fetch items from the database, * thus optimizing the cache and reducing query size. * * If any keys are missing from the database, the 'object' parameter will be nil. * * IMPORTANT: * Due to cache optimizations, the items may not be enumerated in the same order as the 'keys' parameter. **/ - (void)enumerateObjectsForKeys:(NSArray *)keys inCollection:(NSString *)collection unorderedUsingBlock:(void (^)(NSUInteger keyIndex, id object, BOOL *stop))block { if (block == NULL) return; if ([keys count] == 0) return; if (collection == nil) collection = @""; isMutated = NO; // mutation during enumeration protection BOOL stop = NO; // Check the cache first (to optimize cache) NSMutableArray *missingIndexes = [NSMutableArray arrayWithCapacity:[keys count]]; NSUInteger keyIndex = 0; for (NSString *key in keys) { YapCollectionKey *cacheKey = [[YapCollectionKey alloc] initWithCollection:collection key:key]; id object = [connection->objectCache objectForKey:cacheKey]; if (object) { block(keyIndex, object, &stop); if (stop || isMutated) break; } else { [missingIndexes addObject:@(keyIndex)]; } keyIndex++; } if (stop) { return; } if (isMutated) { @throw [self mutationDuringEnumerationException]; return; } if ([missingIndexes count] == 0) { return; } // Go to database for any missing keys (if needed) // Sqlite has an upper bound on the number of host parameters that may be used in a single query. // We need to watch out for this in case a large array of keys is passed. NSUInteger maxHostParams = (NSUInteger) sqlite3_limit(connection->db, SQLITE_LIMIT_VARIABLE_NUMBER, -1); YapDatabaseString _collection; MakeYapDatabaseString(&_collection, collection); do { // Determine how many parameters to use in the query NSUInteger numKeyParams = MIN([missingIndexes count], (maxHostParams-1)); // minus 1 for collection param // Create the SQL query: // // SELECT "key", "data" FROM "database2" WHERE "collection" = ? AND key IN (?, ?, ...); int const column_idx_key = SQLITE_COLUMN_START + 0; int const column_idx_data = SQLITE_COLUMN_START + 1; NSUInteger capacity = 80 + (numKeyParams * 3); NSMutableString *query = [NSMutableString stringWithCapacity:capacity]; [query appendString:@"SELECT \"key\", \"data\" FROM \"database2\""]; [query appendString:@" WHERE \"collection\" = ? AND \"key\" IN ("]; NSUInteger i; for (i = 0; i < numKeyParams; i++) { if (i == 0) [query appendString:@"?"]; else [query appendString:@", ?"]; } [query appendString:@");"]; sqlite3_stmt *statement; int status = sqlite3_prepare_v2(connection->db, [query UTF8String], -1, &statement, NULL); if (status != SQLITE_OK) { YDBLogError(@"Error creating 'objectsForKeys' statement: %d %s", status, sqlite3_errmsg(connection->db)); break; // Break from do/while. Still need to free _collection. } // Bind parameters. // And move objects from the missingIndexes array into keyIndexDict. NSMutableDictionary *keyIndexDict = [NSMutableDictionary dictionaryWithCapacity:numKeyParams]; sqlite3_bind_text(statement, SQLITE_BIND_START, _collection.str, _collection.length, SQLITE_STATIC); for (i = 0; i < numKeyParams; i++) { NSNumber *keyIndexNumber = [missingIndexes objectAtIndex:i]; NSString *key = [keys objectAtIndex:[keyIndexNumber unsignedIntegerValue]]; [keyIndexDict setObject:keyIndexNumber forKey:key]; sqlite3_bind_text(statement, (int)(SQLITE_BIND_START + 1 + i), [key UTF8String], -1, SQLITE_TRANSIENT); } [missingIndexes removeObjectsInRange:NSMakeRange(0, numKeyParams)]; // Execute the query and step over the results status = sqlite3_step(statement); if (status == SQLITE_ROW) { if (connection->needsMarkSqlLevelSharedReadLock) [connection markSqlLevelSharedReadLockAcquired]; do { const unsigned char *text = sqlite3_column_text(statement, column_idx_key); int textSize = sqlite3_column_bytes(statement, column_idx_key); NSString *key = [[NSString alloc] initWithBytes:text length:textSize encoding:NSUTF8StringEncoding]; keyIndex = [[keyIndexDict objectForKey:key] unsignedIntegerValue]; // Note: We already checked the cache (above), // so we already know this item is not in the cache. const void *blob = sqlite3_column_blob(statement, column_idx_data); int blobSize = sqlite3_column_bytes(statement, column_idx_data); NSData *objectData = [NSData dataWithBytesNoCopy:(void *)blob length:blobSize freeWhenDone:NO]; id object = connection->database->objectDeserializer(collection, key, objectData); if (object) { YapCollectionKey *cacheKey = [[YapCollectionKey alloc] initWithCollection:collection key:key]; [connection->objectCache setObject:object forKey:cacheKey]; } block(keyIndex, object, &stop); [keyIndexDict removeObjectForKey:key]; if (stop || isMutated) break; } while ((status = sqlite3_step(statement)) == SQLITE_ROW); } if ((status != SQLITE_DONE) && !stop && !isMutated) { YDBLogError(@"%@ - sqlite_step error: %d %s", THIS_METHOD, status, sqlite3_errmsg(connection->db)); } sqlite3_finalize(statement); statement = NULL; if (stop) { FreeYapDatabaseString(&_collection); return; } if (isMutated) { FreeYapDatabaseString(&_collection); @throw [self mutationDuringEnumerationException]; return; } // If there are any remaining items in the keyIndexDict, // then those items didn't exist in the database. for (NSNumber *keyIndexNumber in [keyIndexDict objectEnumerator]) { block([keyIndexNumber unsignedIntegerValue], nil, &stop); // Do NOT add keys to the cache that don't exist in the database. if (stop || isMutated) break; } if (stop) { FreeYapDatabaseString(&_collection); return; } if (isMutated) { FreeYapDatabaseString(&_collection); @throw [self mutationDuringEnumerationException]; return; } } while ([missingIndexes count] > 0); FreeYapDatabaseString(&_collection); } /** * Enumerates over the given list of keys (unordered). * * This method is faster than fetching individual items as it optimizes cache access. * That is, it will first enumerate over items in the cache and then fetch items from the database, * thus optimizing the cache and reducing query size. * * If any keys are missing from the database, the 'object' parameter will be nil. * * IMPORTANT: * Due to cache optimizations, the items may not be enumerated in the same order as the 'keys' parameter. **/ - (void)enumerateRowsForKeys:(NSArray *)keys inCollection:(NSString *)collection unorderedUsingBlock:(void (^)(NSUInteger keyIndex, id object, id metadata, BOOL *stop))block { if (block == NULL) return; if ([keys count] == 0) return; if (collection == nil) collection = @""; isMutated = NO; // mutation during enumeration protection __block BOOL stop = NO; // Check the cache first (to optimize cache) NSMutableArray *missingIndexes = [NSMutableArray arrayWithCapacity:[keys count]]; NSUInteger keyIndex = 0; for (NSString *key in keys) { YapCollectionKey *cacheKey = [[YapCollectionKey alloc] initWithCollection:collection key:key]; id object = [connection->objectCache objectForKey:cacheKey]; if (object) { id metadata = [connection->metadataCache objectForKey:cacheKey]; if (metadata) { if (metadata == [YapNull null]) block(keyIndex, object, nil, &stop); else block(keyIndex, object, metadata, &stop); if (stop || isMutated) break; } else { [missingIndexes addObject:@(keyIndex)]; } } else { [missingIndexes addObject:@(keyIndex)]; } keyIndex++; } if (stop) { return; } if (isMutated) { @throw [self mutationDuringEnumerationException]; return; } if ([missingIndexes count] == 0) { return; } // Go to database for any missing keys (if needed) // Sqlite has an upper bound on the number of host parameters that may be used in a single query. // We need to watch out for this in case a large array of keys is passed. NSUInteger maxHostParams = (NSUInteger) sqlite3_limit(connection->db, SQLITE_LIMIT_VARIABLE_NUMBER, -1); YapDatabaseString _collection; MakeYapDatabaseString(&_collection, collection); do { // Determine how many parameters to use in the query NSUInteger numKeyParams = MIN([missingIndexes count], (maxHostParams-1)); // minus 1 for collection param // Create the SQL query: // // SELECT "key", "data", "metadata" FROM "database2" WHERE "collection" = ? AND key IN (?, ?, ...); int const column_idx_key = SQLITE_COLUMN_START + 0; int const column_idx_data = SQLITE_COLUMN_START + 1; int const column_idx_metadata = SQLITE_COLUMN_START + 2; NSUInteger capacity = 80 + (numKeyParams * 3); NSMutableString *query = [NSMutableString stringWithCapacity:capacity]; [query appendString:@"SELECT \"key\", \"data\", \"metadata\" FROM \"database2\""]; [query appendString:@" WHERE \"collection\" = ? AND \"key\" IN ("]; NSUInteger i; for (i = 0; i < numKeyParams; i++) { if (i == 0) [query appendString:@"?"]; else [query appendString:@", ?"]; } [query appendString:@");"]; sqlite3_stmt *statement; int status = sqlite3_prepare_v2(connection->db, [query UTF8String], -1, &statement, NULL); if (status != SQLITE_OK) { YDBLogError(@"Error creating 'objectsAndMetadataForKeys' statement: %d %s", status, sqlite3_errmsg(connection->db)); break; // Break from do/while. Still need to free _collection. } // Bind parameters. // And move objects from the missingIndexes array into keyIndexDict. NSMutableDictionary *keyIndexDict = [NSMutableDictionary dictionaryWithCapacity:numKeyParams]; sqlite3_bind_text(statement, SQLITE_BIND_START, _collection.str, _collection.length, SQLITE_STATIC); for (i = 0; i < numKeyParams; i++) { NSNumber *keyIndexNumber = [missingIndexes objectAtIndex:i]; NSString *key = [keys objectAtIndex:[keyIndexNumber unsignedIntegerValue]]; [keyIndexDict setObject:keyIndexNumber forKey:key]; sqlite3_bind_text(statement, (int)(SQLITE_BIND_START + 1 + i), [key UTF8String], -1, SQLITE_TRANSIENT); } [missingIndexes removeObjectsInRange:NSMakeRange(0, numKeyParams)]; // Execute the query and step over the results status = sqlite3_step(statement); if (status == SQLITE_ROW) { if (connection->needsMarkSqlLevelSharedReadLock) [connection markSqlLevelSharedReadLockAcquired]; do { const unsigned char *text = sqlite3_column_text(statement, column_idx_key); int textSize = sqlite3_column_bytes(statement, column_idx_key); NSString *key = [[NSString alloc] initWithBytes:text length:textSize encoding:NSUTF8StringEncoding]; keyIndex = [[keyIndexDict objectForKey:key] unsignedIntegerValue]; // Note: When we checked the caches (above), // we could only process the item if the object & metadata were both cached. // So it's worthwhile to check each individual cache here. YapCollectionKey *cacheKey = [[YapCollectionKey alloc] initWithCollection:collection key:key]; id object = [connection->objectCache objectForKey:cacheKey]; if (object == nil) { const void *oBlob = sqlite3_column_blob(statement, column_idx_data); int oBlobSize = sqlite3_column_bytes(statement, column_idx_data); NSData *oData = [NSData dataWithBytesNoCopy:(void *)oBlob length:oBlobSize freeWhenDone:NO]; object = connection->database->objectDeserializer(collection, key, oData); if (object) [connection->objectCache setObject:object forKey:cacheKey]; } id metadata = [connection->metadataCache objectForKey:cacheKey]; if (metadata) { if (metadata == [YapNull null]) metadata = nil; } else { const void *mBlob = sqlite3_column_blob(statement, column_idx_metadata); int mBlobSize = sqlite3_column_bytes(statement, column_idx_metadata); if (mBlobSize > 0) { NSData *mData = [NSData dataWithBytesNoCopy:(void *)mBlob length:mBlobSize freeWhenDone:NO]; metadata = connection->database->metadataDeserializer(collection, key, mData); } if (metadata) [connection->metadataCache setObject:metadata forKey:cacheKey]; else [connection->metadataCache setObject:[YapNull null] forKey:cacheKey]; } block(keyIndex, object, metadata, &stop); [keyIndexDict removeObjectForKey:key]; if (stop || isMutated) break; } while ((status = sqlite3_step(statement)) == SQLITE_ROW); } if ((status != SQLITE_DONE) && !stop && !isMutated) { YDBLogError(@"%@ - sqlite_step error: %d %s", THIS_METHOD, status, sqlite3_errmsg(connection->db)); } sqlite3_finalize(statement); statement = NULL; if (stop) { FreeYapDatabaseString(&_collection); return; } if (isMutated) { FreeYapDatabaseString(&_collection); @throw [self mutationDuringEnumerationException]; return; } // If there are any remaining items in the keyIndexDict, // then those items didn't exist in the database. for (NSNumber *keyIndexNumber in [keyIndexDict objectEnumerator]) { block([keyIndexNumber unsignedIntegerValue], nil, nil, &stop); // Do NOT add keys to the cache that don't exist in the database. if (stop || isMutated) break; } if (stop) { FreeYapDatabaseString(&_collection); return; } if (isMutated) { FreeYapDatabaseString(&_collection); @throw [self mutationDuringEnumerationException]; return; } } while ([missingIndexes count] > 0); FreeYapDatabaseString(&_collection); } //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// #pragma mark Internal Enumerate (using rowid) //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// /** * Fast enumeration over all keys in the given collection. * * This uses a "SELECT key FROM database WHERE collection = ?" operation, * and then steps over the results invoking the given block handler. **/ - (void)_enumerateKeysInCollection:(NSString *)collection usingBlock:(void (^)(int64_t rowid, NSString *key, BOOL *stop))block { if (block == NULL) return; if (collection == nil) collection = @""; sqlite3_stmt *statement = [connection enumerateKeysInCollectionStatement]; if (statement == NULL) return; isMutated = NO; // mutation during enumeration protection BOOL stop = NO; // SELECT "rowid", "key" FROM "database2" WHERE collection = ?; int const column_idx_rowid = SQLITE_COLUMN_START + 0; int const column_idx_key = SQLITE_COLUMN_START + 1; int const bind_idx_collection = SQLITE_BIND_START; YapDatabaseString _collection; MakeYapDatabaseString(&_collection, collection); sqlite3_bind_text(statement, bind_idx_collection, _collection.str, _collection.length, SQLITE_STATIC); int status = sqlite3_step(statement); if (status == SQLITE_ROW) { if (connection->needsMarkSqlLevelSharedReadLock) [connection markSqlLevelSharedReadLockAcquired]; do { int64_t rowid = sqlite3_column_int64(statement, column_idx_rowid); const unsigned char *text = sqlite3_column_text(statement, column_idx_key); int textSize = sqlite3_column_bytes(statement, column_idx_key); NSString *key = [[NSString alloc] initWithBytes:text length:textSize encoding:NSUTF8StringEncoding]; block(rowid, key, &stop); if (stop || isMutated) break; } while ((status = sqlite3_step(statement)) == SQLITE_ROW); } if ((status != SQLITE_DONE) && !stop && !isMutated) { YDBLogError(@"%@ - sqlite_step error: %d %s", THIS_METHOD, status, sqlite3_errmsg(connection->db)); } sqlite3_clear_bindings(statement); sqlite3_reset(statement); FreeYapDatabaseString(&_collection); if (isMutated && !stop) { @throw [self mutationDuringEnumerationException]; } } /** * Fast enumeration over all keys in select collections. * * This uses a "SELECT key FROM database WHERE collection = ?" operation, * and then steps over the results invoking the given block handler. **/ - (void)_enumerateKeysInCollections:(NSArray *)collections usingBlock:(void (^)(int64_t rowid, NSString *collection, NSString *key, BOOL *stop))block { if (block == NULL) return; if ([collections count] == 0) return; sqlite3_stmt *statement = [connection enumerateKeysInCollectionStatement]; if (statement == NULL) return; isMutated = NO; // mutation during enumeration protection BOOL stop = NO; // SELECT "rowid", "key" FROM "database2" WHERE collection = ?; int const column_idx_rowid = SQLITE_COLUMN_START + 0; int const column_idx_key = SQLITE_COLUMN_START + 1; int const bind_idx_collection = SQLITE_BIND_START; for (NSString *collection in collections) { YapDatabaseString _collection; MakeYapDatabaseString(&_collection, collection); sqlite3_bind_text(statement, bind_idx_collection, _collection.str, _collection.length, SQLITE_STATIC); int status = sqlite3_step(statement); if (status == SQLITE_ROW) { if (connection->needsMarkSqlLevelSharedReadLock) [connection markSqlLevelSharedReadLockAcquired]; do { int64_t rowid = sqlite3_column_int64(statement, column_idx_rowid); const unsigned char *text = sqlite3_column_text(statement, column_idx_key); int textSize = sqlite3_column_bytes(statement, column_idx_key); NSString *key = [[NSString alloc] initWithBytes:text length:textSize encoding:NSUTF8StringEncoding]; block(rowid, collection, key, &stop); if (stop || isMutated) break; } while ((status = sqlite3_step(statement)) == SQLITE_ROW); } if ((status != SQLITE_DONE) && !stop && !isMutated) { YDBLogError(@"%@ - sqlite_step error: %d %s", THIS_METHOD, status, sqlite3_errmsg(connection->db)); } sqlite3_clear_bindings(statement); sqlite3_reset(statement); FreeYapDatabaseString(&_collection); if (isMutated && !stop) { @throw [self mutationDuringEnumerationException]; } if (stop) { break; } } // end for (NSString *collection in collections) } /** * Fast enumeration over all keys in the given collection. * * This uses a "SELECT collection, key FROM database" operation, * and then steps over the results invoking the given block handler. **/ - (void)_enumerateKeysInAllCollectionsUsingBlock: (void (^)(int64_t rowid, NSString *collection, NSString *key, BOOL *stop))block { if (block == NULL) return; sqlite3_stmt *statement = [connection enumerateKeysInAllCollectionsStatement]; if (statement == NULL) return; isMutated = NO; // mutation during enumeration protection BOOL stop = NO; // SELECT "rowid", "collection", "key" FROM "database2"; int const column_idx_rowid = SQLITE_COLUMN_START + 0; int const column_idx_collection = SQLITE_COLUMN_START + 1; int const column_idx_key = SQLITE_COLUMN_START + 2; int status = sqlite3_step(statement); if (status == SQLITE_ROW) { if (connection->needsMarkSqlLevelSharedReadLock) [connection markSqlLevelSharedReadLockAcquired]; do { int64_t rowid = sqlite3_column_int64(statement, column_idx_rowid); const unsigned char *text1 = sqlite3_column_text(statement, column_idx_collection); int textSize1 = sqlite3_column_bytes(statement, column_idx_collection); const unsigned char *text2 = sqlite3_column_text(statement, column_idx_key); int textSize2 = sqlite3_column_bytes(statement, column_idx_key); NSString *collection, *key; collection = [[NSString alloc] initWithBytes:text1 length:textSize1 encoding:NSUTF8StringEncoding]; key = [[NSString alloc] initWithBytes:text2 length:textSize2 encoding:NSUTF8StringEncoding]; block(rowid, collection, key, &stop); if (stop || isMutated) break; } while ((status = sqlite3_step(statement)) == SQLITE_ROW); } if ((status != SQLITE_DONE) && !stop && !isMutated) { YDBLogError(@"%@ - sqlite_step error: %d %s", THIS_METHOD, status, sqlite3_errmsg(connection->db)); } sqlite3_reset(statement); if (isMutated && !stop) { @throw [self mutationDuringEnumerationException]; } } /** * Fast enumeration over all keys and associated metadata in the given collection. * * This uses a "SELECT key, metadata FROM database WHERE collection = ?" operation and steps over the results. * * If you only need to enumerate over certain items (e.g. keys with a particular prefix), * consider using the alternative version below which provides a filter, * allowing you to skip the deserialization step for those items you're not interested in. * * Keep in mind that you cannot modify the collection mid-enumeration (just like any other kind of enumeration). **/ - (void)_enumerateKeysAndMetadataInCollection:(NSString *)collection usingBlock:(void (^)(int64_t rowid, NSString *key, id metadata, BOOL *stop))block { [self _enumerateKeysAndMetadataInCollection:collection usingBlock:block withFilter:NULL]; } /** * Fast enumeration over all keys and associated metadata in the given collection. * * From the filter block, simply return YES if you'd like the block handler to be invoked for the given key. * If the filter block returns NO, then the block handler is skipped for the given key, * which avoids the cost associated with deserializing the object. * * Keep in mind that you cannot modify the collection mid-enumeration (just like any other kind of enumeration). **/ - (void)_enumerateKeysAndMetadataInCollection:(NSString *)collection usingBlock:(void (^)(int64_t rowid, NSString *key, id metadata, BOOL *stop))block withFilter:(BOOL (^)(int64_t rowid, NSString *key))filter { if (block == NULL) return; if (collection == nil) collection = @""; sqlite3_stmt *statement = [connection enumerateKeysAndMetadataInCollectionStatement]; if (statement == NULL) return; isMutated = NO; // mutation during enumeration protection BOOL stop = NO; // SELECT "rowid", "key", "metadata" FROM "database2" WHERE "collection" = ?; int const column_idx_rowid = SQLITE_COLUMN_START + 0; int const column_idx_key = SQLITE_COLUMN_START + 1; int const column_idx_metadata = SQLITE_COLUMN_START + 2; int const bind_idx_collection = SQLITE_BIND_START; YapDatabaseString _collection; MakeYapDatabaseString(&_collection, collection); sqlite3_bind_text(statement, bind_idx_collection, _collection.str, _collection.length, SQLITE_STATIC); BOOL unlimitedMetadataCacheLimit = (connection->metadataCacheLimit == 0); int status = sqlite3_step(statement); if (status == SQLITE_ROW) { if (connection->needsMarkSqlLevelSharedReadLock) [connection markSqlLevelSharedReadLockAcquired]; do { int64_t rowid = sqlite3_column_int64(statement, column_idx_rowid); const unsigned char *text = sqlite3_column_text(statement, column_idx_key); int textSize = sqlite3_column_bytes(statement, column_idx_key); NSString *key = [[NSString alloc] initWithBytes:text length:textSize encoding:NSUTF8StringEncoding]; BOOL invokeBlock = (filter == NULL) ? YES : filter(rowid, key); if (invokeBlock) { YapCollectionKey *cacheKey = [[YapCollectionKey alloc] initWithCollection:collection key:key]; id metadata = [connection->metadataCache objectForKey:cacheKey]; if (metadata) { if (metadata == [YapNull null]) metadata = nil; } else { const void *mBlob = sqlite3_column_blob(statement, column_idx_metadata); int mBlobSize = sqlite3_column_bytes(statement, column_idx_metadata); if (mBlobSize > 0) { // Performance tuning: // Use dataWithBytesNoCopy to avoid an extra allocation and memcpy. NSData *mData = [NSData dataWithBytesNoCopy:(void *)mBlob length:mBlobSize freeWhenDone:NO]; metadata = connection->database->metadataDeserializer(collection, key, mData); } // Cache considerations: // Do we want to add the objects/metadata to the cache here? // If the cache is unlimited then we should. // Otherwise we should only add to the cache if it's not full. // The cache should generally be reserved for items that are explicitly fetched, // and we don't want to crowd them out during enumerations. if (unlimitedMetadataCacheLimit || [connection->metadataCache count] < connection->metadataCacheLimit) { if (metadata) [connection->metadataCache setObject:metadata forKey:cacheKey]; else [connection->metadataCache setObject:[YapNull null] forKey:cacheKey]; } } block(rowid, key, metadata, &stop); if (stop || isMutated) break; } } while ((status = sqlite3_step(statement)) == SQLITE_ROW); } if ((status != SQLITE_DONE) && !stop && !isMutated) { YDBLogError(@"%@ - sqlite_step error: %d %s", THIS_METHOD, status, sqlite3_errmsg(connection->db)); } sqlite3_clear_bindings(statement); sqlite3_reset(statement); FreeYapDatabaseString(&_collection); if (isMutated && !stop) { @throw [self mutationDuringEnumerationException]; } } /** * Fast enumeration over select keys and associated metadata in the given collection. * * This uses a "SELECT key, metadata FROM database WHERE collection = ?" operation and steps over the results. * * If you only need to enumerate over certain items (e.g. keys with a particular prefix), * consider using the alternative version below which provides a filter, * allowing you to skip the deserialization step for those items you're not interested in. * * Keep in mind that you cannot modify the collection mid-enumeration (just like any other kind of enumeration). **/ - (void)_enumerateKeysAndMetadataInCollections:(NSArray *)collections usingBlock:(void (^)(int64_t rowid, NSString *collection, NSString *key, id metadata, BOOL *stop))block { [self _enumerateKeysAndMetadataInCollections:collections usingBlock:block withFilter:NULL]; } /** * Fast enumeration over selected keys and associated metadata in the given collection. * * From the filter block, simply return YES if you'd like the block handler to be invoked for the given key. * If the filter block returns NO, then the block handler is skipped for the given key, * which avoids the cost associated with deserializing the object. * * Keep in mind that you cannot modify the collection mid-enumeration (just like any other kind of enumeration). **/ - (void)_enumerateKeysAndMetadataInCollections:(NSArray *)collections usingBlock:(void (^)(int64_t rowid, NSString *collection, NSString *key, id metadata, BOOL *stop))block withFilter:(BOOL (^)(int64_t rowid, NSString *collection, NSString *key))filter { if (block == NULL) return; if ([collections count] == 0) return; sqlite3_stmt *statement = [connection enumerateKeysAndMetadataInCollectionStatement]; if (statement == NULL) return; isMutated = NO; // mutation during enumeration protection BOOL stop = NO; BOOL unlimitedMetadataCacheLimit = (connection->metadataCacheLimit == 0); // SELECT "rowid", "key", "metadata" FROM "database2" WHERE "collection" = ?; int const column_idx_rowid = SQLITE_COLUMN_START + 0; int const column_idx_key = SQLITE_COLUMN_START + 1; int const column_idx_metadata = SQLITE_COLUMN_START + 2; int const bind_idx_collection = SQLITE_BIND_START; for (NSString *collection in collections) { YapDatabaseString _collection; MakeYapDatabaseString(&_collection, collection); sqlite3_bind_text(statement, bind_idx_collection, _collection.str, _collection.length, SQLITE_STATIC); int status = sqlite3_step(statement); if (status == SQLITE_ROW) { if (connection->needsMarkSqlLevelSharedReadLock) [connection markSqlLevelSharedReadLockAcquired]; do { int64_t rowid = sqlite3_column_int64(statement, column_idx_rowid); const unsigned char *text = sqlite3_column_text(statement, column_idx_key); int textSize = sqlite3_column_bytes(statement, column_idx_key); NSString *key = [[NSString alloc] initWithBytes:text length:textSize encoding:NSUTF8StringEncoding]; BOOL invokeBlock = (filter == NULL) ? YES : filter(rowid, collection, key); if (invokeBlock) { YapCollectionKey *cacheKey = [[YapCollectionKey alloc] initWithCollection:collection key:key]; id metadata = [connection->metadataCache objectForKey:cacheKey]; if (metadata) { if (metadata == [YapNull null]) metadata = nil; } else { const void *mBlob = sqlite3_column_blob(statement, column_idx_metadata); int mBlobSize = sqlite3_column_bytes(statement, column_idx_metadata); if (mBlobSize > 0) { // Performance tuning: // Use dataWithBytesNoCopy to avoid an extra allocation and memcpy. NSData *mData = [NSData dataWithBytesNoCopy:(void *)mBlob length:mBlobSize freeWhenDone:NO]; metadata = connection->database->metadataDeserializer(collection, key, mData); } // Cache considerations: // Do we want to add the objects/metadata to the cache here? // If the cache is unlimited then we should. // Otherwise we should only add to the cache if it's not full. // The cache should generally be reserved for items that are explicitly fetched, // and we don't want to crowd them out during enumerations. if (unlimitedMetadataCacheLimit || [connection->metadataCache count] < connection->metadataCacheLimit) { if (metadata) [connection->metadataCache setObject:metadata forKey:cacheKey]; else [connection->metadataCache setObject:[YapNull null] forKey:cacheKey]; } } block(rowid, collection, key, metadata, &stop); if (stop || isMutated) break; } } while ((status = sqlite3_step(statement)) == SQLITE_ROW); } if ((status != SQLITE_DONE) && !stop && !isMutated) { YDBLogError(@"%@ - sqlite_step error: %d %s", THIS_METHOD, status, sqlite3_errmsg(connection->db)); } sqlite3_clear_bindings(statement); sqlite3_reset(statement); FreeYapDatabaseString(&_collection); if (isMutated && !stop) { @throw [self mutationDuringEnumerationException]; } if (stop) { break; } } // end for (NSString *collection in collections) } /** * Fast enumeration over all key/metadata pairs in all collections. * * This uses a "SELECT metadata FROM database ORDER BY collection ASC" operation, and steps over the results. * * If you only need to enumerate over certain objects (e.g. keys with a particular prefix), * consider using the alternative version below which provides a filter, * allowing you to skip the deserialization step for those objects you're not interested in. * * Keep in mind that you cannot modify the database mid-enumeration (just like any other kind of enumeration). **/ - (void)_enumerateKeysAndMetadataInAllCollectionsUsingBlock: (void (^)(int64_t rowid, NSString *collection, NSString *key, id metadata, BOOL *stop))block { [self _enumerateKeysAndMetadataInAllCollectionsUsingBlock:block withFilter:NULL]; } /** * Fast enumeration over all key/metadata pairs in all collections. * * This uses a "SELECT metadata FROM database ORDER BY collection ASC" operation and steps over the results. * * From the filter block, simply return YES if you'd like the block handler to be invoked for the given key. * If the filter block returns NO, then the block handler is skipped for the given key, * which avoids the cost associated with deserializing the object. * * Keep in mind that you cannot modify the database mid-enumeration (just like any other kind of enumeration). **/ - (void)_enumerateKeysAndMetadataInAllCollectionsUsingBlock: (void (^)(int64_t rowid, NSString *collection, NSString *key, id metadata, BOOL *stop))block withFilter:(BOOL (^)(int64_t rowid, NSString *collection, NSString *key))filter { if (block == NULL) return; sqlite3_stmt *statement = [connection enumerateKeysAndMetadataInAllCollectionsStatement]; if (statement == NULL) return; isMutated = NO; // mutation during enumeration protection BOOL stop = NO; // SELECT "rowid", "collection", "key", "metadata" FROM "database2" ORDER BY "collection" ASC; int const column_idx_rowid = SQLITE_COLUMN_START + 0; int const column_idx_collection = SQLITE_COLUMN_START + 1; int const column_idx_key = SQLITE_COLUMN_START + 2; int const column_idx_metadata = SQLITE_COLUMN_START + 3; BOOL unlimitedMetadataCacheLimit = (connection->metadataCacheLimit == 0); int status = sqlite3_step(statement); if (status == SQLITE_ROW) { if (connection->needsMarkSqlLevelSharedReadLock) [connection markSqlLevelSharedReadLockAcquired]; do { int64_t rowid = sqlite3_column_int64(statement, column_idx_rowid); const unsigned char *text1 = sqlite3_column_text(statement, column_idx_collection); int textSize1 = sqlite3_column_bytes(statement, column_idx_collection); const unsigned char *text2 = sqlite3_column_text(statement, column_idx_key); int textSize2 = sqlite3_column_bytes(statement, column_idx_key); NSString *collection, *key; collection = [[NSString alloc] initWithBytes:text1 length:textSize1 encoding:NSUTF8StringEncoding]; key = [[NSString alloc] initWithBytes:text2 length:textSize2 encoding:NSUTF8StringEncoding]; BOOL invokeBlock = (filter == NULL) ? YES : filter(rowid, collection, key); if (invokeBlock) { YapCollectionKey *cacheKey = [[YapCollectionKey alloc] initWithCollection:collection key:key]; id metadata = [connection->metadataCache objectForKey:cacheKey]; if (metadata) { if (metadata == [YapNull null]) metadata = nil; } else { const void *mBlob = sqlite3_column_blob(statement, column_idx_metadata); int mBlobSize = sqlite3_column_bytes(statement, column_idx_metadata); if (mBlobSize > 0) { // Performance tuning: // Use dataWithBytesNoCopy to avoid an extra allocation and memcpy. NSData *mData = [NSData dataWithBytesNoCopy:(void *)mBlob length:mBlobSize freeWhenDone:NO]; metadata = connection->database->metadataDeserializer(collection, key, mData); } // Cache considerations: // Do we want to add the objects/metadata to the cache here? // If the cache is unlimited then we should. // Otherwise we should only add to the cache if it's not full. // The cache should generally be reserved for items that are explicitly fetched, // and we don't want to crowd them out during enumerations. if (unlimitedMetadataCacheLimit || [connection->metadataCache count] < connection->metadataCacheLimit) { if (metadata) [connection->metadataCache setObject:metadata forKey:cacheKey]; else [connection->metadataCache setObject:[YapNull null] forKey:cacheKey]; } } block(rowid, collection, key, metadata, &stop); if (stop || isMutated) break; } } while ((status = sqlite3_step(statement)) == SQLITE_ROW); } if ((status != SQLITE_DONE) && !stop && !isMutated) { YDBLogError(@"%@ - sqlite_step error: %d %s", THIS_METHOD, status, sqlite3_errmsg(connection->db)); } sqlite3_reset(statement); if (isMutated && !stop) { @throw [self mutationDuringEnumerationException]; } } /** * Fast enumeration over all objects in the database. * * This uses a "SELECT key, object from database WHERE collection = ?" operation, and then steps over the results, * deserializing each object, and then invoking the given block handler. * * If you only need to enumerate over certain objects (e.g. keys with a particular prefix), * consider using the alternative version below which provides a filter, * allowing you to skip the serialization step for those objects you're not interested in. **/ - (void)_enumerateKeysAndObjectsInCollection:(NSString *)collection usingBlock:(void (^)(int64_t rowid, NSString *key, id object, BOOL *stop))block { [self _enumerateKeysAndObjectsInCollection:collection usingBlock:block withFilter:NULL]; } /** * Fast enumeration over objects in the database for which you're interested in. * The filter block allows you to decide which objects you're interested in. * * From the filter block, simply return YES if you'd like the block handler to be invoked for the given key. * If the filter block returns NO, then the block handler is skipped for the given key, * which avoids the cost associated with deserializing the object. **/ - (void)_enumerateKeysAndObjectsInCollection:(NSString *)collection usingBlock:(void (^)(int64_t rowid, NSString *key, id object, BOOL *stop))block withFilter:(BOOL (^)(int64_t rowid, NSString *key))filter { if (block == NULL) return; if (collection == nil) collection = @""; sqlite3_stmt *statement = [connection enumerateKeysAndObjectsInCollectionStatement]; if (statement == NULL) return; isMutated = NO; // mutation during enumeration protection BOOL stop = NO; // SELECT "rowid", "key", "data", FROM "database2" WHERE "collection" = ?; int const column_idx_rowid = SQLITE_COLUMN_START + 0; int const column_idx_key = SQLITE_COLUMN_START + 1; int const column_idx_data = SQLITE_COLUMN_START + 2; int const bind_idx_collection = SQLITE_BIND_START; YapDatabaseString _collection; MakeYapDatabaseString(&_collection, collection); sqlite3_bind_text(statement, bind_idx_collection, _collection.str, _collection.length, SQLITE_STATIC); BOOL unlimitedObjectCacheLimit = (connection->objectCacheLimit == 0); int status = sqlite3_step(statement); if (status == SQLITE_ROW) { if (connection->needsMarkSqlLevelSharedReadLock) [connection markSqlLevelSharedReadLockAcquired]; do { int64_t rowid = sqlite3_column_int64(statement, column_idx_rowid); const unsigned char *text = sqlite3_column_text(statement, column_idx_key); int textSize = sqlite3_column_bytes(statement, column_idx_key); NSString *key = [[NSString alloc] initWithBytes:text length:textSize encoding:NSUTF8StringEncoding]; BOOL invokeBlock = (filter == NULL) ? YES : filter(rowid, key); if (invokeBlock) { YapCollectionKey *cacheKey = [[YapCollectionKey alloc] initWithCollection:collection key:key]; id object = [connection->objectCache objectForKey:cacheKey]; if (object == nil) { const void *oBlob = sqlite3_column_blob(statement, column_idx_data); int oBlobSize = sqlite3_column_bytes(statement, column_idx_data); // Performance tuning: // Use dataWithBytesNoCopy to avoid an extra allocation and memcpy. NSData *oData = [NSData dataWithBytesNoCopy:(void *)oBlob length:oBlobSize freeWhenDone:NO]; object = connection->database->objectDeserializer(collection, key, oData); // Cache considerations: // Do we want to add the objects/metadata to the cache here? // If the cache is unlimited then we should. // Otherwise we should only add to the cache if it's not full. // The cache should generally be reserved for items that are explicitly fetched, // and we don't want to crowd them out during enumerations. if (unlimitedObjectCacheLimit || [connection->objectCache count] < connection->objectCacheLimit) { if (object) [connection->objectCache setObject:object forKey:cacheKey]; } } block(rowid, key, object, &stop); if (stop || isMutated) break; } } while ((status = sqlite3_step(statement)) == SQLITE_ROW); } if ((status != SQLITE_DONE) && !stop && !isMutated) { YDBLogError(@"%@ - sqlite_step error: %d %s", THIS_METHOD, status, sqlite3_errmsg(connection->db)); } sqlite3_clear_bindings(statement); sqlite3_reset(statement); FreeYapDatabaseString(&_collection); if (isMutated && !stop) { @throw [self mutationDuringEnumerationException]; } } /** * Fast enumeration over selected objects in the database. * * This uses a "SELECT key, object from database WHERE collection = ?" operation, and then steps over the results, * deserializing each object, and then invoking the given block handler. * * If you only need to enumerate over certain objects (e.g. keys with a particular prefix), * consider using the alternative version below which provides a filter, * allowing you to skip the serialization step for those objects you're not interested in. **/ - (void)_enumerateKeysAndObjectsInCollections:(NSArray *)collections usingBlock: (void (^)(int64_t rowid, NSString *collection, NSString *key, id object, BOOL *stop))block { [self _enumerateKeysAndObjectsInCollections:collections usingBlock:block withFilter:NULL]; } /** * Fast enumeration over objects in the database for which you're interested in. * The filter block allows you to decide which objects you're interested in. * * From the filter block, simply return YES if you'd like the block handler to be invoked for the given key. * If the filter block returns NO, then the block handler is skipped for the given key, * which avoids the cost associated with deserializing the object. **/ - (void)_enumerateKeysAndObjectsInCollections:(NSArray *)collections usingBlock:(void (^)(int64_t rowid, NSString *collection, NSString *key, id object, BOOL *stop))block withFilter:(BOOL (^)(int64_t rowid, NSString *collection, NSString *key))filter { if (block == NULL) return; if ([collections count] == 0) return; sqlite3_stmt *statement = [connection enumerateKeysAndObjectsInCollectionStatement]; if (statement == NULL) return; isMutated = NO; // mutation during enumeration protection BOOL stop = NO; BOOL unlimitedObjectCacheLimit = (connection->objectCacheLimit == 0); // SELECT "rowid", "key", "data", FROM "database2" WHERE "collection" = ?; int const column_idx_rowid = SQLITE_COLUMN_START + 0; int const column_idx_key = SQLITE_COLUMN_START + 1; int const column_idx_data = SQLITE_COLUMN_START + 2; int const bind_idx_collection = SQLITE_BIND_START; for (NSString *collection in collections) { YapDatabaseString _collection; MakeYapDatabaseString(&_collection, collection); sqlite3_bind_text(statement, bind_idx_collection, _collection.str, _collection.length, SQLITE_STATIC); int status = sqlite3_step(statement); if (status == SQLITE_ROW) { if (connection->needsMarkSqlLevelSharedReadLock) [connection markSqlLevelSharedReadLockAcquired]; do { int64_t rowid = sqlite3_column_int64(statement, column_idx_rowid); const unsigned char *text = sqlite3_column_text(statement, column_idx_key); int textSize = sqlite3_column_bytes(statement, column_idx_key); NSString *key = [[NSString alloc] initWithBytes:text length:textSize encoding:NSUTF8StringEncoding]; BOOL invokeBlock = (filter == NULL) ? YES : filter(rowid, collection, key); if (invokeBlock) { YapCollectionKey *cacheKey = [[YapCollectionKey alloc] initWithCollection:collection key:key]; id object = [connection->objectCache objectForKey:cacheKey]; if (object == nil) { const void *oBlob = sqlite3_column_blob(statement, column_idx_data); int oBlobSize = sqlite3_column_bytes(statement, column_idx_data); // Performance tuning: // Use dataWithBytesNoCopy to avoid an extra allocation and memcpy. NSData *oData = [NSData dataWithBytesNoCopy:(void *)oBlob length:oBlobSize freeWhenDone:NO]; object = connection->database->objectDeserializer(collection, key, oData); // Cache considerations: // Do we want to add the objects/metadata to the cache here? // If the cache is unlimited then we should. // Otherwise we should only add to the cache if it's not full. // The cache should generally be reserved for items that are explicitly fetched, // and we don't want to crowd them out during enumerations. if (unlimitedObjectCacheLimit || [connection->objectCache count] < connection->objectCacheLimit) { if (object) [connection->objectCache setObject:object forKey:cacheKey]; } } block(rowid, collection, key, object, &stop); if (stop || isMutated) break; } } while ((status = sqlite3_step(statement)) == SQLITE_ROW); } if ((status != SQLITE_DONE) && !stop && !isMutated) { YDBLogError(@"%@ - sqlite_step error: %d %s", THIS_METHOD, status, sqlite3_errmsg(connection->db)); } sqlite3_clear_bindings(statement); sqlite3_reset(statement); FreeYapDatabaseString(&_collection); if (isMutated && !stop) { @throw [self mutationDuringEnumerationException]; } if (stop) { break; } } // end for (NSString *collection in collections) } /** * Enumerates all key/object pairs in all collections. * * The enumeration is sorted by collection. That is, it will enumerate fully over a single collection * before moving onto another collection. * * If you only need to enumerate over certain objects (e.g. subset of collections, or keys with a particular prefix), * consider using the alternative version below which provides a filter, * allowing you to skip the serialization step for those objects you're not interested in. **/ - (void)_enumerateKeysAndObjectsInAllCollectionsUsingBlock: (void (^)(int64_t rowid, NSString *collection, NSString *key, id object, BOOL *stop))block { [self _enumerateKeysAndObjectsInAllCollectionsUsingBlock:block withFilter:NULL]; } /** * Enumerates all key/object pairs in all collections. * The filter block allows you to decide which objects you're interested in. * * The enumeration is sorted by collection. That is, it will enumerate fully over a single collection * before moving onto another collection. * * From the filter block, simply return YES if you'd like the block handler to be invoked for the given * collection/key pair. If the filter block returns NO, then the block handler is skipped for the given pair, * which avoids the cost associated with deserializing the object. **/ - (void)_enumerateKeysAndObjectsInAllCollectionsUsingBlock: (void (^)(int64_t rowid, NSString *collection, NSString *key, id object, BOOL *stop))block withFilter:(BOOL (^)(int64_t rowid, NSString *collection, NSString *key))filter { if (block == NULL) return; sqlite3_stmt *statement = [connection enumerateKeysAndObjectsInAllCollectionsStatement]; if (statement == NULL) return; isMutated = NO; // mutation during enumeration protection BOOL stop = NO; // SELECT "rowid", "collection", "key", "data" FROM "database2" ORDER BY \"collection\" ASC;"; int const column_idx_rowid = SQLITE_COLUMN_START + 0; int const column_idx_collection = SQLITE_COLUMN_START + 1; int const column_idx_key = SQLITE_COLUMN_START + 2; int const column_idx_data = SQLITE_COLUMN_START + 3; BOOL unlimitedObjectCacheLimit = (connection->objectCacheLimit == 0); int status = sqlite3_step(statement); if (status == SQLITE_ROW) { if (connection->needsMarkSqlLevelSharedReadLock) [connection markSqlLevelSharedReadLockAcquired]; do { int64_t rowid = sqlite3_column_int64(statement, column_idx_rowid); const unsigned char *text1 = sqlite3_column_text(statement, column_idx_collection); int textSize1 = sqlite3_column_bytes(statement, column_idx_collection); const unsigned char *text2 = sqlite3_column_text(statement, column_idx_key); int textSize2 = sqlite3_column_bytes(statement, column_idx_key); NSString *collection, *key; collection = [[NSString alloc] initWithBytes:text1 length:textSize1 encoding:NSUTF8StringEncoding]; key = [[NSString alloc] initWithBytes:text2 length:textSize2 encoding:NSUTF8StringEncoding]; BOOL invokeBlock = (filter == NULL) ? YES : filter(rowid, collection, key); if (invokeBlock) { YapCollectionKey *cacheKey = [[YapCollectionKey alloc] initWithCollection:collection key:key]; id object = [connection->objectCache objectForKey:cacheKey]; if (object == nil) { const void *oBlob = sqlite3_column_blob(statement, column_idx_data); int oBlobSize = sqlite3_column_bytes(statement, column_idx_data); NSData *oData = [NSData dataWithBytesNoCopy:(void *)oBlob length:oBlobSize freeWhenDone:NO]; object = connection->database->objectDeserializer(collection, key, oData); if (unlimitedObjectCacheLimit || [connection->objectCache count] < connection->objectCacheLimit) { if (object) [connection->objectCache setObject:object forKey:cacheKey]; } } block(rowid, collection, key, object, &stop); if (stop || isMutated) break; } } while ((status = sqlite3_step(statement)) == SQLITE_ROW); } if ((status != SQLITE_DONE) && !stop && !isMutated) { YDBLogError(@"%@ - sqlite_step error: %d %s", THIS_METHOD, status, sqlite3_errmsg(connection->db)); } sqlite3_clear_bindings(statement); sqlite3_reset(statement); if (isMutated && !stop) { @throw [self mutationDuringEnumerationException]; } } /** * Fast enumeration over all rows in the database. * * This uses a "SELECT key, data, metadata from database WHERE collection = ?" operation, * and then steps over the results, deserializing each object & metadata, and then invoking the given block handler. * * If you only need to enumerate over certain rows (e.g. keys with a particular prefix), * consider using the alternative version below which provides a filter, * allowing you to skip the serialization step for those rows you're not interested in. **/ - (void)_enumerateRowsInCollection:(NSString *)collection usingBlock:(void (^)(int64_t rowid, NSString *key, id object, id metadata, BOOL *stop))block { [self _enumerateRowsInCollection:collection usingBlock:block withFilter:NULL]; } /** * Fast enumeration over rows in the database for which you're interested in. * The filter block allows you to decide which rows you're interested in. * * From the filter block, simply return YES if you'd like the block handler to be invoked for the given key. * If the filter block returns NO, then the block handler is skipped for the given key, * which avoids the cost associated with deserializing the object & metadata. **/ - (void)_enumerateRowsInCollection:(NSString *)collection usingBlock:(void (^)(int64_t rowid, NSString *key, id object, id metadata, BOOL *stop))block withFilter:(BOOL (^)(int64_t rowid, NSString *key))filter { if (block == NULL) return; if (collection == nil) collection = @""; sqlite3_stmt *statement = [connection enumerateRowsInCollectionStatement]; if (statement == NULL) return; isMutated = NO; // mutation during enumeration protection BOOL stop = NO; // SELECT "rowid", "key", "data", "metadata" FROM "database2" WHERE "collection" = ?; int const column_idx_rowid = SQLITE_COLUMN_START + 0; int const column_idx_key = SQLITE_COLUMN_START + 1; int const column_idx_data = SQLITE_COLUMN_START + 2; int const column_idx_metadata = SQLITE_COLUMN_START + 3; int const bind_idx_collection = SQLITE_BIND_START; YapDatabaseString _collection; MakeYapDatabaseString(&_collection, collection); sqlite3_bind_text(statement, bind_idx_collection, _collection.str, _collection.length, SQLITE_STATIC); BOOL unlimitedObjectCacheLimit = (connection->objectCacheLimit == 0); BOOL unlimitedMetadataCacheLimit = (connection->metadataCacheLimit == 0); int status = sqlite3_step(statement); if (status == SQLITE_ROW) { if (connection->needsMarkSqlLevelSharedReadLock) [connection markSqlLevelSharedReadLockAcquired]; do { int64_t rowid = sqlite3_column_int64(statement, column_idx_rowid); const unsigned char *text = sqlite3_column_text(statement, column_idx_key); int textSize = sqlite3_column_bytes(statement, column_idx_key); NSString *key = [[NSString alloc] initWithBytes:text length:textSize encoding:NSUTF8StringEncoding]; BOOL invokeBlock = (filter == NULL) ? YES : filter(rowid, key); if (invokeBlock) { YapCollectionKey *cacheKey = [[YapCollectionKey alloc] initWithCollection:collection key:key]; id object = [connection->objectCache objectForKey:cacheKey]; if (object == nil) { const void *oBlob = sqlite3_column_blob(statement, column_idx_data); int oBlobSize = sqlite3_column_bytes(statement, column_idx_data); // Performance tuning: // Use dataWithBytesNoCopy to avoid an extra allocation and memcpy. NSData *oData = [NSData dataWithBytesNoCopy:(void *)oBlob length:oBlobSize freeWhenDone:NO]; object = connection->database->objectDeserializer(collection, key, oData); // Cache considerations: // Do we want to add the objects/metadata to the cache here? // If the cache is unlimited then we should. // Otherwise we should only add to the cache if it's not full. // The cache should generally be reserved for items that are explicitly fetched, // and we don't want to crowd them out during enumerations. if (unlimitedObjectCacheLimit || [connection->objectCache count] < connection->objectCacheLimit) { if (object) [connection->objectCache setObject:object forKey:cacheKey]; } } id metadata = [connection->metadataCache objectForKey:cacheKey]; if (metadata) { if (metadata == [YapNull null]) metadata = nil; } else { const void *mBlob = sqlite3_column_blob(statement, column_idx_metadata); int mBlobSize = sqlite3_column_bytes(statement, column_idx_metadata); if (mBlobSize > 0) { // Performance tuning: // Use dataWithBytesNoCopy to avoid an extra allocation and memcpy. NSData *mData = [NSData dataWithBytesNoCopy:(void *)mBlob length:mBlobSize freeWhenDone:NO]; metadata = connection->database->metadataDeserializer(collection, key, mData); } // Cache considerations: // Do we want to add the objects/metadata to the cache here? // If the cache is unlimited then we should. // Otherwise we should only add to the cache if it's not full. // The cache should generally be reserved for items that are explicitly fetched, // and we don't want to crowd them out during enumerations. if (unlimitedMetadataCacheLimit || [connection->metadataCache count] < connection->metadataCacheLimit) { if (metadata) [connection->metadataCache setObject:metadata forKey:cacheKey]; else [connection->metadataCache setObject:[YapNull null] forKey:cacheKey]; } } block(rowid, key, object, metadata, &stop); if (stop || isMutated) break; } } while ((status = sqlite3_step(statement)) == SQLITE_ROW); } if ((status != SQLITE_DONE) && !stop && !isMutated) { YDBLogError(@"%@ - sqlite_step error: %d %s", THIS_METHOD, status, sqlite3_errmsg(connection->db)); } sqlite3_clear_bindings(statement); sqlite3_reset(statement); FreeYapDatabaseString(&_collection); if (isMutated && !stop) { @throw [self mutationDuringEnumerationException]; } } /** * Fast enumeration over select rows in the database. * * This uses a "SELECT key, data, metadata from database WHERE collection = ?" operation, * and then steps over the results, deserializing each object & metadata, and then invoking the given block handler. * * If you only need to enumerate over certain rows (e.g. keys with a particular prefix), * consider using the alternative version below which provides a filter, * allowing you to skip the serialization step for those rows you're not interested in. **/ - (void)_enumerateRowsInCollections:(NSArray *)collections usingBlock: (void (^)(int64_t rowid, NSString *collection, NSString *key, id object, id metadata, BOOL *stop))block { [self _enumerateRowsInCollections:collections usingBlock:block withFilter:NULL]; } /** * Fast enumeration over rows in the database for which you're interested in. * The filter block allows you to decide which rows you're interested in. * * From the filter block, simply return YES if you'd like the block handler to be invoked for the given key. * If the filter block returns NO, then the block handler is skipped for the given key, * which avoids the cost associated with deserializing the object & metadata. **/ - (void)_enumerateRowsInCollections:(NSArray *)collections usingBlock:(void (^)(int64_t rowid, NSString *collection, NSString *key, id object, id metadata, BOOL *stop))block withFilter:(BOOL (^)(int64_t rowid, NSString *collection, NSString *key))filter { if (block == NULL) return; if ([collections count] == 0) return; sqlite3_stmt *statement = [connection enumerateRowsInCollectionStatement]; if (statement == NULL) return; isMutated = NO; // mutation during enumeration protection BOOL stop = NO; BOOL unlimitedObjectCacheLimit = (connection->objectCacheLimit == 0); BOOL unlimitedMetadataCacheLimit = (connection->metadataCacheLimit == 0); // SELECT "rowid", "key", "data", "metadata" FROM "database2" WHERE "collection" = ?; int const column_idx_rowid = SQLITE_COLUMN_START + 0; int const column_idx_key = SQLITE_COLUMN_START + 1; int const column_idx_data = SQLITE_COLUMN_START + 2; int const column_idx_metadata = SQLITE_COLUMN_START + 3; int const bind_idx_collection = SQLITE_BIND_START; for (NSString *collection in collections) { YapDatabaseString _collection; MakeYapDatabaseString(&_collection, collection); sqlite3_bind_text(statement, bind_idx_collection, _collection.str, _collection.length, SQLITE_STATIC); int status = sqlite3_step(statement); if (status == SQLITE_ROW) { if (connection->needsMarkSqlLevelSharedReadLock) [connection markSqlLevelSharedReadLockAcquired]; do { int64_t rowid = sqlite3_column_int64(statement, column_idx_rowid); const unsigned char *text = sqlite3_column_text(statement, column_idx_key); int textSize = sqlite3_column_bytes(statement, column_idx_key); NSString *key = [[NSString alloc] initWithBytes:text length:textSize encoding:NSUTF8StringEncoding]; BOOL invokeBlock = (filter == NULL) ? YES : filter(rowid, collection, key); if (invokeBlock) { YapCollectionKey *cacheKey = [[YapCollectionKey alloc] initWithCollection:collection key:key]; id object = [connection->objectCache objectForKey:cacheKey]; if (object == nil) { const void *oBlob = sqlite3_column_blob(statement, column_idx_data); int oBlobSize = sqlite3_column_bytes(statement, column_idx_data); // Performance tuning: // Use dataWithBytesNoCopy to avoid an extra allocation and memcpy. NSData *oData = [NSData dataWithBytesNoCopy:(void *)oBlob length:oBlobSize freeWhenDone:NO]; object = connection->database->objectDeserializer(collection, key, oData); // Cache considerations: // Do we want to add the objects/metadata to the cache here? // If the cache is unlimited then we should. // Otherwise we should only add to the cache if it's not full. // The cache should generally be reserved for items that are explicitly fetched, // and we don't want to crowd them out during enumerations. if (unlimitedObjectCacheLimit || [connection->objectCache count] < connection->objectCacheLimit) { if (object) [connection->objectCache setObject:object forKey:cacheKey]; } } id metadata = [connection->metadataCache objectForKey:cacheKey]; if (metadata) { if (metadata == [YapNull null]) metadata = nil; } else { const void *mBlob = sqlite3_column_blob(statement, column_idx_metadata); int mBlobSize = sqlite3_column_bytes(statement, column_idx_metadata); if (mBlobSize > 0) { // Performance tuning: // Use dataWithBytesNoCopy to avoid an extra allocation and memcpy. NSData *mData = [NSData dataWithBytesNoCopy:(void *)mBlob length:mBlobSize freeWhenDone:NO]; metadata = connection->database->metadataDeserializer(collection, key, mData); } // Cache considerations: // Do we want to add the objects/metadata to the cache here? // If the cache is unlimited then we should. // Otherwise we should only add to the cache if it's not full. // The cache should generally be reserved for items that are explicitly fetched, // and we don't want to crowd them out during enumerations. if (unlimitedMetadataCacheLimit || [connection->metadataCache count] < connection->metadataCacheLimit) { if (metadata) [connection->metadataCache setObject:metadata forKey:cacheKey]; else [connection->metadataCache setObject:[YapNull null] forKey:cacheKey]; } } block(rowid, collection, key, object, metadata, &stop); if (stop || isMutated) break; } } while ((status = sqlite3_step(statement)) == SQLITE_ROW); } if ((status != SQLITE_DONE) && !stop && !isMutated) { YDBLogError(@"%@ - sqlite_step error: %d %s", THIS_METHOD, status, sqlite3_errmsg(connection->db)); } sqlite3_clear_bindings(statement); sqlite3_reset(statement); FreeYapDatabaseString(&_collection); if (isMutated && !stop) { @throw [self mutationDuringEnumerationException]; } if (stop) { break; } } // end for (NSString *collection in collections) } /** * Enumerates all rows in all collections. * * The enumeration is sorted by collection. That is, it will enumerate fully over a single collection * before moving onto another collection. * * If you only need to enumerate over certain rows (e.g. subset of collections, or keys with a particular prefix), * consider using the alternative version below which provides a filter, * allowing you to skip the serialization step for those objects you're not interested in. **/ - (void)_enumerateRowsInAllCollectionsUsingBlock: (void (^)(int64_t rowid, NSString *collection, NSString *key, id object, id metadata, BOOL *stop))block { [self _enumerateRowsInAllCollectionsUsingBlock:block withFilter:NULL]; } /** * Enumerates all rows in all collections. * The filter block allows you to decide which objects you're interested in. * * The enumeration is sorted by collection. That is, it will enumerate fully over a single collection * before moving onto another collection. * * From the filter block, simply return YES if you'd like the block handler to be invoked for the given * collection/key pair. If the filter block returns NO, then the block handler is skipped for the given pair, * which avoids the cost associated with deserializing the object. **/ - (void)_enumerateRowsInAllCollectionsUsingBlock: (void (^)(int64_t rowid, NSString *collection, NSString *key, id object, id metadata, BOOL *stop))block withFilter:(BOOL (^)(int64_t rowid, NSString *collection, NSString *key))filter { if (block == NULL) return; sqlite3_stmt *statement = [connection enumerateRowsInAllCollectionsStatement]; if (statement == NULL) return; isMutated = NO; // mutation during enumeration protection BOOL stop = NO; // SELECT "rowid", "collection", "key", "data", "metadata" FROM "database2" ORDER BY \"collection\" ASC;"; int const column_idx_rowid = SQLITE_COLUMN_START + 0; int const column_idx_collection = SQLITE_COLUMN_START + 1; int const column_idx_key = SQLITE_COLUMN_START + 2; int const column_idx_data = SQLITE_COLUMN_START + 3; int const column_idx_metadata = SQLITE_COLUMN_START + 4; BOOL unlimitedObjectCacheLimit = (connection->objectCacheLimit == 0); BOOL unlimitedMetadataCacheLimit = (connection->metadataCacheLimit == 0); int status = sqlite3_step(statement); if (status == SQLITE_ROW) { if (connection->needsMarkSqlLevelSharedReadLock) [connection markSqlLevelSharedReadLockAcquired]; do { int64_t rowid = sqlite3_column_int64(statement, column_idx_rowid); const unsigned char *text1 = sqlite3_column_text(statement, column_idx_collection); int textSize1 = sqlite3_column_bytes(statement, column_idx_collection); const unsigned char *text2 = sqlite3_column_text(statement, column_idx_key); int textSize2 = sqlite3_column_bytes(statement, column_idx_key); NSString *collection, *key; collection = [[NSString alloc] initWithBytes:text1 length:textSize1 encoding:NSUTF8StringEncoding]; key = [[NSString alloc] initWithBytes:text2 length:textSize2 encoding:NSUTF8StringEncoding]; BOOL invokeBlock = (filter == NULL) ? YES : filter(rowid, collection, key); if (invokeBlock) { YapCollectionKey *cacheKey = [[YapCollectionKey alloc] initWithCollection:collection key:key]; id object = [connection->objectCache objectForKey:cacheKey]; if (object == nil) { const void *oBlob = sqlite3_column_blob(statement, column_idx_data); int oBlobSize = sqlite3_column_bytes(statement, column_idx_data); NSData *oData = [NSData dataWithBytesNoCopy:(void *)oBlob length:oBlobSize freeWhenDone:NO]; object = connection->database->objectDeserializer(collection, key, oData); if (unlimitedObjectCacheLimit || [connection->objectCache count] < connection->objectCacheLimit) { if (object) [connection->objectCache setObject:object forKey:cacheKey]; } } id metadata = [connection->metadataCache objectForKey:cacheKey]; if (metadata) { if (metadata == [YapNull null]) metadata = nil; } else { const void *mBlob = sqlite3_column_blob(statement, column_idx_metadata); int mBlobSize = sqlite3_column_bytes(statement, column_idx_metadata); if (mBlobSize > 0) { NSData *mData = [NSData dataWithBytesNoCopy:(void *)mBlob length:mBlobSize freeWhenDone:NO]; metadata = connection->database->metadataDeserializer(collection, key, mData); } if (unlimitedMetadataCacheLimit || [connection->metadataCache count] < connection->metadataCacheLimit) { if (metadata) [connection->metadataCache setObject:metadata forKey:cacheKey]; else [connection->metadataCache setObject:[YapNull null] forKey:cacheKey]; } } block(rowid, collection, key, object, metadata, &stop); if (stop || isMutated) break; } } while ((status = sqlite3_step(statement)) == SQLITE_ROW); } if ((status != SQLITE_DONE) && !stop && !isMutated) { YDBLogError(@"%@ - sqlite_step error: %d %s", THIS_METHOD, status, sqlite3_errmsg(connection->db)); } sqlite3_clear_bindings(statement); sqlite3_reset(statement); if (isMutated && !stop) { @throw [self mutationDuringEnumerationException]; } } //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// #pragma mark Extensions //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// /** * Returns an extension transaction corresponding to the extension type registered under the given name. * If the extension has not yet been prepared, it is done so automatically. * * @return * A subclass of YapDatabaseExtensionTransaction, * according to the type of extension registered under the given name. * * One must register an extension with the database before it can be accessed from within connections or transactions. * After registration everything works automatically using just the registered extension name. * * @see [YapDatabase registerExtension:withName:] **/ - (id)extension:(NSString *)extensionName { // This method is PUBLIC if (extensionsReady) return [extensions objectForKey:extensionName]; if (extensions == nil) extensions = [[NSMutableDictionary alloc] init]; YapDatabaseExtensionTransaction *extTransaction = [extensions objectForKey:extensionName]; if (extTransaction == nil) { YapDatabaseExtensionConnection *extConnection = [connection extension:extensionName]; if (extConnection) { if (isReadWriteTransaction) extTransaction = [extConnection newReadWriteTransaction:(YapDatabaseReadWriteTransaction *)self]; else extTransaction = [extConnection newReadTransaction:self]; if ([extTransaction prepareIfNeeded]) { [extensions setObject:extTransaction forKey:extensionName]; } else { extTransaction = nil; } } } return extTransaction; } - (id)ext:(NSString *)extensionName { // This method is PUBLIC // The "+ (void)load" method swizzles the implementation of this class // to point to the implementation of the extension: method. // // So the two methods are literally the same thing. return [self extension:extensionName]; // This method is swizzled ! } - (void)prepareExtensions { if (extensions == nil) extensions = [[NSMutableDictionary alloc] init]; NSDictionary *extConnections = [connection extensions]; [extConnections enumerateKeysAndObjectsUsingBlock:^(id key, id obj, BOOL __unused *stop) { __unsafe_unretained NSString *extName = key; __unsafe_unretained YapDatabaseExtensionConnection *extConnection = obj; YapDatabaseExtensionTransaction *extTransaction = [extensions objectForKey:extName]; if (extTransaction == nil) { if (isReadWriteTransaction) extTransaction = [extConnection newReadWriteTransaction:(YapDatabaseReadWriteTransaction *)self]; else extTransaction = [extConnection newReadTransaction:self]; if ([extTransaction prepareIfNeeded]) { [extensions setObject:extTransaction forKey:extName]; } } }]; if (orderedExtensions == nil) orderedExtensions = [[NSMutableArray alloc] initWithCapacity:[extensions count]]; for (NSString *extName in connection->extensionsOrder) { YapDatabaseExtensionTransaction *extTransaction = [extensions objectForKey:extName]; if (extTransaction) { [orderedExtensions addObject:extTransaction]; } } extensionsReady = YES; } - (NSDictionary *)extensions { // This method is INTERNAL if (!extensionsReady) { [self prepareExtensions]; } return extensions; } - (NSArray *)orderedExtensions { // This method is INTERNAL if (!extensionsReady) { [self prepareExtensions]; } return orderedExtensions; } //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// #pragma mark Memory Tables //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// - (YapMemoryTableTransaction *)memoryTableTransaction:(NSString *)tableName { BOOL isYap = [tableName isEqualToString:@"yap"]; if (isYap && yapMemoryTableTransaction) return yapMemoryTableTransaction; YapMemoryTableTransaction *memoryTableTransaction = nil; YapMemoryTable *table = [[connection registeredMemoryTables] objectForKey:tableName]; if (table) { uint64_t snapshot = [connection snapshot]; if (isReadWriteTransaction) memoryTableTransaction = [table newReadWriteTransactionWithSnapshot:(snapshot + 1)]; else memoryTableTransaction = [table newReadTransactionWithSnapshot:snapshot]; } if (isYap) { yapMemoryTableTransaction = memoryTableTransaction; } return memoryTableTransaction; } /** * The system automatically creates a special YapMemoryTable that's available for any extension. * This memoryTable is registered under the reserved name @"yap". * * The yapMemoryTableTransaction uses a keyClass of [YapCollectionKey class]. * Thus, when using it, you must pass a YapCollectionKey, where collectionKey.collection == extensionName. * * This memory table is an in-memory alternative to using the yap sqlite table. **/ - (YapMemoryTableTransaction *)yapMemoryTableTransaction { return [self memoryTableTransaction:@"yap"]; } //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// #pragma mark Yap2 Table //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// - (BOOL)getBoolValue:(BOOL *)valuePtr forKey:(NSString *)key extension:(NSString *)extensionName { int intValue = 0; BOOL result = [self getIntValue:&intValue forKey:key extension:extensionName]; if (valuePtr) *valuePtr = (intValue == 0) ? NO : YES; return result; } - (BOOL)getIntValue:(int *)valuePtr forKey:(NSString *)key extension:(NSString *)extensionName { if (extensionName == nil) extensionName = @""; sqlite3_stmt *statement = [connection yapGetDataForKeyStatement]; if (statement == NULL) { if (valuePtr) *valuePtr = 0; return NO; } BOOL result = NO; int value = 0; // SELECT "data" FROM "yap2" WHERE "extension" = ? AND "key" = ? ; int const column_idx_data = SQLITE_COLUMN_START; int const bind_idx_extension = SQLITE_BIND_START + 0; int const bind_idx_key = SQLITE_BIND_START + 1; YapDatabaseString _extension; MakeYapDatabaseString(&_extension, extensionName); sqlite3_bind_text(statement, bind_idx_extension, _extension.str, _extension.length, SQLITE_STATIC); YapDatabaseString _key; MakeYapDatabaseString(&_key, key); sqlite3_bind_text(statement, bind_idx_key, _key.str, _key.length, SQLITE_STATIC); int status = sqlite3_step(statement); if (status == SQLITE_ROW) { result = YES; value = sqlite3_column_int(statement, column_idx_data); } else if (status == SQLITE_ERROR) { YDBLogError(@"Error executing 'yapGetDataForKeyStatement': %d %s", status, sqlite3_errmsg(connection->db)); } sqlite3_clear_bindings(statement); sqlite3_reset(statement); FreeYapDatabaseString(&_extension); FreeYapDatabaseString(&_key); if (valuePtr) *valuePtr = value; return result; } - (BOOL)getDoubleValue:(double *)valuePtr forKey:(NSString *)key extension:(NSString *)extensionName { if (extensionName == nil) extensionName = @""; sqlite3_stmt *statement = [connection yapGetDataForKeyStatement]; if (statement == NULL) { if (valuePtr) *valuePtr = 0.0; return NO; } BOOL result = NO; double value = 0.0; // SELECT "data" FROM "yap2" WHERE "extension" = ? AND "key" = ? ; int const column_idx_data = SQLITE_COLUMN_START; int const bind_idx_extension = SQLITE_BIND_START + 0; int const bind_idx_key = SQLITE_BIND_START + 1; YapDatabaseString _extension; MakeYapDatabaseString(&_extension, extensionName); sqlite3_bind_text(statement, bind_idx_extension, _extension.str, _extension.length, SQLITE_STATIC); YapDatabaseString _key; MakeYapDatabaseString(&_key, key); sqlite3_bind_text(statement, bind_idx_key, _key.str, _key.length, SQLITE_STATIC); int status = sqlite3_step(statement); if (status == SQLITE_ROW) { result = YES; value = sqlite3_column_double(statement, column_idx_data); } else if (status == SQLITE_ERROR) { YDBLogError(@"Error executing 'yapGetDataForKeyStatement': %d %s", status, sqlite3_errmsg(connection->db)); } sqlite3_clear_bindings(statement); sqlite3_reset(statement); FreeYapDatabaseString(&_extension); FreeYapDatabaseString(&_key); if (valuePtr) *valuePtr = value; return result; } - (NSString *)stringValueForKey:(NSString *)key extension:(NSString *)extensionName { if (extensionName == nil) extensionName = @""; sqlite3_stmt *statement = [connection yapGetDataForKeyStatement]; if (statement == NULL) return nil; NSString *value = nil; // SELECT "data" FROM "yap2" WHERE "extension" = ? AND "key" = ? ; int const column_idx_data = SQLITE_COLUMN_START; int const bind_idx_extension = SQLITE_BIND_START + 0; int const bind_idx_key = SQLITE_BIND_START + 1; YapDatabaseString _extension; MakeYapDatabaseString(&_extension, extensionName); sqlite3_bind_text(statement, bind_idx_extension, _extension.str, _extension.length, SQLITE_STATIC); YapDatabaseString _key; MakeYapDatabaseString(&_key, key); sqlite3_bind_text(statement, bind_idx_key, _key.str, _key.length, SQLITE_STATIC); int status = sqlite3_step(statement); if (status == SQLITE_ROW) { const unsigned char *text = sqlite3_column_text(statement, column_idx_data); int textSize = sqlite3_column_bytes(statement, column_idx_data); value = [[NSString alloc] initWithBytes:text length:textSize encoding:NSUTF8StringEncoding]; } else if (status == SQLITE_ERROR) { YDBLogError(@"Error executing 'yapGetDataForKeyStatement': %d %s", status, sqlite3_errmsg(connection->db)); } sqlite3_clear_bindings(statement); sqlite3_reset(statement); FreeYapDatabaseString(&_extension); FreeYapDatabaseString(&_key); return value; } - (NSData *)dataValueForKey:(NSString *)key extension:(NSString *)extensionName { if (extensionName == nil) extensionName = @""; sqlite3_stmt *statement = [connection yapGetDataForKeyStatement]; if (statement == NULL) return nil; NSData *value = nil; // SELECT "data" FROM "yap2" WHERE "extension" = ? AND "key" = ? ; int const column_idx_data = SQLITE_COLUMN_START; int const bind_idx_extension = SQLITE_BIND_START + 0; int const bind_idx_key = SQLITE_BIND_START + 1; YapDatabaseString _extension; MakeYapDatabaseString(&_extension, extensionName); sqlite3_bind_text(statement, bind_idx_extension, _extension.str, _extension.length, SQLITE_STATIC); YapDatabaseString _key; MakeYapDatabaseString(&_key, key); sqlite3_bind_text(statement, bind_idx_key, _key.str, _key.length, SQLITE_STATIC); int status = sqlite3_step(statement); if (status == SQLITE_ROW) { const void *blob = sqlite3_column_blob(statement, column_idx_data); int blobSize = sqlite3_column_bytes(statement, column_idx_data); value = [[NSData alloc] initWithBytes:(void *)blob length:blobSize]; } else if (status == SQLITE_ERROR) { YDBLogError(@"Error executing 'yapGetDataForKeyStatement': %d %s", status, sqlite3_errmsg(connection->db)); } sqlite3_clear_bindings(statement); sqlite3_reset(statement); FreeYapDatabaseString(&_extension); FreeYapDatabaseString(&_key); return value; } //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// #pragma mark Exceptions //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// - (NSException *)mutationDuringEnumerationException { NSString *reason = [NSString stringWithFormat: @"Database <%@: %p> was mutated while being enumerated.", NSStringFromClass([self class]), self]; NSDictionary *userInfo = @{ NSLocalizedRecoverySuggestionErrorKey: @"If you modify the database during enumeration" @" you MUST set the 'stop' parameter of the enumeration block to YES (*stop = YES;)."}; return [NSException exceptionWithName:@"YapDatabaseException" reason:reason userInfo:userInfo]; } @end //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// #pragma mark - //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// @implementation YapDatabaseReadWriteTransaction #pragma mark Transaction Control /** * Under normal circumstances, when a read-write transaction block completes, * the changes are automatically committed. If, however, something goes wrong and * you'd like to abort and discard all changes made within the transaction, * then invoke this method. * * You should generally return (exit the transaction block) after invoking this method. * Any changes made within the the transaction before and after invoking this method will be discarded. * * Invoking this method from within a read-only transaction does nothing. **/ - (void)rollback { rollback = YES; } /** * The YapDatabaseModifiedNotification is posted following a readwrite transaction which made changes. * * These notifications are used in a variety of ways: * - They may be used as a general notification mechanism to detect changes to the database. * - They may be used by extensions to post change information. * For example, YapDatabaseView will post the index changes, which can easily be used to animate a tableView. * - They are integrated into the architecture of long-lived transactions in order to maintain a steady state. * * Thus it is recommended you integrate your own notification information into this existing notification, * as opposed to broadcasting your own separate notification. * * For more information, and code samples, please see the wiki article: * https://github.com/yapstudios/YapDatabase/wiki/YapDatabaseModifiedNotification **/ @synthesize yapDatabaseModifiedNotificationCustomObject = customObjectForNotification; //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// #pragma mark Object & Metadata //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// /** * Sets the object for the given key/collection. * The object is automatically serialized using the database's configured objectSerializer. * * If you pass nil for the object, then this method will remove the row from the database (if it exists). * This method implicitly sets the associated metadata to nil. * * @param object * The object to store in the database. * This object is automatically serialized using the database's configured objectSerializer. * * @param key * The lookup key. * The <collection, key> tuple is used to uniquely identify the row in the database. * This value should not be nil. If a nil key is passed, then this method does nothing. * * @param collection * The lookup collection. * The <collection, key> tuple is used to uniquely identify the row in the database. * If a nil collection is passed, then the collection is implicitly the empty string (@""). **/ - (void)setObject:(id)object forKey:(NSString *)key inCollection:(NSString *)collection { [self setObject:object forKey:key inCollection:collection withMetadata:nil serializedObject:nil serializedMetadata:nil]; } /** * Sets the object & metadata for the given key/collection. * * If you pass nil for the object, then this method will remove the row from the database (if it exists). * * @param object * The object to store in the database. * This object is automatically serialized using the database's configured objectSerializer. * * @param key * The lookup key. * The <collection, key> tuple is used to uniquely identify the row in the database. * This value should not be nil. If a nil key is passed, then this method does nothing. * * @param collection * The lookup collection. * The <collection, key> tuple is used to uniquely identify the row in the database. * If a nil collection is passed, then the collection is implicitly the empty string (@""). * * @param metadata * The metadata to store in the database. * This metadata is automatically serialized using the database's configured metadataSerializer. * The metadata is optional. You can pass nil for the metadata is unneeded. * If non-nil then the metadata is also written to the database (metadata is also persistent). **/ - (void)setObject:(id)object forKey:(NSString *)key inCollection:(NSString *)collection withMetadata:(id)metadata { [self setObject:object forKey:key inCollection:collection withMetadata:metadata serializedObject:nil serializedMetadata:nil]; } /** * Sets the object & metadata for the given key/collection. * * This method allows for a bit of optimization if you happen to already have a serialized version of * the object and/or metadata. For example, if you downloaded an object in serialized form, * and you still have the raw NSData, then you can use this method to skip the serialization step * when storing the object to the database. * * If you pass nil for the object, then this method will remove the row from the database (if it exists). * * @param object * The object to store in the database. * This object is automatically serialized using the database's configured objectSerializer. * * @param key * The lookup key. * The <collection, key> tuple is used to uniquely identify the row in the database. * This value should not be nil. If a nil key is passed, then this method does nothing. * * @param collection * The lookup collection. * The <collection, key> tuple is used to uniquely identify the row in the database. * If a nil collection is passed, then the collection is implicitly the empty string (@""). * * @param metadata * The metadata to store in the database. * This metadata is automatically serialized using the database's configured metadataSerializer. * The metadata is optional. You can pass nil for the metadata is unneeded. * If non-nil then the metadata is also written to the database (metadata is also persistent). * * @param preSerializedObject * This value is optional. * If non-nil then the object serialization step is skipped, and this value is used instead. * It is assumed that preSerializedObject is equal to what we would get if we ran the object through * the database's configured objectSerializer. * * @param preSerializedMetadata * This value is optional. * If non-nil then the metadata serialization step is skipped, and this value is used instead. * It is assumed that preSerializedMetadata is equal to what we would get if we ran the metadata through * the database's configured metadataSerializer. * * The preSerializedObject is only used if object is non-nil. * The preSerializedMetadata is only used if metadata is non-nil. **/ - (void)setObject:(id)object forKey:(NSString *)key inCollection:(NSString *)collection withMetadata:(id)metadata serializedObject:(NSData *)preSerializedObject serializedMetadata:(NSData *)preSerializedMetadata { if (object == nil) { [self removeObjectForKey:key inCollection:collection]; return; } if (key == nil) return; if (collection == nil) collection = @""; if (connection->database->objectPreSanitizer) { object = connection->database->objectPreSanitizer(collection, key, object); if (object == nil) { YDBLogWarn(@"The objectPreSanitizer returned nil for collection(%@) key(%@)", collection, key); [self removeObjectForKey:key inCollection:collection]; return; } } if (metadata && connection->database->metadataPreSanitizer) { metadata = connection->database->metadataPreSanitizer(collection, key, metadata); if (metadata == nil) { YDBLogWarn(@"The metadataPresanitizer returned nil for collection(%@) key(%@)", collection, key); } } // To use SQLITE_STATIC on our data, we use the objc_precise_lifetime attribute. // This ensures the data isn't released until it goes out of scope. __attribute__((objc_precise_lifetime)) NSData *serializedObject = nil; if (preSerializedObject) serializedObject = preSerializedObject; else serializedObject = connection->database->objectSerializer(collection, key, object); __attribute__((objc_precise_lifetime)) NSData *serializedMetadata = nil; if (metadata) { if (preSerializedMetadata) serializedMetadata = preSerializedMetadata; else serializedMetadata = connection->database->metadataSerializer(collection, key, metadata); } BOOL found = NO; int64_t rowid = 0; YapDatabaseString _collection; MakeYapDatabaseString(&_collection, collection); YapDatabaseString _key; MakeYapDatabaseString(&_key, key); if (YES) // fetch rowid for key { sqlite3_stmt *statement = [connection getRowidForKeyStatement]; if (statement == NULL) { FreeYapDatabaseString(&_collection); FreeYapDatabaseString(&_key); return; } // SELECT "rowid" FROM "database2" WHERE "collection" = ? AND "key" = ?; int const column_idx_rowid = SQLITE_COLUMN_START; int const bind_idx_collection = SQLITE_BIND_START + 0; int const bind_idx_key = SQLITE_BIND_START + 1; sqlite3_bind_text(statement, bind_idx_collection, _collection.str, _collection.length, SQLITE_STATIC); sqlite3_bind_text(statement, bind_idx_key, _key.str, _key.length, SQLITE_STATIC); int status = sqlite3_step(statement); if (status == SQLITE_ROW) { rowid = sqlite3_column_int64(statement, column_idx_rowid); found = YES; } else if (status == SQLITE_ERROR) { YDBLogError(@"Error executing 'getRowidForKeyStatement': %d %s, key(%@)", status, sqlite3_errmsg(connection->db), key); } sqlite3_clear_bindings(statement); sqlite3_reset(statement); } BOOL set = YES; YapCollectionKey *cacheKey = [[YapCollectionKey alloc] initWithCollection:collection key:key]; for (YapDatabaseExtensionTransaction *extTransaction in [self orderedExtensions]) { if (found) [extTransaction handleWillUpdateObject:object forCollectionKey:cacheKey withMetadata:metadata rowid:rowid]; else [extTransaction handleWillInsertObject:object forCollectionKey:cacheKey withMetadata:metadata]; } if (found) // update data for key { sqlite3_stmt *statement = [connection updateAllForRowidStatement]; if (statement == NULL) { FreeYapDatabaseString(&_collection); FreeYapDatabaseString(&_key); return; } // UPDATE "database2" SET "data" = ?, "metadata" = ? WHERE "rowid" = ?; int const bind_idx_data = SQLITE_BIND_START + 0; int const bind_idx_metadata = SQLITE_BIND_START + 1; int const bind_idx_rowid = SQLITE_BIND_START + 2; sqlite3_bind_blob(statement, bind_idx_data, serializedObject.bytes, (int)serializedObject.length, SQLITE_STATIC); sqlite3_bind_blob(statement, bind_idx_metadata, serializedMetadata.bytes, (int)serializedMetadata.length, SQLITE_STATIC); sqlite3_bind_int64(statement, bind_idx_rowid, rowid); int status = sqlite3_step(statement); if (status != SQLITE_DONE) { YDBLogError(@"Error executing 'updateAllForRowidStatement': %d %s", status, sqlite3_errmsg(connection->db)); set = NO; } sqlite3_clear_bindings(statement); sqlite3_reset(statement); } else // insert data for key { sqlite3_stmt *statement = [connection insertForRowidStatement]; if (statement == NULL) { FreeYapDatabaseString(&_collection); FreeYapDatabaseString(&_key); return; } // INSERT INTO "database2" ("collection", "key", "data", "metadata") VALUES (?, ?, ?, ?); int const bind_idx_collection = SQLITE_BIND_START + 0; int const bind_idx_key = SQLITE_BIND_START + 1; int const bind_idx_data = SQLITE_BIND_START + 2; int const bind_idx_metadata = SQLITE_BIND_START + 3; sqlite3_bind_text(statement, bind_idx_collection, _collection.str, _collection.length, SQLITE_STATIC); sqlite3_bind_text(statement, bind_idx_key, _key.str, _key.length, SQLITE_STATIC); sqlite3_bind_blob(statement, bind_idx_data, serializedObject.bytes, (int)serializedObject.length, SQLITE_STATIC); sqlite3_bind_blob(statement, bind_idx_metadata, serializedMetadata.bytes, (int)serializedMetadata.length, SQLITE_STATIC); int status = sqlite3_step(statement); if (status == SQLITE_DONE) { rowid = sqlite3_last_insert_rowid(connection->db); } else { YDBLogError(@"Error executing 'insertForRowidStatement': %d %s", status, sqlite3_errmsg(connection->db)); set = NO; } sqlite3_clear_bindings(statement); sqlite3_reset(statement); } FreeYapDatabaseString(&_collection); FreeYapDatabaseString(&_key); if (!set) return; connection->hasDiskChanges = YES; isMutated = YES; // mutation during enumeration protection [connection->keyCache setObject:cacheKey forKey:@(rowid)]; id _object = nil; if (connection->objectPolicy == YapDatabasePolicyContainment) { _object = [YapNull null]; } else if (connection->objectPolicy == YapDatabasePolicyShare) { _object = object; } else // if (connection->objectPolicy == YapDatabasePolicyCopy) { if ([object conformsToProtocol:@protocol(NSCopying)]) _object = [object copy]; else _object = [YapNull null]; } [connection->objectCache setObject:object forKey:cacheKey]; [connection->objectChanges setObject:_object forKey:cacheKey]; if (metadata) { id _metadata = nil; if (connection->metadataPolicy == YapDatabasePolicyContainment) { _metadata = [YapNull null]; } else if (connection->metadataPolicy == YapDatabasePolicyShare) { _metadata = metadata; } else // if (connection->metadataPolicy = YapDatabasePolicyCopy) { if ([metadata conformsToProtocol:@protocol(NSCopying)]) _metadata = [metadata copy]; else _metadata = [YapNull null]; } [connection->metadataCache setObject:metadata forKey:cacheKey]; [connection->metadataChanges setObject:_metadata forKey:cacheKey]; } else { [connection->metadataCache setObject:[YapNull null] forKey:cacheKey]; [connection->metadataChanges setObject:[YapNull null] forKey:cacheKey]; } for (YapDatabaseExtensionTransaction *extTransaction in [self orderedExtensions]) { if (found) [extTransaction handleUpdateObject:object forCollectionKey:cacheKey withMetadata:metadata rowid:rowid]; else [extTransaction handleInsertObject:object forCollectionKey:cacheKey withMetadata:metadata rowid:rowid]; } if (connection->database->objectPostSanitizer) { connection->database->objectPostSanitizer(collection, key, object); } if (metadata && connection->database->metadataPreSanitizer) { connection->database->metadataPostSanitizer(collection, key, metadata); } } /** * If a row with the given key/collection exists, then replaces the object for that row with the new value. * * It only replaces the object. The metadata for the row doesn't change. * If there is no row in the database for the given key/collection then this method does nothing. * * If you pass nil for the object, then this method will remove the row from the database (if it exists). * * @param object * The object to store in the database. * This object is automatically serialized using the database's configured objectSerializer. * * @param key * The lookup key. * The <collection, key> tuple is used to uniquely identify the row in the database. * This value should not be nil. If a nil key is passed, then this method does nothing. * * @param collection * The lookup collection. * The <collection, key> tuple is used to uniquely identify the row in the database. * If a nil collection is passed, then the collection is implicitly the empty string (@""). **/ - (void)replaceObject:(id)object forKey:(NSString *)key inCollection:(NSString *)collection { int64_t rowid = 0; if ([self getRowid:&rowid forKey:key inCollection:collection]) { [self replaceObject:object forKey:key inCollection:collection withRowid:rowid serializedObject:nil]; } } /** * If a row with the given key/collection exists, then replaces the object for that row with the new value. * * It only replaces the object. The metadata for the row doesn't change. * If there is no row in the database for the given key/collection then this method does nothing. * * If you pass nil for the object, then this method will remove the row from the database (if it exists). * * This method allows for a bit of optimization if you happen to already have a serialized version of * the object and/or metadata. For example, if you downloaded an object in serialized form, * and you still have the raw serialized NSData, then you can use this method to skip the serialization step * when storing the object to the database. * * @param object * The object to store in the database. * This object is automatically serialized using the database's configured objectSerializer. * * @param key * The lookup key. * The <collection, key> tuple is used to uniquely identify the row in the database. * This value should not be nil. If a nil key is passed, then this method does nothing. * * @param collection * The lookup collection. * The <collection, key> tuple is used to uniquely identify the row in the database. * If a nil collection is passed, then the collection is implicitly the empty string (@""). * * @param preSerializedObject * This value is optional. * If non-nil then the object serialization step is skipped, and this value is used instead. * It is assumed that preSerializedObject is equal to what we would get if we ran the object through * the database's configured objectSerializer. **/ - (void)replaceObject:(id)object forKey:(NSString *)key inCollection:(NSString *)collection withSerializedObject:(NSData *)preSerializedObject { int64_t rowid = 0; if ([self getRowid:&rowid forKey:key inCollection:collection]) { [self replaceObject:object forKey:key inCollection:collection withRowid:rowid serializedObject:preSerializedObject]; } } /** * Internal replaceObject method that takes a rowid. **/ - (void)replaceObject:(id)object forKey:(NSString *)key inCollection:(NSString *)collection withRowid:(int64_t)rowid serializedObject:(NSData *)preSerializedObject { if (object == nil) { [self removeObjectForKey:key inCollection:collection withRowid:rowid]; return; } NSAssert(key != nil, @"Internal error"); if (collection == nil) collection = @""; if (connection->database->objectPreSanitizer) { object = connection->database->objectPreSanitizer(collection, key, object); if (object == nil) { YDBLogWarn(@"The objectPreSanitizer returned nil for collection(%@) key(%@)", collection, key); [self removeObjectForKey:key inCollection:collection withRowid:rowid]; return; } } YapCollectionKey *cacheKey = [[YapCollectionKey alloc] initWithCollection:collection key:key]; for (YapDatabaseExtensionTransaction *extTransaction in [self orderedExtensions]) { [extTransaction handleWillReplaceObject:object forCollectionKey:cacheKey withRowid:rowid]; } // To use SQLITE_STATIC on our data blob, we use the objc_precise_lifetime attribute. // This ensures the data isn't released until it goes out of scope. __attribute__((objc_precise_lifetime)) NSData *serializedObject = nil; if (preSerializedObject) serializedObject = preSerializedObject; else serializedObject = connection->database->objectSerializer(collection, key, object); sqlite3_stmt *statement = [connection updateObjectForRowidStatement]; if (statement == NULL) return; // UPDATE "database2" SET "data" = ? WHERE "rowid" = ?; int const bind_idx_data = SQLITE_BIND_START + 0; int const bind_idx_rowid = SQLITE_BIND_START + 1; sqlite3_bind_blob(statement, bind_idx_data, serializedObject.bytes, (int)serializedObject.length, SQLITE_STATIC); sqlite3_bind_int64(statement, bind_idx_rowid, rowid); BOOL updated = YES; int status = sqlite3_step(statement); if (status != SQLITE_DONE) { YDBLogError(@"Error executing 'updateObjectForRowidStatement': %d %s", status, sqlite3_errmsg(connection->db)); updated = NO; } sqlite3_clear_bindings(statement); sqlite3_reset(statement); if (!updated) return; connection->hasDiskChanges = YES; isMutated = YES; // mutation during enumeration protection id _object = nil; if (connection->objectPolicy == YapDatabasePolicyContainment) { _object = [YapNull null]; } else if (connection->objectPolicy == YapDatabasePolicyShare) { _object = object; } else // if (connection->objectPolicy = YapDatabasePolicyCopy) { if ([object conformsToProtocol:@protocol(NSCopying)]) _object = [object copy]; else _object = [YapNull null]; } [connection->objectCache setObject:object forKey:cacheKey]; [connection->objectChanges setObject:_object forKey:cacheKey]; for (YapDatabaseExtensionTransaction *extTransaction in [self orderedExtensions]) { [extTransaction handleReplaceObject:object forCollectionKey:cacheKey withRowid:rowid]; } if (connection->database->objectPostSanitizer) { connection->database->objectPostSanitizer(collection, key, object); } } /** * If a row with the given key/collection exists, then replaces the metadata for that row with the new value. * * It only replaces the metadata. The object for the row doesn't change. * If there is no row in the database for the given key/collection then this method does nothing. * * If you pass nil for the metadata, any metadata previously associated with the key/collection is removed. * * @param metadata * The metadata to store in the database. * This metadata is automatically serialized using the database's configured metadataSerializer. * * @param key * The lookup key. * The <collection, key> tuple is used to uniquely identify the row in the database. * This value should not be nil. If a nil key is passed, then this method does nothing. * * @param collection * The lookup collection. * The <collection, key> tuple is used to uniquely identify the row in the database. * If a nil collection is passed, then the collection is implicitly the empty string (@""). **/ - (void)replaceMetadata:(id)metadata forKey:(NSString *)key inCollection:(NSString *)collection { int64_t rowid = 0; if ([self getRowid:&rowid forKey:key inCollection:collection]) { [self replaceMetadata:metadata forKey:key inCollection:collection withRowid:rowid serializedMetadata:nil]; } } /** * If a row with the given key/collection exists, then replaces the metadata for that row with the new value. * * It only replaces the metadata. The object for the row doesn't change. * If there is no row in the database for the given key/collection then this method does nothing. * * If you pass nil for the metadata, any metadata previously associated with the key/collection is removed. * * This method allows for a bit of optimization if you happen to already have a serialized version of * the object and/or metadata. For example, if you downloaded an object in serialized form, * and you still have the raw serialized NSData, then you can use this method to skip the serialization step * when storing the object to the database. * * @param metadata * The metadata to store in the database. * This metadata is automatically serialized using the database's configured metadataSerializer. * * @param key * The lookup key. * The <collection, key> tuple is used to uniquely identify the row in the database. * This value should not be nil. If a nil key is passed, then this method does nothing. * * @param collection * The lookup collection. * The <collection, key> tuple is used to uniquely identify the row in the database. * If a nil collection is passed, then the collection is implicitly the empty string (@""). * * @param preSerializedMetadata * This value is optional. * If non-nil then the metadata serialization step is skipped, and this value is used instead. * It is assumed that preSerializedMetadata is equal to what we would get if we ran the metadata through * the database's configured metadataSerializer. **/ - (void)replaceMetadata:(id)metadata forKey:(NSString *)key inCollection:(NSString *)collection withSerializedMetadata:(NSData *)preSerializedMetadata { int64_t rowid = 0; if ([self getRowid:&rowid forKey:key inCollection:collection]) { [self replaceMetadata:metadata forKey:key inCollection:collection withRowid:rowid serializedMetadata:preSerializedMetadata]; } } /** * Internal replaceMetadata method that takes a rowid. **/ - (void)replaceMetadata:(id)metadata forKey:(NSString *)key inCollection:(NSString *)collection withRowid:(int64_t)rowid serializedMetadata:(NSData *)preSerializedMetadata { NSAssert(key != nil, @"Internal error"); if (collection == nil) collection = @""; if (metadata && connection->database->metadataPreSanitizer) { metadata = connection->database->metadataPreSanitizer(collection, key, metadata); if (metadata == nil) { YDBLogWarn(@"The metadataPreSanitizer returned nil for collection(%@) key(%@)", collection, key); } } // To use SQLITE_STATIC on our data blob, we use the objc_precise_lifetime attribute. // This ensures the data isn't released until it goes out of scope. __attribute__((objc_precise_lifetime)) NSData *serializedMetadata = nil; if (metadata) { if (preSerializedMetadata) serializedMetadata = preSerializedMetadata; else serializedMetadata = connection->database->metadataSerializer(collection, key, metadata); } sqlite3_stmt *statement = [connection updateMetadataForRowidStatement]; if (statement == NULL) return; // UPDATE "database2" SET "metadata" = ? WHERE "rowid" = ?; int const bind_idx_metadata = SQLITE_BIND_START + 0; int const bind_idx_rowid = SQLITE_BIND_START + 1; sqlite3_bind_blob(statement, bind_idx_metadata, serializedMetadata.bytes, (int)serializedMetadata.length, SQLITE_STATIC); sqlite3_bind_int64(statement, bind_idx_rowid, rowid); BOOL updated = YES; YapCollectionKey *cacheKey = [[YapCollectionKey alloc] initWithCollection:collection key:key]; for (YapDatabaseExtensionTransaction *extTransaction in [self orderedExtensions]) { [extTransaction handleWillReplaceMetadata:metadata forCollectionKey:cacheKey withRowid:rowid]; } int status = sqlite3_step(statement); if (status != SQLITE_DONE) { YDBLogError(@"Error executing 'updateMetadataForRowidStatement': %d %s", status, sqlite3_errmsg(connection->db)); updated = NO; } sqlite3_clear_bindings(statement); sqlite3_reset(statement); if (!updated) return; connection->hasDiskChanges = YES; isMutated = YES; // mutation during enumeration protection if (metadata) { id _metadata = nil; if (connection->metadataPolicy == YapDatabasePolicyContainment) { _metadata = [YapNull null]; } else if (connection->metadataPolicy == YapDatabasePolicyShare) { _metadata = metadata; } else // if (connection->metadataPolicy = YapDatabasePolicyCopy) { if ([metadata conformsToProtocol:@protocol(NSCopying)]) _metadata = [metadata copy]; else _metadata = [YapNull null]; } [connection->metadataCache setObject:metadata forKey:cacheKey]; [connection->metadataChanges setObject:_metadata forKey:cacheKey]; } else { [connection->metadataCache setObject:[YapNull null] forKey:cacheKey]; [connection->metadataChanges setObject:[YapNull null] forKey:cacheKey]; } for (YapDatabaseExtensionTransaction *extTransaction in [self orderedExtensions]) { [extTransaction handleReplaceMetadata:metadata forCollectionKey:cacheKey withRowid:rowid]; } if (metadata && connection->database->metadataPostSanitizer) { connection->database->metadataPostSanitizer(collection, key, metadata); } } //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// #pragma mark Touch //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// - (void)touchObjectForKey:(NSString *)key inCollection:(NSString *)collection { if (collection == nil) collection = @""; int64_t rowid = 0; if (![self getRowid:&rowid forKey:key inCollection:collection]) return; YapCollectionKey *cacheKey = [[YapCollectionKey alloc] initWithCollection:collection key:key]; if ([connection->objectChanges objectForKey:cacheKey] == nil) [connection->objectChanges setObject:[YapTouch touch] forKey:cacheKey]; if ([connection->metadataChanges objectForKey:cacheKey] == nil) [connection->metadataChanges setObject:[YapTouch touch] forKey:cacheKey]; for (YapDatabaseExtensionTransaction *extTransaction in [self orderedExtensions]) { [extTransaction handleTouchObjectForCollectionKey:cacheKey withRowid:rowid]; } } - (void)touchMetadataForKey:(NSString *)key inCollection:(NSString *)collection { if (collection == nil) collection = @""; int64_t rowid = 0; if (![self getRowid:&rowid forKey:key inCollection:collection]) return; YapCollectionKey *cacheKey = [[YapCollectionKey alloc] initWithCollection:collection key:key]; if ([connection->metadataChanges objectForKey:cacheKey] == nil) [connection->metadataChanges setObject:[YapTouch touch] forKey:cacheKey]; for (YapDatabaseExtensionTransaction *extTransaction in [self orderedExtensions]) { [extTransaction handleTouchMetadataForCollectionKey:cacheKey withRowid:rowid]; } } //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// #pragma mark Remove //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// - (void)removeObjectForKey:(NSString *)key inCollection:(NSString *)collection withRowid:(int64_t)rowid { if (key == nil) return; if (collection == nil) collection = @""; sqlite3_stmt *statement = [connection removeForRowidStatement]; if (statement == NULL) return; // DELETE FROM "database" WHERE "rowid" = ?; int const bind_idx_rowid = SQLITE_BIND_START; sqlite3_bind_int64(statement, bind_idx_rowid, rowid); BOOL removed = YES; YapCollectionKey *cacheKey = [[YapCollectionKey alloc] initWithCollection:collection key:key]; for (YapDatabaseExtensionTransaction *extTransaction in [self orderedExtensions]) { [extTransaction handleWillRemoveObjectForCollectionKey:cacheKey withRowid:rowid]; } int status = sqlite3_step(statement); if (status != SQLITE_DONE) { YDBLogError(@"Error executing 'removeForRowidStatement': %d %s, key(%@)", status, sqlite3_errmsg(connection->db), key); removed = NO; } sqlite3_clear_bindings(statement); sqlite3_reset(statement); if (!removed) return; connection->hasDiskChanges = YES; isMutated = YES; // mutation during enumeration protection NSNumber *rowidNumber = @(rowid); [connection->keyCache removeObjectForKey:rowidNumber]; [connection->objectCache removeObjectForKey:cacheKey]; [connection->metadataCache removeObjectForKey:cacheKey]; [connection->objectChanges removeObjectForKey:cacheKey]; [connection->metadataChanges removeObjectForKey:cacheKey]; [connection->removedKeys addObject:cacheKey]; [connection->removedRowids addObject:rowidNumber]; for (YapDatabaseExtensionTransaction *extTransaction in [self orderedExtensions]) { [extTransaction handleRemoveObjectForCollectionKey:cacheKey withRowid:rowid]; } } - (void)removeObjectForKey:(NSString *)key inCollection:(NSString *)collection { int64_t rowid = 0; if ([self getRowid:&rowid forKey:key inCollection:collection]) { [self removeObjectForKey:key inCollection:collection withRowid:rowid]; } } - (void)removeObjectsForKeys:(NSArray *)keys inCollection:(NSString *)collection { NSUInteger keysCount = [keys count]; if (keysCount == 0) return; if (keysCount == 1) { [self removeObjectForKey:[keys objectAtIndex:0] inCollection:collection]; return; } if (collection == nil) collection = @""; else collection = [collection copy]; // mutable string protection NSMutableArray *foundKeys = nil; NSMutableArray *foundRowids = nil; // Sqlite has an upper bound on the number of host parameters that may be used in a single query. // We need to watch out for this in case a large array of keys is passed. NSUInteger maxHostParams = (NSUInteger) sqlite3_limit(connection->db, SQLITE_LIMIT_VARIABLE_NUMBER, -1); // Loop over the keys, and remove them in big batches. YapDatabaseString _collection; MakeYapDatabaseString(&_collection, collection); NSUInteger keysIndex = 0; do { NSUInteger left = keysCount - keysIndex; NSUInteger numKeyParams = MIN(left, (maxHostParams-1)); // minus 1 for collectionParam if (foundKeys == nil) { foundKeys = [NSMutableArray arrayWithCapacity:numKeyParams]; foundRowids = [NSMutableArray arrayWithCapacity:numKeyParams]; } else { [foundKeys removeAllObjects]; [foundRowids removeAllObjects]; } // Find rowids for keys if (YES) { // SELECT "rowid", "key" FROM "database2" WHERE "collection" = ? AND "key" IN (?, ?, ...); int const column_idx_rowid = SQLITE_COLUMN_START + 0; int const column_idx_key = SQLITE_COLUMN_START + 1; NSUInteger capacity = 100 + (numKeyParams * 3); NSMutableString *query = [NSMutableString stringWithCapacity:capacity]; [query appendString: @"SELECT \"rowid\", \"key\" FROM \"database2\" WHERE \"collection\" = ? AND \"key\" IN ("]; NSUInteger i; for (i = 0; i < numKeyParams; i++) { if (i == 0) [query appendString:@"?"]; else [query appendString:@", ?"]; } [query appendString:@");"]; sqlite3_stmt *statement; int status = sqlite3_prepare_v2(connection->db, [query UTF8String], -1, &statement, NULL); if (status != SQLITE_OK) { YDBLogError(@"Error creating 'removeKeys:inCollection:' statement (A): %d %s", status, sqlite3_errmsg(connection->db)); FreeYapDatabaseString(&_collection); return; } sqlite3_bind_text(statement, SQLITE_BIND_START, _collection.str, _collection.length, SQLITE_STATIC); for (i = 0; i < numKeyParams; i++) { NSString *key = [keys objectAtIndex:(keysIndex + i)]; sqlite3_bind_text(statement, (int)(SQLITE_BIND_START + 1 + i), [key UTF8String], -1, SQLITE_TRANSIENT); } while ((status = sqlite3_step(statement)) == SQLITE_ROW) { int64_t rowid = sqlite3_column_int64(statement, column_idx_rowid); const unsigned char *text = sqlite3_column_text(statement, column_idx_key); int textSize = sqlite3_column_bytes(statement, column_idx_key); NSString *key = [[NSString alloc] initWithBytes:text length:textSize encoding:NSUTF8StringEncoding]; [foundKeys addObject:key]; [foundRowids addObject:@(rowid)]; } if (status != SQLITE_DONE) { YDBLogError(@"Error executing 'removeKeys:inCollection:' statement (A): %d %s", status, sqlite3_errmsg(connection->db)); } sqlite3_finalize(statement); statement = NULL; } // Now remove all the matching rows NSUInteger foundCount = [foundRowids count]; if (foundCount > 0) { // DELETE FROM "database2" WHERE "rowid" in (?, ?, ...); NSUInteger capacity = 50 + (foundCount * 3); NSMutableString *query = [NSMutableString stringWithCapacity:capacity]; [query appendString:@"DELETE FROM \"database2\" WHERE \"rowid\" IN ("]; NSUInteger i; for (i = 0; i < foundCount; i++) { if (i == 0) [query appendString:@"?"]; else [query appendString:@", ?"]; } [query appendString:@");"]; sqlite3_stmt *statement; int status = sqlite3_prepare_v2(connection->db, [query UTF8String], -1, &statement, NULL); if (status != SQLITE_OK) { YDBLogError(@"Error creating 'removeKeys:inCollection:' statement (B): %d %s", status, sqlite3_errmsg(connection->db)); return; } for (i = 0; i < foundCount; i++) { int64_t rowid = [[foundRowids objectAtIndex:i] longLongValue]; sqlite3_bind_int64(statement, (int)(SQLITE_BIND_START + i), rowid); } for (YapDatabaseExtensionTransaction *extTransaction in [self orderedExtensions]) { [extTransaction handleWillRemoveObjectsForKeys:foundKeys inCollection:collection withRowids:foundRowids]; } status = sqlite3_step(statement); if (status != SQLITE_DONE) { YDBLogError(@"Error executing 'removeKeys:inCollection:' statement (B): %d %s", status, sqlite3_errmsg(connection->db)); } sqlite3_finalize(statement); statement = NULL; connection->hasDiskChanges = YES; isMutated = YES; // mutation during enumeration protection [connection->keyCache removeObjectsForKeys:foundRowids]; [connection->removedRowids addObjectsFromArray:foundRowids]; for (NSString *key in foundKeys) { YapCollectionKey *cacheKey = [[YapCollectionKey alloc] initWithCollection:collection key:key]; [connection->objectCache removeObjectForKey:cacheKey]; [connection->metadataCache removeObjectForKey:cacheKey]; [connection->objectChanges removeObjectForKey:cacheKey]; [connection->metadataChanges removeObjectForKey:cacheKey]; [connection->removedKeys addObject:cacheKey]; } for (YapDatabaseExtensionTransaction *extTransaction in [self orderedExtensions]) { [extTransaction handleRemoveObjectsForKeys:foundKeys inCollection:collection withRowids:foundRowids]; } } // Move on to the next batch (if there's more) keysIndex += numKeyParams; } while (keysIndex < keysCount); FreeYapDatabaseString(&_collection); } - (void)removeAllObjectsInCollection:(NSString *)collection { if (collection == nil) collection = @""; else collection = [collection copy]; // mutable string protection // Purge the caches and changesets NSMutableArray *toRemove = [NSMutableArray array]; { // keyCache [connection->keyCache enumerateKeysAndObjectsWithBlock:^(id key, id obj, BOOL __unused *stop) { __unsafe_unretained NSNumber *rowidNumber = (NSNumber *)key; __unsafe_unretained YapCollectionKey *collectionKey = (YapCollectionKey *)obj; if ([collectionKey.collection isEqualToString:collection]) { [toRemove addObject:rowidNumber]; } }]; [connection->keyCache removeObjectsForKeys:toRemove]; [toRemove removeAllObjects]; } { // objectCache [connection->objectCache enumerateKeysWithBlock:^(id key, BOOL __unused *stop) { __unsafe_unretained YapCollectionKey *cacheKey = (YapCollectionKey *)key; if ([cacheKey.collection isEqualToString:collection]) { [toRemove addObject:cacheKey]; } }]; [connection->objectCache removeObjectsForKeys:toRemove]; [toRemove removeAllObjects]; } { // objectChanges for (id key in [connection->objectChanges keyEnumerator]) { __unsafe_unretained YapCollectionKey *cacheKey = (YapCollectionKey *)key; if ([cacheKey.collection isEqualToString:collection]) { [toRemove addObject:cacheKey]; } } [connection->objectChanges removeObjectsForKeys:toRemove]; [toRemove removeAllObjects]; } { // metadataCache [connection->metadataCache enumerateKeysWithBlock:^(id key, BOOL __unused *stop) { __unsafe_unretained YapCollectionKey *cacheKey = (YapCollectionKey *)key; if ([cacheKey.collection isEqualToString:collection]) { [toRemove addObject:cacheKey]; } }]; [connection->metadataCache removeObjectsForKeys:toRemove]; [toRemove removeAllObjects]; } { // metadataChanges for (id key in [connection->metadataChanges keyEnumerator]) { __unsafe_unretained YapCollectionKey *cacheKey = (YapCollectionKey *)key; if ([cacheKey.collection isEqualToString:collection]) { [toRemove addObject:cacheKey]; } } [connection->metadataChanges removeObjectsForKeys:toRemove]; } [connection->removedCollections addObject:collection]; // If there are no active extensions we can take a shortcut if ([[self extensions] count] == 0) { sqlite3_stmt *statement = [connection removeCollectionStatement]; if (statement == NULL) return; // DELETE FROM "database2" WHERE "collection" = ?; int const bind_idx_collection = SQLITE_BIND_START; YapDatabaseString _collection; MakeYapDatabaseString(&_collection, collection); sqlite3_bind_text(statement, bind_idx_collection, _collection.str, _collection.length, SQLITE_STATIC); int status = sqlite3_step(statement); if (status != SQLITE_DONE) { YDBLogError(@"Error executing 'removeCollectionStatement': %d %s, collection(%@)", status, sqlite3_errmsg(connection->db), collection); } sqlite3_clear_bindings(statement); sqlite3_reset(statement); FreeYapDatabaseString(&_collection); connection->hasDiskChanges = YES; isMutated = YES; // mutation during enumeration protection return; } // end shortcut NSUInteger left = [self numberOfKeysInCollection:collection]; NSMutableArray *foundKeys = nil; NSMutableArray *foundRowids = nil; // Sqlite has an upper bound on the number of host parameters that may be used in a single query. // We need to watch out for this in case a large array of keys is passed. NSUInteger maxHostParams = (NSUInteger) sqlite3_limit(connection->db, SQLITE_LIMIT_VARIABLE_NUMBER, -1); // Loop over the keys, and remove them in big batches. YapDatabaseString _collection; MakeYapDatabaseString(&_collection, collection); do { NSUInteger numKeyParams = MIN(left, maxHostParams-1); // minus 1 for collectionParam if (foundKeys == nil) { foundKeys = [NSMutableArray arrayWithCapacity:numKeyParams]; foundRowids = [NSMutableArray arrayWithCapacity:numKeyParams]; } else { [foundKeys removeAllObjects]; [foundRowids removeAllObjects]; } NSUInteger foundCount = 0; // Find rowids for keys if (YES) { sqlite3_stmt *statement = [connection enumerateKeysInCollectionStatement]; if (statement == NULL) { FreeYapDatabaseString(&_collection); return; } // SELECT "rowid", "key" FROM "database2" WHERE "collection" = ?; int const column_idx_rowid = SQLITE_COLUMN_START + 0; int const column_idx_key = SQLITE_COLUMN_START + 1; int const bind_idx_collection = SQLITE_BIND_START; sqlite3_bind_text(statement, bind_idx_collection, _collection.str, _collection.length, SQLITE_STATIC); int status; while ((status = sqlite3_step(statement)) == SQLITE_ROW) { int64_t rowid = sqlite3_column_int64(statement, column_idx_rowid); const unsigned char *text = sqlite3_column_text(statement, column_idx_key); int textSize = sqlite3_column_bytes(statement, column_idx_key); NSString *key = [[NSString alloc] initWithBytes:text length:textSize encoding:NSUTF8StringEncoding]; [foundKeys addObject:key]; [foundRowids addObject:@(rowid)]; if (++foundCount >= numKeyParams) { break; } } if ((foundCount < numKeyParams) && (status != SQLITE_DONE)) { YDBLogError(@"%@ - sqlite_step error: %d %s", THIS_METHOD, status, sqlite3_errmsg(connection->db)); } sqlite3_clear_bindings(statement); sqlite3_reset(statement); } // Now remove all the matching rows if (foundCount > 0) { // DELETE FROM "database2" WHERE "rowid" in (?, ?, ...); NSUInteger capacity = 50 + (foundCount * 3); NSMutableString *query = [NSMutableString stringWithCapacity:capacity]; [query appendString:@"DELETE FROM \"database2\" WHERE \"rowid\" IN ("]; NSUInteger i; for (i = 0; i < foundCount; i++) { if (i == 0) [query appendString:@"?"]; else [query appendString:@", ?"]; } [query appendString:@");"]; sqlite3_stmt *statement; int status = sqlite3_prepare_v2(connection->db, [query UTF8String], -1, &statement, NULL); if (status != SQLITE_OK) { YDBLogError(@"Error creating 'removeAllObjectsInCollection:' statement: %d %s", status, sqlite3_errmsg(connection->db)); FreeYapDatabaseString(&_collection); return; } for (i = 0; i < foundCount; i++) { int64_t rowid = [[foundRowids objectAtIndex:i] longLongValue]; sqlite3_bind_int64(statement, (int)(SQLITE_BIND_START + i), rowid); } for (YapDatabaseExtensionTransaction *extTransaction in [self orderedExtensions]) { [extTransaction handleWillRemoveObjectsForKeys:foundKeys inCollection:collection withRowids:foundRowids]; } status = sqlite3_step(statement); if (status != SQLITE_DONE) { YDBLogError(@"Error executing 'removeAllObjectsInCollection:' statement: %d %s", status, sqlite3_errmsg(connection->db)); } sqlite3_finalize(statement); statement = NULL; connection->hasDiskChanges = YES; isMutated = YES; // mutation during enumeration protection [connection->removedRowids addObjectsFromArray:foundRowids]; for (YapDatabaseExtensionTransaction *extTransaction in [self orderedExtensions]) { [extTransaction handleRemoveObjectsForKeys:foundKeys inCollection:collection withRowids:foundRowids]; } } // Move on to the next batch (if there's more) left -= foundCount; } while((left > 0) && ([foundKeys count] > 0)); FreeYapDatabaseString(&_collection); } - (void)removeAllObjectsInAllCollections { sqlite3_stmt *statement = [connection removeAllStatement]; if (statement == NULL) return; for (YapDatabaseExtensionTransaction *extTransaction in [self orderedExtensions]) { [extTransaction handleWillRemoveAllObjectsInAllCollections]; } int status = sqlite3_step(statement); if (status != SQLITE_DONE) { YDBLogError(@"Error executing 'removeAllStatement': %d %s", status, sqlite3_errmsg(connection->db)); } sqlite3_reset(statement); connection->hasDiskChanges = YES; isMutated = YES; // mutation during enumeration protection [connection->keyCache removeAllObjects]; [connection->objectCache removeAllObjects]; [connection->metadataCache removeAllObjects]; [connection->objectChanges removeAllObjects]; [connection->metadataChanges removeAllObjects]; [connection->removedKeys removeAllObjects]; [connection->removedCollections removeAllObjects]; [connection->removedRowids removeAllObjects]; connection->allKeysRemoved = YES; for (YapDatabaseExtensionTransaction *extTransaction in [self orderedExtensions]) { [extTransaction handleRemoveAllObjectsInAllCollections]; } } //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// #pragma mark Extensions //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// - (void)addRegisteredExtensionTransaction:(YapDatabaseExtensionTransaction *)extTransaction withName:(NSString *)extName { // This method is INTERNAL if (extensions == nil) extensions = [[NSMutableDictionary alloc] init]; [extensions setObject:extTransaction forKey:extName]; } - (void)removeRegisteredExtensionTransactionWithName:(NSString *)extName { // This method is INTERNAL [extensions removeObjectForKey:extName]; } //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// #pragma mark Yap2 Table //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// - (void)setBoolValue:(BOOL)value forKey:(NSString *)key extension:(NSString *)extensionName { [self setIntValue:(value ? 1 : 0) forKey:key extension:extensionName]; } - (void)setIntValue:(int)value forKey:(NSString *)key extension:(NSString *)extensionName { if (extensionName == nil) extensionName = @""; sqlite3_stmt *statement = [connection yapSetDataForKeyStatement]; if (statement == NULL) return; // INSERT OR REPLACE INTO "yap2" ("extension", "key", "data") VALUES (?, ?, ?); int const bind_idx_extension = SQLITE_BIND_START + 0; int const bind_idx_key = SQLITE_BIND_START + 1; int const bind_idx_data = SQLITE_BIND_START + 2; YapDatabaseString _extension; MakeYapDatabaseString(&_extension, extensionName); sqlite3_bind_text(statement, bind_idx_extension, _extension.str, _extension.length, SQLITE_STATIC); YapDatabaseString _key; MakeYapDatabaseString(&_key, key); sqlite3_bind_text(statement, bind_idx_key, _key.str, _key.length, SQLITE_STATIC); sqlite3_bind_int(statement, bind_idx_data, value); int status = sqlite3_step(statement); if (status == SQLITE_DONE) { connection->hasDiskChanges = YES; } else { YDBLogError(@"Error executing 'yapSetDataForKeyStatement': %d %s", status, sqlite3_errmsg(connection->db)); } sqlite3_clear_bindings(statement); sqlite3_reset(statement); FreeYapDatabaseString(&_extension); FreeYapDatabaseString(&_key); } - (void)setDoubleValue:(double)value forKey:(NSString *)key extension:(NSString *)extensionName { if (extensionName == nil) extensionName = @""; sqlite3_stmt *statement = [connection yapSetDataForKeyStatement]; if (statement == NULL) return; // INSERT OR REPLACE INTO "yap2" ("extension", "key", "data") VALUES (?, ?, ?); int const bind_idx_extension = SQLITE_BIND_START + 0; int const bind_idx_key = SQLITE_BIND_START + 1; int const bind_idx_data = SQLITE_BIND_START + 2; YapDatabaseString _extension; MakeYapDatabaseString(&_extension, extensionName); sqlite3_bind_text(statement, bind_idx_extension, _extension.str, _extension.length, SQLITE_STATIC); YapDatabaseString _key; MakeYapDatabaseString(&_key, key); sqlite3_bind_text(statement, bind_idx_key, _key.str, _key.length, SQLITE_STATIC); sqlite3_bind_double(statement, bind_idx_data, value); int status = sqlite3_step(statement); if (status == SQLITE_DONE) { connection->hasDiskChanges = YES; } else { YDBLogError(@"Error executing 'yapSetDataForKeyStatement': %d %s", status, sqlite3_errmsg(connection->db)); } sqlite3_clear_bindings(statement); sqlite3_reset(statement); FreeYapDatabaseString(&_extension); FreeYapDatabaseString(&_key); } - (void)setStringValue:(NSString *)value forKey:(NSString *)key extension:(NSString *)extensionName { if (extensionName == nil) extensionName = @""; sqlite3_stmt *statement = [connection yapSetDataForKeyStatement]; if (statement == NULL) return; // INSERT OR REPLACE INTO "yap2" ("extension", "key", "data") VALUES (?, ?, ?); int const bind_idx_extension = SQLITE_BIND_START + 0; int const bind_idx_key = SQLITE_BIND_START + 1; int const bind_idx_data = SQLITE_BIND_START + 2; YapDatabaseString _extension; MakeYapDatabaseString(&_extension, extensionName); sqlite3_bind_text(statement, bind_idx_extension, _extension.str, _extension.length, SQLITE_STATIC); YapDatabaseString _key; MakeYapDatabaseString(&_key, key); sqlite3_bind_text(statement, bind_idx_key, _key.str, _key.length, SQLITE_STATIC); YapDatabaseString _value; MakeYapDatabaseString(&_value, value); sqlite3_bind_text(statement, bind_idx_data, _value.str, _value.length, SQLITE_STATIC); int status = sqlite3_step(statement); if (status == SQLITE_DONE) { connection->hasDiskChanges = YES; } else { YDBLogError(@"Error executing 'yapSetDataForKeyStatement': %d %s", status, sqlite3_errmsg(connection->db)); } sqlite3_clear_bindings(statement); sqlite3_reset(statement); FreeYapDatabaseString(&_extension); FreeYapDatabaseString(&_key); FreeYapDatabaseString(&_value); } - (void)setDataValue:(NSData *)value forKey:(NSString *)key extension:(NSString *)extensionName { if (extensionName == nil) extensionName = @""; sqlite3_stmt *statement = [connection yapSetDataForKeyStatement]; if (statement == NULL) return; // INSERT OR REPLACE INTO "yap2" ("extension", "key", "data") VALUES (?, ?, ?); int const bind_idx_extension = SQLITE_BIND_START + 0; int const bind_idx_key = SQLITE_BIND_START + 1; int const bind_idx_data = SQLITE_BIND_START + 2; YapDatabaseString _extension; MakeYapDatabaseString(&_extension, extensionName); sqlite3_bind_text(statement, bind_idx_extension, _extension.str, _extension.length, SQLITE_STATIC); YapDatabaseString _key; MakeYapDatabaseString(&_key, key); sqlite3_bind_text(statement, bind_idx_key, _key.str, _key.length, SQLITE_STATIC); __attribute__((objc_precise_lifetime)) NSData *data = value; sqlite3_bind_blob(statement, bind_idx_data, data.bytes, (int)data.length, SQLITE_STATIC); int status = sqlite3_step(statement); if (status == SQLITE_DONE) { connection->hasDiskChanges = YES; } else { YDBLogError(@"Error executing 'yapSetDataForKeyStatement': %d %s", status, sqlite3_errmsg(connection->db)); } sqlite3_clear_bindings(statement); sqlite3_reset(statement); FreeYapDatabaseString(&_extension); FreeYapDatabaseString(&_key); } - (void)removeValueForKey:(NSString *)key extension:(NSString *)extensionName { // Be careful with this statement. // // The snapshot value is in the yap table, and uses an empty string for the extensionName. // The snapshot value is critical to the underlying architecture of the system. // Removing it could cripple the system. NSAssert(key != nil, @"Invalid key!"); NSAssert(extensionName != nil, @"Invalid extensionName!"); sqlite3_stmt *statement = [connection yapRemoveForKeyStatement]; if (statement == NULL) return; // DELETE FROM "yap2" WHERE "extension" = ? AND "key" = ?; int const bind_idx_extension = SQLITE_BIND_START + 0; int const bind_idx_key = SQLITE_BIND_START + 1; YapDatabaseString _extension; MakeYapDatabaseString(&_extension, extensionName); sqlite3_bind_text(statement, bind_idx_extension, _extension.str, _extension.length, SQLITE_STATIC); YapDatabaseString _key; MakeYapDatabaseString(&_key, key); sqlite3_bind_text(statement, bind_idx_key, _key.str, _key.length, SQLITE_STATIC); int status = sqlite3_step(statement); if (status == SQLITE_DONE) { connection->hasDiskChanges = YES; } else { YDBLogError(@"Error executing 'yapRemoveForKeyStatement': %d %s, extension(%@)", status, sqlite3_errmsg(connection->db), extensionName); } sqlite3_clear_bindings(statement); sqlite3_reset(statement); FreeYapDatabaseString(&_extension); FreeYapDatabaseString(&_key); } - (void)removeAllValuesForExtension:(NSString *)extensionName { // Be careful with this statement. // // The snapshot value is in the yap table, and uses an empty string for the extensionName. // The snapshot value is critical to the underlying architecture of the system. // Removing it could cripple the system. NSAssert(extensionName != nil, @"Invalid extensionName!"); sqlite3_stmt *statement = [connection yapRemoveExtensionStatement]; if (statement == NULL) return; // DELETE FROM "yap2" WHERE "extension" = ?; int const bind_idx_extension = SQLITE_BIND_START; YapDatabaseString _extension; MakeYapDatabaseString(&_extension, extensionName); sqlite3_bind_text(statement, bind_idx_extension, _extension.str, _extension.length, SQLITE_STATIC); int status = sqlite3_step(statement); if (status == SQLITE_DONE) { connection->hasDiskChanges = YES; } else { YDBLogError(@"Error executing 'yapRemoveExtensionStatement': %d %s, extension(%@)", status, sqlite3_errmsg(connection->db), extensionName); } sqlite3_clear_bindings(statement); sqlite3_reset(statement); FreeYapDatabaseString(&_extension); } @end
{ "content_hash": "5c436ac3020f595500561f640dbf5c85", "timestamp": "", "source": "github", "line_count": 5866, "max_line_length": 124, "avg_line_length": 34.140811455847256, "alnum_prop": 0.6856244070504819, "repo_name": "ramoslin02/YapDatabase", "id": "46b20dc749359a94e1b9340a329b55426365a8c7", "size": "200270", "binary": false, "copies": "4", "ref": "refs/heads/master", "path": "YapDatabase/YapDatabaseTransaction.m", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "C", "bytes": "30390" }, { "name": "C++", "bytes": "797" }, { "name": "Objective-C", "bytes": "4289736" }, { "name": "Objective-C++", "bytes": "7986" }, { "name": "Ruby", "bytes": "1645" }, { "name": "Shell", "bytes": "14913" }, { "name": "Swift", "bytes": "14832" } ], "symlink_target": "" }
import Ember from 'ember'; var require = Ember.__loader.require; var OutletKeyword = require('ember-htmlbars/keywords/outlet').default; var ViewNodeManager = require('ember-htmlbars/node-managers/view-node-manager').default; export function patchOutletKeyword() { var baseRender = OutletKeyword.render; OutletKeyword.render = function (renderNode, env, scope, params, hash, template, inverse, visitor) { let state = renderNode.getState(); let owner = env.owner; let parentView = env.view; let outletState = state.outletState; let toRender = outletState.render; let componentName = toRender.name; let Component = owner._lookupFactory(`component:${componentName}`); let layout = owner.lookup(`template:components/${componentName}`); if (!(Component || layout)) { //routable component or template not found, use base implementation return baseRender(...arguments); } let options = { component: Component || Ember.Component.create(), layout: layout }; let attrs = { model: Ember.get(toRender.controller, 'model'), target: Ember.get(toRender.controller, 'target') }; if (state.manager) { state.manager.destroy(); state.manager = null; } let nodeManager = ViewNodeManager.create(renderNode, env, attrs, options, parentView, null, null, template); state.manager = nodeManager; nodeManager.render(env, hash, visitor); }; }
{ "content_hash": "5133d87ca6ff63a00de922301beaddcb", "timestamp": "", "source": "github", "line_count": 43, "max_line_length": 112, "avg_line_length": 33.76744186046512, "alnum_prop": 0.6873278236914601, "repo_name": "mdehoog/ember-routable-components-shim", "id": "9a9f45104ffdda50785e0fd0ba6cc38edfb87aee", "size": "1452", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "addon/outlet.js", "mode": "33188", "license": "mit", "language": [ { "name": "HTML", "bytes": "1789" }, { "name": "JavaScript", "bytes": "8304" } ], "symlink_target": "" }
Raytracer in haskell ## Goal Implementing a haskell raytracer which can render physically believable pictures. The 'pbrt' of haskell ( https://github.com/mmp ). ## TODO - [ ] Absract stuff into modules. - [ ] Use lua to define scene(s), camera's, objects, shaders, texture (image and mapping), position and scale (STR matrices). - [ ] Use lua, multiple scenes and something like ffmpeg to create animation. - [ ] Make asynchreous processing using the lua scripting -possible- default. Use the Surface datatype with only funtions. Add state using (custom) constructor function. Static state by inserting partially evaluated functions. Like colorplain :: Color -> Hitpoint -> Color the Surface takes a Hitpoint -> Color so suplly the plain color. -Dynamic state by using a ST/Ref or something. Most of the time a Configuration as SRT-matrix as state is enough.- Dynamic state is not needed. Add SRT to init and make lua plumbing. (With an object keeping track of STR. Make STR setting (even if null) happen before setting shaders etc.) Actual contructor can be in haskell taking some long record. ![Diffuse balls](/examples/images/diffuse_balls.png) Example using a point light: ![Diffuse balls pointlight](/examples/images/diffuse_balls_pointlight.png) Example using a point light and the reflection shader with a blue teint: ![Reflection](/examples/images/reflection.png) Example with sheen (schlick approximation): ![Sheen](/examples/images/schlick_sheen.png) Example with Schlick- (yellow ivory) and SchlickMetal-shader (gold): ![Gold](/examples/images/yellow_ivory_vs_gold.png)
{ "content_hash": "b7aade733c5d5d2408b0dbccd733e614", "timestamp": "", "source": "github", "line_count": 33, "max_line_length": 609, "avg_line_length": 48.333333333333336, "alnum_prop": 0.768025078369906, "repo_name": "wouteroostervld/snell", "id": "5ec3b5bcbb2cfecd9934a791aafb3015416796f0", "size": "1604", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "README.md", "mode": "33188", "license": "mit", "language": [ { "name": "Haskell", "bytes": "10979" } ], "symlink_target": "" }
<?php namespace ZendTest\Http\Header; use Zend\Http\Header\IfModifiedSince; class IfModifiedSinceTest extends \PHPUnit_Framework_TestCase { public function testIfModifiedSinceFromStringCreatesValidIfModifiedSinceHeader() { $ifModifiedSinceHeader = IfModifiedSince::fromString('If-Modified-Since: Sun, 06 Nov 1994 08:49:37 GMT'); $this->assertInstanceOf('Zend\Http\Header\HeaderInterface', $ifModifiedSinceHeader); $this->assertInstanceOf('Zend\Http\Header\IfModifiedSince', $ifModifiedSinceHeader); } public function testIfModifiedSinceGetFieldNameReturnsHeaderName() { $ifModifiedSinceHeader = new IfModifiedSince(); $this->assertEquals('If-Modified-Since', $ifModifiedSinceHeader->getFieldName()); } public function testIfModifiedSinceGetFieldValueReturnsProperValue() { $ifModifiedSinceHeader = new IfModifiedSince(); $ifModifiedSinceHeader->setDate('Sun, 06 Nov 1994 08:49:37 GMT'); $this->assertEquals('Sun, 06 Nov 1994 08:49:37 GMT', $ifModifiedSinceHeader->getFieldValue()); } public function testIfModifiedSinceToStringReturnsHeaderFormattedString() { $ifModifiedSinceHeader = new IfModifiedSince(); $ifModifiedSinceHeader->setDate('Sun, 06 Nov 1994 08:49:37 GMT'); $this->assertEquals('If-Modified-Since: Sun, 06 Nov 1994 08:49:37 GMT', $ifModifiedSinceHeader->toString()); } /** * Implementation specific tests are covered by DateTest * @see ZendTest\Http\Header\DateTest */ /** * @see http://en.wikipedia.org/wiki/HTTP_response_splitting * @group ZF2015-04 * @expectedException Zend\Http\Header\Exception\InvalidArgumentException */ public function testPreventsCRLFAttackViaFromString() { $header = IfModifiedSince::fromString( "If-Modified-Since: Sun, 06 Nov 1994 08:49:37 GMT\r\n\r\nevilContent" ); } }
{ "content_hash": "b673f5c80a1f8e509a1a0481a6a6ed5b", "timestamp": "", "source": "github", "line_count": 53, "max_line_length": 116, "avg_line_length": 36.679245283018865, "alnum_prop": 0.7052469135802469, "repo_name": "malinink/zend-http", "id": "8a9cf0514995eb90ac9e83aa36157bb44bf22d91", "size": "2246", "binary": false, "copies": "7", "ref": "refs/heads/master", "path": "test/Header/IfModifiedSinceTest.php", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "PHP", "bytes": "795200" } ], "symlink_target": "" }
package com.reason.lang.core.psi; import com.intellij.psi.impl.source.tree.*; import com.intellij.psi.tree.*; import org.jetbrains.annotations.*; public class PsiDefaultValue extends CompositePsiElement { public PsiDefaultValue(@NotNull IElementType elementType) { super(elementType); } @Override public @NotNull String toString() { return "Default value"; } }
{ "content_hash": "fae0fe6a2e69287ac69c5d1fe14d0ac6", "timestamp": "", "source": "github", "line_count": 16, "max_line_length": 63, "avg_line_length": 24.9375, "alnum_prop": 0.7167919799498746, "repo_name": "reasonml-editor/reasonml-idea-plugin", "id": "1555812d1f15f5f856eb0eceb67c0f57109f7618", "size": "399", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/com/reason/lang/core/psi/PsiDefaultValue.java", "mode": "33188", "license": "mit", "language": [ { "name": "HTML", "bytes": "133" }, { "name": "Java", "bytes": "1219386" }, { "name": "Lex", "bytes": "18748" }, { "name": "OCaml", "bytes": "17262" }, { "name": "Reason", "bytes": "1296" } ], "symlink_target": "" }
/// Deserialization infrastructure for tflite. Provides functionality /// to go from a serialized tflite model in flatbuffer format to an /// interpreter. /// #ifndef TENSORFLOW_LITE_MODEL_H_ #define TENSORFLOW_LITE_MODEL_H_ #include <memory> #include "tensorflow/lite/c/c_api_internal.h" #include "tensorflow/lite/core/api/error_reporter.h" #include "tensorflow/lite/core/api/op_resolver.h" #include "tensorflow/lite/interpreter.h" #include "tensorflow/lite/mutable_op_resolver.h" #include "tensorflow/lite/schema/schema_generated.h" namespace tflite { /// Abstract interface that verifies whether a given model is legit. /// It facilitates the use-case to verify and build a model without loading it /// twice. class TfLiteVerifier { public: /// Returns true if the model is legit. virtual bool Verify(const char* data, int length, ErrorReporter* reporter) = 0; virtual ~TfLiteVerifier() {} }; /// An RAII object that represents a read-only tflite model, copied from disk, /// or mmapped. This uses flatbuffers as the serialization format. /// /// NOTE: The current API requires that a FlatBufferModel instance be kept alive /// by the client as long as it is in use by any dependent Interpreter /// instances. /// <pre><code> /// using namespace tflite; /// StderrReporter error_reporter; /// auto model = FlatBufferModel::BuildFromFile("interesting_model.tflite", /// &error_reporter); /// MyOpResolver resolver; // You need to subclass OpResolver to provide /// // implementations. /// InterpreterBuilder builder(*model, resolver); /// std::unique_ptr<Interpreter> interpreter; /// if(builder(&interpreter) == kTfLiteOk) { /// .. run model inference with interpreter /// } /// </code></pre> /// /// OpResolver must be defined to provide your kernel implementations to the /// interpreter. This is environment specific and may consist of just the /// builtin ops, or some custom operators you defined to extend tflite. class FlatBufferModel { public: /// Builds a model based on a file. /// Caller retains ownership of `error_reporter` and must ensure its lifetime /// is longer than the FlatBufferModel instance. /// Returns a nullptr in case of failure. static std::unique_ptr<FlatBufferModel> BuildFromFile( const char* filename, ErrorReporter* error_reporter = DefaultErrorReporter()); /// Verifies whether the content of the file is legit, then builds a model /// based on the file. /// The extra_verifier argument is an additional optional verifier for the /// file contents. By default, we always check with tflite::VerifyModelBuffer. /// If extra_verifier is supplied, the file contents is also checked against /// the extra_verifier after the check against tflite::VerifyModelBuilder. /// Caller retains ownership of `error_reporter` and must ensure its lifetime /// is longer than the FlatBufferModel instance. /// Returns a nullptr in case of failure. static std::unique_ptr<FlatBufferModel> VerifyAndBuildFromFile( const char* filename, TfLiteVerifier* extra_verifier = nullptr, ErrorReporter* error_reporter = DefaultErrorReporter()); /// Builds a model based on a pre-loaded flatbuffer. /// Caller retains ownership of the buffer and should keep it alive until /// the returned object is destroyed. Caller also retains ownership of /// `error_reporter` and must ensure its lifetime is longer than the /// FlatBufferModel instance. /// Returns a nullptr in case of failure. /// NOTE: this does NOT validate the buffer so it should NOT be called on /// invalid/untrusted input. Use VerifyAndBuildFromBuffer in that case static std::unique_ptr<FlatBufferModel> BuildFromBuffer( const char* caller_owned_buffer, size_t buffer_size, ErrorReporter* error_reporter = DefaultErrorReporter()); /// Verifies whether the content of the buffer is legit, then builds a model /// based on the pre-loaded flatbuffer. /// The extra_verifier argument is an additional optional verifier for the /// buffer. By default, we always check with tflite::VerifyModelBuffer. If /// extra_verifier is supplied, the buffer is checked against the /// extra_verifier after the check against tflite::VerifyModelBuilder. The /// caller retains ownership of the buffer and should keep it alive until the /// returned object is destroyed. Caller retains ownership of `error_reporter` /// and must ensure its lifetime is longer than the FlatBufferModel instance. /// Returns a nullptr in case of failure. static std::unique_ptr<FlatBufferModel> VerifyAndBuildFromBuffer( const char* buffer, size_t buffer_size, TfLiteVerifier* extra_verifier = nullptr, ErrorReporter* error_reporter = DefaultErrorReporter()); /// Builds a model directly from a flatbuffer pointer /// Caller retains ownership of the buffer and should keep it alive until the /// returned object is destroyed. Caller retains ownership of `error_reporter` /// and must ensure its lifetime is longer than the FlatBufferModel instance. /// Returns a nullptr in case of failure. static std::unique_ptr<FlatBufferModel> BuildFromModel( const tflite::Model* caller_owned_model_spec, ErrorReporter* error_reporter = DefaultErrorReporter()); // Releases memory or unmaps mmaped memory. ~FlatBufferModel(); // Copying or assignment is disallowed to simplify ownership semantics. FlatBufferModel(const FlatBufferModel&) = delete; FlatBufferModel& operator=(const FlatBufferModel&) = delete; bool initialized() const { return model_ != nullptr; } const tflite::Model* operator->() const { return model_; } const tflite::Model* GetModel() const { return model_; } ErrorReporter* error_reporter() const { return error_reporter_; } const Allocation* allocation() const { return allocation_.get(); } /// Returns true if the model identifier is correct (otherwise false and /// reports an error). bool CheckModelIdentifier() const; private: /// Loads a model from a given allocation. FlatBufferModel will take over the /// ownership of `allocation`, and delete it in destructor. The ownership of /// `error_reporter`remains with the caller and must have lifetime at least /// as much as FlatBufferModel. This is to allow multiple models to use the /// same ErrorReporter instance. FlatBufferModel(std::unique_ptr<Allocation> allocation, ErrorReporter* error_reporter = DefaultErrorReporter()); /// Loads a model from Model flatbuffer. The `model` has to remain alive and /// unchanged until the end of this flatbuffermodel's lifetime. FlatBufferModel(const Model* model, ErrorReporter* error_reporter); /// Flatbuffer traverser pointer. (Model* is a pointer that is within the /// allocated memory of the data allocated by allocation's internals. const tflite::Model* model_ = nullptr; /// The error reporter to use for model errors and subsequent errors when /// the interpreter is created ErrorReporter* error_reporter_; /// The allocator used for holding memory of the model. Note that this will /// be null if the client provides a tflite::Model directly. std::unique_ptr<Allocation> allocation_; }; /// Build an interpreter capable of interpreting `model`. /// /// model: A model whose lifetime must be at least as long as any /// interpreter(s) created by the builder. In principle multiple interpreters /// can be made from a single model. /// op_resolver: An instance that implements the OpResolver interface, which /// maps /// custom op names and builtin op codes to op registrations. The lifetime /// of the provided `op_resolver` object must be at least as long as the /// InterpreterBuilder; unlike `model` and `error_reporter`, the `op_resolver` /// does not need to exist for the duration of any created Interpreter /// objects. /// error_reporter: a functor that is called to report errors that handles /// printf var arg semantics. The lifetime of the `error_reporter` object must /// be greater than or equal to the Interpreter created by operator(). /// /// Returns a kTfLiteOk when successful and sets interpreter to a valid /// Interpreter. Note: The user must ensure the model lifetime (and error /// reporter, if provided) is at least as long as interpreter's lifetime. class InterpreterBuilder { public: InterpreterBuilder(const FlatBufferModel& model, const OpResolver& op_resolver); /// Builds an interpreter given only the raw flatbuffer Model object (instead /// of a FlatBufferModel). Mostly used for testing. /// If `error_reporter` is null, then DefaultErrorReporter() is used. InterpreterBuilder(const ::tflite::Model* model, const OpResolver& op_resolver, ErrorReporter* error_reporter = DefaultErrorReporter()); ~InterpreterBuilder(); InterpreterBuilder(const InterpreterBuilder&) = delete; InterpreterBuilder& operator=(const InterpreterBuilder&) = delete; TfLiteStatus operator()(std::unique_ptr<Interpreter>* interpreter); TfLiteStatus operator()(std::unique_ptr<Interpreter>* interpreter, int num_threads); private: TfLiteStatus BuildLocalIndexToRegistrationMapping(); TfLiteStatus ParseNodes( const flatbuffers::Vector<flatbuffers::Offset<Operator>>* operators, Subgraph* subgraph); TfLiteStatus ParseTensors( const flatbuffers::Vector<flatbuffers::Offset<Buffer>>* buffers, const flatbuffers::Vector<flatbuffers::Offset<Tensor>>* tensors, Subgraph* subgraph); TfLiteStatus ApplyDelegates(Interpreter* interpreter); TfLiteStatus ParseQuantization(const QuantizationParameters* src_quantization, TfLiteQuantization* quantization); const ::tflite::Model* model_; const OpResolver& op_resolver_; ErrorReporter* error_reporter_; std::vector<const TfLiteRegistration*> flatbuffer_op_index_to_registration_; std::vector<BuiltinOperator> flatbuffer_op_index_to_registration_types_; const Allocation* allocation_ = nullptr; }; } // namespace tflite #endif // TENSORFLOW_LITE_MODEL_H_
{ "content_hash": "d52fcfbf7186efdcfe084b9479c8376c", "timestamp": "", "source": "github", "line_count": 213, "max_line_length": 80, "avg_line_length": 47.96244131455399, "alnum_prop": 0.7293461237274863, "repo_name": "ghchinoy/tensorflow", "id": "cf5c930455fbd8c6be7daefc9755d7d3501c5d95", "size": "10884", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "tensorflow/lite/model.h", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Assembly", "bytes": "3568" }, { "name": "Batchfile", "bytes": "15317" }, { "name": "C", "bytes": "699905" }, { "name": "C#", "bytes": "8446" }, { "name": "C++", "bytes": "67022491" }, { "name": "CMake", "bytes": "206499" }, { "name": "Dockerfile", "bytes": "73602" }, { "name": "Go", "bytes": "1585039" }, { "name": "HTML", "bytes": "4680118" }, { "name": "Java", "bytes": "836400" }, { "name": "Jupyter Notebook", "bytes": "1665583" }, { "name": "LLVM", "bytes": "6536" }, { "name": "Makefile", "bytes": "98194" }, { "name": "Objective-C", "bytes": "94022" }, { "name": "Objective-C++", "bytes": "175222" }, { "name": "PHP", "bytes": "17600" }, { "name": "Pascal", "bytes": "3239" }, { "name": "Perl", "bytes": "7536" }, { "name": "Python", "bytes": "48407007" }, { "name": "RobotFramework", "bytes": "891" }, { "name": "Ruby", "bytes": "4733" }, { "name": "Shell", "bytes": "476920" }, { "name": "Smarty", "bytes": "27495" }, { "name": "Swift", "bytes": "56155" } ], "symlink_target": "" }
package co.cdev.agave.web; import java.io.File; import java.io.IOException; import java.lang.reflect.InvocationTargetException; import java.util.Comparator; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.SortedSet; import java.util.TreeSet; import java.util.logging.Level; import java.util.logging.Logger; import javax.servlet.Filter; import javax.servlet.FilterChain; import javax.servlet.FilterConfig; import javax.servlet.ServletContext; import javax.servlet.ServletException; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import co.cdev.agave.configuration.Config; import co.cdev.agave.configuration.ConfigGenerator; import co.cdev.agave.configuration.ConfigGeneratorImpl; import co.cdev.agave.configuration.ConfigImpl; import co.cdev.agave.configuration.HandlerDescriptor; import co.cdev.agave.configuration.ParamDescriptor; import co.cdev.agave.configuration.RoutingContext; import co.cdev.agave.conversion.AgaveConversionException; public class AgaveFilter implements Filter { private static final Logger LOGGER = Logger.getLogger(AgaveFilter.class.getName()); private static final String WORKFLOW_HANDLER_SUFFIX = "-handler"; private static final String WORKFLOW_FORM_SUFFIX = "-form"; private static final String DEFAULT_CONFIG_FILE_NAME = "agave.conf"; private FilterConfig filterConfig; private Config config; private LifecycleHooks lifecycleHooks; private File classesDirectory; private HandlerFactory handlerFactory; private FormFactory formFactory; private RequestMatcher requestMatcher; private SortedSet<ResultProcessor> resultProcessors; protected File provideClassesDirectory(FilterConfig filterConfig) throws ClassNotFoundException, InstantiationException, IllegalAccessException { File classesDir = null; if (System.getProperty("classesDirectory") != null) { classesDir = new File(System.getProperty("classesDirectory")); } else { classesDir = new File(filterConfig.getServletContext().getRealPath("/WEB-INF/classes")); } return classesDir; } protected LifecycleHooks provideLifecycleHooks(FilterConfig filterConfig) throws ClassNotFoundException, InstantiationException, IllegalAccessException { LifecycleHooks hooks = null; String lifecycleHooksParameter = filterConfig.getInitParameter("lifecycleHooks"); if (lifecycleHooksParameter != null) { hooks = (LifecycleHooks) Class.forName(lifecycleHooksParameter).newInstance(); } else { hooks = new DefaultLifecycleHooks(); } return hooks; } protected HandlerFactory provideHandlerFactory(FilterConfig filterConfig) throws ClassNotFoundException, InstantiationException, IllegalAccessException { HandlerFactory factory = null; String handlerFactoryParameter = filterConfig.getInitParameter("handlerFactory"); if (handlerFactoryParameter != null) { factory = (HandlerFactory) Class.forName(handlerFactoryParameter).newInstance(); } else { factory = new HandlerFactoryImpl(); } return factory; } protected FormFactory provideFormFactory(FilterConfig filterConfig) throws ClassNotFoundException, InstantiationException, IllegalAccessException { FormFactory factory = null; String formFactoryParameter = filterConfig.getInitParameter("formFactory"); if (formFactoryParameter != null) { factory = (FormFactory) Class.forName(formFactoryParameter).newInstance(); } else { factory = new FormFactoryImpl(); } return factory; } @Override public void init(FilterConfig filterConfig) throws ServletException { this.filterConfig = filterConfig; try { classesDirectory = provideClassesDirectory(filterConfig); lifecycleHooks = provideLifecycleHooks(filterConfig); File configFile = new File(classesDirectory, DEFAULT_CONFIG_FILE_NAME); if (configFile.exists() && configFile.canRead()) { config = new ConfigImpl(); config.readFromFile(configFile); } else { ConfigGenerator configGenerator = new ConfigGeneratorImpl(classesDirectory); config = configGenerator.generateConfig(); } requestMatcher = new RequestMatcherImpl(config); // These need to support dependency injection handlerFactory = provideHandlerFactory(filterConfig); handlerFactory.initialize(); formFactory = provideFormFactory(filterConfig); formFactory.initialize(); resultProcessors = new TreeSet<ResultProcessor>(new Comparator<ResultProcessor>() { @Override public int compare(ResultProcessor a, ResultProcessor b) { Class<?> aa = a.getClass(); Class<?> bb = b.getClass(); while (true) { if (aa == null) { return 1; } else if (bb == null) { return -1; } aa = aa.getSuperclass(); bb = bb.getSuperclass(); } } }); addResultProcessor(new DestinationProcessor()); addResultProcessor(new HTTPResponseProcessor()); addResultProcessor(new URIProcessor()); } catch (Exception ex) { throw new ServletException(ex); } } protected void addResultProcessor(ResultProcessor resultProcessor) { resultProcessors.add(resultProcessor); } /** * Destroys this filter. */ @Override public void destroy() { classesDirectory = null; config = null; filterConfig = null; requestMatcher = null; handlerFactory = null; formFactory = null; } @SuppressWarnings("unchecked") @Override public final void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws IOException, ServletException { ServletContext servletContext = filterConfig.getServletContext(); HttpServletRequest request = (HttpServletRequest) req; HttpServletResponse response = (HttpServletResponse) resp; HandlerDescriptor handlerDescriptor = requestMatcher.findMatch(request); if (handlerDescriptor != null) { // Wrap the request if necessary so that the uploaded content can be accessed like // regular string parameters if (RequestUtils.isMultipart(request)) { try { request = wrapMultipartRequest(request); } catch (Exception e) { throw new ServletException(e); } } HttpSession session = request.getSession(true); RoutingContext routingContext = new RoutingContext(servletContext, request, response, session); if (lifecycleHooks.beforeFilteringRequest(handlerDescriptor, routingContext)) { return; } LOGGER.log(Level.FINE, "Handling requests to \"{0}\" with \"{1}\"", new Object[] { request.getServletPath(), handlerDescriptor.getHandlerMethod() }); URIParamExtractor uriParamExtractor = new URIParamExtractorImpl(handlerDescriptor.getURIPattern()); Map<String, String> uriParams = uriParamExtractor.extractParams(request); Object formInstance = null; // Attempt to pull a form instance out of the session, stored from a // previous workflow phase if (handlerDescriptor.getWorkflowName() != null && !handlerDescriptor.initiatesWorkflow()) { formInstance = session.getAttribute(handlerDescriptor.getWorkflowName() + WORKFLOW_FORM_SUFFIX); } // Create a form instance if (formInstance == null) { formInstance = formFactory.createFormInstance(servletContext, handlerDescriptor); if (handlerDescriptor.getFormClass() != null && formInstance == null) { throw new FormException(String.format("Unable to create instance of \"%s\" with \"%s\"", handlerDescriptor.getFormClass().getName(), handlerFactory.getClass().getName())); } } // Populate the form if necessary. If the handler method only has one additional argument // beyond the HandlerContext, it is assumed that it will be a form object. if (formInstance != null) { if (handlerDescriptor.initiatesWorkflow()) { session.setAttribute(handlerDescriptor.getWorkflowName() + WORKFLOW_FORM_SUFFIX, formInstance); } if (lifecycleHooks.beforeHandlingRequest(handlerDescriptor, formInstance, routingContext)) { return; } try { // Populate a form and converts it into the target types if they can be // described by the standard suite of converters out of the agave.conversion // package FormPopulator formPopulator = new RequestParameterFormPopulator(request); formPopulator.populate(formInstance); if (RequestUtils.isMultipart(request)) { formPopulator = new RequestPartFormPopulator<Object>((MultipartRequest<Object>) request); formPopulator.populate(formInstance); } formPopulator = new URIParamFormPopulator(request, handlerDescriptor, uriParams); formPopulator.populate(formInstance); } catch (NoSuchMethodException ex) { throw new FormException(ex); } catch (IllegalAccessException ex) { throw new FormException(ex); } catch (InvocationTargetException ex) { throw new FormException(ex.getCause()); } catch (InstantiationException ex) { throw new FormException(ex); } catch (AgaveConversionException ex) { throw new FormException(ex); } if (lifecycleHooks.afterInitializingForm(handlerDescriptor, formInstance, routingContext)) { return; } } // If no form was found, attempt to supply arguments by taking the parameterized values // from either the URI path or the request params. URI params override request params. LinkedHashMap<String, Object> arguments = null; List<ParamDescriptor> paramDescriptors = handlerDescriptor.getParamDescriptors(); if (formInstance == null && !paramDescriptors.isEmpty()) { // A LinkedHashMap is used because the iteration order will match the arguments that // the handler method is expecting. Reinsertion into the map is negligible arguments = new LinkedHashMap<String, Object>(); // Establish the order of the parameter so the params can be looked up for (ParamDescriptor paramDescriptor : paramDescriptors) { String value = uriParams.get(paramDescriptor.getName()); if (value == null) { value = request.getParameter(paramDescriptor.getName()); } arguments.put(paramDescriptor.getName(), null); } // Now that the argument order has been established, populate // the actual values MapPopulator argumentPopulator = new MapPopulatorImpl(request, uriParams, handlerDescriptor); try { argumentPopulator.populate(arguments); } catch (AgaveConversionException ex) { throw new FormException(ex); } } Object handlerInstance = null; // Attempt to pull a handler from a previous workflow phase out of // the session if (handlerDescriptor.getWorkflowName() != null && !handlerDescriptor.initiatesWorkflow()) { handlerInstance = session.getAttribute(handlerDescriptor.getWorkflowName() + WORKFLOW_HANDLER_SUFFIX); } // Create a handler if (handlerInstance == null) { handlerInstance = handlerFactory.createHandlerInstance(servletContext, handlerDescriptor); if (handlerInstance == null) { throw new HandlerException(String.format("Unable to create instance of \"%s\" with \"%s\"", handlerDescriptor.getHandlerClass().getName(), handlerFactory.getClass().getName())); } } // Initiate a new workflow if necessary if (handlerDescriptor.initiatesWorkflow()) { session.setAttribute(handlerDescriptor.getWorkflowName() + WORKFLOW_HANDLER_SUFFIX, handlerInstance); } if (lifecycleHooks.beforeHandlingRequest(handlerDescriptor, handlerInstance, routingContext)) { return; } Object result = null; // Invoke the handler method, by either supplying a context and a form // instance, a context and a string of named parameters, or a single // HandlerContext try { if (formInstance != null) { if (handlerDescriptor.getHandlerMethod().getReturnType() != null) { result = handlerDescriptor.getHandlerMethod().invoke(handlerInstance, routingContext, formInstance); } else { handlerDescriptor.getHandlerMethod().invoke(handlerInstance, routingContext, formInstance); } } else if (arguments != null) { Object[] actualArguments = new Object[arguments.size() + 1]; int i = 0; actualArguments[i++] = routingContext; for (String name : arguments.keySet()) { actualArguments[i++] = arguments.get(name); } if (handlerDescriptor.getHandlerMethod().getReturnType() != null) { result = handlerDescriptor.getHandlerMethod().invoke(handlerInstance, actualArguments); } else { handlerDescriptor.getHandlerMethod().invoke(handlerInstance, actualArguments); } } else { if (handlerDescriptor.getHandlerMethod().getReturnType() != null) { result = handlerDescriptor.getHandlerMethod().invoke(handlerInstance, routingContext); } else { handlerDescriptor.getHandlerMethod().invoke(handlerInstance, routingContext); } } } catch (InvocationTargetException ex) { if (ex.getCause() instanceof AgaveWebException) { logRequestInformation(request); throw (AgaveWebException) ex.getCause(); } else if (ex.getCause() instanceof IOException) { logRequestInformation(request); throw (IOException) ex.getCause(); } else if (ex.getCause() instanceof RuntimeException) { logRequestInformation(request); throw (RuntimeException) ex.getCause(); } else { logRequestInformation(request); throw new HandlerException(ex.getMessage(), ex.getCause()); } } catch (IllegalAccessException ex) { logRequestInformation(request); throw new HandlerException(handlerDescriptor, ex); } // Complete a workflow and flushes the referenced attributes from // the session if (handlerDescriptor.completesWorkflow()) { session.removeAttribute(handlerDescriptor.getWorkflowName() + WORKFLOW_HANDLER_SUFFIX); session.removeAttribute(handlerDescriptor.getWorkflowName() + WORKFLOW_FORM_SUFFIX); } if (handlerDescriptor.getHandlerMethod().getReturnType() != null && result != null && !response.isCommitted()) { for (ResultProcessor resultProcessor : resultProcessors) { if (resultProcessor.canProcessResult(result, routingContext, handlerDescriptor)) { resultProcessor.process(result, routingContext, handlerDescriptor); break; } } } if (lifecycleHooks.afterHandlingRequest(handlerDescriptor, handlerInstance, routingContext)) { return; } } else { chain.doFilter(req, resp); } } private void logRequestInformation(HttpServletRequest request) { LOGGER.log(Level.INFO, "Remote details for exception: {0}@{1} ({2}:{3,number,#})", new Object[] { request.getRemoteUser(), request.getRemoteHost(), request.getRemoteAddr(), request.getRemotePort()}); } protected HttpServletRequest wrapMultipartRequest(HttpServletRequest request) throws Exception { return new DefaultMultipartRequest<File>(request, new FileMultipartParser()); } public FilterConfig getFilterConfig() { return filterConfig; } public Config getConfig() { return config; } public RequestMatcher getRequestMatcher() { return requestMatcher; } public HandlerFactory getHandlerFactory() { return handlerFactory; } public FormFactory getFormFactory() { return formFactory; } public File getClassesDirectory() { return classesDirectory; } }
{ "content_hash": "2efe713fbd0f1bb4bbabb2b842e6a642", "timestamp": "", "source": "github", "line_count": 464, "max_line_length": 124, "avg_line_length": 41.75431034482759, "alnum_prop": 0.5856302260761845, "repo_name": "damiancarrillo/agave-framework", "id": "11b1a01154713af04d606ce5500244a38e9fdaa0", "size": "19374", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "agave-web-framework/src/main/java/co/cdev/agave/web/AgaveFilter.java", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "Java", "bytes": "746959" }, { "name": "JavaScript", "bytes": "476" } ], "symlink_target": "" }
/** * A Lambda function that looks up a AMI ID for a given ami name. **/ const CfnLambda = require('cfn-lambda'); const CleanupLogic = require('./bucketCleanupLogic.js'); //Clean up S3 bucket var Delete = (requestPhysicalID, cfnRequestParams, reply) => { new CleanupLogic(cfnRequestParams.BucketName, function () { reply(null, requestPhysicalID); }, function (err) { reply(err, requestPhysicalID); }).cleanupBucket(); }; // empty create var Create = (cfnRequestParams, reply) => { reply(null, `BucketCleanup${Math.ceil(Math.random() * 1000000)}`); }; // empty update var Update = (requestPhysicalID, cfnRequestParams, oldCfnRequestParams, reply) => { reply(null, requestPhysicalID); }; exports.handler = CfnLambda({ Create: Create, Update: Update, Delete: Delete, TriggersReplacement: [], SchemaPath: [__dirname, 'schema.json'] });
{ "content_hash": "6e8e65929b59bcf585e560ad1578601d", "timestamp": "", "source": "github", "line_count": 34, "max_line_length": 83, "avg_line_length": 26.352941176470587, "alnum_prop": 0.6741071428571429, "repo_name": "base2Services/cloudformation-custom-resouces", "id": "b830d056b4776052678736bbc61d79e1cb292d7f", "size": "896", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/cleanup-s3-bucket/index.js", "mode": "33188", "license": "mit", "language": [ { "name": "JavaScript", "bytes": "24052" }, { "name": "Shell", "bytes": "503" } ], "symlink_target": "" }
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:id="@+id/activity_main" android:layout_width="match_parent" android:layout_height="match_parent" > <include layout="@layout/title_bar" /> <FrameLayout android:layout_width="match_parent" android:layout_height="0dp" android:layout_weight="1" android:id="@+id/fl_pager"> </FrameLayout> <RadioGroup android:id="@+id/rg_bottomtag" android:orientation="horizontal" android:layout_width="match_parent" android:layout_height="wrap_content"> <RadioButton android:id="@+id/rb_localvideo" style="@style/tag_style" android:text="@string/tag_local_video" android:drawableTop="@drawable/tag_drawable_localvideo" /> <RadioButton android:id="@+id/rb_localmusic" style="@style/tag_style" android:text="@string/tag_local_music" android:drawableTop="@drawable/tag_drawable_localmusic" /> <RadioButton android:id="@+id/rb_netvideo" style="@style/tag_style" android:text="@string/tag_net_video" android:drawableTop="@drawable/tag_drawable_netvideo" /> <RadioButton android:id="@+id/rb_netmusic" style="@style/tag_style" android:text="@string/tag_net_music" android:drawableTop="@drawable/tag_drawable_netmusic" /> </RadioGroup> </LinearLayout>
{ "content_hash": "0bff8a8021b76d51ee48f08fc3075b92", "timestamp": "", "source": "github", "line_count": 48, "max_line_length": 72, "avg_line_length": 34.75, "alnum_prop": 0.5833333333333334, "repo_name": "chen4346/MyMedialPlayer", "id": "13632419917478bd19cea2bcfaf18f77eb7357c3", "size": "1668", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "app/src/main/res/layout/activity_main.xml", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "27015" } ], "symlink_target": "" }