text
stringlengths
2
1.04M
meta
dict
SYNONYM #### According to The Catalogue of Life, 3rd January 2011 #### Published in null #### Original name null ### Remarks null
{ "content_hash": "52914032627f1005a3ad490c9effb058", "timestamp": "", "source": "github", "line_count": 13, "max_line_length": 39, "avg_line_length": 10.23076923076923, "alnum_prop": 0.6917293233082706, "repo_name": "mdoering/backbone", "id": "fb0057b726a981d0910d843a8093d25abcb3d6e6", "size": "183", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "life/Plantae/Magnoliophyta/Magnoliopsida/Malpighiales/Euphorbiaceae/Jatropha/Jatropha glauca/ Syn. Jatropha lobata/README.md", "mode": "33188", "license": "apache-2.0", "language": [], "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 (version 1.7.0_45) on Mon Mar 03 10:44:37 EST 2014 --> <title>Uses of Class org.hibernate.property.DirectPropertyAccessor.DirectSetter (Hibernate JavaDocs)</title> <meta name="date" content="2014-03-03"> <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.hibernate.property.DirectPropertyAccessor.DirectSetter (Hibernate JavaDocs)"; } //--> </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/hibernate/property/DirectPropertyAccessor.DirectSetter.html" title="class in org.hibernate.property">Class</a></li> <li class="navBarCell1Rev">Use</li> <li><a href="../../../../overview-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/hibernate/property/class-use/DirectPropertyAccessor.DirectSetter.html" target="_top">Frames</a></li> <li><a href="DirectPropertyAccessor.DirectSetter.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.hibernate.property.DirectPropertyAccessor.DirectSetter" class="title">Uses of Class<br>org.hibernate.property.DirectPropertyAccessor.DirectSetter</h2> </div> <div class="classUseContainer">No usage of org.hibernate.property.DirectPropertyAccessor.DirectSetter</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/hibernate/property/DirectPropertyAccessor.DirectSetter.html" title="class in org.hibernate.property">Class</a></li> <li class="navBarCell1Rev">Use</li> <li><a href="../../../../overview-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/hibernate/property/class-use/DirectPropertyAccessor.DirectSetter.html" target="_top">Frames</a></li> <li><a href="DirectPropertyAccessor.DirectSetter.html" target="_top">No Frames</a></li> </ul> <ul class="navList" id="allclasses_navbar_bottom"> <li><a href="../../../../allclasses-noframe.html">All Classes</a></li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_bottom"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } //--> </script> </div> <a name="skip-navbar_bottom"> <!-- --> </a></div> <!-- ======== END OF BOTTOM NAVBAR ======= --> <p class="legalCopy"><small>Copyright &copy; 2001-2014 <a href="http://redhat.com">Red Hat, Inc.</a> All Rights Reserved.</small></p> </body> </html>
{ "content_hash": "41c7784037b91e62eae0556dcb4270ed", "timestamp": "", "source": "github", "line_count": 116, "max_line_length": 179, "avg_line_length": 38.922413793103445, "alnum_prop": 0.6394241417497232, "repo_name": "serious6/HibernateSimpleProject", "id": "dd7c3ff79398aad24f5dd512a19006984a52cbde", "size": "4515", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "javadoc/hibernate_Doc/org/hibernate/property/class-use/DirectPropertyAccessor.DirectSetter.html", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "12560" }, { "name": "Java", "bytes": "15329" } ], "symlink_target": "" }
In the interest of fostering an open and welcoming environment, we as contributors and maintainers pledge to making participation in our project and our community a harassment-free experience for everyone, regardless of age, body size, disability, ethnicity, gender identity and expression, level of experience, nationality, personal appearance, race, religion, or sexual identity and orientation. ## Our Standards Examples of behavior that contributes to creating a positive environment include: * Using welcoming and inclusive language * Being respectful of differing viewpoints and experiences * Gracefully accepting constructive criticism * Focusing on what is best for the community * Showing empathy towards other community members Examples of unacceptable behavior by participants include: * The use of sexualized language or imagery and unwelcome sexual attention or advances * Trolling, insulting/derogatory comments, and personal or political attacks * Public or private harassment * Publishing others' private information, such as a physical or electronic address, without explicit permission * Other conduct which could reasonably be considered inappropriate in a professional setting ## Our Responsibilities Project maintainers are responsible for clarifying the standards of acceptable behavior and are expected to take appropriate and fair corrective action in response to any instances of unacceptable behavior. Project maintainers have the right and responsibility to remove, edit, or reject comments, commits, code, wiki edits, issues, and other contributions that are not aligned to this Code of Conduct, or to ban temporarily or permanently any contributor for other behaviors that they deem inappropriate, threatening, offensive, or harmful. ## Scope This Code of Conduct applies both within project spaces and in public spaces when an individual is representing the project or its community. Examples of representing a project or community include using an official project e-mail address, posting via an official social media account, or acting as an appointed representative at an online or offline event. Representation of a project may be further defined and clarified by project maintainers. ## Enforcement Instances of abusive, harassing, or otherwise unacceptable behavior may be reported by contacting the project team at rohitpaulk@live.com. All complaints will be reviewed and investigated and will result in a response that is deemed necessary and appropriate to the circumstances. The project team is obligated to maintain confidentiality with regard to the reporter of an incident. Further details of specific enforcement policies may be posted separately. Project maintainers who do not follow or enforce the Code of Conduct in good faith may face temporary or permanent repercussions as determined by other members of the project's leadership. ## Attribution This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4, available at [http://contributor-covenant.org/version/1/4][version] [homepage]: http://contributor-covenant.org [version]: http://contributor-covenant.org/version/1/4/
{ "content_hash": "f5c2d5be4fa0a8b7fa6841ee9bd40544", "timestamp": "", "source": "github", "line_count": 70, "max_line_length": 87, "avg_line_length": 45.31428571428572, "alnum_prop": 0.8212484237074401, "repo_name": "rohitpaulk/befunge-ruby", "id": "a74e746450c1d01d3067fb711039807b7c04e9e1", "size": "3227", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "CODE_OF_CONDUCT.md", "mode": "33188", "license": "mit", "language": [ { "name": "Ruby", "bytes": "10208" }, { "name": "Shell", "bytes": "131" } ], "symlink_target": "" }
namespace autofill_assistant { PlatformDependenciesDesktop::PlatformDependenciesDesktop() = default; bool PlatformDependenciesDesktop::IsCustomTab( const content::WebContents& web_contents) const { return false; } } // namespace autofill_assistant
{ "content_hash": "b4caf70c6c40f12c1b11e4df2676ad72", "timestamp": "", "source": "github", "line_count": 10, "max_line_length": 69, "avg_line_length": 25.8, "alnum_prop": 0.7945736434108527, "repo_name": "nwjs/chromium.src", "id": "cf98e59b88f1f2acc45205c339092db86c3f8a99", "size": "482", "binary": false, "copies": "6", "ref": "refs/heads/nw70", "path": "chrome/browser/autofill_assistant/platform_dependencies_desktop.cc", "mode": "33188", "license": "bsd-3-clause", "language": [], "symlink_target": "" }
import sys sys.path.append('LeetCode') from ListNode import ListNode import heapq class Solution: def mergeKLists(self, lists: list) -> ListNode: dummy_head = current = ListNode(-1) heap = [(list_head.val, i, list_head) for i, list_head in enumerate(lists) if list_head] heapq.heapify(heap) while len(heap) > 0: _, i, node = heapq.heappop(heap) current.next = node current = current.next if node.next is not None: heapq.heappush(heap, (node.next.val, i, node.next)) return dummy_head.next
{ "content_hash": "bca2fce29cf85a9c113033429a093a47", "timestamp": "", "source": "github", "line_count": 22, "max_line_length": 96, "avg_line_length": 27.40909090909091, "alnum_prop": 0.5970149253731343, "repo_name": "BigEgg/LeetCode", "id": "838af0a8b5fb8c355605d89c94c8f8caf434f8d6", "size": "603", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "Python/LeetCode/_001_050/_023_MergeKSortedLists.py", "mode": "33188", "license": "mit", "language": [ { "name": "C", "bytes": "6405" }, { "name": "C#", "bytes": "460435" }, { "name": "C++", "bytes": "49261" }, { "name": "HTML", "bytes": "1371" }, { "name": "Java", "bytes": "22777" }, { "name": "JavaScript", "bytes": "41935" }, { "name": "Python", "bytes": "167427" }, { "name": "Smalltalk", "bytes": "1174" } ], "symlink_target": "" }
NS_ASSUME_NONNULL_BEGIN // Begins: when numberOfTouchesRequired have tapped numberOfTapsRequired times and been held for minumPressDuration // Changes: when a finger moves // Ends: when a finger is lifted NS_CLASS_AVAILABLE_IOS(3_2) @interface UILongPressGestureRecognizer : UIGestureRecognizer @property (nonatomic) NSUInteger numberOfTapsRequired; // Default is 0. The number of full taps required before the press for gesture to be recognized @property (nonatomic) NSUInteger numberOfTouchesRequired __TVOS_PROHIBITED; // Default is 1. Number of fingers that must be held down for the gesture to be recognized @property (nonatomic) CFTimeInterval minimumPressDuration; // Default is 0.5. Time in seconds the fingers must be held down for the gesture to be recognized @property (nonatomic) CGFloat allowableMovement; // Default is 10. Maximum movement in pixels allowed before the gesture fails. Once recognized (after minimumPressDuration) there is no limit on finger movement for the remainder of the touch tracking @end NS_ASSUME_NONNULL_END
{ "content_hash": "da882f1cab8741615c651a657778b69b", "timestamp": "", "source": "github", "line_count": 17, "max_line_length": 259, "avg_line_length": 63.1764705882353, "alnum_prop": 0.792364990689013, "repo_name": "caolonghan/First", "id": "684fb6e4ad9a229eb35b08c063869e871935697d", "size": "1301", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "CapitaStar_IOS_1.2.4 2 11.14适配x/kaidexing/Pods/UIKit.framework/Headers/UILongPressGestureRecognizer.h", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "C", "bytes": "252220" }, { "name": "C++", "bytes": "38429" }, { "name": "HTML", "bytes": "2335" }, { "name": "JavaScript", "bytes": "64403" }, { "name": "Objective-C", "bytes": "7326896" }, { "name": "Objective-C++", "bytes": "21082" }, { "name": "Ruby", "bytes": "279" }, { "name": "Shell", "bytes": "11756" }, { "name": "Swift", "bytes": "5136" } ], "symlink_target": "" }
 CKEDITOR.dom.range = function( document ) { this.startContainer = null; this.startOffset = null; this.endContainer = null; this.endOffset = null; this.collapsed = true; this.document = document; }; (function() { // Updates the "collapsed" property for the given range object. var updateCollapsed = function( range ) { range.collapsed = ( range.startContainer && range.endContainer && range.startContainer.equals( range.endContainer ) && range.startOffset == range.endOffset ); }; // This is a shared function used to delete, extract and clone the range // contents. // V2 var execContentsAction = function( range, action, docFrag ) { range.optimizeBookmark(); var startNode = range.startContainer; var endNode = range.endContainer; var startOffset = range.startOffset; var endOffset = range.endOffset; var removeStartNode; var removeEndNode; // For text containers, we must simply split the node and point to the // second part. The removal will be handled by the rest of the code . if ( endNode.type == CKEDITOR.NODE_TEXT ) endNode = endNode.split( endOffset ); else { // If the end container has children and the offset is pointing // to a child, then we should start from it. if ( endNode.getChildCount() > 0 ) { // If the offset points after the last node. if ( endOffset >= endNode.getChildCount() ) { // Let's create a temporary node and mark it for removal. endNode = endNode.append( range.document.createText( '' ) ); removeEndNode = true; } else endNode = endNode.getChild( endOffset ); } } // For text containers, we must simply split the node. The removal will // be handled by the rest of the code . if ( startNode.type == CKEDITOR.NODE_TEXT ) { startNode.split( startOffset ); // In cases the end node is the same as the start node, the above // splitting will also split the end, so me must move the end to // the second part of the split. if ( startNode.equals( endNode ) ) endNode = startNode.getNext(); } else { // If the start container has children and the offset is pointing // to a child, then we should start from its previous sibling. // If the offset points to the first node, we don't have a // sibling, so let's use the first one, but mark it for removal. if ( !startOffset ) { // Let's create a temporary node and mark it for removal. startNode = startNode.getFirst().insertBeforeMe( range.document.createText( '' ) ); removeStartNode = true; } else if ( startOffset >= startNode.getChildCount() ) { // Let's create a temporary node and mark it for removal. startNode = startNode.append( range.document.createText( '' ) ); removeStartNode = true; } else startNode = startNode.getChild( startOffset ).getPrevious(); } // Get the parent nodes tree for the start and end boundaries. var startParents = startNode.getParents(); var endParents = endNode.getParents(); // Compare them, to find the top most siblings. var i, topStart, topEnd; for ( i = 0 ; i < startParents.length ; i++ ) { topStart = startParents[ i ]; topEnd = endParents[ i ]; // The compared nodes will match until we find the top most // siblings (different nodes that have the same parent). // "i" will hold the index in the parents array for the top // most element. if ( !topStart.equals( topEnd ) ) break; } var clone = docFrag, levelStartNode, levelClone, currentNode, currentSibling; // Remove all successive sibling nodes for every node in the // startParents tree. for ( var j = i ; j < startParents.length ; j++ ) { levelStartNode = startParents[j]; // For Extract and Clone, we must clone this level. if ( clone && !levelStartNode.equals( startNode ) ) // action = 0 = Delete levelClone = clone.append( levelStartNode.clone() ); currentNode = levelStartNode.getNext(); while ( currentNode ) { // Stop processing when the current node matches a node in the // endParents tree or if it is the endNode. if ( currentNode.equals( endParents[ j ] ) || currentNode.equals( endNode ) ) break; // Cache the next sibling. currentSibling = currentNode.getNext(); // If cloning, just clone it. if ( action == 2 ) // 2 = Clone clone.append( currentNode.clone( true ) ); else { // Both Delete and Extract will remove the node. currentNode.remove(); // When Extracting, move the removed node to the docFrag. if ( action == 1 ) // 1 = Extract clone.append( currentNode ); } currentNode = currentSibling; } if ( clone ) clone = levelClone; } clone = docFrag; // Remove all previous sibling nodes for every node in the // endParents tree. for ( var k = i ; k < endParents.length ; k++ ) { levelStartNode = endParents[ k ]; // For Extract and Clone, we must clone this level. if ( action > 0 && !levelStartNode.equals( endNode ) ) // action = 0 = Delete levelClone = clone.append( levelStartNode.clone() ); // The processing of siblings may have already been done by the parent. if ( !startParents[ k ] || levelStartNode.$.parentNode != startParents[ k ].$.parentNode ) { currentNode = levelStartNode.getPrevious(); while ( currentNode ) { // Stop processing when the current node matches a node in the // startParents tree or if it is the startNode. if ( currentNode.equals( startParents[ k ] ) || currentNode.equals( startNode ) ) break; // Cache the next sibling. currentSibling = currentNode.getPrevious(); // If cloning, just clone it. if ( action == 2 ) // 2 = Clone clone.$.insertBefore( currentNode.$.cloneNode( true ), clone.$.firstChild ) ; else { // Both Delete and Extract will remove the node. currentNode.remove(); // When Extracting, mode the removed node to the docFrag. if ( action == 1 ) // 1 = Extract clone.$.insertBefore( currentNode.$, clone.$.firstChild ); } currentNode = currentSibling; } } if ( clone ) clone = levelClone; } if ( action == 2 ) // 2 = Clone. { // No changes in the DOM should be done, so fix the split text (if any). var startTextNode = range.startContainer; if ( startTextNode.type == CKEDITOR.NODE_TEXT ) { startTextNode.$.data += startTextNode.$.nextSibling.data; startTextNode.$.parentNode.removeChild( startTextNode.$.nextSibling ); } var endTextNode = range.endContainer; if ( endTextNode.type == CKEDITOR.NODE_TEXT && endTextNode.$.nextSibling ) { endTextNode.$.data += endTextNode.$.nextSibling.data; endTextNode.$.parentNode.removeChild( endTextNode.$.nextSibling ); } } else { // Collapse the range. // If a node has been partially selected, collapse the range between // topStart and topEnd. Otherwise, simply collapse it to the start. (W3C specs). if ( topStart && topEnd && ( startNode.$.parentNode != topStart.$.parentNode || endNode.$.parentNode != topEnd.$.parentNode ) ) { var endIndex = topEnd.getIndex(); // If the start node is to be removed, we must correct the // index to reflect the removal. if ( removeStartNode && topEnd.$.parentNode == startNode.$.parentNode ) endIndex--; range.setStart( topEnd.getParent(), endIndex ); } // Collapse it to the start. range.collapse( true ); } // Cleanup any marked node. if ( removeStartNode ) startNode.remove(); if ( removeEndNode && endNode.$.parentNode ) endNode.remove(); }; var inlineChildReqElements = { abbr:1,acronym:1,b:1,bdo:1,big:1,cite:1,code:1,del:1,dfn:1,em:1,font:1,i:1,ins:1,label:1,kbd:1,q:1,samp:1,small:1,span:1,strike:1,strong:1,sub:1,sup:1,tt:1,u:1,'var':1 }; // Creates the appropriate node evaluator for the dom walker used inside // check(Start|End)OfBlock. function getCheckStartEndBlockEvalFunction( isStart ) { var hadBr = false, bookmarkEvaluator = CKEDITOR.dom.walker.bookmark( true ); return function( node ) { // First ignore bookmark nodes. if ( bookmarkEvaluator( node ) ) return true; if ( node.type == CKEDITOR.NODE_TEXT ) { // If there's any visible text, then we're not at the start. if ( CKEDITOR.tools.trim( node.getText() ).length ) return false; } else if ( node.type == CKEDITOR.NODE_ELEMENT ) { // If there are non-empty inline elements (e.g. <img />), then we're not // at the start. if ( !inlineChildReqElements[ node.getName() ] ) { // If we're working at the end-of-block, forgive the first <br /> in non-IE // browsers. if ( !isStart && !CKEDITOR.env.ie && node.getName() == 'br' && !hadBr ) hadBr = true; else return false; } } return true; }; } // Evaluator for CKEDITOR.dom.element::checkBoundaryOfElement, reject any // text node and non-empty elements unless it's being bookmark text. function elementBoundaryEval( node ) { // Reject any text node unless it's being bookmark // OR it's spaces. (#3883) return node.type != CKEDITOR.NODE_TEXT && node.getName() in CKEDITOR.dtd.$removeEmpty || !CKEDITOR.tools.trim( node.getText() ) || node.getParent().hasAttribute( '_fck_bookmark' ); } var whitespaceEval = new CKEDITOR.dom.walker.whitespaces(), bookmarkEval = new CKEDITOR.dom.walker.bookmark(); function nonWhitespaceOrBookmarkEval( node ) { // Whitespaces and bookmark nodes are to be ignored. return !whitespaceEval( node ) && !bookmarkEval( node ); } CKEDITOR.dom.range.prototype = { clone : function() { var clone = new CKEDITOR.dom.range( this.document ); clone.startContainer = this.startContainer; clone.startOffset = this.startOffset; clone.endContainer = this.endContainer; clone.endOffset = this.endOffset; clone.collapsed = this.collapsed; return clone; }, collapse : function( toStart ) { if ( toStart ) { this.endContainer = this.startContainer; this.endOffset = this.startOffset; } else { this.startContainer = this.endContainer; this.startOffset = this.endOffset; } this.collapsed = true; }, // The selection may be lost when cloning (due to the splitText() call). cloneContents : function() { var docFrag = new CKEDITOR.dom.documentFragment( this.document ); if ( !this.collapsed ) execContentsAction( this, 2, docFrag ); return docFrag; }, deleteContents : function() { if ( this.collapsed ) return; execContentsAction( this, 0 ); }, extractContents : function() { var docFrag = new CKEDITOR.dom.documentFragment( this.document ); if ( !this.collapsed ) execContentsAction( this, 1, docFrag ); return docFrag; }, /** * Creates a bookmark object, which can be later used to restore the * range by using the moveToBookmark function. * This is an "intrusive" way to create a bookmark. It includes <span> tags * in the range boundaries. The advantage of it is that it is possible to * handle DOM mutations when moving back to the bookmark. * Attention: the inclusion of nodes in the DOM is a design choice and * should not be changed as there are other points in the code that may be * using those nodes to perform operations. See GetBookmarkNode. * @param {Boolean} [serializable] Indicates that the bookmark nodes * must contain ids, which can be used to restore the range even * when these nodes suffer mutations (like a clonation or innerHTML * change). * @returns {Object} And object representing a bookmark. */ createBookmark : function( serializable ) { var startNode, endNode; var baseId; var clone; startNode = this.document.createElement( 'span' ); startNode.setAttribute( '_fck_bookmark', 1 ); startNode.setStyle( 'display', 'none' ); // For IE, it must have something inside, otherwise it may be // removed during DOM operations. startNode.setHtml( '&nbsp;' ); if ( serializable ) { baseId = 'cke_bm_' + CKEDITOR.tools.getNextNumber(); startNode.setAttribute( 'id', baseId + 'S' ); } // If collapsed, the endNode will not be created. if ( !this.collapsed ) { endNode = startNode.clone(); endNode.setHtml( '&nbsp;' ); if ( serializable ) endNode.setAttribute( 'id', baseId + 'E' ); clone = this.clone(); clone.collapse(); clone.insertNode( endNode ); } clone = this.clone(); clone.collapse( true ); clone.insertNode( startNode ); // Update the range position. if ( endNode ) { this.setStartAfter( startNode ); this.setEndBefore( endNode ); } else this.moveToPosition( startNode, CKEDITOR.POSITION_AFTER_END ); return { startNode : serializable ? baseId + 'S' : startNode, endNode : serializable ? baseId + 'E' : endNode, serializable : serializable }; }, /** * Creates a "non intrusive" and "mutation sensible" bookmark. This * kind of bookmark should be used only when the DOM is supposed to * remain stable after its creation. * @param {Boolean} [normalized] Indicates that the bookmark must * normalized. When normalized, the successive text nodes are * considered a single node. To sucessful load a normalized * bookmark, the DOM tree must be also normalized before calling * moveToBookmark. * @returns {Object} An object representing the bookmark. */ createBookmark2 : function( normalized ) { var startContainer = this.startContainer, endContainer = this.endContainer; var startOffset = this.startOffset, endOffset = this.endOffset; var child, previous; // If there is no range then get out of here. // It happens on initial load in Safari #962 and if the editor it's // hidden also in Firefox if ( !startContainer || !endContainer ) return { start : 0, end : 0 }; if ( normalized ) { // Find out if the start is pointing to a text node that will // be normalized. if ( startContainer.type == CKEDITOR.NODE_ELEMENT ) { child = startContainer.getChild( startOffset ); // In this case, move the start information to that text // node. if ( child && child.type == CKEDITOR.NODE_TEXT && startOffset > 0 && child.getPrevious().type == CKEDITOR.NODE_TEXT ) { startContainer = child; startOffset = 0; } } // Normalize the start. while ( startContainer.type == CKEDITOR.NODE_TEXT && ( previous = startContainer.getPrevious() ) && previous.type == CKEDITOR.NODE_TEXT ) { startContainer = previous; startOffset += previous.getLength(); } // Process the end only if not normalized. if ( !this.isCollapsed ) { // Find out if the start is pointing to a text node that // will be normalized. if ( endContainer.type == CKEDITOR.NODE_ELEMENT ) { child = endContainer.getChild( endOffset ); // In this case, move the start information to that // text node. if ( child && child.type == CKEDITOR.NODE_TEXT && endOffset > 0 && child.getPrevious().type == CKEDITOR.NODE_TEXT ) { endContainer = child; endOffset = 0; } } // Normalize the end. while ( endContainer.type == CKEDITOR.NODE_TEXT && ( previous = endContainer.getPrevious() ) && previous.type == CKEDITOR.NODE_TEXT ) { endContainer = previous; endOffset += previous.getLength(); } } } return { start : startContainer.getAddress( normalized ), end : this.isCollapsed ? null : endContainer.getAddress( normalized ), startOffset : startOffset, endOffset : endOffset, normalized : normalized, is2 : true // It's a createBookmark2 bookmark. }; }, moveToBookmark : function( bookmark ) { if ( bookmark.is2 ) // Created with createBookmark2(). { // Get the start information. var startContainer = this.document.getByAddress( bookmark.start, bookmark.normalized ), startOffset = bookmark.startOffset; // Get the end information. var endContainer = bookmark.end && this.document.getByAddress( bookmark.end, bookmark.normalized ), endOffset = bookmark.endOffset; // Set the start boundary. this.setStart( startContainer, startOffset ); // Set the end boundary. If not available, collapse it. if ( endContainer ) this.setEnd( endContainer, endOffset ); else this.collapse( true ); } else // Created with createBookmark(). { var serializable = bookmark.serializable, startNode = serializable ? this.document.getById( bookmark.startNode ) : bookmark.startNode, endNode = serializable ? this.document.getById( bookmark.endNode ) : bookmark.endNode; // Set the range start at the bookmark start node position. this.setStartBefore( startNode ); // Remove it, because it may interfere in the setEndBefore call. startNode.remove(); // Set the range end at the bookmark end node position, or simply // collapse it if it is not available. if ( endNode ) { this.setEndBefore( endNode ); endNode.remove(); } else this.collapse( true ); } }, getBoundaryNodes : function() { var startNode = this.startContainer, endNode = this.endContainer, startOffset = this.startOffset, endOffset = this.endOffset, childCount; if ( startNode.type == CKEDITOR.NODE_ELEMENT ) { childCount = startNode.getChildCount(); if ( childCount > startOffset ) startNode = startNode.getChild( startOffset ); else if ( childCount < 1 ) startNode = startNode.getPreviousSourceNode(); else // startOffset > childCount but childCount is not 0 { // Try to take the node just after the current position. startNode = startNode.$; while ( startNode.lastChild ) startNode = startNode.lastChild; startNode = new CKEDITOR.dom.node( startNode ); // Normally we should take the next node in DFS order. But it // is also possible that we've already reached the end of // document. startNode = startNode.getNextSourceNode() || startNode; } } if ( endNode.type == CKEDITOR.NODE_ELEMENT ) { childCount = endNode.getChildCount(); if ( childCount > endOffset ) endNode = endNode.getChild( endOffset ).getPreviousSourceNode( true ); else if ( childCount < 1 ) endNode = endNode.getPreviousSourceNode(); else // endOffset > childCount but childCount is not 0 { // Try to take the node just before the current position. endNode = endNode.$; while ( endNode.lastChild ) endNode = endNode.lastChild; endNode = new CKEDITOR.dom.node( endNode ); } } // Sometimes the endNode will come right before startNode for collapsed // ranges. Fix it. (#3780) if ( startNode.getPosition( endNode ) & CKEDITOR.POSITION_FOLLOWING ) startNode = endNode; return { startNode : startNode, endNode : endNode }; }, /** * Find the node which fully contains the range. * @param includeSelf * @param {Boolean} ignoreTextNode Whether ignore CKEDITOR.NODE_TEXT type. */ getCommonAncestor : function( includeSelf , ignoreTextNode ) { var start = this.startContainer, end = this.endContainer, ancestor; if ( start.equals( end ) ) { if ( includeSelf && start.type == CKEDITOR.NODE_ELEMENT && this.startOffset == this.endOffset - 1 ) ancestor = start.getChild( this.startOffset ); else ancestor = start; } else ancestor = start.getCommonAncestor( end ); return ignoreTextNode && !ancestor.is ? ancestor.getParent() : ancestor; }, /** * Transforms the startContainer and endContainer properties from text * nodes to element nodes, whenever possible. This is actually possible * if either of the boundary containers point to a text node, and its * offset is set to zero, or after the last char in the node. */ optimize : function() { var container = this.startContainer; var offset = this.startOffset; if ( container.type != CKEDITOR.NODE_ELEMENT ) { if ( !offset ) this.setStartBefore( container ); else if ( offset >= container.getLength() ) this.setStartAfter( container ); } container = this.endContainer; offset = this.endOffset; if ( container.type != CKEDITOR.NODE_ELEMENT ) { if ( !offset ) this.setEndBefore( container ); else if ( offset >= container.getLength() ) this.setEndAfter( container ); } }, /** * Move the range out of bookmark nodes if they're been the container. */ optimizeBookmark: function() { var startNode = this.startContainer, endNode = this.endContainer; if ( startNode.is && startNode.is( 'span' ) && startNode.hasAttribute( '_fck_bookmark' ) ) this.setStartAt( startNode, CKEDITOR.POSITION_BEFORE_START ); if ( endNode && endNode.is && endNode.is( 'span' ) && endNode.hasAttribute( '_fck_bookmark' ) ) this.setEndAt( endNode, CKEDITOR.POSITION_AFTER_END ); }, trim : function( ignoreStart, ignoreEnd ) { var startContainer = this.startContainer, startOffset = this.startOffset, collapsed = this.collapsed; if ( ( !ignoreStart || collapsed ) && startContainer && startContainer.type == CKEDITOR.NODE_TEXT ) { // If the offset is zero, we just insert the new node before // the start. if ( !startOffset ) { startOffset = startContainer.getIndex(); startContainer = startContainer.getParent(); } // If the offset is at the end, we'll insert it after the text // node. else if ( startOffset >= startContainer.getLength() ) { startOffset = startContainer.getIndex() + 1; startContainer = startContainer.getParent(); } // In other case, we split the text node and insert the new // node at the split point. else { var nextText = startContainer.split( startOffset ); startOffset = startContainer.getIndex() + 1; startContainer = startContainer.getParent(); // Check all necessity of updating the end boundary. if ( this.startContainer.equals( this.endContainer ) ) this.setEnd( nextText, this.endOffset - this.startOffset ); else if ( startContainer.equals( this.endContainer ) ) this.endOffset += 1; } this.setStart( startContainer, startOffset ); if ( collapsed ) { this.collapse( true ); return; } } var endContainer = this.endContainer; var endOffset = this.endOffset; if ( !( ignoreEnd || collapsed ) && endContainer && endContainer.type == CKEDITOR.NODE_TEXT ) { // If the offset is zero, we just insert the new node before // the start. if ( !endOffset ) { endOffset = endContainer.getIndex(); endContainer = endContainer.getParent(); } // If the offset is at the end, we'll insert it after the text // node. else if ( endOffset >= endContainer.getLength() ) { endOffset = endContainer.getIndex() + 1; endContainer = endContainer.getParent(); } // In other case, we split the text node and insert the new // node at the split point. else { endContainer.split( endOffset ); endOffset = endContainer.getIndex() + 1; endContainer = endContainer.getParent(); } this.setEnd( endContainer, endOffset ); } }, enlarge : function( unit ) { switch ( unit ) { case CKEDITOR.ENLARGE_ELEMENT : if ( this.collapsed ) return; // Get the common ancestor. var commonAncestor = this.getCommonAncestor(); var body = this.document.getBody(); // For each boundary // a. Depending on its position, find out the first node to be checked (a sibling) or, if not available, to be enlarge. // b. Go ahead checking siblings and enlarging the boundary as much as possible until the common ancestor is not reached. After reaching the common ancestor, just save the enlargeable node to be used later. var startTop, endTop; var enlargeable, sibling, commonReached; // Indicates that the node can be added only if whitespace // is available before it. var needsWhiteSpace = false; var isWhiteSpace; var siblingText; // Process the start boundary. var container = this.startContainer; var offset = this.startOffset; if ( container.type == CKEDITOR.NODE_TEXT ) { if ( offset ) { // Check if there is any non-space text before the // offset. Otherwise, container is null. container = !CKEDITOR.tools.trim( container.substring( 0, offset ) ).length && container; // If we found only whitespace in the node, it // means that we'll need more whitespace to be able // to expand. For example, <i> can be expanded in // "A <i> [B]</i>", but not in "A<i> [B]</i>". needsWhiteSpace = !!container; } if ( container ) { if ( !( sibling = container.getPrevious() ) ) enlargeable = container.getParent(); } } else { // If we have offset, get the node preceeding it as the // first sibling to be checked. if ( offset ) sibling = container.getChild( offset - 1 ) || container.getLast(); // If there is no sibling, mark the container to be // enlarged. if ( !sibling ) enlargeable = container; } while ( enlargeable || sibling ) { if ( enlargeable && !sibling ) { // If we reached the common ancestor, mark the flag // for it. if ( !commonReached && enlargeable.equals( commonAncestor ) ) commonReached = true; if ( !body.contains( enlargeable ) ) break; // If we don't need space or this element breaks // the line, then enlarge it. if ( !needsWhiteSpace || enlargeable.getComputedStyle( 'display' ) != 'inline' ) { needsWhiteSpace = false; // If the common ancestor has been reached, // we'll not enlarge it immediately, but just // mark it to be enlarged later if the end // boundary also enlarges it. if ( commonReached ) startTop = enlargeable; else this.setStartBefore( enlargeable ); } sibling = enlargeable.getPrevious(); } // Check all sibling nodes preceeding the enlargeable // node. The node wil lbe enlarged only if none of them // blocks it. while ( sibling ) { // This flag indicates that this node has // whitespaces at the end. isWhiteSpace = false; if ( sibling.type == CKEDITOR.NODE_TEXT ) { siblingText = sibling.getText(); if ( /[^\s\ufeff]/.test( siblingText ) ) sibling = null; isWhiteSpace = /[\s\ufeff]$/.test( siblingText ); } else { // If this is a visible element. // We need to check for the bookmark attribute because IE insists on // rendering the display:none nodes we use for bookmarks. (#3363) if ( sibling.$.offsetWidth > 0 && !sibling.getAttribute( '_fck_bookmark' ) ) { // We'll accept it only if we need // whitespace, and this is an inline // element with whitespace only. if ( needsWhiteSpace && CKEDITOR.dtd.$removeEmpty[ sibling.getName() ] ) { // It must contains spaces and inline elements only. siblingText = sibling.getText(); if ( (/[^\s\ufeff]/).test( siblingText ) ) // Spaces + Zero Width No-Break Space (U+FEFF) sibling = null; else { var allChildren = sibling.$.all || sibling.$.getElementsByTagName( '*' ); for ( var i = 0, child ; child = allChildren[ i++ ] ; ) { if ( !CKEDITOR.dtd.$removeEmpty[ child.nodeName.toLowerCase() ] ) { sibling = null; break; } } } if ( sibling ) isWhiteSpace = !!siblingText.length; } else sibling = null; } } // A node with whitespaces has been found. if ( isWhiteSpace ) { // Enlarge the last enlargeable node, if we // were waiting for spaces. if ( needsWhiteSpace ) { if ( commonReached ) startTop = enlargeable; else if ( enlargeable ) this.setStartBefore( enlargeable ); } else needsWhiteSpace = true; } if ( sibling ) { var next = sibling.getPrevious(); if ( !enlargeable && !next ) { // Set the sibling as enlargeable, so it's // parent will be get later outside this while. enlargeable = sibling; sibling = null; break; } sibling = next; } else { // If sibling has been set to null, then we // need to stop enlarging. enlargeable = null; } } if ( enlargeable ) enlargeable = enlargeable.getParent(); } // Process the end boundary. This is basically the same // code used for the start boundary, with small changes to // make it work in the oposite side (to the right). This // makes it difficult to reuse the code here. So, fixes to // the above code are likely to be replicated here. container = this.endContainer; offset = this.endOffset; // Reset the common variables. enlargeable = sibling = null; commonReached = needsWhiteSpace = false; if ( container.type == CKEDITOR.NODE_TEXT ) { // Check if there is any non-space text after the // offset. Otherwise, container is null. container = !CKEDITOR.tools.trim( container.substring( offset ) ).length && container; // If we found only whitespace in the node, it // means that we'll need more whitespace to be able // to expand. For example, <i> can be expanded in // "A <i> [B]</i>", but not in "A<i> [B]</i>". needsWhiteSpace = !( container && container.getLength() ); if ( container ) { if ( !( sibling = container.getNext() ) ) enlargeable = container.getParent(); } } else { // Get the node right after the boudary to be checked // first. sibling = container.getChild( offset ); if ( !sibling ) enlargeable = container; } while ( enlargeable || sibling ) { if ( enlargeable && !sibling ) { if ( !commonReached && enlargeable.equals( commonAncestor ) ) commonReached = true; if ( !body.contains( enlargeable ) ) break; if ( !needsWhiteSpace || enlargeable.getComputedStyle( 'display' ) != 'inline' ) { needsWhiteSpace = false; if ( commonReached ) endTop = enlargeable; else if ( enlargeable ) this.setEndAfter( enlargeable ); } sibling = enlargeable.getNext(); } while ( sibling ) { isWhiteSpace = false; if ( sibling.type == CKEDITOR.NODE_TEXT ) { siblingText = sibling.getText(); if ( /[^\s\ufeff]/.test( siblingText ) ) sibling = null; isWhiteSpace = /^[\s\ufeff]/.test( siblingText ); } else { // If this is a visible element. // We need to check for the bookmark attribute because IE insists on // rendering the display:none nodes we use for bookmarks. (#3363) if ( sibling.$.offsetWidth > 0 && !sibling.getAttribute( '_fck_bookmark' ) ) { // We'll accept it only if we need // whitespace, and this is an inline // element with whitespace only. if ( needsWhiteSpace && CKEDITOR.dtd.$removeEmpty[ sibling.getName() ] ) { // It must contains spaces and inline elements only. siblingText = sibling.getText(); if ( (/[^\s\ufeff]/).test( siblingText ) ) sibling = null; else { allChildren = sibling.$.all || sibling.$.getElementsByTagName( '*' ); for ( i = 0 ; child = allChildren[ i++ ] ; ) { if ( !CKEDITOR.dtd.$removeEmpty[ child.nodeName.toLowerCase() ] ) { sibling = null; break; } } } if ( sibling ) isWhiteSpace = !!siblingText.length; } else sibling = null; } } if ( isWhiteSpace ) { if ( needsWhiteSpace ) { if ( commonReached ) endTop = enlargeable; else this.setEndAfter( enlargeable ); } } if ( sibling ) { next = sibling.getNext(); if ( !enlargeable && !next ) { enlargeable = sibling; sibling = null; break; } sibling = next; } else { // If sibling has been set to null, then we // need to stop enlarging. enlargeable = null; } } if ( enlargeable ) enlargeable = enlargeable.getParent(); } // If the common ancestor can be enlarged by both boundaries, then include it also. if ( startTop && endTop ) { commonAncestor = startTop.contains( endTop ) ? endTop : startTop; this.setStartBefore( commonAncestor ); this.setEndAfter( commonAncestor ); } break; case CKEDITOR.ENLARGE_BLOCK_CONTENTS: case CKEDITOR.ENLARGE_LIST_ITEM_CONTENTS: // Enlarging the start boundary. var walkerRange = new CKEDITOR.dom.range( this.document ); body = this.document.getBody(); walkerRange.setStartAt( body, CKEDITOR.POSITION_AFTER_START ); walkerRange.setEnd( this.startContainer, this.startOffset ); var walker = new CKEDITOR.dom.walker( walkerRange ), blockBoundary, // The node on which the enlarging should stop. tailBr, // defaultGuard = CKEDITOR.dom.walker.blockBoundary( ( unit == CKEDITOR.ENLARGE_LIST_ITEM_CONTENTS ) ? { br : 1 } : null ), // Record the encountered 'blockBoundary' for later use. boundaryGuard = function( node ) { var retval = defaultGuard( node ); if ( !retval ) blockBoundary = node; return retval; }, // Record the encounted 'tailBr' for later use. tailBrGuard = function( node ) { var retval = boundaryGuard( node ); if ( !retval && node.is && node.is( 'br' ) ) tailBr = node; return retval; }; walker.guard = boundaryGuard; enlargeable = walker.lastBackward(); // It's the body which stop the enlarging if no block boundary found. blockBoundary = blockBoundary || body; // Start the range at different position by comparing // the document position of it with 'enlargeable' node. this.setStartAt( blockBoundary, !blockBoundary.is( 'br' ) && ( !enlargeable && this.checkStartOfBlock() || enlargeable && blockBoundary.contains( enlargeable ) ) ? CKEDITOR.POSITION_AFTER_START : CKEDITOR.POSITION_AFTER_END ); // Enlarging the end boundary. walkerRange = this.clone(); walkerRange.collapse(); walkerRange.setEndAt( body, CKEDITOR.POSITION_BEFORE_END ); walker = new CKEDITOR.dom.walker( walkerRange ); // tailBrGuard only used for on range end. walker.guard = ( unit == CKEDITOR.ENLARGE_LIST_ITEM_CONTENTS ) ? tailBrGuard : boundaryGuard; blockBoundary = null; // End the range right before the block boundary node. enlargeable = walker.lastForward(); // It's the body which stop the enlarging if no block boundary found. blockBoundary = blockBoundary || body; // Start the range at different position by comparing // the document position of it with 'enlargeable' node. this.setEndAt( blockBoundary, ( !enlargeable && this.checkEndOfBlock() || enlargeable && blockBoundary.contains( enlargeable ) ) ? CKEDITOR.POSITION_BEFORE_END : CKEDITOR.POSITION_BEFORE_START ); // We must include the <br> at the end of range if there's // one and we're expanding list item contents if ( tailBr ) this.setEndAfter( tailBr ); } }, /** * Descrease the range to make sure that boundaries * always anchor beside text nodes or innermost element. * @param {Number} mode ( CKEDITOR.SHRINK_ELEMENT | CKEDITOR.SHRINK_TEXT ) The shrinking mode. */ shrink : function( mode ) { // Unable to shrink a collapsed range. if ( !this.collapsed ) { mode = mode || CKEDITOR.SHRINK_TEXT; var walkerRange = this.clone(); var startContainer = this.startContainer, endContainer = this.endContainer, startOffset = this.startOffset, endOffset = this.endOffset, collapsed = this.collapsed; // Whether the start/end boundary is moveable. var moveStart = 1, moveEnd = 1; if ( startContainer && startContainer.type == CKEDITOR.NODE_TEXT ) { if ( !startOffset ) walkerRange.setStartBefore( startContainer ); else if ( startOffset >= startContainer.getLength( ) ) walkerRange.setStartAfter( startContainer ); else { // Enlarge the range properly to avoid walker making // DOM changes caused by triming the text nodes later. walkerRange.setStartBefore( startContainer ); moveStart = 0; } } if ( endContainer && endContainer.type == CKEDITOR.NODE_TEXT ) { if ( !endOffset ) walkerRange.setEndBefore( endContainer ); else if ( endOffset >= endContainer.getLength( ) ) walkerRange.setEndAfter( endContainer ); else { walkerRange.setEndAfter( endContainer ); moveEnd = 0; } } var walker = new CKEDITOR.dom.walker( walkerRange ); walker.evaluator = function( node ) { return node.type == ( mode == CKEDITOR.SHRINK_ELEMENT ? CKEDITOR.NODE_ELEMENT : CKEDITOR.NODE_TEXT ); }; var currentElement; walker.guard = function( node, movingOut ) { // Stop when we're shrink in element mode while encountering a text node. if ( mode == CKEDITOR.SHRINK_ELEMENT && node.type == CKEDITOR.NODE_TEXT ) return false; // Stop when we've already walked "through" an element. if ( movingOut && node.equals( currentElement ) ) return false; if ( !movingOut && node.type == CKEDITOR.NODE_ELEMENT ) currentElement = node; return true; }; if ( moveStart ) { var textStart = walker[ mode == CKEDITOR.SHRINK_ELEMENT ? 'lastForward' : 'next'](); textStart && this.setStartBefore( textStart ); } if ( moveEnd ) { walker.reset(); var textEnd = walker[ mode == CKEDITOR.SHRINK_ELEMENT ? 'lastBackward' : 'previous'](); textEnd && this.setEndAfter( textEnd ); } return !!( moveStart || moveEnd ); } }, /** * Inserts a node at the start of the range. The range will be expanded * the contain the node. */ insertNode : function( node ) { this.optimizeBookmark(); this.trim( false, true ); var startContainer = this.startContainer; var startOffset = this.startOffset; var nextNode = startContainer.getChild( startOffset ); if ( nextNode ) node.insertBefore( nextNode ); else startContainer.append( node ); // Check if we need to update the end boundary. if ( node.getParent().equals( this.endContainer ) ) this.endOffset++; // Expand the range to embrace the new node. this.setStartBefore( node ); }, moveToPosition : function( node, position ) { this.setStartAt( node, position ); this.collapse( true ); }, selectNodeContents : function( node ) { this.setStart( node, 0 ); this.setEnd( node, node.type == CKEDITOR.NODE_TEXT ? node.getLength() : node.getChildCount() ); }, /** * Sets the start position of a Range. * @param {CKEDITOR.dom.node} startNode The node to start the range. * @param {Number} startOffset An integer greater than or equal to zero * representing the offset for the start of the range from the start * of startNode. */ setStart : function( startNode, startOffset ) { // W3C requires a check for the new position. If it is after the end // boundary, the range should be collapsed to the new start. It seams // we will not need this check for our use of this class so we can // ignore it for now. this.startContainer = startNode; this.startOffset = startOffset; if ( !this.endContainer ) { this.endContainer = startNode; this.endOffset = startOffset; } updateCollapsed( this ); }, /** * Sets the end position of a Range. * @param {CKEDITOR.dom.node} endNode The node to end the range. * @param {Number} endOffset An integer greater than or equal to zero * representing the offset for the end of the range from the start * of endNode. */ setEnd : function( endNode, endOffset ) { // W3C requires a check for the new position. If it is before the start // boundary, the range should be collapsed to the new end. It seams we // will not need this check for our use of this class so we can ignore // it for now. this.endContainer = endNode; this.endOffset = endOffset; if ( !this.startContainer ) { this.startContainer = endNode; this.startOffset = endOffset; } updateCollapsed( this ); }, setStartAfter : function( node ) { this.setStart( node.getParent(), node.getIndex() + 1 ); }, setStartBefore : function( node ) { this.setStart( node.getParent(), node.getIndex() ); }, setEndAfter : function( node ) { this.setEnd( node.getParent(), node.getIndex() + 1 ); }, setEndBefore : function( node ) { this.setEnd( node.getParent(), node.getIndex() ); }, setStartAt : function( node, position ) { switch( position ) { case CKEDITOR.POSITION_AFTER_START : this.setStart( node, 0 ); break; case CKEDITOR.POSITION_BEFORE_END : if ( node.type == CKEDITOR.NODE_TEXT ) this.setStart( node, node.getLength() ); else this.setStart( node, node.getChildCount() ); break; case CKEDITOR.POSITION_BEFORE_START : this.setStartBefore( node ); break; case CKEDITOR.POSITION_AFTER_END : this.setStartAfter( node ); } updateCollapsed( this ); }, setEndAt : function( node, position ) { switch( position ) { case CKEDITOR.POSITION_AFTER_START : this.setEnd( node, 0 ); break; case CKEDITOR.POSITION_BEFORE_END : if ( node.type == CKEDITOR.NODE_TEXT ) this.setEnd( node, node.getLength() ); else this.setEnd( node, node.getChildCount() ); break; case CKEDITOR.POSITION_BEFORE_START : this.setEndBefore( node ); break; case CKEDITOR.POSITION_AFTER_END : this.setEndAfter( node ); } updateCollapsed( this ); }, fixBlock : function( isStart, blockTag ) { var bookmark = this.createBookmark(), fixedBlock = this.document.createElement( blockTag ); this.collapse( isStart ); this.enlarge( CKEDITOR.ENLARGE_BLOCK_CONTENTS ); this.extractContents().appendTo( fixedBlock ); fixedBlock.trim(); if ( !CKEDITOR.env.ie ) fixedBlock.appendBogus(); this.insertNode( fixedBlock ); this.moveToBookmark( bookmark ); return fixedBlock; }, splitBlock : function( blockTag ) { var startPath = new CKEDITOR.dom.elementPath( this.startContainer ), endPath = new CKEDITOR.dom.elementPath( this.endContainer ); var startBlockLimit = startPath.blockLimit, endBlockLimit = endPath.blockLimit; var startBlock = startPath.block, endBlock = endPath.block; var elementPath = null; // Do nothing if the boundaries are in different block limits. if ( !startBlockLimit.equals( endBlockLimit ) ) return null; // Get or fix current blocks. if ( blockTag != 'br' ) { if ( !startBlock ) { startBlock = this.fixBlock( true, blockTag ); endBlock = new CKEDITOR.dom.elementPath( this.endContainer ).block; } if ( !endBlock ) endBlock = this.fixBlock( false, blockTag ); } // Get the range position. var isStartOfBlock = startBlock && this.checkStartOfBlock(), isEndOfBlock = endBlock && this.checkEndOfBlock(); // Delete the current contents. // TODO: Why is 2.x doing CheckIsEmpty()? this.deleteContents(); if ( startBlock && startBlock.equals( endBlock ) ) { if ( isEndOfBlock ) { elementPath = new CKEDITOR.dom.elementPath( this.startContainer ); this.moveToPosition( endBlock, CKEDITOR.POSITION_AFTER_END ); endBlock = null; } else if ( isStartOfBlock ) { elementPath = new CKEDITOR.dom.elementPath( this.startContainer ); this.moveToPosition( startBlock, CKEDITOR.POSITION_BEFORE_START ); startBlock = null; } else { endBlock = this.splitElement( startBlock ); // In Gecko, the last child node must be a bogus <br>. // Note: bogus <br> added under <ul> or <ol> would cause // lists to be incorrectly rendered. if ( !CKEDITOR.env.ie && !startBlock.is( 'ul', 'ol') ) startBlock.appendBogus() ; } } return { previousBlock : startBlock, nextBlock : endBlock, wasStartOfBlock : isStartOfBlock, wasEndOfBlock : isEndOfBlock, elementPath : elementPath }; }, /** * Branch the specified element from the collapsed range position and * place the caret between the two result branches. * Note: The range must be collapsed and been enclosed by this element. * @param {CKEDITOR.dom.element} element * @return {CKEDITOR.dom.element} Root element of the new branch after the split. */ splitElement : function( toSplit ) { if ( !this.collapsed ) return null; // Extract the contents of the block from the selection point to the end // of its contents. this.setEndAt( toSplit, CKEDITOR.POSITION_BEFORE_END ); var documentFragment = this.extractContents(); // Duplicate the element after it. var clone = toSplit.clone( false ); // Place the extracted contents into the duplicated element. documentFragment.appendTo( clone ); clone.insertAfter( toSplit ); this.moveToPosition( toSplit, CKEDITOR.POSITION_AFTER_END ); return clone; }, /** * Check whether current range is on the inner edge of the specified element. * @param {Number} checkType ( CKEDITOR.START | CKEDITOR.END ) The checking side. * @param {CKEDITOR.dom.element} element The target element to check. */ checkBoundaryOfElement : function( element, checkType ) { var walkerRange = this.clone(); // Expand the range to element boundary. walkerRange[ checkType == CKEDITOR.START ? 'setStartAt' : 'setEndAt' ] ( element, checkType == CKEDITOR.START ? CKEDITOR.POSITION_AFTER_START : CKEDITOR.POSITION_BEFORE_END ); var walker = new CKEDITOR.dom.walker( walkerRange ), retval = false; walker.evaluator = elementBoundaryEval; return walker[ checkType == CKEDITOR.START ? 'checkBackward' : 'checkForward' ](); }, // Calls to this function may produce changes to the DOM. The range may // be updated to reflect such changes. checkStartOfBlock : function() { var startContainer = this.startContainer, startOffset = this.startOffset; // If the starting node is a text node, and non-empty before the offset, // then we're surely not at the start of block. if ( startOffset && startContainer.type == CKEDITOR.NODE_TEXT ) { var textBefore = CKEDITOR.tools.ltrim( startContainer.substring( 0, startOffset ) ); if ( textBefore.length ) return false; } // Antecipate the trim() call here, so the walker will not make // changes to the DOM, which would not get reflected into this // range otherwise. this.trim(); // We need to grab the block element holding the start boundary, so // let's use an element path for it. var path = new CKEDITOR.dom.elementPath( this.startContainer ); // Creates a range starting at the block start until the range start. var walkerRange = this.clone(); walkerRange.collapse( true ); walkerRange.setStartAt( path.block || path.blockLimit, CKEDITOR.POSITION_AFTER_START ); var walker = new CKEDITOR.dom.walker( walkerRange ); walker.evaluator = getCheckStartEndBlockEvalFunction( true ); return walker.checkBackward(); }, checkEndOfBlock : function() { var endContainer = this.endContainer, endOffset = this.endOffset; // If the ending node is a text node, and non-empty after the offset, // then we're surely not at the end of block. if ( endContainer.type == CKEDITOR.NODE_TEXT ) { var textAfter = CKEDITOR.tools.rtrim( endContainer.substring( endOffset ) ); if ( textAfter.length ) return false; } // Antecipate the trim() call here, so the walker will not make // changes to the DOM, which would not get reflected into this // range otherwise. this.trim(); // We need to grab the block element holding the start boundary, so // let's use an element path for it. var path = new CKEDITOR.dom.elementPath( this.endContainer ); // Creates a range starting at the block start until the range start. var walkerRange = this.clone(); walkerRange.collapse( false ); walkerRange.setEndAt( path.block || path.blockLimit, CKEDITOR.POSITION_BEFORE_END ); var walker = new CKEDITOR.dom.walker( walkerRange ); walker.evaluator = getCheckStartEndBlockEvalFunction( false ); return walker.checkForward(); }, /** * Moves the range boundaries to the first/end editing point inside an * element. For example, in an element tree like * "&lt;p&gt;&lt;b&gt;&lt;i&gt;&lt;/i&gt;&lt;/b&gt; Text&lt;/p&gt;", the start editing point is * "&lt;p&gt;&lt;b&gt;&lt;i&gt;^&lt;/i&gt;&lt;/b&gt; Text&lt;/p&gt;" (inside &lt;i&gt;). * @param {CKEDITOR.dom.element} el The element into which look for the * editing spot. * @param {Boolean} isMoveToEnd Whether move to the end editable position. */ moveToElementEditablePosition : function( el, isMoveToEnd ) { var isEditable; // Empty elements are rejected. if ( CKEDITOR.dtd.$empty[ el.getName() ] ) return false; while ( el && el.type == CKEDITOR.NODE_ELEMENT ) { isEditable = el.isEditable(); // If an editable element is found, move inside it. if ( isEditable ) this.moveToPosition( el, isMoveToEnd ? CKEDITOR.POSITION_BEFORE_END : CKEDITOR.POSITION_AFTER_START ); // Stop immediately if we've found a non editable inline element (e.g <img>). else if ( CKEDITOR.dtd.$inline[ el.getName() ] ) { this.moveToPosition( el, isMoveToEnd ? CKEDITOR.POSITION_AFTER_END : CKEDITOR.POSITION_BEFORE_START ); return true; } // Non-editable non-inline elements are to be bypassed, getting the next one. if ( CKEDITOR.dtd.$empty[ el.getName() ] ) el = el[ isMoveToEnd ? 'getPrevious' : 'getNext' ]( nonWhitespaceOrBookmarkEval ); else el = el[ isMoveToEnd ? 'getLast' : 'getFirst' ]( nonWhitespaceOrBookmarkEval ); // Stop immediately if we've found a text node. if ( el && el.type == CKEDITOR.NODE_TEXT ) { this.moveToPosition( el, isMoveToEnd ? CKEDITOR.POSITION_AFTER_END : CKEDITOR.POSITION_BEFORE_START ); return true; } } return isEditable; }, /** *@see {CKEDITOR.dom.range.moveToElementEditablePosition} */ moveToElementEditStart : function( target ) { return this.moveToElementEditablePosition( target ); }, /** *@see {CKEDITOR.dom.range.moveToElementEditablePosition} */ moveToElementEditEnd : function( target ) { return this.moveToElementEditablePosition( target, true ); }, /** * Get the single node enclosed within the range if there's one. */ getEnclosedNode : function() { var walkerRange = this.clone(), walker = new CKEDITOR.dom.walker( walkerRange ), isNotBookmarks = CKEDITOR.dom.walker.bookmark( true ), isNotWhitespaces = CKEDITOR.dom.walker.whitespaces( true ), evaluator = function( node ) { return isNotWhitespaces( node ) && isNotBookmarks( node ); }; walkerRange.evaluator = evaluator; var node = walker.next(); walker.reset(); return node && node.equals( walker.previous() ) ? node : null; }, getTouchedStartNode : function() { var container = this.startContainer ; if ( this.collapsed || container.type != CKEDITOR.NODE_ELEMENT ) return container ; return container.getChild( this.startOffset ) || container ; }, getTouchedEndNode : function() { var container = this.endContainer ; if ( this.collapsed || container.type != CKEDITOR.NODE_ELEMENT ) return container ; return container.getChild( this.endOffset - 1 ) || container ; } }; })(); CKEDITOR.POSITION_AFTER_START = 1; // <element>^contents</element> "^text" CKEDITOR.POSITION_BEFORE_END = 2; // <element>contents^</element> "text^" CKEDITOR.POSITION_BEFORE_START = 3; // ^<element>contents</element> ^"text" CKEDITOR.POSITION_AFTER_END = 4; // <element>contents</element>^ "text" CKEDITOR.ENLARGE_ELEMENT = 1; CKEDITOR.ENLARGE_BLOCK_CONTENTS = 2; CKEDITOR.ENLARGE_LIST_ITEM_CONTENTS = 3; /** * Check boundary types. * @see CKEDITOR.dom.range::checkBoundaryOfElement */ CKEDITOR.START = 1; CKEDITOR.END = 2; CKEDITOR.STARTEND = 3; CKEDITOR.SHRINK_ELEMENT = 1; CKEDITOR.SHRINK_TEXT = 2;
{ "content_hash": "812cd6789936e6e1e70478ba9206a582", "timestamp": "", "source": "github", "line_count": 1833, "max_line_length": 212, "avg_line_length": 29.623567921440262, "alnum_prop": 0.6333885819521179, "repo_name": "raulcastro/villaaqua", "id": "919b7816ff8ff24f8ca7ab6e137a73aecbfa41a8", "size": "54446", "binary": false, "copies": "8", "ref": "refs/heads/master", "path": "js/ckeditor/_source/core/dom/range.js", "mode": "33261", "license": "apache-2.0", "language": [ { "name": "ApacheConf", "bytes": "4590" }, { "name": "CSS", "bytes": "1169541" }, { "name": "HTML", "bytes": "109652" }, { "name": "JavaScript", "bytes": "2688343" }, { "name": "PHP", "bytes": "2400172" }, { "name": "Shell", "bytes": "152" } ], "symlink_target": "" }
/* * * * Sankey diagram module * * (c) 2010-2020 Torstein Honsi * * License: www.highcharts.com/license * * !!!!!!! SOURCE GETS TRANSPILED BY TYPESCRIPT. EDIT TS FILE ONLY. !!!!!!! * * */ 'use strict'; import H from '../parts/Globals.js'; /** * A node in a sankey diagram. * * @interface Highcharts.SankeyNodeObject * @extends Highcharts.Point * @product highcharts */ /** * The color of the auto generated node. * * @name Highcharts.SankeyNodeObject#color * @type {Highcharts.ColorString|Highcharts.GradientColorObject|Highcharts.PatternObject} */ /** * The color index of the auto generated node, especially for use in styled * mode. * * @name Highcharts.SankeyNodeObject#colorIndex * @type {number} */ /** * An optional column index of where to place the node. The default behaviour is * to place it next to the preceding node. * * @see {@link https://jsfiddle.net/gh/get/library/pure/highcharts/highcharts/tree/master/samples/highcharts/plotoptions/sankey-node-column/|Highcharts-Demo:} * Specified node column * * @name Highcharts.SankeyNodeObject#column * @type {number} * @since 6.0.5 */ /** * The id of the auto-generated node, refering to the `from` or `to` setting of * the link. * * @name Highcharts.SankeyNodeObject#id * @type {string} */ /** * The name to display for the node in data labels and tooltips. Use this when * the name is different from the `id`. Where the id must be unique for each * node, this is not necessary for the name. * * @see {@link https://jsfiddle.net/gh/get/library/pure/highcharts/highcharts/tree/master/samples/highcharts/css/sankey/|Highcharts-Demo:} * Sankey diagram with node options * * @name Highcharts.SankeyNodeObject#name * @type {string} * @product highcharts */ /** * The vertical offset of a node in terms of weight. Positive values shift the * node downwards, negative shift it upwards. * * @see {@link https://jsfiddle.net/gh/get/library/pure/highcharts/highcharts/tree/master/samples/highcharts/plotoptions/sankey-node-column/|Highcharts-Demo:} * Specified node offset * * @name Highcharts.SankeyNodeObject#offset * @type {number} * @default 0 * @since 6.0.5 */ /** * Formatter callback function. * * @callback Highcharts.SeriesSankeyDataLabelsFormatterCallbackFunction * * @param {Highcharts.SeriesSankeyDataLabelsFormatterContextObject|Highcharts.PointLabelObject} this * Data label context to format * * @return {string|undefined} * Formatted data label text */ /** * Context for the node formatter function. * * @interface Highcharts.SeriesSankeyDataLabelsFormatterContextObject * @extends Highcharts.PointLabelObject */ /** * The node object. The node name, if defined, is available through * `this.point.name`. * @name Highcharts.SeriesSankeyDataLabelsFormatterContextObject#point * @type {Highcharts.SankeyNodeObject} */ import Color from '../parts/Color.js'; import Point from '../parts/Point.js'; import U from '../parts/Utilities.js'; var defined = U.defined, find = U.find, isObject = U.isObject, merge = U.merge, pick = U.pick, relativeLength = U.relativeLength, seriesType = U.seriesType, stableSort = U.stableSort; import '../parts/Options.js'; import '../mixins/nodes.js'; import mixinTreeSeries from '../mixins/tree-series.js'; var getLevelOptions = mixinTreeSeries.getLevelOptions; // eslint-disable-next-line valid-jsdoc /** * @private */ var getDLOptions = function getDLOptions(params) { var optionsPoint = (isObject(params.optionsPoint) ? params.optionsPoint.dataLabels : {}), optionsLevel = (isObject(params.level) ? params.level.dataLabels : {}), options = merge({ style: {} }, optionsLevel, optionsPoint); return options; }; /** * @private * @class * @name Highcharts.seriesTypes.sankey * * @augments Highcharts.Series */ seriesType('sankey', 'column', /** * A sankey diagram is a type of flow diagram, in which the width of the * link between two nodes is shown proportionally to the flow quantity. * * @sample highcharts/demo/sankey-diagram/ * Sankey diagram * @sample highcharts/plotoptions/sankey-inverted/ * Inverted sankey diagram * @sample highcharts/plotoptions/sankey-outgoing * Sankey diagram with outgoing links * * @extends plotOptions.column * @since 6.0.0 * @product highcharts * @excluding animationLimit, boostThreshold, borderRadius, * crisp, cropThreshold, colorAxis, colorKey, depth, dragDrop, * edgeColor, edgeWidth, findNearestPointBy, grouping, * groupPadding, groupZPadding, maxPointWidth, negativeColor, * pointInterval, pointIntervalUnit, pointPadding, * pointPlacement, pointRange, pointStart, pointWidth, * shadow, softThreshold, stacking, threshold, zoneAxis, * zones, minPointLength, dataSorting * @requires modules/sankey * @optionparent plotOptions.sankey */ { borderWidth: 0, colorByPoint: true, /** * Higher numbers makes the links in a sankey diagram or dependency * wheelrender more curved. A `curveFactor` of 0 makes the lines * straight. * * @private */ curveFactor: 0.33, /** * Options for the data labels appearing on top of the nodes and links. * For sankey charts, data labels are visible for the nodes by default, * but hidden for links. This is controlled by modifying the * `nodeFormat`, and the `format` that applies to links and is an empty * string by default. * * @declare Highcharts.SeriesSankeyDataLabelsOptionsObject * * @private */ dataLabels: { enabled: true, backgroundColor: 'none', crop: false, /** * The * [format string](https://www.highcharts.com/docs/chart-concepts/labels-and-string-formatting) * specifying what to show for _nodes_ in the sankey diagram. By * default the `nodeFormatter` returns `{point.name}`. * * @sample highcharts/plotoptions/sankey-link-datalabels/ * Node and link data labels * * @type {string} */ nodeFormat: void 0, // eslint-disable-next-line valid-jsdoc /** * Callback to format data labels for _nodes_ in the sankey diagram. * The `nodeFormat` option takes precedence over the * `nodeFormatter`. * * @type {Highcharts.SeriesSankeyDataLabelsFormatterCallbackFunction} * @since 6.0.2 */ nodeFormatter: function () { return this.point.name; }, format: void 0, // eslint-disable-next-line valid-jsdoc /** * @type {Highcharts.SeriesSankeyDataLabelsFormatterCallbackFunction} */ formatter: function () { return; }, inside: true }, /** * @ignore-option * * @private */ inactiveOtherPoints: true, /** * Set options on specific levels. Takes precedence over series options, * but not node and link options. * * @sample highcharts/demo/sunburst * Sunburst chart * * @type {Array<*>} * @since 7.1.0 * @apioption plotOptions.sankey.levels */ /** * Can set `borderColor` on all nodes which lay on the same level. * * @type {Highcharts.ColorString} * @apioption plotOptions.sankey.levels.borderColor */ /** * Can set `borderWidth` on all nodes which lay on the same level. * * @type {number} * @apioption plotOptions.sankey.levels.borderWidth */ /** * Can set `color` on all nodes which lay on the same level. * * @type {Highcharts.ColorString|Highcharts.GradientColorObject|Highcharts.PatternObject} * @apioption plotOptions.sankey.levels.color */ /** * Can set `colorByPoint` on all nodes which lay on the same level. * * @type {boolean} * @default true * @apioption plotOptions.sankey.levels.colorByPoint */ /** * Can set `dataLabels` on all points which lay on the same level. * * @extends plotOptions.sankey.dataLabels * @apioption plotOptions.sankey.levels.dataLabels */ /** * Decides which level takes effect from the options set in the levels * object. * * @type {number} * @apioption plotOptions.sankey.levels.level */ /** * Can set `linkOpacity` on all points which lay on the same level. * * @type {number} * @default 0.5 * @apioption plotOptions.sankey.levels.linkOpacity */ /** * Can set `states` on all nodes and points which lay on the same level. * * @extends plotOptions.sankey.states * @apioption plotOptions.sankey.levels.states */ /** * Opacity for the links between nodes in the sankey diagram. * * @private */ linkOpacity: 0.5, /** * The minimal width for a line of a sankey. By default, * 0 values are not shown. * * @sample highcharts/plotoptions/sankey-minlinkwidth * Sankey diagram with minimal link height * * @type {number} * @since 7.1.3 * @default 0 * @apioption plotOptions.sankey.minLinkWidth * * @private */ minLinkWidth: 0, /** * The pixel width of each node in a sankey diagram or dependency wheel, * or the height in case the chart is inverted. * * @private */ nodeWidth: 20, /** * The padding between nodes in a sankey diagram or dependency wheel, in * pixels. * * If the number of nodes is so great that it is possible to lay them * out within the plot area with the given `nodePadding`, they will be * rendered with a smaller padding as a strategy to avoid overflow. * * @private */ nodePadding: 10, showInLegend: false, states: { hover: { /** * Opacity for the links between nodes in the sankey diagram in * hover mode. */ linkOpacity: 1 }, /** * The opposite state of a hover for a single point node/link. * * @declare Highcharts.SeriesStatesInactiveOptionsObject */ inactive: { /** * Opacity for the links between nodes in the sankey diagram in * inactive mode. */ linkOpacity: 0.1, /** * Opacity of inactive markers. * * @type {number} * @apioption plotOptions.series.states.inactive.opacity */ opacity: 0.1, /** * Animation when not hovering over the marker. * * @type {boolean|Highcharts.AnimationOptionsObject} * @apioption plotOptions.series.states.inactive.animation */ animation: { /** @internal */ duration: 50 } } }, tooltip: { /** * A callback for defining the format for _nodes_ in the chart's * tooltip, as opposed to links. * * @type {Highcharts.FormatterCallbackFunction<Highcharts.SankeyNodeObject>} * @since 6.0.2 * @apioption plotOptions.sankey.tooltip.nodeFormatter */ /** * Whether the tooltip should follow the pointer or stay fixed on * the item. */ followPointer: true, headerFormat: '<span style="font-size: 10px">{series.name}</span><br/>', pointFormat: '{point.fromNode.name} \u2192 {point.toNode.name}: <b>{point.weight}</b><br/>', /** * The * [format string](https://www.highcharts.com/docs/chart-concepts/labels-and-string-formatting) * specifying what to show for _nodes_ in tooltip of a diagram * series, as opposed to links. */ nodeFormat: '{point.name}: <b>{point.sum}</b><br/>' } }, { isCartesian: false, invertable: true, forceDL: true, orderNodes: true, pointArrayMap: ['from', 'to'], // Create a single node that holds information on incoming and outgoing // links. createNode: H.NodesMixin.createNode, searchPoint: H.noop, setData: H.NodesMixin.setData, destroy: H.NodesMixin.destroy, /* eslint-disable valid-jsdoc */ /** * Overridable function to get node padding, overridden in dependency * wheel series type. * @private */ getNodePadding: function () { var nodePadding = this.options.nodePadding || 0; // If the number of columns is so great that they will overflow with // the given nodePadding, we sacrifice the padding in order to // render all nodes within the plot area (#11917). if (this.nodeColumns) { var maxLength = this.nodeColumns.reduce(function (acc, col) { return Math.max(acc, col.length); }, 0); if (maxLength * nodePadding > this.chart.plotSizeY) { nodePadding = this.chart.plotSizeY / maxLength; } } return nodePadding; }, /** * Create a node column. * @private */ createNodeColumn: function () { var series = this, chart = this.chart, column = []; column.sum = function () { return this.reduce(function (sum, node) { return sum + node.getSum(); }, 0); }; // Get the offset in pixels of a node inside the column. column.offset = function (node, factor) { var offset = 0, totalNodeOffset, nodePadding = series.nodePadding; for (var i = 0; i < column.length; i++) { var sum = column[i].getSum(); var height = Math.max(sum * factor, series.options.minLinkWidth); if (sum) { totalNodeOffset = height + nodePadding; } else { // If node sum equals 0 nodePadding is missed #12453 totalNodeOffset = 0; } if (column[i] === node) { return { relativeTop: offset + relativeLength(node.options.offset || 0, totalNodeOffset) }; } offset += totalNodeOffset; } }; // Get the top position of the column in pixels. column.top = function (factor) { var nodePadding = series.nodePadding; var height = this.reduce(function (height, node) { if (height > 0) { height += nodePadding; } var nodeHeight = Math.max(node.getSum() * factor, series.options.minLinkWidth); height += nodeHeight; return height; }, 0); return (chart.plotSizeY - height) / 2; }; return column; }, /** * Create node columns by analyzing the nodes and the relations between * incoming and outgoing links. * @private */ createNodeColumns: function () { var columns = []; this.nodes.forEach(function (node) { var fromColumn = -1, fromNode, i, point; if (!defined(node.options.column)) { // No links to this node, place it left if (node.linksTo.length === 0) { node.column = 0; // There are incoming links, place it to the right of the // highest order column that links to this one. } else { for (i = 0; i < node.linksTo.length; i++) { point = node.linksTo[0]; if (point.fromNode.column > fromColumn) { fromNode = point.fromNode; fromColumn = fromNode.column; } } node.column = fromColumn + 1; // Hanging layout for organization chart if (fromNode && fromNode.options.layout === 'hanging') { node.hangsFrom = fromNode; i = -1; // Reuse existing variable i find(fromNode.linksFrom, function (link, index) { var found = link.toNode === node; if (found) { i = index; } return found; }); node.column += i; } } } if (!columns[node.column]) { columns[node.column] = this.createNodeColumn(); } columns[node.column].push(node); }, this); // Fill in empty columns (#8865) for (var i = 0; i < columns.length; i++) { if (typeof columns[i] === 'undefined') { columns[i] = this.createNodeColumn(); } } return columns; }, /** * Define hasData function for non-cartesian series. * @private * @return {boolean} * Returns true if the series has points at all. */ hasData: function () { return !!this.processedXData.length; // != 0 }, /** * Return the presentational attributes. * @private */ pointAttribs: function (point, state) { var series = this, level = point.isNode ? point.level : point.fromNode.level, levelOptions = series.mapOptionsToLevel[level || 0] || {}, options = point.options, stateOptions = (levelOptions.states && levelOptions.states[state]) || {}, values = [ 'colorByPoint', 'borderColor', 'borderWidth', 'linkOpacity' ].reduce(function (obj, key) { obj[key] = pick(stateOptions[key], options[key], levelOptions[key], series.options[key]); return obj; }, {}), color = pick(stateOptions.color, options.color, values.colorByPoint ? point.color : levelOptions.color); // Node attributes if (point.isNode) { return { fill: color, stroke: values.borderColor, 'stroke-width': values.borderWidth }; } // Link attributes return { fill: Color.parse(color).setOpacity(values.linkOpacity).get() }; }, /** * Extend generatePoints by adding the nodes, which are Point objects * but pushed to the this.nodes array. * @private */ generatePoints: function () { H.NodesMixin.generatePoints.apply(this, arguments); /** * Order the nodes, starting with the root node(s). (#9818) * @private */ function order(node, level) { // Prevents circular recursion: if (typeof node.level === 'undefined') { node.level = level; node.linksFrom.forEach(function (link) { if (link.toNode) { order(link.toNode, level + 1); } }); } } if (this.orderNodes) { this.nodes // Identify the root node(s) .filter(function (node) { return node.linksTo.length === 0; }) // Start by the root node(s) and recursively set the level // on all following nodes. .forEach(function (node) { order(node, 0); }); stableSort(this.nodes, function (a, b) { return a.level - b.level; }); } }, /** * Run translation operations for one node. * @private */ translateNode: function (node, column) { var translationFactor = this.translationFactor, chart = this.chart, options = this.options, sum = node.getSum(), height = Math.max(Math.round(sum * translationFactor), this.options.minLinkWidth), crisp = Math.round(options.borderWidth) % 2 / 2, nodeOffset = column.offset(node, translationFactor), fromNodeTop = Math.floor(pick(nodeOffset.absoluteTop, (column.top(translationFactor) + nodeOffset.relativeTop))) + crisp, left = Math.floor(this.colDistance * node.column + options.borderWidth / 2) + crisp, nodeLeft = chart.inverted ? chart.plotSizeX - left : left, nodeWidth = Math.round(this.nodeWidth); node.sum = sum; // If node sum is 0, don't render the rect #12453 if (sum) { // Draw the node node.shapeType = 'rect'; node.nodeX = nodeLeft; node.nodeY = fromNodeTop; if (!chart.inverted) { node.shapeArgs = { x: nodeLeft, y: fromNodeTop, width: node.options.width || options.width || nodeWidth, height: node.options.height || options.height || height }; } else { node.shapeArgs = { x: nodeLeft - nodeWidth, y: chart.plotSizeY - fromNodeTop - height, width: node.options.height || options.height || nodeWidth, height: node.options.width || options.width || height }; } node.shapeArgs.display = node.hasShape() ? '' : 'none'; // Calculate data label options for the point node.dlOptions = getDLOptions({ level: this.mapOptionsToLevel[node.level], optionsPoint: node.options }); // Pass test in drawPoints node.plotY = 1; // Set the anchor position for tooltips node.tooltipPos = chart.inverted ? [ chart.plotSizeY - node.shapeArgs.y - node.shapeArgs.height / 2, chart.plotSizeX - node.shapeArgs.x - node.shapeArgs.width / 2 ] : [ node.shapeArgs.x + node.shapeArgs.width / 2, node.shapeArgs.y + node.shapeArgs.height / 2 ]; } else { node.dlOptions = { enabled: false }; } }, /** * Run translation operations for one link. * @private */ translateLink: function (point) { var getY = function (node, fromOrTo) { var _a; var linkTop = (node.offset(point, fromOrTo) * translationFactor); var y = Math.min(node.nodeY + linkTop, // Prevent links from spilling below the node (#12014) node.nodeY + ((_a = node.shapeArgs) === null || _a === void 0 ? void 0 : _a.height) - linkHeight); return y; }; var fromNode = point.fromNode, toNode = point.toNode, chart = this.chart, translationFactor = this.translationFactor, linkHeight = Math.max(point.weight * translationFactor, this.options.minLinkWidth), options = this.options, curvy = ((chart.inverted ? -this.colDistance : this.colDistance) * options.curveFactor), fromY = getY(fromNode, 'linksFrom'), toY = getY(toNode, 'linksTo'), nodeLeft = fromNode.nodeX, nodeW = this.nodeWidth, right = toNode.column * this.colDistance, outgoing = point.outgoing, straight = right > nodeLeft + nodeW; if (chart.inverted) { fromY = chart.plotSizeY - fromY; toY = (chart.plotSizeY || 0) - toY; right = chart.plotSizeX - right; nodeW = -nodeW; linkHeight = -linkHeight; straight = nodeLeft > right; } point.shapeType = 'path'; point.linkBase = [ fromY, fromY + linkHeight, toY, toY + linkHeight ]; // Links going from left to right if (straight && typeof toY === 'number') { point.shapeArgs = { d: [ ['M', nodeLeft + nodeW, fromY], [ 'C', nodeLeft + nodeW + curvy, fromY, right - curvy, toY, right, toY ], ['L', right + (outgoing ? nodeW : 0), toY + linkHeight / 2], ['L', right, toY + linkHeight], [ 'C', right - curvy, toY + linkHeight, nodeLeft + nodeW + curvy, fromY + linkHeight, nodeLeft + nodeW, fromY + linkHeight ], ['Z'] ] }; // Experimental: Circular links pointing backwards. In // v6.1.0 this breaks the rendering completely, so even // this experimental rendering is an improvement. #8218. // @todo // - Make room for the link in the layout // - Automatically determine if the link should go up or // down. } else if (typeof toY === 'number') { var bend = 20, vDist = chart.plotHeight - fromY - linkHeight, x1 = right - bend - linkHeight, x2 = right - bend, x3 = right, x4 = nodeLeft + nodeW, x5 = x4 + bend, x6 = x5 + linkHeight, fy1 = fromY, fy2 = fromY + linkHeight, fy3 = fy2 + bend, y4 = fy3 + vDist, y5 = y4 + bend, y6 = y5 + linkHeight, ty1 = toY, ty2 = ty1 + linkHeight, ty3 = ty2 + bend, cfy1 = fy2 - linkHeight * 0.7, cy2 = y5 + linkHeight * 0.7, cty1 = ty2 - linkHeight * 0.7, cx1 = x3 - linkHeight * 0.7, cx2 = x4 + linkHeight * 0.7; point.shapeArgs = { d: [ ['M', x4, fy1], ['C', cx2, fy1, x6, cfy1, x6, fy3], ['L', x6, y4], ['C', x6, cy2, cx2, y6, x4, y6], ['L', x3, y6], ['C', cx1, y6, x1, cy2, x1, y4], ['L', x1, ty3], ['C', x1, cty1, cx1, ty1, x3, ty1], ['L', x3, ty2], ['C', x2, ty2, x2, ty2, x2, ty3], ['L', x2, y4], ['C', x2, y5, x2, y5, x3, y5], ['L', x4, y5], ['C', x5, y5, x5, y5, x5, y4], ['L', x5, fy3], ['C', x5, fy2, x5, fy2, x4, fy2], ['Z'] ] }; } // Place data labels in the middle point.dlBox = { x: nodeLeft + (right - nodeLeft + nodeW) / 2, y: fromY + (toY - fromY) / 2, height: linkHeight, width: 0 }; // And set the tooltip anchor in the middle point.tooltipPos = chart.inverted ? [ chart.plotSizeY - point.dlBox.y - linkHeight / 2, chart.plotSizeX - point.dlBox.x ] : [ point.dlBox.x, point.dlBox.y + linkHeight / 2 ]; // Pass test in drawPoints point.y = point.plotY = 1; if (!point.color) { point.color = fromNode.color; } }, /** * Run pre-translation by generating the nodeColumns. * @private */ translate: function () { var _this = this; // Get the translation factor needed for each column to fill up the // plot height var getColumnTranslationFactor = function (column) { var nodes = column.slice(); var minLinkWidth = _this.options.minLinkWidth || 0; var exceedsMinLinkWidth; var factor = 0; var i; var remainingHeight = chart.plotSizeY - options.borderWidth - (column.length - 1) * series.nodePadding; // Because the minLinkWidth option doesn't obey the direct // translation, we need to run translation iteratively, check // node heights, remove those nodes affected by minLinkWidth, // check again, etc. while (column.length) { factor = remainingHeight / column.sum(); exceedsMinLinkWidth = false; i = column.length; while (i--) { if (column[i].getSum() * factor < minLinkWidth) { column.splice(i, 1); remainingHeight -= minLinkWidth + series.nodePadding; exceedsMinLinkWidth = true; } } if (!exceedsMinLinkWidth) { break; } } // Re-insert original nodes column.length = 0; nodes.forEach(function (node) { return column.push(node); }); return factor; }; if (!this.processedXData) { this.processData(); } this.generatePoints(); this.nodeColumns = this.createNodeColumns(); this.nodeWidth = relativeLength(this.options.nodeWidth, this.chart.plotSizeX); var series = this, chart = this.chart, options = this.options, nodeWidth = this.nodeWidth, nodeColumns = this.nodeColumns; this.nodePadding = this.getNodePadding(); // Find out how much space is needed. Base it on the translation // factor of the most spaceous column. this.translationFactor = nodeColumns.reduce(function (translationFactor, column) { return Math.min(translationFactor, getColumnTranslationFactor(column)); }, Infinity); this.colDistance = (chart.plotSizeX - nodeWidth - options.borderWidth) / Math.max(1, nodeColumns.length - 1); // Calculate level options used in sankey and organization series.mapOptionsToLevel = getLevelOptions({ // NOTE: if support for allowTraversingTree is added, then from // should be the level of the root node. from: 1, levels: options.levels, to: nodeColumns.length - 1, defaults: { borderColor: options.borderColor, borderRadius: options.borderRadius, borderWidth: options.borderWidth, color: series.color, colorByPoint: options.colorByPoint, // NOTE: if support for allowTraversingTree is added, then // levelIsConstant should be optional. levelIsConstant: true, linkColor: options.linkColor, linkLineWidth: options.linkLineWidth, linkOpacity: options.linkOpacity, states: options.states } }); // First translate all nodes so we can use them when drawing links nodeColumns.forEach(function (column) { column.forEach(function (node) { series.translateNode(node, column); }); }, this); // Then translate links this.nodes.forEach(function (node) { // Translate the links from this node node.linksFrom.forEach(function (linkPoint) { // If weight is 0 - don't render the link path #12453, // render null points (for organization chart) if ((linkPoint.weight || linkPoint.isNull) && linkPoint.to) { series.translateLink(linkPoint); linkPoint.allowShadow = false; } }); }); }, /** * Extend the render function to also render this.nodes together with * the points. * @private */ render: function () { var points = this.points; this.points = this.points.concat(this.nodes || []); H.seriesTypes.column.prototype.render.call(this); this.points = points; }, /* eslint-enable valid-jsdoc */ animate: H.Series.prototype.animate }, { applyOptions: function (options, x) { Point.prototype.applyOptions.call(this, options, x); // Treat point.level as a synonym of point.column if (defined(this.options.level)) { this.options.column = this.column = this.options.level; } return this; }, setState: H.NodesMixin.setNodeState, getClassName: function () { return (this.isNode ? 'highcharts-node ' : 'highcharts-link ') + Point.prototype.getClassName.call(this); }, isValid: function () { return this.isNode || typeof this.weight === 'number'; } }); /** * A `sankey` series. If the [type](#series.sankey.type) option is not * specified, it is inherited from [chart.type](#chart.type). * * @extends series,plotOptions.sankey * @excluding animationLimit, boostBlending, boostThreshold, borderColor, * borderRadius, borderWidth, crisp, cropThreshold, dataParser, * dataURL, depth, dragDrop, edgeColor, edgeWidth, * findNearestPointBy, getExtremesFromAll, grouping, groupPadding, * groupZPadding, label, maxPointWidth, negativeColor, pointInterval, * pointIntervalUnit, pointPadding, pointPlacement, pointRange, * pointStart, pointWidth, shadow, softThreshold, stacking, * threshold, zoneAxis, zones, dataSorting * @product highcharts * @requires modules/sankey * @apioption series.sankey */ /** * A collection of options for the individual nodes. The nodes in a sankey * diagram are auto-generated instances of `Highcharts.Point`, but options can * be applied here and linked by the `id`. * * @sample highcharts/css/sankey/ * Sankey diagram with node options * * @declare Highcharts.SeriesSankeyNodesOptionsObject * @type {Array<*>} * @product highcharts * @apioption series.sankey.nodes */ /** * The id of the auto-generated node, refering to the `from` or `to` setting of * the link. * * @type {string} * @product highcharts * @apioption series.sankey.nodes.id */ /** * The color of the auto generated node. * * @type {Highcharts.ColorString|Highcharts.GradientColorObject|Highcharts.PatternObject} * @product highcharts * @apioption series.sankey.nodes.color */ /** * The color index of the auto generated node, especially for use in styled * mode. * * @type {number} * @product highcharts * @apioption series.sankey.nodes.colorIndex */ /** * An optional column index of where to place the node. The default behaviour is * to place it next to the preceding node. Note that this option name is * counter intuitive in inverted charts, like for example an organization chart * rendered top down. In this case the "columns" are horizontal. * * @sample highcharts/plotoptions/sankey-node-column/ * Specified node column * * @type {number} * @since 6.0.5 * @product highcharts * @apioption series.sankey.nodes.column */ /** * Individual data label for each node. The options are the same as * the ones for [series.sankey.dataLabels](#series.sankey.dataLabels). * * @extends plotOptions.sankey.dataLabels * @apioption series.sankey.nodes.dataLabels */ /** * An optional level index of where to place the node. The default behaviour is * to place it next to the preceding node. Alias of `nodes.column`, but in * inverted sankeys and org charts, the levels are laid out as rows. * * @type {number} * @since 7.1.0 * @product highcharts * @apioption series.sankey.nodes.level */ /** * The name to display for the node in data labels and tooltips. Use this when * the name is different from the `id`. Where the id must be unique for each * node, this is not necessary for the name. * * @sample highcharts/css/sankey/ * Sankey diagram with node options * * @type {string} * @product highcharts * @apioption series.sankey.nodes.name */ /** * In a horizontal layout, the vertical offset of a node in terms of weight. * Positive values shift the node downwards, negative shift it upwards. In a * vertical layout, like organization chart, the offset is horizontal. * * If a percantage string is given, the node is offset by the percentage of the * node size plus `nodePadding`. * * @sample highcharts/plotoptions/sankey-node-column/ * Specified node offset * * @type {number|string} * @default 0 * @since 6.0.5 * @product highcharts * @apioption series.sankey.nodes.offset */ /** * An array of data points for the series. For the `sankey` series type, * points can be given in the following way: * * An array of objects with named values. The following snippet shows only a * few settings, see the complete options set below. If the total number of data * points exceeds the series' [turboThreshold](#series.area.turboThreshold), * this option is not available. * * ```js * data: [{ * from: 'Category1', * to: 'Category2', * weight: 2 * }, { * from: 'Category1', * to: 'Category3', * weight: 5 * }] * ``` * * @sample {highcharts} highcharts/series/data-array-of-objects/ * Config objects * * @declare Highcharts.SeriesSankeyPointOptionsObject * @type {Array<*>} * @extends series.line.data * @excluding dragDrop, drilldown, marker, x, y * @product highcharts * @apioption series.sankey.data */ /** * The color for the individual _link_. By default, the link color is the same * as the node it extends from. The `series.fillOpacity` option also applies to * the points, so when setting a specific link color, consider setting the * `fillOpacity` to 1. * * @type {Highcharts.ColorString|Highcharts.GradientColorObject|Highcharts.PatternObject} * @product highcharts * @apioption series.sankey.data.color */ /** * @type {Highcharts.SeriesSankeyDataLabelsOptionsObject|Array<Highcharts.SeriesSankeyDataLabelsOptionsObject>} * @product highcharts * @apioption series.sankey.data.dataLabels */ /** * The node that the link runs from. * * @type {string} * @product highcharts * @apioption series.sankey.data.from */ /** * The node that the link runs to. * * @type {string} * @product highcharts * @apioption series.sankey.data.to */ /** * Whether the link goes out of the system. * * @sample highcharts/plotoptions/sankey-outgoing * Sankey chart with outgoing links * * @type {boolean} * @default false * @product highcharts * @apioption series.sankey.data.outgoing */ /** * The weight of the link. * * @type {number|null} * @product highcharts * @apioption series.sankey.data.weight */ ''; // adds doclets above to transpiled file
{ "content_hash": "cb07658c8c1f7a61adfcad49f0cda30a", "timestamp": "", "source": "github", "line_count": 1064, "max_line_length": 512, "avg_line_length": 36.755639097744364, "alnum_prop": 0.566201288738877, "repo_name": "cdnjs/cdnjs", "id": "f29f2b42a89db8fe4ea4078b9221c45d8fd932c6", "size": "39108", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "ajax/libs/highcharts/8.1.0/es-modules/modules/sankey.src.js", "mode": "33188", "license": "mit", "language": [], "symlink_target": "" }
<?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:paddingBottom="@dimen/activity_vertical_margin" android:paddingLeft="@dimen/activity_horizontal_margin" android:paddingRight="@dimen/activity_horizontal_margin" android:paddingTop="@dimen/activity_vertical_margin" tools:context=".view.MainActivity"> <Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="@string/get_random_joke" android:id="@+id/btnRandomJoke" android:layout_alignParentTop="true" android:layout_alignParentStart="true" /> <Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="@string/get_nerdy_joke" android:id="@+id/btnNerdyJoke" android:layout_above="@+id/txtstatus" android:layout_alignParentEnd="true" /> <TextView android:layout_width="match_parent" android:layout_height="wrap_content" android:textAppearance="?android:attr/textAppearanceLarge" android:id="@+id/txtstatus" android:layout_below="@+id/btnRandomJoke" android:layout_alignParentStart="true" /> </RelativeLayout>
{ "content_hash": "2e20262fc593a77d8f63e4e85e693a75", "timestamp": "", "source": "github", "line_count": 36, "max_line_length": 74, "avg_line_length": 39.30555555555556, "alnum_prop": 0.6862190812720848, "repo_name": "ruwanka/ChuckNorrisMVP", "id": "bc1d8c8946844024d8dab76ef83eca821e8664d4", "size": "1415", "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": "11126" } ], "symlink_target": "" }
<?php if ( ! defined( '\Tinify\VERSION' ) ) { /* Load vendored client if it is not yet loaded. */ require_once dirname( __FILE__ ) . '/vendor/tinify/Tinify/Exception.php'; require_once dirname( __FILE__ ) . '/vendor/tinify/Tinify/ResultMeta.php'; require_once dirname( __FILE__ ) . '/vendor/tinify/Tinify/Result.php'; require_once dirname( __FILE__ ) . '/vendor/tinify/Tinify/Source.php'; require_once dirname( __FILE__ ) . '/vendor/tinify/Tinify/Client.php'; require_once dirname( __FILE__ ) . '/vendor/tinify/Tinify.php'; } class Tiny_Compress_Client extends Tiny_Compress { private $last_error_code = 0; private $last_message = ''; private $proxy; protected function __construct( $api_key, $after_compress_callback ) { parent::__construct( $after_compress_callback ); $this->proxy = new WP_HTTP_Proxy(); \Tinify\setAppIdentifier( self::identifier() ); \Tinify\setKey( $api_key ); } public function can_create_key() { return true; } public function get_compression_count() { return \Tinify\getCompressionCount(); } public function get_key() { return \Tinify\getKey(); } public function limit_reached() { return 429 == $this->last_error_code; } protected function validate() { try { $this->last_error_code = 0; $this->set_request_options( \Tinify\Tinify::getClient() ); \Tinify\Tinify::getClient()->request( 'post', '/shrink' ); return true; } catch ( \Tinify\Exception $err ) { $this->last_error_code = $err->status; if ( 429 == $err->status || 400 == $err->status ) { return true; } throw new Tiny_Exception( $err->getMessage(), get_class( $err ), $err->status ); } } protected function compress( $input, $resize_opts, $preserve_opts ) { try { $this->last_error_code = 0; $this->set_request_options( \Tinify\Tinify::getClient() ); $source = \Tinify\fromBuffer( $input ); if ( $resize_opts ) { $source = $source->resize( $resize_opts ); } if ( $preserve_opts ) { $source = $source->preserve( $preserve_opts ); } $result = $source->result(); $meta = array( 'input' => array( 'size' => strlen( $input ), 'type' => $result->mediaType(), ), 'output' => array( 'size' => $result->size(), 'type' => $result->mediaType(), 'width' => $result->width(), 'height' => $result->height(), 'ratio' => round( $result->size() / strlen( $input ), 4 ), ), ); $buffer = $result->toBuffer(); return array( $buffer, $meta ); } catch ( \Tinify\Exception $err ) { $this->last_error_code = $err->status; throw new Tiny_Exception( $err->getMessage(), get_class( $err ), $err->status ); }// End try(). } public function create_key( $email, $options ) { try { $this->last_error_code = 0; $this->set_request_options( \Tinify\Tinify::getClient( \Tinify\Tinify::ANONYMOUS ) ); \Tinify\createKey( $email, $options ); } catch ( \Tinify\Exception $err ) { $this->last_error_code = $err->status; throw new Tiny_Exception( $err->getMessage(), get_class( $err ), $err->status ); } } private function set_request_options( $client ) { /* The client does not let us override cURL properties yet, so we have to use a reflection property. */ $property = new ReflectionProperty( $client, 'options' ); $property->setAccessible( true ); $options = $property->getValue( $client ); if ( TINY_DEBUG ) { $file = fopen( dirname( __FILE__ ) . '/curl.log', 'w' ); if ( is_resource( $file ) ) { $options[ CURLOPT_VERBOSE ] = true; $options[ CURLOPT_STDERR ] = $file; } } if ( $this->proxy->is_enabled() && $this->proxy->send_through_proxy( $url ) ) { $options[ CURLOPT_PROXYTYPE ] = CURLPROXY_HTTP; $options[ CURLOPT_PROXY ] = $this->proxy->host(); $options[ CURLOPT_PROXYPORT ] = $this->proxy->port(); if ( $this->proxy->use_authentication() ) { $options[ CURLOPT_PROXYAUTH ] = CURLAUTH_ANY; $options[ CURLOPT_PROXYUSERPWD ] = $this->proxy->authentication(); } } } }
{ "content_hash": "8f1b7f1c10a23364677e46f02ab803b8", "timestamp": "", "source": "github", "line_count": 157, "max_line_length": 81, "avg_line_length": 25.94267515923567, "alnum_prop": 0.6056960471397005, "repo_name": "20steps/alexa", "id": "d17467240ca2c0553070efdcb0c662cbbc7b3458", "size": "4867", "binary": false, "copies": "4", "ref": "refs/heads/master", "path": "web/wp-content/plugins/tiny-compress-images/src/class-tiny-compress-client.php", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "4889348" }, { "name": "CoffeeScript", "bytes": "8023" }, { "name": "Gherkin", "bytes": "4336" }, { "name": "HTML", "bytes": "357026" }, { "name": "JavaScript", "bytes": "9076289" }, { "name": "PHP", "bytes": "33450039" }, { "name": "Perl", "bytes": "365" }, { "name": "Ruby", "bytes": "3054" }, { "name": "Shell", "bytes": "30158" }, { "name": "TypeScript", "bytes": "35051" }, { "name": "VCL", "bytes": "22958" }, { "name": "XSLT", "bytes": "5437" } ], "symlink_target": "" }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. using System.IO; using System.Threading.Tasks; using Azure.Core; using Azure.Storage.Blobs.Models; using Azure.Storage.Blobs.Specialized; namespace Azure.Storage.Blobs.Tests { public class PageBlobClientOpenReadTests : BlobBaseClientOpenReadTests<PageBlobClient> { public PageBlobClientOpenReadTests(bool async, BlobClientOptions.ServiceVersion serviceVersion) : base(async, serviceVersion, null /* RecordedTestMode.Record /* to re-record */) { } #region Client-Specific Impl protected override PageBlobClient GetResourceClient(BlobContainerClient container, string resourceName = null, BlobClientOptions options = null) { Argument.AssertNotNull(container, nameof(container)); string blobName = resourceName ?? GetNewResourceName(); if (options == null) { return container.GetPageBlobClient(blobName); } container = InstrumentClient(new BlobContainerClient(container.Uri, Tenants.GetNewSharedKeyCredentials(), options ?? ClientBuilder.GetOptions())); return InstrumentClient(container.GetPageBlobClient(blobName)); } protected override async Task StageDataAsync(PageBlobClient client, Stream data) { Argument.AssertNotNull(client, nameof(client)); Argument.AssertNotNull(data, nameof(data)); using Stream writeStream = await client.OpenWriteAsync(overwrite: true, position: 0, new PageBlobOpenWriteOptions { Size = data.Length }); await data.CopyToAsync(writeStream); } protected override async Task ModifyDataAsync(PageBlobClient client, Stream data, ModifyDataMode mode) { Argument.AssertNotNull(client, nameof(client)); Argument.AssertNotNull(data, nameof(data)); long position = mode switch { ModifyDataMode.Replace => 0, ModifyDataMode.Append => (await client.GetPropertiesAsync()).Value.ContentLength, _ => throw Errors.InvalidArgument(nameof(mode)) }; await client.ResizeAsync(position + data.Length); using Stream writeStream = await client.OpenWriteAsync(overwrite: false, position, new PageBlobOpenWriteOptions { Size = data.Length }); await data.CopyToAsync(writeStream); } #endregion } }
{ "content_hash": "9e3eb7ed763e61bef0cde6ee6a578137", "timestamp": "", "source": "github", "line_count": 68, "max_line_length": 158, "avg_line_length": 38.470588235294116, "alnum_prop": 0.6487003058103975, "repo_name": "Azure/azure-sdk-for-net", "id": "77c0626105da5d088a0068f6a908572bb78b58ae", "size": "2618", "binary": false, "copies": "1", "ref": "refs/heads/main", "path": "sdk/storage/Azure.Storage.Blobs/tests/PageBlobClientOpenReadTests.cs", "mode": "33188", "license": "mit", "language": [], "symlink_target": "" }
#include "media/engine/internaldecoderfactory.h" #include "api/video_codecs/sdp_video_format.h" #include "api/video_codecs/video_decoder.h" #include "media/base/mediaconstants.h" #include "test/gtest.h" namespace webrtc { TEST(InternalDecoderFactory, TestVP8) { InternalDecoderFactory factory; std::unique_ptr<VideoDecoder> decoder = factory.CreateVideoDecoder(SdpVideoFormat(cricket::kVp8CodecName)); EXPECT_TRUE(decoder); } } // namespace webrtc
{ "content_hash": "2868988b95fed0a93149a1576fc045c6", "timestamp": "", "source": "github", "line_count": 19, "max_line_length": 73, "avg_line_length": 24.57894736842105, "alnum_prop": 0.7665952890792291, "repo_name": "wangcy6/storm_app", "id": "147293dcf714ad1f32593932d1028cb037705f1f", "size": "879", "binary": false, "copies": "3", "ref": "refs/heads/master", "path": "frame/c++/webrtc-master/media/engine/internaldecoderfactory_unittest.cc", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "ActionScript", "bytes": "86225" }, { "name": "Assembly", "bytes": "4834" }, { "name": "Batchfile", "bytes": "50141" }, { "name": "C", "bytes": "9700081" }, { "name": "C#", "bytes": "1587148" }, { "name": "C++", "bytes": "14378340" }, { "name": "CMake", "bytes": "756439" }, { "name": "CSS", "bytes": "59712" }, { "name": "Clojure", "bytes": "535480" }, { "name": "DTrace", "bytes": "147" }, { "name": "Fancy", "bytes": "6234" }, { "name": "FreeMarker", "bytes": "3512" }, { "name": "Go", "bytes": "27069" }, { "name": "Groovy", "bytes": "1755" }, { "name": "HTML", "bytes": "1235479" }, { "name": "Java", "bytes": "41653938" }, { "name": "JavaScript", "bytes": "260093" }, { "name": "Lua", "bytes": "11887" }, { "name": "M4", "bytes": "96283" }, { "name": "Makefile", "bytes": "977879" }, { "name": "NSIS", "bytes": "6522" }, { "name": "Objective-C", "bytes": "324010" }, { "name": "PHP", "bytes": "348909" }, { "name": "Perl", "bytes": "182487" }, { "name": "PowerShell", "bytes": "19465" }, { "name": "Prolog", "bytes": "243" }, { "name": "Python", "bytes": "3649738" }, { "name": "QML", "bytes": "9975" }, { "name": "QMake", "bytes": "63106" }, { "name": "Roff", "bytes": "12319" }, { "name": "Ruby", "bytes": "858066" }, { "name": "Scala", "bytes": "5203874" }, { "name": "Shell", "bytes": "714435" }, { "name": "Smarty", "bytes": "1047" }, { "name": "Swift", "bytes": "3486" }, { "name": "Tcl", "bytes": "492616" }, { "name": "Thrift", "bytes": "31449" }, { "name": "XS", "bytes": "20183" }, { "name": "XSLT", "bytes": "8784" } ], "symlink_target": "" }
package ch21.exec; import java.sql.Connection; import java.sql.ResultSet; import java.sql.ResultSetMetaData; import java.sql.Statement; import java.sql.SQLException; import java.io.File; import java.io.IOException; import java.util.Scanner; /** Executes all SQL statements from a file or the console. */ public class ExecSQL { public static void main(String[] args) throws SQLException, IOException, ClassNotFoundException { if (args.length == 0) { System.out.println( "Usage: java -classpath driver_class_path" + File.pathSeparator + ". ExecSQL propertiesFile [SQLcommandFile]"); return; } SimpleDataSource.init(args[0]); Scanner in; if (args.length > 1) in = new Scanner(new File(args[1])); else in = new Scanner(System.in); Connection conn = SimpleDataSource.getConnection(); try { Statement stat = conn.createStatement(); while (in.hasNextLine()) { String line = in.nextLine(); try { boolean hasResultSet = stat.execute(line); if (hasResultSet) { ResultSet result = stat.getResultSet(); showResultSet(result); result.close(); } } catch (SQLException ex) { System.out.println(ex); } } } finally { conn.close(); } } /** Prints a result set. @param result the result set */ public static void showResultSet(ResultSet result) throws SQLException { ResultSetMetaData metaData = result.getMetaData(); int columnCount = metaData.getColumnCount(); for (int i = 1; i <= columnCount; i++) { if (i > 1) System.out.print(", "); System.out.print(metaData.getColumnLabel(i)); } System.out.println(); while (result.next()) { for (int i = 1; i <= columnCount; i++) { if (i > 1) System.out.print(", "); System.out.print(result.getString(i)); } System.out.println(); } } }
{ "content_hash": "56f7f292a0a0051801597886feb0e881", "timestamp": "", "source": "github", "line_count": 93, "max_line_length": 65, "avg_line_length": 24.956989247311828, "alnum_prop": 0.5204653166738474, "repo_name": "raeffu/prog1", "id": "345a842ab9d18e1754fb77f755d7891b2b024a10", "size": "2321", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/ch21/exec/ExecSQL.java", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "2782" }, { "name": "Java", "bytes": "323212" } ], "symlink_target": "" }
#include <TRCharts/Impl/PointImpl.hpp> Charts::Point::Point(void) :GeneratedPoint() { } Charts::Point::Point(double x, double y) :GeneratedPoint(x, y) { } Charts::Point Charts::Point::add(const Point & point, const Point & otherPoint) { return Point(point.x + otherPoint.x, point.y + otherPoint.y); } Charts::Point Charts::Point::subtract(const Point & point, const Point & otherPoint) { return Point(point.x - otherPoint.x, point.y - otherPoint.y); } Charts::Point Charts::Point::multiply(const Point & point, const Point & otherPoint) { return Point(point.x * otherPoint.x, point.y * otherPoint.y); } Charts::Point Charts::Point::divide(const Point & point, const Point & otherPoint) { return Point(point.x / otherPoint.x, point.y / otherPoint.y); }
{ "content_hash": "52f1e74976a0dfd1c1fb4554bc081935", "timestamp": "", "source": "github", "line_count": 35, "max_line_length": 84, "avg_line_length": 22.285714285714285, "alnum_prop": 0.6974358974358974, "repo_name": "AndroidT/TRCharts", "id": "fe9a99c028b643b312cc220e86ac6081c209e51b", "size": "1533", "binary": false, "copies": "3", "ref": "refs/heads/master", "path": "Charts/TRCharts/TRCharts/Impl/PointImpl.cpp", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "C", "bytes": "5418" }, { "name": "C++", "bytes": "3313416" }, { "name": "CMake", "bytes": "1566" }, { "name": "Java", "bytes": "421721" }, { "name": "Makefile", "bytes": "2679" }, { "name": "Objective-C", "bytes": "334981" }, { "name": "Objective-C++", "bytes": "510699" }, { "name": "Shell", "bytes": "2273" } ], "symlink_target": "" }
package org.apache.activemq.artemis.tests.integration.stomp.util; import java.util.StringTokenizer; /** * 1.1 frames * <p/> * 1. CONNECT/STOMP(new) * 2. CONNECTED * 3. SEND * 4. SUBSCRIBE * 5. UNSUBSCRIBE * 6. BEGIN * 7. COMMIT * 8. ACK * 9. NACK (new) * 10. ABORT * 11. DISCONNECT * 12. MESSAGE * 13. RECEIPT * 14. ERROR */ public class StompFrameFactoryV11 implements StompFrameFactory { @Override public ClientStompFrame createFrame(final String data) { //split the string at "\n\n" String[] dataFields = data.split("\n\n"); StringTokenizer tokenizer = new StringTokenizer(dataFields[0], "\n"); String command = tokenizer.nextToken(); ClientStompFrame frame = new ClientStompFrameV11(command); while (tokenizer.hasMoreTokens()) { String header = tokenizer.nextToken(); String[] fields = splitAndDecodeHeader(header); frame.addHeader(fields[0], fields[1]); } //body (without null byte) if (dataFields.length == 2) { frame.setBody(dataFields[1]); } return frame; } private String[] splitAndDecodeHeader(String header) { // split the header into the key and value at the ":" since there shouldn't be any unescaped colons in the header // except for the one separating the key and value String[] result = header.split(":"); for (int j = 0; j < result.length; j++) { StringBuffer decodedHeader = new StringBuffer(); boolean isEsc = false; for (int i = 0; i < result[j].length(); i++) { char b = result[j].charAt(i); switch (b) { //escaping case '\\': { if (isEsc) { //this is a backslash decodedHeader.append(b); isEsc = false; } else { //begin escaping isEsc = true; } break; } case 'c': { if (isEsc) { decodedHeader.append(":"); isEsc = false; } else { decodedHeader.append(b); } break; } case 'n': { if (isEsc) { decodedHeader.append('\n'); isEsc = false; } else { decodedHeader.append(b); } break; } default: { decodedHeader.append(b); } } } result[j] = decodedHeader.toString(); } return result; } @Override public ClientStompFrame newFrame(String command) { return new ClientStompFrameV11(command); } @Override public ClientStompFrame newAnyFrame(String command) { return new ClientStompFrameV11(command, false); } }
{ "content_hash": "dd54ecb4a11391cf0556d2e5db4a3bc2", "timestamp": "", "source": "github", "line_count": 137, "max_line_length": 119, "avg_line_length": 24.963503649635037, "alnum_prop": 0.4415204678362573, "repo_name": "jbertram/activemq-artemis-old", "id": "51dbde8f8807aedc6e312fe586fcc92cebe716c5", "size": "4220", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/stomp/util/StompFrameFactoryV11.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "C", "bytes": "2088" }, { "name": "C++", "bytes": "39402" }, { "name": "CSS", "bytes": "17995" }, { "name": "HTML", "bytes": "655853" }, { "name": "Java", "bytes": "16910061" }, { "name": "JavaScript", "bytes": "31054" }, { "name": "Python", "bytes": "3626" }, { "name": "Ruby", "bytes": "3412" }, { "name": "Shell", "bytes": "17315" } ], "symlink_target": "" }
/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using System; using java = biz.ritter.javapi; using org.apache.harmony.luni; namespace biz.ritter.javapi.security { public class Provider : java.util.Properties { private String name; //The provider preference order number. // Equals -1 for non registered provider. [NonSerialized] private int providerNumber = -1; // Contains "Service.Algorithm" and Provider.Service classes added using // putService() [NonSerialized] private TwoKeyHashMap<String, String, Service> serviceTable; // Contains "Service.Alias" and Provider.Service classes added using // putService() [NonSerialized] private TwoKeyHashMap<String, String, Service> aliasTable; // Contains "Service.Algorithm" and Provider.Service classes added using // put() [NonSerialized] private TwoKeyHashMap<String, String, Service> propertyServiceTable; // Contains "Service.Alias" and Provider.Service classes added using put() [NonSerialized] private TwoKeyHashMap<String, String, Service> propertyAliasTable; // The properties changed via put() [NonSerialized] private java.util.Properties changedProperties; // For getService(String type, String algorithm) optimization: // previous result [NonSerialized] private Provider.Service returnedService; // previous parameters [NonSerialized] private String lastAlgorithm; // last name [NonSerialized] private String lastServiceName; // For getServices() optimization: [NonSerialized] private java.util.Set<Service> lastServicesSet; // For getService(String type) optimization: [NonSerialized] private String lastType; // last Service found by type [NonSerialized] private Provider.Service lastServicesByType; /** * Returns the service with the specified {@code type} implementing the * specified {@code algorithm}, or {@code null} if no such implementation * exists. * <p/> * If two services match the requested type and algorithm, the one added * with the {@link #putService(Service)} is returned (as opposed to the one * added via {@link #put(Object, Object)}. * * @param type * the type of the service (for example {@code KeyPairGenerator}) * @param algorithm * the algorithm name (case insensitive) * @return the requested service, or {@code null} if no such implementation * exists */ public Provider.Service getService(String type, String algorithm) { lock (this) { if (type == null || algorithm == null) { throw new java.lang.NullPointerException(); } if (type.equals(lastServiceName) && algorithm.equalsIgnoreCase(lastAlgorithm)) { return returnedService; } String alg = algorithm.toUpperCase(); Object o = null; if (serviceTable != null) { o = serviceTable.get(type, alg); } if (o == null && aliasTable != null) { o = aliasTable.get(type, alg); } if (o == null) { updatePropertyServiceTable(); } if (o == null && propertyServiceTable != null) { o = propertyServiceTable.get(type, alg); } if (o == null && propertyAliasTable != null) { o = propertyAliasTable.get(type, alg); } if (o != null) { lastServiceName = type; lastAlgorithm = algorithm; returnedService = (Provider.Service)o; return returnedService; } return null; } } /** * Returns true if this provider implements the given algorithm. Caller * must specify the cryptographic service and specify constraints via the * attribute name and value. * * @param serv * Crypto service. * @param alg * Algorithm or type. * @param attribute * The attribute name or {@code null}. * @param val * The attribute value. * @return */ internal bool implementsAlg(String serv, String alg, String attribute, String val) { String servAlg = serv + "." + alg; //$NON-NLS-1$ String prop = getPropertyIgnoreCase(servAlg); if (prop == null) { alg = getPropertyIgnoreCase("Alg.Alias." + servAlg); //$NON-NLS-1$ if (alg != null) { servAlg = serv + "." + alg; //$NON-NLS-1$ prop = getPropertyIgnoreCase(servAlg); } } if (prop != null) { if (attribute == null) { return true; } return checkAttribute(servAlg, attribute, val); } return false; } // Returns true if this provider has the same value as is given for the // given attribute private bool checkAttribute(String servAlg, String attribute, String val) { String attributeValue = getPropertyIgnoreCase(servAlg + ' ' + attribute); if (attributeValue != null) { if (attribute.equalsIgnoreCase("KeySize")) { //$NON-NLS-1$ if (java.lang.Integer.valueOf(attributeValue).compareTo( java.lang.Integer.valueOf(val)) >= 0) { return true; } } else { // other attributes if (attributeValue.equalsIgnoreCase(val)) { return true; } } } return false; } // Searches for the property with the specified key in the provider // properties. Key is not case-sensitive. // // @param prop // @return the property value with the specified key value. private String getPropertyIgnoreCase(String key) { String res = getProperty(key); if (res != null) { return res; } for (java.util.Enumeration<Object> e = propertyNames(); e.hasMoreElements();) { String pname = (String) e.nextElement(); if (key.equalsIgnoreCase(pname)) { return getProperty(pname); } } return null; } /** * Get the service of the specified type * */ internal Provider.Service getService(String type) { lock (this) { updatePropertyServiceTable(); if (lastServicesByType != null && type.equals(lastType)) { return lastServicesByType; } Provider.Service service; for (java.util.Iterator<Service> it = getServices().iterator(); it.hasNext(); ) { service = it.next(); if (type.equals(service.type)) { lastType = type; lastServicesByType = service; return service; } } return null; } } /** * Returns an unmodifiable {@code Set} of all services registered by this * provider. * * @return an unmodifiable {@code Set} of all services registered by this * provider */ public java.util.Set<Provider.Service> getServices() { lock (this) { updatePropertyServiceTable(); if (lastServicesSet != null) { return lastServicesSet; } if (serviceTable != null) { lastServicesSet = new java.util.HashSet<Service>(serviceTable.values()); } else { lastServicesSet = new java.util.HashSet<Service>(); } if (propertyServiceTable != null) { lastServicesSet.addAll(propertyServiceTable.values()); } lastServicesSet = java.util.Collections<Object>.unmodifiableSet(lastServicesSet); return lastServicesSet; } } /** * * Set the provider preference order number. * * @param n */ internal void setProviderNumber(int n) { providerNumber = n; } /** * * Get the provider preference order number. * * @return */ internal int getProviderNumber() { return providerNumber; } // Update provider Services if the properties was changed private void updatePropertyServiceTable() { Object _key; Object _value; Provider.Service s; String serviceName; String algorithm; if (changedProperties == null || changedProperties.isEmpty()) { return; } java.util.Iterator<java.util.MapNS.Entry<String, String>> it = changedProperties.entrySet().iterator(); for (; it.hasNext(); ) { java.util.MapNS.Entry<String, String> entry = it.next(); _key = entry.getKey(); _value = entry.getValue(); if (_key == null || _value == null || !(_key is String) || !(_value is String)) { continue; } String key = (String)_key; String value = (String)_value; if (key.startsWith("Provider")) { // Provider service type is reserved //$NON-NLS-1$ continue; } int i; if (key.startsWith("Alg.Alias.")) { // Alg.Alias.<crypto_service>.<aliasName>=<stanbdardName> //$NON-NLS-1$ String aliasName; String service_alias = key.substring(10); i = service_alias.indexOf('.'); serviceName = service_alias.substring(0, i); aliasName = service_alias.substring(i + 1); algorithm = value; String algUp = algorithm.toUpperCase(); Object o = null; if (propertyServiceTable == null) { propertyServiceTable = new TwoKeyHashMap<String, String, Service>(128); } else { o = propertyServiceTable.get(serviceName, algUp); } if (o != null) { s = (Provider.Service)o; s.aliases.add(aliasName); if (propertyAliasTable == null) { propertyAliasTable = new TwoKeyHashMap<String, String, Service>(256); } propertyAliasTable.put(serviceName, aliasName.toUpperCase(), s); } else { String className = (String)changedProperties .get(serviceName + "." + algorithm); //$NON-NLS-1$ if (className != null) { java.util.ArrayList<String> l = new java.util.ArrayList<String>(); l.add(aliasName); s = new Provider.Service(this, serviceName, algorithm, className, l, new java.util.HashMap<String, String>()); propertyServiceTable.put(serviceName, algUp, s); if (propertyAliasTable == null) { propertyAliasTable = new TwoKeyHashMap<String, String, Service>(256); } propertyAliasTable.put(serviceName, aliasName .toUpperCase(), s); } } continue; } int j = key.indexOf('.'); if (j == -1) { // unknown format continue; } i = key.indexOf(' '); if (i == -1) { // <crypto_service>.<algorithm_or_type>=<className> serviceName = key.substring(0, j); algorithm = key.substring(j + 1); String alg = algorithm.toUpperCase(); Object o = null; if (propertyServiceTable != null) { o = propertyServiceTable.get(serviceName, alg); } if (o != null) { s = (Provider.Service)o; s.className = value; } else { s = new Provider.Service(this, serviceName, algorithm, value, new java.util.ArrayList<String>(), new java.util.HashMap<String, String>()); if (propertyServiceTable == null) { propertyServiceTable = new TwoKeyHashMap<String, String, Service>(128); } propertyServiceTable.put(serviceName, alg, s); } } else { // <crypto_service>.<algorithm_or_type> // <attribute_name>=<attrValue> serviceName = key.substring(0, j); algorithm = key.substring(j + 1, i); String attribute = key.substring(i + 1); String alg = algorithm.toUpperCase(); Object o = null; if (propertyServiceTable != null) { o = propertyServiceTable.get(serviceName, alg); } if (o != null) { s = (Provider.Service)o; s.attributes.put(attribute, value); } else { String className = (String)changedProperties .get(serviceName + "." + algorithm); //$NON-NLS-1$ if (className != null) { java.util.HashMap<String, String> m = new java.util.HashMap<String, String>(); m.put(attribute, value); s = new Provider.Service(this, serviceName, algorithm, className, new java.util.ArrayList<String>(), m); if (propertyServiceTable == null) { propertyServiceTable = new TwoKeyHashMap<String, String, Service>(128); } propertyServiceTable.put(serviceName, alg, s); } } } } servicesChanged(); changedProperties.clear(); } private void servicesChanged() { lastServicesByType = null; lastServiceName = null; lastServicesSet = null; } /** * Returns the name of this provider. * * @return the name of this provider. */ public String getName() { return name; } /** * {@code Service} represents a service in the Java Security infrastructure. * Each service describes its type, the algorithm it implements, to which * provider it belongs and other properties. */ public class Service { // The provider private Provider provider; // The type of this service internal String type; // The algorithm name private String algorithm; // The class implementing this service internal String className; // The aliases internal java.util.List<String> aliases; // The attributes internal java.util.Map<String, String> attributes; // Service implementation private java.lang.Class implementation; // For newInstance() optimization private String lastClassName; /** * Constructs a new instance of {@code Service} with the given * attributes. * * @param provider * the provider to which this service belongs. * @param type * the type of this service (for example {@code * KeyPairGenerator}). * @param algorithm * the algorithm this service implements. * @param className * the name of the class implementing this service. * @param aliases * {@code List} of aliases for the algorithm name, or {@code * null} if the implemented algorithm has no aliases. * @param attributes * {@code Map} of additional attributes, or {@code null} if * this {@code Service} has no attributed. * @throws NullPointerException * if {@code provider, type, algorithm} or {@code className} * is {@code null}. */ public Service(Provider provider, String type, String algorithm, String className, java.util.List<String> aliases, java.util.Map<String, String> attributes) { if (provider == null || type == null || algorithm == null || className == null) { throw new java.lang.NullPointerException(); } this.provider = provider; this.type = type; this.algorithm = algorithm; this.className = className; this.aliases = aliases; this.attributes = attributes; } /** * Returns the type of this {@code Service}. For example {@code * KeyPairGenerator}. * * @return the type of this {@code Service}. */ public String getType() { return type; } /** * Returns the name of the algorithm implemented by this {@code * Service}. * * @return the name of the algorithm implemented by this {@code * Service}. */ public String getAlgorithm() { return algorithm; } /** * Returns the {@code Provider} this {@code Service} belongs to. * * @return the {@code Provider} this {@code Service} belongs to. */ public Provider getProvider() { return provider; } /** * Returns the name of the class implementing this {@code Service}. * * @return the name of the class implementing this {@code Service}. */ public String getClassName() { return className; } /** * Returns the value of the attribute with the specified {@code name}. * * @param name * the name of the attribute. * @return the value of the attribute, or {@code null} if no attribute * with the given name is set. * @throws NullPointerException * if {@code name} is {@code null}. */ public String getAttribute(String name) { if (name == null) { throw new java.lang.NullPointerException(); } if (attributes == null) { return null; } return attributes.get(name); } internal java.util.Iterator<String> getAliases() { if (aliases == null) { aliases = new java.util.ArrayList<String>(0); } return aliases.iterator(); } /** * Creates and returns a new instance of the implementation described by * this {@code Service}. * * @param constructorParameter * the parameter that is used by the constructor, or {@code * null} if the implementation does not declare a constructor * parameter. * @return a new instance of the implementation described by this * {@code Service}. * @throws NoSuchAlgorithmException * if the instance could not be constructed. * @throws InvalidParameterException * if the implementation does not support the specified * {@code constructorParameter}. */ public Object newInstance(Object constructorParameter) {//throws NoSuchAlgorithmException { if (implementation == null || !className.equals(lastClassName)) { java.lang.ClassLoader cl = provider.getClass() .getClassLoader(); if (cl == null) { cl = java.lang.ClassLoader.getSystemClassLoader(); } try { implementation = java.lang.Class.forName(className, true, cl); } catch (Exception e) { return new NoSuchAlgorithmException( type + " " + algorithm + " implementation not found: " + e); } lastClassName = className; } java.lang.Class[] parameterTypes = new java.lang.Class[1]; if (constructorParameter != null && !supportsParameter(constructorParameter)) { throw new InvalidParameterException(type + ": service cannot use the parameter"); //$NON-NLS-1$ } Object[] initargs = { constructorParameter }; try { if (type.equalsIgnoreCase("CertStore")) { //$NON-NLS-1$ parameterTypes[0] = java.lang.Class .forName("java.security.cert.CertStoreParameters"); //$NON-NLS-1$ } else if (type.equalsIgnoreCase("Configuration")) { parameterTypes[0] = java.lang.Class .forName("javax.security.auth.login.Configuration$Parameters"); } if (parameterTypes[0] == null) { if (constructorParameter == null) { return implementation.newInstance(); } else { parameterTypes[0] = constructorParameter.getClass(); } } return implementation.getConstructor(parameterTypes) .newInstance(initargs); } catch (java.lang.Exception e) { throw new NoSuchAlgorithmException(type + " " + algorithm + " implementation not found: ", e); } } /** * Indicates whether this {@code Service} supports the specified * constructor parameter. * * @param parameter * the parameter to test. * @return {@code true} if this {@code Service} supports the specified * constructor parameter, {@code false} otherwise. */ public bool supportsParameter(Object parameter) { return true; } /** * Returns a string containing a concise, human-readable description of * this {@code Service}. * * @return a printable representation for this {@code Service}. */ public override String ToString() { String result = "Provider " + provider.getName() + " Service " //$NON-NLS-1$ //$NON-NLS-2$ + type + "." + algorithm + " " + className; //$NON-NLS-1$ //$NON-NLS-2$ if (aliases != null) { result = result + "\nAliases " + aliases.toString(); //$NON-NLS-1$ } if (attributes != null) { result = result + "\nAttributes " + attributes.toString(); //$NON-NLS-1$ } return result; } } } }
{ "content_hash": "65dd7aae8a42706915064cd85f68f906", "timestamp": "", "source": "github", "line_count": 738, "max_line_length": 115, "avg_line_length": 37.66395663956639, "alnum_prop": 0.45218736508850194, "repo_name": "sailesh341/JavApi", "id": "882f89190c7d686ffd6bea54b53e085066234056", "size": "27798", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "JavApi_Core/java/security/Provider.cs", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "C#", "bytes": "6253300" }, { "name": "Java", "bytes": "410496" } ], "symlink_target": "" }
namespace School.Data.Repositories { using School.Models; public interface ISchoolClassRepository : IDeletableEntityRepository<SchoolClass> { SchoolClass GetByDetails(int gradeYear, string letter, int startYear); } }
{ "content_hash": "4a2c964507cc9a9368d8c2028f438091", "timestamp": "", "source": "github", "line_count": 9, "max_line_length": 85, "avg_line_length": 28, "alnum_prop": 0.7182539682539683, "repo_name": "encounter12/School.Me", "id": "5ec7a9c52a11ad3c4bb91dde12891ce88a91b784", "size": "254", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "School/School.Data/Repositories/ISchoolClassRepository.cs", "mode": "33188", "license": "mit", "language": [ { "name": "ASP", "bytes": "102" }, { "name": "C#", "bytes": "395814" }, { "name": "CSS", "bytes": "24295" }, { "name": "HTML", "bytes": "5275" }, { "name": "JavaScript", "bytes": "563278" } ], "symlink_target": "" }
package example.repo; import example.model.Customer1328; import java.util.List; import org.springframework.data.repository.CrudRepository; public interface Customer1328Repository extends CrudRepository<Customer1328, Long> { List<Customer1328> findByLastName(String lastName); }
{ "content_hash": "33aa9e44f2a3b3831b6ecc7270447001", "timestamp": "", "source": "github", "line_count": 12, "max_line_length": 84, "avg_line_length": 23.666666666666668, "alnum_prop": 0.8309859154929577, "repo_name": "spring-projects/spring-data-examples", "id": "0e2c440a39e375912a2b3d86840cef001a0d6197", "size": "284", "binary": false, "copies": "2", "ref": "refs/heads/main", "path": "jpa/deferred/src/main/java/example/repo/Customer1328Repository.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "407" }, { "name": "HTML", "bytes": "11754" }, { "name": "Java", "bytes": "3549318" }, { "name": "Kotlin", "bytes": "25902" } ], "symlink_target": "" }
 namespace Minimal.Models { public class NavigationPatternInfo { public NavigationPattern ID { get; set; } public string Name { get; set; } public string Description { get; set; } } }
{ "content_hash": "3b7f300c1b553fbdcfe2e332603f8b1b", "timestamp": "", "source": "github", "line_count": 12, "max_line_length": 49, "avg_line_length": 19.166666666666668, "alnum_prop": 0.591304347826087, "repo_name": "NoleHealth/Template10", "id": "e2865ff80cb74ae4e40fd0241b0785cedad6045b", "size": "232", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "Templates (Project)/Minimal/Models/NavigationPatternInfo.cs", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "C#", "bytes": "284287" } ], "symlink_target": "" }
package org.jenkinsci.plugins.customcommandscm; import hudson.model.AbstractBuild; import hudson.scm.ChangeLogParser; import hudson.scm.ChangeLogSet; import hudson.util.IOException2; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import java.util.logging.Logger; import org.apache.commons.digester3.Digester; import org.xml.sax.SAXException; class CustomCommandSCMChangeLogSet extends ChangeLogSet<CustomCommandSCMChangeLogEntry> { private final List<CustomCommandSCMChangeLogEntry> changeLogEntries; public CustomCommandSCMChangeLogSet(AbstractBuild<?, ?> build, List<CustomCommandSCMChangeLogEntry> changeLogEntries) { super(build); this.changeLogEntries = changeLogEntries; for(CustomCommandSCMChangeLogEntry changeLogEntry: changeLogEntries) { changeLogEntry.setParent(this); } } @Override public boolean isEmptySet() { return this.changeLogEntries.isEmpty(); } public Iterator<CustomCommandSCMChangeLogEntry> iterator() { return this.changeLogEntries.iterator(); } public static class Parser extends ChangeLogParser { private static final Logger LOG = Logger.getLogger(Parser.class.getName()); @Override public ChangeLogSet<? extends Entry> parse(AbstractBuild ab, File file) throws IOException, SAXException { List<CustomCommandSCMChangeLogEntry> changeLogEntries = new ArrayList<CustomCommandSCMChangeLogEntry>(); Digester digester = new Digester(); digester.push(changeLogEntries); digester.addObjectCreate("*/entry", CustomCommandSCMChangeLogEntry.class); digester.addBeanPropertySetter("*/entry/date"); digester.addBeanPropertySetter("*/entry/user-id", "userId"); digester.addBeanPropertySetter("*/entry/changeset-number", "changesetNumber"); digester.addBeanPropertySetter("*/entry/changeset-url", "changesetUrl"); digester.addBeanPropertySetter("*/entry/comment", "comment"); digester.addSetNext("*/entry", "add"); digester.addObjectCreate("*/entry/items/item", CustomCommandSCMChangeLogEntry.Item.class); digester.addBeanPropertySetter("*/entry/items/item/change-type", "changeType"); digester.addBeanPropertySetter("*/entry/items/item/file-name", "filename"); digester.addSetNext("*/entry/items/item", "addFile"); try { if(file.exists() && file.length() > 0) { digester.parse(file); } } catch(IOException e) { throw new IOException2("Failed to parse " + file, e); } catch(SAXException e) { throw new IOException2("Failed to parse " + file, e); } return new CustomCommandSCMChangeLogSet(ab, changeLogEntries); } } }
{ "content_hash": "c3bc0e3b07146f0975b80480041ef435", "timestamp": "", "source": "github", "line_count": 77, "max_line_length": 122, "avg_line_length": 39.4025974025974, "alnum_prop": 0.6657877389584707, "repo_name": "anderl86/custom-command-scm", "id": "c17f2035067a3a1398aa259d8f16ffa04793a512", "size": "3034", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/main/java/org/jenkinsci/plugins/customcommandscm/CustomCommandSCMChangeLogSet.java", "mode": "33188", "license": "mit", "language": [ { "name": "Java", "bytes": "12856" } ], "symlink_target": "" }
/* * File : WaitFor.spec.js * Description : TEST WaitFor class definition tests. * ------------------------------------------------------------------------------------------------ */ "use strict"; var path = require("path"); module.exports = { "WaitFor should be exported": function (test) { test.expect(2); var WaitFor = require(path.join(process.cwd(), "src/WaitFor.js")); test.equal(!!WaitFor, true, "Expected to be able to require WaitFor"); test.equal(WaitFor.name, "WaitFor", "Expected name to be `WaitFor`"); test.done(); }, "WaitFor callback should always be set to a function": function (test) { test.expect(4); var WaitFor = require(path.join(process.cwd(), "src/WaitFor.js")); var waitFor1 = new WaitFor(), waitFor2 = new WaitFor({ callback : null }); test.equal(typeof waitFor1.callback === "function", true); test.equal(typeof waitFor2.callback === "function", true); test.equal(waitFor1.callback(), undefined); test.equal(waitFor2.callback(), undefined); test.done(); } };
{ "content_hash": "9e5abf01be252ee2e69e661b99987bcc", "timestamp": "", "source": "github", "line_count": 39, "max_line_length": 102, "avg_line_length": 32.282051282051285, "alnum_prop": 0.4988085782366958, "repo_name": "allenevans/essencejs", "id": "1b814baeb1268ae9cf3d1493fcbf02d3556b7f77", "size": "1259", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "test/WaitFor/WaitFor.spec.js", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "935" }, { "name": "HTML", "bytes": "3514" }, { "name": "JavaScript", "bytes": "229397" } ], "symlink_target": "" }
package gr.bytecode.apps.android.phonebook.ui.activities; import gr.bytecode.apps.android.phonebook.R; import gr.bytecode.apps.android.phonebook.application.AppConstants; import gr.bytecode.apps.android.phonebook.application.AppUtil; import gr.bytecode.apps.android.phonebook.repositories.PreferencesRepository; import gr.bytecode.apps.android.phonebook.repositories.VersionRepository; import gr.bytecode.apps.android.phonebook.services.DataUpdaterService; import gr.bytecode.apps.android.phonebook.services.JavaWebServiceClient; import java.text.DateFormat; import java.util.Date; import android.app.AlertDialog; import android.content.BroadcastReceiver; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.content.IntentFilter; import android.content.SharedPreferences; import android.content.SharedPreferences.OnSharedPreferenceChangeListener; import android.net.Uri; import android.os.AsyncTask; import android.os.Bundle; import android.preference.ListPreference; import android.preference.Preference; import android.preference.Preference.OnPreferenceClickListener; import android.preference.PreferenceScreen; import com.actionbarsherlock.app.ActionBar; import com.actionbarsherlock.app.SherlockPreferenceActivity; import com.actionbarsherlock.view.MenuItem; import com.actionbarsherlock.view.Window; import com.google.analytics.tracking.android.EasyTracker; public class PreferencesActivity extends SherlockPreferenceActivity implements OnSharedPreferenceChangeListener { /** * Reference to the data-check interval list-preference */ private ListPreference dataCheckListPreference; /** * Preference Item/Button used to initiate the data synch check */ private Preference checkDataNowPreference; /** * Preference Item/Button used to send us an email */ private Preference sendEmailPreference; /** * Preference Item/Button used to visit ByteCode.gr */ private Preference visitBytecodePreference; /** * Repository of App preferences */ protected PreferencesRepository preferencesRepository; /** * Reference to the applications SharedPreferences */ private SharedPreferences prefs; /** * App Context */ private Context mcontext; /** * The preference Screen */ private PreferenceScreen prefScreen; private boolean isRunning; private static String PREF_AUTO_DATA_CHECK_INTERVAL; /* * (non-Javadoc) * * @see android.support.v4.app.FragmentActivity#onStart() */ @Override public void onStart() { super.onStart(); // start G-A tracker EasyTracker.getInstance(this).activityStart(this); } /* * (non-Javadoc) * * @see com.actionbarsherlock.app.SherlockFragmentActivity#onStop() */ @Override public void onStop() { super.onStop(); // stop G-A tracker EasyTracker.getInstance(this).activityStop(this); } /** Called when the activity is first created. */ @SuppressWarnings("deprecation") @Override public void onCreate(Bundle savedInstanceState) { requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS); super.onCreate(savedInstanceState); // save the context in the field mcontext = this; // initiate indeterminate the progress bar setProgressBarIndeterminate(true); // start with a hidden progress bar setSupportProgressBarIndeterminateVisibility(false); // set the content view setContentView(R.layout.activity_preferences); // load the usage repository preferencesRepository = PreferencesRepository.getInstance(this); addPreferencesFromResource(R.xml.preferences); // initiate the preference screen prefScreen = getPreferenceScreen(); // get the name of the check interval reference PREF_AUTO_DATA_CHECK_INTERVAL = getString(R.string.PREF_AUTO_DATA_CHECK_INTERVAL); // locate the check interval preference dataCheckListPreference = (ListPreference) prefScreen .findPreference(PREF_AUTO_DATA_CHECK_INTERVAL); checkDataNowPreference = (Preference) prefScreen .findPreference(getString(R.string.PREF_DATA_CHECK_NOW)); sendEmailPreference = (Preference) prefScreen .findPreference(getString(R.string.PREF_EMAIL_US)); visitBytecodePreference = (Preference) prefScreen .findPreference(getString(R.string.PREF_VISIT_BYTECODE)); // initiate the reference to the SharedPreferences prefs = prefScreen.getSharedPreferences(); ActionBar actionBar = getSupportActionBar(); // configure the default look of the actionbar if (actionBar != null) { actionBar.setDisplayShowHomeEnabled(true); actionBar.setDisplayHomeAsUpEnabled(true); actionBar.setHomeButtonEnabled(true); actionBar.setDisplayShowTitleEnabled(true); actionBar.setTitle(getString(R.string.LBL_SETTINGS)); actionBar.setIcon(R.drawable.ic_ab_settings); } // set tap listeners setPreferencetapListeners(); } /** * Starts the mail activity * */ private void startMailActivity() { /* Create the Intent */ final Intent emailIntent = new Intent(android.content.Intent.ACTION_SEND); /* Fill it with Data */ emailIntent.setType("plain/text"); emailIntent.putExtra(android.content.Intent.EXTRA_EMAIL, new String[] { getString(R.string.TXT_BYTECODE_EMAIL) }); emailIntent.putExtra(android.content.Intent.EXTRA_SUBJECT, getString(R.string.TXT_SEND_EMAIL_SUBJ)); /* Send it off to the Activity-Chooser */ mcontext.startActivity(Intent.createChooser(emailIntent, getString(R.string.TITLE_SEND_EMAIL_CHOOSER))); } /** * Starts the browser app on the ByteCode homepage * */ private void visitBytecode() { Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(getText( R.string.TXT_BYTECODE_URL).toString())); startActivity(browserIntent); } /** * Starts the data check service */ private void startDataUpdateService() { // check if connected if (checkConnected()) { Intent intent = new Intent(this, DataUpdaterService.class); intent.putExtra(DataUpdaterService.PARAM_CHECK_DATA_VERSION_FIRST, false); intent.putExtra(DataUpdaterService.PARAM_OPEN_MAIN_ACTIVITY_AFTER_UPDATE, false); startService(intent); // inform the user that the check has started AppUtil.postToast(mcontext, getString(R.string.TXT_UPDATE_STARTED)); } } /** * Checks whether the device is connected and emits a notification if not * * @return */ private boolean checkConnected() { boolean verdict = AppUtil.isDeviceConnected(this); if (verdict == false) { // no network; notify the user AppUtil.postToast(this, getString(R.string.ERROR_NO_NETWORK)); } return verdict; } /** * Starts the data check task */ private void startDataCheckTask() { if (checkConnected()) { // disable the data-check button checkDataNowPreference.setEnabled(false); // show indeterminate progress bar setSupportProgressBarIndeterminateVisibility(true); AsyncDataChecker dataChecker = new AsyncDataChecker(); // get an instance of the version repository VersionRepository versionRepostiroy = VersionRepository.getInstance(); // get the current version Integer version = versionRepostiroy.getDataVersion(); // create a version String versionStr = version == null ? "" : version.toString(); // execute the task dataChecker.execute(versionStr); } } /** * Called when the update is finished */ private void finishedDataCheckTask() { // hide the progress bar setSupportProgressBarIndeterminateVisibility(false); // re-enable the data-check button checkDataNowPreference.setEnabled(true); } /* * (non-Javadoc) * * @see * com.actionbarsherlock.app.SherlockPreferenceActivity#onOptionsItemSelected * (android.view.MenuItem) */ @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case android.R.id.home: finish(); return true; default: return super.onOptionsItemSelected(item); } } /* * (non-Javadoc) * * @see android.app.Activity#onResume() */ @Override protected void onResume() { // android is resuming our app isRunning = true; // Call super super.onResume(); // Register mMessageReceiver to receive messages. registerReceiver(dataUpdatedReceiver, new IntentFilter(AppConstants.DATA_UPDATED_ACTION)); // Setup the initial values setDataCheckIntervalPrefDescription(prefs); // Set up a listener whenever a key changes prefScreen.getSharedPreferences().registerOnSharedPreferenceChangeListener(this); setLastDataUpdateDate(); } /* * (non-Javadoc) * * @see android.app.Activity#onPause() */ @Override protected void onPause() { super.onPause(); // android is resuming our app isRunning = false; // Unregister the listener whenever a key changes prefScreen.getSharedPreferences().unregisterOnSharedPreferenceChangeListener(this); // Unregister since the activity is not visible unregisterReceiver(dataUpdatedReceiver); } /* * (non-Javadoc) * * @see android.content.SharedPreferences.OnSharedPreferenceChangeListener# * onSharedPreferenceChanged(android.content.SharedPreferences, * java.lang.String) */ @Override public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) { if (key.equals(PREF_AUTO_DATA_CHECK_INTERVAL)) { setDataCheckIntervalPrefDescription(sharedPreferences); } } /** * Updates the description of the data-check-interval preference with * dynamic data * * @param prefs * The SharedPreferences object */ private void setDataCheckIntervalPrefDescription(SharedPreferences prefs) { // String value = prefs.getString(PREF_AUTO_DATA_CHECK_INTERVAL, ""); int value = preferencesRepository.getDataCheckInteral(); if (value == 0) { dataCheckListPreference.setSummary(getString(R.string.TXT_INACTIVE)); } else { dataCheckListPreference.setSummary(getString( R.string.TXT_SUMMARY_AUTO_DATA_CHECK_INTERVAL, value)); } } /** * Sets the last update's date on the related preference */ private void setLastDataUpdateDate() { // get the last data check date Date lastUpdate = preferencesRepository.getLastDataUpdateDate(); if (checkDataNowPreference != null && lastUpdate != null) { checkDataNowPreference.setSummary(getString(R.string.TXT_TITLE_LAST_DATA_UPDATE) + ": " + DateFormat.getDateInstance().format(lastUpdate)); } } /** * Sets some tap listeners on button-preferences */ private void setPreferencetapListeners() { // set a click listener on the check checkDataNowPreference.setOnPreferenceClickListener(new OnPreferenceClickListener() { /* * (non-Javadoc) * * @see android.preference.Preference.OnPreferenceClickListener# * onPreferenceClick(android.preference.Preference) */ public boolean onPreferenceClick(Preference preference) { startDataCheckTask(); return true; } }); sendEmailPreference.setOnPreferenceClickListener(new OnPreferenceClickListener() { /* * (non-Javadoc) * * @see android.preference.Preference.OnPreferenceClickListener# * onPreferenceClick(android.preference.Preference) */ public boolean onPreferenceClick(Preference preference) { startMailActivity(); return true; } }); visitBytecodePreference.setOnPreferenceClickListener(new OnPreferenceClickListener() { /* * (non-Javadoc) * * @see android.preference.Preference.OnPreferenceClickListener# * onPreferenceClick(android.preference.Preference) */ public boolean onPreferenceClick(Preference preference) { visitBytecode(); return true; } }); } /** * Show the update dialog * * @param newDataFound */ private void showUpdateDialog(boolean newDataFound) { // instantiate an AlertDialog.Builder with its constructor AlertDialog.Builder builder = new AlertDialog.Builder(mcontext); // choose the correct message to show String message = newDataFound ? getString(R.string.TXT_NEW_DATA_FOUND) : getString(R.string.TXT_DATA_IS_UP_TO_DATE); // choose the correct download button label String downloadButtonLabel = newDataFound ? getString(R.string.TXT_UPDATE_NOW) : getString(R.string.TXT_UPDATE_ANYWAY); // set the message and title of the dialog; builder.setTitle(message); // set the positive button builder.setPositiveButton(downloadButtonLabel, new DialogInterface.OnClickListener() { /* * (non-Javadoc) * * @see * android.content.DialogInterface.OnClickListener#onClick(android * .content.DialogInterface, int) */ public void onClick(DialogInterface dialog, int id) { // start the update service startDataUpdateService(); } }); // set the cancel button builder.setNegativeButton(getString(R.string.TXT_CLOSE), new DialogInterface.OnClickListener() { /* * (non-Javadoc) * * @see * android.content.DialogInterface.OnClickListener#onClick * (android .content.DialogInterface, int) */ public void onClick(DialogInterface dialog, int id) { // User cancelled the dialog; do nothing } }); // get the AlertDialog from create() AlertDialog dialog = builder.create(); // show the dialog dialog.show(); } /** * @author Dimitris Balaouras * @copyright 2013 ByteCode.gr * */ private class AsyncDataChecker extends AsyncTask<String, Integer, Boolean> { /* * (non-Javadoc) * * @see android.os.AsyncTask#doInBackground(Params[]) */ @Override protected Boolean doInBackground(String... params) { // create a Web Service client JavaWebServiceClient client = new JavaWebServiceClient(); // the first parameter *must* me the current version String currentVersion = params[0]; return client.isNewDataAvailable(currentVersion); } /* * (non-Javadoc) * * @see android.os.AsyncTask#onPostExecute(java.lang.Object) */ @Override protected void onPostExecute(Boolean result) { super.onPostExecute(result); // we are now done finishedDataCheckTask(); // show the dialog only if the activity is running if (isRunning) { // open the data-update dialog showUpdateDialog(result); } } } /** * Handler for data updates */ private BroadcastReceiver dataUpdatedReceiver = new BroadcastReceiver() { /* * (non-Javadoc) * * @see * android.content.BroadcastReceiver#onReceive(android.content.Context, * android.content.Intent) */ @Override public void onReceive(Context context, Intent intent) { // update the date setLastDataUpdateDate(); } }; }
{ "content_hash": "f9bdee140cebe771a45f32a6dea4cd5a", "timestamp": "", "source": "github", "line_count": 600, "max_line_length": 92, "avg_line_length": 24.411666666666665, "alnum_prop": 0.7320270362531577, "repo_name": "dbalaouras/greece-phonebook-android", "id": "d5d458d23ea06d470bb3ab84802b3b6c61a1849b", "size": "14781", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/gr/bytecode/apps/android/phonebook/ui/activities/PreferencesActivity.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "124363" } ], "symlink_target": "" }
"use strict"; var eol = require('os').EOL; var Pattern = require('../core/lib/object_factory').Pattern; var extend = require('util')._extend; function createFakePatternLab(customProps) { var pl = { config: { paths: { source: { patterns: './test/files/_patterns' }, public: { patterns: './test/output' } }, styleGuideExcludes: [ 'templates' ], debug: false, outputFileSuffixes: { rendered: '.rendered', rawTemplate: '', markupOnly: '.markup-only' } } }; return extend(pl, customProps); } var ui = require('../core/lib/ui_builder')(); exports['ui_builder'] = { 'isPatternExcluded - returns true when pattern filename starts with underscore': function (test) { //arrange var patternlab = createFakePatternLab({}); var pattern = new Pattern('00-test/_ignored-pattern.mustache'); //act var result = ui.isPatternExcluded(pattern, patternlab); //assert test.equals(result, true); test.done(); }, 'isPatternExcluded - returns true when pattern is defaultPattern': function (test) { //arrange var patternlab = createFakePatternLab({}); var pattern = new Pattern('00-test/foo.mustache'); patternlab.config.defaultPattern = 'test-foo'; //act var result = ui.isPatternExcluded(pattern, patternlab); //assert test.equals(result, true); test.done(); }, 'isPatternExcluded - returns true when pattern within underscored directory - top level': function (test) { //arrange var patternlab = createFakePatternLab({}); var pattern = Pattern.createEmpty({ relPath: '_hidden/patternsubtype/foo.mustache', isPattern: true, fileName : 'foo.mustache', patternPartial: 'hidden-foo' }); //act var result = ui.isPatternExcluded(pattern, patternlab); //assert test.equals(result, true); test.done(); }, 'isPatternExcluded - returns true when pattern within underscored directory - subtype level': function (test) { //arrange var patternlab = createFakePatternLab({}); var pattern = Pattern.createEmpty({ relPath: 'shown/_patternsubtype/foo.mustache', isPattern: true, fileName : 'foo.mustache', patternPartial: 'shown-foo' }); //act var result = ui.isPatternExcluded(pattern, patternlab); //assert test.equals(result, true); test.done(); }, 'groupPatterns - creates pattern groups correctly': function (test) { //arrange var patternlab = createFakePatternLab({ patterns: [], patternGroups: {}, subtypePatterns: {} }); patternlab.patterns.push( new Pattern('00-test/foo.mustache'), new Pattern('00-test/bar.mustache'), new Pattern('patternType1/patternSubType1/blue.mustache'), new Pattern('patternType1/patternSubType1/red.mustache'), new Pattern('patternType1/patternSubType1/yellow.mustache'), new Pattern('patternType1/patternSubType2/black.mustache'), new Pattern('patternType1/patternSubType2/grey.mustache'), new Pattern('patternType1/patternSubType2/white.mustache') ); ui.resetUIBuilderState(patternlab); //act var result = ui.groupPatterns(patternlab); //assert test.equals(result.patternGroups.patternType1.patternSubType1.blue.patternPartial, 'patternType1-blue'); test.equals(result.patternGroups.patternType1.patternSubType1.red.patternPartial, 'patternType1-red'); test.equals(result.patternGroups.patternType1.patternSubType1.yellow.patternPartial, 'patternType1-yellow'); test.equals(result.patternGroups.patternType1.patternSubType2.black.patternPartial, 'patternType1-black'); test.equals(result.patternGroups.patternType1.patternSubType2.grey.patternPartial, 'patternType1-grey'); test.equals(result.patternGroups.patternType1.patternSubType2.white.patternPartial, 'patternType1-white'); test.equals(patternlab.patternTypes[0].patternItems[0].patternPartial, 'test-bar'); test.equals(patternlab.patternTypes[0].patternItems[1].patternPartial, 'test-foo'); //todo: patternlab.patternTypes[0].patternItems[1] looks malformed test.done(); }, 'groupPatterns - creates documentation patterns for each type and subtype if not exists': function (test) { //arrange var patternlab = createFakePatternLab({ patterns: [], patternGroups: {}, subtypePatterns: {} }); patternlab.patterns.push( new Pattern('00-test/foo.mustache'), new Pattern('00-test/bar.mustache'), new Pattern('patternType1/patternSubType1/blue.mustache'), new Pattern('patternType1/patternSubType1/red.mustache'), new Pattern('patternType1/patternSubType1/yellow.mustache'), new Pattern('patternType1/patternSubType2/black.mustache'), new Pattern('patternType1/patternSubType2/grey.mustache'), new Pattern('patternType1/patternSubType2/white.mustache') ); ui.resetUIBuilderState(patternlab); //act var result = ui.groupPatterns(patternlab); //assert test.equals(result.patternGroups.patternType1.patternSubType1['viewall-patternType1-patternSubType1'].patternPartial, 'viewall-patternType1-patternSubType1'); test.equals(result.patternGroups.patternType1.patternSubType2['viewall-patternType1-patternSubType2'].patternPartial, 'viewall-patternType1-patternSubType2'); test.done(); }, 'groupPatterns - adds each pattern to the patternPaths object': function (test) { //arrange var patternlab = createFakePatternLab({ patterns: [], patternGroups: {}, subtypePatterns: {} }); patternlab.patterns.push( new Pattern('00-test/foo.mustache'), new Pattern('00-test/bar.mustache'), new Pattern('patternType1/patternSubType1/blue.mustache'), new Pattern('patternType1/patternSubType1/red.mustache'), new Pattern('patternType1/patternSubType1/yellow.mustache'), new Pattern('patternType1/patternSubType2/black.mustache'), new Pattern('patternType1/patternSubType2/grey.mustache'), new Pattern('patternType1/patternSubType2/white.mustache') ); ui.resetUIBuilderState(patternlab); //act var result = ui.groupPatterns(patternlab); //assert test.equals(patternlab.patternPaths['test']['foo'], '00-test-foo'); test.equals(patternlab.patternPaths['test']['bar'], '00-test-bar'); test.equals(patternlab.patternPaths['patternType1']['blue'], 'patternType1-patternSubType1-blue'); test.equals(patternlab.patternPaths['patternType1']['red'], 'patternType1-patternSubType1-red'); test.equals(patternlab.patternPaths['patternType1']['yellow'], 'patternType1-patternSubType1-yellow'); test.equals(patternlab.patternPaths['patternType1']['black'], 'patternType1-patternSubType2-black'); test.equals(patternlab.patternPaths['patternType1']['grey'], 'patternType1-patternSubType2-grey'); test.equals(patternlab.patternPaths['patternType1']['white'], 'patternType1-patternSubType2-white'); test.done(); }, 'groupPatterns - adds each pattern to the view all paths object': function (test) { //arrange var patternlab = createFakePatternLab({ patterns: [], patternGroups: {}, subtypePatterns: {} }); patternlab.patterns.push( new Pattern('00-test/foo.mustache'), new Pattern('00-test/bar.mustache'), new Pattern('patternType1/patternSubType1/blue.mustache'), new Pattern('patternType1/patternSubType1/red.mustache'), new Pattern('patternType1/patternSubType1/yellow.mustache'), new Pattern('patternType1/patternSubType2/black.mustache'), new Pattern('patternType1/patternSubType2/grey.mustache'), new Pattern('patternType1/patternSubType2/white.mustache') ); ui.resetUIBuilderState(patternlab); //act var result = ui.groupPatterns(patternlab); //assert test.equals('todo', 'todo'); test.done(); }, 'resetUIBuilderState - reset global objects' : function (test) { //arrange var patternlab = createFakePatternLab({ patternPaths: { foo: 1}, viewAllPaths: { bar: 2}, patternTypes: ['baz'] }); //act ui.resetUIBuilderState(patternlab); //assert test.equals(patternlab.patternPaths.foo, undefined); test.equals(patternlab.viewAllPaths.bar, undefined); test.equals(patternlab.patternTypes.length, 0); test.done(); } };
{ "content_hash": "ffa55c3fcbd636bfbf474f7c7a012113", "timestamp": "", "source": "github", "line_count": 250, "max_line_length": 162, "avg_line_length": 34.936, "alnum_prop": 0.6700251889168766, "repo_name": "firesidefiction/fireside-style-guide", "id": "bd3766c52c64451d61a074ed971ca263c0555273", "size": "8734", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "node_modules/patternlab-node/test/ui_builder_tests.js", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "93690" }, { "name": "HTML", "bytes": "2141926" }, { "name": "JavaScript", "bytes": "93632" } ], "symlink_target": "" }
package com.izhbg.typz.sso.audit.component; import java.util.concurrent.BlockingQueue; import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.TimeUnit; import org.springframework.stereotype.Component; import com.izhbg.typz.sso.audit.dto.AuditLog; @Component public class AuditLogQueue { private BlockingQueue<AuditLog> blockingQueue = new LinkedBlockingQueue<AuditLog>(); public void add(AuditLog auditLog) { blockingQueue.add(auditLog); } public AuditLog poll() throws InterruptedException { return blockingQueue.poll(1, TimeUnit.SECONDS); } }
{ "content_hash": "ddeebc321e7800e058ef037d1aa91981", "timestamp": "", "source": "github", "line_count": 23, "max_line_length": 88, "avg_line_length": 27.52173913043478, "alnum_prop": 0.7393364928909952, "repo_name": "izhbg/typz", "id": "cb2ed777fc2e2967f10db6fd9f6ca5136550cdb2", "size": "633", "binary": false, "copies": "1", "ref": "refs/heads/shop_0.1", "path": "typz-all/typz-sso/src/main/java/com/izhbg/typz/sso/audit/component/AuditLogQueue.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "553872" }, { "name": "CoffeeScript", "bytes": "105801" }, { "name": "FreeMarker", "bytes": "1156" }, { "name": "HTML", "bytes": "579555" }, { "name": "Java", "bytes": "1633285" }, { "name": "JavaScript", "bytes": "4805618" }, { "name": "Shell", "bytes": "1345" } ], "symlink_target": "" }
package parser import ( "net" "github.com/NoUseFreak/sawsh/internal/sawsh" "github.com/spf13/cobra" ) func ipParser(cmd *cobra.Command, hostname string) (*sawsh.Instance, error) { if net.ParseIP(hostname) != nil { return &sawsh.Instance{ IP: hostname, }, nil } return nil, nil }
{ "content_hash": "2c1f2b932ad631b4542a8c77bd7c04ca", "timestamp": "", "source": "github", "line_count": 18, "max_line_length": 77, "avg_line_length": 16.444444444444443, "alnum_prop": 0.6891891891891891, "repo_name": "NoUseFreak/sawsh", "id": "c35dd2cd57548418f5a58196a2a78cca762b9940", "size": "296", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "internal/sawsh/parser/ip.go", "mode": "33188", "license": "mit", "language": [ { "name": "Go", "bytes": "10791" }, { "name": "Makefile", "bytes": "139" }, { "name": "Shell", "bytes": "2886" } ], "symlink_target": "" }
// Copyright (c) egmkang wang. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. namespace Gateway { using System; using System.Configuration; public static class GatewaySettings { public static int Port => int.Parse(ConfigurationManager.AppSettings["port"]); public static string LogPrefix { get { var str = ConfigurationManager.AppSettings["log_prefix"]; return String.IsNullOrWhiteSpace(str) ? "gateway" : str; } } public static NLog.LogLevel LogLevel { get { var str = ConfigurationManager.AppSettings["log_level"]; return String.IsNullOrWhiteSpace(str) ? NLog.LogLevel.Debug : NLog.LogLevel.FromString(str); } } } }
{ "content_hash": "38c5f5a7a9bb15210d5e016ebdb288b5", "timestamp": "", "source": "github", "line_count": 30, "max_line_length": 108, "avg_line_length": 30.333333333333332, "alnum_prop": 0.5912087912087912, "repo_name": "egmkang/SharpServer", "id": "ff1060e6eef0ddf870d416ac4eb11f605f2a9ea1", "size": "912", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/Gateway/GatewaySettings.cs", "mode": "33188", "license": "mit", "language": [ { "name": "Batchfile", "bytes": "91" }, { "name": "C#", "bytes": "621444" }, { "name": "Protocol Buffer", "bytes": "89930" } ], "symlink_target": "" }
@interface AppBarWKWebViewLargeContentNoBugExample : UIViewController @property(nonatomic, strong) MDCAppBar *appBar; @property(nonatomic, strong) MDCSemanticColorScheme *colorScheme; @property(nonatomic, strong) MDCTypographyScheme *typographyScheme; @end @implementation AppBarWKWebViewLargeContentNoBugExample - (void)dealloc { // Required for pre-iOS 11 devices because we've enabled observesTrackingScrollViewScrollEvents. self.appBar.headerViewController.headerView.trackingScrollView = nil; } - (id)init { self = [super init]; if (self) { self.title = @"App Bar"; _appBar = [[MDCAppBar alloc] init]; // Behavioral flags. _appBar.inferTopSafeAreaInsetFromViewController = YES; _appBar.headerViewController.topLayoutGuideViewController = self; _appBar.headerViewController.headerView.minMaxHeightIncludesSafeArea = NO; _appBar.headerViewController.headerView.observesTrackingScrollViewScrollEvents = YES; [self addChildViewController:_appBar.headerViewController]; _appBar.navigationBar.inkColor = [UIColor colorWithWhite:(CGFloat)0.9 alpha:(CGFloat)0.1]; self.colorScheme = [[MDCSemanticColorScheme alloc] initWithDefaults:MDCColorSchemeDefaultsMaterial201804]; self.typographyScheme = [[MDCTypographyScheme alloc] init]; } return self; } - (void)viewDidLoad { [super viewDidLoad]; [MDCAppBarColorThemer applySemanticColorScheme:self.colorScheme toAppBar:_appBar]; [MDCAppBarTypographyThemer applyTypographyScheme:self.typographyScheme toAppBar:_appBar]; // Need to update the status bar style after applying the theme. [self setNeedsStatusBarAppearanceUpdate]; WKWebViewConfiguration *config = [[WKWebViewConfiguration alloc] init]; WKWebView *webView = [[WKWebView alloc] initWithFrame:self.view.bounds configuration:config]; webView.autoresizingMask = (UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight); [self.view addSubview:webView]; NSMutableArray *content = [@[ @"<html>\n<head></head><body>" ] mutableCopy]; for (NSInteger ix = 0; ix < 500; ++ix) { [content addObject:@"<p>Hello</p>"]; } [content addObject:@"</body></html>"]; [webView loadHTMLString:[content componentsJoinedByString:@"\n"] baseURL:nil]; self.appBar.headerViewController.headerView.trackingScrollView = webView.scrollView; [self.appBar addSubviewsToParent]; } - (UIViewController *)childViewControllerForStatusBarHidden { return self.appBar.headerViewController; } - (UIViewController *)childViewControllerForStatusBarStyle { return self.appBar.headerViewController; } - (void)viewWillAppear:(BOOL)animated { [super viewWillAppear:animated]; [self.navigationController setNavigationBarHidden:YES animated:animated]; } @end @implementation AppBarWKWebViewLargeContentNoBugExample (CatalogByConvention) + (NSDictionary *)catalogMetadata { return @{ @"breadcrumbs" : @[ @"App Bar", @"WKWebView large content no bug" ], @"primaryDemo" : @NO, @"presentable" : @NO, @"skip_snapshots" : @YES, // The webview content sometimes takes long to load. }; } - (BOOL)catalogShouldHideNavigation { return YES; } @end
{ "content_hash": "00f765e828ead62b7c3bb95d6321707c", "timestamp": "", "source": "github", "line_count": 96, "max_line_length": 98, "avg_line_length": 32.885416666666664, "alnum_prop": 0.7624326892619575, "repo_name": "material-components/material-components-ios", "id": "207a432804584e473088e6a17d89f268a88446c5", "size": "4302", "binary": false, "copies": "2", "ref": "refs/heads/develop", "path": "components/AppBar/examples/AppBarWKWebViewLargeContentNoBugExample.m", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "C", "bytes": "15108" }, { "name": "Objective-C", "bytes": "7907886" }, { "name": "Python", "bytes": "22330" }, { "name": "Ruby", "bytes": "108390" }, { "name": "Shell", "bytes": "118227" }, { "name": "Swift", "bytes": "896400" } ], "symlink_target": "" }
import re from collections import defaultdict from textwrap import dedent from generation_utils import GenerationUtils class Target(object): """Class to organize target template instances for generated BUILD files. To add a new target, created it as a class variable (see existing templates below), then add it to the list in get_template at the bottom so that it can be properly discovered. """ class NoSuchTargetError(Exception): def __init__(self, name): super(Target.NoSuchTargetError, self).__init__( 'Target "{name}" does not exist.'.format(name=name)) class NoSuchValueType(Exception): pass class MissingTemplateArgumentError(Exception): pass class Template(object): def __init__(self, name, params, template, blank_lines=True): """Creates a new target template, which can be used to generate code for targets in BUILD files using the format() method. :param name: The target type (eg, 'java_library') :param params: The list of parameters which can be injected into this template, optionally with an associated type declared by following with :type. Eg, 'sources:list' would create a parameter with the name 'sources' and the type 'list'. Understood types currently include 'raw', 'string', and 'list'. These types affect how the parameters are ultimately formatted when data is injected into this template. When the type is unspecified, it defaults to the values defined in DEFAULT_TYPES, or 'raw' if not present. Parameters also have a notion of extra flags, which basically act like type modifiers. These are specified in the following format: param_name:type:flags1:flag2:more_flags. Supported flags include: collapsible - when applied to a list, the list will be made a one-liner if it only has one argument. optional - if not specified (or specified as None), the argument will be entirely removed from the formatted output. This is done by splitting the output at the ',' character, and removing and entry which has optional parameters that are None, then joining it back together before returning the formatted result. sorted - when applied to a list, the list will be sorted() before formatting. emptyable - will format as the empty string rather than {} or [] for empty lists and dicts. :param template: The code for the actual template string, with parameter names specified in the same style used for str.format, eg 'Hello {person_name}.'. The parameters included in the template code must exactly match those defined in params, or an error will be raised when format() is invoked. :param blank_lines: Whether to pad the formatted output string with blank lines. """ self.name = name self.template = template self.blank_lines = blank_lines DEFAULT_TYPES = { 'name':'string', 'sources':'list', 'resources':'list', 'dependencies':'list', 'imports':'list', 'platform':'string', } self.flags = defaultdict(set) self.flags.update({ 'sources': {'collapsible'}, 'platform':'optional', }) self.params = {} for param in params: if ':' in param: parts = param.split(':') name, kind = parts[:2] self.params[name] = kind flags = set(parts[2:]) self.flags[name] = flags elif param in DEFAULT_TYPES: self.params[param] = DEFAULT_TYPES[param] else: self.params[param] = 'raw' def _indent_text(self, text, indent=2): lines = str(text).split('\n') lines = ['{0}{1}'.format(' '*indent, line).rstrip() for line in lines] return '\n'.join(lines) def _format_item(self, item): string_pattern = re.compile(r"^(?P<quote>'?)(?P<content>.*?)(?P=quote)(?P<comma>,?)$") object_pattern = re.compile(r'^(?P<content>[a-zA-Z_$0-9]+[(].*?[)].*?)(,?)$', re.DOTALL | re.MULTILINE) original = item item = item.strip() match = re.match(object_pattern, item) if match: # Handle things like jar() objects. return match.group('content') match = re.match(string_pattern, item) if not match: print(' Warning: Unrecognized item format, assuming raw object: {}.'.format(item)) return original return "'{}'".format(match.group('content')) def _format_dict(self, param, data): if not data: return '{}' items = [ (self._format_item(key), self._format_item(value)) for (key, value) in data.items() ] if 'sorted' in self.flags[param]: items = sorted(items) return '{{{}\n }}'.format(''.join('\n {}: {},'.format(key, val) for (key, val) in items)) def _format_list(self, param, items): if not items: return '[]' items = [self._format_item(item) for item in items if item] if len(items) == 1 and 'collapsible' in self.flags[param]: return '[{}]'.format(items[0]) if 'sorted' in self.flags[param]: items = sorted(items) return '[{}\n ]'.format(','.join('\n{}'.format(self._indent_text(item, indent=4)) for item in items)) def _extract(self, param, args): value = args.get(param) or '' kind = self.params[param] if kind == 'raw': return value # Value that can be matched properly by regexes. re_value = str(value).replace('\n', ' ') if kind == 'string': if not value: return "''" if re.match(r'^\s*(["{quote}]).*?[^\\]\1\s*$'.format(quote="'"), re_value): return value return "'{0}'".format(value) if 'emptyable' in self.flags[param] and not value: return '' if kind == 'list': if not value: return '[]' if isinstance(value, str): if '(' in value: return value # Hack for globs() and jar(). value = [value,] return self._format_list(param, value) if kind == 'dict': if not value: return '{}' if hasattr(value, '__getitem__') and hasattr(value, 'items'): return self._format_dict(param, value) if isinstance(value, str): return value raise ValueError('Illegally formatted dict argument: {} = {}.'.format(param, value)) raise Target.NoSuchValueType('No such value type "{kind}".'.format(kind=kind)) def _is_optional(self, param): return 'optional' in self.flags[param] def _strip_optional(self, **kwargs): parts = self.template.split(',') for param in self.params: if self._is_optional(param): if param not in kwargs or kwargs[param] is None: parts = [part for part in parts if '{%s}'%param not in part] elif param not in kwargs: completed = kwargs completed.update({ p: 'MISSING VALUE!' for p in self.params if p not in kwargs }) args_text = self.format(skip_missing_check=True, **completed) raise Target.MissingTemplateArgumentError('Missing argument "{}" for {}().\n{}' .format(param, self.name, args_text)) return ','.join(parts) def format(self, symbols=None, file_name=None, skip_missing_check=False, **kwargs): """Behaves somewhat like str.format, creating a 'concrete' by injecting relevant parameters into this template. Parameters which were not specified when this template was initialized are ignored. Unspecified parameters will default to reasonable values based on their types (eg, [] or ''). The parameters are formatted according to their type (specified as 'name:type', defaulting to their value in DEFAULT_TYPES or 'raw'). This means parameters which are lists should be passed in as actual list objects, not as strings. If a string is passed in, it will be inserted literally, which is useful for specifying things like "globs('*.java')" rather than an explicit list of sources. Parameters which are strings will be automatically wrapped in single-quotes if they aren't already (eg, '"hello"' will become "hello" in the output file, and 'hello' will become 'hello'). Raw parameters will be inserted literally, so the string 'hello' will just become hello in the output. Example usage: Target.jar_library.format(name='lib', jars=["'3rdparty:fake-library'",],) :param dict symbols: If present, replaces all instances of ${key} with symbols[key] in the formatted output string. :param string file_name: Optional string used to format error messages if something goes wrong. :param skip_missing_check: If true, will skip the normal check for missing arguments. :returns: a string containing the target, which can be inserted directly into a BUILD file. """ if symbols: def substitute(value): return GenerationUtils.symbol_substitution(symbols, value, symbols_name=file_name) for key, value in list(kwargs.items()): if not value: continue if any(isinstance(value, t) for t in (list,set,tuple,)): kwargs[key] = [substitute(v) for v in value] elif hasattr(value, '__getitem__') and hasattr(value, 'items'): kwargs[key] = { k: substitute(v) for k,v in value.items() } else: kwargs[key] = substitute(value) relevant = {} for param in self.params.keys(): relevant[param] = self._extract(param, kwargs) template = self._strip_optional(**kwargs) if not skip_missing_check else self.template text = template.format(**relevant) if not self.blank_lines: return text return '\n{0}\n'.format(text) _ALL_TEMPLATES = {} @classmethod def create_template(cls, *args, **kwargs): template = cls.Template(*args, **kwargs) cls._ALL_TEMPLATES[template.name] = template return template @classmethod def get_template(cls, name): if name in cls._ALL_TEMPLATES: return cls._ALL_TEMPLATES[name] raise Target.NoSuchTargetError(name) @classmethod def reset(cls): """Clear out existing templates. Intended for testing. """ cls._ALL_TEMPLATES = {} Target.annotation_processor = Target.create_template('annotation_processor', ['name', 'sources', 'resources', 'dependencies', 'platform',], '''annotation_processor(name={name}, sources = {sources}, resources = {resources}, dependencies = {dependencies}, platform = {platform}, )''') Target.dependencies = Target.create_template('dependencies', ['name', 'dependencies',], '''target(name={name}, dependencies = {dependencies}, )''') Target.fingerprint = Target.create_template('fingerprint', ['name', 'sources', 'dependencies'], dedent(''' # This target's sole purpose is just to invalidate the cache if loose files (eg app-manifest.yaml) # for the jvm_binary change. fingerprint(name={name}, sources = {sources}, dependencies = {dependencies}, ) ''').strip()) Target.placeholder = Target.create_template('placeholder', ['name',], '''target(name={name}) ''') Target.jar_library = Target.create_template('jar_library', ['name', 'jars:list:sorted',], '''jar_library(name={name}, jars = {jars}, )''') Target.java_library = Target.create_template('java_library', ['name', 'sources', 'resources', 'dependencies', 'groupId', 'artifactId', 'platform',], '''java_library(name={name}, sources = {sources}, resources = {resources}, dependencies = {dependencies}, platform = {platform}, provides = artifact(org='{groupId}', name='{artifactId}', repo=square,), # see squarepants/plugin/repo/register.py )''') Target.java_protobuf_library = Target.create_template('java_protobuf_library', ['name', 'sources', 'dependencies', 'imports', 'platform', 'groupId', 'artifactId'], '''java_protobuf_library(name={name}, sources = {sources}, imports = {imports}, dependencies = {dependencies}, platform = {platform}, provides = artifact(org='{groupId}', name='{artifactId}', repo=square,), # see squarepants/plugin/repo/register.py )''') Target.java_wire_library = Target.create_template('java_wire_library', ['name', 'sources', 'dependencies', 'roots:list', 'service_factory:string', 'enum_options:list:optional', 'registry_class:string', 'no_options:raw:optional', 'platform'], '''java_wire_library(name={name}, sources = {sources}, dependencies = {dependencies}, roots = {roots}, service_factory = {service_factory}, enum_options = {enum_options}, no_options = {no_options}, registry_class = {registry_class}, platform = {platform}, )''') Target.jvm_prep_command = Target.create_template('jvm_prep_command', ['name', 'mainclass:string', 'goal:string:optional', 'args:list:optional', 'jvm_options:list:optional', 'dependencies:list'], dedent(''' jvm_prep_command(name={name}, goal={goal}, mainclass={mainclass}, args={args}, jvm_options={jvm_options}, dependencies={dependencies}, ) ''')) Target.junit_tests = Target.create_template('junit_tests', ['name', 'sources', 'cwd:string', 'dependencies', 'platform', 'tags:list:optional', 'extra_env_vars:dict:optional', 'extra_jvm_options:list:optional'], '''junit_tests(name={name}, # TODO: Ideally, sources between :test, :integration-tests and :lib should not intersect sources = {sources}, cwd = {cwd}, tags = {tags}, dependencies = {dependencies}, platform = {platform}, extra_env_vars = {extra_env_vars}, extra_jvm_options = {extra_jvm_options}, )''') Target.jvm_binary = Target.create_template('jvm_binary', ['name', 'main:string', 'basename:string', 'dependencies', 'manifest_entries:dict:emptyable', 'deploy_excludes:list:optional', 'platform', 'shading_rules:list:optional'], '''jvm_binary(name={name}, main = {main}, basename= {basename}, dependencies = {dependencies}, manifest_entries = square_manifest({manifest_entries}), deploy_excludes = {deploy_excludes}, platform = {platform}, shading_rules = {shading_rules}, )''') Target.resources = Target.create_template('resources', ['name', 'sources', 'dependencies:list:optional'], '''resources(name={name}, sources = {sources}, dependencies = {dependencies}, )''') Target.signed_jars = Target.create_template('signed_jars', ['name', 'dependencies', 'strip_version:raw:optional'], '''signed_jars(name={name}, dependencies={dependencies}, strip_version={strip_version}, )''') Target.unpacked_jars = Target.create_template('unpacked_jars', ['name', 'libraries:list', 'include_patterns:list', 'exclude_patterns:list'], '''unpacked_jars(name={name}, libraries = {libraries}, include_patterns = {include_patterns}, exclude_patterns = {exclude_patterns}, )''') Target.jar = Target.create_template('jar', ['org:string', 'name:string', 'rev:string', 'force:raw:optional', 'excludes:list:optional', 'mutable:raw:optional', 'artifacts:list:optional', 'ext:string:optional', 'url:string:optional', 'classifier:string:optional', 'apidocs:string:optional', 'type_:string:optional', 'intransitive:raw:optional',], '''sjar(org={org}, name={name}, rev={rev}, force={force}, mutable={mutable}, ext={ext}, \ classifier={classifier}, ext={type_}, intransitive={intransitive}, url={url}, apidocs={apidocs}, artifacts={artifacts}, excludes={excludes},) '''.strip(), blank_lines=False) Target.sjar = Target.create_template('sjar', ['org:string', 'name:string', 'rev:string', 'force:raw:optional', 'excludes:list:optional', 'mutable:raw:optional', 'artifacts:list:optional', 'ext:string:optional', 'url:string:optional', 'classifier:string:optional', 'apidocs:string:optional', 'type_:string:optional', 'intransitive:raw:optional',], '''sjar(org={org}, name={name}, rev={rev}, mutable={mutable}, ext={ext}, \ classifier={classifier}, ext={type_}, intransitive={intransitive}, url={url}, force={force}, apidocs={apidocs}, artifacts={artifacts}, excludes={excludes},) '''.strip(), blank_lines=False) Target.wire_proto_path = Target.create_template('wire_proto_path', ['name', 'sources', 'dependencies'], dedent(''' wire_proto_path(name={name}, sources={sources}, dependencies={dependencies}, ) ''').strip())
{ "content_hash": "675bd1b66ba6421b7eb112b109490dd7", "timestamp": "", "source": "github", "line_count": 425, "max_line_length": 100, "avg_line_length": 39.78588235294118, "alnum_prop": 0.6280087527352297, "repo_name": "ericzundel/mvn2pants", "id": "709705f3a89c95727641ee4a745c9e735c585911", "size": "16909", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/python/squarepants/target_template.py", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "283" }, { "name": "Python", "bytes": "641401" }, { "name": "Shell", "bytes": "240" } ], "symlink_target": "" }
ACCEPTED #### According to Index Fungorum #### Published in Öst. bot. Z. 20(2): 33 (1870) #### Original name Hydnum schiedermayeri var. schiedermayeri ### Remarks null
{ "content_hash": "59c027a7e8cda8172e1f6df117d0b218", "timestamp": "", "source": "github", "line_count": 13, "max_line_length": 41, "avg_line_length": 13.153846153846153, "alnum_prop": 0.695906432748538, "repo_name": "mdoering/backbone", "id": "2c3c6bcac1a991f824dc85a0e0b6ec41cced4647", "size": "237", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "life/Fungi/Basidiomycota/Agaricomycetes/Polyporales/Meruliaceae/Sarcodontia/Sarcodontia crocea/Hydnum schiedermayeri schiedermayeri/README.md", "mode": "33188", "license": "apache-2.0", "language": [], "symlink_target": "" }
namespace Merchello.Core.Models.Rdbms { using System; using Umbraco.Core.Persistence; using Umbraco.Core.Persistence.DatabaseAnnotations; /// <summary> /// A DTO object for performing product attribute related data operations. /// </summary> [TableName("merchProductAttribute")] [PrimaryKey("pk", autoIncrement = false)] [ExplicitColumns] internal class ProductAttributeDto { /// <summary> /// Gets or sets the key. /// </summary> [Column("pk")] [PrimaryKeyColumn(AutoIncrement = false)] [Constraint(Default = "newid()")] public Guid Key { get; set; } /// <summary> /// Gets or sets the option key. /// </summary> [Column("optionKey")] [ForeignKey(typeof(ProductOptionDto), Name = "FK_merchProductAttribute_merchOption", Column = "pk")] public Guid OptionKey { get; set; } /// <summary> /// Gets or sets the name. /// </summary> [Column("name")] public string Name { get; set; } /// <summary> /// Gets or sets the SKU. /// </summary> [Column("sku")] public string Sku { get; set; } /// <summary> /// Gets or sets the detached content values. /// </summary> [Column("detachedContentValues")] [NullSetting(NullSetting = NullSettings.Null)] public string DetachedContentValues { get; set; } /// <summary> /// Gets or sets the sort order. /// </summary> [Column("sortOrder")] public int SortOrder { get; set; } /// <summary> /// Gets or sets a value indicating whether is default choice. /// </summary> [Column("isDefaultChoice")] [Constraint(Default = "0")] public bool IsDefaultChoice { get; set; } /// <summary> /// Gets or sets the update date. /// </summary> [Column("updateDate")] [Constraint(Default = "getdate()")] public DateTime UpdateDate { get; set; } /// <summary> /// Gets or sets the create date. /// </summary> [Column("createDate")] [Constraint(Default = "getdate()")] public DateTime CreateDate { get; set; } } }
{ "content_hash": "774bc8b5d7418bc93efcef61880d5fae", "timestamp": "", "source": "github", "line_count": 77, "max_line_length": 108, "avg_line_length": 29.896103896103895, "alnum_prop": 0.547784535186794, "repo_name": "ProNotion/Merchello", "id": "0ff5fff5eb3546fecbf11b73ebe9b564407ffda0", "size": "2304", "binary": false, "copies": "1", "ref": "refs/heads/merchello-dev", "path": "src/Merchello.Core/Models/Rdbms/ProductAttributeDto.cs", "mode": "33188", "license": "mit", "language": [ { "name": "ASP", "bytes": "549078" }, { "name": "Batchfile", "bytes": "1815" }, { "name": "C#", "bytes": "7570084" }, { "name": "CSS", "bytes": "623289" }, { "name": "HTML", "bytes": "2286001" }, { "name": "JavaScript", "bytes": "13445607" }, { "name": "XSLT", "bytes": "97082" } ], "symlink_target": "" }
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>checker: 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 / checker - 8.5.0</a></li> </ul> </div> </div> </div> <div class="article"> <div class="row"> <div class="col-md-12"> <a href="../..">« Up</a> <h1> checker <small> 8.5.0 <span class="label label-info">Not compatible 👼</span> </small> </h1> <p>📅 <em><script>document.write(moment("2022-03-10 06:33:29 +0000", "YYYY-MM-DD HH:mm:ss Z").fromNow());</script> (2022-03-10 06:33:29 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.08.1 The OCaml compiler (virtual package) ocaml-base-compiler 4.08.1 Official release 4.08.1 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;matej.kosik@inria.fr&quot; homepage: &quot;https://github.com/coq-contribs/checker&quot; license: &quot;LGPL 2&quot; build: [make &quot;-j%{jobs}%&quot;] install: [make &quot;install&quot;] remove: [&quot;rm&quot; &quot;-R&quot; &quot;%{lib}%/coq/user-contrib/Checker&quot;] depends: [ &quot;ocaml&quot; &quot;coq&quot; {&gt;= &quot;8.5&quot; &amp; &lt; &quot;8.6~&quot;} ] tags: [ &quot;keyword:checker&quot; &quot;keyword:dominos&quot; &quot;keyword:puzzles&quot; &quot;category:Miscellaneous/Logical Puzzles and Entertainment&quot; ] authors: [ &quot;Gérard Huet &lt;&gt;&quot; ] bug-reports: &quot;https://github.com/coq-contribs/checker/issues&quot; dev-repo: &quot;git+https://github.com/coq-contribs/checker.git&quot; synopsis: &quot;The Mutilated Checkerboard&quot; flags: light-uninstall url { src: &quot;https://github.com/coq-contribs/checker/archive/v8.5.0.tar.gz&quot; checksum: &quot;md5=09c7c97bb8d0bd55db2674679d6fbbc6&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-checker.8.5.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-checker -&gt; coq &lt; 8.6~ -&gt; ocaml &lt; 4.06.0 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-checker.8.5.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": "4692d9784e5ab531172a2e4d6491ee55", "timestamp": "", "source": "github", "line_count": 163, "max_line_length": 162, "avg_line_length": 41.57055214723926, "alnum_prop": 0.5373376623376623, "repo_name": "coq-bench/coq-bench.github.io", "id": "ecb29f3c8d8a355a35007e33b9cc707f414e565d", "size": "6802", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "clean/Linux-x86_64-4.08.1-2.0.5/extra-dev/dev/checker/8.5.0.html", "mode": "33188", "license": "mit", "language": [], "symlink_target": "" }
package com.rest.client.ds; import com.fasterxml.jackson.annotation.JsonProperty; import com.google.gson.annotations.SerializedName; import com.chopping.rest.RestObject; import io.realm.Realm; import io.realm.RealmObject; public class RequestForResponse extends RestObject { @SerializedName("reqId") @JsonProperty("reqId") private String mReqId; @SerializedName("reqTime") @JsonProperty("reqTime") private long mReqTime; public String getReqId() { return mReqId; } public void setReqId( String reqId ) { mReqId = reqId; } public long getReqTime() { return mReqTime; } public void setReqTime( long reqTime ) { mReqTime = reqTime; } @Override protected RealmObject[] newInstances( Realm db, int status ) { RequestForResponseDB dbItem = new RequestForResponseDB(); dbItem.setReqId( getReqId() ); dbItem.setReqTime( getReqTime() ); dbItem.setStatus( status ); return new RealmObject[] { dbItem }; } @Override public Class<? extends RealmObject> DBType() { return RequestForResponseDB.class; } }
{ "content_hash": "2419d4d3a08b42ff249678da038b5505", "timestamp": "", "source": "github", "line_count": 49, "max_line_length": 64, "avg_line_length": 21.3265306122449, "alnum_prop": 0.738755980861244, "repo_name": "XinyueZ/rest-20121015-client", "id": "0147ea7dcfe340cf1db6900a5699a43e04e413e8", "size": "1045", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "app/src/main/java/com/rest/client/ds/RequestForResponse.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "112007" } ], "symlink_target": "" }
<!DOCTYPE html> <html xmlns:msxsl="urn:schemas-microsoft-com:xslt"> <head> <meta content="en-us" http-equiv="Content-Language" /> <meta content="text/html; charset=utf-16" http-equiv="Content-Type" /> <title _locid="PortabilityAnalysis0">.NET Portability Report</title> <style> /* Body style, for the entire document */ body { background: #F3F3F4; color: #1E1E1F; font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif; padding: 0; margin: 0; } /* Header1 style, used for the main title */ h1 { padding: 10px 0px 10px 10px; font-size: 21pt; background-color: #E2E2E2; border-bottom: 1px #C1C1C2 solid; color: #201F20; margin: 0; font-weight: normal; } /* Header2 style, used for "Overview" and other sections */ h2 { font-size: 18pt; font-weight: normal; padding: 15px 0 5px 0; margin: 0; } /* Header3 style, used for sub-sections, such as project name */ h3 { font-weight: normal; font-size: 15pt; margin: 0; padding: 15px 0 5px 0; background-color: transparent; } h4 { font-weight: normal; font-size: 12pt; margin: 0; padding: 0 0 0 0; background-color: transparent; } /* Color all hyperlinks one color */ a { color: #1382CE; } /* Paragraph text (for longer informational messages) */ p { font-size: 10pt; } /* Table styles */ table { border-spacing: 0 0; border-collapse: collapse; font-size: 10pt; } table th { background: #E7E7E8; text-align: left; text-decoration: none; font-weight: normal; padding: 3px 6px 3px 6px; } table td { vertical-align: top; padding: 3px 6px 5px 5px; margin: 0px; border: 1px solid #E7E7E8; background: #F7F7F8; } .NoBreakingChanges { color: darkgreen; font-weight:bold; } .FewBreakingChanges { color: orange; font-weight:bold; } .ManyBreakingChanges { color: red; font-weight:bold; } .BreakDetails { margin-left: 30px; } .CompatMessage { font-style: italic; font-size: 10pt; } .GoodMessage { color: darkgreen; } /* Local link is a style for hyperlinks that link to file:/// content, there are lots so color them as 'normal' text until the user mouse overs */ .localLink { color: #1E1E1F; background: #EEEEED; text-decoration: none; } .localLink:hover { color: #1382CE; background: #FFFF99; text-decoration: none; } /* Center text, used in the over views cells that contain message level counts */ .textCentered { text-align: center; } /* The message cells in message tables should take up all avaliable space */ .messageCell { width: 100%; } /* Padding around the content after the h1 */ #content { padding: 0px 12px 12px 12px; } /* The overview table expands to width, with a max width of 97% */ #overview table { width: auto; max-width: 75%; } /* The messages tables are always 97% width */ #messages table { width: 97%; } /* All Icons */ .IconSuccessEncoded, .IconInfoEncoded, .IconWarningEncoded, .IconErrorEncoded { min-width: 18px; min-height: 18px; background-repeat: no-repeat; background-position: center; } /* Success icon encoded */ .IconSuccessEncoded { /* Note: Do not delete the comment below. It is used to verify the correctness of the encoded image resource below before the product is released */ /* [---XsltValidateInternal-Base64EncodedImage:IconSuccess#Begin#background-image: url(data:image/png;base64,#Separator#);#End#] */ background-image: url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAABPElEQVR4Xp1Tv0vDUBi8FqeA4NpBcBLcWnQSApncOnTo4FSnjP0DsnXpH5CxiwbHDg4Zuj4oOEXiJgiC4FDcCkLWmIMc1Pfw+eMgQ77v3Xf3Pe51YKGqqisAEwCR1TIAsiAIblSo6xrdHeJR85Xle3mdmCQKb0PsfqyxxzM8K15HZADl/H5+sHpZwYfxyRjTs+kWwKBx8yoHd2mRiuzF8mkJniWH/13u3Fjrs/EdhsdDFHGB/DLXEJBDLh1MWPAhPo1BLB4WX5yQywHR+m3tVe/t97D52CB/ziG0nIgD/qDuYg8WuCcVZ2YGwlJ3YDugkpR/VNcAEx6GEKhERSr71FuO4YCM4XBdwKvecjIlkSnsO0Hyp/GxSeJAdzBKzpOtnPwyyiPdAZhpZptT04tU+zk7s8czeges//s5C5+CwqrR4/gw+AAAAABJRU5ErkJggg==); } /* Information icon encoded */ .IconInfoEncoded { /* Note: Do not delete the comment below. It is used to verify the correctness of the encoded image resource below before the product is released */ /* [---XsltValidateInternal-Base64EncodedImage:IconInformation#Begin#background-image: url(data:image/png;base64,#Separator#);#End#] */ background-image: url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAABHElEQVR4Xs2TsUoDQRRF7wwoziokjZUKadInhdhukR9YP8DMX1hYW+QvdsXa/QHBbcXC7W0CamWTQnclFutceIQJwwaWNLlwm5k5d94M76mmaeCrrmsLYOocY12FcxZFUeozCqKqqgYA8uevv1H6VuPxcwlfk5N92KHBxfFeCSAxxswlYAW/Xr989x/mv9gkhtyMDhcAxgzRsp7flj8B/HF1RsMXq+NZMkopaHe7lbKxQUEIGbKsYNoGn969060hZBkQex/W8oRQwsQaW2o3Ago2SVcJUzAgY3N0lTCZZm+zPS8HB51gMmS1DEYyOz9acKO1D8JWTlafKIMxdhvlfdyT94Vv5h7P8Ky7nQzACmhvKq3zk3PjW9asz9D/1oigecsioooAAAAASUVORK5CYII=); } /* Warning icon encoded */ .IconWarningEncoded { /* Note: Do not delete the comment below. It is used to verify the correctness of the encoded image resource below before the product is released */ /* [---XsltValidateInternal-Base64EncodedImage:IconWarning#Begin#background-image: url(data:image/png;base64,#Separator#);#End#] */ background-image: url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAAACXBIWXMAAA7EAAAOxAGVKw4bAAAAx0lEQVR4XpWSMQ7CMAxFf4xAyBMLCxMrO8dhaBcuwdCJS3RJBw7SA/QGTCxdWJgiQYWKXJWKIXHIlyw5lqr34tQgEOdcBsCOx5yZK3hCCKdYXneQkh4pEfqzLfu+wVDSyyzFoJjfz9NB+pAF+eizx2Vruts0k15mPgvS6GYvpVtQhB61IB/dk6AF6fS4Ben0uIX5odtFe8Q/eW1KvFeH4e8khT6+gm5B+t3juyDt7n0jpe+CANTd+oTUjN/U3yVaABnSUjFz/gFq44JaVSCXeQAAAABJRU5ErkJggg==); } /* Error icon encoded */ .IconErrorEncoded { /* Note: Do not delete the comment below. It is used to verify the correctness of the encoded image resource below before the product is released */ /* [---XsltValidateInternal-Base64EncodedImage:IconError#Begin#background-image: url(data:image/png;base64,#Separator#);#End#] */ background-image: url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAABQElEQVR4XqWTvUoEQRCE6wYPZUA80AfwAQz23uCMjA7MDRQEIzPBVEyNTQUFIw00vcQTTMzuAh/AxEQQT8HF/3G/oGGnEUGuoNnd6qoZuqltyKEsyzVJq5I6rnUp6SjGeGhESikzzlc1eL7opfuVbrqbU1Zw9NCgtQMaZpY0eNnaaL2fHusvTK5vKu7sjSS1Y4y3QUA6K3e3Mau5UFDyMP7tYF9o8cAHZv68vipoIJg971PZIZ5HiwdvYGGvFVFHmGmZ2MxwmQYPXubPl9Up0tfoMQGetXd6mRbvhBw+boZ6WF7Mbv1+GsHRk0fQmPAH1GfmZirbCfDJ61tw3Px8/8pZsPAG4jlVhcPgZ7adwNWBB68lkRQWFiTgFlbnLY3DGGM7izIJIyT/jjIvEJw6fdJTc6krDzh6aMwMP9bvDH4ADSsa9uSWVJkAAAAASUVORK5CYII=); } </style> </head> <body> <h1 _locid="PortabilityReport">.NET Portability Report</h1> <div id="content"> <div id="submissionId" style="font-size:8pt;"> <p> <i> Submission Id&nbsp; b210ff74-af0b-48ff-bb69-36827aa83e06 </i> </p> </div> <h2 _locid="SummaryTitle"> <a name="Portability Summary"></a>Portability Summary </h2> <div id="summary"> <table> <tbody> <tr> <th>Assembly</th> <th>ASP.NET 5,Version=v1.0</th> <th>Windows,Version=v8.1</th> <th>.NET Framework,Version=v4.6</th> <th>Windows Phone,Version=v8.1</th> </tr> <tr> <td><strong><a href="#IASL.BioTextMining.NamedEntityIdentification">IASL.BioTextMining.NamedEntityIdentification</a></strong></td> <td class="text-center">98.43 %</td> <td class="text-center">91.64 %</td> <td class="text-center">100.00 %</td> <td class="text-center">91.64 %</td> </tr> </tbody> </table> </div> <div id="details"> <a name="IASL.BioTextMining.NamedEntityIdentification"><h3>IASL.BioTextMining.NamedEntityIdentification</h3></a> <table> <tbody> <tr> <th>Target type</th> <th>ASP.NET 5,Version=v1.0</th> <th>Windows,Version=v8.1</th> <th>.NET Framework,Version=v4.6</th> <th>Windows Phone,Version=v8.1</th> <th>Recommended changes</th> </tr> <tr> <td>System.Console</td> <td class="IconSuccessEncoded"></td> <td class="IconErrorEncoded"></td> <td class="IconSuccessEncoded"></td> <td class="IconErrorEncoded"></td> <td></td> </tr> <tr> <td style="padding-left:2em">get_Error</td> <td class="IconSuccessEncoded"></td> <td class="IconErrorEncoded"></td> <td class="IconSuccessEncoded"></td> <td class="IconErrorEncoded"></td> <td></td> </tr> <tr> <td>&nbsp;</td> <td>&nbsp;</td> <td>&nbsp;</td> <td>&nbsp;</td> <td>&nbsp;</td> <td>&nbsp;</td> </tr> <tr> <td>System.Diagnostics.Process</td> <td class="IconSuccessEncoded"></td> <td class="IconErrorEncoded"></td> <td class="IconSuccessEncoded"></td> <td class="IconErrorEncoded"></td> <td></td> </tr> <tr> <td style="padding-left:2em">#ctor</td> <td class="IconSuccessEncoded"></td> <td class="IconErrorEncoded"></td> <td class="IconSuccessEncoded"></td> <td class="IconErrorEncoded"></td> <td></td> </tr> <tr> <td style="padding-left:2em">Close</td> <td class="IconErrorEncoded"></td> <td class="IconErrorEncoded"></td> <td class="IconSuccessEncoded"></td> <td class="IconErrorEncoded"></td> <td>Use Dispose() instead</td> </tr> <tr> <td style="padding-left:2em">get_StandardOutput</td> <td class="IconSuccessEncoded"></td> <td class="IconErrorEncoded"></td> <td class="IconSuccessEncoded"></td> <td class="IconErrorEncoded"></td> <td></td> </tr> <tr> <td style="padding-left:2em">get_StartInfo</td> <td class="IconSuccessEncoded"></td> <td class="IconErrorEncoded"></td> <td class="IconSuccessEncoded"></td> <td class="IconErrorEncoded"></td> <td></td> </tr> <tr> <td style="padding-left:2em">set_EnableRaisingEvents(System.Boolean)</td> <td class="IconSuccessEncoded"></td> <td class="IconErrorEncoded"></td> <td class="IconSuccessEncoded"></td> <td class="IconErrorEncoded"></td> <td></td> </tr> <tr> <td style="padding-left:2em">Start</td> <td class="IconSuccessEncoded"></td> <td class="IconErrorEncoded"></td> <td class="IconSuccessEncoded"></td> <td class="IconErrorEncoded"></td> <td></td> </tr> <tr> <td>&nbsp;</td> <td>&nbsp;</td> <td>&nbsp;</td> <td>&nbsp;</td> <td>&nbsp;</td> <td>&nbsp;</td> </tr> <tr> <td>System.Diagnostics.ProcessStartInfo</td> <td class="IconSuccessEncoded"></td> <td class="IconErrorEncoded"></td> <td class="IconSuccessEncoded"></td> <td class="IconErrorEncoded"></td> <td></td> </tr> <tr> <td style="padding-left:2em">set_Arguments(System.String)</td> <td class="IconSuccessEncoded"></td> <td class="IconErrorEncoded"></td> <td class="IconSuccessEncoded"></td> <td class="IconErrorEncoded"></td> <td></td> </tr> <tr> <td style="padding-left:2em">set_CreateNoWindow(System.Boolean)</td> <td class="IconSuccessEncoded"></td> <td class="IconErrorEncoded"></td> <td class="IconSuccessEncoded"></td> <td class="IconErrorEncoded"></td> <td></td> </tr> <tr> <td style="padding-left:2em">set_FileName(System.String)</td> <td class="IconSuccessEncoded"></td> <td class="IconErrorEncoded"></td> <td class="IconSuccessEncoded"></td> <td class="IconErrorEncoded"></td> <td></td> </tr> <tr> <td style="padding-left:2em">set_RedirectStandardOutput(System.Boolean)</td> <td class="IconSuccessEncoded"></td> <td class="IconErrorEncoded"></td> <td class="IconSuccessEncoded"></td> <td class="IconErrorEncoded"></td> <td></td> </tr> <tr> <td style="padding-left:2em">set_UseShellExecute(System.Boolean)</td> <td class="IconSuccessEncoded"></td> <td class="IconErrorEncoded"></td> <td class="IconSuccessEncoded"></td> <td class="IconErrorEncoded"></td> <td>Remove ShellExecute usage (Can Pinvoke if needed)</td> </tr> <tr> <td style="padding-left:2em">set_WorkingDirectory(System.String)</td> <td class="IconSuccessEncoded"></td> <td class="IconErrorEncoded"></td> <td class="IconSuccessEncoded"></td> <td class="IconErrorEncoded"></td> <td></td> </tr> <tr> <td>&nbsp;</td> <td>&nbsp;</td> <td>&nbsp;</td> <td>&nbsp;</td> <td>&nbsp;</td> <td>&nbsp;</td> </tr> <tr> <td>System.IO.Directory</td> <td class="IconSuccessEncoded"></td> <td class="IconErrorEncoded"></td> <td class="IconSuccessEncoded"></td> <td class="IconErrorEncoded"></td> <td></td> </tr> <tr> <td style="padding-left:2em">GetCurrentDirectory</td> <td class="IconSuccessEncoded"></td> <td class="IconErrorEncoded"></td> <td class="IconSuccessEncoded"></td> <td class="IconErrorEncoded"></td> <td></td> </tr> <tr> <td>&nbsp;</td> <td>&nbsp;</td> <td>&nbsp;</td> <td>&nbsp;</td> <td>&nbsp;</td> <td>&nbsp;</td> </tr> <tr> <td>System.IO.StreamReader</td> <td class="IconErrorEncoded"></td> <td class="IconErrorEncoded"></td> <td class="IconSuccessEncoded"></td> <td class="IconErrorEncoded"></td> <td>Use File.OpenText, or use File.Open to get a Stream then pass it to StreamReader constructor</td> </tr> <tr> <td style="padding-left:2em">#ctor(System.String)</td> <td class="IconErrorEncoded"></td> <td class="IconErrorEncoded"></td> <td class="IconSuccessEncoded"></td> <td class="IconErrorEncoded"></td> <td>Use File.OpenText, or use File.Open to get a Stream then pass it to StreamReader constructor</td> </tr> <tr> <td>&nbsp;</td> <td>&nbsp;</td> <td>&nbsp;</td> <td>&nbsp;</td> <td>&nbsp;</td> <td>&nbsp;</td> </tr> <tr> <td>System.IO.StreamWriter</td> <td class="IconErrorEncoded"></td> <td class="IconErrorEncoded"></td> <td class="IconSuccessEncoded"></td> <td class="IconErrorEncoded"></td> <td>Use File.Open to get a Stream then pass it to StreamWriter constructor</td> </tr> <tr> <td style="padding-left:2em">#ctor(System.String)</td> <td class="IconErrorEncoded"></td> <td class="IconErrorEncoded"></td> <td class="IconSuccessEncoded"></td> <td class="IconErrorEncoded"></td> <td>Use File.Open to get a Stream then pass it to StreamWriter constructor</td> </tr> <tr> <td>&nbsp;</td> <td>&nbsp;</td> <td>&nbsp;</td> <td>&nbsp;</td> <td>&nbsp;</td> <td>&nbsp;</td> </tr> <tr> <td>System.Threading.Thread</td> <td class="IconSuccessEncoded"></td> <td class="IconErrorEncoded"></td> <td class="IconSuccessEncoded"></td> <td class="IconErrorEncoded"></td> <td></td> </tr> <tr> <td style="padding-left:2em">get_CurrentThread</td> <td class="IconSuccessEncoded"></td> <td class="IconErrorEncoded"></td> <td class="IconSuccessEncoded"></td> <td class="IconErrorEncoded"></td> <td></td> </tr> <tr> <td style="padding-left:2em">get_ManagedThreadId</td> <td class="IconSuccessEncoded"></td> <td class="IconErrorEncoded"></td> <td class="IconSuccessEncoded"></td> <td class="IconErrorEncoded"></td> <td></td> </tr> <tr> <td>&nbsp;</td> <td>&nbsp;</td> <td>&nbsp;</td> <td>&nbsp;</td> <td>&nbsp;</td> <td>&nbsp;</td> </tr> <tr> <td>System.Xml.XmlDocument</td> <td class="IconErrorEncoded"></td> <td class="IconErrorEncoded"></td> <td class="IconSuccessEncoded"></td> <td class="IconErrorEncoded"></td> <td>Use Load(System.IO.Stream) overload</td> </tr> <tr> <td style="padding-left:2em">#ctor</td> <td class="IconSuccessEncoded"></td> <td class="IconErrorEncoded"></td> <td class="IconSuccessEncoded"></td> <td class="IconErrorEncoded"></td> <td></td> </tr> <tr> <td style="padding-left:2em">Load(System.String)</td> <td class="IconErrorEncoded"></td> <td class="IconErrorEncoded"></td> <td class="IconSuccessEncoded"></td> <td class="IconErrorEncoded"></td> <td>Use Load(System.IO.Stream) overload</td> </tr> <tr> <td>&nbsp;</td> <td>&nbsp;</td> <td>&nbsp;</td> <td>&nbsp;</td> <td>&nbsp;</td> <td>&nbsp;</td> </tr> <tr> <td>System.Xml.XmlNode</td> <td class="IconSuccessEncoded"></td> <td class="IconErrorEncoded"></td> <td class="IconSuccessEncoded"></td> <td class="IconErrorEncoded"></td> <td></td> </tr> <tr> <td style="padding-left:2em">get_InnerText</td> <td class="IconSuccessEncoded"></td> <td class="IconErrorEncoded"></td> <td class="IconSuccessEncoded"></td> <td class="IconErrorEncoded"></td> <td></td> </tr> <tr> <td style="padding-left:2em">SelectNodes(System.String)</td> <td class="IconErrorEncoded"></td> <td class="IconErrorEncoded"></td> <td class="IconSuccessEncoded"></td> <td class="IconErrorEncoded"></td> <td></td> </tr> <tr> <td style="padding-left:2em">SelectSingleNode(System.String)</td> <td class="IconErrorEncoded"></td> <td class="IconErrorEncoded"></td> <td class="IconSuccessEncoded"></td> <td class="IconErrorEncoded"></td> <td>Create one of the XPathNavigator implementations. There are 3 implementations of the CreateNavigator () method in XPathDocument, System.Xml.XPath.XDocument, and System.Xml.XPath.XmlDocument, use this to find your node.</td> </tr> <tr> <td>&nbsp;</td> <td>&nbsp;</td> <td>&nbsp;</td> <td>&nbsp;</td> <td>&nbsp;</td> <td>&nbsp;</td> </tr> <tr> <td>System.Xml.XmlNodeList</td> <td class="IconSuccessEncoded"></td> <td class="IconErrorEncoded"></td> <td class="IconSuccessEncoded"></td> <td class="IconErrorEncoded"></td> <td></td> </tr> <tr> <td style="padding-left:2em">GetEnumerator</td> <td class="IconSuccessEncoded"></td> <td class="IconErrorEncoded"></td> <td class="IconSuccessEncoded"></td> <td class="IconErrorEncoded"></td> <td></td> </tr> <tr> <td>&nbsp;</td> <td>&nbsp;</td> <td>&nbsp;</td> <td>&nbsp;</td> <td>&nbsp;</td> <td>&nbsp;</td> </tr> </tbody> </table> <p> <a href="#Portability Summary">Back to Summary</a> </p> </div> </div> </body> </html>
{ "content_hash": "483798c2f5f9ea1a55e1ae74ba2cbbf6", "timestamp": "", "source": "github", "line_count": 677, "max_line_length": 562, "avg_line_length": 43.737075332348596, "alnum_prop": 0.40469436001350895, "repo_name": "kuhlenh/port-to-core", "id": "c800ad2341bf258675115f930db19541388d467c", "size": "29610", "binary": false, "copies": "1", "ref": "refs/heads/gh-pages", "path": "Reports/ia/iasl-biotextmining.namedentityrecognition.2.0.3.9/IASL.BioTextMining.NamedEntityIdentification-net40.html", "mode": "33188", "license": "mit", "language": [ { "name": "HTML", "bytes": "2323514650" } ], "symlink_target": "" }
A simple error package for node. ## Installation Install the package using npm: `npm install muses-error` ## Usage Load the module as usual: `var MuError = require('muses-error');` ### Basic Usage ``` var MuError = require('muses-error'); var error = new MuError('Some error', 500); var UserError = MuError.extend('UserError', 'default message', 400); var error = new UserError('nope', 403); error.name === 'UserError'; // true error.code === 403; // true error instanceof UserError; // true error instanceof MuError; // true error instanceof Error; // true ``` ## License See [LICENSE.md](LICENSE.md)
{ "content_hash": "d24154bfcd96820bf67d81f68fa939f1", "timestamp": "", "source": "github", "line_count": 30, "max_line_length": 68, "avg_line_length": 20.433333333333334, "alnum_prop": 0.6916802610114192, "repo_name": "Muses/error", "id": "6575243eab6c5300e2f8d03749a0032f106d7dcc", "size": "637", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "README.md", "mode": "33188", "license": "mit", "language": [ { "name": "JavaScript", "bytes": "4176" } ], "symlink_target": "" }
const {parse} = require('./parser') module.exports = {parse}
{ "content_hash": "a5d902cc41fcb22ef00405acc6b527ed", "timestamp": "", "source": "github", "line_count": 2, "max_line_length": 35, "avg_line_length": 30.5, "alnum_prop": 0.6721311475409836, "repo_name": "atom/atomdoc", "id": "7ff40f2911c6c41f92f8c70513d4de1d0527c916", "size": "61", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/atomdoc.js", "mode": "33188", "license": "mit", "language": [ { "name": "JavaScript", "bytes": "45215" } ], "symlink_target": "" }
package com.github.xsavikx.androidscreencast.ui.interaction; import com.github.xsavikx.androidscreencast.api.command.SwipeCommand; import com.github.xsavikx.androidscreencast.api.command.TapCommand; import com.github.xsavikx.androidscreencast.api.command.executor.CommandExecutor; import com.github.xsavikx.androidscreencast.api.command.factory.InputCommandFactory; import com.github.xsavikx.androidscreencast.api.injector.Injector; import com.github.xsavikx.androidscreencast.ui.JPanelScreen; import javax.inject.Inject; import javax.inject.Singleton; import javax.swing.*; import java.awt.*; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import java.awt.event.MouseWheelEvent; @Singleton public final class MouseActionAdapter extends MouseAdapter { private final static long ONE_SECOND = 1000L; private final JPanelScreen jp; private final CommandExecutor commandExecutor; private final InputCommandFactory inputCommandFactory; private final Injector injector; private int dragFromX = -1; private int dragFromY = -1; private long timeFromPress = -1; @Inject MouseActionAdapter(final JPanelScreen jp, final CommandExecutor commandExecutor, final InputCommandFactory inputCommandFactory, final Injector injector) { this.jp = jp; this.commandExecutor = commandExecutor; this.inputCommandFactory = inputCommandFactory; this.injector = injector; } @Override public void mouseClicked(final MouseEvent e) { if (injector != null && e.getButton() == MouseEvent.BUTTON3) { injector.toggleOrientation(); e.consume(); return; } final Point p2 = jp.getRawPoint(e.getPoint()); if (p2.x > 0 && p2.y > 0) { SwingUtilities.invokeLater(() -> { final TapCommand command = inputCommandFactory.getTapCommand(p2.x, p2.y); commandExecutor.execute(command); }); } } @Override public void mouseDragged(final MouseEvent e) { if (dragFromX == -1 && dragFromY == -1) { final Point p2 = jp.getRawPoint(e.getPoint()); dragFromX = p2.x; dragFromY = p2.y; timeFromPress = System.currentTimeMillis(); } } @Override public void mouseReleased(MouseEvent e) { if (timeFromPress >= ONE_SECOND) { final Point p2 = jp.getRawPoint(e.getPoint()); final int xFrom = dragFromX; final int yFrom = dragFromY; final int xTo = p2.x; final int yTo = p2.y; SwingUtilities.invokeLater(() -> { final SwipeCommand command = inputCommandFactory.getSwipeCommand(xFrom, yFrom, xTo, yTo, timeFromPress); commandExecutor.execute(command); }); clearState(); } } private void clearState() { dragFromX = -1; dragFromY = -1; timeFromPress = -1; } @Override public void mouseWheelMoved(final MouseWheelEvent arg0) { // if (JFrameMain.this.injector == null) // return; // JFrameMain.this.injector.injectTrackball(arg0.getWheelRotation() < 0 ? // -1f : 1f); } }
{ "content_hash": "249cd8b5b103e23238904777b9576d60", "timestamp": "", "source": "github", "line_count": 99, "max_line_length": 120, "avg_line_length": 33.676767676767675, "alnum_prop": 0.6394721055788842, "repo_name": "xSAVIKx/AndroidScreencast", "id": "68b271022af52eb6b6f0f31f9952ceb1d73b68d7", "size": "3936", "binary": false, "copies": "1", "ref": "refs/heads/develop", "path": "src/main/java/com/github/xsavikx/androidscreencast/ui/interaction/MouseActionAdapter.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "260906" } ], "symlink_target": "" }
@class NSArray, NSNumber, NSString, XCSDevice, XCSIntegration; @interface XCSTestObjectPlaceholder : NSObject <XCSPlaceholderProtocol> { XCSIntegration *_integration; XCSTestObjectPlaceholder *_parent; NSString *_name; NSArray *_children; long long _status; NSString *_keyPath; XCSDevice *_deviceFilter; NSNumber *_hasPerfMetricsCachedValue; } @property(retain, nonatomic) NSNumber *hasPerfMetricsCachedValue; // @synthesize hasPerfMetricsCachedValue=_hasPerfMetricsCachedValue; @property(retain, nonatomic) XCSDevice *deviceFilter; // @synthesize deviceFilter=_deviceFilter; @property(retain, nonatomic) NSString *keyPath; // @synthesize keyPath=_keyPath; @property(nonatomic) long long status; // @synthesize status=_status; @property(retain, nonatomic) NSArray *children; // @synthesize children=_children; @property(copy, nonatomic) NSString *name; // @synthesize name=_name; @property(retain, nonatomic) XCSTestObjectPlaceholder *parent; // @synthesize parent=_parent; @property(retain, nonatomic) XCSIntegration *integration; // @synthesize integration=_integration; - (void).cxx_destruct; - (BOOL)_validateWithIntegration:(id)arg1 name:(id)arg2 keyPath:(id)arg3 validationErrors:(id *)arg4; - (id)_statusInfoForKeyPath:(id)arg1; - (id)saveRepresentationHumanReadable:(BOOL)arg1; - (id)description; @property(readonly, nonatomic) BOOL hasPerfTests; @property(readonly, nonatomic) long long aggregatedStatus; - (double)statusValueForDeviceIdentifier:(id)arg1; - (long long)statusForDeviceIdentifier:(id)arg1; - (id)initWithIntegration:(id)arg1 name:(id)arg2 keyPath:(id)arg3 validationErrors:(id *)arg4; @end
{ "content_hash": "e199e5d7673503b91e8c7e41ed1b8edb", "timestamp": "", "source": "github", "line_count": 35, "max_line_length": 134, "avg_line_length": 47.142857142857146, "alnum_prop": 0.7751515151515151, "repo_name": "wczekalski/Distraction-Free-Xcode-plugin", "id": "440d548e5e0d3bfd09c3f0cc043f7fbd1322ae4f", "size": "1847", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "Archived/v1/WCDistractionFreeXcodePlugin/Headers/SharedFrameworks/XCSCore/XCSTestObjectPlaceholder.h", "mode": "33188", "license": "mit", "language": [ { "name": "C", "bytes": "81011" }, { "name": "C++", "bytes": "588495" }, { "name": "DTrace", "bytes": "1835" }, { "name": "Objective-C", "bytes": "10151940" }, { "name": "Ruby", "bytes": "1105" } ], "symlink_target": "" }
/* global -Promise */ var Promise = require('bluebird'); var auth = require('../auth'); var clients = require('../clients'); var Controller = require('../controller'); var repo = require('../repo'); module.exports = new Controller({ 'latest': { '0.1.0': { get: { authorize: auth.user, processing: function getLatest(req) { return repo.entry.findingLatest(req.app.repo).then(function (entry) { // ToDo: add ETag header with version return { entry: entry }; }); } } } }, ':id': { '0.1.0': { get: { authorize: auth.user, processing: function getById(req) { return repo.entry.findingById(req.app.repo, req.params.id); } }, patch: { // ToDo: auth.author?? authorize: auth.user, processing: function patchById(req) { // ToDo: move extraction of IF-Match header and req.body to server plugin // guided by the mime type var id = req.params.id; var version = parseInt(req.headers['if-match']); var patch = req.body; return repo.entry.patching(req.app.repo, id, version, patch) .then(function (result) { req.app.clients.notifyPatch({ path: req.url, fromVersion: version.toString(), patch: patch, toVersion: result.version.toString() }); return result; }); } } } } });
{ "content_hash": "e9faee26bb55307e87202a04fd57f681", "timestamp": "", "source": "github", "line_count": 57, "max_line_length": 93, "avg_line_length": 34.10526315789474, "alnum_prop": 0.40997942386831276, "repo_name": "larsthorup/mars", "id": "d0c0821c597632a46c73edb7bfcc879378b2a7a5", "size": "1944", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/controller/entry.js", "mode": "33188", "license": "mit", "language": [ { "name": "JavaScript", "bytes": "74117" }, { "name": "Shell", "bytes": "374" } ], "symlink_target": "" }
#include "modules/prediction/evaluator/vehicle/cruise_mlp_evaluator.h" #include <omp.h> #include <limits> #include <utility> #include "cyber/common/file.h" #include "modules/prediction/common/feature_output.h" #include "modules/prediction/common/prediction_constants.h" #include "modules/prediction/common/prediction_gflags.h" #include "modules/prediction/common/prediction_system_gflags.h" #include "modules/prediction/common/prediction_util.h" #include "modules/prediction/container/container_manager.h" #include "modules/prediction/container/obstacles/obstacles_container.h" namespace apollo { namespace prediction { using apollo::common::adapter::AdapterConfig; using apollo::cyber::common::GetProtoFromFile; using apollo::prediction::math_util::Sigmoid; // Helper function for computing the mean value of a vector. double ComputeMean(const std::vector<double>& nums, size_t start, size_t end) { int count = 0; double sum = 0.0; for (size_t i = start; i <= end && i < nums.size(); i++) { sum += nums[i]; ++count; } return (count == 0) ? 0.0 : sum / count; } CruiseMLPEvaluator::CruiseMLPEvaluator() : device_(torch::kCPU) { evaluator_type_ = ObstacleConf::CRUISE_MLP_EVALUATOR; LoadModels(); } void CruiseMLPEvaluator::Clear() {} bool CruiseMLPEvaluator::Evaluate(Obstacle* obstacle_ptr) { // Sanity checks. omp_set_num_threads(1); Clear(); CHECK_NOTNULL(obstacle_ptr); obstacle_ptr->SetEvaluatorType(evaluator_type_); int id = obstacle_ptr->id(); if (!obstacle_ptr->latest_feature().IsInitialized()) { AERROR << "Obstacle [" << id << "] has no latest feature."; return false; } Feature* latest_feature_ptr = obstacle_ptr->mutable_latest_feature(); CHECK_NOTNULL(latest_feature_ptr); if (!latest_feature_ptr->has_lane() || !latest_feature_ptr->lane().has_lane_graph()) { ADEBUG << "Obstacle [" << id << "] has no lane graph."; return false; } LaneGraph* lane_graph_ptr = latest_feature_ptr->mutable_lane()->mutable_lane_graph(); CHECK_NOTNULL(lane_graph_ptr); if (lane_graph_ptr->lane_sequence_size() == 0) { AERROR << "Obstacle [" << id << "] has no lane sequences."; return false; } ADEBUG << "There are " << lane_graph_ptr->lane_sequence_size() << " lane sequences with probabilities:"; // For every possible lane sequence, extract features that are needed // to feed into our trained model. // Then compute the likelihood of the obstacle moving onto that laneseq. for (int i = 0; i < lane_graph_ptr->lane_sequence_size(); ++i) { LaneSequence* lane_sequence_ptr = lane_graph_ptr->mutable_lane_sequence(i); CHECK_NOTNULL(lane_sequence_ptr); std::vector<double> feature_values; ExtractFeatureValues(obstacle_ptr, lane_sequence_ptr, &feature_values); if (feature_values.size() != OBSTACLE_FEATURE_SIZE + SINGLE_LANE_FEATURE_SIZE * LANE_POINTS_SIZE) { lane_sequence_ptr->set_probability(0.0); ADEBUG << "Skip lane sequence due to incorrect feature size"; continue; } // Insert features to DataForLearning if (FLAGS_prediction_offline_mode == PredictionConstants::kDumpDataForLearning) { std::vector<double> interaction_feature_values; SetInteractionFeatureValues(obstacle_ptr, lane_sequence_ptr, &interaction_feature_values); if (interaction_feature_values.size() != INTERACTION_FEATURE_SIZE) { ADEBUG << "Obstacle [" << id << "] has fewer than " << "expected lane feature_values" << interaction_feature_values.size() << "."; return false; } ADEBUG << "Interaction feature size = " << interaction_feature_values.size(); feature_values.insert(feature_values.end(), interaction_feature_values.begin(), interaction_feature_values.end()); FeatureOutput::InsertDataForLearning(*latest_feature_ptr, feature_values, "lane_scanning", lane_sequence_ptr); ADEBUG << "Save extracted features for learning locally."; return true; // Skip Compute probability for offline mode } std::vector<torch::jit::IValue> torch_inputs; int input_dim = static_cast<int>( OBSTACLE_FEATURE_SIZE + SINGLE_LANE_FEATURE_SIZE * LANE_POINTS_SIZE); torch::Tensor torch_input = torch::zeros({1, input_dim}); for (size_t i = 0; i < feature_values.size(); ++i) { torch_input[0][i] = static_cast<float>(feature_values[i]); } torch_inputs.push_back(std::move(torch_input.to(device_))); if (lane_sequence_ptr->vehicle_on_lane()) { ModelInference(torch_inputs, torch_go_model_, lane_sequence_ptr); } else { ModelInference(torch_inputs, torch_cutin_model_, lane_sequence_ptr); } } return true; } void CruiseMLPEvaluator::ExtractFeatureValues( Obstacle* obstacle_ptr, LaneSequence* lane_sequence_ptr, std::vector<double>* feature_values) { // Sanity checks. CHECK_NOTNULL(obstacle_ptr); CHECK_NOTNULL(lane_sequence_ptr); int id = obstacle_ptr->id(); // Extract obstacle related features. std::vector<double> obstacle_feature_values; SetObstacleFeatureValues(obstacle_ptr, &obstacle_feature_values); if (obstacle_feature_values.size() != OBSTACLE_FEATURE_SIZE) { ADEBUG << "Obstacle [" << id << "] has fewer than " << "expected obstacle feature_values " << obstacle_feature_values.size() << "."; return; } ADEBUG << "Obstacle feature size = " << obstacle_feature_values.size(); feature_values->insert(feature_values->end(), obstacle_feature_values.begin(), obstacle_feature_values.end()); // Extract lane related features. std::vector<double> lane_feature_values; SetLaneFeatureValues(obstacle_ptr, lane_sequence_ptr, &lane_feature_values); if (lane_feature_values.size() != SINGLE_LANE_FEATURE_SIZE * LANE_POINTS_SIZE) { ADEBUG << "Obstacle [" << id << "] has fewer than " << "expected lane feature_values" << lane_feature_values.size() << "."; return; } ADEBUG << "Lane feature size = " << lane_feature_values.size(); feature_values->insert(feature_values->end(), lane_feature_values.begin(), lane_feature_values.end()); } void CruiseMLPEvaluator::SetObstacleFeatureValues( const Obstacle* obstacle_ptr, std::vector<double>* feature_values) { // Sanity checks and variable declarations. CHECK_NOTNULL(obstacle_ptr); feature_values->clear(); feature_values->reserve(OBSTACLE_FEATURE_SIZE); std::vector<double> thetas; std::vector<double> lane_ls; std::vector<double> dist_lbs; std::vector<double> dist_rbs; std::vector<int> lane_types; std::vector<double> speeds; std::vector<double> timestamps; std::vector<double> has_history(FLAGS_cruise_historical_frame_length, 1.0); std::vector<std::pair<double, double>> pos_history( FLAGS_cruise_historical_frame_length, std::make_pair(0.0, 0.0)); std::vector<std::pair<double, double>> vel_history( FLAGS_cruise_historical_frame_length, std::make_pair(0.0, 0.0)); std::vector<std::pair<double, double>> acc_history( FLAGS_cruise_historical_frame_length, std::make_pair(0.0, 0.0)); std::vector<double> vel_heading_history(FLAGS_cruise_historical_frame_length, 0.0); std::vector<double> vel_heading_changing_rate_history( FLAGS_cruise_historical_frame_length, 0.0); // Get obstacle's current position to set up the relative coord. system. const Feature& obs_curr_feature = obstacle_ptr->latest_feature(); double obs_curr_heading = obs_curr_feature.velocity_heading(); std::pair<double, double> obs_curr_pos = std::make_pair( obs_curr_feature.position().x(), obs_curr_feature.position().y()); double obs_feature_history_start_time = obstacle_ptr->timestamp() - FLAGS_prediction_trajectory_time_length; int count = 0; // int num_available_history_frames = 0; double prev_timestamp = obs_curr_feature.timestamp(); // Starting from the most recent timestamp and going backward. ADEBUG << "Obstacle has " << obstacle_ptr->history_size() << " history timestamps."; for (std::size_t i = 0; i < obstacle_ptr->history_size(); ++i) { const Feature& feature = obstacle_ptr->feature(i); if (!feature.IsInitialized()) { continue; } if (feature.timestamp() < obs_feature_history_start_time) { break; } if (!feature.has_lane()) { ADEBUG << "Feature has no lane. Quit."; } // These are for the old 23 features. if (feature.has_lane() && feature.lane().has_lane_feature()) { thetas.push_back(feature.lane().lane_feature().angle_diff()); lane_ls.push_back(feature.lane().lane_feature().lane_l()); dist_lbs.push_back(feature.lane().lane_feature().dist_to_left_boundary()); dist_rbs.push_back( feature.lane().lane_feature().dist_to_right_boundary()); lane_types.push_back(feature.lane().lane_feature().lane_turn_type()); timestamps.push_back(feature.timestamp()); speeds.push_back(feature.speed()); ++count; } else { ADEBUG << "Feature has no lane_feature!!!"; ADEBUG << feature.lane().current_lane_feature_size(); } // These are for the new features based on the relative coord. system. if (i >= FLAGS_cruise_historical_frame_length) { continue; } if (i != 0 && has_history[i - 1] == 0.0) { has_history[i] = 0.0; continue; } if (feature.has_position()) { pos_history[i] = WorldCoordToObjCoord( std::make_pair(feature.position().x(), feature.position().y()), obs_curr_pos, obs_curr_heading); } else { has_history[i] = 0.0; } if (feature.has_velocity()) { auto vel_end = WorldCoordToObjCoord( std::make_pair(feature.velocity().x(), feature.velocity().y()), obs_curr_pos, obs_curr_heading); auto vel_begin = WorldCoordToObjCoord(std::make_pair(0.0, 0.0), obs_curr_pos, obs_curr_heading); vel_history[i] = std::make_pair(vel_end.first - vel_begin.first, vel_end.second - vel_begin.second); } else { has_history[i] = 0.0; } if (feature.has_acceleration()) { auto acc_end = WorldCoordToObjCoord(std::make_pair(feature.acceleration().x(), feature.acceleration().y()), obs_curr_pos, obs_curr_heading); auto acc_begin = WorldCoordToObjCoord(std::make_pair(0.0, 0.0), obs_curr_pos, obs_curr_heading); acc_history[i] = std::make_pair(acc_end.first - acc_begin.first, acc_end.second - acc_begin.second); } else { has_history[i] = 0.0; } if (feature.has_velocity_heading()) { vel_heading_history[i] = WorldAngleToObjAngle(feature.velocity_heading(), obs_curr_heading); if (i != 0) { vel_heading_changing_rate_history[i] = (vel_heading_history[i - 1] - vel_heading_history[i]) / (FLAGS_double_precision + feature.timestamp() - prev_timestamp); prev_timestamp = feature.timestamp(); } } else { has_history[i] = 0.0; } } if (count <= 0) { ADEBUG << "There is no feature with lane info. Quit."; return; } // The following entire part is setting up the old 23 features. /////////////////////////////////////////////////////////////// int curr_size = 5; int hist_size = static_cast<int>(obstacle_ptr->history_size()); double theta_mean = ComputeMean(thetas, 0, hist_size - 1); double theta_filtered = ComputeMean(thetas, 0, curr_size - 1); double lane_l_mean = ComputeMean(lane_ls, 0, hist_size - 1); double lane_l_filtered = ComputeMean(lane_ls, 0, curr_size - 1); double speed_mean = ComputeMean(speeds, 0, hist_size - 1); double time_diff = timestamps.front() - timestamps.back(); double dist_lb_rate = (timestamps.size() > 1) ? (dist_lbs.front() - dist_lbs.back()) / time_diff : 0.0; double dist_rb_rate = (timestamps.size() > 1) ? (dist_rbs.front() - dist_rbs.back()) / time_diff : 0.0; double delta_t = 0.0; if (timestamps.size() > 1) { delta_t = (timestamps.front() - timestamps.back()) / static_cast<double>(timestamps.size() - 1); } double angle_curr = ComputeMean(thetas, 0, curr_size - 1); double angle_prev = ComputeMean(thetas, curr_size, 2 * curr_size - 1); double angle_diff = (hist_size >= 2 * curr_size) ? angle_curr - angle_prev : 0.0; double lane_l_curr = ComputeMean(lane_ls, 0, curr_size - 1); double lane_l_prev = ComputeMean(lane_ls, curr_size, 2 * curr_size - 1); double lane_l_diff = (hist_size >= 2 * curr_size) ? lane_l_curr - lane_l_prev : 0.0; double angle_diff_rate = 0.0; double lane_l_diff_rate = 0.0; if (delta_t > std::numeric_limits<double>::epsilon()) { angle_diff_rate = angle_diff / (delta_t * curr_size); lane_l_diff_rate = lane_l_diff / (delta_t * curr_size); } double acc = 0.0; double jerk = 0.0; if (static_cast<int>(speeds.size()) >= 3 * curr_size && delta_t > std::numeric_limits<double>::epsilon()) { double speed_1st_recent = ComputeMean(speeds, 0, curr_size - 1); double speed_2nd_recent = ComputeMean(speeds, curr_size, 2 * curr_size - 1); double speed_3rd_recent = ComputeMean(speeds, 2 * curr_size, 3 * curr_size - 1); acc = (speed_1st_recent - speed_2nd_recent) / (curr_size * delta_t); jerk = (speed_1st_recent - 2 * speed_2nd_recent + speed_3rd_recent) / (curr_size * curr_size * delta_t * delta_t); } double dist_lb_rate_curr = 0.0; if (hist_size >= 2 * curr_size && delta_t > std::numeric_limits<double>::epsilon()) { double dist_lb_curr = ComputeMean(dist_lbs, 0, curr_size - 1); double dist_lb_prev = ComputeMean(dist_lbs, curr_size, 2 * curr_size - 1); dist_lb_rate_curr = (dist_lb_curr - dist_lb_prev) / (curr_size * delta_t); } double dist_rb_rate_curr = 0.0; if (hist_size >= 2 * curr_size && delta_t > std::numeric_limits<double>::epsilon()) { double dist_rb_curr = ComputeMean(dist_rbs, 0, curr_size - 1); double dist_rb_prev = ComputeMean(dist_rbs, curr_size, 2 * curr_size - 1); dist_rb_rate_curr = (dist_rb_curr - dist_rb_prev) / (curr_size * delta_t); } feature_values->push_back(theta_filtered); feature_values->push_back(theta_mean); feature_values->push_back(theta_filtered - theta_mean); feature_values->push_back(angle_diff); feature_values->push_back(angle_diff_rate); feature_values->push_back(lane_l_filtered); feature_values->push_back(lane_l_mean); feature_values->push_back(lane_l_filtered - lane_l_mean); feature_values->push_back(lane_l_diff); feature_values->push_back(lane_l_diff_rate); feature_values->push_back(speed_mean); feature_values->push_back(acc); feature_values->push_back(jerk); feature_values->push_back(dist_lbs.front()); feature_values->push_back(dist_lb_rate); feature_values->push_back(dist_lb_rate_curr); feature_values->push_back(dist_rbs.front()); feature_values->push_back(dist_rb_rate); feature_values->push_back(dist_rb_rate_curr); feature_values->push_back(lane_types.front() == 0 ? 1.0 : 0.0); feature_values->push_back(lane_types.front() == 1 ? 1.0 : 0.0); feature_values->push_back(lane_types.front() == 2 ? 1.0 : 0.0); feature_values->push_back(lane_types.front() == 3 ? 1.0 : 0.0); for (std::size_t i = 0; i < FLAGS_cruise_historical_frame_length; i++) { feature_values->push_back(has_history[i]); feature_values->push_back(pos_history[i].first); feature_values->push_back(pos_history[i].second); feature_values->push_back(vel_history[i].first); feature_values->push_back(vel_history[i].second); feature_values->push_back(acc_history[i].first); feature_values->push_back(acc_history[i].second); feature_values->push_back(vel_heading_history[i]); feature_values->push_back(vel_heading_changing_rate_history[i]); } } void CruiseMLPEvaluator::SetInteractionFeatureValues( Obstacle* obstacle_ptr, LaneSequence* lane_sequence_ptr, std::vector<double>* feature_values) { // forward / backward: relative_s, relative_l, speed, length feature_values->clear(); // Initialize forward and backward obstacles NearbyObstacle forward_obstacle; NearbyObstacle backward_obstacle; forward_obstacle.set_s(FLAGS_default_s_if_no_obstacle_in_lane_sequence); forward_obstacle.set_l(FLAGS_default_l_if_no_obstacle_in_lane_sequence); backward_obstacle.set_s(-FLAGS_default_s_if_no_obstacle_in_lane_sequence); backward_obstacle.set_l(FLAGS_default_l_if_no_obstacle_in_lane_sequence); for (const auto& nearby_obstacle : lane_sequence_ptr->nearby_obstacle()) { if (nearby_obstacle.s() < 0.0) { if (nearby_obstacle.s() > backward_obstacle.s()) { backward_obstacle.set_id(nearby_obstacle.id()); backward_obstacle.set_s(nearby_obstacle.s()); backward_obstacle.set_l(nearby_obstacle.l()); } } else { if (nearby_obstacle.s() < forward_obstacle.s()) { forward_obstacle.set_id(nearby_obstacle.id()); forward_obstacle.set_s(nearby_obstacle.s()); forward_obstacle.set_l(nearby_obstacle.l()); } } } auto obstacles_container = ContainerManager::Instance()->GetContainer<ObstaclesContainer>( AdapterConfig::PERCEPTION_OBSTACLES); // Set feature values for forward obstacle feature_values->push_back(forward_obstacle.s()); feature_values->push_back(forward_obstacle.l()); if (!forward_obstacle.has_id()) { // no forward obstacle feature_values->push_back(0.0); feature_values->push_back(0.0); } else { Obstacle* forward_obs_ptr = obstacles_container->GetObstacle(forward_obstacle.id()); const Feature& feature = forward_obs_ptr->latest_feature(); feature_values->push_back(feature.length()); feature_values->push_back(feature.speed()); } // Set feature values for backward obstacle feature_values->push_back(backward_obstacle.s()); feature_values->push_back(backward_obstacle.l()); if (!backward_obstacle.has_id()) { // no forward obstacle feature_values->push_back(0.0); feature_values->push_back(0.0); } else { Obstacle* backward_obs_ptr = obstacles_container->GetObstacle(backward_obstacle.id()); const Feature& feature = backward_obs_ptr->latest_feature(); feature_values->push_back(feature.length()); feature_values->push_back(feature.speed()); } } void CruiseMLPEvaluator::SetLaneFeatureValues( const Obstacle* obstacle_ptr, const LaneSequence* lane_sequence_ptr, std::vector<double>* feature_values) { // Sanity checks. feature_values->clear(); feature_values->reserve(SINGLE_LANE_FEATURE_SIZE * LANE_POINTS_SIZE); const Feature& feature = obstacle_ptr->latest_feature(); if (!feature.IsInitialized()) { ADEBUG << "Obstacle [" << obstacle_ptr->id() << "] has no latest feature."; return; } else if (!feature.has_position()) { ADEBUG << "Obstacle [" << obstacle_ptr->id() << "] has no position."; return; } double heading = feature.velocity_heading(); for (int i = 0; i < lane_sequence_ptr->lane_segment_size(); ++i) { if (feature_values->size() >= SINGLE_LANE_FEATURE_SIZE * LANE_POINTS_SIZE) { break; } const LaneSegment& lane_segment = lane_sequence_ptr->lane_segment(i); for (int j = 0; j < lane_segment.lane_point_size(); ++j) { if (feature_values->size() >= SINGLE_LANE_FEATURE_SIZE * LANE_POINTS_SIZE) { break; } const LanePoint& lane_point = lane_segment.lane_point(j); if (!lane_point.has_position()) { AERROR << "Lane point has no position."; continue; } std::pair<double, double> relative_s_l = WorldCoordToObjCoord( std::make_pair(lane_point.position().x(), lane_point.position().y()), std::make_pair(feature.position().x(), feature.position().y()), heading); double relative_ang = WorldAngleToObjAngle(lane_point.heading(), heading); feature_values->push_back(relative_s_l.second); feature_values->push_back(relative_s_l.first); feature_values->push_back(relative_ang); feature_values->push_back(lane_point.kappa()); } } // If the lane points are not sufficient, apply a linear extrapolation. std::size_t size = feature_values->size(); while (size >= 10 && size < SINGLE_LANE_FEATURE_SIZE * LANE_POINTS_SIZE) { double relative_l_new = 2 * feature_values->operator[](size - 5) - feature_values->operator[](size - 10); double relative_s_new = 2 * feature_values->operator[](size - 4) - feature_values->operator[](size - 9); double relative_ang_new = feature_values->operator[](size - 3); feature_values->push_back(relative_l_new); feature_values->push_back(relative_s_new); feature_values->push_back(relative_ang_new); feature_values->push_back(0.0); size = feature_values->size(); } } void CruiseMLPEvaluator::LoadModels() { if (FLAGS_use_cuda && torch::cuda::is_available()) { ADEBUG << "CUDA is available"; device_ = torch::Device(torch::kCUDA); } torch::set_num_threads(1); torch_go_model_ = torch::jit::load(FLAGS_torch_vehicle_cruise_go_file, device_); torch_cutin_model_ = torch::jit::load(FLAGS_torch_vehicle_cruise_cutin_file, device_); } void CruiseMLPEvaluator::ModelInference( const std::vector<torch::jit::IValue>& torch_inputs, torch::jit::script::Module torch_model_ptr, LaneSequence* lane_sequence_ptr) { auto torch_output_tuple = torch_model_ptr.forward(torch_inputs).toTuple(); auto probability_tensor = torch_output_tuple->elements()[0].toTensor().to(torch::kCPU); auto finish_time_tensor = torch_output_tuple->elements()[1].toTensor().to(torch::kCPU); lane_sequence_ptr->set_probability(Sigmoid( static_cast<double>(probability_tensor.accessor<float, 2>()[0][0]))); lane_sequence_ptr->set_time_to_lane_center( static_cast<double>(finish_time_tensor.accessor<float, 2>()[0][0])); } } // namespace prediction } // namespace apollo
{ "content_hash": "69690db6c60278fb9120ceaa785e5b29", "timestamp": "", "source": "github", "line_count": 550, "max_line_length": 80, "avg_line_length": 41.07272727272727, "alnum_prop": 0.6395307658255865, "repo_name": "wanglei828/apollo", "id": "da71b7ca3bd562b34540ed9f39d034ee988de55b", "size": "23362", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "modules/prediction/evaluator/vehicle/cruise_mlp_evaluator.cc", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Assembly", "bytes": "1922" }, { "name": "Batchfile", "bytes": "791" }, { "name": "C", "bytes": "22662" }, { "name": "C++", "bytes": "17378263" }, { "name": "CMake", "bytes": "3600" }, { "name": "CSS", "bytes": "40785" }, { "name": "Cuda", "bytes": "97324" }, { "name": "Dockerfile", "bytes": "11960" }, { "name": "GLSL", "bytes": "7000" }, { "name": "HTML", "bytes": "21068" }, { "name": "JavaScript", "bytes": "364183" }, { "name": "Makefile", "bytes": "6626" }, { "name": "Python", "bytes": "1902086" }, { "name": "Shell", "bytes": "302902" }, { "name": "Smarty", "bytes": "33258" } ], "symlink_target": "" }
#region Using Directives using System; using System.Collections.Generic; #endregion /* * $author: QmQ * $source: http://www.codeproject.com/useritems/SimpleStringTokenizer.asp * $date: 10-June-2006 */ namespace PetShop.Data { #region [Summary and remarks] /// <summary> /// Implements a StringTokenizer class for splitting a string /// into substrings using a set of delimiters. /// </summary> /// <remarks> /// C# version of the java.util.StringTokenizer class. /// Basicly it's a wrapper class around the <c>String.Split</c> method.<pare/> /// It implements all of it's Java equivalent methods apart from those only needed by the Enumeration interface. /// All implemented Java-compilant methods have their C# equivalents in properties. They however differ in names /// since Java uses the (Hungarian-like) notation <c>runMe()</c> while C# uses Camel-cased <c>RunMe()</c> and thus /// Java's <c>nextToken()</c> method is just an alias of the <c>NextToken</c> property. /// </remarks> #endregion public class StringTokenizer : IEnumerable<string> { /// <summary> /// String conatining the default set of delimiters which are <c>" \t\n\r\f"</c>: /// the space character, the tab character, the newline character, the carriage-return character, and the form-feed character. /// </summary> public const string DefaultDelimiters = " \t\n\r\f"; private readonly string delims = DefaultDelimiters; private string[] tokens = null; private int index = 0; private string empty = String.Empty; #region [Constructors] /// <summary> /// Constructs a string tokenizer for the specified string using the <see cref="F:DefaultDelimiters">default delimiters</see>. /// </summary> /// <param name="str">The string to be tokenized.</param> /// <exception cref="System.NullReferenceException">Thrown when the passed string is <c>null</c></exception> public StringTokenizer(string str) { Tokenize(str, false, false); } /// <summary> /// Constructs a string tokenizer for the specified string using the given delimiters. /// </summary> /// <param name="str">The string to be tokenized.</param> /// <param name="delims">The delimiters used to tokenize the string (each <see cref="!:char"/> will be used as a delimiter).</param> /// <exception cref="System.NullReferenceException">Thrown when the passed string is <c>null</c></exception> public StringTokenizer(string str, string delims) { if(delims!=null) this.delims = delims; Tokenize(str, false, false); } /// <summary> /// Constructs a string tokenizer for the specified string using the given delimiters. /// </summary> /// <param name="str">The string to be tokenized.</param> /// <param name="delims">The delimiters used to tokenize the string.</param> public StringTokenizer(string str, params char[] delims) { if (delims != null) this.delims = new string(delims); Tokenize(str, false, false); } /// <summary> /// Constructs a string tokenizer for the specified string using the given delimiters and optionally returning them as tokens. /// </summary> /// <param name="str">The string to be tokenized.</param> /// <param name="delims">The delimiters used to tokenize the string (each <see cref="!:char"/> will be used as a delimiter).</param> /// <param name="returnDelims">If set to <c>true</c> the encountered delimiters will also be returned as tokens.</param> /// <exception cref="System.NullReferenceException">Thrown when the passed string is <c>null</c></exception> public StringTokenizer(string str, string delims, bool returnDelims) { if (delims != null) this.delims = delims; Tokenize(str, returnDelims, false); } /// <summary> /// Constructs a string tokenizer for the specified string using the given delimiters, /// optionally returning them as tokens. Also empty tokens may be returned using the <see cref="!:String.Empty"/> string. /// </summary> /// <param name="str">The string to be tokenized.</param> /// <param name="delims">The delimiters used to tokenize the string (each <see cref="!:char"/> will be used as a delimiter).</param> /// <param name="returnDelims">If set to <c>true</c> the encountered delimiters will also be returned as tokens.</param> /// <param name="returnEmpty">If set to <c>true</c> empty tokens will also be returned.</param> /// <exception cref="System.NullReferenceException">Thrown when the passed string is <c>null</c></exception> public StringTokenizer(string str, string delims, bool returnDelims, bool returnEmpty) { if (delims != null) this.delims = delims; Tokenize(str, returnDelims, returnEmpty); } /// <summary> /// Constructs a string tokenizer for the specified string using the given delimiters, /// optionally returning them as tokens. Also empty tokens may be returned using the <paramref name="empty"/> string. /// </summary> /// <param name="str">The string to be tokenized.</param> /// <param name="delims">The delimiters used to tokenize the string (each <see cref="!:char"/> will be used as a delimiter).</param> /// <param name="returnDelims">If set to <c>true</c> the encountered delimiters will also be returned as tokens.</param> /// <param name="returnEmpty">If set to <c>true</c> empty tokens will also be returned.</param> /// <param name="empty">The string to be returned as an empty token.</param> /// <exception cref="System.NullReferenceException">Thrown when the passed string is <c>null</c></exception> public StringTokenizer(string str, string delims, bool returnDelims, bool returnEmpty, string empty) { if (delims != null) this.delims = delims; this.empty = empty; Tokenize(str, returnDelims, returnEmpty); } #endregion #region [The big tokenization method] private void Tokenize(string str, bool returnDelims, bool returnEmpty) { if(returnDelims) { this.tokens = str.Split(this.delims.ToCharArray(), StringSplitOptions.RemoveEmptyEntries); List<string> tmp = new List<string>(tokens.Length << 1); int delimIndex = str.IndexOfAny(this.delims.ToCharArray()); int tokensIndex = 0; int prevDelimIdx = delimIndex-1; if (delimIndex == 0) do { tmp.Add(new string(str[delimIndex], 1)); prevDelimIdx = delimIndex++; delimIndex = str.IndexOfAny(this.delims.ToCharArray(), delimIndex); if (returnEmpty && delimIndex == prevDelimIdx + 1) tmp.Add(this.empty); } while (delimIndex == prevDelimIdx + 1); while (delimIndex > -1) { tmp.Add(this.tokens[tokensIndex++]); do { tmp.Add(new string(str[delimIndex], 1)); prevDelimIdx = delimIndex++; delimIndex = str.IndexOfAny(this.delims.ToCharArray(), delimIndex); if (returnEmpty && delimIndex == prevDelimIdx + 1) tmp.Add(this.empty); } while (delimIndex == prevDelimIdx + 1); } if (tokensIndex < tokens.Length) tmp.Add(this.tokens[tokensIndex++]); this.tokens = tmp.ToArray(); tmp = null; } else if (returnEmpty) { this.tokens = str.Split(this.delims.ToCharArray(), StringSplitOptions.None); if (this.empty != String.Empty) for(int i=0; i<this.tokens.Length; i++) if (this.tokens[i] == String.Empty) this.tokens[i] = this.empty; } else this.tokens = str.Split(this.delims.ToCharArray(), StringSplitOptions.RemoveEmptyEntries); } #endregion #region [Properties covering Java methods] /// <summary> /// Tests if there are more tokens available from this tokenizer's string. /// If this method returns <c>true</c>, then a subsequent /// use of the <see cref="P:NextToken"/> property will successfully return a token. /// </summary> /// <value> /// <c>true</c> if more tokens are available; otherwise <c>false</c>. /// </value> public bool HasMoreTokens { get { return this.index < this.tokens.Length; } } /// <summary> /// Gets the next token. /// </summary> /// <value>The next token.</value> /// <exception cref="System.IndexOutOfRangeException">Thrown when trying to get a token which doesn't exist. /// Usually caused by not checking if the <see cref="P:HasMoreTokens"/> property returns <c>true</c> before trying to get the next token.</exception> public string NextToken { get { return this.tokens[index++]; } } /// <summary> /// Counts the <see cref="!:remaining"/> tokens - the number of times the /// <see cref="P:NextToken"/> property can be used before it throws an exception. /// </summary> /// <value>The number of remaining tokens.</value> /// <seealso cref="P:Count"/> public int CountTokens { get { return this.tokens.Length - this.index; } } #endregion #region [New methods/properties] /// <summary> /// Gets the total number of tokens extracted. /// </summary> /// <remarks> /// <see cref="!:Equivalent not available in Java!"/> /// This property returns the total number of extracted tokens, /// contrary to <see cref="P:CountTokens"/>. /// </remarks> /// <value>The number of tokens extracted.</value> /// <seealso cref="P:StringTokenizer.CountTokens"/> public int Count { get { return this.tokens.Length; } } /// <summary> /// Gets the token with the specified index from the tokenizer without moving the current position index. /// </summary> /// <remarks><see cref="!:Equivalent not available in Java!"/></remarks> /// <param name="index">The index of the token to get.</param> /// <value>The token with the given index</value> /// <exception cref="System.IndexOutOfRangeException">Thrown when trying to get a token which doesn't exist, that is when <see cref="!:index"/> is equal or greater then <see cref="!:Count"/> or <see cref="!:index"/> is negative.</exception> public string this[int index] { get { return this.tokens[index]; } } /// <summary> /// Resets the current position index so that the tokens can be extracted again. /// </summary> /// <remarks><see cref="!:Equivalent not available in Java!"/></remarks> public void Reset() { this.index = 0; } /// <summary> /// Gets the currently set string for empty tokens. /// </summary> /// <remarks>Default is <c>System.String.Empty</c></remarks> /// <value>The empty token string.</value> public string EmptyString { get { return this.empty; } } #endregion #region [Java-compilant methods] /* /// <summary> /// Tests if there are more tokens available from this tokenizer's string. /// If this method returns <c>true</c>, then a subsequent call to <see cref="M:nextToken"/> will successfully return a token. /// </summary> /// <returns> /// <c>true</c> if and only if there is at least one token in the string after the current position; otherwise <c>false</c>. /// </returns> /// <seealso cref="M:nextToken"/> public bool hasMoreTokens() { return HasMoreTokens; } /// <summary> /// Returns the next token from this string tokenizer. /// </summary> /// <returns>The next token from this string tokenizer.</returns> public string nextToken() { return NextToken; } /// <summary> /// Calculates the number of times that this tokenizer's <see cref="M:nextToken"/> method can be called before it generates an exception. The current position is not advanced. /// </summary> /// <returns>The number of tokens remaining in the string using the current delimiter set.</returns> public int countTokens() { return CountTokens; } */ #endregion #region [IEnumerable implementation] /// <summary> /// Returns an enumerator that iterates through the collection. /// </summary> /// <returns> /// A <see cref="T:System.Collections.Generic.IEnumerator"/> that can be used to iterate through the collection. /// </returns> public IEnumerator<string> GetEnumerator() { while (this.HasMoreTokens) yield return this.NextToken; } System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { return GetEnumerator(); } #endregion } }
{ "content_hash": "7049e03b2d2f520e62c82ac7781759b5", "timestamp": "", "source": "github", "line_count": 315, "max_line_length": 248, "avg_line_length": 45.5015873015873, "alnum_prop": 0.5730830949556966, "repo_name": "netTiers/netTiers", "id": "cb8a1fc31fc892982f825e4f7dd70b660a659254", "size": "14335", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "Samples/Petshop/Source/PetShop.Data/Query/StringTokenizer.cs", "mode": "33188", "license": "mit", "language": [ { "name": "ASP.NET", "bytes": "620" }, { "name": "C#", "bytes": "336934" }, { "name": "CSS", "bytes": "9299" }, { "name": "JavaScript", "bytes": "18312" }, { "name": "XSLT", "bytes": "26775" } ], "symlink_target": "" }
The core plugins for the [Catdown](https://github.com/zuren/catdown) Markdown editor. Included by default. ### Events EventEmitter extracted from CodeMirror and extended. Now allows multiple event names and is manually bound to Catdown instance. #### Usage ```js // Add a handler to an event editor.on("render", handler); // Add a handler to multiple events editor.on("ready change", handler); // Signal an event with some args, calling any handlers listening to it. editor.signal("something", 1, 2, 3); ``` ### Render Accepts a `preview` DOM element or jQuery object. On editor `ready` and `change` events, converts editor value to HTML using the Catdown `parser` and displays it in the preview. ### Keys Key handling functionality. Accepts a hash of key combinations and handlers and binds to CodeMirror instance. Unlike CodeMirror's `editor.setOption("extraKeys", hash);`, it extends the existing keymap rather than replacing it. The syntax is identical though. #### Usage ```js editor.keys({ "Ctrl-Shift-Up": function(){ // add your functionality } }); ``` #### Default keymap * `Ctrl-B` - Bold * `Ctrl-I` - Italics * `Ctrl-Alt-U` - Strikethrough * `Ctrl-K` - Inline code * `Ctrl-L` - List * `Ctrl-Q` - Blockquote * `Shift-Ctrl-L` - Insert link * `Shift-Ctrl-I` - Insert image ### Controls Adds some additional CodeMirror functionality to Catdown. `moveCursorX`, `moveCursorY` and `wrapSelection` are available in `editor.controls`. #### `moveCursorX(int)` Move cursor horizontally. Positive number goes right, negative goes left. ```js // Move three spaces back editor.controls.moveCursorX(-3); ``` #### `moveCursorY(int)` Move cursor vertically. Positive number goes down, negative goes up. ```js // Move two lines down editor.controls.moveCursorY(2); ``` #### wrapSelections(leftStr, rightStr) Wrap current selections between two strings. `rightStr` is empty by default so not required. ```js // Make the current selections bold editor.controls.wrapSelection("**", "**"); ```
{ "content_hash": "d8900193eec73b4150a76c664200ba98", "timestamp": "", "source": "github", "line_count": 78, "max_line_length": 258, "avg_line_length": 25.78205128205128, "alnum_prop": 0.720537046245649, "repo_name": "zuren/catdown-core", "id": "cd318314d253dfc289f554e3d964df6577165e6f", "size": "2027", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "README.md", "mode": "33188", "license": "mit", "language": [ { "name": "JavaScript", "bytes": "3043" } ], "symlink_target": "" }
package conv import ( "fmt" "math" "reflect" "strconv" "strings" iconv "github.com/hairyhenderson/gomplate/v3/internal/conv" "github.com/pkg/errors" ) // Bool converts a string to a boolean value, using strconv.ParseBool under the covers. // Possible true values are: 1, t, T, TRUE, true, True // All other values are considered false. // // See ToBool also for a more flexible version. // // Deprecated: use ToBool instead func Bool(in string) bool { if b, err := strconv.ParseBool(in); err == nil { return b } return false } // ToBool converts an arbitrary input into a boolean. // Possible non-boolean true values are: 1 or the strings "t", "true", or "yes" // (any capitalizations) // All other values are considered false. func ToBool(in interface{}) bool { if b, ok := in.(bool); ok { return b } if str, ok := in.(string); ok { str = strings.ToLower(str) switch str { case "1", "t", "true", "yes": return true default: return strToFloat64(str) == 1 } } val := reflect.Indirect(reflect.ValueOf(in)) switch val.Kind() { case reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64, reflect.Int: return val.Int() == 1 case reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uint: return val.Uint() == 1 case reflect.Float32, reflect.Float64: return val.Float() == 1 default: return false } } // ToBools - func ToBools(in ...interface{}) []bool { out := make([]bool, len(in)) for i, v := range in { out[i] = ToBool(v) } return out } // Slice creates a slice from a bunch of arguments // // Deprecated: use [github.com/hairyhenderson/gomplate/v3/coll.Slice] instead func Slice(args ...interface{}) []interface{} { return args } // Join concatenates the elements of a to create a single string. // The separator string sep is placed between elements in the resulting string. // // This is functionally identical to strings.Join, except that each element is // coerced to a string first func Join(in interface{}, sep string) (out string, err error) { s, ok := in.([]string) if ok { return strings.Join(s, sep), nil } var a []interface{} a, ok = in.([]interface{}) if !ok { a, err = iconv.InterfaceSlice(in) if err != nil { return "", errors.Wrap(err, "input to Join must be an array") } ok = true } if ok { b := make([]string, len(a)) for i := range a { b[i] = ToString(a[i]) } return strings.Join(b, sep), nil } return "", errors.New("input to Join must be an array") } // Has determines whether or not a given object has a property with the given key func Has(in interface{}, key interface{}) bool { av := reflect.ValueOf(in) switch av.Kind() { case reflect.Map: kv := reflect.ValueOf(key) return av.MapIndex(kv).IsValid() case reflect.Slice, reflect.Array: l := av.Len() for i := 0; i < l; i++ { v := av.Index(i).Interface() if reflect.DeepEqual(v, key) { return true } } } return false } // ToString - func ToString(in interface{}) string { if in == nil { return "nil" } if s, ok := in.(string); ok { return s } if s, ok := in.(fmt.Stringer); ok { return s.String() } if s, ok := in.([]byte); ok { return string(s) } v, ok := printableValue(reflect.ValueOf(in)) if ok { in = v } return fmt.Sprint(in) } // ToStrings - func ToStrings(in ...interface{}) []string { out := make([]string, len(in)) for i, v := range in { out[i] = ToString(v) } return out } // MustParseInt - wrapper for strconv.ParseInt that returns 0 in the case of error func MustParseInt(s string, base, bitSize int) int64 { // nolint: gosec i, _ := strconv.ParseInt(s, base, bitSize) return i } // MustParseFloat - wrapper for strconv.ParseFloat that returns 0 in the case of error func MustParseFloat(s string, bitSize int) float64 { // nolint: gosec i, _ := strconv.ParseFloat(s, bitSize) return i } // MustParseUint - wrapper for strconv.ParseUint that returns 0 in the case of error func MustParseUint(s string, base, bitSize int) uint64 { // nolint: gosec i, _ := strconv.ParseUint(s, base, bitSize) return i } // MustAtoi - wrapper for strconv.Atoi that returns 0 in the case of error func MustAtoi(s string) int { // nolint: gosec i, _ := strconv.Atoi(s) return i } // ToInt64 - convert input to an int64, if convertible. Otherwise, returns 0. func ToInt64(v interface{}) int64 { if str, ok := v.(string); ok { return strToInt64(str) } val := reflect.Indirect(reflect.ValueOf(v)) switch val.Kind() { case reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64, reflect.Int: return val.Int() case reflect.Uint8, reflect.Uint16, reflect.Uint32: return int64(val.Uint()) case reflect.Uint, reflect.Uint64: tv := val.Uint() // this can overflow and give -1, but IMO this is better than // returning maxint64 return int64(tv) case reflect.Float32, reflect.Float64: return int64(val.Float()) case reflect.Bool: if val.Bool() { return 1 } return 0 default: return 0 } } // ToInt - func ToInt(in interface{}) int { // Protect against CWE-190 and CWE-681 // https://cwe.mitre.org/data/definitions/190.html // https://cwe.mitre.org/data/definitions/681.html if i := ToInt64(in); i <= math.MaxInt || i >= math.MinInt { return int(i) } // we're probably on a 32-bit system, so we can't represent this number return -1 } // ToInt64s - func ToInt64s(in ...interface{}) []int64 { out := make([]int64, len(in)) for i, v := range in { out[i] = ToInt64(v) } return out } // ToInts - func ToInts(in ...interface{}) []int { out := make([]int, len(in)) for i, v := range in { out[i] = ToInt(v) } return out } // ToFloat64 - convert input to a float64, if convertible. Otherwise, returns 0. func ToFloat64(v interface{}) float64 { if str, ok := v.(string); ok { return strToFloat64(str) } val := reflect.Indirect(reflect.ValueOf(v)) switch val.Kind() { case reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64, reflect.Int: return float64(val.Int()) case reflect.Uint8, reflect.Uint16, reflect.Uint32: return float64(val.Uint()) case reflect.Uint, reflect.Uint64: return float64(val.Uint()) case reflect.Float32, reflect.Float64: return val.Float() case reflect.Bool: if val.Bool() { return 1 } return 0 default: return 0 } } func strToInt64(str string) int64 { if strings.Contains(str, ",") { str = strings.ReplaceAll(str, ",", "") } iv, err := strconv.ParseInt(str, 0, 64) if err != nil { // maybe it's a float? var fv float64 fv, err = strconv.ParseFloat(str, 64) if err != nil { return 0 } return ToInt64(fv) } return iv } func strToFloat64(str string) float64 { if strings.Contains(str, ",") { str = strings.ReplaceAll(str, ",", "") } // this is inefficient, but it's the only way I can think of to // properly convert octal integers to floats iv, err := strconv.ParseInt(str, 0, 64) if err != nil { // ok maybe it's a float? var fv float64 fv, err = strconv.ParseFloat(str, 64) if err != nil { return 0 } return fv } return float64(iv) } // ToFloat64s - func ToFloat64s(in ...interface{}) []float64 { out := make([]float64, len(in)) for i, v := range in { out[i] = ToFloat64(v) } return out } // Dict is a convenience function that creates a map with string keys. // Provide arguments as key/value pairs. If an odd number of arguments // is provided, the last is used as the key, and an empty string is // set as the value. // All keys are converted to strings, regardless of input type. func Dict(v ...interface{}) (map[string]interface{}, error) { dict := map[string]interface{}{} lenv := len(v) for i := 0; i < lenv; i += 2 { key := ToString(v[i]) if i+1 >= lenv { dict[key] = "" continue } dict[key] = v[i+1] } return dict, nil }
{ "content_hash": "3e888473df20388bb386fcedd7723af7", "timestamp": "", "source": "github", "line_count": 335, "max_line_length": 87, "avg_line_length": 23.229850746268657, "alnum_prop": 0.6576715497301465, "repo_name": "hairyhenderson/gomplate", "id": "c61319f3cf891f49da9846c172c9a8f9e880ccb7", "size": "7867", "binary": false, "copies": "1", "ref": "refs/heads/main", "path": "conv/conv.go", "mode": "33188", "license": "mit", "language": [ { "name": "Dockerfile", "bytes": "2007" }, { "name": "Go", "bytes": "644531" }, { "name": "Makefile", "bytes": "6672" } ], "symlink_target": "" }
require 'dashify/extensions/action_view/tag_builder' require 'dashify/railtie' require 'dashify/version' module Dashify end
{ "content_hash": "521cae04e5e37f80fe446768663bfc09", "timestamp": "", "source": "github", "line_count": 6, "max_line_length": 52, "avg_line_length": 20.833333333333332, "alnum_prop": 0.816, "repo_name": "mmontossi/hyphenify", "id": "104f9fc4e788c929d112ddab84585ae4bc8238bb", "size": "125", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "lib/dashify.rb", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "686" }, { "name": "HTML", "bytes": "5349" }, { "name": "JavaScript", "bytes": "596" }, { "name": "Ruby", "bytes": "20007" } ], "symlink_target": "" }
var adminsockets = []; var g_tlg = [ "RM", "PP", "EO", "JB", "HH" ]; var g_subg = [ ["ALT", "PRG", "EXT", "FUS", "FNK", "NA"], ["SIN", "IND", "CN", "REG"], ["DnB", "PP", "EDM", "AMB", "EXP"], ["JZ", "BL", "PP"], ["SL", "RAP", "EH", "REGG"] ]; var TotalSongs; var socketServer = function() { var data = null, timerID = null, sockets = [], socketServer = null, /** Add module imports here */ WebSocketServer = require('ws').Server, http = require('http'), fs = require('fs'), url = require('url'), domain = require('domain'), reqDomain = domain.create(), socketDomain = domain.create(), httpDomain = domain.create(), DOMParser = require('xmldom').DOMParser, crypto = require('crypto'), mailer = require("nodemailer"), mime = require('mime'), oppressor = require('oppressor'), Throttle = require('throttle'), path = require('path'); httpListen = function(port) { httpDomain.on('error', function(err) { console.log('Error caught in http domain:' + err); }); httpDomain.run(function() { http.createServer(function(request, response) { var filePath = decodeURI(url.parse(request.url).pathname); if (filePath == '/') { readFile(request, response, './www/' + 'index.html'); } else if (filePath.startsWith('/api.')) { var api = filePath.split('api.')[1]; console.log('API request : ' + api); response.write(JSON.stringify({music: 8082, chat: 8081})); response.end(); return; } else { readFile(request, response, './www' + filePath); return; } }).listen(port); }); }, readFile = function(request, response, filePath) { var contentType = mime.lookup(path.extname(filePath)); console.log(request.method + " mime : " + contentType + " file : " + filePath); var stat = null; try { stat = fs.statSync(filePath); } catch (error) { response.writeHead(404, {'content-type': 'text/html'}); response.write('File not found: ' + filePath); response.end(); console.log(error.message); return; } if (!filePath.endsWith('.m4a')) { /** * cache everything except pm3's for 1 hour, webp for a day */ var age = 0; filePath.endsWith('.webp') ? age = 3600 * 24 : age = 3600; response.setHeader('Cache-Control', 'public, max-age=' + age.toString()); } response.setHeader('content-type', contentType); var total = stat.size; if (request.headers.range) { var range = request.headers.range; var parts = range.replace(/bytes=/, "").split("-"); var partialstart = parts[0]; var partialend = parts[1]; var start = parseInt(partialstart, 10); var end = partialend ? parseInt(partialend, 10) : (total - 1); var chunksize = (end - start) + 1; console.log('RANGE: ' + start + ' - ' + end + ' = ' + chunksize); response.statusCode = 206; response.setHeader('Content-Range', 'bytes ' + start + '-' + end + '/' + total); response.setHeader('Accept-Ranges', 'bytes'); response.setHeader('Content-Length', chunksize); } else { response.statusCode = 200; response.setHeader('Content-Length', total); } var strewam = fs.createReadStream(filePath, {start: start, end: end}); stream.on('error', function(error) { console.log('stream on error !!!'); response.writeHead(500); response.end(); }); stream.on('end', function(error) { /*console.log('stream ended');*/ }); stream.on('close', function(error) { /*console.log('stream closed');*/ }); if (filePath.endsWith('.m4a')) { /** * Here's an example of throttling stdin at 1 byte per second and outputting the data to stdout: * create a "Throttle" instance that reads at 1 bps */ var throttle = new Throttle(1024*60); stream.pipe(throttle).pipe(response); } else { stream.pipe(oppressor(request)).pipe(response); } }, socketListen = function(port) { socketDomain.on('error', function(err) { console.log('Error caught in socket domain:' + err); }); socketDomain.run(function() { socketServer = new WebSocketServer({ port: port }); socketServer.on('listening',function(){ console.log("socket server running on port : " + port); }); socketServer.broadcast = function broadcast(message) { // var json = JSON.stringify({type: "broadcast", data: message}); // adminsockets.forEach(function each(admin) { // admin.send(json); // }); }; socketServer.on('connection', function (socket) { var username; socket.on("message", function(data) { var json = JSON.parse(data), user = null, userhome = null, userdb = null, historyfile = null, trunkfile = null, scorefile = null; user = json.token; if (json.type != "login" && /** token not requred */ json.type != "register" && /** token not required */ json.type != "ReachOut" && /** token not required */ json.type != "echo") { /** token not required */ /** * Except for the above messages anything else without a token * is flagged as error. Playlist can also come without a token. */ if (!user && json.type != "playlist") { sendMessage("error", "Message without token !"); return; } /** * if we have a user for playlist and other commands then * validate here. validate_authenticator(authenticator) */ if (user && !fs.existsSync("./users/" + user)) { if (json.type == 'is ok ?') sendMessage("token.delete", 'user not found'); else sendMessage("error", "user not found : [" + user + "] " + json.type); return; } /** here the user token is valid */ if (json.type == 'is ok ?') sendMessage("token.ok", 'user found'); } if (user) { userhome = "./users/" + user; userdb = "./users/" + user + ".txt"; historyfile = "./users/" + user + "/" + user + ".history.txt"; trunkfile = "./users/" + user + "/" + user + ".trunk.txt"; scorefile = "./users/" + user + "/" + user + ".score.txt"; console.log(user + " : " + data); } else { console.log("user null for message : " + data); } if (json.type == "TJ-") { /** remove the line from trunk file */ console.log(typeof json.line); var line = JSON.stringify(json.line); console.log(line); fs.readFile(trunkfile, function(error, trunk) { if (error) { sendMessage("error", error); return console.log(error); } if (trunk.toString('ascii').indexOf(line) != -1) { /** replace the incoming json line with " " */ var newtrunk = trunk.toString('ascii').replace(line, "TJ-"); /** writeFile will overwrite the file if file already exists */ fs.writeFile(trunkfile, newtrunk + '\r\n', 'utf8', function(error) { if (error) { return console.log(error); }; console.log("trunk updated for : " + user); sendTrunkProfileSlider("Get Trunk", user); }); } }); return; } else if (json.type == "HISTORY+") { /** update the user's play history */ if (user) { /** update history only if the user is logged on */ fs.appendFileSync(historyfile, json.song + '\r\n'); /*, function (error) { if (error) { sendMessage("error", "Failed to update user history"); } else { //console.log("play history updated"); } });*/ } } else if (json.type == "LOGOUT") { socketServer.broadcast(json.token + ' -'); } else if (json.type == "playlist") { var songs = []; var sliderfile = "./users/" + user + "/" + user + ".slider.txt"; var TotalRating = parseInt(json.gr.TotalRating); /** * overwrite the server slider scores if and only if TotalRating * of the incoming client slider scores is valid i.e. > 0, as login from * a fresh browser (0 client score and with a valid server side slider * score)would otherwise purge the server score. * If the incoming TotalRating is zero and the file exists on the server then * send that as the slider score back to the client. writeFile will overwrite the file if * file already exists. */ if (user) { if (TotalRating > 0) { fs.writeFile(sliderfile, data, 'utf8', function(error) { if (error) { return console.log(error); }; console.log("slider scores written."); }); } else if (TotalRating == 0 && fs.existsSync(sliderfile)) { /** * send the slider scores which we have, back to the client. */ console.log("sending slider scores for user : " + user); sendTrunkProfileSlider("Get Slider", user); } /*console.log("TRACE : " + TotalRating + " " + fs.existsSync(sliderfile));*/ } /** * sort g_tlg it based on initial ratings */ var sorted = g_tlg.slice(0); sorted.sort(function(tlg1, tlg2) { if (tlg1 == "RM") { r1 = json.gr.RM; } else if (tlg1 == "PP") { r1 = json.gr.PP; } else if (tlg1 == "EO") { r1 = json.gr.EO; } else if (tlg1 == "JB") { r1 = json.gr.JB; } else if (tlg1 == "HH") { r1 = json.gr.HH; } if (tlg2 == "RM") { r2 = json.gr.RM; } else if (tlg2 == "PP") { r2 = json.gr.PP; } else if (tlg2 == "EO") { r2 = json.gr.EO; } else if (tlg2 == "JB") { r2 = json.gr.JB; } else if (tlg2 == "HH") { r2 = json.gr.HH; } return parseInt(r2) - parseInt(r1); }); console.log('----sorted----'); sorted.forEach(function(tlg) { console.log(tlg); }); console.log('----sorted----'); var attempts = 0; while (true) { attempts++; /** * Slider score bucket : for_each(TLG) */ for (var i = 0; i < sorted.length; i++) { var tlg = sorted[i], subgs = g_subg[g_tlg.indexOf(tlg)], rating = null; if (tlg == "RM") { rating = json.gr.RM; } else if (tlg == "PP") { rating = json.gr.PP; } else if (tlg == "EO") { rating = json.gr.EO; } else if (tlg == "JB") { rating = json.gr.JB; } else if (tlg == "HH") { rating = json.gr.HH; } if (parseInt(rating) > 0 && parseInt(rating) <= 50) rating = "1"; else if (parseInt(rating) > 50 && parseInt(rating) <= 100) rating = "2"; console.log("-->slider rating for " + tlg + " : " + rating); var discover = false; if (parseInt(rating) == 0) { /** * Zero slider rating would contribute 1 song to the discover bucket. */ rating = "1"; console.log(".. +1 for discover bucket contribution for [" + tlg + "]"); discover = true; } else { /** * rating > 0 and the user is not logged on : double the slider rating.. this is permanent change. */ if (!json.token) { rating = (parseInt(rating) * 2).toString(); console.log("..doubled rating for [" + tlg + "] since user is not logged on : " + rating); } /** * Also for now, since user score bucket is not active add 2 to the user slider rating (which can be 1 or 2) */ rating = (parseInt(rating) + 2).toString(); console.log("..increased rating for [" + tlg + "] by 2 (to account for user-score bucket): " + rating); } /** * Pick 'rating' random and different SubGs under this TLGx. */ var s = []; for (var j = 0; j < parseInt(rating); j++) { while(true) { var candidate = getRandomInt(0, (subgs.length - 1)); if ((s.indexOf(candidate) == -1) || (s.length >= subgs.length)) { s.push(candidate); console.log(" " + subgs[candidate]); break; } } } /** * read the history in memory */ var history = null; if (fs.existsSync(historyfile)) { history = fs.readFileSync(historyfile, 'utf8'); } /** For_each (SubG of TLGx in set [S]) */ for (var j = 0; j < s.length; j++) { var star = subgWalk("./www/music/" + tlg + "/" + subgs[s[j]], discover, history); /*star.forEach(function(file) { console.log(file); });*/ if ((!star.length) && (!discover)) { console.log("walking subg " + subgs[s[j]] + " again with discover mode"); star = subgWalk("./www/music/" + tlg + "/" + subgs[s[j]], true, history); } if (star.length) { /** * ./www/music/RockMetal/Alternative/Alice in Chains/Jar Of Flies/~dont follow.m4a */ var item = star[getRandomInt(0, (star.length - 1))], tokens = item.split("/"), song = tokens[tokens.length - 1], album = tokens[tokens.length - 2], artist = tokens[tokens.length - 3]; item = item.replace("./www", "."); if (song.startsWith("~")) song = song.replace("~", ""); if (song.endsWith(".m4a")) song = song.replace(".m4a", ""); console.log("Genre: " + tlg + " Sub-Genre: " + subgs[s[j]] + " song: " + song); var albart = "./www/music/" + tlg + "/" + subgs[s[j]] + "/" + artist + "/" + album + "/" + "album.jpg", artart = "./www/music/" + tlg + "/" + subgs[s[j]] + "/" + artist + "/" + "artist.webp"; try { fs.statSync(albart); } catch (error) { albart = null; } try { fs.statSync(artart); } catch (error) { artart = null; } if (albart) albart = albart.replace("./www", "."); if (artart) artart = artart.replace("./www", "."); songs.push([song, album, artist, item, tlg, subgs[s[j]], albart, albart]); } }/** For_each (SubG of TLGx in set [S]) */ } /** slider score bucket */ /** * user score bucket : valid only when we have a token. */ if (json.token) { } /** * Discover bucket : always valid; with or without token. */ // songs.push(["Max payne Theme", "MP", "Discover", "./music/JazzBlues/Fusion/Max Payne.m4a", "0"]); // songs.push(["Fell on black days", "Soundgarden", "discover", "./music/RockMetal/Alternative/Soundgarden/Fell On Black Days.m4a", "0"]); // songs.push(["Gettysburg", "Ratatat", "Discover", "./music/Electro/Rock/Gettysburg.m4a", "0"]); // songs.push(["Rotten Apple", "Alice in chains", "Discover", "http://trunkitmusic.com/Music/RockMetal/Alternative/Alice in Chains/Jar Of Flies/~Rotten Apple.m4a", "0"]); if (songs.length) { sendMessage("playlist", songs); break; } else { console.log('zero songs enumerated, attempt : ' + attempts.toString()); if (user) { var d = new Date(); d = d.toLocaleTimeString(); fs.rename(historyfile, historyfile + '_' + (d.split(' '))[0].replace(/:/gi, '.') + '_' + Math.random().toString(36).substr(2, 9)); if (attempts <= 1) { continue; } } sendMessage("warning", "server : zero songs computed"); break; } } /*while(true)*/ return; } else if (json.type == "echo") { sendMessage(json.cmd, JSON.stringify(json.data)); return; } else if (json.type == "Trunk" || json.type == "Junk") { fs.readFile(trunkfile, function(error, trunk) { /** * Allow ENOENT to pass as the first trunk or junk on a song would create the file anyways. */ if (error && error.code != 'ENOENT') { /** everything else we fail */ sendMessage("error", error); return console.log(error); } if (!error && trunk.toString('ascii').indexOf(data) != -1) { /** * multiple trunk or junk should have effect on the score ? */ sendMessage("error", "song \"" + json.song + "\" alreay in " + json.type); return; } /** Update the user score for this genre-subgenre captured in the trunk/junk json */ var scorejson = JSON.stringify({type: json.type, genre: json.genre, subgenre: json.subgenre}); /** append "Trunk" or "Junk" to this g.subg.txt score file*/ fs.appendFile(scorefile, scorejson + '\r\n', function (error) { if (error) { sendMessage("error", "Failed to update user score file"); } else { console.log("server : " + "user score updated successfully."); } }); /** * Check if there's a change from trunk to junk on the song or vice versa */ var flipped = data.replace(json.type, (json.type == "Trunk" ? "Junk" : "Trunk")); if (!error && (trunk.toString('ascii').indexOf(flipped) != -1)) { /** replace the "flipped" json line in the "trunk" with incoming "data" json line */ var newtrunk = trunk.toString('ascii').replace(flipped, data); /** writeFile will overwrite the file if file already exists */ fs.writeFile(trunkfile, newtrunk + '\r\n', 'utf8', function(error) { if (error) { return console.log(error); }; console.log("new trunk written !"); sendMessage("notify", "song \"" + json.song + "\" moved from " + (json.type == "Trunk" ? "Junk" : "Trunk") + " to " + json.type); sendTrunkProfileSlider("Get Trunk", user); }); return; } /** * This is a new trunk/junk json line. Asynchronously append data to a file, * creating the file if it not yet exists. data can be a string or a buffer. */ fs.appendFile(trunkfile, data + '\r\n', function (error) { if (error) { sendMessage("error", "Failed to write to trunk file"); } else { console.log("server : " + "user trunk written successfully."); sendMessage("notify", json.song + " added to " + json.type); sendTrunkProfileSlider("Get Trunk", user); } }); }); /** fs.readFile */ return; } else if (json.type == "Get Trunk" || json.type == "Get Profile") { sendTrunkProfileSlider(json.type, user); if (json.type == "Get Profile") { if (user.includes('neelabh')) adminsockets.push(this); socketServer.broadcast(user + ' +'); } return; } else if (json.type == "ReachOut") { /** Use Smtp Protocol to send Email */ var smtpTransport = mailer.createTransport("SMTP",{ service: "Gmail", auth: { user: "contact.trunkit@gmail.com", pass: "zaq12WSX" } }); var mail = { from: "TRUNK-IT <contact.trunkit@gmail.com>", to: "contact.trunkit@gmail.com;robinc88@gmail.com;karannambiar@hotmail.com;kishore12@micamail.in", subject: "REACH OUT : Message from [" + json.name + "," + json.email + "]", text: json.message //html: .replace("\n", "<\/br>") } smtpTransport.sendMail(mail, function(error, response) { if (error){ console.log(error); sendMessage("error", "Failed to deliver message."); }else{ console.log("Message sent: " + response.message); sendMessage("notify", "Message delivered."); } smtpTransport.close(); }); return; } else if (json.type == "login" || json.type == "register") { if (user || userdb || userhome) { sendMessage("error", "user : " + user + " userdb : " + userdb + " userhome : " + userhome); return; } if (json.method && (json.method == "FB" || json.method == "GPLUS")) { user = json.userID; } else { user = json.email; } userhome = "./users/" + user; userdb = "./users/" + user + ".txt"; if (json.type == "register") { /** * register handler should close the connection * check if the user already has a db file */ if (fs.existsSync(userdb)) { if (json.method && (json.method == "FB" || json.method == "GPLUS")) { sendMessage("token", {id: user, type: json.method}); } else { sendMessage("warning", "User [" + user + "] already registered"); } return; } /** * user db file does not exist; we are good to go.. */ console.log("register user : creating user db file " + userdb) var dbData = null, /* xml */ profileData = "{"; /* json start */ if (json.method && (json.method == "FB" || json.method == "GPLUS")) { profileData += "\"name\": \"" + json.name + "\","; profileData += "\"email\": \"" + json.email + "\","; profileData += "\"gender\": \"" + json.gender + "\","; if (json.avatar != undefined) profileData += "\"avatar\": \"" + json.avatar + "\""; //last dbData = "<id>" + json.userID + "</id>" } else { const salt = crypto.randomBytes(512); const iterations = 274; /* Math.floor(Math.random() * (200000 - 100000 + 1)) + 100000; */ console.log("register user : running pbkdf2 with iteration count " + iterations + "...") const key = crypto.pbkdf2Sync(json.password, salt, iterations, 512, 'sha512'); dbData = "<key>" + key.toString('hex') + "</key>" dbData += "<salt>" + salt.toString('hex') + "</salt>" dbData += "<iterations>" + iterations + "</iterations>" profileData += "\"email\": \"" + json.email + "\""; //last } profileData += "}"; /* json end */ console.log(profileData); /** * Asynchronously append data to a file, creating the file if * it not yet exists. data can be a string or a buffer. */ fs.appendFile(userdb, dbData, function (error) { if (error) { sendMessage("error", "Failed to write to user db file"); } else { console.log("register user : authentication data written successfully !") console.log("register user : creating user's home directory..."); fs.mkdir(userhome, function(error) { if (error) { sendMessage("error", "Failed to create user's home directory."); return console.error(error); } console.log("register user : user's home directory created successfully !"); var userprofile = userhome + "/" + user + ".profile.txt"; fs.appendFile(userprofile, profileData, function (error) { if (error) { sendMessage("error", "Failed to write to user profile"); } else { console.log("register user : user's profile written successfully !"); /** * once the user has been registered log him in immediately. */ sendMessage("token", {id: user, type: json.method}); } }); }); } }); return; } else if (json.type == "login") { /** open the user's db file */ fs.open(userdb, 'r+', function(error, fd) { if (error) { sendMessage("error", "user [" + user + "] not registered."); return console.log(error); } console.log("user's db file opened successfully !"); console.log("reading user's db file " + userdb); var buf = new Buffer(4096); fs.read(fd, buf, 0, buf.length, 0, function(err, bytes) { if (err) { sendMessage("error", "Unable to read user db file."); fs.closeSync(fd); return console.log(err); } console.log(bytes + " bytes read"); /** Print only read bytes to avoid junk. */ if (bytes > 0) { var db = buf.slice(0, bytes).toString(); /*console.log(db);*/ var parser = new DOMParser(); var xmlDoc = parser.parseFromString(db, "text/xml"); var key = xmlDoc.getElementsByTagName("key")[0].childNodes[0].nodeValue, salt = xmlDoc.getElementsByTagName("salt")[0].childNodes[0].nodeValue, iterations = xmlDoc.getElementsByTagName("iterations")[0].childNodes[0].nodeValue var saltx = new Buffer(salt, 'hex'), iterationsx = Number(iterations); var generated = crypto.pbkdf2Sync(json.password, saltx, iterationsx, 512, 'sha512'); if (generated.toString('hex') == key) { console.log("user authentication successful."); sendMessage("token", {id: user, type: "email"}); } else { console.log("user authentication failed."); sendMessage("error", "Authentication failed."); return; } } else { console.log("failed to read user db"); sendMessage("error", "Authentication failed !"); fs.closeSync(fd); } }); /** fs.read */ }); /** fs.open */ } /* login */ } /* login or register */ else { /*console.log(data);*/ } }); console.log("\nserver : client connected. ip : " + socket.upgradeReq.connection.remoteAddress); socket.on("error", function(data) { console.log("server : socket error : " + data); }); socket.on("close", function(data) { console.log("server : socket close"); var found = adminsockets.indexOf(this); while (found !== -1) { adminsockets.splice(found, 1); found = adminsockets.indexOf(this); } }); function sendMessage(kind, message) { var json = null; if (kind) json = JSON.stringify({type: kind, data: message}); else json = message; socket.send(json, function ack(error) { if (error) { console.log("server send : " + error); } console.log("SEND : " + json); }); } function sendTrunkProfileSlider(type, user) { var file = null, response = null; if (type == "Get Trunk") { file = "./users/" + user + "/" + user + ".trunk.txt"; response = "Trunk"; } else if (type == "Get Profile") { file = "./users/" + user + "/" + user + ".profile.txt"; response = "Profile"; } else if (type == "Get Slider") { file = "./users/" + user + "/" + user + ".slider.txt"; response = "Slider"; } if (!file) return; /** open the user's trunk, profile or slider file */ console.log("reading user file : " + file); fs.readFile(file, function(error, data) { if (error) { //sendMessage("warning", file.substring(file.lastIndexOf("/") + 1)); return console.log(error); } sendMessage(response, data.toString('ascii')); }); /** fs.readFile */ } }); }); }, init = function(httpPort, socketPort) { httpListen(httpPort); socketListen(socketPort); TotalSongs = contentWalk('./www/music','.m4a'); console.log("Total number of songs : " + TotalSongs); }; /** * Returns a random integer between min (inclusive) and max (inclusive) * Using Math.round() will give you a non-uniform distribution! */ function getRandomInt(min, max) { return Math.floor(Math.random() * (max - min + 1)) + min; } function contentWalk(dir, pattern) { var list = fs.readdirSync(dir), count = 0; list.forEach(function(file) { file = dir + '/' + file; var stat = fs.statSync(file); if (stat && stat.isDirectory()) count += contentWalk(file, pattern); else if (file.includes('Yankee Doodle')) { /** skip */ } else if (file.endsWith(pattern)) { count++; } else { //console.log(file); } }); return count; } var subgWalk = function(dir, discover, history) { var results = []; var list = fs.readdirSync(dir) list.forEach(function(file) { file = dir + '/' + file; var stat = fs.statSync(file); if (stat && stat.isDirectory()) results = results.concat(subgWalk(file, discover, history)); else if (file.includes('Yankee Doodle')) { /** skip */ } else if (history && history.includes(file)) { console.log("skipping history song"); } else if (file.includes('/~') && !discover) results.push(file); else if (file.endsWith('.m4a')) { results.push(file); } }); return results; } return { init: init }; }(); module.exports = socketServer;
{ "content_hash": "a0d9fc6934c50cb83e1d73fe3a24e0ab", "timestamp": "", "source": "github", "line_count": 959, "max_line_length": 189, "avg_line_length": 40.53076120959333, "alnum_prop": 0.3971802721963518, "repo_name": "n-mam/DATACRAFT", "id": "64307ebc58a0d17aa8000204e1b27e1e09c80d15", "size": "38869", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "socketServer.js", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "2686" }, { "name": "HTML", "bytes": "4055" }, { "name": "JavaScript", "bytes": "76332" } ], "symlink_target": "" }
package org.wso2.carbon.apimgt.importexport; import java.io.File; /** * This class contains all the constants required for API Import and Export */ public final class APIImportExportConstants { //system dependent default path separator character, represented as a string public static final String DIRECTORY_SEPARATOR = File.separator; //System independent file separator for zip files public static final char ZIP_FILE_SEPARATOR = '/'; //string representing the false state when preserving the provider public static final String STATUS_FALSE = "FALSE"; //length of the name of the temporary directory public static final int TEMP_FILENAME_LENGTH = 5; //system property for default temporary directory public static final String TEMP_DIR = "java.io.tmpdir"; //name of the uploaded zip file public static final String UPLOAD_FILE_NAME = "APIArchive.zip"; //location of the api JSON file public static final String JSON_FILE_LOCATION = DIRECTORY_SEPARATOR + "Meta-information" + DIRECTORY_SEPARATOR + "api.json"; //name of the id element tag of the api.json file public static final String ID_ELEMENT = "id"; //name of the api provider element tag of the api.json file public static final String PROVIDER_ELEMENT = "providerName"; //location of the api swagger definition file public static final String SWAGGER_DEFINITION_LOCATION = DIRECTORY_SEPARATOR + "Meta-information" + DIRECTORY_SEPARATOR + "swagger.json"; //location of the image public static final String IMAGE_FILE_LOCATION = DIRECTORY_SEPARATOR + "Image" + DIRECTORY_SEPARATOR; //name of the image public static final String IMAGE_FILE_NAME = "icon"; //location of the documents JSON file public static final String DOCUMENT_FILE_LOCATION = DIRECTORY_SEPARATOR + "Docs" + DIRECTORY_SEPARATOR + "docs.json"; //name of the inline file type public static final String INLINE_DOC_TYPE = "INLINE"; //name of the url file type public static final String URL_DOC_TYPE = "URL"; //name of the physical file type public static final String FILE_DOC_TYPE = "FILE"; //location of the in sequence public static final String IN_SEQUENCE_LOCATION = DIRECTORY_SEPARATOR + "Sequences" + DIRECTORY_SEPARATOR + "in-sequence" + DIRECTORY_SEPARATOR; //location of the out sequence public static final String OUT_SEQUENCE_LOCATION = DIRECTORY_SEPARATOR + "Sequences" + DIRECTORY_SEPARATOR + "out-sequence" + DIRECTORY_SEPARATOR; //location of the fault sequence public static final String FAULT_SEQUENCE_LOCATION = DIRECTORY_SEPARATOR + "Sequences" + DIRECTORY_SEPARATOR + "fault-sequence" + DIRECTORY_SEPARATOR; //extension of xml files public static final String XML_EXTENSION = ".xml"; //location of the wsdl file public static final String WSDL_LOCATION = DIRECTORY_SEPARATOR + "WSDL" + DIRECTORY_SEPARATOR; //extension of wsdl files public static final String WSDL_EXTENSION = ".wsdl"; public static final String DOCUMENT_DIRECTORY = "Docs"; public static final String INLINE_DOCUMENT_DIRECTORY = "InlineContents"; public static final String FILE_DOCUMENT_DIRECTORY = "FileContents"; public static final String INLINE_DOC_CONTENT_REGISTRY_DIRECTORY = "contents"; public static final String API_REGISTRY_BASE_LOCATION = "/registry/resource/_system/governance/apimgt/applicationdata/"; public static final String CHARSET = "UTF-8"; }
{ "content_hash": "dfad0fe88c8e1ac0435023b8d9566d55", "timestamp": "", "source": "github", "line_count": 76, "max_line_length": 116, "avg_line_length": 47.03947368421053, "alnum_prop": 0.718041958041958, "repo_name": "hevayo/product-apim", "id": "45b6ff029c8c501e35d41bdd9c596cc677c5ed32", "size": "4229", "binary": false, "copies": "7", "ref": "refs/heads/master", "path": "modules/api-import-export/src/main/java/org.wso2.carbon.apimgt/importexport/APIImportExportConstants.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Batchfile", "bytes": "3946" }, { "name": "CSS", "bytes": "69611" }, { "name": "HTML", "bytes": "37375" }, { "name": "Java", "bytes": "3165563" }, { "name": "JavaScript", "bytes": "314001" }, { "name": "PLSQL", "bytes": "63706" }, { "name": "Shell", "bytes": "4142" }, { "name": "XSLT", "bytes": "3161" } ], "symlink_target": "" }
/* * plane.h - This file contains the defines for planes etc. * * $Id: plane.h,v 1.12 2002/08/04 21:43:34 johns Exp $ */ object * newplane(void * tex, vector ctr, vector norm); #ifdef PLANE_PRIVATE typedef struct { RT_OBJECT_HEAD flt d; vector norm; } plane; static void plane_intersect(const plane *, ray *); static int plane_bbox(void * obj, vector * min, vector * max); static void plane_normal(const plane *, const vector *, const ray * incident, vector *); #endif
{ "content_hash": "58f7c1d69ebdb3d51cf64334b3618a3c", "timestamp": "", "source": "github", "line_count": 21, "max_line_length": 88, "avg_line_length": 23.238095238095237, "alnum_prop": 0.6721311475409836, "repo_name": "shaotuanchen/sunflower_exp", "id": "dcd4f77b13609c915c7bae07b38f04a123f7a0e2", "size": "488", "binary": false, "copies": "3", "ref": "refs/heads/master", "path": "benchmarks/source/ALPBench/Ray_Trace/tachyon/src/plane.h", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "Assembly", "bytes": "459993" }, { "name": "Awk", "bytes": "6562" }, { "name": "Batchfile", "bytes": "9028" }, { "name": "C", "bytes": "50326113" }, { "name": "C++", "bytes": "2040239" }, { "name": "CSS", "bytes": "2355" }, { "name": "Clarion", "bytes": "2484" }, { "name": "Coq", "bytes": "61440" }, { "name": "DIGITAL Command Language", "bytes": "69150" }, { "name": "Emacs Lisp", "bytes": "186910" }, { "name": "Fortran", "bytes": "5364" }, { "name": "HTML", "bytes": "2171356" }, { "name": "JavaScript", "bytes": "27164" }, { "name": "Logos", "bytes": "159114" }, { "name": "M", "bytes": "109006" }, { "name": "M4", "bytes": "100614" }, { "name": "Makefile", "bytes": "5409865" }, { "name": "Mercury", "bytes": "702" }, { "name": "Module Management System", "bytes": "56956" }, { "name": "OCaml", "bytes": "253115" }, { "name": "Objective-C", "bytes": "57800" }, { "name": "Papyrus", "bytes": "3298" }, { "name": "Perl", "bytes": "70992" }, { "name": "Perl 6", "bytes": "693" }, { "name": "PostScript", "bytes": "3440120" }, { "name": "Python", "bytes": "40729" }, { "name": "Redcode", "bytes": "1140" }, { "name": "Roff", "bytes": "3794721" }, { "name": "SAS", "bytes": "56770" }, { "name": "SRecode Template", "bytes": "540157" }, { "name": "Shell", "bytes": "1560436" }, { "name": "Smalltalk", "bytes": "10124" }, { "name": "Standard ML", "bytes": "1212" }, { "name": "TeX", "bytes": "385584" }, { "name": "WebAssembly", "bytes": "52904" }, { "name": "Yacc", "bytes": "510934" } ], "symlink_target": "" }
#ifndef __GENERIC_TIME_INTERVALTIMER__ #define __GENERIC_TIME_INTERVALTIMER__ //============================================================================== // EXTERNAL DECLARATIONS //============================================================================== #include "Time.h" #ifdef GENERIC_NAMESPACE namespace GENERIC_NAMESPACE { #endif //============================================================================== // CLASS IntervalTimer //============================================================================== template <class TIMER> class IntervalTimer { public: IntervalTimer(); ~IntervalTimer(); IntervalTimer(const IntervalTimer& rhs); IntervalTimer& operator=(const IntervalTimer &rhs); void start(); Time stop(); private: typename TIMER::TimeStamp mStartTime; }; #ifdef GENERIC_NAMESPACE } #endif #include "src/IntervalTimer.inline.h" #endif // __GENERIC_TIME_INTERVALTIMER__
{ "content_hash": "02d9047b7a90d5606d90685a0df9d4d9", "timestamp": "", "source": "github", "line_count": 39, "max_line_length": 80, "avg_line_length": 23.512820512820515, "alnum_prop": 0.48636859323882226, "repo_name": "Enseed/GenericTime", "id": "4161339492673a5283d382c61bcb3548c1491cfc", "size": "2169", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "IntervalTimer.h", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "C++", "bytes": "42335" } ], "symlink_target": "" }
package xworker.groovy; import java.util.List; import java.util.Map; import org.codehaus.groovy.ast.ASTNode; import org.codehaus.groovy.ast.GroovyCodeVisitor; import org.codehaus.groovy.ast.Variable; import org.codehaus.groovy.ast.builder.AstBuilder; import org.codehaus.groovy.ast.expr.ArgumentListExpression; import org.codehaus.groovy.ast.expr.ArrayExpression; import org.codehaus.groovy.ast.expr.AttributeExpression; import org.codehaus.groovy.ast.expr.BinaryExpression; import org.codehaus.groovy.ast.expr.BitwiseNegationExpression; import org.codehaus.groovy.ast.expr.BooleanExpression; import org.codehaus.groovy.ast.expr.CastExpression; import org.codehaus.groovy.ast.expr.ClassExpression; import org.codehaus.groovy.ast.expr.ClosureExpression; import org.codehaus.groovy.ast.expr.ClosureListExpression; import org.codehaus.groovy.ast.expr.ConstantExpression; import org.codehaus.groovy.ast.expr.ConstructorCallExpression; import org.codehaus.groovy.ast.expr.DeclarationExpression; import org.codehaus.groovy.ast.expr.ElvisOperatorExpression; import org.codehaus.groovy.ast.expr.Expression; import org.codehaus.groovy.ast.expr.FieldExpression; import org.codehaus.groovy.ast.expr.GStringExpression; import org.codehaus.groovy.ast.expr.ListExpression; import org.codehaus.groovy.ast.expr.MapEntryExpression; import org.codehaus.groovy.ast.expr.MapExpression; import org.codehaus.groovy.ast.expr.MethodCallExpression; import org.codehaus.groovy.ast.expr.MethodPointerExpression; import org.codehaus.groovy.ast.expr.NotExpression; import org.codehaus.groovy.ast.expr.PostfixExpression; import org.codehaus.groovy.ast.expr.PrefixExpression; import org.codehaus.groovy.ast.expr.PropertyExpression; import org.codehaus.groovy.ast.expr.RangeExpression; import org.codehaus.groovy.ast.expr.SpreadExpression; import org.codehaus.groovy.ast.expr.SpreadMapExpression; import org.codehaus.groovy.ast.expr.StaticMethodCallExpression; import org.codehaus.groovy.ast.expr.TernaryExpression; import org.codehaus.groovy.ast.expr.TupleExpression; import org.codehaus.groovy.ast.expr.UnaryMinusExpression; import org.codehaus.groovy.ast.expr.UnaryPlusExpression; import org.codehaus.groovy.ast.expr.VariableExpression; import org.codehaus.groovy.ast.stmt.AssertStatement; import org.codehaus.groovy.ast.stmt.BlockStatement; import org.codehaus.groovy.ast.stmt.BreakStatement; import org.codehaus.groovy.ast.stmt.CaseStatement; import org.codehaus.groovy.ast.stmt.CatchStatement; import org.codehaus.groovy.ast.stmt.ContinueStatement; import org.codehaus.groovy.ast.stmt.DoWhileStatement; import org.codehaus.groovy.ast.stmt.ExpressionStatement; import org.codehaus.groovy.ast.stmt.ForStatement; import org.codehaus.groovy.ast.stmt.IfStatement; import org.codehaus.groovy.ast.stmt.ReturnStatement; import org.codehaus.groovy.ast.stmt.Statement; import org.codehaus.groovy.ast.stmt.SwitchStatement; import org.codehaus.groovy.ast.stmt.SynchronizedStatement; import org.codehaus.groovy.ast.stmt.ThrowStatement; import org.codehaus.groovy.ast.stmt.TryCatchStatement; import org.codehaus.groovy.ast.stmt.WhileStatement; import org.codehaus.groovy.classgen.BytecodeExpression; import org.xmeta.Thing; import org.xmeta.World; public class TestGroovyAst implements GroovyCodeVisitor{ public void test() { try { World world = World.getInstance(); world.init(null); Thing thing = world.getThing("xworker.ide.worldexplorer.swt.SimpleExplorer/@shell1/@scripts/@openDataObject"); String code = thing.getString("code"); AstBuilder ac = new AstBuilder(); List<ASTNode> nodes = ac.buildFromString(code); for(ASTNode node : nodes) { node.visit(this); } }catch(Exception e) { e.printStackTrace(); } } public static void main(String args[]) { TestGroovyAst test = new TestGroovyAst(); test.test(); } @Override public void visitBlockStatement(BlockStatement statement) { System.out.println("visitBlockStatement, " + statement); System.out.println(statement.getVariableScope().getDeclaredVariables()); for(Statement st : statement.getStatements()) { System.out.println(statement.getVariableScope().getDeclaredVariables()); st.visit(this); } } @Override public void visitForLoop(ForStatement forLoop) { System.out.println("visitForLoop"); } @Override public void visitWhileLoop(WhileStatement loop) { System.out.println("visitWhileLoop"); } @Override public void visitDoWhileLoop(DoWhileStatement loop) { System.out.println("visitDoWhileLoop"); } @Override public void visitIfElse(IfStatement ifElse) { System.out.println("visitIfElse"); BlockStatement ifBlok = (BlockStatement) ifElse.getIfBlock(); Map<String, Variable> variables = ifBlok.getVariableScope().getDeclaredVariables(); for(String key : variables.keySet()) { Variable v = variables.get(key); if(v != null) { Expression exp = v.getInitialExpression(); if(exp != null) { System.out.println(key + ": " + v.getType() + " ," + v.getInitialExpression().getLineNumber() + ", " + v.getInitialExpression().getColumnNumber()); }else { System.out.println(key + ": " + v.getType()); } }else { System.out.println(key + ": is null"); } } for(Statement st : ifBlok.getStatements()) { st.visit(this); } } @Override public void visitExpressionStatement(ExpressionStatement statement) { System.out.println("visitExpressionStatement"); } @Override public void visitReturnStatement(ReturnStatement statement) { System.out.println("visitReturnStatement"); } @Override public void visitAssertStatement(AssertStatement statement) { System.out.println("visitAssertStatement"); } @Override public void visitTryCatchFinally(TryCatchStatement finally1) { System.out.println("visitTryCatchFinally"); } @Override public void visitSwitch(SwitchStatement statement) { System.out.println("visitSwitch"); } @Override public void visitCaseStatement(CaseStatement statement) { System.out.println("visitCaseStatement"); } @Override public void visitBreakStatement(BreakStatement statement) { System.out.println("visitBreakStatement"); } @Override public void visitContinueStatement(ContinueStatement statement) { System.out.println("visitContinueStatement"); } @Override public void visitThrowStatement(ThrowStatement statement) { System.out.println("visitThrowStatement"); } @Override public void visitSynchronizedStatement(SynchronizedStatement statement) { System.out.println("visitSynchronizedStatement"); } @Override public void visitCatchStatement(CatchStatement statement) { System.out.println("visitCatchStatement"); } @Override public void visitMethodCallExpression(MethodCallExpression call) { System.out.println("visitMethodCallExpression"); } @Override public void visitStaticMethodCallExpression(StaticMethodCallExpression expression) { System.out.println("visitStaticMethodCallExpression"); } @Override public void visitConstructorCallExpression(ConstructorCallExpression expression) { System.out.println("visitConstructorCallExpression"); } @Override public void visitTernaryExpression(TernaryExpression expression) { System.out.println("visitTernaryExpression"); } @Override public void visitShortTernaryExpression(ElvisOperatorExpression expression) { System.out.println("visitBlockStatement"); } @Override public void visitBinaryExpression(BinaryExpression expression) { System.out.println("visitBlockStatement"); } @Override public void visitPrefixExpression(PrefixExpression expression) { System.out.println("visitBlockStatement"); } @Override public void visitPostfixExpression(PostfixExpression expression) { System.out.println("visitBlockStatement"); } @Override public void visitBooleanExpression(BooleanExpression expression) { System.out.println("visitBlockStatement"); } @Override public void visitClosureExpression(ClosureExpression expression) { System.out.println("visitBlockStatement"); } @Override public void visitTupleExpression(TupleExpression expression) { System.out.println("visitTupleExpression"); } @Override public void visitMapExpression(MapExpression expression) { System.out.println("visitMapExpression"); } @Override public void visitMapEntryExpression(MapEntryExpression expression) { System.out.println("visitMapEntryExpression"); } @Override public void visitListExpression(ListExpression expression) { System.out.println("visitListExpression"); } @Override public void visitRangeExpression(RangeExpression expression) { System.out.println("visitRangeExpression"); } @Override public void visitPropertyExpression(PropertyExpression expression) { System.out.println("visitPropertyExpression"); } @Override public void visitAttributeExpression(AttributeExpression attributeExpression) { System.out.println("visitAttributeExpression"); } @Override public void visitFieldExpression(FieldExpression expression) { System.out.println("visitFieldExpression"); } @Override public void visitMethodPointerExpression(MethodPointerExpression expression) { System.out.println("visitMethodPointerExpression"); } @Override public void visitConstantExpression(ConstantExpression expression) { System.out.println("visitConstantExpression"); } @Override public void visitClassExpression(ClassExpression expression) { System.out.println("visitClassExpression"); } @Override public void visitVariableExpression(VariableExpression expression) { System.out.println("visitVariableExpression"); } @Override public void visitDeclarationExpression(DeclarationExpression expression) { System.out.println("visitDeclarationExpression"); } @Override public void visitGStringExpression(GStringExpression expression) { System.out.println("visitGStringExpression"); } @Override public void visitArrayExpression(ArrayExpression expression) { System.out.println("visitArrayExpression"); } @Override public void visitSpreadExpression(SpreadExpression expression) { System.out.println("visitSpreadExpression"); } @Override public void visitSpreadMapExpression(SpreadMapExpression expression) { System.out.println("visitSpreadMapExpression"); } @Override public void visitNotExpression(NotExpression expression) { System.out.println("visitNotExpression"); } @Override public void visitUnaryMinusExpression(UnaryMinusExpression expression) { System.out.println("visitUnaryMinusExpression"); } @Override public void visitUnaryPlusExpression(UnaryPlusExpression expression) { System.out.println("visitUnaryPlusExpression"); } @Override public void visitBitwiseNegationExpression(BitwiseNegationExpression expression) { System.out.println("visitBitwiseNegationExpression"); } @Override public void visitCastExpression(CastExpression expression) { System.out.println("visitCastExpression"); } @Override public void visitArgumentlistExpression(ArgumentListExpression expression) { System.out.println("visitArgumentlistExpression"); } @Override public void visitClosureListExpression(ClosureListExpression closureListExpression) { System.out.println("visitClosureListExpression"); } @Override public void visitBytecodeExpression(BytecodeExpression expression) { System.out.println("visitBytecodeExpression"); } }
{ "content_hash": "575720d70458e4172ff08260feaa9137", "timestamp": "", "source": "github", "line_count": 369, "max_line_length": 113, "avg_line_length": 31.78590785907859, "alnum_prop": 0.7698866058487509, "repo_name": "x-meta/xworker", "id": "059d7cc8bc3a113ea4e15c07105febe51dd7e8e5", "size": "11729", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "xworker_groovy/src/main/java/xworker/groovy/TestGroovyAst.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Batchfile", "bytes": "13302" }, { "name": "CSS", "bytes": "608135" }, { "name": "Fluent", "bytes": "1420" }, { "name": "FreeMarker", "bytes": "245430" }, { "name": "Groovy", "bytes": "2259" }, { "name": "HTML", "bytes": "228023" }, { "name": "Java", "bytes": "12283468" }, { "name": "JavaScript", "bytes": "804030" }, { "name": "Lex", "bytes": "5606489" }, { "name": "PHP", "bytes": "2232" }, { "name": "Python", "bytes": "572" }, { "name": "Ruby", "bytes": "302" }, { "name": "SCSS", "bytes": "16447" }, { "name": "Shell", "bytes": "13983" } ], "symlink_target": "" }
extensions ========== This is where I put extensions that I use and like as is, and don't have to worry about someone buying it out and using it for bad stuff
{ "content_hash": "ec4c7763f4e4c230ea9e92cf3c1fee04", "timestamp": "", "source": "github", "line_count": 4, "max_line_length": 136, "avg_line_length": 40, "alnum_prop": 0.725, "repo_name": "kolodny/extensions", "id": "8b76ddba6b84636e7aa968d44c44ad679c7de8a8", "size": "160", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "README.md", "mode": "33188", "license": "mit", "language": [ { "name": "JavaScript", "bytes": "31042" } ], "symlink_target": "" }
package ersir.shared import com.github.plokhotnyuk.jsoniter_scala.core.{JsonValueCodec, readFromString, writeToString} import com.github.plokhotnyuk.jsoniter_scala.macros.JsonCodecMaker import loci.MessageBuffer import loci.registry.Binding import loci.transmitter.Serializable import loci.transmitter.transmittable.IdenticallyTransmittable import rescala.extra.lattices.delta.CContext._ import rescala.extra.lattices.delta.crdt.reactive.RGA import rescala.extra.lattices.delta.JsoniterCodecs._ import scala.concurrent.Future import scala.util.Try case class Posting(title: String, desc: String, img: String) object Posting { def parse(textfield: String, url: String = ""): Posting = { val split = textfield.split("\n", 2) val Array(title, desc) = if (split.length == 2) split else Array(textfield, "") Posting(title, desc, url) } implicit val PostingCodec: JsonValueCodec[Posting] = JsonCodecMaker.make } object Bindings { implicit def jsoniterBasedSerializable[T](implicit codec: JsonValueCodec[T]): Serializable[T] = new Serializable[T] { override def serialize(value: T): MessageBuffer = MessageBuffer.encodeString(writeToString(value)) override def deserialize(value: MessageBuffer): Try[T] = Try(readFromString[T](value.decodeString)) } implicit val _Tbm: IdenticallyTransmittable[RGA.State[Posting, DietMapCContext]] = IdenticallyTransmittable() val crdtDescriptions : Binding[RGA.State[Posting, DietMapCContext] => Unit, RGA.State[Posting, DietMapCContext] => Future[Unit]] = Binding[RGA.State[Posting, DietMapCContext] => Unit]("postings"): @scala.annotation.nowarn }
{ "content_hash": "520c5ade97c034406b862c15c4b510a9", "timestamp": "", "source": "github", "line_count": 40, "max_line_length": 119, "avg_line_length": 41.075, "alnum_prop": 0.768715763846622, "repo_name": "guidosalva/REScala", "id": "50fe3f18d9c8c87cfc0ff1ce612cc5a139fa5035", "size": "1643", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "Code/Examples/Ersir/shared/src/main/scala/ersir/shared/Bindings.scala", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Dockerfile", "bytes": "233" }, { "name": "Java", "bytes": "9082" }, { "name": "Perl", "bytes": "138894" }, { "name": "Scala", "bytes": "1056257" } ], "symlink_target": "" }
import type { Action } from './actionTypes' import { FETCH_REQUEST, FETCH_SUCCESS, FETCH_FAILRE } from './constants' export function fetchRequest(word: string): Action { return { type: FETCH_REQUEST, word, } } export function fetchSuccess(keywords: Array<string>): Action { return { type: FETCH_SUCCESS, keywords, } } export function fetchFailre(error: string): Action { return { type: FETCH_FAILRE, error, } }
{ "content_hash": "665dfb1bdcdae05bf8ab81647e61bf15", "timestamp": "", "source": "github", "line_count": 23, "max_line_length": 72, "avg_line_length": 19.565217391304348, "alnum_prop": 0.6711111111111111, "repo_name": "akameco/PixivDeck", "id": "13ad91c73d065bbd88718ed9c980cafd31be1b28", "size": "459", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "app/containers/SearchField/actions.js", "mode": "33188", "license": "mit", "language": [ { "name": "HTML", "bytes": "714" }, { "name": "JavaScript", "bytes": "330164" } ], "symlink_target": "" }
std::vector<std::pair<size_t, float>> get_pruned_log_probs( const std::vector<double> &prob_step, double cutoff_prob, size_t cutoff_top_n, int log_input) { std::vector<std::pair<int, double>> prob_idx; double log_cutoff_prob = log(cutoff_prob); for (size_t i = 0; i < prob_step.size(); ++i) { prob_idx.push_back(std::pair<int, double>(i, prob_step[i])); } // pruning of vacobulary size_t cutoff_len = prob_step.size(); if (log_cutoff_prob < 0.0 || cutoff_top_n < cutoff_len) { std::sort( prob_idx.begin(), prob_idx.end(), pair_comp_second_rev<int, double>); if (cutoff_prob < 0.0) { double cum_prob = 0.0; cutoff_len = 0; for (size_t i = 0; i < prob_idx.size(); ++i) { cum_prob = log_sum_exp(cum_prob, log_input ? prob_idx[i].second : log(prob_idx[i].second) ); cutoff_len += 1; if (cum_prob >= cutoff_prob || cutoff_len >= cutoff_top_n) break; } } prob_idx = std::vector<std::pair<int, double>>( prob_idx.begin(), prob_idx.begin() + cutoff_len); } std::vector<std::pair<size_t, float>> log_prob_idx; for (size_t i = 0; i < cutoff_len; ++i) { log_prob_idx.push_back(std::pair<int, float>( prob_idx[i].first, log_input ? prob_idx[i].second : log(prob_idx[i].second + NUM_FLT_MIN))); } return log_prob_idx; } std::vector<std::pair<double, Output>> get_beam_search_result( const std::vector<PathTrie *> &prefixes, size_t beam_size) { // allow for the post processing std::vector<PathTrie *> space_prefixes; if (space_prefixes.empty()) { for (size_t i = 0; i < beam_size && i < prefixes.size(); ++i) { space_prefixes.push_back(prefixes[i]); } } std::sort(space_prefixes.begin(), space_prefixes.end(), prefix_compare); std::vector<std::pair<double, Output>> output_vecs; for (size_t i = 0; i < beam_size && i < space_prefixes.size(); ++i) { std::vector<int> output; std::vector<int> timesteps; space_prefixes[i]->get_path_vec(output, timesteps); Output outputs; outputs.tokens = output; outputs.timesteps = timesteps; std::pair<double, Output> output_pair(-space_prefixes[i]->approx_ctc, outputs); output_vecs.emplace_back(output_pair); } return output_vecs; } size_t get_utf8_str_len(const std::string &str) { size_t str_len = 0; for (char c : str) { str_len += ((c & 0xc0) != 0x80); } return str_len; } std::vector<std::string> split_utf8_str(const std::string &str) { std::vector<std::string> result; std::string out_str; for (char c : str) { if ((c & 0xc0) != 0x80) // new UTF-8 character { if (!out_str.empty()) { result.push_back(out_str); out_str.clear(); } } out_str.append(1, c); } result.push_back(out_str); return result; } std::vector<std::string> split_str(const std::string &s, const std::string &delim) { std::vector<std::string> result; std::size_t start = 0, delim_len = delim.size(); while (true) { std::size_t end = s.find(delim, start); if (end == std::string::npos) { if (start < s.size()) { result.push_back(s.substr(start)); } break; } if (end > start) { result.push_back(s.substr(start, end - start)); } start = end + delim_len; } return result; } bool prefix_compare(const PathTrie *x, const PathTrie *y) { if (x->score == y->score) { if (x->character == y->character) { return false; } else { return (x->character < y->character); } } else { return x->score > y->score; } } void add_word_to_fst(const std::vector<int> &word, fst::StdVectorFst *dictionary) { if (dictionary->NumStates() == 0) { fst::StdVectorFst::StateId start = dictionary->AddState(); assert(start == 0); dictionary->SetStart(start); } fst::StdVectorFst::StateId src = dictionary->Start(); fst::StdVectorFst::StateId dst; for (auto c : word) { dst = dictionary->AddState(); dictionary->AddArc(src, fst::StdArc(c, c, 0, dst)); src = dst; } dictionary->SetFinal(dst, fst::StdArc::Weight::One()); } bool add_word_to_dictionary( const std::string &word, const std::unordered_map<std::string, int> &char_map, bool add_space, int SPACE_ID, fst::StdVectorFst *dictionary) { auto characters = split_utf8_str(word); std::vector<int> int_word; for (auto &c : characters) { if (c == " ") { int_word.push_back(SPACE_ID); } else { auto int_c = char_map.find(c); if (int_c != char_map.end()) { int_word.push_back(int_c->second); } else { return false; // return without adding } } } if (add_space) { int_word.push_back(SPACE_ID); } add_word_to_fst(int_word, dictionary); return true; // return with successful adding }
{ "content_hash": "d4771ae49a09df8d5a0218e76b8fef14", "timestamp": "", "source": "github", "line_count": 170, "max_line_length": 100, "avg_line_length": 28.988235294117647, "alnum_prop": 0.5819805194805194, "repo_name": "parlance/pytorch-ctc", "id": "dab6ceb42046e8d3b1221cfca2804765f18ea8c5", "size": "5013", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "ctcdecode/src/decoder_utils.cpp", "mode": "33188", "license": "mit", "language": [ { "name": "C", "bytes": "1242" }, { "name": "C++", "bytes": "70344" }, { "name": "Python", "bytes": "13083" } ], "symlink_target": "" }
require 'spec_helper' describe Snippet do describe "Associations" do it { should belong_to(:author).class_name('User') } it { should have_many(:notes).dependent(:destroy) } end describe "Mass assignment" do it { should_not allow_mass_assignment_of(:author_id) } end describe "Validation" do it { should validate_presence_of(:author) } it { should validate_presence_of(:title) } it { should ensure_length_of(:title).is_within(0..255) } it { should validate_presence_of(:file_name) } it { should ensure_length_of(:title).is_within(0..255) } it { should validate_presence_of(:content) } end end
{ "content_hash": "7f211392348d147c1cc13c3cd3812346", "timestamp": "", "source": "github", "line_count": 24, "max_line_length": 60, "avg_line_length": 26.916666666666668, "alnum_prop": 0.6687306501547987, "repo_name": "1ed/gitlabhq", "id": "52355c38f0c8b2b8a258e451cd5fc93a64f8edfe", "size": "1016", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "spec/models/snippet_spec.rb", "mode": "33188", "license": "mit", "language": [ { "name": "CoffeeScript", "bytes": "48099" }, { "name": "JavaScript", "bytes": "41951" }, { "name": "Ruby", "bytes": "932494" }, { "name": "Shell", "bytes": "1241" } ], "symlink_target": "" }
namespace EntityFramework.Northwind.Entities { using System; using System.Collections.Generic; public partial class Sales_Totals_by_Amount { public Nullable<decimal> SaleAmount { get; set; } public int OrderID { get; set; } public string CompanyName { get; set; } public Nullable<System.DateTime> ShippedDate { get; set; } } }
{ "content_hash": "3d3009efde95661645061088f2ff4d87", "timestamp": "", "source": "github", "line_count": 13, "max_line_length": 66, "avg_line_length": 29.53846153846154, "alnum_prop": 0.6536458333333334, "repo_name": "Vavro/Tests", "id": "2b58ab53334790301faf1d171058bfda50801a1c", "size": "805", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "EntityFrameworkTests/EntityFramework.Northwind.Entities/Sales_Totals_by_Amount.cs", "mode": "33188", "license": "mit", "language": [ { "name": "ASP", "bytes": "104" }, { "name": "C#", "bytes": "445272" }, { "name": "CSS", "bytes": "3049" }, { "name": "HTML", "bytes": "5081" }, { "name": "Java", "bytes": "72496" }, { "name": "JavaScript", "bytes": "137199" } ], "symlink_target": "" }
from __future__ import division import pysam from Bio.Seq import Seq from Bio import SeqIO from Bio.Alphabet import generic_dna from Bio.SeqRecord import SeqRecord from trim_to_coding import trim_to_regions def checkORF(seq): """ This function varifies the input is an ORF by checking it has i) a start codon ii) is made of complete codons mod(lenth(seg),3)=0 taking gaps into account iii) Has a stop codon at the end and not before. """ protien = seq.translate() # check for ATG at start if seq.find('ATG') !=0: if seq.find('ATG') ==-1: raise ValueError("No start codon") if seq.find('ATG')>0: raise ValueError("start codon found at position "+ str(seq.find('ATG'))) elif len(seq)% 3!=0: raise ValueError("The sequence is not multiple of 3") elif protien.find('*') != len(protien)-1: if protien.find('*') ==-1: raise ValueError("No stop codon in ORF") else: raise ValueError("Internal stop codon found at position "+ str(protien.find('*'))) else: return(True) def classify(sequence,codingRegion,pos,nucleotide): """ seqeunce is a seqRecord codingRegion is a diction in the form { "name": "NS1", "regions": [ { "start": 26, "stop": 719 } ] } The ouput is a dictionary added to the mutationalClass list it is of the form { ORF: The name of the ORF, codonPos: the position in the codon either [0,1,2], codingPos: the nucleotide position in the ORF aminoAcidPos: The position of the amino acid in the polypetide, consensusAA: The consensus amino acid, varAA: The variant amino acid, classification: Nonsynonymous,Synonymous,indel, stop, } """ # Get the coding sequence # Get the new position in the coding sequence i = 0 # Has to catch the case where it's outside these regions outsideORF=True for seg in codingRegion["regions"]: if pos >= seg["start"] and pos<seg["stop"]: outsideORF=False break else: i+=1 if outsideORF: return({ "ORF": codingRegion["name"], "codonPos": None, "codingPos": None, "aminoAcidPos": None, "consensusAA": None, "varAA": None, "classification": "Noncoding" }) codingSequence="" for seg in codingRegion["regions"]: codingSequence=codingSequence+sequence[seg["start"]:seg["stop"]] #consensusSequence = Seq(codingSequence,generic_dna) checkORF(codingSequence) posInSeg = pos-codingRegion["regions"][i]["start"] otherRegions = codingRegion["regions"][:i] adjustment = 0 if len(otherRegions)>0: for seg in otherRegions: adjustment+=seg["stop"]-seg["start"] codingPos = posInSeg+adjustment codonPos = codingPos % 3 aminoAcidPos = codingPos // 3 consensusProtien = codingSequence.translate() consensusAA = consensusProtien[aminoAcidPos] if nucleotide=="-": return({ "ORF": codingRegion["name"], "codonPos": codonPos, "codingPos": codingPos, "aminoAcidPos": aminoAcidPos, "consensusAA": consensusAA, "varAA": None, "classification": "Indel" }) mutantCodingSequence = codingSequence mutantCodingSequence = mutantCodingSequence[:codingPos]+ str(nucleotide) + mutantCodingSequence[codingPos+1:] # this is still seq object #mutantSequence = Seq(mutantCodingSequence,generic_dna) mutantProtein = mutantCodingSequence.translate() varAA = mutantProtein[aminoAcidPos] if varAA==consensusAA: classification = "Synonymous" elif varAA=="*": classification = "Stop" elif consensusAA=="*" and varAA!=consensusAA: classification= "Readthrough" elif varAA!=consensusAA: classification="Nonsynonymous" return({ "ORF": codingRegion["name"], "codonPos": codonPos, "codingPos": codingPos, "aminoAcidPos": aminoAcidPos, "consensusAA": consensusAA, "varAA": varAA, "classification": classification }) class allele(object): """ The allele present at a loci and their accompanying data """ def __init__(self,nucleotide): self.nucleotide=nucleotide self.count = 0 self.freq = 0 self.mutationalClass =[] def classifyVar(self,sequence,codingRegion,pos): self.mutationalClass.append(classify(sequence,codingRegion,pos,self.nucleotide)) def reprJSON(self): # https://stackoverflow.com/questions/5160077/encoding-nested-python-object-in-json d = dict() for a, v in self.__dict__.items(): if (hasattr(v, "reprJSON")): d[a] = v.reprJSON() else: d[a] = v return d class locus(object): """ A base which has the following characteristics Atrributes : Chr : chromosome pos : position on chromosome base 0 counts : a dictionary of { A : the number of As T : the number of Ts C : the number of Cs G : the number of Gs - : the number of of deletions } add consensus. add concat_pos methods : update : update counts calc_freqs : calculate the frequency of each base consensus : caculate the consensus sequence as this position """ def __init__(self,pos): """ return a base object with chr and pos and starting counts of 0 Posisition is base 0 because this is python and I want to keep everything easy to remember. If it came from python it is base 0. """ self.pos = pos # self.alleles = {'A':allele("A"), # 'T':allele("T"), # 'C':allele("C"), # 'G':allele("G"), # '-':allele("-")} self.alleles = {} self.coverage = 0 self.concat_pos = None self.consensus = '' def update(self,base): self.coverage = self.coverage+1 if base in self.alleles.keys(): self.alleles[base].count+=1 else: self.alleles.update({base:allele(base)}) self.alleles[base].count+=1 self.calc_freqs() self.consensus = self.calc_consensus() def calc_freqs(self): for base in self.alleles.keys(): self.alleles[base].freq = self.alleles[base].count/self.coverage def calc_consensus(self,cutoff=None): if self.coverage==0: return '-' else: self.calc_freqs() v=[y.freq for y in self.alleles.values()] #values k=list(self.alleles.keys()) # key # check for cutoff method if cutoff ==None: # Return the most common base return k[v.index(max(v))] else: # return the base that is above the cutoff if type(cutoff)!=float or (cutoff>1 or cutoff<0.5): raise ValueError('cutoff must be a float in [0.5,1.0] or nothing') indexes = [index for index, value in enumerate(v) if value > cutoff] if len(indexes)==1: consensus = k[indexes[0]] else: consensus = "N" return consensus def reprJSON(self): # https://stackoverflow.com/questions/5160077/encoding-nested-python-object-in-json d = dict() for a, v in self.__dict__.items(): if (hasattr(v, "reprJSON")): d[a] = v.reprJSON() elif a=="alleles": d["alleles"]={} for nt, alle in v.items(): d["alleles"].update({nt: alle.reprJSON()}) else: d[a] = v return d class segment(object): """ A sequence like object made up of locus objects Attriutes: chr - the name of the chr seq - a list of loci methods: append: append another position update: update base count at a position (loci base 1) consensus: calcuate the consensus sequence""" def __init__(self,chr): self.chr = chr self.seq = [] def append_loci(self,loci): if type(loci) is not locus: raise ValueError('Only class locus can be appended to a segment object') # if loci.chr!=self.chr: # raise ValueError('The loci chr does not match the segement chr') if len(self.seq)>0 and loci.pos!=max([x.pos for x in self.seq])+1: raise ValueError('The position of the loci does not match current segment length') self.seq.append(loci) def consensus(self,cutoff=None): seg_consensus = "" for loci in self.seq: seg_consensus=seg_consensus+loci.calc_consensus(cutoff) return seg_consensus def locus(self,pos): loci = [x for x in self.seq if x.pos==pos] return loci[0] def calc_coverage(self): cov = [] for loci in self.seq: cov.append(loci.coverage) return cov def reprJSON(self): # https://stackoverflow.com/questions/5160077/encoding-nested-python-object-in-json d = dict() for a, v in self.__dict__.items(): if hasattr(v, "reprJSON"): d[a] = v.reprJSON() elif a=="seq": d["seq"]=[] for l in v: d["seq"].append(l.reprJSON()) else: d[a] = v return d # reference object def tally(bamfile,chr,start,stop,maxDepth = 1000,phred = 30): """ This function takes in a pysam alignment file and tallies base calls across a defined region. Bases must pass a phred score cutoff. """ seg = segment(chr) pileup = bamfile.pileup(chr,start,stop,stepper='all',truncate=True,max_depth = maxDepth) # pileup = bamfile.pileup(chr,pos,pos+1,stepper='all',truncate=True,max_depth = maxDepth) for pileupColumn in pileup: l = locus(pos=pileupColumn.pos) # loci positions are base 0 for pileupRead in pileupColumn.pileups: if not pileupRead.is_del: if pileupRead.is_refskip: l.update("-") else: # query_alignment_* removes solf clipped bases, this confirms we don't look at positions beyond this clipping if pileupRead.query_position >= pileupRead.alignment.query_alignment_start and pileupRead.query_position < pileupRead.alignment.query_alignment_end: try: called_base= pileupRead.alignment.query_alignment_sequence[pileupRead.query_position-pileupRead.alignment.query_alignment_start] called_phred= pileupRead.alignment.query_alignment_qualities[pileupRead.query_position-pileupRead.alignment.query_alignment_start] except IndexError: print " chr : %s [%d - %d] query_pos : %d pos: %d" %(chr,pileupRead.alignment.query_alignment_start,pileupRead.alignment.query_alignment_end,pileupRead.query_position,pileupColumn.pos) print pileupRead.alignment.query_sequence print "-"*pileupRead.alignment.query_alignment_start + pileupRead.alignment.query_alignment_sequence print pileupRead.alignment.is_reverse if called_phred>=phred: l.update(called_base) seg.append_loci(l) return seg
{ "content_hash": "a062530e276f64418de88ecfef68119a", "timestamp": "", "source": "github", "line_count": 339, "max_line_length": 212, "avg_line_length": 36.905604719764014, "alnum_prop": 0.5455199424506434, "repo_name": "lauringlab/variant_pipeline", "id": "51978f70c216c4614e3629525a5663f5d09c9f99", "size": "12511", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "scripts/seq_classes.py", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Groovy", "bytes": "28853" }, { "name": "HTML", "bytes": "44728" }, { "name": "Python", "bytes": "164241" }, { "name": "R", "bytes": "19287" }, { "name": "Shell", "bytes": "90739" } ], "symlink_target": "" }
# After 6 years of Harpy and 4 years of [Siren](https://github.com/ArtSabintsev/Siren), I have decided to deprecate Harpy in favor of Siren. Why? Siren is written in Swift and has a feature set that is superior to that of Harpy. [More information can be found on this Medium post](https://link.medium.com/jE1FGj1DYS). The repository will live on, however, there will be no further updates and no transfers of the codebase at this time. --- # Harpy ### Notify users when a new version of your app is available and prompt them to upgrade. [![Build Status](https://travis-ci.org/ArtSabintsev/Harpy.svg?branch=master)](https://travis-ci.org/ArtSabintsev/Harpy) [![CocoaPods](https://img.shields.io/cocoapods/v/Harpy.svg)](https://cocoapods.org/pods/Harpy) [![Carthage Compatible](https://img.shields.io/badge/Carthage-compatible-4BC51D.svg?style=flat)](https://github.com/Carthage/Carthage) [![CocoaPods](https://img.shields.io/cocoapods/dt/Harpy.svg)](https://cocoapods.org/pods/Harpy) --- ## About **Harpy** checks a user's currently installed version of your iOS app against the version that is currently available in the App Store. If a new version is available, an alert can be presented to the user informing them of the newer version, and giving them the option to update the application. Harpy is built to work with the [Semantic Versioning](http://www.semver.org) system. - Semantic Versioning is a three number versioning system (e.g., 1.0.0) - Harpy also supports two-number versioning (e.g., 1.0) - Harpy also supports four-number versioning (e.g., 1.0.0.0) - Harpy only works with numbers. ## Swift Support Harpy was ported to Swift by myself and [**Aaron Brager**](http://twitter.com/GetAaron). We've called the new project [**Siren**](https://github.com/ArtSabintsev/Siren). ## Features - [x] CocoaPods Support - [x] Carthage Support - [x] Localized for 40+ languages (See **Localization**) - [x] Pre-Update Device Compatibility Check (See **Device Compatibility**) - [x] Three types of alerts (see **Screenshots & Alert Types**) - [x] Optional delegate methods (see **Optional Delegate** section) - [x] Unit Tests! ## Screenshots - The **left picture** forces the user to update the app. - The **center picture** gives the user the option to update the app. - The **right picture** gives the user the option to skip the current update. - These options are controlled by the `HarpyAlertType` enum that is found in `Harpy.h`. <img src="https://github.com/ArtSabintsev/Harpy/blob/master/Assets/picForcedUpdate.png?raw=true" height="480"> <img src="https://github.com/ArtSabintsev/Harpy/blob/master/Assets/picOptionalUpdate.png?raw=true" height="480"> <img src="https://github.com/ArtSabintsev/Harpy/blob/master/Assets/picSkippedUpdate.png?raw=true" height="480"> ## Installation Instructions ### CocoaPods ``` ruby pod 'Harpy' ``` ### Carthage ``` swift github "ArtSabintsev/Harpy" ``` ### Manual Copy the 'Harpy' folder into your Xcode project. It contains the Harpy.h and Harpy.m files. ## Setup 1. Import **Harpy.h** into your AppDelegate or Pre-Compiler Header (.pch) 1. In your `AppDelegate`, optionally set the **alertType**. 1. In your `AppDelegate`, call **only one** of the `checkVersion` methods, as all three perform a check on your application's first launch. Use either: - `checkVersion` in `application:didFinishLaunchingWithOptions:` - `checkVersionDaily` in `applicationDidBecomeActive:`. - `checkVersionWeekly` in `applicationDidBecomeActive:`. ``` obj-c - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions { // Present Window before calling Harpy [self.window makeKeyAndVisible]; // Set the UIViewController that will present an instance of UIAlertController [[Harpy sharedInstance] setPresentingViewController:_window.rootViewController]; // (Optional) Set the Delegate to track what a user clicked on, or to use a custom UI to present your message. [[Harpy sharedInstance] setDelegate:self]; // (Optional) When this is set, the alert will only show up if the current version has already been released for X days. // By default, this value is set to 1 (day) to avoid an issue where Apple updates the JSON faster than the app binary propogates to the App Store. [[Harpy sharedInstance] setShowAlertAfterCurrentVersionHasBeenReleasedForDays:3]; // (Optional) The tintColor for the alertController [[Harpy sharedInstance] setAlertControllerTintColor:@"<#alert_controller_tint_color#>"]; // (Optional) Set the App Name for your app [[Harpy sharedInstance] setAppName:@"<#app_name#>"]; /* (Optional) Set the Alert Type for your app By default, Harpy is configured to use HarpyAlertTypeOption */ [[Harpy sharedInstance] setAlertType:<#alert_type#>]; /* (Optional) If your application is not available in the U.S. App Store, you must specify the two-letter country code for the region in which your applicaiton is available. */ [[Harpy sharedInstance] setCountryCode:@"<#country_code#>"]; /* (Optional) Overrides system language to predefined language. Please use the HarpyLanguage constants defined in Harpy.h. */ [[Harpy sharedInstance] setForceLanguageLocalization:<#HarpyLanguageConstant#>]; /* (Optional): Delays the update prompt by a specific number of days. By default, this value is set to 1 day to avoid an issue where Apple updates the JSON faster than the app binary propogates to the App Store.*/ [[Harpy sharedInstance] setShowAlertAfterCurrentVersionHasBeenReleasedForDays:<#Int#>]; // Perform check for new version of your app [[Harpy sharedInstance] checkVersion]; } - (void)applicationDidBecomeActive:(UIApplication *)application { /* Perform daily check for new version of your app Useful if user returns to you app from background after extended period of time Place in applicationDidBecomeActive: Also, performs version check on first launch. */ [[Harpy sharedInstance] checkVersionDaily]; /* Perform weekly check for new version of your app Useful if you user returns to your app from background after extended period of time Place in applicationDidBecomeActive: Also, performs version check on first launch. */ [[Harpy sharedInstance] checkVersionWeekly]; } - (void)applicationWillEnterForeground:(UIApplication *)application { /* Perform check for new version of your app Useful if user returns to you app from background after being sent tot he App Store, but doesn't update their app before coming back to your app. ONLY USE THIS IF YOU ARE USING *HarpyAlertTypeForce* Also, performs version check on first launch. */ [[Harpy sharedInstance] checkVersion]; } ``` And you're all set! ## Differentiated Alerts for Patch, Minor, and Major Updates If you would like to set a different type of alert for revision, patch, minor, and/or major updates, simply add one or all of the following *optional* lines to your setup *before* calling any of the `checkVersion` methods: ``` obj-c /* By default, Harpy is configured to use HarpyAlertTypeOption for all version updates */ [[Harpy sharedInstance] setPatchUpdateAlertType:<#alert_type#>]; [[Harpy sharedInstance] setMinorUpdateAlertType:<#alert_type#>]; [[Harpy sharedInstance] setMajorUpdateAlertType:<#alert_type#>]; [[Harpy sharedInstance] setRevisionUpdateAlertType:<#alert_type#>]; ``` ## Optional Delegate and Delegate Methods If you'd like to handle or track the end-user's behavior, four delegate methods have been made available to you: ``` obj-c // User presented with update dialog - (void)harpyDidShowUpdateDialog; // User did click on button that launched App Store.app - (void)harpyUserDidLaunchAppStore; // User did click on button that skips version update - (void)harpyUserDidSkipVersion; // User did click on button that cancels update dialog - (void)harpyUserDidCancel; ``` If you would like to use your own UI, please use the following delegate method to obtain the localized update message if a new version is available: ``` obj-c - (void)harpyDidDetectNewVersionWithoutAlert:(NSString *)message; ``` ## Localization Harpy is localized for - Arabic - Armenian - Basque - Chinese (Simplified and Traditional) - Croatian - Czech - Danish - Dutch - English - Estonian - Finnish - French - German - Greek - Hebrew - Hungarian - Indonesian - Italian - Japanese - Korean - Latvian - Lithuanian - Malay - Norwegian (Bokmål) - Persian (Iran, Afghanistan, Persian) - Polish - Portuguese (Brazil and Portugal) - Russian - Serbian (Cyrillic and Latin) - Slovenian - Spanish - Swedish - Thai - Turkish - Ukrainian - Urdu - Vietnamese You may want the update dialog to *always* appear in a certain language, ignoring iOS's language setting (e.g. apps released in a specific country). You can enable it like this: ``` obj-c [[Harpy sharedInstance] setForceLanguageLocalization<#HarpyLanguageConstant#>]; ``` ## Device Compatibility If an app update is available, Harpy checks to make sure that the version of iOS on the user's device is compatible the one that is required by the app update. For example, if a user has iOS 9 installed on their device, but the app update requires iOS 10, an alert will not be shown. This takes care of the *false positive* case regarding app updating. ## Testing Harpy Temporarily change the version string in Xcode (within the `.xcodeproj`) to an older version than the one that's currently available in the App Store. Afterwards, build and run your app, and you should see the alert. If you currently don't have an app in the store, change your bundleID to one that is already in the store. In the sample app packaged with this library, we use the [App Store Connect](https://itunes.apple.com/us/app/itunes-connect/id376771144?mt=8) app's bundleID: `com.apple.itunesconnect.mobile`. ## Important Note on App Store Submissions The App Store reviewer will **not** see the alert. ## Phased Releases In 2017, Apple announced the [ability to rollout app updates gradually (a.k.a. Phased Releases)](https://itunespartner.apple.com/en/apps/faq/Managing%20Your%20Apps_Submission%20Process). Harpy will continue to work as it has in the past, presenting an update modal to _all_ users. If you opt-in to a phased rollout for a specific version, you will need to remotely disable Harpy until the rollout is done. ## Created and maintained by [Arthur Ariel Sabintsev](http://www.sabintsev.com/)
{ "content_hash": "60a228826256fef6fe05bf6db9e7c587", "timestamp": "", "source": "github", "line_count": 247, "max_line_length": 435, "avg_line_length": 42.38056680161943, "alnum_prop": 0.754107756973634, "repo_name": "ArtSabintsev/Harpy", "id": "6ee242343a881b014a57c8e0f314158e5dff4860", "size": "10469", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "README.md", "mode": "33188", "license": "mit", "language": [ { "name": "Objective-C", "bytes": "65410" }, { "name": "Ruby", "bytes": "2506" } ], "symlink_target": "" }
using System; using System.Collections.Generic; using System.Collections.Specialized; using System.Net; using System.Threading.Tasks; using Elasticsearch.Net; using FluentAssertions; using Nest; using Newtonsoft.Json; using Tests.Framework; namespace Tests.ClientConcepts.LowLevel { public class Lifetimes { /** * ## Lifetimes * * If you are using an IOC container its always useful to know the best practices around the lifetime of your objects * In general we advise folks to register their ElasticClient instances as singleton. The client is thread safe * so sharing this instance over threads is ok. * Zooming in however the actual moving part that benefits the most of being static for most of the duration of your * application is ConnectionSettings. Caches are per ConnectionSettings. * In some applications it could make perfect sense to have multiple singleton IElasticClient's registered with different * connectionsettings. e.g if you have 2 functionally isolated Elasticsearch clusters. */ [U] public void InitialDisposeState() { var connection = new AConnection(); var connectionPool = new AConnectionPool(new Uri("http://localhost:9200")); var settings = new AConnectionSettings(connectionPool, connection); settings.IsDisposed.Should().BeFalse(); connectionPool.IsDisposed.Should().BeFalse(); connection.IsDisposed.Should().BeFalse(); } /** * Disposing the ConnectionSettings will dispose the IConnectionPool and IConnection it has a hold of */ [U] public void DisposingSettingsDisposesMovingParts() { var connection = new AConnection(); var connectionPool = new AConnectionPool(new Uri("http://localhost:9200")); var settings = new AConnectionSettings(connectionPool, connection); using (settings) { } settings.IsDisposed.Should().BeTrue(); connectionPool.IsDisposed.Should().BeTrue(); connection.IsDisposed.Should().BeTrue(); } class AConnectionPool : SingleNodeConnectionPool { public AConnectionPool(Uri uri, IDateTimeProvider dateTimeProvider = null) : base(uri, dateTimeProvider) { } public bool IsDisposed { get; private set; } protected override void DisposeManagedResources() { this.IsDisposed = true; base.DisposeManagedResources(); } } class AConnectionSettings : ConnectionSettings { public AConnectionSettings(IConnectionPool pool, IConnection connection) : base(pool, connection) { } public bool IsDisposed { get; private set; } protected override void DisposeManagedResources() { this.IsDisposed = true; base.DisposeManagedResources(); } } class AConnection : InMemoryConnection { public bool IsDisposed { get; private set; } protected override void DisposeManagedResources() { this.IsDisposed = true; base.DisposeManagedResources(); } } } }
{ "content_hash": "f3ee54fef77cc48ad6ca7a76297490e1", "timestamp": "", "source": "github", "line_count": 93, "max_line_length": 122, "avg_line_length": 30.827956989247312, "alnum_prop": 0.7422392745029648, "repo_name": "azubanov/elasticsearch-net", "id": "f6fcadfc92e92fbc506a5086dfc208d6adb55136", "size": "2869", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "src/Tests/ClientConcepts/LowLevel/Lifetimes.doc.cs", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Batchfile", "bytes": "1521" }, { "name": "C#", "bytes": "6640106" }, { "name": "F#", "bytes": "40329" }, { "name": "HTML", "bytes": "348323" }, { "name": "Shell", "bytes": "698" }, { "name": "Smalltalk", "bytes": "3426" } ], "symlink_target": "" }
package org.apache.storm.kafka.spout; import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.MatcherAssert.assertThat; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.reset; import static org.mockito.Mockito.spy; import static org.mockito.Mockito.verify; import java.util.HashMap; import java.util.Map; import org.apache.kafka.clients.consumer.KafkaConsumer; import org.apache.kafka.clients.consumer.OffsetAndMetadata; import org.apache.kafka.common.TopicPartition; import org.apache.storm.kafka.KafkaUnitExtension; import org.apache.storm.kafka.spout.config.builder.SingleTopicKafkaSpoutConfiguration; import org.apache.storm.kafka.spout.internal.ConsumerFactory; import org.apache.storm.kafka.spout.internal.ConsumerFactoryDefault; import org.apache.storm.kafka.spout.subscription.TopicAssigner; import org.apache.storm.spout.SpoutOutputCollector; import org.apache.storm.task.TopologyContext; import org.apache.storm.tuple.Values; import org.apache.storm.utils.Time; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.extension.ExtendWith; import org.junit.jupiter.api.extension.RegisterExtension; import org.mockito.ArgumentCaptor; import org.mockito.Captor; import org.mockito.junit.jupiter.MockitoExtension; @ExtendWith(MockitoExtension.class) public abstract class KafkaSpoutAbstractTest { @RegisterExtension public KafkaUnitExtension kafkaUnitExtension = new KafkaUnitExtension(); final TopologyContext topologyContext = mock(TopologyContext.class); final Map<String, Object> conf = new HashMap<>(); final SpoutOutputCollector collectorMock = mock(SpoutOutputCollector.class); final long commitOffsetPeriodMs; private KafkaConsumer<String, String> consumerSpy; KafkaSpout<String, String> spout; @Captor ArgumentCaptor<Map<TopicPartition, OffsetAndMetadata>> commitCapture; private Time.SimulatedTime simulatedTime; private KafkaSpoutConfig<String, String> spoutConfig; /** * This constructor should be called by the subclass' default constructor with the desired value * @param commitOffsetPeriodMs commit offset period to be used in commit and verification of messages committed */ protected KafkaSpoutAbstractTest(long commitOffsetPeriodMs) { this.commitOffsetPeriodMs = commitOffsetPeriodMs; } @BeforeEach public void setUp() { spoutConfig = createSpoutConfig(); consumerSpy = createConsumerSpy(); spout = new KafkaSpout<>(spoutConfig, createConsumerFactory(), new TopicAssigner()); simulatedTime = new Time.SimulatedTime(); } protected KafkaConsumer<String, String> getKafkaConsumer() { return consumerSpy; } private ConsumerFactory<String, String> createConsumerFactory() { return new ConsumerFactory<String, String>() { @Override public KafkaConsumer<String, String> createConsumer(Map<String, Object> consumerProps) { return consumerSpy; } }; } KafkaConsumer<String, String> createConsumerSpy() { return spy(new ConsumerFactoryDefault<String, String>().createConsumer(spoutConfig.getKafkaProps())); } @AfterEach public void tearDown() throws Exception { simulatedTime.close(); } abstract KafkaSpoutConfig<String, String> createSpoutConfig(); void prepareSpout(int messageCount) throws Exception { SingleTopicKafkaUnitSetupHelper.populateTopicData(kafkaUnitExtension.getKafkaUnit(), SingleTopicKafkaSpoutConfiguration.TOPIC, messageCount); SingleTopicKafkaUnitSetupHelper.initializeSpout(spout, conf, topologyContext, collectorMock); } /** * Helper method to in sequence do: * <li> * <ul>spout.nexTuple()</ul> * <ul>verify messageId</ul> * <ul>spout.ack(msgId)</ul> * <ul>reset(collector) to be able to reuse mock</ul> * </li> * * @param offset offset of message to be verified * @return {@link ArgumentCaptor} of the messageId verified */ ArgumentCaptor<Object> nextTuple_verifyEmitted_ack_resetCollector(int offset) { spout.nextTuple(); ArgumentCaptor<Object> messageId = verifyMessageEmitted(offset); spout.ack(messageId.getValue()); reset(collectorMock); return messageId; } // offset and messageId are used interchangeably ArgumentCaptor<Object> verifyMessageEmitted(int offset) { final ArgumentCaptor<Object> messageId = ArgumentCaptor.forClass(Object.class); verify(collectorMock).emit( eq(SingleTopicKafkaSpoutConfiguration.STREAM), eq(new Values(SingleTopicKafkaSpoutConfiguration.TOPIC, Integer.toString(offset), Integer.toString(offset))), messageId.capture()); return messageId; } void commitAndVerifyAllMessagesCommitted(long msgCount) { // reset commit timer such that commit happens on next call to nextTuple() Time.advanceTime(commitOffsetPeriodMs + KafkaSpout.TIMER_DELAY_MS); //Commit offsets spout.nextTuple(); verifyAllMessagesCommitted(msgCount); } /* * Asserts that commitSync has been called once, * that there are only commits on one topic, * and that the committed offset covers messageCount messages */ void verifyAllMessagesCommitted(long messageCount) { verify(consumerSpy).commitSync(commitCapture.capture()); final Map<TopicPartition, OffsetAndMetadata> commits = commitCapture.getValue(); assertThat("Expected commits for only one topic partition", commits.entrySet().size(), is(1)); OffsetAndMetadata offset = commits.entrySet().iterator().next().getValue(); assertThat("Expected committed offset to cover all emitted messages", offset.offset(), is(messageCount)); reset(consumerSpy); } }
{ "content_hash": "b2650bc9e555a7ce03ec35bcee3477ae", "timestamp": "", "source": "github", "line_count": 168, "max_line_length": 149, "avg_line_length": 36.107142857142854, "alnum_prop": 0.7253544345532477, "repo_name": "hmcl/storm-apache", "id": "d8288735a29609bb1caa661c1bcf8ba5546517e0", "size": "6895", "binary": false, "copies": "5", "ref": "refs/heads/master", "path": "external/storm-kafka-client/src/test/java/org/apache/storm/kafka/spout/KafkaSpoutAbstractTest.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "C", "bytes": "54084" }, { "name": "CSS", "bytes": "12597" }, { "name": "Clojure", "bytes": "323393" }, { "name": "Fancy", "bytes": "6234" }, { "name": "FreeMarker", "bytes": "3512" }, { "name": "HTML", "bytes": "193952" }, { "name": "Java", "bytes": "12471832" }, { "name": "JavaScript", "bytes": "74893" }, { "name": "M4", "bytes": "1522" }, { "name": "Makefile", "bytes": "1302" }, { "name": "PowerShell", "bytes": "3405" }, { "name": "Python", "bytes": "1072987" }, { "name": "Ruby", "bytes": "15824" }, { "name": "Shell", "bytes": "24778" }, { "name": "Thrift", "bytes": "31772" }, { "name": "XSLT", "bytes": "1365" } ], "symlink_target": "" }
if type lv > /dev/null 2>&1; then export PAGER="lv" else export PAGER="less" fi # ### ### less ### export LESS="--no-init --LONG-PROMPT --ignore-case -RF" # ### ### Miscellaneous ### alias ls="ls -G" alias ll='ls -l' alias la='ls -A' alias lla="ls -l -A" alias mkdir="mkdir -p" alias tmux='tmux -u' alias pd=" pushd" alias po=" popd" alias dirs=" dirs | tr ' ' '\n'" alias vimhist=' vim $HISTFILE' alias jqless="jq -C '.' | less " alias tarx="tar xvzf" alias tarc="tar cvzf" alias iconvEU="iconv -f EUC-JP -t UTF-8" function lsEU() { ls $@ | iconv -f EUC-JP -t UTF-8 } alias lse="lsEU -G" alias k='kubectl' # ### ### X Window System ### # bugs here alias akill="ps -x | canything | awk '{print \$1}' | xargs kill -9" alias mkill="xprop | grep _NET_WM_PID | cut -d = -f 2 | xargs kill -9" # ### ### misc ### export KEU_CHROME_EXECUTABLE='/Applications/Google\ Chrome.app/Contents/MacOS/Google\ Chrome' alias peco-git-merge-commit-url-open="peco-git-merge-commit-url | xargs $KEU_CHROME_EXECUTABLE" alias js-beautify-replace='js-beautify -rn' export DEVELOPER_DIR=/Applications/Xcode.app/Contents/Developer alias symbolicatecrash='/Applications/Xcode.app/Contents/SharedFrameworks/DTDeviceKitBase.framework/Versions/A/Resources/symbolicatecrash'
{ "content_hash": "d20ecbed2a98c58c50e41a7426188bfa", "timestamp": "", "source": "github", "line_count": 73, "max_line_length": 138, "avg_line_length": 17.506849315068493, "alnum_prop": 0.6658841940532081, "repo_name": "kenoss/dotfiles", "id": "cf07541aa5ea1cad6bcd225d253e60187909cf38", "size": "1286", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "config/.zsh.d/config/alias.sh", "mode": "33188", "license": "mit", "language": [ { "name": "Ruby", "bytes": "7849" }, { "name": "Shell", "bytes": "39829" }, { "name": "Vim script", "bytes": "5645" } ], "symlink_target": "" }
using System; using System.Text; using System.ComponentModel; using System.Diagnostics.CodeAnalysis; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Graphics; using MonoGame.Extended.BitmapFonts; using MonoGame.Extended.Graphics.Effects; using MonoGame.Extended.Graphics.Geometry; namespace MonoGame.Extended.Graphics { /// <summary> /// A general purpose <see cref="Batcher{TDrawCallInfo}" /> for two-dimensional geometry that change /// frequently between frames such as sprites and shapes. /// </summary> /// <seealso cref="IDisposable" /> /// <remarks> /// <para>For drawing user interfaces, consider using <see cref="UIBatcher(ref Matrix, ref Matrix, BlendState, SamplerState, DepthStencilState, RasterizerState, Effect)" /> instead because it supports scissor rectangles.</para> /// </remarks> public sealed class Batcher2D : Batcher<Batcher2D.DrawCallInfo> { internal const int DefaultMaximumVerticesCount = 8192; internal const int DefaultMaximumIndicesCount = 12288; private readonly VertexBuffer _vertexBuffer; private readonly IndexBuffer _indexBuffer; private readonly VertexPositionColorTexture[] _vertices; private int _vertexCount; private readonly ushort[] _indices; private int _indexCount; private readonly ushort[] _sortedIndices; private readonly GeometryBuilder2D _geometryBuilder; /// <summary> /// Initializes a new instance of the <see cref="Batcher2D" /> class. /// </summary> /// <param name="graphicsDevice">The graphics device.</param> /// <param name="maximumVerticesCount"> /// The maximum number of vertices that can be enqueued before a /// <see cref="Batcher{TDrawCallInfo}.Flush" /> is required. The default value is <code>8192</code>. /// </param> /// <param name="maximumIndicesCount"> /// The maximum number of indices that can be enqueued before a /// <see cref="Batcher{TDrawCallInfo}.Flush" /> is required. The default value is <code>12288</code>. /// </param> /// <param name="maximumDrawCallsCount"> /// The maximum number of <see cref="DrawCallInfo" /> structs that can be enqueued before a /// <see cref="Batcher{TDrawCallInfo}.Flush" /> is required. The default value is <code>2048</code>. /// </param> /// <exception cref="ArgumentNullException"><paramref name="graphicsDevice" />.</exception> /// <exception cref="ArgumentOutOfRangeException"> /// <paramref name="maximumDrawCallsCount" /> is less than or equal /// <code>0</code>, or <paramref name="maximumVerticesCount" /> is less than or equal to <code>0</code>, or, /// <paramref name="maximumVerticesCount" /> is less than or equal to <code>0</code>. /// </exception> public Batcher2D(GraphicsDevice graphicsDevice, ushort maximumVerticesCount = DefaultMaximumVerticesCount, ushort maximumIndicesCount = DefaultMaximumIndicesCount, int maximumDrawCallsCount = DefaultBatchMaximumDrawCallsCount) : base( graphicsDevice, new DefaultEffect(graphicsDevice) { TextureEnabled = true, VertexColorEnabled = true }, maximumDrawCallsCount) { _vertices = new VertexPositionColorTexture[maximumVerticesCount]; _vertexBuffer = new DynamicVertexBuffer(graphicsDevice, VertexPositionColorTexture.VertexDeclaration, maximumVerticesCount, BufferUsage.WriteOnly); _indices = new ushort[maximumIndicesCount]; _sortedIndices = new ushort[maximumIndicesCount]; _indexBuffer = new DynamicIndexBuffer(graphicsDevice, IndexElementSize.SixteenBits, maximumIndicesCount, BufferUsage.WriteOnly); _geometryBuilder = new GeometryBuilder2D(4, 6); } protected override void SortDrawCallsAndBindBuffers() { // Upload the vertices to the GPU and then select that vertex stream for drawing _vertexBuffer.SetData(_vertices, 0, _vertexCount); GraphicsDevice.SetVertexBuffer(_vertexBuffer); Array.Sort(DrawCalls, 0, EnqueuedDrawCallCount); BuildSortedIndices(); // Upload the indices to the GPU and then select that index stream for drawing _indexBuffer.SetData(_sortedIndices, 0, _indexCount); GraphicsDevice.Indices = _indexBuffer; _indexCount = 0; _vertexCount = 0; } private void BuildSortedIndices() { var newDrawCallsCount = 0; DrawCalls[0].StartIndex = 0; var currentDrawCall = DrawCalls[0]; DrawCalls[newDrawCallsCount++] = DrawCalls[0]; var drawCallIndexCount = currentDrawCall.PrimitiveCount * 3; Array.Copy(_indices, currentDrawCall.StartIndex, _sortedIndices, 0, drawCallIndexCount); var sortedIndexCount = drawCallIndexCount; // iterate through sorted draw calls checking if any can now be merged to reduce expensive draw calls to the graphics API // this might need to be changed for next-gen graphics API (Vulkan, Metal, DirectX 12) where the draw calls are not so expensive for (var i = 1; i < EnqueuedDrawCallCount; i++) { currentDrawCall = DrawCalls[i]; drawCallIndexCount = currentDrawCall.PrimitiveCount * 3; Array.Copy(_indices, currentDrawCall.StartIndex, _sortedIndices, sortedIndexCount, drawCallIndexCount); sortedIndexCount += drawCallIndexCount; if (currentDrawCall.TryMerge(ref DrawCalls[newDrawCallsCount - 1])) continue; currentDrawCall.StartIndex = sortedIndexCount; DrawCalls[newDrawCallsCount++] = currentDrawCall; } EnqueuedDrawCallCount = newDrawCallsCount; } /// <summary> /// Submits a draw operation to the <see cref="GraphicsDevice" /> using the specified <see cref="DrawCallInfo"/>. /// </summary> /// <param name="drawCall">The draw call information.</param> protected override void InvokeDrawCall(ref DrawCallInfo drawCall) { GraphicsDevice.DrawIndexedPrimitives(drawCall.PrimitiveType, 0, drawCall.StartIndex, drawCall.PrimitiveCount); } /// <summary> /// Draws a sprite using a specified <see cref="Texture" />, transform <see cref="Matrix2" />, source /// <see cref="Rectangle" />, and an optional /// <see cref="Color" />, origin <see cref="Vector2" />, <see cref="FlipFlags" />, and depth <see cref="float" />. /// </summary> /// <param name="texture">The <see cref="Texture" />.</param> /// <param name="transformMatrix">The transform <see cref="Matrix2" />.</param> /// <param name="sourceRectangle"> /// The texture region <see cref="Rectangle" /> of the <paramref name="texture" />. Use /// <code>null</code> to use the entire <see cref="Texture2D" />. /// </param> /// <param name="color">The <see cref="Color" />. Use <code>null</code> to use the default <see cref="Color.White" />.</param> /// <param name="flags">The <see cref="FlipFlags" />. The default value is <see cref="FlipFlags.None" />.</param> /// <param name="depth">The depth <see cref="float" />. The default value is <code>0</code>.</param> /// <exception cref="InvalidOperationException">The <see cref="Batcher{TDrawCallInfo}.Begin(ref Matrix, ref Matrix, BlendState, SamplerState, DepthStencilState, RasterizerState, Effect)" /> method has not been called.</exception> /// <exception cref="ArgumentNullException"><paramref name="texture" /> is null.</exception> public void DrawSprite(Texture2D texture, ref Matrix2 transformMatrix, ref Rectangle sourceRectangle, Color? color = null, FlipFlags flags = FlipFlags.None, float depth = 0) { _geometryBuilder.BuildSprite(_vertexCount, ref transformMatrix, texture, ref sourceRectangle, color, flags, depth); EnqueueBuiltGeometry(texture, depth); } /// <summary> /// Draws a <see cref="Texture" /> using the specified transform <see cref="Matrix2" /> and an optional /// <see cref="Color" />, origin <see cref="Vector2" />, <see cref="FlipFlags" />, and depth <see cref="float" />. /// </summary> /// <param name="texture">The <see cref="Texture" />.</param> /// <param name="transformMatrix">The transform <see cref="Matrix2" />.</param> /// <param name="color">The <see cref="Color" />. Use <code>null</code> to use the default <see cref="Color.White" />.</param> /// <param name="flags">The <see cref="FlipFlags" />. The default value is <see cref="FlipFlags.None" />.</param> /// <param name="depth">The depth <see cref="float" />. The default value is <code>0</code>.</param> /// <exception cref="InvalidOperationException">The <see cref="Batcher{TDrawCallInfo}.Begin(ref Matrix, ref Matrix, BlendState, SamplerState, DepthStencilState, RasterizerState, Effect)" /> method has not been called.</exception> /// <exception cref="ArgumentNullException"><paramref name="texture" /> is null.</exception> public void DrawTexture(Texture2D texture, ref Matrix2 transformMatrix, Color? color = null, FlipFlags flags = FlipFlags.None, float depth = 0) { var rectangle = default(Rectangle); _geometryBuilder.BuildSprite(_vertexCount, ref transformMatrix, texture, ref rectangle, color, flags, depth); EnqueueBuiltGeometry(texture, depth); } private void EnqueueBuiltGeometry(Texture2D texture, float depth) { if ((_vertexCount + _geometryBuilder.VertexCount > _vertices.Length) || (_indexCount + _geometryBuilder.IndexCount > _indices.Length)) Flush(); var drawCall = new DrawCallInfo(texture, _geometryBuilder.PrimitiveType, _indexCount, _geometryBuilder.PrimitivesCount, depth); Array.Copy(_geometryBuilder.Vertices, 0, _vertices, _vertexCount, _geometryBuilder.VertexCount); _vertexCount += _geometryBuilder.VertexCount; Array.Copy(_geometryBuilder.Indices, 0, _indices, _indexCount, _geometryBuilder.IndexCount); _indexCount += _geometryBuilder.IndexCount; Enqueue(ref drawCall); } /// <summary> /// Draws unicode (UTF-16) characters as sprites using the specified <see cref="BitmapFont" />, text /// <see cref="StringBuilder" />, transform <see cref="Matrix2" /> and optional <see cref="Color" />, origin /// <see cref="Vector2" />, <see cref="FlipFlags" />, and depth <see cref="float" />. /// </summary> /// <param name="bitmapFont">The <see cref="BitmapFont" />.</param> /// <param name="text">The text <see cref="StringBuilder" />.</param> /// <param name="transformMatrix">The transform <see cref="Matrix2" />.</param> /// <param name="color"> /// The <see cref="Color" />. Use <code>null</code> to use the default /// <see cref="Color.White" />. /// </param> /// <param name="flags">The <see cref="FlipFlags" />. The default value is <see cref="FlipFlags.None" />.</param> /// <param name="depth">The depth <see cref="float" />. The default value is <code>0f</code>.</param> /// <exception cref="InvalidOperationException">The <see cref="Batcher{TDrawCallInfo}.Begin(ref Matrix, ref Matrix, BlendState, SamplerState, DepthStencilState, RasterizerState, Effect)" /> method has not been called.</exception> /// <exception cref="ArgumentNullException"><paramref name="bitmapFont" /> is null or <paramref name="text" /> is null.</exception> public void DrawString(BitmapFont bitmapFont, StringBuilder text, ref Matrix2 transformMatrix, Color? color = null, FlipFlags flags = FlipFlags.None, float depth = 0f) { EnsureHasBegun(); if (bitmapFont == null) throw new ArgumentNullException(nameof(bitmapFont)); if (text == null) throw new ArgumentNullException(nameof(text)); var lineSpacing = bitmapFont.LineHeight; var offset = new Vector2(0, 0); BitmapFontRegion lastGlyph = null; for (var i = 0; i < text.Length;) { int character; if (char.IsLowSurrogate(text[i])) { character = char.ConvertToUtf32(text[i - 1], text[i]); i += 2; } else if (char.IsHighSurrogate(text[i])) { character = char.ConvertToUtf32(text[i], text[i - 1]); i += 2; } else { character = text[i]; i += 1; } // ReSharper disable once SwitchStatementMissingSomeCases switch (character) { case '\r': continue; case '\n': offset.X = 0; offset.Y += lineSpacing; lastGlyph = null; continue; } var fontRegion = bitmapFont.GetCharacterRegion(character); if (fontRegion == null) continue; var transform1Matrix = transformMatrix; transform1Matrix.M31 += offset.X + fontRegion.XOffset; transform1Matrix.M32 += offset.Y + fontRegion.YOffset; var textureRegion = fontRegion.TextureRegion; var bounds = textureRegion.Bounds; DrawSprite(textureRegion.Texture, ref transform1Matrix, ref bounds, color, flags, depth); var advance = fontRegion.XAdvance + bitmapFont.LetterSpacing; if (BitmapFont.UseKernings && lastGlyph != null) { int amount; if (lastGlyph.Kernings.TryGetValue(character, out amount)) { advance += amount; } } offset.X += i != text.Length - 1 ? advance : fontRegion.XOffset + fontRegion.Width; lastGlyph = fontRegion; } } /// <summary> /// Draws unicode (UTF-16) characters as sprites using the specified <see cref="BitmapFont" />, text /// <see cref="StringBuilder" />, position <see cref="Vector2" /> and optional <see cref="Color" />, rotation /// <see cref="float" />, origin <see cref="Vector2" />, scale <see cref="Vector2" /> <see cref="FlipFlags" />, and /// depth <see cref="float" />. /// </summary> /// <param name="bitmapFont">The <see cref="BitmapFont" />.</param> /// <param name="text">The text <see cref="string" />.</param> /// <param name="position">The position <see cref="Vector2" />.</param> /// <param name="color"> /// The <see cref="Color" />. Use <code>null</code> to use the default /// <see cref="Color.White" />. /// </param> /// <param name="rotation"> /// The angle <see cref="float" /> (in radians) to rotate each sprite about its <paramref name="origin" />. The default /// value is <code>0f</code>. /// </param> /// <param name="origin"> /// The origin <see cref="Vector2" />. Use <code>null</code> to use the default /// <see cref="Vector2.Zero" />. /// </param> /// <param name="scale"> /// The scale <see cref="Vector2" />. Use <code>null</code> to use the default /// <see cref="Vector2.One" />. /// </param> /// <param name="flags">The <see cref="FlipFlags" />. The default value is <see cref="FlipFlags.None" />.</param> /// <param name="depth">The depth <see cref="float" />. The default value is <code>0f</code></param> /// <exception cref="InvalidOperationException">The <see cref="Batcher{TDrawCallInfo}.Begin(ref Matrix, ref Matrix, BlendState, SamplerState, DepthStencilState, RasterizerState, Effect)" /> method has not been called.</exception> /// <exception cref="ArgumentNullException"><paramref name="bitmapFont" /> is null or <paramref name="text" /> is null.</exception> public void DrawString(BitmapFont bitmapFont, StringBuilder text, Vector2 position, Color? color = null, float rotation = 0f, Vector2? origin = null, Vector2? scale = null, FlipFlags flags = FlipFlags.None, float depth = 0f) { Matrix2 transformMatrix; Matrix2.CreateFrom(position, rotation, scale, origin, out transformMatrix); DrawString(bitmapFont, text, ref transformMatrix, color, flags, depth); } /// <summary> /// Draws unicode (UTF-16) characters as sprites using the specified <see cref="BitmapFont" />, text /// <see cref="string" />, transform <see cref="Matrix2" /> and optional <see cref="Color" />, origin /// <see cref="Vector2" />, <see cref="FlipFlags" />, and depth <see cref="float" />. /// </summary> /// <param name="bitmapFont">The <see cref="BitmapFont" />.</param> /// <param name="text">The text <see cref="string" />.</param> /// <param name="transformMatrix">The transform <see cref="Matrix2" />.</param> /// <param name="color"> /// The <see cref="Color" />. Use <code>null</code> to use the default /// <see cref="Color.White" />. /// </param> /// <param name="flags">The <see cref="FlipFlags" />. The default value is <see cref="FlipFlags.None" />.</param> /// <param name="depth">The depth <see cref="float" />. The default value is <code>0f</code></param> /// <exception cref="InvalidOperationException">The <see cref="Batcher{TDrawCallInfo}.Begin(ref Matrix, ref Matrix, BlendState, SamplerState, DepthStencilState, RasterizerState, Effect)" /> method has not been called.</exception> /// <exception cref="ArgumentNullException"><paramref name="bitmapFont" /> is null or <paramref name="text" /> is null.</exception> public void DrawString(BitmapFont bitmapFont, string text, ref Matrix2 transformMatrix, Color? color = null, FlipFlags flags = FlipFlags.None, float depth = 0f) { EnsureHasBegun(); if (bitmapFont == null) throw new ArgumentNullException(nameof(bitmapFont)); if (text == null) throw new ArgumentNullException(nameof(text)); var glyphs = bitmapFont.GetGlyphs(text); foreach (var glyph in glyphs) { var transform1Matrix = transformMatrix; transform1Matrix.M31 += glyph.Position.X; transform1Matrix.M32 += glyph.Position.Y; var texture = glyph.FontRegion.TextureRegion.Texture; var bounds = texture.Bounds; DrawSprite(texture, ref transform1Matrix, ref bounds, color, flags, depth); } } /// <summary> /// Draws unicode (UTF-16) characters as sprites using the specified <see cref="BitmapFont" />, text /// <see cref="string" />, position <see cref="Vector2" /> and optional <see cref="Color" />, rotation /// <see cref="float" />, origin <see cref="Vector2" />, scale <see cref="Vector2" /> <see cref="FlipFlags" />, and /// depth <see cref="float" />. /// </summary> /// <param name="bitmapFont">The <see cref="BitmapFont" />.</param> /// <param name="text">The text <see cref="string" />.</param> /// <param name="position">The position <see cref="Vector2" />.</param> /// <param name="color"> /// The <see cref="Color" />. Use <code>null</code> to use the default /// <see cref="Color.White" />. /// </param> /// <param name="rotation"> /// The angle <see cref="float" /> (in radians) to rotate each sprite about its <paramref name="origin" />. The default /// value is <code>0f</code>. /// </param> /// <param name="origin"> /// The origin <see cref="Vector2" />. Use <code>null</code> to use the default /// <see cref="Vector2.Zero" />. /// </param> /// <param name="scale"> /// The scale <see cref="Vector2" />. Use <code>null</code> to use the default /// <see cref="Vector2.One" />. /// </param> /// <param name="flags">The <see cref="FlipFlags" />. The default value is <see cref="FlipFlags.None" />.</param> /// <param name="depth">The depth <see cref="float" />. The default value is <code>0f</code></param> /// <exception cref="InvalidOperationException">The <see cref="Batcher{TDrawCallInfo}.Begin(ref Matrix, ref Matrix, BlendState, SamplerState, DepthStencilState, RasterizerState, Effect)" /> method has not been called.</exception> /// <exception cref="ArgumentNullException"><paramref name="bitmapFont" /> is null or <paramref name="text" /> is null.</exception> public void DrawString(BitmapFont bitmapFont, string text, Vector2 position, Color? color = null, float rotation = 0f, Vector2? origin = null, Vector2? scale = null, FlipFlags flags = FlipFlags.None, float depth = 0f) { Matrix2 matrix; Matrix2.CreateFrom(position, rotation, scale, origin, out matrix); DrawString(bitmapFont, text, ref matrix, color, flags, depth); } [StructLayout(LayoutKind.Sequential, Pack = 1)] [EditorBrowsable(EditorBrowsableState.Never)] public struct DrawCallInfo : IBatchDrawCallInfo<DrawCallInfo>, IComparable<DrawCallInfo> { internal readonly PrimitiveType PrimitiveType; internal int StartIndex; internal int PrimitiveCount; internal readonly Texture2D Texture; internal readonly uint TextureKey; internal readonly uint DepthKey; internal unsafe DrawCallInfo(Texture2D texture, PrimitiveType primitiveType, int startIndex, int primitiveCount, float depth) { PrimitiveType = primitiveType; StartIndex = startIndex; PrimitiveCount = primitiveCount; Texture = texture; TextureKey = (uint)RuntimeHelpers.GetHashCode(texture); DepthKey = *(uint*)&depth; } public void SetState(Effect effect) { var textureEffect = effect as ITextureEffect; if (textureEffect != null) textureEffect.Texture = Texture; } public bool TryMerge(ref DrawCallInfo drawCall) { if (PrimitiveType != drawCall.PrimitiveType || TextureKey != drawCall.TextureKey || DepthKey != drawCall.DepthKey) return false; drawCall.PrimitiveCount += PrimitiveCount; return true; } [SuppressMessage("ReSharper", "ImpureMethodCallOnReadonlyValueField")] public int CompareTo(DrawCallInfo other) { var result = TextureKey.CompareTo(other.TextureKey);; if (result != 0) return result; result = DepthKey.CompareTo(other.DepthKey); return result != 0 ? result : ((byte)PrimitiveType).CompareTo((byte)other.PrimitiveType); } } } }
{ "content_hash": "396b48c464c0496ccc263130537f2fd9", "timestamp": "", "source": "github", "line_count": 450, "max_line_length": 237, "avg_line_length": 54.42666666666667, "alnum_prop": 0.5933774293646905, "repo_name": "rafaelalmeidatk/MonoGame.Extended", "id": "e7ec533f74b3176b140d71ebdccca1ca21b7c82a", "size": "24494", "binary": false, "copies": "3", "ref": "refs/heads/develop", "path": "Source/MonoGame.Extended.Graphics/Batcher2D.cs", "mode": "33188", "license": "mit", "language": [ { "name": "Batchfile", "bytes": "267" }, { "name": "C#", "bytes": "1860120" }, { "name": "HLSL", "bytes": "5112" }, { "name": "PowerShell", "bytes": "7471" }, { "name": "Shell", "bytes": "3210" } ], "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/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.almasb.fxglgames</groupId> <artifactId>SpaceRanger</artifactId> <version>1.0</version> <properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <source.version>11</source.version> <!-- plugins --> <maven.compiler.version>3.8.1</maven.compiler.version> <maven.shade.version>3.0.0</maven.shade.version> <jfx.maven.plugin.version>0.0.6</jfx.maven.plugin.version> <fxgl.version>11.17</fxgl.version> <mainClassName>com.almasb.fxglgames.spaceranger.SpaceRangerApp</mainClassName> </properties> <dependencies> <dependency> <groupId>com.github.almasb</groupId> <artifactId>fxgl</artifactId> <version>${fxgl.version}</version> </dependency> </dependencies> <build> <plugins> <plugin> <artifactId>maven-compiler-plugin</artifactId> <version>${maven.compiler.version}</version> <configuration> <release>${source.version}</release> </configuration> </plugin> <plugin> <groupId>org.openjfx</groupId> <artifactId>javafx-maven-plugin</artifactId> <version>${jfx.maven.plugin.version}</version> <configuration> <stripDebug>true</stripDebug> <compress>2</compress> <noHeaderFiles>true</noHeaderFiles> <noManPages>true</noManPages> <launcher>Start-game</launcher> <jlinkImageName>game</jlinkImageName> <jlinkZipName>spaceranger-game</jlinkZipName> <mainClass>${mainClassName}</mainClass> </configuration> </plugin> </plugins> </build> </project>
{ "content_hash": "0dc7a2c0cc15690b18a88a537d9e008a", "timestamp": "", "source": "github", "line_count": 59, "max_line_length": 108, "avg_line_length": 37.47457627118644, "alnum_prop": 0.5689733152419719, "repo_name": "AlmasB/FXGLGames", "id": "076ba9d56bbffedd24722877fd96bb8ab7c38eeb", "size": "2211", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "SpaceRanger/pom.xml", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "1680" }, { "name": "Java", "bytes": "645889" }, { "name": "Kotlin", "bytes": "30338" }, { "name": "Shell", "bytes": "443" }, { "name": "kvlang", "bytes": "17" } ], "symlink_target": "" }
Copyright (c) 2009-2013 Bitcoin Developers Distributed under the MIT/X11 software license, see the accompanying file COPYING or http://www.opensource.org/licenses/mit-license.php. This product includes software developed by the OpenSSL Project for use in the [OpenSSL Toolkit](http://www.openssl.org/). This product includes cryptographic software written by Eric Young ([eay@cryptsoft.com](mailto:eay@cryptsoft.com)), and UPnP software written by Thomas Bernard. UNIX BUILD NOTES ==================== To Build --------------------- cd src/ make -f makefile.unix # Headless AsiaDigiCoin See readme-qt.rst for instructions on building AsiaDigiCoin-Qt, the graphical user interface. Dependencies --------------------- Library Purpose Description ------- ------- ----------- libssl SSL Support Secure communications libdb4.8 Berkeley DB Blockchain & wallet storage libboost Boost C++ Library miniupnpc UPnP Support Optional firewall-jumping support [miniupnpc](http://miniupnp.free.fr/) may be used for UPnP port mapping. It can be downloaded from [here]( http://miniupnp.tuxfamily.org/files/). UPnP support is compiled in and turned off by default. Set USE_UPNP to a different value to control this: USE_UPNP= No UPnP support miniupnp not required USE_UPNP=0 (the default) UPnP support turned off by default at runtime USE_UPNP=1 UPnP support turned on by default at runtime IPv6 support may be disabled by setting: USE_IPV6=0 Disable IPv6 support Licenses of statically linked libraries: Berkeley DB New BSD license with additional requirement that linked software must be free open source Boost MIT-like license miniupnpc New (3-clause) BSD license - Versions used in this release: - GCC 4.3.3 - OpenSSL 1.0.1c - Berkeley DB 4.8.30.NC - Boost 1.37 - miniupnpc 1.6 Dependency Build Instructions: Ubuntu & Debian ---------------------------------------------- Build requirements: sudo apt-get install build-essential sudo apt-get install libssl-dev for Ubuntu 12.04: sudo apt-get install libboost-all-dev db4.8 packages are available [here](https://launchpad.net/~bitcoin/+archive/bitcoin). Ubuntu precise has packages for libdb5.1-dev and libdb5.1++-dev, but using these will break binary wallet compatibility, and is not recommended. for other Ubuntu & Debian: sudo apt-get install libdb4.8-dev sudo apt-get install libdb4.8++-dev sudo apt-get install libboost1.37-dev (If using Boost 1.37, append -mt to the boost libraries in the makefile) Optional: sudo apt-get install libminiupnpc-dev (see USE_UPNP compile flag) Notes ----- The release is built with GCC and then "strip bitcoind" to strip the debug symbols, which reduces the executable size by about 90%. miniupnpc --------- tar -xzvf miniupnpc-1.6.tar.gz cd miniupnpc-1.6 make sudo su make install Berkeley DB ----------- You need Berkeley DB 4.8. If you have to build Berkeley DB yourself: ../dist/configure --enable-cxx make Boost ----- If you need to build Boost yourself: sudo su ./bootstrap.sh ./bjam install Security -------- To help make your AsiaDigiCoin installation more secure by making certain attacks impossible to exploit even if a vulnerability is found, you can take the following measures: * Position Independent Executable Build position independent code to take advantage of Address Space Layout Randomization offered by some kernels. An attacker who is able to cause execution of code at an arbitrary memory location is thwarted if he doesn't know where anything useful is located. The stack and heap are randomly located by default but this allows the code section to be randomly located as well. On an Amd64 processor where a library was not compiled with -fPIC, this will cause an error such as: "relocation R_X86_64_32 against `......' can not be used when making a shared object;" To build with PIE, use: make -f makefile.unix ... -e PIE=1 To test that you have built PIE executable, install scanelf, part of paxutils, and use: scanelf -e ./AsiaDigiCoin The output should contain: TYPE ET_DYN * Non-executable Stack If the stack is executable then trivial stack based buffer overflow exploits are possible if vulnerable buffers are found. By default, bitcoin should be built with a non-executable stack but if one of the libraries it uses asks for an executable stack or someone makes a mistake and uses a compiler extension which requires an executable stack, it will silently build an executable without the non-executable stack protection. To verify that the stack is non-executable after compiling use: `scanelf -e ./AsiaDigiCoin` the output should contain: STK/REL/PTL RW- R-- RW- The STK RW- means that the stack is readable and writeable but not executable.
{ "content_hash": "d397d2046ffcbc0b277c9321a70c8adc", "timestamp": "", "source": "github", "line_count": 154, "max_line_length": 144, "avg_line_length": 32.31818181818182, "alnum_prop": 0.7144866385372715, "repo_name": "slothxx/adcnfork", "id": "5a5b9bfef9cc8a741d40e038d668ed4d0e556517", "size": "4977", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "doc/build-unix.md", "mode": "33188", "license": "mit", "language": [ { "name": "C++", "bytes": "55572" }, { "name": "Groff", "bytes": "18284" }, { "name": "Makefile", "bytes": "885" }, { "name": "NSIS", "bytes": "6042" }, { "name": "Python", "bytes": "69713" }, { "name": "QMake", "bytes": "15559" }, { "name": "Shell", "bytes": "2527" } ], "symlink_target": "" }
'use strict'; var webpack = require('webpack'); var path = require('path'); var sassPaths = [ 'client/stylesheets/', ] .map(function(m){ return path.resolve(__dirname, m); }) .join('&includePaths[]='); module.exports = { context: __dirname + '/client', entry: { main: "./components/App.jsx", WeiqiBoard: ['react', './components/WeiqiBoard.jsx'], vendors: ['page', 'js-csp'] }, output: { path: "./build", filename: "[name].js" }, resolve: { modulesDirectories: [ 'node_modules' ], extensions: ['', '.js', '.jsx'], }, plugins: [ new webpack.optimize.DedupePlugin(), new webpack.optimize.CommonsChunkPlugin('WeiqiBoard', 'WeiqiBoard.js'), new webpack.optimize.CommonsChunkPlugin('vendors', 'shared.js'), new webpack.ProvidePlugin({ regeneratorRuntime: 'regenerator/runtime' }), ], module: { loaders: [ { test: /\.css$/, loader: "style!css" }, { test: /\.scss$/, loader: "style!css!sass?includePaths[]=" + sassPaths}, { test: /\.jsx$|\.js$/, loader: 'jsx?harmony!regenerator'}, { test: /\.jsx$|\.js$/, loader: 'babel-loader'}, //{ test: /jquery.*\.js$/, loader: 'expose?jq4gv' }, { test: /\.(woff|ttf|eot|svg|png)(\?.*)?/, loader: "url-loader" } ] } }
{ "content_hash": "763a002c90c2ce409b67a1f6a3939f03", "timestamp": "", "source": "github", "line_count": 50, "max_line_length": 79, "avg_line_length": 25.56, "alnum_prop": 0.5766823161189358, "repo_name": "gcao/weiqi-app", "id": "ea57028dbb2e814384773461893f87024d377e38", "size": "1278", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "webpack.config.js", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "26058" }, { "name": "JavaScript", "bytes": "122970" }, { "name": "Ruby", "bytes": "2379" } ], "symlink_target": "" }
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.Extensions.Logging; using NServiceBus; using SFA.DAS.CommitmentsV2.Messages.Commands; using SFA.DAS.EAS.Account.Api.Client; using SFA.DAS.Notifications.Messages.Commands; namespace SFA.DAS.CommitmentsV2.MessageHandlers.CommandHandlers { public class SendEmailToEmployerCommandHandler : IHandleMessages<SendEmailToEmployerCommand> { private const string Owner = "Owner"; private const string Transactor = "Transactor"; private readonly ILogger<SendEmailToEmployerCommandHandler> _logger; private readonly IAccountApiClient _accountApiClient; public SendEmailToEmployerCommandHandler(IAccountApiClient accountApiClient, ILogger<SendEmailToEmployerCommandHandler> logger) { _logger = logger; _accountApiClient = accountApiClient; } public async Task Handle(SendEmailToEmployerCommand message, IMessageHandlerContext context) { bool IsOwnerOrTransactor(string role) { return role.Equals(Owner, StringComparison.InvariantCultureIgnoreCase) || role.Equals(Transactor, StringComparison.InvariantCultureIgnoreCase); } try { _logger.LogInformation($"Getting AccountUsers for {message.AccountId}"); var emails = new List<(string Email, string Name)>(); var users = await _accountApiClient.GetAccountUsers(message.AccountId); if (string.IsNullOrWhiteSpace(message.EmailAddress)) { _logger.LogInformation("Sending emails to all AccountUsers who can recieve emails"); emails.AddRange(users.Where(x => x.CanReceiveNotifications && !string.IsNullOrWhiteSpace(x.Email) && IsOwnerOrTransactor(x.Role)) .Select(x => (x.Email, x.Name))); } else { var user = users.FirstOrDefault(x => x.CanReceiveNotifications && message.EmailAddress.Equals(x.Email, StringComparison.InvariantCultureIgnoreCase)); if (user != null) { _logger.LogInformation("Sending email to the explicit user in message"); emails.Add((Email: message.EmailAddress, user.Name)); } } if (emails.Any()) { _logger.LogInformation($"Calling SendEmailCommand for {emails.Count()} emails"); var emailTasks = emails.Select(email => { var tokens = new Dictionary<string, string>(message.Tokens); if (!string.IsNullOrEmpty(message.NameToken)) { tokens.Add(message.NameToken, email.Name); } return context.Send(new SendEmailCommand(message.Template, email.Email, tokens)); }); await Task.WhenAll(emailTasks); } else { _logger.LogWarning($"No Email Addresses found to send Template {message.Template} for AccountId {message.AccountId}"); } } catch (Exception e) { _logger.LogError($"Error processing {nameof(SendEmailToEmployerCommand)}", e); throw; } } } }
{ "content_hash": "ecd25bf9acc905421c3c0eefaa6bc289", "timestamp": "", "source": "github", "line_count": 92, "max_line_length": 138, "avg_line_length": 40.08695652173913, "alnum_prop": 0.5648047722342733, "repo_name": "SkillsFundingAgency/das-commitments", "id": "b15932f5f7f65a0962b049ba3ff95e88881567ab", "size": "3688", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/CommitmentsV2/SFA.DAS.CommitmentsV2.MessageHandlers/CommandHandlers/SendEmailToEmployerCommandHandler.cs", "mode": "33188", "license": "mit", "language": [ { "name": "Batchfile", "bytes": "167" }, { "name": "C#", "bytes": "4259078" }, { "name": "CSS", "bytes": "330874" }, { "name": "F#", "bytes": "20884" }, { "name": "HTML", "bytes": "37546" }, { "name": "JavaScript", "bytes": "30001" }, { "name": "PLpgSQL", "bytes": "477" }, { "name": "PowerShell", "bytes": "7972" }, { "name": "TSQL", "bytes": "99241" } ], "symlink_target": "" }
<!DOCTYPE html> <html> <head> <title>PageLoading Time</title> <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0"/> <META HTTP-Equiv="MinimizeButton" content="visibility:Visible;top:30 " > <META HTTP-Equiv="quitbutton" Content="visibility:visible"> <META HTTP-Equiv="ReloadButton" Content="visibility:visible"> <script type="text/javascript"> var start = new Date().getTime(); var latency ="1"; function onLoad() { var now = new Date().getTime(); latency = now - start; var ele = document.getElementById('res'); ele.innerHTML = "<b> Page Loading time with all Modules : " + latency + "ms</b>"; } </script> <script type="text/javascript" src="/public/api/rhoapi.js" data-api-modules="Barcode,Battery,CardReader,Database,Intent,KeyCapture,KeyState,Log,Mediaplayer,NativeMenubar,NativeTabbar,NativeToolbar,Navbar,Network,Notification,Push,RhoFile,Sensor,SignalIndicators,Signature,System,WebView"></script> <script type="text/javascript"> function startTest(){ var moduleObj = [ {"name":"Barcode", "value":typeof(Rho.Barcode)=="function"}, {"name":"Battery", "value":typeof(Rho.Battery)=="function"}, {"name":"CardReader", "value":typeof(Rho.CardReader)=="function"}, {"name":"Database", "value":typeof(Rho.Database)=="function"}, {"name":"Intent", "value":typeof(Rho.Intent)=="function"}, {"name":"KeyCapture", "value":typeof(Rho.KeyCapture)=="function"}, {"name":"KeyState", "value":typeof(Rho.KeyState)=="function"}, {"name":"Log", "value":typeof(Rho.Log)=="function"}, {"name":"Mediaplayer", "value":typeof(Rho.Mediaplayer)=="function"}, {"name":"NativeMenubar", "value":typeof(Rho.NativeMenubar)=="function"}, {"name":"NativeTabbar", "value":typeof(Rho.NativeTabbar)=="function"}, {"name":"NativeToolbar", "value":typeof(Rho.NativeToolbar)=="function"}, {"name":"Navbar", "value":typeof(Rho.Navbar)=="function"}, {"name":"Network", "value":typeof(Rho.Network)=="function"}, {"name":"NewORM", "value":typeof(Rho.NewORM)=="function"}, {"name":"ORM", "value":typeof(Rho.ORM)=="function"}, {"name":"Push", "value":typeof(Rho.Push)=="function"}, {"name":"Rho.File", "value":typeof(Rho.RhoFile)=="function"}, {"name":"Sensor", "value":typeof(Rho.Sensor)=="function"}, {"name":"SignalIndicators", "value":typeof(Rho.SignalIndicators)=="function"}, {"name":"Signature", "value":typeof(Rho.Signature)=="function"}, {"name":"System", "value":typeof(Rho.System)=="function"}, {"name":"WebView", "value":typeof(Rho.WebView)=="function"}, {"name":"Notification", "value":typeof(Rho.Notification)=="function"}]; moduleObj.forEach(function(val, index){ var table = document.getElementById('result'); var rowCount = table.rows.length; var row = table.insertRow(rowCount); var cell1 = row.insertCell(0); cell1.innerHTML = val.name; var cell2 = row.insertCell(1); cell2.innerHTML = val.value; }); } </script> </head> <body onload="onLoad()"> <h2>Performance Improvement:</h2> <h3 id='res'></h3> <h3>Expected Result: </h3> <ol> <li>Compare the Page Loading time with 4.1 application</li> <li>Also Check for the module inclusion status</li> </ol> <input type="button" id="startTest" onclick="startTest()" value="startTest" /> <table id='result' border> <tr> <td>Module</td> <td>Status</td> </tr> <script type="text/javascript"> </script> </table> </body> </html>
{ "content_hash": "91bd5efa884702b4c89c492c96ac65fa", "timestamp": "", "source": "github", "line_count": 101, "max_line_length": 298, "avg_line_length": 33.73267326732673, "alnum_prop": 0.6791899031405929, "repo_name": "rhomobile/RMS-Testing", "id": "4f660e178385cb2170901efb9bcef5adea7c3ee9", "size": "3407", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "manual/feature_def/manual_common_spec/app/PerformanceImprovement(4.2)/pageWithAllModule.html", "mode": "33188", "license": "mit", "language": [ { "name": "Batchfile", "bytes": "1331" }, { "name": "C", "bytes": "186353" }, { "name": "C#", "bytes": "8479" }, { "name": "C++", "bytes": "39820" }, { "name": "CSS", "bytes": "1139222" }, { "name": "HTML", "bytes": "1567841" }, { "name": "Java", "bytes": "10719" }, { "name": "JavaScript", "bytes": "10349389" }, { "name": "Objective-C", "bytes": "12953" }, { "name": "QMake", "bytes": "3864" }, { "name": "Ruby", "bytes": "6893177" }, { "name": "Shell", "bytes": "1051" }, { "name": "Zimpl", "bytes": "624" } ], "symlink_target": "" }
#include "config.h" #include "core/css/FontFace.h" #include "bindings/core/v8/ExceptionState.h" #include "bindings/core/v8/ScriptState.h" #include "bindings/core/v8/UnionTypesCore.h" #include "core/CSSValueKeywords.h" #include "core/css/BinaryDataFontFaceSource.h" #include "core/css/CSSFontFace.h" #include "core/css/CSSFontFaceSrcValue.h" #include "core/css/CSSFontSelector.h" #include "core/css/CSSPrimitiveValue.h" #include "core/css/CSSUnicodeRangeValue.h" #include "core/css/CSSValueList.h" #include "core/css/FontFaceDescriptors.h" #include "core/css/LocalFontFaceSource.h" #include "core/css/RemoteFontFaceSource.h" #include "core/css/StylePropertySet.h" #include "core/css/StyleRule.h" #include "core/css/parser/CSSParser.h" #include "core/dom/DOMArrayBuffer.h" #include "core/dom/DOMArrayBufferView.h" #include "core/dom/DOMException.h" #include "core/dom/Document.h" #include "core/dom/ExceptionCode.h" #include "core/dom/StyleEngine.h" #include "core/frame/LocalFrame.h" #include "core/frame/Settings.h" #include "core/frame/UseCounter.h" #include "platform/FontFamilyNames.h" #include "platform/SharedBuffer.h" namespace blink { static PassRefPtrWillBeRawPtr<CSSValue> parseCSSValue(const Document* document, const String& s, CSSPropertyID propertyID) { CSSParserContext context(*document, UseCounter::getFrom(document)); return CSSParser::parseSingleValue(propertyID, s, context); } PassRefPtrWillBeRawPtr<FontFace> FontFace::create(ExecutionContext* context, const AtomicString& family, StringOrArrayBufferOrArrayBufferView& source, const FontFaceDescriptors& descriptors) { if (source.isString()) return create(context, family, source.getAsString(), descriptors); if (source.isArrayBuffer()) return create(context, family, source.getAsArrayBuffer(), descriptors); if (source.isArrayBufferView()) return create(context, family, source.getAsArrayBufferView(), descriptors); ASSERT_NOT_REACHED(); return nullptr; } PassRefPtrWillBeRawPtr<FontFace> FontFace::create(ExecutionContext* context, const AtomicString& family, const String& source, const FontFaceDescriptors& descriptors) { RefPtrWillBeRawPtr<FontFace> fontFace = adoptRefWillBeNoop(new FontFace(context, family, descriptors)); RefPtrWillBeRawPtr<CSSValue> src = parseCSSValue(toDocument(context), source, CSSPropertySrc); if (!src || !src->isValueList()) fontFace->setError(DOMException::create(SyntaxError, "The source provided ('" + source + "') could not be parsed as a value list.")); fontFace->initCSSFontFace(toDocument(context), src); return fontFace.release(); } PassRefPtrWillBeRawPtr<FontFace> FontFace::create(ExecutionContext* context, const AtomicString& family, PassRefPtr<DOMArrayBuffer> source, const FontFaceDescriptors& descriptors) { RefPtrWillBeRawPtr<FontFace> fontFace = adoptRefWillBeNoop(new FontFace(context, family, descriptors)); fontFace->initCSSFontFace(static_cast<const unsigned char*>(source->data()), source->byteLength()); return fontFace.release(); } PassRefPtrWillBeRawPtr<FontFace> FontFace::create(ExecutionContext* context, const AtomicString& family, PassRefPtr<DOMArrayBufferView> source, const FontFaceDescriptors& descriptors) { RefPtrWillBeRawPtr<FontFace> fontFace = adoptRefWillBeNoop(new FontFace(context, family, descriptors)); fontFace->initCSSFontFace(static_cast<const unsigned char*>(source->baseAddress()), source->byteLength()); return fontFace.release(); } PassRefPtrWillBeRawPtr<FontFace> FontFace::create(Document* document, const StyleRuleFontFace* fontFaceRule) { const StylePropertySet& properties = fontFaceRule->properties(); // Obtain the font-family property and the src property. Both must be defined. RefPtrWillBeRawPtr<CSSValue> family = properties.getPropertyCSSValue(CSSPropertyFontFamily); if (!family || !family->isValueList()) return nullptr; RefPtrWillBeRawPtr<CSSValue> src = properties.getPropertyCSSValue(CSSPropertySrc); if (!src || !src->isValueList()) return nullptr; RefPtrWillBeRawPtr<FontFace> fontFace = adoptRefWillBeNoop(new FontFace(document)); if (fontFace->setFamilyValue(toCSSValueList(family.get())) && fontFace->setPropertyFromStyle(properties, CSSPropertyFontStyle) && fontFace->setPropertyFromStyle(properties, CSSPropertyFontWeight) && fontFace->setPropertyFromStyle(properties, CSSPropertyFontStretch) && fontFace->setPropertyFromStyle(properties, CSSPropertyUnicodeRange) && fontFace->setPropertyFromStyle(properties, CSSPropertyFontVariant) && fontFace->setPropertyFromStyle(properties, CSSPropertyWebkitFontFeatureSettings) && !fontFace->family().isEmpty() && fontFace->traits().bitfield()) { fontFace->initCSSFontFace(document, src); return fontFace.release(); } return nullptr; } FontFace::FontFace(ExecutionContext* context) : ActiveDOMObject(context) , m_status(Unloaded) { suspendIfNeeded(); } FontFace::FontFace(ExecutionContext* context, const AtomicString& family, const FontFaceDescriptors& descriptors) : ActiveDOMObject(context) , m_family(family) , m_status(Unloaded) { Document* document = toDocument(context); setPropertyFromString(document, descriptors.style(), CSSPropertyFontStyle); setPropertyFromString(document, descriptors.weight(), CSSPropertyFontWeight); // FIXME: we don't implement 'font-strech' property yet so we can't set the property. setPropertyFromString(document, descriptors.unicodeRange(), CSSPropertyUnicodeRange); setPropertyFromString(document, descriptors.variant(), CSSPropertyFontVariant); setPropertyFromString(document, descriptors.featureSettings(), CSSPropertyWebkitFontFeatureSettings); suspendIfNeeded(); } FontFace::~FontFace() { } String FontFace::style() const { return m_style ? m_style->cssText() : "normal"; } String FontFace::weight() const { return m_weight ? m_weight->cssText() : "normal"; } String FontFace::stretch() const { return m_stretch ? m_stretch->cssText() : "normal"; } String FontFace::unicodeRange() const { return m_unicodeRange ? m_unicodeRange->cssText() : "U+0-10FFFF"; } String FontFace::variant() const { return m_variant ? m_variant->cssText() : "normal"; } String FontFace::featureSettings() const { return m_featureSettings ? m_featureSettings->cssText() : "normal"; } void FontFace::setStyle(ExecutionContext* context, const String& s, ExceptionState& exceptionState) { setPropertyFromString(toDocument(context), s, CSSPropertyFontStyle, &exceptionState); } void FontFace::setWeight(ExecutionContext* context, const String& s, ExceptionState& exceptionState) { setPropertyFromString(toDocument(context), s, CSSPropertyFontWeight, &exceptionState); } void FontFace::setStretch(ExecutionContext* context, const String& s, ExceptionState& exceptionState) { setPropertyFromString(toDocument(context), s, CSSPropertyFontStretch, &exceptionState); } void FontFace::setUnicodeRange(ExecutionContext* context, const String& s, ExceptionState& exceptionState) { setPropertyFromString(toDocument(context), s, CSSPropertyUnicodeRange, &exceptionState); } void FontFace::setVariant(ExecutionContext* context, const String& s, ExceptionState& exceptionState) { setPropertyFromString(toDocument(context), s, CSSPropertyFontVariant, &exceptionState); } void FontFace::setFeatureSettings(ExecutionContext* context, const String& s, ExceptionState& exceptionState) { setPropertyFromString(toDocument(context), s, CSSPropertyWebkitFontFeatureSettings, &exceptionState); } void FontFace::setPropertyFromString(const Document* document, const String& s, CSSPropertyID propertyID, ExceptionState* exceptionState) { RefPtrWillBeRawPtr<CSSValue> value = parseCSSValue(document, s, propertyID); if (value && setPropertyValue(value, propertyID)) return; String message = "Failed to set '" + s + "' as a property value."; if (exceptionState) exceptionState->throwDOMException(SyntaxError, message); else setError(DOMException::create(SyntaxError, message)); } bool FontFace::setPropertyFromStyle(const StylePropertySet& properties, CSSPropertyID propertyID) { return setPropertyValue(properties.getPropertyCSSValue(propertyID), propertyID); } bool FontFace::setPropertyValue(PassRefPtrWillBeRawPtr<CSSValue> value, CSSPropertyID propertyID) { switch (propertyID) { case CSSPropertyFontStyle: m_style = value; break; case CSSPropertyFontWeight: m_weight = value; break; case CSSPropertyFontStretch: m_stretch = value; break; case CSSPropertyUnicodeRange: if (value && !value->isValueList()) return false; m_unicodeRange = value; break; case CSSPropertyFontVariant: m_variant = value; break; case CSSPropertyWebkitFontFeatureSettings: m_featureSettings = value; break; default: ASSERT_NOT_REACHED(); return false; } return true; } bool FontFace::setFamilyValue(CSSValueList* familyList) { // The font-family descriptor has to have exactly one family name. if (familyList->length() != 1) return false; CSSPrimitiveValue* familyValue = toCSSPrimitiveValue(familyList->item(0)); AtomicString family; if (familyValue->isString()) { family = AtomicString(familyValue->getStringValue()); } else if (familyValue->isValueID()) { // We need to use the raw text for all the generic family types, since @font-face is a way of actually // defining what font to use for those types. switch (familyValue->getValueID()) { case CSSValueSerif: family = FontFamilyNames::webkit_serif; break; case CSSValueSansSerif: family = FontFamilyNames::webkit_sans_serif; break; case CSSValueCursive: family = FontFamilyNames::webkit_cursive; break; case CSSValueFantasy: family = FontFamilyNames::webkit_fantasy; break; case CSSValueMonospace: family = FontFamilyNames::webkit_monospace; break; case CSSValueWebkitPictograph: family = FontFamilyNames::webkit_pictograph; break; default: return false; } } m_family = family; return true; } String FontFace::status() const { switch (m_status) { case Unloaded: return "unloaded"; case Loading: return "loading"; case Loaded: return "loaded"; case Error: return "error"; default: ASSERT_NOT_REACHED(); } return emptyString(); } void FontFace::setLoadStatus(LoadStatus status) { m_status = status; ASSERT(m_status != Error || m_error); if (m_status == Loaded || m_status == Error) { if (m_loadedProperty) { if (m_status == Loaded) m_loadedProperty->resolve(this); else m_loadedProperty->reject(m_error.get()); } WillBeHeapVector<RefPtrWillBeMember<LoadFontCallback>> callbacks; m_callbacks.swap(callbacks); for (size_t i = 0; i < callbacks.size(); ++i) { if (m_status == Loaded) callbacks[i]->notifyLoaded(this); else callbacks[i]->notifyError(this); } } } void FontFace::setError(PassRefPtrWillBeRawPtr<DOMException> error) { if (!m_error) m_error = error ? error : DOMException::create(NetworkError); setLoadStatus(Error); } ScriptPromise FontFace::fontStatusPromise(ScriptState* scriptState) { if (!m_loadedProperty) { m_loadedProperty = new LoadedProperty(scriptState->executionContext(), this, LoadedProperty::Loaded); if (m_status == Loaded) m_loadedProperty->resolve(this); else if (m_status == Error) m_loadedProperty->reject(m_error.get()); } return m_loadedProperty->promise(scriptState->world()); } ScriptPromise FontFace::load(ScriptState* scriptState) { loadInternal(scriptState->executionContext()); return fontStatusPromise(scriptState); } void FontFace::loadWithCallback(PassRefPtrWillBeRawPtr<LoadFontCallback> callback, ExecutionContext* context) { loadInternal(context); if (m_status == Loaded) callback->notifyLoaded(this); else if (m_status == Error) callback->notifyError(this); else m_callbacks.append(callback); } void FontFace::loadInternal(ExecutionContext* context) { if (m_status != Unloaded) return; m_cssFontFace->load(); toDocument(context)->styleEngine().fontSelector()->fontLoader()->loadPendingFonts(); } FontTraits FontFace::traits() const { FontStyle style = FontStyleNormal; if (m_style) { if (!m_style->isPrimitiveValue()) return 0; switch (toCSSPrimitiveValue(m_style.get())->getValueID()) { case CSSValueNormal: style = FontStyleNormal; break; case CSSValueItalic: case CSSValueOblique: style = FontStyleItalic; break; default: break; } } FontWeight weight = FontWeight400; if (m_weight) { if (!m_weight->isPrimitiveValue()) return 0; switch (toCSSPrimitiveValue(m_weight.get())->getValueID()) { case CSSValueBold: case CSSValue700: weight = FontWeight700; break; case CSSValueNormal: case CSSValue400: weight = FontWeight400; break; case CSSValue900: weight = FontWeight900; break; case CSSValue800: weight = FontWeight800; break; case CSSValue600: weight = FontWeight600; break; case CSSValue500: weight = FontWeight500; break; case CSSValue300: weight = FontWeight300; break; case CSSValue200: weight = FontWeight200; break; case CSSValue100: weight = FontWeight100; break; // Although 'lighter' and 'bolder' are valid keywords for font-weights, they are invalid // inside font-face rules so they are ignored. Reference: http://www.w3.org/TR/css3-fonts/#descdef-font-weight. case CSSValueLighter: case CSSValueBolder: break; default: ASSERT_NOT_REACHED(); break; } } FontVariant variant = FontVariantNormal; if (RefPtrWillBeRawPtr<CSSValue> fontVariant = m_variant) { // font-variant descriptor can be a value list. if (fontVariant->isPrimitiveValue()) { RefPtrWillBeRawPtr<CSSValueList> list = CSSValueList::createCommaSeparated(); list->append(fontVariant); fontVariant = list; } else if (!fontVariant->isValueList()) { return 0; } CSSValueList* variantList = toCSSValueList(fontVariant.get()); unsigned numVariants = variantList->length(); if (!numVariants) return 0; for (unsigned i = 0; i < numVariants; ++i) { switch (toCSSPrimitiveValue(variantList->item(i))->getValueID()) { case CSSValueNormal: variant = FontVariantNormal; break; case CSSValueSmallCaps: variant = FontVariantSmallCaps; break; default: break; } } } return FontTraits(style, variant, weight, FontStretchNormal); } static PassOwnPtrWillBeRawPtr<CSSFontFace> createCSSFontFace(FontFace* fontFace, CSSValue* unicodeRange) { Vector<CSSFontFace::UnicodeRange> ranges; if (CSSValueList* rangeList = toCSSValueList(unicodeRange)) { unsigned numRanges = rangeList->length(); for (unsigned i = 0; i < numRanges; i++) { CSSUnicodeRangeValue* range = toCSSUnicodeRangeValue(rangeList->item(i)); ranges.append(CSSFontFace::UnicodeRange(range->from(), range->to())); } } return adoptPtrWillBeNoop(new CSSFontFace(fontFace, ranges)); } void FontFace::initCSSFontFace(Document* document, PassRefPtrWillBeRawPtr<CSSValue> src) { m_cssFontFace = createCSSFontFace(this, m_unicodeRange.get()); if (m_error) return; // Each item in the src property's list is a single CSSFontFaceSource. Put them all into a CSSFontFace. ASSERT(src); ASSERT(src->isValueList()); CSSValueList* srcList = toCSSValueList(src.get()); int srcLength = srcList->length(); for (int i = 0; i < srcLength; i++) { // An item in the list either specifies a string (local font name) or a URL (remote font to download). CSSFontFaceSrcValue* item = toCSSFontFaceSrcValue(srcList->item(i)); OwnPtrWillBeRawPtr<CSSFontFaceSource> source = nullptr; if (!item->isLocal()) { Settings* settings = document ? document->frame() ? document->frame()->settings() : 0 : 0; bool allowDownloading = settings && settings->downloadableBinaryFontsEnabled(); if (allowDownloading && item->isSupportedFormat() && document) { FontResource* fetched = item->fetch(document); if (fetched) { FontLoader* fontLoader = document->styleEngine().fontSelector()->fontLoader(); source = adoptPtrWillBeNoop(new RemoteFontFaceSource(fetched, fontLoader)); } } } else { source = adoptPtrWillBeNoop(new LocalFontFaceSource(item->resource())); } if (source) m_cssFontFace->addSource(source.release()); } } void FontFace::initCSSFontFace(const unsigned char* data, unsigned size) { m_cssFontFace = createCSSFontFace(this, m_unicodeRange.get()); if (m_error) return; RefPtr<SharedBuffer> buffer = SharedBuffer::create(data, size); OwnPtrWillBeRawPtr<BinaryDataFontFaceSource> source = adoptPtrWillBeNoop(new BinaryDataFontFaceSource(buffer.get())); if (source->isValid()) setLoadStatus(Loaded); else setError(DOMException::create(SyntaxError, "Invalid font data in ArrayBuffer.")); m_cssFontFace->addSource(source.release()); } DEFINE_TRACE(FontFace) { visitor->trace(m_src); visitor->trace(m_style); visitor->trace(m_weight); visitor->trace(m_stretch); visitor->trace(m_unicodeRange); visitor->trace(m_variant); visitor->trace(m_featureSettings); visitor->trace(m_error); visitor->trace(m_loadedProperty); visitor->trace(m_cssFontFace); visitor->trace(m_callbacks); ActiveDOMObject::trace(visitor); } bool FontFace::hadBlankText() const { return m_cssFontFace->hadBlankText(); } bool FontFace::hasPendingActivity() const { return m_status == Loading && executionContext() && !executionContext()->activeDOMObjectsAreStopped(); } } // namespace blink
{ "content_hash": "5231c98bcccb68d1383d8e2ba999fac0", "timestamp": "", "source": "github", "line_count": 561, "max_line_length": 190, "avg_line_length": 34.28163992869875, "alnum_prop": 0.6774646422628952, "repo_name": "sgraham/nope", "id": "c34574b89d34dae03d1562df94128fe3527ddaaa", "size": "20794", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "third_party/WebKit/Source/core/css/FontFace.cpp", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "AppleScript", "bytes": "6973" }, { "name": "Arduino", "bytes": "464" }, { "name": "Assembly", "bytes": "39967" }, { "name": "C", "bytes": "4061434" }, { "name": "C++", "bytes": "279546186" }, { "name": "CMake", "bytes": "27212" }, { "name": "CSS", "bytes": "919339" }, { "name": "Emacs Lisp", "bytes": "988" }, { "name": "Go", "bytes": "13628" }, { "name": "Groff", "bytes": "5283" }, { "name": "HTML", "bytes": "15989749" }, { "name": "Java", "bytes": "7541683" }, { "name": "JavaScript", "bytes": "32372588" }, { "name": "Lua", "bytes": "16189" }, { "name": "Makefile", "bytes": "40513" }, { "name": "Objective-C", "bytes": "1584184" }, { "name": "Objective-C++", "bytes": "8249988" }, { "name": "PHP", "bytes": "97817" }, { "name": "PLpgSQL", "bytes": "169060" }, { "name": "Perl", "bytes": "63937" }, { "name": "Protocol Buffer", "bytes": "427339" }, { "name": "Python", "bytes": "8346306" }, { "name": "Scheme", "bytes": "10604" }, { "name": "Shell", "bytes": "844553" }, { "name": "Standard ML", "bytes": "4965" }, { "name": "VimL", "bytes": "4075" }, { "name": "XSLT", "bytes": "418" }, { "name": "nesC", "bytes": "18347" } ], "symlink_target": "" }
// Copyright (c) 2009-2010 Satoshi Nakamoto // Copyright (c) 2009-2012 The Bitcoin developers // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #ifndef BITCOIN_UTIL_H #define BITCOIN_UTIL_H #include "uint256.h" #include <stdarg.h> #ifndef WIN32 #include <sys/types.h> #include <sys/time.h> #include <sys/resource.h> #else typedef int pid_t; /* define for Windows compatibility */ #endif #include <map> #include <list> #include <utility> #include <vector> #include <string> #include <boost/thread.hpp> #include <boost/filesystem.hpp> #include <boost/filesystem/path.hpp> #include <boost/date_time/gregorian/gregorian_types.hpp> #include <boost/date_time/posix_time/posix_time_types.hpp> #include "netbase.h" // for AddTimeData typedef long long int64; typedef unsigned long long uint64; static const mpq COIN = mpq("100000000/1"); static const mpq CENT = mpq("1000000/1"); #define loop for (;;) #define BEGIN(a) ((char*)&(a)) #define END(a) ((char*)&((&(a))[1])) #define UBEGIN(a) ((unsigned char*)&(a)) #define UEND(a) ((unsigned char*)&((&(a))[1])) #define ARRAYLEN(array) (sizeof(array)/sizeof((array)[0])) #ifndef PRI64d #if defined(_MSC_VER) || defined(__MSVCRT__) #define PRI64d "I64d" #define PRI64u "I64u" #define PRI64x "I64x" #else #define PRI64d "lld" #define PRI64u "llu" #define PRI64x "llx" #endif #endif /* Format characters for (s)size_t and ptrdiff_t */ #if defined(_MSC_VER) || defined(__MSVCRT__) /* (s)size_t and ptrdiff_t have the same size specifier in MSVC: http://msdn.microsoft.com/en-us/library/tcxf1dw6%28v=vs.100%29.aspx */ #define PRIszx "Ix" #define PRIszu "Iu" #define PRIszd "Id" #define PRIpdx "Ix" #define PRIpdu "Iu" #define PRIpdd "Id" #else /* C99 standard */ #define PRIszx "zx" #define PRIszu "zu" #define PRIszd "zd" #define PRIpdx "tx" #define PRIpdu "tu" #define PRIpdd "td" #endif // This is needed because the foreach macro can't get over the comma in pair<t1, t2> #define PAIRTYPE(t1, t2) std::pair<t1, t2> // Align by increasing pointer, must have extra space at end of buffer template <size_t nBytes, typename T> T* alignup(T* p) { union { T* ptr; size_t n; } u; u.ptr = p; u.n = (u.n + (nBytes-1)) & ~(nBytes-1); return u.ptr; } #ifdef WIN32 #define MSG_NOSIGNAL 0 #define MSG_DONTWAIT 0 #ifndef S_IRUSR #define S_IRUSR 0400 #define S_IWUSR 0200 #endif #else #define MAX_PATH 1024 #endif inline void MilliSleep(int64 n) { #if BOOST_VERSION >= 105000 boost::this_thread::sleep_for(boost::chrono::milliseconds(n)); #else boost::this_thread::sleep(boost::posix_time::milliseconds(n)); #endif } /* This GNU C extension enables the compiler to check the format string against the parameters provided. * X is the number of the "format string" parameter, and Y is the number of the first variadic parameter. * Parameters count from 1. */ #ifdef __GNUC__ #define ATTR_WARN_PRINTF(X,Y) __attribute__((format(printf,X,Y))) #else #define ATTR_WARN_PRINTF(X,Y) #endif extern std::map<std::string, std::string> mapArgs; extern std::map<std::string, std::vector<std::string> > mapMultiArgs; extern bool fDebug; extern bool fDebugNet; extern bool fPrintToConsole; extern bool fPrintToDebugger; extern bool fDaemon; extern bool fServer; extern bool fCommandLine; extern std::string strMiscWarning; extern bool fTestNet; extern bool fNoListen; extern bool fLogTimestamps; extern volatile bool fReopenDebugLog; void RandAddSeed(); void RandAddSeedPerfmon(); int ATTR_WARN_PRINTF(1,2) OutputDebugStringF(const char* pszFormat, ...); /* Rationale for the real_strprintf / strprintf construction: It is not allowed to use va_start with a pass-by-reference argument. (C++ standard, 18.7, paragraph 3). Use a dummy argument to work around this, and use a macro to keep similar semantics. */ /** Overload strprintf for char*, so that GCC format type warnings can be given */ std::string ATTR_WARN_PRINTF(1,3) real_strprintf(const char *format, int dummy, ...); /** Overload strprintf for std::string, to be able to use it with _ (translation). * This will not support GCC format type warnings (-Wformat) so be careful. */ std::string real_strprintf(const std::string &format, int dummy, ...); #define strprintf(format, ...) real_strprintf(format, 0, __VA_ARGS__) std::string vstrprintf(const char *format, va_list ap); bool ATTR_WARN_PRINTF(1,2) error(const char *format, ...); /* Redefine printf so that it directs output to debug.log * * Do this *after* defining the other printf-like functions, because otherwise the * __attribute__((format(printf,X,Y))) gets expanded to __attribute__((format(OutputDebugStringF,X,Y))) * which confuses gcc. */ #define printf OutputDebugStringF void LogException(std::exception* pex, const char* pszThread); void PrintException(std::exception* pex, const char* pszThread); void PrintExceptionContinue(std::exception* pex, const char* pszThread); void ParseString(const std::string& str, char c, std::vector<std::string>& v); std::string FormatMoney(int64 n, bool fPlus=false); std::string FormatMoney(const mpq &q, bool fPlus=false); bool ParseMoney(const std::string& str, mpq& nRet); bool ParseMoney(const char* pszIn, mpq& nRet); std::vector<unsigned char> ParseHex(const char* psz); std::vector<unsigned char> ParseHex(const std::string& str); bool IsHex(const std::string& str); std::vector<unsigned char> DecodeBase64(const char* p, bool* pfInvalid = NULL); std::string DecodeBase64(const std::string& str); std::string EncodeBase64(const unsigned char* pch, size_t len); std::string EncodeBase64(const std::string& str); std::vector<unsigned char> DecodeBase32(const char* p, bool* pfInvalid = NULL); std::string DecodeBase32(const std::string& str); std::string EncodeBase32(const unsigned char* pch, size_t len); std::string EncodeBase32(const std::string& str); void ParseParameters(int argc, const char*const argv[]); bool WildcardMatch(const char* psz, const char* mask); bool WildcardMatch(const std::string& str, const std::string& mask); void FileCommit(FILE *fileout); int GetFilesize(FILE* file); bool TruncateFile(FILE *file, unsigned int length); int RaiseFileDescriptorLimit(int nMinFD); void AllocateFileRange(FILE *file, unsigned int offset, unsigned int length); bool RenameOver(boost::filesystem::path src, boost::filesystem::path dest); boost::filesystem::path GetDefaultDataDir(); const boost::filesystem::path &GetDataDir(bool fNetSpecific = true); boost::filesystem::path GetConfigFile(); boost::filesystem::path GetPidFile(); void CreatePidFile(const boost::filesystem::path &path, pid_t pid); void ReadConfigFile(std::map<std::string, std::string>& mapSettingsRet, std::map<std::string, std::vector<std::string> >& mapMultiSettingsRet); #ifdef WIN32 boost::filesystem::path GetSpecialFolderPath(int nFolder, bool fCreate = true); #endif boost::filesystem::path GetTempPath(); void ShrinkDebugFile(); int GetRandInt(int nMax); uint64 GetRand(uint64 nMax); uint256 GetRandHash(); int64 GetTime(); void SetMockTime(int64 nMockTimeIn); int64 GetAdjustedTime(); int64 GetTimeOffset(); std::string FormatFullVersion(); std::string FormatSubVersion(const std::string& name, int nClientVersion, const std::vector<std::string>& comments); void AddTimeData(const CNetAddr& ip, int64 nTime); void runCommand(std::string strCommand); inline std::string i64tostr(int64 n) { return strprintf("%"PRI64d, n); } inline std::string itostr(int n) { return strprintf("%d", n); } inline int64 atoi64(const char* psz) { #ifdef _MSC_VER return _atoi64(psz); #else return strtoll(psz, NULL, 10); #endif } inline int64 atoi64(const std::string& str) { #ifdef _MSC_VER return _atoi64(str.c_str()); #else return strtoll(str.c_str(), NULL, 10); #endif } inline int atoi(const std::string& str) { return atoi(str.c_str()); } inline int roundint(double d) { return (int)(d > 0 ? d + 0.5 : d - 0.5); } inline int64 roundint64(double d) { return (int64)(d > 0 ? d + 0.5 : d - 0.5); } inline int64 abs64(int64 n) { return (n >= 0 ? n : -n); } mpz inline i64_to_mpz(int64 nValue) { return mpz(i64tostr(nValue)); } mpq inline i64_to_mpq(int64 nValue) { return i64_to_mpz(nValue); } int64 inline mpz_to_i64(const mpz &zValue) { static mpz MPZ_MAX_I64( "9223372036854775807"); static mpz MPZ_MIN_I64("-9223372036854775808"); if (zValue < MPZ_MIN_I64 || zValue > MPZ_MAX_I64) throw std::runtime_error("mpz_to_i64 : input exceeds range of int64 type"); int64 result = 0; mpz tmp(zValue); bool sign = tmp < 0; if ( sign ) tmp = -tmp; result = atoi64(tmp.get_str()); return (sign ? -result : result); } enum { ROUND_TIES_TO_EVEN, ROUND_TOWARDS_ZERO, ROUND_AWAY_FROM_ZERO, ROUND_TOWARD_POSITIVE, ROUND_TOWARD_NEGATIVE, ROUND_SIGNAL, }; mpq RoundAbsolute(const mpq &q, int mode=ROUND_TIES_TO_EVEN, int magnitude=0); template<typename T> std::string HexStr(const T itbegin, const T itend, bool fSpaces=false) { std::string rv; static const char hexmap[16] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' }; rv.reserve((itend-itbegin)*3); for(T it = itbegin; it < itend; ++it) { unsigned char val = (unsigned char)(*it); if(fSpaces && it != itbegin) rv.push_back(' '); rv.push_back(hexmap[val>>4]); rv.push_back(hexmap[val&15]); } return rv; } inline std::string HexStr(const std::vector<unsigned char>& vch, bool fSpaces=false) { return HexStr(vch.begin(), vch.end(), fSpaces); } template<typename T> void PrintHex(const T pbegin, const T pend, const char* pszFormat="%s", bool fSpaces=true) { printf(pszFormat, HexStr(pbegin, pend, fSpaces).c_str()); } inline void PrintHex(const std::vector<unsigned char>& vch, const char* pszFormat="%s", bool fSpaces=true) { printf(pszFormat, HexStr(vch, fSpaces).c_str()); } inline int64 GetPerformanceCounter() { int64 nCounter = 0; #ifdef WIN32 QueryPerformanceCounter((LARGE_INTEGER*)&nCounter); #else timeval t; gettimeofday(&t, NULL); nCounter = (int64) t.tv_sec * 1000000 + t.tv_usec; #endif return nCounter; } inline int64 GetTimeMillis() { return (boost::posix_time::ptime(boost::posix_time::microsec_clock::universal_time()) - boost::posix_time::ptime(boost::gregorian::date(1970,1,1))).total_milliseconds(); } inline int64 GetTimeMicros() { return (boost::posix_time::ptime(boost::posix_time::microsec_clock::universal_time()) - boost::posix_time::ptime(boost::gregorian::date(1970,1,1))).total_microseconds(); } inline std::string DateTimeStrFormat(const char* pszFormat, int64 nTime) { time_t n = nTime; struct tm* ptmTime = gmtime(&n); char pszTime[200]; strftime(pszTime, sizeof(pszTime), pszFormat, ptmTime); return pszTime; } template<typename T> void skipspaces(T& it) { while (isspace(*it)) ++it; } inline bool IsSwitchChar(char c) { #ifdef WIN32 return c == '-' || c == '/'; #else return c == '-'; #endif } /** * Return string argument or default value * * @param strArg Argument to get (e.g. "-foo") * @param default (e.g. "1") * @return command-line argument or default value */ std::string GetArg(const std::string& strArg, const std::string& strDefault); /** * Return integer argument or default value * * @param strArg Argument to get (e.g. "-foo") * @param default (e.g. 1) * @return command-line argument (0 if invalid number) or default value */ int64 GetArg(const std::string& strArg, int64 nDefault); /** * Return boolean argument or default value * * @param strArg Argument to get (e.g. "-foo") * @param default (true or false) * @return command-line argument or default value */ bool GetBoolArg(const std::string& strArg, bool fDefault=false); /** * Set an argument if it doesn't already have a value * * @param strArg Argument to set (e.g. "-foo") * @param strValue Value (e.g. "1") * @return true if argument gets set, false if it already had a value */ bool SoftSetArg(const std::string& strArg, const std::string& strValue); /** * Set a boolean argument if it doesn't already have a value * * @param strArg Argument to set (e.g. "-foo") * @param fValue Value (e.g. false) * @return true if argument gets set, false if it already had a value */ bool SoftSetBoolArg(const std::string& strArg, bool fValue); /** * MWC RNG of George Marsaglia * This is intended to be fast. It has a period of 2^59.3, though the * least significant 16 bits only have a period of about 2^30.1. * * @return random value */ extern uint32_t insecure_rand_Rz; extern uint32_t insecure_rand_Rw; static inline uint32_t insecure_rand(void) { insecure_rand_Rz = 36969 * (insecure_rand_Rz & 65535) + (insecure_rand_Rz >> 16); insecure_rand_Rw = 18000 * (insecure_rand_Rw & 65535) + (insecure_rand_Rw >> 16); return (insecure_rand_Rw << 16) + insecure_rand_Rz; } /** * Seed insecure_rand using the random pool. * @param Deterministic Use a determinstic seed */ void seed_insecure_rand(bool fDeterministic=false); /** Median filter over a stream of values. * Returns the median of the last N numbers */ template <typename T> class CMedianFilter { private: std::vector<T> vValues; std::vector<T> vSorted; unsigned int nSize; public: CMedianFilter(unsigned int size, T initial_value): nSize(size) { vValues.reserve(size); vValues.push_back(initial_value); vSorted = vValues; } void input(T value) { if(vValues.size() == nSize) { vValues.erase(vValues.begin()); } vValues.push_back(value); vSorted.resize(vValues.size()); std::copy(vValues.begin(), vValues.end(), vSorted.begin()); std::sort(vSorted.begin(), vSorted.end()); } T median() const { int size = vSorted.size(); assert(size>0); if(size & 1) // Odd number of elements { return vSorted[size/2]; } else // Even number of elements { return (vSorted[size/2-1] + vSorted[size/2]) / 2; } } int size() const { return vValues.size(); } std::vector<T> sorted () const { return vSorted; } }; bool NewThread(void(*pfn)(void*), void* parg); #ifdef WIN32 inline void SetThreadPriority(int nPriority) { SetThreadPriority(GetCurrentThread(), nPriority); } #else #define THREAD_PRIORITY_LOWEST PRIO_MAX #define THREAD_PRIORITY_BELOW_NORMAL 2 #define THREAD_PRIORITY_NORMAL 0 #define THREAD_PRIORITY_ABOVE_NORMAL 0 inline void SetThreadPriority(int nPriority) { // It's unclear if it's even possible to change thread priorities on Linux, // but we really and truly need it for the generation threads. #ifdef PRIO_THREAD setpriority(PRIO_THREAD, 0, nPriority); #else setpriority(PRIO_PROCESS, 0, nPriority); #endif } inline void ExitThread(size_t nExitCode) { pthread_exit((void*)nExitCode); } #endif void RenameThread(const char* name); inline uint32_t ByteReverse(uint32_t value) { value = ((value & 0xFF00FF00) >> 8) | ((value & 0x00FF00FF) << 8); return (value<<16) | (value>>16); } // Standard wrapper for do-something-forever thread functions. // "Forever" really means until the thread is interrupted. // Use it like: // new boost::thread(boost::bind(&LoopForever<void (*)()>, "dumpaddr", &DumpAddresses, 900000)); // or maybe: // boost::function<void()> f = boost::bind(&FunctionWithArg, argument); // threadGroup.create_thread(boost::bind(&LoopForever<boost::function<void()> >, "nothing", f, milliseconds)); template <typename Callable> void LoopForever(const char* name, Callable func, int64 msecs) { std::string s = strprintf("bitcoin-%s", name); RenameThread(s.c_str()); printf("%s thread start\n", name); try { while (1) { MilliSleep(msecs); func(); } } catch (boost::thread_interrupted) { printf("%s thread stop\n", name); throw; } catch (std::exception& e) { PrintException(&e, name); } catch (...) { PrintException(NULL, name); } } // .. and a wrapper that just calls func once template <typename Callable> void TraceThread(const char* name, Callable func) { std::string s = strprintf("bitcoin-%s", name); RenameThread(s.c_str()); try { printf("%s thread start\n", name); func(); printf("%s thread exit\n", name); } catch (boost::thread_interrupted) { printf("%s thread interrupt\n", name); throw; } catch (std::exception& e) { PrintException(&e, name); } catch (...) { PrintException(NULL, name); } } #endif
{ "content_hash": "d11f7f4146fee934d90337feedd7551f", "timestamp": "", "source": "github", "line_count": 624, "max_line_length": 143, "avg_line_length": 27.556089743589745, "alnum_prop": 0.6650770572840942, "repo_name": "Sphere2013/GlobeCrypto", "id": "8e2a6690e744ecb91e604a87193b848c3a18275a", "size": "17195", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/util.h", "mode": "33188", "license": "mit", "language": [ { "name": "C", "bytes": "102405" }, { "name": "C++", "bytes": "2442641" }, { "name": "CSS", "bytes": "1127" }, { "name": "IDL", "bytes": "13841" }, { "name": "Objective-C", "bytes": "2656" }, { "name": "Python", "bytes": "38730" }, { "name": "Ruby", "bytes": "5362" }, { "name": "Shell", "bytes": "5888" }, { "name": "TypeScript", "bytes": "5357216" } ], "symlink_target": "" }
layout: page title: Tushar Joshi subtitle: I Like to Solve Problems. --- <p align="justify">Hi! I’m Tushar Joshi, a chemical engineer, and a person who is passionate about new technology and entrepreneurship. With the hunger to learn, get involved and ‘hustle’, I often involve myself with opportunities that differ from my peers. I am inspired by challenging the norm, and utilizing my analytical skills to solve problems.</p> <p></p> <p align="justify">I am always interested in researching new technologies, and how they can be implemented for the everyday consumer. Click the link above to find out more about <a href="http://tusharjoshi1.com/projects/">projects</a> and <a href="http://tusharjoshi1.com/initiatives/">initiatives</a> I have been a part of.</p>
{ "content_hash": "e74e210737a3c6caa25f3df10f105b1f", "timestamp": "", "source": "github", "line_count": 9, "max_line_length": 354, "avg_line_length": 85.22222222222223, "alnum_prop": 0.7666232073011734, "repo_name": "tusharjoshi1/tusharjoshi1.github.io", "id": "ecfac86d519da53d66ebd7a558e9c97cf740755b", "size": "777", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "index.html", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "16773" }, { "name": "HTML", "bytes": "21524" }, { "name": "JavaScript", "bytes": "4356" }, { "name": "Ruby", "bytes": "4363" } ], "symlink_target": "" }
<?php class IMDT_Util_Acl { private static $_instance; private $_aclRules; public static function getInstance() { if (self::$_instance == null) { self::$_instance = new self(); } return self::$_instance; } public function __construct() { $aclNs = new Zend_Session_Namespace('acl'); $this->_aclRules = $aclNs->aclRules; } public function isAllowed($resource, $privilege) { return $this->_aclRules->isAllowed('loggedUser', strtoupper($resource), strtoupper($privilege)); } public function getAclRules() { return $this->_aclRules; } }
{ "content_hash": "8ec2f68b6f45cd089dc632bd7481bde8", "timestamp": "", "source": "github", "line_count": 29, "max_line_length": 104, "avg_line_length": 23.344827586206897, "alnum_prop": 0.5568685376661743, "repo_name": "BBBManager/web-ui", "id": "33e97777846f755a9b496d124b805f3a07fd136c", "size": "677", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "private/library/IMDT/Util/Acl.php", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "ApacheConf", "bytes": "422" }, { "name": "Batchfile", "bytes": "1036" }, { "name": "CSS", "bytes": "97940" }, { "name": "HTML", "bytes": "481284" }, { "name": "JavaScript", "bytes": "595867" }, { "name": "PHP", "bytes": "17078840" }, { "name": "PowerShell", "bytes": "1028" } ], "symlink_target": "" }
package xworker.swt.xworker.attributeEditor; import org.xmeta.ActionContext; import org.xmeta.Thing; import org.xmeta.World; import xworker.swt.util.SwtUtils; import xworker.swt.util.ThingCompositeCreator; public class TwoInputs { public static Object create(ActionContext actionContext) { Thing self = actionContext.getObject("self"); String type = self.getString("type"); Thing prototype = null; if("date".equals(type)) { prototype = World.getInstance().getThing("xworker.swt.xworker.attributeEditor.prototypes.TwoInputsShell/@Composite1"); }else { prototype = World.getInstance().getThing("xworker.swt.xworker.attributeEditor.prototypes.TwoInputsShell/@Composite"); } ThingCompositeCreator cc = SwtUtils.createCompositeCreator(self, actionContext); cc.setCompositeThing(prototype); Object obj = cc.create(); actionContext.g().put(self.getString("input1Name"), cc.getNewActionContext().get("input1")); actionContext.g().put(self.getString("input2Name"), cc.getNewActionContext().get("input2")); return obj; } }
{ "content_hash": "4400705538ecba8cc5bf21e898a734b1", "timestamp": "", "source": "github", "line_count": 32, "max_line_length": 121, "avg_line_length": 34.28125, "alnum_prop": 0.7329079307201458, "repo_name": "x-meta/xworker", "id": "bf49503b8f4d5b314aea3403c23a1befcda8e9ca", "size": "1097", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "xworker_swt/src/main/java/xworker/swt/xworker/attributeEditor/TwoInputs.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Batchfile", "bytes": "13302" }, { "name": "CSS", "bytes": "608135" }, { "name": "Fluent", "bytes": "1420" }, { "name": "FreeMarker", "bytes": "245430" }, { "name": "Groovy", "bytes": "2259" }, { "name": "HTML", "bytes": "228023" }, { "name": "Java", "bytes": "12283468" }, { "name": "JavaScript", "bytes": "804030" }, { "name": "Lex", "bytes": "5606489" }, { "name": "PHP", "bytes": "2232" }, { "name": "Python", "bytes": "572" }, { "name": "Ruby", "bytes": "302" }, { "name": "SCSS", "bytes": "16447" }, { "name": "Shell", "bytes": "13983" } ], "symlink_target": "" }
echo "Starting the fabric8 container" #docker pull sonatype/nexus:oss #docker run -d -p 8081:8081 --name nexus sonatype/nexus:oss docker run -p 8101:18101 -p 8181:18181 -d -t --link nexus:nexus --name fabric8 -e DOCKER_HOST=http://192.168.59.103:2375 eurotrip:fabric8 #docker port fabric8demo 8181 #docker port fabric8demo 8101
{ "content_hash": "afeabae70e091f5f19cf2978bc4b2a62", "timestamp": "", "source": "github", "line_count": 6, "max_line_length": 137, "avg_line_length": 54.5, "alnum_prop": 0.7706422018348624, "repo_name": "eurotrip11/docker-fabric8", "id": "8e5c791aedd1a374e98c0524b046b9b08d03abf8", "size": "348", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "fabric8.sh", "mode": "33261", "license": "apache-2.0", "language": [ { "name": "Shell", "bytes": "1198" } ], "symlink_target": "" }
Reader for sevice Reddit. ## Demo https://viktor777.github.io/reader/?/javascript
{ "content_hash": "8ae130ffc9668042da3c8fd130c3dbdc", "timestamp": "", "source": "github", "line_count": 5, "max_line_length": 47, "avg_line_length": 16.6, "alnum_prop": 0.7590361445783133, "repo_name": "Viktor777/reader", "id": "bdb92425776ffcd2daa984292a54e6d8c1b4e015", "size": "93", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "README.md", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "21701" }, { "name": "HTML", "bytes": "594" }, { "name": "JavaScript", "bytes": "21155" } ], "symlink_target": "" }
package com.ericsson.eiffel.semantics.events; import java.util.ArrayList; import java.util.List; import com.google.gson.annotations.Expose; import com.google.gson.annotations.SerializedName; public class EiffelSourceChangeCreatedEventData { @SerializedName("author") @Expose private Author author; @SerializedName("change") @Expose private Change change; @SerializedName("issues") @Expose private List<Issue> issues = new ArrayList<Issue>(); @SerializedName("gitIdentifier") @Expose private GitIdentifier gitIdentifier; @SerializedName("svnIdentifier") @Expose private SvnIdentifier svnIdentifier; @SerializedName("ccCompositeIdentifier") @Expose private CcCompositeIdentifier ccCompositeIdentifier; @SerializedName("hgIdentifier") @Expose private HgIdentifier hgIdentifier; @SerializedName("customData") @Expose private List<CustomData> customData = new ArrayList<CustomData>(); public Author getAuthor() { return author; } public void setAuthor(Author author) { this.author = author; } public Change getChange() { return change; } public void setChange(Change change) { this.change = change; } public List<Issue> getIssues() { return issues; } public void setIssues(List<Issue> issues) { this.issues = issues; } public GitIdentifier getGitIdentifier() { return gitIdentifier; } public void setGitIdentifier(GitIdentifier gitIdentifier) { this.gitIdentifier = gitIdentifier; } public SvnIdentifier getSvnIdentifier() { return svnIdentifier; } public void setSvnIdentifier(SvnIdentifier svnIdentifier) { this.svnIdentifier = svnIdentifier; } public CcCompositeIdentifier getCcCompositeIdentifier() { return ccCompositeIdentifier; } public void setCcCompositeIdentifier(CcCompositeIdentifier ccCompositeIdentifier) { this.ccCompositeIdentifier = ccCompositeIdentifier; } public HgIdentifier getHgIdentifier() { return hgIdentifier; } public void setHgIdentifier(HgIdentifier hgIdentifier) { this.hgIdentifier = hgIdentifier; } public List<CustomData> getCustomData() { return customData; } public void setCustomData(List<CustomData> customData) { this.customData = customData; } }
{ "content_hash": "6c59d67a101423dbb24859371be77918", "timestamp": "", "source": "github", "line_count": 100, "max_line_length": 87, "avg_line_length": 25.53, "alnum_prop": 0.6635330983157071, "repo_name": "xdurvak/eiffel-remrem-semantics", "id": "9b3201f32a7d6622401672748b1446db0ebf04a8", "size": "3237", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "src/main/java/com/ericsson/eiffel/semantics/events/EiffelSourceChangeCreatedEventData.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "520793" } ], "symlink_target": "" }
<?php namespace Wookieb\ZorroDataSchema\Schema\Type; use Wookieb\TypeCheck\ObjectTypeCheck; use Wookieb\ZorroDataSchema\Exception\InvalidValueException; /** * Date type which represents date as \DateTime object * * @author Łukasz Kużyński "wookieb" <lukasz.kuzynski@gmail.com> */ class DateType extends AbstractTypeCheckCachingType { /** * {@inheritDoc} */ public function create($data) { if ($data instanceof \DateTime) { return $data; } try { if (is_numeric($data)) { return \DateTime::createFromFormat('U', $data); } if (is_string($data)) { return new \DateTime($data); } } catch (\Exception $e) { throw new InvalidValueException('Invalid format of data to create a Date', null, $e); } throw new InvalidValueException('Invalid data to create a Date'); } /** * {@inheritDoc} */ public function extract($value) { if (!$value instanceof \DateTime) { throw new InvalidValueException('Invalid value to extract. Only DateTime objects allowed'); } return $value->format(\DateTime::ISO8601); } /** * {@inheritDoc} */ public function isTargetType($value) { return $value instanceof \DateTime; } protected function createTypeCheck() { return new ObjectTypeCheck('\DateTime'); } }
{ "content_hash": "2b7a8f6289c12b4fca181508d10d04ae", "timestamp": "", "source": "github", "line_count": 59, "max_line_length": 103, "avg_line_length": 25.033898305084747, "alnum_prop": 0.5863236289776574, "repo_name": "wookieb/zorro-data-schema", "id": "872e74bc799bebd7783a4c487df2bf4343fa9152", "size": "1480", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/Wookieb/ZorroDataSchema/Schema/Type/DateType.php", "mode": "33188", "license": "mit", "language": [ { "name": "PHP", "bytes": "299769" } ], "symlink_target": "" }
<?php class uploadVideoTask extends sfBaseTask { protected function configure() { // // add your own arguments here // $this->addArguments(array( // new sfCommandArgument('my_arg', sfCommandArgument::REQUIRED, 'My argument'), // )); $this->addOptions(array( new sfCommandOption('application', null, sfCommandOption::PARAMETER_REQUIRED, 'ChristMedia', 'frontend'), new sfCommandOption('env', null, sfCommandOption::PARAMETER_REQUIRED, 'The environment', 'dev'), new sfCommandOption('connection', null, sfCommandOption::PARAMETER_REQUIRED, 'The connection name', 'doctrine'), // add your own options here )); $this->namespace = ''; $this->name = 'uploadVideo'; $this->briefDescription = ''; $this->detailedDescription = <<<EOF The [uploadVideo|INFO] task does things. Call it with: [php symfony uploadVideo|INFO] EOF; } protected function execute($arguments = array(), $options = array()) { // initialize the database connection $databaseManager = new sfDatabaseManager($this->configuration); $connection = $databaseManager->getDatabase($options['connection'])->getConnection(); // add your code here $videos = YoutubeTable::getUploadFile(); foreach($videos as $video) { $parse=parse_url($video->getLinkYoutube()); $video_id = str_replace('v=', 'video_id=', $parse['query']); $link = "http://www.youtube.com/get_video_info?".$video_id; if( $curl = curl_init() ) { curl_setopt($curl,CURLOPT_URL, $link); // Скачанные данные не выводить поток curl_setopt($curl,CURLOPT_RETURNTRANSFER,true); // Скачиваем $out = curl_exec($curl); $out = urldecode($out); $out = urldecode($out); if($title= strstr($out, "title=")) { $title2=strpos($title, "&"); $title=substr($title, 0, $title2); } $title_mas = explode(" ", $title); $title=$title_mas[0]; $p = explode("url=",$out); $link1=null; $link2=null; $link3=null; $link_download=null; for($i=0; $i <= count($p)-1; $i++) { $itag=substr($p[$i], strpos($p[$i], "&itag="), 8); if($itag == "&itag=35") { $link1=$i; $link_download = str_replace('&sig=', '&signature=', $p[$i]); $p[$i]="http://o".substr($p[$i],0,strripos($p[$i], "&itag="))."&".$title; } elseif($itag == "&itag=34") { $link2=$i; $link_download = str_replace('&sig=', '&signature=', $p[$i]); $p[$i]="http://o".substr($p[$i],0,strripos($p[$i], "&itag="))."&".$title; } elseif($itag == "&itag=5&" || $itag == "&itag=5,") { $link3=$i; $link_download = str_replace('&sig=', '&signature=', $p[$i]); $p[$i]="http://o".substr($p[$i],0,strripos($p[$i], "&itag="))."&".$title; } } set_time_limit(0); $filename= sha1($video["title"].rand(11111, 99999)).'.flv'; $fullpath= sfConfig::get('sf_upload_dir').'/video/'.$filename; echo $link_download; $data = @file_get_contents($link_download); if(file_put_contents($fullpath, $data)) { $cmd = "ffmpeg -i " . $fullpath . " 2>&1"; exec($cmd); if (preg_match('/Duration: ((\d+):(\d+):(\d+))/s', `$cmd`, $time)) { $total = ($time[2] * 3600) + ($time[3] * 60) + $time[4]; } $show_videos = new Video(); $show_videos->setTitle($video["title"]); $show_videos->setDescription($video["description"]); $show_videos->setFile($filename); $show_videos->setDuration($total); $show_videos->setIsActive(true); $show_videos->setIsConverted(false); $show_videos->setIsEdit(false); $show_videos->setStatus("complete"); $show_videos->save(); $video->setDownload(false); $video->setIsEdit(false); $video->setVideoId($show_videos->getId()); $video->save(); echo "video downloaded"; } else { echo 'Something error'; } } } } }
{ "content_hash": "1bdfcd152f1ab4b3c4bee9ed1880b3ef", "timestamp": "", "source": "github", "line_count": 135, "max_line_length": 118, "avg_line_length": 36.148148148148145, "alnum_prop": 0.46024590163934426, "repo_name": "lebedta/christmedia", "id": "cc6c8829bd76a283070b2a1feaef099ae3532796", "size": "4919", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "lib/task/uploadVideoTask.class.php", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "78711" }, { "name": "JavaScript", "bytes": "169066" }, { "name": "PHP", "bytes": "6137605" }, { "name": "Shell", "bytes": "1970" } ], "symlink_target": "" }
import netaddr import sqlalchemy as sa from sqlalchemy import orm from sqlalchemy.orm import exc from neutron.api.rpc.agentnotifiers import l3_rpc_agent_api from neutron.api.v2 import attributes from neutron.common import constants as l3_constants from neutron.common import exceptions as n_exc from neutron.common import rpc as n_rpc from neutron.common import utils from neutron.db import model_base from neutron.db import models_v2 from neutron.extensions import external_net from neutron.extensions import l3 from neutron import manager from neutron.openstack.common import log as logging from neutron.openstack.common import uuidutils from neutron.plugins.common import constants LOG = logging.getLogger(__name__) DEVICE_OWNER_ROUTER_INTF = l3_constants.DEVICE_OWNER_ROUTER_INTF DEVICE_OWNER_ROUTER_GW = l3_constants.DEVICE_OWNER_ROUTER_GW DEVICE_OWNER_FLOATINGIP = l3_constants.DEVICE_OWNER_FLOATINGIP EXTERNAL_GW_INFO = l3.EXTERNAL_GW_INFO # Maps API field to DB column # API parameter name and Database column names may differ. # Useful to keep the filtering between API and Database. API_TO_DB_COLUMN_MAP = {'port_id': 'fixed_port_id'} CORE_ROUTER_ATTRS = ('id', 'name', 'tenant_id', 'admin_state_up', 'status') class RouterPort(model_base.BASEV2): router_id = sa.Column( sa.String(36), sa.ForeignKey('routers.id', ondelete="CASCADE"), primary_key=True) port_id = sa.Column( sa.String(36), sa.ForeignKey('ports.id', ondelete="CASCADE"), primary_key=True) # The port_type attribute is redundant as the port table already specifies # it in DEVICE_OWNER.However, this redundancy enables more efficient # queries on router ports, and also prevents potential error-prone # conditions which might originate from users altering the DEVICE_OWNER # property of router ports. port_type = sa.Column(sa.String(255)) port = orm.relationship( models_v2.Port, backref=orm.backref('routerport', uselist=False, cascade="all,delete")) class Router(model_base.BASEV2, models_v2.HasId, models_v2.HasTenant): """Represents a v2 neutron router.""" name = sa.Column(sa.String(255)) status = sa.Column(sa.String(16)) admin_state_up = sa.Column(sa.Boolean) gw_port_id = sa.Column(sa.String(36), sa.ForeignKey('ports.id')) gw_port = orm.relationship(models_v2.Port, lazy='joined') attached_ports = orm.relationship( RouterPort, backref='router', lazy='dynamic') class FloatingIP(model_base.BASEV2, models_v2.HasId, models_v2.HasTenant): """Represents a floating IP address. This IP address may or may not be allocated to a tenant, and may or may not be associated with an internal port/ip address/router. """ floating_ip_address = sa.Column(sa.String(64), nullable=False) floating_network_id = sa.Column(sa.String(36), nullable=False) floating_port_id = sa.Column(sa.String(36), sa.ForeignKey('ports.id'), nullable=False) fixed_port_id = sa.Column(sa.String(36), sa.ForeignKey('ports.id')) fixed_ip_address = sa.Column(sa.String(64)) router_id = sa.Column(sa.String(36), sa.ForeignKey('routers.id')) # Additional attribute for keeping track of the router where the floating # ip was associated in order to be able to ensure consistency even if an # aysnchronous backend is unavailable when the floating IP is disassociated last_known_router_id = sa.Column(sa.String(36)) status = sa.Column(sa.String(16)) router = orm.relationship(Router, backref='floating_ips') class L3_NAT_dbonly_mixin(l3.RouterPluginBase): """Mixin class to add L3/NAT router methods to db_base_plugin_v2.""" router_device_owners = ( DEVICE_OWNER_ROUTER_INTF, DEVICE_OWNER_ROUTER_GW, DEVICE_OWNER_FLOATINGIP ) @property def _core_plugin(self): return manager.NeutronManager.get_plugin() def _get_router(self, context, router_id): try: router = self._get_by_id(context, Router, router_id) except exc.NoResultFound: raise l3.RouterNotFound(router_id=router_id) return router def _make_router_dict(self, router, fields=None, process_extensions=True): res = dict((key, router[key]) for key in CORE_ROUTER_ATTRS) if router['gw_port_id']: ext_gw_info = { 'network_id': router.gw_port['network_id'], 'external_fixed_ips': [{'subnet_id': ip["subnet_id"], 'ip_address': ip["ip_address"]} for ip in router.gw_port['fixed_ips']]} else: ext_gw_info = None res.update({ EXTERNAL_GW_INFO: ext_gw_info, 'gw_port_id': router['gw_port_id'], }) # NOTE(salv-orlando): The following assumes this mixin is used in a # class inheriting from CommonDbMixin, which is true for all existing # plugins. if process_extensions: self._apply_dict_extend_functions(l3.ROUTERS, res, router) return self._fields(res, fields) def _create_router_db(self, context, router, tenant_id): """Create the DB object.""" with context.session.begin(subtransactions=True): # pre-generate id so it will be available when # configuring external gw port router_db = Router(id=uuidutils.generate_uuid(), tenant_id=tenant_id, name=router['name'], admin_state_up=router['admin_state_up'], status="ACTIVE") context.session.add(router_db) return router_db def create_router(self, context, router): r = router['router'] gw_info = r.pop(EXTERNAL_GW_INFO, None) tenant_id = self._get_tenant_id_for_create(context, r) with context.session.begin(subtransactions=True): router_db = self._create_router_db(context, r, tenant_id) if gw_info: self._update_router_gw_info(context, router_db['id'], gw_info, router=router_db) return self._make_router_dict(router_db) def _update_router_db(self, context, router_id, data, gw_info): """Update the DB object and related gw info, if available.""" with context.session.begin(subtransactions=True): if gw_info != attributes.ATTR_NOT_SPECIFIED: self._update_router_gw_info(context, router_id, gw_info) router_db = self._get_router(context, router_id) if data: router_db.update(data) return router_db def update_router(self, context, id, router): r = router['router'] gw_info = r.pop(EXTERNAL_GW_INFO, attributes.ATTR_NOT_SPECIFIED) # check whether router needs and can be rescheduled to the proper # l3 agent (associated with given external network); # do check before update in DB as an exception will be raised # in case no proper l3 agent found if gw_info != attributes.ATTR_NOT_SPECIFIED: candidates = self._check_router_needs_rescheduling( context, id, gw_info) else: candidates = None router_db = self._update_router_db(context, id, r, gw_info) if candidates: l3_plugin = manager.NeutronManager.get_service_plugins().get( constants.L3_ROUTER_NAT) l3_plugin.reschedule_router(context, id, candidates) return self._make_router_dict(router_db) def _check_router_needs_rescheduling(self, context, router_id, gw_info): """Checks whether router's l3 agent can handle the given network When external_network_bridge is set, each L3 agent can be associated with at most one external network. If router's new external gateway is on other network then the router needs to be rescheduled to the proper l3 agent. If external_network_bridge is not set then the agent can support multiple external networks and rescheduling is not needed :return: list of candidate agents if rescheduling needed, None otherwise; raises exception if there is no eligible l3 agent associated with target external network """ # TODO(obondarev): rethink placement of this func as l3 db manager is # not really a proper place for agent scheduling stuff network_id = gw_info.get('network_id') if gw_info else None if not network_id: return nets = self._core_plugin.get_networks( context, {external_net.EXTERNAL: [True]}) # nothing to do if there is only one external network if len(nets) <= 1: return # first get plugin supporting l3 agent scheduling # (either l3 service plugin or core_plugin) l3_plugin = manager.NeutronManager.get_service_plugins().get( constants.L3_ROUTER_NAT) if (not utils.is_extension_supported( l3_plugin, l3_constants.L3_AGENT_SCHEDULER_EXT_ALIAS) or l3_plugin.router_scheduler is None): # that might mean that we are dealing with non-agent-based # implementation of l3 services return cur_agents = l3_plugin.list_l3_agents_hosting_router( context, router_id)['agents'] for agent in cur_agents: ext_net_id = agent['configurations'].get( 'gateway_external_network_id') ext_bridge = agent['configurations'].get( 'external_network_bridge', 'br-ex') if (ext_net_id == network_id or (not ext_net_id and not ext_bridge)): return # otherwise find l3 agent with matching gateway_external_network_id active_agents = l3_plugin.get_l3_agents(context, active=True) router = { 'id': router_id, 'external_gateway_info': {'network_id': network_id} } candidates = l3_plugin.get_l3_agent_candidates(context, router, active_agents) if not candidates: msg = (_('No eligible l3 agent associated with external network ' '%s found') % network_id) raise n_exc.BadRequest(resource='router', msg=msg) return candidates def _create_router_gw_port(self, context, router, network_id): # Port has no 'tenant-id', as it is hidden from user gw_port = self._core_plugin.create_port(context.elevated(), { 'port': {'tenant_id': '', # intentionally not set 'network_id': network_id, 'mac_address': attributes.ATTR_NOT_SPECIFIED, 'fixed_ips': attributes.ATTR_NOT_SPECIFIED, 'device_id': router['id'], 'device_owner': DEVICE_OWNER_ROUTER_GW, 'admin_state_up': True, 'name': ''}}) if not gw_port['fixed_ips']: self._core_plugin.delete_port(context.elevated(), gw_port['id'], l3_port_check=False) msg = (_('No IPs available for external network %s') % network_id) raise n_exc.BadRequest(resource='router', msg=msg) with context.session.begin(subtransactions=True): router.gw_port = self._core_plugin._get_port(context.elevated(), gw_port['id']) router_port = RouterPort( router_id=router.id, port_id=gw_port['id'], port_type=DEVICE_OWNER_ROUTER_GW ) context.session.add(router) context.session.add(router_port) def _validate_gw_info(self, context, gw_port, info): network_id = info['network_id'] if info else None if network_id: network_db = self._core_plugin._get_network(context, network_id) if not network_db.external: msg = _("Network %s is not an external network") % network_id raise n_exc.BadRequest(resource='router', msg=msg) return network_id def _delete_current_gw_port(self, context, router_id, router, new_network): """Delete gw port, if it is attached to an old network.""" is_gw_port_attached_to_existing_network = ( router.gw_port and router.gw_port['network_id'] != new_network) admin_ctx = context.elevated() if is_gw_port_attached_to_existing_network: if self.get_floatingips_count( admin_ctx, {'router_id': [router_id]}): raise l3.RouterExternalGatewayInUseByFloatingIp( router_id=router_id, net_id=router.gw_port['network_id']) with context.session.begin(subtransactions=True): gw_port = router.gw_port router.gw_port = None context.session.add(router) context.session.expire(gw_port) self._core_plugin.delete_port( admin_ctx, gw_port['id'], l3_port_check=False) def _create_gw_port(self, context, router_id, router, new_network): new_valid_gw_port_attachment = ( new_network and (not router.gw_port or router.gw_port['network_id'] != new_network)) if new_valid_gw_port_attachment: subnets = self._core_plugin._get_subnets_by_network(context, new_network) for subnet in subnets: self._check_for_dup_router_subnet(context, router, new_network, subnet['id'], subnet['cidr']) self._create_router_gw_port(context, router, new_network) def _update_router_gw_info(self, context, router_id, info, router=None): # TODO(salvatore-orlando): guarantee atomic behavior also across # operations that span beyond the model classes handled by this # class (e.g.: delete_port) router = router or self._get_router(context, router_id) gw_port = router.gw_port network_id = self._validate_gw_info(context, gw_port, info) self._delete_current_gw_port(context, router_id, router, network_id) self._create_gw_port(context, router_id, router, network_id) def _ensure_router_not_in_use(self, context, router_id): admin_ctx = context.elevated() router = self._get_router(context, router_id) if self.get_floatingips_count( admin_ctx, filters={'router_id': [router_id]}): raise l3.RouterInUse(router_id=router_id) device_owner = self._get_device_owner(context, router) if any(rp.port_type == device_owner for rp in router.attached_ports.all()): raise l3.RouterInUse(router_id=router_id) return router def delete_router(self, context, id): with context.session.begin(subtransactions=True): router = self._ensure_router_not_in_use(context, id) #TODO(nati) Refactor here when we have router insertion model vpnservice = manager.NeutronManager.get_service_plugins().get( constants.VPN) if vpnservice: vpnservice.check_router_in_use(context, id) router_ports = router.attached_ports.all() # Set the router's gw_port to None to avoid a constraint violation. router.gw_port = None for rp in router_ports: self._core_plugin._delete_port(context.elevated(), rp.port.id) context.session.delete(router) def get_router(self, context, id, fields=None): router = self._get_router(context, id) return self._make_router_dict(router, fields) def get_routers(self, context, filters=None, fields=None, sorts=None, limit=None, marker=None, page_reverse=False): marker_obj = self._get_marker_obj(context, 'router', limit, marker) return self._get_collection(context, Router, self._make_router_dict, filters=filters, fields=fields, sorts=sorts, limit=limit, marker_obj=marker_obj, page_reverse=page_reverse) def get_routers_count(self, context, filters=None): return self._get_collection_count(context, Router, filters=filters) def _check_for_dup_router_subnet(self, context, router, network_id, subnet_id, subnet_cidr): try: # It's possible these ports are on the same network, but # different subnets. new_ipnet = netaddr.IPNetwork(subnet_cidr) for p in (rp.port for rp in router.attached_ports): for ip in p['fixed_ips']: if ip['subnet_id'] == subnet_id: msg = (_("Router already has a port on subnet %s") % subnet_id) raise n_exc.BadRequest(resource='router', msg=msg) sub_id = ip['subnet_id'] cidr = self._core_plugin._get_subnet(context.elevated(), sub_id)['cidr'] ipnet = netaddr.IPNetwork(cidr) match1 = netaddr.all_matching_cidrs(new_ipnet, [cidr]) match2 = netaddr.all_matching_cidrs(ipnet, [subnet_cidr]) if match1 or match2: data = {'subnet_cidr': subnet_cidr, 'subnet_id': subnet_id, 'cidr': cidr, 'sub_id': sub_id} msg = (_("Cidr %(subnet_cidr)s of subnet " "%(subnet_id)s overlaps with cidr %(cidr)s " "of subnet %(sub_id)s") % data) raise n_exc.BadRequest(resource='router', msg=msg) except exc.NoResultFound: pass def _get_device_owner(self, context, router=None): """Get device_owner for the specified router.""" # NOTE(armando-migliaccio): in the base case this is invariant return DEVICE_OWNER_ROUTER_INTF def _validate_interface_info(self, interface_info): port_id_specified = interface_info and 'port_id' in interface_info subnet_id_specified = interface_info and 'subnet_id' in interface_info if not (port_id_specified or subnet_id_specified): msg = _("Either subnet_id or port_id must be specified") raise n_exc.BadRequest(resource='router', msg=msg) if port_id_specified and subnet_id_specified: msg = _("Cannot specify both subnet-id and port-id") raise n_exc.BadRequest(resource='router', msg=msg) return port_id_specified, subnet_id_specified def _add_interface_by_port(self, context, router, port_id, owner): with context.session.begin(subtransactions=True): port = self._core_plugin._get_port(context, port_id) if port['device_id']: raise n_exc.PortInUse(net_id=port['network_id'], port_id=port['id'], device_id=port['device_id']) fixed_ips = [ip for ip in port['fixed_ips']] if len(fixed_ips) != 1: msg = _('Router port must have exactly one fixed IP') raise n_exc.BadRequest(resource='router', msg=msg) subnet_id = fixed_ips[0]['subnet_id'] subnet = self._core_plugin._get_subnet(context, subnet_id) self._check_for_dup_router_subnet(context, router, port['network_id'], subnet['id'], subnet['cidr']) port.update({'device_id': router.id, 'device_owner': owner}) return port def _add_interface_by_subnet(self, context, router, subnet_id, owner): subnet = self._core_plugin._get_subnet(context, subnet_id) if not subnet['gateway_ip']: msg = _('Subnet for router interface must have a gateway IP') raise n_exc.BadRequest(resource='router', msg=msg) self._check_for_dup_router_subnet(context, router, subnet['network_id'], subnet_id, subnet['cidr']) fixed_ip = {'ip_address': subnet['gateway_ip'], 'subnet_id': subnet['id']} return self._core_plugin.create_port(context, { 'port': {'tenant_id': subnet['tenant_id'], 'network_id': subnet['network_id'], 'fixed_ips': [fixed_ip], 'mac_address': attributes.ATTR_NOT_SPECIFIED, 'admin_state_up': True, 'device_id': router.id, 'device_owner': owner, 'name': ''}}) @staticmethod def _make_router_interface_info( router_id, tenant_id, port_id, subnet_id): return { 'id': router_id, 'tenant_id': tenant_id, 'port_id': port_id, 'subnet_id': subnet_id } def add_router_interface(self, context, router_id, interface_info): router = self._get_router(context, router_id) add_by_port, add_by_sub = self._validate_interface_info(interface_info) device_owner = self._get_device_owner(context, router_id) if add_by_port: port = self._add_interface_by_port( context, router, interface_info['port_id'], device_owner) elif add_by_sub: port = self._add_interface_by_subnet( context, router, interface_info['subnet_id'], device_owner) with context.session.begin(subtransactions=True): router_port = RouterPort( port_id=port['id'], router_id=router.id, port_type=device_owner ) context.session.add(router_port) return self._make_router_interface_info( router.id, port['tenant_id'], port['id'], port['fixed_ips'][0]['subnet_id']) def _confirm_router_interface_not_in_use(self, context, router_id, subnet_id): subnet_db = self._core_plugin._get_subnet(context, subnet_id) subnet_cidr = netaddr.IPNetwork(subnet_db['cidr']) fip_qry = context.session.query(FloatingIP) for fip_db in fip_qry.filter_by(router_id=router_id): if netaddr.IPAddress(fip_db['fixed_ip_address']) in subnet_cidr: raise l3.RouterInterfaceInUseByFloatingIP( router_id=router_id, subnet_id=subnet_id) def _remove_interface_by_port(self, context, router_id, port_id, subnet_id, owner): qry = context.session.query(RouterPort) qry = qry.filter_by( port_id=port_id, router_id=router_id, port_type=owner ) try: port_db = qry.one().port except exc.NoResultFound: raise l3.RouterInterfaceNotFound(router_id=router_id, port_id=port_id) port_subnet_id = port_db['fixed_ips'][0]['subnet_id'] if subnet_id and port_subnet_id != subnet_id: raise n_exc.SubnetMismatchForPort( port_id=port_id, subnet_id=subnet_id) subnet = self._core_plugin._get_subnet(context, port_subnet_id) self._confirm_router_interface_not_in_use( context, router_id, port_subnet_id) self._core_plugin.delete_port(context, port_db['id'], l3_port_check=False) return (port_db, subnet) def _remove_interface_by_subnet(self, context, router_id, subnet_id, owner): self._confirm_router_interface_not_in_use( context, router_id, subnet_id) subnet = self._core_plugin._get_subnet(context, subnet_id) try: rport_qry = context.session.query(models_v2.Port).join(RouterPort) ports = rport_qry.filter( RouterPort.router_id == router_id, RouterPort.port_type == owner, models_v2.Port.network_id == subnet['network_id'] ) for p in ports: if p['fixed_ips'][0]['subnet_id'] == subnet_id: self._core_plugin.delete_port(context, p['id'], l3_port_check=False) return (p, subnet) except exc.NoResultFound: pass raise l3.RouterInterfaceNotFoundForSubnet(router_id=router_id, subnet_id=subnet_id) def remove_router_interface(self, context, router_id, interface_info): if not interface_info: msg = _("Either subnet_id or port_id must be specified") raise n_exc.BadRequest(resource='router', msg=msg) port_id = interface_info.get('port_id') subnet_id = interface_info.get('subnet_id') device_owner = self._get_device_owner(context, router_id) if port_id: port, subnet = self._remove_interface_by_port(context, router_id, port_id, subnet_id, device_owner) elif subnet_id: port, subnet = self._remove_interface_by_subnet( context, router_id, subnet_id, device_owner) return self._make_router_interface_info(router_id, port['tenant_id'], port['id'], subnet['id']) def _get_floatingip(self, context, id): try: floatingip = self._get_by_id(context, FloatingIP, id) except exc.NoResultFound: raise l3.FloatingIPNotFound(floatingip_id=id) return floatingip def _make_floatingip_dict(self, floatingip, fields=None): res = {'id': floatingip['id'], 'tenant_id': floatingip['tenant_id'], 'floating_ip_address': floatingip['floating_ip_address'], 'floating_network_id': floatingip['floating_network_id'], 'router_id': floatingip['router_id'], 'port_id': floatingip['fixed_port_id'], 'fixed_ip_address': floatingip['fixed_ip_address'], 'status': floatingip['status']} return self._fields(res, fields) def _get_interface_ports_for_network(self, context, network_id): router_intf_qry = context.session.query(RouterPort) router_intf_qry = router_intf_qry.join(models_v2.Port) return router_intf_qry.filter( models_v2.Port.network_id == network_id, RouterPort.port_type == DEVICE_OWNER_ROUTER_INTF ) def _get_router_for_floatingip(self, context, internal_port, internal_subnet_id, external_network_id): subnet_db = self._core_plugin._get_subnet(context, internal_subnet_id) if not subnet_db['gateway_ip']: msg = (_('Cannot add floating IP to port on subnet %s ' 'which has no gateway_ip') % internal_subnet_id) raise n_exc.BadRequest(resource='floatingip', msg=msg) router_intf_ports = self._get_interface_ports_for_network( context, internal_port['network_id']) # This joins on port_id so is not a cross-join routerport_qry = router_intf_ports.join(models_v2.IPAllocation) routerport_qry = routerport_qry.filter( models_v2.IPAllocation.subnet_id == internal_subnet_id ) router_port = routerport_qry.first() if router_port and router_port.router.gw_port: return router_port.router.id raise l3.ExternalGatewayForFloatingIPNotFound( subnet_id=internal_subnet_id, external_network_id=external_network_id, port_id=internal_port['id']) def _internal_fip_assoc_data(self, context, fip): """Retrieve internal port data for floating IP. Retrieve information concerning the internal port where the floating IP should be associated to. """ internal_port = self._core_plugin._get_port(context, fip['port_id']) if not internal_port['tenant_id'] == fip['tenant_id']: port_id = fip['port_id'] if 'id' in fip: floatingip_id = fip['id'] data = {'port_id': port_id, 'floatingip_id': floatingip_id} msg = (_('Port %(port_id)s is associated with a different ' 'tenant than Floating IP %(floatingip_id)s and ' 'therefore cannot be bound.') % data) else: msg = (_('Cannot create floating IP and bind it to ' 'Port %s, since that port is owned by a ' 'different tenant.') % port_id) raise n_exc.BadRequest(resource='floatingip', msg=msg) internal_subnet_id = None if 'fixed_ip_address' in fip and fip['fixed_ip_address']: internal_ip_address = fip['fixed_ip_address'] for ip in internal_port['fixed_ips']: if ip['ip_address'] == internal_ip_address: internal_subnet_id = ip['subnet_id'] if not internal_subnet_id: msg = (_('Port %(id)s does not have fixed ip %(address)s') % {'id': internal_port['id'], 'address': internal_ip_address}) raise n_exc.BadRequest(resource='floatingip', msg=msg) else: ips = [ip['ip_address'] for ip in internal_port['fixed_ips']] if not ips: msg = (_('Cannot add floating IP to port %s that has' 'no fixed IP addresses') % internal_port['id']) raise n_exc.BadRequest(resource='floatingip', msg=msg) if len(ips) > 1: msg = (_('Port %s has multiple fixed IPs. Must provide' ' a specific IP when assigning a floating IP') % internal_port['id']) raise n_exc.BadRequest(resource='floatingip', msg=msg) internal_ip_address = internal_port['fixed_ips'][0]['ip_address'] internal_subnet_id = internal_port['fixed_ips'][0]['subnet_id'] return internal_port, internal_subnet_id, internal_ip_address def get_assoc_data(self, context, fip, floating_network_id): """Determine/extract data associated with the internal port. When a floating IP is associated with an internal port, we need to extract/determine some data associated with the internal port, including the internal_ip_address, and router_id. The confirmation of the internal port whether owned by the tenant who owns the floating IP will be confirmed by _get_router_for_floatingip. """ (internal_port, internal_subnet_id, internal_ip_address) = self._internal_fip_assoc_data(context, fip) router_id = self._get_router_for_floatingip(context, internal_port, internal_subnet_id, floating_network_id) return (fip['port_id'], internal_ip_address, router_id) def _check_and_get_fip_assoc(self, context, fip, floatingip_db): port_id = internal_ip_address = router_id = None if (('fixed_ip_address' in fip and fip['fixed_ip_address']) and not ('port_id' in fip and fip['port_id'])): msg = _("fixed_ip_address cannot be specified without a port_id") raise n_exc.BadRequest(resource='floatingip', msg=msg) if 'port_id' in fip and fip['port_id']: port_id, internal_ip_address, router_id = self.get_assoc_data( context, fip, floatingip_db['floating_network_id']) fip_qry = context.session.query(FloatingIP) try: fip_qry.filter_by( fixed_port_id=fip['port_id'], floating_network_id=floatingip_db['floating_network_id'], fixed_ip_address=internal_ip_address).one() raise l3.FloatingIPPortAlreadyAssociated( port_id=fip['port_id'], fip_id=floatingip_db['id'], floating_ip_address=floatingip_db['floating_ip_address'], fixed_ip=internal_ip_address, net_id=floatingip_db['floating_network_id']) except exc.NoResultFound: pass return port_id, internal_ip_address, router_id def _update_fip_assoc(self, context, fip, floatingip_db, external_port): previous_router_id = floatingip_db.router_id port_id, internal_ip_address, router_id = ( self._check_and_get_fip_assoc(context, fip, floatingip_db)) floatingip_db.update({'fixed_ip_address': internal_ip_address, 'fixed_port_id': port_id, 'router_id': router_id, 'last_known_router_id': previous_router_id}) def create_floatingip(self, context, floatingip, initial_status=l3_constants.FLOATINGIP_STATUS_ACTIVE): fip = floatingip['floatingip'] tenant_id = self._get_tenant_id_for_create(context, fip) fip_id = uuidutils.generate_uuid() f_net_id = fip['floating_network_id'] if not self._core_plugin._network_is_external(context, f_net_id): msg = _("Network %s is not a valid external network") % f_net_id raise n_exc.BadRequest(resource='floatingip', msg=msg) with context.session.begin(subtransactions=True): # This external port is never exposed to the tenant. # it is used purely for internal system and admin use when # managing floating IPs. external_port = self._core_plugin.create_port(context.elevated(), { 'port': {'tenant_id': '', # tenant intentionally not set 'network_id': f_net_id, 'mac_address': attributes.ATTR_NOT_SPECIFIED, 'fixed_ips': attributes.ATTR_NOT_SPECIFIED, 'admin_state_up': True, 'device_id': fip_id, 'device_owner': DEVICE_OWNER_FLOATINGIP, 'name': ''}}) # Ensure IP addresses are allocated on external port if not external_port['fixed_ips']: raise n_exc.ExternalIpAddressExhausted(net_id=f_net_id) floating_fixed_ip = external_port['fixed_ips'][0] floating_ip_address = floating_fixed_ip['ip_address'] floatingip_db = FloatingIP( id=fip_id, tenant_id=tenant_id, status=initial_status, floating_network_id=fip['floating_network_id'], floating_ip_address=floating_ip_address, floating_port_id=external_port['id']) fip['tenant_id'] = tenant_id # Update association with internal port # and define external IP address self._update_fip_assoc(context, fip, floatingip_db, external_port) context.session.add(floatingip_db) return self._make_floatingip_dict(floatingip_db) def _update_floatingip(self, context, id, floatingip): fip = floatingip['floatingip'] with context.session.begin(subtransactions=True): floatingip_db = self._get_floatingip(context, id) old_floatingip = self._make_floatingip_dict(floatingip_db) fip['tenant_id'] = floatingip_db['tenant_id'] fip['id'] = id fip_port_id = floatingip_db['floating_port_id'] self._update_fip_assoc(context, fip, floatingip_db, self._core_plugin.get_port( context.elevated(), fip_port_id)) return old_floatingip, self._make_floatingip_dict(floatingip_db) def _floatingips_to_router_ids(self, floatingips): return list(set([floatingip['router_id'] for floatingip in floatingips if floatingip['router_id']])) def update_floatingip(self, context, id, floatingip): _old_floatingip, floatingip = self._update_floatingip( context, id, floatingip) return floatingip def update_floatingip_status(self, context, floatingip_id, status): """Update operational status for floating IP in neutron DB.""" fip_query = self._model_query(context, FloatingIP).filter( FloatingIP.id == floatingip_id) fip_query.update({'status': status}, synchronize_session=False) def _delete_floatingip(self, context, id): floatingip = self._get_floatingip(context, id) router_id = floatingip['router_id'] with context.session.begin(subtransactions=True): context.session.delete(floatingip) self._core_plugin.delete_port(context.elevated(), floatingip['floating_port_id'], l3_port_check=False) return router_id def delete_floatingip(self, context, id): self._delete_floatingip(context, id) def get_floatingip(self, context, id, fields=None): floatingip = self._get_floatingip(context, id) return self._make_floatingip_dict(floatingip, fields) def get_floatingips(self, context, filters=None, fields=None, sorts=None, limit=None, marker=None, page_reverse=False): marker_obj = self._get_marker_obj(context, 'floatingip', limit, marker) if filters is not None: for key, val in API_TO_DB_COLUMN_MAP.iteritems(): if key in filters: filters[val] = filters.pop(key) return self._get_collection(context, FloatingIP, self._make_floatingip_dict, filters=filters, fields=fields, sorts=sorts, limit=limit, marker_obj=marker_obj, page_reverse=page_reverse) def delete_disassociated_floatingips(self, context, network_id): query = self._model_query(context, FloatingIP) query = query.filter_by(floating_network_id=network_id, fixed_port_id=None, router_id=None) for fip in query: self.delete_floatingip(context, fip.id) def get_floatingips_count(self, context, filters=None): return self._get_collection_count(context, FloatingIP, filters=filters) def prevent_l3_port_deletion(self, context, port_id): """Checks to make sure a port is allowed to be deleted. Raises an exception if this is not the case. This should be called by any plugin when the API requests the deletion of a port, since some ports for L3 are not intended to be deleted directly via a DELETE to /ports, but rather via other API calls that perform the proper deletion checks. """ port_db = self._core_plugin._get_port(context, port_id) if port_db['device_owner'] in self.router_device_owners: # Raise port in use only if the port has IP addresses # Otherwise it's a stale port that can be removed fixed_ips = port_db['fixed_ips'] if fixed_ips: raise l3.L3PortInUse(port_id=port_id, device_owner=port_db['device_owner']) else: LOG.debug(_("Port %(port_id)s has owner %(port_owner)s, but " "no IP address, so it can be deleted"), {'port_id': port_db['id'], 'port_owner': port_db['device_owner']}) def disassociate_floatingips(self, context, port_id): """Disassociate all floating IPs linked to specific port. @param port_id: ID of the port to disassociate floating IPs. @param do_notify: whether we should notify routers right away. @return: set of router-ids that require notification updates if do_notify is False, otherwise None. """ router_ids = set() with context.session.begin(subtransactions=True): fip_qry = context.session.query(FloatingIP) floating_ips = fip_qry.filter_by(fixed_port_id=port_id) for floating_ip in floating_ips: router_ids.add(floating_ip['router_id']) floating_ip.update({'fixed_port_id': None, 'fixed_ip_address': None, 'router_id': None}) return router_ids def _build_routers_list(self, context, routers, gw_ports): for router in routers: gw_port_id = router['gw_port_id'] # Collect gw ports only if available if gw_port_id and gw_ports.get(gw_port_id): router['gw_port'] = gw_ports[gw_port_id] return routers def _get_sync_routers(self, context, router_ids=None, active=None): """Query routers and their gw ports for l3 agent. Query routers with the router_ids. The gateway ports, if any, will be queried too. l3 agent has an option to deal with only one router id. In addition, when we need to notify the agent the data about only one router (when modification of router, its interfaces, gw_port and floatingips), we will have router_ids. @param router_ids: the list of router ids which we want to query. if it is None, all of routers will be queried. @return: a list of dicted routers with dicted gw_port populated if any """ filters = {'id': router_ids} if router_ids else {} if active is not None: filters['admin_state_up'] = [active] router_dicts = self.get_routers(context, filters=filters) gw_port_ids = [] if not router_dicts: return [] for router_dict in router_dicts: gw_port_id = router_dict['gw_port_id'] if gw_port_id: gw_port_ids.append(gw_port_id) gw_ports = [] if gw_port_ids: gw_ports = dict((gw_port['id'], gw_port) for gw_port in self.get_sync_gw_ports(context, gw_port_ids)) # NOTE(armando-migliaccio): between get_routers and get_sync_gw_ports # gw ports may get deleted, which means that router_dicts may contain # ports that gw_ports does not; we should rebuild router_dicts, but # letting the callee check for missing gw_ports sounds like a good # defensive approach regardless return self._build_routers_list(context, router_dicts, gw_ports) def _get_sync_floating_ips(self, context, router_ids): """Query floating_ips that relate to list of router_ids.""" if not router_ids: return [] return self.get_floatingips(context, {'router_id': router_ids}) def get_sync_gw_ports(self, context, gw_port_ids): if not gw_port_ids: return [] filters = {'id': gw_port_ids} gw_ports = self._core_plugin.get_ports(context, filters) if gw_ports: self._populate_subnet_for_ports(context, gw_ports) return gw_ports def get_sync_interfaces(self, context, router_ids, device_owners=None): """Query router interfaces that relate to list of router_ids.""" device_owners = device_owners or [DEVICE_OWNER_ROUTER_INTF] if not router_ids: return [] qry = context.session.query(RouterPort) qry = qry.filter( Router.id.in_(router_ids), RouterPort.port_type.in_(device_owners) ) # TODO(markmcclain): This is suboptimal but was left to reduce # changeset size since it is late in cycle ports = [rp.port.id for rp in qry] interfaces = self._core_plugin.get_ports(context, {'id': ports}) if interfaces: self._populate_subnet_for_ports(context, interfaces) return interfaces def _populate_subnet_for_ports(self, context, ports): """Populate ports with subnet. These ports already have fixed_ips populated. """ if not ports: return def each_port_with_ip(): for port in ports: fixed_ips = port.get('fixed_ips', []) if len(fixed_ips) > 1: LOG.info(_("Ignoring multiple IPs on router port %s"), port['id']) continue elif not fixed_ips: # Skip ports without IPs, which can occur if a subnet # attached to a router is deleted LOG.info(_("Skipping port %s as no IP is configure on it"), port['id']) continue yield (port, fixed_ips[0]) network_ids = set(p['network_id'] for p, _ in each_port_with_ip()) filters = {'network_id': [id for id in network_ids]} fields = ['id', 'cidr', 'gateway_ip', 'network_id', 'ipv6_ra_mode'] subnets_by_network = dict((id, []) for id in network_ids) for subnet in self._core_plugin.get_subnets(context, filters, fields): subnets_by_network[subnet['network_id']].append(subnet) for port, fixed_ip in each_port_with_ip(): port['extra_subnets'] = [] for subnet in subnets_by_network[port['network_id']]: subnet_info = {'id': subnet['id'], 'cidr': subnet['cidr'], 'gateway_ip': subnet['gateway_ip'], 'ipv6_ra_mode': subnet['ipv6_ra_mode']} if subnet['id'] == fixed_ip['subnet_id']: port['subnet'] = subnet_info else: port['extra_subnets'].append(subnet_info) def _process_floating_ips(self, context, routers_dict, floating_ips): for floating_ip in floating_ips: router = routers_dict.get(floating_ip['router_id']) if router: router_floatingips = router.get(l3_constants.FLOATINGIP_KEY, []) router_floatingips.append(floating_ip) router[l3_constants.FLOATINGIP_KEY] = router_floatingips def _process_interfaces(self, routers_dict, interfaces): for interface in interfaces: router = routers_dict.get(interface['device_id']) if router: router_interfaces = router.get(l3_constants.INTERFACE_KEY, []) router_interfaces.append(interface) router[l3_constants.INTERFACE_KEY] = router_interfaces def _get_router_info_list(self, context, router_ids=None, active=None, device_owners=None): """Query routers and their related floating_ips, interfaces.""" with context.session.begin(subtransactions=True): routers = self._get_sync_routers(context, router_ids=router_ids, active=active) router_ids = [router['id'] for router in routers] interfaces = self.get_sync_interfaces( context, router_ids, device_owners) floating_ips = self._get_sync_floating_ips(context, router_ids) return (routers, interfaces, floating_ips) def get_sync_data(self, context, router_ids=None, active=None): routers, interfaces, floating_ips = self._get_router_info_list( context, router_ids=router_ids, active=active) routers_dict = dict((router['id'], router) for router in routers) self._process_floating_ips(context, routers_dict, floating_ips) self._process_interfaces(routers_dict, interfaces) return routers_dict.values() class L3RpcNotifierMixin(object): """Mixin class to add rpc notifier attribute to db_base_plugin_v2.""" @property def l3_rpc_notifier(self): if not hasattr(self, '_l3_rpc_notifier'): self._l3_rpc_notifier = l3_rpc_agent_api.L3AgentNotifyAPI() return self._l3_rpc_notifier @l3_rpc_notifier.setter def l3_rpc_notifier(self, value): self._l3_rpc_notifier = value def notify_router_updated(self, context, router_id, operation=None, data=None): if router_id: self.l3_rpc_notifier.routers_updated( context, [router_id], operation, data) def notify_routers_updated(self, context, router_ids, operation=None, data=None): if router_ids: self.l3_rpc_notifier.routers_updated( context, router_ids, operation, data) def notify_router_deleted(self, context, router_id): self.l3_rpc_notifier.router_deleted(context, router_id) class L3_NAT_db_mixin(L3_NAT_dbonly_mixin, L3RpcNotifierMixin): """Mixin class to add rpc notifier methods to db_base_plugin_v2.""" def update_router(self, context, id, router): r = router['router'] payload = {'gw_exists': r.get(EXTERNAL_GW_INFO, attributes.ATTR_NOT_SPECIFIED) != attributes.ATTR_NOT_SPECIFIED} router_dict = super(L3_NAT_db_mixin, self).update_router(context, id, router) self.notify_router_updated(context, router_dict['id'], None, payload) return router_dict def delete_router(self, context, id): super(L3_NAT_db_mixin, self).delete_router(context, id) self.notify_router_deleted(context, id) def notify_router_interface_action( self, context, router_interface_info, action): l3_method = '%s_router_interface' % action super(L3_NAT_db_mixin, self).notify_routers_updated( context, [router_interface_info['id']], l3_method, {'subnet_id': router_interface_info['subnet_id']}) mapping = {'add': 'create', 'remove': 'delete'} notifier = n_rpc.get_notifier('network') router_event = 'router.interface.%s' % mapping[action] notifier.info(context, router_event, {'router_interface': router_interface_info}) def add_router_interface(self, context, router_id, interface_info): router_interface_info = super( L3_NAT_db_mixin, self).add_router_interface( context, router_id, interface_info) self.notify_router_interface_action( context, router_interface_info, 'add') return router_interface_info def remove_router_interface(self, context, router_id, interface_info): router_interface_info = super( L3_NAT_db_mixin, self).remove_router_interface( context, router_id, interface_info) self.notify_router_interface_action( context, router_interface_info, 'remove') return router_interface_info def create_floatingip(self, context, floatingip, initial_status=l3_constants.FLOATINGIP_STATUS_ACTIVE): floatingip_dict = super(L3_NAT_db_mixin, self).create_floatingip( context, floatingip, initial_status) router_id = floatingip_dict['router_id'] self.notify_router_updated(context, router_id, 'create_floatingip', {}) return floatingip_dict def update_floatingip(self, context, id, floatingip): old_floatingip, floatingip = self._update_floatingip( context, id, floatingip) router_ids = self._floatingips_to_router_ids( [old_floatingip, floatingip]) super(L3_NAT_db_mixin, self).notify_routers_updated( context, router_ids, 'update_floatingip', {}) return floatingip def delete_floatingip(self, context, id): router_id = self._delete_floatingip(context, id) self.notify_router_updated(context, router_id, 'delete_floatingip', {}) def disassociate_floatingips(self, context, port_id, do_notify=True): """Disassociate all floating IPs linked to specific port. @param port_id: ID of the port to disassociate floating IPs. @param do_notify: whether we should notify routers right away. @return: set of router-ids that require notification updates if do_notify is False, otherwise None. """ router_ids = super(L3_NAT_db_mixin, self).disassociate_floatingips( context, port_id) if do_notify: self.notify_routers_updated(context, router_ids) # since caller assumes that we handled notifications on its # behalf, return nothing return return router_ids def notify_routers_updated(self, context, router_ids): super(L3_NAT_db_mixin, self).notify_routers_updated( context, list(router_ids), 'disassociate_floatingips', {})
{ "content_hash": "c2f3452427c3982dd687d937af3a4c82", "timestamp": "", "source": "github", "line_count": 1179, "max_line_length": 79, "avg_line_length": 46.60559796437659, "alnum_prop": 0.5680643517507462, "repo_name": "huaweiswitch/neutron", "id": "0f8a56c0efb24a73ba7a242df101b83be6051c4e", "size": "55575", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "neutron/db/l3_db.py", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "20821" }, { "name": "JavaScript", "bytes": "59989" }, { "name": "Python", "bytes": "10355534" }, { "name": "Shell", "bytes": "9456" }, { "name": "XSLT", "bytes": "50907" } ], "symlink_target": "" }
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <title>Source: src/tween/TweenManager.js · Phaser CE</title> <!--[if lt IE 9]> <script src="//html5shiv.googlecode.com/svn/trunk/html5.js"></script> <![endif]--> <link type="text/css" rel="stylesheet" href="styles/default.css"> <link type="text/css" rel="stylesheet" href="styles/sunlight.default.css"> <link type="text/css" rel="stylesheet" href="styles/site.cerulean.css"> <script src="https://use.typekit.net/fmc0gtt.js"></script> <script>Typekit.load()</script> </head> <body> <div class="container-fluid"> <div class="navbar navbar-fixed-top navbar-inverse"> <div style="position: absolute; width: 143px; height: 31px; right: 10px; top: 10px; z-index: 1050"><a href="http://phaser.io"><img src="img/phaser.png" border="0" /></a></div> <div class="navbar-inner"> <a class="brand" href="index.html">Phaser API</a> <ul class="nav"> <li> <a href="https://github.com/photonstorm/phaser-ce/blob/master/README.md"> <i class="icon-info-sign icon-white"></i> Read Me </a> </li> <li> <a href="https://github.com/photonstorm/phaser-ce/blob/master/CHANGELOG.md"> <i class="icon-list icon-white"></i> Change Log </a> </li> <li class="dropdown"> <a href="namespaces.list.html" class="dropdown-toggle" data-toggle="dropdown">Namespaces<b class="caret"></b></a> <ul class="dropdown-menu "> <li class="class-depth-0"> <a href="Phaser.html">Phaser</a> </li> <li class="class-depth-0"> <a href="PIXI.html">PIXI</a> </li> </ul> </li> <li class="dropdown"> <a href="classes.list.html" class="dropdown-toggle" data-toggle="dropdown">Classes<b class="caret"></b></a> <ul class="dropdown-menu "> <li class="class-depth-0"> <a href="CreatureShader.html">CreatureShader</a> </li> <li class="class-depth-0"> <a href="EarCut.html">EarCut</a> </li> <li class="class-depth-0"> <a href="Event.html">Event</a> </li> <li class="class-depth-0"> <a href="EventTarget.html">EventTarget</a> </li> <li class="class-depth-1"> <a href="Phaser.Animation.html">Animation</a> </li> <li class="class-depth-1"> <a href="Phaser.AnimationManager.html">AnimationManager</a> </li> <li class="class-depth-1"> <a href="Phaser.AnimationParser.html">AnimationParser</a> </li> <li class="class-depth-1"> <a href="Phaser.ArraySet.html">ArraySet</a> </li> <li class="class-depth-1"> <a href="Phaser.ArrayUtils.html">ArrayUtils</a> </li> <li class="class-depth-1"> <a href="Phaser.AudioSprite.html">AudioSprite</a> </li> <li class="class-depth-1"> <a href="Phaser.BitmapData.html">BitmapData</a> </li> <li class="class-depth-1"> <a href="Phaser.BitmapText.html">BitmapText</a> </li> <li class="class-depth-1"> <a href="Phaser.Bullet.html">Bullet</a> </li> <li class="class-depth-1"> <a href="Phaser.Button.html">Button</a> </li> <li class="class-depth-1"> <a href="Phaser.Cache.html">Cache</a> </li> <li class="class-depth-1"> <a href="Phaser.Camera.html">Camera</a> </li> <li class="class-depth-1"> <a href="Phaser.Canvas.html">Canvas</a> </li> <li class="class-depth-1"> <a href="Phaser.CanvasPool.html">CanvasPool</a> </li> <li class="class-depth-1"> <a href="Phaser.Circle.html">Circle</a> </li> <li class="class-depth-1"> <a href="Phaser.Color.html">Color</a> </li> <li class="class-depth-2"> <a href="Phaser.Component.Angle.html">Angle</a> </li> <li class="class-depth-2"> <a href="Phaser.Component.Animation.html">Animation</a> </li> <li class="class-depth-2"> <a href="Phaser.Component.AutoCull.html">AutoCull</a> </li> <li class="class-depth-2"> <a href="Phaser.Component.Bounds.html">Bounds</a> </li> <li class="class-depth-2"> <a href="Phaser.Component.BringToTop.html">BringToTop</a> </li> <li class="class-depth-2"> <a href="Phaser.Component.Core.html">Core</a> </li> <li class="class-depth-2"> <a href="Phaser.Component.Crop.html">Crop</a> </li> <li class="class-depth-2"> <a href="Phaser.Component.Delta.html">Delta</a> </li> <li class="class-depth-2"> <a href="Phaser.Component.Destroy.html">Destroy</a> </li> <li class="class-depth-2"> <a href="Phaser.Component.FixedToCamera.html">FixedToCamera</a> </li> <li class="class-depth-2"> <a href="Phaser.Component.Health.html">Health</a> </li> <li class="class-depth-2"> <a href="Phaser.Component.InCamera.html">InCamera</a> </li> <li class="class-depth-2"> <a href="Phaser.Component.InputEnabled.html">InputEnabled</a> </li> <li class="class-depth-2"> <a href="Phaser.Component.InWorld.html">InWorld</a> </li> <li class="class-depth-2"> <a href="Phaser.Component.LifeSpan.html">LifeSpan</a> </li> <li class="class-depth-2"> <a href="Phaser.Component.LoadTexture.html">LoadTexture</a> </li> <li class="class-depth-2"> <a href="Phaser.Component.Overlap.html">Overlap</a> </li> <li class="class-depth-2"> <a href="Phaser.Component.PhysicsBody.html">PhysicsBody</a> </li> <li class="class-depth-2"> <a href="Phaser.Component.Reset.html">Reset</a> </li> <li class="class-depth-2"> <a href="Phaser.Component.ScaleMinMax.html">ScaleMinMax</a> </li> <li class="class-depth-2"> <a href="Phaser.Component.Smoothed.html">Smoothed</a> </li> <li class="class-depth-1"> <a href="Phaser.Create.html">Create</a> </li> <li class="class-depth-1"> <a href="Phaser.Creature.html">Creature</a> </li> <li class="class-depth-1"> <a href="Phaser.Device.html">Device</a> </li> <li class="class-depth-1"> <a href="Phaser.DeviceButton.html">DeviceButton</a> </li> <li class="class-depth-1"> <a href="Phaser.DOM.html">DOM</a> </li> <li class="class-depth-1"> <a href="Phaser.Easing.html">Easing</a> </li> <li class="class-depth-2"> <a href="Phaser.Easing.Back.html">Back</a> </li> <li class="class-depth-2"> <a href="Phaser.Easing.Bounce.html">Bounce</a> </li> <li class="class-depth-2"> <a href="Phaser.Easing.Circular.html">Circular</a> </li> <li class="class-depth-2"> <a href="Phaser.Easing.Cubic.html">Cubic</a> </li> <li class="class-depth-2"> <a href="Phaser.Easing.Elastic.html">Elastic</a> </li> <li class="class-depth-2"> <a href="Phaser.Easing.Exponential.html">Exponential</a> </li> <li class="class-depth-2"> <a href="Phaser.Easing.Linear.html">Linear</a> </li> <li class="class-depth-2"> <a href="Phaser.Easing.Quadratic.html">Quadratic</a> </li> <li class="class-depth-2"> <a href="Phaser.Easing.Quartic.html">Quartic</a> </li> <li class="class-depth-2"> <a href="Phaser.Easing.Quintic.html">Quintic</a> </li> <li class="class-depth-2"> <a href="Phaser.Easing.Sinusoidal.html">Sinusoidal</a> </li> <li class="class-depth-1"> <a href="Phaser.Ellipse.html">Ellipse</a> </li> <li class="class-depth-1"> <a href="Phaser.Events.html">Events</a> </li> <li class="class-depth-1"> <a href="Phaser.Filter.html">Filter</a> </li> <li class="class-depth-1"> <a href="Phaser.FlexGrid.html">FlexGrid</a> </li> <li class="class-depth-1"> <a href="Phaser.FlexLayer.html">FlexLayer</a> </li> <li class="class-depth-1"> <a href="Phaser.Frame.html">Frame</a> </li> <li class="class-depth-1"> <a href="Phaser.FrameData.html">FrameData</a> </li> <li class="class-depth-1"> <a href="Phaser.Game.html">Game</a> </li> <li class="class-depth-1"> <a href="Phaser.GameObjectCreator.html">GameObjectCreator</a> </li> <li class="class-depth-1"> <a href="Phaser.GameObjectFactory.html">GameObjectFactory</a> </li> <li class="class-depth-1"> <a href="Phaser.Gamepad.html">Gamepad</a> </li> <li class="class-depth-1"> <a href="Phaser.Graphics.html">Graphics</a> </li> <li class="class-depth-1"> <a href="Phaser.Group.html">Group</a> </li> <li class="class-depth-1"> <a href="Phaser.Hermite.html">Hermite</a> </li> <li class="class-depth-1"> <a href="Phaser.Image.html">Image</a> </li> <li class="class-depth-1"> <a href="Phaser.ImageCollection.html">ImageCollection</a> </li> <li class="class-depth-1"> <a href="Phaser.Input.html">Input</a> </li> <li class="class-depth-1"> <a href="Phaser.InputHandler.html">InputHandler</a> </li> <li class="class-depth-1"> <a href="Phaser.Key.html">Key</a> </li> <li class="class-depth-1"> <a href="Phaser.Keyboard.html">Keyboard</a> </li> <li class="class-depth-1"> <a href="Phaser.KeyCode.html">KeyCode</a> </li> <li class="class-depth-1"> <a href="Phaser.Line.html">Line</a> </li> <li class="class-depth-1"> <a href="Phaser.LinkedList.html">LinkedList</a> </li> <li class="class-depth-1"> <a href="Phaser.Loader.html">Loader</a> </li> <li class="class-depth-1"> <a href="Phaser.LoaderParser.html">LoaderParser</a> </li> <li class="class-depth-1"> <a href="Phaser.Math.html">Math</a> </li> <li class="class-depth-1"> <a href="Phaser.Matrix.html">Matrix</a> </li> <li class="class-depth-1"> <a href="Phaser.Mouse.html">Mouse</a> </li> <li class="class-depth-1"> <a href="Phaser.MSPointer.html">MSPointer</a> </li> <li class="class-depth-1"> <a href="Phaser.Net.html">Net</a> </li> <li class="class-depth-1"> <a href="Phaser.Particle.html">Particle</a> </li> <li class="class-depth-1"> <a href="Phaser.Particles.html">Particles</a> </li> <li class="class-depth-2"> <a href="Phaser.Particles.Arcade.html">Arcade</a> </li> <li class="class-depth-3"> <a href="Phaser.Particles.Arcade.Emitter.html">Emitter</a> </li> <li class="class-depth-1"> <a href="Phaser.Path.html">Path</a> </li> <li class="class-depth-1"> <a href="Phaser.PathFollower.html">PathFollower</a> </li> <li class="class-depth-1"> <a href="Phaser.PathPoint.html">PathPoint</a> </li> <li class="class-depth-1"> <a href="Phaser.Physics.html">Physics</a> </li> <li class="class-depth-2"> <a href="Phaser.Physics.Arcade.html">Arcade</a> </li> <li class="class-depth-3"> <a href="Phaser.Physics.Arcade.Body.html">Body</a> </li> <li class="class-depth-3"> <a href="Phaser.Physics.Arcade.TilemapCollision.html">TilemapCollision</a> </li> <li class="class-depth-2"> <a href="Phaser.Physics.Ninja.html">Ninja</a> </li> <li class="class-depth-3"> <a href="Phaser.Physics.Ninja.AABB.html">AABB</a> </li> <li class="class-depth-3"> <a href="Phaser.Physics.Ninja.Body.html">Body</a> </li> <li class="class-depth-3"> <a href="Phaser.Physics.Ninja.Circle.html">Circle</a> </li> <li class="class-depth-3"> <a href="Phaser.Physics.Ninja.Tile.html">Tile</a> </li> <li class="class-depth-2"> <a href="Phaser.Physics.P2.html">P2</a> </li> <li class="class-depth-3"> <a href="Phaser.Physics.P2.Body.html">Body</a> </li> <li class="class-depth-3"> <a href="Phaser.Physics.P2.BodyDebug.html">BodyDebug</a> </li> <li class="class-depth-3"> <a href="Phaser.Physics.P2.CollisionGroup.html">CollisionGroup</a> </li> <li class="class-depth-3"> <a href="Phaser.Physics.P2.ContactMaterial.html">ContactMaterial</a> </li> <li class="class-depth-3"> <a href="Phaser.Physics.P2.DistanceConstraint.html">DistanceConstraint</a> </li> <li class="class-depth-3"> <a href="Phaser.Physics.P2.FixtureList.html">FixtureList</a> </li> <li class="class-depth-3"> <a href="Phaser.Physics.P2.GearConstraint.html">GearConstraint</a> </li> <li class="class-depth-3"> <a href="Phaser.Physics.P2.InversePointProxy.html">InversePointProxy</a> </li> <li class="class-depth-3"> <a href="Phaser.Physics.P2.LockConstraint.html">LockConstraint</a> </li> <li class="class-depth-3"> <a href="Phaser.Physics.P2.Material.html">Material</a> </li> <li class="class-depth-3"> <a href="Phaser.Physics.P2.PointProxy.html">PointProxy</a> </li> <li class="class-depth-3"> <a href="Phaser.Physics.P2.PrismaticConstraint.html">PrismaticConstraint</a> </li> <li class="class-depth-3"> <a href="Phaser.Physics.P2.RevoluteConstraint.html">RevoluteConstraint</a> </li> <li class="class-depth-3"> <a href="Phaser.Physics.P2.RotationalSpring.html">RotationalSpring</a> </li> <li class="class-depth-3"> <a href="Phaser.Physics.P2.Spring.html">Spring</a> </li> <li class="class-depth-1"> <a href="Phaser.Plugin.html">Plugin</a> </li> <li class="class-depth-2"> <a href="Phaser.Plugin.AStar.html">AStar</a> </li> <li class="class-depth-3"> <a href="Phaser.Plugin.AStar.AStarNode.html">AStarNode</a> </li> <li class="class-depth-3"> <a href="Phaser.Plugin.AStar.AStarPath.html">AStarPath</a> </li> <li class="class-depth-2"> <a href="Phaser.Plugin.ColorHarmony.html">ColorHarmony</a> </li> <li class="class-depth-2"> <a href="Phaser.Plugin.CSS3Filters.html">CSS3Filters</a> </li> <li class="class-depth-2"> <a href="Phaser.Plugin.Juicy.html">Juicy</a> </li> <li class="class-depth-3"> <a href="Phaser.Plugin.Juicy.ScreenFlash.html">ScreenFlash</a> </li> <li class="class-depth-3"> <a href="Phaser.Plugin.Juicy.Trail.html">Trail</a> </li> <li class="class-depth-2"> <a href="Phaser.Plugin.KineticScrolling.html">KineticScrolling</a> </li> <li class="class-depth-2"> <a href="Phaser.Plugin.PathManager.html">PathManager</a> </li> <li class="class-depth-2"> <a href="Phaser.Plugin.SamplePlugin.html">SamplePlugin</a> </li> <li class="class-depth-2"> <a href="Phaser.Plugin.TilemapWalker.html">TilemapWalker</a> </li> <li class="class-depth-2"> <a href="Phaser.Plugin.VirtualJoystick.html">VirtualJoystick</a> </li> <li class="class-depth-2"> <a href="Phaser.Plugin.Webcam.html">Webcam</a> </li> <li class="class-depth-1"> <a href="Phaser.PluginManager.html">PluginManager</a> </li> <li class="class-depth-1"> <a href="Phaser.Point.html">Point</a> </li> <li class="class-depth-1"> <a href="Phaser.Pointer.html">Pointer</a> </li> <li class="class-depth-1"> <a href="Phaser.PointerMode.html">PointerMode</a> </li> <li class="class-depth-1"> <a href="Phaser.Polygon.html">Polygon</a> </li> <li class="class-depth-1"> <a href="Phaser.QuadTree.html">QuadTree</a> </li> <li class="class-depth-1"> <a href="Phaser.RandomDataGenerator.html">RandomDataGenerator</a> </li> <li class="class-depth-1"> <a href="Phaser.Rectangle.html">Rectangle</a> </li> <li class="class-depth-1"> <a href="Phaser.RenderTexture.html">RenderTexture</a> </li> <li class="class-depth-1"> <a href="Phaser.RequestAnimationFrame.html">RequestAnimationFrame</a> </li> <li class="class-depth-1"> <a href="Phaser.RetroFont.html">RetroFont</a> </li> <li class="class-depth-1"> <a href="Phaser.Rope.html">Rope</a> </li> <li class="class-depth-1"> <a href="Phaser.RoundedRectangle.html">RoundedRectangle</a> </li> <li class="class-depth-1"> <a href="Phaser.ScaleManager.html">ScaleManager</a> </li> <li class="class-depth-1"> <a href="Phaser.Signal.html">Signal</a> </li> <li class="class-depth-1"> <a href="Phaser.SignalBinding.html">SignalBinding</a> </li> <li class="class-depth-1"> <a href="Phaser.SinglePad.html">SinglePad</a> </li> <li class="class-depth-1"> <a href="Phaser.Sound.html">Sound</a> </li> <li class="class-depth-1"> <a href="Phaser.SoundManager.html">SoundManager</a> </li> <li class="class-depth-1"> <a href="Phaser.Sprite.html">Sprite</a> </li> <li class="class-depth-1"> <a href="Phaser.SpriteBatch.html">SpriteBatch</a> </li> <li class="class-depth-1"> <a href="Phaser.Stage.html">Stage</a> </li> <li class="class-depth-1"> <a href="Phaser.State.html">State</a> </li> <li class="class-depth-1"> <a href="Phaser.StateManager.html">StateManager</a> </li> <li class="class-depth-1"> <a href="Phaser.Text.html">Text</a> </li> <li class="class-depth-1"> <a href="Phaser.Tile.html">Tile</a> </li> <li class="class-depth-1"> <a href="Phaser.Tilemap.html">Tilemap</a> </li> <li class="class-depth-1"> <a href="Phaser.TilemapLayer.html">TilemapLayer</a> </li> <li class="class-depth-1"> <a href="Phaser.TilemapParser.html">TilemapParser</a> </li> <li class="class-depth-1"> <a href="Phaser.Tileset.html">Tileset</a> </li> <li class="class-depth-1"> <a href="Phaser.TileSprite.html">TileSprite</a> </li> <li class="class-depth-1"> <a href="Phaser.Time.html">Time</a> </li> <li class="class-depth-1"> <a href="Phaser.Timer.html">Timer</a> </li> <li class="class-depth-1"> <a href="Phaser.TimerEvent.html">TimerEvent</a> </li> <li class="class-depth-1"> <a href="Phaser.Touch.html">Touch</a> </li> <li class="class-depth-1"> <a href="Phaser.Tween.html">Tween</a> </li> <li class="class-depth-1"> <a href="Phaser.TweenData.html">TweenData</a> </li> <li class="class-depth-1"> <a href="Phaser.TweenManager.html">TweenManager</a> </li> <li class="class-depth-1"> <a href="Phaser.Utils.html">Utils</a> </li> <li class="class-depth-2"> <a href="Phaser.Utils.Debug.html">Debug</a> </li> <li class="class-depth-1"> <a href="Phaser.Video.html">Video</a> </li> <li class="class-depth-1"> <a href="Phaser.Weapon.html">Weapon</a> </li> <li class="class-depth-1"> <a href="Phaser.World.html">World</a> </li> <li class="class-depth-1"> <a href="PIXI.BaseTexture.html">BaseTexture</a> </li> <li class="class-depth-1"> <a href="PIXI.CanvasBuffer.html">CanvasBuffer</a> </li> <li class="class-depth-1"> <a href="PIXI.CanvasGraphics.html">CanvasGraphics</a> </li> <li class="class-depth-1"> <a href="PIXI.CanvasMaskManager.html">CanvasMaskManager</a> </li> <li class="class-depth-1"> <a href="PIXI.CanvasRenderer.html">CanvasRenderer</a> </li> <li class="class-depth-1"> <a href="PIXI.CanvasTinter.html">CanvasTinter</a> </li> <li class="class-depth-1"> <a href="PIXI.ComplexPrimitiveShader.html">ComplexPrimitiveShader</a> </li> <li class="class-depth-1"> <a href="PIXI.DisplayObject.html">DisplayObject</a> </li> <li class="class-depth-1"> <a href="PIXI.DisplayObjectContainer.html">DisplayObjectContainer</a> </li> <li class="class-depth-1"> <a href="PIXI.FilterTexture.html">FilterTexture</a> </li> <li class="class-depth-2"> <a href="PIXI.Phaser.GraphicsData.html">Phaser.GraphicsData</a> </li> <li class="class-depth-1"> <a href="PIXI.PIXI.html">PIXI</a> </li> <li class="class-depth-1"> <a href="PIXI.PixiFastShader.html">PixiFastShader</a> </li> <li class="class-depth-1"> <a href="PIXI.PixiShader.html">PixiShader</a> </li> <li class="class-depth-1"> <a href="PIXI.PrimitiveShader.html">PrimitiveShader</a> </li> <li class="class-depth-1"> <a href="PIXI.Sprite.html">Sprite</a> </li> <li class="class-depth-1"> <a href="PIXI.StripShader.html">StripShader</a> </li> <li class="class-depth-1"> <a href="PIXI.Texture.html">Texture</a> </li> <li class="class-depth-1"> <a href="PIXI.WebGLBlendModeManager.html">WebGLBlendModeManager</a> </li> <li class="class-depth-1"> <a href="PIXI.WebGLFastSpriteBatch.html">WebGLFastSpriteBatch</a> </li> <li class="class-depth-1"> <a href="PIXI.WebGLFilterManager.html">WebGLFilterManager</a> </li> <li class="class-depth-1"> <a href="PIXI.WebGLRenderer.html">WebGLRenderer</a> </li> </ul> </li> <li class="dropdown"> <a href="global.html" class="dropdown-toggle" data-toggle="dropdown">Global<b class="caret"></b></a> <ul class="dropdown-menu "> <li class="class-depth-0"> <a href="global.html#destroy">destroy</a> </li> <li class="class-depth-0"> <a href="global.html#init">init</a> </li> <li class="class-depth-0"> <a href="global.html#set">set</a> </li> </ul> </li> <li class="dropdown"> <a href="#" class="dropdown-toggle" data-toggle="dropdown">Core<b class="caret"></b></a> <ul class="dropdown-menu "> <li class="class-depth-1"><a href="Phaser.Game.html">Game</a></li> <li class="class-depth-1"><a href="Phaser.Group.html">Group</a></li> <li class="class-depth-1"><a href="Phaser.World.html">World</a></li> <li class="class-depth-1"><a href="Phaser.Loader.html">Loader</a></li> <li class="class-depth-1"><a href="Phaser.Cache.html">Cache</a></li> <li class="class-depth-1"><a href="Phaser.Time.html">Time</a></li> <li class="class-depth-1"><a href="Phaser.Camera.html">Camera</a></li> <li class="class-depth-1"><a href="Phaser.StateManager.html">State Manager</a></li> <li class="class-depth-1"><a href="Phaser.TweenManager.html">Tween Manager</a></li> <li class="class-depth-1"><a href="Phaser.SoundManager.html">Sound Manager</a></li> <li class="class-depth-1"><a href="Phaser.Input.html">Input Manager</a></li> <li class="class-depth-1"><a href="Phaser.ScaleManager.html">Scale Manager</a></li> </ul> </li> <li class="dropdown"> <a href="#" class="dropdown-toggle" data-toggle="dropdown">Game Objects<b class="caret"></b></a> <ul class="dropdown-menu "> <li class="class-depth-1"><a href="Phaser.GameObjectFactory.html">Factory (game.add)</a></li> <li class="class-depth-1"><a href="Phaser.GameObjectCreator.html">Creator (game.make)</a></li> <li class="class-depth-1"><a href="Phaser.Sprite.html">Sprite</a></li> <li class="class-depth-1"><a href="Phaser.Image.html">Image</a></li> <li class="class-depth-1"><a href="Phaser.Sound.html">Sound</a></li> <li class="class-depth-1"><a href="Phaser.Video.html">Video</a></li> <li class="class-depth-1"><a href="Phaser.Particles.Arcade.Emitter.html">Particle Emitter</a></li> <li class="class-depth-1"><a href="Phaser.Particle.html">Particle</a></li> <li class="class-depth-1"><a href="Phaser.Text.html">Text</a></li> <li class="class-depth-1"><a href="Phaser.Tween.html">Tween</a></li> <li class="class-depth-1"><a href="Phaser.BitmapText.html">BitmapText</a></li> <li class="class-depth-1"><a href="Phaser.Tilemap.html">Tilemap</a></li> <li class="class-depth-1"><a href="Phaser.BitmapData.html">BitmapData</a></li> <li class="class-depth-1"><a href="Phaser.RetroFont.html">RetroFont</a></li> <li class="class-depth-1"><a href="Phaser.Button.html">Button</a></li> <li class="class-depth-1"><a href="Phaser.Animation.html">Animation</a></li> <li class="class-depth-1"><a href="Phaser.Graphics.html">Graphics</a></li> <li class="class-depth-1"><a href="Phaser.RenderTexture.html">RenderTexture</a></li> <li class="class-depth-1"><a href="Phaser.TileSprite.html">TileSprite</a></li> </ul> </li> <li class="dropdown"> <a href="#" class="dropdown-toggle" data-toggle="dropdown">Geometry<b class="caret"></b></a> <ul class="dropdown-menu "> <li class="class-depth-1"><a href="Phaser.Circle.html">Circle</a></li> <li class="class-depth-1"><a href="Phaser.Ellipse.html">Ellipse</a></li> <li class="class-depth-1"><a href="Phaser.Line.html">Line</a></li> <li class="class-depth-1"><a href="Phaser.Matrix.html">Matrix</a></li> <li class="class-depth-1"><a href="Phaser.Point.html">Point</a></li> <li class="class-depth-1"><a href="Phaser.Polygon.html">Polygon</a></li> <li class="class-depth-1"><a href="Phaser.Rectangle.html">Rectangle</a></li> <li class="class-depth-1"><a href="Phaser.RoundedRectangle.html">Rounded Rectangle</a></li> </ul> </li> <li class="dropdown"> <a href="#" class="dropdown-toggle" data-toggle="dropdown">Physics<b class="caret"></b></a> <ul class="dropdown-menu "> <li class="class-depth-1"><a href="Phaser.Physics.Arcade.html">Arcade Physics</a></li> <li class="class-depth-2"><a href="Phaser.Physics.Arcade.Body.html">Body</a></li> <li class="class-depth-2"><a href="Phaser.Weapon.html">Weapon</a></li> <li class="class-depth-1"><a href="Phaser.Physics.P2.html">P2 Physics</a></li> <li class="class-depth-2"><a href="Phaser.Physics.P2.Body.html">Body</a></li> <li class="class-depth-2"><a href="Phaser.Physics.P2.Spring.html">Spring</a></li> <li class="class-depth-2"><a href="Phaser.Physics.P2.CollisionGroup.html">CollisionGroup</a></li> <li class="class-depth-2"><a href="Phaser.Physics.P2.ContactMaterial.html">ContactMaterial</a></li> <li class="class-depth-1"><a href="Phaser.Physics.Ninja.html">Ninja Physics</a></li> <li class="class-depth-2"><a href="Phaser.Physics.Body.html">Body</a></li> </ul> </li> <li class="dropdown"> <a href="#" class="dropdown-toggle" data-toggle="dropdown">Input<b class="caret"></b></a> <ul class="dropdown-menu "> <li class="class-depth-1"><a href="Phaser.InputHandler.html">Input Handler</a></li> <li class="class-depth-1"><a href="Phaser.Pointer.html">Pointer</a></li> <li class="class-depth-1"><a href="Phaser.DeviceButton.html">Device Button</a></li> <li class="class-depth-1"><a href="Phaser.Mouse.html">Mouse</a></li> <li class="class-depth-1"><a href="Phaser.Keyboard.html">Keyboard</a></li> <li class="class-depth-1"><a href="Phaser.Key.html">Key</a></li> <li class="class-depth-1"><a href="Phaser.KeyCode.html">Key Codes</a></li> <li class="class-depth-1"><a href="Phaser.Gamepad.html">Gamepad</a></li> </ul> </li> <li class="dropdown"> <a href="#" class="dropdown-toggle" data-toggle="dropdown"><i class="icon-globe icon-white"></i> Community<b class="caret"></b></a> <ul class="dropdown-menu "> <li class="class-depth-1"><a href="http://phaser.io">Phaser Web Site</a></li> <li class="class-depth-1"><a href="https://github.com/photonstorm/phaser-ce">Phaser CE Github</a></li> <li class="class-depth-1"><a href="http://phaser.io/examples">Phaser Examples</a></li> <li class="class-depth-1"><a href="https://github.com/photonstorm/phaser-plugins">Phaser Plugins</a></li> <li class="class-depth-1"><a href="http://www.html5gamedevs.com/forum/14-phaser/">Forum</a></li> <li class="class-depth-1"><a href="http://stackoverflow.com/questions/tagged/phaser-framework">Stack Overflow</a></li> <li class="class-depth-1"><a href="http://phaser.io/learn">Tutorials</a></li> <li class="class-depth-1"><a href="http://phaser.io/community/newsletter">Newsletter</a></li> <li class="class-depth-1"><a href="http://phaser.io/community/twitter">Twitter</a></li> <li class="class-depth-1"><a href="http://phaser.io/community/slack">Slack</a></li> <li class="class-depth-1"><a href="http://phaser.io/community/donate">Donate</a></li> <li class="class-depth-1"><a href="https://www.codeandweb.com/texturepacker/phaser">Texture Packer</a></li> </ul> </li> </ul> </div> </div> <div class="row-fluid"> <div class="span12"> <div id="main"> <h1 class="page-title">Source: src/tween/TweenManager.js</h1> <section> <article> <pre class="sunlight-highlight-javascript linenums"> /** * Phaser.Game has a single instance of the TweenManager through which all Tween objects are created and updated. * Tweens are hooked into the game clock and pause system, adjusting based on the game state. * * TweenManager is based heavily on tween.js by http://soledadpenades.com. * The difference being that tweens belong to a games instance of TweenManager, rather than to a global TWEEN object. * It also has callbacks swapped for Signals and a few issues patched with regard to properties and completion errors. * Please see https://github.com/sole/tween.js for a full list of contributors. * * @class Phaser.TweenManager * @constructor * @param {Phaser.Game} game - A reference to the currently running game. */ Phaser.TweenManager = function (game) { /** * @property {Phaser.Game} game - Local reference to game. */ this.game = game; /** * Are all newly created Tweens frame or time based? A frame based tween will use the physics elapsed timer when updating. This means * it will retain the same consistent frame rate, regardless of the speed of the device. The duration value given should * be given in frames. * * If the Tween uses a time based update (which is the default) then the duration is given in milliseconds. * In this situation a 2000ms tween will last exactly 2 seconds, regardless of the device and how many visual updates the tween * has actually been through. For very short tweens you may wish to experiment with a frame based update instead. * @property {boolean} frameBased * @default */ this.frameBased = false; /** * @property {array&lt;Phaser.Tween>} _tweens - All of the currently running tweens. * @private */ this._tweens = []; /** * @property {array&lt;Phaser.Tween>} _add - All of the tweens queued to be added in the next update. * @private */ this._add = []; this.easeMap = { "Power0": Phaser.Easing.Power0, "Power1": Phaser.Easing.Power1, "Power2": Phaser.Easing.Power2, "Power3": Phaser.Easing.Power3, "Power4": Phaser.Easing.Power4, "Linear": Phaser.Easing.Linear.None, "Quad": Phaser.Easing.Quadratic.Out, "Cubic": Phaser.Easing.Cubic.Out, "Quart": Phaser.Easing.Quartic.Out, "Quint": Phaser.Easing.Quintic.Out, "Sine": Phaser.Easing.Sinusoidal.Out, "Expo": Phaser.Easing.Exponential.Out, "Circ": Phaser.Easing.Circular.Out, "Elastic": Phaser.Easing.Elastic.Out, "Back": Phaser.Easing.Back.Out, "Bounce": Phaser.Easing.Bounce.Out, "Quad.easeIn": Phaser.Easing.Quadratic.In, "Cubic.easeIn": Phaser.Easing.Cubic.In, "Quart.easeIn": Phaser.Easing.Quartic.In, "Quint.easeIn": Phaser.Easing.Quintic.In, "Sine.easeIn": Phaser.Easing.Sinusoidal.In, "Expo.easeIn": Phaser.Easing.Exponential.In, "Circ.easeIn": Phaser.Easing.Circular.In, "Elastic.easeIn": Phaser.Easing.Elastic.In, "Back.easeIn": Phaser.Easing.Back.In, "Bounce.easeIn": Phaser.Easing.Bounce.In, "Quad.easeOut": Phaser.Easing.Quadratic.Out, "Cubic.easeOut": Phaser.Easing.Cubic.Out, "Quart.easeOut": Phaser.Easing.Quartic.Out, "Quint.easeOut": Phaser.Easing.Quintic.Out, "Sine.easeOut": Phaser.Easing.Sinusoidal.Out, "Expo.easeOut": Phaser.Easing.Exponential.Out, "Circ.easeOut": Phaser.Easing.Circular.Out, "Elastic.easeOut": Phaser.Easing.Elastic.Out, "Back.easeOut": Phaser.Easing.Back.Out, "Bounce.easeOut": Phaser.Easing.Bounce.Out, "Quad.easeInOut": Phaser.Easing.Quadratic.InOut, "Cubic.easeInOut": Phaser.Easing.Cubic.InOut, "Quart.easeInOut": Phaser.Easing.Quartic.InOut, "Quint.easeInOut": Phaser.Easing.Quintic.InOut, "Sine.easeInOut": Phaser.Easing.Sinusoidal.InOut, "Expo.easeInOut": Phaser.Easing.Exponential.InOut, "Circ.easeInOut": Phaser.Easing.Circular.InOut, "Elastic.easeInOut": Phaser.Easing.Elastic.InOut, "Back.easeInOut": Phaser.Easing.Back.InOut, "Bounce.easeInOut": Phaser.Easing.Bounce.InOut }; this.game.onPause.add(this._pauseAll, this); this.game.onResume.add(this._resumeAll, this); }; Phaser.TweenManager.prototype = { /** * Get all the tween objects in an array. * @method Phaser.TweenManager#getAll * @returns {Phaser.Tween[]} Array with all tween objects. */ getAll: function () { return this._tweens; }, /** * Remove all tweens running and in the queue. Doesn't call any of the tween onComplete events. * @method Phaser.TweenManager#removeAll */ removeAll: function () { for (var i = 0; i &lt; this._tweens.length; i++) { this._tweens[i].pendingDelete = true; } this._add = []; }, /** * Remove all tweens from a specific object, array of objects or Group. * * @method Phaser.TweenManager#removeFrom * @param {object|object[]|Phaser.Group} obj - The object you want to remove the tweens from. * @param {boolean} [children=true] - If passing a group, setting this to true will remove the tweens from all of its children instead of the group itself. */ removeFrom: function (obj, children) { if (children === undefined) { children = true; } var i; var len; if (Array.isArray(obj)) { for (i = 0, len = obj.length; i &lt; len; i++) { this.removeFrom(obj[i]); } } else if (obj.type === Phaser.GROUP &amp;&amp; children) { for (var i = 0, len = obj.children.length; i &lt; len; i++) { this.removeFrom(obj.children[i]); } } else { for (i = 0, len = this._tweens.length; i &lt; len; i++) { if (obj === this._tweens[i].target) { this.remove(this._tweens[i]); } } for (i = 0, len = this._add.length; i &lt; len; i++) { if (obj === this._add[i].target) { this.remove(this._add[i]); } } } }, /** * Add a new tween into the TweenManager. * * @method Phaser.TweenManager#add * @param {Phaser.Tween} tween - The tween object you want to add. * @returns {Phaser.Tween} The tween object you added to the manager. */ add: function (tween) { tween._manager = this; this._add.push(tween); }, /** * Create a tween object for a specific object. The object can be any JavaScript object or Phaser object such as Sprite. * * @method Phaser.TweenManager#create * @param {object} object - Object the tween will be run on. * @returns {Phaser.Tween} The newly created tween object. */ create: function (object) { return new Phaser.Tween(object, this.game, this); }, /** * Remove a tween from this manager. * * @method Phaser.TweenManager#remove * @param {Phaser.Tween} tween - The tween object you want to remove. */ remove: function (tween) { var i = this._tweens.indexOf(tween); if (i !== -1) { this._tweens[i].pendingDelete = true; } else { i = this._add.indexOf(tween); if (i !== -1) { this._add[i].pendingDelete = true; } } }, /** * Update all the tween objects you added to this manager. * * @method Phaser.TweenManager#update * @returns {boolean} Return false if there's no tween to update, otherwise return true. */ update: function () { var addTweens = this._add.length; var numTweens = this._tweens.length; if (numTweens === 0 &amp;&amp; addTweens === 0) { return false; } var i = 0; while (i &lt; numTweens) { if (this._tweens[i].update(this.game.time.time)) { i++; } else { this._tweens.splice(i, 1); numTweens--; } } // If there are any new tweens to be added, do so now - otherwise they can be spliced out of the array before ever running if (addTweens > 0) { this._tweens = this._tweens.concat(this._add); this._add.length = 0; } return true; }, /** * Checks to see if a particular Sprite is currently being tweened. * * @method Phaser.TweenManager#isTweening * @param {object} object - The object to check for tweens against. * @returns {boolean} Returns true if the object is currently being tweened, false if not. */ isTweening: function(object) { return this._tweens.some(function(tween) { return tween.target === object; }); }, /** * Private. Called by game focus loss. Pauses all currently running tweens. * * @method Phaser.TweenManager#_pauseAll * @private */ _pauseAll: function () { for (var i = this._tweens.length - 1; i >= 0; i--) { this._tweens[i]._pause(); } }, /** * Private. Called by game focus loss. Resumes all currently paused tweens. * * @method Phaser.TweenManager#_resumeAll * @private */ _resumeAll: function () { for (var i = this._tweens.length - 1; i >= 0; i--) { this._tweens[i]._resume(); } }, /** * Pauses all currently running tweens. * * @method Phaser.TweenManager#pauseAll */ pauseAll: function () { for (var i = this._tweens.length - 1; i >= 0; i--) { this._tweens[i].pause(); } }, /** * Resumes all currently paused tweens. * * @method Phaser.TweenManager#resumeAll */ resumeAll: function () { for (var i = this._tweens.length - 1; i >= 0; i--) { this._tweens[i].resume(true); } } }; Phaser.TweenManager.prototype.constructor = Phaser.TweenManager; </pre> </article> </section> </div> <div class="clearfix"></div> <footer> <span class="copyright"> Phaser Copyright © 2012-2016 Photon Storm Ltd. </span> <br /> <span class="jsdoc-message"> Documentation generated by <a href="https://github.com/jsdoc3/jsdoc">JSDoc 3.5.3</a> on Fri Jul 21 2017 07:19:16 GMT-0700 (PDT) using the <a href="https://github.com/terryweiss/docstrap">DocStrap template</a>. </span> </footer> </div> <br clear="both"> </div> </div> <script src="scripts/sunlight.js"></script> <script src="scripts/sunlight.javascript.js"></script> <script src="scripts/sunlight-plugin.doclinks.js"></script> <script src="scripts/sunlight-plugin.linenumbers.js"></script> <script src="scripts/sunlight-plugin.menu.js"></script> <script src="scripts/jquery.min.js"></script> <script src="scripts/jquery.scrollTo.js"></script> <script src="scripts/jquery.localScroll.js"></script> <script src="scripts/bootstrap-dropdown.js"></script> <script src="scripts/toc.js"></script> <script> Sunlight.highlightAll({lineNumbers:true, showMenu: true, enableDoclinks :true}); </script> <script> $( function () { $( "#toc" ).toc( { anchorName : function(i, heading, prefix) { return $(heading).attr("id") || ( prefix + i ); }, selectors : "h1,h2,h3,h4", showAndHide : false, scrollTo : 60 } ); $( "#toc>ul" ).addClass( "nav nav-pills nav-stacked" ); $( "#main span[id^='toc']" ).addClass( "toc-shim" ); } ); </script> </body> </html>
{ "content_hash": "e37765c8be492467fdf67f7078d88555", "timestamp": "", "source": "github", "line_count": 1437, "max_line_length": 177, "avg_line_length": 30.25678496868476, "alnum_prop": 0.5605234711009913, "repo_name": "agusto3/phaserPrototype", "id": "d6648723b909788f378fd5ad3a1be0189128b642", "size": "43680", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "docs/src_tween_TweenManager.js.html", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "201761" }, { "name": "HTML", "bytes": "169926" }, { "name": "JavaScript", "bytes": "20170613" }, { "name": "PHP", "bytes": "87936" }, { "name": "TypeScript", "bytes": "4168" } ], "symlink_target": "" }
#ifndef FMGRTAB_H #define FMGRTAB_H #include "access/transam.h" #include "fmgr.h" /* * This table stores info about all the built-in functions (ie, functions * that are compiled into the Postgres executable). */ typedef struct { Oid foid; /* OID of the function */ short nargs; /* 0..FUNC_MAX_ARGS, or -1 if variable count */ bool strict; /* T if function is "strict" */ bool retset; /* T if function returns a set */ const char *funcName; /* C name of the function */ PGFunction func; /* pointer to compiled function */ } FmgrBuiltin; extern const FmgrBuiltin fmgr_builtins[]; extern const int fmgr_nbuiltins; /* number of entries in table */ extern const Oid fmgr_last_builtin_oid; /* highest function OID in table */ /* * Mapping from a builtin function's OID to its index in the fmgr_builtins * array. This is indexed from 0 through fmgr_last_builtin_oid. */ #define InvalidOidBuiltinMapping PG_UINT16_MAX extern const uint16 fmgr_builtin_oid_index[]; #endif /* FMGRTAB_H */
{ "content_hash": "779775fa245829e75db59d2bf88cf9a6", "timestamp": "", "source": "github", "line_count": 37, "max_line_length": 75, "avg_line_length": 27.675675675675677, "alnum_prop": 0.69921875, "repo_name": "greenplum-db/gpdb", "id": "e981f34934733b905334ee9038deb368aabc6a64", "size": "1437", "binary": false, "copies": "11", "ref": "refs/heads/main", "path": "src/include/utils/fmgrtab.h", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Assembly", "bytes": "3266" }, { "name": "Awk", "bytes": "836" }, { "name": "Batchfile", "bytes": "15613" }, { "name": "C", "bytes": "48211707" }, { "name": "C++", "bytes": "12681024" }, { "name": "CMake", "bytes": "41408" }, { "name": "DTrace", "bytes": "3833" }, { "name": "Emacs Lisp", "bytes": "4164" }, { "name": "Fortran", "bytes": "14873" }, { "name": "GDB", "bytes": "576" }, { "name": "Gherkin", "bytes": "504216" }, { "name": "HTML", "bytes": "215381" }, { "name": "JavaScript", "bytes": "23969" }, { "name": "Lex", "bytes": "254578" }, { "name": "M4", "bytes": "133878" }, { "name": "Makefile", "bytes": "511186" }, { "name": "PLpgSQL", "bytes": "9280413" }, { "name": "Perl", "bytes": "1161283" }, { "name": "PowerShell", "bytes": "422" }, { "name": "Python", "bytes": "3404111" }, { "name": "Roff", "bytes": "30385" }, { "name": "Ruby", "bytes": "299639" }, { "name": "SCSS", "bytes": "339" }, { "name": "Shell", "bytes": "403369" }, { "name": "XS", "bytes": "7098" }, { "name": "XSLT", "bytes": "448" }, { "name": "Yacc", "bytes": "748098" }, { "name": "sed", "bytes": "1231" } ], "symlink_target": "" }
package org.gradle.test.performance.mediummonolithicjavaproject.p226; public class Production4538 { private String property0; public String getProperty0() { return property0; } public void setProperty0(String value) { property0 = value; } private String property1; public String getProperty1() { return property1; } public void setProperty1(String value) { property1 = value; } private String property2; public String getProperty2() { return property2; } public void setProperty2(String value) { property2 = value; } private String property3; public String getProperty3() { return property3; } public void setProperty3(String value) { property3 = value; } private String property4; public String getProperty4() { return property4; } public void setProperty4(String value) { property4 = value; } private String property5; public String getProperty5() { return property5; } public void setProperty5(String value) { property5 = value; } private String property6; public String getProperty6() { return property6; } public void setProperty6(String value) { property6 = value; } private String property7; public String getProperty7() { return property7; } public void setProperty7(String value) { property7 = value; } private String property8; public String getProperty8() { return property8; } public void setProperty8(String value) { property8 = value; } private String property9; public String getProperty9() { return property9; } public void setProperty9(String value) { property9 = value; } }
{ "content_hash": "e35b5044fe29d54b8918ef4efd452a13", "timestamp": "", "source": "github", "line_count": 105, "max_line_length": 69, "avg_line_length": 18.00952380952381, "alnum_prop": 0.6171337916446324, "repo_name": "oehme/analysing-gradle-performance", "id": "9b524cb6b5a4556b68eb542a928e61d4f28158c8", "size": "1891", "binary": false, "copies": "1", "ref": "refs/heads/before", "path": "my-app/src/main/java/org/gradle/test/performance/mediummonolithicjavaproject/p226/Production4538.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "40770723" } ], "symlink_target": "" }
""" Created on Jan 21, 2020 @author: alfoa, wangc Gaussian process regression (GPR) """ #Internal Modules (Lazy Importer)-------------------------------------------------------------------- #Internal Modules (Lazy Importer) End---------------------------------------------------------------- #External Modules------------------------------------------------------------------------------------ #External Modules End-------------------------------------------------------------------------------- #Internal Modules------------------------------------------------------------------------------------ from ....SupervisedLearning.ScikitLearn import ScikitLearnBase from ....utils import utils from ....utils import InputData, InputTypes #Internal Modules End-------------------------------------------------------------------------------- class GaussianProcessRegressor(ScikitLearnBase): """ Gaussian process regression (GPR) """ info = {'problemtype':'regression', 'normalize':False} def __init__(self): """ Constructor that will appropriately initialize a supervised learning object @ In, None @ Out, None """ super().__init__() import sklearn import sklearn.gaussian_process self.model = sklearn.gaussian_process.GaussianProcessRegressor @classmethod def getInputSpecification(cls): """ Method to get a reference to a class that specifies the input data for class cls. @ In, cls, the class for which we are retrieving the specification @ Out, inputSpecification, InputData.ParameterInput, class to use for specifying input of cls. """ specs = super(GaussianProcessRegressor, cls).getInputSpecification() specs.description = r"""The \xmlNode{GaussianProcessRegressor} is based on Algorithm 2.1 of Gaussian Processes for Machine Learning (GPML) by Rasmussen and Williams. The method is a generic supervised learning method primarily designed to solve regression problems. The advantages of Gaussian Processes for Machine Learning are: \begin{itemize} \item The prediction interpolates the observations (at least for regular correlation models). \item The prediction is probabilistic (Gaussian) so that one can compute empirical confidence intervals and exceedance probabilities that might be used to refit (online fitting, adaptive fitting) the prediction in some region of interest. \item Versatile: different linear regression models and correlation models can be specified. Common models are provided, but it is also possible to specify custom models provided they are stationary. \end{itemize} The disadvantages of Gaussian Processes for Machine Learning include: \begin{itemize} \item It is not sparse. It uses the whole samples/features information to perform the prediction. \item It loses efficiency in high dimensional spaces – namely when the number of features exceeds a few dozens. It might indeed give poor performance and it loses computational efficiency. \item Classification is only a post-processing, meaning that one first needs to solve a regression problem by providing the complete scalar float precision output $y$ of the experiment one is attempting to model. \end{itemize} \zNormalizationNotPerformed{GaussianProcessRegressor} """ # create kernel node specs.addSub(InputData.parameterInputFactory("kernel", contentType=InputTypes.makeEnumType("kernel", "kernelType",['Constant', 'DotProduct', 'ExpSineSquared', 'Exponentiation', 'Matern','PairwiseLinear','PairwiseAdditiveChi2','PairwiseChi2','PairwisePoly','PairwisePolynomial','PairwiseRBF','PairwiseLaplassian','PairwiseSigmoid','PairwiseCosine', 'RBF', 'RationalQuadratic']), descr=r"""The kernel specifying the covariance function of the GP. If None is passed, the kernel $Constant$ is used as default. The kernel hyperparameters are optimized during fitting and consequentially the hyperparameters are not inputable. The following kernels are avaialable: \begin{itemize} \item Constant, Constant kernel: $k(x_1, x_2) = constant\_value \;\forall\; x_1, x_2$. \item DotProduct, it is non-stationary and can be obtained from linear regression by putting $N(0, 1)$ priors on the coefficients of $x_d (d = 1, . . . , D)$ and a prior of $N(0, \sigma_0^2)$ on the bias. The DotProduct kernel is invariant to a rotation of the coordinates about the origin, but not translations. It is parameterized by a parameter sigma\_0 $\sigma$ which controls the inhomogenity of the kernel. \item ExpSineSquared, it allows one to model functions which repeat themselves exactly. It is parameterized by a length scale parameter $l>0$ and a periodicity parameter $p>0$. The kernel is given by $k(x_i, x_j) = \text{exp}\left(-\frac{ 2\sin^2(\pi d(x_i, x_j)/p) }{ l^ 2} \right)$ where $d(\\cdot,\\cdot)$ is the Euclidean distance. \item Exponentiation, it takes one base kernel and a scalar parameter $p$ and combines them via $k_{exp}(X, Y) = k(X, Y) ^p$. \item Matern, is a generalization of the RBF. It has an additional parameter $\nu$ which controls the smoothness of the resulting function. The smaller $\nu$, the less smooth the approximated function is. As $\nu\rightarrow\infty$, the kernel becomes equivalent to the RBF kernel. When $\nu = 1/2$, the Matérn kernel becomes identical to the absolute exponential kernel. Important intermediate values are $\nu = 1.5$ (once differentiable functions) and $\nu = 2.5$ (twice differentiable functions). The kernel is given by $k(x_i, x_j) = \frac{1}{\Gamma(\nu)2^{\nu-1}}\Bigg( \frac{\sqrt{2\nu}}{l} d(x_i , x_j ) \Bigg)^\nu K_\nu\Bigg( \frac{\sqrt{2\nu}}{l} d(x_i , x_j )\Bigg)$ where $d(\cdot,\cdot)$ is the Euclidean distance, $K_{\nu}(\cdot)$ is a modified Bessel function and $\Gamma(\cdot)$ is the gamma function. \item PairwiseLinear, it is a thin wrapper around the functionality of the pairwise kernels. It uses the a linear metric to calculate kernel between instances in a feature array. Evaluation of the gradient is not analytic but numeric and all kernels support only isotropic distances. \item PairwiseAdditiveChi2, it is a thin wrapper around the functionality of the pairwise metrics. It uses the an additive chi squared metric to calculate kernel between instances in a feature array. Evaluation of the gradient is not analytic but numeric and all kernels support only isotropic distances. \item PairwiseChi2, it is a thin wrapper around the functionality of the pairwise metrics. It uses the a chi squared metric to calculate kernel between instances in a feature array. Evaluation of the gradient is not analytic but numeric and all kernels support only isotropic distances. \item PairwisePoly, it is a thin wrapper around the functionality of the pairwise metrics. It uses the a poly metric to calculate kernel between instances in a feature array. Evaluation of the gradient is not analytic but numeric and all kernels support only isotropic distances. \item PairwisePolynomial, it is a thin wrapper around the functionality of the pairwise metrics. It uses the a polynomial metric to calculate kernel between instances in a feature array. Evaluation of the gradient is not analytic but numeric and all kernels support only isotropic distances. \item PairwiseRbf, it is a thin wrapper around the functionality of the pairwise metrics. It uses the a rbf metric to calculate kernel between instances in a feature array. Evaluation of the gradient is not analytic but numeric and all kernels support only isotropic distances. \item PairwiseLaplacian, it is a thin wrapper around the functionality of the pairwise metrics. It uses the a laplacian metric to calculate kernel between instances in a feature array. Evaluation of the gradient is not analytic but numeric and all kernels support only isotropic distances. \item PairwiseSigmoid, it is a thin wrapper around the functionality of the pairwise metrics. It uses the a sigmoid metric to calculate kernel between instances in a feature array. Evaluation of the gradient is not analytic but numeric and all kernels support only isotropic distances. \item PairwiseCosine, it is a thin wrapper around the functionality of the pairwise metrics. It uses the a cosine metric to calculate kernel between instances in a feature array. Evaluation of the gradient is not analytic but numeric and all kernels support only isotropic distances. \item RBF, it is a stationary kernel. It is also known as the ``squared exponential'' kernel. It is parameterized by a length scale parameter $l>0$, which can either be a scalar (isotropic variant of the kernel) or a vector with the same number of dimensions as the inputs $X$ (anisotropic variant of the kernel). The kernel is given by $k(x_i, x_j) = \exp\left(- \frac{d(x_i, x_j)^2}{2l^2} \right)$ where $l$ is the length scale of the kernel and $d(\cdot,\cdot)$ is the Euclidean distance. \item RationalQuadratic, it can be seen as a scale mixture (an infinite sum) of RBF kernels with different characteristic length scales. It is parameterized by a length scale parameter $l>0$ and a scale mixture parameter $\alpha>0$ . The kernel is given by $k(x_i, x_j) = \left(1 + \frac{d(x_i, x_j)^2 }{ 2\alpha l^2}\right)^{-\alpha}$ where $d(\cdot,\cdot)$ is the Euclidean distance. \end{itemize}.""",default=None)) specs.addSub(InputData.parameterInputFactory("alpha", contentType=InputTypes.FloatType, descr=r"""Value added to the diagonal of the kernel matrix during fitting. This can prevent a potential numerical issue during fitting, by ensuring that the calculated values form a positive definite matrix. It can also be interpreted as the variance of additional Gaussian measurement noise on the training observations.""",default=1e-10)) specs.addSub(InputData.parameterInputFactory("n_restarts_optimizer", contentType=InputTypes.IntegerType, descr=r"""The number of restarts of the optimizer for finding the kernel's parameters which maximize the log-marginal likelihood. The first run of the optimizer is performed from the kernel's initial parameters, the remaining ones (if any) from thetas sampled log-uniform randomly from the space of allowed theta-values. If greater than 0, all bounds must be finite.""", default=0)) specs.addSub(InputData.parameterInputFactory("normalize_y", contentType=InputTypes.BoolType, descr=r"""Whether the target values y are normalized, the mean and variance of the target values are set equal to 0 and 1 respectively. This is recommended for cases where zero-mean, unit-variance priors are used.""",default=False )) specs.addSub(InputData.parameterInputFactory("random_state", contentType=InputTypes.IntegerType, descr=r"""Seed for the internal random number generator.""",default=None)) specs.addSub(InputData.parameterInputFactory("optimizer", contentType=InputTypes.makeEnumType("optimizer", "optimizerType",['fmin_l_bfgs_b']), descr=r"""Per default, the 'L-BFGS-B' algorithm from scipy.optimize.minimize is used. If None is passed, the kernel’s parameters are kept fixed.""",default='fmin_l_bfgs_b')) return specs def pickKernel(self, name): """ This method is used to pick a kernel from the iternal factory @ In, name, str, the kernel name @ Out, kernel, object, the kernel object """ import sklearn if name.lower() == 'constant': kernel = sklearn.gaussian_process.kernels.ConstantKernel() elif name.lower() == 'dotproduct': kernel = sklearn.gaussian_process.kernels.DotProduct() elif name.lower() == 'expsinesquared': kernel = sklearn.gaussian_process.kernels.ExpSineSquared() elif name.lower() == 'exponentiation': kernel = sklearn.gaussian_process.kernels.Exponentiation() elif name.lower() == 'matern': kernel = sklearn.gaussian_process.kernels.Matern() elif name.lower() == 'pairwiselinear': kernel = sklearn.gaussian_process.kernels.PairwiseKernel(metric='linear') elif name.lower() == 'pairwiseadditivechi2': kernel = sklearn.gaussian_process.kernels.PairwiseKernel(metric='additive_chi2') elif name.lower() == 'pairwisechi2': kernel = sklearn.gaussian_process.kernels.PairwiseKernel(metric='chi2') elif name.lower() == 'pairwisepoly': kernel = sklearn.gaussian_process.kernels.PairwiseKernel(metric='poly') elif name.lower() == 'pairwisepolynomial': kernel = sklearn.gaussian_process.kernels.PairwiseKernel(metric='polynomial') elif name.lower() == 'pairwiserbf': kernel = sklearn.gaussian_process.kernels.PairwiseKernel(metric='rbf') elif name.lower() == 'pairwiselaplacian': kernel = sklearn.gaussian_process.kernels.PairwiseKernel(metric='laplacian') elif name.lower() == 'pairwisesigmoid': kernel = sklearn.gaussian_process.kernels.PairwiseKernel(metric='sigmoid') elif name.lower() == 'pairwisecosine': kernel = sklearn.gaussian_process.kernels.PairwiseKernel(metric='cosine') elif name.lower() == 'rbf': kernel = sklearn.gaussian_process.kernels.RBF() elif name.lower() == 'rationalquadratic': kernel = sklearn.gaussian_process.kernels.RationalQuadratic() return kernel def _handleInput(self, paramInput): """ Function to handle the common parts of the distribution parameter input. @ In, paramInput, ParameterInput, the already parsed input. @ Out, None """ super()._handleInput(paramInput) settings, notFound = paramInput.findNodesAndExtractValues(['kernel', 'alpha', 'n_restarts_optimizer', 'normalize_y', 'random_state', 'optimizer']) # notFound must be empty assert(not notFound) # special treatment for kernel settings['kernel'] = self.pickKernel(settings['kernel']) if settings['kernel'] is not None else None self.initializeModel(settings)
{ "content_hash": "63c1398331cc3810a5ff47b307c4ab8d", "timestamp": "", "source": "github", "line_count": 194, "max_line_length": 315, "avg_line_length": 90.77835051546391, "alnum_prop": 0.5709499744477883, "repo_name": "joshua-cogliati-inl/raven", "id": "6c7963aa28667d0db21466764bbd2dbbe34aaf36", "size": "18205", "binary": false, "copies": "2", "ref": "refs/heads/devel", "path": "ravenframework/SupervisedLearning/ScikitLearn/GaussianProcess/GaussianProcessRegressor.py", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Assembly", "bytes": "1556080" }, { "name": "Batchfile", "bytes": "1095" }, { "name": "C", "bytes": "148504" }, { "name": "C++", "bytes": "48279546" }, { "name": "CMake", "bytes": "9998" }, { "name": "Jupyter Notebook", "bytes": "84202" }, { "name": "MATLAB", "bytes": "202335" }, { "name": "Makefile", "bytes": "2399" }, { "name": "Perl", "bytes": "1297" }, { "name": "Python", "bytes": "6952659" }, { "name": "R", "bytes": "67" }, { "name": "SWIG", "bytes": "8574" }, { "name": "Shell", "bytes": "124279" }, { "name": "TeX", "bytes": "479725" } ], "symlink_target": "" }
using System; using System.Collections.Generic; using System.ComponentModel; using System.Net.Http.Headers; namespace SDS.Clould.WebAPI.Areas.HelpPage { /// <summary> /// This is used to identify the place where the sample should be applied. /// </summary> public class HelpPageSampleKey { /// <summary> /// Creates a new <see cref="HelpPageSampleKey"/> based on media type. /// </summary> /// <param name="mediaType">The media type.</param> public HelpPageSampleKey(MediaTypeHeaderValue mediaType) { if (mediaType == null) { throw new ArgumentNullException("mediaType"); } ActionName = String.Empty; ControllerName = String.Empty; MediaType = mediaType; ParameterNames = new HashSet<string>(StringComparer.OrdinalIgnoreCase); } /// <summary> /// Creates a new <see cref="HelpPageSampleKey"/> based on media type and CLR type. /// </summary> /// <param name="mediaType">The media type.</param> /// <param name="type">The CLR type.</param> public HelpPageSampleKey(MediaTypeHeaderValue mediaType, Type type) : this(mediaType) { if (type == null) { throw new ArgumentNullException("type"); } ParameterType = type; } /// <summary> /// Creates a new <see cref="HelpPageSampleKey"/> based on <see cref="SampleDirection"/>, controller name, action name and parameter names. /// </summary> /// <param name="sampleDirection">The <see cref="SampleDirection"/>.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public HelpPageSampleKey(SampleDirection sampleDirection, string controllerName, string actionName, IEnumerable<string> parameterNames) { if (!Enum.IsDefined(typeof(SampleDirection), sampleDirection)) { throw new InvalidEnumArgumentException("sampleDirection", (int)sampleDirection, typeof(SampleDirection)); } if (controllerName == null) { throw new ArgumentNullException("controllerName"); } if (actionName == null) { throw new ArgumentNullException("actionName"); } if (parameterNames == null) { throw new ArgumentNullException("parameterNames"); } ControllerName = controllerName; ActionName = actionName; ParameterNames = new HashSet<string>(parameterNames, StringComparer.OrdinalIgnoreCase); SampleDirection = sampleDirection; } /// <summary> /// Creates a new <see cref="HelpPageSampleKey"/> based on media type, <see cref="SampleDirection"/>, controller name, action name and parameter names. /// </summary> /// <param name="mediaType">The media type.</param> /// <param name="sampleDirection">The <see cref="SampleDirection"/>.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public HelpPageSampleKey(MediaTypeHeaderValue mediaType, SampleDirection sampleDirection, string controllerName, string actionName, IEnumerable<string> parameterNames) : this(sampleDirection, controllerName, actionName, parameterNames) { if (mediaType == null) { throw new ArgumentNullException("mediaType"); } MediaType = mediaType; } /// <summary> /// Gets the name of the controller. /// </summary> /// <value> /// The name of the controller. /// </value> public string ControllerName { get; private set; } /// <summary> /// Gets the name of the action. /// </summary> /// <value> /// The name of the action. /// </value> public string ActionName { get; private set; } /// <summary> /// Gets the media type. /// </summary> /// <value> /// The media type. /// </value> public MediaTypeHeaderValue MediaType { get; private set; } /// <summary> /// Gets the parameter names. /// </summary> public HashSet<string> ParameterNames { get; private set; } public Type ParameterType { get; private set; } /// <summary> /// Gets the <see cref="SampleDirection"/>. /// </summary> public SampleDirection? SampleDirection { get; private set; } public override bool Equals(object obj) { HelpPageSampleKey otherKey = obj as HelpPageSampleKey; if (otherKey == null) { return false; } return String.Equals(ControllerName, otherKey.ControllerName, StringComparison.OrdinalIgnoreCase) && String.Equals(ActionName, otherKey.ActionName, StringComparison.OrdinalIgnoreCase) && (MediaType == otherKey.MediaType || (MediaType != null && MediaType.Equals(otherKey.MediaType))) && ParameterType == otherKey.ParameterType && SampleDirection == otherKey.SampleDirection && ParameterNames.SetEquals(otherKey.ParameterNames); } public override int GetHashCode() { int hashCode = ControllerName.ToUpperInvariant().GetHashCode() ^ ActionName.ToUpperInvariant().GetHashCode(); if (MediaType != null) { hashCode ^= MediaType.GetHashCode(); } if (SampleDirection != null) { hashCode ^= SampleDirection.GetHashCode(); } if (ParameterType != null) { hashCode ^= ParameterType.GetHashCode(); } foreach (string parameterName in ParameterNames) { hashCode ^= parameterName.ToUpperInvariant().GetHashCode(); } return hashCode; } } }
{ "content_hash": "b0d490df04c99b7ce23e956117c0ff40", "timestamp": "", "source": "github", "line_count": 172, "max_line_length": 175, "avg_line_length": 37.68023255813954, "alnum_prop": 0.5698194723036568, "repo_name": "dzhenko/SpawnedDeliveryService", "id": "e1e7f10b30bf42e9f88ae06122e3c65d35122ceb", "size": "6481", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "SDS.Clould/SDS.Clould.WebAPI/Areas/HelpPage/SampleGeneration/HelpPageSampleKey.cs", "mode": "33188", "license": "mit", "language": [ { "name": "ASP", "bytes": "111" }, { "name": "C#", "bytes": "237544" }, { "name": "CSS", "bytes": "2626" }, { "name": "Groovy", "bytes": "812" }, { "name": "Java", "bytes": "143187" }, { "name": "JavaScript", "bytes": "10918" } ], "symlink_target": "" }
<project xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://maven.apache.org/POM/4.0.0" 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>jvmsnippets</groupId> <artifactId>jvmsnippets-examples-xrecords</artifactId> <version>1.0.0-SNAPSHOT</version> <relativePath>../pom.xml</relativePath> </parent> <artifactId>jvmsnippets-examples-xrecords-java</artifactId> <packaging>jar</packaging> <name>Tabular Record Conversion Framework - Java</name> </project>
{ "content_hash": "650c7c7e5b235f5521288fd6fe8091a4", "timestamp": "", "source": "github", "line_count": 16, "max_line_length": 105, "avg_line_length": 39.3125, "alnum_prop": 0.6947535771065183, "repo_name": "jvmsnippets/jvmsnippets-examples", "id": "c5899c9b73a87dded2d13ded0981a23e0a9c35f5", "size": "629", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "xrecords/java-xrecords/pom.xml", "mode": "33261", "license": "apache-2.0", "language": [ { "name": "Scala", "bytes": "17317" }, { "name": "Shell", "bytes": "723" }, { "name": "Xtend", "bytes": "127606" } ], "symlink_target": "" }
<?php namespace Vda\Datasource\Relational; class QueryBuilderState { private $isRoot = false; private $ignoreScope = false; private $ignoreAlias = false; private $preferAlias = false; private $parenthesizeSubSelect = true; private $quoteWildcards = false; public function isRoot() { return $this->isRoot; } public function setRoot($isRoot) { $this->isRoot = $isRoot; } public function isScopeIgnored() { return $this->ignoreScope; } public function setScopeIgnored($ignoreScope) { $this->ignoreScope = $ignoreScope; } public function isAliasIgnored() { return $this->ignoreAlias; } public function setAliasIgnored($ignoreAlias) { $this->ignoreAlias = $ignoreAlias; } public function isAliasPreferred() { return $this->preferAlias; } public function setAliasPreferred($preferAlias) { $this->preferAlias = $preferAlias; } public function isSelectParenthesized() { return !$this->isRoot && $this->parenthesizeSubSelect; } public function setSelectParenthesized($parenthesizeSubSelect) { $this->parenthesizeSubSelect = $parenthesizeSubSelect; } public function isWildcardsQuoted() { return $this->quoteWildcards; } public function setWildcardsQuoted($quoteWildcards) { $this->quoteWildcards = $quoteWildcards; } }
{ "content_hash": "1f0317285de98fde631b1a3994a9f0be", "timestamp": "", "source": "github", "line_count": 72, "max_line_length": 66, "avg_line_length": 21.375, "alnum_prop": 0.6120857699805068, "repo_name": "VDALLC/datasource", "id": "2a1863796ed939e5b4e2d1408da8fd363fe24572", "size": "1539", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "src/Relational/QueryBuilderState.php", "mode": "33188", "license": "mit", "language": [ { "name": "PHP", "bytes": "89241" } ], "symlink_target": "" }
import os import sys import time import threading import multiprocessing import subprocess import supybot.conf as conf import supybot.utils as utils import supybot.world as world from supybot.commands import * import supybot.callbacks as callbacks class Status(callbacks.Plugin): def __init__(self, irc): self.__parent = super(Status, self) self.__parent.__init__(irc) # XXX It'd be nice if these could be kept in the registry. self.sentMsgs = 0 self.recvdMsgs = 0 self.sentBytes = 0 self.recvdBytes = 0 self.connected = {} def __call__(self, irc, msg): self.recvdMsgs += 1 self.recvdBytes += len(msg) self.__parent.__call__(irc, msg) def outFilter(self, irc, msg): self.sentMsgs += 1 self.sentBytes += len(msg) return msg def do001(self, irc, msg): self.connected[irc] = time.time() def status(self, irc, msg, args): """takes no arguments Returns the status of the bot. """ networks = {} for Irc in world.ircs: networks.setdefault(Irc.network, []).append(Irc.nick) networks = networks.items() networks.sort() networks = [format('%s as %L', net, nicks) for (net,nicks) in networks] L = [format('I am connected to %L.', networks)] if world.profiling: L.append('I am currently in code profiling mode.') irc.reply(' '.join(L)) status = wrap(status) def threads(self, irc, msg, args): """takes no arguments Returns the current threads that are active. """ threads = [t.getName() for t in threading.enumerate()] threads.sort() s = format('I have spawned %n; %n %b still currently active: %L.', (world.threadsSpawned, 'thread'), (len(threads), 'thread'), len(threads), threads) irc.reply(s) threads = wrap(threads) def processes(self, irc, msg, args): """takes no arguments Returns the number of processes that have been spawned, and list of ones that are still active. """ ps = [multiprocessing.current_process().name] ps = ps + [p.name for p in multiprocessing.active_children()] s = format('I have spawned %n; %n %b still currently active: %L.', (world.processesSpawned, 'process'), (len(ps), 'process'), len(ps), ps) irc.reply(s) processes = wrap(processes) def net(self, irc, msg, args): """takes no arguments Returns some interesting network-related statistics. """ try: elapsed = time.time() - self.connected[irc.getRealIrc()] timeElapsed = utils.timeElapsed(elapsed) except KeyError: timeElapsed = 'an indeterminate amount of time' irc.reply('I have received %s messages for a total of %s bytes. ' 'I have sent %s messages for a total of %s bytes. ' 'I have been connected to %s for %s.' % (self.recvdMsgs, self.recvdBytes, self.sentMsgs, self.sentBytes, irc.server, timeElapsed)) net = wrap(net) def cpu(self, irc, msg, args): """takes no arguments Returns some interesting CPU-related statistics on the bot. """ (user, system, childUser, childSystem, elapsed) = os.times() now = time.time() target = msg.args[0] timeRunning = now - world.startedAt if self.registryValue('cpu.children', target) and \ user+system < timeRunning+1: # Fudge for FPU inaccuracies. children = 'My children have taken %.2f seconds of user time ' \ 'and %.2f seconds of system time ' \ 'for a total of %.2f seconds of CPU time. ' % \ (childUser, childSystem, childUser+childSystem) else: children = '' activeThreads = threading.activeCount() response = 'I have taken %.2f seconds of user time and %.2f seconds ' \ 'of system time, for a total of %.2f seconds of CPU ' \ 'time. %s' % (user, system, user + system, children) if self.registryValue('cpu.threads', target): response += format('I have spawned %n; I currently have %i still ' 'running.', (world.threadsSpawned, 'thread'), activeThreads) if self.registryValue('cpu.memory', target): mem = 'an unknown amount' pid = os.getpid() plat = sys.platform try: if plat.startswith('linux') or plat.startswith('sunos') or \ plat.startswith('freebsd') or plat.startswith('openbsd') or \ plat.startswith('darwin'): cmd = 'ps -o rss -p %s' % pid try: inst = subprocess.Popen(cmd.split(), close_fds=True, stdin=file(os.devnull), stdout=subprocess.PIPE, stderr=subprocess.PIPE) except OSError: irc.error('Unable to run ps command.', Raise=True) (out, _) = inst.communicate() inst.wait() mem = out.splitlines()[1] elif sys.platform.startswith('netbsd'): mem = '%s kB' % os.stat('/proc/%s/mem' % pid)[7] response += ' I\'m taking up %s kB of memory.' % mem except Exception: self.log.exception('Uncaught exception in cpu.memory:') irc.reply(utils.str.normalizeWhitespace(response)) cpu = wrap(cpu) def cmd(self, irc, msg, args): """takes no arguments Returns some interesting command-related statistics. """ commands = 0 callbacksPlugin = 0 for cb in irc.callbacks: if isinstance(cb, callbacks.Plugin): callbacksPlugin += 1 commands += len(cb.listCommands()) s = format('I offer a total of %n in %n. I have processed %n.', (commands, 'command'), (callbacksPlugin, 'command-based', 'plugin'), (world.commandsProcessed, 'command')) irc.reply(s) cmd = wrap(cmd) def commands(self, irc, msg, args): """takes no arguments Returns a list of the commands offered by the bot. """ commands = set() for cb in irc.callbacks: if isinstance(cb, callbacks.Plugin): for command in cb.listCommands(): commands.add(command) irc.reply(format('%L', sorted(commands))) commands = wrap(commands) def uptime(self, irc, msg, args): """takes no arguments Returns the amount of time the bot has been running. """ response = 'I have been running for %s.' % \ utils.timeElapsed(time.time() - world.startedAt) irc.reply(response) uptime = wrap(uptime) def server(self, irc, msg, args): """takes no arguments Returns the server the bot is on. """ irc.reply(irc.server) server = wrap(server) Class = Status # vim:set shiftwidth=4 softtabstop=4 expandtab textwidth=79:
{ "content_hash": "70cb7d94a390ab2766f0cce7f4d29041", "timestamp": "", "source": "github", "line_count": 204, "max_line_length": 80, "avg_line_length": 37.06372549019608, "alnum_prop": 0.5386853590794869, "repo_name": "mazaclub/mazabot-core", "id": "61ccfccdeca66da2f8bfbd2a04e0238e84a230d6", "size": "9183", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "plugins/Status/plugin.py", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "Python", "bytes": "2344559" }, { "name": "Shell", "bytes": "454" } ], "symlink_target": "" }
/* ------------------------------------------------------------------------------ * * # Invoice template * * Specific JS code additions for invoice_template.html page * * Version: 1.0 * Latest update: Aug 1, 2015 * * ---------------------------------------------------------------------------- */ $(function() { // Setup CKEditor CKEDITOR.disableAutoInline = true; CKEDITOR.dtd.$removeEmpty['i'] = false; CKEDITOR.config.startupShowBorders = false; CKEDITOR.config.extraAllowedContent = 'table(*)'; // Initialize inline editor var editor = CKEDITOR.inline('invoice-editable'); });
{ "content_hash": "540fe20843f3a4f2ecc4ef34999021d3", "timestamp": "", "source": "github", "line_count": 24, "max_line_length": 81, "avg_line_length": 26.916666666666668, "alnum_prop": 0.47368421052631576, "repo_name": "iBase4J/iBase4J", "id": "328ebed0493f39037a90036c484ca0e09ea301a4", "size": "646", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "iBase4J-UI/iBase4J-UI-DataTables/src/assets/js/pages/invoice_template.js", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "2040473" }, { "name": "HTML", "bytes": "702651" }, { "name": "Java", "bytes": "285812" }, { "name": "JavaScript", "bytes": "6362897" }, { "name": "PHP", "bytes": "11363" }, { "name": "TSQL", "bytes": "1053172" } ], "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_66-internal) on Tue Dec 08 09:28:00 GMT 2015 --> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>Uses of Class org.apache.jena.riot.SysRIOT (Apache Jena ARQ)</title> <meta name="date" content="2015-12-08"> <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 org.apache.jena.riot.SysRIOT (Apache Jena ARQ)"; } } 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="../../../../../org/apache/jena/riot/SysRIOT.html" title="class in org.apache.jena.riot">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/jena/riot/class-use/SysRIOT.html" target="_top">Frames</a></li> <li><a href="SysRIOT.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 org.apache.jena.riot.SysRIOT" class="title">Uses of Class<br>org.apache.jena.riot.SysRIOT</h2> </div> <div class="classUseContainer">No usage of org.apache.jena.riot.SysRIOT</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="../../../../../org/apache/jena/riot/SysRIOT.html" title="class in org.apache.jena.riot">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/jena/riot/class-use/SysRIOT.html" target="_top">Frames</a></li> <li><a href="SysRIOT.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>Licenced under the Apache License, Version 2.0</small></p> </body> </html>
{ "content_hash": "64d40011b1078b0e7f101ece985d0321", "timestamp": "", "source": "github", "line_count": 126, "max_line_length": 119, "avg_line_length": 35.46031746031746, "alnum_prop": 0.6069829901521934, "repo_name": "manonsys/MVC", "id": "4ac0113505356ca49e79bf7501542a54473f7c1d", "size": "4468", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "libs/Jena/javadoc-arq/org/apache/jena/riot/class-use/SysRIOT.html", "mode": "33188", "license": "mit", "language": [ { "name": "ApacheConf", "bytes": "419" }, { "name": "Batchfile", "bytes": "14683" }, { "name": "C", "bytes": "233384" }, { "name": "C++", "bytes": "5473" }, { "name": "CSS", "bytes": "672088" }, { "name": "HTML", "bytes": "88037916" }, { "name": "Java", "bytes": "197704" }, { "name": "JavaScript", "bytes": "3308500" }, { "name": "Makefile", "bytes": "1758" }, { "name": "PHP", "bytes": "1202703" }, { "name": "Perl", "bytes": "1542" }, { "name": "Shell", "bytes": "97135" }, { "name": "Web Ontology Language", "bytes": "7918" } ], "symlink_target": "" }
package com.tvd12.ezyfox.sfs2x.command.impl; import com.smartfoxserver.v2.api.ISFSApi; import com.smartfoxserver.v2.exceptions.SFSRoomException; import com.smartfoxserver.v2.extensions.ISFSExtension; import com.tvd12.ezyfox.core.command.PlayerToSpectator; import com.tvd12.ezyfox.core.entities.ApiBaseUser; import com.tvd12.ezyfox.core.entities.ApiRoom; import com.tvd12.ezyfox.sfs2x.content.impl.AppContextImpl; /** * @see PlayerToSpectator * * @author tavandung12 * Created on May 27, 2016 * */ public class PlayerToSpectatorImpl extends BaseCommandImpl implements PlayerToSpectator { private String user; private String targetRoom; private boolean fireClientEvent = true; private boolean fireServerEvent = true; /** * @param context the context * @param api the api * @param extension the extension */ public PlayerToSpectatorImpl(AppContextImpl context, ISFSApi api, ISFSExtension extension) { super(context, api, extension); } /* (non-Javadoc) * @see com.tvd12.ezyfox.core.command.BaseCommand#execute() */ @SuppressWarnings("unchecked") @Override public Boolean execute() { try { api.playerToSpectator(CommandUtil.getSfsUser(user, api), CommandUtil.getSfsRoom(targetRoom, extension), fireClientEvent, fireServerEvent); } catch (SFSRoomException e) { throw new IllegalStateException(e); } return Boolean.TRUE; } /* (non-Javadoc) * @see com.tvd12.ezyfox.core.command.PlayerToSpectator#user(com.tvd12.ezyfox.core.entities.ApiBaseUser) */ @Override public PlayerToSpectator user(ApiBaseUser user) { this.user = user.getName(); return this; } /* (non-Javadoc) * @see com.tvd12.ezyfox.core.command.PlayerToSpectator#room(com.tvd12.ezyfox.core.entities.ApiRoom) */ @Override public PlayerToSpectator room(ApiRoom room) { this.targetRoom = room.getName(); return this; } /* (non-Javadoc) * @see com.tvd12.ezyfox.core.command.PlayerToSpectator#fireClientEvent(boolean) */ @Override public PlayerToSpectator fireClientEvent(boolean value) { this.fireClientEvent = value; return this; } /* (non-Javadoc) * @see com.tvd12.ezyfox.core.command.PlayerToSpectator#fireServerEvent(boolean) */ @Override public PlayerToSpectator fireServerEvent(boolean value) { this.fireServerEvent = value; return this; } }
{ "content_hash": "91ceffeca526c3bcf18e540a4b62d31a", "timestamp": "", "source": "github", "line_count": 86, "max_line_length": 108, "avg_line_length": 29.872093023255815, "alnum_prop": 0.6788633709614637, "repo_name": "youngmonkeys/ezyfox-sfs2x", "id": "acc52553b159ac98ade9f91c40c27da3ec5c358e", "size": "2569", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/main/java/com/tvd12/ezyfox/sfs2x/command/impl/PlayerToSpectatorImpl.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "789702" } ], "symlink_target": "" }
<?php /** * Returns the HTML for the Campaign Run page. */ ?> <h4>Campaign: <p><?php print l($campaign_title, 'node/' . $field_campaigns[0]['target_id']); ?></p> </h4> <h4>Campaign Closed State: <p><?php print l($campaign_title . ': Closed State', 'node/' . $field_campaigns[0]['target_id'] . '/closed'); ?></p> </h4> <h4>Run Description: <p> <?php $run_nid = node_load($field_campaigns[0]['entity']->field_current_run['en'][0]['target_id']); print render($run_nid->description_field['en'][0]['value']); ?> </p> </h4> <?php print render($content['field_winners']); print render($content['field_gallery_collection']); print render($content['field_run_date']); ?>
{ "content_hash": "93ad4f49b0ff4eceabbf05c1ccbb08a8", "timestamp": "", "source": "github", "line_count": 29, "max_line_length": 118, "avg_line_length": 24.03448275862069, "alnum_prop": 0.6025824964131994, "repo_name": "DoSomething/dosomething", "id": "efb22612a070993a770111b739208010bf36d42b", "size": "697", "binary": false, "copies": "5", "ref": "refs/heads/dev", "path": "lib/themes/dosomething/paraneue_dosomething/templates/campaign_run/node--campaign_run.tpl.php", "mode": "33188", "license": "mit", "language": [ { "name": "Assembly", "bytes": "799" }, { "name": "C++", "bytes": "4672" }, { "name": "CSS", "bytes": "43232" }, { "name": "CoffeeScript", "bytes": "11860" }, { "name": "HTML", "bytes": "3144" }, { "name": "JavaScript", "bytes": "183563" }, { "name": "PHP", "bytes": "1392083" }, { "name": "Ruby", "bytes": "903" }, { "name": "Shell", "bytes": "32392" }, { "name": "SourcePawn", "bytes": "153822" } ], "symlink_target": "" }
import React from "react" import { render, screen } from "@testing-library/react" import Login, { createOauthURL, generateErrorDisplayMessage } from "./Login" import { MockAuthProvider } from "common/utils/testing" import userEvent from "@testing-library/user-event" describe("features/Authentication/Login", () => { const globalAny = global as any const openMock = jest.fn() globalAny.open = openMock describe("initial render", () => { it("displays login header", () => { render( <MockAuthProvider mocks={[]}> <Login /> </MockAuthProvider>, ) expect(screen.getByText(/Log in/)).toBeInTheDocument() }) it("displays expected buttons", () => { render( <MockAuthProvider mocks={[]}> <Login /> </MockAuthProvider>, ) expect(screen.getAllByRole("button")).toHaveLength(3) expect(screen.getByText(/Sign in with ORCID/)).toBeInTheDocument() expect(screen.getByText(/Sign in with Google/)).toBeInTheDocument() expect(screen.getByText(/Sign in with LinkedIn/)).toBeInTheDocument() }) it("calls function on button click", () => { render( <MockAuthProvider mocks={[]}> <Login /> </MockAuthProvider>, ) const orcid = screen.getByRole("button", { name: "Sign in with ORCID" }) const google = screen.getByRole("button", { name: "Sign in with Google" }) const linkedin = screen.getByRole("button", { name: "Sign in with LinkedIn", }) // click orcid button expect(orcid).toBeInTheDocument() userEvent.click(orcid) expect(openMock).toHaveBeenCalledTimes(1) // click google button expect(google).toBeInTheDocument() userEvent.click(google) expect(openMock).toHaveBeenCalledTimes(2) // click linkedin button expect(linkedin).toBeInTheDocument() userEvent.click(linkedin) expect(openMock).toHaveBeenCalledTimes(3) }) }) describe("createOauthURL function", () => { it("should return expected URL for full config object", () => { const fullConfig = { name: "Review", url: "/forrest/macneil", authorizationEndpoint: "https://testendpoint.com/auth", clientId: "testID", redirectUrl: "https://localhost:3000/review/callback", requiredUrlParams: [["response_type", "code"]], scopes: ["email"], scopeDelimiter: " ", optionalUrlParams: [["state", "review"]], popupOptions: { width: 1020, height: 633 }, } expect(createOauthURL(fullConfig)).toBe( "https://testendpoint.com/auth?client_id=testID&scope=email&response_type=code&state=review&redirect_uri=https://localhost:3000/review/callback", ) }) it("should return expected URL without URL params", () => { const configNoParams = { name: "Review", url: "/forrest/macneil", authorizationEndpoint: "https://testendpoint.com/auth", clientId: "testID", redirectUrl: "https://localhost:3000/review/callback", scopes: ["email"], scopeDelimiter: " ", popupOptions: { width: 1020, height: 633 }, } expect(createOauthURL(configNoParams)).toBe( "https://testendpoint.com/auth?client_id=testID&scope=email&redirect_uri=https://localhost:3000/review/callback", ) }) }) describe("generateErrorDisplayMessage function", () => { it("should return correct network error message", () => { const error = { message: "", networkError: { error: "test error", name: "err", message: "test error msg", }, extraInfo: {}, name: "", graphQLErrors: [ { message: "", extensions: {}, locations: undefined, nodes: undefined, source: undefined, positions: undefined, originalError: undefined, name: "", path: [""], }, ], } expect(generateErrorDisplayMessage(error)).toEqual("Network Error") }) it("should return appropriate error if user not found", () => { const error = { message: "", networkError: null, extraInfo: {}, name: "", graphQLErrors: [ { message: "", extensions: { code: "NotFound", timestamp: "cye", }, locations: undefined, nodes: undefined, source: undefined, positions: undefined, originalError: undefined, name: "", path: [""], }, ], } expect(generateErrorDisplayMessage(error)).toContain( "Could not find user account", ) }) it("should return generic error if not network or not found error", () => { const error = { message: "", networkError: null, extraInfo: {}, name: "", graphQLErrors: [ { message: "", extensions: {}, locations: undefined, nodes: undefined, source: undefined, positions: undefined, originalError: undefined, name: "", path: [""], }, ], } expect(generateErrorDisplayMessage(error)).toContain("Could not log in") }) }) })
{ "content_hash": "8608dba8496245c107c65a5a0fe15364", "timestamp": "", "source": "github", "line_count": 172, "max_line_length": 153, "avg_line_length": 31.796511627906977, "alnum_prop": 0.5598829767782044, "repo_name": "dictyBase/Dicty-Stock-Center", "id": "f3693d24607a53b506e711d13fcc05bdef66cc98", "size": "5469", "binary": false, "copies": "1", "ref": "refs/heads/develop", "path": "src/features/Authentication/Login.test.tsx", "mode": "33188", "license": "bsd-2-clause", "language": [ { "name": "Dockerfile", "bytes": "2350" }, { "name": "HTML", "bytes": "1816" }, { "name": "JavaScript", "bytes": "7136" }, { "name": "Smarty", "bytes": "1078" }, { "name": "TypeScript", "bytes": "394162" } ], "symlink_target": "" }
What is this? ------------- This is a simple script that wraps around boot2docker to make docker feel more native on windows. What does it do? ---------------- 1. Automatically starts boot2docker if it is not already running. 2. Mounts your `C:\` drive on the VM at `/c` if it's not already mounted. 3. Determines your current working directory on the Windows machine and changes to the equivalent directory on the VM. 4. Runs your docker command. Example ------- If you have a simple `Dockerfile` like the following at `C:\example\Dockerfile`: ```dockerfile FROM ubuntu ENTRYPOINT ["echo"] CMD ["hello world"] ``` With the wrapper script you can just open up a Windows command prompt and enter the following to build the image and then run it: ```batch > cd C:\example > docker build -t hello . > docker run -ti --rm hello ``` No need to run `boot2docker start` or `boot2docker ssh`. Just work with your local files as you would with docker on Linux. Requirements ------------ Boot2Docker v1.3.0 or later Quick Installation ------------------ Run these commands from a Windows command prompt: ```batch > boot2docker stop > VBoxManage.exe sharedfolder add boot2docker-vm --name c --hostpath C:\ --automount > git clone https://github.com/klieber/boot2docker-windows.git > cd boot2docker-windows > copy docker* C:\Program Files\Boot2Docker for Windows > docker run -ti --rm hello-world ``` Cygwin ------ Cygwin is also supported and the same installation steps should be taken to install it for both Cygwin and CMD.EXE.
{ "content_hash": "d7e3d26d5128cfb9774dd8ae53a66036", "timestamp": "", "source": "github", "line_count": 50, "max_line_length": 129, "avg_line_length": 30.68, "alnum_prop": 0.7196870925684485, "repo_name": "klieber/boot2docker-windows", "id": "4eff1d92ee061018e0383bb46fbc998a74d38708", "size": "1534", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "README.md", "mode": "33188", "license": "mit", "language": [ { "name": "Shell", "bytes": "686" } ], "symlink_target": "" }
<?php use Illuminate\Database\Seeder; use Illuminate\Database\Eloquent\Model; class DatabaseSeeder extends Seeder { /** * Run the database seeds. * * @return void */ public function run() { Model::unguard(); DB::statement('SET FOREIGN_KEY_CHECKS=0;'); $this->call('ProfileTableSeeder'); $this->call('UserTableSeeder'); $this->call('CategoryTableSeeder'); $this->call('ArticleTableSeeder'); $this->call('TopicTableSeeder'); $this->call('VoteTableSeeder'); $this->call('DebateTableSeeder'); $this->call('DebateUserTableSeeder'); $this->call('PostTableSeeder'); $this->call('JobTableSeeder'); $this->call('JobUserTableSeeder'); $this->call('ChoiceTableSeeder'); DB::statement('SET FOREIGN_KEY_CHECKS=1;'); Model::reguard(); } }
{ "content_hash": "81ce956e9c0ad12f52b00a4569befb8e", "timestamp": "", "source": "github", "line_count": 33, "max_line_length": 51, "avg_line_length": 26.96969696969697, "alnum_prop": 0.5921348314606741, "repo_name": "soywod/MAD", "id": "4791e64e3200e2b02f3da3acc9c59a893ca4d22d", "size": "890", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "database/seeds/DatabaseSeeder.php", "mode": "33261", "license": "mit", "language": [ { "name": "ApacheConf", "bytes": "412" }, { "name": "HTML", "bytes": "280999" }, { "name": "JavaScript", "bytes": "24002" }, { "name": "PHP", "bytes": "704426" }, { "name": "Shell", "bytes": "511" } ], "symlink_target": "" }
import React from 'react'; import { ModelListView, ModelListViewImpl } from './ModelListView'; import { mockModelVersionDetailed, mockRegisteredModelDetailed } from '../test-utils'; import { Alert } from '@databricks/design-system'; import { ModelVersionStatus, Stages } from '../constants'; import { BrowserRouter } from 'react-router-dom'; import Utils from '../../common/utils/Utils'; import { ModelRegistryDocUrl } from '../../common/constants'; import { Table } from 'antd'; import configureStore from 'redux-mock-store'; import thunk from 'redux-thunk'; import promiseMiddleware from 'redux-promise-middleware'; import { Provider } from 'react-redux'; import { mountWithIntl } from '../../common/utils/TestUtils'; const mockStore = configureStore([thunk, promiseMiddleware()]); const ANTD_TABLE_PLACEHOLDER_CLS = 'tr.ant-table-placeholder'; describe('ModelListView', () => { let wrapper; let instance; let minimalProps; let minimalStore; let onSearchSpy; beforeEach(() => { onSearchSpy = jest.fn(); minimalProps = { models: [], searchInput: '', orderByKey: 'name', orderByAsc: true, currentPage: 1, nextPageToken: null, // no next page selectedStatusFilter: '', selectedOwnerFilter: '', onSearch: onSearchSpy, onClear: jest.fn(), onClickNext: jest.fn(), onClickPrev: jest.fn(), onClickSortableColumn: jest.fn(), onSetMaxResult: jest.fn(), getMaxResultValue: jest.fn().mockReturnValue(10), onSearchInputChange: jest.fn(), onStatusFilterChange: jest.fn(), onOwnerFilterChange: jest.fn(), }; minimalStore = mockStore({}); }); function setupModelListViewWithIntl(propsParam) { const props = propsParam || minimalProps; return mountWithIntl( <Provider store={minimalStore}> <BrowserRouter> <ModelListView {...props} /> </BrowserRouter> </Provider>, ); } test('should render with minimal props without exploding', () => { wrapper = setupModelListViewWithIntl(); expect(wrapper.length).toBe(1); }); test('should display onBoarding helper', () => { wrapper = setupModelListViewWithIntl(); expect(wrapper.find(Alert).length).toBe(1); }); test('should not display onBoarding helper if disabled', () => { wrapper = setupModelListViewWithIntl(); wrapper.find(ModelListViewImpl).setState({ showOnboardingHelper: false, }); expect(wrapper.find(Alert).length).toBe(0); }); test('should show correct link in onboarding helper', () => { wrapper = setupModelListViewWithIntl(); expect(wrapper.find(`a[href="${ModelRegistryDocUrl}"]`)).toHaveLength(1); }); test('should render correct information if table is empty', () => { wrapper = setupModelListViewWithIntl(); expect(wrapper.find(ANTD_TABLE_PLACEHOLDER_CLS).text()).toBe( 'No models yet. Create a model to get started.', ); wrapper.setProps({ children: ( <BrowserRouter> <ModelListView {...{ ...minimalProps, searchInput: 'xyz' }} /> </BrowserRouter> ), }); expect(wrapper.find(ANTD_TABLE_PLACEHOLDER_CLS).text()).toBe('No models found.'); wrapper.find(ModelListViewImpl).setState({ lastNavigationActionWasClickPrev: true }); expect(wrapper.find(ANTD_TABLE_PLACEHOLDER_CLS).text()).toBe( 'No models found for the page. ' + 'Please refresh the page as the underlying data may have changed significantly.', ); }); test('should render latest version correctly', () => { const models = [ mockRegisteredModelDetailed('Model A', [ mockModelVersionDetailed('Model A', 1, Stages.PRODUCTION, ModelVersionStatus.READY), mockModelVersionDetailed('Model A', 2, Stages.STAGING, ModelVersionStatus.READY), mockModelVersionDetailed('Model A', 3, Stages.NONE, ModelVersionStatus.READY), ]), ]; const props = { ...minimalProps, models }; wrapper = setupModelListViewWithIntl(props); expect(wrapper.find('td.latest-version').text()).toBe('Version 3'); expect(wrapper.find('td.latest-staging').text()).toBe('Version 2'); expect(wrapper.find('td.latest-production').text()).toBe('Version 1'); }); test('should render `_` when there is no version to display for the cell', () => { const models = [ mockRegisteredModelDetailed('Model A', [ mockModelVersionDetailed('Model A', 1, Stages.NONE, ModelVersionStatus.READY), ]), ]; const props = { ...minimalProps, models }; wrapper = setupModelListViewWithIntl(props); expect(wrapper.find('td.latest-version').text()).toBe('Version 1'); expect(wrapper.find('td.latest-staging').text()).toBe('_'); expect(wrapper.find('td.latest-production').text()).toBe('_'); }); test('should render tags correctly', () => { const models = [ mockRegisteredModelDetailed( 'Model A', [], [ { key: 'key', value: 'value' }, { key: 'key2', value: 'value2' }, { key: 'key3', value: 'value3' }, { key: 'key4', value: 'value4' }, ], ), ]; const props = { ...minimalProps, models }; wrapper = setupModelListViewWithIntl(props); expect(wrapper.find('td.table-tag-container').text()).toContain('key:value'); expect(wrapper.find('td.table-tag-container').text()).toContain('key2:value2'); expect(wrapper.find('td.table-tag-container').text()).toContain('key3:value3'); expect(wrapper.find('td.table-tag-container').text()).toContain('key4:value4'); }); test('tags cell renders multiple tags and collapses with more than 4 tags', () => { const models = [ mockRegisteredModelDetailed( 'Model A', [], [ { key: 'key', value: 'value' }, { key: 'key2', value: 'value2' }, { key: 'key3', value: 'value3' }, { key: 'key4', value: 'value4' }, { key: 'key5', value: 'value5' }, ], ), ]; const props = { ...minimalProps, models }; wrapper = setupModelListViewWithIntl(props); expect(wrapper.find('td.table-tag-container').text()).toContain('key:value'); expect(wrapper.find('td.table-tag-container').text()).toContain('key2:value2'); expect(wrapper.find('td.table-tag-container').text()).toContain('key3:value3'); expect(wrapper.find('td.table-tag-container').text()).toContain('2 more'); }); test('should render `_` when there are no tags to display for the cell', () => { const models = [ mockRegisteredModelDetailed('Model A', [ mockModelVersionDetailed('Model A', 1, Stages.NONE, ModelVersionStatus.READY), ]), ]; const props = { ...minimalProps, models }; wrapper = setupModelListViewWithIntl(props); expect(wrapper.find('td.table-tag-container').text()).toBe('_'); }); const findColumn = (table, index) => table.props().columns.find((elem) => elem.dataIndex === index); test('orderByKey, orderByASC props are correctly passed to the table', () => { const models = [ mockRegisteredModelDetailed('Model B', [], [], 'CAN_EDIT', 3), mockRegisteredModelDetailed('model c', [], [], 'CAN_EDIT', 1), mockRegisteredModelDetailed('Model a', [], [], 'CAN_EDIT', 2), ]; let props = { ...minimalProps, models, orderByKey: 'name', orderByAsc: true, }; wrapper = setupModelListViewWithIntl(props); let table = wrapper.find(Table); // prop values look legit expect(findColumn(table, 'name').sortOrder).toBe('ascend'); expect(findColumn(table, 'last_updated_timestamp').sortOrder).toBe(undefined); // the table doesn't actually sort, though, and displays exactly what's given. expect(wrapper.find('td.model-name').length).toBe(3); expect(wrapper.find('td.model-name').at(0).text()).toBe('Model B'); expect(wrapper.find('td.model-name').at(1).text()).toBe('model c'); expect(wrapper.find('td.model-name').at(2).text()).toBe('Model a'); props = { ...minimalProps, models, orderByKey: 'timestamp', orderByAsc: false, }; wrapper = setupModelListViewWithIntl(props); table = wrapper.find(Table); // prop values look legit expect(findColumn(table, 'name').sortOrder).toBe(undefined); expect(findColumn(table, 'last_updated_timestamp').sortOrder).toBe('descend'); // the table doesn't actually sort, though, and displays exactly what's given. expect(wrapper.find('td.model-name').length).toBe(3); expect(wrapper.find('td.model-name').at(0).text()).toBe('Model B'); expect(wrapper.find('td.model-name').at(1).text()).toBe('model c'); expect(wrapper.find('td.model-name').at(2).text()).toBe('Model a'); }); test('lastNavigationActionWasClickPrev is set properly on actions', () => { wrapper = setupModelListViewWithIntl(); instance = wrapper.find(ModelListViewImpl).instance(); expect(instance.state.lastNavigationActionWasClickPrev).toBe(false); instance.handleClickPrev(); expect(instance.state.lastNavigationActionWasClickPrev).toBe(true); instance.handleClickNext(); expect(instance.state.lastNavigationActionWasClickPrev).toBe(false); const event = { preventDefault: () => {} }; instance.handleSearch(event); expect(instance.state.lastNavigationActionWasClickPrev).toBe(false); instance.handleTableChange(null, null, { field: 'name', order: 'ascend' }); expect(instance.state.lastNavigationActionWasClickPrev).toBe(false); }); test('Page title is set', () => { const mockUpdatePageTitle = jest.fn(); Utils.updatePageTitle = mockUpdatePageTitle; wrapper = setupModelListViewWithIntl(); expect(mockUpdatePageTitle.mock.calls[0][0]).toBe('MLflow Models'); }); // eslint-disable-next-line });
{ "content_hash": "a90f6f9ec665b349081d25d6c8bdb651", "timestamp": "", "source": "github", "line_count": 259, "max_line_length": 92, "avg_line_length": 38.011583011583014, "alnum_prop": 0.6479431183341798, "repo_name": "mlflow/mlflow", "id": "4e64063ad056136dbb619c80f89f7a0ecbe82819", "size": "9845", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "mlflow/server/js/src/model-registry/components/ModelListView.test.js", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "24965" }, { "name": "Dockerfile", "bytes": "1206" }, { "name": "HTML", "bytes": "16439" }, { "name": "Java", "bytes": "276538" }, { "name": "JavaScript", "bytes": "3606345" }, { "name": "Mako", "bytes": "494" }, { "name": "Python", "bytes": "6057051" }, { "name": "R", "bytes": "202454" }, { "name": "Scala", "bytes": "39353" }, { "name": "Shell", "bytes": "27246" }, { "name": "TSQL", "bytes": "211" }, { "name": "TypeScript", "bytes": "313772" } ], "symlink_target": "" }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; public static class ArrayExtensions { public static T[] Filter<T>(this T[] data, int[] indexesToStay) { T[] newArr = new T[indexesToStay.Length]; for (int i = 0; i < indexesToStay.Length; i++) { newArr[i] = data[indexesToStay[i]]; } return newArr; } public static T[][] Filter<T>(this T[][] data, int[] indexesToStay) { T[][] newArr = new T[indexesToStay.Length][]; for (int i = 0; i < indexesToStay.Length; i++) { newArr[i] = data[indexesToStay[i]]; } return newArr; } public static int[] createIndexesToStay(this bool[] isIndexInResult) { List<int> a = new List<int>(); for (int i = 0; i < isIndexInResult.Length; i++) { if (isIndexInResult[i]) { a.Add(i); } } return a.ToArray(); } public static int[] createIndexesToStay(this byte[] isIndexInResult) { List<int> a = new List<int>(); for (int i = 0; i < isIndexInResult.Length; i++) { if (isIndexInResult[i] == 1) { a.Add(i); } } return a.ToArray(); } public static void Swap<T>(this T[] arr, int a, int b) { T tmp = arr[a]; arr[a] = arr[b]; arr[b] = tmp; } public static T[][] Filter<T>(this T[][] data, bool[] isIndexInResult) { return data.Filter(isIndexInResult.createIndexesToStay()); } public static T[] Filter<T>(this T[] data, bool[] isIndexInResult) { return data.Filter(isIndexInResult.createIndexesToStay()); } public static T[] CreateCopy<T>(this T[] toCopy) { T[] arr = new T[toCopy.Length]; Array.Copy(toCopy, arr, toCopy.Length); return arr; } }
{ "content_hash": "950e55c32514c63b3142781525d915cc", "timestamp": "", "source": "github", "line_count": 81, "max_line_length": 74, "avg_line_length": 24.567901234567902, "alnum_prop": 0.5256281407035176, "repo_name": "saper150/vectors-and-dimensions-reduction-for-machine-learning", "id": "429055370cfe5eaa1af058c55ba9be3d20878fe3", "size": "1992", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "Knn/ArrayExtensions.cs", "mode": "33188", "license": "mit", "language": [ { "name": "C", "bytes": "1959" }, { "name": "C#", "bytes": "112220" }, { "name": "C++", "bytes": "1971" }, { "name": "Cuda", "bytes": "25358" } ], "symlink_target": "" }
"""Test using a proxy.""" # External imports import multiprocessing import pytest import http.server import socketserver from urllib.request import urlopen # Internal imports import vcr # Conditional imports requests = pytest.importorskip("requests") class Proxy(http.server.SimpleHTTPRequestHandler): """ Simple proxy server. (Inspired by: http://effbot.org/librarybook/simplehttpserver.htm). """ def do_GET(self): upstream_response = urlopen(self.path) try: status = upstream_response.status headers = upstream_response.headers.items() except AttributeError: # In Python 2 the response is an addinfourl instance. status = upstream_response.code headers = upstream_response.info().items() self.send_response(status, upstream_response.msg) for header in headers: self.send_header(*header) self.end_headers() self.copyfile(upstream_response, self.wfile) @pytest.yield_fixture(scope="session") def proxy_server(): httpd = socketserver.ThreadingTCPServer(("", 0), Proxy) proxy_process = multiprocessing.Process(target=httpd.serve_forever) proxy_process.start() yield "http://{}:{}".format(*httpd.server_address) proxy_process.terminate() def test_use_proxy(tmpdir, httpbin, proxy_server): """Ensure that it works with a proxy.""" with vcr.use_cassette(str(tmpdir.join("proxy.yaml"))): response = requests.get(httpbin.url, proxies={"http": proxy_server}) with vcr.use_cassette(str(tmpdir.join("proxy.yaml"))) as cassette: cassette_response = requests.get(httpbin.url, proxies={"http": proxy_server}) assert cassette_response.headers == response.headers assert cassette.play_count == 1
{ "content_hash": "91641b824683c6e9b02e6f672656e4d9", "timestamp": "", "source": "github", "line_count": 59, "max_line_length": 85, "avg_line_length": 30.491525423728813, "alnum_prop": 0.67982212340189, "repo_name": "graingert/vcrpy", "id": "b465b59e92b7850959430223b4c6ea51678970b3", "size": "1823", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "tests/integration/test_proxy.py", "mode": "33188", "license": "mit", "language": [ { "name": "Python", "bytes": "293647" }, { "name": "Shell", "bytes": "379" } ], "symlink_target": "" }
import json import pymol from pymol.cgo import * # This is a heavily modified version of the cgoCircle script found on the pymol wiki) # This tool has been developed to support the EMRinger software, but is useful for all dihedral-sampling visualization. def ringerRing(jsonfile, cr=1, cg=0.4, cb=0.8, width=28): with open(jsonfile, 'r') as file: vertices = json.load(file) obj=[BEGIN, LINES, COLOR, float(cr), float(cg), float(cb)] for i in range(len(vertices)): obj.append( VERTEX ) obj.append(vertices[i][0]) obj.append(vertices[i][1]) obj.append(vertices[i][2]) obj.append( VERTEX ) obj.append(vertices[(i+1)%len(vertices)][0]) obj.append(vertices[(i+1)%len(vertices)][1]) obj.append(vertices[(i+1)%len(vertices)][2]) obj.append(END) cName=str(jsonfile) cmd.load_cgo(obj, cName) cmd.set("cgo_line_width", width) return obj cmd.extend("ringerRing", ringerRing)
{ "content_hash": "c65bfef2211e15aecba954c12eb02bb4", "timestamp": "", "source": "github", "line_count": 28, "max_line_length": 119, "avg_line_length": 32.892857142857146, "alnum_prop": 0.6894679695982627, "repo_name": "fraser-lab/EMRinger", "id": "905a98de0c067b489c9ad14a6457837c571e0ed4", "size": "921", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "Figures/Pymol_Plugin/pymol_ringer.py", "mode": "33261", "license": "bsd-3-clause", "language": [ { "name": "Python", "bytes": "154551" }, { "name": "Shell", "bytes": "344" } ], "symlink_target": "" }
package com.ldxx.lottery.orm; /** * * @author wangzhuo * */ public class FirstDistribution { private String pid; private String issue; private String province_name; private String province_py; private int num; public String getPid() { return pid; } public void setPid(String pid) { this.pid = pid; } public String getIssue() { return issue; } public void setIssue(String issue) { this.issue = issue; } public String getProvince_name() { return province_name; } public void setProvince_name(String province_name) { this.province_name = province_name; } public String getProvince_py() { return province_py; } public void setProvince_py(String province_py) { this.province_py = province_py; } public int getNum() { return num; } public void setNum(int num) { this.num = num; } @Override public String toString() { StringBuilder sb = new StringBuilder(" insert into first_distribution values( '"); sb.append(this.pid).append("','").append(this.issue).append("','") .append(this.province_name).append("','").append(this.province_py) .append("','").append(this.num).append("')"); return sb.toString(); } }
{ "content_hash": "548379343dc3948e1865a983623cdddb", "timestamp": "", "source": "github", "line_count": 58, "max_line_length": 85, "avg_line_length": 20.224137931034484, "alnum_prop": 0.6786018755328218, "repo_name": "liaodongxiaoxiao/MybatisSqlite", "id": "3a2c7aa3bbcc9edcb5db988ea85501786ac09e0a", "size": "1173", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "MybatisSqlite/src/com/ldxx/lottery/orm/FirstDistribution.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "28641" } ], "symlink_target": "" }
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/> <title>Ignite Tools: Shared/Airship/External/UA_ZipFile-OC/UA_minizip/UA_mztools.h Source File</title> <link href="tabs.css" rel="stylesheet" type="text/css"/> <link href="search/search.css" rel="stylesheet" type="text/css"/> <script type="text/javascript" src="search/search.js"></script> <link href="doxygen.css" rel="stylesheet" type="text/css"/> </head> <body onload='searchBox.OnSelectItem(0);'> <!-- Generated by Doxygen 1.7.4 --> <script type="text/javascript"><!-- var searchBox = new SearchBox("searchBox", "search",false,'Search'); --></script> <div id="top"> <div id="titlearea"> <table cellspacing="0" cellpadding="0"> <tbody> <tr style="height: 56px;"> <td id="projectlogo"><img alt="Logo" src="ASLogo.png"/></td> <td style="padding-left: 0.5em;"> <div id="projectname">Ignite Tools</div> </td> </tr> </tbody> </table> </div> <div id="navrow1" class="tabs"> <ul class="tablist"> <li><a href="index.html"><span>Main&#160;Page</span></a></li> <li><a href="annotated.html"><span>Classes</span></a></li> <li class="current"><a href="files.html"><span>Files</span></a></li> <li id="searchli"> <div id="MSearchBox" class="MSearchBoxInactive"> <span class="left"> <img id="MSearchSelect" src="search/mag_sel.png" onmouseover="return searchBox.OnSearchSelectShow()" onmouseout="return searchBox.OnSearchSelectHide()" alt=""/> <input type="text" id="MSearchField" value="Search" accesskey="S" onfocus="searchBox.OnSearchFieldFocus(true)" onblur="searchBox.OnSearchFieldFocus(false)" onkeyup="searchBox.OnSearchFieldChange(event)"/> </span><span class="right"> <a id="MSearchClose" href="javascript:searchBox.CloseResultsWindow()"><img id="MSearchCloseImg" border="0" src="search/close.png" alt=""/></a> </span> </div> </li> </ul> </div> <div id="navrow2" class="tabs2"> <ul class="tablist"> <li><a href="files.html"><span>File&#160;List</span></a></li> </ul> </div> <div class="header"> <div class="headertitle"> <div class="title">Shared/Airship/External/UA_ZipFile-OC/UA_minizip/UA_mztools.h</div> </div> </div> <div class="contents"> <div class="fragment"><pre class="fragment"><a name="l00001"></a>00001 <span class="comment">/*</span> <a name="l00002"></a>00002 <span class="comment"> Additional tools for Minizip</span> <a name="l00003"></a>00003 <span class="comment"> Code: Xavier Roche &#39;2004</span> <a name="l00004"></a>00004 <span class="comment"> License: Same as ZLIB (www.gzip.org)</span> <a name="l00005"></a>00005 <span class="comment">*/</span> <a name="l00006"></a>00006 <a name="l00007"></a>00007 <span class="preprocessor">#ifndef _zip_tools_H</span> <a name="l00008"></a>00008 <span class="preprocessor"></span><span class="preprocessor">#define _zip_tools_H</span> <a name="l00009"></a>00009 <span class="preprocessor"></span> <a name="l00010"></a>00010 <span class="preprocessor">#ifdef __cplusplus</span> <a name="l00011"></a>00011 <span class="preprocessor"></span><span class="keyword">extern</span> <span class="stringliteral">&quot;C&quot;</span> { <a name="l00012"></a>00012 <span class="preprocessor">#endif</span> <a name="l00013"></a>00013 <span class="preprocessor"></span> <a name="l00014"></a>00014 <span class="preprocessor">#ifndef _ZLIB_H</span> <a name="l00015"></a>00015 <span class="preprocessor"></span><span class="preprocessor">#include &quot;zlib.h&quot;</span> <a name="l00016"></a>00016 <span class="preprocessor">#endif</span> <a name="l00017"></a>00017 <span class="preprocessor"></span> <a name="l00018"></a>00018 <span class="preprocessor">#include &quot;UA_unzip.h&quot;</span> <a name="l00019"></a>00019 <a name="l00020"></a>00020 <span class="comment">/* Repair a ZIP file (missing central directory) </span> <a name="l00021"></a>00021 <span class="comment"> file: file to recover</span> <a name="l00022"></a>00022 <span class="comment"> fileOut: output file after recovery</span> <a name="l00023"></a>00023 <span class="comment"> fileOutTmp: temporary file name used for recovery</span> <a name="l00024"></a>00024 <span class="comment">*/</span> <a name="l00025"></a>00025 <span class="keyword">extern</span> <span class="keywordtype">int</span> ZEXPORT UA_unzRepair(<span class="keyword">const</span> <span class="keywordtype">char</span>* file, <a name="l00026"></a>00026 <span class="keyword">const</span> <span class="keywordtype">char</span>* fileOut, <a name="l00027"></a>00027 <span class="keyword">const</span> <span class="keywordtype">char</span>* fileOutTmp, <a name="l00028"></a>00028 uLong* nRecovered, <a name="l00029"></a>00029 uLong* bytesRecovered); <a name="l00030"></a>00030 <a name="l00031"></a>00031 <span class="preprocessor">#endif</span> </pre></div></div> </div> <!-- window showing the filter options --> <div id="MSearchSelectWindow" onmouseover="return searchBox.OnSearchSelectShow()" onmouseout="return searchBox.OnSearchSelectHide()" onkeydown="return searchBox.OnSearchSelectKey(event)"> <a class="SelectItem" href="javascript:void(0)" onclick="searchBox.OnSelectItem(0)"><span class="SelectionMark">&#160;</span>All</a><a class="SelectItem" href="javascript:void(0)" onclick="searchBox.OnSelectItem(1)"><span class="SelectionMark">&#160;</span>Classes</a><a class="SelectItem" href="javascript:void(0)" onclick="searchBox.OnSelectItem(2)"><span class="SelectionMark">&#160;</span>Functions</a><a class="SelectItem" href="javascript:void(0)" onclick="searchBox.OnSelectItem(3)"><span class="SelectionMark">&#160;</span>Variables</a><a class="SelectItem" href="javascript:void(0)" onclick="searchBox.OnSelectItem(4)"><span class="SelectionMark">&#160;</span>Properties</a></div> <!-- iframe showing the search results (closed by default) --> <div id="MSearchResultsWindow"> <iframe src="javascript:void(0)" frameborder="0" name="MSearchResults" id="MSearchResults"> </iframe> </div> <hr class="footer"/><address class="footer"><small>Generated on Tue Aug 30 2011 10:11:53 for Ignite Tools by&#160; <a href="http://www.doxygen.org/index.html"> <img class="footer" src="doxygen.png" alt="doxygen"/></a> 1.7.4 </small></address> </body> </html>
{ "content_hash": "fc9cfe4fd1af2eef379b8c4c5a7904a0", "timestamp": "", "source": "github", "line_count": 113, "max_line_length": 689, "avg_line_length": 59.08849557522124, "alnum_prop": 0.6616744046727572, "repo_name": "jflasher/IgniteTools", "id": "c182468672ec13fb03db7d9b576c81450f21045e", "size": "6677", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "DoxygenDocs.docset/html/com.arssollertia.ignitetools.docset/Contents/Resources/Documents/_u_a__mztools_8h_source.html", "mode": "33188", "license": "bsd-2-clause", "language": [ { "name": "C", "bytes": "1285" }, { "name": "JavaScript", "bytes": "41572" }, { "name": "Objective-C", "bytes": "525661" }, { "name": "Perl", "bytes": "5034" } ], "symlink_target": "" }
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>KEY_INTERVAL property - TrackerResponse class - tracker library - Dart API</title> <!-- required because all the links are pseudo-absolute --> <base href="../.."> <link href='https://fonts.googleapis.com/css?family=Source+Code+Pro|Roboto:500,400italic,300,400' rel='stylesheet' type='text/css'> <link rel="stylesheet" href="static-assets/prettify.css"> <link rel="stylesheet" href="static-assets/css/bootstrap.min.css"> <link rel="stylesheet" href="static-assets/styles.css"> <meta name="description" content="API docs for the KEY_INTERVAL property from the TrackerResponse class, for the Dart programming language."> <link rel="icon" href="static-assets/favicon.png"> <!-- Do not remove placeholder --> <!-- Header Placeholder --> </head> <body> <div id="overlay-under-drawer"></div> <header class="container-fluid" id="title"> <nav class="navbar navbar-fixed-top"> <div class="container"> <button id="sidenav-left-toggle" type="button">&nbsp;</button> <ol class="breadcrumbs gt-separated hidden-xs"> <li><a href="index.html">hetimatorrent</a></li> <li><a href="tracker/tracker-library.html">tracker</a></li> <li><a href="tracker/TrackerResponse-class.html">TrackerResponse</a></li> <li class="self-crumb">KEY_INTERVAL</li> </ol> <div class="self-name">KEY_INTERVAL</div> </div> </nav> <div class="container masthead"> <ol class="breadcrumbs gt-separated visible-xs"> <li><a href="index.html">hetimatorrent</a></li> <li><a href="tracker/tracker-library.html">tracker</a></li> <li><a href="tracker/TrackerResponse-class.html">TrackerResponse</a></li> <li class="self-crumb">KEY_INTERVAL</li> </ol> <div class="title-description"> <h1 class="title"> <div class="kind">property</div> KEY_INTERVAL </h1> <!-- p class="subtitle"> </p --> </div> <ul class="subnav"> </ul> </div> </header> <div class="container body"> <div class="col-xs-6 col-sm-3 sidebar sidebar-offcanvas-left"> <h5><a href="index.html">hetimatorrent</a></h5> <h5><a href="tracker/tracker-library.html">tracker</a></h5> <h5><a href="tracker/TrackerResponse-class.html">TrackerResponse</a></h5> <ol> <li class="section-title"><a href="tracker/TrackerResponse-class.html#static-properties">Static properties</a></li> <li><a href="tracker/TrackerResponse/KEY_FAILURE_REASON.html">KEY_FAILURE_REASON</a></li> <li><a href="tracker/TrackerResponse/KEY_INTERVAL.html">KEY_INTERVAL</a></li> <li><a href="tracker/TrackerResponse/KEY_IP.html">KEY_IP</a></li> <li><a href="tracker/TrackerResponse/KEY_PEERS.html">KEY_PEERS</a></li> <li><a href="tracker/TrackerResponse/KEY_PEER_ID.html">KEY_PEER_ID</a></li> <li><a href="tracker/TrackerResponse/KEY_PEER_ID2.html">KEY_PEER_ID2</a></li> <li><a href="tracker/TrackerResponse/KEY_PORT.html">KEY_PORT</a></li> <li class="section-title"><a href="tracker/TrackerResponse-class.html#static-methods">Static methods</a></li> <li><a href="tracker/TrackerResponse/createFromContent.html">createFromContent</a></li> <li class="section-title"><a href="tracker/TrackerResponse-class.html#instance-properties">Properties</a></li> <li><a href="tracker/TrackerResponse/failureReason.html">failureReason</a> </li> <li><a href="tracker/TrackerResponse/interval.html">interval</a> </li> <li><a href="tracker/TrackerResponse/isOK.html">isOK</a> </li> <li><a href="tracker/TrackerResponse/peers.html">peers</a> </li> <li class="section-title"><a href="tracker/TrackerResponse-class.html#constructors">Constructors</a></li> <li><a href="tracker/TrackerResponse/TrackerResponse.html">TrackerResponse</a></li> <li><a href="tracker/TrackerResponse/TrackerResponse.bencode.html">bencode</a></li> <li class="section-title"><a href="tracker/TrackerResponse-class.html#methods">Methods</a></li> <li><a href="tracker/TrackerResponse/createResponse.html">createResponse</a> </li> <li><a href="tracker/TrackerResponse/initFromMap.html">initFromMap</a> </li> </ol> </div><!--/.sidebar-offcanvas--> <div class="col-xs-12 col-sm-9 col-md-6 main-content"> <section class="multi-line-signature"> <span class="returntype">String</span> <span class="name ">KEY_INTERVAL</span> <div class="readable-writable"> read-only </div> </section> <section class="desc markdown"> <p class="no-docs">Not documented.</p> </section> </div> <!-- /.main-content --> </div> <!-- container --> <footer> <div class="container-fluid"> <div class="container"> <p class="text-center"> <span class="no-break"> hetimatorrent 0.0.1 api docs </span> &bull; <span class="copyright no-break"> <a href="https://www.dartlang.org"> <img src="static-assets/favicon.png" alt="Dart" title="Dart"width="16" height="16"> </a> </span> &bull; <span class="copyright no-break"> <a href="http://creativecommons.org/licenses/by-sa/4.0/">cc license</a> </span> </p> </div> </div> </footer> <script src="static-assets/prettify.js"></script> <script src="static-assets/script.js"></script> <!-- Do not remove placeholder --> <!-- Footer Placeholder --> </body> </html>
{ "content_hash": "a6b9e7692132fd073ffa926754f6795b", "timestamp": "", "source": "github", "line_count": 153, "max_line_length": 145, "avg_line_length": 39.333333333333336, "alnum_prop": 0.6050182784978398, "repo_name": "kyorohiro/dart_hetimatorrent", "id": "072f313c8e6bbb5e68c752c641be44ba16fe3fdd", "size": "6018", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "doc/api/tracker/TrackerResponse/KEY_INTERVAL.html", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "CSS", "bytes": "165425" }, { "name": "Dart", "bytes": "453550" }, { "name": "HTML", "bytes": "19043" }, { "name": "JavaScript", "bytes": "2312" } ], "symlink_target": "" }
// Copyright (c) 2009-2010 Satoshi Nakamoto // Copyright (c) 2009-2021 The Bitcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include <addrdb.h> #include <addrman.h> #include <chainparams.h> #include <clientversion.h> #include <cstdint> #include <hash.h> #include <logging/timer.h> #include <netbase.h> #include <random.h> #include <streams.h> #include <tinyformat.h> #include <univalue.h> #include <util/settings.h> #include <util/system.h> #include <util/translation.h> namespace { class DbNotFoundError : public std::exception { using std::exception::exception; }; template <typename Stream, typename Data> bool SerializeDB(Stream& stream, const Data& data) { // Write and commit header, data try { CHashWriter hasher(stream.GetType(), stream.GetVersion()); stream << Params().MessageStart() << data; hasher << Params().MessageStart() << data; stream << hasher.GetHash(); } catch (const std::exception& e) { return error("%s: Serialize or I/O error - %s", __func__, e.what()); } return true; } template <typename Data> bool SerializeFileDB(const std::string& prefix, const fs::path& path, const Data& data, int version) { // Generate random temporary filename uint16_t randv = 0; GetRandBytes((unsigned char*)&randv, sizeof(randv)); std::string tmpfn = strprintf("%s.%04x", prefix, randv); // open temp output file, and associate with CAutoFile fs::path pathTmp = gArgs.GetDataDirNet() / tmpfn; FILE *file = fsbridge::fopen(pathTmp, "wb"); CAutoFile fileout(file, SER_DISK, version); if (fileout.IsNull()) { fileout.fclose(); remove(pathTmp); return error("%s: Failed to open file %s", __func__, fs::PathToString(pathTmp)); } // Serialize if (!SerializeDB(fileout, data)) { fileout.fclose(); remove(pathTmp); return false; } if (!FileCommit(fileout.Get())) { fileout.fclose(); remove(pathTmp); return error("%s: Failed to flush file %s", __func__, fs::PathToString(pathTmp)); } fileout.fclose(); // replace existing file, if any, with new file if (!RenameOver(pathTmp, path)) { remove(pathTmp); return error("%s: Rename-into-place failed", __func__); } return true; } template <typename Stream, typename Data> void DeserializeDB(Stream& stream, Data& data, bool fCheckSum = true) { CHashVerifier<Stream> verifier(&stream); // de-serialize file header (network specific magic number) and .. unsigned char pchMsgTmp[4]; verifier >> pchMsgTmp; // ... verify the network matches ours if (memcmp(pchMsgTmp, Params().MessageStart(), sizeof(pchMsgTmp))) { throw std::runtime_error{"Invalid network magic number"}; } // de-serialize data verifier >> data; // verify checksum if (fCheckSum) { uint256 hashTmp; stream >> hashTmp; if (hashTmp != verifier.GetHash()) { throw std::runtime_error{"Checksum mismatch, data corrupted"}; } } } template <typename Data> void DeserializeFileDB(const fs::path& path, Data& data, int version) { // open input file, and associate with CAutoFile FILE* file = fsbridge::fopen(path, "rb"); CAutoFile filein(file, SER_DISK, version); if (filein.IsNull()) { throw DbNotFoundError{}; } DeserializeDB(filein, data); } } // namespace CBanDB::CBanDB(fs::path ban_list_path) : m_banlist_dat(ban_list_path + ".dat"), m_banlist_json(ban_list_path + ".json") { } bool CBanDB::Write(const banmap_t& banSet) { std::vector<std::string> errors; if (util::WriteSettings(m_banlist_json, {{JSON_KEY, BanMapToJson(banSet)}}, errors)) { return true; } for (const auto& err : errors) { error("%s", err); } return false; } bool CBanDB::Read(banmap_t& banSet) { if (fs::exists(m_banlist_dat)) { LogPrintf("banlist.dat ignored because it can only be read by " PACKAGE_NAME " version 22.x. Remove %s to silence this warning.\n", fs::quoted(fs::PathToString(m_banlist_dat))); } // If the JSON banlist does not exist, then recreate it if (!fs::exists(m_banlist_json)) { return false; } std::map<std::string, util::SettingsValue> settings; std::vector<std::string> errors; if (!util::ReadSettings(m_banlist_json, settings, errors)) { for (const auto& err : errors) { LogPrintf("Cannot load banlist %s: %s\n", fs::PathToString(m_banlist_json), err); } return false; } try { BanMapFromJson(settings[JSON_KEY], banSet); } catch (const std::runtime_error& e) { LogPrintf("Cannot parse banlist %s: %s\n", fs::PathToString(m_banlist_json), e.what()); return false; } return true; } bool DumpPeerAddresses(const ArgsManager& args, const AddrMan& addr) { const auto pathAddr = args.GetDataDirNet() / "peers.dat"; return SerializeFileDB("peers", pathAddr, addr, CLIENT_VERSION); } void ReadFromStream(AddrMan& addr, CDataStream& ssPeers) { DeserializeDB(ssPeers, addr, false); } std::optional<bilingual_str> LoadAddrman(const std::vector<bool>& asmap, const ArgsManager& args, std::unique_ptr<AddrMan>& addrman) { auto check_addrman = std::clamp<int32_t>(args.GetIntArg("-checkaddrman", DEFAULT_ADDRMAN_CONSISTENCY_CHECKS), 0, 1000000); addrman = std::make_unique<AddrMan>(asmap, /* deterministic */ false, /* consistency_check_ratio */ check_addrman); int64_t nStart = GetTimeMillis(); const auto path_addr{args.GetDataDirNet() / "peers.dat"}; try { DeserializeFileDB(path_addr, *addrman, CLIENT_VERSION); LogPrintf("Loaded %i addresses from peers.dat %dms\n", addrman->size(), GetTimeMillis() - nStart); } catch (const DbNotFoundError&) { // Addrman can be in an inconsistent state after failure, reset it addrman = std::make_unique<AddrMan>(asmap, /* deterministic */ false, /* consistency_check_ratio */ check_addrman); LogPrintf("Creating peers.dat because the file was not found (%s)\n", fs::quoted(fs::PathToString(path_addr))); DumpPeerAddresses(args, *addrman); } catch (const std::exception& e) { addrman = nullptr; return strprintf(_("Invalid or corrupt peers.dat (%s). If you believe this is a bug, please report it to %s. As a workaround, you can move the file (%s) out of the way (rename, move, or delete) to have a new one created on the next start."), e.what(), PACKAGE_BUGREPORT, fs::quoted(fs::PathToString(path_addr))); } return std::nullopt; } void DumpAnchors(const fs::path& anchors_db_path, const std::vector<CAddress>& anchors) { LOG_TIME_SECONDS(strprintf("Flush %d outbound block-relay-only peer addresses to anchors.dat", anchors.size())); SerializeFileDB("anchors", anchors_db_path, anchors, CLIENT_VERSION | ADDRV2_FORMAT); } std::vector<CAddress> ReadAnchors(const fs::path& anchors_db_path) { std::vector<CAddress> anchors; try { DeserializeFileDB(anchors_db_path, anchors, CLIENT_VERSION | ADDRV2_FORMAT); LogPrintf("Loaded %i addresses from %s\n", anchors.size(), fs::quoted(fs::PathToString(anchors_db_path.filename()))); } catch (const std::exception&) { anchors.clear(); } fs::remove(anchors_db_path); return anchors; }
{ "content_hash": "3ba4d73d5799ae7afe3060ead8f962f1", "timestamp": "", "source": "github", "line_count": 225, "max_line_length": 249, "avg_line_length": 33.44888888888889, "alnum_prop": 0.6502790326866862, "repo_name": "mm-s/bitcoin", "id": "94518b88d86704606b855909d472d3de3ea68f13", "size": "7526", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/addrdb.cpp", "mode": "33188", "license": "mit", "language": [ { "name": "Assembly", "bytes": "28178" }, { "name": "C", "bytes": "1228370" }, { "name": "C++", "bytes": "9407360" }, { "name": "CMake", "bytes": "29132" }, { "name": "Cap'n Proto", "bytes": "1256" }, { "name": "Dockerfile", "bytes": "1721" }, { "name": "HTML", "bytes": "21833" }, { "name": "Java", "bytes": "541" }, { "name": "M4", "bytes": "247147" }, { "name": "Makefile", "bytes": "136414" }, { "name": "Objective-C++", "bytes": "5497" }, { "name": "Python", "bytes": "2661378" }, { "name": "QMake", "bytes": "438" }, { "name": "Sage", "bytes": "56897" }, { "name": "Scheme", "bytes": "24076" }, { "name": "Shell", "bytes": "211674" } ], "symlink_target": "" }
body { font-family: sans-serif; } #lsn_mask, #lsn_mask iframe { top: 0; left: 0; background-color: #eee; filter: alpha(opacity=55); -moz-opacity: .55; opacity: .55; position: absolute; z-index: 99; width:100%;/*must have for any big value*/ height:100%;/*must have for any big value*/; } /* Fix for misbehaving mask in ie5.5/6 with select boxes.*/ #lsn_mask iframe { display:none;/*sorry for IE5*/ display/**/:block;/*sorry for IE5*/ position:absolute;/*must have*/ top:0;/*must have*/ left:0;/*must have*/ z-index:-1;/*must have*/ filter:mask();/*must have*/ width:100%;/*must have for any big value*/ height:100%;/*must have for any big value*/; } #lsn_message_box { position: absolute; border: 1px outset; padding: 1em 1em 3em 1em; background: white; z-index: 900; } #lsn_message_box button { position: absolute; right: 10px; bottom: 10px; } #lsn_status { position: absolute; border: 1px outset; padding: 1em; background: white; z-index: 900; } #lsn_trace_box { position: absolute; border: 1px solid; padding: 5px; z-index: 100; overflow: auto; height: 150px; width: 350px; font-size: smaller; }
{ "content_hash": "ee69b40665ff9c09cd79372ff86f2999", "timestamp": "", "source": "github", "line_count": 63, "max_line_length": 59, "avg_line_length": 18.857142857142858, "alnum_prop": 0.6422558922558923, "repo_name": "ryangies/lsn-www-hub", "id": "92b8938be29217f1a2785dbdea877c88df9b8e42", "size": "1188", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/share/web/res/css/minimal.css", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "14426" }, { "name": "HTML", "bytes": "37933" }, { "name": "JavaScript", "bytes": "52098" }, { "name": "Perl", "bytes": "265913" }, { "name": "Shell", "bytes": "22426" } ], "symlink_target": "" }