text
stringlengths
2
1.04M
meta
dict
import os import unittest import imath import IECore import Gaffer import GafferTest import GafferScene import GafferSceneTest class SubTreeTest( GafferSceneTest.SceneTestCase ) : def testPassThrough( self ) : a = GafferScene.SceneReader() a["fileName"].setValue( os.path.dirname( __file__ ) + "/alembicFiles/groupedPlane.abc" ) s = GafferScene.SubTree() s["in"].setInput( a["out"] ) # We have to skip the test of built in sets, because our alembic file contains cameras # and alembic doesn't provide a means of flagging them upfront. self.assertSceneValid( s["out"], assertBuiltInSetsComplete = False ) self.assertScenesEqual( a["out"], s["out"] ) self.assertSceneHashesEqual( a["out"], s["out"] ) self.assertTrue( a["out"].object( "/group/plane", _copy = False ).isSame( s["out"].object( "/group/plane", _copy = False ) ) ) def testSubTree( self ) : a = GafferScene.SceneReader() a["fileName"].setValue( os.path.dirname( __file__ ) + "/alembicFiles/groupedPlane.abc" ) s = GafferScene.SubTree() s["in"].setInput( a["out"] ) s["root"].setValue( "/group" ) self.assertSceneValid( s["out"] ) self.assertScenesEqual( s["out"], a["out"], scenePlug2PathPrefix = "/group" ) self.assertTrue( a["out"].object( "/group/plane", _copy = False ).isSame( s["out"].object( "/plane", _copy = False ) ) ) def testSets( self ) : l = GafferSceneTest.TestLight() g = GafferScene.Group() g["in"][0].setInput( l["out"] ) self.assertSetsValid( g["out"] ) s = GafferScene.SubTree() s["in"].setInput( g["out"] ) s["root"].setValue( "/group" ) self.assertSetsValid( s["out"] ) def testRootHashesEqual( self ) : a = GafferScene.SceneReader() a["fileName"].setValue( os.path.dirname( __file__ ) + "/alembicFiles/animatedCube.abc" ) s = GafferScene.SubTree() s["in"].setInput( a["out"] ) # We have to skip the test of built in sets, because our alembic file contains cameras # and alembic doesn't provide a means of flagging them upfront. self.assertSceneValid( s["out"], assertBuiltInSetsComplete = False ) self.assertPathHashesEqual( a["out"], "/", s["out"], "/" ) def testDisabled( self ) : p = GafferScene.Plane() g = GafferScene.Group() g["in"][0].setInput( p["out"] ) s = GafferScene.SubTree() s["in"].setInput( g["out"] ) s["root"].setValue( "/group" ) s["enabled"].setValue( False ) self.assertSceneValid( s["out"] ) self.assertScenesEqual( s["out"], g["out"] ) self.assertSceneHashesEqual( s["out"], g["out"] ) def testForwardDeclarationsFromOmittedBranchAreOmitted( self ) : # /group # /lightGroup1 # /light # /lightGroup2 # /light # /lightGroup # /light # /lightGroup10 # /light l = GafferSceneTest.TestLight() lg1 = GafferScene.Group() lg1["name"].setValue( "lightGroup1" ) lg1["in"][0].setInput( l["out"] ) lg2 = GafferScene.Group() lg2["name"].setValue( "lightGroup2" ) lg2["in"][0].setInput( l["out"] ) lg3 = GafferScene.Group() lg3["name"].setValue( "lightGroup" ) lg3["in"][0].setInput( l["out"] ) lg4 = GafferScene.Group() lg4["name"].setValue( "lightGroup10" ) lg4["in"][0].setInput( l["out"] ) g = GafferScene.Group() g["in"][0].setInput( lg1["out"] ) g["in"][1].setInput( lg2["out"] ) g["in"][2].setInput( lg3["out"] ) g["in"][3].setInput( lg4["out"] ) self.assertSetsValid( g["out"] ) # /light s = GafferScene.SubTree() s["in"].setInput( g["out"] ) s["root"].setValue( "/group/lightGroup1" ) lightSet = s["out"].set( "__lights" ) self.assertEqual( lightSet.value.paths(), [ "/light" ] ) self.assertSetsValid( s["out"] ) # with includeRoot == True s["includeRoot"].setValue( True ) lightSet = s["out"].set( "__lights" ) self.assertEqual( lightSet.value.paths(), [ "/lightGroup1/light" ] ) self.assertSetsValid( s["out"] ) def testSetsPassThroughWhenNoRoot( self ) : l = GafferSceneTest.TestLight() g = GafferScene.Group() g["in"][0].setInput( l["out"] ) s = GafferScene.SubTree() s["in"].setInput( g["out"] ) lightSet = s["out"].set( "__lights" ) self.assertEqual( lightSet.value.paths(), [ "/group/light" ] ) self.assertSetsValid( s["out"] ) s["root"].setValue( "/" ) lightSet = s["out"].set( "__lights" ) self.assertEqual( lightSet.value.paths(), [ "/group/light" ] ) self.assertSetsValid( s["out"] ) # with includeRoot == True s["includeRoot"].setValue( True ) s["root"].setValue( "" ) lightSet = s["out"].set( "__lights" ) self.assertEqual( lightSet.value.paths(), [ "/group/light" ] ) self.assertSetsValid( s["out"] ) s["root"].setValue( "/" ) lightSet = s["out"].set( "__lights" ) self.assertEqual( lightSet.value.paths(), [ "/group/light" ] ) self.assertSetsValid( s["out"] ) def testAffects( self ) : s = GafferScene.SubTree() for n in [ "bound", "transform", "attributes", "object", "childNames", "set" ] : a = s.affects( s["in"][n] ) self.assertEqual( len( a ), 1 ) self.assertTrue( a[0].isSame( s["out"][n] ) ) def testIncludeRoot( self ) : a = GafferScene.SceneReader() a["fileName"].setValue( os.path.dirname( __file__ ) + "/alembicFiles/groupedPlane.abc" ) s = GafferScene.SubTree() s["in"].setInput( a["out"] ) s["root"].setValue( "/group" ) s["includeRoot"].setValue( True ) self.assertSceneValid( s["out"] ) self.assertScenesEqual( s["out"], a["out"] ) self.assertEqual( s["out"].childNames( "/" ), IECore.InternedStringVectorData( [ "group" ] ) ) self.assertEqual( s["out"].bound( "/" ), a["out"].bound( "/group" ) ) self.assertTrue( a["out"].object( "/group/plane", _copy = False ).isSame( s["out"].object( "/group/plane", _copy = False ) ) ) def testRootBoundWithTransformedChild( self ) : a = GafferScene.SceneReader() a["fileName"].setValue( os.path.dirname( __file__ ) + "/alembicFiles/animatedCube.abc" ) s = GafferScene.SubTree() s["in"].setInput( a["out"] ) s["root"].setValue( "/pCube1" ) s["includeRoot"].setValue( True ) with Gaffer.Context() as c : c.setFrame( 10 ) expectedRootBound = a["out"].bound( "/pCube1" ) expectedRootBound = expectedRootBound * a["out"].transform( "/pCube1" ) self.assertEqual( s["out"].bound( "/" ), expectedRootBound ) def testIncludeRootPassesThroughWhenNoRootSpecified( self ) : a = GafferScene.SceneReader() a["fileName"].setValue( os.path.dirname( __file__ ) + "/alembicFiles/animatedCube.abc" ) s = GafferScene.SubTree() s["in"].setInput( a["out"] ) s["root"].setValue( "" ) s["includeRoot"].setValue( True ) # We have to skip the test of built in sets, because our alembic file contains cameras # and alembic doesn't provide a means of flagging them upfront. self.assertSceneValid( s["out"], assertBuiltInSetsComplete = False ) self.assertScenesEqual( a["out"], s["out"] ) self.assertSceneHashesEqual( a["out"], s["out"] ) self.assertTrue( a["out"].object( "/pCube1", _copy = False ).isSame( s["out"].object( "/pCube1", _copy = False ) ) ) def testSetsWithIncludeRoot( self ) : l = GafferSceneTest.TestLight() g = GafferScene.Group() g["in"][0].setInput( l["out"] ) self.assertSetsValid( g["out"] ) s = GafferScene.SubTree() s["in"].setInput( g["out"] ) s["root"].setValue( "/group" ) s["includeRoot"].setValue( True ) lightSet = s["out"].set( "__lights" ) self.assertEqual( lightSet.value.paths(), [ "/group/light" ] ) self.assertSetsValid( s["out"] ) def testSetsWithNoLeadingSlash( self ) : l = GafferSceneTest.TestLight() g = GafferScene.Group() g["in"][0].setInput( l["out"] ) self.assertSetsValid( g["out"] ) s = GafferScene.SubTree() s["in"].setInput( g["out"] ) s["root"].setValue( "group" ) lightSet = s["out"].set( "__lights" ) self.assertEqual( lightSet.value.paths(), [ "/light" ] ) self.assertSetsValid( s["out"] ) def testSetNamesAndGlobalsPassThrough( self ) : l = GafferSceneTest.TestLight() g = GafferScene.Group() g["in"][0].setInput( l["out"] ) s = GafferScene.SubTree() s["in"].setInput( g["out"] ) s["root"].setValue( "group" ) self.assertEqual( s["out"]["globals"].hash(), g["out"]["globals"].hash() ) self.assertTrue( s["out"]["globals"].getValue( _copy = False ).isSame( g["out"]["globals"].getValue( _copy = False ) ) ) self.assertEqual( s["out"]["setNames"].hash(), g["out"]["setNames"].hash() ) self.assertTrue( s["out"]["setNames"].getValue( _copy = False ).isSame( g["out"]["setNames"].getValue( _copy = False ) ) ) def testInvalidRoot( self ) : p = GafferScene.Plane() p["sets"].setValue( "A" ) g = GafferScene.Group() g["in"][0].setInput( p["out"] ) s = GafferScene.SubTree() s["in"].setInput( g["out"] ) # An invalid root matches nothing, so should output an empty scene for includeRoot in ( True, False ) : s["includeRoot"].setValue( includeRoot ) for root in ( "notAThing", "/group/stillNotAThing", "/group/definitely/not/a/thing" ) : s["root"].setValue( root ) self.assertSceneValid( s["out"] ) self.assertEqual( s["out"].childNames( "/" ), IECore.InternedStringVectorData() ) self.assertEqual( s["out"].set( "A" ), IECore.PathMatcherData() ) self.assertEqual( s["out"].bound( "/" ), imath.Box3f() ) self.assertEqual( s["out"].attributes( "/" ), IECore.CompoundObject() ) self.assertEqual( s["out"].transform( "/" ), imath.M44f() ) if __name__ == "__main__": unittest.main()
{ "content_hash": "c36108af9b3f88f446aa30fa30f49966", "timestamp": "", "source": "github", "line_count": 318, "max_line_length": 128, "avg_line_length": 29.547169811320753, "alnum_prop": 0.6330353341847594, "repo_name": "ImageEngine/gaffer", "id": "7cc4f8c5f13f6860deb0c678632443afc64818e1", "size": "11261", "binary": false, "copies": "1", "ref": "refs/heads/main", "path": "python/GafferSceneTest/SubTreeTest.py", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "C", "bytes": "4486" }, { "name": "C++", "bytes": "5353598" }, { "name": "CSS", "bytes": "28027" }, { "name": "GLSL", "bytes": "6250" }, { "name": "Python", "bytes": "5296193" }, { "name": "Shell", "bytes": "8008" }, { "name": "Slash", "bytes": "41159" } ], "symlink_target": "" }
<?xml version="1.0" encoding="utf-8"?><!-- ~ Copyright (C) 2014 barter.li ~ ~ 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. --> <resources> <string name="app_name">barter.li</string> <string name="receiver_network">Network Change Receiver</string> <string name="team_heading">Team Members</string> <string name="action_settings">Settings</string> <string name="service_chat">Chat Service</string> <string name="scanactivity_title">Scan Barcode On Book</string> <string name="editbook_title">Add Book</string> <string name="editbook_title2">Edit Book</string> <string name="chat_fragment_title">Chats</string> <string name="Report_fragment_title">Send Feedback</string> <string name="Collaborate_fragment_title">Collaborate</string> <string name="Opensource_fragment_title">Open Source</string> <string name="Aboutus_fragment_title">About us</string> <string name="Tribute_fragment_title">Tribute</string> <string name="Book_Detail_fragment_title">Book Detail</string> <string name="update_info">Update Info</string> <string name="preferred_location">Preferred location</string> <string name="forgot_password_underlined"><u>Forgot password?</u></string> <string name="forgot_password">Forgot password</string> <string name="enable_location">Enable location</string> <string name="enable">Enable</string> <string name="enable_location_message">Please enable your location settings for getting nearby books</string> <string name="cancel">Cancel</string> <string name="about_me">About me</string> <string name="my_books">My Books</string> <string name="no_books_found_nearby">Oops! There were no books found near you.</string> <string name="no_places_found_nearby">No places found near you</string> <string name="loading">loading books please wait &#8230;</string> <string name="try_again"><u>Try Again</u></string> <string name="or">or</string> <string name="add_your_own"><u>Add A Book</u></string> <string name="add_location_manually"><u>Add Your Current Location</u></string> <string name="logout">Logout</string> <string name="delete_chat_alert_message">Are you sure you want to delete this chat?</string> <string name="block_user_alert_message">Are you sure you want to block this user?</string> <!-- menu strings --> <string name="signup">Sign Up</string> <string name="build_library">Build Library</string> <string name="search">Search Books</string> <string name="welcome_back">Welcome Back!</string> <string name="welcome_fb">Welcome %s!</string> <string name="welcome_to_barterli">Welcome to barter.li!</string> <string name="location_pref_set">We have remembered your preferred location.</string> <string name="profile">Profile</string> <string name="library">My Books</string> <string name="scan_book">Scan Book</string> <string name="refresh">Refresh</string> <string name="add_book">Add Book</string> <string name="add_manually">Add Book Manually</string> <string name="no_network_connection">No network connection!</string> <string name="meters_away">%d meters away</string> <string name="send">Send</string> <string name="enter_message">Enter your message</string> <string name="new_messages">%d new messages!</string> <string name="take_picture">Take Picture</string> <string name="add_book_dialog_head">Add Book</string> <string name="chat_longclick_dialog_head">Chat Options</string> <string name="complete_action_using">Complete action using</string> <string name="no_books_found">No books were found in this area.</string> <string name="no_more_books_found">No more books were found.</string> <string name="location_format" formatted="false">%s, %s</string> <!-- Strings for AddBookActivity --> <string name="search_hint">Search by Title|Author|ISBN</string> <string name="search_by_author_hint">Search by Author</string> <string name="scan_barcode_button_label">Scan ISBN BarCode</string> <string name="add_new_book_label">Manual Entry</string> <string name="search_for_books">Search for books</string> <string name="share">Share</string> <string name="set_sell_hint">Set Price (eg $10)</string> <string name="set_lend_hint">Set Lend Price (eg $10)</string> <string name="confirm_delete_book">Are you sure you want to delete this book?</string> <!-- Strings for EditBookDetailsActivity --> <string name="isbn_label">ISBN Number</string> <string name="title_label">Book Title</string> <string name="author_label">Author</string> <string name="description_label">Description</string> <string name="publication_year_label">Publication Year</string> <string name="suggested_price_label">Suggested Price</string> <string name="publication_month_label">Publication Month</string> <string name="publication_date_label">Publication</string> <string name="barter_type_label">Barter Type</string> <string name="error_enter_title">Enter a book title</string> <string name="book_added">Book has been added!</string> <string name="select_a_barter_type">Select at least one barter type to add the book</string> <string name="unable_to_fetch_book_info">Unable to fetch book info.</string> <string name="unable_to_create_book">Unable to create book</string> <string name="unable_to_delete_book">Unable to delete book</string> <string name="not_a_valid_isbn">Not a valid ISBN.</string> <string name="unable_to_fetch_books">Unable to fetch books.</string> <string name="unable_to_fetch_hangouts">Unable to fetch hangouts.</string> <string name="error_enter_email">Please enter your email address.</string> <string name="error_enter_token">Please enter your token</string> <string name="error_block_user">User cannot be blocked this time, Please try again later</string> <string name="error_invalid_email">Please enter a valid email address.</string> <string name="error_enter_password">Please enter a password.</string> <string name="error_password_minimum_length">Password must be at least %d characters long.</string> <string name="error_unable_to_login">Unable to login.</string> <string name="error_unable_to_set_preferred_location">Unable to set preferred location for user.</string> <string name="error_not_connected_to_chat_service">Not connected to chat service.</string> <string name="no_personal_info_bug_and_suggest">Please don\'t include any personally identifiable information(email, name, phone number, address, etc) as this bug report or feature suggestion will be available publicly.</string> <string name="no_personal_info_suggest">Please don\'t include any personally identifiable information(email, name, phone number, address, etc) as this feature suggestion will be available publicly.</string> <string name="token_email_message">Token is emailed to you</string> <string name="error_required">Required</string> <string name="delete">Delete</string> <string name="help_select_location">Please select your preferred location for book exchange.</string> <string name="your_privacy_is_important">Your privacy is important to us. We don\'t reveal your actual location to anyone.</string> <string name="hint_location_name">Enter preferred location name</string> <string name="about">About</string> <string name="ok">OK</string> <string name="title_unavailable">This book has no name!</string> <string name="author_unavailable">The author is unknown.</string> <string name="by_author" formatted="false">by %s</string> <string name="published_on" formatter="false">Published on %s</string> <string name="description_unavailable">Nothing is known about this book. It\'s a total mystery!</string> <string name="isbn_unavailable">ISBN number not entered.</string> <string name="isbn_number" formatted="false">ISBN Number: %s</string> <string name="publication_date_unavailable">Published a long, long time ago(Really, we don\'t know).</string> <!-- Barter options when adding/editing a book --> <string name="willing_to_barter">I\'m willing to barter this book for another</string> <string name="willing_to_sell">I\'m willing to sell this book for</string> <string name="willing_to_lend">I\'m willing to lend this book</string> <!-- Barter Type Options --> <string name="buy_for">Buy for %s</string> <string name="buy">Buy</string> <string name="borrow">Borrow</string> <string name="give_away">Give Away</string> <string name="barter">Barter</string> <string name="sell">Sell</string> <string name="read">Read</string> <string name="lend">Lend</string> <string name="keep_private">Keep Private</string> <string name="submit">Submit</string> <string name="reset">Reset</string> <string name="chat_with_owner">Chat with owner</string> <string name="owner_profile">Book Owner</string> <string name="owner_location">Owner\'s Preferred Barter Location</string> <string name="login_with_facebook">Login with Facebook</string> <string name="login_with_google">Login with Google</string> <string name="email_label">Email Id</string> <string name="token_label">Token</string> <string name="new_password_label">New password</string> <string name="confirm_password_label">Confirm password</string> <string name="password_label">Password</string> <string name="share_via">Share Via</string> <string name="barter_book">Hey, I\'d like to barter %s for one of my own.</string> <string name="buy_book">Hello! I\'d like to buy %s.</string> <!-- Strings for TakeLatLongActivity --> <string name="lat_long">Location</string> <string name="select_preferred_location_hint">Select your preferred Meeting Location</string> <string name="text_sign_in">Sign In</string> <!-- Primary options for nav drawer --> <string-array name="nav_drawer_primary"> <item>Find Books</item> <item>My Chats</item> </string-array> <!-- Secondary options for nav drawer--> <string-array name="nav_drawer_secondary"> <item>SETTINGS</item> <item>SHARE THE APP</item> <item>RATE US</item> <item>SEND FEEDBACK</item> <item>ABOUT US</item> </string-array> <string-array name="take_photo_choices"> <item>Capture from Camera</item> <item>Add from Gallery</item> </string-array> <string-array name="add_book_choices"> <item>Scan Barcode</item> <item>Add Manually</item> </string-array> <string-array name="chat_longclick_choices"> <item>Delete Chat</item> <item>Block User</item> </string-array> <!-- Strings for chat details --> <string name="sending">&#8230;</string> <string name="failed">Failed to send. Tap to retry.</string> <string name="success_message_for_chatblock">User blocked successfully</string> <string-array name="aboutus_fragment_titles"> <item>Our Inspiration</item> <item>barter.li</item> <item>Team</item> <item>Collaborate</item> <item>Attributions</item> </string-array> <string name="tribute_message">A tribute to Aaron Swartz for inspiring us with his passion</string> <string name="app_share_message">Enter the local book community. Download the android app at &#160;</string> <string name="book_share_message">Found the book, %s, shared on barter.li! Get the app at &#160;</string> <string name="subject">Check this out!</string> <string-array name="months"> <item>January</item> <item>February</item> <item>March</item> <item>April</item> <item>May</item> <item>June</item> <item>July</item> <item>August</item> <item>September</item> <item>October</item> <item>November</item> <item>December</item> </string-array> <!-- String Related to Profile --> <string name="local_profile_image">barterli_avatar_small.png</string> <string name="image_profile_pic_description">Profile Picture</string> <string name="text_default_profile_name">Profile Name</string> <string name="button_edit_preferred_location">Edit Preferred Location</string> <string name="hint_default_current_location"><u>Tap to set your preferred barter location</u></string> <string name="label_about_me">Let us know a bit about you. :-)</string> <string name="label_current_location">Where would you like to meet to barter?</string> <string name="label_referral_count">Number of installs via me</string> <string name="text_edit_profile">Edit</string> <string name="text_save">Save</string> <string name="text_delete">Delete</string> <string name="hint_first_name">First Name</string> <string name="hint_last_name">Last Name(optional)</string> <string name="label_my_books">My Books</string> <string name="profilepage_title">My Profile</string> <string name="book_updated">Book Updated successfully.</string> <string name="format_address_underline" formatted="false"><u>%s, %s</u></string> <!-- Strings/URLs related to ShowWebViewFragment --> <string name="url_google">http://www.google.com</string> <string name="url_me">http://barter.li</string> <!-- String Related to Report Bug --> <string name="text_report_bug">Report Bug</string> <string name="button_submit">Submit</string> <string name="text_bug_title">Barter.Li/Reported Bug</string> <string name="hint_report_bug">Enter Your Findings Here.</string> <string name="hint_enter_device">Enter Device,Version and 3G/Wifi</string> <string name="deviceinfo_tag">Device Info: </string> <!-- String Related to Suggest Feature --> <string name="text_suggest_feature">Suggest a Feature</string> <string name="text_suggest_feature_title">Barter.Li/Suggest Feature</string> <string name="hint_suggest_feature">Enter Your Thoughts Here.</string> <!-- String Related to Collaborate Page --> <string name="text_collaborate">I am interested to be a pro-bono partner in the role of</string> <string name="sponsor">Sponsor</string> <string name="designer">Designer</string> <string name="developer">Developer</string> <string name="campus_ambassador">Campus Ambassador</string> <string name="product_evangelist">Product Evangelist</string> <string name="marketing">Marketing/PR/Social Media</string> <string name="barterli_email">joinus@barter.li</string> <string name="hint_about_me_description">About Me.</string> <!-- String Related to Show Single Book Fragment --> <!-- Strings related to open source licenses --> <string-array name="oss_titles"> <item>Picasso, A powerful image downloading and caching library for Android. Licensed under the Apache v2.0 License\nhttps://github.com/square/picasso</item> <item>Facebook Android SDK, Licensed under the Apache v2.0 License\nhttps://github.com/facebook/facebook-android-sdk</item> <item>enhanced-volley, A networking toolkit based on Volley, from the Android Open Source Project. Licenced under the Apache v2.0 License.\nhttps://github.com/vinaysshenoy/enhanced-volley</item> <item>android-quick-response-code, A library for scanning barcodes. Licensed under the Apache v2.0 License.\nhttps://github.com/phishman3579/android-quick-response-code</item> <item>Crouton, Context sensitive notifications for Android. Licensed under the Apache v2.0 License.\nhttps://github.com/keyboardsurfer/Crouton</item> <item>AndroidSlidingUpPanel, This library provides a simple way to add a draggable sliding up panel (popularized by Google Music, Google Maps and Rdio) to your Android application. Licensed under the Apache v2.0 License.\nhttps://github.com/umano/AndroidSlidingUpPanel</item> <item>Android ViewPagerIndicator, Paging indicator widgets that are compatible with the ViewPager from the Android Support Library to improve discoverability of content.Licensed under the Apache v2.0 License.\nhttps://github.com/JakeWharton/Android-ViewPagerIndicator</item> <item>Aaron Swartz photo credit: Fred Benenson/www.fredbenenson.com; licenced under Creative Commons Attribution 2.0 Generic License</item> </string-array> <string name="about_barterli">An open source, community driven, not-for-profit project.\n\n\n We aim to enable sharing of a billion books across the globe.</string> <!-- Preference Group Titles --> <string name="pref_group_notifications">Chat Notifications</string> <string name="pref_group_barter_lend">Barter &amp; Lend Events</string> <string name="pref_group_sort">Sort</string> <!-- Preference Item titles--> <string name="pref_title_enabled">Enabled</string> <string name="pref_title_vibrate">Vibrate</string> <string name="pref_title_ringtone">Ringtone</string> <string name="pref_title_auto_add_to_calendar">Automatically add to Calendar</string> <string name="pref_title_calendar_to_add">Add to</string> <string name="pref_title_reminder">Reminder</string> <string name="pref_title_sort_books">Books by</string> <!-- Entries for multi-choice preference items --> <string-array name="pref_choices_reminder"> <item>30 minutes</item> <item>1 hour</item> <item>2 hours</item> <item>4 hours</item> <item>8 hours</item> <item>12 hours</item> <item>1 day</item> </string-array> <string-array name="pref_choices_sort_books"> <item>Nearby</item> <item>Newest</item> <item>Alphabetically</item> </string-array> </resources>
{ "content_hash": "19b454d7c0baac6ecbad3c40099b804f", "timestamp": "", "source": "github", "line_count": 326, "max_line_length": 309, "avg_line_length": 56.24233128834356, "alnum_prop": 0.6995364057812926, "repo_name": "siddharth-shah/barterli_android", "id": "0927dd61a47c6a31c56cb598d36179ce9cb80ad2", "size": "18335", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "barterli/src/main/res/values/strings.xml", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "2684049" } ], "symlink_target": "" }
class Micronaut < Formula desc "Modern JVM-based framework for building modular microservices" homepage "https://micronaut.io/" url "https://github.com/micronaut-projects/micronaut-starter/archive/v2.5.5.tar.gz" sha256 "d40fadba548df087c57919ac8ad685624ad39e3add2fad8e52d2af1912c68815" license "Apache-2.0" livecheck do url :stable regex(/^v?(\d+(?:\.\d+)+)$/i) end bottle do sha256 cellar: :any_skip_relocation, big_sur: "c0b1768ca7cfca0affcd1d899546ed1a5711dbc7d585620e94f972451609fee0" sha256 cellar: :any_skip_relocation, catalina: "f68adbee84c552cfb5bc4b5fc63a49dcfca6949aa1f5b21e6eae7b8339bd5df9" sha256 cellar: :any_skip_relocation, mojave: "1a700958ff2cd4e563480860d487aea05af460794b1c8ecfd718d840773dbe3a" end depends_on "gradle" => :build depends_on "openjdk" def install system "./gradlew", "micronaut-cli:assemble", "-x", "test" mkdir_p libexec/"bin" mv "starter-cli/build/exploded/bin/mn", libexec/"bin/mn" mv "starter-cli/build/exploded/lib", libexec/"lib" bash_completion.install "starter-cli/build/exploded/bin/mn_completion" (bin/"mn").write_env_script libexec/"bin/mn", Language::Java.overridable_java_home_env end test do system "#{bin}/mn", "create-app", "hello-world" assert_predicate testpath/"hello-world", :directory? end end
{ "content_hash": "0c82ddcce6a22050797180cf824b79da", "timestamp": "", "source": "github", "line_count": 37, "max_line_length": 117, "avg_line_length": 36.270270270270274, "alnum_prop": 0.7354694485842027, "repo_name": "JCount/homebrew-core", "id": "84ea4f792431babf28ca1e4fbbcd93906378b805", "size": "1342", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "Formula/micronaut.rb", "mode": "33188", "license": "bsd-2-clause", "language": [ { "name": "Perl", "bytes": "628" }, { "name": "Ruby", "bytes": "8290585" } ], "symlink_target": "" }
package org.apache.stratos.kubernetes.client.model; import org.apache.commons.lang3.ArrayUtils; import javax.xml.bind.annotation.XmlRootElement; import java.util.Arrays; @XmlRootElement public class ServiceList { private String kind; private String apiVersion; private Service[] items; public String getKind() { return kind; } public void setKind(String kind) { this.kind = kind; } public String getApiVersion() { return apiVersion; } public void setApiVersion(String apiVersion) { this.apiVersion = apiVersion; } public Service[] getItems() { return items; } public void setItems(Service[] items) { this.items = ArrayUtils.clone(items); } @Override public String toString() { return "ServiceList [kind=" + kind + ", apiVersion=" + apiVersion + ", items=" + Arrays.toString(items) + "]"; } }
{ "content_hash": "cd66df25d518a6290f70619e67a8fadd", "timestamp": "", "source": "github", "line_count": 46, "max_line_length": 73, "avg_line_length": 20.630434782608695, "alnum_prop": 0.6301369863013698, "repo_name": "agentmilindu/stratos", "id": "ecf396a8e3aaa2d59ce5e7de1eaa595b50a665f9", "size": "1762", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "components/org.apache.stratos.kubernetes.client/src/main/java/org/apache/stratos/kubernetes/client/model/ServiceList.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "C", "bytes": "27195" }, { "name": "CSS", "bytes": "78732" }, { "name": "HTML", "bytes": "42426" }, { "name": "Handlebars", "bytes": "107928" }, { "name": "Java", "bytes": "5852567" }, { "name": "JavaScript", "bytes": "748255" }, { "name": "Python", "bytes": "516805" }, { "name": "Ruby", "bytes": "3546" }, { "name": "Shell", "bytes": "157268" } ], "symlink_target": "" }
<?php /** * * Version 1.1.0 * * Author: Roberto Serra - obi.serra@gmail.com * * * This file handle the image-upload using beforeSave and afterSave behaviour * * Configuration: * * @imagesColumns: array * @paths: array/string; {ID} will be replaced by the ID of the actual model * @rename: array; {filename} will be replaced by the name of the uploaded file * * * * -- Usage: -- * * * public function behaviors(){ * return array( * 'ImagesHandler'=>array( * 'class'=>'application.components.ImagesHandler', * 'imagesColumns'=>array('imageFieldName'), * 'paths'=>'/../images/directoryName/{fieldName}', * 'rename'=>array('{filename}_{ID}'), // {filename} and {ID} are automatically replaced by the relative values * 'thumb'=>array(array('field'=>'thumb','path'=>'/../images/galleries/{id_cartella}/','width'=>'620','height'=>'620','crop'=>true)) * ), * ); * } * **/ class ImagesHandler extends CActiveRecordBehavior{ public $imagesColumns = array(); public $paths = array(); public $rename = array(); public $thumb = array(); private $oldImage; private $name; private $newImages; public function checkPath(){ if(is_string($this->paths)){ $paths = array(); foreach( $this->imagesColumns as $k=>$image ){ $paths[$k] = $this->paths; } $this->paths = $paths; } } public function saveOldImage(){ foreach( $this->imagesColumns as $k=>$image ){ $this->oldImage[$k] = $this->Owner->{$image}; } } private function renameIt($fileSingle,$k,$image){ if($this->rename[$k]){ $fileName = str_replace('.'.$fileSingle->extensionName, '', $fileSingle->name); $this->rename[$k] = str_replace('{filename}', $fileName, $this->rename[$k]); $this->rename[$k] = $this->renameSmart($this->rename[$k]); $this->Owner->{$image} = $this->rename[$k].'.'.$fileSingle->extensionName; } } private function renameSmart($subject){ $pattern = '/{[\w]*}/'; preg_match($pattern, $subject, $matches); foreach ($matches as $m) { $orM = $m; $m = str_replace('{', '', $m); $m = str_replace('}', '', $m); if(isset($this->Owner->$m)){ $subject = str_replace($orM, $this->Owner->$m, $subject); } else if($m === 'timestamp'){ $subject = str_replace($orM, time(), $subject); } } return $subject; } public function beforeSave($event) { //$this->saveOldImage(); $this->checkPath(); foreach( $this->imagesColumns as $k=>$image ) { $i = 0; $fileSingle = CUploadedFile::getInstance($this->Owner,$image); if(!empty($fileSingle)){ if(!is_object($fileSingle)){ do{ $file = CUploadedFile::getInstance($this->Owner,'['.$i.']'.$image); if(is_object($file)){ $this->renameIt($fileSingle,$k,$image); $this->newImages[$k] = $file; } $i++; } while($i<10); } else{ $this->renameIt($fileSingle,$k,$image); $this->newImages[$k] = $fileSingle; } } } return parent::beforeSave($event); } public function afterSave($event){ foreach( $this->imagesColumns as $k=>$image ){ if(isset($this->newImages[$k])){ $fileSingle = $this->newImages[$k]; $this->paths[$k] = $this->renameSmart($this->paths[$k]); $oldName = $this->Owner->{$image}; $this->renameIt($fileSingle,$k,$image); if($oldName !== $this->Owner->{$image}){ $model = $this->Owner->findByPk($this->Owner->ID); $model->save(); } if(!is_dir(Yii::app()->basePath.$this->paths[$k].'/')) mkdir(Yii::app()->basePath.$this->paths[$k].'/', 0755); $fileSingle->saveAs(Yii::app()->basePath.$this->paths[$k].'/'.$this->Owner->{$image}); if(!empty($this->thumb[$k])){ $this->resize($k,Yii::app()->basePath.$this->paths[$k].'/'.$this->Owner->{$image}); } } } if(is_array($this->oldImage)){ $this->checkPath(); foreach($this->oldImage as $k =>$img){ $this->paths[$k] = $this->renameSmart($this->paths[$k]); if(!empty($this->Owner->{$this->imagesColumns[$k]})){ if($this->Owner->{$this->imagesColumns[$k]} != $img ){ if(is_file(Yii::app()->basePath.$this->paths[$k].'/'.$img)){ unlink(Yii::app()->basePath.$this->paths[$k].'/'.$img); } } } } } return parent::afterSave($event); } public function resize($k,$filename){ list($width, $height) = getimagesize($filename); $thumb = imagecreatetruecolor($this->thumb[$k]['width'], $this->thumb[$k]['height']); $source = imagecreatefromjpeg($filename); if($this->thumb[$k]['crop']){ $mX = ($width - $this->thumb[$k]['width']) / 2; $mY = ($height - $this->thumb[$k]['height']) / 2; imagecopyresized($thumb, $source, 0, 0, $mX, $mY, $this->thumb[$k]['width'], $this->thumb[$k]['height'], $this->thumb[$k]['width'], $this->thumb[$k]['height']); } else { imagecopyresized($thumb, $source, 0, 0, 0, 0, $this->thumb[$k]['width'], $this->thumb[$k]['height'], $width, $height); } if(!empty($this->name)){ $thumbFilename = str_replace($this->name['ext'], '_th'.$this->name['ext'], $filename); } else { $thumbFilename = $filename; } imagejpeg($thumb, $thumbFilename, 100); } public function afterFind($event){ $this->saveOldImage(); } public function beforeDelete($event){ $this->checkPath(); foreach( $this->imagesColumns as $k=>$image ){ $this->paths[$k] = $this->renameSmart($this->paths[$k]); if(is_file(Yii::app()->basePath.$this->paths[$k].'/'.$this->Owner->{$image})) unlink(Yii::app()->basePath.$this->paths[$k].'/'.$this->Owner->{$image}); @rmdir(Yii::app()->basePath.$this->paths[$k].'/'); } return parent::beforeDelete($event); } public function beforeValidate($event){ foreach( $this->imagesColumns as $k=>$image ){ $file = CUploadedFile::getInstance($this->Owner,$image); if(is_object($file)){ $this->Owner->{$image} = str_replace('.'.$file->extensionName, '', $file->name); $this->name = array('ext' => '.'.$file->extensionName, 'name'=>$file->name); } else if(!empty($this->oldImage[$k])){ $this->Owner->{$image} = $this->oldImage[$k]; } } return parent::beforeValidate($event); } } ?>
{ "content_hash": "5ffedbec10ecc60db3a34740cd14d70b", "timestamp": "", "source": "github", "line_count": 200, "max_line_length": 172, "avg_line_length": 37.4, "alnum_prop": 0.4788770053475936, "repo_name": "obiSerra/yii-helpers", "id": "7395d127340fdf88c1fbe585dc0fef049d3b506e", "size": "7480", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "components/ImagesHandler.php", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "2776" }, { "name": "JavaScript", "bytes": "14246" }, { "name": "PHP", "bytes": "39508" }, { "name": "Shell", "bytes": "687" } ], "symlink_target": "" }
//Copyright 2014 Spin Services Limited //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.Collections.Generic; namespace SS.Integration.Adapter.Model.Interfaces { /// <summary> /// An IMarketState object represents the state of a market. /// The main purpose of keeping the state of a market /// is to infer properties like "IsActive", "IsSuspended", "IsResulted", "IsPending". /// /// As these properties can only be inferred by looking at the selections' states, /// it is difficult, if not impossibile, to determine a market's state /// on a delta snapshot, as information about selections might be absent. /// /// IMarketState keeps track of information coming from subsequents snapshots (full, or delta) /// updating correcly the above properties and then exposing them. /// /// IMarketRule must infer the values of its properties by looking a the /// selections' states, or in other words, by looking at ISelectionState objects. /// </summary> public interface IMarketState { /// <summary> /// /// Market's Id /// /// </summary> string Id { get; } /// <summary> /// /// Market's name /// /// </summary> string Name { get; } /// <summary> /// /// Returns true if the market is in a "Suspended" state. /// /// This property only makes sense if IsActive is true as /// a "Suspended" state doesn't have any meaning when the market /// is not active. /// /// </summary> bool IsSuspended { get; } /// <summary> /// /// Returns true if the market is active. /// /// </summary> bool IsActive { get; } /// <summary> /// /// Is the market resulted? /// This value returns the resulted state of /// a market as it comes from the Connect platform. /// /// It is not related in any way to the resulted /// stated of any down-stream sytems. /// /// </summary> bool IsResulted { get; } /// <summary> /// /// Determines if all the selecions within /// this market have been voided. /// /// </summary> bool IsVoided { get; } /// <summary> /// /// Is the market in a pending state? /// /// A pending state means that the market /// is in a transition state between two valid states /// (i.e Active and Resulted, ...). /// /// Usually, when the market is an pending state, /// no decision about it should be taken /// /// </summary> bool IsPending { get; } /// <summary> /// /// True if the market has been active at least once /// during the fixture's lifetime /// /// </summary> bool HasBeenActive { get; } /// <summary> /// /// Returns true if the market has been seen /// by the plugin at least once. /// /// Due the market rules it is possibile that /// a market that exists in the feed is never /// processed by the plugin. /// /// This property is set to true if the market /// has been passed to the plugin at least once. /// Please note that it DOES NOT mean that the /// market has been created into the downstream /// system. /// /// </summary> bool HasBeenProcessed { get; } /// <summary> /// /// True if the market has been forcely /// suspended by the adapter. /// /// This is different from IsSuspended /// which only looks at the tradability /// of the market /// /// </summary> bool IsForcedSuspended { get; } /// <summary> /// /// Returns the line of the market. /// Only valid if the market is an /// handicap/rolling market /// /// </summary> double? Line { get; } bool IsDeleted { get; set; } /// <summary> /// /// Returns the index of the market as it appears on the feed. /// /// If a a new market definition is applied (hence, new markets might appear /// and existing markets might disappear), all the new markets will have /// LastIndex + IndexOf(market). In other words, if before the market /// definition changed, we had 10 markets, all the new markets will /// have Index = 10 + IndexOf(market) /// /// </summary> int Index { get; } #region Selections /// <summary> /// /// Lists all the ISelectionState objects /// /// </summary> IEnumerable<ISelectionState> Selections { get; } /// <summary> /// /// Returns the ISelectionState object associated /// to the given selection's id. /// /// It returns null if the selection's id is /// null or empty of if the selection does not /// exist /// /// </summary> /// <param name="selectionId"></param> /// <returns></returns> ISelectionState this[string selectionId] { get; } /// <summary> /// /// True if an ISelectionState object for /// the given selection's id is present /// /// </summary> /// <param name="selectionId"></param> /// <returns></returns> bool HasSelection(string selectionId); /// <summary> /// /// Returns the number of selection in this market /// /// </summary> int SelectionsCount { get; } #endregion #region Tags /// <summary> /// /// Lists all the tags that a market has had /// during its lifetime /// /// </summary> IEnumerable<string> TagKeys { get; } /// <summary> /// /// Get the value associated to the /// given tag key. /// /// It returns null if the tag key /// does not exist /// /// </summary> /// <param name="TagKey"></param> /// <returns></returns> string GetTagValue(string TagKey); /// <summary> /// /// True if the given tag key exists /// /// </summary> /// <param name="TagKey"></param> /// <returns></returns> bool HasTag(string TagKey); /// <summary> /// /// Returns the number of tag associated /// to this market state. /// /// </summary> int TagsCount { get; } #endregion /// <summary> /// /// Determines if the given market state /// is equal to the current object /// /// </summary> /// <param name="newMarket"></param> /// <returns></returns> bool IsEqualTo(IMarketState newMarket); /// <summary> /// /// Determines if the given Market object /// is equivalent to the current IMarketState /// object. /// /// </summary> /// <param name="market"></param> /// <param name="checkTags">If true, tags are checked too</param> /// <param name="checkSelections">If true, the method also checks /// equivalence for the selections</param> /// <returns></returns> bool IsEquivalentTo(Market market, bool checkTags, bool checkSelections); /// <summary> /// /// Allows to set force suspension state on a market. /// /// </summary> void SetForcedSuspensionState(bool isSuspended = true); } }
{ "content_hash": "9906f00a24e9f43ac114c334d702b839", "timestamp": "", "source": "github", "line_count": 281, "max_line_length": 98, "avg_line_length": 31.22064056939502, "alnum_prop": 0.5100877692921464, "repo_name": "jpendlebury/SS.Integration.Adapter", "id": "865c1351eca620ea43ed884fcd0457f9cf485fec", "size": "8775", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "SS.Integration.Adapter.Model/Interfaces/IMarketState.cs", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "C#", "bytes": "816538" }, { "name": "CSS", "bytes": "7085" }, { "name": "Cucumber", "bytes": "19881" }, { "name": "HTML", "bytes": "18332" }, { "name": "JavaScript", "bytes": "210040" } ], "symlink_target": "" }
using System; using System.Collections.Generic; using System.Linq; using System.Windows.Controls; using F2F.ReactiveNavigation.ViewModel; using System.Collections.Concurrent; namespace F2F.ReactiveNavigation.WPF { public class ContentRegionAdapter : RegionAdapter<ContentControl> { private readonly ICreateView _viewFactory; private readonly ConcurrentDictionary<ReactiveViewModel, object> _cachedViews = new ConcurrentDictionary<ReactiveViewModel, object>(); public ContentRegionAdapter(ContentControl regionTarget, ICreateView viewFactory) : base(regionTarget) { if (viewFactory == null) throw new ArgumentNullException("viewFactory", "viewFactory is null."); _viewFactory = viewFactory; } protected internal override void AddView(INavigableRegion region, ReactiveViewModel viewModel) { var view = _cachedViews.GetOrAdd(viewModel, _viewFactory.CreateViewFor(viewModel)); RegionTarget.Content = view; } protected internal override void RemoveView(INavigableRegion region, ReactiveViewModel viewModel) { RegionTarget.Content = null; object view; if (_cachedViews.TryRemove(viewModel, out view)) { var disposable = view as IDisposable; if (disposable != null) { disposable.Dispose(); } } } protected internal override void ActivateView(INavigableRegion region, ReactiveViewModel viewModel) { object view; if (_cachedViews.TryGetValue(viewModel, out view)) { RegionTarget.Content = view; } } protected internal override void DeactivateView(INavigableRegion region, ReactiveViewModel viewModel) { } protected internal override void InitializeView(INavigableRegion region, ReactiveViewModel viewModel) { } } }
{ "content_hash": "b12b566f54d3baaededc5d746d2e20e9", "timestamp": "", "source": "github", "line_count": 65, "max_line_length": 109, "avg_line_length": 32.09230769230769, "alnum_prop": 0.6313518696069031, "repo_name": "F-2-F/F2F.ReactiveNavigation", "id": "38066778b29ea1d801be57e43efd56176831a38d", "size": "2086", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "src/F2F.ReactiveNavigation.WPF/ContentRegionAdapter.cs", "mode": "33188", "license": "mit", "language": [ { "name": "Batchfile", "bytes": "293" }, { "name": "C#", "bytes": "234256" }, { "name": "F#", "bytes": "12840" }, { "name": "Shell", "bytes": "612" } ], "symlink_target": "" }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. package com.azure.aad.controller; import com.azure.aad.model.TodoItem; import com.microsoft.azure.spring.autoconfigure.aad.Constants; import com.microsoft.azure.spring.autoconfigure.aad.UserGroup; import com.microsoft.azure.spring.autoconfigure.aad.UserPrincipal; import org.springframework.http.HttpStatus; import org.springframework.http.MediaType; import org.springframework.http.ResponseEntity; import org.springframework.security.access.prepost.PreAuthorize; import org.springframework.security.web.authentication.preauth.PreAuthenticatedAuthenticationToken; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RestController; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.UUID; import java.util.stream.Collectors; @RestController public class TodoListController { private final List<TodoItem> todoList = new ArrayList<>(); public TodoListController() { todoList.add(0, new TodoItem(2398, "anything", "whoever")); } @RequestMapping("/home") public Map<String, Object> home() { final Map<String, Object> model = new HashMap<>(); model.put("id", UUID.randomUUID().toString()); model.put("content", "home"); return model; } /** * HTTP GET */ @RequestMapping(value = "/api/todolist/{index}", method = RequestMethod.GET, produces = {MediaType.APPLICATION_JSON_VALUE}) public ResponseEntity<?> getTodoItem(@PathVariable("index") int index) { if (index > todoList.size() - 1) { return new ResponseEntity<>(new TodoItem(-1, "index out of range", null), HttpStatus.NOT_FOUND); } return new ResponseEntity<>(todoList.get(index), HttpStatus.OK); } /** * HTTP GET ALL */ @RequestMapping(value = "/api/todolist", method = RequestMethod.GET, produces = {MediaType.APPLICATION_JSON_VALUE}) public ResponseEntity<List<TodoItem>> getAllTodoItems() { return new ResponseEntity<>(todoList, HttpStatus.OK); } @PreAuthorize("hasRole('ROLE_group1')") @RequestMapping(value = "/api/todolist", method = RequestMethod.POST, consumes = MediaType.APPLICATION_JSON_VALUE) public ResponseEntity<String> addNewTodoItem(@RequestBody TodoItem item) { item.setID(todoList.size() + 1); todoList.add(todoList.size(), item); return new ResponseEntity<>("Entity created", HttpStatus.CREATED); } /** * HTTP PUT */ @PreAuthorize("hasRole('ROLE_group1')") @RequestMapping(value = "/api/todolist", method = RequestMethod.PUT, consumes = MediaType.APPLICATION_JSON_VALUE) public ResponseEntity<String> updateTodoItem(@RequestBody TodoItem item) { final List<TodoItem> find = todoList.stream().filter(i -> i.getID() == item.getID()).collect(Collectors.toList()); if (!find.isEmpty()) { todoList.set(todoList.indexOf(find.get(0)), item); return new ResponseEntity<>("Entity is updated", HttpStatus.OK); } return new ResponseEntity<>("Entity not found", HttpStatus.OK); } /** * HTTP DELETE */ @RequestMapping(value = "/api/todolist/{id}", method = RequestMethod.DELETE) public ResponseEntity<String> deleteTodoItem(@PathVariable("id") int id, PreAuthenticatedAuthenticationToken authToken) { final UserPrincipal current = (UserPrincipal) authToken.getPrincipal(); UserGroup userGroup = new UserGroup( "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx", Constants.OBJECT_TYPE_GROUP, "group1"); if (current.isMemberOf(userGroup)) { return todoList.stream() .filter(i -> i.getID() == id) .findFirst() .map(item -> { todoList.remove(item); return new ResponseEntity<>("OK", HttpStatus.OK); }) .orElseGet(() -> new ResponseEntity<>("Entity not found", HttpStatus.OK)); } else { return new ResponseEntity<>("Access is denied", HttpStatus.OK); } } }
{ "content_hash": "4e56cf7c5c97bf63de9af66a6ac6490e", "timestamp": "", "source": "github", "line_count": 113, "max_line_length": 119, "avg_line_length": 40.8141592920354, "alnum_prop": 0.6509106678230703, "repo_name": "selvasingh/azure-sdk-for-java", "id": "4fa45a30bd26b01b5c67766532c6823b150c370b", "size": "4612", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "sdk/spring/azure-spring-boot-samples/azure-spring-boot-sample-active-directory/src/main/java/com/azure/aad/controller/TodoListController.java", "mode": "33188", "license": "mit", "language": [ { "name": "Java", "bytes": "29891970" }, { "name": "JavaScript", "bytes": "6198" }, { "name": "PowerShell", "bytes": "160" }, { "name": "Shell", "bytes": "609" } ], "symlink_target": "" }
"""Database setup and migration commands.""" from nova import utils IMPL = utils.LazyPluggable( 'baremetal_db_backend', sqlalchemy='nova.virt.baremetal.db.sqlalchemy.migration') INIT_VERSION = 0 def db_sync(version=None): """Migrate the database to `version` or the most recent version.""" return IMPL.db_sync(version=version) def db_version(): """Display the current database version.""" return IMPL.db_version()
{ "content_hash": "71f1eef4038a0520b445c13c645a2b32", "timestamp": "", "source": "github", "line_count": 20, "max_line_length": 71, "avg_line_length": 22.7, "alnum_prop": 0.6916299559471366, "repo_name": "houshengbo/nova_vmware_compute_driver", "id": "40631bf45c8218121b847352d19865a54773c20c", "size": "1231", "binary": false, "copies": "3", "ref": "refs/heads/attach-detach-VMware-iSCSI-driver", "path": "nova/virt/baremetal/db/migration.py", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "JavaScript", "bytes": "7403" }, { "name": "Python", "bytes": "7173520" }, { "name": "Shell", "bytes": "15478" } ], "symlink_target": "" }
<?php /** * produce debug information * * $HeadURL: https://www.onthegosystems.com/misc_svn/common/trunk/debug/functions_debug_information.php $ * $LastChangedDate: 2014-09-26 12:15:05 +0000 (Fri, 26 Sep 2014) $ * $LastChangedRevision: 27495 $ * $LastChangedBy: marcin $ * */ class ICL_Debug_Information { function __construct() { } function __destruct() { } function get_debug_info($info=array()) { if (!is_array($info)) { $info = explode(',', $info); } if (empty($info)) { $info = array('core', 'plugins', 'theme', 'extra-debug'); } $output = array(); foreach ($info as $type) { switch ($type) { case 'core': $output['core'] = $this->get_core_info(); break; case 'plugins': $output['plugins'] = $this->get_plugins_info(); break; case 'theme': $output['theme'] = $this->get_theme_info(); break; case 'extra-debug': $output['extra-debug'] = apply_filters('icl_get_extra_debug_info', array()); break; } } return $output; } function get_core_info() { global $wpdb; $core = array( 'Wordpress' => array( 'Multisite' => is_multisite() ? 'Yes' : 'No', 'SiteURL' => site_url(), 'HomeURL' => home_url(), 'Version' => get_bloginfo( 'version' ), 'PermalinkStructure' => get_option( 'permalink_structure' ), 'PostTypes' => implode( ', ', get_post_types( '', 'names' ) ), 'PostSatus' => implode( ', ', get_post_stati() ) ), 'Server' => array( 'jQueryVersion' => wp_script_is( 'jquery', 'registered' ) ? $GLOBALS['wp_scripts']->registered['jquery']->ver : __( 'n/a', 'wpv-views' ), 'PHPVersion' => phpversion(), 'MySQLVersion' => $wpdb->db_version(), 'ServerSoftware' => $_SERVER['SERVER_SOFTWARE'] ), 'PHP' => array( 'MemoryLimit' => ini_get( 'memory_limit' ), 'UploadMax' => ini_get( 'upload_max_filesize' ), 'PostMax' => ini_get( 'post_max_size' ), 'TimeLimit' => ini_get( 'max_execution_time' ), 'MaxInputVars' => ini_get( 'max_input_vars' ), ), ); return $core; } function get_plugins_info() { if ( ! function_exists( 'get_plugins' ) ) { $admin_includes_path = str_replace( site_url('/', 'admin'), ABSPATH, admin_url('includes/', 'admin') ); require_once $admin_includes_path . 'plugin.php'; } $plugins = get_plugins(); $active_plugins = get_option('active_plugins'); $active_plugins_info = array(); foreach ($active_plugins as $plugin) { if (isset($plugins[$plugin])) { unset($plugins[$plugin]['Description']); $active_plugins_info[$plugin] = $plugins[$plugin]; } } $mu_plugins = get_mu_plugins(); $dropins = get_dropins(); $output =array( 'active_plugins' => $active_plugins_info, 'mu_plugins' => $mu_plugins, 'dropins' => $dropins, ); return $output; } function get_theme_info() { if ( get_bloginfo( 'version' ) < '3.4' ) { $current_theme = get_theme_data( get_stylesheet_directory() . '/style.css' ); $theme = $current_theme; unset($theme['Description']); unset($theme['Satus']); unset($theme['Tags']); } else { $current_theme = wp_get_theme(); $theme = array( 'Name' => $current_theme->Name, 'ThemeURI' => $current_theme->ThemeURI, 'Author' => $current_theme->Author, 'AuthorURI' => $current_theme->AuthorURI, 'Template' => $current_theme->Template, 'Version' => $current_theme->Version, 'TextDomain' => $current_theme->TextDomain, 'DomainPath' => $current_theme->DomainPath, ); } return $theme; } function do_json_encode($data) { if (version_compare(phpversion(), '5.3.0', '<')) { return json_encode($data); } $json_options = 0; if (defined('JSON_HEX_TAG')) { $json_options += JSON_HEX_TAG; } if (defined('JSON_HEX_APOS')) { $json_options += JSON_HEX_APOS; } if (defined('JSON_HEX_QUOT')) { $json_options += JSON_HEX_QUOT; } if (defined('JSON_HEX_AMP')) { $json_options += JSON_HEX_AMP; } if (defined('JSON_UNESCAPED_UNICODE')) { $json_options += JSON_UNESCAPED_UNICODE; } return json_encode($data, $json_options); } }
{ "content_hash": "b0c5a93054ec422dbca524d37566f54f", "timestamp": "", "source": "github", "line_count": 159, "max_line_length": 141, "avg_line_length": 27.9748427672956, "alnum_prop": 0.54181654676259, "repo_name": "doudou2012/tdshipu", "id": "fc157199909bb1e3345e072c7665bb1f2c54d6dc", "size": "4448", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "wp-content/plugins/cred-frontend-editor/icl-common/debug/functions_debug_information.php", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "2022352" }, { "name": "JavaScript", "bytes": "4848883" }, { "name": "LiveScript", "bytes": "6103" }, { "name": "PHP", "bytes": "15633097" }, { "name": "Shell", "bytes": "291" } ], "symlink_target": "" }
\documentclass[twoside]{book} % Packages required by doxygen \usepackage{fixltx2e} \usepackage{calc} \usepackage{doxygen} \usepackage[export]{adjustbox} % also loads graphicx \usepackage{graphicx} \usepackage[utf8]{inputenc} \usepackage{makeidx} \usepackage{multicol} \usepackage{multirow} \PassOptionsToPackage{warn}{textcomp} \usepackage{textcomp} \usepackage[nointegrals]{wasysym} \usepackage[table]{xcolor} % Font selection \usepackage[T1]{fontenc} \usepackage[scaled=.90]{helvet} \usepackage{courier} \usepackage{amssymb} \usepackage{sectsty} \renewcommand{\familydefault}{\sfdefault} \allsectionsfont{% \fontseries{bc}\selectfont% \color{darkgray}% } \renewcommand{\DoxyLabelFont}{% \fontseries{bc}\selectfont% \color{darkgray}% } \newcommand{\+}{\discretionary{\mbox{\scriptsize$\hookleftarrow$}}{}{}} % Page & text layout \usepackage{geometry} \geometry{% a4paper,% top=2.5cm,% bottom=2.5cm,% left=2.5cm,% right=2.5cm% } \tolerance=750 \hfuzz=15pt \hbadness=750 \setlength{\emergencystretch}{15pt} \setlength{\parindent}{0cm} \setlength{\parskip}{3ex plus 2ex minus 2ex} \makeatletter \renewcommand{\paragraph}{% \@startsection{paragraph}{4}{0ex}{-1.0ex}{1.0ex}{% \normalfont\normalsize\bfseries\SS@parafont% }% } \renewcommand{\subparagraph}{% \@startsection{subparagraph}{5}{0ex}{-1.0ex}{1.0ex}{% \normalfont\normalsize\bfseries\SS@subparafont% }% } \makeatother % Headers & footers \usepackage{fancyhdr} \pagestyle{fancyplain} \fancyhead[LE]{\fancyplain{}{\bfseries\thepage}} \fancyhead[CE]{\fancyplain{}{}} \fancyhead[RE]{\fancyplain{}{\bfseries\leftmark}} \fancyhead[LO]{\fancyplain{}{\bfseries\rightmark}} \fancyhead[CO]{\fancyplain{}{}} \fancyhead[RO]{\fancyplain{}{\bfseries\thepage}} \fancyfoot[LE]{\fancyplain{}{}} \fancyfoot[CE]{\fancyplain{}{}} \fancyfoot[RE]{\fancyplain{}{\bfseries\scriptsize Generated by Doxygen }} \fancyfoot[LO]{\fancyplain{}{\bfseries\scriptsize Generated by Doxygen }} \fancyfoot[CO]{\fancyplain{}{}} \fancyfoot[RO]{\fancyplain{}{}} \renewcommand{\footrulewidth}{0.4pt} \renewcommand{\chaptermark}[1]{% \markboth{#1}{}% } \renewcommand{\sectionmark}[1]{% \markright{\thesection\ #1}% } % Indices & bibliography \usepackage{natbib} \usepackage[titles]{tocloft} \setcounter{tocdepth}{3} \setcounter{secnumdepth}{5} \makeindex % Hyperlinks (required, but should be loaded last) \usepackage{ifpdf} \ifpdf \usepackage[pdftex,pagebackref=true]{hyperref} \else \usepackage[ps2pdf,pagebackref=true]{hyperref} \fi \hypersetup{% colorlinks=true,% linkcolor=blue,% citecolor=blue,% unicode% } % Custom commands \newcommand{\clearemptydoublepage}{% \newpage{\pagestyle{empty}\cleardoublepage}% } \usepackage{caption} \captionsetup{labelsep=space,justification=centering,font={bf},singlelinecheck=off,skip=4pt,position=top} %===== C O N T E N T S ===== \begin{document} % Titlepage & ToC \hypersetup{pageanchor=false, bookmarksnumbered=true, pdfencoding=unicode } \pagenumbering{roman} \begin{titlepage} \vspace*{7cm} \begin{center}% {\Large My Project }\\ \vspace*{1cm} {\large Generated by Doxygen 1.8.11}\\ \end{center} \end{titlepage} \clearemptydoublepage \tableofcontents \clearemptydoublepage \pagenumbering{arabic} \hypersetup{pageanchor=true} %--- Begin generated contents --- \chapter{File Index} \input{files} \chapter{File Documentation} \input{main_8cpp} %--- End generated contents --- % Index \backmatter \newpage \phantomsection \clearemptydoublepage \addcontentsline{toc}{chapter}{Index} \printindex \end{document}
{ "content_hash": "47ba9b3c98f184494f913da9fc8245f4", "timestamp": "", "source": "github", "line_count": 154, "max_line_length": 105, "avg_line_length": 23.162337662337663, "alnum_prop": 0.7328287075974208, "repo_name": "Akshaybj0221/ENPM808X_Midterm", "id": "611746a053db070165ed62430474057ccb53c827", "size": "3567", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "docs/app folder/latex/refman.tex", "mode": "33188", "license": "mit", "language": [ { "name": "C", "bytes": "17745" }, { "name": "C++", "bytes": "61129" }, { "name": "CMake", "bytes": "32671" }, { "name": "HTML", "bytes": "8860" }, { "name": "Makefile", "bytes": "45543" }, { "name": "Python", "bytes": "5095" } ], "symlink_target": "" }
class Gem::Commands::AutoCompileCommand < Gem::Command include Gem::UserInteraction def initialize super 'auto_compile', 'Enable gem compilation at install time' end def description # :nodoc: 'Toggle a setting that enables compiling gems at install time.' end def usage "#{progname}" end def execute Gem.configuration[:compile] = if Gem.configuration[:compile] say 'Disabling automatic compilation' false else say 'Enabling automatic compilation' true end Gem.configuration.write end end
{ "content_hash": "d50d80fbe1fc77f41fc87a4251593e5b", "timestamp": "", "source": "github", "line_count": 27, "max_line_length": 73, "avg_line_length": 27.51851851851852, "alnum_prop": 0.5248990578734859, "repo_name": "ferrous26/rubygems-compile", "id": "cd8a2df7076ef66daf31f1b6f2af5a12f933f013", "size": "743", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "lib/rubygems-compile/commands/autocompile_command.rb", "mode": "33188", "license": "mit", "language": [ { "name": "Ruby", "bytes": "13868" } ], "symlink_target": "" }
namespace slave = mesos::internal::slave; using process::Future; using process::Owned; using std::string; using std::vector; using mesos::internal::master::Master; using mesos::internal::slave::DockerRuntimeIsolatorProcess; using mesos::internal::slave::DockerVolumeIsolatorProcess; using mesos::internal::slave::Fetcher; using mesos::internal::slave::Launcher; using mesos::internal::slave::LinuxFilesystemIsolatorProcess; using mesos::internal::slave::LinuxLauncher; using mesos::internal::slave::MesosContainerizer; using mesos::internal::slave::MesosContainerizerProcess; using mesos::internal::slave::Provisioner; using mesos::internal::slave::Slave; using mesos::master::detector::MasterDetector; using mesos::slave::Isolator; using slave::docker::volume::DriverClient; using testing::DoAll; namespace mesos { namespace internal { namespace tests { class MockDockerVolumeDriverClient : public DriverClient { public: MockDockerVolumeDriverClient() {} virtual ~MockDockerVolumeDriverClient() {} MOCK_METHOD3( mount, Future<string>( const string& driver, const string& name, const hashmap<string, string>& options)); MOCK_METHOD2( unmount, Future<Nothing>( const string& driver, const string& name)); }; class DockerVolumeIsolatorTest : public MesosTest { protected: virtual void TearDown() { // Try to remove any mounts under sandbox. if (::geteuid() == 0) { Try<Nothing> unmountAll = fs::unmountAll(sandbox.get(), MNT_DETACH); if (unmountAll.isError()) { LOG(ERROR) << "Failed to unmount '" << sandbox.get() << "': " << unmountAll.error(); return; } } MesosTest::TearDown(); } Volume createDockerVolume( const string& driver, const string& name, const string& containerPath, const Option<hashmap<string, string>>& options = None()) { Volume volume; volume.set_mode(Volume::RW); volume.set_container_path(containerPath); Volume::Source* source = volume.mutable_source(); source->set_type(Volume::Source::DOCKER_VOLUME); Volume::Source::DockerVolume* docker = source->mutable_docker_volume(); docker->set_driver(driver); docker->set_name(name); Parameters parameters; if (options.isSome()) { foreachpair (const string& key, const string& value, options.get()) { Parameter* parameter = parameters.add_parameter(); parameter->set_key(key); parameter->set_value(value); } docker->mutable_driver_options()->CopyFrom(parameters); } return volume; } // This helper creates a MesosContainerizer instance that uses the // LinuxFilesystemIsolator and DockerVolumeIsolator. Try<Owned<MesosContainerizer>> createContainerizer( const slave::Flags& flags, const Owned<DriverClient>& mockClient) { fetcher.reset(new Fetcher(flags)); Try<Isolator*> linuxIsolator_ = LinuxFilesystemIsolatorProcess::create(flags); if (linuxIsolator_.isError()) { return Error( "Failed to create LinuxFilesystemIsolator: " + linuxIsolator_.error()); } Owned<Isolator> linuxIsolator(linuxIsolator_.get()); Try<Isolator*> runtimeIsolator_ = DockerRuntimeIsolatorProcess::create(flags); if (runtimeIsolator_.isError()) { return Error( "Failed to create DockerRuntimeIsolator: " + runtimeIsolator_.error()); } Owned<Isolator> runtimeIsolator(runtimeIsolator_.get()); Try<Isolator*> volumeIsolator_ = DockerVolumeIsolatorProcess::_create(flags, mockClient); if (volumeIsolator_.isError()) { return Error( "Failed to create DockerVolumeIsolator: " + volumeIsolator_.error()); } Owned<Isolator> volumeIsolator(volumeIsolator_.get()); Try<Launcher*> launcher_ = LinuxLauncher::create(flags); if (launcher_.isError()) { return Error("Failed to create LinuxLauncher: " + launcher_.error()); } Owned<Launcher> launcher(launcher_.get()); Try<Owned<Provisioner>> provisioner = Provisioner::create(flags); if (provisioner.isError()) { return Error("Failed to create provisioner: " + provisioner.error()); } Try<MesosContainerizer*> containerizer = MesosContainerizer::create( flags, true, fetcher.get(), std::move(launcher), provisioner->share(), {std::move(linuxIsolator), std::move(runtimeIsolator), std::move(volumeIsolator)}); if (containerizer.isError()) { return Error("Failed to create containerizer: " + containerizer.error()); } return Owned<MesosContainerizer>(containerizer.get()); } private: Owned<Fetcher> fetcher; }; // This test verifies that multiple docker volumes with both absolute // path and relative path are properly mounted to a container without // rootfs, and launches a command task that reads files from the // mounted docker volumes. TEST_F(DockerVolumeIsolatorTest, ROOT_CommandTaskNoRootfsWithVolumes) { Try<Owned<cluster::Master>> master = StartMaster(); ASSERT_SOME(master); slave::Flags flags = CreateSlaveFlags(); MockDockerVolumeDriverClient* mockClient = new MockDockerVolumeDriverClient; Try<Owned<MesosContainerizer>> containerizer = createContainerizer(flags, Owned<DriverClient>(mockClient)); ASSERT_SOME(containerizer); Owned<MasterDetector> detector = master.get()->createDetector(); Try<Owned<cluster::Slave>> slave = StartSlave( detector.get(), containerizer->get(), flags); ASSERT_SOME(slave); MockScheduler sched; MesosSchedulerDriver driver( &sched, DEFAULT_FRAMEWORK_INFO, master.get()->pid, DEFAULT_CREDENTIAL); Future<FrameworkID> frameworkId; EXPECT_CALL(sched, registered(&driver, _, _)) .WillOnce(FutureArg<1>(&frameworkId)); Future<vector<Offer>> offers; EXPECT_CALL(sched, resourceOffers(&driver, _)) .WillOnce(FutureArg<1>(&offers)) .WillRepeatedly(Return()); // Ignore subsequent offers. driver.start(); AWAIT_READY(frameworkId); AWAIT_READY(offers); ASSERT_FALSE(offers->empty()); const Offer& offer = offers.get()[0]; const string key = "iops"; const string value = "150"; hashmap<string, string> options = {{key, value}}; // Create a volume with relative path. const string driver1 = "driver1"; const string name1 = "name1"; const string containerPath1 = "tmp/foo1"; Volume volume1 = createDockerVolume(driver1, name1, containerPath1, options); // Create a volume with absolute path. const string driver2 = "driver2"; const string name2 = "name2"; // Make sure the absolute path exist. const string containerPath2 = path::join(os::getcwd(), "foo2"); ASSERT_SOME(os::mkdir(containerPath2)); Volume volume2 = createDockerVolume(driver2, name2, containerPath2); TaskInfo task = createTask( offer.slave_id(), offer.resources(), "test -f " + containerPath1 + "/file1 && " "test -f " + containerPath2 + "/file2;"); ContainerInfo containerInfo; containerInfo.set_type(ContainerInfo::MESOS); containerInfo.add_volumes()->CopyFrom(volume1); containerInfo.add_volumes()->CopyFrom(volume2); task.mutable_container()->CopyFrom(containerInfo); // Create mount point for volume1. const string mountPoint1 = path::join(os::getcwd(), "volume1"); ASSERT_SOME(os::mkdir(mountPoint1)); ASSERT_SOME(os::touch(path::join(mountPoint1, "file1"))); // Create mount point for volume2. const string mountPoint2 = path::join(os::getcwd(), "volume2"); ASSERT_SOME(os::mkdir(mountPoint2)); ASSERT_SOME(os::touch(path::join(mountPoint2, "file2"))); Future<string> mount1Name; Future<string> mount2Name; Future<hashmap<string, string>> mount1Options; EXPECT_CALL(*mockClient, mount(driver1, _, _)) .WillOnce(DoAll(FutureArg<1>(&mount1Name), FutureArg<2>(&mount1Options), Return(mountPoint1))); EXPECT_CALL(*mockClient, mount(driver2, _, _)) .WillOnce(DoAll(FutureArg<1>(&mount2Name), Return(mountPoint2))); Future<string> unmount1Name; Future<string> unmount2Name; EXPECT_CALL(*mockClient, unmount(driver1, _)) .WillOnce(DoAll(FutureArg<1>(&unmount1Name), Return(Nothing()))); EXPECT_CALL(*mockClient, unmount(driver2, _)) .WillOnce(DoAll(FutureArg<1>(&unmount2Name), Return(Nothing()))); Future<TaskStatus> statusStarting; Future<TaskStatus> statusRunning; Future<TaskStatus> statusFinished; EXPECT_CALL(sched, statusUpdate(&driver, _)) .WillOnce(FutureArg<1>(&statusStarting)) .WillOnce(FutureArg<1>(&statusRunning)) .WillOnce(FutureArg<1>(&statusFinished)); driver.launchTasks(offer.id(), {task}); AWAIT_READY(statusStarting); EXPECT_EQ(TASK_STARTING, statusStarting->state()); AWAIT_READY(statusRunning); EXPECT_EQ(TASK_RUNNING, statusRunning->state()); // Make sure the docker volume mount parameters are same with the // parameters in `containerInfo`. AWAIT_EXPECT_EQ(name1, mount1Name); AWAIT_EXPECT_EQ(name2, mount2Name); AWAIT_READY(mount1Options); EXPECT_SOME_EQ(value, mount1Options->get(key)); AWAIT_READY(statusFinished); EXPECT_EQ(TASK_FINISHED, statusFinished->state()); // Make sure the docker volume unmount parameters are same with // the parameters in `containerInfo`. AWAIT_EXPECT_EQ(name1, unmount1Name); AWAIT_EXPECT_EQ(name2, unmount2Name); driver.stop(); driver.join(); } // This test verifies that multiple docker volumes with the same // driver and name cannot be mounted to the same container. If that // happens, the task will fail. TEST_F(DockerVolumeIsolatorTest, ROOT_CommandTaskNoRootfsFailedWithSameVolumes) { Try<Owned<cluster::Master>> master = StartMaster(); ASSERT_SOME(master); slave::Flags flags = CreateSlaveFlags(); MockDockerVolumeDriverClient* mockClient = new MockDockerVolumeDriverClient; Try<Owned<MesosContainerizer>> containerizer = createContainerizer(flags, Owned<DriverClient>(mockClient)); ASSERT_SOME(containerizer); Owned<MasterDetector> detector = master.get()->createDetector(); Try<Owned<cluster::Slave>> slave = StartSlave( detector.get(), containerizer->get(), flags); ASSERT_SOME(slave); MockScheduler sched; MesosSchedulerDriver driver( &sched, DEFAULT_FRAMEWORK_INFO, master.get()->pid, DEFAULT_CREDENTIAL); Future<FrameworkID> frameworkId; EXPECT_CALL(sched, registered(&driver, _, _)) .WillOnce(FutureArg<1>(&frameworkId)); Future<vector<Offer>> offers; EXPECT_CALL(sched, resourceOffers(&driver, _)) .WillOnce(FutureArg<1>(&offers)) .WillRepeatedly(Return()); // Ignore subsequent offers. driver.start(); AWAIT_READY(frameworkId); AWAIT_READY(offers); ASSERT_FALSE(offers->empty()); const Offer& offer = offers.get()[0]; const string key = "iops"; const string value = "150"; hashmap<string, string> options = {{key, value}}; // Create a volume with relative path. const string driver1 = "driver1"; const string name1 = "name1"; const string containerPath1 = "tmp/foo1"; Volume volume1 = createDockerVolume(driver1, name1, containerPath1, options); // Create a volume with absolute path and make sure the absolute // path exist. Please note that volume1 and volume2 will be created // with same volume driver and name, this will cause task failed // when mounting same mount point to one container. const string containerPath2 = path::join(os::getcwd(), "foo2"); ASSERT_SOME(os::mkdir(containerPath2)); Volume volume2 = createDockerVolume(driver1, name1, containerPath2); TaskInfo task = createTask( offer.slave_id(), offer.resources(), "test -f " + containerPath1 + "/file1 && " "test -f " + containerPath2 + "/file2;"); ContainerInfo containerInfo; containerInfo.set_type(ContainerInfo::MESOS); containerInfo.add_volumes()->CopyFrom(volume1); containerInfo.add_volumes()->CopyFrom(volume2); task.mutable_container()->CopyFrom(containerInfo); Future<TaskStatus> statusFailed; EXPECT_CALL(sched, statusUpdate(&driver, _)) .WillOnce(FutureArg<1>(&statusFailed)); driver.launchTasks(offer.id(), {task}); AWAIT_READY(statusFailed); EXPECT_EQ(task.task_id(), statusFailed->task_id()); EXPECT_EQ(TASK_FAILED, statusFailed->state()); driver.stop(); driver.join(); } // This test verifies that the docker volumes are properly recovered // during slave recovery. TEST_F(DockerVolumeIsolatorTest, ROOT_CommandTaskNoRootfsSlaveRecovery) { Try<Owned<cluster::Master>> master = StartMaster(); ASSERT_SOME(master); slave::Flags flags = CreateSlaveFlags(); MockDockerVolumeDriverClient* mockClient = new MockDockerVolumeDriverClient; Try<Owned<MesosContainerizer>> containerizer = createContainerizer(flags, Owned<DriverClient>(mockClient)); ASSERT_SOME(containerizer); Owned<MasterDetector> detector = master.get()->createDetector(); Try<Owned<cluster::Slave>> slave = StartSlave( detector.get(), containerizer->get(), flags); ASSERT_SOME(slave); // Enable checkpointing for the framework. FrameworkInfo frameworkInfo = DEFAULT_FRAMEWORK_INFO; frameworkInfo.set_checkpoint(true); MockScheduler sched; MesosSchedulerDriver driver( &sched, frameworkInfo, master.get()->pid, DEFAULT_CREDENTIAL); Future<FrameworkID> frameworkId; EXPECT_CALL(sched, registered(&driver, _, _)) .WillOnce(FutureArg<1>(&frameworkId)); Future<vector<Offer>> offers; EXPECT_CALL(sched, resourceOffers(&driver, _)) .WillOnce(FutureArg<1>(&offers)) .WillRepeatedly(Return()); // Ignore subsequent offers. driver.start(); AWAIT_READY(frameworkId); AWAIT_READY(offers); ASSERT_FALSE(offers->empty()); const Offer& offer = offers.get()[0]; const string key = "iops"; const string value = "150"; hashmap<string, string> options = {{key, value}}; // Create a volume with relative path. const string driver1 = "driver1"; const string name1 = "name1"; const string containerPath1 = "tmp/foo1"; Volume volume1 = createDockerVolume(driver1, name1, containerPath1, options); // Create a volume with absolute path. const string driver2 = "driver2"; const string name2 = "name2"; // Make sure the absolute path exist. const string containerPath2 = path::join(os::getcwd(), "foo2"); ASSERT_SOME(os::mkdir(containerPath2)); Volume volume2 = createDockerVolume(driver2, name2, containerPath2); TaskInfo task = createTask( offer.slave_id(), offer.resources(), "while true; do test -f " + containerPath1 + "/file1 && " "test -f " + containerPath2 + "/file2; done"); ContainerInfo containerInfo; containerInfo.set_type(ContainerInfo::MESOS); containerInfo.add_volumes()->CopyFrom(volume1); containerInfo.add_volumes()->CopyFrom(volume2); task.mutable_container()->CopyFrom(containerInfo); // Create mount point for volume1. const string mountPoint1 = path::join(os::getcwd(), "volume1"); ASSERT_SOME(os::mkdir(mountPoint1)); ASSERT_SOME(os::touch(path::join(mountPoint1, "file1"))); // Create mount point for volume2. const string mountPoint2 = path::join(os::getcwd(), "volume2"); ASSERT_SOME(os::mkdir(mountPoint2)); ASSERT_SOME(os::touch(path::join(mountPoint2, "file2"))); Future<string> mount1Name; Future<string> mount2Name; Future<hashmap<string, string>> mount1Options; EXPECT_CALL(*mockClient, mount(driver1, _, _)) .WillOnce(DoAll(FutureArg<1>(&mount1Name), FutureArg<2>(&mount1Options), Return(mountPoint1))); EXPECT_CALL(*mockClient, mount(driver2, _, _)) .WillOnce(DoAll(FutureArg<1>(&mount2Name), Return(mountPoint2))); Future<TaskStatus> statusStarting; Future<TaskStatus> statusRunning; EXPECT_CALL(sched, statusUpdate(&driver, _)) .WillOnce(FutureArg<1>(&statusStarting)) .WillOnce(FutureArg<1>(&statusRunning)); Future<Nothing> ack1 = FUTURE_DISPATCH(_, &Slave::_statusUpdateAcknowledgement); Future<Nothing> ack2 = FUTURE_DISPATCH(_, &Slave::_statusUpdateAcknowledgement); driver.launchTasks(offer.id(), {task}); AWAIT_READY(statusStarting); EXPECT_EQ(TASK_STARTING, statusStarting->state()); // Wait for the ACK to be checkpointed. AWAIT_READY(ack1); AWAIT_READY(statusRunning); EXPECT_EQ(TASK_RUNNING, statusRunning->state()); // Wait for the ACK to be checkpointed. AWAIT_READY(ack2); // Stop the slave after TASK_RUNNING is received. slave.get()->terminate(); // Set up so we can wait until the new slave updates the container's // resources (this occurs after the executor has reregistered). Future<Nothing> update = FUTURE_DISPATCH(_, &MesosContainerizerProcess::update); mockClient = new MockDockerVolumeDriverClient; containerizer = createContainerizer( flags, Owned<DriverClient>(mockClient)); ASSERT_SOME(containerizer); Future<SlaveReregisteredMessage> reregistered = FUTURE_PROTOBUF(SlaveReregisteredMessage(), master.get()->pid, _); Future<string> unmount1Name; Future<string> unmount2Name; EXPECT_CALL(*mockClient, unmount(driver1, _)) .WillOnce(DoAll(FutureArg<1>(&unmount1Name), Return(Nothing()))); EXPECT_CALL(*mockClient, unmount(driver2, _)) .WillOnce(DoAll(FutureArg<1>(&unmount2Name), Return(Nothing()))); // Use the same flags. slave = StartSlave(detector.get(), containerizer->get(), flags); ASSERT_SOME(slave); AWAIT_READY(reregistered); // Wait until the containerizer is updated. AWAIT_READY(update); Future<hashset<ContainerID>> containers = containerizer.get()->containers(); AWAIT_READY(containers); ASSERT_EQ(1u, containers->size()); ContainerID containerId = *(containers->begin()); Future<TaskStatus> statusKilled; EXPECT_CALL(sched, statusUpdate(&driver, _)) .WillOnce(FutureArg<1>(&statusKilled)); // Kill the task. driver.killTask(task.task_id()); AWAIT_READY(statusKilled); EXPECT_EQ(TASK_KILLED, statusKilled->state()); // Make sure the docker volume unmount parameters are same with // the parameters in `containerInfo`. AWAIT_EXPECT_EQ(name1, unmount1Name); AWAIT_EXPECT_EQ(name2, unmount2Name); driver.stop(); driver.join(); } // This test verifies that a single docker volumes can be used by // multiple containers, and the docker volume isolator will mount // the single volume to multiple containers when running tasks and // the docker volume isolator will call unmount only once when cleanup // the last container that is using the volume. TEST_F(DockerVolumeIsolatorTest, ROOT_CommandTaskNoRootfsSingleVolumeMultipleContainers) { Try<Owned<cluster::Master>> master = StartMaster(); ASSERT_SOME(master); slave::Flags flags = CreateSlaveFlags(); MockDockerVolumeDriverClient* mockClient = new MockDockerVolumeDriverClient; Try<Owned<MesosContainerizer>> containerizer = createContainerizer(flags, Owned<DriverClient>(mockClient)); ASSERT_SOME(containerizer); Owned<MasterDetector> detector = master.get()->createDetector(); Try<Owned<cluster::Slave>> slave = StartSlave( detector.get(), containerizer->get(), flags); ASSERT_SOME(slave); MockScheduler sched; MesosSchedulerDriver driver( &sched, DEFAULT_FRAMEWORK_INFO, master.get()->pid, DEFAULT_CREDENTIAL); Future<FrameworkID> frameworkId; EXPECT_CALL(sched, registered(&driver, _, _)) .WillOnce(FutureArg<1>(&frameworkId)); Future<vector<Offer>> offers; EXPECT_CALL(sched, resourceOffers(&driver, _)) .WillOnce(FutureArg<1>(&offers)) .WillRepeatedly(Return()); // Ignore subsequent offers. driver.start(); AWAIT_READY(frameworkId); AWAIT_READY(offers); ASSERT_FALSE(offers->empty()); const Offer& offer = offers.get()[0]; // Create a volume with relative path and share the volume with // two different containers. const string driver1 = "driver1"; const string name1 = "name1"; const string containerPath1 = "tmp/foo"; Volume volume1 = createDockerVolume(driver1, name1, containerPath1); TaskInfo task1 = createTask( offer.slave_id(), Resources::parse("cpus:1;mem:64").get(), "while true; do test -f " + containerPath1 + "/file; done"); ContainerInfo containerInfo1; containerInfo1.set_type(ContainerInfo::MESOS); containerInfo1.add_volumes()->CopyFrom(volume1); task1.mutable_container()->CopyFrom(containerInfo1); // Create mount point for volume. const string mountPoint1 = path::join(os::getcwd(), "volume"); ASSERT_SOME(os::mkdir(mountPoint1)); ASSERT_SOME(os::touch(path::join(mountPoint1, "file"))); TaskInfo task2 = createTask( offer.slave_id(), Resources::parse("cpus:1;mem:64").get(), "while true; do test -f " + containerPath1 + "/file; done"); ContainerInfo containerInfo2; containerInfo2.set_type(ContainerInfo::MESOS); containerInfo2.add_volumes()->CopyFrom(volume1); task2.mutable_container()->CopyFrom(containerInfo2); // The mount operation will be called multiple times as there are // two containers using the same volume. EXPECT_CALL(*mockClient, mount(driver1, _, _)) .WillRepeatedly(Return(mountPoint1)); // Expect the unmount was called only once because two containers // sharing one volume. EXPECT_CALL(*mockClient, unmount(driver1, _)) .WillOnce(Return(Nothing())); Future<TaskStatus> statusStarting1; Future<TaskStatus> statusRunning1; Future<TaskStatus> statusKilled1; Future<TaskStatus> statusStarting2; Future<TaskStatus> statusRunning2; Future<TaskStatus> statusKilled2; EXPECT_CALL(sched, statusUpdate(&driver, _)) .WillOnce(FutureArg<1>(&statusStarting1)) .WillOnce(FutureArg<1>(&statusStarting2)) .WillOnce(FutureArg<1>(&statusRunning1)) .WillOnce(FutureArg<1>(&statusRunning2)) .WillOnce(FutureArg<1>(&statusKilled1)) .WillOnce(FutureArg<1>(&statusKilled2)); driver.launchTasks(offer.id(), {task1, task2}); // TASK_STARTING and TASK_RUNNING updates might arrive interleaved, // so we only check the first and the last where the values are known. AWAIT_READY(statusStarting1); EXPECT_EQ(TASK_STARTING, statusStarting1->state()); AWAIT_READY(statusRunning2); EXPECT_EQ(TASK_RUNNING, statusRunning2->state()); // Kill both of the tasks. driver.killTask(task1.task_id()); driver.killTask(task2.task_id()); AWAIT_READY(statusKilled1); EXPECT_EQ(TASK_KILLED, statusKilled1->state()); AWAIT_READY(statusKilled2); EXPECT_EQ(TASK_KILLED, statusKilled2->state()); driver.stop(); driver.join(); } // This test verifies that a docker volume with absolute path can // be properly mounted to a container with rootfs, and launches a // command task that reads files from the mounted docker volume. TEST_F(DockerVolumeIsolatorTest, ROOT_INTERNET_CURL_CommandTaskRootfsWithAbsolutePathVolume) { Try<Owned<cluster::Master>> master = StartMaster(); ASSERT_SOME(master); slave::Flags flags = CreateSlaveFlags(); flags.isolation = "docker/volume,docker/runtime,filesystem/linux"; flags.image_providers = "docker"; MockDockerVolumeDriverClient* mockClient = new MockDockerVolumeDriverClient; Try<Owned<MesosContainerizer>> containerizer = createContainerizer(flags, Owned<DriverClient>(mockClient)); ASSERT_SOME(containerizer); Owned<MasterDetector> detector = master.get()->createDetector(); Try<Owned<cluster::Slave>> slave = StartSlave( detector.get(), containerizer->get(), flags); ASSERT_SOME(slave); MockScheduler sched; MesosSchedulerDriver driver( &sched, DEFAULT_FRAMEWORK_INFO, master.get()->pid, DEFAULT_CREDENTIAL); Future<FrameworkID> frameworkId; EXPECT_CALL(sched, registered(&driver, _, _)) .WillOnce(FutureArg<1>(&frameworkId)); Future<vector<Offer>> offers; EXPECT_CALL(sched, resourceOffers(&driver, _)) .WillOnce(FutureArg<1>(&offers)) .WillRepeatedly(Return()); // Ignore subsequent offers. driver.start(); AWAIT_READY(frameworkId); AWAIT_READY(offers); ASSERT_FALSE(offers->empty()); const Offer& offer = offers.get()[0]; // Create a volume with absolute path. const string volumeDriver = "driver"; const string name = "name"; const string containerPath = path::join(os::getcwd(), "foo"); Volume volume = createDockerVolume(volumeDriver, name, containerPath); // NOTE: We use a non-shell command here because 'sh' might not be // in the PATH. 'alpine' does not specify env PATH in the image. On // some linux distribution, '/bin' is not in the PATH by default. CommandInfo command; command.set_shell(false); command.set_value("/usr/bin/test"); command.add_arguments("test"); command.add_arguments("-f"); command.add_arguments(containerPath + "/file"); TaskInfo task = createTask( offer.slave_id(), offer.resources(), command); Image image; image.set_type(Image::DOCKER); image.mutable_docker()->set_name("alpine"); ContainerInfo containerInfo; containerInfo.set_type(ContainerInfo::MESOS); containerInfo.add_volumes()->CopyFrom(volume); containerInfo.mutable_mesos()->mutable_image()->CopyFrom(image); task.mutable_container()->CopyFrom(containerInfo); // Create mount point for volume. const string mountPoint = path::join(os::getcwd(), "volume"); ASSERT_SOME(os::mkdir(mountPoint)); ASSERT_SOME(os::touch(path::join(mountPoint, "file"))); Future<string> mountName; EXPECT_CALL(*mockClient, mount(volumeDriver, _, _)) .WillOnce(DoAll(FutureArg<1>(&mountName), Return(mountPoint))); Future<string> unmountName; EXPECT_CALL(*mockClient, unmount(volumeDriver, _)) .WillOnce(DoAll(FutureArg<1>(&unmountName), Return(Nothing()))); Future<TaskStatus> statusStarting; Future<TaskStatus> statusRunning; Future<TaskStatus> statusFinished; EXPECT_CALL(sched, statusUpdate(&driver, _)) .WillOnce(FutureArg<1>(&statusStarting)) .WillOnce(FutureArg<1>(&statusRunning)) .WillOnce(FutureArg<1>(&statusFinished)); driver.launchTasks(offer.id(), {task}); AWAIT_READY(statusStarting); EXPECT_EQ(TASK_STARTING, statusStarting->state()); AWAIT_READY(statusRunning); EXPECT_EQ(TASK_RUNNING, statusRunning->state()); // Make sure the docker volume mount parameters are same with the // parameters in `containerInfo`. AWAIT_EXPECT_EQ(name, mountName); AWAIT_READY(statusFinished); EXPECT_EQ(TASK_FINISHED, statusFinished->state()); // Make sure the docker volume unmount parameters are same with // the parameters in `containerInfo`. AWAIT_EXPECT_EQ(name, unmountName); driver.stop(); driver.join(); } // This test verifies that a docker volume with relative path can // be properly mounted to a container with rootfs, and launches a // command task that reads files from the mounted docker volume. TEST_F(DockerVolumeIsolatorTest, ROOT_INTERNET_CURL_CommandTaskRootfsWithRelativeVolume) { Try<Owned<cluster::Master>> master = StartMaster(); ASSERT_SOME(master); slave::Flags flags = CreateSlaveFlags(); flags.isolation = "docker/volume,docker/runtime,filesystem/linux"; flags.image_providers = "docker"; MockDockerVolumeDriverClient* mockClient = new MockDockerVolumeDriverClient; Try<Owned<MesosContainerizer>> containerizer = createContainerizer(flags, Owned<DriverClient>(mockClient)); ASSERT_SOME(containerizer); Owned<MasterDetector> detector = master.get()->createDetector(); Try<Owned<cluster::Slave>> slave = StartSlave( detector.get(), containerizer->get(), flags); ASSERT_SOME(slave); MockScheduler sched; MesosSchedulerDriver driver( &sched, DEFAULT_FRAMEWORK_INFO, master.get()->pid, DEFAULT_CREDENTIAL); Future<FrameworkID> frameworkId; EXPECT_CALL(sched, registered(&driver, _, _)) .WillOnce(FutureArg<1>(&frameworkId)); Future<vector<Offer>> offers; EXPECT_CALL(sched, resourceOffers(&driver, _)) .WillOnce(FutureArg<1>(&offers)) .WillRepeatedly(Return()); // Ignore subsequent offers. driver.start(); AWAIT_READY(frameworkId); AWAIT_READY(offers); ASSERT_FALSE(offers->empty()); const Offer& offer = offers.get()[0]; const string key = "iops"; const string value = "150"; hashmap<string, string> options = {{key, value}}; // Create a volume with relative path. const string volumeDriver = "driver"; const string name = "name"; const string containerPath = "tmp/foo"; Volume volume = createDockerVolume( volumeDriver, name, containerPath, options); // NOTE: We use a non-shell command here because 'sh' might not be // in the PATH. 'alpine' does not specify env PATH in the image. On // some linux distribution, '/bin' is not in the PATH by default. CommandInfo command; command.set_shell(false); command.set_value("/usr/bin/test"); command.add_arguments("test"); command.add_arguments("-f"); command.add_arguments(containerPath + "/file"); TaskInfo task = createTask( offer.slave_id(), offer.resources(), command); Image image; image.set_type(Image::DOCKER); image.mutable_docker()->set_name("alpine"); ContainerInfo containerInfo; containerInfo.set_type(ContainerInfo::MESOS); containerInfo.add_volumes()->CopyFrom(volume); containerInfo.mutable_mesos()->mutable_image()->CopyFrom(image); task.mutable_container()->CopyFrom(containerInfo); // Create mount point for volume. const string mountPoint = path::join(os::getcwd(), "volume"); ASSERT_SOME(os::mkdir(mountPoint)); ASSERT_SOME(os::touch(path::join(mountPoint, "file"))); Future<string> mountName; Future<hashmap<string, string>> mountOptions; EXPECT_CALL(*mockClient, mount(volumeDriver, _, _)) .WillOnce(DoAll(FutureArg<1>(&mountName), FutureArg<2>(&mountOptions), Return(mountPoint))); Future<string> unmountName; EXPECT_CALL(*mockClient, unmount(volumeDriver, _)) .WillOnce(DoAll(FutureArg<1>(&unmountName), Return(Nothing()))); Future<TaskStatus> statusStarting; Future<TaskStatus> statusRunning; Future<TaskStatus> statusFinished; EXPECT_CALL(sched, statusUpdate(&driver, _)) .WillOnce(FutureArg<1>(&statusStarting)) .WillOnce(FutureArg<1>(&statusRunning)) .WillOnce(FutureArg<1>(&statusFinished)); driver.launchTasks(offer.id(), {task}); AWAIT_READY(statusStarting); EXPECT_EQ(TASK_STARTING, statusStarting->state()); AWAIT_READY(statusRunning); EXPECT_EQ(TASK_RUNNING, statusRunning->state()); // Make sure the docker volume mount parameters are same with the // parameters in `containerInfo`. AWAIT_EXPECT_EQ(name, mountName); AWAIT_READY(mountOptions); EXPECT_SOME_EQ(value, mountOptions->get(key)); AWAIT_READY(statusFinished); EXPECT_EQ(TASK_FINISHED, statusFinished->state()); // Make sure the docker volume unmount parameters are same with // the parameters in `containerInfo`. AWAIT_EXPECT_EQ(name, unmountName); driver.stop(); driver.join(); } } // namespace tests { } // namespace internal { } // namespace mesos {
{ "content_hash": "e71c555566d80b3d062a12fccc06d8a5", "timestamp": "", "source": "github", "line_count": 1077, "max_line_length": 79, "avg_line_length": 29.234911792014856, "alnum_prop": 0.697484596328527, "repo_name": "asamerh4/mesos", "id": "36fffe2ca7692ed11581e46a5035769db556a793", "size": "32941", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/tests/containerizer/docker_volume_isolator_tests.cpp", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "ApacheConf", "bytes": "94" }, { "name": "Batchfile", "bytes": "7980" }, { "name": "C++", "bytes": "10968773" }, { "name": "CMake", "bytes": "105879" }, { "name": "CSS", "bytes": "6958" }, { "name": "HTML", "bytes": "85503" }, { "name": "Java", "bytes": "142025" }, { "name": "JavaScript", "bytes": "1011428" }, { "name": "M4", "bytes": "175144" }, { "name": "Makefile", "bytes": "107012" }, { "name": "PowerShell", "bytes": "2547" }, { "name": "Protocol Buffer", "bytes": "471405" }, { "name": "Python", "bytes": "236812" }, { "name": "Ruby", "bytes": "9164" }, { "name": "Shell", "bytes": "120461" } ], "symlink_target": "" }
namespace mojo { namespace test { struct NestedStructWithTraitsImpl { public: NestedStructWithTraitsImpl(); explicit NestedStructWithTraitsImpl(int32_t in_value); bool operator==(const NestedStructWithTraitsImpl& other) const { return value == other.value; } int32_t value = 0; }; enum class EnumWithTraitsImpl { CUSTOM_VALUE_0 = 10, CUSTOM_VALUE_1 = 11 }; // A type which knows how to look like a mojo::test::StructWithTraits mojom type // by way of mojo::StructTraits. class StructWithTraitsImpl { public: StructWithTraitsImpl(); ~StructWithTraitsImpl(); StructWithTraitsImpl(const StructWithTraitsImpl& other); void set_enum(EnumWithTraitsImpl value) { enum_ = value; } EnumWithTraitsImpl get_enum() const { return enum_; } void set_bool(bool value) { bool_ = value; } bool get_bool() const { return bool_; } void set_uint32(uint32_t value) { uint32_ = value; } uint32_t get_uint32() const { return uint32_; } void set_uint64(uint64_t value) { uint64_ = value; } uint64_t get_uint64() const { return uint64_; } void set_string(std::string value) { string_ = value; } base::StringPiece get_string_as_string_piece() const { return string_; } const std::string& get_string() const { return string_; } const std::vector<std::string>& get_string_array() const { return string_array_; } std::vector<std::string>& get_mutable_string_array() { return string_array_; } const std::set<std::string>& get_string_set() const { return string_set_; } std::set<std::string>& get_mutable_string_set() { return string_set_; } const NestedStructWithTraitsImpl& get_struct() const { return struct_; } NestedStructWithTraitsImpl& get_mutable_struct() { return struct_; } const std::vector<NestedStructWithTraitsImpl>& get_struct_array() const { return struct_array_; } std::vector<NestedStructWithTraitsImpl>& get_mutable_struct_array() { return struct_array_; } const std::map<std::string, NestedStructWithTraitsImpl>& get_struct_map() const { return struct_map_; } std::map<std::string, NestedStructWithTraitsImpl>& get_mutable_struct_map() { return struct_map_; } private: EnumWithTraitsImpl enum_ = EnumWithTraitsImpl::CUSTOM_VALUE_0; bool bool_ = false; uint32_t uint32_ = 0; uint64_t uint64_ = 0; std::string string_; std::vector<std::string> string_array_; std::set<std::string> string_set_; NestedStructWithTraitsImpl struct_; std::vector<NestedStructWithTraitsImpl> struct_array_; std::map<std::string, NestedStructWithTraitsImpl> struct_map_; }; // A type which corresponds nominally to the // mojo::test::StructWithUnreachableTraits mojom type. Used to test that said // type is never serialized, i.e. objects of this type are simply copied into // a message as-is when written to an intra-process interface. struct StructWithUnreachableTraitsImpl { int32_t magic_number = 0; }; // A type which knows how to look like a mojo::test::TrivialStructWithTraits // mojom type by way of mojo::StructTraits. struct TrivialStructWithTraitsImpl { int32_t value; }; // A type which knows how to look like a mojo::test::MoveOnlyStructWithTraits // mojom type by way of mojo::StructTraits. class MoveOnlyStructWithTraitsImpl { public: MoveOnlyStructWithTraitsImpl(); MoveOnlyStructWithTraitsImpl(MoveOnlyStructWithTraitsImpl&& other); ~MoveOnlyStructWithTraitsImpl(); ScopedHandle& get_mutable_handle() { return handle_; } MoveOnlyStructWithTraitsImpl& operator=(MoveOnlyStructWithTraitsImpl&& other); private: ScopedHandle handle_; DISALLOW_COPY_AND_ASSIGN(MoveOnlyStructWithTraitsImpl); }; class UnionWithTraitsBase { public: enum class Type { INT32, STRUCT }; virtual ~UnionWithTraitsBase() {} Type type() const { return type_; } protected: Type type_ = Type::INT32; }; class UnionWithTraitsInt32 : public UnionWithTraitsBase { public: UnionWithTraitsInt32() {} explicit UnionWithTraitsInt32(int32_t value) : value_(value) {} ~UnionWithTraitsInt32() override; int32_t value() const { return value_; } void set_value(int32_t value) { value_ = value; } private: int32_t value_ = 0; }; class UnionWithTraitsStruct : public UnionWithTraitsBase { public: UnionWithTraitsStruct() { type_ = Type::STRUCT; } explicit UnionWithTraitsStruct(int32_t value) : struct_(value) { type_ = Type::STRUCT; } ~UnionWithTraitsStruct() override; NestedStructWithTraitsImpl& get_mutable_struct() { return struct_; } const NestedStructWithTraitsImpl& get_struct() const { return struct_; } private: NestedStructWithTraitsImpl struct_; }; class StructForceSerializeImpl { public: StructForceSerializeImpl(); ~StructForceSerializeImpl(); void set_value(int32_t value) { value_ = value; } int32_t value() const { return value_; } void set_was_serialized() const { was_serialized_ = true; } bool was_serialized() const { return was_serialized_; } void set_was_deserialized() { was_deserialized_ = true; } bool was_deserialized() const { return was_deserialized_; } private: int32_t value_ = 0; mutable bool was_serialized_ = false; bool was_deserialized_ = false; }; class StructNestedForceSerializeImpl { public: StructNestedForceSerializeImpl(); ~StructNestedForceSerializeImpl(); StructForceSerializeImpl& force() { return force_; } const StructForceSerializeImpl& force() const { return force_; } void set_was_serialized() const { was_serialized_ = true; } bool was_serialized() const { return was_serialized_; } void set_was_deserialized() { was_deserialized_ = true; } bool was_deserialized() const { return was_deserialized_; } private: StructForceSerializeImpl force_; mutable bool was_serialized_ = false; bool was_deserialized_ = false; }; } // namespace test } // namespace mojo #endif // MOJO_PUBLIC_CPP_BINDINGS_TESTS_STRUCT_WITH_TRAITS_IMPL_H_
{ "content_hash": "14cb9a8e42b509a3482cf6737f04b553", "timestamp": "", "source": "github", "line_count": 199, "max_line_length": 80, "avg_line_length": 29.65326633165829, "alnum_prop": 0.7205558379935604, "repo_name": "endlessm/chromium-browser", "id": "e8d96120a201e4a7d0b2e0fd88e32f751b145fec", "size": "6371", "binary": false, "copies": "3", "ref": "refs/heads/master", "path": "mojo/public/cpp/bindings/tests/struct_with_traits_impl.h", "mode": "33188", "license": "bsd-3-clause", "language": [], "symlink_target": "" }
import logging import math import gym from gym import spaces from gym.utils import seeding import numpy as np import sys import cv2 import math class ClassifyEnv(gym.Env): def __init__(self, trainSet, target, batch_size=1000, accuracy_mode=False): """ Data set is a tuple of [0] input data: [nSamples x nInputs] [1] labels: [nSamples x 1] Example data sets are given at the end of this file """ self.t = 0 # Current batch number self.t_limit = 0 # Number of batches if you need them self.batch = batch_size # Number of images per batch self.accuracy_mode = accuracy_mode self.seed() self.viewer = None self.trainSet = trainSet self.target = target nInputs = np.shape(trainSet)[1] high = np.array([1.0]*nInputs) self.action_space = spaces.Box(np.array(0,dtype=np.float32), \ np.array(1,dtype=np.float32)) self.observation_space = spaces.Box(np.array(0,dtype=np.float32), \ np.array(1,dtype=np.float32)) self.state = None self.trainOrder = None self.currIndx = None def seed(self, seed=None): ''' Randomly select from training set''' self.np_random, seed = seeding.np_random(seed) return [seed] def reset(self): ''' Initialize State''' #print('Lucky number', np.random.randint(10)) # same randomness? self.trainOrder = np.random.permutation(len(self.target)) self.t = 0 # timestep self.currIndx = self.trainOrder[self.t:self.t+self.batch] self.state = self.trainSet[self.currIndx,:] return self.state def step(self, action): ''' Judge Classification, increment to next batch action - [batch x output] - softmax output ''' y = self.target[self.currIndx] m = y.shape[0] if self.accuracy_mode: p = np.argmax(action, axis=1) accuracy = (float(np.sum(p==y)) / self.batch) reward = accuracy else: log_likelihood = -np.log(action[range(m),y]) loss = np.sum(log_likelihood) / m reward = -loss if self.t_limit > 0: # We are doing batches reward *= (1/self.t_limit) # average self.t += 1 done = False if self.t >= self.t_limit: done = True self.currIndx = self.trainOrder[(self.t*self.batch):\ (self.t*self.batch + self.batch)] self.state = self.trainSet[self.currIndx,:] else: done = True obs = self.state return obs, reward, done, {} # -- Data Sets ----------------------------------------------------------- -- # def digit_raw(): ''' Converts 8x8 scikit digits to [samples x pixels] ([N X 64]) ''' from sklearn import datasets digits = datasets.load_digits() z = (digits.images/16) z = z.reshape(-1, (64)) return z, digits.target def mnist_784(): ''' Converts 28x28 mnist digits to [samples x pixels] ([N X 784]) ''' import mnist z = (mnist.train_images()/255) z = preprocess(z,(28,28)) z = z.reshape(-1, (784)) return z, mnist.train_labels() def mnist_256(): ''' Converts 28x28 mnist digits to [16x16] [samples x pixels] ([N X 256]) ''' import mnist z = (mnist.train_images()/255) z = preprocess(z,(16,16)) z = z.reshape(-1, (256)) return z, mnist.train_labels() def mnist_256_test(): ''' Converts 28x28 mnist digits to [16x16] [samples x pixels] ([N X 256]) ''' import mnist z = (mnist.test_images()/255) z = preprocess(z,(16,16)) z = z.reshape(-1, (256)) return z, mnist.test_labels() def mnist_patch9(): ''' Crops 28x28 mnist digits to a [9x9] patch [samples x pixels] ([N X 81]) ''' import mnist z = (mnist.train_images()/255) z = preprocess(z,(28,28),patchDim=(9,9),patchCorner=(12,12)) z = z.reshape(-1, (81)) return z, mnist.train_labels() ''' This part can be put in step if we want to try classification from patches --- if self.patchSize != None: # (add self.patchSize to class) z = np.reshape(self.state,(len(self.currIndx),28,28)) corner = (np.random.randint(28 - self.patchSize),\ np.random.randint(28 - self.patchSize) ) #corner = (12,12) z = preprocess(z,(28,28),patchDim=(9,9),patchCorner=corner) z = z.reshape(-1, (81)) self.state = z --- ''' def preprocess(img,size, patchCorner=(0,0), patchDim=None, unskew=True): """ Resizes, crops, and unskewes images """ if patchDim == None: patchDim = size nImg = np.shape(img)[0] procImg = np.empty((nImg,size[0],size[1])) # Unskew and Resize if unskew == True: for i in range(nImg): procImg[i,:,:] = deskew(cv2.resize(img[i,:,:],size),size) # Crop cropImg = np.empty((nImg,patchDim[0],patchDim[1])) for i in range(nImg): cropImg[i,:,:] = procImg[i,patchCorner[0]:patchCorner[0]+patchDim[0],\ patchCorner[1]:patchCorner[1]+patchDim[1]] procImg = cropImg return procImg def deskew(image, image_shape, negated=True): """ This method deskwes an image using moments :param image: a numpy nd array input image :param image_shape: a tuple denoting the image`s shape :param negated: a boolean flag telling whether the input image is negated :returns: a numpy nd array deskewd image source: https://github.com/vsvinayak/mnist-helper """ # negate the image if not negated: image = 255-image # calculate the moments of the image m = cv2.moments(image) if abs(m['mu02']) < 1e-2: return image.copy() # caclulating the skew skew = m['mu11']/m['mu02'] M = np.float32([[1, skew, -0.5*image_shape[0]*skew], [0,1,0]]) img = cv2.warpAffine(image, M, image_shape, \ flags=cv2.WARP_INVERSE_MAP|cv2.INTER_LINEAR) return img
{ "content_hash": "68f659b33636b54e3d946c630c2a5c9f", "timestamp": "", "source": "github", "line_count": 220, "max_line_length": 79, "avg_line_length": 26.45, "alnum_prop": 0.6021653205018044, "repo_name": "google/brain-tokyo-workshop", "id": "742610c1e79b207175c68ba587616f42c9621553", "size": "5820", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "WANNRelease/WANNTool/custom_envs/classify_gym.py", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Dockerfile", "bytes": "671" }, { "name": "HTML", "bytes": "1031" }, { "name": "Jupyter Notebook", "bytes": "47079538" }, { "name": "Python", "bytes": "1037153" }, { "name": "Shell", "bytes": "6053" } ], "symlink_target": "" }
package com.badlogic.gdx.graphics.g2d.freetype; import java.io.IOException; import java.io.InputStream; import java.nio.ByteBuffer; import com.badlogic.gdx.Gdx; import com.badlogic.gdx.files.FileHandle; import com.badlogic.gdx.graphics.Color; import com.badlogic.gdx.graphics.Pixmap; import com.badlogic.gdx.graphics.Pixmap.Format; import com.badlogic.gdx.graphics.Texture.TextureFilter; import com.badlogic.gdx.graphics.g2d.BitmapFont; import com.badlogic.gdx.graphics.g2d.BitmapFont.BitmapFontData; import com.badlogic.gdx.graphics.g2d.BitmapFont.Glyph; import com.badlogic.gdx.graphics.g2d.GlyphLayout.GlyphRun; import com.badlogic.gdx.graphics.g2d.PixmapPacker; import com.badlogic.gdx.graphics.g2d.PixmapPacker.GuillotineStrategy; import com.badlogic.gdx.graphics.g2d.PixmapPacker.PackStrategy; import com.badlogic.gdx.graphics.g2d.PixmapPacker.SkylineStrategy; import com.badlogic.gdx.graphics.g2d.TextureRegion; import com.badlogic.gdx.graphics.g2d.freetype.FreeType.Bitmap; import com.badlogic.gdx.graphics.g2d.freetype.FreeType.Face; import com.badlogic.gdx.graphics.g2d.freetype.FreeType.GlyphMetrics; import com.badlogic.gdx.graphics.g2d.freetype.FreeType.GlyphSlot; import com.badlogic.gdx.graphics.g2d.freetype.FreeType.Library; import com.badlogic.gdx.graphics.g2d.freetype.FreeType.SizeMetrics; import com.badlogic.gdx.graphics.g2d.freetype.FreeType.Stroker; import com.badlogic.gdx.math.MathUtils; import com.badlogic.gdx.math.Rectangle; import com.badlogic.gdx.utils.Array; import com.badlogic.gdx.utils.BufferUtils; import com.badlogic.gdx.utils.Disposable; import com.badlogic.gdx.utils.GdxRuntimeException; import com.badlogic.gdx.utils.StreamUtils; /** Generates {@link BitmapFont} and {@link BitmapFontData} instances from TrueType, OTF, and other FreeType supported fonts. * </p> * * Usage example: * * <pre> * FreeTypeFontGenerator gen = new FreeTypeFontGenerator(Gdx.files.internal(&quot;myfont.ttf&quot;)); * BitmapFont font = gen.generateFont(16); * gen.dispose(); * </pre> * * The generator has to be disposed once it is no longer used. The returned {@link BitmapFont} instances are managed by the user * and have to be disposed as usual. * * @author mzechner * @author Nathan Sweet * @author Rob Rendell */ public class FreeTypeFontGenerator implements Disposable { static public final String DEFAULT_CHARS = "\u0000ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz1234567890\"!`?'.,;:()[]{}<>|/@\\^$-%+=#_&~*\u0080\u0081\u0082\u0083\u0084\u0085\u0086\u0087\u0088\u0089\u008A\u008B\u008C\u008D\u008E\u008F\u0090\u0091\u0092\u0093\u0094\u0095\u0096\u0097\u0098\u0099\u009A\u009B\u009C\u009D\u009E\u009F\u00A0\u00A1\u00A2\u00A3\u00A4\u00A5\u00A6\u00A7\u00A8\u00A9\u00AA\u00AB\u00AC\u00AD\u00AE\u00AF\u00B0\u00B1\u00B2\u00B3\u00B4\u00B5\u00B6\u00B7\u00B8\u00B9\u00BA\u00BB\u00BC\u00BD\u00BE\u00BF\u00C0\u00C1\u00C2\u00C3\u00C4\u00C5\u00C6\u00C7\u00C8\u00C9\u00CA\u00CB\u00CC\u00CD\u00CE\u00CF\u00D0\u00D1\u00D2\u00D3\u00D4\u00D5\u00D6\u00D7\u00D8\u00D9\u00DA\u00DB\u00DC\u00DD\u00DE\u00DF\u00E0\u00E1\u00E2\u00E3\u00E4\u00E5\u00E6\u00E7\u00E8\u00E9\u00EA\u00EB\u00EC\u00ED\u00EE\u00EF\u00F0\u00F1\u00F2\u00F3\u00F4\u00F5\u00F6\u00F7\u00F8\u00F9\u00FA\u00FB\u00FC\u00FD\u00FE\u00FF"; /** A hint to scale the texture as needed, without capping it at any maximum size */ static public final int NO_MAXIMUM = -1; /** The maximum texture size allowed by generateData, when storing in a texture atlas. Multiple texture pages will be created * if necessary. Default is 1024. * @see #setMaxTextureSize(int) */ static private int maxTextureSize = 1024; final Library library; final Face face; final String name; boolean bitmapped = false; private int pixelWidth, pixelHeight; /** Creates a new generator from the given font file. Uses {@link FileHandle#length()} to determine the file size. If the file * length could not be determined (it was 0), an extra copy of the font bytes is performed. Throws a * {@link GdxRuntimeException} if loading did not succeed. */ public FreeTypeFontGenerator (FileHandle fontFile) { name = fontFile.pathWithoutExtension(); int fileSize = (int)fontFile.length(); library = FreeType.initFreeType(); if (library == null) throw new GdxRuntimeException("Couldn't initialize FreeType"); ByteBuffer buffer; InputStream input = fontFile.read(); try { if (fileSize == 0) { // Copy to a byte[] to get the file size, then copy to the buffer. byte[] data = StreamUtils.copyStreamToByteArray(input, fileSize > 0 ? (int)(fileSize * 1.5f) : 1024 * 16); buffer = BufferUtils.newUnsafeByteBuffer(data.length); BufferUtils.copy(data, 0, buffer, data.length); } else { // Trust the specified file size. buffer = BufferUtils.newUnsafeByteBuffer(fileSize); StreamUtils.copyStream(input, buffer); } } catch (IOException ex) { throw new GdxRuntimeException(ex); } finally { StreamUtils.closeQuietly(input); } face = library.newMemoryFace(buffer, 0); if (face == null) throw new GdxRuntimeException("Couldn't create face for font: " + fontFile); if (checkForBitmapFont()) return; setPixelSizes(0, 15); } private int getLoadingFlags (FreeTypeFontParameter parameter) { int loadingFlags = FreeType.FT_LOAD_DEFAULT; switch (parameter.hinting) { case None: loadingFlags |= FreeType.FT_LOAD_NO_HINTING; break; case Slight: loadingFlags |= FreeType.FT_LOAD_FORCE_AUTOHINT | FreeType.FT_LOAD_TARGET_LIGHT; break; case Medium: loadingFlags |= FreeType.FT_LOAD_FORCE_AUTOHINT | FreeType.FT_LOAD_TARGET_NORMAL; break; case Full: loadingFlags |= FreeType.FT_LOAD_FORCE_AUTOHINT | FreeType.FT_LOAD_TARGET_MONO; break; } return loadingFlags; } private boolean loadChar (int c) { return loadChar(c, FreeType.FT_LOAD_DEFAULT | FreeType.FT_LOAD_FORCE_AUTOHINT); } private boolean loadChar (int c, int flags) { return face.loadChar(c, flags); } private boolean checkForBitmapFont () { int faceFlags = face.getFaceFlags(); if (((faceFlags & FreeType.FT_FACE_FLAG_FIXED_SIZES) == FreeType.FT_FACE_FLAG_FIXED_SIZES) && ((faceFlags & FreeType.FT_FACE_FLAG_HORIZONTAL) == FreeType.FT_FACE_FLAG_HORIZONTAL)) { if (loadChar(32)) { GlyphSlot slot = face.getGlyph(); if (slot.getFormat() == 1651078259) { bitmapped = true; } } } return bitmapped; } public BitmapFont generateFont (FreeTypeFontParameter parameter) { return generateFont(parameter, new FreeTypeBitmapFontData()); } /** Generates a new {@link BitmapFont}. The size is expressed in pixels. Throws a GdxRuntimeException if the font could not be * generated. Using big sizes might cause such an exception. * @param parameter configures how the font is generated */ public BitmapFont generateFont (FreeTypeFontParameter parameter, FreeTypeBitmapFontData data) { generateData(parameter, data); if (data.regions == null && parameter.packer != null) { data.regions = new Array(); parameter.packer.updateTextureRegions(data.regions, parameter.minFilter, parameter.magFilter, parameter.genMipMaps); } BitmapFont font = new BitmapFont(data, data.regions, true); font.setOwnsTexture(parameter.packer == null); return font; } /** Uses ascender and descender of font to calculate real height that makes all glyphs to fit in given pixel size. Source: * http://nothings.org/stb/stb_truetype.h / stbtt_ScaleForPixelHeight */ public int scaleForPixelHeight (int height) { setPixelSizes(0, height); SizeMetrics fontMetrics = face.getSize().getMetrics(); int ascent = FreeType.toInt(fontMetrics.getAscender()); int descent = FreeType.toInt(fontMetrics.getDescender()); return height * height / (ascent - descent); } /** Uses max advance, ascender and descender of font to calculate real height that makes any n glyphs to fit in given pixel * width. * @param width the max width to fit (in pixels) * @param numChars max number of characters that to fill width */ public int scaleForPixelWidth (int width, int numChars) { SizeMetrics fontMetrics = face.getSize().getMetrics(); int advance = FreeType.toInt(fontMetrics.getMaxAdvance()); int ascent = FreeType.toInt(fontMetrics.getAscender()); int descent = FreeType.toInt(fontMetrics.getDescender()); int unscaledHeight = ascent - descent; int height = unscaledHeight * width / (advance * numChars); setPixelSizes(0, height); return height; } /** Uses max advance, ascender and descender of font to calculate real height that makes any n glyphs to fit in given pixel * width and height. * @param width the max width to fit (in pixels) * @param height the max height to fit (in pixels) * @param numChars max number of characters that to fill width */ public int scaleToFitSquare (int width, int height, int numChars) { return Math.min(scaleForPixelHeight(height), scaleForPixelWidth(width, numChars)); } public class GlyphAndBitmap { public Glyph glyph; public Bitmap bitmap; } /** Returns null if glyph was not found. If there is nothing to render, for example with various space characters, then bitmap * is null. */ public GlyphAndBitmap generateGlyphAndBitmap (int c, int size, boolean flip) { setPixelSizes(0, size); SizeMetrics fontMetrics = face.getSize().getMetrics(); int baseline = FreeType.toInt(fontMetrics.getAscender()); // Check if character exists in this font. // 0 means 'undefined character code' if (face.getCharIndex(c) == 0) { return null; } // Try to load character if (!loadChar(c)) { throw new GdxRuntimeException("Unable to load character!"); } GlyphSlot slot = face.getGlyph(); // Try to render to bitmap Bitmap bitmap; if (bitmapped) { bitmap = slot.getBitmap(); } else if (!slot.renderGlyph(FreeType.FT_RENDER_MODE_NORMAL)) { bitmap = null; } else { bitmap = slot.getBitmap(); } GlyphMetrics metrics = slot.getMetrics(); Glyph glyph = new Glyph(); if (bitmap != null) { glyph.width = bitmap.getWidth(); glyph.height = bitmap.getRows(); } else { glyph.width = 0; glyph.height = 0; } glyph.xoffset = slot.getBitmapLeft(); glyph.yoffset = flip ? -slot.getBitmapTop() + baseline : -(glyph.height - slot.getBitmapTop()) - baseline; glyph.xadvance = FreeType.toInt(metrics.getHoriAdvance()); glyph.srcX = 0; glyph.srcY = 0; glyph.id = c; GlyphAndBitmap result = new GlyphAndBitmap(); result.glyph = glyph; result.bitmap = bitmap; return result; } /** Generates a new {@link BitmapFontData} instance, expert usage only. Throws a GdxRuntimeException if something went wrong. * @param size the size in pixels */ public FreeTypeBitmapFontData generateData (int size) { FreeTypeFontParameter parameter = new FreeTypeFontParameter(); parameter.size = size; return generateData(parameter); } public FreeTypeBitmapFontData generateData (FreeTypeFontParameter parameter) { return generateData(parameter, new FreeTypeBitmapFontData()); } void setPixelSizes (int pixelWidth, int pixelHeight) { this.pixelWidth = pixelWidth; this.pixelHeight = pixelHeight; if (!bitmapped && !face.setPixelSizes(pixelWidth, pixelHeight)) throw new GdxRuntimeException("Couldn't set size for font"); } /** Generates a new {@link BitmapFontData} instance, expert usage only. Throws a GdxRuntimeException if something went wrong. * @param parameter configures how the font is generated */ public FreeTypeBitmapFontData generateData (FreeTypeFontParameter parameter, FreeTypeBitmapFontData data) { parameter = parameter == null ? new FreeTypeFontParameter() : parameter; char[] characters = parameter.characters.toCharArray(); int charactersLength = characters.length; boolean incremental = parameter.incremental; int flags = getLoadingFlags(parameter); setPixelSizes(0, parameter.size); // set general font data SizeMetrics fontMetrics = face.getSize().getMetrics(); data.flipped = parameter.flip; data.ascent = FreeType.toInt(fontMetrics.getAscender()); data.descent = FreeType.toInt(fontMetrics.getDescender()); data.lineHeight = FreeType.toInt(fontMetrics.getHeight()); float baseLine = data.ascent; // if bitmapped if (bitmapped && (data.lineHeight == 0)) { for (int c = 32; c < (32 + face.getNumGlyphs()); c++) { if (loadChar(c, flags)) { int lh = FreeType.toInt(face.getGlyph().getMetrics().getHeight()); data.lineHeight = (lh > data.lineHeight) ? lh : data.lineHeight; } } } data.lineHeight += parameter.spaceY; // determine space width if (loadChar(' ', flags) || loadChar('l', flags)) { data.spaceWidth = FreeType.toInt(face.getGlyph().getMetrics().getHoriAdvance()); } else { data.spaceWidth = face.getMaxAdvanceWidth(); // Possibly very wrong. } // determine x-height for (char xChar : data.xChars) { if (!loadChar(xChar, flags)) continue; data.xHeight = FreeType.toInt(face.getGlyph().getMetrics().getHeight()); break; } if (data.xHeight == 0) throw new GdxRuntimeException("No x-height character found in font"); // determine cap height for (char capChar : data.capChars) { if (!loadChar(capChar, flags)) continue; data.capHeight = FreeType.toInt(face.getGlyph().getMetrics().getHeight()); break; } if (!bitmapped && data.capHeight == 1) throw new GdxRuntimeException("No cap character found in font"); data.ascent -= data.capHeight; data.down = -data.lineHeight; if (parameter.flip) { data.ascent = -data.ascent; data.down = -data.down; } boolean ownsAtlas = false; PixmapPacker packer = parameter.packer; if (packer == null) { // Create a packer. int size; PackStrategy packStrategy; if (incremental) { size = maxTextureSize; packStrategy = new GuillotineStrategy(); } else { int maxGlyphHeight = (int)Math.ceil(data.lineHeight); size = MathUtils.nextPowerOfTwo((int)Math.sqrt(maxGlyphHeight * maxGlyphHeight * charactersLength)); if (maxTextureSize > 0) size = Math.min(size, maxTextureSize); packStrategy = new SkylineStrategy(); } ownsAtlas = true; packer = new PixmapPacker(size, size, Format.RGBA8888, 1, false, packStrategy); } if (incremental) data.glyphs = new Array(charactersLength + 32); Stroker stroker = null; if (parameter.borderWidth > 0) { stroker = library.createStroker(); stroker.set((int)(parameter.borderWidth * 64f), parameter.borderStraight ? FreeType.FT_STROKER_LINECAP_BUTT : FreeType.FT_STROKER_LINECAP_ROUND, parameter.borderStraight ? FreeType.FT_STROKER_LINEJOIN_MITER_FIXED : FreeType.FT_STROKER_LINEJOIN_ROUND, 0); } Glyph missingGlyph = createGlyph('\0', data, parameter, stroker, baseLine, packer); if (missingGlyph != null && missingGlyph.width != 0 && missingGlyph.height != 0) { data.setGlyph('\0', missingGlyph); if (incremental) data.glyphs.add(missingGlyph); } // Create glyphs largest height first for best packing. int[] heights = new int[charactersLength]; for (int i = 0, n = charactersLength; i < n; i++) { int height = loadChar(characters[i], flags) ? FreeType.toInt(face.getGlyph().getMetrics().getHeight()) : 0; heights[i] = height; } int heightsCount = heights.length; while (heightsCount > 0) { int best = 0, maxHeight = heights[0]; for (int i = 1; i < heightsCount; i++) { int height = heights[i]; if (height > maxHeight) { maxHeight = height; best = i; } } char c = characters[best]; Glyph glyph = createGlyph(c, data, parameter, stroker, baseLine, packer); if (glyph != null) { data.setGlyph(c, glyph); if (incremental) data.glyphs.add(glyph); } heightsCount--; heights[best] = heights[heightsCount]; char tmpChar = characters[best]; characters[best] = characters[heightsCount]; characters[heightsCount] = tmpChar; } if (stroker != null && !incremental) stroker.dispose(); if (incremental) { data.generator = this; data.parameter = parameter; data.stroker = stroker; data.packer = packer; } // Generate kerning. parameter.kerning &= face.hasKerning(); if (parameter.kerning) { for (int i = 0; i < charactersLength; i++) { char firstChar = characters[i]; Glyph first = data.getGlyph(firstChar); if (first == null) continue; int firstIndex = face.getCharIndex(firstChar); for (int ii = i; ii < charactersLength; ii++) { char secondChar = characters[ii]; Glyph second = data.getGlyph(secondChar); if (second == null) continue; int secondIndex = face.getCharIndex(secondChar); int kerning = face.getKerning(firstIndex, secondIndex, 0); if (kerning != 0) first.setKerning(secondChar, FreeType.toInt(kerning)); kerning = face.getKerning(secondIndex, firstIndex, 0); if (kerning != 0) second.setKerning(firstChar, FreeType.toInt(kerning)); } } } // Generate texture regions. if (ownsAtlas) { data.regions = new Array(); packer.updateTextureRegions(data.regions, parameter.minFilter, parameter.magFilter, parameter.genMipMaps); } // Set space glyph. Glyph spaceGlyph = data.getGlyph(' '); if (spaceGlyph == null) { spaceGlyph = new Glyph(); spaceGlyph.xadvance = (int)data.spaceWidth + parameter.spaceX; spaceGlyph.id = (int)' '; data.setGlyph(' ', spaceGlyph); } if (spaceGlyph.width == 0) spaceGlyph.width = (int)(spaceGlyph.xadvance + data.padRight); return data; } /** @return null if glyph was not found. */ Glyph createGlyph (char c, FreeTypeBitmapFontData data, FreeTypeFontParameter parameter, Stroker stroker, float baseLine, PixmapPacker packer) { boolean missing = face.getCharIndex(c) == 0 && c != 0; if (missing) return null; if (!loadChar(c, getLoadingFlags(parameter))) return null; GlyphSlot slot = face.getGlyph(); FreeType.Glyph mainGlyph = slot.getGlyph(); try { mainGlyph.toBitmap(parameter.mono ? FreeType.FT_RENDER_MODE_MONO : FreeType.FT_RENDER_MODE_NORMAL); } catch (GdxRuntimeException e) { mainGlyph.dispose(); Gdx.app.log("FreeTypeFontGenerator", "Couldn't render char: " + c); return null; } Bitmap mainBitmap = mainGlyph.getBitmap(); Pixmap mainPixmap = mainBitmap.getPixmap(Format.RGBA8888, parameter.color, parameter.gamma); if (mainBitmap.getWidth() != 0 && mainBitmap.getRows() != 0) { int offsetX = 0, offsetY = 0; if (parameter.borderWidth > 0) { // execute stroker; this generates a glyph "extended" along the outline int top = mainGlyph.getTop(), left = mainGlyph.getLeft(); FreeType.Glyph borderGlyph = slot.getGlyph(); borderGlyph.strokeBorder(stroker, false); borderGlyph.toBitmap(parameter.mono ? FreeType.FT_RENDER_MODE_MONO : FreeType.FT_RENDER_MODE_NORMAL); offsetX = left - borderGlyph.getLeft(); offsetY = -(top - borderGlyph.getTop()); // Render border (pixmap is bigger than main). Bitmap borderBitmap = borderGlyph.getBitmap(); Pixmap borderPixmap = borderBitmap.getPixmap(Format.RGBA8888, parameter.borderColor, parameter.borderGamma); // Draw main glyph on top of border. for (int i = 0, n = parameter.renderCount; i < n; i++) borderPixmap.drawPixmap(mainPixmap, offsetX, offsetY); mainPixmap.dispose(); mainGlyph.dispose(); mainPixmap = borderPixmap; mainGlyph = borderGlyph; } if (parameter.shadowOffsetX != 0 || parameter.shadowOffsetY != 0) { int mainW = mainPixmap.getWidth(), mainH = mainPixmap.getHeight(); int shadowOffsetX = Math.max(parameter.shadowOffsetX, 0), shadowOffsetY = Math.max(parameter.shadowOffsetY, 0); int shadowW = mainW + Math.abs(parameter.shadowOffsetX), shadowH = mainH + Math.abs(parameter.shadowOffsetY); Pixmap shadowPixmap = new Pixmap(shadowW, shadowH, mainPixmap.getFormat()); Color shadowColor = parameter.shadowColor; byte r = (byte)(shadowColor.r * 255), g = (byte)(shadowColor.g * 255), b = (byte)(shadowColor.b * 255); float a = shadowColor.a; ByteBuffer mainPixels = mainPixmap.getPixels(); ByteBuffer shadowPixels = shadowPixmap.getPixels(); for (int y = 0; y < mainH; y++) { int shadowRow = shadowW * (y + shadowOffsetY) + shadowOffsetX; for (int x = 0; x < mainW; x++) { int mainPixel = (mainW * y + x) * 4; byte mainA = mainPixels.get(mainPixel + 3); if (mainA == 0) continue; int shadowPixel = (shadowRow + x) * 4; shadowPixels.put(shadowPixel, r); shadowPixels.put(shadowPixel + 1, g); shadowPixels.put(shadowPixel + 2, b); shadowPixels.put(shadowPixel + 3, (byte)((mainA & 0xff) * a)); } } // Draw main glyph (with any border) on top of shadow. for (int i = 0, n = parameter.renderCount; i < n; i++) shadowPixmap.drawPixmap(mainPixmap, Math.max(-parameter.shadowOffsetX, 0), Math.max(-parameter.shadowOffsetY, 0)); mainPixmap.dispose(); mainPixmap = shadowPixmap; } else if (parameter.borderWidth == 0) { // No shadow and no border, draw glyph additional times. for (int i = 0, n = parameter.renderCount - 1; i < n; i++) mainPixmap.drawPixmap(mainPixmap, 0, 0); } } GlyphMetrics metrics = slot.getMetrics(); Glyph glyph = new Glyph(); glyph.id = c; glyph.width = mainPixmap.getWidth(); glyph.height = mainPixmap.getHeight(); glyph.xoffset = mainGlyph.getLeft(); glyph.yoffset = parameter.flip ? -mainGlyph.getTop() + (int)baseLine : -(glyph.height - mainGlyph.getTop()) - (int)baseLine; glyph.xadvance = FreeType.toInt(metrics.getHoriAdvance()) + (int)parameter.borderWidth + parameter.spaceX; if (bitmapped) { mainPixmap.setColor(Color.CLEAR); mainPixmap.fill(); ByteBuffer buf = mainBitmap.getBuffer(); int whiteIntBits = Color.WHITE.toIntBits(); int clearIntBits = Color.CLEAR.toIntBits(); for (int h = 0; h < glyph.height; h++) { int idx = h * mainBitmap.getPitch(); for (int w = 0; w < (glyph.width + glyph.xoffset); w++) { int bit = (buf.get(idx + (w / 8)) >>> (7 - (w % 8))) & 1; mainPixmap.drawPixel(w, h, ((bit == 1) ? whiteIntBits : clearIntBits)); } } } Rectangle rect = packer.pack(mainPixmap); glyph.page = packer.getPages().size - 1; // Glyph is always packed into the last page for now. glyph.srcX = (int)rect.x; glyph.srcY = (int)rect.y; // If a page was added, create a new texture region for the incrementally added glyph. if (parameter.incremental && data.regions != null && data.regions.size <= glyph.page) packer.updateTextureRegions(data.regions, parameter.minFilter, parameter.magFilter, parameter.genMipMaps); mainPixmap.dispose(); mainGlyph.dispose(); return glyph; } /** Cleans up all resources of the generator. Call this if you no longer use the generator. */ @Override public void dispose () { face.dispose(); library.dispose(); } /** Sets the maximum size that will be used when generating texture atlases for glyphs with <tt>generateData()</tt>. The * default is 1024. By specifying {@link #NO_MAXIMUM}, the texture atlas will scale as needed. * * The power-of-two square texture size will be capped to the given <tt>texSize</tt>. It's recommended that a power-of-two * value be used here. * * Multiple pages may be used to fit all the generated glyphs. You can query the resulting number of pages by calling * <tt>bitmapFont.getRegions().length</tt> or <tt>freeTypeBitmapFontData.getTextureRegions().length</tt>. * * If PixmapPacker is specified when calling generateData, this parameter is ignored. * * @param texSize the maximum texture size for one page of glyphs */ public static void setMaxTextureSize (int texSize) { maxTextureSize = texSize; } /** Returns the maximum texture size that will be used by generateData() when creating a texture atlas for the glyphs. * @return the power-of-two max texture size */ public static int getMaxTextureSize () { return maxTextureSize; } /** {@link BitmapFontData} used for fonts generated via the {@link FreeTypeFontGenerator}. The texture storing the glyphs is * held in memory, thus the {@link #getImagePaths()} and {@link #getFontFile()} methods will return null. * @author mzechner * @author Nathan Sweet */ static public class FreeTypeBitmapFontData extends BitmapFontData implements Disposable { Array<TextureRegion> regions; // Fields for incremental glyph generation. FreeTypeFontGenerator generator; FreeTypeFontParameter parameter; Stroker stroker; PixmapPacker packer; Array<Glyph> glyphs; private boolean dirty; @Override public Glyph getGlyph (char ch) { Glyph glyph = super.getGlyph(ch); if (glyph == null && generator != null) { generator.setPixelSizes(0, parameter.size); float baseline = ((flipped ? -ascent : ascent) + capHeight) / scaleY; glyph = generator.createGlyph(ch, this, parameter, stroker, baseline, packer); if (glyph == null) return missingGlyph; setGlyphRegion(glyph, regions.get(glyph.page)); setGlyph(ch, glyph); glyphs.add(glyph); dirty = true; Face face = generator.face; if (parameter.kerning) { int glyphIndex = face.getCharIndex(ch); for (int i = 0, n = glyphs.size; i < n; i++) { Glyph other = glyphs.get(i); int otherIndex = face.getCharIndex(other.id); int kerning = face.getKerning(glyphIndex, otherIndex, 0); if (kerning != 0) glyph.setKerning(other.id, FreeType.toInt(kerning)); kerning = face.getKerning(otherIndex, glyphIndex, 0); if (kerning != 0) other.setKerning(ch, FreeType.toInt(kerning)); } } } return glyph; } public void getGlyphs (GlyphRun run, CharSequence str, int start, int end, boolean tightBounds) { if (packer != null) packer.setPackToTexture(true); // All glyphs added after this are packed directly to the texture. super.getGlyphs(run, str, start, end, tightBounds); if (dirty) { dirty = false; packer.updateTextureRegions(regions, parameter.minFilter, parameter.magFilter, parameter.genMipMaps); } } @Override public void dispose () { if (stroker != null) stroker.dispose(); if (packer != null) packer.dispose(); } } /** Font smoothing algorithm. */ public static enum Hinting { /** Disable hinting. Generated glyphs will look blurry. */ None, /** Light hinting with fuzzy edges, but close to the original shape */ Slight, /** Default hinting */ Medium, /** Strong hinting with crisp edges at the expense of shape fidelity */ Full } /** Parameter container class that helps configure how {@link FreeTypeBitmapFontData} and {@link BitmapFont} instances are * generated. * * The packer field is for advanced usage, where it is necessary to pack multiple BitmapFonts (i.e. styles, sizes, families) * into a single Texture atlas. If no packer is specified, the generator will use its own PixmapPacker to pack the glyphs into * a power-of-two sized texture, and the resulting {@link FreeTypeBitmapFontData} will have a valid {@link TextureRegion} which * can be used to construct a new {@link BitmapFont}. * * @author siondream * @author Nathan Sweet */ public static class FreeTypeFontParameter { /** The size in pixels */ public int size = 16; /** If true, font smoothing is disabled. */ public boolean mono; /** Strength of hinting when smoothing is enabled */ public Hinting hinting = Hinting.Medium; /** Foreground color (required for non-black borders) */ public Color color = Color.WHITE; /** Glyph gamma. Values > 1 reduce antialiasing. */ public float gamma = 1.8f; /** Number of times to render the glyph. Useful with a shadow or border, so it doesn't show through the glyph. */ public int renderCount = 2; /** Border width in pixels, 0 to disable */ public float borderWidth = 0; /** Border color; only used if borderWidth > 0 */ public Color borderColor = Color.BLACK; /** true for straight (mitered), false for rounded borders */ public boolean borderStraight = false; /** Values < 1 increase the border size. */ public float borderGamma = 1.8f; /** Offset of text shadow on X axis in pixels, 0 to disable */ public int shadowOffsetX = 0; /** Offset of text shadow on Y axis in pixels, 0 to disable */ public int shadowOffsetY = 0; /** Shadow color; only used if shadowOffset > 0 */ public Color shadowColor = new Color(0, 0, 0, 0.75f); /** Pixels to add to glyph spacing. Can be negative. */ public int spaceX, spaceY; /** The characters the font should contain */ public String characters = DEFAULT_CHARS; /** Whether the font should include kerning */ public boolean kerning = true; /** The optional PixmapPacker to use */ public PixmapPacker packer = null; /** Whether to flip the font vertically */ public boolean flip = false; /** Whether to generate mip maps for the resulting texture */ public boolean genMipMaps = false; /** Minification filter */ public TextureFilter minFilter = TextureFilter.Nearest; /** Magnification filter */ public TextureFilter magFilter = TextureFilter.Nearest; /** When true, glyphs are rendered on the fly to the font's glyph page textures as they are needed. The * FreeTypeFontGenerator must not be disposed until the font is no longer needed. The FreeTypeBitmapFontData must be * disposed (separately from the generator) when the font is no longer needed. The FreeTypeFontParameter should not be * modified after creating a font. If a PixmapPacker is not specified, the font glyph page textures will use * {@link FreeTypeFontGenerator#getMaxTextureSize()}. */ public boolean incremental; } }
{ "content_hash": "70cd88b704ed773777253f9519b5cbda", "timestamp": "", "source": "github", "line_count": 746, "max_line_length": 918, "avg_line_length": 40.64343163538874, "alnum_prop": 0.6942282321899736, "repo_name": "anserran/libgdx", "id": "cb7dd9542cfe48563bf87b98f4a5c57aa4c35c21", "size": "31090", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "extensions/gdx-freetype/src/com/badlogic/gdx/graphics/g2d/freetype/FreeTypeFontGenerator.java", "mode": "33261", "license": "apache-2.0", "language": [ { "name": "Awk", "bytes": "3962" }, { "name": "C", "bytes": "8474436" }, { "name": "C++", "bytes": "10680405" }, { "name": "CMake", "bytes": "50546" }, { "name": "CSS", "bytes": "58715" }, { "name": "DIGITAL Command Language", "bytes": "35809" }, { "name": "GLSL", "bytes": "121172" }, { "name": "Groff", "bytes": "2333" }, { "name": "HTML", "bytes": "1125248" }, { "name": "Java", "bytes": "13269735" }, { "name": "JavaScript", "bytes": "72" }, { "name": "Lua", "bytes": "1354" }, { "name": "Makefile", "bytes": "176822" }, { "name": "Objective-C", "bytes": "67438" }, { "name": "Objective-C++", "bytes": "58296" }, { "name": "OpenEdge ABL", "bytes": "15076" }, { "name": "Perl", "bytes": "12797" }, { "name": "Python", "bytes": "182748" }, { "name": "Ragel in Ruby Host", "bytes": "29592" }, { "name": "Shell", "bytes": "353385" } ], "symlink_target": "" }
#include "tensorflow/compiler/xla/service/elemental_ir_emitter.h" #include <algorithm> #include <memory> #include <string> #include <vector> // IWYU pragma: no_include "llvm/IR/Intrinsics.gen.inc" #include "external/llvm/include/llvm/IR/BasicBlock.h" #include "external/llvm/include/llvm/IR/Instructions.h" #include "external/llvm/include/llvm/IR/Intrinsics.h" #include "external/llvm/include/llvm/Transforms/Utils/BasicBlockUtils.h" #include "tensorflow/compiler/xla/primitive_util.h" #include "tensorflow/compiler/xla/service/hlo_module.h" #include "tensorflow/compiler/xla/service/hlo_opcode.h" #include "tensorflow/compiler/xla/service/llvm_ir/ir_array.h" #include "tensorflow/compiler/xla/service/llvm_ir/llvm_util.h" #include "tensorflow/compiler/xla/shape_util.h" #include "tensorflow/compiler/xla/status_macros.h" #include "tensorflow/compiler/xla/statusor.h" #include "tensorflow/compiler/xla/types.h" #include "tensorflow/compiler/xla/util.h" #include "tensorflow/compiler/xla/xla_data.pb.h" #include "tensorflow/core/lib/random/random.h" #include "tensorflow/core/lib/strings/strcat.h" #include "tensorflow/core/platform/logging.h" #include "tensorflow/core/platform/types.h" namespace xla { using llvm_ir::IrArray; using llvm_ir::SetToFirstInsertPoint; StatusOr<llvm::Value*> ElementalIrEmitter::EmitUnaryOp( const HloInstruction* op, llvm::Value* operand_value) const { if (op->opcode() == HloOpcode::kCopy) { return operand_value; } else { return operand_value->getType()->isIntegerTy() ? EmitIntegerUnaryOp(op, operand_value) : EmitFloatUnaryOp(op, operand_value); } } StatusOr<llvm::Value*> ElementalIrEmitter::EmitIntegerUnaryOp( const HloInstruction* op, llvm::Value* operand_value) const { switch (op->opcode()) { case HloOpcode::kConvert: { PrimitiveType from_type = op->operand(0)->shape().element_type(); PrimitiveType to_type = op->shape().element_type(); CHECK(primitive_util::IsIntegralType(from_type)); if (from_type == to_type) { return operand_value; } if (primitive_util::IsIntegralType(to_type)) { return ir_builder_->CreateIntCast( operand_value, llvm_ir::PrimitiveTypeToIrType(to_type, ir_builder_), primitive_util::IsSignedIntegralType(to_type)); } if (primitive_util::IsFloatingPointType(to_type)) { if (primitive_util::IsSignedIntegralType(from_type)) { return ir_builder_->CreateSIToFP( operand_value, llvm_ir::PrimitiveTypeToIrType(to_type, ir_builder_)); } if (primitive_util::IsUnsignedIntegralType(from_type)) { return ir_builder_->CreateUIToFP( operand_value, llvm_ir::PrimitiveTypeToIrType(to_type, ir_builder_)); } } return Unimplemented("conversion from primitive type %s to %s", PrimitiveType_Name(from_type).c_str(), PrimitiveType_Name(to_type).c_str()); } case HloOpcode::kAbs: { bool is_signed = primitive_util::IsSignedIntegralType(op->shape().element_type()); if (is_signed) { auto type = llvm_ir::PrimitiveTypeToIrType(op->shape().element_type(), ir_builder_); auto zero = llvm::ConstantInt::get(type, 0); auto cmp = ir_builder_->CreateICmpSGE(operand_value, zero); return ir_builder_->CreateSelect(cmp, operand_value, ir_builder_->CreateNeg(operand_value)); } else { return operand_value; } } case HloOpcode::kSign: { bool is_signed = primitive_util::IsSignedIntegralType(op->shape().element_type()); auto type = llvm_ir::PrimitiveTypeToIrType(op->shape().element_type(), ir_builder_); auto zero = llvm::ConstantInt::get(type, 0); auto cmp = ir_builder_->CreateICmpEQ(operand_value, zero); if (is_signed) { auto ashr = ir_builder_->CreateAShr(operand_value, type->getIntegerBitWidth() - 1); return ir_builder_->CreateSelect(cmp, zero, ir_builder_->CreateOr(ashr, 1)); } else { return ir_builder_->CreateSelect(cmp, zero, llvm::ConstantInt::get(type, 1)); } } case HloOpcode::kNegate: return ir_builder_->CreateNeg(operand_value); case HloOpcode::kLogicalNot: // It is not sufficient to just call CreateNot() here because a PRED is // represented as an i8 and the truth value is stored only in the bottom // bit. return ir_builder_->CreateZExt( ir_builder_->CreateNot(ir_builder_->CreateTrunc( operand_value, ir_builder_->getInt1Ty())), llvm_ir::PrimitiveTypeToIrType(PRED, ir_builder_)); default: return Unimplemented("unary integer op '%s'", HloOpcodeString(op->opcode()).c_str()); } } StatusOr<llvm::Value*> ElementalIrEmitter::EmitFloatUnaryOp( const HloInstruction* op, llvm::Value* operand_value) const { switch (op->opcode()) { case HloOpcode::kConvert: { PrimitiveType from_type = op->operand(0)->shape().element_type(); PrimitiveType to_type = op->shape().element_type(); CHECK(primitive_util::IsFloatingPointType(from_type)); if (from_type == to_type) { return operand_value; } if (primitive_util::IsFloatingPointType(to_type)) { return ir_builder_->CreateFPCast( operand_value, llvm_ir::PrimitiveTypeToIrType(to_type, ir_builder_)); } if (primitive_util::IsSignedIntegralType(to_type)) { return ir_builder_->CreateFPToSI( operand_value, llvm_ir::PrimitiveTypeToIrType(to_type, ir_builder_)); } if (primitive_util::IsUnsignedIntegralType(to_type)) { return ir_builder_->CreateFPToUI( operand_value, llvm_ir::PrimitiveTypeToIrType(to_type, ir_builder_)); } return Unimplemented("unhandled conversion operation: %s => %s", PrimitiveType_Name(from_type).c_str(), PrimitiveType_Name(to_type).c_str()); } case HloOpcode::kExp: return llvm_ir::EmitCallToIntrinsic(llvm::Intrinsic::exp, {operand_value}, {operand_value->getType()}, ir_builder_); case HloOpcode::kLog: return llvm_ir::EmitCallToIntrinsic(llvm::Intrinsic::log, {operand_value}, {operand_value->getType()}, ir_builder_); case HloOpcode::kFloor: return llvm_ir::EmitCallToIntrinsic( llvm::Intrinsic::floor, {operand_value}, {operand_value->getType()}, ir_builder_); case HloOpcode::kCeil: return llvm_ir::EmitCallToIntrinsic( llvm::Intrinsic::ceil, {operand_value}, {operand_value->getType()}, ir_builder_); case HloOpcode::kAbs: return llvm_ir::EmitCallToIntrinsic( llvm::Intrinsic::fabs, {operand_value}, {operand_value->getType()}, ir_builder_); case HloOpcode::kSign: { // TODO(b/32151903): Ensure consistent sign behavior for -0.0 auto type = operand_value->getType(); auto zero = llvm::ConstantFP::get(type, 0.0); auto oeq = ir_builder_->CreateFCmpOEQ(operand_value, zero); auto olt = ir_builder_->CreateFCmpOLT(operand_value, zero); return ir_builder_->CreateSelect( oeq, zero, ir_builder_->CreateSelect(olt, llvm::ConstantFP::get(type, -1.0), llvm::ConstantFP::get(type, 1.0))); } case HloOpcode::kIsFinite: { // (x == x) && abs(x) != inf auto type = operand_value->getType(); auto equal_self = ir_builder_->CreateFCmpOEQ(operand_value, operand_value); auto abs_value = llvm_ir::EmitCallToIntrinsic( llvm::Intrinsic::fabs, {operand_value}, {type}, ir_builder_); auto infinity = llvm::ConstantFP::getInfinity(type); auto not_infinite = ir_builder_->CreateFCmpONE(abs_value, infinity); auto result_i1 = ir_builder_->CreateAnd(equal_self, not_infinite); return ir_builder_->CreateZExt( result_i1, llvm_ir::PrimitiveTypeToIrType(PRED, ir_builder_)); } case HloOpcode::kNegate: return ir_builder_->CreateFNeg(operand_value); default: return Unimplemented("unary floating-point op '%s'", HloOpcodeString(op->opcode()).c_str()); } } StatusOr<llvm::Value*> ElementalIrEmitter::EmitBinaryOp( const HloInstruction* op, llvm::Value* lhs_value, llvm::Value* rhs_value) const { return lhs_value->getType()->isIntegerTy() ? EmitIntegerBinaryOp(op, lhs_value, rhs_value, primitive_util::IsSignedIntegralType( op->operand(0)->shape().element_type())) : EmitFloatBinaryOp(op, lhs_value, rhs_value); } StatusOr<llvm::Value*> ElementalIrEmitter::EmitFloatBinaryOp( const HloInstruction* op, llvm::Value* lhs_value, llvm::Value* rhs_value) const { switch (op->opcode()) { case HloOpcode::kAdd: return ir_builder_->CreateFAdd(lhs_value, rhs_value); case HloOpcode::kSubtract: return ir_builder_->CreateFSub(lhs_value, rhs_value); case HloOpcode::kMultiply: return ir_builder_->CreateFMul(lhs_value, rhs_value); case HloOpcode::kDivide: return ir_builder_->CreateFDiv(lhs_value, rhs_value); case HloOpcode::kRemainder: return ir_builder_->CreateFRem(lhs_value, rhs_value); // LLVM comparisons can be "unordered" (U) or "ordered" (O) -- ordered // comparisons always return false when one of the operands is NaN, whereas // unordered comparisons return true. // // We use ordered comparisons for everything except kNe, where we use an // unordered comparison. This makes x != y equivalent to !(x == y), and // matches C++'s semantics. case HloOpcode::kEq: return llvm_ir::EmitComparison(llvm::CmpInst::FCMP_OEQ, lhs_value, rhs_value, ir_builder_); case HloOpcode::kNe: return llvm_ir::EmitComparison(llvm::CmpInst::FCMP_UNE, lhs_value, rhs_value, ir_builder_); case HloOpcode::kLt: return llvm_ir::EmitComparison(llvm::CmpInst::FCMP_OLT, lhs_value, rhs_value, ir_builder_); case HloOpcode::kGt: return llvm_ir::EmitComparison(llvm::CmpInst::FCMP_OGT, lhs_value, rhs_value, ir_builder_); case HloOpcode::kLe: return llvm_ir::EmitComparison(llvm::CmpInst::FCMP_OLE, lhs_value, rhs_value, ir_builder_); case HloOpcode::kGe: return llvm_ir::EmitComparison(llvm::CmpInst::FCMP_OGE, lhs_value, rhs_value, ir_builder_); case HloOpcode::kMaximum: return EmitFloatMax(lhs_value, rhs_value); case HloOpcode::kMinimum: return EmitFloatMin(lhs_value, rhs_value); case HloOpcode::kPower: return llvm_ir::EmitCallToIntrinsic(llvm::Intrinsic::pow, {lhs_value, rhs_value}, {lhs_value->getType()}, ir_builder_); default: return Unimplemented("binary floating point op '%s'", HloOpcodeString(op->opcode()).c_str()); } } llvm::Value* ElementalIrEmitter::EmitFloatMax(llvm::Value* lhs_value, llvm::Value* rhs_value) const { return llvm_ir::EmitCallToIntrinsic(llvm::Intrinsic::maxnum, {lhs_value, rhs_value}, {lhs_value->getType()}, ir_builder_); } llvm::Value* ElementalIrEmitter::EmitFloatMin(llvm::Value* lhs_value, llvm::Value* rhs_value) const { return llvm_ir::EmitCallToIntrinsic(llvm::Intrinsic::minnum, {lhs_value, rhs_value}, {lhs_value->getType()}, ir_builder_); } StatusOr<llvm::Value*> ElementalIrEmitter::EmitErfInv(PrimitiveType prim_type, llvm::Value* x) const { if (prim_type != F32) { return Unimplemented("inverse erf only implemented for F32 (b/34339814)"); } auto getFloat = [&](const float f) { return llvm::ConstantFP::get(ir_builder_->getFloatTy(), f); }; auto multiply_add = [&](tensorflow::gtl::ArraySlice<float> coefficients, llvm::Value* w) { llvm::Value* p = getFloat(coefficients.front()); coefficients.pop_front(); for (float coefficient : coefficients) { p = ir_builder_->CreateFAdd(ir_builder_->CreateFMul(p, w), getFloat(coefficient)); } return p; }; // Approximation for inverse error function from // Giles, M., "Approximating the erfinv function". // The approximation has the form: // w = log((1-x)*(1+x)) // if ( w < 5 ) { // w = w - 2.5 // p = sum_{i=1}^n lq[i]*w^i // } else { // w = sqrt(w) - 3 // p = sum_{i=1}^n gq[i]*w^i // } // return p*x llvm::Function* logf_fn = llvm::Intrinsic::getDeclaration( module_, llvm::Intrinsic::log, {ir_builder_->getFloatTy()}); llvm::Value* w = ir_builder_->CreateFNeg(ir_builder_->CreateCall( logf_fn, {ir_builder_->CreateFMul(ir_builder_->CreateFSub(getFloat(1.0f), x), ir_builder_->CreateFAdd(getFloat(1.0f), x))})); llvm::Value* p_addr = llvm_ir::EmitAllocaAtFunctionEntry( ir_builder_->getFloatTy(), "p.addr", ir_builder_); llvm_ir::LlvmIfData if_data = llvm_ir::EmitIfThenElse(ir_builder_->CreateFCmpOLT(w, getFloat(5.0f)), "w_less_than_five", ir_builder_); // Handle true BB. SetToFirstInsertPoint(if_data.true_block, ir_builder_); { llvm::Value* lw = ir_builder_->CreateFSub(w, getFloat(2.5f)); tensorflow::gtl::ArraySlice<float> lq{ 2.81022636e-08f, 3.43273939e-07f, -3.5233877e-06f, -4.39150654e-06f, 0.00021858087f, -0.00125372503f, -0.00417768164f, 0.246640727f, 1.50140941f}; llvm::Value* p = multiply_add(lq, lw); ir_builder_->CreateStore(p, p_addr); } // Handle false BB. SetToFirstInsertPoint(if_data.false_block, ir_builder_); { llvm::Function* sqrtf_fn = llvm::Intrinsic::getDeclaration( module_, llvm::Intrinsic::sqrt, {ir_builder_->getFloatTy()}); llvm::Value* gw = ir_builder_->CreateFSub( ir_builder_->CreateCall(sqrtf_fn, {w}), getFloat(3.0f)); tensorflow::gtl::ArraySlice<float> gq{ -0.000200214257f, 0.000100950558f, 0.00134934322f, -0.00367342844f, 0.00573950773f, -0.0076224613f, 0.00943887047f, 1.00167406f, 2.83297682f}; llvm::Value* p = multiply_add(gq, gw); ir_builder_->CreateStore(p, p_addr); } SetToFirstInsertPoint(if_data.after_block, ir_builder_); llvm::Value* p = ir_builder_->CreateLoad(p_addr); return ir_builder_->CreateFMul(p, x); } StatusOr<llvm::Value*> ElementalIrEmitter::EmitErfcInv( PrimitiveType prim_type, llvm::Value* value) const { // Compute erfcinv(value) by calculating erfinv(1.0 - value). auto type = llvm_ir::PrimitiveTypeToIrType(prim_type, ir_builder_); auto one = llvm::ConstantFP::get(type, 1.0); return EmitErfInv(prim_type, ir_builder_->CreateFSub(one, value)); } StatusOr<llvm::Value*> ElementalIrEmitter::EmitIntegerBinaryOp( const HloInstruction* op, llvm::Value* lhs_value, llvm::Value* rhs_value, bool is_signed) const { switch (op->opcode()) { // TODO(jingyue): add the "nsw" attribute for signed types. case HloOpcode::kAdd: return ir_builder_->CreateAdd(lhs_value, rhs_value); case HloOpcode::kSubtract: return ir_builder_->CreateSub(lhs_value, rhs_value); case HloOpcode::kMultiply: return ir_builder_->CreateMul(lhs_value, rhs_value); case HloOpcode::kDivide: return is_signed ? ir_builder_->CreateSDiv(lhs_value, rhs_value) : ir_builder_->CreateUDiv(lhs_value, rhs_value); case HloOpcode::kRemainder: return is_signed ? ir_builder_->CreateSRem(lhs_value, rhs_value) : ir_builder_->CreateURem(lhs_value, rhs_value); case HloOpcode::kEq: return llvm_ir::EmitComparison(llvm::CmpInst::ICMP_EQ, lhs_value, rhs_value, ir_builder_); case HloOpcode::kNe: return llvm_ir::EmitComparison(llvm::CmpInst::ICMP_NE, lhs_value, rhs_value, ir_builder_); case HloOpcode::kLt: return llvm_ir::EmitComparison( is_signed ? llvm::CmpInst::ICMP_SLT : llvm::CmpInst::ICMP_ULT, lhs_value, rhs_value, ir_builder_); case HloOpcode::kGt: return llvm_ir::EmitComparison( is_signed ? llvm::CmpInst::ICMP_SGT : llvm::CmpInst::ICMP_UGT, lhs_value, rhs_value, ir_builder_); case HloOpcode::kLe: return llvm_ir::EmitComparison( is_signed ? llvm::CmpInst::ICMP_SLE : llvm::CmpInst::ICMP_ULE, lhs_value, rhs_value, ir_builder_); case HloOpcode::kGe: return llvm_ir::EmitComparison( is_signed ? llvm::CmpInst::ICMP_SGE : llvm::CmpInst::ICMP_UGE, lhs_value, rhs_value, ir_builder_); case HloOpcode::kMinimum: return ir_builder_->CreateSelect( ir_builder_->CreateICmp( is_signed ? llvm::ICmpInst::ICMP_SLE : llvm::ICmpInst::ICMP_ULE, lhs_value, rhs_value), lhs_value, rhs_value); case HloOpcode::kMaximum: return ir_builder_->CreateSelect( ir_builder_->CreateICmp( is_signed ? llvm::ICmpInst::ICMP_SGE : llvm::ICmpInst::ICMP_UGE, lhs_value, rhs_value), lhs_value, rhs_value); case HloOpcode::kLogicalAnd: return ir_builder_->CreateAnd(lhs_value, rhs_value); case HloOpcode::kLogicalOr: return ir_builder_->CreateOr(lhs_value, rhs_value); default: return Unimplemented("binary integer op '%s'", HloOpcodeString(op->opcode()).c_str()); } } llvm_ir::IrArray::Index ElementalIrEmitter::ElementwiseSourceIndex( const llvm_ir::IrArray::Index& target_index, const HloInstruction& hlo, int64 operand_no) const { CHECK(hlo.IsElementwise()) << "HLO " << hlo.ToString() << " is not elementwise."; const Shape& operand_shape = hlo.operand(operand_no)->shape(); // If the operand is scalar, the source index is always {}. if (ShapeUtil::IsScalar(operand_shape)) { return llvm_ir::IrArray::Index(); } // If no implicit broadcast is needed for this operand, returns the target // index as the source index. if (ShapeUtil::Compatible(operand_shape, hlo.shape())) { return target_index; } // If implicit broadcast is needed, the source dimensions that are broadcast // have index 0. CHECK_EQ(ShapeUtil::Rank(operand_shape), ShapeUtil::Rank(hlo.shape())); llvm_ir::IrArray::Index source_index; for (int64 i = 0; i < ShapeUtil::Rank(hlo.shape()); ++i) { if (hlo.shape().dimensions(i) == operand_shape.dimensions(i)) { source_index.push_back(target_index[i]); } else { CHECK_EQ(1, operand_shape.dimensions(i)); source_index.push_back(ir_builder_->getInt64(0)); } } return source_index; } llvm_ir::ElementGenerator ElementalIrEmitter::MakeRngElementGenerator( const HloInstruction* hlo, const ElementalIrEmitter::HloToElementGeneratorMap& operand_to_generator) const { PrimitiveType param_prim_type = hlo->operand(0)->shape().element_type(); llvm::Type* param_ir_type = llvm_ir::PrimitiveTypeToIrType(param_prim_type, ir_builder_); // Same values as PCG library // https://github.com/imneme/pcg-c/blob/master/include/pcg_variants.h llvm::Value* multiplier = ir_builder_->getInt( llvm::APInt(128, {0x4385DF649FCCF645, 0x2360ED051FC65DA4})); llvm::Value* increment = ir_builder_->getInt( llvm::APInt(128, {0x14057B7EF767814F, 0x5851F42D4C957F2D})); auto random_value = [hlo]() { const HloModule* module = hlo->IsFused() ? hlo->fusion_instruction()->parent()->parent() : hlo->parent()->parent(); return module->RandomNew64(); }; // Seed each RNG emitter with a new 64-bit seed from the HloModule. If the // compilation order is deterministic (i.e., RandomNew64 invocation order is // deterministic), then the order of RNG is deterministic for a given seed and // hence tests will be deterministic. // If the user provides a global seed instruction then we only use 64-bits of // the host's random number generator to seed the 128 bit value with the other // 64-bits is due to a user specified global seed instruction. // Create a GlobalVariable to maintain state between invocations. There is a // bug in NVPTX with GlobalVariable and 128 bit values, so using 2 64-bit // values. llvm::GlobalVariable* state_ptr0 = new llvm::GlobalVariable( /*M=*/*module_, /*Ty=*/ir_builder_->getInt64Ty(), /*isConstant=*/false, /*Linkage=*/llvm::GlobalValue::PrivateLinkage, /*Initializer=*/ir_builder_->getInt64(random_value()), /*Name=*/"state_ptr0"); uint64 graph_seed = hlo_module_config_.seed() != 0 ? hlo_module_config_.seed() : random_value(); llvm::GlobalVariable* state_ptr1 = new llvm::GlobalVariable( /*M=*/*module_, /*Ty=*/ir_builder_->getInt64Ty(), /*isConstant=*/false, /*Linkage=*/llvm::GlobalValue::PrivateLinkage, /*Initializer=*/ir_builder_->getInt64(graph_seed), /*Name=*/"state_ptr1"); // We want each thread to use its own stream, so we modify the increment per // thread. We want the increment to remain odd, so we shift the thread id left // 1 and add it to the increment. increment = ir_builder_->CreateAdd(increment, ir_builder_->CreateShl(EmitThreadId(), 1)); // PCG-XSL-RR algorithm // http://www.pcg-random.org/pdf/toms-oneill-pcg-family-v1.02.pdf // state = multiplier * state + increment // return uint64_t(state ^ (state >> 64))) >>> (state >> 122) // where ">>>" is bitwise rotation auto get_next_i64 = [=]() { llvm::Value* state0 = ir_builder_->CreateZExtOrTrunc( ir_builder_->CreateLoad(state_ptr0, "state0"), ir_builder_->getInt128Ty()); llvm::Value* state1 = ir_builder_->CreateShl( ir_builder_->CreateZExtOrTrunc( ir_builder_->CreateLoad(state_ptr1, "state1"), ir_builder_->getInt128Ty()), 64); llvm::Value* state = ir_builder_->CreateOr(state0, state1); llvm::Value* updated = ir_builder_->CreateAdd( ir_builder_->CreateMul(state, multiplier), increment); ir_builder_->CreateStore( ir_builder_->CreateTrunc(updated, ir_builder_->getInt64Ty()), state_ptr0); ir_builder_->CreateStore( ir_builder_->CreateTrunc(ir_builder_->CreateLShr(updated, 64), ir_builder_->getInt64Ty()), state_ptr1); return llvm_ir::CreateRor( ir_builder_->CreateTrunc( ir_builder_->CreateXor(state, ir_builder_->CreateLShr(state, 64)), ir_builder_->getInt64Ty()), ir_builder_->CreateTrunc(ir_builder_->CreateLShr(state, 122), ir_builder_->getInt64Ty()), ir_builder_); }; auto get_next_uniform_float = [=]() { return ir_builder_->CreateFDiv( ir_builder_->CreateUIToFP(get_next_i64(), param_ir_type), llvm::ConstantFP::get(param_ir_type, 0x1p64)); }; return [=](const llvm_ir::IrArray::Index& index) -> StatusOr<llvm::Value*> { switch (hlo->random_distribution()) { case RNG_UNIFORM: { TF_ASSIGN_OR_RETURN(llvm::Value * p, operand_to_generator.at(hlo->operand(0))(index)); TF_ASSIGN_OR_RETURN(llvm::Value * q, operand_to_generator.at(hlo->operand(1))(index)); if (primitive_util::IsFloatingPointType(param_prim_type)) { return ir_builder_->CreateFAdd( ir_builder_->CreateFMul(ir_builder_->CreateFSub(q, p), get_next_uniform_float()), p); } else { auto r = ir_builder_->CreateSub(q, p); auto leading_zeros = llvm_ir::EmitCallToIntrinsic( llvm::Intrinsic::ctlz, {r, ir_builder_->getInt1(1)}, {param_ir_type}, ir_builder_); auto in_block = ir_builder_->GetInsertBlock(); auto body_block = in_block->splitBasicBlock( ir_builder_->GetInsertPoint(), "rng_body"); SetToFirstInsertPoint(body_block, ir_builder_); auto out_block = body_block->splitBasicBlock( ir_builder_->GetInsertPoint(), "rng_out"); SetToFirstInsertPoint(body_block, ir_builder_); auto random = ir_builder_->CreateAnd( ir_builder_->CreateZExtOrTrunc(get_next_i64(), param_ir_type), ir_builder_->CreateLShr(llvm::ConstantInt::get(param_ir_type, ~0), leading_zeros)); llvm::ReplaceInstWithInst( body_block->getTerminator(), llvm::BranchInst::Create(out_block, body_block, ir_builder_->CreateICmpULT(random, r))); SetToFirstInsertPoint(out_block, ir_builder_); return ir_builder_->CreateAdd( p, ir_builder_->CreateSelect( ir_builder_->CreateICmpEQ(p, q), llvm::ConstantInt::get(param_ir_type, 0), random)); } } case RNG_NORMAL: { TF_ASSIGN_OR_RETURN(llvm::Value * m, operand_to_generator.at(hlo->operand(0))(index)); TF_ASSIGN_OR_RETURN(llvm::Value * s, operand_to_generator.at(hlo->operand(1))(index)); TF_ASSIGN_OR_RETURN( llvm::Value * r, EmitErfcInv(param_prim_type, ir_builder_->CreateFMul( llvm::ConstantFP::get(param_ir_type, 2.0), get_next_uniform_float()))); return ir_builder_->CreateFAdd(ir_builder_->CreateFMul(r, s), m); } case RNG_BERNOULLI: { TF_ASSIGN_OR_RETURN(llvm::Value * p, operand_to_generator.at(hlo->operand(0))(index)); return ir_builder_->CreateZExt( ir_builder_->CreateFCmpOLT(get_next_uniform_float(), p), llvm_ir::PrimitiveTypeToIrType(hlo->shape().element_type(), ir_builder_)); } default: return InvalidArgument( "unhandled distribution %s", RandomDistribution_Name(hlo->random_distribution()).c_str()); } }; } llvm_ir::ElementGenerator ElementalIrEmitter::MakeElementGenerator( const HloInstruction* hlo, const ElementalIrEmitter::HloToElementGeneratorMap& operand_to_generator) const { switch (hlo->opcode()) { case HloOpcode::kAbs: case HloOpcode::kCeil: case HloOpcode::kConvert: case HloOpcode::kCopy: case HloOpcode::kExp: case HloOpcode::kFloor: case HloOpcode::kIsFinite: case HloOpcode::kLog: case HloOpcode::kNegate: case HloOpcode::kSign: case HloOpcode::kTanh: case HloOpcode::kLogicalNot: return [this, hlo, &operand_to_generator]( const IrArray::Index& index) -> StatusOr<llvm::Value*> { TF_ASSIGN_OR_RETURN(llvm::Value * operand_value, operand_to_generator.at(hlo->operand(0))( ElementwiseSourceIndex(index, *hlo, 0))); return EmitUnaryOp(hlo, operand_value); }; case HloOpcode::kAdd: case HloOpcode::kDivide: case HloOpcode::kEq: case HloOpcode::kGe: case HloOpcode::kGt: case HloOpcode::kLe: case HloOpcode::kLt: case HloOpcode::kMaximum: case HloOpcode::kMinimum: case HloOpcode::kMultiply: case HloOpcode::kNe: case HloOpcode::kPower: case HloOpcode::kRemainder: case HloOpcode::kSubtract: case HloOpcode::kLogicalAnd: case HloOpcode::kLogicalOr: return [this, hlo, &operand_to_generator]( const IrArray::Index& index) -> StatusOr<llvm::Value*> { const HloInstruction* lhs = hlo->operand(0); const HloInstruction* rhs = hlo->operand(1); TF_ASSIGN_OR_RETURN(llvm::Value * lhs_value, operand_to_generator.at(lhs)( ElementwiseSourceIndex(index, *hlo, 0))); TF_ASSIGN_OR_RETURN(llvm::Value * rhs_value, operand_to_generator.at(rhs)( ElementwiseSourceIndex(index, *hlo, 1))); return EmitBinaryOp(hlo, lhs_value, rhs_value); }; case HloOpcode::kSelect: return [this, hlo, &operand_to_generator]( const IrArray::Index& index) -> StatusOr<llvm::Value*> { TF_ASSIGN_OR_RETURN(llvm::Value * pred_value, operand_to_generator.at(hlo->operand(0))( ElementwiseSourceIndex(index, *hlo, 0))); TF_ASSIGN_OR_RETURN(llvm::Value * on_true_value, operand_to_generator.at(hlo->operand(1))( ElementwiseSourceIndex(index, *hlo, 1))); TF_ASSIGN_OR_RETURN(llvm::Value * on_false_value, operand_to_generator.at(hlo->operand(2))( ElementwiseSourceIndex(index, *hlo, 2))); return ir_builder_->CreateSelect( ir_builder_->CreateTrunc(pred_value, ir_builder_->getInt1Ty()), on_true_value, on_false_value); }; case HloOpcode::kClamp: return [this, hlo, &operand_to_generator]( const IrArray::Index& index) -> StatusOr<llvm::Value*> { TF_ASSIGN_OR_RETURN(llvm::Value * min_value, operand_to_generator.at(hlo->operand(0))( ElementwiseSourceIndex(index, *hlo, 0))); TF_ASSIGN_OR_RETURN(llvm::Value * arg_value, operand_to_generator.at(hlo->operand(1))( ElementwiseSourceIndex(index, *hlo, 1))); TF_ASSIGN_OR_RETURN(llvm::Value * max_value, operand_to_generator.at(hlo->operand(2))( ElementwiseSourceIndex(index, *hlo, 2))); return EmitFloatMin(max_value, EmitFloatMax(min_value, arg_value)); }; case HloOpcode::kConcatenate: return [this, hlo, &operand_to_generator]( const IrArray::Index target_index) -> StatusOr<llvm::Value*> { const int64 concat_dim = hlo->dimensions(0); auto source_index = target_index; llvm::PHINode* output = ir_builder_->CreatePHI( llvm_ir::PrimitiveTypeToIrType(hlo->shape().element_type(), ir_builder_), hlo->operands().size()); llvm::BasicBlock* init_block = ir_builder_->GetInsertBlock(); auto prior_insert_point = ir_builder_->GetInsertPoint(); llvm::BasicBlock* exit_block = init_block->splitBasicBlock(output, "concat_merge"); ir_builder_->SetInsertPoint(init_block); init_block->getTerminator()->eraseFromParent(); for (int64 operand_idx = 0; operand_idx < hlo->operand_count(); ++operand_idx) { const HloInstruction* operand = hlo->operand(operand_idx); auto true_block = llvm_ir::CreateBasicBlock( exit_block, tensorflow::strings::StrCat( "concat_index_from_operand", operand_idx), ir_builder_); auto false_block = llvm_ir::CreateBasicBlock( exit_block, tensorflow::strings::StrCat( "concat_index_not_from_operand", operand_idx), ir_builder_); auto concat_dim_size = llvm::ConstantInt::get(source_index[concat_dim]->getType(), operand->shape().dimensions(concat_dim)); ir_builder_->CreateCondBr( ir_builder_->CreateICmpULT(source_index[concat_dim], concat_dim_size), true_block, false_block); // Create the terminator of the true block before calling operand // generators, because they require non-degenerate basic blocks. ir_builder_->SetInsertPoint( llvm::BranchInst::Create(exit_block, /*InsertAtEnd=*/true_block)); TF_ASSIGN_OR_RETURN(llvm::Value * value, operand_to_generator.at(operand)(source_index)); output->addIncoming(value, ir_builder_->GetInsertBlock()); // Subtract the size of the concat dimension of the current operand // from the source index. ir_builder_->SetInsertPoint(false_block); source_index[concat_dim] = ir_builder_->CreateSub(source_index[concat_dim], concat_dim_size); } ir_builder_->CreateUnreachable(); ir_builder_->SetInsertPoint(exit_block, prior_insert_point); return output; }; case HloOpcode::kReverse: return [this, hlo, &operand_to_generator]( const IrArray::Index& target_index) -> StatusOr<llvm::Value*> { const HloInstruction* operand = hlo->operand(0); auto source_index = target_index; for (int64 dim : hlo->dimensions()) { source_index[dim] = ir_builder_->CreateSub( llvm::ConstantInt::get(target_index[dim]->getType(), hlo->shape().dimensions(dim) - 1), target_index[dim]); } return operand_to_generator.at(operand)(source_index); }; case HloOpcode::kBroadcast: return [this, hlo, &operand_to_generator]( const IrArray::Index& target_index) -> StatusOr<llvm::Value*> { // The `dimensions` member of the broadcast instruction maps from // input dimensions to output dimensions. const HloInstruction* operand = hlo->operand(0); int64 rank = ShapeUtil::Rank(operand->shape()); IrArray::Index source_index(rank); for (int64 i = 0; i < rank; ++i) { source_index[i] = target_index[hlo->dimensions(i)]; } return operand_to_generator.at(operand)(source_index); }; case HloOpcode::kSlice: return [this, hlo, &operand_to_generator]( const IrArray::Index& index) -> StatusOr<llvm::Value*> { IrArray::Index sliced_index(index.size()); for (int i = 0; i < index.size(); ++i) { int64 stride = hlo->slice_stride(i); if (stride != 1) { sliced_index[i] = ir_builder_->CreateAdd( ir_builder_->CreateMul( index[i], llvm::ConstantInt::get(index[i]->getType(), stride)), llvm::ConstantInt::get(index[i]->getType(), hlo->slice_starts(i))); } else { sliced_index[i] = ir_builder_->CreateAdd( index[i], llvm::ConstantInt::get(index[i]->getType(), hlo->slice_starts(i))); } } return operand_to_generator.at(hlo->operand(0))(sliced_index); }; case HloOpcode::kDynamicSlice: return [this, hlo, &operand_to_generator]( const IrArray::Index& index) -> StatusOr<llvm::Value*> { // Emit IR to read dynamic start indices from hlo->operand(1). const HloInstruction* input_hlo = hlo->operand(0); const int64 rank = ShapeUtil::Rank(input_hlo->shape()); llvm_ir::IrArray::Index slice_start_index(rank); for (int64 i = 0; i < rank; ++i) { llvm_ir::IrArray::Index dim_index(1, ir_builder_->getInt64(i)); TF_ASSIGN_OR_RETURN( llvm::Value * start_index_value, operand_to_generator.at(hlo->operand(1))(dim_index)); slice_start_index[i] = start_index_value; } llvm_ir::IrArray::Index input_index(rank); for (int64 i = 0; i < rank; ++i) { // Emit IR which computes: // input_index = (start_index + offset_index) % dim_size // Security note: this is the code that keeps the indices in-bounds. llvm::Value* dim_size = llvm::ConstantInt::get( index[i]->getType(), input_hlo->shape().dimensions(i)); llvm::Value* start_index = ir_builder_->CreateZExtOrBitCast( slice_start_index[i], index[i]->getType()); input_index[i] = ir_builder_->CreateURem( ir_builder_->CreateAdd(start_index, index[i]), dim_size); } return operand_to_generator.at(input_hlo)(input_index); }; case HloOpcode::kDynamicUpdateSlice: return [this, hlo, &operand_to_generator]( const IrArray::Index& index) -> StatusOr<llvm::Value*> { const HloInstruction* input_hlo = hlo->operand(0); const HloInstruction* update_hlo = hlo->operand(1); const HloInstruction* start_hlo = hlo->operand(2); // Calculate slice start/end indices. const int64 rank = ShapeUtil::Rank(input_hlo->shape()); llvm_ir::IrArray::Index slice_start_index(rank); llvm_ir::IrArray::Index slice_limit_index(rank); for (int64 i = 0; i < rank; ++i) { // Emit IR to read dynamic start indices from 'start_hlo'. llvm_ir::IrArray::Index dim_index(1, ir_builder_->getInt64(i)); TF_ASSIGN_OR_RETURN(llvm::Value * start_index_value, operand_to_generator.at(start_hlo)(dim_index)); slice_start_index[i] = ir_builder_->CreateZExtOrBitCast( start_index_value, index[i]->getType()); // Emit IR to compute: slice_limit_index = start_index + update_dim // NOTE: Although 'start_indices' is dynamic and could be // out-of-range, we do not compute 'slice_limit_index' mod input dim // size here, because subsequent array index calculations will be // computed mod input dim size for safety. llvm::Value* update_dim_size = llvm::ConstantInt::get( index[i]->getType(), update_hlo->shape().dimensions(i)); slice_limit_index[i] = ir_builder_->CreateAdd(slice_start_index[i], update_dim_size); } // Check if 'index' intersects start/end indices. llvm::Value* slice_intersection = llvm::ConstantInt::get(ir_builder_->getInt1Ty(), 1); for (int64 i = 0; i < rank; ++i) { // Check that index[i] >= slice_start_index[i]. slice_intersection = ir_builder_->CreateAnd( slice_intersection, ir_builder_->CreateICmpSGE(index[i], slice_start_index[i]), "slice_intersection"); // Check that index[i] < slice_limit_index[i]. slice_intersection = ir_builder_->CreateAnd( slice_intersection, ir_builder_->CreateICmpSLT(index[i], slice_limit_index[i]), "slice_intersection"); } // Emit: // if (slice_intersection) -> return data from 'update'. // else -> return data from 'index'. llvm::Value* ret_value_addr = llvm_ir::EmitAllocaAtFunctionEntry( llvm_ir::PrimitiveTypeToIrType(hlo->shape().element_type(), ir_builder_), "ret_value_addr", ir_builder_); llvm_ir::LlvmIfData if_data = llvm_ir::EmitIfThenElse( slice_intersection, "slice_intersection", ir_builder_); // Handle true BB. SetToFirstInsertPoint(if_data.true_block, ir_builder_); // Compute update index for intersection case. llvm_ir::IrArray::Index update_index(rank); for (int64 i = 0; i < rank; ++i) { llvm::Value* update_dim_size = llvm::ConstantInt::get( index[i]->getType(), update_hlo->shape().dimensions(i)); // NOTE: Subtraction will be positive due to bounds checking above. update_index[i] = ir_builder_->CreateURem( ir_builder_->CreateSub(index[i], slice_start_index[i]), update_dim_size); } TF_ASSIGN_OR_RETURN(llvm::Value * true_value, operand_to_generator.at(update_hlo)(update_index)); ir_builder_->CreateStore(true_value, ret_value_addr); // Handle false BB. SetToFirstInsertPoint(if_data.false_block, ir_builder_); TF_ASSIGN_OR_RETURN(llvm::Value * false_value, operand_to_generator.at(input_hlo)(index)); ir_builder_->CreateStore(false_value, ret_value_addr); SetToFirstInsertPoint(if_data.after_block, ir_builder_); return ir_builder_->CreateLoad(ret_value_addr); }; case HloOpcode::kReshape: CHECK_EQ(ShapeUtil::ElementsIn(hlo->shape()), ShapeUtil::ElementsIn(hlo->operand(0)->shape())); return [this, hlo, &operand_to_generator](const IrArray::Index& index) { const HloInstruction* operand = hlo->operand(0); return operand_to_generator.at(operand)(index.SourceIndexOfReshape( hlo->shape(), operand->shape(), ir_builder_)); }; case HloOpcode::kTranspose: return [this, hlo, &operand_to_generator](const IrArray::Index& target_index) { return operand_to_generator.at(hlo->operand(0))( target_index.SourceIndexOfTranspose( hlo->shape(), hlo->operand(0)->shape(), hlo->dimensions(), ir_builder_)); }; case HloOpcode::kRng: return MakeRngElementGenerator(hlo, operand_to_generator); case HloOpcode::kPad: return [=, &operand_to_generator]( const IrArray::Index& padded_index) -> StatusOr<llvm::Value*> { auto index = padded_index; llvm::Value* in_bounds = ir_builder_->getTrue(); for (size_t i = 0; i < index.size(); ++i) { auto index_typed_const = [=](int64 n) { return llvm::ConstantInt::get(index[i]->getType(), n); }; const auto& pad_dim = hlo->padding_config().dimensions(i); index[i] = ir_builder_->CreateSub( index[i], index_typed_const(pad_dim.edge_padding_low())); in_bounds = ir_builder_->CreateAnd( in_bounds, ir_builder_->CreateICmpSGE(index[i], index_typed_const(0)), "in_bounds"); in_bounds = ir_builder_->CreateAnd( in_bounds, ir_builder_->CreateICmpEQ( index_typed_const(0), ir_builder_->CreateURem( index[i], index_typed_const(pad_dim.interior_padding() + 1))), "in_bounds"); index[i] = ir_builder_->CreateSDiv( index[i], index_typed_const(pad_dim.interior_padding() + 1)); in_bounds = ir_builder_->CreateAnd( in_bounds, ir_builder_->CreateICmpSLT( index[i], index_typed_const(hlo->operand(0)->shape().dimensions(i))), "in_bounds"); } // if (in_bounds) { // ret_value = operand0[index]; // source // } else { // ret_value = *operand1; // padding // } llvm::Value* ret_value_addr = llvm_ir::EmitAllocaAtFunctionEntry( llvm_ir::PrimitiveTypeToIrType(hlo->shape().element_type(), ir_builder_), "pad_result_addr", ir_builder_); llvm_ir::LlvmIfData if_data = llvm_ir::EmitIfThenElse(in_bounds, "in_bounds", ir_builder_); SetToFirstInsertPoint(if_data.true_block, ir_builder_); TF_ASSIGN_OR_RETURN(llvm::Value * operand_value, operand_to_generator.at(hlo->operand(0))(index)); ir_builder_->CreateStore(operand_value, ret_value_addr); SetToFirstInsertPoint(if_data.false_block, ir_builder_); TF_ASSIGN_OR_RETURN(llvm::Value * padding_value, operand_to_generator.at(hlo->operand(1))({})); ir_builder_->CreateStore(padding_value, ret_value_addr); SetToFirstInsertPoint(if_data.after_block, ir_builder_); // Don't create phi(operand_value, padding_value) here, because invoking // operand_to_generator may create new basic blocks, making the parent // of operand_value or padding_value no longer a predecessor of // if_data.after_block. return ir_builder_->CreateLoad(ret_value_addr); }; default: return [this, hlo, &operand_to_generator](const IrArray::Index& index) { return Unimplemented("%s", HloOpcodeString(hlo->opcode()).c_str()); }; } } } // namespace xla
{ "content_hash": "8ed76aebb18aafc648386ec4549a3047", "timestamp": "", "source": "github", "line_count": 1011, "max_line_length": 80, "avg_line_length": 45.31256181998022, "alnum_prop": 0.5846630721879025, "repo_name": "benoitsteiner/tensorflow", "id": "be4aadb6522b8d6ad9d6425df56c1746c3849f11", "size": "46479", "binary": false, "copies": "3", "ref": "refs/heads/master", "path": "tensorflow/compiler/xla/service/elemental_ir_emitter.cc", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Batchfile", "bytes": "7666" }, { "name": "C", "bytes": "186881" }, { "name": "C++", "bytes": "25687793" }, { "name": "CMake", "bytes": "171016" }, { "name": "Go", "bytes": "896024" }, { "name": "HTML", "bytes": "609802" }, { "name": "Java", "bytes": "338088" }, { "name": "JavaScript", "bytes": "1399" }, { "name": "Jupyter Notebook", "bytes": "1833659" }, { "name": "LLVM", "bytes": "6536" }, { "name": "Makefile", "bytes": "37393" }, { "name": "Objective-C", "bytes": "7056" }, { "name": "Objective-C++", "bytes": "63700" }, { "name": "Protocol Buffer", "bytes": "235179" }, { "name": "PureBasic", "bytes": "24932" }, { "name": "Python", "bytes": "22443846" }, { "name": "Ruby", "bytes": "327" }, { "name": "Shell", "bytes": "338730" }, { "name": "TypeScript", "bytes": "805273" } ], "symlink_target": "" }
require 'spec_helper' describe PersonMock do it "can chain ActiveRecord query methods" do PersonMock.all.joins(:any).where(:any).where(:more).limit(10).order(:id).should be PersonMock end end
{ "content_hash": "c9fba1763107a0060fef5f89d63789fc", "timestamp": "", "source": "github", "line_count": 8, "max_line_length": 97, "avg_line_length": 25.25, "alnum_prop": 0.7376237623762376, "repo_name": "padwasabimasala/lou", "id": "3ed09f293015ff23015023b6c8dd6d3017e4caa2", "size": "202", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "spec/person_mock_spec.rb", "mode": "33188", "license": "mit", "language": [ { "name": "Ruby", "bytes": "19510" } ], "symlink_target": "" }
/* Network.js KC3改 Network Listener Must only be imported on devtools pages! Listens to network history and triggers callback if game events happen */ (function(){ "use strict"; window.KC3Network = { hasOverlay: false, isNextBlockerArmed: false, isNextBlockerNetworkFallback: false, isNextBlockerLarger: false, lastUrl: "", eventTypes : { GameStart: [], CatBomb: [], APIError: [], Bomb201: [], ModalBox: [], GameUpdate: [], DebuffNotify: [], HomeScreen: [], HQ: [], Consumables: [], ShipSlots: [], GearSlots: [], Timers: [], QuestList: [], Quests: [], Fleet: [], Lbas: [], SortieStart: [], CompassResult: [], LandBaseAirRaid: [], BattleStart: [], BattleNight: [], BattleResult: [], CraftGear: [], CraftShip: [], Modernize: [], ClearedMap: [], PvPList: [], PvPFleet: [], PvPStart: [], PvPNight: [], PvPEnd: [], ExpeditionSelection: [], ExpeditionStart: [], ExpedResult: [], GunFit: [], GearRemodelList: [], GearRemodelDetail: [], GearRemodel: [], }, delayedUpdate: {}, deferredEvents: [], battleEvent: { entered: false, time: undefined, identifier: undefined, resultRecieved: false, }, submissionModuleNames: ["PoiDBSubmission", "TsunDBSubmission"], submissionConfigs: {}, /* ADD LISTENER All callback to an event ------------------------------------------*/ addListener : function( eventName, callback ){ this.eventTypes[eventName].push(callback); }, /* ADD GLOBAL LISTENER All callback to all events ------------------------------------------*/ addGlobalListener : function( callback ){ $.each(this.eventTypes, function( eventType, eventCallbacks ){ eventCallbacks.push( callback ); }); }, /* TRIGGER Execute subscribed callbacks to an event ------------------------------------------*/ trigger : function( eventName, data ){ if((this.delayedUpdate[eventName] || 0) <= 0) { $.each(this.eventTypes[eventName], function( index, callback ){ callback( eventName, data || {}); }); this.delayedUpdate[eventName] = 0; } else { this.delayedUpdate[eventName] -= 1; console.log(`Prevented to call [${eventName}], delay ${this.delayedUpdate[eventName]} left`); } }, /* DEFER TRIGGER Defers event performing after specified amount of API calls ------------------------------------------*/ deferTrigger : function(count, eventName, data){ // Only allow `after` API call advice for now, // `before` and `around` seem not useful yet. const advice = "after"; // +1 if not before since it will be handled at once after current API call const amount = count + (advice !== "before" ? 1 : 0); this.deferredEvents.push({ advice: advice, amount: amount, name: eventName, data: data }); //console.log(`Deferred to call [${eventName}] after ${count} time(s)`); }, /* DELAY Prevents event performing ------------------------------------------*/ delay : function(){ var self = this; var amount = Array.prototype.shift.apply(arguments); $.each(arguments, function( i,eventName ){ self.delayedUpdate[eventName] = amount; }); }, /* LISTEN Start listening and define callback ------------------------------------------*/ listen :function(){ // Call Chrome API to start listening chrome.devtools.network.onRequestFinished.addListener(this.received); }, /* INIT CONFIGS Store and listen to the changes of used config values ------------------------------------------*/ initConfigs :function(){ ConfigManager.loadIfNecessary(); // Initial config values const configSuffix = "_enabled"; this.submissionModuleNames.forEach(name => { this.submissionConfigs[name] = ConfigManager[name + configSuffix]; }); const configChangedListener = ({key, timeStamp, url}) => { if(key === ConfigManager.keyName()) { const newConfigs = localStorage.getObject(ConfigManager.keyName()); this.submissionModuleNames.forEach(name => { if(this.submissionConfigs[name] !== newConfigs[name + configSuffix]) { const isToCleanup = !this.submissionConfigs[name] && !!newConfigs[name + configSuffix]; this.submissionConfigs[name] = newConfigs[name + configSuffix]; // Clean previous states if config is changed from disabled to enabled, // because it is buggy especially on config changed during sortie. const submission = window[name], cleanMethod = submission && submission.cleanup, isAbleToCleanup = isToCleanup && typeof cleanMethod === "function"; console.log(`${name} enabled changed to ${this.submissionConfigs[name]}${isAbleToCleanup ? ", cleaning previous states..." : ""}`); if(isAbleToCleanup) { try { cleanMethod.call(submission); } catch (error) { console.warn("Uncaught states cleanup", error); } } } }); // Do not need to reload here, because it has been already listened and updated in theme scripts //ConfigManager.load(); } }; // Do not try to call this multiple times, otherwise this is needed: //window.removeEventListener("storage", configChangeListener); // Listen to the changes of local storage configs window.addEventListener("storage", configChangedListener); }, /* RECEIVED Fired when we receive network entry Inside, use "KC3Network" instead of "this" It's a callback so "this" is in the context of the chrome listener Argument HAR see: https://developer.chrome.com/extensions/devtools_network#type-Request ------------------------------------------*/ received : function(har){ const requestUrl = har.request.url; // If request is an API Call if(requestUrl.indexOf("/kcsapi/") > -1){ KC3Network.lastUrl = requestUrl; // Clear overlays before processing this new API call KC3Network.clearOverlays(); // Create new request and process it // console.debug(request, request.request); var thisRequest = new KC3Request(har), message = { tabId: chrome.devtools.inspectedWindow.tabId, message_id: "goodResponses", tcp_status: har.response.status, api_status: undefined, api_result: "他のリクエストが成功!", }; if(thisRequest.validateHeaders()){ thisRequest.readResponse(har, function(){ if(thisRequest.validateData()){ // Invoke remote DB submission modules KC3Network.submissionModuleNames.forEach(name => { if(KC3Network.submissionConfigs[name]) { // Assume module already loaded globally KC3Network.asyncSubmit(window[name], thisRequest, name); } }); // Trigger deferred events before this API call if there are some //KC3Network.handleDeferredEvents(thisRequest, "before"); // Reset battle event before any valided API call KC3Network.setBattleEvent(false); thisRequest.process(); // Trigger deferred events after this API call if there are some KC3Network.handleDeferredEvents(thisRequest, "after"); } }); har.getContent(function(x){ try { var data = JSON.parse(/^[\s\S]*svdata=(.+)$/.exec(x)[1]); message.api_status = data.api_result; message.api_result = data.api_result_msg; } catch (e) { // Only prevent the data parsing error message.api_status = e.name; message.api_result = e.message; console.warn("Prevented unhandled", e); } finally { (new RMsg("service", "gameScreenChg", message)).execute(); } }); } else { message.api_status = false; message.api_result = har.response.statusText; (new RMsg("service", "gameScreenChg", message)).execute(); } // When a sortie begins, assume fallback until we know SE isn't muted if(requestUrl.endsWith("/api_req_map/start")){ KC3Network.isNextBlockerNetworkFallback = true; } } // If request is a furniture asset if(requestUrl.includes("/img/interior/interior_parts")){ // Clear overlays upon entering furniture menu, // not work everytime since Phase 2 caches assets KC3Network.clearOverlays(); } // Node 'sonar ping' sound should always be heard before a battle if SE is on; // Will allow us to determine whether SE is muted for the next blocker if(requestUrl.includes("/resources/se/252.")) { KC3Network.isNextBlockerNetworkFallback = false; } // If it's switching to NextNode or Yasen screen (might be others?) if(requestUrl.includes("/resources/se/217.") && ConfigManager.next_blocker === 1){ KC3Network.triggerNextBlock(undefined, true); } // If request is a sound effect of closing shutter animation on battle ended, // to activiate and focus on game tab before battle result API call, // it only works if in-game SE is not completely off. // Also, to trigger when first taiha/chuuha CG cutin occurs, as game may be paused if in background tab // battle_cutin_damage requested only once per battle (but not sortie) const focusPaths = ["/resources/se/217.", "img/battle/battle_cutin_damage.json"]; if(ConfigManager.focus_game_tab && KC3Network.battleEvent.entered // Only after: daytime? day / night to day? night start? // seems no side effect if game tab already focused, so use any time for now //&& KC3Network.battleEvent.time === "day" && focusPaths.some(path => requestUrl.includes(path))){ (new RMsg("service", "focusGameTab", { tabId: chrome.devtools.inspectedWindow.tabId })).execute(); // console.debug("Battle end SE detected, focus on game tab requested"); } // Try to detect gadget server HTTP 403 error if(requestUrl.includes("/203.104.209.7/gadget_html5/js/") && har.response.status == 403){ console.warn("Gadget server block detected", har.serverIPAddress, har.request, har.response); // Ensure panel display activiated from waiting homeport KC3Network.trigger("GameStart"); KC3Network.trigger("CatBomb", { title: KC3Meta.term("CatBombRegionalBlockTitle"), message: KC3Meta.term("CatBombRegionalBlockMsg"), }); } // Overlay subtitles KC3Network.showSubtitle(har); }, /** * Set some state attributes for tracking events of game battle. */ setBattleEvent :function(isEntered = false, time = undefined, identifier = undefined, isResultReceived = false){ this.battleEvent.entered = isEntered; this.battleEvent.time = time; this.battleEvent.identifier = identifier; this.battleEvent.resultRecieved = isResultReceived; }, /** * Call those events deferred by specified API call amount on specified advice. */ handleDeferredEvents :function(request, advice){ if(!this.deferredEvents.length) { return false; } // Check the event queue if advice is matched const eventsToHandle = this.deferredEvents .filter(e => (e.advice === advice || e.advice === "around") && e.amount > 0); let eventTriggered = 0; eventsToHandle.forEach(e => { // Avoid to reduce API call count duplicatedly if advice is around if(e.advice !== "around" || (e.advice === "around" && advice === "before")) { e.amount -= 1; } if(e.amount <= 0) { // Remove the event already triggered from queue const index = this.deferredEvents.indexOf(e); if(index >= 0) { this.deferredEvents.splice(index, 1); } // Only trigger the event on first time countdown reaches if(e.amount === 0) { this.trigger(e.name, e.data); console.log(`Deferred event [${e.name}] called on [${request.call}]`, e); eventTriggered += 1; } } else { console.log(`Deferred event [${e.name}], ${e.amount} left on [${request.call}]`); } }); // Indicate if there is an event triggered at least return eventTriggered > 0; }, /** * Asynchronously invoke a remote DB submission module to submit KCSAPI request data. */ asyncSubmit :function(submission, request, moduleName){ // turns out "Request.process()" modifies the request, so clone the unmodified instance first. var clonedRequest = $.extend(true, new KC3Request(), request); // although submission processes should not be slow, still make them parallel async. setTimeout(function(){ try { //console.log(`Processing data via ${moduleName}...`); submission.processData.call(submission, clonedRequest); } catch (error) { // suppose all exceptions thrown are caught already, should not reach here. console.warn(`Uncaught data submission to ${moduleName}`, error); } }, 0); }, /** * Send a message to content script (via background script service) * to show subtitles at overlay for supported sound audio files. */ showSubtitle :function(har){ // url sample: http://203.104.209.39/kcs/sound/kcdbtrdgatxdpl/178798.mp3?version=5 // http://203.104.209.39/kcs2/resources/voice/titlecall_1/050.mp3 const requestUrl = har.request.url; const isV2Voice = requestUrl.includes("/kcs2/resources/voice/"); if(!(isV2Voice || requestUrl.includes("/kcs/sound/"))) { return; } const soundPaths = requestUrl.split("/"); const voiceType = soundPaths[isV2Voice ? 6 : 5]; switch(voiceType) { case "titlecall": // console.debug("DETECTED titlecall sound"); (new RMsg("service", "subtitle", { voicetype: "titlecall", fullurl: requestUrl, filename: soundPaths[6], voiceNum: soundPaths[7].split(".")[0], tabId: chrome.devtools.inspectedWindow.tabId })).execute(); break; case "titlecall_1": case "titlecall_2": // console.debug("DETECTED kcs2 titlecall sound"); (new RMsg("service", "subtitle", { voicetype: "titlecall", fullurl: requestUrl, filename: voiceType.split("_")[1], voiceNum: soundPaths[7].split(".")[0], tabId: chrome.devtools.inspectedWindow.tabId })).execute(); break; case "tutorial": // Ignore this for now break; case "kc9997": // console.debug("DETECTED Event special sound", soundPaths); (new RMsg("service", "subtitle", { voicetype: "event", fullurl: requestUrl, filename: "", voiceNum: soundPaths[6].split(".")[0], voiceSize: har.response.content.size || 0, tabId: chrome.devtools.inspectedWindow.tabId })).execute(); break; case "kc9998": // console.debug("DETECTED Abyssal sound", soundPaths); (new RMsg("service", "subtitle", { voicetype: "abyssal", fullurl: requestUrl, filename: "", voiceNum: soundPaths[6].split(".")[0], voiceSize: har.response.content.size || 0, tabId: chrome.devtools.inspectedWindow.tabId })).execute(); break; case "kc9999": // console.debug("DETECTED NPC sound", soundPaths); (new RMsg("service", "subtitle", { voicetype: "npc", fullurl: requestUrl, filename: "", voiceNum: soundPaths[6].split(".")[0], tabId: chrome.devtools.inspectedWindow.tabId })).execute(); break; default: // console.debug("DETECTED shipgirl sound"); const shipGirl = KC3Master.graph_file(soundPaths[5].substring(2)); const voiceLine = KC3Meta.getVoiceLineByFilename(shipGirl, soundPaths[6].split(".")[0]); const audioFileSize = har.response.content.size || 0; (new RMsg("service", "subtitle", { voicetype: "shipgirl", fullurl: requestUrl, shipID: shipGirl, voiceNum: voiceLine, voiceSize: audioFileSize, tabId: chrome.devtools.inspectedWindow.tabId })).execute(); } }, /* NEXT BLOCK TRIGGER signals to game tab that next button blocking overlay needs to be shown triggered either by network request to results or SE network request -------------------------------------------------------*/ triggerNextBlock: function({ effectiveTaihaFlag, isDameconDecision } = {}, bySE = false) { if(typeof effectiveTaihaFlag === "boolean") { /* For every time it checks HP predictions. * If any ship predicted to be in Taiha, it arms locker in game page preventing player from advancing into next node. * TODO cases like 1-6, where next node is end node without battle and it is safe to advance. * TODO get FCF info and find a method to delay blocker after denying FCF decision screen. */ this.isNextBlockerArmed = effectiveTaihaFlag; } // Cache flagship damecon use decision screen flag, enlarge blocker area to block 2 large buttons on the left if true. if(typeof isDameconDecision === "boolean") { this.isNextBlockerLarger = isDameconDecision; } let toShowNextBlock = false; if (ConfigManager.next_blocker > 0 && this.isNextBlockerArmed) { if (bySE) { if (this.battleEvent.resultRecieved) { toShowNextBlock = true; } else { // battle result wasn't recieved, it must be yasen switch? do nothing. } } else { if (ConfigManager.next_blocker === 2 || this.isNextBlockerNetworkFallback) { // not from SE check or setting selected api check, // start showing block from fleets result and drop screen. toShowNextBlock = true; } else { // se/217.mp3 might fire twice. once for yasen and once for next node, // this flag prevents blocking until result data actually recieved. // if player wants it through sound warnings we must signal that we got result to distinguish it from yasen switch. // this flag has been already set by #setBattleEvent, here just a duplication. this.battleEvent.resultRecieved = true; } } } if (toShowNextBlock) { this.hasOverlay = true; (new RMsg("service", "showNextBlock", { tabId: chrome.devtools.inspectedWindow.tabId, fairy: bySE, large: this.isNextBlockerLarger, })).execute(); } }, /* Disarms Next Node Blocker */ disarmNextBlock :function(){ this.isNextBlockerArmed = false; this.isNextBlockerLarger = false; this.setBattleEvent(false); this.clearOverlays(); }, /* CLEAR OVERLAYS Ask background page to forward a message to play screen. Requests to remove existing HTML on-screen overlays ------------------------------------------*/ clearOverlays :function(){ if(this.hasOverlay) { this.hasOverlay = false; (new RMsg("service", "clearOverlays", { tabId: chrome.devtools.inspectedWindow.tabId })).execute(); } } }; })();
{ "content_hash": "2d17955e393ad6960cda7313b0d74eb1", "timestamp": "", "source": "github", "line_count": 514, "max_line_length": 138, "avg_line_length": 36.8715953307393, "alnum_prop": 0.6270578303081469, "repo_name": "KC3Kai/KC3Kai", "id": "53950c6df033dc35a5c9eab9018579128e93162c", "size": "18976", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/library/modules/Network.js", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "736159" }, { "name": "HTML", "bytes": "613776" }, { "name": "JavaScript", "bytes": "4240263" }, { "name": "Perl", "bytes": "969" } ], "symlink_target": "" }
using System.Drawing; using FoxTrader.UI.ControlInternal; using OpenTK.Input; using static FoxTrader.Constants; namespace FoxTrader.UI.Control { /// <summary>Menu item</summary> internal class MenuItem : Button { private Label m_accelerator; private bool m_checked; private Menu m_menu; private GameControl m_submenuArrow; /// <summary>Initializes a new instance of the <see cref="MenuItem" /> class</summary> /// <param name="c_parentControl">Parent control</param> public MenuItem(GameControl c_parentControl) : base(c_parentControl) { IsOnStrip = false; IsTabable = false; IsCheckable = false; IsChecked = false; m_accelerator = new Label(this); } /// <summary>Indicates whether the item is on a menu strip</summary> public bool IsOnStrip { get; set; } /// <summary>Determines if the menu item is checkable</summary> public bool IsCheckable { get; set; } /// <summary>Indicates if the parent menu is open</summary> public bool IsMenuOpen { get { if (m_menu == null) { return false; } return !m_menu.IsHidden; } } /// <summary>Gets or sets the check value</summary> public bool IsChecked { get { return m_checked; } set { if (value == m_checked) { return; } m_checked = value; if (CheckChanged != null) { CheckChanged.Invoke(this); } if (value) { if (Checked != null) { Checked.Invoke(this); } } else { if (UnChecked != null) { UnChecked.Invoke(this); } } } } /// <summary>Gets the parent menu</summary> public Menu Menu { get { if (null == m_menu) { m_menu = new Menu(GetCanvas()); m_menu.IsHidden = true; if (!IsOnStrip) { if (m_submenuArrow != null) { m_submenuArrow.Dispose(); } m_submenuArrow = new RightArrow(this); m_submenuArrow.SetSize(15, 15); } Invalidate(); } return m_menu; } } /// <summary>Invoked when the item is selected</summary> public event GameControlEventHandler Selected; /// <summary>Invoked when the item is checked</summary> public event CheckBoxEventHandler Checked; /// <summary>Invoked when the item is unchecked</summary> public event CheckBoxEventHandler UnChecked; /// <summary>Invoked when the item's check value is changed</summary> public event CheckBoxEventHandler CheckChanged; /// <summary>Renders the control using specified skin</summary> /// <param name="c_skin">Skin to use</param> protected override void Render(Skin c_skin) { c_skin.DrawMenuItem(this, IsMenuOpen, IsCheckable ? m_checked : false); RenderText(c_skin.Renderer); } /// <summary>Lays out the control's interior according to alignment, padding, dock etc</summary> /// <param name="c_skin">Skin to use</param> protected override void OnLayout(Skin c_skin) { if (m_submenuArrow != null) { m_submenuArrow.SetRelativePosition(Pos.Right | Pos.CenterV, 4, 0); } base.OnLayout(c_skin); } /// <summary>Internal OnPressed implementation</summary> public override void OnClicked(MouseButtonEventArgs c_mouseButtonEventArgs) { if (m_menu != null) { ToggleMenu(); } else if (!IsOnStrip) { IsChecked = !IsChecked; Selected?.Invoke(this); GetCanvas().CloseMenus(); } base.OnClicked(c_mouseButtonEventArgs); } /// <summary>Toggles the menu open state</summary> public void ToggleMenu() { if (IsMenuOpen) { CloseMenu(); } else { OpenMenu(); } } /// <summary>Opens the menu</summary> public void OpenMenu() { if (null == m_menu) { return; } m_menu.IsHidden = false; m_menu.BringToFront(); var a_p = LocalPosToCanvas(Point.Empty); // Strip menus open downwards if (IsOnStrip) { m_menu.SetPosition(a_p.X, a_p.Y + Height + 1); } // Submenus open sidewards else { m_menu.SetPosition(a_p.X + Width, a_p.Y); } // TODO: Option this. // TODO: Make sure on screen, open the other side of the // parent if it's better... } /// <summary>Closes the menu</summary> public void CloseMenu() { if (null == m_menu) { return; } m_menu.Close(); m_menu.CloseAll(); } public override void SizeToContents() { base.SizeToContents(); if (m_accelerator != null) { m_accelerator.SizeToContents(); Width = Width + m_accelerator.Width; } } public MenuItem SetAction(GameControlEventHandler c_handler) { if (m_accelerator != null) { AddAccelerator(m_accelerator.Text, c_handler); } Selected += c_handler; return this; } public void SetAccelerator(string c_acc) { if (m_accelerator != null) { //m_Accelerator.DelayedDelete(); // to prevent double disposing m_accelerator = null; } if (c_acc == string.Empty) { return; } m_accelerator = new Label(this); m_accelerator.Dock = Pos.Right; m_accelerator.Alignment = Pos.Right | Pos.CenterV; m_accelerator.Text = c_acc; m_accelerator.Margin = new Margin(0, 0, 16, 0); } } }
{ "content_hash": "20afdd3b1b0512f2f37b5eceee6fa977", "timestamp": "", "source": "github", "line_count": 262, "max_line_length": 104, "avg_line_length": 27.519083969465647, "alnum_prop": 0.44826629680998614, "repo_name": "FoxCouncil/FoxTrader", "id": "053f21d39389eb944ca61b0714796253045b5ee5", "size": "7210", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "FoxTrader/UI/Control/MenuItem.cs", "mode": "33188", "license": "mit", "language": [ { "name": "C#", "bytes": "688037" } ], "symlink_target": "" }
ACCEPTED #### According to International Plant Names Index #### Published in null #### Original name null ### Remarks null
{ "content_hash": "6670803ad28d38b38f9368cc8035cf3c", "timestamp": "", "source": "github", "line_count": 13, "max_line_length": 31, "avg_line_length": 9.692307692307692, "alnum_prop": 0.7063492063492064, "repo_name": "mdoering/backbone", "id": "6be97d0ed170a555da3ecb4fe6d64677e9430c45", "size": "175", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "life/Plantae/Magnoliophyta/Liliopsida/Poales/Poaceae/Koeleria/Koeleria domini/README.md", "mode": "33188", "license": "apache-2.0", "language": [], "symlink_target": "" }
from setuptools import setup def readme(): with open('README.rst') as f: return f.read() setup(name='oeis', version='0.1', description='OEIS utilities and sequence generation', long_description=readme(), classifiers=[ 'Programming Language :: Python :: 2.7.3', ], keywords='oeis', url='https://github.com/GuySrinivasan/oeis', author='Guy Srinivasan', author_email='srinivgp@gmail.com', license='MIT', packages=['oeis'], install_requires=[ 'markdown', ], test_suite='nose.collector', tests_require=['nose'], scripts=['scripts/print-factorials'], zip_safe=False)
{ "content_hash": "1ba677ae98548f5a92851122c06fc0b5", "timestamp": "", "source": "github", "line_count": 28, "max_line_length": 59, "avg_line_length": 25.107142857142858, "alnum_prop": 0.5803698435277382, "repo_name": "GuySrinivasan/oeis", "id": "7c794f9e2339589a161df8c62ca1720302cab9e1", "size": "703", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "setup.py", "mode": "33188", "license": "mit", "language": [ { "name": "Python", "bytes": "456" } ], "symlink_target": "" }
var gridOptions = { columnDefs: [ { field: 'country', rowGroup: true, hide: true }, { field: 'athlete' }, { field: 'year' }, { field: 'gold', aggFunc: 'sum' }, { field: 'silver', aggFunc: 'sum' }, { field: 'bronze', aggFunc: 'sum' }, { field: 'total', aggFunc: 'sum' }, { field: 'age' }, { field: 'date' }, { field: 'sport' }, ], defaultColDef: { flex: 1, minWidth: 150, resizable: true, }, autoGroupColumnDef: { headerName: 'Country', minWidth: 300, }, animateRows: true, showOpenedGroup: true }; // setup the grid after the page has finished loading document.addEventListener('DOMContentLoaded', function() { var gridDiv = document.querySelector('#myGrid'); new agGrid.Grid(gridDiv, gridOptions); agGrid.simpleHttpRequest({ url: 'https://www.ag-grid.com/example-assets/olympic-winners.json' }) .then(function(data) { gridOptions.api.setRowData(data); }); });
{ "content_hash": "c3b6beacb07d8a436930858cb589b058", "timestamp": "", "source": "github", "line_count": 36, "max_line_length": 100, "avg_line_length": 29.305555555555557, "alnum_prop": 0.5526066350710901, "repo_name": "ceolter/ag-grid", "id": "99b2efb95b83d517d6da3a27ce99c28bbb1a4d37", "size": "1055", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "grid-packages/ag-grid-docs/documentation/doc-pages/grouping/examples/show-opened-group/main.js", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "37765" }, { "name": "JavaScript", "bytes": "22118" }, { "name": "TypeScript", "bytes": "1267988" } ], "symlink_target": "" }
from __future__ import unicode_literals from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('farmwork', '0008_auto_20170608_1217'), ] operations = [ migrations.CreateModel( name='Job', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('created', models.DateTimeField(auto_now_add=True)), ('modified', models.DateTimeField(auto_now=True)), ('role', models.CharField(max_length=50)), ('person', models.CharField(max_length=50)), ], options={ 'abstract': False, }, ), migrations.AlterField( model_name='farmwork', name='con_number', field=models.CharField(max_length=10), ), migrations.AlterField( model_name='farmwork', name='job_fruit', field=models.CharField(choices=[(None, '— Select fruit type -'), ('ap', 'Apples'), ('ar', 'Apricots'), ('as', 'Asparagus'), ('ba', 'Bananas'), ('bl', 'Blueberries'), ('br', 'Brocolli'), ('ca', 'Capsicums'), ('ch', 'Cherries'), ('cn', 'Chestnuts'), ('ci', 'Citrus'), ('co', 'Colliflower'), ('eg', 'Eggplant'), ('he', 'Herbs'), ('le', 'Lemons'), ('ly', 'Lychees'), ('ma', 'Mandarins'), ('mg', 'Mangoes'), ('me', 'Melons'), ('or', 'Oranges'), ('pe', 'Pears'), ('ra', 'Raspberries'), ('st', 'Strawberries'), ('ta', 'Tomatoes'), ('zu', 'Zuchinni')], max_length=2), ), migrations.AlterField( model_name='farmwork', name='slug', field=models.SlugField(unique=True), ), migrations.AddField( model_name='farmwork', name='get_job', field=models.ForeignKey(null=True, on_delete=django.db.models.deletion.CASCADE, to='farmwork.Job'), ), ]
{ "content_hash": "b1b09877be5325ef1f86517792be72e4", "timestamp": "", "source": "github", "line_count": 47, "max_line_length": 571, "avg_line_length": 42.765957446808514, "alnum_prop": 0.5308457711442786, "repo_name": "ianmilliken/rwf", "id": "88f1c0847242b2f8da02c2dba37226b135206a8e", "size": "2083", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "backend/apps/farmwork/migrations/0009_auto_20170618_1335.py", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "441558" }, { "name": "HTML", "bytes": "13521" }, { "name": "JavaScript", "bytes": "1036656" }, { "name": "Python", "bytes": "28122" } ], "symlink_target": "" }
<RaiseFault name='RF-InvalidRequest'> <IgnoreUnresolvedVariables>true</IgnoreUnresolvedVariables> <FaultResponse> <Set> <Payload contentType='application/json'>{ "error" : { "code" : 400.14, "message" : "missing query parameter: txid" } } </Payload> <StatusCode>400</StatusCode> <ReasonPhrase>Bad Request</ReasonPhrase> </Set> </FaultResponse> </RaiseFault>
{ "content_hash": "bc6e9c16d2d5d91617b12f20ba521112", "timestamp": "", "source": "github", "line_count": 16, "max_line_length": 61, "avg_line_length": 25.125, "alnum_prop": 0.6691542288557214, "repo_name": "DinoChiesa/devjam3-20170405", "id": "ec9c47e244c5c5f2322c5c89e1632feb0afe97e8", "size": "402", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "Resources/oauth2-ac/apiproxy/policies/RF-InvalidRequest.xml", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "4868" }, { "name": "HTML", "bytes": "9605" }, { "name": "JavaScript", "bytes": "76177" } ], "symlink_target": "" }
interface options { recurse?: boolean; duplicates?: boolean; filter?: any; mapKey?: any; mapValue?: any; } declare function requireDir(directory: string, options?: options): { [path: string]: any }; export = requireDir;
{ "content_hash": "5edece5d887e2c448e3d8f0d872436d6", "timestamp": "", "source": "github", "line_count": 11, "max_line_length": 91, "avg_line_length": 21.545454545454547, "alnum_prop": 0.6708860759493671, "repo_name": "AgentME/DefinitelyTyped", "id": "2792fe3914168c363d6be41b5bbe77f0dfa51558", "size": "450", "binary": false, "copies": "41", "ref": "refs/heads/master", "path": "types/require-dir/index.d.ts", "mode": "33188", "license": "mit", "language": [ { "name": "JavaScript", "bytes": "10652407" }, { "name": "Ruby", "bytes": "40" }, { "name": "Shell", "bytes": "60" }, { "name": "TypeScript", "bytes": "11370242" } ], "symlink_target": "" }
title: Clojure Lists They Are Everything --- Lists are fundamental to Clojure. Clojure is a Lisp, and Lisps were originally used for list processing. Everything in a Lisp is a list! (def foo "bar") That piece of code is actually a list! So is anything between two round brackets in Clojure. Interesting, isn't it? This is what makes Lisps so interesting - you can easily write code that generates new code, because generating code is as simple as making a list. ## Making an actual list The problem is, since everything is a list in Clojure, something like this will return an error: (1 2 3 4 5) ; => ClassCastException java.lang.Long cannot be cast to clojure.lang.IFn What a horrid error message. What the REPL is trying to tell us is, "1 is not a function, and it can't be made into one." Because everything in a Lisp is a list, the first item of any list is treated as a function, like `def`, `+` or `str`, so if we write `(1 2 3 4 5)`, it treats the first element (`1`) as a function, which it clearly isn't. We can solve this in two ways. One is using the `list` function to construct a list, like using `str` to concatenate strings together. (list 1 2 3 4 5) ; => (1 2 3 4 5) You can also use quoting. Quoting a list essentially says to the compiler that that list is _not_ a function call, and it shouldn't evaluate any of the code inside it. '(1 2 3 4 5) ; => (1 2 3 4 5) Interestingly, you can also quote function calls. This is how macros work. They're pretty complex, and deserve their own article, so we won't elaborate here. ;; Without a ' to quote it, this would return "foobarbaz". '(str "foo" "bar" "baz") ; => (str "foo" "bar" "baz") ![:rocket:](//forum.freecodecamp.com/images/emoji/emoji_one/rocket.png?v=2 ":rocket:") <a href='https://ideone.com/6c7UxY' target='_blank' rel='nofollow'>IDEOne it!</a> ## Adding to a list Lists are designed for prepending, rather than appending. There is no real way to append to a list. You can prepend to a list using `cons`. `conj` also works, but that's meant for vectors, and `cons` is faster for lists. (cons 1 '(2 3 4)) ; => (1 2 3 4) ## Retrieving from lists You retrieve items from lists using `nth`. `get` does not work on lists, because lists are designed for sequential access, rather than random access. Note that `nth` works on vectors, but is slower than `get` because of this. (nth '(1 2 3 4) 0) ; => 1 ## Converting other collections into lists The `list` function can't convert other collections into lists, because it tries to construct a list using the arguments it's given. Passing `list` a collection will return a list containing that collection. (list [1 2 3 4 5]) ; => ([1 2 3 4 5]) To convert to a list, use the `seq` function instead. (seq [1 2 3 4 5]) ; => (1 2 3 4 5) ## Lazy sequences Clojure has a brilliant feature called 'lazy sequences'. A lazy sequence is a list whose elements aren't generated until you refer to an element of the sequence later, at which point, it evaluates all the elements of the sequence up until the one you want. This allows you to construct "infinite" sequences! `range` is perhaps the most simple lazy sequence. It contains all numbers. (range 10) ; => (0 1 2 3 4 5 6 7 8 9) (range -5 5) ; => (-5 -4 -3 -2 -1 0 1 2 3 4) You can use lazy sequences to do really cool things, like generating a lazy sequence of all fibonacci numbers. (def fibs (lazy-cat [0 1] (map + (rest fibs) fibs))) (take 10 fibs) ;; this means, "evaluate the first 10 fibonacci numbers." ; => (0 1 1 2 3 5 8 13 21 34) This example is a bit advanced, and you shouldn't be expected to understand it if you're a beginner. It's just an example of something cool you can do with lazy sequences. Perhaps you can figure it out anyway! ![:rocket:](//forum.freecodecamp.com/images/emoji/emoji_one/rocket.png?v=2 ":rocket:") <a href='https://ideone.com/jwpvt8' target='_blank' rel='nofollow'>IDEOne it!</a> ## When to use a list? Using a vector is usually preferable to using a list, since there's no risk of the compiler accidentally evaluating a vector as a function, and it's faster to access arbitrary elements of a vector. Lists are most useful in 3 cases: * Generating code using a macro. * Generating "infinite" lazy sequences. * Prepending elements to a collection. | [![:point_left:](//forum.freecodecamp.com/images/emoji/emoji_one/point_left.png?v=2 ":point_left:") Previous](//forum.freecodecamp.com/t/clojure-collections/18411) | [![:book:](//forum.freecodecamp.com/images/emoji/emoji_one/book.png?v=2 ":book:") Home ![:book:](//forum.freecodecamp.com/images/emoji/emoji_one/book.png?v=2 ":book:")](//forum.freecodecamp.com/t/clojure-resources/18422) | [Next ![:point_right:](//forum.freecodecamp.com/images/emoji/emoji_one/point_right.png?v=2 ":point_right:")](//forum.freecodecamp.com/t/clojure-vectors/18421)| | [Collections](//forum.freecodecamp.com/t/clojure-collections/18411) | [Table of Contents](//forum.freecodecamp.com/t/clojure-resources/18422) | [Vectors](//forum.freecodecamp.com/t/clojure-vectors/18421)|
{ "content_hash": "ee1c6b845bbe1ff77b50ad2a1058b5b1", "timestamp": "", "source": "github", "line_count": 94, "max_line_length": 552, "avg_line_length": 54.87234042553192, "alnum_prop": 0.7089957347809228, "repo_name": "pahosler/freecodecamp", "id": "bf9dbe6ff569a3206d4b6dcd297b5d529597181f", "size": "5162", "binary": false, "copies": "4", "ref": "refs/heads/master", "path": "guide/english/clojure/lists-are-everything/index.md", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "CSS", "bytes": "35491" }, { "name": "HTML", "bytes": "17600" }, { "name": "JavaScript", "bytes": "777274" } ], "symlink_target": "" }
import * as sinon from 'sinon'; import {AccessClientAdapter} from '../amp-access-client'; import {AccessService} from '../amp-access'; import {AmpEvents} from '../../../../src/amp-events'; import {Observable} from '../../../../src/observable'; import {cidServiceForDocForTesting} from '../../../../src/service/cid-impl'; import {installPerformanceService} from '../../../../src/service/performance-impl'; import {toggleExperiment} from '../../../../src/experiments'; describes.fakeWin('AccessService', { amp: true, location: 'https://pub.com/doc1', }, env => { let win, document; let ampdoc; let element; beforeEach(() => { win = env.win; ampdoc = env.ampdoc; document = win.document; cidServiceForDocForTesting(ampdoc); installPerformanceService(win); element = document.createElement('script'); element.setAttribute('id', 'amp-access'); element.setAttribute('type', 'application/json'); document.body.appendChild(element); document.documentElement.classList.remove('amp-access-error'); }); afterEach(() => { toggleExperiment(win, 'amp-access-server', false); }); it('should disable service when no config', () => { document.body.removeChild(element); const service = new AccessService(ampdoc); expect(service.isEnabled()).to.be.false; expect(service.accessElement_).to.be.undefined; }); it('should fail if config is malformed', () => { expect(() => { new AccessService(ampdoc); }).to.throw(Error); }); it('should default to "client" and fail if authorization is missing', () => { const config = {}; element.textContent = JSON.stringify(config); expect(() => { new AccessService(ampdoc); }).to.throw(/"authorization" URL must be specified/); }); it('should fail if config login is malformed', () => { const config = { 'authorization': 'https://acme.com/a', 'pingback': 'https://acme.com/p', 'login': 'http://acme.com/l', }; element.textContent = JSON.stringify(config); expect(() => { new AccessService(ampdoc); }).to.throw(/https\:/); }); it('should parse the complete config', () => { const config = { 'authorization': 'https://acme.com/a', 'pingback': 'https://acme.com/p', 'login': 'https://acme.com/l', }; element.textContent = JSON.stringify(config); const service = new AccessService(ampdoc); expect(service.isEnabled()).to.be.true; expect(service.accessElement_).to.equal(element); const source = service.sources_[0]; expect(source.type_).to.equal('client'); expect(source.loginConfig_).to.deep.equal({'': 'https://acme.com/l'}); expect(source.adapter_).to.be.instanceOf(AccessClientAdapter); expect(source.adapter_.authorizationUrl_).to.equal('https://acme.com/a'); }); it('should fail if type is unknown', () => { const config = { 'type': 'unknown', 'authorization': 'https://acme.com/a', 'pingback': 'https://acme.com/p', 'login': 'https://acme.com/l', }; element.textContent = JSON.stringify(config); expect(() => { new AccessService(ampdoc); }).to.throw(/Unknown access type/); }); it('should start when enabled', () => { element.textContent = JSON.stringify({ 'authorization': 'https://acme.com/a', 'pingback': 'https://acme.com/p', 'login': 'https://acme.com/l', }); const service = new AccessService(ampdoc); service.startInternal_ = sandbox.spy(); service.start_(); expect(service.startInternal_).to.be.calledOnce; }); it('should start all services', () => { element.textContent = JSON.stringify({ 'authorization': 'https://acme.com/a', 'pingback': 'https://acme.com/p', 'login': 'https://acme.com/l', }); const service = new AccessService(ampdoc); service.sources_[0].buildLoginUrls_ = sandbox.spy(); service.sources_[0].signIn_.start = sandbox.spy(); service.runAuthorization_ = sandbox.spy(); service.scheduleView_ = sandbox.spy(); service.listenToBroadcasts_ = sandbox.spy(); service.startInternal_(); expect(service.sources_[0].buildLoginUrls_).to.be.calledOnce; expect(service.sources_[0].signIn_.start).to.be.calledOnce; expect(service.runAuthorization_).to.be.calledOnce; expect(service.scheduleView_).to.be.calledOnce; expect(service.scheduleView_.firstCall.args[0]).to.equal(2000); expect(service.listenToBroadcasts_).to.be.calledOnce; }); it('should initialize publisher origin', () => { element.textContent = JSON.stringify({ 'authorization': 'https://acme.com/a', 'pingback': 'https://acme.com/p', 'login': 'https://acme.com/l', }); const service = new AccessService(ampdoc); expect(service.pubOrigin_).to.exist; expect(service.pubOrigin_).to.match(/^http.*/); }); it('should find and register vendor', () => { const config = { 'vendor': 'vendor1', }; element.textContent = JSON.stringify(config); const accessService = new AccessService(ampdoc); const source = accessService.getVendorSource('vendor1'); expect(source).to.equal(accessService.sources_[0]); class Vendor1 {} const vendor1 = new Vendor1(); source.getAdapter().registerVendor(vendor1); return source.adapter_.vendorPromise_.then(vendor => { expect(vendor).to.equal(vendor1); }); }); it('should fail to find non-existent vendor', () => { const config = { 'authorization': 'https://acme.com/a', 'pingback': 'https://acme.com/p', 'login': 'https://acme.com/l', }; element.textContent = JSON.stringify(config); const accessService = new AccessService(ampdoc); expect(() => { accessService.getVendorSource('vendor1'); }).to.throw(/can only be used for "type=vendor"/); }); it('should parse multiple sources', () => { const config = [ { 'authorization': 'https://acme.com/a', 'pingback': 'https://acme.com/p', 'login': 'https://acme.com/l', 'namespace': 'donuts', }, { 'authorization': 'https://beta.com/a', 'pingback': 'https://beta.com/p', 'login': 'https://beta.com/l', 'namespace': 'beer', }, ]; element.textContent = JSON.stringify(config); const accessService = new AccessService(ampdoc); expect(accessService.sources_.length).to.equal(2); expect(accessService.sources_[0].getNamespace()).to.equal('donuts'); expect(accessService.sources_[1].getNamespace()).to.equal('beer'); }); it('should reject invalid multiple sources', () => { const config = [ { 'authorization': 'https://acme.com/a', 'pingback': 'https://acme.com/p', 'login': 'https://acme.com/l', 'namespace': 'beer', }, { 'authorization': 'https://beta.com/a', 'pingback': 'https://beta.com/p', 'login': 'https://beta.com/l', 'namespace': 'beer', }, ]; element.textContent = JSON.stringify(config); expect(() => { new AccessService(ampdoc); }).to.throw(/Namespace already used/); delete (config[0].namespace); element.textContent = JSON.stringify(config); expect(() => { new AccessService(ampdoc); }).to.throw(/Namespace required/); }); }); describes.fakeWin('AccessService authorization', { amp: true, location: 'https://pub.com/doc1', }, env => { let win, document, ampdoc; let clock; let configElement, elementOn, elementOff, elementError; let cidMock; let adapterMock; let performanceMock; let service; beforeEach(() => { win = env.win; ampdoc = env.ampdoc; document = win.document; clock = sandbox.useFakeTimers(); clock.tick(0); cidServiceForDocForTesting(ampdoc); installPerformanceService(win); configElement = document.createElement('script'); configElement.setAttribute('id', 'amp-access'); configElement.setAttribute('type', 'application/json'); configElement.textContent = JSON.stringify({ 'authorization': 'https://acme.com/a?rid=READER_ID', 'pingback': 'https://acme.com/p?rid=READER_ID', 'login': 'https://acme.com/l?rid=READER_ID', }); document.body.appendChild(configElement); document.documentElement.classList.remove('amp-access-error'); elementOn = document.createElement('div'); elementOn.setAttribute('amp-access', 'access'); document.body.appendChild(elementOn); elementOff = document.createElement('div'); elementOff.setAttribute('amp-access', 'NOT access'); document.body.appendChild(elementOff); elementError = document.createElement('div'); elementError.setAttribute('amp-access', 'error'); elementError.setAttribute('amp-access-hide', ''); document.body.appendChild(elementError); service = new AccessService(ampdoc); service.viewer_ = { isVisible: () => true, whenFirstVisible: () => Promise.resolve(), onVisibilityChanged: () => {}, broadcast: () => {}, onBroadcast: () => {}, }; const adapter = { getConfig: () => {}, isAuthorizationEnabled: () => true, isPingbackEnabled: () => true, authorize: () => {}, }; service.sources_[0].adapter_ = adapter; adapterMock = sandbox.mock(adapter); sandbox.stub(service.resources_, 'mutateElement').callsFake( (unusedElement, mutator) => { mutator(); return Promise.resolve(); }); service.vsync_ = { mutate: callback => { callback(); }, mutatePromise: callback => { callback(); return Promise.resolve(); }, }; const cid = { get: () => {}, }; cidMock = sandbox.mock(cid); service.cid_ = Promise.resolve(cid); service.analyticsEvent_ = sandbox.spy(); service.sources_[0].analyticsEvent_ = sandbox.spy(); performanceMock = sandbox.mock(service.performance_); performanceMock.expects('onload_').atLeast(0); }); afterEach(() => { if (configElement.parentElement) { configElement.parentElement.removeChild(configElement); } if (elementOn.parentElement) { elementOn.parentElement.removeChild(elementOn); } if (elementOff.parentElement) { elementOff.parentElement.removeChild(elementOff); } if (elementError.parentElement) { elementError.parentElement.removeChild(elementError); } adapterMock.verify(); performanceMock.verify(); }); function expectGetReaderId(result) { cidMock.expects('get') .withExactArgs( {scope: 'amp-access', createCookieIfNotPresent: true}, sinon.match(() => true)) .returns(Promise.resolve(result)) .once(); } it('should short-circuit authorization flow when disabled', () => { adapterMock.expects('isAuthorizationEnabled') .withExactArgs() .returns(false) .once(); adapterMock.expects('authorize').never(); cidMock.expects('get').never(); const promise = service.runAuthorization_(); expect(document.documentElement).to.have.class('amp-access-loading'); expect(document.documentElement).not.to.have.class('amp-access-error'); return promise.then(() => { expect(document.documentElement).not.to.have.class('amp-access-loading'); expect(document.documentElement).not.to.have.class('amp-access-error'); return service.lastAuthorizationPromises_; }).then(() => { expect(service.sources_[0].authResponse_).to.be.null; }); }); it('should run authorization flow', () => { const source = service.sources_[0]; adapterMock.expects('authorize') .withExactArgs() .returns(Promise.resolve({access: true})) .once(); expectGetReaderId('reader1'); source.buildLoginUrls_ = sandbox.spy(); const firstPromise = service.lastAuthorizationPromises_; const promise = service.runAuthorization_(); expect(firstPromise).not.to.equal(promise); const lastPromise = service.lastAuthorizationPromises_; expect(lastPromise).to.equal(promise); expect(document.documentElement).to.have.class('amp-access-loading'); expect(document.documentElement).not.to.have.class('amp-access-error'); expect(source.buildLoginUrls_).to.have.not.been.called; return promise.then(() => { expect(document.documentElement).not.to.have.class('amp-access-loading'); expect(document.documentElement).not.to.have.class('amp-access-error'); expect(elementOn).not.to.have.attribute('amp-access-hide'); expect(elementOff).to.have.attribute('amp-access-hide'); expect(source.authResponse_).to.exist; expect(source.authResponse_.access).to.be.true; expect(source.buildLoginUrls_).to.be.calledOnce; // Last authorization promise stays unchanged. expect(service.lastAuthorizationPromises_).to.equal(lastPromise); }); }); it('should recover from authorization failure', () => { expectGetReaderId('reader1'); adapterMock.expects('authorize') .withExactArgs() .returns(Promise.reject('intentional')) .once(); const promise = service.runAuthorization_(); expect(document.documentElement).to.have.class('amp-access-loading'); expect(document.documentElement).not.to.have.class('amp-access-error'); return promise.then(() => { expect(document.documentElement).not.to.have.class('amp-access-loading'); expect(document.documentElement).to.have.class('amp-access-error'); expect(elementOn).to.have.attribute('amp-access-hide'); expect(elementOff).not.to.have.attribute('amp-access-hide'); }); }); it('should apply authorization response to new sections', () => { function createElements() { const container = win.document.createElement('div'); const elementOff = win.document.createElement('div'); elementOff.setAttribute('amp-access', 'NOT access'); container.appendChild(elementOff); const elementOn = win.document.createElement('div'); elementOn.setAttribute('amp-access', 'access'); container.appendChild(elementOn); return {container, elementOn, elementOff}; } function dispatchUpdateEvent(target) { const event = win.document.createEvent('Event'); event.initEvent(AmpEvents.DOM_UPDATE, true, true); target.dispatchEvent(event); } expectGetReaderId('reader1'); adapterMock.expects('authorize') .withExactArgs() .returns(Promise.resolve({access: true})) .once(); const early = createElements(); const later = createElements(); // Add "early" elements right away. win.document.body.appendChild(early.container); dispatchUpdateEvent(early.container); expect(early.elementOn).not.to.have.attribute('amp-access-hide'); expect(early.elementOff).not.to.have.attribute('amp-access-hide'); return service.runAuthorization_().then(() => { // "early" applied by the authorization response. expect(early.elementOn).not.to.have.attribute('amp-access-hide'); expect(early.elementOff).to.have.attribute('amp-access-hide'); // "later" is not applied yet, not even after event. win.document.body.appendChild(later.container); dispatchUpdateEvent(later.container); expect(later.elementOn).not.to.have.attribute('amp-access-hide'); expect(later.elementOff).not.to.have.attribute('amp-access-hide'); return service.lastAuthorizationPromises_; }).then(() => { expect(later.elementOn).not.to.have.attribute('amp-access-hide'); expect(later.elementOff).to.have.attribute('amp-access-hide'); }); }); it('should use fallback on authorization failure when available', () => { expectGetReaderId('reader1'); adapterMock.expects('authorize') .withExactArgs() .returns(Promise.reject('intentional')) .once(); service.sources_[0].authorizationFallbackResponse_ = {'error': true}; const promise = service.runAuthorization_(); expect(document.documentElement).to.have.class('amp-access-loading'); expect(document.documentElement).not.to.have.class('amp-access-error'); return promise.then(() => { expect(document.documentElement).not.to.have.class('amp-access-loading'); expect(document.documentElement).not.to.have.class('amp-access-error'); expect(elementOn).to.have.attribute('amp-access-hide'); expect(elementOff).not.to.have.attribute('amp-access-hide'); expect(elementError).not.to.have.attribute('amp-access-hide'); }); }); it('should NOT fallback on authorization failure when disabled', () => { expectGetReaderId('reader1'); adapterMock.expects('authorize') .withExactArgs() .returns(Promise.reject('intentional')) .once(); service.authorizationFallbackResponse_ = {'error': true}; const promise = service.runAuthorization_(/* disableFallback */ true); expect(document.documentElement).to.have.class('amp-access-loading'); expect(document.documentElement).not.to.have.class('amp-access-error'); return promise.then(() => { expect(document.documentElement).to.have.class('amp-access-error'); }); }); it('should run authorization for broadcast events on same origin', () => { let broadcastHandler; sandbox.stub(service.viewer_, 'onBroadcast').callsFake(handler => { broadcastHandler = handler; }); service.runAuthorization_ = sandbox.spy(); service.listenToBroadcasts_(); expect(broadcastHandler).to.exist; // Unknown message. broadcastHandler({}); expect(service.runAuthorization_).to.have.not.been.called; // Wrong origin. broadcastHandler({type: 'amp-access-reauthorize', origin: 'other'}); expect(service.runAuthorization_).to.have.not.been.called; // Broadcast with the right origin. broadcastHandler({type: 'amp-access-reauthorize', origin: service.pubOrigin_}); expect(service.runAuthorization_).to.be.calledOnce; }); }); describes.fakeWin('AccessService applyAuthorizationToElement_', { amp: true, location: 'https://pub.com/doc1', }, env => { let win, document, ampdoc; let configElement, elementOn, elementOff; let templatesMock; let mutateElementStub; let service; beforeEach(() => { win = env.win; ampdoc = env.ampdoc; document = win.document; cidServiceForDocForTesting(ampdoc); installPerformanceService(win); configElement = document.createElement('script'); configElement.setAttribute('id', 'amp-access'); configElement.setAttribute('type', 'application/json'); configElement.textContent = JSON.stringify({ 'authorization': 'https://acme.com/a?rid=READER_ID', 'pingback': 'https://acme.com/p?rid=READER_ID', 'login': 'https://acme.com/l?rid=READER_ID', }); document.body.appendChild(configElement); document.documentElement.classList.remove('amp-access-error'); elementOn = document.createElement('div'); elementOn.setAttribute('amp-access', 'access'); document.body.appendChild(elementOn); elementOff = document.createElement('div'); elementOff.setAttribute('amp-access', 'NOT access'); document.body.appendChild(elementOff); service = new AccessService(ampdoc); mutateElementStub = sandbox.stub(service.resources_, 'mutateElement').callsFake( (unusedElement, mutator) => { mutator(); return Promise.resolve(); }); service.vsync_ = { mutatePromise: callback => { callback(); return Promise.resolve(); }, }; templatesMock = sandbox.mock(service.templates_); }); afterEach(() => { if (configElement.parentElement) { configElement.parentElement.removeChild(configElement); } if (elementOn.parentElement) { elementOn.parentElement.removeChild(elementOn); } if (elementOff.parentElement) { elementOff.parentElement.removeChild(elementOff); } }); function createTemplate() { const template = document.createElement('template'); template.setAttribute('amp-access-template', ''); return template; } it('should toggle authorization attribute', () => { expect(elementOn).not.to.have.attribute('amp-access-hide'); expect(elementOff).not.to.have.attribute('amp-access-hide'); service.applyAuthorizationToElement_(elementOn, {access: true}); service.applyAuthorizationToElement_(elementOff, {access: true}); expect(elementOn).not.to.have.attribute('amp-access-hide'); expect(elementOff).to.have.attribute('amp-access-hide'); expect(mutateElementStub).to.be.calledOnce; expect(mutateElementStub.getCall(0).args[0]).to.equal(elementOff); service.applyAuthorizationToElement_(elementOn, {access: false}); service.applyAuthorizationToElement_(elementOff, {access: false}); expect(elementOn).to.have.attribute('amp-access-hide'); expect(elementOff).not.to.have.attribute('amp-access-hide'); expect(mutateElementStub).to.have.callCount(3); expect(mutateElementStub.getCall(1).args[0]).to.equal(elementOn); expect(mutateElementStub.getCall(2).args[0]).to.equal(elementOff); }); it('should render and re-render templates when access is on', () => { const template1 = createTemplate(); const template2 = createTemplate(); elementOn.appendChild(template1); elementOn.appendChild(template2); function renderAndCheck() { templatesMock = sandbox.mock(service.templates_); const result1 = document.createElement('div'); const result2 = document.createElement('div'); templatesMock.expects('renderTemplate') .withExactArgs(template1, {access: true}) .returns(Promise.resolve(result1)) .once(); templatesMock.expects('renderTemplate') .withExactArgs(template2, {access: true}) .returns(Promise.resolve(result2)) .once(); const p = service.applyAuthorizationToElement_(elementOn, {access: true}); return p.then(() => { expect(elementOn.contains(template1)).to.be.false; expect(elementOn.contains(result1)).to.be.true; expect(result1).to.have.attribute('amp-access-template'); expect(result1['__AMP_ACCESS__TEMPLATE']).to.equal(template1); expect(elementOn.contains(template2)).to.be.false; expect(elementOn.contains(result2)).to.be.true; expect(result2).to.have.attribute('amp-access-template'); expect(result2['__AMP_ACCESS__TEMPLATE']).to.equal(template2); expect(elementOn.querySelectorAll('[amp-access-template]').length) .to.equal(2); templatesMock.verify(); }); } return renderAndCheck().then(() => { // Render second time. return renderAndCheck(); }).then(() => { // Render third time. return renderAndCheck(); }); }); it('should NOT render templates when access is off', () => { elementOff.appendChild(createTemplate()); templatesMock.expects('renderTemplate').never(); service.applyAuthorizationToElement_(elementOff, {access: true}); }); }); describes.fakeWin('AccessService pingback', { amp: true, location: 'https://pub.com/doc1', }, env => { let win, document, ampdoc; let clock; let configElement; let adapterMock; let cidMock; let visibilityChanged; let scrolled; let service; beforeEach(() => { win = env.win; ampdoc = env.ampdoc; document = win.document; clock = sandbox.useFakeTimers(); cidServiceForDocForTesting(ampdoc); installPerformanceService(win); configElement = document.createElement('script'); configElement.setAttribute('id', 'amp-access'); configElement.setAttribute('type', 'application/json'); configElement.textContent = JSON.stringify({ 'authorization': 'https://acme.com/a?rid=READER_ID', 'pingback': 'https://acme.com/p?rid=READER_ID&type=AUTHDATA(child.type)', 'login': 'https://acme.com/l?rid=READER_ID', }); document.body.appendChild(configElement); document.documentElement.classList.remove('amp-access-error'); service = new AccessService(ampdoc); const adapter = { isPingbackEnabled: () => true, pingback: () => Promise.resolve(), }; service.sources_[0].adapter_ = adapter; adapterMock = sandbox.mock(adapter); const cid = { get: () => {}, }; cidMock = sandbox.mock(cid); service.cid_ = Promise.resolve(cid); service.analyticsEvent_ = sandbox.spy(); service.sources_[0].analyticsEvent_ = sandbox.spy(); win.docState_ = { onReady: callback => callback(), }; visibilityChanged = new Observable(); service.viewer_ = { isVisible: () => true, whenFirstVisible: () => Promise.resolve(), onVisibilityChanged: callback => visibilityChanged.add(callback), broadcast: () => {}, }; scrolled = new Observable(); service.viewport_ = { onScroll: callback => scrolled.add(callback), }; // Emulate first authorization complete. service.sources_[0].firstAuthorizationResolver_(); }); afterEach(() => { if (configElement.parentElement) { configElement.parentElement.removeChild(configElement); } adapterMock.verify(); }); function expectGetReaderId(result) { cidMock.expects('get') .withExactArgs( {scope: 'amp-access', createCookieIfNotPresent: true}, sinon.match(() => true)) .returns(Promise.resolve(result)) .once(); } it('should register "viewed" signal after timeout', () => { service.reportViewToServer_ = sandbox.spy(); const p = service.reportWhenViewed_(/* timeToView */ 2000); return Promise.resolve().then(() => { clock.tick(2001); return p; }).then(() => {}, () => {}).then(() => { expect(service.reportViewToServer_).to.be.calledOnce; expect(visibilityChanged.getHandlerCount()).to.equal(0); expect(scrolled.getHandlerCount()).to.equal(0); expect(service.analyticsEvent_).to.have.been.calledWith('access-viewed'); }); }); it('should register "viewed" signal after scroll', () => { service.reportViewToServer_ = sandbox.spy(); const p = service.reportWhenViewed_(/* timeToView */ 2000); return Promise.resolve().then(() => { scrolled.fire(); return p; }).then(() => {}, () => {}).then(() => { expect(service.reportViewToServer_).to.be.calledOnce; expect(visibilityChanged.getHandlerCount()).to.equal(0); expect(scrolled.getHandlerCount()).to.equal(0); expect(service.analyticsEvent_).to.have.been.calledWith('access-viewed'); }); }); it('should register "viewed" signal after click', () => { service.reportViewToServer_ = sandbox.spy(); const p = service.reportWhenViewed_(/* timeToView */ 2000); return Promise.resolve().then(() => { let clickEvent; if (document.createEvent) { clickEvent = document.createEvent('MouseEvent'); clickEvent.initMouseEvent('click', true, true, window, 1); } else { clickEvent = document.createEventObject(); clickEvent.type = 'click'; } document.documentElement.dispatchEvent(clickEvent); return p; }).then(() => {}, () => {}).then(() => { expect(service.reportViewToServer_).to.be.calledOnce; expect(visibilityChanged.getHandlerCount()).to.equal(0); expect(scrolled.getHandlerCount()).to.equal(0); expect(service.analyticsEvent_).to.have.been.calledWith('access-viewed'); }); }); it('should wait for last authorization completion', () => { expect(service.lastAuthorizationPromises_).to.exist; let lastAuthorizationResolver; service.lastAuthorizationPromises_ = new Promise(resolve => { lastAuthorizationResolver = resolve; }); const triggerStart = 1; // First event is "access-authorization-received". service.reportViewToServer_ = sandbox.spy(); service.reportWhenViewed_(/* timeToView */ 2000); return Promise.resolve().then(() => { clock.tick(2001); return Promise.resolve(); }).then(() => { expect(service.reportViewToServer_).to.have.not.been.called; // First event is "access-authorization-received". expect(service.analyticsEvent_.callCount).to.equal(triggerStart); lastAuthorizationResolver(); return Promise.all([service.lastAuthorizationPromises_, service.reportViewPromise_]); }).then(() => { expect(service.reportViewToServer_).to.be.calledOnce; expect(service.analyticsEvent_.callCount).to.equal(triggerStart + 1); expect(service.analyticsEvent_.getCall(triggerStart).args[0]) .to.equal('access-viewed'); }); }); it('should cancel "viewed" signal after click', () => { service.reportViewToServer_ = sandbox.spy(); const p = service.reportWhenViewed_(/* timeToView */ 2000); return Promise.resolve().then(() => { service.viewer_.isVisible = () => false; visibilityChanged.fire(); return p; }).then(() => {}, () => {}).then(() => { expect(service.reportViewToServer_).to.have.not.been.called; expect(visibilityChanged.getHandlerCount()).to.equal(0); expect(scrolled.getHandlerCount()).to.equal(0); }); }); it('should schedule "viewed" monitoring only once', () => { const timeToView = 2000; service.whenViewed_ = ttv => { expect(ttv).to.equal(timeToView); return Promise.resolve(); }; service.reportViewToServer_ = sandbox.spy(); const p1 = service.reportWhenViewed_(timeToView); const p2 = service.reportWhenViewed_(timeToView); expect(p2).to.equal(p1); return p1.then(() => { const p3 = service.reportWhenViewed_(timeToView); expect(p3).to.equal(p1); return p3; }).then(() => { expect(service.reportViewToServer_).to.be.calledOnce; }); }); it('should ignore "viewed" monitoring when pingback is disabled', () => { adapterMock.expects('isPingbackEnabled').returns(false); service.reportWhenViewed_ = sandbox.spy(); const broadcastStub = sandbox.stub(service.viewer_, 'broadcast'); service.scheduleView_(/* timeToView */ 2000); expect(service.reportWhenViewed_).to.have.not.been.called; expect(service.reportViewPromise_).to.be.null; expect(broadcastStub).to.have.not.been.called; }); it('should re-schedule "viewed" monitoring after visibility change', () => { service.reportViewToServer_ = sandbox.spy(); service.scheduleView_(/* timeToView */ 2000); // 1. First attempt fails due to document becoming invisible. let p1; return ampdoc.whenReady().then(() => { p1 = service.reportViewPromise_; expect(p1).to.exist; service.viewer_.isVisible = () => false; visibilityChanged.fire(); return p1; }).then(() => 'SUCCESS', () => 'ERROR').then(result => { expect(result).to.equal('ERROR'); expect(service.reportViewToServer_).to.have.not.been.called; expect(service.reportViewPromise_).to.not.exist; }).then(() => { // 2. Second attempt is rescheduled and will complete. service.viewer_.isVisible = () => true; visibilityChanged.fire(); const p2 = service.reportViewPromise_; expect(p2).to.exist; expect(p2).to.not.equal(p1); expect(service.reportViewToServer_).to.have.not.been.called; return Promise.resolve().then(() => { clock.tick(2001); expect(service.reportViewToServer_).to.have.not.been.called; return p2; }); }).then(() => 'SUCCESS', reason => reason).then(result => { expect(result).to.equal('SUCCESS'); expect(service.reportViewToServer_).to.be.calledOnce; expect(service.reportViewPromise_).to.exist; }); }); it('should re-start "viewed" monitoring when directly requested', () => { service.lastAuthorizationPromise_ = Promise.resolve(); const whenViewedSpy = sandbox.stub(service, 'whenViewed_').callsFake(() => { return Promise.resolve(); }); service.scheduleView_(/* timeToView */ 0); return Promise.resolve().then(() => { expect(whenViewedSpy).to.be.calledOnce; service.scheduleView_(/* timeToView */ 0); }).then(() => { expect(whenViewedSpy).to.have.callCount(2); }); }); it('should send POST pingback', () => { expectGetReaderId('reader1'); adapterMock.expects('pingback') .withExactArgs() .returns(Promise.resolve()) .once(); return service.reportViewToServer_().then(() => { return 'SUCCESS'; }, error => { return 'ERROR ' + error; }).then(result => { expect(result).to.equal('SUCCESS'); expect(service.sources_[0].analyticsEvent_).to.have.been.calledWith( 'access-pingback-sent'); }); }); it('should NOT send analytics event if postback failed', () => { expectGetReaderId('reader1'); adapterMock.expects('pingback') .withExactArgs() .returns(Promise.reject('intentional')) .once(); return service.reportViewToServer_().then(() => { return 'SUCCESS'; }, error => { return 'ERROR ' + error; }).then(result => { expect(result).to.match(/ERROR/); expect(service.sources_[0].analyticsEvent_).to.have.not.been.calledWith( 'access-pingback-sent'); expect(service.sources_[0].analyticsEvent_).to.have.been.calledWith( 'access-pingback-failed'); }); }); it('should broadcast "viewed" signal to other documents', () => { service.reportViewToServer_ = sandbox.stub().returns(Promise.resolve()); const broadcastStub = sandbox.stub(service.viewer_, 'broadcast'); const p = service.reportWhenViewed_(/* timeToView */ 2000); return Promise.resolve().then(() => { clock.tick(2001); return p; }).then(() => {}, () => {}).then(() => { expect(service.reportViewToServer_).to.be.calledOnce; expect(broadcastStub).to.be.calledOnce; expect(broadcastStub.firstCall.args[0]).to.deep.equal({ 'type': 'amp-access-reauthorize', 'origin': service.pubOrigin_, }); }); }); }); describes.fakeWin('AccessService login', { amp: true, location: 'https://pub.com/doc1', }, env => { let win, document, ampdoc; let clock; let configElement; let cidMock; let serviceMock; let sourceMock; let service; beforeEach(() => { win = env.win; ampdoc = env.ampdoc; document = win.document; clock = sandbox.useFakeTimers(); cidServiceForDocForTesting(ampdoc); installPerformanceService(win); configElement = document.createElement('script'); configElement.setAttribute('id', 'amp-access'); configElement.setAttribute('type', 'application/json'); configElement.textContent = JSON.stringify({ 'authorization': 'https://acme.com/a?rid=READER_ID', 'pingback': 'https://acme.com/p?rid=READER_ID', 'login': 'https://acme.com/l?rid=READER_ID', }); document.body.appendChild(configElement); document.documentElement.classList.remove('amp-access-error'); service = new AccessService(ampdoc); const cid = { get: () => {}, }; cidMock = sandbox.mock(cid); service.cid_ = Promise.resolve(cid); service.analyticsEvent_ = sandbox.spy(); serviceMock = sandbox.mock(service); sourceMock = sandbox.mock(service.sources_[0]); service.sources_[0].openLoginDialog_ = () => {}; service.sources_[0].loginUrlMap_[''] = 'https://acme.com/l?rid=R'; service.sources_[0].analyticsEvent_ = sandbox.spy(); service.viewer_ = { broadcast: () => {}, isVisible: () => true, onVisibilityChanged: () => {}, }; }); afterEach(() => { if (configElement.parentElement) { configElement.parentElement.removeChild(configElement); } }); it('should intercept global action to login', () => { serviceMock.expects('loginWithType_') .withExactArgs('') .once(); const event = {preventDefault: sandbox.spy()}; service.handleAction_({method: 'login', event}); expect(event.preventDefault).to.be.calledOnce; }); it('should intercept global action to login-other', () => { serviceMock.expects('loginWithType_') .withExactArgs('other') .once(); const event = {preventDefault: sandbox.spy()}; service.handleAction_({method: 'login-other', event}); expect(event.preventDefault).to.be.calledOnce; }); it('should build login url', () => { cidMock.expects('get') .withExactArgs( {scope: 'amp-access', createCookieIfNotPresent: true}, sinon.match(() => true)) .returns(Promise.resolve('reader1')) .once(); return service.sources_[0].buildLoginUrls_().then(urls => { const url = urls[0].url; expect(url).to.equal('https://acme.com/l?rid=reader1'); expect(service.sources_[0].loginUrlMap_['']).to.equal(url); }); }); it('should build multiple login url', () => { const source = service.sources_[0]; source.loginConfig_ = { 'login1': 'https://acme.com/l1?rid=READER_ID', 'login2': 'https://acme.com/l2?rid=READER_ID', }; cidMock.expects('get') .withExactArgs( {scope: 'amp-access', createCookieIfNotPresent: true}, sinon.match(() => true)) .returns(Promise.resolve('reader1')) .atLeast(1); return source.buildLoginUrls_().then(urls => { expect(urls).to.have.length(2); let l1, l2; if (urls[0].type == 'login1') { l1 = 0; l2 = 1; } else { l1 = 1; l2 = 0; } expect(urls[l1]).to.deep.equal({ 'type': 'login1', 'url': 'https://acme.com/l1?rid=reader1', }); expect(urls[l2]).to.deep.equal({ 'type': 'login2', 'url': 'https://acme.com/l2?rid=reader1', }); expect(source.loginUrlMap_['login1']).to .equal('https://acme.com/l1?rid=reader1'); expect(source.loginUrlMap_['login2']).to .equal('https://acme.com/l2?rid=reader1'); }); }); it('should build login url with RETURN_URL', () => { const source = service.sources_[0]; source.loginConfig_[''] = 'https://acme.com/l?rid=READER_ID&ret=RETURN_URL'; cidMock.expects('get') .withExactArgs( {scope: 'amp-access', createCookieIfNotPresent: true}, sinon.match(() => true)) .returns(Promise.resolve('reader1')) .once(); return source.buildLoginUrls_().then(urls => { const url = urls[0].url; expect(url).to.equal('https://acme.com/l?rid=reader1&ret=RETURN_URL'); expect(source.loginUrlMap_['']).to.equal(url); }); }); it('should open dialog in the same microtask', () => { const source = service.sources_[0]; source.openLoginDialog_ = sandbox.stub(); source.openLoginDialog_.returns(new Promise(() => {})); service.loginWithType_(''); expect(source.openLoginDialog_).to.be.calledOnce; expect(source.openLoginDialog_.firstCall.args[0]) .to.equal('https://acme.com/l?rid=R'); expect(source.analyticsEvent_).to.have.been.calledWith( 'access-login-started'); }); it('should fail to open dialog if loginUrl is not built yet', () => { service.sources_[0].loginUrlMap_[''] = null; expect(() => service.loginWithType_('')).to.throw(/Login URL is not ready/); }); it('should succeed login with success=true', () => { const source = service.sources_[0]; const authorizationStub = sandbox.stub(source, 'runAuthorization').callsFake( () => Promise.resolve()); const viewStub = sandbox.stub(source, 'scheduleView_'); const broadcastStub = sandbox.stub(service.viewer_, 'broadcast'); sourceMock.expects('openLoginDialog_') .withExactArgs('https://acme.com/l?rid=R') .returns(Promise.resolve('#success=true')) .once(); return service.loginWithType_('').then(() => { expect(source.loginPromise_).to.not.exist; expect(authorizationStub).to.be.calledOnce; expect(authorizationStub).to.be.calledWithExactly( /* disableFallback */ true); expect(viewStub).to.be.calledOnce; expect(viewStub).to.be.calledWithExactly(/* timeToView */ 0); expect(broadcastStub).to.be.calledOnce; expect(broadcastStub.firstCall.args[0]).to.deep.equal({ 'type': 'amp-access-reauthorize', 'origin': service.pubOrigin_, }); expect(source.analyticsEvent_).to.have.been.calledWith( 'access-login-started'); expect(source.analyticsEvent_).to.have.been.calledWith( 'access-login-success'); }); }); it('should fail login with success=no', () => { const source = service.sources_[0]; service.runAuthorization_ = sandbox.spy(); sourceMock.expects('openLoginDialog_') .withExactArgs('https://acme.com/l?rid=R') .returns(Promise.resolve('#success=no')) .once(); return service.loginWithType_('').then(() => { expect(source.loginPromise_).to.not.exist; expect(service.runAuthorization_).to.have.not.been.called; expect(source.analyticsEvent_).to.have.been.calledWith( 'access-login-rejected'); expect(source.analyticsEvent_).to.have.been.calledWith( 'access-login-started'); }); }); it('should fail login with empty response, but re-authorize', () => { const source = service.sources_[0]; const authorizationStub = sandbox.stub(source, 'runAuthorization').callsFake( () => Promise.resolve()); const viewStub = sandbox.stub(source, 'scheduleView_'); const broadcastStub = sandbox.stub(service.viewer_, 'broadcast'); sourceMock.expects('openLoginDialog_') .withExactArgs('https://acme.com/l?rid=R') .returns(Promise.resolve('')) .once(); return service.loginWithType_('').then(() => { expect(source.loginPromise_).to.not.exist; expect(authorizationStub).to.be.calledOnce; expect(authorizationStub).to.be.calledWithExactly( /* disableFallback */ true); expect(viewStub).to.be.calledOnce; expect(viewStub).to.be.calledWithExactly(/* timeToView */ 0); expect(broadcastStub).to.be.calledOnce; expect(broadcastStub.firstCall.args[0]).to.deep.equal({ 'type': 'amp-access-reauthorize', 'origin': service.pubOrigin_, }); expect(source.analyticsEvent_).to.have.been.calledWith( 'access-login-started'); expect(source.analyticsEvent_).to.have.been.calledWith( 'access-login-rejected'); }); }); it('should fail login with aborted dialog', () => { const source = service.sources_[0]; service.runAuthorization_ = sandbox.spy(); sourceMock.expects('openLoginDialog_') .withExactArgs('https://acme.com/l?rid=R') .returns(Promise.reject('abort')) .once(); return service.loginWithType_('') .then(() => 'S', () => 'ERROR').then(result => { expect(result).to.equal('ERROR'); expect(source.loginPromise_).to.not.exist; expect(service.runAuthorization_).to.have.not.been.called; expect(source.analyticsEvent_).to.have.been.calledWith( 'access-login-started'); expect(source.analyticsEvent_).to.have.been.calledWith( 'access-login-failed'); }); }); it('should succeed login with success=true with multiple logins', () => { const source = service.sources_[0]; source.loginConfig_ = { 'login1': 'https://acme.com/l1?rid=READER_ID', 'login2': 'https://acme.com/l2?rid=READER_ID', }; source.loginUrlMap_ = { 'login1': 'https://acme.com/l1?rid=R', 'login2': 'https://acme.com/l2?rid=R', }; const authorizationStub = sandbox.stub(source, 'runAuthorization').callsFake( () => Promise.resolve()); const broadcastStub = sandbox.stub(service.viewer_, 'broadcast'); sourceMock.expects('openLoginDialog_') .withExactArgs('https://acme.com/l2?rid=R') .returns(Promise.resolve('#success=true')) .once(); return service.loginWithType_('login2').then(() => { expect(service.loginPromise_).to.not.exist; expect(authorizationStub).to.be.calledOnce; expect(broadcastStub).to.be.calledOnce; expect(broadcastStub.firstCall.args[0]).to.deep.equal({ 'type': 'amp-access-reauthorize', 'origin': service.pubOrigin_, }); expect(source.analyticsEvent_).to.have.been.calledWith( 'access-login-started'); expect(source.analyticsEvent_).to.have.been.calledWith( 'access-login-login2-started'); expect(source.analyticsEvent_).to.have.been.calledWith( 'access-login-success'); expect(source.analyticsEvent_).to.have.been.calledWith( 'access-login-login2-success'); }); }); it('should block login for 1 second', () => { let p1Reject; const p1Promise = new Promise((unusedResolve, reject) => { p1Reject = reject; }); const source = service.sources_[0]; service.runAuthorization_ = sandbox.spy(); const openLoginDialogStub = sandbox.stub(source, 'openLoginDialog_'); openLoginDialogStub.onCall(0).returns(p1Promise); openLoginDialogStub.onCall(1).returns(new Promise(() => {})); openLoginDialogStub.onCall(2).throws(); const p1 = service.loginWithType_(''); // The immediate second attempt is blocked. const p2 = service.loginWithType_(''); expect(source.loginPromise_).to.equal(p1); expect(p2).to.equal(p1); // The delayed third attempt succeeds after 1 second. clock.tick(1001); const p3 = service.loginWithType_(''); expect(source.loginPromise_).to.equal(p3); expect(p3).to.not.equal(p1); // Rejecting the first login attempt does not reject the current promise. p1Reject(); return p1Promise.then(() => 'SUCCESS', () => 'ERROR').then(res => { expect(res).to.equal('ERROR'); expect(source.loginPromise_).to.equal(p3); }); }); it('should request sign-in when configured', () => { const source = service.sources_[0]; source.signIn_.requestSignIn = sandbox.stub(); source.signIn_.requestSignIn.returns(Promise.resolve('#signin')); source.openLoginDialog_ = sandbox.stub(); source.openLoginDialog_.returns(Promise.resolve('#login')); service.loginWithType_(''); expect(source.signIn_.requestSignIn).to.be.calledOnce; expect(source.signIn_.requestSignIn.firstCall.args[0]) .to.equal('https://acme.com/l?rid=R'); expect(source.openLoginDialog_).to.have.not.been.called; }); it('should wait for token exchange post-login with success=true', () => { const source = service.sources_[0]; source.signIn_.postLoginResult = sandbox.stub(); source.signIn_.postLoginResult.returns(Promise.resolve()); const authorizationStub = sandbox.stub(source, 'runAuthorization').callsFake( () => Promise.resolve()); const viewStub = sandbox.stub(source, 'scheduleView_'); const broadcastStub = sandbox.stub(service.viewer_, 'broadcast'); sourceMock.expects('openLoginDialog_') .withExactArgs('https://acme.com/l?rid=R') .returns(Promise.resolve('#success=true')) .once(); return service.loginWithType_('').then(() => { expect(source.loginPromise_).to.not.exist; expect(source.signIn_.postLoginResult).to.be.calledOnce; expect(source.signIn_.postLoginResult.firstCall.args[0]).to.deep.equal({ 'success': 'true', }); expect(authorizationStub).to.be.calledOnce; expect(viewStub).to.be.calledOnce; expect(broadcastStub).to.be.calledOnce; }); }); }); describes.fakeWin('AccessService analytics', { amp: true, location: 'https://pub.com/doc1', }, env => { let win, document, ampdoc; let configElement; let service; beforeEach(() => { win = env.win; ampdoc = env.ampdoc; document = win.document; cidServiceForDocForTesting(ampdoc); installPerformanceService(win); configElement = document.createElement('script'); configElement.setAttribute('id', 'amp-access'); configElement.setAttribute('type', 'application/json'); configElement.textContent = JSON.stringify({ 'authorization': 'https://acme.com/a?rid=READER_ID', 'pingback': 'https://acme.com/p?rid=READER_ID', 'login': 'https://acme.com/l?rid=READER_ID', }); document.body.appendChild(configElement); document.documentElement.classList.remove('amp-access-error'); service = new AccessService(ampdoc); service.enabled_ = true; service.getReaderId_ = () => { return Promise.resolve('reader1'); }; service.sources_[0].setAuthResponse_( {views: 3, child: {type: 'premium'}, zero: 0}); }); afterEach(() => { if (configElement.parentElement) { configElement.parentElement.removeChild(configElement); } }); it('should return null when not enabled', () => { service.enabled_ = false; expect(service.getAccessReaderId()).to.be.null; expect(service.getAuthdataField('views')).to.be.null; }); it('should return reader id', () => { return service.getAccessReaderId().then(readerId => { expect(readerId).to.equal('reader1'); }); }); it('should return authdata', () => { service.sources_[0].firstAuthorizationResolver_(); return Promise.all([ service.getAuthdataField('views'), service.getAuthdataField('child.type'), service.getAuthdataField('other'), service.getAuthdataField('child.other'), service.getAuthdataField('zero'), ]).then(res => { expect(res[0]).to.equal(3); expect(res[1]).to.equal('premium'); expect(res[2]).to.be.null; expect(res[3]).to.be.null; expect(res[4]).to.equal(0); }); }); it('should wait the first authorization for authdata', () => { let viewsValue; const promise = service.getAuthdataField('views').then(res => { viewsValue = res; }); return Promise.resolve().then(() => { expect(viewsValue).to.be.undefined; // Resolve the authorization. service.sources_[0].firstAuthorizationResolver_(); return promise; }).then(() => { expect(viewsValue).to.equal(3); }); }); it('should wait the latest authorization for authdata if started', () => { let resolver; service.lastAuthorizationPromises_ = new Promise(resolve => { resolver = resolve; }); let viewsValue; const promise = service.getAuthdataField('views').then(res => { viewsValue = res; }); return Promise.resolve().then(() => { expect(viewsValue).to.be.undefined; // Resolve the first authorization. service.sources_[0].firstAuthorizationResolver_(); }).then(() => { expect(viewsValue).to.be.undefined; // Resolve the second authorization. resolver(); return promise; }).then(() => { expect(viewsValue).to.equal(3); }); }); }); describes.fakeWin('AccessService multiple sources', { amp: true, location: 'https://pub.com/doc1', }, env => { let win, document, ampdoc; let clock; let configElement, elementOnBeer, elementOnBeerOrDonuts, elementError; let cidMock; let adapterBeerMock, adapterDonutsMock; let performanceMock; let service; let sourceBeer, sourceDonuts; beforeEach(() => { win = env.win; ampdoc = env.ampdoc; document = win.document; clock = sandbox.useFakeTimers(); clock.tick(0); cidServiceForDocForTesting(ampdoc); installPerformanceService(win); configElement = document.createElement('script'); configElement.setAttribute('id', 'amp-access'); configElement.setAttribute('type', 'application/json'); configElement.textContent = JSON.stringify([ { 'authorization': 'https://acme.com/a?rid=READER_ID', 'pingback': 'https://acme.com/p?rid=READER_ID', 'login': 'https://acme.com/l?rid=READER_ID', 'namespace': 'beer', }, { 'authorization': 'https://acme.com/a?rid=READER_ID', 'pingback': 'https://acme.com/p?rid=READER_ID', 'login': { 'login2': 'https://acme.com/l?rid=READER_ID', }, 'namespace': 'donuts', }, ]); document.body.appendChild(configElement); document.documentElement.classList.remove('amp-access-error'); elementOnBeer = document.createElement('div'); elementOnBeer.setAttribute('amp-access', 'beer.access'); document.body.appendChild(elementOnBeer); elementOnBeerOrDonuts = document.createElement('div'); elementOnBeerOrDonuts.setAttribute('amp-access', 'beer.access OR donuts.access'); document.body.appendChild(elementOnBeerOrDonuts); elementError = document.createElement('div'); elementError.setAttribute('amp-access', 'error'); elementError.setAttribute('amp-access-hide', ''); document.body.appendChild(elementError); service = new AccessService(ampdoc); sourceBeer = service.sources_[0]; sourceDonuts = service.sources_[1]; const adapterBeer = { getConfig: () => {}, isAuthorizationEnabled: () => true, isPingbackEnabled: () => true, authorize: () => {}, }; const adapterDonuts = { getConfig: () => {}, isAuthorizationEnabled: () => true, isPingbackEnabled: () => true, authorize: () => {}, }; sourceBeer.adapter_ = adapterBeer; adapterBeerMock = sandbox.mock(adapterBeer); sourceDonuts.adapter_ = adapterDonuts; adapterDonutsMock = sandbox.mock(adapterDonuts); sandbox.stub(service.resources_, 'mutateElement').callsFake( (unusedElement, mutator) => { mutator(); return Promise.resolve(); }); service.vsync_ = { mutate: callback => { callback(); }, mutatePromise: callback => { callback(); return Promise.resolve(); }, }; const cid = { get: () => {}, }; cidMock = sandbox.mock(cid); service.cid_ = Promise.resolve(cid); service.analyticsEvent_ = sandbox.spy(); sourceBeer.analyticsEvent_ = sandbox.spy(); sourceDonuts.analyticsEvent_ = sandbox.spy(); performanceMock = sandbox.mock(service.performance_); performanceMock.expects('onload_').atLeast(0); }); afterEach(() => { if (configElement.parentElement) { configElement.parentElement.removeChild(configElement); } if (elementOnBeer.parentElement) { elementOnBeer.parentElement.removeChild(elementOnBeer); } if (elementOnBeerOrDonuts.parentElement) { elementOnBeerOrDonuts.parentElement.removeChild(elementOnBeerOrDonuts); } if (elementError.parentElement) { elementError.parentElement.removeChild(elementError); } adapterBeerMock.verify(); adapterDonutsMock.verify(); performanceMock.verify(); }); function expectGetReaderId(result) { cidMock.expects('get') .withExactArgs( {scope: 'amp-access', createCookieIfNotPresent: true}, sinon.match(() => true)) .returns(Promise.resolve(result)) .once(); } it('should run authorization flow', () => { expectGetReaderId('reader1'); adapterBeerMock.expects('authorize') .withExactArgs() .returns(Promise.resolve({access: false})) .once(); adapterDonutsMock.expects('authorize') .withExactArgs() .returns(Promise.resolve({access: true})) .once(); const promise = service.runAuthorization_(); const lastPromise = service.lastAuthorizationPromises_; expect(lastPromise).to.equal(promise); expect(document.documentElement).to.have.class('amp-access-loading'); expect(document.documentElement).not.to.have.class('amp-access-error'); return promise.then(() => { expect(document.documentElement).not.to.have.class('amp-access-loading'); expect(document.documentElement).not.to.have.class('amp-access-error'); expect(elementOnBeer).to.have.attribute('amp-access-hide'); expect(elementOnBeerOrDonuts).not.to.have.attribute('amp-access-hide'); expect(sourceBeer.authResponse_).to.exist; expect(sourceBeer.authResponse_.access).to.be.false; expect(sourceDonuts.authResponse_).to.exist; expect(sourceDonuts.authResponse_.access).to.be.true; // Last authorization promise stays unchanged. expect(service.lastAuthorizationPromises_).to.equal(lastPromise); }); }); it('should return authdata', () => { expectGetReaderId('reader1'); adapterBeerMock.expects('authorize') .withExactArgs() .returns(Promise.reject('rejected')) .once(); adapterDonutsMock.expects('authorize') .withExactArgs() .returns(Promise.resolve({access: true})) .once(); service.runAuthorization_(); return Promise.all([ service.getAuthdataField('beer.access'), service.getAuthdataField('donuts.access'), service.getAuthdataField('garbage'), service.getAuthdataField('donuts.garbage'), service.getAuthdataField('garbage.garbage'), ]).then(res => { expect(res[0]).to.be.null; expect(res[1]).to.equal(true); expect(res[2]).to.be.null; expect(res[3]).to.be.null; expect(res[4]).to.be.null; }); }); it('should succeed login flat', () => { expectGetReaderId('reader1'); const authorizationStub = sandbox.stub(sourceBeer, 'runAuthorization').callsFake( () => Promise.resolve()); const broadcastStub = sandbox.stub(sourceBeer.viewer_, 'broadcast'); const sourceBeerMock = sandbox.mock(sourceBeer); sourceBeerMock.expects('openLoginDialog_') .withExactArgs('https://acme.com/l?rid=reader1') .returns(Promise.resolve('#success=true')) .once(); sourceBeer.analyticsEvent_ = sandbox.spy(); return sourceBeer.buildLoginUrls_() .then(() => service.loginWithType_('beer')) .then(() => { expect(sourceBeer.loginPromise_).to.not.exist; expect(authorizationStub).to.be.calledOnce; expect(broadcastStub).to.be.calledOnce; expect(broadcastStub.firstCall.args[0]).to.deep.equal({ 'type': 'amp-access-reauthorize', 'origin': service.pubOrigin_, }); expect(sourceBeer.analyticsEvent_).to.have.been.calledWith( 'access-login-started'); expect(sourceBeer.analyticsEvent_).to.have.been.calledWith( 'access-login-success'); sourceBeerMock.verify(); }); }); it('should succeed login hierarchy', () => { expectGetReaderId('reader1'); const authorizationStub = sandbox.stub(sourceDonuts, 'runAuthorization').callsFake( () => Promise.resolve()); const broadcastStub = sandbox.stub(sourceDonuts.viewer_, 'broadcast'); const sourceDonutsMock = sandbox.mock(sourceDonuts); sourceDonutsMock.expects('openLoginDialog_') .withExactArgs('https://acme.com/l?rid=reader1') .returns(Promise.resolve('#success=true')) .once(); sourceDonuts.analyticsEvent_ = sandbox.spy(); return sourceDonuts.buildLoginUrls_() .then(() => service.loginWithType_('donuts-login2')) .then(() => { expect(sourceDonuts.loginPromise_).to.not.exist; expect(authorizationStub).to.be.calledOnce; expect(broadcastStub).to.be.calledOnce; expect(broadcastStub.firstCall.args[0]).to.deep.equal({ 'type': 'amp-access-reauthorize', 'origin': service.pubOrigin_, }); expect(sourceDonuts.analyticsEvent_).to.have.been.calledWith( 'access-login-started'); expect(sourceDonuts.analyticsEvent_).to.have.been.calledWith( 'access-login-login2-started'); expect(sourceDonuts.analyticsEvent_).to.have.been.calledWith( 'access-login-success'); expect(sourceDonuts.analyticsEvent_).to.have.been.calledWith( 'access-login-login2-success'); sourceDonutsMock.verify(); }); }); });
{ "content_hash": "cde5550ab01cd001891ad7c238d97536", "timestamp": "", "source": "github", "line_count": 1717, "max_line_length": 80, "avg_line_length": 35.22655794991264, "alnum_prop": 0.6377223728589378, "repo_name": "yieldmo/amphtml", "id": "571da0d34f28d2f03312bd280d4e81b2fb16dda6", "size": "61111", "binary": false, "copies": "3", "ref": "refs/heads/master", "path": "extensions/amp-access/0.1/test/test-amp-access.js", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "206113" }, { "name": "Go", "bytes": "15254" }, { "name": "HTML", "bytes": "1104594" }, { "name": "Java", "bytes": "36670" }, { "name": "JavaScript", "bytes": "10018090" }, { "name": "Python", "bytes": "80081" }, { "name": "Ruby", "bytes": "15912" }, { "name": "Shell", "bytes": "12162" }, { "name": "Yacc", "bytes": "22292" } ], "symlink_target": "" }
@interface TYRecordEncoder : NSObject + (instancetype)recordEncoderPath:(NSString *)filePath videoWidth:(int)videoWidth videoHeight:(int)videoHeight audioChannel:(UInt32)channel audioRate:(Float64)rate; - (instancetype)initPath:(NSString *)filePath videoWidth:(int)videoWidth videoHeight:(int)videoHeight audioChannel:(UInt32)channel audioRate:(Float64)rate; - (void)encoderFrame:(CMSampleBufferRef)sampleBuffer isVideo:(BOOL)isVideo; - (void)encoderFinishCompletionHandler:(void(^)())handler; @end
{ "content_hash": "a4be5c3eb39d4ac8480c8c4837ff35ee", "timestamp": "", "source": "github", "line_count": 11, "max_line_length": 164, "avg_line_length": 45.81818181818182, "alnum_prop": 0.8134920634920635, "repo_name": "Samueler/TYCamera", "id": "c17e1c2f66be62909cf9db53b25d17c7df77fe6a", "size": "718", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "TYCamera/Camera/TYRecordEncoder.h", "mode": "33188", "license": "mit", "language": [ { "name": "Objective-C", "bytes": "69342" }, { "name": "Ruby", "bytes": "6293" } ], "symlink_target": "" }
import os class DefaultConfig(object): INSTANCE_FOLDER_PATH = '/usr/lib/camus' # Get app root path, also can use flask.root_path. # ../../config.py PROJECT_ROOT = os.path.abspath(os.path.dirname(os.path.dirname(__file__))) DEBUG = False TESTING = False ADMINS = ['youremail@yourdomain.com'] # Fild upload, should override in production. # Limited the maximum allowed payload to 16 megabytes. # http://flask.pocoo.org/docs/patterns/fileuploads/#improving-uploads MAX_CONTENT_LENGTH = 16 * 1024 * 1024 DEBUG = False # Flask-babel: http://pythonhosted.org/Flask-Babel/ # ACCEPT_LANGUAGES = ['zh'] BABEL_DEFAULT_LOCALE = 'en' # Flask-cache: http://pythonhosted.org/Flask-Cache/ CACHE_TYPE = 'simple' CACHE_DEFAULT_TIMEOUT = 60 # Flask-mail: http://pythonhosted.org/flask-mail/ # https://bitbucket.org/danjac/flask-mail/issue/3/problem-with-gmails-smtp-server MAIL_DEBUG = DEBUG MAIL_SERVER = 'smtp.gmail.com' MAIL_PORT = 587 MAIL_USE_TLS = True MAIL_USE_SSL = False # Should put MAIL_USERNAME and MAIL_PASSWORD in production under instance folder. MAIL_USERNAME = 'yourmail@gmail.com' MAIL_PASSWORD = 'yourpass' MAIL_DEFAULT_SENDER = MAIL_USERNAME _UPLOADS_FOLDER = None class TestConfig(DefaultConfig): INSTANCE_FOLDER_PATH = '/tmp/testing/camus' TESTING = True DEBUG = False WTF_CSRF_ENABLED = False SECRET_KEY = 'secret key' class DevelopConfig(DefaultConfig): DEBUG = True INSTANCE_FOLDER_PATH = '/tmp/developer/camus' SECRET_KEY = 'secret key' DB_URL = 'postgres://camus:camus@localhost/camus'
{ "content_hash": "4028d251f5b13ef14809935910b053af", "timestamp": "", "source": "github", "line_count": 57, "max_line_length": 85, "avg_line_length": 29.210526315789473, "alnum_prop": 0.6732732732732732, "repo_name": "kindly/camus", "id": "af0e2bee43a0cb0c7bc245617a83d10913d099f3", "size": "1690", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "camus/config.py", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "CSS", "bytes": "148356" }, { "name": "JavaScript", "bytes": "2571" }, { "name": "Python", "bytes": "28464" }, { "name": "Shell", "bytes": "224" } ], "symlink_target": "" }
/* / _____) _ | | ( (____ _____ ____ _| |_ _____ ____| |__ \____ \| ___ | (_ _) ___ |/ ___) _ \ _____) ) ____| | | || |_| ____( (___| | | | (______/|_____)_|_|_| \__)_____)\____)_| |_| (C)2013 Semtech Description: Generic driver for the GPS receiver UP501 License: Revised BSD License, see LICENSE.TXT file include in the project Maintainer: Miguel Luis and Gregory Cristian */ #ifndef __GPS_H__ #define __GPS_H__ /* Structure to handle the GPS parsed data in ASCII */ typedef struct { char NmeaDataType[6]; char NmeaUtcTime[11]; char NmeaDataStatus[2]; char NmeaLatitude[10]; char NmeaLatitudePole[2]; char NmeaLongitude[11]; char NmeaLongitudePole[2]; char NmeaFixQuality[2]; char NmeaSatelliteTracked[3]; char NmeaHorizontalDilution[6]; char NmeaAltitude[8]; char NmeaAltitudeUnit[2]; char NmeaHeightGeoid[8]; char NmeaHeightGeoidUnit[2]; char NmeaSpeed[8]; char NmeaDetectionAngle[8]; char NmeaDate[8]; } tNmeaGpsData; typedef struct { unsigned char second; // 0-59 unsigned char minute; // 0-59 unsigned char hour; // 0-23 unsigned char day; // 1-31 unsigned char month; // 1-12 unsigned char year; // 0-99 (representing 2000-2099) } datetime_t; extern tNmeaGpsData NmeaGpsData; /*! * \brief Initializes the handling of the GPS receiver */ void GpsInit( void ); /*! * \brief PPS signal handling function */ void GpsPpsHandler( bool *parseData ); /*! * \brief PPS signal handling function * * \retval ppsDetected State of PPS signal. */ bool GpsGetPpsDetectedState( void ); /*! * \brief Indicates if GPS has fix * * \retval hasFix */ bool GpsHasFix( void ); /*! * \brief Indicates if GPS has a valid datetime * * \retval has valid datetime */ bool GpsHasValidDateTime( void ); /*! * \brief Converts the latest Position (latitude and longitude) into a binary * number */ void GpsConvertPositionIntoBinary( void ); /*! * \brief Converts the latest Position (latitude and Longitude) from ASCII into * DMS numerical format */ void GpsConvertPositionFromStringToNumerical( void ); /*! * \brief Get current unix time * * \retval unixTime Current unix time */ time_t GpsGetCurrentUnixTime( void ); /*! * \brief Gets the latest Position (latitude and Longitude) as two double values * if available * * \param [OUT] lati Latitude value * \param [OUT] longi Longitude value * * \retval status [SUCCESS, FAIL] */ uint8_t GpsGetLatestGpsPositionDouble( double *lati, double *longi ); /*! * \brief Gets the latest Position (latitude and Longitude) as two binary values * if available * * \param [OUT] latiBin Latitude value * \param [OUT] longiBin Longitude value * * \retval status [SUCCESS, FAIL] */ uint8_t GpsGetLatestGpsPositionBinary( int32_t *latiBin, int32_t *longiBin ); /*! * \brief Calculates the distance between the latest position and the specified * location. * * \param[IN] latiBin Latitude value * \param[IN] longiBin Longitude value * \param[OUT] distance Calculated distance * * \retval status [SUCCESS, FAIL] */ uint8_t GpsGetDistanceToLatestGpsPositionBinary( int32_t latiBin, int32_t longiBin, uint32_t *distance ); /*! * \brief Parses the NMEA sentence. * * \remark Only parses GPGGA and GPRMC sentences * * \param [IN] rxBuffer Data buffer to be parsed * \param [IN] rxBufferSize Size of data buffer * * \retval status [SUCCESS, FAIL] */ uint8_t GpsParseGpsData( char *rxBuffer, size_t rxBufferSize ); /*! * \brief Returns the latest altitude from the parsed NMEA sentence * * \retval altitude */ uint16_t GpsGetLatestGpsAltitude( void ); /*! * \brief Gets the latest Vector track (ground speed and track) if available * * \param [OUT] groundSpeed Ground speed * \param [OUT] track Direction * * \retval status [SUCCESS, FAIL] */ uint8_t GpsGetLatestTrack( uint16_t *groundSpeed, uint16_t *track ); /*! * \brief Format GPS data into numeric and binary formats */ void GpsFormatGpsData( void ); /*! * \brief Resets the GPS position variables */ void GpsResetPosition( void ); #endif // __GPS_H__
{ "content_hash": "5ecd26422053733acd2badf97caef13f", "timestamp": "", "source": "github", "line_count": 174, "max_line_length": 83, "avg_line_length": 24.137931034482758, "alnum_prop": 0.6561904761904762, "repo_name": "AlexanderWiniger/LoRaMac-node", "id": "8be48501dd83c9066c753bee81d702eea01d2d19", "size": "4200", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/system/gps.h", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "Assembly", "bytes": "153011" }, { "name": "C", "bytes": "8297449" }, { "name": "C++", "bytes": "114110" }, { "name": "HTML", "bytes": "76231" }, { "name": "Objective-C", "bytes": "1600" } ], "symlink_target": "" }
<template name="databaseDumpRestore"> {{> pageHeading title=getPageHeading }} {{#if isConnected}} <div class="wrapper wrapper-content animated fadeInRight"> <div class="row"> <div class="col-lg-6"> <div class="ibox float-e-margins"> <div class="ibox-title"> <h5>Mongodump</h5> <div class="ibox-tools"> <a id="btnClearMongodumpLogs" href="#" title="{{_ "delete_logs"}}"> <i class="fa fa-trash"></i> </a> </div> </div> <div class="ibox-content"> <form method="get" class="form-horizontal"> <div class="form-group"> <label class="col-lg-2 control-label">{{_ "arguments"}}</label> <div class="col-lg-10"> <select id="cmbMongodumpArgs" data-placeholder="{{_ "select_options"}}" multiple="true" class="chosen-select form-control" tabindex="-1"> <option value="-v">verbose</option> <option value="--quiet">quiet</option> <option value="--host">host</option> <option value="--port">port</option> <option value="--ipv6">ipv6</option> <option value="--ssl">ssl</option> <option value="--sslCAFile">sslCAFile</option> <option value="--sslPEMKeyFile">sslPEMKeyFile</option> <option value="--sslPEMKeyPassword">sslPEMKeyPassword</option> <option value="--sslCRLFile">sslCRLFile</option> <option value="--sslAllowInvalidCertificates"> sslAllowInvalidCertificates </option> <option value="--sslAllowInvalidHostnames"> sslAllowInvalidHostnames </option> <option value="--sslFIPSMode">sslFIPSMode</option> <option value="--username">username</option> <option value="--password">password</option> <option value="--authenticationDatabase"> authenticationDatabase </option> <option value="--authenticationMechanism"> authenticationMechanism </option> <option value="--gssapiServiceName">gssapiServiceName</option> <option value="--gssapiHostName">gssapiHostName</option> <option value="--db">db</option> <option value="--collection">collection</option> <option value="--query">query</option> <option value="--queryFile">queryFile</option> <option value="--readPreference">readPreference</option> <option value="--forceTableScan">forceTableScan</option> <option value="--gzip">gzip</option> <option value="--out">out</option> <option value="--archive">archive</option> <option value="--repair">repair</option> <option value="--oplog">oplog</option> <option value="--dumpDbUsersAndRoles">dumpDbUsersAndRoles </option> <option value="--excludeCollection">excludeCollection</option> <option value="--excludeCollectionsWithPrefix"> excludeCollectionsWithPrefix </option> <option value="--numParallelCollections"> numParallelCollections </option> <option value="--viewsAsCollections">viewsAsCollections</option> </select> </div> </div> {{> mongodumpOptions}} <div class="form-group"> <div id="mongodump"> <label class="col-lg-2 control-label">{{_ "logs"}}</label> <div class="col-lg-10"> <textarea id="txtMongodumpLogs" class="form-control"></textarea> </div> </div> </div> </form> </div> <div class="ibox-footer"> <div class="row"> <div class="col-lg-12"> <button id="btnExecuteMongodump" class="btn btn-block btn-outline btn-primary ladda-button" type="button" data-style="contract"> <strong>{{_ "execute"}}</strong></button> </div> </div> </div> </div> </div> <div class="col-lg-6"> <div class="ibox float-e-margins"> <div class="ibox-title"> <h5>Mongorestore</h5> <div class="ibox-tools"> <a id="btnClearMongorestoreLogs" href="#" title="{{_ "delete_logs"}}"> <i class="fa fa-trash"></i> </a> </div> </div> <div class="ibox-content"> <form method="get" class="form-horizontal"> <div class="form-group"> <label class="col-lg-2 control-label">{{_ "arguments"}}</label> <div class="col-lg-10"> <select id="cmbMongorestoreArgs" data-placeholder="{{_ "select_options"}}" multiple="true" class="chosen-select form-control" tabindex="-1"> <option value="-v">verbose</option> <option value="--quiet">quiet</option> <option value="--host">host</option> <option value="--port">port</option> <option value="--ssl">ssl</option> <option value="--sslCAFile">sslCAFile</option> <option value="--sslPEMKeyFile">sslPEMKeyFile</option> <option value="--sslPEMKeyPassword">sslPEMKeyPassword</option> <option value="--sslCRLFile">sslCRLFile</option> <option value="--sslAllowInvalidCertificates"> sslAllowInvalidCertificates </option> <option value="--sslAllowInvalidHostnames"> sslAllowInvalidHostnames </option> <option value="--sslFIPSMode">sslFIPSMode</option> <option value="--username">username</option> <option value="--password">password</option> <option value="--authenticationDatabase"> authenticationDatabase </option> <option value="--authenticationMechanism"> authenticationMechanism </option> <option value="--gssapiServiceName">gssapiServiceName</option> <option value="--gssapiHostName">gssapiHostName</option> <option value="--db">db</option> <option value="--collection">collection</option> <option value="--nsExclude">nsExclude</option> <option value="--nsInclude">nsInclude</option> <option value="--nsFrom">nsFrom</option> <option value="--nsTo">nsTo</option> <option value="--objcheck">objcheck</option> <option value="--drop">drop</option> <option value="--dryRun">dryRun</option> <option value="--oplogReplay">oplogReplay</option> <option value="--oplogLimit">oplogLimit</option> <option value="--oplogFile">oplogFile</option> <option value="--keepIndexVersion">keepIndexVersion</option> <option value="--noIndexRestore">noIndexRestore</option> <option value="--noOptionsRestore">noOptionsRestore</option> <option value="--restoreDbUsersAndRoles">restoreDbUsersAndRoles</option> <option value="--writeConcern">writeConcern</option> <option value="--maintainInsertionOrder">maintainInsertionOrder</option> <option value="--numParallelCollections">numParallelCollections</option> <option value="--numInsertionWorkersPerCollection"> numInsertionWorkersPerCollection </option> <option value="--stopOnError">stopOnError</option> <option value="--bypassDocumentValidation">bypassDocumentValidation</option> <option value="--gzip">gzip</option> <option value="--archive">archive</option> <option value="--dir">dir</option> </select> </div> </div> {{> mongorestoreOptions}} <div class="form-group"> <div id="mongorestore"> <label class="col-lg-2 control-label">{{_ "logs"}}</label> <div class="col-lg-10"> <textarea id="txtMongorestoreLogs" class="form-control"></textarea> </div> </div> </div> </form> </div> <div class="ibox-footer"> <div class="row"> <div class="col-lg-12"> <button id="btnExecuteMongorestore" class="btn btn-block btn-outline btn-primary ladda-button" type="button" data-style="contract"> <strong>{{_ "execute"}}</strong></button> </div> </div> </div> </div> </div> </div> <div class="row"> <div class="col-lg-6"> <div class="ibox float-e-margins"> <div class="ibox-title"> <h5>Mongoexport</h5> <div class="ibox-tools"> <a id="btnClearMongoexportLogs" href="#" title="{{_ "delete_logs"}}"> <i class="fa fa-trash"></i> </a> </div> </div> <div class="ibox-content"> <form method="get" class="form-horizontal"> <div class="form-group"> <label class="col-lg-2 control-label">{{_ "arguments"}}</label> <div class="col-lg-10"> <select id="cmbMongoexportArgs" data-placeholder="{{_ "select_options"}}" multiple="true" class="chosen-select form-control" tabindex="-1"> <option value="-v">verbose</option> <option value="--quiet">quiet</option> <option value="--host">host</option> <option value="--port">port</option> <option value="--ipv6">ipv6</option> <option value="--ssl">ssl</option> <option value="--sslCAFile">sslCAFile</option> <option value="--sslPEMKeyFile">sslPEMKeyFile</option> <option value="--sslPEMKeyPassword">sslPEMKeyPassword</option> <option value="--sslCRLFile">sslCRLFile</option> <option value="--sslAllowInvalidCertificates"> sslAllowInvalidCertificates </option> <option value="--sslAllowInvalidHostnames"> sslAllowInvalidHostnames </option> <option value="--sslFIPSMode">sslFIPSMode</option> <option value="--username">username</option> <option value="--password">password</option> <option value="--authenticationDatabase"> authenticationDatabase </option> <option value="--authenticationMechanism"> authenticationMechanism </option> <option value="--gssapiServiceName">gssapiServiceName</option> <option value="--gssapiHostName">gssapiHostName</option> <option value="--db">db</option> <option value="--collection">collection</option> <option value="--fields">fields</option> <option value="--fieldFile">fieldFile</option> <option value="--query">query</option> <option value="--type">type</option> <option value="--out">out</option> <option value="--jsonArray">jsonArray</option> <option value="--pretty">pretty</option> <option value="--slaveOk">slaveOk</option> <option value="--readPreference">readPreference</option> <option value="--forceTableScan">forceTableScan</option> <option value="--skip">skip</option> <option value="--limit">limit</option> <option value="--sort">sort</option> </select> </div> </div> {{> mongoexportOptions}} <div class="form-group"> <div id="mongoexport"> <label class="col-lg-2 control-label">{{_ "logs"}}</label> <div class="col-lg-10"> <textarea id="txtMongoexportLogs" class="form-control"></textarea> </div> </div> </div> </form> </div> <div class="ibox-footer"> <div class="row"> <div class="col-lg-12"> <button id="btnExecuteMongoexport" class="btn btn-block btn-outline btn-primary ladda-button" type="button" data-style="contract"> <strong>{{_ "execute"}}</strong></button> </div> </div> </div> </div> </div> <div class="col-lg-6"> <div class="ibox float-e-margins"> <div class="ibox-title"> <h5>Mongoimport</h5> <div class="ibox-tools"> <a id="btnClearMongoimportLogs" href="#" title="{{_ "delete_logs"}}"> <i class="fa fa-trash"></i> </a> </div> </div> <div class="ibox-content"> <form method="get" class="form-horizontal"> <div class="form-group"> <label class="col-lg-2 control-label">{{_ "arguments"}}</label> <div class="col-lg-10"> <select id="cmbMongoimportArgs" data-placeholder="{{_ "select_options"}}" multiple="true" class="chosen-select form-control" tabindex="-1"> <option value="-v">verbose</option> <option value="--quiet">quiet</option> <option value="--host">host</option> <option value="--port">port</option> <option value="--ipv6">ipv6</option> <option value="--ssl">ssl</option> <option value="--sslCAFile">sslCAFile</option> <option value="--sslPEMKeyFile">sslPEMKeyFile</option> <option value="--sslPEMKeyPassword">sslPEMKeyPassword</option> <option value="--sslCRLFile">sslCRLFile</option> <option value="--sslAllowInvalidCertificates"> sslAllowInvalidCertificates </option> <option value="--sslAllowInvalidHostnames"> sslAllowInvalidHostnames </option> <option value="--sslFIPSMode">sslFIPSMode</option> <option value="--username">username</option> <option value="--password">password</option> <option value="--authenticationDatabase"> authenticationDatabase </option> <option value="--authenticationMechanism"> authenticationMechanism </option> <option value="--gssapiServiceName">gssapiServiceName</option> <option value="--gssapiHostName">gssapiHostName</option> <option value="--db">db</option> <option value="--collection">collection</option> <option value="--fields">fields</option> <option value="--fieldFile">fieldFile</option> <option value="--ignoreBlanks">ignoreBlanks</option> <option value="--type">type</option> <option value="--file">file</option> <option value="--drop">drop</option> <option value="--headerline">headerline</option> <option value="--mode">mode</option> <option value="--upsertFields">upsertFields</option> <option value="--stopOnError">stopOnError</option> <option value="--jsonArray">jsonArray</option> <option value="--maintainInsertionOrder">maintainInsertionOrder</option> <option value="--numInsertionWorkers">numInsertionWorkers</option> <option value="--writeConcern">writeConcern</option> <option value="--bypassDocumentValidation">bypassDocumentValidation</option> <option value="--columnsHaveTypes">columnsHaveTypes</option> <option value="--parseGrace">parseGrace</option> </select> </div> </div> {{> mongoimportOptions}} <div class="form-group"> <div id="mongoimport"> <label class="col-lg-2 control-label">{{_ "logs"}}</label> <div class="col-lg-10"> <textarea id="txtMongoimportLogs" class="form-control"></textarea> </div> </div> </div> </form> </div> <div class="ibox-footer"> <div class="row"> <div class="col-lg-12"> <button id="btnExecuteMongoimport" class="btn btn-block btn-outline btn-primary ladda-button" type="button" data-style="contract"> <strong>{{_ "execute"}}</strong></button> </div> </div> </div> </div> </div> </div> </div> {{/if}} </template>
{ "content_hash": "d0f3d9b1f18a33aedd3c4fc7b32821d1", "timestamp": "", "source": "github", "line_count": 414, "max_line_length": 120, "avg_line_length": 65.76086956521739, "alnum_prop": 0.3337373737373737, "repo_name": "rsercano/mongoclient", "id": "404cac9c98655d6d332e17d2bc22e7b56bfbcf35", "size": "27225", "binary": false, "copies": "3", "ref": "refs/heads/master", "path": "client/imports/views/pages/database_dump_restore/database_dump_restore.html", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "231960" }, { "name": "HTML", "bytes": "257863" }, { "name": "JavaScript", "bytes": "790708" }, { "name": "Shell", "bytes": "5146" } ], "symlink_target": "" }
import { graphql } from "gatsby" import * as React from "react" import slugify from "slugify" import Layout from "../components/layout" import * as components from "../components/references" function renderReferencedComponent(ref) { const Component = components[ref.__typename] if (!Component) { throw new Error( `Unable to render referenced component of type ${ref.__typename}` ) } return <Component {...ref} /> } const ContentReferencePage = ({ data }) => { const defaultEntries = data.default.nodes const englishEntries = data.english.nodes const germanEntries = data.german.nodes return ( <Layout> <h1>Default</h1> {defaultEntries.map(({ contentful_id, title, one, many }) => { const slug = slugify(title, { strict: true, lower: true }) let content = null if (many) { content = many.map(renderReferencedComponent) } if (one) { content = renderReferencedComponent(one) } return ( <div data-cy-id={`default-${slug}`} key={contentful_id}> <h2>{title}</h2> {content} </div> ) })} <h1>English Locale</h1> {englishEntries.map( ({ contentful_id, title, oneLocalized, manyLocalized }) => { const slug = slugify(title, { strict: true, lower: true }) let content = null if (manyLocalized) { content = manyLocalized.map(renderReferencedComponent) } if (oneLocalized) { content = renderReferencedComponent(oneLocalized) } return ( <div data-cy-id={`english-${slug}`} key={contentful_id}> <h2>{title}</h2> {content} </div> ) } )} <h1>German Locale</h1> {germanEntries.map( ({ contentful_id, title, oneLocalized, manyLocalized }) => { const slug = slugify(title, { strict: true, lower: true }) let content = null if (manyLocalized) { content = manyLocalized.map(renderReferencedComponent) } if (oneLocalized) { content = renderReferencedComponent(oneLocalized) } return ( <div data-cy-id={`german-${slug}`} key={contentful_id}> <h2>{title}</h2> {content} </div> ) } )} </Layout> ) } export default ContentReferencePage export const pageQuery = graphql` query ContentReferenceQuery { default: allContentfulContentReference( sort: { fields: title } filter: { node_locale: { eq: "en-US" }, title: { glob: "!*Localized*" } } ) { nodes { title contentful_id one { __typename ... on ContentfulText { contentful_id title short } ... on ContentfulContentReference { contentful_id title one { ... on ContentfulText { title short } ... on ContentfulContentReference { title } } many { ... on ContentfulText { title short } ... on ContentfulNumber { title integer } ... on ContentfulContentReference { title } } } } many { __typename ... on ContentfulText { contentful_id title short } ... on ContentfulNumber { contentful_id title integer } ... on ContentfulContentReference { contentful_id title one { ... on ContentfulText { title short } ... on ContentfulContentReference { title } } many { ... on ContentfulText { title short } ... on ContentfulNumber { title integer } ... on ContentfulContentReference { title } } } } } } english: allContentfulContentReference( sort: { fields: title } filter: { node_locale: { eq: "en-US" }, title: { glob: "*Localized*" } } ) { nodes { title contentful_id oneLocalized { __typename title decimal integer } manyLocalized { __typename ... on ContentfulNumber { title decimal integer } ... on ContentfulText { title short longPlain { longPlain } } } } } german: allContentfulContentReference( sort: { fields: title } filter: { node_locale: { eq: "de-DE" }, title: { glob: "*Localized*" } } ) { nodes { title contentful_id oneLocalized { __typename title decimal integer } manyLocalized { __typename ... on ContentfulNumber { title decimal integer } ... on ContentfulText { title short longPlain { longPlain } } } } } } `
{ "content_hash": "07b21cae0bccc56f8cde94c904e3bb0e", "timestamp": "", "source": "github", "line_count": 241, "max_line_length": 79, "avg_line_length": 23.904564315352697, "alnum_prop": 0.44766533587918766, "repo_name": "gatsbyjs/gatsby", "id": "642722e2a92d6d2e6490d32185951d4ab44d2e6d", "size": "5761", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "e2e-tests/contentful/src/pages/content-reference.js", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "93774" }, { "name": "Dockerfile", "bytes": "2751" }, { "name": "EJS", "bytes": "461" }, { "name": "HTML", "bytes": "62227" }, { "name": "JavaScript", "bytes": "5243904" }, { "name": "Less", "bytes": "218" }, { "name": "PHP", "bytes": "2010" }, { "name": "Python", "bytes": "281" }, { "name": "SCSS", "bytes": "218" }, { "name": "Shell", "bytes": "10621" }, { "name": "Stylus", "bytes": "206" }, { "name": "TypeScript", "bytes": "3099577" } ], "symlink_target": "" }
// Copyright 2014 Sean Farrow // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. namespace EventStoreRunner { public class EventStoreRunnerOptionsBuilder { private bool _useembeddedclient; private bool _purgedata; private bool _runinmemory; private string _datadirectory; internal EventStoreRunnerOptionsBuilder UseEmbeddedClient() { _useembeddedclient = true; _runinmemory = true; _datadirectory = "data"; return this; } public EventStoreRunnerOptionsBuilder RunInMemory() { _runinmemory = true; return this; } public EventStoreRunnerOptionsBuilder UseFullServer() { _useembeddedclient = false; return this; } public EventStoreRunnerOptionsBuilder UseDataDirectory(string directory) { _datadirectory = directory; return this; } public EventStoreRunnerOptionsBuilder PurgeData() { _purgedata = true; return this; } public EventStoreRunnerOptions Build() { return new EventStoreRunnerOptions(_useembeddedclient, _runinmemory, _datadirectory, _purgedata); } } }
{ "content_hash": "08854dc5385ab7b03de8295f855a3925", "timestamp": "", "source": "github", "line_count": 61, "max_line_length": 109, "avg_line_length": 30.114754098360656, "alnum_prop": 0.6287425149700598, "repo_name": "SeanFarrow/EventStoreRunner", "id": "de5857361324514b30c6e5e693869cd79bb7c2da", "size": "1839", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/EventStoreRunner/EventStoreRunnerOptionsBuilder.cs", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "C#", "bytes": "11997" }, { "name": "JavaScript", "bytes": "33828" } ], "symlink_target": "" }
@interface POIImageSlider : UIView @property (strong,nonatomic) NSArray *imageData; + (NSString*)nibName; -(void)setImageViewData:(NSArray *)imageData; - (void)startAutoPagingWithDuration:(NSTimeInterval)pagingInterval; @end
{ "content_hash": "e83f03f650f678248a0bc36b212ceb47", "timestamp": "", "source": "github", "line_count": 8, "max_line_length": 67, "avg_line_length": 28.375, "alnum_prop": 0.7973568281938326, "repo_name": "JingtingChen/POIImageSlider", "id": "ba18ab15f9e12a0d624420ae6d7224fc9151718d", "size": "332", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "Pod/Classes/POIImageSlider.h", "mode": "33188", "license": "mit", "language": [ { "name": "C", "bytes": "440" }, { "name": "Objective-C", "bytes": "7244" }, { "name": "Ruby", "bytes": "4315" }, { "name": "Shell", "bytes": "6817" } ], "symlink_target": "" }
layout: book number: 1 title: Introduction --- This is a very short book about **doobie**, which is a pure-functional JDBC layer for Scala. **doobie** provides low-level access to everything in `java.sql` (as of JDK 1.6, JDBC 4.0), allowing you to write any JDBC program in a pure functional style. However the focus of this book is the **high-level API**, which is where most users will spend their time. This book is organized cookbook-style: we demonstrate a common task and then explain how it works, perhaps in more detail than you want right now. The goal is to get you up and running quickly, but give you a handle on the deeper stuff if you need it later. ### Target Audience This library is designed for people who are interested in typed, pure functional programming. If you are not a [scalaz](https://github.com/scalaz/scalaz) user or are not familiar with functional I/O and monadic effects, you may need to go slowly and may want to spend some time reading [Functional Programming in Scala](http://manning.com/bjarnason/), which introduces all of the ideas that you will find when exploring **doobie**. Having said this, if you find yourself confused or frustrated by this documentation or the **doobie** API, *please* ask a question on [Gitter](https://gitter.im/tpolecat/doobie), file an [issue](https://github.com/tpolecat/doobie/issues) or find **tpolecat** on [Twitter](https://twitter.com/tpolecat) or `#scala` (FreeNode IRC) and ask for help. Both the library and the documentation are young and are changing quickly, and it is inevitable that some things will be unclear. Accordingly, **this book is updated for each release** to address problems and omissions. > Please take a moment to check the banner in the upper-right corner to ensure that you are reading the right version of this book! If not, use the **versions** menu above to select the one you want. ### The Setup This book is compiled as part of the build using the [tut](https://github.com/tpolecat/tut) tutorial generator, so the code examples are guaranteed to compile (and with luck should also work correctly). Each page stands on its own: if you copy and paste code samples starting from the top, it will work in your REPL as long as you have the proper setup, described here. #### Sample Database Setup The example code assumes a local [PostgreSQL](http://www.postgresql.org/) server with a `postgres` user with no password, [PostGIS](http://postgis.net/) extensions (optional), and the sample `world` database loaded up. If you're on a Mac you might check out the excellent [Postgres.app](http://postgresapp.com/) if you don't want to install PostgreSQL as a service. You can set up the user and sample database (and an `enum` we use in a few examples) as follows: ``` $ curl -O https://raw.githubusercontent.com/tpolecat/doobie/master/world.sql $ psql -c 'create user postgres createdb' $ psql -c 'create database world;' -U postgres $ psql -c '\i world.sql' -d world -U postgres $ psql -d world -c "create type myenum as enum ('foo', 'bar')" -U postgres $ psql -d world -c "create extension postgis" -U postgres ``` Skip the last statement if you don't have PostGIS installed. Note that the final `ANALYZE` comand in the import will emit a few errors for system tables. This is expected and is fine. Try a query or two to double-check your setup: ``` $ psql -d world -U postgres psql (9.3.5) Type "help" for help. world=> select name, continent, population from country where name like 'U%'; name | continent | population --------------------------------------+---------------+------------ United Arab Emirates | Asia | 2441000 United Kingdom | Europe | 59623400 Uganda | Africa | 21778000 Ukraine | Europe | 50456000 Uruguay | South America | 3337000 Uzbekistan | Asia | 24318000 United States | North America | 278357000 United States Minor Outlying Islands | Oceania | 0 (8 rows) world=> \q $ ``` You can of course change this setup if you like, but you will need to adjust your JDBC connection information accordingly. Most examples will work with any compliant database, but in a few cases (noted in the text) we rely on vendor-specific behavior. #### Scala Setup On the Scala side you just need a console with the proper dependencies. A minimal `build.sbt` would look something like this. ```scala scalaVersion := "2.11.7" // also works with 2.10 lazy val doobieVersion = "0.3.0" libraryDependencies ++= Seq( "org.tpolecat" %% "doobie-core" % doobieVersion, "org.tpolecat" %% "doobie-contrib-postgresql" % doobieVersion, "org.tpolecat" %% "doobie-contrib-specs2" % doobieVersion ) ``` If you are not using PostgreSQL you can omit `doobie-contrib-postgresql` and will need to add the appropriate JDBC driver as a dependency. Note that there is a `doobie-contrib-h2` add-on if you happen to be using [H2](http://www.h2database.com/). ### Conventions Each page begins with some imports, like this. ```scala import scalaz._, Scalaz._ import doobie.imports._ ``` After that there is text interspersed with code examples. Sometimes definitions will stand alone. ```scala case class Person(name: String, age: Int) val nel = NonEmptyList(Person("Bob", 12), Person("Alice", 14)) ``` And sometimes they will appear as a REPL interaction. ```scala scala> nel.head res2: Person = Person(Bob,12) scala> nel.tail res3: scalaz.IList[Person] = [Person(Alice,14)] ``` Sometimes we demonstrate that something doesn't compile. In such cases it will be clear from the context that this is expected, and not a problem with the documentation. ```scala scala> woozle(nel) // doesn't compile <console>:25: error: not found: value woozle woozle(nel) // doesn't compile ^ ``` ### Feedback and Contributions Feedback on **doobie** or this book is genuinely welcome. Please feel free to file a [pull request](https://github.com/tpolecat/doobie) if you have a contribution, or file an [issue](https://github.com/tpolecat/doobie/issues), or find and chat with **tpolecat** as mentioned above.
{ "content_hash": "0cd2f5252e361f1d9f8f2716fafe4262", "timestamp": "", "source": "github", "line_count": 122, "max_line_length": 566, "avg_line_length": 51.877049180327866, "alnum_prop": 0.7018486332753989, "repo_name": "tpolecat/tpolecat.github.io", "id": "f06db6890280d64e13dd09a820c8cfeebcce5b30", "size": "6333", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "_doobie-0.3.0/01-Introduction.md", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "72020" }, { "name": "HTML", "bytes": "1529544" }, { "name": "JavaScript", "bytes": "416954" }, { "name": "PHP", "bytes": "1742" }, { "name": "Ruby", "bytes": "3312" } ], "symlink_target": "" }
/*! ***************************************************************************** Copyright (c) Microsoft Corporation. Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted. THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. ***************************************************************************** */ var __assign = function() { __assign = Object.assign || function __assign(t) { for (var s, i = 1, n = arguments.length; i < n; i++) { s = arguments[i]; for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p]; } return t; }; return __assign.apply(this, arguments); }; var thumbnailsSettings = { thumbnail: true, animateThumb: true, currentPagerPosition: 'middle', alignThumbnails: 'middle', thumbWidth: 100, thumbHeight: '80px', thumbMargin: 5, appendThumbnailsTo: '.lg-components', toggleThumb: false, enableThumbDrag: true, enableThumbSwipe: true, thumbnailSwipeThreshold: 10, loadYouTubeThumbnail: true, youTubeThumbSize: 1, }; /** * List of lightGallery events * All events should be documented here * Below interfaces are used to build the website documentations * */ var lGEvents = { afterAppendSlide: 'lgAfterAppendSlide', init: 'lgInit', hasVideo: 'lgHasVideo', containerResize: 'lgContainerResize', updateSlides: 'lgUpdateSlides', afterAppendSubHtml: 'lgAfterAppendSubHtml', beforeOpen: 'lgBeforeOpen', afterOpen: 'lgAfterOpen', slideItemLoad: 'lgSlideItemLoad', beforeSlide: 'lgBeforeSlide', afterSlide: 'lgAfterSlide', posterClick: 'lgPosterClick', dragStart: 'lgDragStart', dragMove: 'lgDragMove', dragEnd: 'lgDragEnd', beforeNextSlide: 'lgBeforeNextSlide', beforePrevSlide: 'lgBeforePrevSlide', beforeClose: 'lgBeforeClose', afterClose: 'lgAfterClose', }; var Thumbnail = /** @class */ (function () { function Thumbnail(instance, $LG) { this.thumbOuterWidth = 0; this.thumbTotalWidth = 0; this.translateX = 0; this.thumbClickable = false; // get lightGallery core plugin instance this.core = instance; this.$LG = $LG; return this; } Thumbnail.prototype.init = function () { // extend module default settings with lightGallery core settings this.settings = __assign(__assign({}, thumbnailsSettings), this.core.settings); this.thumbOuterWidth = 0; this.thumbTotalWidth = this.core.galleryItems.length * (this.settings.thumbWidth + this.settings.thumbMargin); // Thumbnail animation value this.translateX = 0; this.setAnimateThumbStyles(); if (!this.core.settings.allowMediaOverlap) { this.settings.toggleThumb = false; } if (this.settings.thumbnail) { this.build(); if (this.settings.animateThumb) { if (this.settings.enableThumbDrag) { this.enableThumbDrag(); } if (this.settings.enableThumbSwipe) { this.enableThumbSwipe(); } this.thumbClickable = false; } else { this.thumbClickable = true; } this.toggleThumbBar(); this.thumbKeyPress(); } }; Thumbnail.prototype.build = function () { var _this = this; this.setThumbMarkup(); this.manageActiveClassOnSlideChange(); this.$lgThumb.first().on('click.lg touchend.lg', function (e) { var $target = _this.$LG(e.target); if (!$target.hasAttribute('data-lg-item-id')) { return; } setTimeout(function () { // In IE9 and bellow touch does not support // Go to slide if browser does not support css transitions if (_this.thumbClickable && !_this.core.lgBusy) { var index = parseInt($target.attr('data-lg-item-id')); _this.core.slide(index, false, true, false); } }, 50); }); this.core.LGel.on(lGEvents.beforeSlide + ".thumb", function (event) { var index = event.detail.index; _this.animateThumb(index); }); this.core.LGel.on(lGEvents.beforeOpen + ".thumb", function () { _this.thumbOuterWidth = _this.core.outer.get().offsetWidth; }); this.core.LGel.on(lGEvents.updateSlides + ".thumb", function () { _this.rebuildThumbnails(); }); this.core.LGel.on(lGEvents.containerResize + ".thumb", function () { if (!_this.core.lgOpened) return; setTimeout(function () { _this.thumbOuterWidth = _this.core.outer.get().offsetWidth; _this.animateThumb(_this.core.index); _this.thumbOuterWidth = _this.core.outer.get().offsetWidth; }, 50); }); }; Thumbnail.prototype.setThumbMarkup = function () { var thumbOuterClassNames = 'lg-thumb-outer '; if (this.settings.alignThumbnails) { thumbOuterClassNames += "lg-thumb-align-" + this.settings.alignThumbnails; } var html = "<div class=\"" + thumbOuterClassNames + "\">\n <div class=\"lg-thumb lg-group\">\n </div>\n </div>"; this.core.outer.addClass('lg-has-thumb'); if (this.settings.appendThumbnailsTo === '.lg-components') { this.core.$lgComponents.append(html); } else { this.core.outer.append(html); } this.$thumbOuter = this.core.outer.find('.lg-thumb-outer').first(); this.$lgThumb = this.core.outer.find('.lg-thumb').first(); if (this.settings.animateThumb) { this.core.outer .find('.lg-thumb') .css('transition-duration', this.core.settings.speed + 'ms') .css('width', this.thumbTotalWidth + 'px') .css('position', 'relative'); } this.setThumbItemHtml(this.core.galleryItems); }; Thumbnail.prototype.enableThumbDrag = function () { var _this = this; var thumbDragUtils = { cords: { startX: 0, endX: 0, }, isMoved: false, newTranslateX: 0, startTime: new Date(), endTime: new Date(), touchMoveTime: 0, }; var isDragging = false; this.$thumbOuter.addClass('lg-grab'); this.core.outer .find('.lg-thumb') .first() .on('mousedown.lg.thumb', function (e) { if (_this.thumbTotalWidth > _this.thumbOuterWidth) { // execute only on .lg-object e.preventDefault(); thumbDragUtils.cords.startX = e.pageX; thumbDragUtils.startTime = new Date(); _this.thumbClickable = false; isDragging = true; // ** Fix for webkit cursor issue https://code.google.com/p/chromium/issues/detail?id=26723 _this.core.outer.get().scrollLeft += 1; _this.core.outer.get().scrollLeft -= 1; // * _this.$thumbOuter .removeClass('lg-grab') .addClass('lg-grabbing'); } }); this.$LG(window).on("mousemove.lg.thumb.global" + this.core.lgId, function (e) { if (!_this.core.lgOpened) return; if (isDragging) { thumbDragUtils.cords.endX = e.pageX; thumbDragUtils = _this.onThumbTouchMove(thumbDragUtils); } }); this.$LG(window).on("mouseup.lg.thumb.global" + this.core.lgId, function () { if (!_this.core.lgOpened) return; if (thumbDragUtils.isMoved) { thumbDragUtils = _this.onThumbTouchEnd(thumbDragUtils); } else { _this.thumbClickable = true; } if (isDragging) { isDragging = false; _this.$thumbOuter.removeClass('lg-grabbing').addClass('lg-grab'); } }); }; Thumbnail.prototype.enableThumbSwipe = function () { var _this = this; var thumbDragUtils = { cords: { startX: 0, endX: 0, }, isMoved: false, newTranslateX: 0, startTime: new Date(), endTime: new Date(), touchMoveTime: 0, }; this.$lgThumb.on('touchstart.lg', function (e) { if (_this.thumbTotalWidth > _this.thumbOuterWidth) { e.preventDefault(); thumbDragUtils.cords.startX = e.targetTouches[0].pageX; _this.thumbClickable = false; thumbDragUtils.startTime = new Date(); } }); this.$lgThumb.on('touchmove.lg', function (e) { if (_this.thumbTotalWidth > _this.thumbOuterWidth) { e.preventDefault(); thumbDragUtils.cords.endX = e.targetTouches[0].pageX; thumbDragUtils = _this.onThumbTouchMove(thumbDragUtils); } }); this.$lgThumb.on('touchend.lg', function () { if (thumbDragUtils.isMoved) { thumbDragUtils = _this.onThumbTouchEnd(thumbDragUtils); } else { _this.thumbClickable = true; } }); }; // Rebuild thumbnails Thumbnail.prototype.rebuildThumbnails = function () { var _this = this; // Remove transitions this.$thumbOuter.addClass('lg-rebuilding-thumbnails'); setTimeout(function () { _this.thumbTotalWidth = _this.core.galleryItems.length * (_this.settings.thumbWidth + _this.settings.thumbMargin); _this.$lgThumb.css('width', _this.thumbTotalWidth + 'px'); _this.$lgThumb.empty(); _this.setThumbItemHtml(_this.core.galleryItems); _this.animateThumb(_this.core.index); }, 50); setTimeout(function () { _this.$thumbOuter.removeClass('lg-rebuilding-thumbnails'); }, 200); }; // @ts-check Thumbnail.prototype.setTranslate = function (value) { this.$lgThumb.css('transform', 'translate3d(-' + value + 'px, 0px, 0px)'); }; Thumbnail.prototype.getPossibleTransformX = function (left) { if (left > this.thumbTotalWidth - this.thumbOuterWidth) { left = this.thumbTotalWidth - this.thumbOuterWidth; } if (left < 0) { left = 0; } return left; }; Thumbnail.prototype.animateThumb = function (index) { this.$lgThumb.css('transition-duration', this.core.settings.speed + 'ms'); if (this.settings.animateThumb) { var position = 0; switch (this.settings.currentPagerPosition) { case 'left': position = 0; break; case 'middle': position = this.thumbOuterWidth / 2 - this.settings.thumbWidth / 2; break; case 'right': position = this.thumbOuterWidth - this.settings.thumbWidth; } this.translateX = (this.settings.thumbWidth + this.settings.thumbMargin) * index - 1 - position; if (this.translateX > this.thumbTotalWidth - this.thumbOuterWidth) { this.translateX = this.thumbTotalWidth - this.thumbOuterWidth; } if (this.translateX < 0) { this.translateX = 0; } this.setTranslate(this.translateX); } }; Thumbnail.prototype.onThumbTouchMove = function (thumbDragUtils) { thumbDragUtils.newTranslateX = this.translateX; thumbDragUtils.isMoved = true; thumbDragUtils.touchMoveTime = new Date().valueOf(); thumbDragUtils.newTranslateX -= thumbDragUtils.cords.endX - thumbDragUtils.cords.startX; thumbDragUtils.newTranslateX = this.getPossibleTransformX(thumbDragUtils.newTranslateX); // move current slide this.setTranslate(thumbDragUtils.newTranslateX); this.$thumbOuter.addClass('lg-dragging'); return thumbDragUtils; }; Thumbnail.prototype.onThumbTouchEnd = function (thumbDragUtils) { thumbDragUtils.isMoved = false; thumbDragUtils.endTime = new Date(); this.$thumbOuter.removeClass('lg-dragging'); var touchDuration = thumbDragUtils.endTime.valueOf() - thumbDragUtils.startTime.valueOf(); var distanceXnew = thumbDragUtils.cords.endX - thumbDragUtils.cords.startX; var speedX = Math.abs(distanceXnew) / touchDuration; // Some magical numbers // Can be improved if (speedX > 0.15 && thumbDragUtils.endTime.valueOf() - thumbDragUtils.touchMoveTime < 30) { speedX += 1; if (speedX > 2) { speedX += 1; } speedX = speedX + speedX * (Math.abs(distanceXnew) / this.thumbOuterWidth); this.$lgThumb.css('transition-duration', Math.min(speedX - 1, 2) + 'settings'); distanceXnew = distanceXnew * speedX; this.translateX = this.getPossibleTransformX(this.translateX - distanceXnew); this.setTranslate(this.translateX); } else { this.translateX = thumbDragUtils.newTranslateX; } if (Math.abs(thumbDragUtils.cords.endX - thumbDragUtils.cords.startX) < this.settings.thumbnailSwipeThreshold) { this.thumbClickable = true; } return thumbDragUtils; }; Thumbnail.prototype.getThumbHtml = function (thumb, index) { var slideVideoInfo = this.core.galleryItems[index].__slideVideoInfo || {}; var thumbImg; if (slideVideoInfo.youtube) { if (this.settings.loadYouTubeThumbnail) { thumbImg = '//img.youtube.com/vi/' + slideVideoInfo.youtube[1] + '/' + this.settings.youTubeThumbSize + '.jpg'; } else { thumbImg = thumb; } } else { thumbImg = thumb; } return "<div data-lg-item-id=\"" + index + "\" class=\"lg-thumb-item " + (index === this.core.index ? ' active' : '') + "\" \n style=\"width:" + this.settings.thumbWidth + "px; height: " + this.settings.thumbHeight + ";\n margin-right: " + this.settings.thumbMargin + "px;\">\n <img data-lg-item-id=\"" + index + "\" src=\"" + thumbImg + "\" />\n </div>"; }; Thumbnail.prototype.getThumbItemHtml = function (items) { var thumbList = ''; for (var i = 0; i < items.length; i++) { thumbList += this.getThumbHtml(items[i].thumb, i); } return thumbList; }; Thumbnail.prototype.setThumbItemHtml = function (items) { var thumbList = this.getThumbItemHtml(items); this.$lgThumb.html(thumbList); }; Thumbnail.prototype.setAnimateThumbStyles = function () { if (this.settings.animateThumb) { this.core.outer.addClass('lg-animate-thumb'); } }; // Manage thumbnail active calss Thumbnail.prototype.manageActiveClassOnSlideChange = function () { var _this = this; // manage active class for thumbnail this.core.LGel.on(lGEvents.beforeSlide + ".thumb", function (event) { var $thumb = _this.core.outer.find('.lg-thumb-item'); var index = event.detail.index; $thumb.removeClass('active'); $thumb.eq(index).addClass('active'); }); }; // Toggle thumbnail bar Thumbnail.prototype.toggleThumbBar = function () { var _this = this; if (this.settings.toggleThumb) { this.core.outer.addClass('lg-can-toggle'); this.core.$toolbar.append('<button type="button" aria-label="Toggle thumbnails" class="lg-toggle-thumb lg-icon"></button>'); this.core.outer .find('.lg-toggle-thumb') .first() .on('click.lg', function () { _this.core.outer.toggleClass('lg-components-open'); }); } }; Thumbnail.prototype.thumbKeyPress = function () { var _this = this; this.$LG(window).on("keydown.lg.thumb.global" + this.core.lgId, function (e) { if (!_this.core.lgOpened || !_this.settings.toggleThumb) return; if (e.keyCode === 38) { e.preventDefault(); _this.core.outer.addClass('lg-components-open'); } else if (e.keyCode === 40) { e.preventDefault(); _this.core.outer.removeClass('lg-components-open'); } }); }; Thumbnail.prototype.destroy = function () { if (this.settings.thumbnail) { this.$LG(window).off(".lg.thumb.global" + this.core.lgId); this.core.LGel.off('.lg.thumb'); this.core.LGel.off('.thumb'); this.$thumbOuter.remove(); this.core.outer.removeClass('lg-has-thumb'); } }; return Thumbnail; }()); export default Thumbnail; //# sourceMappingURL=lg-thumbnail.es5.js.map
{ "content_hash": "ac7995f5510e0df7ad6f4f5eb757bf1f", "timestamp": "", "source": "github", "line_count": 466, "max_line_length": 399, "avg_line_length": 40.47854077253219, "alnum_prop": 0.5341144038594073, "repo_name": "cdnjs/cdnjs", "id": "90bbecc84af1ecaf38bde690e05290b5b4722bda", "size": "19002", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "ajax/libs/lightgallery/2.1.4/plugins/thumbnail/lg-thumbnail.es5.js", "mode": "33188", "license": "mit", "language": [], "symlink_target": "" }
"""Tests for tensorflow.ops.io_ops.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import math import os.path import time import contextlib import shutil import tempfile import tensorflow as tf import numpy as np import six from google.protobuf.any_pb2 import Any from tensorflow.core.framework import graph_pb2 from tensorflow.core.protobuf import meta_graph_pb2 from tensorflow.core.protobuf import queue_runner_pb2 from tensorflow.python.framework import errors from tensorflow.python.framework import function from tensorflow.python.platform import gfile from tensorflow.python.training import saver as saver_module from tensorflow.python.util import compat def _TestDir(test_name): test_dir = os.path.join(tf.test.get_temp_dir(), test_name) if os.path.exists(test_dir): shutil.rmtree(test_dir) gfile.MakeDirs(test_dir) return test_dir class SaverTest(tf.test.TestCase): def testBasics(self): save_path = os.path.join(self.get_temp_dir(), "basics") # Build a graph with 2 parameter nodes, and Save and # Restore nodes for them. v0 = tf.Variable(10.0, name="v0") v1 = tf.Variable(20.0, name="v1") save = tf.train.Saver({"v0": v0, "v1": v1}, restore_sequentially=True) init_all_op = tf.initialize_all_variables() with self.test_session() as sess: # Initialize all variables sess.run(init_all_op) # Check that the parameter nodes have been initialized. self.assertEqual(10.0, v0.eval()) self.assertEqual(20.0, v1.eval()) # Save the initialized values in the file at "save_path" val = save.save(sess, save_path) self.assertTrue(isinstance(val, six.string_types)) self.assertEqual(save_path, val) # Start a second session. In that session the parameter nodes # have not been initialized either. with self.test_session() as sess: v0 = tf.Variable(-1.0, name="v0") v1 = tf.Variable(-1.0, name="v1") save = tf.train.Saver({"v0": v0, "v1": v1}) with self.assertRaisesWithPredicateMatch( tf.OpError, lambda e: "uninitialized value v0" in e.message): sess.run(v0) with self.assertRaisesWithPredicateMatch( tf.OpError, lambda e: "uninitialized value v1" in e.message): sess.run(v1) # Restore the saved values in the parameter nodes. save.restore(sess, save_path) # Check that the parameter nodes have been restored. self.assertEqual(10.0, v0.eval()) self.assertEqual(20.0, v1.eval()) # Build another graph with 2 nodes, initialized # differently, and a Restore node for them. with self.test_session() as sess: v0_2 = tf.Variable(1000.0, name="v0") v1_2 = tf.Variable(2000.0, name="v1") save2 = tf.train.Saver({"v0": v0_2, "v1": v1_2}) tf.initialize_all_variables().run() # Check that the parameter nodes have been initialized. self.assertEqual(1000.0, v0_2.eval()) self.assertEqual(2000.0, v1_2.eval()) # Restore the values saved earlier in the parameter nodes. save2.restore(sess, save_path) # Check that the parameter nodes have been restored. self.assertEqual(10.0, v0_2.eval()) self.assertEqual(20.0, v1_2.eval()) def testInt64(self): save_path = os.path.join(self.get_temp_dir(), "int64") with self.test_session() as sess: # Build a graph with 1 node, and save and restore for them. v = tf.Variable(np.int64(15), name="v") save = tf.train.Saver({"v": v}, restore_sequentially=True) tf.initialize_all_variables().run() # Save the initialized values in the file at "save_path" val = save.save(sess, save_path) self.assertTrue(isinstance(val, six.string_types)) self.assertEqual(save_path, val) with self.test_session() as sess: v = tf.Variable(np.int64(-1), name="v") save = tf.train.Saver({"v": v}) with self.assertRaisesWithPredicateMatch( tf.OpError, lambda e: "uninitialized value v" in e.message): sess.run(v) # Restore the saved values in the parameter nodes. save.restore(sess, save_path) # Check that the parameter nodes have been restored. self.assertEqual(np.int64(15), v.eval()) def testSomeErrors(self): with tf.Graph().as_default(): v0 = tf.Variable([10.0], name="v0") v1 = tf.Variable([20.0], name="v1") v2 = tf.Variable([20.0], name="v2") v2._set_save_slice_info(tf.Variable.SaveSliceInfo("v1", [1], [0], [1])) # By default the name used for "v2" will be "v1" and raise an error. with self.assertRaisesRegexp(ValueError, "same name: v1"): tf.train.Saver([v0, v1, v2]) # The names are different and will work. tf.train.Saver({"vee1": v1, "other": [v2]}) def testBasicsWithListOfVariables(self): save_path = os.path.join(self.get_temp_dir(), "basics_with_list") with self.test_session(graph=tf.Graph()) as sess: # Build a graph with 2 parameter nodes, and Save and # Restore nodes for them. v0 = tf.Variable(10.0, name="v0") v1 = tf.Variable(20.0, name="v1") save = tf.train.Saver([v0, v1]) tf.initialize_all_variables().run() # Check that the parameter nodes have been initialized. self.assertEqual(10.0, v0.eval()) self.assertEqual(20.0, v1.eval()) # Save the initialized values in the file at "save_path" val = save.save(sess, save_path) self.assertTrue(isinstance(val, six.string_types)) self.assertEqual(save_path, val) # Start a second session. In that session the variables # have not been initialized either. with self.test_session(graph=tf.Graph()) as sess: v0 = tf.Variable(-1.0, name="v0") v1 = tf.Variable(-1.0, name="v1") save = tf.train.Saver([v0, v1]) with self.assertRaisesWithPredicateMatch( tf.OpError, lambda e: "uninitialized value v0" in e.message): sess.run(v0) with self.assertRaisesWithPredicateMatch( tf.OpError, lambda e: "uninitialized value v1" in e.message): sess.run(v1) # Restore the saved values in the parameter nodes. save.restore(sess, save_path) # Check that the parameter nodes have been restored. self.assertEqual(10.0, v0.eval()) self.assertEqual(20.0, v1.eval()) # Build another graph with 2 nodes, initialized # differently, and a Restore node for them. with self.test_session(graph=tf.Graph()) as sess: v0_2 = tf.Variable(1000.0, name="v0") v1_2 = tf.Variable(2000.0, name="v1") save2 = tf.train.Saver([v0_2, v1_2]) tf.initialize_all_variables().run() # Check that the parameter nodes have been initialized. self.assertEqual(1000.0, v0_2.eval()) self.assertEqual(2000.0, v1_2.eval()) # Restore the values saved earlier in the parameter nodes. save2.restore(sess, save_path) # Check that the parameter nodes have been restored. self.assertEqual(10.0, v0_2.eval()) self.assertEqual(20.0, v1_2.eval()) def _SaveAndLoad(self, var_name, var_value, other_value, save_path): with self.test_session() as sess: var = tf.Variable(var_value, name=var_name) save = tf.train.Saver({var_name: var}) var.initializer.run() val = save.save(sess, save_path) self.assertEqual(save_path, val) with self.test_session() as sess: var = tf.Variable(other_value, name=var_name) save = tf.train.Saver({var_name: var}) save.restore(sess, save_path) self.assertAllClose(var_value, var.eval()) def testCacheRereadsFile(self): save_path = os.path.join(self.get_temp_dir(), "cache_rereads") # Save and reload one Variable named "var0". self._SaveAndLoad("var0", 0.0, 1.0, save_path) # Save and reload one Variable named "var1" in the same file. # The cached readers should know to re-read the file. self._SaveAndLoad("var1", 1.1, 2.2, save_path) def testGPU(self): if not tf.test.is_built_with_cuda(): return save_path = os.path.join(self.get_temp_dir(), "gpu") with tf.Session("", graph=tf.Graph()) as sess: with sess.graph.device("/gpu:0"): v0_1 = tf.Variable(123.45) save = tf.train.Saver({"v0": v0_1}) tf.initialize_all_variables().run() save.save(sess, save_path) with tf.Session("", graph=tf.Graph()) as sess: with sess.graph.device("/gpu:0"): v0_2 = tf.Variable(543.21) save = tf.train.Saver({"v0": v0_2}) tf.initialize_all_variables().run() self.assertAllClose(543.21, v0_2.eval()) save.restore(sess, save_path) self.assertAllClose(123.45, v0_2.eval()) def testVariables(self): save_path = os.path.join(self.get_temp_dir(), "variables") with tf.Session("", graph=tf.Graph()) as sess: one = tf.Variable(1.0) twos = tf.Variable([2.0, 2.0, 2.0]) init = tf.initialize_all_variables() save = tf.train.Saver(tf.all_variables()) init.run() save.save(sess, save_path) with tf.Session("", graph=tf.Graph()) as sess: one = tf.Variable(0.0) twos = tf.Variable([0.0, 0.0, 0.0]) # Saver with no arg, defaults to 'all variables'. save = tf.train.Saver() save.restore(sess, save_path) self.assertAllClose(1.0, one.eval()) self.assertAllClose([2.0, 2.0, 2.0], twos.eval()) def testSaveWithGlobalStep(self): save_path = os.path.join(self.get_temp_dir(), "ckpt_with_global_step") global_step_int = 5 # Save and reload one Variable named "var0". self._SaveAndLoad("var0", 0.0, 1.0, save_path) for use_tensor in [True, False]: with self.test_session() as sess: var = tf.Variable(1.0, name="var0") save = tf.train.Saver({var.op.name: var}) var.initializer.run() if use_tensor: global_step = tf.constant(global_step_int) val = save.save(sess, save_path, global_step=global_step) else: val = save.save(sess, save_path, global_step=global_step_int) expected_save_path = "%s-%d" % (save_path, global_step_int) self.assertEqual(expected_save_path, val) class SaveRestoreShardedTest(tf.test.TestCase): def testBasics(self): save_path = os.path.join(self.get_temp_dir(), "sharded") # Build a graph with 2 parameter nodes on different devices. with tf.Session( target="", config=tf.ConfigProto(device_count={"CPU": 2})) as sess: with sess.graph.device("/cpu:0"): v0 = tf.Variable(10, name="v0") with sess.graph.device("/cpu:1"): v1 = tf.Variable(20, name="v1") save = tf.train.Saver({"v0": v0, "v1": v1}, sharded=True) tf.initialize_all_variables().run() val = save.save(sess, save_path) self.assertEqual(save_path + "-?????-of-00002", val) meta_graph_filename = save._MetaGraphFilename(val) self.assertEqual(save_path + ".meta", meta_graph_filename) # Restore a different "v0" from shard 0 of the saved files. with tf.Session( target="", config=tf.ConfigProto(device_count={"CPU": 2})) as sess: with sess.graph.device("/cpu:0"): v0 = tf.Variable(111, name="v0") save = tf.train.Saver({"v0": v0}, sharded=True) tf.initialize_all_variables().run() self.assertEqual(111, v0.eval()) save.restore(sess, save_path + "-00000-of-00002") self.assertEqual(10, v0.eval()) # Restore a different "v1" from shard 1 of the saved files. with tf.Session( target="", config=tf.ConfigProto(device_count={"CPU": 2})) as sess: with sess.graph.device("/cpu:0"): v1 = tf.Variable(222) save = tf.train.Saver({"v1": v1}, sharded=True) tf.initialize_all_variables().run() self.assertEqual(222, v1.eval()) save.restore(sess, save_path + "-00001-of-00002") self.assertEqual(20, v1.eval()) # Now try a restore with the sharded filename. with tf.Session( target="", config=tf.ConfigProto(device_count={"CPU": 2})) as sess: with sess.graph.device("/cpu:0"): v0 = tf.Variable(111, name="v0") with sess.graph.device("/cpu:1"): v1 = tf.Variable(222, name="v1") save = tf.train.Saver({"v0": v0, "v1": v1}, sharded=True) tf.initialize_all_variables().run() self.assertEqual(111, v0.eval()) self.assertEqual(222, v1.eval()) save_path = os.path.join(self.get_temp_dir(), "sharded") save.restore(sess, save_path + "-?????-of-?????") self.assertEqual(10, v0.eval()) self.assertEqual(20, v1.eval()) self.assertEqual( tf.train.latest_checkpoint(self.get_temp_dir()), os.path.join(self.get_temp_dir(), "sharded-?????-of-00002")) def testSaverDef(self): with self.test_session(): v0 = tf.Variable(123, name="v0") save = tf.train.Saver({"v0": v0}, sharded=True) sd = save.as_saver_def() self.assertTrue(sd.sharded) class MaxToKeepTest(tf.test.TestCase): def testNonSharded(self): save_dir = _TestDir("max_to_keep_non_sharded") with self.test_session() as sess: v = tf.Variable(10.0, name="v") save = tf.train.Saver({"v": v}, max_to_keep=2) tf.initialize_all_variables().run() self.assertEqual([], save.last_checkpoints) s1 = save.save(sess, os.path.join(save_dir, "s1")) self.assertEqual([s1], save.last_checkpoints) self.assertTrue(gfile.Exists(s1)) s2 = save.save(sess, os.path.join(save_dir, "s2")) self.assertEqual([s1, s2], save.last_checkpoints) self.assertTrue(gfile.Exists(s1)) self.assertTrue(gfile.Exists(s2)) s3 = save.save(sess, os.path.join(save_dir, "s3")) self.assertEqual([s2, s3], save.last_checkpoints) self.assertFalse(gfile.Exists(s1)) self.assertTrue(gfile.Exists(s2)) self.assertTrue(gfile.Exists(s3)) # Create a second helper, identical to the first. save2 = tf.train.Saver(saver_def=save.as_saver_def()) save2.set_last_checkpoints(save.last_checkpoints) # Create a third helper, with the same configuration but no knowledge of # previous checkpoints. save3 = tf.train.Saver(saver_def=save.as_saver_def()) # Exercise the first helper. # Adding s2 again (old s2 is removed first, then new s2 appended) s2 = save.save(sess, os.path.join(save_dir, "s2")) self.assertEqual([s3, s2], save.last_checkpoints) self.assertFalse(gfile.Exists(s1)) self.assertFalse(gfile.Exists(save._MetaGraphFilename(s1))) self.assertTrue(gfile.Exists(s3)) self.assertTrue(gfile.Exists(save._MetaGraphFilename(s3))) self.assertTrue(gfile.Exists(s2)) self.assertTrue(gfile.Exists(save._MetaGraphFilename(s2))) # Adding s1 (s3 should now be deleted as oldest in list) s1 = save.save(sess, os.path.join(save_dir, "s1")) self.assertEqual([s2, s1], save.last_checkpoints) self.assertFalse(gfile.Exists(s3)) self.assertFalse(gfile.Exists(save._MetaGraphFilename(s3))) self.assertTrue(gfile.Exists(s2)) self.assertTrue(gfile.Exists(save._MetaGraphFilename(s2))) self.assertTrue(gfile.Exists(s1)) self.assertTrue(gfile.Exists(save._MetaGraphFilename(s1))) # Exercise the second helper. # Adding s2 again (old s2 is removed first, then new s2 appended) s2 = save2.save(sess, os.path.join(save_dir, "s2")) self.assertEqual([s3, s2], save2.last_checkpoints) # Created by the first helper. self.assertTrue(gfile.Exists(s1)) self.assertTrue(gfile.Exists(save._MetaGraphFilename(s1))) # Deleted by the first helper. self.assertFalse(gfile.Exists(s3)) self.assertFalse(gfile.Exists(save._MetaGraphFilename(s3))) self.assertTrue(gfile.Exists(s2)) self.assertTrue(gfile.Exists(save._MetaGraphFilename(s2))) # Adding s1 (s3 should now be deleted as oldest in list) s1 = save2.save(sess, os.path.join(save_dir, "s1")) self.assertEqual([s2, s1], save2.last_checkpoints) self.assertFalse(gfile.Exists(s3)) self.assertFalse(gfile.Exists(save._MetaGraphFilename(s3))) self.assertTrue(gfile.Exists(s2)) self.assertTrue(gfile.Exists(save._MetaGraphFilename(s2))) self.assertTrue(gfile.Exists(s1)) self.assertTrue(gfile.Exists(save._MetaGraphFilename(s1))) # Exercise the third helper. # Adding s2 again (but helper is unaware of previous s2) s2 = save3.save(sess, os.path.join(save_dir, "s2")) self.assertEqual([s2], save3.last_checkpoints) # Created by the first helper. self.assertTrue(gfile.Exists(s1)) self.assertTrue(gfile.Exists(save._MetaGraphFilename(s1))) # Deleted by the first helper. self.assertFalse(gfile.Exists(s3)) self.assertFalse(gfile.Exists(save._MetaGraphFilename(s3))) self.assertTrue(gfile.Exists(s2)) self.assertTrue(gfile.Exists(save._MetaGraphFilename(s2))) # Adding s1 (s3 should not be deleted because helper is unaware of it) s1 = save3.save(sess, os.path.join(save_dir, "s1")) self.assertEqual([s2, s1], save3.last_checkpoints) self.assertFalse(gfile.Exists(s3)) self.assertFalse(gfile.Exists(save._MetaGraphFilename(s3))) self.assertTrue(gfile.Exists(s2)) self.assertTrue(gfile.Exists(save._MetaGraphFilename(s2))) self.assertTrue(gfile.Exists(s1)) self.assertTrue(gfile.Exists(save._MetaGraphFilename(s1))) def testSharded(self): save_dir = _TestDir("max_to_keep_sharded") with tf.Session( target="", config=tf.ConfigProto(device_count={"CPU": 2})) as sess: with sess.graph.device("/cpu:0"): v0 = tf.Variable(111, name="v0") with sess.graph.device("/cpu:1"): v1 = tf.Variable(222, name="v1") save = tf.train.Saver({"v0": v0, "v1": v1}, sharded=True, max_to_keep=2) tf.initialize_all_variables().run() self.assertEqual([], save.last_checkpoints) s1 = save.save(sess, os.path.join(save_dir, "s1")) self.assertEqual([s1], save.last_checkpoints) self.assertEqual(2, len(gfile.Glob(s1))) self.assertTrue(gfile.Exists(save._MetaGraphFilename(s1))) s2 = save.save(sess, os.path.join(save_dir, "s2")) self.assertEqual([s1, s2], save.last_checkpoints) self.assertEqual(2, len(gfile.Glob(s1))) self.assertTrue(gfile.Exists(save._MetaGraphFilename(s1))) self.assertEqual(2, len(gfile.Glob(s2))) self.assertTrue(gfile.Exists(save._MetaGraphFilename(s2))) s3 = save.save(sess, os.path.join(save_dir, "s3")) self.assertEqual([s2, s3], save.last_checkpoints) self.assertEqual(0, len(gfile.Glob(s1))) self.assertFalse(gfile.Exists(save._MetaGraphFilename(s1))) self.assertEqual(2, len(gfile.Glob(s2))) self.assertTrue(gfile.Exists(save._MetaGraphFilename(s2))) self.assertEqual(2, len(gfile.Glob(s3))) self.assertTrue(gfile.Exists(save._MetaGraphFilename(s3))) def testNoMaxToKeep(self): save_dir = _TestDir("no_max_to_keep") save_dir2 = _TestDir("max_to_keep_0") with self.test_session() as sess: v = tf.Variable(10.0, name="v") tf.initialize_all_variables().run() # Test max_to_keep being None. save = tf.train.Saver({"v": v}, max_to_keep=None) self.assertEqual([], save.last_checkpoints) s1 = save.save(sess, os.path.join(save_dir, "s1")) self.assertEqual([], save.last_checkpoints) self.assertTrue(gfile.Exists(s1)) s2 = save.save(sess, os.path.join(save_dir, "s2")) self.assertEqual([], save.last_checkpoints) self.assertTrue(gfile.Exists(s2)) # Test max_to_keep being 0. save2 = tf.train.Saver({"v": v}, max_to_keep=0) self.assertEqual([], save2.last_checkpoints) s1 = save2.save(sess, os.path.join(save_dir2, "s1")) self.assertEqual([], save2.last_checkpoints) self.assertTrue(gfile.Exists(s1)) s2 = save2.save(sess, os.path.join(save_dir2, "s2")) self.assertEqual([], save2.last_checkpoints) self.assertTrue(gfile.Exists(s2)) def testNoMetaGrap(self): save_dir = _TestDir("no_meta_graph") with self.test_session() as sess: v = tf.Variable(10.0, name="v") save = tf.train.Saver({"v": v}) tf.initialize_all_variables().run() s1 = save.save(sess, os.path.join(save_dir, "s1"), write_meta_graph=False) self.assertTrue(gfile.Exists(s1)) self.assertFalse(gfile.Exists(save._MetaGraphFilename(s1))) class KeepCheckpointEveryNHoursTest(tf.test.TestCase): def testNonSharded(self): save_dir = _TestDir("keep_checkpoint_every_n_hours") with self.test_session() as sess: v = tf.Variable([10.0], name="v") # Run the initializer NOW to avoid the 0.5s overhead of the first Run() # call, which throws the test timing off in fastbuild mode. tf.initialize_all_variables().run() # Create a saver that will keep the last 2 checkpoints plus one every 0.7 # seconds. start_time = time.time() save = tf.train.Saver({"v": v}, max_to_keep=2, keep_checkpoint_every_n_hours=0.7 / 3600) self.assertEqual([], save.last_checkpoints) # Wait till 0.7 second have elapsed so s1 will be old enough to keep. time.sleep((time.time() + 0.7) - start_time) s1 = save.save(sess, os.path.join(save_dir, "s1")) self.assertEqual([s1], save.last_checkpoints) s2 = save.save(sess, os.path.join(save_dir, "s2")) self.assertEqual([s1, s2], save.last_checkpoints) # We now have 2 'last_checkpoints': [s1, s2]. The next call to Save(), # would normally delete s1, because max_to_keep is 2. However, s1 is # older than 0.7s so we must keep it. s3 = save.save(sess, os.path.join(save_dir, "s3")) self.assertEqual([s2, s3], save.last_checkpoints) # s1 should still be here, we are Not checking now to reduce time # variance in the test. # We now have 2 'last_checkpoints': [s2, s3], and s1 on disk. The next # call to Save(), will delete s2, because max_to_keep is 2, and because # we already kept the old s1. s2 is very close in time to s1 so it gets # deleted. s4 = save.save(sess, os.path.join(save_dir, "s4")) self.assertEqual([s3, s4], save.last_checkpoints) # Check that s1 is still here, but s2 is gone. self.assertTrue(gfile.Exists(s1)) self.assertFalse(gfile.Exists(s2)) self.assertTrue(gfile.Exists(s3)) self.assertTrue(gfile.Exists(s4)) class SaveRestoreWithVariableNameMap(tf.test.TestCase): def testNonReshape(self): save_path = os.path.join(self.get_temp_dir(), "basics") with self.test_session() as sess: # Build a graph with 2 parameter nodes, and Save and # Restore nodes for them. v0 = tf.Variable(10.0, name="v0") v1 = tf.Variable(20.0, name="v1") save = tf.train.Saver({"save_prefix/v0": v0, "save_prefix/v1": v1}) tf.initialize_all_variables().run() # Check that the parameter nodes have been initialized. self.assertEqual(10.0, v0.eval()) self.assertEqual(20.0, v1.eval()) # Save the initialized values in the file at "save_path" # Use a variable name map to set the saved tensor names val = save.save(sess, save_path) self.assertTrue(isinstance(val, six.string_types)) self.assertEqual(save_path, val) # Verify that the original names are not in the Saved file save = tf.train.Saver({"v0": v0, "v1": v1}) with self.assertRaisesOpError("not found in checkpoint"): save.restore(sess, save_path) # Verify that the mapped names are present in the Saved file and can be # Restored using remapped names. with self.test_session() as sess: v0 = tf.Variable(-1.0, name="v0") v1 = tf.Variable(-1.0, name="v1") with self.assertRaisesOpError("uninitialized value v0"): sess.run(v0) with self.assertRaisesOpError("uninitialized value v1"): sess.run(v1) save = tf.train.Saver({"save_prefix/v0": v0, "save_prefix/v1": v1}) save.restore(sess, save_path) # Check that the parameter nodes have been restored. self.assertEqual(10.0, v0.eval()) self.assertEqual(20.0, v1.eval()) # Add a prefix to the node names in the current graph and Restore using # remapped names. with self.test_session() as sess: v0 = tf.Variable(-1.0, name="restore_prefix/v0") v1 = tf.Variable(-1.0, name="restore_prefix/v1") with self.assertRaisesOpError("uninitialized value restore_prefix/v0"): sess.run(v0) with self.assertRaisesOpError("uninitialized value restore_prefix/v1"): sess.run(v1) # Restore the saved values in the parameter nodes. save = tf.train.Saver({"save_prefix/v0": v0, "save_prefix/v1": v1}) save.restore(sess, save_path) # Check that the parameter nodes have been restored. self.assertEqual(10.0, v0.eval()) self.assertEqual(20.0, v1.eval()) class LatestCheckpointWithRelativePaths(tf.test.TestCase): @staticmethod @contextlib.contextmanager def tempWorkingDir(temppath): cwd = os.getcwd() os.chdir(temppath) try: yield finally: os.chdir(cwd) @staticmethod @contextlib.contextmanager def tempDir(): tempdir = tempfile.mkdtemp() try: yield tempdir finally: shutil.rmtree(tempdir) def testRelativePath(self): # Make sure we have a clean directory to work in. with self.tempDir() as tempdir: # Jump to that directory until this test is done. with self.tempWorkingDir(tempdir): # Save training snapshots to a relative path. traindir = "train/" os.mkdir(traindir) filename = "snapshot" filepath = os.path.join(traindir, filename) with self.test_session() as sess: # Build a simple graph. v0 = tf.Variable(0.0) inc = v0.assign_add(1.0) save = tf.train.Saver({"v0": v0}) # Record a short training history. tf.initialize_all_variables().run() save.save(sess, filepath, global_step=0) inc.eval() save.save(sess, filepath, global_step=1) inc.eval() save.save(sess, filepath, global_step=2) with self.test_session() as sess: # Build a new graph with different initialization. v0 = tf.Variable(-1.0) # Create a new saver. save = tf.train.Saver({"v0": v0}) tf.initialize_all_variables().run() # Get the most recent checkpoint name from the training history file. name = tf.train.latest_checkpoint(traindir) self.assertIsNotNone(name) # Restore "v0" from that checkpoint. save.restore(sess, name) self.assertEqual(v0.eval(), 2.0) class CheckpointStateTest(tf.test.TestCase): def testAbsPath(self): save_dir = _TestDir("abs_paths") abs_path = os.path.join(save_dir, "model-0") ckpt = tf.train.generate_checkpoint_state_proto(save_dir, abs_path) self.assertEqual(ckpt.model_checkpoint_path, abs_path) self.assertTrue(os.path.isabs(ckpt.model_checkpoint_path)) self.assertEqual(len(ckpt.all_model_checkpoint_paths), 1) self.assertEqual(ckpt.all_model_checkpoint_paths[-1], abs_path) def testRelPath(self): train_dir = "train" model = os.path.join(train_dir, "model-0") # model_checkpoint_path should have no "train" directory part. new_rel_path = "model-0" ckpt = tf.train.generate_checkpoint_state_proto(train_dir, model) self.assertEqual(ckpt.model_checkpoint_path, new_rel_path) self.assertEqual(len(ckpt.all_model_checkpoint_paths), 1) self.assertEqual(ckpt.all_model_checkpoint_paths[-1], new_rel_path) def testAllModelCheckpointPaths(self): save_dir = _TestDir("all_models_test") abs_path = os.path.join(save_dir, "model-0") for paths in [None, [], ["model-2"]]: ckpt = tf.train.generate_checkpoint_state_proto( save_dir, abs_path, all_model_checkpoint_paths=paths) self.assertEqual(ckpt.model_checkpoint_path, abs_path) self.assertTrue(os.path.isabs(ckpt.model_checkpoint_path)) self.assertEqual( len(ckpt.all_model_checkpoint_paths), len(paths) if paths else 1) self.assertEqual(ckpt.all_model_checkpoint_paths[-1], abs_path) def testUpdateCheckpointState(self): save_dir = _TestDir("update_checkpoint_state") os.chdir(save_dir) # Make a temporary train directory. train_dir = "train" os.mkdir(train_dir) abs_path = os.path.join(save_dir, "model-0") rel_path = "train/model-2" tf.train.update_checkpoint_state( train_dir, rel_path, all_model_checkpoint_paths=[abs_path, rel_path]) ckpt = tf.train.get_checkpoint_state(train_dir) self.assertEqual(ckpt.model_checkpoint_path, rel_path) self.assertEqual(len(ckpt.all_model_checkpoint_paths), 2) self.assertEqual(ckpt.all_model_checkpoint_paths[-1], rel_path) self.assertEqual(ckpt.all_model_checkpoint_paths[0], abs_path) class MetaGraphTest(tf.test.TestCase): def testNoVariables(self): test_dir = _TestDir("no_variables") filename = os.path.join(test_dir, "metafile") input_feed_value = -10 # Arbitrary input value for feed_dict. orig_graph = tf.Graph() with self.test_session(graph=orig_graph) as sess: # Create a minimal graph with zero variables. input_tensor = tf.placeholder(tf.float32, shape=[], name="input") offset = tf.constant(42, dtype=tf.float32, name="offset") output_tensor = tf.add(input_tensor, offset, name="add_offset") # Add input and output tensors to graph collections. tf.add_to_collection("input_tensor", input_tensor) tf.add_to_collection("output_tensor", output_tensor) output_value = sess.run(output_tensor, {input_tensor: input_feed_value}) self.assertEqual(output_value, 32) # Generates MetaGraphDef. # # Note that this is calling the saver *module-level* export_meta_graph and # not the Saver.export_meta_graph instance-level method. meta_graph_def = saver_module.export_meta_graph( filename=filename, graph_def=tf.get_default_graph().as_graph_def(add_shapes=True), collection_list=["input_tensor", "output_tensor"], saver_def=None, ) # Create a clean graph and import the MetaGraphDef nodes. new_graph = tf.Graph() with self.test_session(graph=new_graph) as sess: # Import the previously export meta graph. saver_instance = saver_module.import_meta_graph(filename) # The saver instance should be None since there are no graph variables # to be restored in this case. self.assertIsNone(saver_instance) # Re-exports the current graph state for comparison to the original. new_meta_graph_def = saver_module.export_meta_graph(filename + "_new") self.assertProtoEquals(meta_graph_def, new_meta_graph_def) # Ensures that we can still get a reference to our graph collections. new_input_tensor = tf.get_collection("input_tensor")[0] new_output_tensor = tf.get_collection("output_tensor")[0] # Verifies that the new graph computes the same result as the original. new_output_value = sess.run( new_output_tensor, {new_input_tensor: input_feed_value}) self.assertEqual(new_output_value, output_value) def testAddCollectionDef(self): test_dir = _TestDir("good_collection") filename = os.path.join(test_dir, "metafile") with self.test_session(): # Creates a graph. v0 = tf.Variable(10.0, name="v0") var = tf.Variable(tf.constant(0, dtype=tf.int64)) count_up_to = var.count_up_to(3) input_queue = tf.FIFOQueue(30, tf.float32, shared_name="collection_queue") qr = tf.train.QueueRunner(input_queue, [count_up_to]) tf.initialize_all_variables() # Creates a saver. save = tf.train.Saver({"v0": v0}) # Adds a set of collections. tf.add_to_collection("int_collection", 3) tf.add_to_collection("float_collection", 3.5) tf.add_to_collection("string_collection", "hello") tf.add_to_collection("variable_collection", v0) # Add QueueRunners. tf.train.add_queue_runner(qr) # Adds user_defined proto in three formats: string, bytes and Any. queue_runner = queue_runner_pb2.QueueRunnerDef(queue_name="test_queue") tf.add_to_collection("user_defined_string_collection", str(queue_runner)) tf.add_to_collection("user_defined_bytes_collection", queue_runner.SerializeToString()) any_buf = Any() any_buf.Pack(queue_runner) tf.add_to_collection("user_defined_any_collection", any_buf) # Generates MetaGraphDef. meta_graph_def = save.export_meta_graph(filename) self.assertTrue(meta_graph_def.HasField("saver_def")) self.assertTrue(meta_graph_def.HasField("graph_def")) collection_def = meta_graph_def.collection_def self.assertEqual(len(collection_def), 10) with tf.Graph().as_default(): # Restores from MetaGraphDef. new_saver = tf.train.import_meta_graph(filename) # Generates a new MetaGraphDef. new_meta_graph_def = new_saver.export_meta_graph() # It should be the same as the original. self.assertProtoEquals(meta_graph_def, new_meta_graph_def) def testAddCollectionDefFails(self): with self.test_session(): # Creates a graph. v0 = tf.Variable(10.0, name="v0") # Creates a saver. save = tf.train.Saver({"v0": v0}) # Generates MetaGraphDef. meta_graph_def = meta_graph_pb2.MetaGraphDef() # Verifies that collection with unsupported key will not be added. tf.add_to_collection(save, 3) save._add_collection_def(meta_graph_def, save) self.assertEqual(len(meta_graph_def.collection_def), 0) # Verifies that collection where item type does not match expected # type will not be added. tf.add_to_collection("int_collection", 3) tf.add_to_collection("int_collection", 3.5) save._add_collection_def(meta_graph_def, "int_collection") self.assertEqual(len(meta_graph_def.collection_def), 0) def _testMultiSaverCollectionSave(self): test_dir = _TestDir("saver_collection") filename = os.path.join(test_dir, "metafile") saver0_ckpt = os.path.join(test_dir, "saver0.ckpt") saver1_ckpt = os.path.join(test_dir, "saver1.ckpt") with self.test_session(graph=tf.Graph()) as sess: # Creates a graph. v0 = tf.Variable([[1.0, 2.0], [3.0, 4.0], [5.0, 6.0]], name="v0") v1 = tf.Variable(11.0, name="v1") # Creates 2 savers. saver0 = tf.train.Saver({"v0": v0}, name="saver0") saver1 = tf.train.Saver({"v1": v1}, name="saver1") tf.add_to_collection("savers", saver0) tf.add_to_collection("savers", saver1) tf.initialize_all_variables().run() # Saves to different checkpoints. saver0.save(sess, saver0_ckpt) saver1.save(sess, saver1_ckpt) # Generates MetaGraphDef. meta_graph_def = tf.train.export_meta_graph(filename) meta_graph_def0 = saver0.export_meta_graph() meta_graph_def1 = saver1.export_meta_graph() # Verifies that there is no saver_def in meta_graph_def. self.assertFalse(meta_graph_def.HasField("saver_def")) # Verifies that there is saver_def in meta_graph_def0 and 1. self.assertTrue(meta_graph_def0.HasField("saver_def")) self.assertTrue(meta_graph_def1.HasField("saver_def")) # Verifies SAVERS is saved as bytes_list for meta_graph_def. collection_def = meta_graph_def.collection_def["savers"] kind = collection_def.WhichOneof("kind") self.assertEqual(kind, "bytes_list") # Verifies that there are 2 entries in SAVERS collection. savers = getattr(collection_def, kind) self.assertEqual(2, len(savers.value)) # Verifies SAVERS collection is saved as bytes_list for meta_graph_def0. collection_def = meta_graph_def0.collection_def["savers"] kind = collection_def.WhichOneof("kind") self.assertEqual(kind, "bytes_list") # Verifies that there are 3 entries in SAVERS collection. savers = getattr(collection_def, kind) self.assertEqual(2, len(savers.value)) def _testMultiSaverCollectionRestore(self): test_dir = os.path.join(self.get_temp_dir(), "saver_collection") filename = os.path.join(test_dir, "metafile") saver0_ckpt = os.path.join(test_dir, "saver0.ckpt") saver1_ckpt = os.path.join(test_dir, "saver1.ckpt") with self.test_session(graph=tf.Graph()) as sess: # Imports from meta_graph. tf.train.import_meta_graph(filename) # Retrieves SAVERS collection. Verifies there are 2 entries. savers = tf.get_collection("savers") self.assertEqual(2, len(savers)) # Retrieves saver0. Verifies that new_saver0 can restore v0, but not v1. new_saver0 = savers[0] new_saver0.restore(sess, saver0_ckpt) v0 = sess.graph.get_tensor_by_name("v0:0") v1 = sess.graph.get_tensor_by_name("v1:0") self.assertAllEqual([[1.0, 2.0], [3.0, 4.0], [5.0, 6.0]], v0.eval()) self.assertEqual([3, 2], v0.get_shape()) self.assertEqual([], v1.get_shape()) with self.assertRaisesWithPredicateMatch( tf.OpError, lambda e: "uninitialized value v1" in e.message): sess.run(v1) # Retrieves saver1. Verifies that new_saver1 can restore v1. new_saver1 = savers[1] new_saver1.restore(sess, saver1_ckpt) v1 = sess.graph.get_tensor_by_name("v1:0") self.assertEqual(11.0, v1.eval()) def testMultiSaverCollection(self): self._testMultiSaverCollectionSave() self._testMultiSaverCollectionRestore() def testBinaryAndTextFormat(self): test_dir = _TestDir("binary_and_text") filename = os.path.join(test_dir, "metafile") with self.test_session(graph=tf.Graph()): # Creates a graph. tf.Variable(10.0, name="v0") # Exports the graph as binary format. tf.train.export_meta_graph(filename, as_text=False) with self.test_session(graph=tf.Graph()): # Imports the binary format graph. saver = tf.train.import_meta_graph(filename) self.assertIsNotNone(saver) # Exports the graph as text format. saver.export_meta_graph(filename, as_text=True) with self.test_session(graph=tf.Graph()): # Imports the text format graph. tf.train.import_meta_graph(filename) # Writes wrong contents to the file. tf.train.write_graph(saver.as_saver_def(), os.path.dirname(filename), os.path.basename(filename)) with self.test_session(graph=tf.Graph()): # Import should fail. with self.assertRaisesWithPredicateMatch( IOError, lambda e: "Cannot parse file"): tf.train.import_meta_graph(filename) # Deletes the file gfile.Remove(filename) with self.assertRaisesWithPredicateMatch( IOError, lambda e: "does not exist"): tf.train.import_meta_graph(filename) def testSliceVariable(self): test_dir = _TestDir("slice_saver") filename = os.path.join(test_dir, "metafile") with self.test_session(): v1 = tf.Variable([20.0], name="v1") v2 = tf.Variable([20.0], name="v2") v2._set_save_slice_info(tf.Variable.SaveSliceInfo("v1", [1], [0], [1])) # The names are different and will work. slice_saver = tf.train.Saver({"first": v1, "second": v2}) tf.initialize_all_variables().run() # Exports to meta_graph meta_graph_def = slice_saver.export_meta_graph(filename) with tf.Graph().as_default(): # Restores from MetaGraphDef. new_saver = tf.train.import_meta_graph(filename) self.assertIsNotNone(new_saver) # Generates a new MetaGraphDef. new_meta_graph_def = new_saver.export_meta_graph() # It should be the same as the original. self.assertProtoEquals(meta_graph_def, new_meta_graph_def) def _testGraphExtensionSave(self): test_dir = _TestDir("graph_extension") filename = os.path.join(test_dir, "metafile") saver0_ckpt = os.path.join(test_dir, "saver0.ckpt") # Creates an inference graph. # Hidden 1 images = tf.constant(1.2, tf.float32, shape=[100, 28]) with tf.name_scope("hidden1"): weights = tf.Variable( tf.truncated_normal([28, 128], stddev=1.0 / math.sqrt(float(28))), name="weights") biases = tf.Variable(tf.zeros([128]), name="biases") hidden1 = tf.nn.relu(tf.matmul(images, weights) + biases) # Hidden 2 with tf.name_scope("hidden2"): weights = tf.Variable( tf.truncated_normal([128, 32], stddev=1.0 / math.sqrt(float(128))), name="weights") biases = tf.Variable(tf.zeros([32]), name="biases") hidden2 = tf.nn.relu(tf.matmul(hidden1, weights) + biases) # Linear with tf.name_scope("softmax_linear"): weights = tf.Variable( tf.truncated_normal([32, 10], stddev=1.0 / math.sqrt(float(32))), name="weights") biases = tf.Variable(tf.zeros([10]), name="biases") logits = tf.matmul(hidden2, weights) + biases tf.add_to_collection("logits", logits) init_all_op = tf.initialize_all_variables() with self.test_session() as sess: # Initializes all the variables. sess.run(init_all_op) # Runs to logit. sess.run(logits) # Creates a saver. saver0 = tf.train.Saver() saver0.save(sess, saver0_ckpt) # Generates MetaGraphDef. saver0.export_meta_graph(filename) def _testGraphExtensionRestore(self): test_dir = os.path.join(self.get_temp_dir(), "graph_extension") filename = os.path.join(test_dir, "metafile") saver0_ckpt = os.path.join(test_dir, "saver0.ckpt") with self.test_session(graph=tf.Graph()) as sess: # Restores from MetaGraphDef. new_saver = tf.train.import_meta_graph(filename) # Generates a new MetaGraphDef. new_saver.export_meta_graph() # Restores from checkpoint. new_saver.restore(sess, saver0_ckpt) # Addes loss and train. labels = tf.constant(0, tf.int32, shape=[100], name="labels") batch_size = tf.size(labels) labels = tf.expand_dims(labels, 1) indices = tf.expand_dims(tf.range(0, batch_size), 1) concated = tf.concat(1, [indices, labels]) onehot_labels = tf.sparse_to_dense( concated, tf.pack([batch_size, 10]), 1.0, 0.0) logits = tf.get_collection("logits")[0] cross_entropy = tf.nn.softmax_cross_entropy_with_logits(logits, onehot_labels, name="xentropy") loss = tf.reduce_mean(cross_entropy, name="xentropy_mean") tf.scalar_summary(loss.op.name, loss) # Creates the gradient descent optimizer with the given learning rate. optimizer = tf.train.GradientDescentOptimizer(0.01) # Runs train_op. train_op = optimizer.minimize(loss) sess.run(train_op) def testGraphExtension(self): self._testGraphExtensionSave() self._testGraphExtensionRestore() def testStrippedOpListDef(self): with self.test_session(): # Creates a graph. v0 = tf.Variable(0.0) var = tf.Variable(10.0) tf.add(v0, var) @function.Defun(x=tf.float32) def minus_one(x): return x - 1 minus_one(tf.identity(v0)) save = tf.train.Saver({"v0": v0}) tf.initialize_all_variables() # Generates MetaGraphDef. meta_graph_def = save.export_meta_graph() ops = [o.name for o in meta_graph_def.meta_info_def.stripped_op_list.op] self.assertEqual(ops, ["Add", "Assign", "Const", "Identity", "NoOp", "RestoreSlice", "SaveSlices", "Sub", "Variable"]) # Test calling stripped_op_list_for_graph directly op_list = tf.contrib.util.stripped_op_list_for_graph( meta_graph_def.graph_def) self.assertEqual(ops, [o.name for o in op_list.op]) for o in op_list.op: self.assertEqual(o.summary, "") self.assertEqual(o.description, "") def testStrippedOpListNestedFunctions(self): with self.test_session(): # Square two levels deep def f0(x): return tf.square(x) f0 = function.define_function(f0, {"x": tf.int32}) def f1(x): return function.call_function(f0, x) f1 = function.define_function(f1, {"x": tf.int32}) # At this point we've defined two functions but haven't called them, so # there should be no used ops. op_list = tf.contrib.util.stripped_op_list_for_graph( tf.get_default_graph().as_graph_def()) self.assertEquals(len(op_list.op), 0) # If we call the function on a constant, there should be two ops function.call_function(f1, tf.constant(7)) op_list = tf.contrib.util.stripped_op_list_for_graph( tf.get_default_graph().as_graph_def()) self.assertEquals(["Const", "Square"], [op.name for op in op_list.op]) def testStrippedOpListRecursiveFunctions(self): # The function module doesn't support recursive functions, so we build a # recursive function situation by ourselves: A calls B calls A and Const. graph = graph_pb2.GraphDef() a = graph.library.function.add() b = graph.library.function.add() a.signature.name = "A" b.signature.name = "B" a.node.add().op = "B" b.node.add().op = "Const" b.node.add().op = "A" # Use A in the graph graph.node.add().op = "A" # The stripped op list should contain just Const. op_list = tf.contrib.util.stripped_op_list_for_graph(graph) self.assertEquals(["Const"], [op.name for op in op_list.op]) class CheckpointReaderTest(tf.test.TestCase): def testDebugString(self): # Builds a graph. v0 = tf.Variable([[1, 2, 3], [4, 5, 6]], dtype=tf.float32, name="v0") v1 = tf.Variable([[[1], [2]], [[3], [4]], [[5], [6]]], dtype=tf.float32, name="v1") init_all_op = tf.initialize_all_variables() save = tf.train.Saver({"v0": v0, "v1": v1}) save_path = os.path.join(self.get_temp_dir(), "ckpt_for_debug_string") with self.test_session() as sess: sess.run(init_all_op) # Saves a checkpoint. save.save(sess, save_path) # Creates a reader. reader = tf.train.NewCheckpointReader(save_path) # Verifies that the tensors exist. self.assertTrue(reader.has_tensor("v0")) self.assertTrue(reader.has_tensor("v1")) debug_string = reader.debug_string() # Verifies that debug string contains the right strings. self.assertTrue(compat.as_bytes("v0 (DT_FLOAT) [2,3]") in debug_string) self.assertTrue(compat.as_bytes("v1 (DT_FLOAT) [3,2,1]") in debug_string) # Verifies get_variable_to_shape_map() returns the correct information. var_map = reader.get_variable_to_shape_map() self.assertEquals([2, 3], var_map["v0"]) self.assertEquals([3, 2, 1], var_map["v1"]) # Verifies get_tensor() returns the tensor value. v0_tensor = reader.get_tensor("v0") v1_tensor = reader.get_tensor("v1") self.assertAllEqual(v0.eval(), v0_tensor) self.assertAllEqual(v1.eval(), v1_tensor) # Verifies get_tensor() fails for non-existent tensors. with self.assertRaisesRegexp(errors.NotFoundError, "v3 not found in checkpoint file"): reader.get_tensor("v3") def testNonexistentPath(self): with self.assertRaisesRegexp(errors.NotFoundError, "Unsuccessful TensorSliceReader"): tf.train.NewCheckpointReader("non-existent") if __name__ == "__main__": tf.test.main()
{ "content_hash": "7338f57963d079673f63b9dc759412d6", "timestamp": "", "source": "github", "line_count": 1217, "max_line_length": 80, "avg_line_length": 39.75842235004109, "alnum_prop": 0.6402265118009342, "repo_name": "ibab/tensorflow", "id": "88839d421e1a83b7f795075c1af213534f05f6f6", "size": "49064", "binary": false, "copies": "4", "ref": "refs/heads/master", "path": "tensorflow/python/training/saver_test.py", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "C", "bytes": "156010" }, { "name": "C++", "bytes": "9133299" }, { "name": "CMake", "bytes": "29372" }, { "name": "CSS", "bytes": "1297" }, { "name": "HTML", "bytes": "773228" }, { "name": "Java", "bytes": "39181" }, { "name": "JavaScript", "bytes": "10779" }, { "name": "Jupyter Notebook", "bytes": "1772913" }, { "name": "Protocol Buffer", "bytes": "111555" }, { "name": "Python", "bytes": "6393079" }, { "name": "Shell", "bytes": "164997" }, { "name": "TypeScript", "bytes": "409165" } ], "symlink_target": "" }
var React = require('react'); var pagination = require('pagination'); module.exports = React.createClass({ propTypes: { currentPage : React.PropTypes.number, resultsPerPage: React.PropTypes.number, totalResults: React.PropTypes.number, pageLinks: React.PropTypes.number, onSelectPage: React.PropTypes.func, }, getDefaultProps: function() { return { currentPage : 1, resultsPerPage: 1, totalResults: 1, pageLinks: 10, onSelectPage: null, }; }, _onSelectPage: function(e) { e.preventDefault(); if (this.props.onSelectPage) { var newPage = e.currentTarget.dataset.page; // if page empty (i.e. disabled button) then do nothing if (!newPage || !newPage.length) { return; } newPage = parseInt(newPage); if (newPage === this.props.currentPage) { return; } this.props.onSelectPage( newPage ); } }, render: function() { var self = this; var p = new pagination.SearchPaginator({ prelink:'/', pageLinks: this.props.pageLinks, current: this.props.currentPage, rowsPerPage: this.props.resultsPerPage, totalResult: this.props.totalResults, }).getPaginationData(); var leftCssClass = (!p.previous) ? 'disabled' : 'waves-effect'; var rightCssClass = (!p.next) ? 'disabled' : 'waves-effect'; // if range empty then we want a single page if (p.current && !p.range.length) { p.range = [1]; } var pageNumbers = p.range.map(function(n) { var cssClass = (p.current === n) ? 'active' : 'waves-effect'; return ( <li className={cssClass}> <a href="#!" onClick={self._onSelectPage} data-page={n}>{n}</a> </li> ); }); return ( <ul className="pagination"> <li className={leftCssClass}> <a href="#!" onClick={self._onSelectPage} data-page={p.previous}> <i className="mdi-navigation-chevron-left"></i> </a> </li> {pageNumbers} <li className={rightCssClass}> <a href="#!" onClick={self._onSelectPage} data-page={p.next}> <i className="mdi-navigation-chevron-right"></i> </a> </li> </ul> ); }, });
{ "content_hash": "8210886dc7cf4fdd781b74c12068d709", "timestamp": "", "source": "github", "line_count": 92, "max_line_length": 75, "avg_line_length": 24.804347826086957, "alnum_prop": 0.5775635407537248, "repo_name": "waigo/admin", "id": "9f5a6a385fddb41b3cd4dddeee447edc28f6ec18", "size": "2282", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/frontend/js/components/pagination.js", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "187876" }, { "name": "CoffeeScript", "bytes": "6960" }, { "name": "HTML", "bytes": "2260" }, { "name": "JavaScript", "bytes": "315848" } ], "symlink_target": "" }
#ifdef HAVE_CONFIG_H # include <config.h> #endif #include <assert.h> #include <limits.h> #include <stdlib.h> #include <string.h> #include "libdwP.h" int dwarf_getsrc_file (Dwarf *dbg, const char *fname, int lineno, int column, Dwarf_Line ***srcsp, size_t *nsrcs) { if (dbg == NULL) return -1; bool is_basename = strchr (fname, '/') == NULL; size_t max_match = *nsrcs ?: ~0u; size_t act_match = *nsrcs; size_t cur_match = 0; Dwarf_Line **match = *nsrcs == 0 ? NULL : *srcsp; Dwarf_Off off = 0; size_t cuhl; Dwarf_Off noff; while (INTUSE(dwarf_nextcu) (dbg, off, &noff, &cuhl, NULL, NULL, NULL) == 0) { Dwarf_Die cudie_mem; Dwarf_Die *cudie = INTUSE(dwarf_offdie) (dbg, off + cuhl, &cudie_mem); if (cudie == NULL) continue; /* Get the line number information for this file. */ Dwarf_Lines *lines; size_t nlines; if (INTUSE(dwarf_getsrclines) (cudie, &lines, &nlines) != 0) return -1; /* Search through all the line number records for a matching file and line/column number. If any of the numbers is zero, no match is performed. */ unsigned int lastfile = UINT_MAX; bool lastmatch = false; for (size_t cnt = 0; cnt < nlines; ++cnt) { Dwarf_Line *line = &lines->info[cnt]; if (lastfile != line->file) { lastfile = line->file; if (lastfile >= line->files->nfiles) { __libdw_seterrno (DWARF_E_INVALID_DWARF); return -1; } /* Match the name with the name the user provided. */ const char *fname2 = line->files->info[lastfile].name; if (is_basename) lastmatch = strcmp (basename (fname2), fname) == 0; else lastmatch = strcmp (fname2, fname) == 0; } if (!lastmatch) continue; /* See whether line and possibly column match. */ if (lineno != 0 && (lineno > line->line || (column != 0 && column > line->column))) /* Cannot match. */ continue; /* Determine whether this is the best match so far. */ size_t inner; for (inner = 0; inner < cur_match; ++inner) if (match[inner]->files == line->files && match[inner]->file == line->file) break; if (inner < cur_match && (match[inner]->line != line->line || match[inner]->line != lineno || (column != 0 && (match[inner]->column != line->column || match[inner]->column != column)))) { /* We know about this file already. If this is a better match for the line number, use it. */ if (match[inner]->line >= line->line && (match[inner]->line != line->line || match[inner]->column >= line->column)) /* Use the new line. Otherwise the old one. */ match[inner] = line; continue; } if (cur_match < max_match) { if (cur_match == act_match) { /* Enlarge the array for the results. */ act_match += 10; Dwarf_Line **newp = realloc (match, act_match * sizeof (Dwarf_Line *)); if (newp == NULL) { free (match); __libdw_seterrno (DWARF_E_NOMEM); return -1; } match = newp; } match[cur_match++] = line; } } /* If we managed to find as many matches as the user requested already, there is no need to go on to the next CU. */ if (cur_match == max_match) break; off = noff; } if (cur_match > 0) { assert (*nsrcs == 0 || *srcsp == match); *nsrcs = cur_match; *srcsp = match; return 0; } __libdw_seterrno (DWARF_E_NO_MATCH); return -1; }
{ "content_hash": "03867cd136a9ce5879b94a63964c8884", "timestamp": "", "source": "github", "line_count": 145, "max_line_length": 78, "avg_line_length": 24.689655172413794, "alnum_prop": 0.5614525139664804, "repo_name": "indashnet/InDashNet.Open.UN2000", "id": "2c4fc768d7027f3cce141b267652c1a5bf07af27", "size": "6594", "binary": false, "copies": "25", "ref": "refs/heads/master", "path": "android/external/elfutils/libdw/dwarf_getsrc_file.c", "mode": "33188", "license": "apache-2.0", "language": [], "symlink_target": "" }
ACCEPTED #### According to NUB Generator [autonym] #### Published in null #### Original name null ### Remarks null
{ "content_hash": "de6ea115b1e0328c4af23cc731461f0a", "timestamp": "", "source": "github", "line_count": 13, "max_line_length": 23, "avg_line_length": 9.076923076923077, "alnum_prop": 0.6779661016949152, "repo_name": "mdoering/backbone", "id": "339471239fda353aeda14a7cdd8b3270428445f6", "size": "180", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "life/Plantae/Magnoliophyta/Magnoliopsida/Ranunculales/Ranunculaceae/Adonis/Adonis aestivalis/Adonis aestivalis aestivalis/README.md", "mode": "33188", "license": "apache-2.0", "language": [], "symlink_target": "" }
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /> <link rel="stylesheet" href="/static/css/default.css" /> <link rel="stylesheet" href="/static/css/print.css" media="print" /> {% if state.command_url not in ("/auth/login/", "/auth/logout/") %} <link rel="stylesheet" href="/jsapi/as.css?ts={{ config.version }}-{{ config.timestamp }}" /> {% endif %} <!-- Apple Icons --> <link rel="apple-touch-icon" sizes="57x57" href="/static/img/apple-touch-icon.png" /> <link rel="apple-touch-icon" sizes="72x72" href="/static/img/apple-touch-icon-72x72.png" /> <link rel="apple-touch-icon" sizes="114x114" href="/static/img/apple-touch-icon-114x114.png" /> <!-- Favicon --> <link rel="shortcut icon" id="basic-favicon" href="/static/img/favicon.png" /> <link rel="icon" id="basic-favicon" type="image/png" href="/static/img/favicon.png" /> <!-- JS Global Libraries --> <script src="/static/js/jquery.min.js"></script> <script src="/static/js/libraries.min.js"></script> {% if state.command_url not in ("/auth/login/", "/auth/logout/", "/setup/welcome/") %} <script src="/api/0/jsapi/as.js?ts={{ config.version }}-{{ config.timestamp }}"></script> {% if state.command_url in ("/message/draft/", "/message/") %} <script src="/static/js/plupload.full.min.js"></script> {% endif %} <!-- JS - App Specific --> {% if state.command_url not in ("/setup/crypto/") %} <script> {% if result.data and result.data.addresses %} {% set addresses_json = result.data.addresses|json %} {% endif %} {% if result.data and result.data.messages %} {% set messages_json = result.data.messages|json %} {% endif %} {% if result.data and result.data.metadata %} {% set metadata_json = result.data.metadata|json %} {% endif %} {% set tags_json = mailpile("tags", "display=*", "mode=flat").result.tags|json %} $(document).ready(function() { // Print JSON for JS Use Mailpile.instance = { "command": "{{ command }}", "state": {{state|json|safe}}, "args": "{{ args }}", "addresses": {% if result.data and result.data.addresses %}{{ addresses_json|safe }}{% else %}{}{% endif %}, "messages": {% if result.data and result.data.messages %}{{ messages_json|safe }}{% else %}{}{% endif %}, "metadata": {% if result.data and result.data.metadata %}{{ metadata_json|safe }}{% else %}{}{% endif %}, "search_tag_ids": {% if result.search_tag_ids %}{{result.search_tag_ids|safe }}{% else %}[]{% endif %}, "search_addresses": [], "tags": {{ tags_json|safe }} }; // Nagifications {% if show_nagification(config.web.nag_backup_key) %} Mailpile.notification({ status: 'warning', message: '{{_("Back up your encryption key & passphrase")}}', type: 'nagify', action: '/settings/backup-keys.html' }); {% endif %} // HTML5 Browser Notifications if (Notification.permission == "granted") { $('#notifications-permission-option').text("{{_("Browser notifications allowed")}}") } $('#notifications-permission-option').click(function() { Notification.requestPermission(); }); }); /* Plugins */ $(document).ready( {{ui_elements_setup('.plugin-activity-%(name)s', get_ui_elements('activities', state, '/'))}} ); </script> <script src="/api/0/jsapi/app.js?ts={{ config.version }}-{{ config.timestamp }}"></script> {% endif %} {% endif %}
{ "content_hash": "3656d76ff3c31d7e9e6b1e557ea80e32", "timestamp": "", "source": "github", "line_count": 82, "max_line_length": 113, "avg_line_length": 41.91463414634146, "alnum_prop": 0.6080884492289788, "repo_name": "laborautonomo/Mailpile", "id": "49e7f9f7d73d1a09d25981a7fc2b25a437d59d39", "size": "3437", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "mailpile/www/default/html/partials/head.html", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "131369" }, { "name": "JavaScript", "bytes": "563983" }, { "name": "Makefile", "bytes": "5962" }, { "name": "Python", "bytes": "1261330" }, { "name": "Shell", "bytes": "18103" } ], "symlink_target": "" }
import os from build_swift.build_swift.constants import MULTIROOT_DATA_FILE_PATH from . import cmark from . import foundation from . import libcxx from . import libdispatch from . import libicu from . import llbuild from . import llvm from . import product from . import swift from . import swiftpm from . import xctest from .. import shell class SwiftSyntax(product.Product): @classmethod def product_source_name(cls): """product_source_name() -> str The name of the source code directory of this product. """ return "swift-syntax" @classmethod def is_build_script_impl_product(cls): return False @classmethod def is_swiftpm_unified_build_product(cls): return True def run_swiftsyntax_build_script(self, target, additional_params=[]): llvm_build_dir = os.path.join(self.build_dir, '..', 'llvm-' + target) llvm_build_dir = os.path.realpath(llvm_build_dir) script_path = os.path.join(self.source_dir, 'build-script.py') build_cmd = [ script_path, '--build-dir', self.build_dir, '--multiroot-data-file', MULTIROOT_DATA_FILE_PATH, '--toolchain', self.install_toolchain_path(target), '--filecheck-exec', os.path.join(llvm_build_dir, 'bin', 'FileCheck'), ] if self.is_release(): build_cmd.append('--release') if self.args.swiftsyntax_verify_generated_files: build_cmd.append('--verify-generated-files') build_cmd.extend(additional_params) if self.args.verbose_build: build_cmd.append('--verbose') shell.call(build_cmd) def should_build(self, host_target): return True def build(self, host_target): self.run_swiftsyntax_build_script(target=host_target) def should_test(self, host_target): return self.args.test_swiftsyntax def test(self, host_target): self.run_swiftsyntax_build_script(target=host_target, additional_params=['--test']) def should_install(self, host_target): return self.args.install_swiftsyntax def install(self, target_name): install_prefix = self.args.install_destdir + self.args.install_prefix dylib_dir = os.path.join(install_prefix, 'lib') additional_params = [ '--dylib-dir', dylib_dir, '--install' ] self.run_swiftsyntax_build_script(target=target_name, additional_params=additional_params) @classmethod def get_dependencies(cls): return [cmark.CMark, llvm.LLVM, libcxx.LibCXX, libicu.LibICU, swift.Swift, libdispatch.LibDispatch, foundation.Foundation, xctest.XCTest, llbuild.LLBuild, swiftpm.SwiftPM]
{ "content_hash": "8513a767127484219f7bb47ea7a81ff7", "timestamp": "", "source": "github", "line_count": 104, "max_line_length": 78, "avg_line_length": 28.990384615384617, "alnum_prop": 0.5887230514096186, "repo_name": "CodaFi/swift", "id": "00cdef0dd0c5c7007e9e6395b230cc285d963783", "size": "3523", "binary": false, "copies": "3", "ref": "refs/heads/master", "path": "utils/swift_build_support/swift_build_support/products/swiftsyntax.py", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Batchfile", "bytes": "13716" }, { "name": "C", "bytes": "272549" }, { "name": "C++", "bytes": "38990943" }, { "name": "CMake", "bytes": "560004" }, { "name": "D", "bytes": "1107" }, { "name": "DTrace", "bytes": "2593" }, { "name": "Emacs Lisp", "bytes": "57457" }, { "name": "LLVM", "bytes": "70652" }, { "name": "MATLAB", "bytes": "2576" }, { "name": "Makefile", "bytes": "1841" }, { "name": "Objective-C", "bytes": "428976" }, { "name": "Objective-C++", "bytes": "244095" }, { "name": "Python", "bytes": "1794381" }, { "name": "Roff", "bytes": "3495" }, { "name": "Ruby", "bytes": "2117" }, { "name": "Shell", "bytes": "188874" }, { "name": "Swift", "bytes": "33839781" }, { "name": "Vim Script", "bytes": "19900" }, { "name": "sed", "bytes": "1050" } ], "symlink_target": "" }
from swgpy.object import * def create(kernel): result = Tangible() result.template = "object/tangible/mission/quest_item/shared_attunement_grid.iff" result.attribute_template_id = -1 result.stfName("item_n","attunement_grid") #### BEGIN MODIFICATIONS #### #### END MODIFICATIONS #### return result
{ "content_hash": "7a4f2a095273d9e7d4801410d7549074", "timestamp": "", "source": "github", "line_count": 13, "max_line_length": 82, "avg_line_length": 24.23076923076923, "alnum_prop": 0.7015873015873015, "repo_name": "anhstudios/swganh", "id": "ddf605b5d2e37eb365cbf7a0808f0e7b443f5323", "size": "460", "binary": false, "copies": "2", "ref": "refs/heads/develop", "path": "data/scripts/templates/object/tangible/mission/quest_item/shared_attunement_grid.py", "mode": "33188", "license": "mit", "language": [ { "name": "Batchfile", "bytes": "11887" }, { "name": "C", "bytes": "7699" }, { "name": "C++", "bytes": "2357839" }, { "name": "CMake", "bytes": "41264" }, { "name": "PLSQL", "bytes": "42065" }, { "name": "Python", "bytes": "7503510" }, { "name": "SQLPL", "bytes": "42770" } ], "symlink_target": "" }
#include "su_tests/simple_tests.h" #include "su_saxparser.h" #include "su_flat_map.h" #ifdef HAS_EXPAT #include <sstream> #include <cctype> class MyParser : public su::saxparser { public: MyParser( std::istream &i_stream ) : su::saxparser( i_stream ){} virtual void startDocument() { ++_seenStartDoc; } virtual void endDocument() { ++_seenEndDoc; } virtual bool startElement( const su::NameURI &i_nameURI, const std::unordered_map<su::NameURI,std::string_view> &i_attribs ) { _startElem.emplace_back( i_nameURI.name, i_nameURI.URI, i_attribs ); return true; } virtual bool endElement( const su::NameURI &i_nameURI ) { _endElem.emplace_back( i_nameURI.name, i_nameURI.URI ); return true; } virtual bool characters( const std::string_view &i_s ) { std::string_view s( i_s ); while ( not s.empty() and std::isspace(s[0]) ) s.remove_prefix( 1 ); while ( not s.empty() and std::isspace(s.back()) ) s.remove_suffix( 1 ); if ( not s.empty() ) _characters.push_back( std::string{ s } ); return true; } int _seenStartDoc = 0; int _seenEndDoc = 0; struct Elem { Elem( const std::string_view &i_localname, const std::string_view &i_URI, const std::unordered_map<su::NameURI,std::string_view> &i_attribs ) : localname( i_localname ), URI( i_URI ) { for ( auto &it : i_attribs ) attribs[MyNameURI{std::string(it.first.name),std::string(it.first.URI)}] = it.second; } Elem( const std::string_view &i_localname, const std::string_view &i_URI ) : localname( i_localname ), URI( i_URI ) {} std::string localname; std::string URI; struct MyNameURI { std::string name; std::string URI; bool operator<( const MyNameURI &rhs ) const { return std::tie(name,URI) < std::tie(rhs.name,rhs.URI); } }; su::flat_map<MyNameURI,std::string> attribs; }; std::vector<Elem> _startElem; std::vector<Elem> _endElem; std::vector<std::string> _characters; }; struct xml_tests { void test_case_1() { const char *xmlPtr = R"(<?xml version="1.0" encoding="UTF-8"?> <instructionals module="Qt"> this is text </instructionals> )"; std::istringstream istr( xmlPtr ); MyParser parser( istr ); parser.parse(); TEST_ASSERT_EQUAL( parser._seenStartDoc, 1 ); TEST_ASSERT_EQUAL( parser._seenEndDoc, 1 ); TEST_ASSERT_EQUAL( parser._startElem.size(), 1 ); TEST_ASSERT_EQUAL( parser._startElem.at(0).localname, "instructionals" ); TEST_ASSERT( parser._startElem.at(0).URI.empty() ); TEST_ASSERT_EQUAL( parser._startElem.at(0).attribs.size(), 1 ); TEST_ASSERT_EQUAL( parser._startElem.at(0).attribs.begin()->first.name, "module" ); TEST_ASSERT( parser._startElem.at(0).attribs.begin()->first.URI.empty() ); TEST_ASSERT_EQUAL( parser._startElem.at(0).attribs.begin()->second, "Qt" ); TEST_ASSERT_EQUAL( parser._endElem.size(), 1 ); TEST_ASSERT_EQUAL( parser._endElem.at(0).localname, "instructionals" ); TEST_ASSERT( parser._endElem.at(0).URI.empty() ); TEST_ASSERT_EQUAL( parser._characters.size(), 1 ); TEST_ASSERT_EQUAL( parser._characters.at(0), "this is text" ); } }; REGISTER_TEST_SUITE( xml_tests, su::timed_test(), &xml_tests::test_case_1 ); #endif
{ "content_hash": "399eee5b099fe2ae15a73fbc3707220d", "timestamp": "", "source": "github", "line_count": 120, "max_line_length": 107, "avg_line_length": 26.658333333333335, "alnum_prop": 0.6567677399187246, "repo_name": "sandym/sutils", "id": "3f588c60ca50f577cec90d83559829615fe9252d", "size": "3655", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "tests/xml_tests.cpp", "mode": "33188", "license": "mit", "language": [ { "name": "C", "bytes": "2578" }, { "name": "C++", "bytes": "421128" }, { "name": "CMake", "bytes": "2542" } ], "symlink_target": "" }
import buildtool.command COMMAND = 'test_command_example' CUSTOM_ARG_NAME = 'custom_test_arg' CUSTOM_ARG_DEFAULT_VALUE = 'Custom Default Value' class TestCommand(buildtool.command.CommandProcessor): @property def calls(self): return self.__calls def __init__(self, factory, options): super(TestCommand, self).__init__(factory, options) self.__calls = 0 def _do_command(self): self.__calls += 1 class TestCommandFactory(buildtool.command.CommandFactory): def __init__(self): super(TestCommandFactory, self).__init__( COMMAND, TestCommand, 'My Test Command') def init_argparser(self, parser, defaults): super(TestCommandFactory, self).init_argparser(parser, defaults) TestCommandFactory.add_argument( parser, CUSTOM_ARG_NAME, defaults, CUSTOM_ARG_DEFAULT_VALUE) def register_commands(registry, subparsers, defaults): TestCommandFactory().register(registry, subparsers, defaults)
{ "content_hash": "766e227184e84795193e766bba101df1", "timestamp": "", "source": "github", "line_count": 32, "max_line_length": 68, "avg_line_length": 29.5, "alnum_prop": 0.722457627118644, "repo_name": "skim1420/spinnaker", "id": "1cdba67ec569eb9c0a4646a9fe8e83c5d5042a89", "size": "1578", "binary": false, "copies": "3", "ref": "refs/heads/master", "path": "unittest/buildtool/custom_test_command.py", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Dockerfile", "bytes": "1199" }, { "name": "Go", "bytes": "2745" }, { "name": "HTML", "bytes": "422" }, { "name": "Makefile", "bytes": "276" }, { "name": "Python", "bytes": "1221215" }, { "name": "Shell", "bytes": "182975" }, { "name": "Smarty", "bytes": "2087" } ], "symlink_target": "" }
/*! * Copyright (c) 2015 by Contributors * \file base.h * \brief configuration of MXNet as well as basic data structure. */ #ifndef MXNET_BASE_H_ #define MXNET_BASE_H_ #include "dmlc/base.h" #include <string> #include "dmlc/io.h" #include "dmlc/type_traits.h" #include "dmlc/parameter.h" #include "mshadow/tensor.h" // nnvm headers for symbolic construction. #include "nnvm/op.h" #include "nnvm/symbolic.h" #include "libinfo.h" #include "tuple.h" /*! * \brief define dllexport for Visual Studio */ #ifdef _MSC_VER #ifdef MXNET_EXPORTS #define MXNET_API __declspec(dllexport) #else #define MXNET_API __declspec(dllimport) #endif #else #define MXNET_API #endif /*! * \brief define prediction only */ #ifndef MXNET_PREDICT_ONLY #define MXNET_PREDICT_ONLY 0 #endif /*! \brief major version */ #define MXNET_MAJOR 2 /*! \brief minor version */ #define MXNET_MINOR 0 /*! \brief patch version */ #define MXNET_PATCH 0 /*! \brief mxnet version */ #define MXNET_VERSION (MXNET_MAJOR*10000 + MXNET_MINOR*100 + MXNET_PATCH) /*! \brief helper for making version number */ #define MXNET_MAKE_VERSION(major, minor, patch) ((major)*10000 + (minor)*100 + patch) /*! * \brief define function name as profiler message */ #define PROFILER_MESSAGE_FUNCNAME (__FUNCTION__) /*! \brief namespace of mxnet */ namespace mxnet { /*! \brief mxnet cpu */ typedef mshadow::cpu cpu; /*! \brief mxnet gpu */ typedef mshadow::gpu gpu; /*! \brief index type usually use unsigned */ typedef mshadow::index_t index_t; /*! \brief data type that will be used to store ndarray */ typedef mshadow::default_real_t real_t; /*! \brief operator structure from NNVM */ using Op = nnvm::Op; /*! \brief Context information about the execution environment */ struct Context { /*! \brief Type of device */ enum DeviceType { kCPU = cpu::kDevMask, kGPU = gpu::kDevMask, kCPUPinned = 3, kCPUShared = 5, }; /*! \brief the device type we run the op on */ DeviceType dev_type; /*! \brief device id we are going to run it on */ int32_t dev_id; /*! \brief default constructor */ Context() : dev_type(kCPU), dev_id(0) {} /*! * \brief Get corresponding device mask * \return cpu::kDevMask or gpu::kDevMask */ inline DeviceType dev_mask() const { if (dev_type == kCPUPinned || dev_type == kCPUShared) return kCPU; return dev_type; } /*! * \brief Returns dev_id for kGPU and kCPUPinned, 0 otherwise */ inline int real_dev_id() const { if (dev_type == kCPUPinned || dev_type == kGPU) return dev_id; return 0; } /*! * \brief Comparator, used to enable Context as std::map key. * \param b another context to compare * \return compared result */ inline bool operator<(const Context &b) const; /*! * \brief check if current context equals another one * \param b another context to compare * \return whether dev mask and id are same */ inline bool operator==(const Context &b) const { return dev_type == b.dev_type && dev_id == b.dev_id; } /*! * \brief check if current context not equals another one * \param b another context to compare * \return whether they are not the same */ inline bool operator!=(const Context &b) const { return !(*this == b); } /*! * \brief save the content into binary stream * \param strm the output stream */ inline void Save(dmlc::Stream *strm) const { strm->Write(&dev_type, sizeof(dev_type)); strm->Write(&dev_id, sizeof(dev_id)); } /*! * \brief load the content from binary stream * \param strm the output stream * \return whether the load is successful */ inline bool Load(dmlc::Stream *strm) { if (strm->Read(&dev_type, sizeof(dev_type)) != sizeof(dev_type)) return false; if (strm->Read(&dev_id, sizeof(int32_t)) != sizeof(int32_t)) return false; return true; } /*! \brief the maximal device type */ static const int32_t kMaxDevType = 6; /*! \brief the maximal device index */ static const int32_t kMaxDevID = 16; /*! * \brief Create a new context. * \param dev_type device type. * \param dev_id device id. -1 for current device. */ inline static Context Create(DeviceType dev_type, int32_t dev_id = -1); /*! \return CPU Context */ inline static Context CPU(int32_t dev_id = 0); /*! * Create a GPU context. * \param dev_id the device id. * \return GPU Context. -1 for current GPU. */ inline static Context GPU(int32_t dev_id = -1); /*! * Get the number of GPUs available. * \return The number of GPUs that are available. */ inline static int32_t GetGPUCount(); /*! * Is the cuda driver installed and visible to the system. * \return Whether the driver is present. */ inline static bool GPUDriverPresent(); /*! * Get the number of streams that a GPU Worker has available to operations. * \return The number of streams that are available. */ inline static int32_t GetGPUStreamsPerWorker(); /*! * \brief get the free and total available memory on a GPU * \param dev the GPU number to query * \param free_mem pointer to the uint64_t holding free GPU memory * \param total_mem pointer to the uint64_t holding total GPU memory * \return No return value */ inline static void GetGPUMemoryInformation(int dev, uint64_t *free, uint64_t *total); /*! * Create a pinned CPU context. * \param dev_id the device id for corresponding GPU. * \return Pinned CPU context. -1 for current GPU. */ inline static Context CPUPinned(int32_t dev_id = -1); /*! * Create a CPU shared memory context. * \param dev_id dummy device id. * \return CPU shared memory context. */ inline static Context CPUShared(int32_t dev_id = 0); /*! * Create a context from string of the format [cpu|gpu|cpu_pinned](n) * \param str the string pattern * \return Context */ inline static Context FromString(const std::string& str); private: #if MXNET_USE_CUDA static void CudaLibChecks(); #endif #if MXNET_USE_CUDNN static void CuDNNLibChecks(); #endif }; #if MXNET_USE_CUDA /*! \brief Holds an auxiliary mshadow gpu stream that can be synced with a primary stream. */ class GPUAuxStream { public: /*! * \brief constructor. * \param primary_stream gpu stream that is synced with the created auxiliary stream. */ explicit GPUAuxStream(mshadow::Stream<gpu> *primary_stream) : primary_stream_(primary_stream), aux_stream_(primary_stream), gpu_stream_sync_event_(nullptr) { if (Context::GetGPUStreamsPerWorker() >= 2) { // Create auxiliary stream on the same device with the same properties as the primary stream bool primary_has_blas_handle = primary_stream->blas_handle_ownership_ == mshadow::Stream<gpu>::OwnHandle; bool primary_has_dnn_handle = primary_stream->dnn_handle_ownership_ == mshadow::Stream<gpu>::OwnHandle; aux_stream_ = mshadow::NewStream<gpu>(primary_has_blas_handle, primary_has_dnn_handle, primary_stream->dev_id); MSHADOW_CUDA_CALL(cudaEventCreateWithFlags(&gpu_stream_sync_event_, cudaEventDisableTiming)); } } /*! \brief destructor */ ~GPUAuxStream() { // If the aux_stream_ == primary_stream_, then we created no new streams to destroy. if (aux_stream_ != primary_stream_) { MSHADOW_CATCH_ERROR(mshadow::DeleteStream<gpu>(aux_stream_)); MSHADOW_CATCH_ERROR(cudaEventDestroy(gpu_stream_sync_event_)); } } /*! * \brief Makes future aux stream work wait on the completion of existing primary stream work. */ void PreAuxStreamUseSync() { // If the aux_stream_ == primary_stream_, then no synchronization is necessary. if (aux_stream_ != primary_stream_) StreamSync(primary_stream_, aux_stream_, gpu_stream_sync_event_); } /*! * \brief Makes future primary stream work wait on the completion of existing aux stream work. */ void PostAuxStreamUseSync() { // If the aux_stream_ == primary_stream_, then no synchronization is necessary. if (aux_stream_ != primary_stream_) StreamSync(aux_stream_, primary_stream_, gpu_stream_sync_event_); } /*! \brief Getter for created auxiliary stream. */ mshadow::Stream<gpu> *GetStream() { return aux_stream_; } /*! * \brief Make future work enqueued to `s2` wait on completion of current work enqueued to `s1`. * \param s1 stream with work that must be completed before future s2 work can begin. * \param s2 stream whose future work is made to wait on the completion of existing s1 work. * \param event used to pass s1 state to s2. */ static void StreamSync(mshadow::Stream<gpu> *s1, mshadow::Stream<gpu> *s2, cudaEvent_t event) { MSHADOW_CUDA_CALL(cudaEventRecord(event, s1->stream_)); MSHADOW_CUDA_CALL(cudaStreamWaitEvent(s2->stream_, event, 0)); } private: mshadow::Stream<gpu> *primary_stream_; mshadow::Stream<gpu> *aux_stream_; cudaEvent_t gpu_stream_sync_event_; }; /*! * \brief Provides automatic coordination of an auxilary stream with a primary one. * This object, upon construction, prepares an aux stream for use by syncing it with enqueued * primary-stream work. Object destruction will sync again so future primary-stream work * will wait on enqueued aux-stream work. If MXNET_GPU_WORKER_NSTREAMS == 1, then this defaults * simply: the primary stream will equal the aux stream and the syncs will be executed as nops. * See ./src/operator/cudnn/cudnn_convolution-inl.h for a usage example. */ class SyncedGPUAuxStream { public: /*! * \brief constructor. * \param gpu_aux_stream auxilary gpu stream that is managed by this RAII object. */ explicit SyncedGPUAuxStream(GPUAuxStream *gpu_aux_stream) : gpu_aux_stream_(gpu_aux_stream) { gpu_aux_stream_->PreAuxStreamUseSync(); } /*! \brief destructor */ ~SyncedGPUAuxStream() { gpu_aux_stream_->PostAuxStreamUseSync(); } /*! \brief copy constructor deleted to prevent unexpected synchronizations. */ SyncedGPUAuxStream(const SyncedGPUAuxStream&) = delete; /*! \brief copy assignment operator deleted to prevent unexpected synchronizations. */ void operator=(const SyncedGPUAuxStream&) = delete; /*! \brief move constructor permitted as alternative to copying. */ SyncedGPUAuxStream(SyncedGPUAuxStream&&) = default; /*! \brief move assignment operator permitted as alternative to copy assignment. */ SyncedGPUAuxStream& operator=(SyncedGPUAuxStream&&) = default; /*! \brief Getter for underlying mshadow::Stream<gpu>. */ inline mshadow::Stream<gpu>* GetStream() const { return gpu_aux_stream_->GetStream(); } private: GPUAuxStream *gpu_aux_stream_; }; #endif // MXNET_USE_CUDA /*! * \brief execution time context. * The information needed in runtime for actual execution. */ struct RunContext { /*! \brief base Context */ Context ctx; /*! * \brief the stream of the device, can be nullptr or Stream<gpu>* in GPU mode */ void *stream; /*! * \brief the auxiliary stream of the device, can be nullptr or Stream<gpu>* in GPU mode */ void *aux_stream; /*! * \brief indicator of whether this execution is run in bulk mode */ bool is_bulk; /*! * \brief get mshadow stream from Context * \return the mshadow stream * \tparam xpu the device type of the stream */ template<typename xpu> inline mshadow::Stream<xpu>* get_stream() const { return static_cast<mshadow::Stream<xpu>*>(stream); } #if MXNET_USE_CUDA /*! * \brief get an RAII object that transparently handles the syncing of the auxiliary stream. * \return the aux stream auto-syncing object */ inline SyncedGPUAuxStream get_gpu_aux_stream() const { return SyncedGPUAuxStream(static_cast<GPUAuxStream*>(aux_stream)); } #endif /*! \brief get the base Context from RunContext */ inline const Context& get_ctx() const { return ctx; } }; } // namespace mxnet //! \cond Doxygen_Suppress namespace mxnet { // implementing Context inline bool Context::operator<(const Context &b) const { if (dev_type == b.dev_type) { return dev_id < b.dev_id; } else { return dev_type < b.dev_type; } } inline Context Context::Create(DeviceType dev_type, int32_t dev_id) { Context ctx; ctx.dev_type = dev_type; ctx.dev_id = dev_id < 0 ? 0 : dev_id; if (dev_type & kGPU) { #if MXNET_USE_CUDA CudaLibChecks(); #endif #if MXNET_USE_CUDNN CuDNNLibChecks(); #endif if (dev_id < 0) { #if MXNET_USE_CUDA CHECK_EQ(cudaGetDevice(&ctx.dev_id), cudaSuccess); #else LOG(FATAL) << "Please compile with CUDA enabled for cuda features"; #endif } } return ctx; } inline Context Context::CPU(int32_t dev_id) { return Create(kCPU, dev_id); } inline Context Context::CPUPinned(int32_t dev_id) { return Create(kCPUPinned, dev_id); } inline Context Context::CPUShared(int32_t dev_id) { return Create(kCPUShared, dev_id); } inline Context Context::GPU(int32_t dev_id) { return Create(kGPU, dev_id); } inline bool Context::GPUDriverPresent() { #if MXNET_USE_CUDA int cuda_driver_version = 0; CHECK_EQ(cudaDriverGetVersion(&cuda_driver_version), cudaSuccess); return cuda_driver_version > 0; #else return false; #endif } inline int32_t Context::GetGPUCount() { #if MXNET_USE_CUDA if (!GPUDriverPresent()) { return 0; } int32_t count; cudaError_t e = cudaGetDeviceCount(&count); // TODO(junwu): Remove e == cudaErrorInsufficientDriver // This is skipped for working around wheel build system with older CUDA driver. if (e == cudaErrorNoDevice || e == cudaErrorInsufficientDriver) { return 0; } CHECK_EQ(e, cudaSuccess) << " CUDA: " << cudaGetErrorString(e); return count; #else return 0; #endif } inline int32_t Context::GetGPUStreamsPerWorker() { // The default number of streams available if the user has not set MXNET_GPU_WORKER_NSTREAMS. const int32_t default_num_streams = 1; // The get_aux_stream() interface can supply one additional stream beyond the standard one. static int32_t num_streams = dmlc::GetEnv("MXNET_GPU_WORKER_NSTREAMS", default_num_streams) >= 2 ? 2 : 1; return num_streams; } inline void Context::GetGPUMemoryInformation(int dev, uint64_t *free_mem, uint64_t *total_mem) { #if MXNET_USE_CUDA size_t memF, memT; cudaError_t e; int curDevice; e = cudaGetDevice(&curDevice); CHECK_EQ(e, cudaSuccess) << " CUDA: " << cudaGetErrorString(e); e = cudaSetDevice(dev); CHECK_EQ(e, cudaSuccess) << " CUDA: " << cudaGetErrorString(e); e = cudaMemGetInfo(&memF, &memT); CHECK_EQ(e, cudaSuccess) << " CUDA: " << cudaGetErrorString(e); e = cudaSetDevice(curDevice); CHECK_EQ(e, cudaSuccess) << " CUDA: " << cudaGetErrorString(e); *free_mem = static_cast<uint64_t>(memF); *total_mem = static_cast<uint64_t>(memT); #else LOG(FATAL) << "This call is only supported for MXNet built with CUDA support."; #endif } inline Context Context::FromString(const std::string& str) { Context ret; try { const std::string::size_type l = str.find('('); CHECK_NE(l, std::string::npos); const std::string::size_type r = str.find(')'); CHECK_EQ(r, str.length()-1); const std::string type = str.substr(0, l); int id = std::stoi(str.substr(l+1, r-l-1)); if (type == "cpu") { ret = CPU(id); } else if (type == "gpu") { ret = GPU(id); } else if (type == "cpu_pinned") { ret = CPUPinned(id); } else if (type == "cpu_shared") { ret = CPUShared(id); } else { LOG(FATAL) << "Invalid context string " << str; } } catch (...) { LOG(FATAL) << "Invalid context string " << str; } return ret; } inline std::ostream& operator<<(std::ostream &out, const Context &ctx) { if (ctx.dev_type == Context::kCPU) { out << "cpu("; } else if (ctx.dev_type == Context::kGPU) { out << "gpu("; } else if (ctx.dev_type == Context::kCPUPinned) { out << "cpu_pinned("; } else if (ctx.dev_type == Context::kCPUShared) { out << "cpu_shared("; } else { out << "unknown("; } out << ctx.dev_id << ")"; return out; } // describe op registration point #define STRINGIZE_DETAIL(x) #x #define STRINGIZE(x) STRINGIZE_DETAIL(x) #define MXNET_DESCRIBE(...) describe(__VA_ARGS__ "\n\nFrom:" __FILE__ ":" STRINGIZE(__LINE__)) #define ADD_FILELINE "\n\nDefined in " __FILE__ ":L" STRINGIZE(__LINE__) #if MXNET_USE_MKLDNN == 1 || MXNET_USE_INTGEMM == 1 constexpr size_t kMKLDNNAlign = 64; #endif } // namespace mxnet namespace std { template<> struct hash<mxnet::Context> { size_t operator()(const mxnet::Context& ctx) const { size_t res = 0; res = dmlc::HashCombine(res, static_cast<size_t>(ctx.dev_type)); res = dmlc::HashCombine(res, static_cast<size_t>(ctx.dev_id)); return res; } }; #if __cplusplus < 201402L && !defined(_MSC_VER) template<typename T, typename... Args> inline std::unique_ptr<T> make_unique(Args&&... args) { return std::unique_ptr<T>(new T(std::forward<Args>(args)...)); } #endif } // namespace std #include "./tensor_blob.h" //! \endcond #endif // MXNET_BASE_H_
{ "content_hash": "925ec48845d9522401e2a7b63d83dbb1", "timestamp": "", "source": "github", "line_count": 551, "max_line_length": 99, "avg_line_length": 31.17059891107078, "alnum_prop": 0.6650363901018923, "repo_name": "sxjscience/mxnet", "id": "addd7665f5be287d526612b4e30c45e5ce3101c6", "size": "17982", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "include/mxnet/base.h", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "ANTLR", "bytes": "1731" }, { "name": "Batchfile", "bytes": "13130" }, { "name": "C", "bytes": "233076" }, { "name": "C++", "bytes": "9825123" }, { "name": "CMake", "bytes": "164182" }, { "name": "Clojure", "bytes": "622640" }, { "name": "Cuda", "bytes": "1342259" }, { "name": "Dockerfile", "bytes": "100733" }, { "name": "Groovy", "bytes": "167263" }, { "name": "HTML", "bytes": "40268" }, { "name": "Java", "bytes": "202775" }, { "name": "Julia", "bytes": "445413" }, { "name": "Jupyter Notebook", "bytes": "3660357" }, { "name": "MATLAB", "bytes": "36633" }, { "name": "Makefile", "bytes": "149220" }, { "name": "Perl", "bytes": "1558293" }, { "name": "PowerShell", "bytes": "9244" }, { "name": "Python", "bytes": "9890105" }, { "name": "R", "bytes": "357982" }, { "name": "Raku", "bytes": "9012" }, { "name": "SWIG", "bytes": "161870" }, { "name": "Scala", "bytes": "1304635" }, { "name": "Shell", "bytes": "464521" }, { "name": "Smalltalk", "bytes": "3497" } ], "symlink_target": "" }
package de.kaiserpfalzedv.commons.api.data.types; import java.io.Serializable; /** * @author klenkes {@literal <rlichti@kaiserpfalz-edv.de>} * @version 1.0.0 * @since 2017-08-19 */ public interface Email extends Serializable { String getAddress(); }
{ "content_hash": "fcb9801fac215857217495b6d2edb6de", "timestamp": "", "source": "github", "line_count": 14, "max_line_length": 58, "avg_line_length": 18.714285714285715, "alnum_prop": 0.7137404580152672, "repo_name": "klenkes74/kp-office", "id": "807a7778b3be9bb44a990619a08837279a82fede", "size": "886", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "kp-commons-root/kp-commons-api/src/main/java/de/kaiserpfalzedv/commons/api/data/types/Email.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "30222" }, { "name": "HTML", "bytes": "842" }, { "name": "Java", "bytes": "1180354" } ], "symlink_target": "" }
/* * Created on Sep 28, 2005 * * TODO To change the template for this generated file go to Window - Preferences - Java - Code * Style - Code Templates */ package org.apache.geode.cache.query.data; import java.util.ArrayList; import java.util.List; public class Student { private static int counter = 0; static String[] names = {"English", "Hindi", "Maths", "Bio"}; static String[] teacher_names = {"X", "Y", "Z", "A"}; public String name; public int rollnum; public List subjects = new ArrayList(); public List teachers = new ArrayList(); public static void initializeCounter() { counter = 0; } public Student(String name) { this.name = name; synchronized (Student.class) { rollnum = ++counter; } int rem = rollnum % names.length; if (rem == 0) { rem = 4; } for (int j = 0; j < rem; ++j) { subjects.add(new Subject(names[j])); teachers.add(new Teacher(teacher_names[j])); } } public class Subject { public String subject; public Subject(String sub) { subject = sub; } } public static class Teacher { public String teacher; public Teacher(String teacher) { this.teacher = teacher; } } }
{ "content_hash": "a78353e48a513acd2b519f30792997af", "timestamp": "", "source": "github", "line_count": 60, "max_line_length": 95, "avg_line_length": 20.5, "alnum_prop": 0.6186991869918699, "repo_name": "jdeppe-pivotal/geode", "id": "4cb5aba7224d993cfc9fe39675c78b6d457293d5", "size": "2019", "binary": false, "copies": "4", "ref": "refs/heads/develop", "path": "geode-junit/src/main/java/org/apache/geode/cache/query/data/Student.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "104031" }, { "name": "Dockerfile", "bytes": "15956" }, { "name": "Go", "bytes": "40709" }, { "name": "Groovy", "bytes": "41916" }, { "name": "HTML", "bytes": "4037680" }, { "name": "Java", "bytes": "33151406" }, { "name": "JavaScript", "bytes": "1780821" }, { "name": "Python", "bytes": "29801" }, { "name": "Ruby", "bytes": "1801" }, { "name": "SCSS", "bytes": "2677" }, { "name": "Shell", "bytes": "275617" } ], "symlink_target": "" }
<readable><title>2709648336_15455e60b2</title><content> A brown dog in midair with a Frisbee in his mouth . A brown dog is catching a Frisbee in midair . A brown dog jumped into the air and caught a Frisbee . A large brown and black dog jumps in the air holding a white Frisbee in its mouth . The dog leaps to catch the Frisbee . </content></readable>
{ "content_hash": "7f0fd37c283c941b16f8b94b5136c549", "timestamp": "", "source": "github", "line_count": 7, "max_line_length": 83, "avg_line_length": 50.142857142857146, "alnum_prop": 0.7663817663817664, "repo_name": "kevint2u/audio-collector", "id": "27a0063a14bc700ad24c303cb1a5bb1de7a660d3", "size": "351", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "captions/xml/2709648336_15455e60b2.xml", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "1015" }, { "name": "HTML", "bytes": "18349" }, { "name": "JavaScript", "bytes": "109819" }, { "name": "Python", "bytes": "3260" }, { "name": "Shell", "bytes": "4319" } ], "symlink_target": "" }
define([ 'knockout', './ComparativeCohortAnalysis/ComparativeCohortAnalysis' ], function ( ko, ComparativeCohortAnalysis ) { class EstimationAnalysisSettings { constructor(data = {}, estimationType, defaultCovariateSettings) { this.estimationType = (data.estimationType || estimationType); this.analysisSpecification = this.getAnalysisObject(this.estimationType, data.analysisSpecification, defaultCovariateSettings); } getAnalysisObject(estimationType, analysisSpecification, defaultCovariateSettings) { if (estimationType === "ComparativeCohortAnalysis") { return new ComparativeCohortAnalysis(analysisSpecification, defaultCovariateSettings); } else { console.error("estimationType property not set on Estimation Analysis and cannot initialize properly.") } } } return EstimationAnalysisSettings; });
{ "content_hash": "b00ff9af614c08911b10fcec8c8a02c3", "timestamp": "", "source": "github", "line_count": 24, "max_line_length": 139, "avg_line_length": 39.541666666666664, "alnum_prop": 0.7007376185458377, "repo_name": "OHDSI/Atlas", "id": "e2dcd7142dc2642da563b62ec5cd983cd86c4b5a", "size": "949", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "js/pages/estimation/inputTypes/EstimationAnalysisSettings.js", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "77555" }, { "name": "Dockerfile", "bytes": "2111" }, { "name": "HTML", "bytes": "1145023" }, { "name": "JavaScript", "bytes": "2067738" }, { "name": "Less", "bytes": "63037" }, { "name": "R", "bytes": "4254" }, { "name": "Shell", "bytes": "847" } ], "symlink_target": "" }
declare module JSX { interface Element {} interface IntrinsicElements { div: any; } } // The "React" module is the runtime API of React. declare module React { function createElement(...args: any[]): Element; function render(element: JSX.Element, node: HTMLElement): void; } // Fake a subcomponent, just to exercise components within components. declare var Component: any; let simple = <div></div>; let hello = 'hello'; let helloDiv = <div> {hello} hello, world <Component/> </div>; React.render(helloDiv, document.body);
{ "content_hash": "186dfb2e3688c7ee27b8ac0fe336080f", "timestamp": "", "source": "github", "line_count": 26, "max_line_length": 70, "avg_line_length": 21.076923076923077, "alnum_prop": 0.6970802919708029, "repo_name": "PaulMrn/TFC", "id": "3c2762167f77503ec001948111c2ae171a4c1e1b", "size": "750", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "node_modules/tsickle/test_files/jsx/jsx.tsx", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "7520" }, { "name": "HTML", "bytes": "9300" }, { "name": "JavaScript", "bytes": "1649" }, { "name": "TypeScript", "bytes": "107063" } ], "symlink_target": "" }
import {isDefined, isTabVisible, isValue, parseDate} from "../../module/util"; export default { /** * Flow data to the chart.<br><br> * By this API, you can append new data points to the chart. * @function flow * @instance * @memberof Chart * @param {object} args The object can consist with following members:<br> * * | Key | Type | Description | * | --- | --- | --- | * | json | Object | Data as JSON format (@see [data․json](Options.html#.data%25E2%2580%25A4json)) | * | rows | Array | Data in array as row format (@see [data․rows](Options.html#.data%25E2%2580%25A4json)) | * | columns | Array | Data in array as column format (@see [data․columns](Options.html#.data%25E2%2580%25A4columns)) | * | to | String | The lower x edge will move to that point. If not given, the lower x edge will move by the number of given data points | * | length | Number | The lower x edge will move by the number of this argument | * | duration | Number | The duration of the transition will be specified value. If not given, transition.duration will be used as default | * | done | Function | The specified function will be called when flow ends | * * - **NOTE:** * - If json, rows and columns given, the data will be loaded. * - If data that has the same target id is given, the chart will be appended. * - Otherwise, new target will be added. One of these is required when calling. * - If json specified, keys is required as well as data.json. * - If tab isn't visible(by evaluating `document.hidden`), will not be executed to prevent unnecessary work. * @example * // 2 data points will be apprended to the tail and popped from the head. * // After that, 4 data points will be appended and no data points will be poppoed. * chart.flow({ * columns: [ * ["x", "2018-01-11", "2018-01-21"], * ["data1", 500, 200], * ["data2", 100, 300], * ["data3", 200, 120] * ], * to: "2013-01-11", * done: function () { * chart.flow({ * columns: [ * ["x", "2018-02-11", "2018-02-12", "2018-02-13", "2018-02-14"], * ["data1", 200, 300, 100, 250], * ["data2", 100, 90, 40, 120], * ["data3", 100, 100, 300, 500] * ], * length: 2, * duration: 1500 * }); * } * }); */ flow(args): void { const $$ = this.internal; let data; if (args.json || args.rows || args.columns) { $$.convertData(args, res => { data = res; _(); }); } /** * Process flows * @private */ function _(): void { let domain; let length: number = 0; let tail = 0; let diff; let to; if ($$.state.redrawing || !data || !isTabVisible()) { return; } const notfoundIds: string[] = []; const orgDataCount = $$.getMaxDataCount(); const targets = $$.convertDataToTargets(data, true); const isTimeSeries = $$.axis.isTimeSeries(); // Update/Add data $$.data.targets.forEach(t => { let found = false; for (let i = 0; i < targets.length; i++) { if (t.id === targets[i].id) { found = true; if (t.values[t.values.length - 1]) { tail = t.values[t.values.length - 1].index + 1; } length = targets[i].values.length; for (let j = 0; j < length; j++) { targets[i].values[j].index = tail + j; if (!isTimeSeries) { targets[i].values[j].x = tail + j; } } t.values = t.values.concat(targets[i].values); targets.splice(i, 1); break; } } !found && notfoundIds.push(t.id); }); // Append null for not found targets $$.data.targets.forEach(t => { for (let i = 0; i < notfoundIds.length; i++) { if (t.id === notfoundIds[i]) { tail = t.values[t.values.length - 1].index + 1; for (let j = 0; j < length; j++) { t.values.push({ id: t.id, index: tail + j, x: isTimeSeries ? $$.getOtherTargetX(tail + j) : tail + j, value: null }); } } } }); // Generate null values for new target if ($$.data.targets.length) { targets.forEach(t => { const missing: any[] = []; for (let i = $$.data.targets[0].values[0].index; i < tail; i++) { missing.push({ id: t.id, index: i, x: isTimeSeries ? $$.getOtherTargetX(i) : i, value: null }); } t.values.forEach(v => { v.index += tail; if (!isTimeSeries) { v.x += tail; } }); t.values = missing.concat(t.values); }); } $$.data.targets = $$.data.targets.concat(targets); // add remained // check data count because behavior needs to change when it"s only one // const dataCount = $$.getMaxDataCount(); const baseTarget = $$.data.targets[0]; const baseValue = baseTarget.values[0]; // Update length to flow if needed if (isDefined(args.to)) { length = 0; to = isTimeSeries ? parseDate.call($$, args.to) : args.to; baseTarget.values.forEach(v => { v.x < to && length++; }); } else if (isDefined(args.length)) { length = args.length; } // If only one data, update the domain to flow from left edge of the chart if (!orgDataCount) { if (isTimeSeries) { diff = baseTarget.values.length > 1 ? baseTarget.values[baseTarget.values.length - 1].x - baseValue.x : baseValue.x - $$.getXDomain($$.data.targets)[0]; } else { diff = 1; } domain = [baseValue.x - diff, baseValue.x]; } else if (orgDataCount === 1 && isTimeSeries) { diff = (baseTarget.values[baseTarget.values.length - 1].x - baseValue.x) / 2; domain = [new Date(+baseValue.x - diff), new Date(+baseValue.x + diff)]; } domain && $$.updateXDomain(null, true, true, false, domain); // Set targets $$.updateTargets($$.data.targets); // Redraw with new targets $$.redraw({ flow: { index: baseValue.index, length: length, duration: isValue(args.duration) ? args.duration : $$.config.transition_duration, done: args.done, orgDataCount: orgDataCount, }, withLegend: true, withTransition: orgDataCount > 1, withTrimXDomain: false, withUpdateXAxis: true }); } } };
{ "content_hash": "70153ba21870cc3ff794226b323843ab", "timestamp": "", "source": "github", "line_count": 216, "max_line_length": 144, "avg_line_length": 28.912037037037038, "alnum_prop": 0.5703763010408327, "repo_name": "naver/billboard.js", "id": "02373389667b9cede2483f4bdbaed30711ef23c3", "size": "6360", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/Chart/api/flow.ts", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "1069" }, { "name": "HTML", "bytes": "432" }, { "name": "JavaScript", "bytes": "22426" }, { "name": "SCSS", "bytes": "23498" }, { "name": "Shell", "bytes": "2920" }, { "name": "TypeScript", "bytes": "1461190" } ], "symlink_target": "" }
#ifndef ALIABSO_H #define ALIABSO_H /* $Id$ */ //////////////////////////////////////////////// // Manager class for detector: ABSO // //////////////////////////////////////////////// #include "AliModule.h" class AliABSO : public AliModule { public: AliABSO(); AliABSO(const char *name, const char *title); virtual ~AliABSO() {} virtual void CreateGeometry(); virtual void CreateMaterials(); virtual void Init(); virtual Int_t IsVersion() const {return 0;} virtual Int_t GetMatId(Int_t imat) const; virtual Int_t NumberOfLayers(Int_t i) const {return fNLayers[i];} virtual Float_t ZPositionOfLayer(Int_t i, Int_t il) const {return fZLayers[i][il];} virtual Int_t MaterialOfLayer (Int_t i, Int_t il) const {return fMLayers[i][il];} protected: Int_t fNLayers[2]; // Number of Material Layers in the tracking Region Float_t fZLayers[2][15]; // z-position of layers Int_t fMLayers[2][15]; // Material type of layers ClassDef(AliABSO,1) // Muon Absorber Class }; #endif
{ "content_hash": "d093780680eb7497c23441faf29a6d08", "timestamp": "", "source": "github", "line_count": 37, "max_line_length": 83, "avg_line_length": 30.18918918918919, "alnum_prop": 0.5666965085049239, "repo_name": "mkrzewic/AliRoot", "id": "6e19c2197283bbf6d3d6865c7e23404c17a77abe", "size": "1269", "binary": false, "copies": "9", "ref": "refs/heads/dev", "path": "STRUCT/AliABSO.h", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "Assembly", "bytes": "4478" }, { "name": "Batchfile", "bytes": "701" }, { "name": "C", "bytes": "14439474" }, { "name": "C++", "bytes": "92441913" }, { "name": "CMake", "bytes": "1182874" }, { "name": "CSS", "bytes": "9136" }, { "name": "Cuda", "bytes": "51450" }, { "name": "Fortran", "bytes": "33166465" }, { "name": "HTML", "bytes": "9522910" }, { "name": "M4", "bytes": "77872" }, { "name": "Makefile", "bytes": "868205" }, { "name": "Objective-C", "bytes": "287693" }, { "name": "PHP", "bytes": "10833197" }, { "name": "PLSQL", "bytes": "701975" }, { "name": "Pascal", "bytes": "2295" }, { "name": "Perl", "bytes": "12019" }, { "name": "PostScript", "bytes": "1946897" }, { "name": "Python", "bytes": "58967" }, { "name": "Shell", "bytes": "303176" }, { "name": "SourcePawn", "bytes": "7668" }, { "name": "TeX", "bytes": "936449" } ], "symlink_target": "" }
import System.FilePath.Glob import Test.DocTest main :: IO () main = glob "src/**/*.hs" >>= doctest
{ "content_hash": "d3151d16d87c0a417ed5e6e5edf7c93a", "timestamp": "", "source": "github", "line_count": 5, "max_line_length": 37, "avg_line_length": 20.2, "alnum_prop": 0.6633663366336634, "repo_name": "angerman/data-bitcode-edsl", "id": "4e85e16e7814394abacc97af3a3dd3d2c0bc7432", "size": "101", "binary": false, "copies": "12", "ref": "refs/heads/master", "path": "test/Doctest.hs", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "C", "bytes": "84" }, { "name": "Haskell", "bytes": "126309" }, { "name": "LLVM", "bytes": "1616" } ], "symlink_target": "" }
<?php namespace Google\Cloud\BigQuery; use Google\Cloud\BigQuery\Connection\ConnectionInterface; use Google\Cloud\Exception\NotFoundException; use Google\Cloud\Storage\StorageObject; /** * [BigQuery Tables](https://cloud.google.com/bigquery/docs/tables) are a * standard two-dimensional table with individual records organized in rows, and * a data type assigned to each column (also called a field). */ class Table { use JobConfigurationTrait; /** * @var ConnectionInterface $connection Represents a connection to BigQuery. */ protected $connection; /** * @var array The table's identity. */ private $identity; /** * @var array The table's metadata */ private $info; /** * @var ValueMapper Maps values between PHP and BigQuery. */ private $mapper; /** * @param ConnectionInterface $connection Represents a connection to * BigQuery. * @param string $id The table's id. * @param string $datasetId The dataset's id. * @param string $projectId The project's id. * @param ValueMapper $mapper Maps values between PHP and BigQuery. * @param array $info [optional] The table's metadata. */ public function __construct( ConnectionInterface $connection, $id, $datasetId, $projectId, ValueMapper $mapper, array $info = [] ) { $this->connection = $connection; $this->info = $info; $this->mapper = $mapper; $this->identity = [ 'tableId' => $id, 'datasetId' => $datasetId, 'projectId' => $projectId ]; } /** * Check whether or not the table exists. * * Example: * ``` * if ($table->exists()) { * echo "Table exists!"; * } * ``` * * @return bool */ public function exists() { try { $this->connection->getTable($this->identity + ['fields' => 'tableReference']); } catch (NotFoundException $ex) { return false; } return true; } /** * Delete the table. * * Example: * ``` * $table->delete(); * ``` * * @see https://cloud.google.com/bigquery/docs/reference/v2/tables/delete Tables delete API documentation. * * @param array $options [optional] Configuration options. */ public function delete(array $options = []) { $this->connection->deleteTable($options + $this->identity); } /** * Update the table. * * Example: * ``` * $table->update([ * 'friendlyName' => 'A friendly name.' * ]); * ``` * * @see https://cloud.google.com/bigquery/docs/reference/v2/tables/patch Tables patch API documentation. * * @param array $metadata The available options for metadata are outlined * at the [Table Resource API docs](https://cloud.google.com/bigquery/docs/reference/v2/tables#resource) * @param array $options [optional] Configuration options. */ public function update(array $metadata, array $options = []) { $options += $metadata; $this->info = $this->connection->patchTable($options + $this->identity); return $this->info; } /** * Retrieves the rows associated with the table and merges them together * with the schema. * * Example: * ``` * $rows = $table->rows(); * * foreach ($rows as $row) { * echo $row['name'] . PHP_EOL; * } * ``` * * @see https://cloud.google.com/bigquery/docs/reference/v2/tabledata/list Tabledata list API Documentation. * * @param array $options [optional] { * Configuration options. * * @type int $maxResults Maximum number of results to return. * @type int $startIndex Zero-based index of the starting row. * } * @return \Generator<array> * @throws GoogleException */ public function rows(array $options = []) { $options['pageToken'] = null; $schema = $this->info()['schema']['fields']; do { $response = $this->connection->listTableData($options + $this->identity); if (!isset($response['rows'])) { return; } foreach ($response['rows'] as $row) { $mergedRow = []; if ($row === null) { continue; } if (!array_key_exists('f', $row)) { throw new GoogleException('Bad response - missing key "f" for a row.'); } foreach ($row['f'] as $key => $value) { $fieldSchema = $schema[$key]; $mergedRow[$fieldSchema['name']] = $this->mapper->fromBigQuery($value, $fieldSchema); } yield $mergedRow; } $options['pageToken'] = isset($response['nextPageToken']) ? $response['nextPageToken'] : null; } while ($options['pageToken']); } /** * Runs a copy job which copies this table to a specified destination table. * * Example: * ``` * $sourceTable = $bigQuery->dataset('myDataset')->table('mySourceTable'); * $destinationTable = $bigQuery->dataset('myDataset')->table('myDestinationTable'); * * $job = $sourceTable->copy($destinationTable); * ``` * * @see https://cloud.google.com/bigquery/docs/reference/v2/jobs Jobs insert API Documentation. * * @param Table $destination The destination table. * @param array $options [optional] { * Configuration options. * * @type array $jobConfig Configuration settings for a copy job are * outlined in the [API Docs for `configuration.copy`](https://goo.gl/m8dro9). * If not provided default settings will be used. * } * @return Job */ public function copy(Table $destination, array $options = []) { $config = $this->buildJobConfig( 'copy', $this->identity['projectId'], [ 'destinationTable' => $destination->identity(), 'sourceTable' => $this->identity ], $options ); $response = $this->connection->insertJob($config); return new Job($this->connection, $response['jobReference']['jobId'], $this->identity['projectId'], $response); } /** * Runs an extract job which exports the contents of a table to Cloud * Storage. * * Example: * ``` * $destinationObject = $storage->bucket('myBucket')->object('tableOutput'); * $job = $table->export($destinationObject); * ``` * * @see https://cloud.google.com/bigquery/docs/reference/v2/jobs Jobs insert API Documentation. * * @param StorageObject $destination The destination object. * @param array $options [optional] { * Configuration options. * * @type array $jobConfig Configuration settings for an extract job are * outlined in the [API Docs for `configuration.extract`](https://goo.gl/SQ9XAE). * If not provided default settings will be used. * } * @return Job */ public function export(StorageObject $destination, array $options = []) { $objIdentity = $destination->identity(); $config = $this->buildJobConfig( 'extract', $this->identity['projectId'], [ 'sourceTable' => $this->identity, 'destinationUris' => ['gs://' . $objIdentity['bucket'] . '/' . $objIdentity['object']] ], $options ); $response = $this->connection->insertJob($config); return new Job($this->connection, $response['jobReference']['jobId'], $this->identity['projectId'], $response); } /** * Runs a load job which loads the provided data into the table. * * Example: * ``` * $job = $table->load(fopen('/path/to/my/data.csv', 'r')); * ``` * * @see https://cloud.google.com/bigquery/docs/reference/v2/jobs Jobs insert API Documentation. * * @param string|resource|StreamInterface $data The data to load. * @param array $options [optional] { * Configuration options. * * @type array $jobConfig Configuration settings for a load job are * outlined in the [API Docs for `configuration.load`](https://goo.gl/j6jyHv). * If not provided default settings will be used. * } * @return Job */ public function load($data, array $options = []) { $response = null; $config = $this->buildJobConfig( 'load', $this->identity['projectId'], ['destinationTable' => $this->identity], $options ); if ($data) { $config['data'] = $data; $response = $this->connection->insertJobUpload($config)->upload(); } else { $response = $this->connection->insertJob($config); } return new Job( $this->connection, $response['jobReference']['jobId'], $this->identity['projectId'], $response ); } /** * Runs a load job which loads data from a file in a Storage bucket into the * table. * * Example: * ``` * $object = $storage->bucket('myBucket')->object('important-data.csv'); * $job = $table->load($object); * ``` * * @see https://cloud.google.com/bigquery/docs/reference/v2/jobs Jobs insert API Documentation. * * @param StorageObject $destination The object to load data from. * @param array $options [optional] { * Configuration options. * * @type array $jobConfig Configuration settings for a load job are * outlined in the [API Docs for `configuration.load`](https://goo.gl/j6jyHv). * If not provided default settings will be used. * } * @return Job */ public function loadFromStorage(StorageObject $object, array $options = []) { $objIdentity = $object->identity(); $options['jobConfig']['sourceUris'] = ['gs://' . $objIdentity['bucket'] . '/' . $objIdentity['object']]; return $this->load(null, $options); } /** * Insert a record into the table without running a load job. * * Example: * ``` * $row = [ * 'city' => 'Detroit', * 'state' => 'MI' * ]; * * $insertResponse = $table->insertRow($row, [ * 'insertId' => '1' * ]); * * if (!$insertResponse->isSuccessful()) { * $row = $insertResponse->failedRows()[0]; * * print_r($row['rowData']); * * foreach ($row['errors'] as $error) { * echo $error['reason'] . ': ' . $error['message'] . PHP_EOL; * } * } * ``` * * @codingStandardsIgnoreStart * @see https://cloud.google.com/bigquery/docs/reference/v2/tabledata/insertAll Tabledata insertAll API Documentation. * @see https://cloud.google.com/bigquery/streaming-data-into-bigquery Streaming data into BigQuery. * * @param array $row Key/value set of data matching the table's schema. * @param array $options [optional] { * Please see * {@see Google\Cloud\BigQuery\Table::insertRows()} for the * other available configuration options. * * @type string $insertId Used to * [ensure data consistency](https://cloud.google.com/bigquery/streaming-data-into-bigquery#dataconsistency). * } * @return InsertResponse * @throws \InvalidArgumentException * @codingStandardsIgnoreEnd */ public function insertRow(array $row, array $options = []) { $row = ['data' => $row]; if (isset($options['insertId'])) { $row['insertId'] = $options['insertId']; unset($options['insertId']); } return $this->insertRows([$row], $options); } /** * Insert records into the table without running a load job. * * Example: * ``` * $rows = [ * [ * 'insertId' => '1', * 'data' => [ * 'city' => 'Detroit', * 'state' => 'MI' * ] * ], * [ * 'insertId' => '2', * 'data' => [ * 'city' => 'New York', * 'state' => 'NY' * ] * ] * ]; * * $insertResponse = $table->insertRows($rows); * * if (!$insertResponse->isSuccessful()) { * foreach ($insertResponse->failedRows() as $row) { * print_r($row['rowData']); * * foreach ($row['errors'] as $error) { * echo $error['reason'] . ': ' . $error['message'] . PHP_EOL; * } * } * } * ``` * * @codingStandardsIgnoreStart * @see https://cloud.google.com/bigquery/docs/reference/v2/tabledata/insertAll Tabledata insertAll API Documentation. * @see https://cloud.google.com/bigquery/streaming-data-into-bigquery Streaming data into BigQuery. * * @param array $rows The rows to insert. Each item in the array must * contain a `data` key which is to hold a key/value array with data * matching the schema of the table. Optionally, one may also provide * an `insertId` key which will be used to * [ensure data consistency](https://cloud.google.com/bigquery/streaming-data-into-bigquery#dataconsistency). * @param array $options [optional] { * Configuration options. * * @type bool $skipInvalidRows Insert all valid rows of a request, even * if invalid rows exist. The default value is `false`, which * causes the entire request to fail if any invalid rows exist. * **Defaults to** `false`. * @type bool $ignoreUnknownValues Accept rows that contain values that * do not match the schema. The unknown values are ignored. * The default value is `false`, which treats unknown values as errors. * **Defaults to** `false`. * @type string $templateSuffix If specified, treats the destination * table as a base template, and inserts the rows into an instance * table named "{destination}{templateSuffix}". BigQuery will * manage creation of the instance table, using the schema of the * base template table. See * [Creating tables automatically using template tables](https://cloud.google.com/bigquery/streaming-data-into-bigquery#template-tables) * for considerations when working with templates tables. * } * @return InsertResponse * @throws \InvalidArgumentException * @codingStandardsIgnoreEnd */ public function insertRows(array $rows, array $options = []) { foreach ($rows as $row) { if (!isset($row['data'])) { throw new \InvalidArgumentException('A row must have a data key.'); } foreach ($row['data'] as $key => $item) { $row['data'][$key] = $this->mapper->toBigQuery($item); } $row['json'] = $row['data']; unset($row['data']); $options['rows'][] = $row; } return new InsertResponse( $this->connection->insertAllTableData($this->identity + $options), $options['rows'] ); } /** * Retrieves the table's details. If no table data is cached a network * request will be made to retrieve it. * * Example: * ``` * $info = $table->info(); * echo $info['friendlyName']; * ``` * * @see https://cloud.google.com/bigquery/docs/reference/v2/tables#resource Tables resource documentation. * * @param array $options [optional] Configuration options. * @return array */ public function info(array $options = []) { if (!$this->info) { $this->reload($options); } return $this->info; } /** * Triggers a network request to reload the table's details. * * Example: * ``` * $table->reload(); * $info = $table->info(); * echo $info['friendlyName']; * ``` * * @see https://cloud.google.com/bigquery/docs/reference/v2/tables/get Tables get API documentation. * * @param array $options [optional] Configuration options. * @return array */ public function reload(array $options = []) { return $this->info = $this->connection->getTable($options + $this->identity); } /** * Retrieves the table's ID. * * Example: * ``` * echo $table->id(); * ``` * * @return string */ public function id() { return $this->identity['tableId']; } /** * Retrieves the table's identity. * * An identity provides a description of a nested resource. * * Example: * ``` * echo $table->identity()['projectId']; * ``` * * @return array */ public function identity() { return $this->identity; } }
{ "content_hash": "e5f904848ae8f251de16b97b20f9be90", "timestamp": "", "source": "github", "line_count": 562, "max_line_length": 150, "avg_line_length": 31.259786476868328, "alnum_prop": 0.543943533697632, "repo_name": "IRWNetwork/Stakeholders", "id": "0d9b7502af0ac4c59a95b16348bae8f8d14c90a0", "size": "18185", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "application/libraries/Gcloud/vendor/google/cloud/src/BigQuery/Table.php", "mode": "33188", "license": "mit", "language": [ { "name": "ApacheConf", "bytes": "3485" }, { "name": "CSS", "bytes": "1469000" }, { "name": "HTML", "bytes": "1040650" }, { "name": "JavaScript", "bytes": "2326357" }, { "name": "Makefile", "bytes": "285" }, { "name": "PHP", "bytes": "18185943" }, { "name": "Shell", "bytes": "680" }, { "name": "Smarty", "bytes": "4111127" } ], "symlink_target": "" }
<!-- Copyright Contributors to the Qiskit project. --> # Code of Conduct All members of this project agree to adhere to the Qiskit Code of Conduct listed at [https://github.com/Qiskit/qiskit/blob/master/CODE_OF_CONDUCT.md](https://github.com/Qiskit/qiskit/blob/master/CODE_OF_CONDUCT.md) ---- License: [CC BY 4.0](https://creativecommons.org/licenses/by/4.0/), Copyright Contributors to Qiskit.
{ "content_hash": "b9f66738350d364afbbe3954a8384f06", "timestamp": "", "source": "github", "line_count": 9, "max_line_length": 214, "avg_line_length": 44.22222222222222, "alnum_prop": 0.7512562814070352, "repo_name": "QISKit/qiskit-sdk-py", "id": "f82b61c5f62641335b41cdda1e459c6a8e9a716c", "size": "398", "binary": false, "copies": "1", "ref": "refs/heads/main", "path": "CODE_OF_CONDUCT.md", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Batchfile", "bytes": "2582" }, { "name": "C++", "bytes": "327518" }, { "name": "CMake", "bytes": "19294" }, { "name": "Makefile", "bytes": "5608" }, { "name": "Pascal", "bytes": "2444" }, { "name": "Python", "bytes": "1312801" }, { "name": "Shell", "bytes": "8385" } ], "symlink_target": "" }
package blue.lapis.pore.impl.event.vehicle; import static com.google.common.base.Preconditions.checkNotNull; import org.apache.commons.lang3.NotImplementedException; import org.bukkit.Location; import org.bukkit.entity.Vehicle; import org.bukkit.event.vehicle.VehicleMoveEvent; import org.spongepowered.api.event.entity.EntityMoveEvent; public class PoreVehicleMoveEvent extends VehicleMoveEvent { private final EntityMoveEvent handle; public PoreVehicleMoveEvent(EntityMoveEvent handle) { super(null, null, null); this.handle = checkNotNull(handle, "handle"); } public EntityMoveEvent getHandle() { return handle; } @Override public Vehicle getVehicle() { throw new NotImplementedException("TODO"); // TODO } @Override public Location getFrom() { throw new NotImplementedException("TODO"); // TODO } @Override public Location getTo() { throw new NotImplementedException("TODO"); // TODO } }
{ "content_hash": "5d8ab06942ccbb905d6931d72e440dd6", "timestamp": "", "source": "github", "line_count": 40, "max_line_length": 64, "avg_line_length": 25.175, "alnum_prop": 0.7130089374379345, "repo_name": "skcoreimaj/Pore", "id": "fa67bf8d2104498396904224d1de39aae98fdac5", "size": "2183", "binary": false, "copies": "4", "ref": "refs/heads/master", "path": "src/main/java/blue/lapis/pore/impl/event/vehicle/PoreVehicleMoveEvent.java", "mode": "33188", "license": "mit", "language": [ { "name": "Java", "bytes": "1365663" }, { "name": "Shell", "bytes": "4379" } ], "symlink_target": "" }
/** * @file minibatch_sgd_impl.hpp * @author Ryan Curtin * * Implementation of mini-batch SGD. */ #ifndef MLPACK_CORE_OPTIMIZERS_MINIBATCH_SGD_MINIBATCH_SGD_IMPL_HPP #define MLPACK_CORE_OPTIMIZERS_MINIBATCH_SGD_MINIBATCH_SGD_IMPL_HPP // In case it hasn't been included yet. #include "minibatch_sgd.hpp" namespace mlpack { namespace optimization { template<typename DecomposableFunctionType> MiniBatchSGD<DecomposableFunctionType>::MiniBatchSGD( DecomposableFunctionType& function, const size_t batchSize, const double stepSize, const size_t maxIterations, const double tolerance, const bool shuffle) : function(function), batchSize(batchSize), stepSize(stepSize), maxIterations(maxIterations), tolerance(tolerance), shuffle(shuffle) { /* Nothing to do. */ } //! Optimize the function (minimize). template<typename DecomposableFunctionType> double MiniBatchSGD<DecomposableFunctionType>::Optimize(arma::mat& iterate) { // Find the number of functions. const size_t numFunctions = function.NumFunctions(); size_t numBatches = numFunctions / batchSize; if (numFunctions % batchSize != 0) ++numBatches; // Capture last few. // This is only used if shuffle is true. arma::Col<size_t> visitationOrder; if (shuffle) visitationOrder = arma::shuffle(arma::linspace<arma::Col<size_t>>(0, (numBatches - 1), numBatches)); // To keep track of where we are and how things are going. size_t currentBatch = 0; double overallObjective = 0; double lastObjective = DBL_MAX; // Calculate the first objective function. for (size_t i = 0; i < numFunctions; ++i) overallObjective += function.Evaluate(iterate, i); // Now iterate! arma::mat gradient(iterate.n_rows, iterate.n_cols); for (size_t i = 1; i != maxIterations; ++i, ++currentBatch) { // Is this iteration the start of a sequence? if ((currentBatch % numBatches) == 0) { // Output current objective function. Log::Info << "Mini-batch SGD: iteration " << i << ", objective " << overallObjective << "." << std::endl; if (std::isnan(overallObjective) || std::isinf(overallObjective)) { Log::Warn << "Mini-batch SGD: converged to " << overallObjective << "; terminating with failure. Try a smaller step size?" << std::endl; return overallObjective; } if (std::abs(lastObjective - overallObjective) < tolerance) { Log::Info << "Mini-batch SGD: minimized within tolerance " << tolerance << "; terminating optimization." << std::endl; return overallObjective; } // Reset the counter variables. lastObjective = overallObjective; overallObjective = 0; currentBatch = 0; if (shuffle) visitationOrder = arma::shuffle(visitationOrder); } // Evaluate the gradient for this mini-batch. const size_t offset = (shuffle) ? batchSize * visitationOrder[currentBatch] : batchSize * currentBatch; function.Gradient(iterate, offset, gradient); if (visitationOrder[currentBatch] != numBatches - 1) { for (size_t j = 1; j < batchSize; ++j) { arma::mat funcGradient; function.Gradient(iterate, offset + j, funcGradient); gradient += funcGradient; } // Now update the iterate. iterate -= (stepSize / batchSize) * gradient; // Add that to the overall objective function. for (size_t j = 0; j < batchSize; ++j) overallObjective += function.Evaluate(iterate, offset + j); } else { // Handle last batch differently: it's not a full-size batch. const size_t lastBatchSize = numFunctions - offset - 1; for (size_t j = 1; j < lastBatchSize; ++j) { arma::mat funcGradient; function.Gradient(iterate, offset + j, funcGradient); gradient += funcGradient; } // Ensure the last batch size isn't zero, to avoid division by zero before // updating. if (lastBatchSize > 0) { // Now update the iterate. iterate -= (stepSize / lastBatchSize) * gradient; } else { // Now update the iterate. iterate -= stepSize * gradient; } // Add that to the overall objective function. for (size_t j = 0; j < lastBatchSize; ++j) overallObjective += function.Evaluate(iterate, offset + j); } } Log::Info << "Mini-batch SGD: maximum iterations (" << maxIterations << ") " << "reached; terminating optimization." << std::endl; // Calculate final objective. overallObjective = 0; for (size_t i = 0; i < numFunctions; ++i) overallObjective += function.Evaluate(iterate, i); return overallObjective; } } // namespace optimization } // namespace mlpack #endif
{ "content_hash": "9f31f25205f4b357a1449a92c0375848", "timestamp": "", "source": "github", "line_count": 156, "max_line_length": 80, "avg_line_length": 30.993589743589745, "alnum_prop": 0.6413650465356774, "repo_name": "ajjl/mlpack", "id": "9a2adf2e01ffbac3026fd9d1e0d86df6a8ca7771", "size": "4835", "binary": false, "copies": "5", "ref": "refs/heads/master", "path": "src/mlpack/core/optimizers/minibatch_sgd/minibatch_sgd_impl.hpp", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "C++", "bytes": "3769217" }, { "name": "CMake", "bytes": "114033" }, { "name": "Matlab", "bytes": "20897" }, { "name": "Shell", "bytes": "4045" } ], "symlink_target": "" }
/* eslint-disable no-unused-vars, no-unused-expressions */ /* @flow */ import React from "react"; import { compose, withProps } from "recompose"; import type { HOC } from "recompose"; type EnhancedCompProps = { a: string, b: number }; const Comp = ({ hello, b }) => ( <div> {hello} {b} { // $FlowExpectedError (b: number) } { // $FlowExpectedError (hello: number) } </div> ); const enhancer: HOC<*, EnhancedCompProps> = compose( withProps(({ a, b }) => ({ hello: a, b: `${b}` })), withProps(({ b, hello }) => ({ hello: (hello: string), // $FlowExpectedError (This type is incompatible with number) c: (b: number) })), // check non functional form of with props withProps({ d: "hi" }), withProps(props => ({ a: (props.a: string), d: (props.d: string), // $FlowExpectedError property not found err: props.iMNotExists, // $FlowExpectedError a not a number and not any aErr: (props.a: number), // $FlowExpectedError d not a number and not any dErr: (props.d: number) })) ); const EnhancedComponent = enhancer(Comp); <EnhancedComponent a={"1"} b={1} />; // $FlowExpectedError <EnhancedComponent a={"1"} b={"1"} />; // $FlowExpectedError <EnhancedComponent a={"1"} />;
{ "content_hash": "6a1414dd1513b351074328240f7890b9", "timestamp": "", "source": "github", "line_count": 58, "max_line_length": 65, "avg_line_length": 22.344827586206897, "alnum_prop": 0.5879629629629629, "repo_name": "splodingsocks/FlowTyped", "id": "8ade23063d179711b6a7b3b9cdb0812ca5f1673f", "size": "1296", "binary": false, "copies": "4", "ref": "refs/heads/master", "path": "definitions/npm/recompose_v0.26.x/flow_v0.55.x-v0.56.x/test_withProps.js", "mode": "33188", "license": "mit", "language": [ { "name": "JavaScript", "bytes": "55555" }, { "name": "Shell", "bytes": "234" } ], "symlink_target": "" }
SYNONYM #### According to The Catalogue of Life, 3rd January 2011 #### Published in Opredelitel' trutovykh gribov Belorussii 97 (1964) #### Original name Polyporus hoehnelii Bres., 1912 ### Remarks null
{ "content_hash": "29b384e72eb428547d3271694efb3be1", "timestamp": "", "source": "github", "line_count": 13, "max_line_length": 50, "avg_line_length": 15.846153846153847, "alnum_prop": 0.7378640776699029, "repo_name": "mdoering/backbone", "id": "20b89b4b2faf616b99aa9f4f136849daeb8d9a40", "size": "272", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "life/Fungi/Basidiomycota/Agaricomycetes/Polyporales/Phanerochaetaceae/Antrodiella/Antrodiella hoehnelii/ Syn. Tyromyces hoehnelii/README.md", "mode": "33188", "license": "apache-2.0", "language": [], "symlink_target": "" }
package org.jetbrains.idea.svn.dialogs; import com.intellij.openapi.actionSystem.ActionManager; import com.intellij.openapi.actionSystem.ActionPopupMenu; import com.intellij.openapi.actionSystem.DefaultActionGroup; import com.intellij.openapi.project.Project; import com.intellij.openapi.util.text.StringUtil; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.util.containers.hash.HashSet; import com.intellij.util.ui.JBUI; import org.jetbrains.annotations.NotNull; import org.tmatesoft.svn.core.internal.util.SVNPathUtil; import javax.swing.*; import javax.swing.event.TreeSelectionEvent; import javax.swing.event.TreeSelectionListener; import java.awt.*; import java.awt.event.*; import java.util.Set; /** * Created with IntelliJ IDEA. * User: Irina.Chernushina * Date: 7/6/12 * Time: 7:53 PM */ public class SelectCreateExternalTargetDialog extends RepositoryBrowserDialog { private String mySelectedURL; private boolean myCheckout; private JTextField myFolderName; private boolean myFollowRemoteTarget; // light check for same file existence - check before private final Set<String> myUsedNames; public SelectCreateExternalTargetDialog(Project project, final VirtualFile below) { super(project, true, "Point to repository location"); final VirtualFile[] children = below.getChildren(); myUsedNames = new HashSet<String>(); int maxCnt = 1000; // maybe not take it too seriously ? for (VirtualFile child : children) { myUsedNames.add(child.getName()); -- maxCnt; if (maxCnt <= 0) break; } } @Override protected void init() { super.init(); myFollowRemoteTarget = true; setTitle("Select Target For External"); setOKButtonText("Select"); getRepositoryBrowser().addChangeListener(new TreeSelectionListener() { public void valueChanged(TreeSelectionEvent e) { if (getOKAction() != null) { final String selectedURL = getRepositoryBrowser().getSelectedURL(); if (myFollowRemoteTarget && selectedURL != null) { myFolderName.setText(SVNPathUtil.tail(selectedURL)); } checkEnabled(); } } }); getOKAction().setEnabled(getRepositoryBrowser().getSelectedURL() != null); } private void checkEnabled() { final String selectedURL = getRepositoryBrowser().getSelectedURL(); final String text = myFolderName.getText(); final boolean contains = myUsedNames.contains(text); final boolean enabled = selectedURL != null && !StringUtil.isEmptyOrSpaces(text) && !contains; if (contains) { setErrorText("Target File Already Exists"); } else { setErrorText(null); } getOKAction().setEnabled(enabled); } @NotNull protected Action[] createActions() { return new Action[] {getOKAction(), getCancelAction()}; } @Override protected void doOKAction() { mySelectedURL = getRepositoryBrowser().getSelectedURL(); super.doOKAction(); } public String getSelectedURL() { return mySelectedURL; } protected JPopupMenu createPopup(boolean toolWindow) { DefaultActionGroup group = new DefaultActionGroup(); DefaultActionGroup newGroup = new DefaultActionGroup("_New", true); final RepositoryBrowserComponent browser = getRepositoryBrowser(); newGroup.add(new AddLocationAction(browser)); newGroup.add(new MkDirAction(browser)); group.add(newGroup); group.addSeparator(); group.add(new RefreshAction(browser)); group.add(new DiscardLocationAction(browser)); ActionPopupMenu menu = ActionManager.getInstance().createActionPopupMenu("", group); return menu.getComponent(); } @Override public JComponent createCenterPanel() { final JComponent repositoryPanel = super.createCenterPanel(); final JPanel wrapper = new JPanel(new GridBagLayout()); final GridBagConstraints gb = new GridBagConstraints(0, 0, 1, 1, 0, 0, GridBagConstraints.NORTHWEST, GridBagConstraints.BOTH, JBUI.insets(1), 0, 0); gb.weightx = 1; gb.weighty = 1; gb.gridwidth = 2; wrapper.add(repositoryPanel, gb); ++ gb.gridy; gb.fill = GridBagConstraints.NONE; gb.weightx = 0; gb.weighty = 0; gb.gridwidth = 1; myFolderName = new JTextField(); gb.insets.top = 5; gb.anchor = GridBagConstraints.WEST; wrapper.add(new JLabel("Local Target:"), gb); ++ gb.gridx; gb.weightx = 1; gb.fill = GridBagConstraints.HORIZONTAL; wrapper.add(myFolderName, gb); gb.insets.top = 1; gb.weightx = 0; gb.fill = GridBagConstraints.NONE; gb.gridx = 0; ++ gb.gridy; myFolderName.addFocusListener(new FocusAdapter() { @Override public void focusGained(FocusEvent e) { myFollowRemoteTarget = false; myFolderName.removeFocusListener(this); } }); myFolderName.addKeyListener(new KeyAdapter() { @Override public void keyTyped(KeyEvent e) { } @Override public void keyReleased(KeyEvent e) { checkEnabled(); } }); myFolderName.addInputMethodListener(new InputMethodListener() { @Override public void inputMethodTextChanged(InputMethodEvent event) { checkEnabled(); } @Override public void caretPositionChanged(InputMethodEvent event) { } }); final JCheckBox checkout = new JCheckBox("Checkout"); checkout.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { myCheckout = checkout.isSelected(); } }); wrapper.add(checkout, gb); return wrapper; } public boolean isCheckout() { return myCheckout; } public String getLocalTarget() { return myFolderName.getText(); } }
{ "content_hash": "5260c4b26fa57b648645500aed6442b1", "timestamp": "", "source": "github", "line_count": 184, "max_line_length": 129, "avg_line_length": 31.559782608695652, "alnum_prop": 0.689512657137937, "repo_name": "salguarnieri/intellij-community", "id": "2be89412dc427dd6b4076a5354f26e13b4849bf8", "size": "6407", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "plugins/svn4idea/src/org/jetbrains/idea/svn/dialogs/SelectCreateExternalTargetDialog.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "AMPL", "bytes": "20665" }, { "name": "AspectJ", "bytes": "182" }, { "name": "Batchfile", "bytes": "63554" }, { "name": "C", "bytes": "214994" }, { "name": "C#", "bytes": "1538" }, { "name": "C++", "bytes": "190765" }, { "name": "CSS", "bytes": "164277" }, { "name": "CoffeeScript", "bytes": "1759" }, { "name": "Cucumber", "bytes": "14382" }, { "name": "Erlang", "bytes": "10" }, { "name": "FLUX", "bytes": "57" }, { "name": "Groff", "bytes": "35232" }, { "name": "Groovy", "bytes": "2364806" }, { "name": "HTML", "bytes": "1755457" }, { "name": "J", "bytes": "5050" }, { "name": "Java", "bytes": "153383814" }, { "name": "JavaScript", "bytes": "141020" }, { "name": "Kotlin", "bytes": "1297292" }, { "name": "Lex", "bytes": "166321" }, { "name": "Makefile", "bytes": "2352" }, { "name": "NSIS", "bytes": "88100" }, { "name": "Objective-C", "bytes": "28878" }, { "name": "Perl6", "bytes": "26" }, { "name": "Protocol Buffer", "bytes": "6570" }, { "name": "Python", "bytes": "23157608" }, { "name": "Ruby", "bytes": "1213" }, { "name": "Scala", "bytes": "11698" }, { "name": "Shell", "bytes": "64014" }, { "name": "Smalltalk", "bytes": "64" }, { "name": "TeX", "bytes": "62325" }, { "name": "TypeScript", "bytes": "6152" }, { "name": "XSLT", "bytes": "113040" } ], "symlink_target": "" }
<!doctype html> <!--[if lt IE 7]> <html class="no-js lt-ie9 lt-ie8 lt-ie7" ng-app="docsApp" lang="en" ng-controller="DocsController"> <![endif]--> <!--[if IE 7]> <html class="no-js lt-ie9 lt-ie8" ng-app="docsApp" lang="en" ng-controller="DocsController"> <![endif]--> <!--[if IE 8]> <html class="no-js lt-ie9" ng-app="docsApp" lang="en" ng-controller="DocsController"> <![endif]--> <!--[if gt IE 8]><!--> <html class="no-js" ng-app="docsApp" lang="en" ng-controller="DocsController"><![endif] <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1"> <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"> <meta name="Description" content="Widgets used to build dashboards based on Opendatasoft platform datasets."> <meta name="fragment" content="!"> <title ng-bind-template="ODS-Widgets: {{partialTitle}}">Opendatasoft's Widgets Documentation</title> <link rel="shortcut icon" type="image/x-icon" href="./assets/ods-favicon.ico"/> <script type="text/javascript"> // dynamically add base tag as well as css and javascript files. // we can't add css/js the usual way, because some browsers (FF) eagerly prefetch resources // before the base attribute is added, causing 404 and terribly slow loading of the docs app. (function () { var indexFile = (location.pathname.match(/\/(index[^\.]*\.html)/) || ['', ''])[1], origin, baseUrl, rUrl = /(\/?#!\/.*|\/(introduction|getting-started|api)\/?(\?.*)*|\/index[^\.]*\.html.*)$/, headEl = document.getElementsByTagName('head')[0], sync = true; if (location.href.slice(0, 7) == 'file://') { baseUrl = location.href.replace(rUrl, '/' + indexFile); } else { origin = location.origin || (window.location.protocol + "//" + window.location.hostname + (window.location.port ? ':' + window.location.port : '')); baseUrl = origin + location.href.substr(origin.length).replace(rUrl, '/' + indexFile); } addTag('base', { href: baseUrl }); addTag('link', { rel: 'stylesheet', href: 'css/bootstrap.min.css', type: 'text/css' }); addTag('link', { rel: 'stylesheet', href: 'css/font-awesome.css', type: 'text/css' }); addTag('link', { rel: 'stylesheet', href: 'css/prettify.css', type: 'text/css' }); addTag('link', { rel: 'stylesheet', href: 'css/docs.css', type: 'text/css' }); addTag('link', { rel: 'stylesheet', href: 'css/animations.css', type: 'text/css' }); addTag('link', { rel: 'stylesheet', href: 'css/ods-widgets.min.css', type: 'text/css' }, sync); addTag('link', { rel: 'stylesheet', href: 'css/ods-theme.min.css', type: 'text/css' }, sync); addTag('link', { rel: 'stylesheet', href: 'https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css', type: 'text/css' }, sync); addTag('script', { src: 'js/google-code-prettify.js' }, sync); addTag('script', { src: 'js/marked.js' }, sync); addTag('script', { src: 'https://code.jquery.com/jquery-2.2.4.min.js' }, sync); addTag('script', { src: 'https://ajax.googleapis.com/ajax/libs/angularjs/1.8.0/angular.js' }, sync); addTag('script', { src: 'https://ajax.googleapis.com/ajax/libs/angularjs/1.8.0/angular-animate.js' }, sync); addTag('script', { src: 'https://ajax.googleapis.com/ajax/libs/angularjs/1.8.0/angular-sanitize.js' }, sync); addTag('script', { src: 'grunt-scripts/ods-widgets.js' }, sync); addTag('script', { src: 'grunt-scripts/docs-load-css.js' }, sync); addTag('script', { src: 'js/angular-bootstrap.js' }, sync); addTag('script', { src: 'js/angular-bootstrap-prettify.js' }, sync); addTag('script', { src: 'js/docs-setup.js' }, sync); addTag('script', { src: 'js/docs.js' }, sync); function addTag(name, attributes, sync) { var el = document.createElement(name), attrName; for (attrName in attributes) { el.setAttribute(attrName, attributes[attrName]); } sync ? document.write(outerHTML(el)) : headEl.appendChild(el); } function outerHTML(node) { // if IE, Chrome take the internal method otherwise build one return node.outerHTML || ( function (n) { var div = document.createElement('div'), h; div.appendChild(n); h = div.innerHTML; div = null; return h; })(node); } })(); </script> </head> <body> <div class="ods-header"> <button type="button" class="menu-button ods-header__menu-toggle" id="sidebar-button" aria-label="Main menu"> <img class="ods-header__menu-toggle__openlogo" id="sidebar-button" src="/assets/menu-fill.svg" alt="Open documentation menu"> </button> <a class="ods-header-logo ods-header-logo-link" href="https://help.opendatasoft.com/"> <img src="grunt-styles/assets/ods-logo-noir.svg" alt="Opendatasoft logo"> <span class="ods-header__brandname"> Help Center </span> </a> <div class="ods-header__nav" id="helphub-nav"> <div class="ods-header__nav-item"> <a class="ods-header__nav-item-link" href="/platform/en/"> User guide </a> </div> <div class="ods-header__nav-item"> <a class="ods-header__nav-item-link" href="https://codelibrary.opendatasoft.com/"> Code library </a> </div> <div class="ods-header__nav-item"> <a class="ods-header__nav-item-link is-active" href="#/introduction/"> Widgets </a> </div> <div class="ods-header__nav-item"> <a class="ods-header__nav-item-link" href="/en/apis/"> APIs </a> </div> <div class="ods-header__nav-item"> <a class="ods-header__nav-item-link" href="https://academy.opendatasoft.com/page/homepage"> Academy </a> </div> <div class="ods-header__nav-item"> <a class="ods-header__nav-item-link" href="https://changes.opendatasoft.com/en"> Release notes </a> </div> </div> <button type="button" class="menu-button ods-header__menu-toggle" id="helphub-button"> <img class="ods-header__menu-toggle__openlogo" id="helphub-button" src="assets/apps-custo.svg" alt="Open help center menu"> </button> </div> <div role="main" class="ods-container"> <div class="row"> <div class="ods-sidebar" id="sidebar-nav"> <form class="form-search" ng-submit="submitForm()"> <input type="text" ng-model="search" placeholder="Search in documentation" tabindex="1" accesskey="s" class="search-query"> <ul class="content-nav-items"> <li class="nav-items"> <a class="nav-items-link" id="nav-introduction" href="#/introduction/">Introduction</a> </li> <li class="nav-items"> <a class="nav-items-link" id="nav-getting-started" href="#/getting-started/">Getting started</a> </li> </ul> <ul class="nav nav-list well" ng-show="pages.length"> <li ng-repeat="page in pages track by page.url" ng-class="navClass(page)" class="api-list-item expand"> <a href="{{page.url}}" tabindex="2">{{page.shortName}}</a> </li> </ul> <ul class="nav nav-list well" ng-repeat="module in modules track by module.url" class="api-list-item"> <!--<li class="nav-header module"> <a class="guide">module</a> <a class="code" href="{{module.url}}" title="{{module.name}}">{{module.name}}</a> </li> <li ng-repeat="page in module.others track by page.url" ng-class="navClass(page)" class="api-list-item expand"> <a href="{{page.url}}" tabindex="2">{{page.shortName}}</a> </li> <li class="nav-header section" ng-show="module.components.length"> <a class="guide">component</a> </li> <li ng-repeat="page in module.components track by page.url" ng-class="navClass(page)" class="api-list-item expand"> <a href="{{page.url}}" tabindex="2">{{page.shortName}}</a> </li>--> <li class="nav-header section" ng-show="module.directives.length"> <a class="guide">Widgets</a> </li> <li ng-repeat="page in module.directives track by page.url" ng-class="navClass(page)" class="api-list-item expand"> <a href="{{page.url}}" tabindex="2">{{page.shortName}}</a> </li> <li class="nav-header section" ng-show="module.controllers.length"> <a class="guide">controller</a> </li> <li ng-repeat="page in module.controllers track by page.url" ng-class="navClass(page)" class="api-list-item expand"> <a href="{{page.url}}" tabindex="2">{{page.shortName}}</a> </li> <li class="nav-header section" ng-show="module.filters.length"> <a class="guide">Filters</a> </li> <li ng-repeat="page in module.filters track by page.url" ng-class="navClass(page)" class="api-list-item expand"> <a href="{{page.url}}" tabindex="2">{{page.shortName}}</a> </li> <li class="nav-header section" ng-show="module.services.length"> <a class="guide">Services</a> </li> <li ng-repeat="service in module.services track by (service.instance.url || service.provider.url)" ng-class="navClass(service.instance, service.provider)" class="api-list-item expand"> <a ng-show="service.provider" class="pull-right" href="{{service.provider.url}}" tabindex="2"> <i class="icon-cog"></i> </a> <a href="{{service.instance ? service.instance.url : service.provider.url}}" tabindex="2">{{service.name}}</a> </li> <li class="nav-header section" ng-show="module.types.length"> <a class="guide">Types</a> </li> <li ng-repeat="page in module.types track by page.url" ng-class="navClass(page)" class="api-list-item expand"> <a href="{{page.url}}" tabindex="2">{{page.shortName}}</a> </li> <li class="nav-header section" ng-show="module.globals.length"> <a class="global guide">global APIs</a> &nbsp; </li> <li ng-repeat="page in module.globals track by page.url" ng-class="navClass(page)" class="api-list-item expand"> <a href="{{page.url}}" tabindex="2">{{page.id}}</a> </li> </ul> </form> </div> <div class="ods-content" id="content-principal"> <div id="loading" ng-show="loading">Loading...</div> <div ng-hide="loading" ng-include src="currentPage.partialUrl" onload="afterPartialLoaded()" autoscroll class="content slide-reveal"></div> </div> </div> </div> <script type="text/javascript" src="./js/script.min.js"></script> </body> </html>
{ "content_hash": "cb08c23961915957edf40ef247643f71", "timestamp": "", "source": "github", "line_count": 268, "max_line_length": 183, "avg_line_length": 53.15298507462686, "alnum_prop": 0.4537030537030537, "repo_name": "opendatasoft/ods-widgets", "id": "f9ab6b46de5d8b15b87a189d6e7f3ac2310b0923", "size": "14245", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "docs/index.html", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "14617" }, { "name": "JavaScript", "bytes": "1840678" }, { "name": "Less", "bytes": "110718" }, { "name": "Shell", "bytes": "172" } ], "symlink_target": "" }
<?php /** * Default Spanish lexicon topic * * @language es_MX * @package MODX * @subpackage lexicon */ $_lang['access'] = 'Acceso'; $_lang['access_denied'] = 'Acceso denegado.'; $_lang['action'] = 'Acción'; $_lang['action_err_nfs'] = 'No se encontró acción con ID:[[+id]].'; $_lang['actions'] = 'Acciones'; $_lang['active_users_none'] = 'No se encontraron usuarios activos.'; $_lang['activity_message'] = 'Esta lista muestra los últimos recursos que creaste o editaste:'; $_lang['activity_title'] = 'Documentos recientmente editados/creados'; $_lang['add'] = 'Añadir'; $_lang['add_chunk'] = 'Añadir Chunk'; $_lang['add_folder'] = 'Folder Nuevo'; $_lang['add_plugin'] = 'Añadir Plugin'; $_lang['add_snippet'] = 'Añadir Snippet'; $_lang['add_tag'] = 'Añadir Etiqueta'; $_lang['add_template'] = 'Añadir Plantilla'; $_lang['add_to_category_this'] = 'Crear un Nuevo [[+type]] Aquí'; $_lang['add_tv'] = 'Añadir VdP'; $_lang['add_weblink'] = 'Weblink Nuevo'; $_lang['add_symlink'] = 'Symlink Nuevo'; $_lang['alias'] = 'Alias'; $_lang['and'] = 'y'; $_lang['anonymous'] = 'anónimo'; $_lang['assets'] = 'Assets'; $_lang['at'] = 'En'; $_lang['attachment'] = 'Adjunto'; $_lang['attributes'] = 'Atributos'; $_lang['back'] = '&lt;- Regresar'; $_lang['backup'] = 'Respaldar'; $_lang['bk_manager'] = 'Respaldo'; $_lang['bulk_actions'] = 'Acciones en Masa'; $_lang['cache_files_deleted'] = 'Los siguientes archivos fueron borrados:'; $_lang['cache_publish_event_error'] = '<p>ERROR: No se pudo determinar el evento de publicación siguiente!</p><pre>[[+info]]</pre>'; $_lang['cache_sitepublishing_file_error'] = '<p>ERROR: No se pudo escribir el archivo de publicación de sitio al cache.</p>'; $_lang['cache_unpublish_event_error'] = '<p>ERROR: No se pudo determnar el evento de despublicación siguiente!</p><pre>[[+info]]</pre>'; $_lang['cached'] = 'Al Cache'; $_lang['cancel'] = 'Cancelado'; $_lang['categories'] = 'Categorías'; $_lang['category'] = 'Categoría'; $_lang['category_create'] = 'Crear Categoría Nueva'; $_lang['category_confirm_delete'] = 'Estás seguro de que quieres remover esta categoría? Todos los Elementos dentro de ella se revertirán a no tener una categoría.'; $_lang['category_rename'] = 'Renombrar Categoría'; $_lang['category_remove'] = 'Remover Categoría'; $_lang['chunk'] = 'Chunk'; $_lang['chunks'] = 'Chunks'; $_lang['class_key'] = 'Clave de Clase'; $_lang['cleaningup'] = 'Limpiando'; $_lang['clear_cache'] = 'Limpiar Cache'; $_lang['clear_cache_on_save'] = 'Limpiar Cache al Guradar'; $_lang['clear_cache_on_save_msg'] = 'Si esto es seleccionado, limpiará los archivos de este elemento en el cache cuando el elemento sea guardado.'; $_lang['clear_filter'] = 'Limpiar Filter'; $_lang['click_to_change'] = 'Haz Click para Cambiar'; $_lang['close'] = 'Cerrar'; $_lang['code'] = 'Código'; $_lang['collapse_all'] = 'Colapsar Todos'; $_lang['collapse_tree'] = 'Colapsar Árbol'; $_lang['combo'] = 'ComboBox'; $_lang['comment'] = 'Comentario'; $_lang['configuration'] = 'Configuración'; $_lang['confirm'] = 'Confirmar'; $_lang['confirm_delete_message'] = 'Estás seguro de que quieres borrar este mensaje?'; $_lang['confirm_remove'] = 'Estás seguro de que quieres remover este elemento?'; $_lang['confirm_remove_locks'] = 'Los usuarios a veces cierran sus navegadores mientras están editando documentos, plantillas, snippets o parsers, posiblemente dejando el elemento que estaban editando en un estado cerrado. Al presionar OK puedes remover todos los candados que estén puestos.<br /><br />Proceder?'; $_lang['confirm_undelete'] = 'Cualquier documento hijo borrado al mismo tiempo que este documento también será recuperado, pero documentos hijos borrados con anterioridad seguirán estando borrados.'; $_lang['confirm_unpublish'] = 'Al despublicar este documento ahora removerá cualquier fecha de (des)publicación que haya sido establecida. Si deseas establecer o mantener las fechas de publicación o despublicación, por favor escoge editar el documento.\n\nProceder?'; $_lang['console'] = 'Consola'; $_lang['console_download_output'] = 'Descarga la Salida a un Archivo'; $_lang['console_running'] = 'Consola activa...'; $_lang['content'] = 'Contenido'; $_lang['content_elements'] = 'Elementos del Contenido'; $_lang['context_duplicate'] = 'Contexto Duplicado'; $_lang['context_refresh'] = 'Refrescar Contenido'; $_lang['context_remove'] = 'Remover Contenido'; $_lang['context_remove_confirm'] = 'Estás seguro de que quieres remover este Contexto? También removerá permanentemente cualquier Recurso dentro del Contexto. Esto es irreversible.'; $_lang['copy_to_clipboard'] = 'Copiar al Clipboard'; $_lang['core_rte'] = 'Editor de MODX'; $_lang['correct_errors'] = 'Favor de corregir los errores en la forma antes de presentarla.'; $_lang['create'] = 'Crear'; $_lang['create_document_here'] = 'Crear documento aquí'; $_lang['create_folder_here'] = 'Crear carpeta aquí'; $_lang['create_new'] = 'Crear Nuevo'; $_lang['create_user_group'] = 'Crear Grupo de Usuarios'; $_lang['created'] = 'Creado'; $_lang['createdon'] = 'Fecha de Creación'; $_lang['current'] = 'Actual'; $_lang['data_err_load'] = 'Error cargando datos.'; $_lang['date'] = 'Fecha'; $_lang['datechanged'] = 'Fecha cambiada'; $_lang['db_header'] = 'Tabls de Base de Datos'; $_lang['db_info'] = 'Si una tabla tiene una tara, puedes optimizarla al hacer click en el enlace en la columna de Tara.'; $_lang['db_info_sqlsrv'] = 'Puedes reconstruir el índice de una tabla haciendo clic en el enlace en la columna No Usada.'; $_lang['delete'] = 'Borrar'; $_lang['deleted'] = 'Borrado'; $_lang['description'] = 'Descripción'; $_lang['directory_refresh'] = 'Refrescar Directorio'; $_lang['disabled'] = 'Deshabilitado'; $_lang['document'] = 'Recurso'; $_lang['documents'] = 'Recursos'; $_lang['done'] = 'Hecho'; $_lang['downloading'] = 'Descargando...'; $_lang['duplicate'] = 'Duplicar'; $_lang['duplicate_children'] = 'Hijos Duplicados'; $_lang['duplicate_of'] = 'Duplicado de [[+name]]'; $_lang['duplication_options'] = 'Opciones de Duplicación'; $_lang['edit'] = 'Editar'; $_lang['edit_context'] = 'Editar contexto'; $_lang['editedon'] = 'Editar Fecha'; $_lang['editing_form'] = 'Editando Forma'; $_lang['element_duplicate'] = 'Duplicar Elemento'; $_lang['element_duplicate_values'] = 'Duplicar Valores?'; $_lang['element_name_new'] = 'Nombre del Elemento Nuevo'; $_lang['elements'] = 'Elementos'; $_lang['email'] = 'Email'; $_lang['empty_recycle_bin'] = 'Remover Recursos Borrados'; $_lang['empty_recycle_bin_confirm'] = 'Estás seguro de que quieres remover completa y permanentemente todos los Recursos borrados? Esto es irreversible.'; $_lang['empty_recycle_bin_empty'] = 'No existen Recursos borrados que remover.'; $_lang['empty_recycle_bin_emptied'] = 'Todos los Recursos borrados han sido permanentemente removidos.'; $_lang['enabled'] = 'Habilitado'; $_lang['err_self_parent'] = 'No puedes hacer algo ser su propio padre!'; $_lang['error'] = 'Error'; $_lang['error_sending_email'] = 'Error enviando email'; $_lang['error_sending_email_to'] = 'Error mientra se mandaba email a '; $_lang['event_id'] = 'ID del Evento'; $_lang['existing_category'] = 'Categoría Existente'; $_lang['expand_all'] = 'Expander Todos'; $_lang['expand_tree'] = 'Expander árbol'; $_lang['ext_afterpage'] = 'de {0}'; $_lang['ext_beforepage'] = 'Página'; $_lang['ext_checkboxinv'] = 'Debes de seleccionar por lo menos un elemento en este grupo'; $_lang['ext_choosemonth'] = 'Elige un mes (Control+Arriba/Abajo para mover los años)'; $_lang['ext_column_lock'] = 'Cerrar Columna'; $_lang['ext_column_unlock'] = 'Abrir Columna'; $_lang['ext_columns'] = 'Columnas'; $_lang['ext_dateinv'] = '{0} no es una fecha válida - debe de ser en el formato {1}'; $_lang['ext_datemax'] = 'La fecha en este campo debe de ser antes de {0}'; $_lang['ext_datemin'] = 'La fecha en este campo debe de ser despues de {0}'; $_lang['ext_displaying'] = 'Mostrando {0} - {1} de {2}'; $_lang['ext_emptygroup'] = '(Ninguno)'; $_lang['ext_emptymsg'] = 'No. de datos a mostrar'; $_lang['ext_first'] = 'Primera Página'; $_lang['ext_groupby'] = 'Agrupar for Este Campo'; $_lang['ext_inv_alpha'] = 'Este campo solo debe de contener letras y _'; $_lang['ext_inv_alphanum'] = 'Este campo solo debe de contener letras, números y _'; $_lang['ext_inv_email'] = 'Este campo debe de ser una dirección electrónica con el formato "usuario@dominio.com"'; $_lang['ext_inv_url'] = 'Este campo debe de ser un URL con el formato "http://www.dominio.com"'; $_lang['ext_invalidfield'] = 'El valor en este campo no es válido.'; $_lang['ext_last'] = 'Última Página'; $_lang['ext_mindate'] = 'Esta fecha es antes que la fecha mínima.'; $_lang['ext_minlenfield'] = 'La longitud mínima para este campo es {minLength}'; $_lang['ext_minvalfield'] = 'El valor mínimo para este campo es {0}'; $_lang['ext_maxdate'] = 'Esta fecha es antes que la fecha máxima.'; $_lang['ext_maxlenfield'] = 'La longitud máxima para este campo es {maxLength}'; $_lang['ext_maxvalfield'] = 'El valor máximo para este campo es {0}'; $_lang['ext_nanfield'] = '{0} no es un número válido.'; $_lang['ext_next'] = 'Página Siguiente'; $_lang['ext_nextmonth'] = 'Mes Posterior (Control+Derecha)'; $_lang['ext_prev'] = 'Previous Page'; $_lang['ext_prevmonth'] = 'Mes Anterior (Control+Izquierda)'; $_lang['ext_refresh'] = 'Refrescar'; $_lang['ext_showgroups'] = 'Mostrar en Grupos'; $_lang['ext_sortasc'] = 'Ordenar Ascendentemente'; $_lang['ext_sortdesc'] = 'Ordenar Descendentemente'; $_lang['ext_tabclose'] = 'Cerrar esta pestaña'; $_lang['ext_timeinv'] = '{0} no es un tiempo válido'; $_lang['ext_timemax'] = 'El tiempo en este campo debe de ser igual a o antes que {0}'; $_lang['ext_timemin'] = 'El tiempo en este campo debe de ser igual a o despues que {0}'; $_lang['ext_today_tip'] = '{0} (Barra de Espacio)'; $_lang['failure'] = 'Falla'; $_lang['female'] = 'Mujer'; $_lang['files'] = 'Archivos'; $_lang['filter'] = 'Filtro'; $_lang['filter_clear'] = 'Limpiar Filtro'; $_lang['filter_by_key'] = 'Filtrar por Clave...'; $_lang['filter_by_name'] = 'Filtrar por nombre...'; $_lang['filter_by_username'] = 'Filtrar por nombre de usuario...'; $_lang['finish'] = 'Terminar'; $_lang['folder'] = 'Carpeta'; $_lang['general'] = 'General'; $_lang['general_information'] = 'Información General'; $_lang['general_settings'] = 'Configuración General'; $_lang['go'] = 'Ir'; $_lang['group'] = 'Grupo'; $_lang['guid'] = 'GUID'; $_lang['handler'] = 'Manejador'; $_lang['help'] = 'Ayuda'; $_lang['help_ex'] = 'Ayuda!'; $_lang['help_not_yet'] = 'La ayuda para este componente no ha sido implmentada todavía.'; $_lang['hide_tree'] = 'Ocultar árbol'; $_lang['home'] = 'Inicio'; $_lang['icon'] = 'Icono'; $_lang['id'] = 'ID'; $_lang['info'] = 'Info'; $_lang['information'] = 'Información'; $_lang['inline'] = 'En línea'; $_lang['insert'] = 'Insertar'; $_lang['install'] = 'Instalar'; $_lang['installed'] = 'Instalado'; $_lang['integer'] = 'Entero'; $_lang['introtext'] = 'Introtext'; $_lang['key'] = 'Clave'; $_lang['keyword'] = 'Palabra clave'; $_lang['keywords'] = 'Palabras clave'; $_lang['last_modified'] = 'Última Modificación'; $_lang['launch_site'] = 'Ver Sitio'; $_lang['language'] = 'Idioma'; $_lang['lexicon'] = 'Léxico'; $_lang['list'] = 'Lista'; $_lang['load_headers'] = 'Cargar Headers'; $_lang['loading'] = 'Cargando...'; $_lang['locked'] = 'Cerrado'; $_lang['locked_by'] = 'cerrado por [[+username]]'; $_lang['lock_msg'] = '[[+name]] está actualmente editando este [[+object]]. Por favor espera hasta que el otro usuario haya terminado e inténtalo otra vez.'; $_lang['logged_in_as'] = 'en sesión como [[+username]]'; $_lang['login'] = 'Entrar'; $_lang['logout'] = 'Salir'; $_lang['logout_confirm'] = 'Estás seguro de que quieres salir?'; $_lang['long_title'] = 'Título largo'; $_lang['male'] = 'Hombre'; $_lang['manage_files'] = 'Admin Archivos'; $_lang['manager'] = 'Administrador'; $_lang['manager_log_err_save'] = 'Ocurrió un error mientras se anotaba la acción del administrador.'; $_lang['menu_order'] = 'Orden del Menu'; $_lang['mime_type'] = 'Tipo MIME'; $_lang['mime_type_desc'] = 'El tipo MIME para todos los archivos con el tipo de contenido.'; $_lang['mode'] = 'Modo'; $_lang['MODX_browser'] = 'Navegador de MODX'; $_lang['MODX_resource_browser'] = 'Navegador de Recursos de MODX'; $_lang['move'] = 'Mover'; $_lang['name'] = 'Nombre'; $_lang['new'] = 'Nuevo'; $_lang['new_category'] = 'Categoría Nueva'; $_lang['new_chunk'] = 'Chunk Nuevo'; $_lang['new_folder'] = 'Carpeta Nueva'; $_lang['new_key'] = 'Clave Nueva'; $_lang['new_message'] = 'Mensaje Nuevo'; $_lang['new_name'] = 'Nombre Nuevo'; $_lang['new_parent'] = 'Padre Nuevo'; $_lang['new_plugin'] = 'Plugin Nuevo'; $_lang['new_role'] = 'Crear un rol nuevo'; $_lang['new_snippet'] = 'Snippet Nuevo'; $_lang['new_template'] = 'Plantilla Nueva'; $_lang['new_tv'] = 'Variable de Plantilla Nueva'; $_lang['new_user'] = 'Usuario Nuevo'; $_lang['next'] = 'Siguiente -&gt;'; $_lang['no'] = 'No'; $_lang['none'] = 'Ningún'; $_lang['notset'] = 'No configurado'; $_lang['not_deleted'] = 'no ha sido borrado.'; $_lang['not_logged_in'] = 'No ingresado!'; $_lang['not_set'] = 'No configurado'; $_lang['no_activity_message'] = 'No has creado o editado ningún documento todavía.'; $_lang['no_action'] = 'No Acción'; $_lang['no_category'] = 'sin categoría'; $_lang['no_records_found'] = 'No se encontraron registros.'; $_lang['no_results'] = 'No se encontraron resultados'; $_lang['offline'] = 'Desconectado'; $_lang['ok'] = 'OK'; $_lang['old_key'] = 'Clave Antigua'; $_lang['old_name'] = 'Nombre Antiguo'; $_lang['on'] = 'On'; $_lang['online'] = 'En línea'; $_lang['open'] = 'Abierto'; $_lang['options'] = 'Opciones'; $_lang['orm_attribute_add'] = 'Añadir Atributo'; $_lang['orm_attribute_add_below'] = 'Añair Atributo Aquí Abajo'; $_lang['orm_attribute_ae'] = 'Un atributo ya existe con esta clave a este nivel!'; $_lang['orm_attribute_remove'] = 'Remover Atributo'; $_lang['orm_attribute_remove_confirm'] = 'Estás seguro de que quieres remover este atributo? Esto es irreversible.'; $_lang['orm_container_add'] = 'Añadir Contenedor'; $_lang['orm_container_add_below'] = 'Añadir Contenedor Aquí Abajo'; $_lang['orm_container_rename'] = 'Renombrar Contenedor'; $_lang['orm_container_remove'] = 'Remover Contenedor'; $_lang['orm_container_remove_confirm'] = 'Estás seguro de que quieres remover este contenedor y todos los atributos debajo de él? Esto es irreversible.'; $_lang['pagetitle'] = 'Título del Recurso'; $_lang['page_title'] = 'Título del Recurso'; $_lang['parameter'] = 'Parámetro'; $_lang['parameters'] = 'Parámetros'; $_lang['password'] = 'Contraseña'; $_lang['path'] = 'Ruta'; $_lang['per_page'] = 'Por Página'; $_lang['permissions'] = 'Permisos'; $_lang['permission_denied'] = 'Permiso dengado!'; $_lang['permission_denied_msg'] = 'No tienes los permisos de la póliza de acceso apropiados para ver esta página. Si crees que esto es un error, por favor contacta a tu administrador de sistema.'; $_lang['please_wait'] = 'Por favor espera...'; $_lang['plugin'] = 'Plugin'; $_lang['plugins'] = 'Plugins'; $_lang['preview'] = 'Vista Previa'; $_lang['private'] = 'Privado'; $_lang['processor_err_nf'] = 'Procesador no encontrado: [[+target]]'; $_lang['progress'] = 'Progreso'; $_lang['properties'] = 'Propiedades'; $_lang['property_set'] = 'Conjunto de Propiedades'; $_lang['public'] = 'Público'; $_lang['publish'] = 'Publicar'; $_lang['publish_date'] = 'Fecha de Publicación'; $_lang['publish_document'] = 'Publicar documento'; $_lang['publish_events'] = 'Publicar Eventos'; $_lang['published'] = 'Publicado'; $_lang['publishedon'] = 'Publicado En'; $_lang['quick_create'] = 'Crear Rápido'; $_lang['quick_create_chunk'] = 'Crear Chunk Rápido'; $_lang['quick_create_plugin'] = 'Crear Plugin Rápido'; $_lang['quick_create_resource'] = 'Crear Recurso Rápido'; $_lang['quick_create_snippet'] = 'Crear Snippet Rápido'; $_lang['quick_create_template'] = 'Crear Plantilla Rápido'; $_lang['quick_create_tv'] = 'Crear VdP Rápido'; $_lang['quick_update_chunk'] = 'Actualizar Chunk'; $_lang['quick_update_plugin'] = 'Actualizar Plugin Rápido'; $_lang['quick_update_resource'] = 'Actualizar Resource Rápido'; $_lang['quick_update_snippet'] = 'Actualizar Snippet Rápido'; $_lang['quick_update_template'] = 'Actualizar Plantilla Rápido'; $_lang['quick_update_tv'] = 'Actualizar VdP Rápido'; $_lang['recent_docs'] = 'Documentos Recientes'; $_lang['redirecting'] = 'Redireccionando...'; $_lang['refresh_action_map'] = 'Limpiando el cache del mapa de Acciones'; $_lang['refresh_auto_publish'] = 'Procesando fechas de publicación automáticas'; $_lang['refresh_context_settings'] = 'Regenerando el cache de contextos'; $_lang['refresh_db'] = 'Limpiando el cache del conjunto de resultados de la base de datos'; $_lang['refresh_default'] = 'Limpiando el cache prefijado'; $_lang['refresh_failure'] = 'Falló refrescar! (NOTA: puede que esta partición de cache simplemente esté vacía)'; $_lang['refresh_lexicon_topics'] = 'Limpiando el cache de los temas del léxico'; $_lang['refresh_menu'] = 'Limpiando el cache del menú'; $_lang['refresh_published'] = '<strong>[[+num]]</strong> documentos fueron publicados.'; $_lang['refresh_resource'] = 'Limpiando el cache de Recursos'; $_lang['refresh_scripts'] = 'Limpiando el cache de Snippets/Plugins'; $_lang['refresh_success'] = 'Refrescar exitoso!'; $_lang['refresh_system_settings'] = 'Regenerando el cache de la configuración del sistema'; $_lang['refresh_title'] = 'Refrescar sitio'; $_lang['refresh_tree'] = 'Refrescar árbol'; $_lang['refresh_unpublished'] = '<strong>[[+num]]</strong> documentos fueron despublicados.'; $_lang['refreshing_tree'] = 'Refrescando árbol...'; $_lang['release'] = 'Liberar'; $_lang['reload'] = 'Recargar'; $_lang['remember_username'] = 'Recuérdame'; $_lang['remove'] = 'Remover'; $_lang['remove_category'] = 'Remover Categoría'; $_lang['remove_date'] = 'Remover fecha'; $_lang['remove_selected'] = 'Remover Selección'; $_lang['remove_this_confirm'] = 'Estás seguro de que quieres remover el [[+type]]: "[[+name]]"?'; $_lang['remove_user_from_group'] = 'Remover Usuario del Grupo'; $_lang['rename'] = 'Renombrar'; $_lang['reset'] = 'Restaurar'; $_lang['reset_failedlogins'] = 'restaurar'; $_lang['reset_password'] = 'Restaurar Contraseña'; $_lang['resource'] = 'Recurso'; $_lang['resources'] = 'Recursos'; $_lang['resource_categories'] = 'Vista Combinada'; $_lang['resource_group'] = 'Grupo de Recursos'; $_lang['resource_group_id'] = 'ID de GdR'; $_lang['resource_groups'] = 'Grupos de Recursos'; $_lang['resource_management'] = 'Admin recursos'; $_lang['resource_name'] = 'Nombre del recurso'; $_lang['resource_name_new'] = 'Nuevo nombre del recurso'; $_lang['resource_preview'] = 'Vista Previa de Recurso'; $_lang['resource_settings'] = 'Configuración de Recurso'; $_lang['role'] = 'Rol'; $_lang['roles'] = 'Roles'; $_lang['save'] = 'Guardar'; $_lang['save_and_close'] = 'Guardar y Cerrar'; $_lang['save_changes'] = 'Guardar Cambios'; $_lang['save_successful'] = 'Guardado exitoso.'; $_lang['save_tag'] = 'Guardar Etiqueta'; $_lang['saving'] = 'Guardando...'; $_lang['scroll_dn'] = 'Desplazar hacia abajo'; $_lang['scroll_up'] = 'Desplazar hacia arriba'; $_lang['search'] = 'Buscar'; $_lang['search_criteria'] = 'Criterios de Búsqueda'; $_lang['search_ellipsis'] = 'Buscar...'; $_lang['search_results'] = 'Resultados de Búsqueda'; $_lang['security'] = 'Seguridad'; $_lang['select_date'] = 'Selecciona una fecha'; $_lang['select_el_opts'] = 'Selecciona Opciones de Elemento'; $_lang['selected_activate'] = 'Activar Seleccionados'; $_lang['selected_deactivate'] = 'Desactivar Seleccionados'; $_lang['selected_remove'] = 'Remover Seleccionados'; $_lang['send'] = 'Enviar'; $_lang['service_url'] = 'URL del Servicio'; $_lang['set'] = 'Configurar'; $_lang['set_to_default'] = 'Configurar a Prefijado'; $_lang['setting'] = 'Configuración'; $_lang['settings'] = 'Configuraciones'; $_lang['settings_general'] = 'General'; $_lang['settings_page_settings'] = 'Configuraciones de Página'; $_lang['showing'] = 'Mostrando'; $_lang['show_preview'] = 'Mostrar Ventana de Vista Previa'; $_lang['show_tree'] = 'Mostrar árbol'; $_lang['showing_pub'] = 'Mostrando Fechas de Publicación'; $_lang['showing_unpub'] = 'Mostrando Fechas de Despublicación'; $_lang['snippet'] = 'Snippet'; $_lang['snippets'] = 'Snippets'; $_lang['sort_asc'] = 'Ascendiendo'; $_lang['sort_by'] = 'Ordenar Por'; $_lang['sort_desc'] = 'Descendiendo'; $_lang['sort_tree'] = 'Ordenar el árbol'; $_lang['source'] = 'Fuente'; $_lang['specify_name_error'] = 'Por favor escpecifica un nombre.'; $_lang['statistics'] = 'Estadísticas'; $_lang['stay'] = 'Continuar editando'; $_lang['stay_new'] = 'Añadir otro'; $_lang['submit'] = 'Presentar'; $_lang['success'] = 'Éxito!'; $_lang['sysinfo_activity_message'] = 'Esta lista muestra que recursos han sido editados recientemente por tus usuarios.'; $_lang['sysinfo_userid'] = 'Usuario'; $_lang['sys_alert'] = 'Alerta del Sistema'; $_lang['system'] = 'Sistema'; $_lang['tag'] = 'Etiqueta'; $_lang['target'] = 'Blanco'; $_lang['template'] = 'Plantilla'; $_lang['templates'] = 'Plantillas'; $_lang['text'] = 'Texto'; $_lang['textarea'] = 'Área de texto'; $_lang['textfield'] = 'Campo de texto'; $_lang['title'] = 'Título'; $_lang['tmplvar'] = 'Variable de Plantilla'; $_lang['tmplvars'] = 'Variables de Plantilla'; $_lang['to'] = 'a'; $_lang['today'] = 'Hoy'; $_lang['toggle_richtext'] = 'Conmutar Texto Formateado'; $_lang['total'] = 'total'; $_lang['track_visitors_title'] = 'Tracear Visitantes'; $_lang['tree_collapse'] = 'Colapsar árbol'; $_lang['tree_expand'] = 'Expandir árbol'; $_lang['tree_refresh'] = 'Refrescar árbol'; $_lang['tree_sort'] = 'Ordenar árbol'; $_lang['tv'] = 'VdP'; $_lang['tv_default'] = 'Valor Prefijado'; $_lang['tv_elements'] = 'Valores de Opción de Entrada'; $_lang['tv_type'] = 'Tipo de Entrada'; $_lang['tv_value_inherited'] = 'Valor Heredado'; $_lang['type'] = 'Tipo'; $_lang['uncategorized'] = 'no categorizado'; $_lang['undelete'] = 'Recuperar'; $_lang['undeleted'] = 'No Borrado'; $_lang['unpublish'] = 'Despublicar'; $_lang['unpublish_date'] = 'Fecha de Despublicación'; $_lang['unpublish_events'] = 'Eventos Despublicados'; $_lang['unpublished'] = 'Despublicado'; $_lang['untitle_variable'] = 'Variable sin Título'; $_lang['untitled_template'] = 'Plantilla sin Título'; $_lang['untitled_tv'] = 'VdP sin Título'; $_lang['untitled_weblink'] = 'Weblink sin Título'; $_lang['untitled_symlink'] = 'Symlink sin Título'; $_lang['update'] = 'Actualización'; $_lang['updated'] = 'Actualizado'; $_lang['upload'] = 'Subir'; $_lang['value'] = 'Valor'; $_lang['version'] = 'Versión'; $_lang['view'] = 'Vista'; $_lang['view_context'] = 'Ver contexto'; $_lang['view_document'] = 'Ver documento'; $_lang['view_log'] = 'Ver bitácora'; $_lang['warning'] = 'Advertencia!'; $_lang['web_resources'] = 'Recursos Web'; $_lang['which_editor_title'] = 'Editor a usar:'; $_lang['working'] = 'Trabajando...'; $_lang['workspaces'] = 'Espacios de Trabajo'; $_lang['xtype'] = 'Tipo del Campo'; $_lang['xtype_desc'] = 'El tipo del campo de la configuración. Esto puede ser: campo de texto, área de texto o boolean.'; $_lang['yes'] = 'Si'; $_lang['yesno'] = 'Si/No'; $_lang['january'] = 'Enero'; $_lang['february'] = 'Febrero'; $_lang['march'] = 'Marzo'; $_lang['april'] = 'Abril'; $_lang['may'] = 'Mayo'; $_lang['june'] = 'Junio'; $_lang['july'] = 'Julio'; $_lang['august'] = 'Agosto'; $_lang['september'] = 'Septiembre'; $_lang['october'] = 'Octubre'; $_lang['november'] = 'Noviembre'; $_lang['december'] = 'Diciembre'; $_lang['sunday'] = 'Domingo'; $_lang['monday'] = 'Lunes'; $_lang['tuesday'] = 'Martes'; $_lang['wednesday'] = 'Miércoles'; $_lang['thursday'] = 'Jueves'; $_lang['friday'] = 'Viernes'; $_lang['saturday'] = 'Sábado';
{ "content_hash": "7231bf7a850dd377cc6116b3544c83c1", "timestamp": "", "source": "github", "line_count": 488, "max_line_length": 315, "avg_line_length": 49.61065573770492, "alnum_prop": 0.6475010326311441, "repo_name": "yenbekbay/clinic", "id": "3069c4155ba494e1466da92b1c08624202cfc8b2", "size": "24387", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "core/lexicon/es/default.inc.php", "mode": "33261", "license": "mit", "language": [ { "name": "ApacheConf", "bytes": "304" }, { "name": "CSS", "bytes": "1404366" }, { "name": "Erlang", "bytes": "3424" }, { "name": "HTML", "bytes": "691311" }, { "name": "Java", "bytes": "23806" }, { "name": "JavaScript", "bytes": "4252472" }, { "name": "PHP", "bytes": "14377574" }, { "name": "Smarty", "bytes": "247379" } ], "symlink_target": "" }
Hooks - Complete List ===================== * 'about_hook' * 'account_settings' * 'app_menu' * 'atom_author' * 'atom_entry' * 'atom_feed' * 'atom_feed_end' * 'authenticate' * 'avatar_lookup' * 'bb2diaspora' * 'bbcode' * 'channel_remove' * 'check_account_email' * 'check_account_invite' * 'check_account_password' * 'connect_premium' * 'connector_settings' * 'contact_block_end' * 'contact_edit' * 'contact_edit_post' * 'contact_photo_menu' * 'contact_select_options' * 'conversation_start' * 'cron' * 'directory_item' * 'display_item' * 'display_item' * 'display_settings' * 'display_settings_post' * 'enotify' * 'enotify_mail' * 'enotify_store' * 'event_created' * 'event_updated' * 'feature_enabled' * 'feature_settings' * 'feature_settings_post' * 'follow' * 'gender_selector' * 'get_all_perms' * 'get_features' * 'get_widgets' * 'global_permissions' * 'home_content' * 'home_init' * 'html2bbcode' * 'import_directory_profile' * 'init_1' * 'item_photo_menu' * 'item_translate' * 'jot_networks' * 'jot_tool' * 'logged_in' * 'login_hook' * 'logging_out' * 'magic_auth' * 'magic_auth_success' * 'main_slider' * 'marital_selector' * 'mood_verbs' * 'network_content_init' * 'network_ping' * 'network_tabs' * 'network_to_name' * 'notifier_end' * 'notifier_normal' * 'obj_verbs' * 'oembed_probe' * 'page_content_top' * 'page_end' * 'page_header' * 'parse_atom' * 'parse_link' * 'pdl_selector' * 'perm_is_allowed' * 'personal_xrd' * 'photo_post_end' * 'photo_post_end' * 'photo_upload_begin' * 'photo_upload_end' * 'photo_upload_file' * 'photo_upload_form' * 'poke_verbs' * 'post_local' * 'post_local_end' * 'post_local_start' * 'post_mail' * 'post_mail_end' * 'post_remote' * 'post_remote_end' * 'post_remote_update' * 'post_remote_update_end' * 'prepare_body' * 'prepare_body_final' * 'prepare_body_init' * 'proc_run' * 'profile_advanced' * 'profile_edit' * 'profile_post' * 'profile_sidebar' * 'profile_sidebar_enter' * 'profile_tabs' * 'register_account' * 'render_location' * 'settings_account' * 'settings_form' * 'settings_post' * 'sexpref_selector' * 'smilie' * 'validate_channelname' * 'webfinger' * 'zid' * 'zid_init' ***General Module Hooks*** * $a->module . '_mod_aftercontent' * $a->module . '_mod_aside' * $a->module . '_mod_content' * $a->module . '_mod_init' * $a->module . '_mod_post' ***General Selector Hooks*** * $a->module . '_post_' . $selname * $a->module . '_post_' . $selname * $a->module . '_post_' . $selname * $a->module . '_pre_' . $selname * $a->module . '_pre_' . $selname * $a->module . '_pre_' . $selname #include doc/macros/main_footer.bb;
{ "content_hash": "0d7f52d3f9dbea20d9b9397ca175c293", "timestamp": "", "source": "github", "line_count": 136, "max_line_length": 35, "avg_line_length": 18.941176470588236, "alnum_prop": 0.6393633540372671, "repo_name": "solstag/redmatrix", "id": "90edff62305cd02ef68306968a0a5744902f8cd0", "size": "2576", "binary": false, "copies": "10", "ref": "refs/heads/master", "path": "doc/Hooks.md", "mode": "33188", "license": "mit", "language": [ { "name": "ActionScript", "bytes": "17461" }, { "name": "ApacheConf", "bytes": "2791" }, { "name": "Batchfile", "bytes": "22" }, { "name": "CSS", "bytes": "596860" }, { "name": "Go", "bytes": "14151" }, { "name": "HTML", "bytes": "559782" }, { "name": "JavaScript", "bytes": "1350822" }, { "name": "Makefile", "bytes": "1726" }, { "name": "PHP", "bytes": "7878384" }, { "name": "Python", "bytes": "36179" }, { "name": "Ruby", "bytes": "4978" }, { "name": "Shell", "bytes": "27815" }, { "name": "Smarty", "bytes": "384590" } ], "symlink_target": "" }
CREATE OR REPLACE FUNCTION ts2_page_title() RETURNS TRIGGER LANGUAGE plpgsql AS $mw$ BEGIN IF TG_OP = 'INSERT' THEN NEW.titlevector = to_tsvector(REPLACE(NEW.page_title,'/',' ')); ELSIF NEW.page_title != OLD.page_title THEN NEW.titlevector := to_tsvector(REPLACE(NEW.page_title,'/',' ')); END IF; RETURN NEW; END; $mw$; CREATE OR REPLACE FUNCTION ts2_page_text() RETURNS TRIGGER LANGUAGE plpgsql AS $mw$ BEGIN IF TG_OP = 'INSERT' THEN NEW.textvector = to_tsvector(NEW.old_text); ELSIF NEW.old_text != OLD.old_text THEN NEW.textvector := to_tsvector(NEW.old_text); END IF; RETURN NEW; END; $mw$;
{ "content_hash": "e8435bc9c54d37463b9180b9862cfcbb", "timestamp": "", "source": "github", "line_count": 27, "max_line_length": 66, "avg_line_length": 22.37037037037037, "alnum_prop": 0.7102649006622517, "repo_name": "stuartbman/mediawiki-vagrant", "id": "c24efef3df6580051eb7855ef737709b1bea084c", "size": "671", "binary": false, "copies": "283", "ref": "refs/heads/master", "path": "mediawiki/maintenance/postgres/archives/patch-tsearch2funcs.sql", "mode": "33188", "license": "mit", "language": [ { "name": "ApacheConf", "bytes": "3446" }, { "name": "Batchfile", "bytes": "495" }, { "name": "CSS", "bytes": "480614" }, { "name": "Cucumber", "bytes": "16201" }, { "name": "HTML", "bytes": "225396" }, { "name": "JavaScript", "bytes": "3366202" }, { "name": "Makefile", "bytes": "5945" }, { "name": "Nginx", "bytes": "513" }, { "name": "PHP", "bytes": "22034302" }, { "name": "PLSQL", "bytes": "60144" }, { "name": "PLpgSQL", "bytes": "32705" }, { "name": "Pascal", "bytes": "1044" }, { "name": "Perl", "bytes": "31741" }, { "name": "Puppet", "bytes": "409448" }, { "name": "Python", "bytes": "35272" }, { "name": "Ruby", "bytes": "341717" }, { "name": "SQLPL", "bytes": "705" }, { "name": "Shell", "bytes": "47587" } ], "symlink_target": "" }
ACCEPTED #### According to The Catalogue of Life, 3rd January 2011 #### Published in null #### Original name null ### Remarks null
{ "content_hash": "301b87b263e055ef51e9f50367633efc", "timestamp": "", "source": "github", "line_count": 13, "max_line_length": 39, "avg_line_length": 10.307692307692308, "alnum_prop": 0.6940298507462687, "repo_name": "mdoering/backbone", "id": "1431be25a8bac1e6bbd665dbc2e6f55d03c139f2", "size": "191", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "life/Plantae/Magnoliophyta/Liliopsida/Pandanales/Velloziaceae/Barbacenia/Barbacenia lilacina/Barbacenia lilacina lilacina/README.md", "mode": "33188", "license": "apache-2.0", "language": [], "symlink_target": "" }
package org.onosproject.kubevirtnode.api; import com.google.common.base.MoreObjects; import org.apache.commons.lang.StringUtils; import org.onlab.osgi.DefaultServiceDirectory; import org.onlab.packet.IpAddress; import org.onosproject.net.DeviceId; import org.onosproject.net.Port; import org.onosproject.net.PortNumber; import org.onosproject.net.device.DeviceService; import java.util.ArrayList; import java.util.Collection; import java.util.HashSet; import java.util.Objects; import java.util.Set; import static com.google.common.base.Preconditions.checkArgument; import static org.onosproject.kubevirtnode.api.Constants.DEFAULT_CLUSTER_NAME; import static org.onosproject.kubevirtnode.api.Constants.GENEVE; import static org.onosproject.kubevirtnode.api.Constants.GRE; import static org.onosproject.kubevirtnode.api.Constants.INTEGRATION_TO_PHYSICAL_PREFIX; import static org.onosproject.kubevirtnode.api.Constants.STT; import static org.onosproject.kubevirtnode.api.Constants.VXLAN; import static org.onosproject.net.AnnotationKeys.PORT_NAME; /** * Representation of a KubeVirt node. */ public class DefaultKubevirtNode implements KubevirtNode { private static final String NOT_NULL_MSG = "Node % cannot be null"; private static final String OVSDB = "ovsdb:"; private static final int PORT_NAME_MAX_LENGTH = 15; private final String clusterName; private final String hostname; private final Type type; private final DeviceId intgBridge; private final DeviceId tunBridge; private final IpAddress managementIp; private final IpAddress dataIp; private final KubevirtNodeState state; private final Collection<KubevirtPhyInterface> phyIntfs; private final String gatewayBridgeName; /** * A default constructor of kubevirt node. * * @param clusterName clusterName * @param hostname hostname * @param type node type * @param intgBridge integration bridge * @param tunBridge tunnel bridge * @param managementIp management IP address * @param dataIp data IP address * @param state node state * @param phyIntfs physical interfaces * @param gatewayBridgeName gateway bridge name */ protected DefaultKubevirtNode(String clusterName, String hostname, Type type, DeviceId intgBridge, DeviceId tunBridge, IpAddress managementIp, IpAddress dataIp, KubevirtNodeState state, Collection<KubevirtPhyInterface> phyIntfs, String gatewayBridgeName) { this.clusterName = clusterName; this.hostname = hostname; this.type = type; this.intgBridge = intgBridge; this.tunBridge = tunBridge; this.managementIp = managementIp; this.dataIp = dataIp; this.state = state; this.phyIntfs = phyIntfs; this.gatewayBridgeName = gatewayBridgeName; } @Override public String clusterName() { return clusterName; } @Override public String hostname() { return hostname; } @Override public Type type() { return type; } @Override public DeviceId ovsdb() { return DeviceId.deviceId(OVSDB + managementIp().toString()); } @Override public DeviceId intgBridge() { return intgBridge; } @Override public DeviceId tunBridge() { return tunBridge; } @Override public IpAddress managementIp() { return managementIp; } @Override public IpAddress dataIp() { return dataIp; } @Override public KubevirtNodeState state() { return state; } @Override public KubevirtNode updateState(KubevirtNodeState newState) { return new Builder() .hostname(hostname) .clusterName(clusterName) .type(type) .intgBridge(intgBridge) .tunBridge(tunBridge) .managementIp(managementIp) .dataIp(dataIp) .state(newState) .phyIntfs(phyIntfs) .gatewayBridgeName(gatewayBridgeName) .build(); } @Override public KubevirtNode updateIntgBridge(DeviceId deviceId) { return new Builder() .hostname(hostname) .clusterName(clusterName) .type(type) .intgBridge(deviceId) .tunBridge(tunBridge) .managementIp(managementIp) .dataIp(dataIp) .state(state) .phyIntfs(phyIntfs) .gatewayBridgeName(gatewayBridgeName) .build(); } @Override public KubevirtNode updateTunBridge(DeviceId deviceId) { return new Builder() .hostname(hostname) .clusterName(clusterName) .type(type) .intgBridge(intgBridge) .tunBridge(deviceId) .managementIp(managementIp) .dataIp(dataIp) .state(state) .phyIntfs(phyIntfs) .gatewayBridgeName(gatewayBridgeName) .build(); } @Override public Collection<KubevirtPhyInterface> phyIntfs() { if (phyIntfs == null) { return new ArrayList<>(); } return phyIntfs; } @Override public Set<PortNumber> physPatchPorts() { Set<PortNumber> portNumbers = new HashSet<>(); for (KubevirtPhyInterface phyIntf : this.phyIntfs()) { String portName = structurePortName( INTEGRATION_TO_PHYSICAL_PREFIX + phyIntf.network()); PortNumber portNumber = patchPort(portName); if (portNumber != null) { portNumbers.add(portNumber); } } return portNumbers; } @Override public PortNumber vxlanPort() { return tunnelPort(VXLAN); } @Override public PortNumber grePort() { return tunnelPort(GRE); } @Override public PortNumber genevePort() { return tunnelPort(GENEVE); } @Override public PortNumber sttPort() { return tunnelPort(STT); } @Override public String gatewayBridgeName() { return gatewayBridgeName; } private PortNumber tunnelPort(String tunnelType) { if (dataIp == null) { return null; } DeviceService deviceService = DefaultServiceDirectory.getService(DeviceService.class); Port port = deviceService.getPorts(tunBridge).stream() .filter(p -> p.isEnabled() && Objects.equals(p.annotations().value(PORT_NAME), tunnelType)) .findAny().orElse(null); return port != null ? port.number() : null; } private PortNumber patchPort(String portName) { DeviceService deviceService = DefaultServiceDirectory.getService(DeviceService.class); Port port = deviceService.getPorts(intgBridge).stream() .filter(p -> p.isEnabled() && Objects.equals(p.annotations().value(PORT_NAME), portName)) .findAny().orElse(null); return port != null ? port.number() : null; } /** * Re-structures the OVS port name. * The length of OVS port name should be not large than 15. * * @param portName original port name * @return re-structured OVS port name */ private String structurePortName(String portName) { // The size of OVS port name should not be larger than 15 if (portName.length() > PORT_NAME_MAX_LENGTH) { return StringUtils.substring(portName, 0, PORT_NAME_MAX_LENGTH); } return portName; } /** * Returns new builder instance. * * @return kubevirt node builder */ public static Builder builder() { return new Builder(); } /** * Returns new builder instance with the given node as a default value. * * @param node kubevirt node * @return kubevirt node builder */ public static Builder from(KubevirtNode node) { return new Builder() .hostname(node.hostname()) .clusterName(node.clusterName()) .type(node.type()) .intgBridge(node.intgBridge()) .tunBridge(node.tunBridge()) .managementIp(node.managementIp()) .dataIp(node.dataIp()) .state(node.state()) .phyIntfs(node.phyIntfs()) .gatewayBridgeName(node.gatewayBridgeName()); } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } DefaultKubevirtNode that = (DefaultKubevirtNode) o; return clusterName.equals(that.clusterName) && hostname.equals(that.hostname) && type == that.type && intgBridge.equals(that.intgBridge) && tunBridge.equals(that.tunBridge) && managementIp.equals(that.managementIp) && dataIp.equals(that.dataIp); } @Override public int hashCode() { return Objects.hash(clusterName, hostname, type, intgBridge, tunBridge, managementIp, dataIp); } @Override public String toString() { return MoreObjects.toStringHelper(this) .add("clusterName", clusterName) .add("hostname", hostname) .add("type", type) .add("intgBridge", intgBridge) .add("tunBridge", tunBridge) .add("managementIp", managementIp) .add("dataIp", dataIp) .add("state", state) .add("phyIntfs", phyIntfs) .add("gatewayBridgeName", gatewayBridgeName) .toString(); } public static final class Builder implements KubevirtNode.Builder { private String clusterName; private String hostname; private Type type; private DeviceId intgBridge; private DeviceId tunBridge; private IpAddress managementIp; private IpAddress dataIp; private KubevirtNodeState state; private Collection<KubevirtPhyInterface> phyIntfs; private String gatewayBridgeName; // private constructor not intended to use from external private Builder() { } @Override public KubevirtNode build() { checkArgument(hostname != null, NOT_NULL_MSG, "hostname"); checkArgument(type != null, NOT_NULL_MSG, "type"); checkArgument(state != null, NOT_NULL_MSG, "state"); checkArgument(managementIp != null, NOT_NULL_MSG, "management IP"); if (StringUtils.isEmpty(clusterName)) { clusterName = DEFAULT_CLUSTER_NAME; } return new DefaultKubevirtNode( clusterName, hostname, type, intgBridge, tunBridge, managementIp, dataIp, state, phyIntfs, gatewayBridgeName ); } @Override public Builder clusterName(String clusterName) { this.clusterName = clusterName; return this; } @Override public Builder hostname(String hostname) { this.hostname = hostname; return this; } @Override public Builder type(Type type) { this.type = type; return this; } @Override public Builder intgBridge(DeviceId deviceId) { this.intgBridge = deviceId; return this; } @Override public Builder tunBridge(DeviceId deviceId) { this.tunBridge = deviceId; return this; } @Override public Builder managementIp(IpAddress managementIp) { this.managementIp = managementIp; return this; } @Override public Builder dataIp(IpAddress dataIp) { this.dataIp = dataIp; return this; } @Override public Builder phyIntfs(Collection<KubevirtPhyInterface> phyIntfs) { this.phyIntfs = phyIntfs; return this; } @Override public Builder state(KubevirtNodeState state) { this.state = state; return this; } @Override public Builder gatewayBridgeName(String gatewayBridgeName) { this.gatewayBridgeName = gatewayBridgeName; return this; } } }
{ "content_hash": "4a4d4fec743541bb1f3c9768c72b9223", "timestamp": "", "source": "github", "line_count": 430, "max_line_length": 94, "avg_line_length": 30.6, "alnum_prop": 0.5797233622131023, "repo_name": "opennetworkinglab/onos", "id": "45c2e6c0e686a4e28e0e05108951020752263942", "size": "13775", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "apps/kubevirt-node/api/src/main/java/org/onosproject/kubevirtnode/api/DefaultKubevirtNode.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "367433" }, { "name": "Dockerfile", "bytes": "3187" }, { "name": "HTML", "bytes": "332756" }, { "name": "Java", "bytes": "38791946" }, { "name": "JavaScript", "bytes": "3999775" }, { "name": "Jinja", "bytes": "2272195" }, { "name": "Makefile", "bytes": "1852" }, { "name": "P4", "bytes": "197536" }, { "name": "Python", "bytes": "489477" }, { "name": "SCSS", "bytes": "3578" }, { "name": "Shell", "bytes": "342726" }, { "name": "Starlark", "bytes": "495306" }, { "name": "TypeScript", "bytes": "959357" } ], "symlink_target": "" }
from __future__ import absolute_import from __future__ import with_statement import errno import os import resource import signal from mock import Mock, patch from celery import current_app from celery import platforms from celery.platforms import ( get_fdmax, shellsplit, ignore_EBADF, set_process_title, signals, maybe_drop_privileges, setuid, setgid, seteuid, setegid, initgroups, parse_uid, parse_gid, detached, DaemonContext, create_pidlock, PIDFile, LockFailed, setgroups, _setgroups_hack ) from celery.tests.utils import Case, WhateverIO, override_stdouts class test_ignore_EBADF(Case): def test_raises_EBADF(self): with ignore_EBADF(): exc = OSError() exc.errno = errno.EBADF raise exc def test_otherwise(self): with self.assertRaises(OSError): with ignore_EBADF(): exc = OSError() exc.errno = errno.ENOENT raise exc class test_shellsplit(Case): def test_split(self): self.assertEqual(shellsplit("the 'quick' brown fox"), ["the", "quick", "brown", "fox"]) class test_set_process_title(Case): def when_no_setps(self): prev = platforms._setproctitle = platforms._setproctitle, None try: set_process_title("foo") finally: platforms._setproctitle = prev class test_Signals(Case): @patch("signal.getsignal") def test_getitem(self, getsignal): signals["SIGINT"] getsignal.assert_called_with(signal.SIGINT) def test_supported(self): self.assertTrue(signals.supported("INT")) self.assertFalse(signals.supported("SIGIMAGINARY")) def test_signum(self): self.assertEqual(signals.signum(13), 13) self.assertEqual(signals.signum("INT"), signal.SIGINT) self.assertEqual(signals.signum("SIGINT"), signal.SIGINT) with self.assertRaises(TypeError): signals.signum("int") signals.signum(object()) @patch("signal.signal") def test_ignore(self, set): signals.ignore("SIGINT") set.assert_called_with(signals.signum("INT"), signals.ignored) signals.ignore("SIGTERM") set.assert_called_with(signals.signum("TERM"), signals.ignored) @patch("signal.signal") def test_setitem(self, set): handle = lambda *a: a signals["INT"] = handle set.assert_called_with(signal.SIGINT, handle) @patch("signal.signal") def test_setitem_raises(self, set): set.side_effect = ValueError() signals["INT"] = lambda *a: a if not current_app.IS_WINDOWS: class test_get_fdmax(Case): @patch("resource.getrlimit") def test_when_infinity(self, getrlimit): getrlimit.return_value = [None, resource.RLIM_INFINITY] default = object() self.assertIs(get_fdmax(default), default) @patch("resource.getrlimit") def test_when_actual(self, getrlimit): getrlimit.return_value = [None, 13] self.assertEqual(get_fdmax(None), 13) class test_maybe_drop_privileges(Case): @patch("celery.platforms.parse_uid") @patch("pwd.getpwuid") @patch("celery.platforms.setgid") @patch("celery.platforms.setuid") @patch("celery.platforms.initgroups") def test_with_uid(self, initgroups, setuid, setgid, getpwuid, parse_uid): class pw_struct(object): pw_gid = 50001 getpwuid.return_value = pw_struct() parse_uid.return_value = 5001 maybe_drop_privileges(uid="user") parse_uid.assert_called_with("user") getpwuid.assert_called_with(5001) setgid.assert_called_with(50001) initgroups.assert_called_with(5001, 50001) setuid.assert_called_with(5001) @patch("celery.platforms.parse_uid") @patch("celery.platforms.parse_gid") @patch("celery.platforms.setgid") @patch("celery.platforms.setuid") @patch("celery.platforms.initgroups") def test_with_guid(self, initgroups, setuid, setgid, parse_gid, parse_uid): parse_uid.return_value = 5001 parse_gid.return_value = 50001 maybe_drop_privileges(uid="user", gid="group") parse_uid.assert_called_with("user") parse_gid.assert_called_with("group") setgid.assert_called_with(50001) initgroups.assert_called_with(5001, 50001) setuid.assert_called_with(5001) @patch("celery.platforms.setuid") @patch("celery.platforms.setgid") @patch("celery.platforms.parse_gid") def test_only_gid(self, parse_gid, setgid, setuid): parse_gid.return_value = 50001 maybe_drop_privileges(gid="group") parse_gid.assert_called_with("group") setgid.assert_called_with(50001) self.assertFalse(setuid.called) class test_setget_uid_gid(Case): @patch("celery.platforms.parse_uid") @patch("os.setuid") def test_setuid(self, _setuid, parse_uid): parse_uid.return_value = 5001 setuid("user") parse_uid.assert_called_with("user") _setuid.assert_called_with(5001) @patch("celery.platforms.parse_uid") @patch("os.geteuid") @patch("os.seteuid") def test_seteuid(self, _seteuid, _geteuid, parse_uid): parse_uid.return_value = 5001 _geteuid.return_value = 5001 seteuid("user") parse_uid.assert_called_with("user") self.assertFalse(_seteuid.called) _geteuid.return_value = 1 seteuid("user") _seteuid.assert_called_with(5001) @patch("celery.platforms.parse_gid") @patch("os.setgid") def test_setgid(self, _setgid, parse_gid): parse_gid.return_value = 50001 setgid("group") parse_gid.assert_called_with("group") _setgid.assert_called_with(50001) @patch("celery.platforms.parse_gid") @patch("os.getegid") @patch("os.setegid") def test_setegid(self, _setegid, _getegid, parse_gid): parse_gid.return_value = 50001 _getegid.return_value = 50001 setegid("group") parse_gid.assert_called_with("group") self.assertFalse(_setegid.called) _getegid.return_value = 1 setegid("group") _setegid.assert_called_with(50001) def test_parse_uid_when_int(self): self.assertEqual(parse_uid(5001), 5001) @patch("pwd.getpwnam") def test_parse_uid_when_existing_name(self, getpwnam): class pwent(object): pw_uid = 5001 getpwnam.return_value = pwent() self.assertEqual(parse_uid("user"), 5001) @patch("pwd.getpwnam") def test_parse_uid_when_nonexisting_name(self, getpwnam): getpwnam.side_effect = KeyError("user") with self.assertRaises(KeyError): parse_uid("user") def test_parse_gid_when_int(self): self.assertEqual(parse_gid(50001), 50001) @patch("grp.getgrnam") def test_parse_gid_when_existing_name(self, getgrnam): class grent(object): gr_gid = 50001 getgrnam.return_value = grent() self.assertEqual(parse_gid("group"), 50001) @patch("grp.getgrnam") def test_parse_gid_when_nonexisting_name(self, getgrnam): getgrnam.side_effect = KeyError("group") with self.assertRaises(KeyError): parse_gid("group") class test_initgroups(Case): @patch("pwd.getpwuid") @patch("os.initgroups", create=True) def test_with_initgroups(self, initgroups_, getpwuid): getpwuid.return_value = ["user"] initgroups(5001, 50001) initgroups_.assert_called_with("user", 50001) @patch("celery.platforms.setgroups") @patch("grp.getgrall") @patch("pwd.getpwuid") def test_without_initgroups(self, getpwuid, getgrall, setgroups): prev = getattr(os, "initgroups", None) try: delattr(os, "initgroups") except AttributeError: pass try: getpwuid.return_value = ["user"] class grent(object): gr_mem = ["user"] def __init__(self, gid): self.gr_gid = gid getgrall.return_value = [grent(1), grent(2), grent(3)] initgroups(5001, 50001) setgroups.assert_called_with([1, 2, 3]) finally: if prev: os.initgroups = prev class test_detached(Case): def test_without_resource(self): prev, platforms.resource = platforms.resource, None try: with self.assertRaises(RuntimeError): detached() finally: platforms.resource = prev @patch("celery.platforms.create_pidlock") @patch("celery.platforms.signals") @patch("celery.platforms.maybe_drop_privileges") @patch("os.geteuid") @patch("__builtin__.open") def test_default(self, open, geteuid, maybe_drop, signals, pidlock): geteuid.return_value = 0 context = detached(uid="user", gid="group") self.assertIsInstance(context, DaemonContext) signals.reset.assert_called_with("SIGCLD") maybe_drop.assert_called_with(uid="user", gid="group") open.return_value = Mock() geteuid.return_value = 5001 context = detached(uid="user", gid="group", logfile="/foo/bar") self.assertIsInstance(context, DaemonContext) open.assert_called_with("/foo/bar", "a") open.return_value.close.assert_called_with() context = detached(pidfile="/foo/bar/pid") self.assertIsInstance(context, DaemonContext) pidlock.assert_called_with("/foo/bar/pid") class test_DaemonContext(Case): @patch("os.fork") @patch("os.setsid") @patch("os._exit") @patch("os.chdir") @patch("os.umask") @patch("os.close") @patch("os.open") @patch("os.dup2") def test_open(self, dup2, open, close, umask, chdir, _exit, setsid, fork): x = DaemonContext(workdir="/opt/workdir") fork.return_value = 0 with x: self.assertTrue(x._is_open) with x: pass self.assertEqual(fork.call_count, 2) setsid.assert_called_with() self.assertFalse(_exit.called) chdir.assert_called_with(x.workdir) umask.assert_called_with(x.umask) open.assert_called_with(platforms.DAEMON_REDIRECT_TO, os.O_RDWR) self.assertEqual(dup2.call_args_list[0], [(0, 1), {}]) self.assertEqual(dup2.call_args_list[1], [(0, 2), {}]) fork.reset_mock() fork.return_value = 1 x = DaemonContext(workdir="/opt/workdir") with x: pass self.assertEqual(fork.call_count, 1) _exit.assert_called_with(0) x = DaemonContext(workdir="/opt/workdir", fake=True) x._detach = Mock() with x: pass self.assertFalse(x._detach.called) class test_PIDFile(Case): @patch("celery.platforms.PIDFile") def test_create_pidlock(self, PIDFile): p = PIDFile.return_value = Mock() p.is_locked.return_value = True p.remove_if_stale.return_value = False with self.assertRaises(SystemExit): create_pidlock("/var/pid") p.remove_if_stale.return_value = True ret = create_pidlock("/var/pid") self.assertIs(ret, p) def test_context(self): p = PIDFile("/var/pid") p.write_pid = Mock() p.remove = Mock() with p as _p: self.assertIs(_p, p) p.write_pid.assert_called_with() p.remove.assert_called_with() def test_acquire_raises_LockFailed(self): p = PIDFile("/var/pid") p.write_pid = Mock() p.write_pid.side_effect = OSError() with self.assertRaises(LockFailed): with p: pass @patch("os.path.exists") def test_is_locked(self, exists): p = PIDFile("/var/pid") exists.return_value = True self.assertTrue(p.is_locked()) exists.return_value = False self.assertFalse(p.is_locked()) @patch("__builtin__.open") def test_read_pid(self, open_): s = open_.return_value = WhateverIO() s.write("1816\n") s.seek(0) p = PIDFile("/var/pid") self.assertEqual(p.read_pid(), 1816) @patch("__builtin__.open") def test_read_pid_partially_written(self, open_): s = open_.return_value = WhateverIO() s.write("1816") s.seek(0) p = PIDFile("/var/pid") with self.assertRaises(ValueError): p.read_pid() @patch("__builtin__.open") def test_read_pid_raises_ENOENT(self, open_): exc = IOError() exc.errno = errno.ENOENT open_.side_effect = exc p = PIDFile("/var/pid") self.assertIsNone(p.read_pid()) @patch("__builtin__.open") def test_read_pid_raises_IOError(self, open_): exc = IOError() exc.errno = errno.EAGAIN open_.side_effect = exc p = PIDFile("/var/pid") with self.assertRaises(IOError): p.read_pid() @patch("__builtin__.open") def test_read_pid_bogus_pidfile(self, open_): s = open_.return_value = WhateverIO() s.write("eighteensixteen\n") s.seek(0) p = PIDFile("/var/pid") with self.assertRaises(ValueError): p.read_pid() @patch("os.unlink") def test_remove(self, unlink): unlink.return_value = True p = PIDFile("/var/pid") p.remove() unlink.assert_called_with(p.path) @patch("os.unlink") def test_remove_ENOENT(self, unlink): exc = OSError() exc.errno = errno.ENOENT unlink.side_effect = exc p = PIDFile("/var/pid") p.remove() unlink.assert_called_with(p.path) @patch("os.unlink") def test_remove_EACCES(self, unlink): exc = OSError() exc.errno = errno.EACCES unlink.side_effect = exc p = PIDFile("/var/pid") p.remove() unlink.assert_called_with(p.path) @patch("os.unlink") def test_remove_OSError(self, unlink): exc = OSError() exc.errno = errno.EAGAIN unlink.side_effect = exc p = PIDFile("/var/pid") with self.assertRaises(OSError): p.remove() unlink.assert_called_with(p.path) @patch("os.kill") def test_remove_if_stale_process_alive(self, kill): p = PIDFile("/var/pid") p.read_pid = Mock() p.read_pid.return_value = 1816 kill.return_value = 0 self.assertFalse(p.remove_if_stale()) kill.assert_called_with(1816, 0) p.read_pid.assert_called_with() kill.side_effect = OSError() kill.side_effect.errno = errno.ENOENT self.assertFalse(p.remove_if_stale()) @patch("os.kill") def test_remove_if_stale_process_dead(self, kill): with override_stdouts(): p = PIDFile("/var/pid") p.read_pid = Mock() p.read_pid.return_value = 1816 p.remove = Mock() exc = OSError() exc.errno = errno.ESRCH kill.side_effect = exc self.assertTrue(p.remove_if_stale()) kill.assert_called_with(1816, 0) p.remove.assert_called_with() def test_remove_if_stale_broken_pid(self): with override_stdouts(): p = PIDFile("/var/pid") p.read_pid = Mock() p.read_pid.side_effect = ValueError() p.remove = Mock() self.assertTrue(p.remove_if_stale()) p.remove.assert_called_with() def test_remove_if_stale_no_pidfile(self): p = PIDFile("/var/pid") p.read_pid = Mock() p.read_pid.return_value = None p.remove = Mock() self.assertTrue(p.remove_if_stale()) p.remove.assert_called_with() @patch("os.fsync") @patch("os.getpid") @patch("os.open") @patch("os.fdopen") @patch("__builtin__.open") def test_write_pid(self, open_, fdopen, osopen, getpid, fsync): getpid.return_value = 1816 osopen.return_value = 13 w = fdopen.return_value = WhateverIO() w.close = Mock() r = open_.return_value = WhateverIO() r.write("1816\n") r.seek(0) p = PIDFile("/var/pid") p.write_pid() w.seek(0) self.assertEqual(w.readline(), "1816\n") self.assertTrue(w.close.called) getpid.assert_called_with() osopen.assert_called_with(p.path, platforms.PIDFILE_FLAGS, platforms.PIDFILE_MODE) fdopen.assert_called_with(13, "w") fsync.assert_called_with(13) open_.assert_called_with(p.path) @patch("os.fsync") @patch("os.getpid") @patch("os.open") @patch("os.fdopen") @patch("__builtin__.open") def test_write_reread_fails(self, open_, fdopen, osopen, getpid, fsync): getpid.return_value = 1816 osopen.return_value = 13 w = fdopen.return_value = WhateverIO() w.close = Mock() r = open_.return_value = WhateverIO() r.write("11816\n") r.seek(0) p = PIDFile("/var/pid") with self.assertRaises(LockFailed): p.write_pid() class test_setgroups(Case): @patch("os.setgroups", create=True) def test_setgroups_hack_ValueError(self, setgroups): def on_setgroups(groups): if len(groups) <= 200: setgroups.return_value = True return raise ValueError() setgroups.side_effect = on_setgroups _setgroups_hack(range(400)) setgroups.side_effect = ValueError() with self.assertRaises(ValueError): _setgroups_hack(range(400)) @patch("os.setgroups", create=True) def test_setgroups_hack_OSError(self, setgroups): exc = OSError() exc.errno = errno.EINVAL def on_setgroups(groups): if len(groups) <= 200: setgroups.return_value = True return raise exc setgroups.side_effect = on_setgroups _setgroups_hack(range(400)) setgroups.side_effect = exc with self.assertRaises(OSError): _setgroups_hack(range(400)) exc2 = OSError() exc.errno = errno.ESRCH setgroups.side_effect = exc2 with self.assertRaises(OSError): _setgroups_hack(range(400)) @patch("os.sysconf") @patch("celery.platforms._setgroups_hack") def test_setgroups(self, hack, sysconf): sysconf.return_value = 100 setgroups(range(400)) hack.assert_called_with(range(100)) @patch("os.sysconf") @patch("celery.platforms._setgroups_hack") def test_setgroups_sysconf_raises(self, hack, sysconf): sysconf.side_effect = ValueError() setgroups(range(400)) hack.assert_called_with(range(400)) @patch("os.getgroups") @patch("os.sysconf") @patch("celery.platforms._setgroups_hack") def test_setgroups_raises_ESRCH(self, hack, sysconf, getgroups): sysconf.side_effect = ValueError() esrch = OSError() esrch.errno = errno.ESRCH hack.side_effect = esrch with self.assertRaises(OSError): setgroups(range(400)) @patch("os.getgroups") @patch("os.sysconf") @patch("celery.platforms._setgroups_hack") def test_setgroups_raises_EPERM(self, hack, sysconf, getgroups): sysconf.side_effect = ValueError() eperm = OSError() eperm.errno = errno.EPERM hack.side_effect = eperm getgroups.return_value = range(400) setgroups(range(400)) getgroups.assert_called_with() getgroups.return_value = [1000] with self.assertRaises(OSError): setgroups(range(400)) getgroups.assert_called_with()
{ "content_hash": "ee0b18c4868471e02c116884d9069f31", "timestamp": "", "source": "github", "line_count": 658, "max_line_length": 76, "avg_line_length": 33.209726443769, "alnum_prop": 0.5417810726706938, "repo_name": "couchbaselabs/celery", "id": "de5494414af49fba2ed3642acfc5cfc9952f56f0", "size": "21852", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "celery/tests/utilities/test_platforms.py", "mode": "33188", "license": "bsd-3-clause", "language": [], "symlink_target": "" }
#!/usr/bin/env node /** * Module dependencies. */ import app from "../app.js"; import dgb from "debug"; import http from "http"; const debug = dgb("drawphone:server"); /** * Get port from environment and store in Express. */ const port = normalizePort(process.env.PORT || "3000"); app.set("port", port); /** * Create HTTP server. */ const server = http.createServer(app); /** * Attach Socket.IO to the Express server. */ const io = app.io; io.attach(server, { pingInterval: 15000, pingTimeout: 30000, }); /** * Listen on provided port, on all network interfaces. */ server.listen(port); console.log(`Drawphone is now running on port ${port}. Press Ctrl+C to stop.`); server.on("error", onError); server.on("listening", onListening); /** * Normalize a port into a number, string, or false. */ function normalizePort(val) { const port = parseInt(val, 10); if (isNaN(port)) { // named pipe return val; } if (port >= 0) { // port number return port; } return false; } /** * Event listener for HTTP server "error" event. */ function onError(error) { if (error.syscall !== "listen") { throw error; } const bind = typeof port === "string" ? `Pipe ${port}` : `Port ${port}`; // handle specific listen errors with friendly messages switch (error.code) { case "EACCES": console.error(`${bind} requires elevated privileges`); process.exit(1); break; case "EADDRINUSE": console.error(`${bind} is already in use`); process.exit(1); break; default: throw error; } } /** * Event listener for HTTP server "listening" event. */ function onListening() { const addr = server.address(); const bind = typeof addr === "string" ? `pipe ${addr}` : `port ${addr.port}`; debug(`Listening on ${bind}`); }
{ "content_hash": "019868020ba4326e2b884eb5071d44ed", "timestamp": "", "source": "github", "line_count": 101, "max_line_length": 79, "avg_line_length": 19.217821782178216, "alnum_prop": 0.5862957238536837, "repo_name": "tannerkrewson/drawphone", "id": "c79ccd5f6ad30dd1e1e8d72325e85b4317e7854c", "size": "1941", "binary": false, "copies": "1", "ref": "refs/heads/dev", "path": "server/bin/www.js", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "6879" }, { "name": "JavaScript", "bytes": "127080" }, { "name": "Pug", "bytes": "14507" } ], "symlink_target": "" }
package getch import ( "errors" "fmt" "strings" "unicode/utf16" "github.com/zetamatta/go-getch/consoleinput" ) const ( RIGHT_ALT_PRESSED = 1 LEFT_ALT_PRESSED = 2 RIGHT_CTRL_PRESSED = 4 LEFT_CTRL_PRESSED = 8 CTRL_PRESSED = RIGHT_CTRL_PRESSED | LEFT_CTRL_PRESSED ALT_PRESSED = RIGHT_ALT_PRESSED | LEFT_ALT_PRESSED ) type keyEvent struct { Rune rune Scan uint16 Shift uint32 } func (k keyEvent) String() string { return fmt.Sprintf("Rune:%v,Scan=%d,Shift=%d", k.Rune, k.Scan, k.Shift) } type resizeEvent struct { Width uint Height uint } func (r resizeEvent) String() string { return fmt.Sprintf("Width:%d,Height:%d", r.Width, r.Height) } const ( // Button FROM_LEFT_1ST_BUTTON_PRESSED = 0x0001 FROM_LEFT_2ND_BUTTON_PRESSED = 0x0004 FROM_LEFT_3RD_BUTTON_PRESSED = 0x0008 FROM_LEFT_4TH_BUTTON_PRESSED = 0x0010 RIGHTMOST_BUTTON_PRESSED = 0x0002 ) type Event struct { Focus *struct{} // MS says it should be ignored Key *keyEvent // == KeyDown KeyDown *keyEvent KeyUp *keyEvent Menu *struct{} // MS says it should be ignored Mouse *consoleinput.MouseEventRecord // not supported,yet Resize *resizeEvent } func (e Event) String() string { event := make([]string, 0, 7) if e.Focus != nil { event = append(event, "Focus") } if e.KeyDown != nil { event = append(event, "KeyDown("+e.KeyDown.String()+")") } if e.KeyUp != nil { event = append(event, "KeyUp("+e.KeyUp.String()+")") } if e.Menu != nil { event = append(event, "Menu") } if e.Mouse != nil { event = append(event, "Mouse") } if e.Resize != nil { event = append(event, "Resize("+e.Resize.String()+")") } if len(event) > 0 { return strings.Join(event, ",") } else { return "no events" } } type Handle struct { consoleinput.Handle lastkey *keyEvent eventBuffer []Event eventBufferRead int } func New() (*Handle, error) { handle, err := consoleinput.New() if err != nil { return nil, err } return &Handle{Handle: handle}, nil } func (h *Handle) Close() { h.Handle.Close() } func (h *Handle) readEvents(flag uint32) []Event { orgConMode := h.GetConsoleMode() h.SetConsoleMode(flag) defer h.SetConsoleMode(orgConMode) result := make([]Event, 0, 2) for len(result) <= 0 { var events [10]consoleinput.InputRecord numberOfEventsRead := h.Read(events[:]) for i := uint32(0); i < numberOfEventsRead; i++ { e := events[i] var r Event switch e.EventType { case consoleinput.FOCUS_EVENT: r = Event{Focus: &struct{}{}} case consoleinput.KEY_EVENT: p := e.KeyEvent() k := &keyEvent{ Rune: rune(p.UnicodeChar), Scan: p.VirtualKeyCode, Shift: p.ControlKeyState, } if p.KeyDown != 0 { r = Event{Key: k, KeyDown: k} } else { r = Event{KeyUp: k} } case consoleinput.MENU_EVENT: r = Event{Menu: &struct{}{}} case consoleinput.MOUSE_EVENT: p := e.MouseEvent() r = Event{ Mouse: &consoleinput.MouseEventRecord{ X: p.X, Y: p.Y, Button: p.Button, ControlKey: p.ControlKey, Event: p.Event, }, } case consoleinput.WINDOW_BUFFER_SIZE_EVENT: width, height := e.ResizeEvent() r = Event{ Resize: &resizeEvent{ Width: uint(width), Height: uint(height), }, } default: continue } result = append(result, r) } } return result } func (h *Handle) bufReadEvent(flag uint32) Event { for h.eventBuffer == nil || h.eventBufferRead >= len(h.eventBuffer) { h.eventBuffer = h.readEvents(flag) h.eventBufferRead = 0 } h.eventBufferRead++ return h.eventBuffer[h.eventBufferRead-1] } // Get a event with concatinating a surrogate-pair of keyevents. func (h *Handle) getEvent(flag uint32) Event { for { event1 := h.bufReadEvent(flag) if k := event1.Key; k != nil { if h.lastkey != nil { k.Rune = utf16.DecodeRune(h.lastkey.Rune, k.Rune) h.lastkey = nil } else if utf16.IsSurrogate(k.Rune) { h.lastkey = k continue } } return event1 } } const ALL_EVENTS = consoleinput.ENABLE_WINDOW_INPUT // | consoleinput.ENABLE_MOUSE_INPUT // Get all console-event (keyboard,resize,...) func (h *Handle) All() Event { return h.getEvent(ALL_EVENTS) } const IGNORE_RESIZE_EVENT uint32 = 0 // Get character as a Rune func (h *Handle) Rune() rune { for { e := h.getEvent(IGNORE_RESIZE_EVENT) if e.Key != nil && e.Key.Rune != 0 { return e.Key.Rune } } } func (h *Handle) Flush() error { org := h.GetConsoleMode() h.SetConsoleMode(ALL_EVENTS) defer h.SetConsoleMode(org) h.eventBuffer = nil return h.FlushConsoleInputBuffer() } // wait for keyboard event func (h *Handle) Wait(timeout_msec uintptr) (bool, error) { status, err := h.WaitForSingleObject(timeout_msec) switch status { case consoleinput.WAIT_OBJECT_0: return true, nil case consoleinput.WAIT_TIMEOUT: return false, nil case consoleinput.WAIT_ABANDONED: return false, errors.New("WAIT_ABANDONED") default: // including WAIT_FAILED: if err != nil { return false, err } else { return false, errors.New("WAIT_FAILED") } } } func (h *Handle) Within(msec uintptr) (Event, error) { orgConMode := h.GetConsoleMode() h.SetConsoleMode(ALL_EVENTS) defer h.SetConsoleMode(orgConMode) if ok, err := h.Wait(msec); err != nil || !ok { return Event{}, err } return h.All(), nil } const NUL = '\000' func (h *Handle) RuneWithin(msec uintptr) (rune, error) { orgConMode := h.GetConsoleMode() h.SetConsoleMode(IGNORE_RESIZE_EVENT) defer h.SetConsoleMode(orgConMode) if ok, err := h.Wait(msec); err != nil || !ok { return NUL, err } e := h.getEvent(IGNORE_RESIZE_EVENT) if e.Key != nil { return e.Key.Rune, nil } return NUL, nil }
{ "content_hash": "af7e082367c09a177d94d2d163276fe8", "timestamp": "", "source": "github", "line_count": 262, "max_line_length": 88, "avg_line_length": 21.984732824427482, "alnum_prop": 0.6432291666666666, "repo_name": "zetamatta/go-getch", "id": "1ddfeac7ef56520553125a92185f948a6644c239", "size": "5760", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "getch.go", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "Batchfile", "bytes": "192" }, { "name": "Go", "bytes": "19458" } ], "symlink_target": "" }
Google Cloud Datastore is a fully managed, schemaless, non-relational datastore accessible through Google APIs infrastructure. It provides a rich set of query capabilities, supports atomic transactions, and automatically scales up and down in response to load. The API is deliberately low-level to map to the underlying Datastore RPC model and provide more flexibility to developers and higher level library implementers. This repository contains the source code of samples and developer resources related to Google Cloud Datastore: - [Service and protocol buffers messages definition][6] - [Python protocol buffers client library and samples][9] - [Java protocol buffers Java client library and samples][10] - [Node.js samples][11] ## Samples ### JSON - [Node.js][3], [todo.js][24] - [Ruby][21], [todos.rb][25] - [[Add yours here][16]] ### Protobuf - [Python][1] - [Java][2] - [[Add yours here][16]] ## Client libraries ### JSON - [Node.js][17]: ``` npm install googleapis ``` - [Ruby (google-api-client)][23] ``` gem install google-api-client ``` - [Ruby (ActiveDatastore)][22] ``` gem install active_datastore ``` - [Dart][26] - [[Add yours here][16]] ### Protobuf - [Python][18] ([readthedocs][19]): ``` pip install googledatastore ``` - Maven/Java ([javadoc][20]): ``` <dependency> <groupId>com.google.apis</groupId> <artifactId>google-api-services-datastore-protobuf</artifactId> <version>v1beta2-rev1-2.1.0</version> </dependency> ``` - [[Add yours here][16]] ## Documentation - [Getting Started][4] - [JSON API reference][5] - [Protocol Buffers API reference][6] ## Filing Issues 1. For production issues and support, see [Google Cloud Platform Support packages][13]. 1. For bugs or feature requests, please first look at [existing issues][14]. 1. When applicable, create a new [report][15]. 1. For bugs, detail the steps to reproduce the problem and the affected version number. 1. For feature requests, articulate the usecase you are trying solve and describe current workaround. 1. Make sure to annotate the issues with the appropriate labels. ## Contributing changes - See [CONTRIB.md][7] ## Licensing - See [LICENSE][8] [1]: python/demos/trivial/adams.py [2]: java/demos/src/main/java/com/google/api/services/datastore/demos/trivial/adams.java [3]: https://github.com/GoogleCloudPlatform/google-cloud-datastore/blob/master/nodejs/demos/trivial/adams.js [4]: https://developers.google.com/datastore [5]: https://developers.google.com/datastore/docs/apis/v1beta2/ [6]: https://developers.google.com/datastore/docs/apis/v1beta2/proto [7]: CONTRIB.md [8]: LICENSE [9]: python [10]: java [11]: nodejs [13]: https://cloud.google.com/support/packages [14]: https://github.com/GoogleCloudPlatform/google-cloud-datastore/issues [15]: https://github.com/GoogleCloudPlatform/google-cloud-datastore/issues/new [16]: https://github.com/GoogleCloudPlatform/google-cloud-datastore/fork [17]: https://npmjs.org/package/googleapis [18]: https://pypi.python.org/pypi/googledatastore [19]: googledatastore.readthedocs.org [20]: https://developers.google.com/datastore/docs/apis/javadoc/ [21]: ruby/demos/trivial/adams.rb [22]: https://github.com/sudhirj/active_datastore [23]: https://rubygems.org/gems/google-api-client [24]: nodejs/demos/todos/todo.js [25]: ruby/demos/todos/todos.rb [26]: https://github.com/dart-google-apis/dart_datastore_v1beta1_api_client
{ "content_hash": "926a7e30f9403e93869caa5a4d08da3f", "timestamp": "", "source": "github", "line_count": 118, "max_line_length": 160, "avg_line_length": 28.728813559322035, "alnum_prop": 0.7389380530973452, "repo_name": "webhost/google-cloud-datastore", "id": "831774062c8e8ff93454951e674eced8773bd7f1", "size": "3416", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "README.md", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "72824" }, { "name": "JavaScript", "bytes": "14278" }, { "name": "Python", "bytes": "60779" }, { "name": "Ruby", "bytes": "6523" } ], "symlink_target": "" }
/** * Manages all shortcut keys. */ 'use strict'; var $ = require('jquery'); var hotkeys = require('hotkeys'); var is = require('is_js'); /** The hotkey dispatcher */ var dispatcher; var $searchText; var $clearButton; function bindHotkeys() { dispatcher = new hotkeys.Dispatcher(); var hotkeyModifier = is.mac() ? 'cmd' : 'alt'; dispatcher.on(hotkeyModifier + ' s', function() { $searchText.focus(); }); dispatcher.on(hotkeyModifier + ' x', function() { $clearButton.click(); }); } $(document).ready(function() { $searchText = $('#searchText'); $clearButton = $('#clearButton'); bindHotkeys(); });
{ "content_hash": "8d1fe793700204d0b0e76b8aea5ff6e3", "timestamp": "", "source": "github", "line_count": 33, "max_line_length": 53, "avg_line_length": 19.939393939393938, "alnum_prop": 0.6048632218844985, "repo_name": "joeattardi/tailstreamer", "id": "cc187c546056e7fb49b3adb6b56762ad1ca9508c", "size": "658", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/main/resources/static/js/ui/hotkeys.js", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "5265" }, { "name": "HTML", "bytes": "3998" }, { "name": "Java", "bytes": "36293" }, { "name": "JavaScript", "bytes": "17537" } ], "symlink_target": "" }
--- title: Xadow - GPS category: RePhone bzurl: https://www.seeedstudio.com/Xadow-GPS-p-1600.html oldwikiname: Xadow - GPS prodimagename: Xadow_gps.jpg surveyurl: https://www.research.net/r/xadow_gps sku: 113040001 --- ![](https://github.com/SeeedDocument/Xadow_GPS/raw/master/img/Xadow_gps.jpg) Xadow GPS is an OEM GNSS receiver module, including the Fastrax IT530M and a tiny 12mm squared ceramic patch antenna. The low power module outputs a series of standard NMEA format data which provides position, satellite information and time, etc. This module can be easily connected directly to Xadow Main board to display and record the above-mentioned information. It features acquisition and tracking capability of weak signals, making it a great choice for navigation projects. [![](https://github.com/SeeedDocument/Seeed-WiKi/raw/master/docs/images/300px-Get_One_Now_Banner-ragular.png)](https://www.seeedstudio.com/Xadow-GPS-p-1600.html) ## Specifications --- - Working voltage: 5.0 VDC - Channels: 99/33 (search/track) - Navigation sensitivity: -165dBm - Tracking sensitivity: -148 dBm - Time to First Fix(cold acq): 23s - Time to First Fix(warm acq): 23s - Time to First Fix (hot acq): 1s - Update rate: 1 Hz (configurable up to 10 Hz) - Data protocol: NMEA-0183 rev. 3.01 - Communication Mode: UART - Default baud rate: 115200 b/s - Operating temperature: -40°C ~+85°C - Dimensions: 25.43mm x 20.35mm ## Demonstration --- There is an example showing how to read data from the GPS using software serial and sends it back out on the serial port. ![](https://github.com/SeeedDocument/Xadow_GPS/raw/master/img/IMG_4200.JPG) !!!Note When connect Xadow GPS to Xadow Main Board, you should concern about the connection direction. The connection method is that the unfilled corner of one Xadow module need to connect to the right angle of another module(see four corners of each Xadow module). ``` #define SerialBaud 9600 #define Serial1Baud 9600 void setup() { Serial.begin(SerialBaud); Serial1.begin(Serial1Baud); } void loop() { for(;;) { // copy from virtual serial line to uart and vice versa /* */ if (Serial.available()) { Serial1.write(Serial.read()); } if (Serial1.available()) { Serial.write(Serial1.read()); } } } ``` - Open the serial monitor, you can see: ![](https://github.com/SeeedDocument/Xadow_GPS/raw/master/img/Read_data_from_serial_monitor.jpg) There is all the information about NMEA 0183 communication protocol. In fact, we only need to pick out the locate data, others can be ignored. The $GPRMC data is useful for us, Now let’s analysis its detail meaning: $GPRMC,091308.000,A,2235.1683,N,11356.3607,E,0.37,259.79,050813,,,A*6E - 091308.000--means Greenwich Mean Time (the standard world time) 09:13:8 am. Standard - time in Beijing is eight hours ahead of Greenwich Mean Time, so Beijing Time is 5:13 pm. - A--means the data is valid, If the letter is V, which means $GPRMC data is valid. - 2235.1683,N--Latitude 22.351683 degrees. - 11356.3607,E--east longitude 113.563607 degrees. - 0.37 -- means motion rate. - 259.79--means motion direction. the north is 0 degrees, east is 90 degrees, south is 180 degrees, west is 270 degrees. - 050813--means August 5, 2013. **We can also observe this data using u-center.** - Download [u-center](https://www.u-blox.com/en/product/u-center-windows) and install it on your computer. - Click Receiver - > Port and select the COM port that the Xadow Main Board is using. If you are opening serial monitor of Arduino IDE, please close it. - Click Receiver -> Baudrate and make sure 9600 is selected. - Click View -> Text Console and you should get a window that will stream NMEA data as show below. ![](https://github.com/SeeedDocument/Xadow_GPS/raw/master/img/Read_data_from_u-_center.jpg) - The right part in the picture above is Satellite Position, World Position, Compass, Watch. You can click View -> Docking Windows and select the windows you want to see. ## Resources --- - [Xadow GPS Eagle File](https://github.com/SeeedDocument/Xadow_GPS/raw/master/res/Xadow_GPS_Eagle_File.zip) - [Xadow GPS Schematic in PDF](https://github.com/SeeedDocument/Xadow_GPS/raw/master/res/Xadow_GPS_in_Schematic.pdf) - [Fastrax IT530M Datasheet](https://github.com/SeeedDocument/Xadow_GPS/raw/master/res/IT530M_DataSheet.pdf)
{ "content_hash": "b56a6709ea15e3b495274d24e6eb3cb4", "timestamp": "", "source": "github", "line_count": 98, "max_line_length": 481, "avg_line_length": 45.88775510204081, "alnum_prop": 0.7184789859906604, "repo_name": "SeeedDocument/Seeed-WiKi", "id": "05077674a21861944f7b1ef944afc1fd89f9bc22", "size": "4525", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "docs/Xadow_GPS.md", "mode": "33188", "license": "bsd-2-clause", "language": [ { "name": "CSS", "bytes": "249062" }, { "name": "HTML", "bytes": "125860" }, { "name": "JavaScript", "bytes": "19949" }, { "name": "Python", "bytes": "198078" }, { "name": "Shell", "bytes": "670" } ], "symlink_target": "" }
module.exports = function(grunt) { var relations = function(basepath){ var path = require("path"); var fs = require('fs'); var modulef = path.join(basepath, 'modules.json'); var modules = grunt.file.readJSON(modulef); var caches = []; for(var i in modules){ var module = modules[i]; if(typeof module == "string"){ var module_path = path.join.apply(this, [basepath].concat(module.split("."))); if(fs.existsSync(module_path + '.js')){ module_file = module_path + '.js'; if(caches.indexOf(module_file) == -1){ caches.push(module_file); } } else if(fs.existsSync(module_path)){ var modulefs = relations(module_path); for(var f in modulefs){ if(caches.indexOf(modulefs[f]) == -1){ caches.push(modulefs[f]); } } } } } return caches; }; "use strict"; // Project configuration. grunt.initConfig({ // Metadata. pkg: grunt.file.readJSON('package.json'), banner: '\n', // Task configuration. clean: { build: ['build'], }, concat: { js: { options: { banner: '<%= banner %>', stripBanners: false }, src: relations('src'), dest: 'build/<%= pkg.name %>.js' } }, uglify: { options: { banner: '<%= banner %>', report: 'min' }, crossflowui: { src: ['<%= concat.js.dest %>'], dest: 'build/<%= pkg.name %>.min.js' } } }); // These plugins provide necessary tasks. grunt.loadNpmTasks('grunt-contrib-clean'); grunt.loadNpmTasks('grunt-contrib-concat'); grunt.loadNpmTasks('grunt-contrib-uglify'); // JS distribution task. grunt.registerTask('build-js', ['concat', 'uglify']); // Full distribution task. grunt.registerTask('build', ['clean', 'build-js']); // Default task. grunt.registerTask('default', ['build']); };
{ "content_hash": "ee06cdbfdeb21a174321c8f3dbe1aebf", "timestamp": "", "source": "github", "line_count": 87, "max_line_length": 86, "avg_line_length": 23.057471264367816, "alnum_prop": 0.5304087736789631, "repo_name": "zxf/g3", "id": "9ac2a8be7ab0780d789ed450b8e466e9f471a37b", "size": "2163", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "Gruntfile.js", "mode": "33188", "license": "mit", "language": [ { "name": "JavaScript", "bytes": "73602" }, { "name": "Python", "bytes": "1151" } ], "symlink_target": "" }
// Template Source: BaseEntityRequest.java.tt // ------------------------------------------------------------------------------ // Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information. // ------------------------------------------------------------------------------ package com.microsoft.graph.requests; import com.microsoft.graph.http.IRequestBuilder; import com.microsoft.graph.core.ClientException; import com.microsoft.graph.models.EducationSubmissionResource; import java.util.Arrays; import java.util.EnumSet; import javax.annotation.Nullable; import javax.annotation.Nonnull; import com.microsoft.graph.core.IBaseClient; import com.microsoft.graph.http.BaseRequest; import com.microsoft.graph.http.HttpMethod; // **NOTE** This file was generated by a tool and any changes will be overwritten. /** * The class for the Education Submission Resource Request. */ public class EducationSubmissionResourceRequest extends BaseRequest<EducationSubmissionResource> { /** * The request for the EducationSubmissionResource * * @param requestUrl the request URL * @param client the service client * @param requestOptions the options for this request */ public EducationSubmissionResourceRequest(@Nonnull final String requestUrl, @Nonnull final IBaseClient<?> client, @Nullable final java.util.List<? extends com.microsoft.graph.options.Option> requestOptions) { super(requestUrl, client, requestOptions, EducationSubmissionResource.class); } /** * Gets the EducationSubmissionResource from the service * * @return a future with the result */ @Nonnull public java.util.concurrent.CompletableFuture<EducationSubmissionResource> getAsync() { return sendAsync(HttpMethod.GET, null); } /** * Gets the EducationSubmissionResource from the service * * @return the EducationSubmissionResource from the request * @throws ClientException this exception occurs if the request was unable to complete for any reason */ @Nullable public EducationSubmissionResource get() throws ClientException { return send(HttpMethod.GET, null); } /** * Delete this item from the service * * @return a future with the deletion result */ @Nonnull public java.util.concurrent.CompletableFuture<EducationSubmissionResource> deleteAsync() { return sendAsync(HttpMethod.DELETE, null); } /** * Delete this item from the service * @return the resulting response if the service returns anything on deletion * * @throws ClientException if there was an exception during the delete operation */ @Nullable public EducationSubmissionResource delete() throws ClientException { return send(HttpMethod.DELETE, null); } /** * Patches this EducationSubmissionResource with a source * * @param sourceEducationSubmissionResource the source object with updates * @return a future with the result */ @Nonnull public java.util.concurrent.CompletableFuture<EducationSubmissionResource> patchAsync(@Nonnull final EducationSubmissionResource sourceEducationSubmissionResource) { return sendAsync(HttpMethod.PATCH, sourceEducationSubmissionResource); } /** * Patches this EducationSubmissionResource with a source * * @param sourceEducationSubmissionResource the source object with updates * @return the updated EducationSubmissionResource * @throws ClientException this exception occurs if the request was unable to complete for any reason */ @Nullable public EducationSubmissionResource patch(@Nonnull final EducationSubmissionResource sourceEducationSubmissionResource) throws ClientException { return send(HttpMethod.PATCH, sourceEducationSubmissionResource); } /** * Creates a EducationSubmissionResource with a new object * * @param newEducationSubmissionResource the new object to create * @return a future with the result */ @Nonnull public java.util.concurrent.CompletableFuture<EducationSubmissionResource> postAsync(@Nonnull final EducationSubmissionResource newEducationSubmissionResource) { return sendAsync(HttpMethod.POST, newEducationSubmissionResource); } /** * Creates a EducationSubmissionResource with a new object * * @param newEducationSubmissionResource the new object to create * @return the created EducationSubmissionResource * @throws ClientException this exception occurs if the request was unable to complete for any reason */ @Nullable public EducationSubmissionResource post(@Nonnull final EducationSubmissionResource newEducationSubmissionResource) throws ClientException { return send(HttpMethod.POST, newEducationSubmissionResource); } /** * Creates a EducationSubmissionResource with a new object * * @param newEducationSubmissionResource the object to create/update * @return a future with the result */ @Nonnull public java.util.concurrent.CompletableFuture<EducationSubmissionResource> putAsync(@Nonnull final EducationSubmissionResource newEducationSubmissionResource) { return sendAsync(HttpMethod.PUT, newEducationSubmissionResource); } /** * Creates a EducationSubmissionResource with a new object * * @param newEducationSubmissionResource the object to create/update * @return the created EducationSubmissionResource * @throws ClientException this exception occurs if the request was unable to complete for any reason */ @Nullable public EducationSubmissionResource put(@Nonnull final EducationSubmissionResource newEducationSubmissionResource) throws ClientException { return send(HttpMethod.PUT, newEducationSubmissionResource); } /** * Sets the select clause for the request * * @param value the select clause * @return the updated request */ @Nonnull public EducationSubmissionResourceRequest select(@Nonnull final String value) { addSelectOption(value); return this; } /** * Sets the expand clause for the request * * @param value the expand clause * @return the updated request */ @Nonnull public EducationSubmissionResourceRequest expand(@Nonnull final String value) { addExpandOption(value); return this; } }
{ "content_hash": "51d5a2a8d2c5b58b548a41f0b3f154fb", "timestamp": "", "source": "github", "line_count": 173, "max_line_length": 212, "avg_line_length": 38.138728323699425, "alnum_prop": 0.7140042437102152, "repo_name": "microsoftgraph/msgraph-sdk-java", "id": "d1fcc392678defe914a0ea0188f0e1bb30f0aae8", "size": "6598", "binary": false, "copies": "1", "ref": "refs/heads/dev", "path": "src/main/java/com/microsoft/graph/requests/EducationSubmissionResourceRequest.java", "mode": "33188", "license": "mit", "language": [ { "name": "Java", "bytes": "27286837" }, { "name": "PowerShell", "bytes": "5635" } ], "symlink_target": "" }
/* ---------------------------------------------------------------------------- */ /* Atmel Microcontroller Software Support */ /* SAM Software Package License */ /* ---------------------------------------------------------------------------- */ /* Copyright (c) 2015, Atmel Corporation */ /* */ /* All rights reserved. */ /* */ /* Redistribution and use in source and binary forms, with or without */ /* modification, are permitted provided that the following condition is met: */ /* */ /* - Redistributions of source code must retain the above copyright notice, */ /* this list of conditions and the disclaimer below. */ /* */ /* Atmel's name may not be used to endorse or promote products derived from */ /* this software without specific prior written permission. */ /* */ /* DISCLAIMER: THIS SOFTWARE IS PROVIDED BY ATMEL "AS IS" AND ANY EXPRESS OR */ /* IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF */ /* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT ARE */ /* DISCLAIMED. IN NO EVENT SHALL ATMEL BE LIABLE FOR ANY DIRECT, INDIRECT, */ /* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT */ /* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, */ /* OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF */ /* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING */ /* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, */ /* EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ /* ---------------------------------------------------------------------------- */ #ifndef _SAM4E_RTT_COMPONENT_ #define _SAM4E_RTT_COMPONENT_ /* ============================================================================= */ /** SOFTWARE API DEFINITION FOR Real-time Timer */ /* ============================================================================= */ /** \addtogroup SAM4E_RTT Real-time Timer */ /*@{*/ #if !(defined(__ASSEMBLY__) || defined(__IAR_SYSTEMS_ASM__)) /** \brief Rtt hardware registers */ typedef struct { __IO uint32_t RTT_MR; /**< \brief (Rtt Offset: 0x00) Mode Register */ __IO uint32_t RTT_AR; /**< \brief (Rtt Offset: 0x04) Alarm Register */ __I uint32_t RTT_VR; /**< \brief (Rtt Offset: 0x08) Value Register */ __I uint32_t RTT_SR; /**< \brief (Rtt Offset: 0x0C) Status Register */ } Rtt; #endif /* !(defined(__ASSEMBLY__) || defined(__IAR_SYSTEMS_ASM__)) */ /* -------- RTT_MR : (RTT Offset: 0x00) Mode Register -------- */ #define RTT_MR_RTPRES_Pos 0 #define RTT_MR_RTPRES_Msk (0xffffu << RTT_MR_RTPRES_Pos) /**< \brief (RTT_MR) Real-time Timer Prescaler Value */ #define RTT_MR_RTPRES(value) ((RTT_MR_RTPRES_Msk & ((value) << RTT_MR_RTPRES_Pos))) #define RTT_MR_ALMIEN (0x1u << 16) /**< \brief (RTT_MR) Alarm Interrupt Enable */ #define RTT_MR_RTTINCIEN (0x1u << 17) /**< \brief (RTT_MR) Real-time Timer Increment Interrupt Enable */ #define RTT_MR_RTTRST (0x1u << 18) /**< \brief (RTT_MR) Real-time Timer Restart */ #define RTT_MR_RTTDIS (0x1u << 20) /**< \brief (RTT_MR) Real-time Timer Disable */ #define RTT_MR_RTC1HZ (0x1u << 24) /**< \brief (RTT_MR) Real-Time Clock 1Hz Clock Selection */ /* -------- RTT_AR : (RTT Offset: 0x04) Alarm Register -------- */ #define RTT_AR_ALMV_Pos 0 #define RTT_AR_ALMV_Msk (0xffffffffu << RTT_AR_ALMV_Pos) /**< \brief (RTT_AR) Alarm Value */ #define RTT_AR_ALMV(value) ((RTT_AR_ALMV_Msk & ((value) << RTT_AR_ALMV_Pos))) /* -------- RTT_VR : (RTT Offset: 0x08) Value Register -------- */ #define RTT_VR_CRTV_Pos 0 #define RTT_VR_CRTV_Msk (0xffffffffu << RTT_VR_CRTV_Pos) /**< \brief (RTT_VR) Current Real-time Value */ /* -------- RTT_SR : (RTT Offset: 0x0C) Status Register -------- */ #define RTT_SR_ALMS (0x1u << 0) /**< \brief (RTT_SR) Real-time Alarm Status */ #define RTT_SR_RTTINC (0x1u << 1) /**< \brief (RTT_SR) Prescaler Roll-over Status */ /*@}*/ #endif /* _SAM4E_RTT_COMPONENT_ */
{ "content_hash": "f444fec461a8ed7d613958a376b2a4b7", "timestamp": "", "source": "github", "line_count": 71, "max_line_length": 112, "avg_line_length": 65.08450704225352, "alnum_prop": 0.5072495130924043, "repo_name": "AtmelUniversityFrance/SAMD21-XPRO", "id": "9b88dc674f750572ca5d443afcaee09ebceda82e", "size": "4621", "binary": false, "copies": "9", "ref": "refs/heads/master", "path": "Examples/CMSIS/Device/ATMEL/sam4e/include/component/rtt.h", "mode": "33188", "license": "bsd-2-clause", "language": [], "symlink_target": "" }
import {Observable} from 'rxjs'; export class WebSocketService{ ws: WebSocket; socketIsOpen = 1; // WebSocket's open createObservableSocket(url:string): Observable<any>{ this.ws = new WebSocket(url); return new Observable( observer => { this.ws.onmessage = (event) => observer.next(event.data); this.ws.onerror = (event) => observer.error(event); this.ws.onclose = (event) => observer.complete(); return () => { this.ws.close(1000, "The user disconnected"); } } ); } sendMessage(message: string): string{ if (this.ws.readyState === this.socketIsOpen) { this.ws.send(message); return `Sent to server ${message}`; } else { return 'Message was not sent - the socket is closed'; } } }
{ "content_hash": "7be1e55b270af3a57e0409e8e2f63e7c", "timestamp": "", "source": "github", "line_count": 37, "max_line_length": 59, "avg_line_length": 22.08108108108108, "alnum_prop": 0.5899632802937577, "repo_name": "Farata/angulartypescript", "id": "547fc8f948f29598b4efe13e18d073c22a8460c5", "size": "817", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "code-samples/Angular6/chapter13/client/src/app/wsservice/websocket.service.ts", "mode": "33261", "license": "mit", "language": [ { "name": "CSS", "bytes": "140384" }, { "name": "HTML", "bytes": "176662" }, { "name": "JavaScript", "bytes": "244230" }, { "name": "TypeScript", "bytes": "1647740" } ], "symlink_target": "" }
@extends('admin/app') @section('breadcrumb') {!! Breadcrumbs::render('menus', 'Menus') !!} @endsection @include('admin.partial._contentheader_title', [$model = new \App\Core\Models\Menu(), $message = "Amount of Menus"]) @section('contentheader_description') @include('admin.partial._content-head_btns', [$routeName = "admin::design::menus::create", $createBtn = 'Add New Menu']) <button class="btn pull-right" style="margin-bottom: 20px;" data-toggle="collapse" href="#info" aria-expanded="false" aria-controls="info"> <span class="fa fa-info"></span>info </button> @endsection @section('main-content') <div class="collapse" id="info"> <div class="alert alert-info"> <strong>How To Use:</strong> <p>You can get the menu by its own type on your site by calling <code>menu($menu->name, 'default')</code></p> <p class="text-mute"><b>types:</b> <span class="text-warning">'default'</span> <span class="divider"> || </span> <span class="text-warning">'navigation'</span> </p> </div> </div> <div class="box"> <div class="box-header"> <h3 class="box-title">List of Menus</h3> </div> <!-- /.box-header --> <div class="box-body"> <table id="menus-table" class="table table-bordered"> <thead> <tr> <thead> <th>Id</th> <th>Name</th> <th>Created At</th> <th>Updated At</th> <th class="text-center"><em class="fa fa-cog"></em> Actions</th> </tr> </thead> </table> </div> <!-- /.box-body --> </div> <div class="modal modal-danger fade" tabindex="-1" id="delete_modal" role="dialog"> <div class="modal-dialog"> <div class="modal-content"> <div class="modal-header"> <button type="button" class="close" data-dismiss="modal" aria-label="Close"> <span aria-hidden="true">&times;</span> </button> <h4 class="modal-title"> <i class="voyager-trash"></i> Are you sure you want to delete this <b>menu</b>? </h4> </div> <div class="modal-footer"> <form action="{{ route('admin::design::menus::index') }}" id="delete_form" method="POST"> {{ method_field("DELETE") }} {{ csrf_field() }} <input type="submit" class="btn btn-danger pull-right delete-confirm" value="Yes, Delete This Menu"> </form> <button type="button" class="btn btn-default pull-right" data-dismiss="modal">Cancel</button> </div> </div> </div> </div> @stop @section('scripts-add') <script> $(function () { $('#menus-table').DataTable({ serverSide: true, processing: true, ajax: "{{route('admin::design::menus::data')}}", stateSave: true, columns: [ {data: 'id'}, {data: 'name'}, { data: 'created_at', render: function (d) { return moment(d.date).fromNow(); } }, { data: 'updated_at', render: function (d) { return moment(d.date).fromNow(); } }, {data: 'action', orderable: false, searchable: false} ], fnInitComplete: function () { $('td').on('click', '.delete', function (e) { id = $(e.target).data('id'); $('#delete_form')[0].action += '/' + id; $('#delete_modal').modal('show'); }); } }); }); </script> @endsection
{ "content_hash": "dab7fc56a104feb5006dc2743fed56b9", "timestamp": "", "source": "github", "line_count": 107, "max_line_length": 124, "avg_line_length": 39.32710280373832, "alnum_prop": 0.4458174904942966, "repo_name": "storecamp/storecamp", "id": "fc23f28a891781b6fe45973b90b45bbd719b5cfa", "size": "4208", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "resources/views/admin/tools/menus/index.blade.php", "mode": "33188", "license": "mit", "language": [ { "name": "Batchfile", "bytes": "306" }, { "name": "CSS", "bytes": "106542" }, { "name": "CoffeeScript", "bytes": "67001" }, { "name": "HTML", "bytes": "2389201" }, { "name": "JavaScript", "bytes": "2020" }, { "name": "PHP", "bytes": "1472645" } ], "symlink_target": "" }
require 'rails_helper' RSpec.describe PropertiesController, type: :controller do # let(:agency_id) { @agency_id = 1} # describe "GET #index" do # it "returns http success" do # get agency_properties_path(:agency_id) # expect(response).to have_http_status(:success) # end # end # # describe "GET #show" do # it "returns http success" do # get :show # expect(response).to have_http_status(:success) # end # end end
{ "content_hash": "1bd419e9d9352e068b916bda1d99a024", "timestamp": "", "source": "github", "line_count": 20, "max_line_length": 57, "avg_line_length": 23.4, "alnum_prop": 0.6260683760683761, "repo_name": "sumonsm/RealEstatePropertyListingApp", "id": "ef16c495d704e1ec2500a69b40644d0feef6b719", "size": "468", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "spec/controllers/properties_controller_spec.rb", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "3348" }, { "name": "CoffeeScript", "bytes": "633" }, { "name": "HTML", "bytes": "11677" }, { "name": "JavaScript", "bytes": "691" }, { "name": "Ruby", "bytes": "48284" } ], "symlink_target": "" }
layout: base --- <!-- Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with this work for additional information regarding copyright ownership. The ASF licenses this file to you 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. --> {% assign active_pages = site.array %} {% assign active = page %} {% for i in (1..10) %} {% assign active_pages = active_pages | push: active %} {% if active.nav-parent_id %} {% assign next = site.pages_by_language[page.language] | where: "nav-id" , active.nav-parent_id %} {% if next.size > 0 %} {% assign active = next[0] %} {% else %} {% break %} {% endif %} {% else %} {% break %} {% endif %} {% endfor %} {% assign active_pages = active_pages | reverse %} <ol class="breadcrumb"> {% for p in active_pages %} {% capture title %}{% if p.nav-title %}{{ p.nav-title }}{% else %}{{ p.title }}{% endif %}{% endcapture %} {% if forloop.last == true %} <li class="active">{{ title }}</li> {% elsif p.nav-show_overview %} <li><a href="{{ site.baseurl }}{{ p.url }}">{{ title }}</a></li> {% else %} <li>{{ title }}</li> {% endif %} {% endfor %} </ol> <h1>{{ page.title }}{% if page.is_beta %} <span class="beta">Beta</span>{% endif %}</h1> {% if site.show_outdated_warning %} <div class="alert alert-danger" role="alert"> {% if page.language == "en" %} <strong>This documentation is for an out-of-date version of Apache Flink. We recommend you use <a href="https://ci.apache.org/projects/flink/flink-docs-stable/">the latest stable version</a>.</strong> {% else if page.language == "zh" %} <strong>本文档是 Apache Flink 的旧版本。建议访问 <a href="https://ci.apache.org/projects/flink/flink-docs-stable/zh">最新的稳定版本</a>。</strong> {% endif %} </div> {% endif %} {{ content }} <div class="footer"> <a href="https://cwiki.apache.org/confluence/display/FLINK/Flink+Translation+Specifications" target="_blank"> {% if page.language == "zh" %} 想参与贡献翻译? {% else if page.language == "en" %} Want to contribute translation? {% endif %} </a> </div>
{ "content_hash": "8f989ff09d93537def1d0f24dfc57875", "timestamp": "", "source": "github", "line_count": 77, "max_line_length": 204, "avg_line_length": 33.935064935064936, "alnum_prop": 0.6460007654037505, "repo_name": "shaoxuan-wang/flink", "id": "10c5993a208aa520ec2fe2948bca17555e63a5e5", "size": "2675", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "docs/_layouts/plain.html", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Batchfile", "bytes": "4588" }, { "name": "CSS", "bytes": "57936" }, { "name": "Clojure", "bytes": "90539" }, { "name": "Dockerfile", "bytes": "10807" }, { "name": "FreeMarker", "bytes": "11851" }, { "name": "HTML", "bytes": "224454" }, { "name": "Java", "bytes": "46844396" }, { "name": "JavaScript", "bytes": "1829" }, { "name": "Makefile", "bytes": "5134" }, { "name": "Python", "bytes": "733285" }, { "name": "Scala", "bytes": "12596192" }, { "name": "Shell", "bytes": "461101" }, { "name": "TypeScript", "bytes": "243702" } ], "symlink_target": "" }
use pongo::ui::{Drawable, Ui}; use sdl2::pixels::Color; use sdl2::rect::Rect; use super::Resettable; pub struct Paddle { pub color: Color, pub initial_x: f32, // The initial x location. Stored so that we can reset the paddle. pub initial_y: f32, // The initial y location. Stored so that we can reset the paddle. pub x: f32, // x pixel coordinate of top left corner pub y: f32, // y pixel coordinate of top left corner pub width: f32, pub height: f32, pub speed: f32, // Speed in pixels per second. Never changes. pub speed_multiplier: f32 // Used to adjust the speed. } impl Paddle { pub fn new(color: Color, x: f32, y: f32, width: f32, height: f32, speed: f32) -> Paddle { let mut paddle = Paddle { color: color, initial_x: x, initial_y: y, x: x, y: y, width: width, height: height, speed: speed, speed_multiplier: 1.0 }; paddle.reset(); return paddle; } } impl Resettable for Paddle { fn reset(&mut self) { // Revert to the initial x and y coordinates. self.x = self.initial_x; self.y = self.initial_y; // Revert to initial speed by setting the multiplier back to 1. self.speed_multiplier = 1.; } } impl Drawable for Paddle { fn draw(&self, ui: &mut Ui) { ui.renderer.set_draw_color(self.color); ui.renderer.fill_rect(Rect::new_unwrap(self.x as i32, self.y as i32, self.width as u32, self.height as u32)); } }
{ "content_hash": "2e66023821d3ccf82ba643ad7f14b718", "timestamp": "", "source": "github", "line_count": 69, "max_line_length": 98, "avg_line_length": 26.72463768115942, "alnum_prop": 0.5010845986984815, "repo_name": "wickus/pongo", "id": "b5cdd151d37e19da9f58599f28c436e518444c13", "size": "1844", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/pongo/paddle.rs", "mode": "33188", "license": "mit", "language": [ { "name": "Rust", "bytes": "41461" } ], "symlink_target": "" }
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /><meta name="generator" content="Docutils 0.19: https://docutils.sourceforge.io/" /> <meta name="viewport" content="width=device-width,initial-scale=1"> <meta http-equiv="x-ua-compatible" content="ie=edge"> <meta name="lang:clipboard.copy" content="Copy to clipboard"> <meta name="lang:clipboard.copied" content="Copied to clipboard"> <meta name="lang:search.language" content="en"> <meta name="lang:search.pipeline.stopwords" content="True"> <meta name="lang:search.pipeline.trimmer" content="True"> <meta name="lang:search.result.none" content="No matching documents"> <meta name="lang:search.result.one" content="1 matching document"> <meta name="lang:search.result.other" content="# matching documents"> <meta name="lang:search.tokenizer" content="[\s\-]+"> <link href="https://fonts.gstatic.com/" rel="preconnect" crossorigin> <link href="https://fonts.googleapis.com/css?family=Roboto+Mono:400,500,700|Roboto:300,400,400i,700&display=fallback" rel="stylesheet"> <style> body, input { font-family: "Roboto", "Helvetica Neue", Helvetica, Arial, sans-serif } code, kbd, pre { font-family: "Roboto Mono", "Courier New", Courier, monospace } </style> <link rel="stylesheet" href="../_static/stylesheets/application.css"/> <link rel="stylesheet" href="../_static/stylesheets/application-palette.css"/> <link rel="stylesheet" href="../_static/stylesheets/application-fixes.css"/> <link rel="stylesheet" href="../_static/fonts/material-icons.css"/> <meta name="theme-color" content="#3f51b5"> <script src="../_static/javascripts/modernizr.js"></script> <title>statsmodels.tsa.statespace.simulation_smoother.SimulationSmoother.fixed_scale &#8212; statsmodels</title> <link rel="icon" type="image/png" sizes="32x32" href="../_static/icons/favicon-32x32.png"> <link rel="icon" type="image/png" sizes="16x16" href="../_static/icons/favicon-16x16.png"> <link rel="manifest" href="../_static/icons/site.webmanifest"> <link rel="mask-icon" href="../_static/icons/safari-pinned-tab.svg" color="#919191"> <meta name="msapplication-TileColor" content="#2b5797"> <meta name="msapplication-config" content="../_static/icons/browserconfig.xml"> <link rel="stylesheet" href="../_static/stylesheets/examples.css"> <link rel="stylesheet" href="../_static/stylesheets/deprecation.css"> <link rel="stylesheet" type="text/css" href="../_static/pygments.css" /> <link rel="stylesheet" type="text/css" href="../_static/material.css" /> <link rel="stylesheet" type="text/css" href="../_static/graphviz.css" /> <link rel="stylesheet" type="text/css" href="../_static/plot_directive.css" /> <script data-url_root="../" id="documentation_options" src="../_static/documentation_options.js"></script> <script src="../_static/jquery.js"></script> <script src="../_static/underscore.js"></script> <script src="../_static/_sphinx_javascript_frameworks_compat.js"></script> <script src="../_static/doctools.js"></script> <script src="../_static/sphinx_highlight.js"></script> <script crossorigin="anonymous" integrity="sha256-Ae2Vz/4ePdIu6ZyI/5ZGsYnb+m0JlOmKPjt6XZ9JJkA=" src="https://cdnjs.cloudflare.com/ajax/libs/require.js/2.3.4/require.min.js"></script> <link rel="shortcut icon" href="../_static/favicon.ico"/> <link rel="author" title="About these documents" href="../about.html" /> <link rel="index" title="Index" href="../genindex.html" /> <link rel="search" title="Search" href="../search.html" /> <link rel="next" title="statsmodels.tsa.statespace.simulation_smoother.SimulationSmoother.get_simulation_output" href="statsmodels.tsa.statespace.simulation_smoother.SimulationSmoother.get_simulation_output.html" /> <link rel="prev" title="statsmodels.tsa.statespace.simulation_smoother.SimulationSmoother.filter" href="statsmodels.tsa.statespace.simulation_smoother.SimulationSmoother.filter.html" /> </head> <body dir=ltr data-md-color-primary=indigo data-md-color-accent=blue> <svg class="md-svg"> <defs data-children-count="0"> <svg xmlns="http://www.w3.org/2000/svg" width="416" height="448" viewBox="0 0 416 448" id="__github"><path fill="currentColor" d="M160 304q0 10-3.125 20.5t-10.75 19T128 352t-18.125-8.5-10.75-19T96 304t3.125-20.5 10.75-19T128 256t18.125 8.5 10.75 19T160 304zm160 0q0 10-3.125 20.5t-10.75 19T288 352t-18.125-8.5-10.75-19T256 304t3.125-20.5 10.75-19T288 256t18.125 8.5 10.75 19T320 304zm40 0q0-30-17.25-51T296 232q-10.25 0-48.75 5.25Q229.5 240 208 240t-39.25-2.75Q130.75 232 120 232q-29.5 0-46.75 21T56 304q0 22 8 38.375t20.25 25.75 30.5 15 35 7.375 37.25 1.75h42q20.5 0 37.25-1.75t35-7.375 30.5-15 20.25-25.75T360 304zm56-44q0 51.75-15.25 82.75-9.5 19.25-26.375 33.25t-35.25 21.5-42.5 11.875-42.875 5.5T212 416q-19.5 0-35.5-.75t-36.875-3.125-38.125-7.5-34.25-12.875T37 371.5t-21.5-28.75Q0 312 0 260q0-59.25 34-99-6.75-20.5-6.75-42.5 0-29 12.75-54.5 27 0 47.5 9.875t47.25 30.875Q171.5 96 212 96q37 0 70 8 26.25-20.5 46.75-30.25T376 64q12.75 25.5 12.75 54.5 0 21.75-6.75 42 34 40 34 99.5z"/></svg> </defs> </svg> <input class="md-toggle" data-md-toggle="drawer" type="checkbox" id="__drawer"> <input class="md-toggle" data-md-toggle="search" type="checkbox" id="__search"> <label class="md-overlay" data-md-component="overlay" for="__drawer"></label> <a href="#generated/statsmodels.tsa.statespace.simulation_smoother.SimulationSmoother.fixed_scale" tabindex="1" class="md-skip"> Skip to content </a> <header class="md-header" data-md-component="header"> <nav class="md-header-nav md-grid"> <div class="md-flex navheader"> <div class="md-flex__cell md-flex__cell--shrink"> <a href="../index.html" title="statsmodels" class="md-header-nav__button md-logo"> <img src="../_static/statsmodels-logo-v2-bw.svg" height="26" alt="statsmodels logo"> </a> </div> <div class="md-flex__cell md-flex__cell--shrink"> <label class="md-icon md-icon--menu md-header-nav__button" for="__drawer"></label> </div> <div class="md-flex__cell md-flex__cell--stretch"> <div class="md-flex__ellipsis md-header-nav__title" data-md-component="title"> <span class="md-header-nav__topic">statsmodels 0.13.5</span> <span class="md-header-nav__topic"> statsmodels.tsa.statespace.simulation_smoother.SimulationSmoother.fixed_scale </span> </div> </div> <div class="md-flex__cell md-flex__cell--shrink"> <label class="md-icon md-icon--search md-header-nav__button" for="__search"></label> <div class="md-search" data-md-component="search" role="dialog"> <label class="md-search__overlay" for="__search"></label> <div class="md-search__inner" role="search"> <form class="md-search__form" action="../search.html" method="get" name="search"> <input type="text" class="md-search__input" name="q" placeholder="Search" autocapitalize="off" autocomplete="off" spellcheck="false" data-md-component="query" data-md-state="active"> <label class="md-icon md-search__icon" for="__search"></label> <button type="reset" class="md-icon md-search__icon" data-md-component="reset" tabindex="-1"> &#xE5CD; </button> </form> <div class="md-search__output"> <div class="md-search__scrollwrap" data-md-scrollfix> <div class="md-search-result" data-md-component="result"> <div class="md-search-result__meta"> Type to start searching </div> <ol class="md-search-result__list"></ol> </div> </div> </div> </div> </div> </div> <div class="md-flex__cell md-flex__cell--shrink"> <div class="md-header-nav__source"> <a href="https://github.com/statsmodels/statsmodels" title="Go to repository" class="md-source" data-md-source="github"> <div class="md-source__icon"> <svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" viewBox="0 0 24 24" width="28" height="28"> <use xlink:href="#__github" width="24" height="24"></use> </svg> </div> <div class="md-source__repository"> statsmodels </div> </a> </div> </div> <script src="../_static/javascripts/version_dropdown.js"></script> <script> var json_loc = "../../versions-v2.json", target_loc = "../../", text = "Versions"; $( document ).ready( add_version_dropdown(json_loc, target_loc, text)); </script> </div> </nav> </header> <div class="md-container"> <nav class="md-tabs" data-md-component="tabs"> <div class="md-tabs__inner md-grid"> <ul class="md-tabs__list"> <li class="md-tabs__item"><a href="../user-guide.html" class="md-tabs__link">User Guide</a></li> <li class="md-tabs__item"><a href="../statespace.html" class="md-tabs__link">Time Series Analysis by State Space Methods <code class="xref py py-mod docutils literal notranslate"><span class="pre">statespace</span></code></a></li> <li class="md-tabs__item"><a href="statsmodels.tsa.statespace.simulation_smoother.SimulationSmoother.html" class="md-tabs__link">statsmodels.tsa.statespace.simulation_smoother.SimulationSmoother</a></li> </ul> </div> </nav> <main class="md-main"> <div class="md-main__inner md-grid" data-md-component="container"> <div class="md-sidebar md-sidebar--primary" data-md-component="navigation"> <div class="md-sidebar__scrollwrap"> <div class="md-sidebar__inner"> <nav class="md-nav md-nav--primary" data-md-level="0"> <label class="md-nav__title md-nav__title--site" for="__drawer"> <a href="../index.html" title="statsmodels" class="md-nav__button md-logo"> <img src="../_static/statsmodels-logo-v2-bw.svg" alt=" logo" width="48" height="48"> </a> <a href="../index.html" title="statsmodels">statsmodels 0.13.5</a> </label> <div class="md-nav__source"> <a href="https://github.com/statsmodels/statsmodels" title="Go to repository" class="md-source" data-md-source="github"> <div class="md-source__icon"> <svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" viewBox="0 0 24 24" width="28" height="28"> <use xlink:href="#__github" width="24" height="24"></use> </svg> </div> <div class="md-source__repository"> statsmodels </div> </a> </div> <ul class="md-nav__list"> <li class="md-nav__item"> <a href="../install.html" class="md-nav__link">Installing statsmodels</a> </li> <li class="md-nav__item"> <a href="../gettingstarted.html" class="md-nav__link">Getting started</a> </li> <li class="md-nav__item"> <a href="../user-guide.html" class="md-nav__link">User Guide</a> <ul class="md-nav__list"> <li class="md-nav__item"> <a href="../user-guide.html#background" class="md-nav__link">Background</a> </li> <li class="md-nav__item"> <a href="../user-guide.html#regression-and-linear-models" class="md-nav__link">Regression and Linear Models</a> </li> <li class="md-nav__item"> <a href="../user-guide.html#time-series-analysis" class="md-nav__link">Time Series Analysis</a> <ul class="md-nav__list"> <li class="md-nav__item"> <a href="../tsa.html" class="md-nav__link">Time Series analysis <code class="xref py py-mod docutils literal notranslate"><span class="pre">tsa</span></code></a> </li> <li class="md-nav__item"> <a href="../statespace.html" class="md-nav__link">Time Series Analysis by State Space Methods <code class="xref py py-mod docutils literal notranslate"><span class="pre">statespace</span></code></a> </li> <li class="md-nav__item"> <a href="../vector_ar.html" class="md-nav__link">Vector Autoregressions <code class="xref py py-mod docutils literal notranslate"><span class="pre">tsa.vector_ar</span></code></a> </li></ul> </li> <li class="md-nav__item"> <a href="../user-guide.html#other-models" class="md-nav__link">Other Models</a> </li> <li class="md-nav__item"> <a href="../user-guide.html#statistics-and-tools" class="md-nav__link">Statistics and Tools</a> </li> <li class="md-nav__item"> <a href="../user-guide.html#data-sets" class="md-nav__link">Data Sets</a> </li> <li class="md-nav__item"> <a href="../user-guide.html#sandbox" class="md-nav__link">Sandbox</a> </li></ul> </li> <li class="md-nav__item"> <a href="../examples/index.html" class="md-nav__link">Examples</a> </li> <li class="md-nav__item"> <a href="../api.html" class="md-nav__link">API Reference</a> </li> <li class="md-nav__item"> <a href="../about.html" class="md-nav__link">About statsmodels</a> </li> <li class="md-nav__item"> <a href="../dev/index.html" class="md-nav__link">Developer Page</a> </li> <li class="md-nav__item"> <a href="../release/index.html" class="md-nav__link">Release Notes</a> </li> </ul> </nav> </div> </div> </div> <div class="md-sidebar md-sidebar--secondary" data-md-component="toc"> <div class="md-sidebar__scrollwrap"> <div class="md-sidebar__inner"> <nav class="md-nav md-nav--secondary"> <label class="md-nav__title" for="__toc">Contents</label> <ul class="md-nav__list" data-md-scrollfix=""> <li class="md-nav__item"><a href="#generated-statsmodels-tsa-statespace-simulation-smoother-simulationsmoother-fixed-scale--page-root" class="md-nav__link">statsmodels.tsa.statespace.simulation_smoother.SimulationSmoother.fixed_scale</a><nav class="md-nav"> <ul class="md-nav__list"> <li class="md-nav__item"><a href="#statsmodels.tsa.statespace.simulation_smoother.SimulationSmoother.fixed_scale" class="md-nav__link"><code class="docutils literal notranslate"><span class="pre">SimulationSmoother.fixed_scale</span></code></a> </li></ul> </nav> </li> <li class="md-nav__item"><a class="md-nav__extra_link" href="../_sources/generated/statsmodels.tsa.statespace.simulation_smoother.SimulationSmoother.fixed_scale.rst.txt">Show Source</a> </li> <li id="searchbox" class="md-nav__item"></li> </ul> </nav> </div> </div> </div> <div class="md-content"> <article class="md-content__inner md-typeset" role="main"> <section id="statsmodels-tsa-statespace-simulation-smoother-simulationsmoother-fixed-scale"> <h1 id="generated-statsmodels-tsa-statespace-simulation-smoother-simulationsmoother-fixed-scale--page-root">statsmodels.tsa.statespace.simulation_smoother.SimulationSmoother.fixed_scale<a class="headerlink" href="#generated-statsmodels-tsa-statespace-simulation-smoother-simulationsmoother-fixed-scale--page-root" title="Permalink to this heading">¶</a></h1> <dl class="py method"> <dt class="sig sig-object py" id="statsmodels.tsa.statespace.simulation_smoother.SimulationSmoother.fixed_scale"> <span class="sig-prename descclassname"><span class="pre">SimulationSmoother.</span></span><span class="sig-name descname"><span class="pre">fixed_scale</span></span><span class="sig-paren">(</span><em class="sig-param"><span class="n"><span class="pre">scale</span></span></em><span class="sig-paren">)</span><a class="headerlink" href="#statsmodels.tsa.statespace.simulation_smoother.SimulationSmoother.fixed_scale" title="Permalink to this definition">¶</a></dt> <dd><p>Context manager for fixing the scale when FILTER_CONCENTRATED is set</p> <dl class="field-list"> <dt class="field-odd">Parameters<span class="colon">:</span></dt> <dd class="field-odd"><dl> <dt><strong>scale</strong><span class="classifier"><code class="xref py py-obj docutils literal notranslate"><span class="pre">numeric</span></code></span></dt><dd><p>Scale of the model.</p> </dd> </dl> </dd> </dl> <p class="rubric">Notes</p> <p>This a no-op if scale is None.</p> <p>This context manager is most useful in models which are explicitly concentrating out the scale, so that the set of parameters they are estimating does not include the scale.</p> </dd></dl> </section> </article> </div> </div> </main> </div> <footer class="md-footer"> <div class="md-footer-nav"> <nav class="md-footer-nav__inner md-grid"> <a href="statsmodels.tsa.statespace.simulation_smoother.SimulationSmoother.filter.html" title="statsmodels.tsa.statespace.simulation_smoother.SimulationSmoother.filter" class="md-flex md-footer-nav__link md-footer-nav__link--prev" rel="prev"> <div class="md-flex__cell md-flex__cell--shrink"> <i class="md-icon md-icon--arrow-back md-footer-nav__button"></i> </div> <div class="md-flex__cell md-flex__cell--stretch md-footer-nav__title"> <span class="md-flex__ellipsis"> <span class="md-footer-nav__direction"> Previous </span> statsmodels.tsa.statespace.simulation_smoother.SimulationSmoother.filter </span> </div> </a> <a href="statsmodels.tsa.statespace.simulation_smoother.SimulationSmoother.get_simulation_output.html" title="statsmodels.tsa.statespace.simulation_smoother.SimulationSmoother.get_simulation_output" class="md-flex md-footer-nav__link md-footer-nav__link--next" rel="next"> <div class="md-flex__cell md-flex__cell--stretch md-footer-nav__title"><span class="md-flex__ellipsis"> <span class="md-footer-nav__direction"> Next </span> statsmodels.tsa.statespace.simulation_smoother.SimulationSmoother.get_simulation_output </span> </div> <div class="md-flex__cell md-flex__cell--shrink"><i class="md-icon md-icon--arrow-forward md-footer-nav__button"></i> </div> </a> </nav> </div> <div class="md-footer-meta md-typeset"> <div class="md-footer-meta__inner md-grid"> <div class="md-footer-copyright"> <div class="md-footer-copyright__highlight"> &#169; Copyright 2009-2019, Josef Perktold, Skipper Seabold, Jonathan Taylor, statsmodels-developers. </div> Last updated on Nov 02, 2022. <br/> Created using <a href="http://www.sphinx-doc.org/">Sphinx</a> 5.3.0. and <a href="https://github.com/bashtage/sphinx-material/">Material for Sphinx</a> </div> </div> </div> </footer> <script src="../_static/javascripts/application.js"></script> <script>app.initialize({version: "1.0.4", url: {base: ".."}})</script> </body> </html>
{ "content_hash": "db8bd97c5a94161b232419f9648e6d29", "timestamp": "", "source": "github", "line_count": 470, "max_line_length": 999, "avg_line_length": 42.11063829787234, "alnum_prop": 0.6192400970088925, "repo_name": "statsmodels/statsmodels.github.io", "id": "9cee06f53c64346cd453c23e99f63e3bb07ffaa8", "size": "19796", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "v0.13.5/generated/statsmodels.tsa.statespace.simulation_smoother.SimulationSmoother.fixed_scale.html", "mode": "33188", "license": "bsd-3-clause", "language": [], "symlink_target": "" }
#ifndef SAMPLES_MOBILENETV1_H #define SAMPLES_MOBILENETV1_H #include <stdint.h> typedef struct { int best_idx; int best_out; } MobilenetV1Output; #endif
{ "content_hash": "4ca32261190ec44c69f33565cfc6bca2", "timestamp": "", "source": "github", "line_count": 13, "max_line_length": 29, "avg_line_length": 12.76923076923077, "alnum_prop": 0.7168674698795181, "repo_name": "AmbiML/iree-rv32-springbok", "id": "d51194698dde6503da5566dd1f53e9c1bf0d43bc", "size": "760", "binary": false, "copies": "1", "ref": "refs/heads/main", "path": "samples/quant_model/mobilenet_v1.h", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Assembly", "bytes": "8816" }, { "name": "C", "bytes": "6864" }, { "name": "C#", "bytes": "21130" }, { "name": "C++", "bytes": "13090" }, { "name": "CMake", "bytes": "30616" }, { "name": "Python", "bytes": "18052" }, { "name": "Shell", "bytes": "4870" } ], "symlink_target": "" }
package org.elasticsearch.index.mapper; import com.google.common.collect.Sets; import org.apache.lucene.document.Field; import org.apache.lucene.index.IndexOptions; import org.apache.lucene.index.IndexableField; import org.apache.lucene.util.CloseableThreadLocal; import org.elasticsearch.Version; import org.elasticsearch.common.Strings; import org.elasticsearch.common.joda.FormatDateTimeFormatter; import org.elasticsearch.common.settings.Settings; import org.elasticsearch.common.util.concurrent.ReleasableLock; import org.elasticsearch.common.xcontent.XContentBuilder; import org.elasticsearch.common.xcontent.XContentFactory; import org.elasticsearch.common.xcontent.XContentHelper; import org.elasticsearch.common.xcontent.XContentParser; import org.elasticsearch.index.mapper.core.NumberFieldMapper; import org.elasticsearch.index.mapper.core.StringFieldMapper; import org.elasticsearch.index.mapper.core.DateFieldMapper.DateFieldType; import org.elasticsearch.index.mapper.core.StringFieldMapper.StringFieldType; import org.elasticsearch.index.mapper.internal.TypeFieldMapper; import org.elasticsearch.index.mapper.internal.UidFieldMapper; import org.elasticsearch.index.mapper.object.ArrayValueMapperParser; import org.elasticsearch.index.mapper.object.ObjectMapper; import org.elasticsearch.index.mapper.object.RootObjectMapper; import org.elasticsearch.percolator.PercolatorService; import java.io.Closeable; import java.io.IOException; import java.util.Collections; import java.util.List; import java.util.Map; import java.util.Set; /** A parser for documents, given mappings from a DocumentMapper */ class DocumentParser implements Closeable { private CloseableThreadLocal<ParseContext.InternalParseContext> cache = new CloseableThreadLocal<ParseContext.InternalParseContext>() { @Override protected ParseContext.InternalParseContext initialValue() { return new ParseContext.InternalParseContext(indexSettings, docMapperParser, docMapper, new ContentPath(0)); } }; private final Settings indexSettings; private final DocumentMapperParser docMapperParser; private final DocumentMapper docMapper; private final ReleasableLock parseLock; public DocumentParser(Settings indexSettings, DocumentMapperParser docMapperParser, DocumentMapper docMapper, ReleasableLock parseLock) { this.indexSettings = indexSettings; this.docMapperParser = docMapperParser; this.docMapper = docMapper; this.parseLock = parseLock; } public ParsedDocument parseDocument(SourceToParse source) throws MapperParsingException { try (ReleasableLock lock = parseLock.acquire()){ return innerParseDocument(source); } } private ParsedDocument innerParseDocument(SourceToParse source) throws MapperParsingException { ParseContext.InternalParseContext context = cache.get(); final Mapping mapping = docMapper.mapping(); if (source.type() != null && !source.type().equals(docMapper.type())) { throw new MapperParsingException("Type mismatch, provide type [" + source.type() + "] but mapper is of type [" + docMapper.type() + "]"); } source.type(docMapper.type()); XContentParser parser = source.parser(); try { if (parser == null) { parser = XContentHelper.createParser(source.source()); } if (mapping.sourceTransforms.length > 0) { parser = transform(mapping, parser); } context.reset(parser, new ParseContext.Document(), source); // will result in START_OBJECT XContentParser.Token token = parser.nextToken(); if (token != XContentParser.Token.START_OBJECT) { throw new MapperParsingException("Malformed content, must start with an object"); } if (mapping.root.isEnabled()) { boolean emptyDoc = false; token = parser.nextToken(); if (token == XContentParser.Token.END_OBJECT) { // empty doc, we can handle it... emptyDoc = true; } else if (token != XContentParser.Token.FIELD_NAME) { throw new MapperParsingException("Malformed content, after first object, either the type field or the actual properties should exist"); } for (MetadataFieldMapper metadataMapper : mapping.metadataMappers) { metadataMapper.preParse(context); } if (emptyDoc == false) { Mapper update = parseObject(context, mapping.root); if (update != null) { context.addDynamicMappingsUpdate(update); } } for (MetadataFieldMapper metadataMapper : mapping.metadataMappers) { metadataMapper.postParse(context); } } else { // entire type is disabled parser.skipChildren(); } // try to parse the next token, this should be null if the object is ended properly // but will throw a JSON exception if the extra tokens is not valid JSON (this will be handled by the catch) if (Version.indexCreated(indexSettings).onOrAfter(Version.V_2_0_0_beta1) && source.parser() == null && parser != null) { // only check for end of tokens if we created the parser here token = parser.nextToken(); if (token != null) { throw new IllegalArgumentException("Malformed content, found extra data after parsing: " + token); } } } catch (Throwable e) { // if its already a mapper parsing exception, no need to wrap it... if (e instanceof MapperParsingException) { throw (MapperParsingException) e; } // Throw a more meaningful message if the document is empty. if (source.source() != null && source.source().length() == 0) { throw new MapperParsingException("failed to parse, document is empty"); } throw new MapperParsingException("failed to parse", e); } finally { // only close the parser when its not provided externally if (source.parser() == null && parser != null) { parser.close(); } } // reverse the order of docs for nested docs support, parent should be last if (context.docs().size() > 1) { Collections.reverse(context.docs()); } // apply doc boost if (context.docBoost() != 1.0f) { Set<String> encounteredFields = Sets.newHashSet(); for (ParseContext.Document doc : context.docs()) { encounteredFields.clear(); for (IndexableField field : doc) { if (field.fieldType().indexOptions() != IndexOptions.NONE && !field.fieldType().omitNorms()) { if (!encounteredFields.contains(field.name())) { ((Field) field).setBoost(context.docBoost() * field.boost()); encounteredFields.add(field.name()); } } } } } Mapper rootDynamicUpdate = context.dynamicMappingsUpdate(); Mapping update = null; if (rootDynamicUpdate != null) { update = mapping.mappingUpdate(rootDynamicUpdate); } ParsedDocument doc = new ParsedDocument(context.uid(), context.version(), context.id(), context.type(), source.routing(), source.timestamp(), source.ttl(), context.docs(), context.source(), update).parent(source.parent()); // reset the context to free up memory context.reset(null, null, null); return doc; } static ObjectMapper parseObject(ParseContext context, ObjectMapper mapper) throws IOException { if (mapper.isEnabled() == false) { context.parser().skipChildren(); return null; } XContentParser parser = context.parser(); String currentFieldName = parser.currentName(); XContentParser.Token token = parser.currentToken(); if (token == XContentParser.Token.VALUE_NULL) { // the object is null ("obj1" : null), simply bail return null; } if (token.isValue()) { throw new MapperParsingException("object mapping for [" + mapper.name() + "] tried to parse field [" + currentFieldName + "] as object, but found a concrete value"); } ObjectMapper.Nested nested = mapper.nested(); if (nested.isNested()) { context = context.createNestedContext(mapper.fullPath()); ParseContext.Document nestedDoc = context.doc(); ParseContext.Document parentDoc = nestedDoc.getParent(); // pre add the uid field if possible (id was already provided) IndexableField uidField = parentDoc.getField(UidFieldMapper.NAME); if (uidField != null) { // we don't need to add it as a full uid field in nested docs, since we don't need versioning // we also rely on this for UidField#loadVersion // this is a deeply nested field nestedDoc.add(new Field(UidFieldMapper.NAME, uidField.stringValue(), UidFieldMapper.Defaults.NESTED_FIELD_TYPE)); } // the type of the nested doc starts with __, so we can identify that its a nested one in filters // note, we don't prefix it with the type of the doc since it allows us to execute a nested query // across types (for example, with similar nested objects) nestedDoc.add(new Field(TypeFieldMapper.NAME, mapper.nestedTypePathAsString(), TypeFieldMapper.Defaults.FIELD_TYPE)); } ContentPath.Type origPathType = context.path().pathType(); context.path().pathType(mapper.pathType()); // if we are at the end of the previous object, advance if (token == XContentParser.Token.END_OBJECT) { token = parser.nextToken(); } if (token == XContentParser.Token.START_OBJECT) { // if we are just starting an OBJECT, advance, this is the object we are parsing, we need the name first token = parser.nextToken(); } ObjectMapper update = null; while (token != XContentParser.Token.END_OBJECT) { ObjectMapper newUpdate = null; if (token == XContentParser.Token.START_OBJECT) { newUpdate = parseObject(context, mapper, currentFieldName); } else if (token == XContentParser.Token.START_ARRAY) { newUpdate = parseArray(context, mapper, currentFieldName); } else if (token == XContentParser.Token.FIELD_NAME) { currentFieldName = parser.currentName(); } else if (token == XContentParser.Token.VALUE_NULL) { parseNullValue(context, mapper, currentFieldName); } else if (token == null) { throw new MapperParsingException("object mapping for [" + mapper.name() + "] tried to parse field [" + currentFieldName + "] as object, but got EOF, has a concrete value been provided to it?"); } else if (token.isValue()) { newUpdate = parseValue(context, mapper, currentFieldName, token); } token = parser.nextToken(); if (newUpdate != null) { if (update == null) { update = newUpdate; } else { MapperUtils.merge(update, newUpdate); } } } // restore the enable path flag context.path().pathType(origPathType); if (nested.isNested()) { ParseContext.Document nestedDoc = context.doc(); ParseContext.Document parentDoc = nestedDoc.getParent(); if (nested.isIncludeInParent()) { for (IndexableField field : nestedDoc.getFields()) { if (field.name().equals(UidFieldMapper.NAME) || field.name().equals(TypeFieldMapper.NAME)) { continue; } else { parentDoc.add(field); } } } if (nested.isIncludeInRoot()) { ParseContext.Document rootDoc = context.rootDoc(); // don't add it twice, if its included in parent, and we are handling the master doc... if (!nested.isIncludeInParent() || parentDoc != rootDoc) { for (IndexableField field : nestedDoc.getFields()) { if (field.name().equals(UidFieldMapper.NAME) || field.name().equals(TypeFieldMapper.NAME)) { continue; } else { rootDoc.add(field); } } } } } return update; } private static Mapper parseObjectOrField(ParseContext context, Mapper mapper) throws IOException { if (mapper instanceof ObjectMapper) { return parseObject(context, (ObjectMapper) mapper); } else { FieldMapper fieldMapper = (FieldMapper)mapper; Mapper update = fieldMapper.parse(context); if (fieldMapper.copyTo() != null) { parseCopyFields(context, fieldMapper, fieldMapper.copyTo().copyToFields()); } return update; } } private static ObjectMapper parseObject(final ParseContext context, ObjectMapper mapper, String currentFieldName) throws IOException { if (currentFieldName == null) { throw new MapperParsingException("object mapping [" + mapper.name() + "] trying to serialize an object with no field associated with it, current value [" + context.parser().textOrNull() + "]"); } context.path().add(currentFieldName); ObjectMapper update = null; Mapper objectMapper = mapper.getMapper(currentFieldName); if (objectMapper != null) { final Mapper subUpdate = parseObjectOrField(context, objectMapper); if (subUpdate != null) { // propagate mapping update update = mapper.mappingUpdate(subUpdate); } } else { ObjectMapper.Dynamic dynamic = mapper.dynamic(); if (dynamic == null) { dynamic = dynamicOrDefault(context.root().dynamic()); } if (dynamic == ObjectMapper.Dynamic.STRICT) { throw new StrictDynamicMappingException(mapper.fullPath(), currentFieldName); } else if (dynamic == ObjectMapper.Dynamic.TRUE) { // remove the current field name from path, since template search and the object builder add it as well... context.path().remove(); Mapper.Builder builder = context.root().findTemplateBuilder(context, currentFieldName, "object"); if (builder == null) { builder = MapperBuilders.object(currentFieldName).enabled(true).pathType(mapper.pathType()); // if this is a non root object, then explicitly set the dynamic behavior if set if (!(mapper instanceof RootObjectMapper) && mapper.dynamic() != ObjectMapper.Defaults.DYNAMIC) { ((ObjectMapper.Builder) builder).dynamic(mapper.dynamic()); } } Mapper.BuilderContext builderContext = new Mapper.BuilderContext(context.indexSettings(), context.path()); objectMapper = builder.build(builderContext); context.path().add(currentFieldName); update = mapper.mappingUpdate(parseAndMergeUpdate(objectMapper, context)); } else { // not dynamic, read everything up to end object context.parser().skipChildren(); } } context.path().remove(); return update; } private static ObjectMapper parseArray(ParseContext context, ObjectMapper parentMapper, String lastFieldName) throws IOException { String arrayFieldName = lastFieldName; Mapper mapper = parentMapper.getMapper(lastFieldName); if (mapper != null) { // There is a concrete mapper for this field already. Need to check if the mapper // expects an array, if so we pass the context straight to the mapper and if not // we serialize the array components if (mapper instanceof ArrayValueMapperParser) { final Mapper subUpdate = parseObjectOrField(context, mapper); if (subUpdate != null) { // propagate the mapping update return parentMapper.mappingUpdate(subUpdate); } else { return null; } } else { return parseNonDynamicArray(context, parentMapper, lastFieldName, arrayFieldName); } } else { ObjectMapper.Dynamic dynamic = parentMapper.dynamic(); if (dynamic == null) { dynamic = dynamicOrDefault(context.root().dynamic()); } if (dynamic == ObjectMapper.Dynamic.STRICT) { throw new StrictDynamicMappingException(parentMapper.fullPath(), arrayFieldName); } else if (dynamic == ObjectMapper.Dynamic.TRUE) { Mapper.Builder builder = context.root().findTemplateBuilder(context, arrayFieldName, "object"); if (builder == null) { return parseNonDynamicArray(context, parentMapper, lastFieldName, arrayFieldName); } Mapper.BuilderContext builderContext = new Mapper.BuilderContext(context.indexSettings(), context.path()); mapper = builder.build(builderContext); if (mapper != null && mapper instanceof ArrayValueMapperParser) { context.path().add(arrayFieldName); mapper = parseAndMergeUpdate(mapper, context); return parentMapper.mappingUpdate(mapper); } else { return parseNonDynamicArray(context, parentMapper, lastFieldName, arrayFieldName); } } else { return parseNonDynamicArray(context, parentMapper, lastFieldName, arrayFieldName); } } } private static ObjectMapper parseNonDynamicArray(ParseContext context, ObjectMapper mapper, String lastFieldName, String arrayFieldName) throws IOException { XContentParser parser = context.parser(); XContentParser.Token token; while ((token = parser.nextToken()) != XContentParser.Token.END_ARRAY) { if (token == XContentParser.Token.START_OBJECT) { return parseObject(context, mapper, lastFieldName); } else if (token == XContentParser.Token.START_ARRAY) { return parseArray(context, mapper, lastFieldName); } else if (token == XContentParser.Token.FIELD_NAME) { lastFieldName = parser.currentName(); } else if (token == XContentParser.Token.VALUE_NULL) { parseNullValue(context, mapper, lastFieldName); } else if (token == null) { throw new MapperParsingException("object mapping for [" + mapper.name() + "] with array for [" + arrayFieldName + "] tried to parse as array, but got EOF, is there a mismatch in types for the same field?"); } else { return parseValue(context, mapper, lastFieldName, token); } } return null; } private static ObjectMapper parseValue(final ParseContext context, ObjectMapper parentMapper, String currentFieldName, XContentParser.Token token) throws IOException { if (currentFieldName == null) { throw new MapperParsingException("object mapping [" + parentMapper.name() + "] trying to serialize a value with no field associated with it, current value [" + context.parser().textOrNull() + "]"); } Mapper mapper = parentMapper.getMapper(currentFieldName); if (mapper != null) { Mapper subUpdate = parseObjectOrField(context, mapper); if (subUpdate == null) { return null; } return parentMapper.mappingUpdate(subUpdate); } else { return parseDynamicValue(context, parentMapper, currentFieldName, token); } } private static void parseNullValue(ParseContext context, ObjectMapper parentMapper, String lastFieldName) throws IOException { // we can only handle null values if we have mappings for them Mapper mapper = parentMapper.getMapper(lastFieldName); if (mapper != null) { // TODO: passing null to an object seems bogus? parseObjectOrField(context, mapper); } else if (parentMapper.dynamic() == ObjectMapper.Dynamic.STRICT) { throw new StrictDynamicMappingException(parentMapper.fullPath(), lastFieldName); } } private static Mapper.Builder<?,?> createBuilderFromFieldType(final ParseContext context, MappedFieldType fieldType, String currentFieldName) { Mapper.Builder builder = null; if (fieldType instanceof StringFieldType) { builder = context.root().findTemplateBuilder(context, currentFieldName, "string"); if (builder == null) { builder = MapperBuilders.stringField(currentFieldName); } } else if (fieldType instanceof DateFieldType) { builder = context.root().findTemplateBuilder(context, currentFieldName, "date"); if (builder == null) { builder = MapperBuilders.dateField(currentFieldName); } } else if (fieldType.numericType() != null) { switch (fieldType.numericType()) { case LONG: builder = context.root().findTemplateBuilder(context, currentFieldName, "long"); if (builder == null) { builder = MapperBuilders.longField(currentFieldName); } break; case DOUBLE: builder = context.root().findTemplateBuilder(context, currentFieldName, "double"); if (builder == null) { builder = MapperBuilders.doubleField(currentFieldName); } break; case INT: builder = context.root().findTemplateBuilder(context, currentFieldName, "integer"); if (builder == null) { builder = MapperBuilders.integerField(currentFieldName); } break; case FLOAT: builder = context.root().findTemplateBuilder(context, currentFieldName, "float"); if (builder == null) { builder = MapperBuilders.floatField(currentFieldName); } break; default: throw new AssertionError("Unexpected numeric type " + fieldType.numericType()); } } return builder; } private static Mapper.Builder<?,?> createBuilderFromDynamicValue(final ParseContext context, XContentParser.Token token, String currentFieldName) throws IOException { if (token == XContentParser.Token.VALUE_STRING) { // do a quick test to see if its fits a dynamic template, if so, use it. // we need to do it here so we can handle things like attachment templates, where calling // text (to see if its a date) causes the binary value to be cleared { Mapper.Builder builder = context.root().findTemplateBuilder(context, currentFieldName, "string", null); if (builder != null) { return builder; } } if (context.root().dateDetection()) { String text = context.parser().text(); // a safe check since "1" gets parsed as well if (Strings.countOccurrencesOf(text, ":") > 1 || Strings.countOccurrencesOf(text, "-") > 1 || Strings.countOccurrencesOf(text, "/") > 1) { for (FormatDateTimeFormatter dateTimeFormatter : context.root().dynamicDateTimeFormatters()) { try { dateTimeFormatter.parser().parseMillis(text); Mapper.Builder builder = context.root().findTemplateBuilder(context, currentFieldName, "date"); if (builder == null) { builder = MapperBuilders.dateField(currentFieldName).dateTimeFormatter(dateTimeFormatter); } return builder; } catch (Exception e) { // failure to parse this, continue } } } } if (context.root().numericDetection()) { String text = context.parser().text(); try { Long.parseLong(text); Mapper.Builder builder = context.root().findTemplateBuilder(context, currentFieldName, "long"); if (builder == null) { builder = MapperBuilders.longField(currentFieldName); } return builder; } catch (NumberFormatException e) { // not a long number } try { Double.parseDouble(text); Mapper.Builder builder = context.root().findTemplateBuilder(context, currentFieldName, "double"); if (builder == null) { builder = MapperBuilders.doubleField(currentFieldName); } return builder; } catch (NumberFormatException e) { // not a long number } } Mapper.Builder builder = context.root().findTemplateBuilder(context, currentFieldName, "string"); if (builder == null) { builder = MapperBuilders.stringField(currentFieldName); } return builder; } else if (token == XContentParser.Token.VALUE_NUMBER) { XContentParser.NumberType numberType = context.parser().numberType(); if (numberType == XContentParser.NumberType.INT) { if (context.parser().estimatedNumberType()) { Mapper.Builder builder = context.root().findTemplateBuilder(context, currentFieldName, "long"); if (builder == null) { builder = MapperBuilders.longField(currentFieldName); } return builder; } else { Mapper.Builder builder = context.root().findTemplateBuilder(context, currentFieldName, "integer"); if (builder == null) { builder = MapperBuilders.integerField(currentFieldName); } return builder; } } else if (numberType == XContentParser.NumberType.LONG) { Mapper.Builder builder = context.root().findTemplateBuilder(context, currentFieldName, "long"); if (builder == null) { builder = MapperBuilders.longField(currentFieldName); } return builder; } else if (numberType == XContentParser.NumberType.FLOAT) { if (context.parser().estimatedNumberType()) { Mapper.Builder builder = context.root().findTemplateBuilder(context, currentFieldName, "double"); if (builder == null) { builder = MapperBuilders.doubleField(currentFieldName); } return builder; } else { Mapper.Builder builder = context.root().findTemplateBuilder(context, currentFieldName, "float"); if (builder == null) { builder = MapperBuilders.floatField(currentFieldName); } return builder; } } else if (numberType == XContentParser.NumberType.DOUBLE) { Mapper.Builder builder = context.root().findTemplateBuilder(context, currentFieldName, "double"); if (builder == null) { builder = MapperBuilders.doubleField(currentFieldName); } return builder; } } else if (token == XContentParser.Token.VALUE_BOOLEAN) { Mapper.Builder builder = context.root().findTemplateBuilder(context, currentFieldName, "boolean"); if (builder == null) { builder = MapperBuilders.booleanField(currentFieldName); } return builder; } else if (token == XContentParser.Token.VALUE_EMBEDDED_OBJECT) { Mapper.Builder builder = context.root().findTemplateBuilder(context, currentFieldName, "binary"); if (builder == null) { builder = MapperBuilders.binaryField(currentFieldName); } return builder; } else { Mapper.Builder builder = context.root().findTemplateBuilder(context, currentFieldName, null); if (builder != null) { return builder; } } // TODO how do we identify dynamically that its a binary value? throw new IllegalStateException("Can't handle serializing a dynamic type with content token [" + token + "] and field name [" + currentFieldName + "]"); } private static ObjectMapper parseDynamicValue(final ParseContext context, ObjectMapper parentMapper, String currentFieldName, XContentParser.Token token) throws IOException { ObjectMapper.Dynamic dynamic = parentMapper.dynamic(); if (dynamic == null) { dynamic = dynamicOrDefault(context.root().dynamic()); } if (dynamic == ObjectMapper.Dynamic.STRICT) { throw new StrictDynamicMappingException(parentMapper.fullPath(), currentFieldName); } if (dynamic == ObjectMapper.Dynamic.FALSE) { return null; } final Mapper.BuilderContext builderContext = new Mapper.BuilderContext(context.indexSettings(), context.path()); final MappedFieldType existingFieldType = context.mapperService().fullName(context.path().fullPathAsText(currentFieldName)); Mapper.Builder builder = null; if (existingFieldType != null) { // create a builder of the same type builder = createBuilderFromFieldType(context, existingFieldType, currentFieldName); if (builder != null) { // best-effort to not introduce a conflict if (builder instanceof StringFieldMapper.Builder) { StringFieldMapper.Builder stringBuilder = (StringFieldMapper.Builder) builder; stringBuilder.fieldDataSettings(existingFieldType.fieldDataType().getSettings()); stringBuilder.store(existingFieldType.stored()); stringBuilder.indexOptions(existingFieldType.indexOptions()); stringBuilder.tokenized(existingFieldType.tokenized()); stringBuilder.omitNorms(existingFieldType.omitNorms()); stringBuilder.docValues(existingFieldType.hasDocValues()); stringBuilder.indexAnalyzer(existingFieldType.indexAnalyzer()); stringBuilder.searchAnalyzer(existingFieldType.searchAnalyzer()); } else if (builder instanceof NumberFieldMapper.Builder) { NumberFieldMapper.Builder<?,?> numberBuilder = (NumberFieldMapper.Builder<?, ?>) builder; numberBuilder.fieldDataSettings(existingFieldType.fieldDataType().getSettings()); numberBuilder.store(existingFieldType.stored()); numberBuilder.indexOptions(existingFieldType.indexOptions()); numberBuilder.tokenized(existingFieldType.tokenized()); numberBuilder.omitNorms(existingFieldType.omitNorms()); numberBuilder.docValues(existingFieldType.hasDocValues()); numberBuilder.precisionStep(existingFieldType.numericPrecisionStep()); } } } if (builder == null) { builder = createBuilderFromDynamicValue(context, token, currentFieldName); } Mapper mapper = builder.build(builderContext); mapper = parseAndMergeUpdate(mapper, context); ObjectMapper update = null; if (mapper != null) { update = parentMapper.mappingUpdate(mapper); } return update; } /** Creates instances of the fields that the current field should be copied to */ private static void parseCopyFields(ParseContext context, FieldMapper fieldMapper, List<String> copyToFields) throws IOException { if (!context.isWithinCopyTo() && copyToFields.isEmpty() == false) { context = context.createCopyToContext(); for (String field : copyToFields) { // In case of a hierarchy of nested documents, we need to figure out // which document the field should go to ParseContext.Document targetDoc = null; for (ParseContext.Document doc = context.doc(); doc != null; doc = doc.getParent()) { if (field.startsWith(doc.getPrefix())) { targetDoc = doc; break; } } assert targetDoc != null; final ParseContext copyToContext; if (targetDoc == context.doc()) { copyToContext = context; } else { copyToContext = context.switchDoc(targetDoc); } parseCopy(field, copyToContext); } } } /** Creates an copy of the current field with given field name and boost */ private static void parseCopy(String field, ParseContext context) throws IOException { FieldMapper fieldMapper = context.docMapper().mappers().getMapper(field); if (fieldMapper != null) { fieldMapper.parse(context); } else { // The path of the dest field might be completely different from the current one so we need to reset it context = context.overridePath(new ContentPath(0)); ObjectMapper mapper = context.root(); String objectPath = ""; String fieldPath = field; int posDot = field.lastIndexOf('.'); if (posDot > 0) { objectPath = field.substring(0, posDot); context.path().add(objectPath); mapper = context.docMapper().objectMappers().get(objectPath); fieldPath = field.substring(posDot + 1); } if (mapper == null) { //TODO: Create an object dynamically? throw new MapperParsingException("attempt to copy value to non-existing object [" + field + "]"); } ObjectMapper update = parseDynamicValue(context, mapper, fieldPath, context.parser().currentToken()); assert update != null; // we are parsing a dynamic value so we necessarily created a new mapping // propagate the update to the root while (objectPath.length() > 0) { String parentPath = ""; ObjectMapper parent = context.root(); posDot = objectPath.lastIndexOf('.'); if (posDot > 0) { parentPath = objectPath.substring(0, posDot); parent = context.docMapper().objectMappers().get(parentPath); } if (parent == null) { throw new IllegalStateException("[" + objectPath + "] has no parent for path [" + parentPath + "]"); } update = parent.mappingUpdate(update); objectPath = parentPath; } context.addDynamicMappingsUpdate(update); } } /** * Parse the given {@code context} with the given {@code mapper} and apply * the potential mapping update in-place. This method is useful when * composing mapping updates. */ private static <M extends Mapper> M parseAndMergeUpdate(M mapper, ParseContext context) throws IOException { final Mapper update = parseObjectOrField(context, mapper); if (update != null) { MapperUtils.merge(mapper, update); } return mapper; } private static XContentParser transform(Mapping mapping, XContentParser parser) throws IOException { Map<String, Object> transformed; try (XContentParser _ = parser) { transformed = transformSourceAsMap(mapping, parser.mapOrdered()); } XContentBuilder builder = XContentFactory.contentBuilder(parser.contentType()).value(transformed); return parser.contentType().xContent().createParser(builder.bytes()); } private static ObjectMapper.Dynamic dynamicOrDefault(ObjectMapper.Dynamic dynamic) { return dynamic == null ? ObjectMapper.Dynamic.TRUE : dynamic; } static Map<String, Object> transformSourceAsMap(Mapping mapping, Map<String, Object> sourceAsMap) { if (mapping.sourceTransforms.length == 0) { return sourceAsMap; } for (Mapping.SourceTransform transform : mapping.sourceTransforms) { sourceAsMap = transform.transformSourceAsMap(sourceAsMap); } return sourceAsMap; } @Override public void close() { cache.close(); } }
{ "content_hash": "f6413959bdedbb68e5e7dc0dd279b021", "timestamp": "", "source": "github", "line_count": 773, "max_line_length": 222, "avg_line_length": 49.94307891332471, "alnum_prop": 0.5914624669740455, "repo_name": "fekaputra/elasticsearch", "id": "403162cf7fc90116f5c8e2d4aaa8b98555fcfdd8", "size": "39394", "binary": false, "copies": "3", "ref": "refs/heads/master", "path": "core/src/main/java/org/elasticsearch/index/mapper/DocumentParser.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Batchfile", "bytes": "10878" }, { "name": "Groovy", "bytes": "451" }, { "name": "HTML", "bytes": "1427" }, { "name": "Java", "bytes": "29157290" }, { "name": "Perl", "bytes": "264364" }, { "name": "Perl6", "bytes": "103207" }, { "name": "Python", "bytes": "77601" }, { "name": "Ruby", "bytes": "17776" }, { "name": "Shell", "bytes": "87409" } ], "symlink_target": "" }
One of the great features of the Go programming language is the commitment to compatibility as decribed on the document [Go 1 and the Future of Go Programs](https://golang.org/doc/go1compat). Most importantly, the policy states that programs written for Go 1.0 should continue to work without modification in Go 1.1, 1.2, etc. Although it isn't necessary for every Go library to commit to this level of forward compatibility, it is important to keep this expectation in mind when releasing your own code to the community. ## Project Maturity and Stability Without defining a formal classification scheme, it is still useful to inform your users of the overall maturity of your library. We suggest including a "Stability and Compatibility" section in your top-level README.md file that summarizes the current status. For example: 1. The Foo library is currently undergoing heavy development with frequent, breaking API changes. When possible, highlight the parts of the API that are likely to change. 2. The Foo library is getting close to a stable release, and we are trying to minimize breaking API changes. However, we cannot make any guarantees at this time. 3. The Foo library is considered stable. We will make every effort to ensure API compatibility in future releases. ## Semantic Versioning There internets are full of heated debates on the topic of version naming. We suggest that Go library authors adopt a versioning scheme that is compatible with the [SemVer 2.0 Standard](http://semver.org): ```text MAJOR.MINOR.PATCH ``` * `MAJOR`: Incremented when you make incompatible API changes. Use `1` for the first API-stable release. * `MINOR`: Incremented when you make backwards-compatible functionality additions or modifications. This also includes fixes that have a non-trivial impact on performance - CPU, memory or storage. * `PATCH`: Incremented when you apply bug fixes or documentation changes. Should not have significant impact on functionality or performance. Another convention to consider adopting is that post-1.0-release breaking API changes should always require a change in the import path. This could be accomplished using either of the following approaches: ### Including a version indicator in the import path. The downside to this approach is that you have to plan for the migration by including the `v1`' package in your path from the very beginning. Keep in mind that this is not recommended by API design experts such as [Martin Fowler](http://martinfowler.com/articles/enterpriseREST.html). ```go import ( apiv1 "github.com/:username/:projectname/v1/:apiname" apiv2 "github.com/:username/:projectname/v2/:apiname" ) ``` ### Creating a new top-level repository. Instead of introducing a version element to your import path, fork your repository to create a version 2. ```go import ( apiv1 "github.com/:username/:projectname/:apiname" apiv2 "github.com/:username/:projectname2/:apiname" ) ``` ### When Breakage is Unavoidable As with all libraries and APIs, it is unlikely that you'll get everything right the first time around. If you find yourself in a situation where breaking API compatibility, there are a few tactics you can use to make this easier on your users: * Inform your users of the version number in which the breaking change will be introduced so that they can vendor the latest working version. For example, update your top-level README.md to include "In version 1.3.0, package `p1` will be moving from `github.com/:username/:projectname/p1` to `github.com/:username/:projectname/sub/p1`" * When you do perform repository restructuring, one convention used by Go projects is to leave behind a `moved.go` placeholder file under the deprecated import path with the following content: ```go // Package moved to: github.com/:username/:projectname/sub/ext. package ext ``` * If you're moving a command from one location to another, you can provide an even more obvious warning by providing a `moved.go` that will terminate with a non-zero exit status and error message: ```go package main import ( "fmt" "os" ) func main() { fmt.Println("This command has moved to github.com/:user/:project/sub/cmd") os.Exit(1) } ``` ## Version Labeling and Import Paths We suggest that you use the version labeling and naming mechanism provided by our version control system. Git users should use [git tagging](https://git-scm.com/book/en/v2/Git-Basics-Tagging), Mercurial users should use [hg tagging](https://mercurial.selenic.com/wiki/Tag), and Subversion users should use [svn tagging](http://svnbook.red-bean.com/en/1.7/svn-book.html#svn.branchmerge.tags). In general, you should avoid including the `v` text in the version tags. Use `1.0.3` instead of `v1.0.3`.
{ "content_hash": "132a0094f33b3739400bcb5f3bc509ee", "timestamp": "", "source": "github", "line_count": 122, "max_line_length": 81, "avg_line_length": 39.057377049180324, "alnum_prop": 0.7729275970619097, "repo_name": "jbuberel/gochecklist", "id": "efc16977ffb3e5b1ef9835e61c17f7225738e8a5", "size": "4795", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "publication/api_stability_and_maturity.md", "mode": "33188", "license": "apache-2.0", "language": [], "symlink_target": "" }
package permission import ( "go/ast" goparser "go/parser" "go/token" "go/types" "reflect" "testing" ) // newInterfaceWithMethod creates a recursive interface permission func newInterfaceWithMethod() *InterfacePermission { iface := &InterfacePermission{ BasePermission: Mutable, Methods: []*FuncPermission{ &FuncPermission{ Name: "foo", BasePermission: Mutable, Params: []Permission{Mutable}, }, }, } iface.Methods[0].Receivers = []Permission{iface} iface.Methods[0].Results = []Permission{iface} return iface } // testCases contains tests for the permission parser. var testCases = map[string]Permission{ "struct { x int64; y interface {}}": &StructPermission{ BasePermission: Mutable, Fields: []Permission{Mutable, &InterfacePermission{ BasePermission: Mutable, }}, }, "[]interface{}": &SlicePermission{ BasePermission: Mutable, ElementPermission: &InterfacePermission{ BasePermission: Mutable, }, }, "[5]interface{}": &ArrayPermission{ BasePermission: Mutable, ElementPermission: &InterfacePermission{ BasePermission: Mutable, }, }, "chan interface{}": &ChanPermission{ BasePermission: Mutable, ElementPermission: &InterfacePermission{ BasePermission: Mutable, }, }, "*interface{}": &PointerPermission{ BasePermission: Mutable, Target: &InterfacePermission{ BasePermission: Mutable, }, }, "map[interface{}] int": &MapPermission{ BasePermission: Mutable, KeyPermission: &InterfacePermission{ BasePermission: Mutable, }, ValuePermission: Mutable, }, "func()": &FuncPermission{ BasePermission: Mutable, }, "func(b interface{})": &FuncPermission{ BasePermission: Mutable, Params: []Permission{ &InterfacePermission{ BasePermission: Mutable, }, }, }, "func(b interface{})(c int)": &FuncPermission{ BasePermission: Mutable, Params: []Permission{ &InterfacePermission{ BasePermission: Mutable, }, }, Results: []Permission{Mutable}, }, "interface { foo(int) t}": newInterfaceWithMethod(), } func Parsed(s string) (types.Type, error) { config := types.Config{} fset := token.NewFileSet() f, err := goparser.ParseFile(fset, s+".go", "package test\ntype t "+s, goparser.ParseComments) if err != nil { return nil, err } info := types.Info{Defs: make(map[*ast.Ident]types.Object)} _, err = config.Check("hello", fset, []*ast.File{f}, &info) if err != nil { return nil, err } for ident, typ := range info.Defs { if ident.Name == "t" { return typ.Type(), nil } } return nil, nil } func TestNewFromType(t *testing.T) { for input, expected := range testCases { input := input expected := expected t.Run(input, func(t *testing.T) { typ, err := Parsed(input) if err != nil { t.Errorf("Invalid test input: %s", err) return } if typ == nil { t.Errorf("Does not parse to a type") return } perm := NewTypeMapper().NewFromType(typ) if !reflect.DeepEqual(perm, expected) { t.Errorf("Input %s: Unexpected permission %#v, expected %#v - error: %v", input, perm, expected, err) } }) } } func TestNewFromType_invalid(t *testing.T) { defer func() { if recover() == nil { t.Fatal("Expected panic") } }() var typ *types.Tuple NewTypeMapper().NewFromType(typ) } func TestNewFromType_nil(t *testing.T) { x := types.Typ[types.UntypedNil] perm := NewTypeMapper().NewFromType(x) if _, ok := perm.(*NilPermission); !ok { t.Errorf("Expected nil permission for untyped nil") } }
{ "content_hash": "b210135abd5ff05d3fb9b9c7cee5371e", "timestamp": "", "source": "github", "line_count": 151, "max_line_length": 105, "avg_line_length": 23.2317880794702, "alnum_prop": 0.6681870011402509, "repo_name": "julian-klode/lingolang", "id": "d5ef6c53af36fb1176bd2ceb144801a11143859f", "size": "3638", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "permission/type_test.go", "mode": "33188", "license": "bsd-2-clause", "language": [ { "name": "Go", "bytes": "195447" } ], "symlink_target": "" }
/***********************************************************************//** * @file EngineComponentCollection.java * @author Kurt E. Clothier * @date December 7, 2015 * * @breif Collection of all Engine Component sets * * @pre Compiler: Eclipse - Mars Release (4.5.0) * @pre Java: JRE 7 or greater * * @see http://www.projectsbykec.com/ * * @copyright The MIT License (MIT) - see LICENSE.txt ****************************************************************************/ package games.engine; import games.engine.util.PlayingCardAlias; public final class EngineComponentCollecion { private final EngineComponentSet<Action> actions; private final EngineComponentSet<Condition> conditions; private final EngineComponentSet<ControlledAction> cActions; private final EngineComponentSet<Phase> phases; private final EngineComponentSet<PlayingCardAlias> aliases; /** * Constructs a new <tt>EngineComponentCollecion</tt>. * * @param actions an <tt>EngineComponentSet</tt> of <tt>Actions</tt> * @param conditionsan <tt>EngineComponentSet</tt> of <tt>Conditions</tt> * @param cActionsan <tt>EngineComponentSet</tt> of <tt>ControlledActions</tt> * @param phasesan <tt>EngineComponentSet</tt> of <tt>Phases</tt> * @param aliasesan <tt>EngineComponentSet</tt> of <tt>PlayingCardAliases</tt> */ public EngineComponentCollecion(final EngineComponentSet<Condition> conditions, final EngineComponentSet<Action> actions, final EngineComponentSet<ControlledAction> cActions, final EngineComponentSet<Phase> phases, final EngineComponentSet<PlayingCardAlias> aliases) { this.actions = actions; this.conditions = conditions; this.cActions = cActions; this.phases = phases; this.aliases = aliases; } /** * Returns the <tt>EngineComponentSet</tt> of <tt>Actions</tt> from this <tt>EngineComponentCollecion</tt>. * * @return the <tt>EngineComponentSet</tt> of <tt>Actions</tt> from this <tt>EngineComponentCollecion</tt> */ public EngineComponentSet<Action> getActions() { return actions; } /** * Returns the <tt>EngineComponentSet</tt> of <tt>Conditions</tt> from this <tt>EngineComponentCollecion</tt>. * * @return the <tt>EngineComponentSet</tt> of <tt>Conditions</tt> from this <tt>EngineComponentCollecion</tt> */ public EngineComponentSet<Condition> getConditions() { return conditions; } /** * Returns the <tt>EngineComponentSet</tt> of <tt>ControlledActions</tt> from this <tt>EngineComponentCollecion</tt>. * * @return the <tt>EngineComponentSet</tt> of <tt>ControlledActions</tt> from this <tt>EngineComponentCollecion</tt> */ public EngineComponentSet<ControlledAction> getControlledActions() { return cActions; } /** * Returns the <tt>EngineComponentSet</tt> of <tt>Phases</tt> from this <tt>EngineComponentCollecion</tt>. * * @return the <tt>EngineComponentSet</tt> of <tt>Phases</tt> from this <tt>EngineComponentCollecion</tt> */ public EngineComponentSet<Phase> getPhases() { return phases; } /** * Returns the <tt>EngineComponentSet</tt> of <tt>PlayingCardAliases</tt> from this <tt>EngineComponentCollecion</tt>. * * @return the <tt>EngineComponentSet</tt> of <tt>PlayingCardAliases</tt> from this <tt>EngineComponentCollecion</tt> */ public EngineComponentSet<PlayingCardAlias> getAliases() { return aliases; } }
{ "content_hash": "ce6869878d637d3d776e4e9101db15cf", "timestamp": "", "source": "github", "line_count": 93, "max_line_length": 119, "avg_line_length": 36.333333333333336, "alnum_prop": 0.6972477064220184, "repo_name": "Kurt-E-Clothier/java-card-game-engine", "id": "341a2642f77f6f83ca71de7ca7e88981033aed8d", "size": "3379", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/games/engine/EngineComponentCollecion.java", "mode": "33188", "license": "mit", "language": [ { "name": "Java", "bytes": "428159" } ], "symlink_target": "" }
'use strict'; angular.module('myApp.view2', []) .controller('View2Ctrl', [function() { }]);
{ "content_hash": "f89dc8f37bd573dbaf29857339cadd18", "timestamp": "", "source": "github", "line_count": 8, "max_line_length": 38, "avg_line_length": 11.875, "alnum_prop": 0.6210526315789474, "repo_name": "idpokute/NG_MME", "id": "87c264f6a0ba2d02e07971da7665a4d3b2e133fd", "size": "95", "binary": false, "copies": "3", "ref": "refs/heads/master", "path": "app/view2/view2.js", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "9976" }, { "name": "HTML", "bytes": "17793" }, { "name": "JavaScript", "bytes": "9325" }, { "name": "Ruby", "bytes": "892" } ], "symlink_target": "" }
package com.chrisomeara.pillar import com.datastax.driver.core.querybuilder.QueryBuilder import com.datastax.driver.core.{Metadata, Session} import org.scalatest.matchers.ShouldMatchers trait AcceptanceAssertions extends ShouldMatchers { val session: Session val keyspaceName: String protected def assertEmptyAppliedMigrationsTable() { session.execute(QueryBuilder.select().from(keyspaceName, "applied_migrations")).all().size() should equal(0) } protected def assertKeyspaceDoesNotExist() { val metadata: Metadata = session.getCluster.getMetadata metadata.getKeyspace(keyspaceName) should be(null) } }
{ "content_hash": "548192c0ec14ef2437fa77ef5a8d74f1", "timestamp": "", "source": "github", "line_count": 19, "max_line_length": 112, "avg_line_length": 33.21052631578947, "alnum_prop": 0.7939778129952456, "repo_name": "smr-co-uk/pillar", "id": "e53674e1d332dcc5354553bd25963ac94151692b", "size": "631", "binary": false, "copies": "3", "ref": "refs/heads/master", "path": "src/test/scala/com/chrisomeara/pillar/AcceptanceAssertions.scala", "mode": "33188", "license": "mit", "language": [ { "name": "Scala", "bytes": "49978" }, { "name": "Shell", "bytes": "407" } ], "symlink_target": "" }
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>izf: 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="">8.10.dev / izf - 8.9.0</a></li> </ul> </div> </div> </div> <div class="article"> <div class="row"> <div class="col-md-12"> <a href="../..">« Up</a> <h1> izf <small> 8.9.0 <span class="label label-info">Not compatible</span> </small> </h1> <p><em><script>document.write(moment("2020-08-22 02:22:20 +0000", "YYYY-MM-DD HH:mm:ss Z").fromNow());</script> (2020-08-22 02:22:20 UTC)</em><p> <h2>Context</h2> <pre># Packages matching: installed # Name # Installed # Synopsis base-bigarray base base-num base Num library distributed with the OCaml compiler base-threads base base-unix base conf-findutils 1 Virtual package relying on findutils conf-m4 1 Virtual package relying on m4 coq 8.10.dev Formal proof management system num 0 The Num library for arbitrary-precision integer and rational arithmetic ocaml 4.05.0 The OCaml compiler (virtual package) ocaml-base-compiler 4.05.0 Official 4.05.0 release ocaml-config 1 OCaml Switch Configuration ocamlfind 1.8.1 A library manager for OCaml # opam file: opam-version: &quot;2.0&quot; maintainer: &quot;Hugo.Herbelin@inria.fr&quot; homepage: &quot;https://github.com/coq-contribs/izf&quot; license: &quot;LGPL 2.1&quot; build: [make &quot;-j%{jobs}%&quot;] install: [make &quot;install&quot;] remove: [&quot;rm&quot; &quot;-R&quot; &quot;%{lib}%/coq/user-contrib/IZF&quot;] depends: [ &quot;ocaml&quot; &quot;coq&quot; {&gt;= &quot;8.9&quot; &amp; &lt; &quot;8.10~&quot;} ] tags: [ &quot;keyword: Intuitionistic set theory&quot; &quot;keyword: pointed graphs&quot; &quot;keyword: type theory&quot; &quot;keyword: intuitionistic choice operator&quot; &quot;keyword: set theory&quot; &quot;keyword: Zermelo-Fraenkel&quot; &quot;category: Mathematics/Logic/Set theory&quot; &quot;date: 2003-02&quot; ] authors: [ &quot;Alexandre Miquel &lt;Alexandre.Miquel@pps.jussieu.fr&gt; [http://www.pps.jussieu.fr/~miquel]&quot; ] bug-reports: &quot;https://github.com/coq-contribs/izf/issues&quot; dev-repo: &quot;git+https://github.com/coq-contribs/izf.git&quot; synopsis: &quot;Intuitionistic Zermelo-Fraenkel Set Theory in Coq&quot; description: &quot;&quot;&quot; This development contains the set-as-pointed-graph interpretation of Intuitionistic Zermelo Frankel set theory in system F_omega.2++ (F_omega + one extra universe + intuitionistic choice operator), which is described in chapter 9 of the author&#39;s PhD thesis (for IZ) and in the author&#39;s CSL&#39;03 paper (for the extension IZ -&gt; IZF).&quot;&quot;&quot; flags: light-uninstall url { src: &quot;https://github.com/coq-contribs/izf/archive/v8.9.0.tar.gz&quot; checksum: &quot;md5=63408951be1dddce6e29a691c2fa95c4&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-izf.8.9.0 coq.8.10.dev</code></dd> <dt>Return code</dt> <dd>5120</dd> <dt>Output</dt> <dd><pre>[NOTE] Package coq is already installed (current version is 8.10.dev). The following dependencies couldn&#39;t be met: - coq-izf -&gt; coq &lt; 8.10~ -&gt; ocaml &lt; 4.05.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-izf.8.9.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"> <small>Sources are on <a href="https://github.com/coq-bench">GitHub</a>. © Guillaume Claret.</small> </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": "ee45363e1e7e860361c9f6b490ac1853", "timestamp": "", "source": "github", "line_count": 181, "max_line_length": 157, "avg_line_length": 40.850828729281766, "alnum_prop": 0.5536921828509602, "repo_name": "coq-bench/coq-bench.github.io", "id": "100e8357f7097afb8b8fc434b3ea3e311a29413b", "size": "7396", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "clean/Linux-x86_64-4.05.0-2.0.6/extra-dev/8.10.dev/izf/8.9.0.html", "mode": "33188", "license": "mit", "language": [], "symlink_target": "" }
use strict; use warnings; use CondorTest; use CondorUtils; # use like this: x_renamebypattern.pl \*trigger\* my $pattern = $ARGV[0]; #open(LOG,">run_test_log"); my $start = localtime; print LOG "Started at $start\n"; open(TESTS,"ls $pattern | "); while(<TESTS>) { CondorUtils::fullchomp($_); my $now = localtime; my $filebase = ""; my $currentfile = $_; my $tempfile = $currentfile . ".new"; #print LOG "fixing $_ at $now\n"; CondorTest::debug("fixing $currentfile at $now\n",1); #print "New file is $tempfile\n"; if( $currentfile =~ /^(.*)(willtrigger)(.*)$/ ) { CondorTest::debug("Change to $1true$3\n",1); system("x_renametool.pl $currentfile $1true$3"); } elsif($currentfile =~ /^(.*)(notrigger)(.*)$/ ) { CondorTest::debug("Change to $1false$3\n",1); system("x_renametool.pl $currentfile $1false$3"); } } my $ended = localtime; print LOG "Ended at $ended\n";
{ "content_hash": "3f164d8b794c53132da8d8529d0384ec", "timestamp": "", "source": "github", "line_count": 39, "max_line_length": 54, "avg_line_length": 22.871794871794872, "alnum_prop": 0.6345291479820628, "repo_name": "djw8605/htcondor", "id": "0aa39078e432a64b6353784b92bb84730bd2c52b", "size": "1721", "binary": false, "copies": "9", "ref": "refs/heads/cached", "path": "src/condor_tests/x_renamebypattern.pl", "mode": "33261", "license": "apache-2.0", "language": [ { "name": "Awk", "bytes": "18848" }, { "name": "Batchfile", "bytes": "187490" }, { "name": "Bison", "bytes": "49146" }, { "name": "C", "bytes": "1707840" }, { "name": "C++", "bytes": "26849384" }, { "name": "CMake", "bytes": "488753" }, { "name": "Fortran", "bytes": "110251" }, { "name": "Groff", "bytes": "6128" }, { "name": "HTML", "bytes": "16109" }, { "name": "Java", "bytes": "44327" }, { "name": "JavaScript", "bytes": "2095" }, { "name": "Makefile", "bytes": "11548" }, { "name": "Objective-C", "bytes": "7926" }, { "name": "PLpgSQL", "bytes": "23393" }, { "name": "Perl", "bytes": "4089668" }, { "name": "Prolog", "bytes": "10104" }, { "name": "Python", "bytes": "1029554" }, { "name": "Ruby", "bytes": "24647" }, { "name": "SQLPL", "bytes": "10933" }, { "name": "Shell", "bytes": "1240687" }, { "name": "TeX", "bytes": "17944" }, { "name": "Visual Basic", "bytes": "4845" } ], "symlink_target": "" }
<?php /** * @file * Class file to control the main Panels editor. */ class panels_renderer_editor extends panels_renderer_standard { /** * An array of AJAX commands to return. If populated it will automatically * be used by the AJAX router. */ var $commands = array(); var $admin = TRUE; /** * Set to true if edit links (for panes and regions) should not be displayed. * This can be used for special edit modes such as layout change and layout * builder that do not actually have real content. */ var $no_edit_links = FALSE; // ------------------------------------------------------------------------- // Display edit rendering. function edit() { $form_state = array( 'display' => &$this->display, 'renderer' => &$this, 'content_types' => $this->cache->content_types, 'no_redirect' => TRUE, 'display_title' => !empty($this->cache->display_title), 'cache key' => $this->display->cache_key, ); $output = drupal_build_form('panels_edit_display_form', $form_state); if (empty($form_state['executed']) || !empty($form_state['clicked_button']['preview'])) { return $output; } if (!empty($form_state['clicked_button']['#save-display'])) { drupal_set_message(t('Panel content has been updated.')); panels_save_display($this->display); } else { drupal_set_message(t('Your changes have been discarded.')); } panels_cache_clear('display', $this->display->did); return $this->display; } function add_meta() { parent::add_meta(); if ($this->admin) { ctools_include('ajax'); ctools_include('modal'); ctools_modal_add_js(); ctools_add_js('panels-base', 'panels'); ctools_add_js('display_editor', 'panels'); ctools_add_css('panels_dnd', 'panels'); ctools_add_css('panels_admin', 'panels'); drupal_add_library('system', 'ui'); } } function render() { // Pass through to normal rendering if not in admin mode. if (!$this->admin) { return parent::render(); } $this->add_meta(); $output = '<div class="panels-dnd" id="panels-dnd-main">'; $output .= $this->render_layout(); $output .= '</div>'; return $output; } function render_region($region_id, $panes) { // Pass through to normal rendering if not in admin mode. if (!$this->admin) { return parent::render_region($region_id, $panes); } $content = implode('', $panes); $panel_buttons = $this->get_region_links($region_id); $output = "<div class='panel-region' id='panel-region-$region_id'>"; $output .= $panel_buttons; $output .= "<h2 class='label'>" . check_plain($this->plugins['layout']['regions'][$region_id]) . "</h2>"; $output .= $content; $output .= "</div>"; return $output; } function render_pane(&$pane) { // Pass through to normal rendering if not in admin mode. if (!$this->admin) { return parent::render_pane($pane); } ctools_include('content'); $content_type = ctools_get_content_type($pane->type); // This is just used for the title bar of the pane, not the content itself. // If we know the content type, use the appropriate title for that type, // otherwise, set the title using the content itself. $title = ctools_content_admin_title($content_type, $pane->subtype, $pane->configuration, $this->display->context); if (!$title) { $title = t('Deleted/missing content type @type', array('@type' => $pane->type)); } $buttons = $this->get_pane_links($pane, $content_type); // Render administrative buttons for the pane. $block = new stdClass(); if (empty($content_type)) { $block->title = '<em>' . t('Missing content type') . '</em>'; $block->content = t('This pane\'s content type is either missing or has been deleted. This pane will not render.'); } else { $block = ctools_content_admin_info($content_type, $pane->subtype, $pane->configuration, $this->display->context); } $grabber_class = 'grab-title grabber'; // If there are region locks, add them. if (!empty($pane->locks['type'])) { if ($pane->locks['type'] == 'regions') { $settings['Panels']['RegionLock'][$pane->pid] = $pane->locks['regions']; drupal_add_js($settings, 'setting'); } else if ($pane->locks['type'] == 'immovable') { $grabber_class = 'grab-title not-grabber'; } } $output = ''; $class = 'panel-pane'; if (empty($pane->shown)) { $class .= ' hidden-pane'; } if (isset($this->display->title_pane) && $this->display->title_pane == $pane->pid) { $class .= ' panel-pane-is-title'; } $output = '<div class="' . $class . '" id="panel-pane-' . $pane->pid . '">'; if (empty($block->title)) { $block->title = t('No title'); } $output .= '<div class="' . $grabber_class . '">'; if ($buttons) { $output .= '<span class="buttons">' . $buttons . '</span>'; } $output .= '<span class="text" title="' . check_plain($title) . '">' . $title . '</span>'; $output .= '</div>'; // grabber $output .= '<div class="panel-pane-collapsible">'; $output .= '<div class="pane-title">' . $block->title . '</div>'; $output .= '<div class="pane-content">' . filter_xss_admin(render($block->content)) . '</div>'; $output .= '</div>'; // panel-pane-collapsible $output .= '</div>'; // panel-pane return $output; } /** * Get the style links. * * This is abstracted out since we have styles on both panes and regions. */ function get_style_links($type, $id = NULL) { $info = $this->get_style($type, $id); $style = $info[0]; $conf = $info[1]; $style_title = isset($style['title']) ? $style['title'] : t('Default'); $style_links['title'] = array( 'title' => $style_title, 'attributes' => array('class' => array('panels-text')), ); $style_links['change'] = array( 'title' => t('Change'), 'href' => $this->get_url('style-type', $type, $id), 'attributes' => array('class' => array('ctools-use-modal')), ); $function = $type != 'pane' ? 'settings form' : 'pane settings form'; if (panels_plugin_get_function('styles', $style, $function)) { $style_links['settings'] = array( 'title' => t('Settings'), 'href' => $this->get_url('style-settings', $type, $id), 'attributes' => array('class' => array('ctools-use-modal')), ); } return $style_links; } /** * Get the links for a panel display. * * This is abstracted out for easy ajax replacement. */ function get_display_links() { $links = array(); if (user_access('administer panels styles')) { $style_links = $this->get_style_links('display'); $links[] = array( 'title' => '<span class="dropdown-header">' . t('Style') . '</span>' . theme_links(array('links' => $style_links, 'attributes' => array(), 'heading' => array())), 'html' => TRUE, 'attributes' => array('class' => array('panels-sub-menu')), ); } if (user_access('use panels caching features')) { $links[] = array( 'title' => '<hr />', 'html' => TRUE, ); $method = isset($this->display->cache['method']) ? $this->display->cache['method'] : 0; $info = panels_get_cache($method); $cache_method = isset($info['title']) ? $info['title'] : t('No caching'); $cache_links[] = array( 'title' => $cache_method, 'attributes' => array('class' => array('panels-text')), ); $cache_links[] = array( 'title' => t('Change'), 'href' => $this->get_url('cache-method', 'display'), 'attributes' => array('class' => array('ctools-use-modal')), ); if (panels_plugin_get_function('cache', $info, 'settings form')) { $cache_links[] = array( 'title' => t('Settings'), 'href' => $this->get_url('cache-settings', 'display'), 'attributes' => array('class' => array('ctools-use-modal')), ); } $links[] = array( 'title' => '<span class="dropdown-header">' . t('Caching') . '</span>' . theme_links(array('links' => $cache_links, 'attributes' => array(), 'heading' => array())), 'html' => TRUE, 'attributes' => array('class' => array('panels-sub-menu')), ); } return theme('ctools_dropdown', array('title' => t('Display settings'), 'links' => $links, 'class' => 'panels-display-links')); } /** * Render the links to display when editing a region. */ function get_region_links($region_id) { if (!empty($this->no_edit_links)) { return ''; } $links = array(); $links[] = array( 'title' => t('Add content'), 'href' => $this->get_url('select-content', $region_id), 'attributes' => array( 'class' => array('ctools-use-modal'), ), ); if (user_access('administer panels styles')) { $links[] = array( 'title' => '<hr />', 'html' => TRUE, ); $style_links = $this->get_style_links('region', $region_id); $links[] = array( 'title' => '<span class="dropdown-header">' . t('Style') . '</span>' . theme_links(array('links' => $style_links, 'attributes' => array(), 'heading' => array())), 'html' => TRUE, 'attributes' => array('class' => array('panels-sub-menu')), ); } return theme('ctools_dropdown', array('title' => theme('image', array('path' => ctools_image_path('icon-addcontent.png', 'panels'))), 'links' => $links, 'image' => TRUE, 'class' => 'pane-add-link panels-region-links-' . $region_id)); } /** * Render the links to display when editing a pane. */ function get_pane_links($pane, $content_type) { if (!empty($this->no_edit_links)) { return ''; } $links = array(); if (!empty($pane->shown)) { $links['top']['disabled'] = array( 'title' => t('Disable this pane'), 'href' => $this->get_url('hide', $pane->pid), 'attributes' => array('class' => array('use-ajax')), ); } else { $links['top']['enable'] = array( 'title' => t('Enable this pane'), 'href' => $this->get_url('show', $pane->pid), 'attributes' => array('class' => array('use-ajax')), ); } if (isset($this->display->title_pane) && $this->display->title_pane == $pane->pid) { $links['top']['panels-set-title'] = array( 'title' => t('&#x2713;Panel title'), 'html' => TRUE, ); } else { $links['top']['panels-set-title'] = array( 'title' => t('Panel title'), 'href' => $this->get_url('panel-title', $pane->pid), 'attributes' => array('class' => array('use-ajax')), ); } $subtype = ctools_content_get_subtype($content_type, $pane->subtype); if (ctools_content_editable($content_type, $subtype, $pane->configuration)) { $links['top']['settings'] = array( 'title' => isset($content_type['edit text']) ? $content_type['edit text'] : t('Settings'), 'href' => $this->get_url('edit-pane', $pane->pid), 'attributes' => array('class' => array('ctools-use-modal')), ); } if (user_access('administer advanced pane settings')) { $links['top']['css'] = array( 'title' => t('CSS properties'), 'href' => $this->get_url('pane-css', $pane->pid), 'attributes' => array('class' => array('ctools-use-modal')), ); } if (user_access('administer panels styles')) { $links['style'] = $this->get_style_links('pane', $pane->pid); } if (user_access('administer pane access')) { $contexts = $this->display->context; // Make sure we have the logged in user context if (!isset($contexts['logged-in-user'])) { $contexts['logged-in-user'] = ctools_access_get_loggedin_context(); } $visibility_links = array(); if (!empty($pane->access['plugins'])) { foreach ($pane->access['plugins'] as $id => $test) { $plugin = ctools_get_access_plugin($test['name']); $access_title = isset($plugin['title']) ? $plugin['title'] : t('Broken/missing access plugin %plugin', array('%plugin' => $test['name'])); $access_description = ctools_access_summary($plugin, $contexts, $test); $visibility_links[] = array( 'title' => $access_description, 'href' => $this->get_url('access-configure-test', $pane->pid, $id), 'attributes' => array('class' => array('ctools-use-modal', 'panels-italic')), ); } } if (empty($visibility_links)) { $visibility_links['no_rules'] = array( 'title' => t('No rules'), 'attributes' => array('class' => array('panels-text')), ); } $visibility_links['add_rule'] = array( 'title' => t('Add new rule'), 'href' => $this->get_url('access-add-test', $pane->pid), 'attributes' => array('class' => array('ctools-use-modal')), ); $visibility_links['settings'] = array( 'title' => t('Settings'), 'href' => $this->get_url('access-settings', $pane->pid), 'attributes' => array('class' => array('ctools-use-modal')), ); $links['visibility'] = $visibility_links; } if (user_access('use panels locks')) { $lock_type = !empty($pane->locks['type']) ? $pane->locks['type'] : 'none'; switch ($lock_type) { case 'immovable': $lock_method = t('Immovable'); break; case 'regions': $lock_method = t('Regions'); break; case 'none': default: $lock_method = t('No lock'); break; } $lock_links['lock'] = array( 'title' => $lock_method, 'attributes' => array('class' => array('panels-text')), ); $lock_links['change'] = array( 'title' => t('Change'), 'href' => $this->get_url('lock', $pane->pid), 'attributes' => array('class' => array('ctools-use-modal')), ); $links['lock'] = $lock_links; } if (panels_get_caches() && user_access('use panels caching features')) { $method = isset($pane->cache['method']) ? $pane->cache['method'] : 0; $info = panels_get_cache($method); $cache_method = isset($info['title']) ? $info['title'] : t('No caching'); $cache_links['title'] = array( 'title' => $cache_method, 'attributes' => array('class' => array('panels-text')), ); $cache_links['change'] = array( 'title' => t('Change'), 'href' => $this->get_url('cache-method', $pane->pid), 'attributes' => array('class' => array('ctools-use-modal')), ); if (panels_plugin_get_function('cache', $info, 'settings form')) { $cache_links['settings'] = array( 'title' => t('Settings'), 'href' => $this->get_url('cache-settings', $pane->pid), 'attributes' => array('class' => array('ctools-use-modal')), ); } $links['cache'] = $cache_links; } $links['bottom']['remove'] = array( 'title' => t('Remove'), 'href' => '#', 'attributes' => array( 'class' => array('pane-delete'), 'id' => "pane-delete-panel-pane-$pane->pid", ), ); // Allow others to add/remove links from pane context menu. // Grouped by 'top', 'style', 'visibility', 'lock', 'cache' and 'bottom' drupal_alter('get_pane_links', $links, $pane, $content_type); $dropdown_links = $links['top']; $category_labels = array( 'style' => 'Style', 'visibility' => 'Visibility rules', 'lock' => 'Locking', 'cache' => 'Caching', ); foreach ($category_labels as $category => $label) { if (array_key_exists($category, $links)) { $dropdown_links[] = array( 'title' => '<hr />', 'html' => TRUE, ); $dropdown_links[] = array( 'title' => '<span class="dropdown-header">' . t($label) . '</span>' . theme_links(array('links' => $links[$category], 'attributes' => array(), 'heading' => array())), 'html' => TRUE, 'attributes' => array('class' => array('panels-sub-menu')), ); } } $dropdown_links[] = array( 'title' => '<hr />', 'html' => TRUE, ); $dropdown_links = array_merge($dropdown_links, $links['bottom']); return theme('ctools_dropdown', array('title' => theme('image', array('path' => ctools_image_path('icon-configure.png', 'panels'))), 'links' => $dropdown_links, 'image' => TRUE)); } // ----------------------------------------------------------------------- // Display edit AJAX callbacks and helpers. /** * Generate a URL path for the AJAX editor. */ function get_url() { $args = func_get_args(); $command = array_shift($args); $url = 'panels/ajax/' . $this->plugin['name'] . '/' . $command . '/' . $this->display->cache_key; if ($args) { $url .= '/' . implode('/', $args); } return $url; } /** * Get the Panels storage oparation for a given renderer AJAX method. * * @param string $method * The method name. * * @return string * The Panels storage op. */ function get_panels_storage_op_for_ajax($method) { switch ($method) { case 'ajax_show': case 'ajax_hide': case 'ajax_select_content': case 'ajax_add_pane': case 'ajax_edit_pane': case 'ajax_panel_title': case 'ajax_cache_method': case 'ajax_cache_settings': case 'ajax_style_type': case 'ajax_style_settings': case 'ajax_pane_css': case 'ajax_lock': case 'ajax_access_settings': case 'ajax_access_add_test': case 'ajax_access_configure_test': case 'ajax_layout': case 'ajax_style': return 'update'; } return parent::get_panels_storage_op_for_ajax($method); } /** * AJAX command to show a pane. */ function ajax_show($pid = NULL) { if (empty($this->display->content[$pid])) { ctools_ajax_render_error(t('Invalid pane id.')); } $this->display->content[$pid]->shown = TRUE; panels_edit_cache_set($this->cache); $this->command_update_pane($pid); } /** * AJAX command to show a pane. */ function ajax_hide($pid = NULL) { if (empty($this->display->content[$pid])) { ctools_ajax_render_error(t('Invalid pane id.')); } $this->display->content[$pid]->shown = FALSE; panels_edit_cache_set($this->cache); $this->command_update_pane($pid); } /** * AJAX command to present a dialog with a list of available content. */ function ajax_select_content($region = NULL, $category = NULL) { if (!array_key_exists($region, $this->plugins['layout']['regions'])) { ctools_modal_render(t('Error'), t('Invalid input')); } $title = t('Add content to !s', array('!s' => $this->plugins['layout']['regions'][$region])); $categories = $this->get_categories($this->cache->content_types); if (empty($categories)) { $output = t('There are no content types you may add to this display.'); } else { $output = theme('panels_add_content_modal', array('renderer' => $this, 'categories' => $categories, 'category' => $category, 'region' => $region)); } $this->commands[] = ctools_modal_command_display($title, $output); // Give keybord focus to the first item in the category we just loaded. if (!empty($category)) { $this->commands[] = ajax_command_invoke(".panels-add-content-modal .panels-section-columns :focusable:first", 'focus'); } } /** * Return the category name and the category key of a given content * type. * * @todo -- this should be in CTools. */ function get_category($content_type) { if (!empty($content_type['top level'])) { $category = 'root'; } else if (isset($content_type['category'])) { if (is_array($content_type['category'])) { list($category, $weight) = $content_type['category']; } else { $category = $content_type['category']; } } else { $category = t('Uncategorized'); } return array(preg_replace('/[^a-z0-9]/', '-', strtolower($category)), $category); } /** * Create a list of categories from all of the content type. * * @return array * An array of categories. Each entry in the array will also be an array * with 'title' as the printable title of the category, and 'content' * being an array of all content in the category. Each item in the 'content' * array contain the array plugin definition so that it can be later * found in the content array. They will be keyed by the title so that they * can be sorted. */ function get_categories($content_types) { $categories = array(); $category_names = array(); foreach ($content_types as $type_name => $subtypes) { foreach ($subtypes as $subtype_name => $content_type) { list($category_key, $category) = $this->get_category($content_type); if (empty($categories[$category_key])) { $categories[$category_key] = array( 'title' => $category, 'content' => array(), ); $category_names[$category_key] = $category; } $content_title = filter_xss_admin($content_type['title']); // Ensure content with the same title doesn't overwrite each other. while (isset($categories[$category_key]['content'][$content_title])) { $content_title .= '-'; } $categories[$category_key]['content'][$content_title] = $content_type; $categories[$category_key]['content'][$content_title]['type_name'] = $type_name; $categories[$category_key]['content'][$content_title]['subtype_name'] = $subtype_name; } } // Now sort natcasesort($category_names); foreach ($category_names as $category => $name) { $output[$category] = $categories[$category]; } return $output; } /** * AJAX entry point to add a new pane. */ function ajax_add_pane($region = NULL, $type_name = NULL, $subtype_name = NULL, $step = NULL) { $content_type = ctools_get_content_type($type_name); $subtype = ctools_content_get_subtype($content_type, $subtype_name); // Determine if we are adding a different pane than previously cached. This // is used to load the different pane into cache so that multistep forms // have the correct context instead of a previously cached version that // does not match the pane currently being added. $is_different_pane = FALSE; if (isset($this->cache) && isset($this->cache->new_pane)) { $diff_type = $type_name != $this->cache->new_pane->type; $diff_subtype = $subtype_name != $this->cache->new_pane->subtype; $is_different_pane = $diff_type || $diff_subtype; } if (!isset($step) || !isset($this->cache->new_pane) || $is_different_pane) { $pane = panels_new_pane($type_name, $subtype_name, TRUE); $this->cache->new_pane = &$pane; } else { $pane = &$this->cache->new_pane; } $form_state = array( 'display' => &$this->cache->display, 'contexts' => $this->cache->display->context, 'pane' => &$pane, 'cache_key' => $this->display->cache_key, 'display cache' => &$this->cache, 'ajax' => TRUE, 'modal' => TRUE, // This will force the system to not automatically render. 'modal return' => TRUE, 'commands' => array(), ); $form_info = array( 'path' => $this->get_url('add-pane', $region, $type_name, $subtype_name, '%step'), 'show cancel' => TRUE, 'next callback' => 'panels_ajax_edit_pane_next', 'finish callback' => 'panels_ajax_edit_pane_finish', 'cancel callback' => 'panels_ajax_edit_pane_cancel', ); $output = ctools_content_form('add', $form_info, $form_state, $content_type, $pane->subtype, $subtype, $pane->configuration, $step); // If $rc is FALSE, there was no actual form. if ($output === FALSE || !empty($form_state['complete'])) { // References get blown away with AJAX caching. This will fix that. $pane = $form_state['pane']; unset($this->cache->new_pane); // Add the pane to the display $this->display->add_pane($pane, $region); panels_edit_cache_set($this->cache); // Tell the client to draw the pane $this->command_add_pane($pane); // Dismiss the modal. $this->commands[] = ctools_modal_command_dismiss(); } else if (!empty($form_state['cancel'])) { // If cancelling, return to the activity. list($category_key, $category) = $this->get_category($subtype); $this->ajax_select_content($region, $category_key); } else { // This overwrites any previous commands. $this->commands = ctools_modal_form_render($form_state, $output); } } /** * AJAX entry point to edit a pane. */ function ajax_edit_pane($pid = NULL, $step = NULL) { if (empty($this->cache->display->content[$pid])) { ctools_modal_render(t('Error'), t('Invalid pane id.')); } $pane = &$this->cache->display->content[$pid]; $content_type = ctools_get_content_type($pane->type); $subtype = ctools_content_get_subtype($content_type, $pane->subtype); $form_state = array( 'display' => &$this->cache->display, 'contexts' => $this->cache->display->context, 'pane' => &$pane, 'display cache' => &$this->cache, 'ajax' => TRUE, 'modal' => TRUE, 'modal return' => TRUE, 'commands' => array(), ); $form_info = array( 'path' => $this->get_url('edit-pane', $pid, '%step'), 'show cancel' => TRUE, 'next callback' => 'panels_ajax_edit_pane_next', 'finish callback' => 'panels_ajax_edit_pane_finish', 'cancel callback' => 'panels_ajax_edit_pane_cancel', ); $output = ctools_content_form('edit', $form_info, $form_state, $content_type, $pane->subtype, $subtype, $pane->configuration, $step); // If $rc is FALSE, there was no actual form. if ($output === FALSE || !empty($form_state['cancel'])) { // Dismiss the modal. $this->commands[] = ctools_modal_command_dismiss(); } else if (!empty($form_state['complete'])) { // References get blown away with AJAX caching. This will fix that. $this->cache->display->content[$pid] = $form_state['pane']; // Conditionally overwrite the context for this panel if present in the form state. if (!empty($form_state['display_cache']->display->context)) { $this->cache->display->context = $form_state['display_cache']->display->context; } panels_edit_cache_set($this->cache); $this->command_update_pane($pid); $this->commands[] = ctools_modal_command_dismiss(); } else { // This overwrites any previous commands. $this->commands = ctools_modal_form_render($form_state, $output); } } /** * AJAX entry point to select which pane is currently the title. * * @param string $pid * The pane id for the pane object whose title state we're setting. */ function ajax_panel_title($pid = NULL) { if (empty($this->display->content[$pid])) { ctools_ajax_render_error(t('Invalid pane id.')); } $pane = &$this->display->content[$pid]; $old_title = !empty($this->display->title_pane) ? $this->display->title_pane : NULL; $this->display->title_pane = $pid; panels_edit_cache_set($this->cache); $this->command_update_pane($pane); if ($old_title && !empty($this->cache->display->content[$old_title])) { $this->command_update_pane($this->cache->display->content[$old_title]); } } /** * AJAX entry point to configure the cache method for a pane or the display. * * @param string $pid * Either a pane id for a pane in the display, or 'display' to edit the * display cache settings. */ function ajax_cache_method($pid = NULL) { ctools_include('content'); // This lets us choose whether we're doing the display's cache or // a pane's. if ($pid == 'display') { $conf = &$this->display->cache; $title = t('Cache method for this display'); } else if (!empty($this->display->content[$pid])) { $pane = &$this->display->content[$pid]; $subtype = ctools_content_get_subtype($pane->type, $pane->subtype); $conf = &$pane->cache; $title = t('Cache method for !subtype_title', array('!subtype_title' => $subtype['title'])); } else { ctools_modal_render(t('Error'), t('Invalid pane id.')); } $form_state = array( 'display' => &$this->display, 'conf' => &$conf, 'title' => $title, 'ajax' => TRUE, ); $output = ctools_modal_form_wrapper('panels_edit_cache_method_form', $form_state); if (empty($form_state['executed'])) { $this->commands = $output; return; } // Preserve this; this way we don't actually change the method until they // have saved the form. $info = panels_get_cache($form_state['method']); $function = panels_plugin_get_function('cache', $info, 'settings form'); if (!$function) { $conf['method'] = $form_state['method']; $conf['settings'] = array(); panels_edit_cache_set($this->cache); $this->commands[] = ctools_modal_command_dismiss(); if ($pid != 'display') { $this->command_update_pane($pane); } else { $this->command_update_display_links(); } } else { $this->cache->method = $form_state['method']; panels_edit_cache_set($this->cache); // send them to next form. return $this->ajax_cache_settings($pid); } } /** * AJAX entry point to configure the cache settings for a pane or the display. * * @param string $pid * Either a pane id for a pane in the display, or 'display' to edit the * display cache settings. */ function ajax_cache_settings($pid = 0) { ctools_include('content'); // This lets us choose whether we're doing the display's cache or // a pane's. if ($pid == 'display') { $conf = &$this->display->cache; $title = t('Cache settings for this display'); } else if (!empty($this->display->content[$pid])) { $pane = &$this->display->content[$pid]; $subtype = ctools_content_get_subtype($pane->type, $pane->subtype); $conf = &$pane->cache; $title = t('Cache settings for !subtype_title', array('!subtype_title' => $subtype['title'])); } else { ctools_modal_render(t('Error'), t('Invalid pane id.')); } if (isset($this->cache->method) && (empty($conf['method']) || $conf['method'] != $this->cache->method)) { $conf['method'] = $this->cache->method; $info = panels_get_cache($conf['method']); $conf['settings'] = isset($info['defaults']) ? $info['defaults'] : array(); } $form_state = array( 'display' => &$this->display, 'pid' => $pid, 'conf' => &$conf, 'ajax' => TRUE, 'title' => $title, 'url' => url($this->get_url('cache-settings', $pid), array('absolute' => TRUE)), ); $output = ctools_modal_form_wrapper('panels_edit_cache_settings_form', $form_state); if (empty($form_state['executed'])) { $this->commands = $output; return; } panels_edit_cache_set($this->cache); $this->commands[] = ctools_modal_command_dismiss(); if ($pid != 'display') { $this->command_update_pane($pane); } else { $this->command_update_display_links(); } } /** * AJAX entry point to select the style for a display, region or pane. * * @param string $type * Either display, region or pane * @param $pid * The pane id, if a pane. The region id, if a region. */ function ajax_style_type($type, $pid = NULL) { // This lets us choose whether we're doing the display's cache or // a pane's. switch ($type) { case 'display': $style = isset($this->display->panel_settings['style']) ? $this->display->panel_settings['style'] : 'default'; $title = t('Default style for this display'); break; case 'region': $style = isset($this->display->panel_settings[$pid]['style']) ? $this->display->panel_settings[$pid]['style'] : '-1'; // -1 signifies to use the default setting. $title = t('Panel style for region "!region"', array('!region' => $this->plugins['layout']['regions'][$pid])); break; case 'pane': ctools_include('content'); $pane = &$this->display->content[$pid]; $style = isset($pane->style['style']) ? $pane->style['style'] : 'default'; $title = ctools_content_admin_title($pane->type, $pane->subtype, $pane->configuration, $this->display->context); if (!$title) { $title = $pane->type; } $title = t('Pane style for "!title"', array('!title' => $title)); break; default: ctools_modal_render(t('Error'), t('Invalid pane id.')); } $info = $this->get_style($type, $pid); $style_plugin = $info[0]; $style_settings = $info[1]; // Backward compatibility: Translate old-style stylizer to new style // stylizer. if ($style == 'stylizer' && !empty($style_settings['style']) && $style_settings['style'] != '$') { $style = 'stylizer:' . $style_settings['style']; } $form_state = array( 'display' => &$this->display, 'style' => $style, 'pane' => ($type == 'pane') ? $this->display->content[$pid] : NULL, 'title' => $title, 'ajax' => TRUE, 'type' => $type, ); $output = ctools_modal_form_wrapper('panels_edit_style_type_form', $form_state); if (empty($form_state['executed'])) { $this->commands = $output; return; } // Preserve this; this way we don't actually change the method until they // have saved the form. $style = panels_get_style($form_state['style']); $function = panels_plugin_get_function('styles', $style, ($type == 'pane') ? 'pane settings form' : 'settings form'); if (!$function) { if (isset($this->cache->style)) { unset($this->cache->style); } // If there's no settings form, just change the style and exit. switch($type) { case 'display': $this->display->panel_settings['style'] = $form_state['style']; if (isset($this->display->panel_settings['style_settings']['default'])) { unset($this->display->panel_settings['style_settings']['default']); } break; case 'region': $this->display->panel_settings[$pid]['style'] = $form_state['style']; if (isset($this->display->panel_settings['style_settings'][$pid])) { unset($this->display->panel_settings['style_settings'][$pid]); } break; case 'pane': $pane->style['style'] = $form_state['style']; if (isset($pane->style['settings'])) { unset($pane->style['settings']); } break; } panels_edit_cache_set($this->cache); $this->commands[] = ctools_modal_command_dismiss(); if ($type == 'pane') { $this->command_update_pane($pane); } else if ($type == 'region') { $this->command_update_region_links($pid); } else { $this->command_update_display_links(); } } else { if ($form_state['style'] != $form_state['old_style']) { $this->cache->style = $form_state['style']; panels_edit_cache_set($this->cache); } // send them to next form. return $this->ajax_style_settings($type, $pid); } } /** * Get the appropriate style from the panel in the cache. * * Since we have styles for regions, panes and the display itself, and * they are stored differently, we use this method to simplify getting * style information into a way that's easy to cope with. */ function get_style($type, $pid = '') { if (isset($this->cache->style)) { $style = panels_get_style($this->cache->style); $defaults = isset($style['defaults']) ? $style['defaults'] : array(); // Get the &$conf variable based upon whose style we're editing. switch ($type) { case 'display': $this->display->panel_settings['style'] = $this->cache->style; $this->display->panel_settings['style_settings']['default'] = $defaults; break; case 'region': $this->display->panel_settings[$pid]['style'] = $this->cache->style; $this->display->panel_settings['style_settings'][$pid] = $defaults; break; case 'pane': $pane = &$this->display->content[$pid]; $pane->style['style'] = $this->cache->style; $pane->style['settings'] = $defaults; $conf = &$pane->style['settings']; break; } } else { switch ($type) { case 'display': $style = panels_get_style((!empty($this->display->panel_settings['style'])) ? $this->display->panel_settings['style'] : 'default'); break; case 'region': $style = panels_get_style((!empty($this->display->panel_settings[$pid]['style'])) ? $this->display->panel_settings[$pid]['style'] : '-1'); break; case 'pane': $pane = &$this->display->content[$pid]; $style = panels_get_style(!empty($pane->style['style']) ? $pane->style['style'] : 'default'); break; } } // Set up our $conf reference. switch ($type) { case 'display': $conf = &$this->display->panel_settings['style_settings']['default']; break; case 'region': $conf = &$this->display->panel_settings['style_settings'][$pid]; break; case 'pane': ctools_include('content'); $pane = &$this->display->content[$pid]; $conf = &$pane->style['settings']; break; } // Backward compatibility: Translate old-style stylizer to new style // stylizer. if ($style['name'] == 'stylizer' && !empty($conf['style']) && $conf['style'] != '$') { $style = panels_get_style('stylizer:' . $conf['style']); } return array($style, &$conf); } /** * AJAX entry point to configure the style for a display, region or pane. * * @param string $type * Either display, region or pane * @param $pid * The pane id, if a pane. The region id, if a region. */ function ajax_style_settings($type, $pid = '') { $info = $this->get_style($type, $pid); $style = $info[0]; $conf = &$info[1]; switch ($type) { case 'display': $title = t('Style settings for @style (display)', array('@style' => $style['title'])); break; case 'region': $title = t('Style settings for style @style (Region "!region")', array('@style' => $style['title'], '!region' => $this->plugins['layout']['regions'][$pid])); break; case 'pane': ctools_include('content'); $pane = &$this->display->content[$pid]; $subtype = ctools_content_get_subtype($pane->type, $pane->subtype); $title = t('Style settings for style @style (Pane "!pane")', array('@style' => $style['title'], '!pane' => $subtype['title'])); break; } $form_state = array( 'display' => &$this->display, 'type' => $type, 'pid' => $pid, 'conf' => &$conf, 'style' => $style, 'ajax' => TRUE, 'title' => $title, 'url' => url($this->get_url('style-settings', $type, $pid), array('absolute' => TRUE)), 'renderer' => &$this, ); $output = ctools_modal_form_wrapper('panels_edit_style_settings_form', $form_state); if (empty($form_state['executed'])) { $this->commands = $output; return; } if (isset($this->cache->style)) { unset($this->cache->style); } if (!empty($form_state['cancel'])) { // The cache must be saved prior to dismissing the modal. panels_edit_cache_set($this->cache); $this->commands[] = ctools_modal_command_dismiss(); return; } // Copy settings from form state back into the cache. if(!empty($form_state['values']['settings'])) { if ($type == 'pane') { $this->cache->display->content[$pid]->style['settings'] = $form_state['values']['settings']; } else if($type == 'region') { $this->cache->display->panel_settings['style_settings'][$pid] = $form_state['values']['settings']; } } panels_edit_cache_set($this->cache); $this->commands[] = ctools_modal_command_dismiss(); if ($type == 'pane') { $this->command_update_pane($pane); } else if ($type == 'region') { $this->command_update_region_links($pid); } else { $this->command_update_display_links(); } } /** * AJAX entry point to configure CSS for a pane. * * @param $pid * The pane id to edit. */ function ajax_pane_css($pid = NULL) { if (empty($this->display->content[$pid])) { ctools_modal_render(t('Error'), t('Invalid pane id.')); } $pane = &$this->display->content[$pid]; $subtype = ctools_content_get_subtype($pane->type, $pane->subtype); $form_state = array( 'display' => &$this->display, 'pane' => &$pane, 'ajax' => TRUE, 'title' => t('Configure CSS on !subtype_title', array('!subtype_title' => $subtype['title'])), ); $output = ctools_modal_form_wrapper('panels_edit_configure_pane_css_form', $form_state); if (empty($form_state['executed'])) { $this->commands = $output; return; } panels_edit_cache_set($this->cache); $this->command_update_pane($pid); $this->commands[] = ctools_modal_command_dismiss(); } /** * AJAX entry point to configure CSS for a pane. * * @param $pid * The pane id to edit. */ function ajax_lock($pid = NULL) { if (empty($this->display->content[$pid])) { ctools_modal_render(t('Error'), t('Invalid pane id.')); } $pane = &$this->display->content[$pid]; $subtype = ctools_content_get_subtype($pane->type, $pane->subtype); $form_state = array( 'display' => &$this->display, 'pane' => &$pane, 'ajax' => TRUE, 'title' => t('Configure lock on !subtype_title', array('!subtype_title' => $subtype['title'])), ); $output = ctools_modal_form_wrapper('panels_edit_configure_pane_lock_form', $form_state); if (empty($form_state['executed'])) { $this->commands = $output; return; } panels_edit_cache_set($this->cache); $this->command_update_pane($pid); $this->commands[] = ctools_modal_command_dismiss(); } /** * AJAX entry point to configure access settings for a pane. * * @param $pid * The pane id to edit. */ function ajax_access_settings($pid = NULL) { if (empty($this->display->content[$pid])) { ctools_modal_render(t('Error'), t('Invalid pane id.')); } $pane = &$this->display->content[$pid]; $subtype = ctools_content_get_subtype($pane->type, $pane->subtype); $form_state = array( 'display' => &$this->display, 'pane' => &$pane, 'ajax' => TRUE, 'title' => t('Access settings on !subtype_title', array('!subtype_title' => $subtype['title'])), ); $output = ctools_modal_form_wrapper('panels_edit_configure_access_settings_form', $form_state); if (empty($form_state['executed'])) { $this->commands = $output; return; } panels_edit_cache_set($this->cache); $this->command_update_pane($pid); $this->commands[] = ctools_modal_command_dismiss(); } /** * AJAX entry point for to add a visibility rule. */ function ajax_access_add_test($pid = NULL) { if (empty($this->display->content[$pid])) { ctools_modal_render(t('Error'), t('Invalid pane id.')); } $pane = &$this->display->content[$pid]; $subtype = ctools_content_get_subtype($pane->type, $pane->subtype); $form_state = array( 'display' => &$this->display, 'pane' => &$pane, 'ajax' => TRUE, 'title' => t('Add visibility rule for !subtype_title', array('!subtype_title' => $subtype['title'])), ); $output = ctools_modal_form_wrapper('panels_edit_add_access_test_form', $form_state); if (!empty($form_state['executed'])) { // Set up the plugin in cache $plugin = ctools_get_access_plugin($form_state['values']['type']); $this->cache->new_plugin = ctools_access_new_test($plugin); panels_edit_cache_set($this->cache); // go to the next step. return $this->ajax_access_configure_test($pid, 'add'); } $this->commands = $output; } /** * AJAX entry point for to configure vsibility rule. */ function ajax_access_configure_test($pid = NULL, $id = NULL) { if (empty($this->display->content[$pid])) { ctools_modal_render(t('Error'), t('Invalid pane id.')); } $pane = &$this->display->content[$pid]; $subtype = ctools_content_get_subtype($pane->type, $pane->subtype); // Set this up here because $id gets changed later. $url = $this->get_url('access-configure-test', $pid, $id); // If we're adding a new one, get the stored data from cache and // add it. It's stored as a cache so that if this is closed // we don't accidentally add an unconfigured plugin. if ($id == 'add') { $pane->access['plugins'][] = $this->cache->new_plugin; $id = max(array_keys($pane->access['plugins'])); } else if (empty($pane->access['plugins'][$id])) { ctools_modal_render(t('Error'), t('Invalid test id.')); } $form_state = array( 'display' => &$this->display, 'pane' => &$pane, 'ajax' => TRUE, 'title' => t('Configure visibility rule for !subtype_title', array('!subtype_title' => $subtype['title'])), 'test' => &$pane->access['plugins'][$id], 'plugin' => ctools_get_access_plugin($pane->access['plugins'][$id]['name']), 'url' => url($url, array('absolute' => TRUE)), ); $output = ctools_modal_form_wrapper('panels_edit_configure_access_test_form', $form_state); if (empty($form_state['executed'])) { $this->commands = $output; return; } // Unset the new plugin if (isset($this->cache->new_plugin)) { unset($this->cache->new_plugin); } if (!empty($form_state['remove'])) { unset($pane->access['plugins'][$id]); } panels_edit_cache_set($this->cache); $this->command_update_pane($pid); $this->commands[] = ctools_modal_command_dismiss(); } /** * AJAX Router function for layout owned AJAX calls. * * Layouts like the flexible layout builder need callbacks of their own. * This allows those layouts to simply declare their callbacks and use * them with $this->get_url('layout', $command). */ function ajax_layout() { $args = func_get_args(); if (empty($args)) { return MENU_NOT_FOUND; } $command = array_shift($args); if (empty($this->plugins['layout']['ajax'][$command]) || !function_exists($this->plugins['layout']['ajax'][$command])) { return MENU_NOT_FOUND; } // Make sure the this is always available to the called functions. array_unshift($args, $this); return call_user_func_array($this->plugins['layout']['ajax'][$command], $args); } /** * AJAX Router function for style owned AJAX calls. * * Styles like the stylizer need AJAX callbacks of their own. This * allows the system to figure out which style is being referenced, * load it, and execute the callback. * * This allows those layouts to simply declare their callbacks and use * them using $this->get_url('style', $command, $type, $pid). */ function ajax_style() { $args = func_get_args(); if (count($args) < 3) { return MENU_NOT_FOUND; } $command = array_shift($args); $type = array_shift($args); $pid = array_shift($args); $info = $this->get_style($type, $pid); $style = $info[0]; $conf = &$info[1]; if (empty($style['ajax'][$command]) || !function_exists($style['ajax'][$command])) { return MENU_NOT_FOUND; } // Make sure the this is always available to the called functions. $args = array_merge(array(&$this, $style, &$conf, $type, $pid), $args); return call_user_func_array($style['ajax'][$command], $args); } // ------------------------------------------------------------------------ // AJAX command generators // // These are used to make sure that child implementations can control their // own AJAX commands as needed. /** * Create a command array to redraw a pane. */ function command_update_pane($pid) { if (is_object($pid)) { $pane = $pid; } else { $pane = $this->display->content[$pid]; } $this->commands[] = ajax_command_replace("#panel-pane-$pane->pid", $this->render_pane($pane)); $this->commands[] = ajax_command_changed("#panel-pane-$pane->pid", "div.grab-title span.text"); } /** * Create a command array to add a new pane. */ function command_add_pane($pid) { if (is_object($pid)) { $pane = $pid; } else { $pane = $this->display->content[$pid]; } $this->commands[] = ajax_command_append("#panel-region-$pane->panel", $this->render_pane($pane)); $this->commands[] = ajax_command_changed("#panel-pane-$pane->pid", "div.grab-title span.text"); } /** * Create a command to update the links on a display after a change was made. */ function command_update_display_links() { $this->commands[] = ajax_command_replace('.panels-display-links', $this->get_display_links()); } /** * Create a command to update the links on a region after a change was made. */ function command_update_region_links($id) { $this->commands[] = ajax_command_replace('.panels-region-links-' . $id, $this->get_region_links($id)); } } /** * Handle the 'next' click on the add/edit pane form wizard. * * All we need to do is store the updated pane in the cache. */ function panels_ajax_edit_pane_next(&$form_state) { $form_state['display cache']->new_pane = $form_state['pane']; panels_edit_cache_set($form_state['display cache']); } /** * Handle the 'finish' click on the add/edit pane form wizard. * * All we need to do is set a flag so the return can handle adding * the pane. */ function panels_ajax_edit_pane_finish(&$form_state) { $form_state['complete'] = TRUE; return; } /** * Handle the 'cancel' click on the add/edit pane form wizard. */ function panels_ajax_edit_pane_cancel(&$form_state) { $form_state['cancel'] = TRUE; return; } // -------------------------------------------------------------------------- // Forms for the editor object /** * Choose cache method form */ function panels_edit_cache_method_form($form, &$form_state) { ctools_form_include($form_state, 'plugins', 'panels'); form_load_include($form_state, 'php', 'panels', '/plugins/display_renderers/panels_renderer_editor.class'); $display = &$form_state['display']; $conf = &$form_state['conf']; // Set to 0 to ensure we get a selected radio. if (!isset($conf['method'])) { $conf['method'] = 0; } $caches = panels_get_caches(); if (empty($caches)) { $form['markup'] = array('#value' => t('No caching options are available at this time. Please enable a panels caching module in order to use caching options.')); return $form; } $options[0] = t('No caching'); foreach ($caches as $cache => $info) { $options[$cache] = check_plain($info['title']); } $form['method'] = array( '#prefix' => '<div class="no-float">', '#suffix' => '</div>', '#type' => 'radios', '#title' => t('Method'), '#options' => $options, '#default_value' => $conf['method'], ); $form['submit'] = array( '#type' => 'submit', '#value' => t('Next'), ); return $form; } /** * Submit callback for panels_edit_cache_method_form. * * All this needs to do is return the method. */ function panels_edit_cache_method_form_submit($form, &$form_state) { $form_state['method'] = $form_state['values']['method']; } /** * Cache settings form */ function panels_edit_cache_settings_form($form, &$form_state) { ctools_form_include($form_state, 'plugins', 'panels'); form_load_include($form_state, 'php', 'panels', '/plugins/display_renderers/panels_renderer_editor.class'); $display = &$form_state['display']; $conf = &$form_state['conf']; $pid = $form_state['pid']; $info = panels_get_cache($conf['method']); $form['#action'] = $form_state['url']; $form['description'] = array( '#prefix' => '<div class="description">', '#suffix' => '</div>', '#value' => check_plain($info['description']), ); $function = panels_plugin_get_function('cache', $conf['method'], 'settings form'); $form['settings'] = $function($conf['settings'], $display, $pid); $form['settings']['#tree'] = TRUE; $form['display'] = array( '#type' => 'value', '#value' => $display, ); $form['pid'] = array( '#type' => 'value', '#value' => $pid, ); $form['submit'] = array( '#type' => 'submit', '#value' => t('Save'), ); return $form; } /** * Validate cache settings. */ function panels_edit_cache_settings_form_validate($form, &$form_state) { if ($function = panels_plugin_get_function('cache', $form_state['conf']['method'], 'settings form validate')) { $function($form, $form_state['values']['settings']); } } /** * Allows panel styles to validate their style settings. */ function panels_edit_cache_settings_form_submit($form, &$form_state) { if ($function = panels_plugin_get_function('cache', $form_state['conf']['method'], 'settings form submit')) { $function($form_state['values']['settings']); } $form_state['conf']['settings'] = $form_state['values']['settings']; } /** * Choose style form */ function panels_edit_style_type_form($form, &$form_state) { ctools_form_include($form_state, 'plugins', 'panels'); form_load_include($form_state, 'php', 'panels', '/plugins/display_renderers/panels_renderer_editor.class'); $display = &$form_state['display']; $style = $form_state['style']; $type = $form_state['type']; $styles = panels_get_styles(); $function = ($type == 'pane' ? 'render pane' : 'render region'); $options = array(); if ($type == 'region') { $options[-1] = t('Use display default style'); } uasort($styles, 'ctools_plugin_sort'); foreach ($styles as $id => $info) { if (empty($info['hidden']) && (!empty($info[$function]) || $id == 'default')) { $options[$id] = check_plain($info['title']); } } $form['style'] = array( '#prefix' => '<div class="no-float">', '#suffix' => '</div>', '#type' => 'radios', '#title' => t('Style'), '#options' => $options, '#default_value' => $style, ); $form['submit'] = array( '#type' => 'submit', '#value' => t('Next'), ); return $form; } /** * Submit callback for panels_edit_style_type_form. * * All this needs to do is return the method. */ function panels_edit_style_type_form_submit($form, &$form_state) { $form_state['old_style'] = $form_state['style']; $form_state['style'] = $form_state['values']['style']; } /** * Style settings form */ function panels_edit_style_settings_form($form, &$form_state) { ctools_form_include($form_state, 'plugins', 'panels'); form_load_include($form_state, 'php', 'panels', '/plugins/display_renderers/panels_renderer_editor.class'); $display = &$form_state['display']; $conf = &$form_state['conf']; $pid = $form_state['pid']; $style = $form_state['style']; $type = $form_state['type']; $form['#action'] = $form_state['url']; $form['description'] = array( '#prefix' => '<div class="description">', '#suffix' => '</div>', '#value' => check_plain($style['description']), ); $function = panels_plugin_get_function('styles', $style, ($type == 'pane') ? 'pane settings form' : 'settings form'); $form['settings'] = $function($conf, $display, $pid, $type, $form_state); $form['settings']['#tree'] = TRUE; $form['submit'] = array( '#type' => 'submit', '#value' => t('Save'), ); // Need a cancel button since the style cache can persist and impact the wrong // pane (or region, or display). $form['cancel_style'] = array( '#type' => 'submit', '#value' => t('Cancel'), '#submit' => array('panels_edit_style_settings_form_cancel'), ); return $form; } /** * Cancel style settings form. * * Clears the editing cache to prevent styles being applied to incorrect regions * or panes. */ function panels_edit_style_settings_form_cancel($form, &$form_state) { $form_state['cancel'] = TRUE; } /** * Validate style settings. */ function panels_edit_style_settings_form_validate($form, &$form_state) { $name = $form_state['type'] == 'pane' ? 'pane settings form validate' : 'settings form validate'; if ($function = panels_plugin_get_function('styles', $form_state['style'], $name)) { $function($form, $form_state['values']['settings'], $form_state); } } /** * Allows panel styles to validate their style settings. */ function panels_edit_style_settings_form_submit($form, &$form_state) { $name = $form_state['type'] == 'pane' ? 'pane settings form submit' : 'settings form submit'; if ($function = panels_plugin_get_function('styles', $form_state['style'], $name)) { $function($form, $form_state['values']['settings'], $form_state); } $form_state['conf'] = $form_state['values']['settings']; } /** * Configure CSS on a pane form. */ function panels_edit_configure_pane_css_form($form, &$form_state) { ctools_form_include($form_state, 'plugins', 'panels'); form_load_include($form_state, 'php', 'panels', '/plugins/display_renderers/panels_renderer_editor.class'); $display = &$form_state['display']; $pane = &$form_state['pane']; $form['css_id'] = array( '#type' => 'textfield', '#default_value' => isset($pane->css['css_id']) ? $pane->css['css_id'] : '', '#title' => t('CSS ID'), '#description' => t('CSS ID to apply to this pane. This may be blank. Keywords from context are allowed.'), ); $form['css_class'] = array( '#type' => 'textfield', '#default_value' => isset($pane->css['css_class']) ? $pane->css['css_class'] : '', '#title' => t('CSS class'), '#description' => t('CSS class to apply to this pane. This may be blank. Keywords from context are allowed.'), ); $form['next'] = array( '#type' => 'submit', '#value' => t('Save'), ); return $form; } /** * FAPI submission function for the CSS configure form. * * All this does is set up $pane properly. The caller is responsible for * actually storing this somewhere. */ function panels_edit_configure_pane_css_form_submit($form, &$form_state) { $pane = &$form_state['pane']; $display = $form_state['display']; $pane->css['css_id'] = $form_state['values']['css_id']; $pane->css['css_class'] = $form_state['values']['css_class']; } /** * Configure lock on a pane form. */ function panels_edit_configure_pane_lock_form($form, &$form_state) { ctools_form_include($form_state, 'plugins', 'panels'); form_load_include($form_state, 'php', 'panels', '/plugins/display_renderers/panels_renderer_editor.class'); $display = &$form_state['display']; $pane = &$form_state['pane']; if (empty($pane->locks)) { $pane->locks = array('type' => 'none', 'regions' => array()); } $form['type'] = array( '#type' => 'radios', '#title' => t('Lock type'), '#options' => array( 'none' => t('No lock'), 'immovable' => t('Immovable'), 'regions' => t('Regions'), ), '#default_value' => $pane->locks['type'], ); $layout = panels_get_layout($display->layout); $regions = panels_get_regions($layout, $display); $form['regions'] = array( '#type' => 'checkboxes', '#title' => t('Regions'), '#options' => $regions, '#description' => t('Select which regions this pane can be moved to.'), '#dependency' => array( 'radio:type' => array('regions'), ), '#default_value' => $pane->locks['regions'], ); $form['#after_build'][] = 'panels_edit_configure_pane_lock_form_after_build'; $form['next'] = array( '#type' => 'submit', '#value' => t('Save'), ); return $form; } function panels_edit_configure_pane_lock_form_after_build($element, $form_state) { $region = $form_state['pane']->panel; $element['regions'][$region]['#required'] = TRUE; $element['regions'][$region]['#disabled'] = TRUE; $element['regions'][$region]['#value'] = TRUE; $element['regions'][$region]['#checked'] = TRUE; $element['regions'][$region]['#attributes']['disabled'] = TRUE; return $element; } /** * FAPI submission function for the lock configure form. * * All this does is set up $pane properly. The caller is responsible for * actually storing this somewhere. */ function panels_edit_configure_pane_lock_form_submit($form, &$form_state) { $pane = &$form_state['pane']; $display = $form_state['display']; // We set this to true but forms do not submit disabled checkboxes // and fapi is ignoring the #value directive probably because it // is checkboxes: $region = $form_state['pane']->panel; $form_state['values']['regions'][$region] = $region; $pane->locks['type'] = $form_state['values']['type']; $pane->locks['regions'] = array_filter($form_state['values']['regions']); } /** * Form to control basic visibility settings. */ function panels_edit_configure_access_settings_form($form, &$form_state) { ctools_form_include($form_state, 'plugins', 'panels'); form_load_include($form_state, 'php', 'panels', '/plugins/display_renderers/panels_renderer_editor.class'); $display = &$form_state['display']; $pane = &$form_state['pane']; $form['logic'] = array( '#type' => 'radios', '#options' => array( 'and' => t('All criteria must pass.'), 'or' => t('Only one criterion must pass.'), ), '#default_value' => isset($pane->access['logic']) ? $pane->access['logic'] : 'and', ); $form['next'] = array( '#type' => 'submit', '#value' => t('Save'), ); return $form; } /** * FAPI submission function for the edit access settings form. * * All this does is set up $pane properly. The caller is responsible for * actually storing this somewhere. */ function panels_edit_configure_access_settings_form_submit($form, &$form_state) { $pane = &$form_state['pane']; $display = $form_state['display']; $pane->access['logic'] = $form_state['values']['logic']; } /** * Form to add a visibility rule. */ function panels_edit_add_access_test_form($form, &$form_state) { ctools_form_include($form_state, 'plugins', 'panels'); form_load_include($form_state, 'php', 'panels', '/plugins/display_renderers/panels_renderer_editor.class'); $display = &$form_state['display']; $pane = &$form_state['pane']; $plugins = ctools_get_relevant_access_plugins($display->context); $options = array(); foreach ($plugins as $id => $plugin) { $options[$id] = $plugin['title']; } asort($options); $form['type'] = array( // This ensures that the form item is added to the URL. '#type' => 'radios', '#options' => $options, ); $form['next'] = array( '#type' => 'submit', '#value' => t('Next'), ); return $form; } /** * Form to configure a visibility rule. */ function panels_edit_configure_access_test_form($form, &$form_state) { ctools_form_include($form_state, 'plugins', 'panels'); form_load_include($form_state, 'php', 'panels', '/plugins/display_renderers/panels_renderer_editor.class'); $display = &$form_state['display']; $test = &$form_state['test']; $plugin = &$form_state['plugin']; $form['#action'] = $form_state['url']; $contexts = $display->context; if (!isset($contexts['logged-in-user'])) { $contexts['logged-in-user'] = ctools_access_get_loggedin_context(); } if (isset($plugin['required context'])) { $form['context'] = ctools_context_selector($contexts, $plugin['required context'], $test['context']); } $form['settings'] = array('#tree' => TRUE); if ($function = ctools_plugin_get_function($plugin, 'settings form')) { $form = $function($form, $form_state, $test['settings']); } $form['not'] = array( '#type' => 'checkbox', '#title' => t('Reverse (NOT)'), '#default_value' => !empty($test['not']), ); $form['save'] = array( '#type' => 'submit', '#value' => t('Save'), ); $form['remove'] = array( '#type' => 'submit', '#value' => t('Remove'), '#remove' => TRUE, ); return $form; } /** * Validate handler for visibility rule settings */ function panels_edit_configure_access_test_form_validate(&$form, &$form_state) { if (!empty($form_state['clicked_button']['#remove'])) { return; } if ($function = ctools_plugin_get_function($form_state['plugin'], 'settings form validate')) { $function($form, $form_state); } } /** * Submit handler for visibility rule settings */ function panels_edit_configure_access_test_form_submit(&$form, &$form_state) { if (!empty($form_state['clicked_button']['#remove'])) { $form_state['remove'] = TRUE; return; } if ($function = ctools_plugin_get_function($form_state['plugin'], 'settings form submit')) { $function($form, $form_state); } $form_state['test']['settings'] = $form_state['values']['settings']; if (isset($form_state['values']['context'])) { $form_state['test']['context'] = $form_state['values']['context']; } $form_state['test']['not'] = !empty($form_state['values']['not']); }
{ "content_hash": "6a23cd9e87ee3ca173a18980c3bd17de", "timestamp": "", "source": "github", "line_count": 2072, "max_line_length": 237, "avg_line_length": 31.936293436293436, "alnum_prop": 0.5738832134437526, "repo_name": "aramboyajyan/d7level3", "id": "c4214dd5067ea3f10e19031aef6cc1a37ac5fcbb", "size": "66172", "binary": false, "copies": "38", "ref": "refs/heads/master", "path": "modules/panels/plugins/display_renderers/panels_renderer_editor.class.php", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "634131" }, { "name": "HTML", "bytes": "640739" }, { "name": "JavaScript", "bytes": "975981" }, { "name": "Makefile", "bytes": "660" }, { "name": "PHP", "bytes": "8472023" }, { "name": "Ruby", "bytes": "804" }, { "name": "Shell", "bytes": "3424" }, { "name": "XSLT", "bytes": "5038" } ], "symlink_target": "" }
/** * @module helpers/Task */ var grunt = require('grunt'); var surrogateSuffix = '_assets_versioning'; var postSuffix = '_post_assets_versioning'; /** * Create a task instance * @param {string} taskName * @param {Array} [taskFiles] * @constructor */ var Task = function (taskName, taskFiles) { grunt.log.writeln("Versioning files from " + taskName + " task."); this.taskName = taskName; this.taskConfig = this.getTaskConfig(); if (!this.taskConfig) { grunt.fail.warn("Task '" + this.taskName + "' doesn't exist or doesn't have any configuration.", 1); } this.taskFiles = taskFiles || this.getFiles(); if (!this.taskFiles || this.taskFiles.length === 0) { grunt.fail.warn("Task '" + this.taskName + "' doesn't have any src-dest file mappings.", 1); } }; /** * Get the task configuration * @returns {Object} */ Task.prototype.getTaskConfig = function () { return grunt.config(this.getTaskConfigKey()); }; /** * Get the task configuration key * @returns {string} */ Task.prototype.getTaskConfigKey = function (taskName) { taskName = taskName || this.taskName; return taskName.replace(':', '.'); }; /** * Get the target task grunt files configuration * @returns {Array} */ Task.prototype.getFiles = function () { return grunt.task.normalizeMultiTaskFiles(this.taskConfig); }; /** * * @param {Array} filesObj * @returns {string} */ Task.prototype.createSurrogate = function (filesObj) { var surrogateTask = this.taskName + surrogateSuffix; var surrogateTaskConfigKey = this.getTaskConfigKey(surrogateTask); if (grunt.config(surrogateTaskConfigKey)) { grunt.fail.warn("Task '" + surrogateTask + "' already exists!"); } var surrogateTaskConfig = this.taskConfig; // remove src & dest keys as they take precedence over the files key delete surrogateTaskConfig.src; delete surrogateTaskConfig.dest; surrogateTaskConfig.files = filesObj; grunt.config.set(surrogateTaskConfigKey, surrogateTaskConfig); grunt.log.debug("Created surrogateTask '" + surrogateTaskConfigKey + "'"); grunt.log.debug("Surrogate Task config: " + JSON.stringify(surrogateTaskConfig)); return surrogateTask; }; /** * * @param {Array} filesObj * @returns {string} */ Task.prototype.createPostVersioningTask = function (filesObj) { var postTask = this.taskName + postSuffix; var taskConfigKey = this.getTaskConfigKey(postTask); if (grunt.config(taskConfigKey)) { grunt.fail.warn("Task '" + postTask + "' already exists!"); } var postTaskConfig = this.taskConfig; // remove src & dest keys as they take precedence over the files key delete postTaskConfig.src; delete postTaskConfig.dest; postTaskConfig.options = postTaskConfig.options || {}; postTaskConfig.options.post = false; postTaskConfig.options.tasks = false; postTaskConfig.isPostVersioningTaskFor = this.getTaskConfigKey(); postTaskConfig.files = filesObj; grunt.config.set(taskConfigKey, postTaskConfig); grunt.log.debug("Created Post Versioning Task '" + taskConfigKey + "'"); grunt.log.debug("Post Versioning Task config: " + JSON.stringify(postTaskConfig)); return this.taskName + postSuffix; }; module.exports = Task;
{ "content_hash": "90f12a0df7e21ff45e9ef84e7cf8b391", "timestamp": "", "source": "github", "line_count": 114, "max_line_length": 104, "avg_line_length": 27.964912280701753, "alnum_prop": 0.7076537013801757, "repo_name": "cjbarth/grunt-assets-versioning", "id": "7186a635dff0ce8cd3eb6cac91ccaf4c38f811ff", "size": "3188", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "tasks/helpers/task.js", "mode": "33188", "license": "mit", "language": [ { "name": "JavaScript", "bytes": "59501" }, { "name": "PHP", "bytes": "265" } ], "symlink_target": "" }
<?php abstract class Scalr_Messaging_Msg_DbMsr extends Scalr_Messaging_Msg { function __construct () { parent::__construct(); } function addDbMsrInfo(Scalr_Db_Msr_Info $msrInfo) { $this->dbType = $msrInfo->databaseType; $this->{$msrInfo->databaseType} = $msrInfo->getMessageProperties(); } }
{ "content_hash": "09270c3335bf8c8d434f19ddbcb6650d", "timestamp": "", "source": "github", "line_count": 13, "max_line_length": 70, "avg_line_length": 23.615384615384617, "alnum_prop": 0.6970684039087948, "repo_name": "wojons/scalr", "id": "44c84505403c4dcd5e259eb8fa7a9e433ea8f31f", "size": "307", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "app/src/Scalr/Messaging/Msg/DbMsr.php", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "JavaScript", "bytes": "7473483" }, { "name": "PHP", "bytes": "11760241" }, { "name": "Python", "bytes": "33435" }, { "name": "Shell", "bytes": "944" } ], "symlink_target": "" }
namespace doppia { using boost::shared_ptr; /// /// Loads images from a video stream stored as a set of images. /// Supports a preprocessor object for things like unbayering, rectification, etc ... /// /// Based on Andreas Ess code /// class VideoFromFiles : public AbstractVideoInput { public: static boost::program_options::options_description get_args_options(); VideoFromFiles(const boost::program_options::variables_map &options, const shared_ptr<StereoCameraCalibration> &stereo_calibration_p); ~VideoFromFiles(); bool next_frame(); bool previous_frame(); const input_image_view_t &get_left_image(); const input_image_view_t &get_right_image(); int get_number_of_frames(); bool set_frame(const int frame_number); /// VideoFromFiles will take ownership over the preprocessor object. /// When VideoFromFiles object is destroyed, AbstractPreprocessor will probably be destroyed too.. void set_preprocessor(const shared_ptr<AbstractPreprocessor> &preprocessor); const shared_ptr<AbstractPreprocessor> &get_preprocessor() const; const StereoCameraCalibration& get_stereo_calibration() const; protected: bool read_frame_from_disk(const int frame_number, input_image_t &left_image, input_image_t &right_image, input_image_view_t &left_view, input_image_view_t &right_view); void read_future_frame_thead(); /// Base for directory and filename std::string left_filename_mask, right_filename_mask; boost::format left_filename_format, right_filename_format; int start_frame, end_frame, total_number_of_frames; shared_ptr<StereoCameraCalibration> stereo_calibration_p; /// Optional preprocessor object shared_ptr<AbstractPreprocessor> preprocessor_p; input_image_t left_image, right_image; input_image_view_t left_image_view, right_image_view; boost::barrier read_future_frame_start_barrier, read_future_frame_ended_barrier; boost::thread image_reading_thread; /// shared_future instead of unique_future to work around lack of move support in pre C++0x compilers boost::shared_future<bool> read_next_image_future; bool found_future_image; int future_image_frame_number; input_image_t future_left_image, future_right_image; input_image_view_t future_left_image_view, future_right_image_view; }; } // end of namespace doppia #endif
{ "content_hash": "5959ddcc86d3e251ae96bfc07586733d", "timestamp": "", "source": "github", "line_count": 78, "max_line_length": 105, "avg_line_length": 31.55128205128205, "alnum_prop": 0.7082486793986185, "repo_name": "LevinJ/Pedestrian-detection-and-tracking", "id": "147c93b29d916935a8186a9eebec0562cac80d21", "size": "2692", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "src/doppia/src/video_input/VideoFromFiles.hpp", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Assembly", "bytes": "10112" }, { "name": "C", "bytes": "9241106" }, { "name": "C++", "bytes": "17667301" }, { "name": "Cuda", "bytes": "268238" }, { "name": "M", "bytes": "2374" }, { "name": "Makefile", "bytes": "2488" }, { "name": "Matlab", "bytes": "55886" }, { "name": "Objective-C", "bytes": "176" }, { "name": "Perl", "bytes": "1417" }, { "name": "Python", "bytes": "482759" }, { "name": "Shell", "bytes": "2863" }, { "name": "Tcl", "bytes": "1739" } ], "symlink_target": "" }
class GURL; class Profile; namespace base { class MessageLoop; } namespace invalidation { class InvalidationService; } namespace syncer { class NetworkResources; class SyncManagerFactory; class UnrecoverableErrorHandler; } namespace sync_driver { class SyncPrefs; } namespace browser_sync { class ChangeProcessor; class SyncBackendHostCore; class SyncBackendRegistrar; struct DoInitializeOptions; // The only real implementation of the SyncBackendHost. See that interface's // definition for documentation of public methods. class SyncBackendHostImpl : public SyncBackendHost, public content::NotificationObserver, public syncer::InvalidationHandler { public: typedef syncer::SyncStatus Status; // Create a SyncBackendHost with a reference to the |frontend| that // it serves and communicates to via the SyncFrontend interface (on // the same thread it used to call the constructor). Must outlive // |sync_prefs|. SyncBackendHostImpl(const std::string& name, Profile* profile, invalidation::InvalidationService* invalidator, const base::WeakPtr<sync_driver::SyncPrefs>& sync_prefs, const base::FilePath& sync_folder); ~SyncBackendHostImpl() override; // SyncBackendHost implementation. void Initialize( sync_driver::SyncFrontend* frontend, scoped_ptr<base::Thread> sync_thread, const syncer::WeakHandle<syncer::JsEventHandler>& event_handler, const GURL& service_url, const syncer::SyncCredentials& credentials, bool delete_sync_data_folder, scoped_ptr<syncer::SyncManagerFactory> sync_manager_factory, const syncer::WeakHandle<syncer::UnrecoverableErrorHandler>& unrecoverable_error_handler, const base::Closure& report_unrecoverable_error_function, syncer::NetworkResources* network_resources, scoped_ptr<syncer::SyncEncryptionHandler::NigoriState> saved_nigori_state) override; void UpdateCredentials(const syncer::SyncCredentials& credentials) override; void StartSyncingWithServer() override; void SetEncryptionPassphrase(const std::string& passphrase, bool is_explicit) override; bool SetDecryptionPassphrase(const std::string& passphrase) override WARN_UNUSED_RESULT; void StopSyncingForShutdown() override; scoped_ptr<base::Thread> Shutdown(syncer::ShutdownReason reason) override; void UnregisterInvalidationIds() override; syncer::ModelTypeSet ConfigureDataTypes( syncer::ConfigureReason reason, const DataTypeConfigStateMap& config_state_map, const base::Callback<void(syncer::ModelTypeSet, syncer::ModelTypeSet)>& ready_task, const base::Callback<void()>& retry_callback) override; void ActivateDataType( syncer::ModelType type, syncer::ModelSafeGroup group, sync_driver::ChangeProcessor* change_processor) override; void DeactivateDataType(syncer::ModelType type) override; void EnableEncryptEverything() override; syncer::UserShare* GetUserShare() const override; scoped_ptr<syncer_v2::SyncContextProxy> GetSyncContextProxy() override; Status GetDetailedStatus() override; syncer::sessions::SyncSessionSnapshot GetLastSessionSnapshot() const override; bool HasUnsyncedItems() const override; bool IsNigoriEnabled() const override; syncer::PassphraseType GetPassphraseType() const override; base::Time GetExplicitPassphraseTime() const override; bool IsCryptographerReady( const syncer::BaseTransaction* trans) const override; void GetModelSafeRoutingInfo( syncer::ModelSafeRoutingInfo* out) const override; void FlushDirectory() const override; void RequestBufferedProtocolEventsAndEnableForwarding() override; void DisableProtocolEventForwarding() override; void EnableDirectoryTypeDebugInfoForwarding() override; void DisableDirectoryTypeDebugInfoForwarding() override; void GetAllNodesForTypes( syncer::ModelTypeSet types, base::Callback<void(const std::vector<syncer::ModelType>&, ScopedVector<base::ListValue>)> type) override; base::MessageLoop* GetSyncLoopForTesting() override; void RefreshTypesForTest(syncer::ModelTypeSet types) override; void ClearServerData( const syncer::SyncManager::ClearServerDataCallback& callback) override; // InvalidationHandler implementation. void OnInvalidatorStateChange(syncer::InvalidatorState state) override; void OnIncomingInvalidation( const syncer::ObjectIdInvalidationMap& invalidation_map) override; std::string GetOwnerName() const override; protected: // The types and functions below are protected so that test // subclasses can use them. // Allows tests to perform alternate core initialization work. virtual void InitCore(scoped_ptr<DoInitializeOptions> options); // Request the syncer to reconfigure with the specfied params. // Virtual for testing. virtual void RequestConfigureSyncer( syncer::ConfigureReason reason, syncer::ModelTypeSet to_download, syncer::ModelTypeSet to_purge, syncer::ModelTypeSet to_journal, syncer::ModelTypeSet to_unapply, syncer::ModelTypeSet to_ignore, const syncer::ModelSafeRoutingInfo& routing_info, const base::Callback<void(syncer::ModelTypeSet, syncer::ModelTypeSet)>& ready_task, const base::Closure& retry_callback); // Called when the syncer has finished performing a configuration. void FinishConfigureDataTypesOnFrontendLoop( const syncer::ModelTypeSet enabled_types, const syncer::ModelTypeSet succeeded_configuration_types, const syncer::ModelTypeSet failed_configuration_types, const base::Callback<void(syncer::ModelTypeSet, syncer::ModelTypeSet)>& ready_task); // Reports backend initialization success. Includes some objects from sync // manager initialization to be passed back to the UI thread. // // |sync_context_proxy| points to an object owned by the SyncManager. // Ownership is not transferred, but we can obtain our own copy of the object // using its Clone() method. virtual void HandleInitializationSuccessOnFrontendLoop( const syncer::WeakHandle<syncer::JsBackend> js_backend, const syncer::WeakHandle<syncer::DataTypeDebugInfoListener> debug_info_listener, syncer_v2::SyncContextProxy* sync_context_proxy, const std::string& cache_guid); // Forwards a ProtocolEvent to the frontend. Will not be called unless a // call to SetForwardProtocolEvents() explicitly requested that we start // forwarding these events. void HandleProtocolEventOnFrontendLoop(syncer::ProtocolEvent* event); // Forwards a directory commit counter update to the frontend loop. Will not // be called unless a call to EnableDirectoryTypeDebugInfoForwarding() // explicitly requested that we start forwarding these events. void HandleDirectoryCommitCountersUpdatedOnFrontendLoop( syncer::ModelType type, const syncer::CommitCounters& counters); // Forwards a directory update counter update to the frontend loop. Will not // be called unless a call to EnableDirectoryTypeDebugInfoForwarding() // explicitly requested that we start forwarding these events. void HandleDirectoryUpdateCountersUpdatedOnFrontendLoop( syncer::ModelType type, const syncer::UpdateCounters& counters); // Forwards a directory status counter update to the frontend loop. Will not // be called unless a call to EnableDirectoryTypeDebugInfoForwarding() // explicitly requested that we start forwarding these events. void HandleDirectoryStatusCountersUpdatedOnFrontendLoop( syncer::ModelType type, const syncer::StatusCounters& counters); // Overwrites the kSyncInvalidationVersions preference with the most recent // set of invalidation versions for each type. void UpdateInvalidationVersions( const std::map<syncer::ModelType, int64>& invalidation_versions); sync_driver::SyncFrontend* frontend() { return frontend_; } private: friend class SyncBackendHostCore; // Checks if we have received a notice to turn on experimental datatypes // (via the nigori node) and informs the frontend if that is the case. // Note: it is illegal to call this before the backend is initialized. void AddExperimentalTypes(); // Handles backend initialization failure. void HandleInitializationFailureOnFrontendLoop(); // Called from Core::OnSyncCycleCompleted to handle updating frontend // thread components. void HandleSyncCycleCompletedOnFrontendLoop( const syncer::sessions::SyncSessionSnapshot& snapshot); // Called when the syncer failed to perform a configuration and will // eventually retry. FinishingConfigurationOnFrontendLoop(..) will be called // on successful completion. void RetryConfigurationOnFrontendLoop(const base::Closure& retry_callback); // Helpers to persist a token that can be used to bootstrap sync encryption // across browser restart to avoid requiring the user to re-enter their // passphrase. |token| must be valid UTF-8 as we use the PrefService for // storage. void PersistEncryptionBootstrapToken( const std::string& token, syncer::BootstrapTokenType token_type); // For convenience, checks if initialization state is INITIALIZED. bool initialized() const { return initialized_; } // Let the front end handle the actionable error event. void HandleActionableErrorEventOnFrontendLoop( const syncer::SyncProtocolError& sync_error); // Handle a migration request. void HandleMigrationRequestedOnFrontendLoop(const syncer::ModelTypeSet types); // Checks if |passphrase| can be used to decrypt the cryptographer's pending // keys that were cached during NotifyPassphraseRequired. Returns true if // decryption was successful. Returns false otherwise. Must be called with a // non-empty pending keys cache. bool CheckPassphraseAgainstCachedPendingKeys( const std::string& passphrase) const; // Invoked when a passphrase is required to decrypt a set of Nigori keys, // or for encrypting. |reason| denotes why the passphrase was required. // |pending_keys| is a copy of the cryptographer's pending keys, that are // cached by the frontend. If there are no pending keys, or if the passphrase // required reason is REASON_ENCRYPTION, an empty EncryptedData object is // passed. void NotifyPassphraseRequired(syncer::PassphraseRequiredReason reason, sync_pb::EncryptedData pending_keys); // Invoked when the passphrase provided by the user has been accepted. void NotifyPassphraseAccepted(); // Invoked when the set of encrypted types or the encrypt // everything flag changes. void NotifyEncryptedTypesChanged( syncer::ModelTypeSet encrypted_types, bool encrypt_everything); // Invoked when sync finishes encrypting new datatypes. void NotifyEncryptionComplete(); // Invoked when the passphrase state has changed. Caches the passphrase state // for later use on the UI thread. // If |type| is FROZEN_IMPLICIT_PASSPHRASE or CUSTOM_PASSPHRASE, // |explicit_passphrase_time| is the time at which that passphrase was set // (if available). void HandlePassphraseTypeChangedOnFrontendLoop( syncer::PassphraseType type, base::Time explicit_passphrase_time); void HandleLocalSetPassphraseEncryptionOnFrontendLoop( const syncer::SyncEncryptionHandler::NigoriState& nigori_state); // Dispatched to from OnConnectionStatusChange to handle updating // frontend UI components. void HandleConnectionStatusChangeOnFrontendLoop( syncer::ConnectionStatus status); // NotificationObserver implementation. void Observe(int type, const content::NotificationSource& source, const content::NotificationDetails& details) override; void ClearServerDataDoneOnFrontendLoop( const syncer::SyncManager::ClearServerDataCallback& frontend_callback); content::NotificationRegistrar notification_registrar_; // A reference to the MessageLoop used to construct |this|, so we know how // to safely talk back to the SyncFrontend. base::MessageLoop* const frontend_loop_; Profile* const profile_; // Name used for debugging (set from profile_->GetDebugName()). const std::string name_; // Our core, which communicates directly to the syncapi. Use refptr instead // of WeakHandle because |core_| is created on UI loop but released on // sync loop. scoped_refptr<SyncBackendHostCore> core_; // A handle referencing the main interface for non-blocking sync types. scoped_ptr<syncer_v2::SyncContextProxy> sync_context_proxy_; bool initialized_; const base::WeakPtr<sync_driver::SyncPrefs> sync_prefs_; ExtensionsActivityMonitor extensions_activity_monitor_; scoped_ptr<SyncBackendRegistrar> registrar_; // The frontend which we serve (and are owned by). sync_driver::SyncFrontend* frontend_; // We cache the cryptographer's pending keys whenever NotifyPassphraseRequired // is called. This way, before the UI calls SetDecryptionPassphrase on the // syncer, it can avoid the overhead of an asynchronous decryption call and // give the user immediate feedback about the passphrase entered by first // trying to decrypt the cached pending keys on the UI thread. Note that // SetDecryptionPassphrase can still fail after the cached pending keys are // successfully decrypted if the pending keys have changed since the time they // were cached. sync_pb::EncryptedData cached_pending_keys_; // The state of the passphrase required to decrypt the bag of encryption keys // in the nigori node. Updated whenever a new nigori node arrives or the user // manually changes their passphrase state. Cached so we can synchronously // check it from the UI thread. syncer::PassphraseType cached_passphrase_type_; // If an explicit passphrase is in use, the time at which the passphrase was // first set (if available). base::Time cached_explicit_passphrase_time_; // UI-thread cache of the last SyncSessionSnapshot received from syncapi. syncer::sessions::SyncSessionSnapshot last_snapshot_; invalidation::InvalidationService* invalidator_; bool invalidation_handler_registered_; base::WeakPtrFactory<SyncBackendHostImpl> weak_ptr_factory_; DISALLOW_COPY_AND_ASSIGN(SyncBackendHostImpl); }; } // namespace browser_sync #endif // CHROME_BROWSER_SYNC_GLUE_SYNC_BACKEND_HOST_IMPL_H_
{ "content_hash": "bf14f01f454e723b7de3395a26d3618b", "timestamp": "", "source": "github", "line_count": 349, "max_line_length": 80, "avg_line_length": 41.90830945558739, "alnum_prop": 0.7520853274989744, "repo_name": "Just-D/chromium-1", "id": "3f1501838457c4a3c0a0552715bd70d613796ed3", "size": "15984", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "chrome/browser/sync/glue/sync_backend_host_impl.h", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "AppleScript", "bytes": "6973" }, { "name": "Arduino", "bytes": "464" }, { "name": "Assembly", "bytes": "37073" }, { "name": "Batchfile", "bytes": "8451" }, { "name": "C", "bytes": "9517927" }, { "name": "C++", "bytes": "244067615" }, { "name": "CSS", "bytes": "944025" }, { "name": "DM", "bytes": "60" }, { "name": "Groff", "bytes": "2494" }, { "name": "HTML", "bytes": "27307576" }, { "name": "Java", "bytes": "14757472" }, { "name": "JavaScript", "bytes": "20666212" }, { "name": "Makefile", "bytes": "70864" }, { "name": "Objective-C", "bytes": "1772355" }, { "name": "Objective-C++", "bytes": "10088862" }, { "name": "PHP", "bytes": "97817" }, { "name": "PLpgSQL", "bytes": "178732" }, { "name": "Perl", "bytes": "63937" }, { "name": "Protocol Buffer", "bytes": "485040" }, { "name": "Python", "bytes": "8652947" }, { "name": "Shell", "bytes": "481276" }, { "name": "Standard ML", "bytes": "5106" }, { "name": "XSLT", "bytes": "418" }, { "name": "nesC", "bytes": "18347" } ], "symlink_target": "" }
<?xml version="1.0" encoding="utf-8"?> <!-- ~ Copyright (c) WSO2 Inc. (http://www.wso2.org) All Rights Reserved. ~ ~ Licensed under the Apache License, Version 2.0 (the "License"); ~ you may not use this file except in compliance with the License. ~ You may obtain a copy of the License at ~ ~ http://www.apache.org/licenses/LICENSE-2.0 ~ ~ Unless required by applicable law or agreed to in writing, software ~ distributed under the License is distributed on an "AS IS" BASIS, ~ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ~ See the License for the specific language governing permissions and ~ limitations under the License. --> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd"> <parent> <groupId>org.wso2.carbon.storagemgt</groupId> <artifactId>hadoop.hdfs-feature</artifactId> <version>4.3.0-SNAPSHOT</version> <relativePath>../pom.xml</relativePath> </parent> <modelVersion>4.0.0</modelVersion> <artifactId>org.wso2.carbon.identity.authenticator.krb5.ui.feature</artifactId> <version>4.3.0-SNAPSHOT</version> <packaging>pom</packaging> <name>WSO2 Carbon - Kerberos Authenticator UI Feature</name> <url>http://wso2.org</url> <description>This feature contains Kerberos authenticator UI</description> <dependencies> <dependency> <groupId>org.wso2.carbon.storagemgt</groupId> <artifactId>org.wso2.carbon.identity.authenticator.krb5.ui</artifactId> </dependency> <dependency> <groupId>org.wso2.carbon.storagemgt</groupId> <artifactId>org.wso2.carbon.identity.authenticator.krb5.stub</artifactId> </dependency> <dependency> <groupId>org.wso2.carbon</groupId> <artifactId>org.wso2.carbon.core.server.feature</artifactId> <type>zip</type> </dependency> </dependencies> <build> <plugins> <plugin> <groupId>org.wso2.maven</groupId> <artifactId>carbon-p2-plugin</artifactId> <version>${carbon.p2.plugin.version}</version> <executions> <execution> <id>4-p2-feature-generation</id> <phase>package</phase> <goals> <goal>p2-feature-gen</goal> </goals> <configuration> <id>org.wso2.carbon.identity.authenticator.krb5.ui</id> <propertiesFile>../../../../etc/feature.properties</propertiesFile> <adviceFile> <properties> <propertyDef>org.wso2.carbon.p2.category.type:console</propertyDef> <propertyDef>org.eclipse.equinox.p2.type.group:false</propertyDef> </properties> </adviceFile> <bundles> <bundleDef>org.wso2.carbon.storagemgt:org.wso2.carbon.identity.authenticator.krb5.ui</bundleDef> <bundleDef>org.wso2.carbon.storagemgt:org.wso2.carbon.identity.authenticator.krb5.stub</bundleDef> </bundles> <importFeatures> <importFeatureDef>org.wso2.carbon.core.ui:${carbon.kernel.version}</importFeatureDef> </importFeatures> </configuration> </execution> </executions> </plugin> </plugins> </build> </project>
{ "content_hash": "52f4a4391c0a54593ce355bdb87250e2", "timestamp": "", "source": "github", "line_count": 89, "max_line_length": 130, "avg_line_length": 45, "alnum_prop": 0.5508114856429464, "repo_name": "lankavitharana/carbon-storage-management", "id": "f508df6dd21d9f23bdb6f16da52d6b933cd04899", "size": "4005", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "features/hadoop/hdfs/org.wso2.carbon.identity.authenticator.krb5.ui.feature/pom.xml", "mode": "33261", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "74343" }, { "name": "Java", "bytes": "2436748" }, { "name": "JavaScript", "bytes": "1181116" } ], "symlink_target": "" }
### Sum of Left Leaves Find the sum of all left leaves in a given binary tree. Example: ``` 3 / \ 9 20 / \ 15 7 ``` There are two left leaves in the binary tree, with values 9 and 15 respectively. Return 24. #### Solution ```java /** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */ public class Solution { /** We only need to consider node.left. The rest node just all recursive check. */ public int sumOfLeftLeaves(TreeNode root) { if (root == null) return 0; int sum = 0; if (root.left != null) { if (root.left.left == null && root.left.right == null) { sum += root.left.val; } else { sum += sumOfLeftLeaves(root.left); } } if (root.right != null) { sum += sumOfLeftLeaves(root.right); } return sum; } } ```
{ "content_hash": "fdc6a1b95d5154383c06bd3e7a95ad48", "timestamp": "", "source": "github", "line_count": 52, "max_line_length": 91, "avg_line_length": 20.692307692307693, "alnum_prop": 0.49535315985130113, "repo_name": "kentsay/TIL", "id": "0351f9a7210f665a3852a78f34d19cd907474c8f", "size": "1076", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "algorithm/leetcode-404-sumofleftleaves.md", "mode": "33188", "license": "mit", "language": [], "symlink_target": "" }
/* TEMPLATE GENERATED TESTCASE FILE Filename: CWE122_Heap_Based_Buffer_Overflow__cpp_CWE193_char_cpy_81_goodG2B.cpp Label Definition File: CWE122_Heap_Based_Buffer_Overflow__cpp_CWE193.label.xml Template File: sources-sink-81_goodG2B.tmpl.cpp */ /* * @description * CWE: 122 Heap Based Buffer Overflow * BadSource: Allocate memory for a string, but do not allocate space for NULL terminator * GoodSource: Allocate enough memory for a string and the NULL terminator * Sinks: cpy * BadSink : Copy string to data using strcpy() * Flow Variant: 81 Data flow: data passed in a parameter to an virtual method called via a reference * * */ #ifndef OMITGOOD #include "std_testcase.h" #include "CWE122_Heap_Based_Buffer_Overflow__cpp_CWE193_char_cpy_81.h" namespace CWE122_Heap_Based_Buffer_Overflow__cpp_CWE193_char_cpy_81 { void CWE122_Heap_Based_Buffer_Overflow__cpp_CWE193_char_cpy_81_goodG2B::action(char * data) const { { char source[10+1] = SRC_STRING; /* POTENTIAL FLAW: data may not have enough space to hold source */ strcpy(data, source); printLine(data); delete [] data; } } } #endif /* OMITGOOD */
{ "content_hash": "211c23228ef22c164950d66459eb5dfb", "timestamp": "", "source": "github", "line_count": 36, "max_line_length": 101, "avg_line_length": 33.416666666666664, "alnum_prop": 0.6940980881130507, "repo_name": "JianpingZeng/xcc", "id": "08f1cbf55aacd78d960bdb35338e4b4367007173", "size": "1203", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "xcc/test/juliet/testcases/CWE122_Heap_Based_Buffer_Overflow/s01/CWE122_Heap_Based_Buffer_Overflow__cpp_CWE193_char_cpy_81_goodG2B.cpp", "mode": "33188", "license": "bsd-3-clause", "language": [], "symlink_target": "" }