text
stringlengths
2
1.04M
meta
dict
/* Global Container */ .liquidDesign #globalContainer { width: 80% !important; } .liquidDesign.sidebarDisplay.sidebarMode #globalContainer { width: calc(90% - 206px) !important; } .liquidDesign:not(.sidebarDisplay) #globalContainer { padding-right: 0 !important; } /* Header */ #fbCoverImageContainer { overflow-x: hidden; } /* Left Column */ #leftCol.fixedTop { position: fixed !important; /* top: 43px; specify by code */ bottom: auto; } #leftCol.fixedBottom { position: fixed !important; top: auto !important; bottom: 0; } .navHeader { border-bottom: solid 1px #90949c; margin-bottom: 4px !important; } .tinyWidth .sideNavItem ._5afe { margin-left: 0 !important; } /* Right Column */ #rightCol { width: 100% !important; clear: right; margin-bottom: -16px; display: none; } .trendingDisplay #rightCol { display: block; } #rightCol .fixed_elem { position: static !important; width: auto !important; } #rightCol .fixed_elem + div { height: 0 !important; } #rightCol ._64a > div[style*="height"] { height: auto !important; } .newsFeedComposer .home_right_column { min-height: 0 !important; } .groups_rhc .uiBoxWhite { border: none !important; } #pagelet_ego_pane, #rhc_work_feedback_pagelet, #pagelet_rhc_footer { display: none; } #groupsNewMembersLink, #admin_flyout_container, .groups_rhc .groupRHCAddMemberTypeaheadBox, .groups_rhc .groupsRHCSectionHeader h6, .groups_rhc .groupsRHCSectionHeader + span { display: none; } .groups_rhc > div:not(:first-child), .groups_rhc > div:first-child > div:first-child { display: none; } .groupsEditDescriptionArea .uiHeaderActions { margin-bottom: -12px !important; } #groupsDescriptionBox .groupsEditDescriptionText { width: 99% !important; height: 150px !important; } /* Content Area */ #contentArea { width: 100% !important; } /* Pagelet Sidebar */ .fbChatSidebar { margin-right: -205px; } .sidebarDisplay .fbChatSidebar { margin-right: 0; } .sidebarMode:not(.sidebarDisplay) ._55fl { display: none !important; } html:not(.topGroupsDisplay) .fbChatSidebar ._1vze { display: none; } /* Expand/Collapse Pagelet Sidebar Horizontally */ .fbChatSidebar::before, #chatSidebarSlider { /* image size = 24x24px, margin = 4px */ background-position: center right; background-repeat: no-repeat; position: absolute; top: 50%; width: 32px; height: 32px; margin-left: -32px; margin-top: 5px; } .mac .fbChatSidebar::before, .mac #chatSidebarSlider { background-position: center left; /* to avoid overlapping by scrollbar */ } .fbChatSidebar::before { content: ''; background-image: url('chrome-extension://__MSG_@@extension_id__/image/ic_chevron_right.png'); } #chatSidebarSlider { background-image: url('chrome-extension://__MSG_@@extension_id__/image/ic_chevron_right_hover.png'); cursor: pointer; visibility: hidden; } .fbChatSidebar:hover #chatSidebarSlider { visibility: visible; } .collapsed .fbChatSidebar::before { background-image: url('chrome-extension://__MSG_@@extension_id__/image/ic_chevron_left.png'); } .collapsed #chatSidebarSlider { background-image: url('chrome-extension://__MSG_@@extension_id__/image/ic_chevron_left_hover.png'); } /* Profile */ .timelineLayout #mainContainer #contentArea { width: 1014px !important; } .liquidDesign .timelineLayout #mainContainer #contentArea { width: 100% !important; } .timelineLayout ._5nb8 { width: calc(100% - 323px - 15px) !important; } ._4lh .fbTimelineTwoColumn[data-type="s"] { width: 100% !important; } .fbTimelineUnit.fbTimelineTwoColumn .timelineUnitContainer.fbTimelineComposerUnit { width: 100% !important; } /* Settings */ .SettingsPage.hasLeftCol #contentArea { padding: 0 !important; } /* "Recent Activity" and "Older" */ #contentArea div[role="heading"] { border-left: 4px solid #4267b2; margin: 28px 8px; padding: 2px 8px; } #contentArea div[role="heading"] span { color: #1d2129; font-size: 14px; } /* Trending Posts */ .singleLineTrending #pagelet_work_trending_rhc_unit ._4bl9 { margin-right: 0.5em; text-overflow: ellipsis; white-space: nowrap; } /* Scroll to Top */ #scrollToTop { position: fixed; bottom: 0; right: 16px; padding-left: 4px; padding-bottom: 25px; display: none; } .sidebarMode #scrollToTop { right: auto; padding-bottom: 0; } .sidebarMode #pagelet_dock ._48gf { /*height: 0; FIXME the bootom toolbar of chat window won't displayed */ } #scrollToTop a { text-decoration: none; } #scrollToTop i { display: inline-block; /* image size = 24x24px, margin = 4px */ width: 32px; height: 32px; background-image: url('chrome-extension://__MSG_@@extension_id__/image/ic_play_circle_outline.png'); background-position: center center; background-repeat: no-repeat; } #scrollToTop i:hover { background-image: url('chrome-extension://__MSG_@@extension_id__/image/ic_play_circle_filled.png'); } /* mouse hover */ a.hoverVisible { opacity: 0; transition: opacity 400ms; } .fbUserContent:hover a.hoverVisible, .userContentWrapper:hover a.hoverVisible { opacity: 1; } /* Expand All */ .expandAll { float: right; margin: 0 4px 4px 4px; } .expandAll i { display: inline-block; width: 18px; height: 18px; background-image: url('chrome-extension://__MSG_@@extension_id__/image/ic_format_line_spacing.png'); background-size: cover; background-repeat: no-repeat; } /* Read Later */ .readLater { float: right; margin: 0 24px 4px 4px; } .readLater i { display: inline-block; width: 18px; height: 18px; background-image: url('chrome-extension://__MSG_@@extension_id__/image/ic_bookmark_border.png'); background-size: cover; background-repeat: no-repeat; } .readLater.pinned i { background-image: url('chrome-extension://__MSG_@@extension_id__/image/ic_bookmark.png'); } /* Media Query */ @media (max-width: 1920px) { /* WUXGA */ } @media (max-width: 1600px) { /* UXGA */ .liquidDesign #globalContainer { width: 85% !important; } .liquidDesign.sidebarDisplay.sidebarMode #globalContainer { width: calc(95% - 206px) !important; } } @media (max-width: 1280px) { /* SXGA */ .liquidDesign #globalContainer { width: 90% !important; } } @media (max-width: 1024px) { /* XGA */ #globalContainer, .liquidDesign #globalContainer { width: 100% !important; } .timelineLayout #mainContainer #contentArea { width: 100% !important; } } @media (max-width: 800px) { /* SVGA */ } @media (max-width: 640px) { /* VGA */ } /* Workaround for another HTML structure */ #leftCol._1qkq._1qks { position: relative !important; } #content_container > #rightCol, #content_container > #contentArea { position: static !important; } #content_container > #rightCol { margin-left: 12px !important; }
{ "content_hash": "934f0d5900dc8f2c91bee5125264d82d", "timestamp": "", "source": "github", "line_count": 337, "max_line_length": 104, "avg_line_length": 20.729970326409497, "alnum_prop": 0.6699112510735757, "repo_name": "rockwillj/Workplace-Readable", "id": "c62a600d88c0a01063aaaec651e934947183bbd8", "size": "6986", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "css/content.css", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "8046" }, { "name": "HTML", "bytes": "2274" }, { "name": "JavaScript", "bytes": "18208" } ], "symlink_target": "" }
package ecommerce import org.json4s.FullTypeHints import org.json4s.ext.EnumSerializer import pl.newicom.dddd.messaging.event.AggregateSnapshotId import pl.newicom.dddd.office.OfficeInfo import pl.newicom.dddd.serialization.JsonSerializationHints package object sales { implicit val salesOffice: OfficeInfo[SalesOffice] = OfficeInfo("Reservation", new JsonSerializationHints { val typeHints = ReservationCommands + ReservationEvents + SalesValueObjects val serializers = List(new EnumSerializer(ProductType)) object ReservationCommands extends FullTypeHints( List( classOf[CreateReservation], classOf[ReserveProduct], classOf[ConfirmReservation], classOf[CancelReservation], classOf[CloseReservation] )) object ReservationEvents extends FullTypeHints( List( classOf[ReservationCreated], classOf[ProductReserved], classOf[ReservationConfirmed], classOf[ReservationCanceled], classOf[ReservationClosed] )) object SalesValueObjects extends FullTypeHints( List( classOf[ReservationItem], classOf[Product], classOf[AggregateSnapshotId], classOf[Money] ) ) }) }
{ "content_hash": "27dc85ba04ca2fc9699394deb70b0059", "timestamp": "", "source": "github", "line_count": 42, "max_line_length": 108, "avg_line_length": 29.476190476190474, "alnum_prop": 0.721324717285945, "repo_name": "dominhtung/ddd-leaven-akka-v2", "id": "9b563880f21501de26e26502602e66d7600c6587", "size": "1238", "binary": false, "copies": "4", "ref": "refs/heads/master", "path": "sales/contracts/src/main/scala/ecommerce/sales/package.scala", "mode": "33188", "license": "mit", "language": [ { "name": "HTML", "bytes": "6653" }, { "name": "JavaScript", "bytes": "3460" }, { "name": "Ruby", "bytes": "3539" }, { "name": "Scala", "bytes": "86524" }, { "name": "Shell", "bytes": "2370" } ], "symlink_target": "" }
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE module PUBLIC "-//Puppy Crawl//DTD Check Configuration 1.1//EN" "http://www.puppycrawl.com/dtds/configuration_1_1.dtd"> <module name="Checker"> <module name="TreeWalker"> <module name="TypeName"> <property name="format" value="^[a-z0-9]*$"/> <property name="severity" value="error"/> </module> </module> </module>
{ "content_hash": "9b5d7e9cdaa946742278c66d03d1f0da", "timestamp": "", "source": "github", "line_count": 14, "max_line_length": 63, "avg_line_length": 30.642857142857142, "alnum_prop": 0.5827505827505828, "repo_name": "mkordas/checkstyle", "id": "74f625fd3d3761b1f7adbff06ac6af91426779a9", "size": "429", "binary": false, "copies": "33", "ref": "refs/heads/master", "path": "src/test/resources/com/puppycrawl/tools/checkstyle/config-classname2-error.xml", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "644" }, { "name": "GAP", "bytes": "67171" }, { "name": "Java", "bytes": "4412656" }, { "name": "JavaScript", "bytes": "1064" }, { "name": "Shell", "bytes": "795" } ], "symlink_target": "" }
cinema.views.StaticSearchOptionsWidget = Backbone.View.extend({ events: { 'change input': function (e) { var el = $(e.target), option = el.closest('.c-options-option').attr('option_id'), value = el.val(); this.updateIndex(option, value); }, 'mousemove input': function (e) { var el = $(e.target), option = el.closest('.c-options-option').attr('option_id'), value = el.val(); this.updateIndex(option, value); }, 'click .c-options-option-button': function (e) { var el = $(e.target), option = el.closest('.c-options-option').attr('option_id'), action = el.attr('action'); this[action](option); } }, initialize: function (settings) { this.zoomLevel = 0.23; this.zoomWidth = $(window).width() * this.zoomLevel; this.toolbarSelector = settings.toolbarSelector; this.toolbarRootView = settings.toolbarRootView || this; this.toolbarView = new cinema.views.StaticSearchToolsToolbar({el: $(this.toolbarSelector, this.toolbarRootView) }); this._annotateOptions(); }, _formatLabel: function (val) { return Number(val).toFixed(2); }, _annotateOptions: function () { this.optionMap = { zoom: { icon: 'icon-zoom-in', iconlabel: 'nbsp', label: '0.25', type: 'range', value: 23, min: 1, max: 100, step: 1 } }; this.options = ['zoom']; }, render: function () { this.$el.html(cinema.templates.searchOptions({ optionMap: this.optionMap, options: this.options })); this.toolbarView.setElement($(this.toolbarSelector, this.toolbarRootView.$el)).render(); }, _refresh: function () { this.options.forEach(function (optionName) { var group = this.$('.c-options-option[option_id="' + optionName + '"]'), label = Number(this.optionMap[optionName].value)/100.0, idx = this.optionMap[optionName].value; group.find('label.value').text( this._formatLabel(label) ); group.find('input').val(idx); }.bind(this)); }, updateIndex: function (optionName, index) { if (optionName === 'zoom') { if (index !== this.optionMap[optionName].value) { this.optionMap[optionName].value = index; this.zoomLevel = Number(this.optionMap[optionName].value) / 100.0; this.zoomWidth = $(window).width() * this.zoomLevel; this._refresh(); cinema.events.trigger('c:handlesearchzoom', {zoomWidth: this.zoomWidth}); } } }, next: function (optionName) { if (optionName === 'zoom') { if (this.optionMap[optionName].value === this.optionMap[optionName].max) { return; } else { this.optionMap[optionName].value = Number(this.optionMap[optionName].value) + 1; this.zoomLevel = this.optionMap[optionName].value / 100.0; this.zoomWidth = $(window).width() * this.zoomLevel; this._refresh(); cinema.events.trigger('c:handlesearchzoom', {zoomWidth: this.zoomWidth}); } } }, previous: function (optionName) { if (optionName === 'zoom') { if (this.optionMap[optionName].value === this.optionMap[optionName].min) { return; } else { this.optionMap[optionName].value -= 1; this.zoomLevel = Number(this.optionMap[optionName].value) / 100.0; this.zoomWidth = $(window).width() * this.zoomLevel; this._refresh(); cinema.events.trigger('c:handlesearchzoom', {zoomWidth: this.zoomWidth}); } } }, last: function (optionName) { if (optionName === 'zoom') { this.optionMap[optionName].value = this.optionMap[optionName].max; this.zoomLevel = Number(this.optionMap[optionName].value) / 100.0; this.zoomWidth = $(window).width() * this.zoomLevel; this._refresh(); cinema.events.trigger('c:handlesearchzoom', {zoomWidth: this.zoomWidth}); } }, first: function (optionName) { if (optionName === 'zoom') { this.optionMap[optionName].value = this.optionMap[optionName].min; this.zoomLevel = Number(this.optionMap[optionName].value) / 100.0; this.zoomWidth = $(window).width() * this.zoomLevel; cinema.events.trigger('c:handlesearchzoom', {zoomWidth: this.zoomWidth}); this._refresh(); } }, getZoomWidth: function() { return this.zoomWidth; } });
{ "content_hash": "1e50249e19f47ab086ac61bf07f56723", "timestamp": "", "source": "github", "line_count": 142, "max_line_length": 123, "avg_line_length": 35.78169014084507, "alnum_prop": 0.5264711670930919, "repo_name": "Kitware/cinema", "id": "9a0583e7310263c8c3af267f231bd3f7df84665b", "size": "5081", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "web/src/js/lib/widgets/StaticSearchOptionsWidget.js", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "C", "bytes": "6645" }, { "name": "CMake", "bytes": "1046" }, { "name": "CSS", "bytes": "160244" }, { "name": "HTML", "bytes": "108738" }, { "name": "JavaScript", "bytes": "628674" }, { "name": "Python", "bytes": "244273" } ], "symlink_target": "" }
package model import "google.golang.org/appengine/datastore" //go:generate generator // Template contains data about a code template assigned to a Task type Template struct { Language string `datastore:",index"` Path string `datastore:",noindex"` Challenge *datastore.Key `datastore:",index"` }
{ "content_hash": "3fddb97dacbc0af01aab930b8190159c", "timestamp": "", "source": "github", "line_count": 12, "max_line_length": 66, "avg_line_length": 26.916666666666668, "alnum_prop": 0.7120743034055728, "repo_name": "coduno/api", "id": "1e05931d5ec2b9b25d76b9bd0d5eb2c4a7687c5b", "size": "323", "binary": false, "copies": "3", "ref": "refs/heads/master", "path": "model/template.go", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Go", "bytes": "200930" }, { "name": "Java", "bytes": "130" }, { "name": "Makefile", "bytes": "308" }, { "name": "Shell", "bytes": "389" } ], "symlink_target": "" }
declare function stringify(data: any): string; export default stringify;
{ "content_hash": "cd3036fd3a912e3937c61b2ecfbf4ea9", "timestamp": "", "source": "github", "line_count": 3, "max_line_length": 46, "avg_line_length": 24.666666666666668, "alnum_prop": 0.7972972972972973, "repo_name": "chaitanyaT99/irRemoteServer", "id": "1d6d1ac4b9b1b1c99f2d545df9e61f9fb0a7899b", "size": "74", "binary": false, "copies": "3", "ref": "refs/heads/master", "path": "node_modules/fast-safe-stringify/index.d.ts", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "4725" }, { "name": "HTML", "bytes": "1673" }, { "name": "JavaScript", "bytes": "1520" } ], "symlink_target": "" }
package io.ttl.sys.math; import io.ttl.val.Frame; import io.ttl.val.Nil; import io.ttl.val.SysFun; import io.ttl.val.Val; public class Round extends SysFun { @Override protected Val syscall(Frame frame) { // TODO return Nil.NIL; } }
{ "content_hash": "58307ddfb6956765de5ec2ad2f451309", "timestamp": "", "source": "github", "line_count": 15, "max_line_length": 40, "avg_line_length": 17.6, "alnum_prop": 0.6590909090909091, "repo_name": "invider/ttl", "id": "6c179349e27276ded45e455b9a2d3071bc241383", "size": "264", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/main/java/io/ttl/sys/math/Round.java", "mode": "33188", "license": "mit", "language": [ { "name": "Groff", "bytes": "848" }, { "name": "Java", "bytes": "88328" }, { "name": "Shell", "bytes": "440" } ], "symlink_target": "" }
$(document).ready(function () { // Feeds comunistes.cat $('#feed-bloc').rssfeed('http://bloc.comunistes.cat/feeds/posts/default',{ snippet: false, limit: 1 }); $('#feed-imatges').rssfeed('http://imatges.comunistes.cat/feeds/posts/default',{ snippet: false, limit: 1 }); $('#feed-videos').rssfeed('http://videos.comunistes.cat/feeds/posts/default',{ snippet: false, limit: 1 }); $('#feed-som').rssfeed('http://som.comunistes.cat/feeds/posts/default',{ snippet: false, limit: 1 }); $('#feed-videos-last').rssfeed('http://videos.comunistes.cat/feeds/posts/default',{ snippet: false, limit: 3 }); // Feeds filtrats del bloc $('#feed-bloc-campanyes').rssfeed('http://bloc.comunistes.cat/feeds/posts/default/-/Campanyes',{ snippet: false, limit: 1 }); $('#feed-bloc-comunicats').rssfeed('http://bloc.comunistes.cat/feeds/posts/default/-/Comunicats',{ snippet: false, limit: 1 }); $('#feed-bloc-documents').rssfeed('http://bloc.comunistes.cat/feeds/posts/default/-/Documents',{ snippet: false, limit: 1 }); $('#feed-bloc-actualitat').rssfeed('http://bloc.comunistes.cat/feeds/posts/default/-/Actualitat',{ snippet: false, limit: 1 }); $('#feed-bloc-accions').rssfeed('http://bloc.comunistes.cat/feeds/posts/default/-/Accions',{ snippet: false, limit: 1 }); // Temes $('#feed-treballdigne').rssfeed('http://bloc.comunistes.cat/feeds/posts/default/-/%23TreballDigne',{ snippet: false, limit: 5 }); $('#feed-rendagarantida').rssfeed('http://bloc.comunistes.cat/feeds/posts/default/-/%23RendaGarantida',{ snippet: false, limit: 5 }); $('#feed-salutpublica').rssfeed('http://bloc.comunistes.cat/feeds/posts/default/-/%23SalutPública',{ snippet: false, limit: 5 }); $('#feed-dretalhabitatge').rssfeed('http://bloc.comunistes.cat/feeds/posts/default/-/%23DretAlHabitatge',{ snippet: false, limit: 5 }); $('#feed-escolapublica').rssfeed('http://bloc.comunistes.cat/feeds/posts/default/-/%23EscolaPública',{ snippet: false, limit: 5 }); $('#feed-universitatpublica').rssfeed('http://bloc.comunistes.cat/feeds/posts/default/-/%23UniversitatPública',{ snippet: false, limit: 5 }); $('#feed-lliureinformacio').rssfeed('http://bloc.comunistes.cat/feeds/posts/default/-/%23LliureInformació',{ snippet: false, limit: 5 }); $('#feed-tecnologiesobertes').rssfeed('http://bloc.comunistes.cat/feeds/posts/default/-/%23TecnologiesObertes',{ snippet: false, limit: 5 }); $('#feed-feminisme').rssfeed('http://bloc.comunistes.cat/feeds/posts/default/-/%23Feminisme',{ snippet: false, limit: 5 }); $('#feed-igualtatdedrets').rssfeed('http://bloc.comunistes.cat/feeds/posts/default/-/%23IgualtatDeDrets',{ snippet: false, limit: 5 }); $('#feed-dretsdelainfancia').rssfeed('http://bloc.comunistes.cat/feeds/posts/default/-/%23DretsDeLaInfància',{ snippet: false, limit: 5 }); $('#feed-racismemaimes').rssfeed('http://bloc.comunistes.cat/feeds/posts/default/-/%23RacismeMaiMés',{ snippet: false, limit: 5 }); $('#feed-rupturademocratica').rssfeed('http://bloc.comunistes.cat/feeds/posts/default/-/%23RupturaDemocràtica',{ snippet: false, limit: 5 }); $('#feed-memoriahistorica').rssfeed('http://bloc.comunistes.cat/feeds/posts/default/-/%23MemòriaHistòrica',{ snippet: false, limit: 5 }); $('#feed-mediambient').rssfeed('http://bloc.comunistes.cat/feeds/posts/default/-/%23MediAmbient',{ snippet: false, limit: 5 }); $('#feed-culturapopular').rssfeed('http://bloc.comunistes.cat/feeds/posts/default/-/%23CulturaPopular',{ snippet: false, limit: 5 }); $('#feed-pau').rssfeed('http://bloc.comunistes.cat/feeds/posts/default/-/%23Pau',{ snippet: false, limit: 5 }); $('#feed-solidaritat').rssfeed('http://bloc.comunistes.cat/feeds/posts/default/-/%23Solidaritat',{ snippet: false, limit: 5 }); $('#feed-republicacatalana').rssfeed('http://bloc.comunistes.cat/feeds/posts/default/-/%23RepúblicaCatalana',{ snippet: false, limit: 5 }); $('#feed-classetreballadora').rssfeed('http://bloc.comunistes.cat/feeds/posts/default/-/%23ClasseTreballadora',{ snippet: false, limit: 5 }); // Feeds filtrats de videos $('#feed-videos-last-one').rssfeed('http://videos.comunistes.cat/feeds/posts/default',{ snippet: true, limit: 1 }); $('#feed-videos-last-two').rssfeed('http://videos.comunistes.cat/feeds/posts/default',{ snippet: true, limit: 2 }); $('#feed-videos-last-five').rssfeed('http://videos.comunistes.cat/feeds/posts/default',{ snippet: true, limit: 5 }); $('#feed-videos-parlament').rssfeed('http://videos.comunistes.cat/feeds/posts/default/-/Parlament',{ snippet: true, limit: 1 }); $('#feed-videos-mobilitzacions').rssfeed('http://videos.comunistes.cat/feeds/posts/default/-/Mobilitzacions',{ snippet: true, limit: 1 }); $('#feed-videos-campanyes').rssfeed('http://videos.comunistes.cat/feeds/posts/default/-/Campanyes',{ snippet: true, limit: 1 }); $('#feed-videos-cinema').rssfeed('http://videos.comunistes.cat/feeds/posts/default/-/Cinema',{ snippet: true, limit: 1 }); // Feeds organitzacions $('#feed-euia').rssfeed('http://euia.cat/apartado_noticias_rss_cat.php?ap=1',{ snippet: true, limit: 1 }); $('#feed-fpereardiaca').rssfeed('http://noticies.fpereardiaca.cat/feeds/posts/default',{ snippet: true, limit: 1 }); $('#feed-el').rssfeed('http://www.european-left.org/english/home/news_archive/newsfeed.xml',{ snippet: true, limit: 1 }); $('#feed-ccoo').rssfeed('http://www.ccoo.cat/aspnet/rss.aspx',{ snippet: true, limit: 1 }); $('#feed-cgt').rssfeed('http://www.cgtcatalunya.cat/spip.php?page=backend',{ snippet: true, limit: 1 }); $('#feed-cobas').rssfeed('http://www.cobas.es/index.php?format=feed&type=rss&lang=en',{ snippet: true, limit: 1 }); $('#feed-dempeus').rssfeed('http://dempeusperlasalut.wordpress.com/feed/',{ snippet: true, limit: 1 }); $('#feed-iaioflautas').rssfeed('http://www.iaioflautas.org/feed/',{ snippet: true, limit: 1 }); $('#feed-falternativa').rssfeed('http://www.fundacioalternativa.cat/?feed=rss2',{ snippet: true, limit: 1 }); $('#feed-pah').rssfeed('http://pahbarcelona.org/feed/',{ snippet: true, limit: 1 }); // Feeds Blocs $('#feed-amcastells').rssfeed('http://puntsdevista.wordpress.com/feed/rss/',{ snippet: true, limit: 1 }); $('#feed-mdelgado').rssfeed('http://manueldelgadoruiz.blogspot.com/feeds/posts/default',{ snippet: true, limit: 1 }); $('#feed-jjnuet').rssfeed('http://feeds.feedburner.com/ElBlocDeJoanJosepNuet',{ snippet: true, limit: 1 }); $('#feed-jmena').rssfeed('http://joanmena.blogspot.com/feeds/posts/default',{ snippet: true, limit: 1 }); $('#feed-tsalado').rssfeed('http://blocpolitikon.blogspot.com/feeds/posts/default',{ snippet: true, limit: 1 }); $('#feed-aitalo').rssfeed('http://antoniitalo.blogspot.com/feeds/posts/default',{ snippet: true, limit: 1 }); $('#feed-mnavarro').rssfeed('http://lescosesdenjomi.blogspot.com/feeds/posts/default',{ snippet: true, limit: 1 }); $('#feed-amoreno').rssfeed('http://unbellfantasma.blogspot.com/feeds/posts/default',{ snippet: true, limit: 1 }); $('#feed-asalmeron').rssfeed('http://alfonso-lhquetuvols.blogspot.com/feeds/posts/default',{ snippet: true, limit: 1 }); $('#feed-rvalls').rssfeed('http://www.albasud.org/rss.php?lan=ca',{ snippet: true, limit: 1 }); $('#feed-sfr').rssfeed('http://seguintfilroig.blogspot.com/feeds/posts/default',{ snippet: true, limit: 1 }); // Feeds Realitat $('#feed-realitat').rssfeed('http://bloc.realitat.cat/feeds/posts/default',{ snippet: false, limit: 1 }); $('#feed-realitat-editorial').rssfeed('http://bloc.realitat.cat/feeds/posts/default/-/Editorial',{ snippet: false, limit: 1 }); $('#feed-realitat-local').rssfeed('http://bloc.realitat.cat/feeds/posts/default/-/Local',{ snippet: false, limit: 1 }); $('#feed-realitat-nacional').rssfeed('http://bloc.realitat.cat/feeds/posts/default/-/Nacional',{ snippet: false, limit: 1 }); $('#feed-realitat-internacional').rssfeed('http://bloc.realitat.cat/feeds/posts/default/-/Internacional',{ snippet: false, limit: 1 }); $('#feed-realitat-historia').rssfeed('http://bloc.realitat.cat/feeds/posts/default/-/Història',{ snippet: false, limit: 1 }); $('#feed-realitat-coneixement').rssfeed('http://bloc.realitat.cat/feeds/posts/default/-/Coneixement',{ snippet: false, limit: 1 }); $('#feed-realitat-lesarrels').rssfeed('http://miquelangelsoria.realitat.cat/feeds/posts/default',{ snippet: false, limit: 1 }); });
{ "content_hash": "5287b740c55cd867976214e56d77fa33", "timestamp": "", "source": "github", "line_count": 288, "max_line_length": 113, "avg_line_length": 29.979166666666668, "alnum_prop": 0.6696780171415335, "repo_name": "ComunistesdeCatalunya/comunistesdecatalunya.github.io", "id": "ed1b54dd97873c9dda023a6a73829822201cb93e", "size": "8645", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/js/redlist.js", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "688471" }, { "name": "HTML", "bytes": "355647" }, { "name": "JavaScript", "bytes": "103320" } ], "symlink_target": "" }
package com.google.common.primitives; import static com.google.common.base.Preconditions.checkArgument; import static com.google.common.base.Preconditions.checkElementIndex; import static com.google.common.base.Preconditions.checkNotNull; import static com.google.common.base.Preconditions.checkPositionIndexes; import com.google.common.annotations.GwtCompatible; import com.google.common.annotations.GwtIncompatible; import java.io.Serializable; import java.util.AbstractList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.Comparator; import java.util.List; import java.util.RandomAccess; import javax.annotation.CheckReturnValue; import javax.annotation.Nullable; /** * Static utility methods pertaining to {@code char} primitives, that are not * already found in either {@link Character} or {@link Arrays}. * * <p>All the operations in this class treat {@code char} values strictly * numerically; they are neither Unicode-aware nor locale-dependent. * * <p>See the Guava User Guide article on <a href= * "https://github.com/google/guava/wiki/PrimitivesExplained"> * primitive utilities</a>. * * @author Kevin Bourrillion * @since 1.0 */ @CheckReturnValue @GwtCompatible(emulated = true) public final class Chars { private Chars() {} /** * The number of bytes required to represent a primitive {@code char} * value. */ public static final int BYTES = Character.SIZE / Byte.SIZE; /** * Returns a hash code for {@code value}; equal to the result of invoking * {@code ((Character) value).hashCode()}. * * @param value a primitive {@code char} value * @return a hash code for the value */ public static int hashCode(char value) { return value; } /** * Returns the {@code char} value that is equal to {@code value}, if possible. * * @param value any value in the range of the {@code char} type * @return the {@code char} value that equals {@code value} * @throws IllegalArgumentException if {@code value} is greater than {@link * Character#MAX_VALUE} or less than {@link Character#MIN_VALUE} */ public static char checkedCast(long value) { char result = (char) value; if (result != value) { // don't use checkArgument here, to avoid boxing throw new IllegalArgumentException("Out of range: " + value); } return result; } /** * Returns the {@code char} nearest in value to {@code value}. * * @param value any {@code long} value * @return the same value cast to {@code char} if it is in the range of the * {@code char} type, {@link Character#MAX_VALUE} if it is too large, * or {@link Character#MIN_VALUE} if it is too small */ public static char saturatedCast(long value) { if (value > Character.MAX_VALUE) { return Character.MAX_VALUE; } if (value < Character.MIN_VALUE) { return Character.MIN_VALUE; } return (char) value; } /** * Compares the two specified {@code char} values. The sign of the value * returned is the same as that of {@code ((Character) a).compareTo(b)}. * * <p><b>Note for Java 7 and later:</b> this method should be treated as * deprecated; use the equivalent {@link Character#compare} method instead. * * @param a the first {@code char} to compare * @param b the second {@code char} to compare * @return a negative value if {@code a} is less than {@code b}; a positive * value if {@code a} is greater than {@code b}; or zero if they are equal */ public static int compare(char a, char b) { return a - b; // safe due to restricted range } /** * Returns {@code true} if {@code target} is present as an element anywhere in * {@code array}. * * @param array an array of {@code char} values, possibly empty * @param target a primitive {@code char} value * @return {@code true} if {@code array[i] == target} for some value of {@code * i} */ public static boolean contains(char[] array, char target) { for (char value : array) { if (value == target) { return true; } } return false; } /** * Returns the index of the first appearance of the value {@code target} in * {@code array}. * * @param array an array of {@code char} values, possibly empty * @param target a primitive {@code char} value * @return the least index {@code i} for which {@code array[i] == target}, or * {@code -1} if no such index exists. */ public static int indexOf(char[] array, char target) { return indexOf(array, target, 0, array.length); } // TODO(kevinb): consider making this public private static int indexOf(char[] array, char target, int start, int end) { for (int i = start; i < end; i++) { if (array[i] == target) { return i; } } return -1; } /** * Returns the start position of the first occurrence of the specified {@code * target} within {@code array}, or {@code -1} if there is no such occurrence. * * <p>More formally, returns the lowest index {@code i} such that {@code * java.util.Arrays.copyOfRange(array, i, i + target.length)} contains exactly * the same elements as {@code target}. * * @param array the array to search for the sequence {@code target} * @param target the array to search for as a sub-sequence of {@code array} */ public static int indexOf(char[] array, char[] target) { checkNotNull(array, "array"); checkNotNull(target, "target"); if (target.length == 0) { return 0; } outer: for (int i = 0; i < array.length - target.length + 1; i++) { for (int j = 0; j < target.length; j++) { if (array[i + j] != target[j]) { continue outer; } } return i; } return -1; } /** * Returns the index of the last appearance of the value {@code target} in * {@code array}. * * @param array an array of {@code char} values, possibly empty * @param target a primitive {@code char} value * @return the greatest index {@code i} for which {@code array[i] == target}, * or {@code -1} if no such index exists. */ public static int lastIndexOf(char[] array, char target) { return lastIndexOf(array, target, 0, array.length); } // TODO(kevinb): consider making this public private static int lastIndexOf(char[] array, char target, int start, int end) { for (int i = end - 1; i >= start; i--) { if (array[i] == target) { return i; } } return -1; } /** * Returns the least value present in {@code array}. * * @param array a <i>nonempty</i> array of {@code char} values * @return the value present in {@code array} that is less than or equal to * every other value in the array * @throws IllegalArgumentException if {@code array} is empty */ public static char min(char... array) { checkArgument(array.length > 0); char min = array[0]; for (int i = 1; i < array.length; i++) { if (array[i] < min) { min = array[i]; } } return min; } /** * Returns the greatest value present in {@code array}. * * @param array a <i>nonempty</i> array of {@code char} values * @return the value present in {@code array} that is greater than or equal to * every other value in the array * @throws IllegalArgumentException if {@code array} is empty */ public static char max(char... array) { checkArgument(array.length > 0); char max = array[0]; for (int i = 1; i < array.length; i++) { if (array[i] > max) { max = array[i]; } } return max; } /** * Returns the values from each provided array combined into a single array. * For example, {@code concat(new char[] {a, b}, new char[] {}, new * char[] {c}} returns the array {@code {a, b, c}}. * * @param arrays zero or more {@code char} arrays * @return a single array containing all the values from the source arrays, in * order */ public static char[] concat(char[]... arrays) { int length = 0; for (char[] array : arrays) { length += array.length; } char[] result = new char[length]; int pos = 0; for (char[] array : arrays) { System.arraycopy(array, 0, result, pos, array.length); pos += array.length; } return result; } /** * Returns a big-endian representation of {@code value} in a 2-element byte * array; equivalent to {@code * ByteBuffer.allocate(2).putChar(value).array()}. For example, the input * value {@code '\\u5432'} would yield the byte array {@code {0x54, 0x32}}. * * <p>If you need to convert and concatenate several values (possibly even of * different types), use a shared {@link java.nio.ByteBuffer} instance, or use * {@link com.google.common.io.ByteStreams#newDataOutput()} to get a growable * buffer. */ @GwtIncompatible("doesn't work") public static byte[] toByteArray(char value) { return new byte[] {(byte) (value >> 8), (byte) value}; } /** * Returns the {@code char} value whose big-endian representation is * stored in the first 2 bytes of {@code bytes}; equivalent to {@code * ByteBuffer.wrap(bytes).getChar()}. For example, the input byte array * {@code {0x54, 0x32}} would yield the {@code char} value {@code '\\u5432'}. * * <p>Arguably, it's preferable to use {@link java.nio.ByteBuffer}; that * library exposes much more flexibility at little cost in readability. * * @throws IllegalArgumentException if {@code bytes} has fewer than 2 * elements */ @GwtIncompatible("doesn't work") public static char fromByteArray(byte[] bytes) { checkArgument(bytes.length >= BYTES, "array too small: %s < %s", bytes.length, BYTES); return fromBytes(bytes[0], bytes[1]); } /** * Returns the {@code char} value whose byte representation is the given 2 * bytes, in big-endian order; equivalent to {@code Chars.fromByteArray(new * byte[] {b1, b2})}. * * @since 7.0 */ @GwtIncompatible("doesn't work") public static char fromBytes(byte b1, byte b2) { return (char) ((b1 << 8) | (b2 & 0xFF)); } /** * Returns an array containing the same values as {@code array}, but * guaranteed to be of a specified minimum length. If {@code array} already * has a length of at least {@code minLength}, it is returned directly. * Otherwise, a new array of size {@code minLength + padding} is returned, * containing the values of {@code array}, and zeroes in the remaining places. * * @param array the source array * @param minLength the minimum length the returned array must guarantee * @param padding an extra amount to "grow" the array by if growth is * necessary * @throws IllegalArgumentException if {@code minLength} or {@code padding} is * negative * @return an array containing the values of {@code array}, with guaranteed * minimum length {@code minLength} */ public static char[] ensureCapacity(char[] array, int minLength, int padding) { checkArgument(minLength >= 0, "Invalid minLength: %s", minLength); checkArgument(padding >= 0, "Invalid padding: %s", padding); return (array.length < minLength) ? copyOf(array, minLength + padding) : array; } // Arrays.copyOf() requires Java 6 private static char[] copyOf(char[] original, int length) { char[] copy = new char[length]; System.arraycopy(original, 0, copy, 0, Math.min(original.length, length)); return copy; } /** * Returns a string containing the supplied {@code char} values separated * by {@code separator}. For example, {@code join("-", '1', '2', '3')} returns * the string {@code "1-2-3"}. * * @param separator the text that should appear between consecutive values in * the resulting string (but not at the start or end) * @param array an array of {@code char} values, possibly empty */ public static String join(String separator, char... array) { checkNotNull(separator); int len = array.length; if (len == 0) { return ""; } StringBuilder builder = new StringBuilder(len + separator.length() * (len - 1)); builder.append(array[0]); for (int i = 1; i < len; i++) { builder.append(separator).append(array[i]); } return builder.toString(); } /** * Returns a comparator that compares two {@code char} arrays * lexicographically. That is, it compares, using {@link * #compare(char, char)}), the first pair of values that follow any * common prefix, or when one array is a prefix of the other, treats the * shorter array as the lesser. For example, * {@code [] < ['a'] < ['a', 'b'] < ['b']}. * * <p>The returned comparator is inconsistent with {@link * Object#equals(Object)} (since arrays support only identity equality), but * it is consistent with {@link Arrays#equals(char[], char[])}. * * @see <a href="http://en.wikipedia.org/wiki/Lexicographical_order"> * Lexicographical order article at Wikipedia</a> * @since 2.0 */ public static Comparator<char[]> lexicographicalComparator() { return LexicographicalComparator.INSTANCE; } private enum LexicographicalComparator implements Comparator<char[]> { INSTANCE; @Override public int compare(char[] left, char[] right) { int minLength = Math.min(left.length, right.length); for (int i = 0; i < minLength; i++) { int result = Chars.compare(left[i], right[i]); if (result != 0) { return result; } } return left.length - right.length; } @Override public String toString() { return "Chars.lexicographicalComparator()"; } } /** * Copies a collection of {@code Character} instances into a new array of * primitive {@code char} values. * * <p>Elements are copied from the argument collection as if by {@code * collection.toArray()}. Calling this method is as thread-safe as calling * that method. * * @param collection a collection of {@code Character} objects * @return an array containing the same values as {@code collection}, in the * same order, converted to primitives * @throws NullPointerException if {@code collection} or any of its elements * is null */ public static char[] toArray(Collection<Character> collection) { if (collection instanceof CharArrayAsList) { return ((CharArrayAsList) collection).toCharArray(); } Object[] boxedArray = collection.toArray(); int len = boxedArray.length; char[] array = new char[len]; for (int i = 0; i < len; i++) { // checkNotNull for GWT (do not optimize) array[i] = (Character) checkNotNull(boxedArray[i]); } return array; } /** * Returns a fixed-size list backed by the specified array, similar to {@link * Arrays#asList(Object[])}. The list supports {@link List#set(int, Object)}, * but any attempt to set a value to {@code null} will result in a {@link * NullPointerException}. * * <p>The returned list maintains the values, but not the identities, of * {@code Character} objects written to or read from it. For example, whether * {@code list.get(0) == list.get(0)} is true for the returned list is * unspecified. * * @param backingArray the array to back the list * @return a list view of the array */ public static List<Character> asList(char... backingArray) { if (backingArray.length == 0) { return Collections.emptyList(); } return new CharArrayAsList(backingArray); } @GwtCompatible private static class CharArrayAsList extends AbstractList<Character> implements RandomAccess, Serializable { final char[] array; final int start; final int end; CharArrayAsList(char[] array) { this(array, 0, array.length); } CharArrayAsList(char[] array, int start, int end) { this.array = array; this.start = start; this.end = end; } @Override public int size() { return end - start; } @Override public boolean isEmpty() { return false; } @Override public Character get(int index) { checkElementIndex(index, size()); return array[start + index]; } @Override public boolean contains(Object target) { // Overridden to prevent a ton of boxing return (target instanceof Character) && Chars.indexOf(array, (Character) target, start, end) != -1; } @Override public int indexOf(Object target) { // Overridden to prevent a ton of boxing if (target instanceof Character) { int i = Chars.indexOf(array, (Character) target, start, end); if (i >= 0) { return i - start; } } return -1; } @Override public int lastIndexOf(Object target) { // Overridden to prevent a ton of boxing if (target instanceof Character) { int i = Chars.lastIndexOf(array, (Character) target, start, end); if (i >= 0) { return i - start; } } return -1; } @Override public Character set(int index, Character element) { checkElementIndex(index, size()); char oldValue = array[start + index]; // checkNotNull for GWT (do not optimize) array[start + index] = checkNotNull(element); return oldValue; } @Override public List<Character> subList(int fromIndex, int toIndex) { int size = size(); checkPositionIndexes(fromIndex, toIndex, size); if (fromIndex == toIndex) { return Collections.emptyList(); } return new CharArrayAsList(array, start + fromIndex, start + toIndex); } @Override public boolean equals(@Nullable Object object) { if (object == this) { return true; } if (object instanceof CharArrayAsList) { CharArrayAsList that = (CharArrayAsList) object; int size = size(); if (that.size() != size) { return false; } for (int i = 0; i < size; i++) { if (array[start + i] != that.array[that.start + i]) { return false; } } return true; } return super.equals(object); } @Override public int hashCode() { int result = 1; for (int i = start; i < end; i++) { result = 31 * result + Chars.hashCode(array[i]); } return result; } @Override public String toString() { StringBuilder builder = new StringBuilder(size() * 3); builder.append('[').append(array[start]); for (int i = start + 1; i < end; i++) { builder.append(", ").append(array[i]); } return builder.append(']').toString(); } char[] toCharArray() { // Arrays.copyOfRange() is not available under GWT int size = size(); char[] result = new char[size]; System.arraycopy(array, start, result, 0, size); return result; } private static final long serialVersionUID = 0; } }
{ "content_hash": "c99bf3c2abee0be4f4973d7f82ae02cb", "timestamp": "", "source": "github", "line_count": 592, "max_line_length": 90, "avg_line_length": 32.380067567567565, "alnum_prop": 0.6302363190568104, "repo_name": "privatemousse/guava", "id": "eb62d9f0a2171c5b965c1ec9dceb1ce3752400e9", "size": "19769", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "guava/src/com/google/common/primitives/Chars.java", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "11478" }, { "name": "Java", "bytes": "11828958" }, { "name": "Shell", "bytes": "1128" } ], "symlink_target": "" }
using System; using System.Collections.Generic; using System.Linq; using System.IO; using MSR.Data.VersionControl; using MSR.Data.Entities.DSL.Mapping; using MSR.Data.Entities.DSL.Selection; namespace MSR.Data.Entities.Mapping { public class ProjectFileMapper : EntityMapper<ProjectFile,CommitMappingExpression,ProjectFileMappingExpression> { public ProjectFileMapper(IScmData scmData) : base(scmData) { } public override IEnumerable<ProjectFileMappingExpression> Map(CommitMappingExpression expression) { List<ProjectFileMappingExpression> fileExpressions = new List<ProjectFileMappingExpression>(); string revision = expression.CurrentEntity<Commit>().Revision; ILog log = scmData.Log(revision); var touchedFiles = FilterTouchedFiles(log.TouchedFiles); foreach (var touchedFile in touchedFiles) { ProjectFileMappingExpression fileExp = null; switch (touchedFile.Action) { case TouchedFile.TouchedFileAction.MODIFIED: fileExp = expression.File(touchedFile.Path); break; case TouchedFile.TouchedFileAction.ADDED: fileExp = expression.AddFile(touchedFile.Path); break; case TouchedFile.TouchedFileAction.DELETED: fileExp = expression.File(touchedFile.Path); fileExp.Delete(); break; default: break; } if (touchedFile.SourcePath != null) { if (touchedFile.SourceRevision == null) { touchedFile.SourceRevision = scmData.PreviousRevision(revision); } fileExp.CopiedFrom(touchedFile.SourcePath, touchedFile.SourceRevision); } fileExpressions.Add( fileExp ); } return fileExpressions; } public IPathSelector[] PathSelectors { get; set; } private IEnumerable<TouchedFile> FilterTouchedFiles(IEnumerable<TouchedFile> touchedFiles) { if (PathSelectors != null) { foreach (var selector in PathSelectors) { touchedFiles = touchedFiles.Where(x => selector.InSelection(x.Path)).ToArray(); } } return touchedFiles; } } }
{ "content_hash": "6f734fd8e23ba05eab80d89ec23b0bb3", "timestamp": "", "source": "github", "line_count": 79, "max_line_length": 112, "avg_line_length": 26.9873417721519, "alnum_prop": 0.6894934333958724, "repo_name": "kirnosenko/msr-tools", "id": "8aad5ec03fb460c9340854d946ee9a742f4b9659", "size": "2246", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/MSR/Data/Entities/Mapping/ProjectFileMapper.cs", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "C#", "bytes": "515535" }, { "name": "CSS", "bytes": "2653" }, { "name": "JavaScript", "bytes": "9553" }, { "name": "Shell", "bytes": "2859" } ], "symlink_target": "" }
package org.robolectric.shadows; import android.os.Build; import android.os.SharedMemory; import android.system.ErrnoException; import android.system.OsConstants; import java.io.File; import java.io.FileDescriptor; import java.io.IOException; import java.io.RandomAccessFile; import java.nio.ByteBuffer; import java.nio.MappedByteBuffer; import java.nio.channels.FileChannel.MapMode; import java.nio.file.Files; import java.util.Collections; import java.util.Map; import java.util.WeakHashMap; import java.util.concurrent.atomic.AtomicReference; import org.robolectric.RuntimeEnvironment; import org.robolectric.annotation.Implementation; import org.robolectric.annotation.Implements; import org.robolectric.annotation.RealObject; import org.robolectric.util.ReflectionHelpers; import org.robolectric.util.TempDirectory; /** * A {@link SharedMemory} fake that uses a private temporary disk file for storage and Java's {@link * MappedByteBuffer} for the memory mappings. */ @Implements(value = SharedMemory.class, minSdk = Build.VERSION_CODES.O_MR1, /* not quite true, but this prevents a useless `shadowOf()` accessor showing * up, which would break people compiling against API 26 and earlier. */ isInAndroidSdk = false ) public class ShadowSharedMemory { private static final Map<FileDescriptor, File> filesByFd = Collections.synchronizedMap(new WeakHashMap<>()); private static final AtomicReference<ErrnoException> fakeCreateException = new AtomicReference<>(); @RealObject private SharedMemory realObject; /** * Only works on {@link SharedMemory} instances from {@link SharedMemory#create}. * * <p>"prot" is ignored -- all mappings are read/write. */ @Implementation protected ByteBuffer map(int prot, int offset, int length) throws ErrnoException { ReflectionHelpers.callInstanceMethod(realObject, "checkOpen"); File file = filesByFd.get(getRealFileDescriptor()); if (file == null) { throw new IllegalStateException("SharedMemory from a parcel isn't yet implemented!"); } try (RandomAccessFile randomAccessFile = new RandomAccessFile(file, "rw")) { // It would be easy to support a MapMode.READ_ONLY type mapping as well except none of the // OsConstants fields are even initialized by robolectric and so "prot" is always zero! return randomAccessFile.getChannel().map(MapMode.READ_WRITE, offset, length); } catch (IOException e) { throw new ErrnoException(e.getMessage(), OsConstants.EIO, e); } } @Implementation protected static void unmap(ByteBuffer mappedBuf) throws ErrnoException { if (mappedBuf instanceof MappedByteBuffer) { // There's no API to clean up a MappedByteBuffer other than GC so we've got nothing to do! } else { throw new IllegalArgumentException( "ByteBuffer wasn't created by #map(int, int, int); can't unmap"); } } @Implementation protected static FileDescriptor nCreate(String name, int size) throws ErrnoException { maybeThrow(fakeCreateException); TempDirectory tempDirectory = RuntimeEnvironment.getTempDirectory(); try { // Give each instance its own private file. File sharedMemoryFile = Files.createTempFile( tempDirectory.createIfNotExists("SharedMemory"), "shmem-" + name, ".tmp") .toFile(); RandomAccessFile randomAccessFile = new RandomAccessFile(sharedMemoryFile, "rw"); randomAccessFile.setLength(0); randomAccessFile.setLength(size); filesByFd.put(randomAccessFile.getFD(), sharedMemoryFile); return randomAccessFile.getFD(); } catch (IOException e) { throw new RuntimeException("Unable to create file descriptior", e); } } @Implementation protected static int nGetSize(FileDescriptor fd) { return (int) filesByFd.get(fd).length(); } private FileDescriptor getRealFileDescriptor() { return ReflectionHelpers.getField(realObject, "mFileDescriptor"); } /** * Causes subsequent calls to {@link SharedMemory#create)} to throw the specified exception, if * non-null. Pass null to restore create to normal operation. */ public static void setCreateShouldThrow(ErrnoException e) { fakeCreateException.set(e); } private static void maybeThrow(AtomicReference<ErrnoException> exceptionRef) throws ErrnoException { ErrnoException exception = exceptionRef.get(); if (exception != null) { throw exception; } } }
{ "content_hash": "e175bda1978211f90e26ec5975607418", "timestamp": "", "source": "github", "line_count": 125, "max_line_length": 100, "avg_line_length": 36, "alnum_prop": 0.7331111111111112, "repo_name": "spotify/robolectric", "id": "735baf981c4eb40a198b656febdd51d19b3b6d41", "size": "4500", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "shadows/framework/src/main/java/org/robolectric/shadows/ShadowSharedMemory.java", "mode": "33188", "license": "mit", "language": [ { "name": "Groovy", "bytes": "27392" }, { "name": "Java", "bytes": "4430781" }, { "name": "Ruby", "bytes": "9159" }, { "name": "Shell", "bytes": "20540" } ], "symlink_target": "" }
using System; using System.Collections.Generic; namespace ClosedXML.Excel { public interface IXLRangeColumns : IEnumerable<IXLRangeColumn> { /// <summary> /// Adds a column range to this group. /// </summary> /// <param name="columRange">The column range to add.</param> void Add(IXLRangeColumn columRange); /// <summary> /// Returns the collection of cells. /// </summary> IXLCells Cells(); /// <summary> /// Returns the collection of cells that have a value. /// </summary> IXLCells CellsUsed(); /// <summary> /// Returns the collection of cells that have a value. /// </summary> /// <param name="includeFormats">if set to <c>true</c> will return all cells with a value or a style different than the default.</param> [Obsolete("Use the overload with XLCellsUsedOptions")] IXLCells CellsUsed(Boolean includeFormats); IXLCells CellsUsed(XLCellsUsedOptions options); /// <summary> /// Deletes all columns and shifts the columns at the right of them accordingly. /// </summary> void Delete(); IXLStyle Style { get; set; } IXLRangeColumns SetDataType(XLDataType dataType); /// <summary> /// Clears the contents of these columns. /// </summary> /// <param name="clearOptions">Specify what you want to clear.</param> IXLRangeColumns Clear(XLClearOptions clearOptions = XLClearOptions.All); void Select(); } }
{ "content_hash": "c3c87fa8bcccd276052b32e2d2b07198", "timestamp": "", "source": "github", "line_count": 50, "max_line_length": 144, "avg_line_length": 31.64, "alnum_prop": 0.6049304677623262, "repo_name": "ClosedXML/ClosedXML", "id": "ad9711850d8d32b94f5e2cc5c03534f12fb4f32e", "size": "1582", "binary": false, "copies": "2", "ref": "refs/heads/develop", "path": "ClosedXML/Excel/Ranges/IXLRangeColumns.cs", "mode": "33188", "license": "mit", "language": [ { "name": "C#", "bytes": "3965501" } ], "symlink_target": "" }
package ninja.bodyparser; import com.fasterxml.jackson.core.JsonParseException; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; import com.google.inject.Inject; import com.google.inject.Singleton; import ninja.ContentTypes; import ninja.Context; import ninja.exceptions.BadRequestException; import java.io.IOException; import java.io.InputStream; /** * Built in Json body parser. * * @author Raphael Bauer * @author Thibault Meyer * @see ninja.bodyparser.BodyParserEngine */ @Singleton public class BodyParserEngineJson implements BodyParserEngine { private final ObjectMapper objectMapper; @Inject public BodyParserEngineJson(ObjectMapper objectMapper) { this.objectMapper = objectMapper; } public <T> T invoke(Context context, Class<T> classOfT) { try (InputStream inputStream = context.getInputStream()) { return objectMapper.readValue(inputStream, classOfT); } catch (JsonParseException | JsonMappingException ex) { throw new BadRequestException("Error parsing incoming Json", ex); } catch (IOException e) { throw new BadRequestException("Invalid Json document", e); } } public String getContentType() { return ContentTypes.APPLICATION_JSON; } }
{ "content_hash": "57835bf504d44f32ef57c17329f739b3", "timestamp": "", "source": "github", "line_count": 48, "max_line_length": 77, "avg_line_length": 28.041666666666668, "alnum_prop": 0.7310549777117384, "repo_name": "tom1120/ninja", "id": "7371926a487fb6ecedbf2ea237cf80414b7952dc", "size": "1970", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "ninja-core/src/main/java/ninja/bodyparser/BodyParserEngineJson.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "1769079" }, { "name": "FreeMarker", "bytes": "193300" }, { "name": "HTML", "bytes": "640943" }, { "name": "Java", "bytes": "3137200" }, { "name": "JavaScript", "bytes": "3201287" }, { "name": "Roff", "bytes": "17565" } ], "symlink_target": "" }
ACCEPTED #### According to International Plant Names Index #### Published in null #### Original name null ### Remarks null
{ "content_hash": "8b98aa4c58e95d71c52214fe48909585", "timestamp": "", "source": "github", "line_count": 13, "max_line_length": 31, "avg_line_length": 9.692307692307692, "alnum_prop": 0.7063492063492064, "repo_name": "mdoering/backbone", "id": "bac5c8d82eba9960984e1541bbcaeaf68b22dcf2", "size": "172", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "life/Plantae/Magnoliophyta/Magnoliopsida/Oxalidales/Oxalidaceae/Oxalis/Oxalis trouiniana/README.md", "mode": "33188", "license": "apache-2.0", "language": [], "symlink_target": "" }
This directory contains the default CLI build, used by the majority of services who don't add custom commands to their service CLIs. As of Jan 2018, default CLI builds are uploaded with every SDK release, along with a SHA256SUMS file in the same directory. Dependencies: - Go 1.8+ - `../../cli` which contains the service CLI libraries - `../../govendor` which contains all vendored dependencies. To build, run `build.sh`. Note that no `GOPATH` is required, as an internal `GOPATH` is constructed for the build. The output will include default CLIs for Linux, OSX, and Windows.
{ "content_hash": "c3b2aeff98f25a792620216bfced97e7", "timestamp": "", "source": "github", "line_count": 8, "max_line_length": 256, "avg_line_length": 72.5, "alnum_prop": 0.7620689655172413, "repo_name": "vishnu2kmohan/dcos-commons", "id": "62b6496435052215fe66819b7f94a6ecbfe9331e", "size": "595", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "sdk/cli/README.md", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Go", "bytes": "168256" }, { "name": "HTML", "bytes": "99573" }, { "name": "Java", "bytes": "2770769" }, { "name": "Makefile", "bytes": "106" }, { "name": "Python", "bytes": "457961" }, { "name": "Shell", "bytes": "46736" } ], "symlink_target": "" }
ACCEPTED #### According to The Catalogue of Life, 3rd January 2011 #### Published in null #### Original name null ### Remarks null
{ "content_hash": "b452f9a10ccb25e38c1219b217a19abb", "timestamp": "", "source": "github", "line_count": 13, "max_line_length": 39, "avg_line_length": 10.307692307692308, "alnum_prop": 0.6940298507462687, "repo_name": "mdoering/backbone", "id": "28153f4cba72476f18e38eceab7194e30051ad3a", "size": "176", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "life/Protozoa/Granuloreticulosea/Foraminiferida/Nodosariidae/Nodosaria/Nodosaria comatula/README.md", "mode": "33188", "license": "apache-2.0", "language": [], "symlink_target": "" }
Check out the [API Reference](http://alt.js.org/docs/) for full in-depth docs. For a high-level walk-through on flux, take a look at the [Getting Started](http://alt.js.org/guide/) guide. What follows below applies only to the master branch of `alt` and not the latest distribution. Any questions? ask in the gitter room. [![Gitter](https://badges.gitter.im/Join%20Chat.svg)](https://gitter.im/goatslacker/alt?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge) [![NPM version](https://badge.fury.io/js/alt.svg)](http://badge.fury.io/js/alt) [![Build Status](https://secure.travis-ci.org/goatslacker/alt.svg?branch=master)](http://travis-ci.org/goatslacker/alt) [![Coverage Status](https://img.shields.io/coveralls/goatslacker/alt.svg?style=flat)](https://coveralls.io/r/goatslacker/alt) [![Dependency Status](https://david-dm.org/goatslacker/alt.svg)](https://david-dm.org/goatslacker/alt) [![Download Count](https://img.shields.io/npm/dm/alt.svg?style=flat)](https://www.npmjs.com/package/alt) [![JS.ORG](https://img.shields.io/badge/js.org-alt-ffb400.svg?style=flat-square)](http://js.org) ### Why you should be using Alt * It is pure [flux](http://facebook.github.io/flux/docs/overview.html). Stores have no setters, the flow is unidirectional. * Isomorphic and works with react-native. * Actively maintained and being used in production. * Extremely [flexible](#flexibility) and unopinionated in how you use flux. Create traditional singletons or use dependency injection. * It is terse. No boilerplate. ### What does it look like? Alt ```js import Alt from 'alt'; export default new Alt(); ``` Actions ```js import alt from './alt'; class TodoActions { updateTodo(id, text) { return { id, text } } } export default alt.createActions(TodoActions); ``` Store ```js import alt from './alt'; import TodoActions from './TodoActions' class TodoStore { constructor() { this.bindListeners({ updateTodo: TodoActions.updateTodo }); this.state = { todos: [] }; } updateTodo(todo) { this.setState({ todos: this.state.todos.concat(todo) }); } } export default alt.createStore(TodoStore, 'TodoStore'); ``` View ```js import connectToStores from 'alt/utils/connectToStores'; import { Component } from 'react'; import TodoStore from './TodoStore'; @connectToStores class TodoView extends Component { static getStores() { return [TodoStore]; } static getPropsFromStores() { return TodoStore.getState(); } render() { return ( <ul> {this.props.todos.map((todo) => { return ( <li key={todo.id}>{todo.text}</li> ); })} </ul> ); } } ``` ## In the Wild ### Examples * [Airbnb Airpal](https://github.com/airbnb/airpal/tree/master/src/main/resources/assets) * [Alt Notify](https://github.com/sourcescript/alt-notify) * [Chrome Devtool](https://github.com/goatslacker/alt-devtool) * [Example Tests](https://github.com/jdlehman/alt-example-tests) * [Github Example](https://github.com/RookieOne/react-alt-github-example) * [Isomorphic Alt](https://github.com/patrickkim/iso-alt) * [Jumar's Tindahan](https://github.com/srph/jumars-tindahan) * [Maple.js Webcomponents](https://github.com/Wildhoney/Maple.js/tree/master/example/app) * [React Native Example](https://github.com/mrblueblue/react-native-alt-demo) * [React Router Example](https://github.com/lostpebble/alt-react-router-example) * [React Router Loopback](https://github.com/bkniffler/react-router-alt-loopback) * [React Webpack Rails Example](https://github.com/justin808/react-webpack-rails-tutorial) * [React Webpack Altjs Example](https://underthehood.myob.com/changing-of-the-guard-in-web-technologies/) * [React Weather](https://github.com/sapegin/react-weather) * [Shopping Cart](https://github.com/voronianski/flux-comparison/tree/master/alt) * [Todo](https://github.com/benstokoe/alt-todo) * [Typeahead](https://github.com/timtyrrell/alt-typeahead) * [Isomorphic React Examples](https://github.com/goatslacker/isomorphic-react-examples) * [Typescript Project](https://github.com/Shearerbeard/alt-typescript-tutorial) * [Why did Social Tables choose Alt?](https://medium.com/social-tables-tech/we-compared-13-top-flux-implementations-you-won-t-believe-who-came-out-on-top-1063db32fe73) ### Boilerplates * [Isomorphic Flux Boilerplate](https://github.com/iam4x/isomorphic-flux-boilerplate) * [React + Webpack + Node](https://github.com/choonkending/react-webpack-node) * [Web-React](https://github.com/darul75/web-react) ## Pure Flux + More * Unidirectional data flow * Stores have no setters * Inversion of control * Single central dispatcher * All Stores receive the dispatch Read about the [Principles of Flux](https://medium.com/@goatslacker/principles-of-flux-ea872bc20772). One really cool aspect of alt is that you can save snapshots of the entire application's state at any given point in time. This has many different use cases like: * Time traveling through the state of your application. For fun and profit. * Being able to debug from a broken state. Have your team send you the exact state the app was in when it crashed. * Isomorphism. You save a snapshot that you send from the server to the client and then bootstrap back on the client. * Rolling back to previous stable states. There are also many [utils](/src/utils) available which interface well with alt: * [ActionListener](/src/utils/ActionListeners.js) lets you listen to individual actions without having to create a store. * [AltContainer](/components/AltContainer.js) a higher-order container component that is your swiss army knife for React. * [AltIso](/src/utils/AltIso.js) addon that uses [iso](https://github.com/goatslacker/iso) to render your application on both server and client. * [atomic](/src/utils/atomic.js) enables your stores for atomic transactions. * [connectToStores](/src/utils/connectToStores.js) a higher-order function that wraps your React components for store listening. * [decorators](/src/utils/decorators.js) a collection of useful ES7 decorators for working with alt. * [DispatchRecorder](/src/utils/DispatcherRecorder.js) lets you record all your dispatches and replay them back at a later time. * [FinalStore](/src/utils/makeFinalStore.js) is a Store that you can listen to that only emits when all your other stores have received all their data. * [ImmutableUtil](/src/utils/ImmutableUtil.js) makes working with immutable-js easy. * [TimeTravel](/src/utils/TimeTravel.js) enhances your stores so they are able to travel through different states in time. ## Topical Guide First we install alt through npm. Although alt is also available through bower. ```sh npm install alt ``` The following topical guide covers on using alt as a singleton in a traditional flux way. We'll be referring back to this code a lot by using the `alt` reference declared. ```js const Alt = require('alt'); const alt = new Alt(); ``` ### ES6 Alt is written in, and encourages ES6. It is completely optional but it is pleasant to write. You can use the es6 transpiler that comes with react courtesy of [jstransform](https://github.com/facebook/jstransform) or you can use one of the other popular ES6 transpilers: [babel](https://babeljs.io/) or [traceur](https://github.com/google/traceur-compiler). You won't need an [es6-shim](https://github.com/paulmillr/es6-shim) but you can use one for further goodies in your javascripts. Alt does depend on ES5 features, the good news is so does React. You can use [es5-shim](https://github.com/es-shims/es5-shim) to support those pesky old browsers. ##Typescript Definitions and Support The typescript definitions for alt are located in the typings directory. This should be included in your project under typings/alt or whatever folder you use to manage your definitions files. You can import the dependencies react and es6-promises, easily with [TSD](https://github.com/DefinitelyTyped/tsd). From here you can reference your typings as per usual with a reference tag ```<reference path="<path>.d.ts" />```. Check the [alt-typescript-tutorial](https://github.com/Shearerbeard/alt-typescript-tutorial) for more information and project examples. Using Typescript 1.5 you can import with the legacy syntax: ``` import Alt = require("alt"); import chromeDebug = require("alt/utils/chromeDebug"); import AltContainer = require("alt/AltContainer"); ``` ### Creating Actions Actions are the way you update state. They're kind of a big deal. `alt.createActions :: Class -> Actions` ```js class LocationActions { updateLocation(city) { return city; } } const locationActions = alt.createActions(LocationActions); ``` You return the data from your action that you wish to dispatch. If you want to run async in your actions then you simply return a function where the first argument is the dispatch: ```js class LocationActions { updateLocationThatDoesItAsync(city) { return (dispatch) => { setTimeout(() => dispatch(city)); }; } } ``` `alt.createActions` then returns an `Object` containing all the methods defined. You can then call your actions directly. ```js locationActions.updateLocation('Paris'); ``` Writing out actions that pass data through directly can get quite tedious so there's a shorthand for writing these what are essentially `identity` functions ```js class LocationActions { constructor() { // for single action this.generateActions('updateLocation'); // as well as for many actions this.generateActions('updateCity', 'updateCountry'); } } const locationActions = alt.createActions(LocationActions); ``` ```js locationActions.updateLocation('Las Vegas') locationActions.updateCity('Las Vegas') locationActions.updateCountry('US') ``` Remember, `dispatch` only takes one argument. Therefore, if you need to pass multiple arguments into a store you can use an Object. ```js class LocationActions { updateLocation(x, y) { return { x, y }; } } const locationActions = alt.createActions(LocationActions); locationActions.updateLocation('Miami', 'Florida'); ``` A shorthand function created in the constructor will pass through the multiple parameters as an Array ```js class LocationActions { constructor() { this.generateActions('updateLocation'); // ['South Lake Tahoe, 'California'] } } const locationActions = alt.createActions(LocationActions); locationActions.updateLocation('South Lake Tahoe', 'California'); ``` There's even a shorthand for the shorthand if all you're doing is generating a list of actions ```js const locationActions = alt.generateActions('updateLocation', 'updateCity', 'updateCountry'); ``` ### Stores Stores are where you keep a part of your application's state. You can either define your stores as a class/constructor-prototype or as an Object. `alt.createStore :: Class, string -> Store` ```js class LocationStore { constructor() { this.bindAction(locationActions.updateLocation, this.onUpdateLocation); this.state = { city: 'Denver', country: 'US' }; } onUpdateLocation(obj) { const { city, country } = obj this.setState({ city, country }); } } const locationStore = alt.createStore(LocationStore); ``` You can also use a regular old JavaScript Object to create your stores. This is more about aesthetic preference. ```js const locationStore = alt.createStore({ displayName: 'LocationStore', bindListeners: { onUpdateLocation: locationActions.updateLocation }, state: { city: 'Denver', country: 'US' }, onUpdateLocation(obj) { const { city, country } = obj this.setState({ city, country }); } }); ``` If you're creating a store using a class/constructor then you also have the option of assigning your state values to your instance directly and then you're able to update them in place. ```js function LocationStore() { this.city = 'San Francisco'; this.country = 'US'; } LocationStore.prototype.onUpdateLocation = function (obj) { this.city = obj.city; this.country = obj.country; }; ``` Store instances returned by `alt.createStore` can be listened to for updates by calling `listen`. `listen` is meant to be used by your View components in order to await changes made to each store. It returns a function you can use to un-listen to your store. ```js locationStore.listen((data) => { console.log(data) }); ``` Alternatively, you can use the `unlisten` method. It takes in the same function you used for `listen` and unregisters it. Another important method is `getState`, which returns a copy of the current store's state. ```js locationStore.getState().city === 'Denver' ``` #### Important Note All defined methods in your Store class **will not** be available on the store instance. They are accessible within the class but not on the returned Object via `alt.createStore`. This ensures that stores have no direct setters and the state remains mutable only through actions keeping the flow unidirectional. If you want to attach public/static functions to your store the recommended method is to call the `exportPublicMethods` method from the constructor: ```js class LocationStore { constructor() { this.exportPublicMethods({ myPublicMethod: this.myPublicMethod }); } myPublicMethod() { const internalInstanceState = this.getState(); return internalInstanceState; } } const locationStore = alt.createStore(LocationStore); locationStore.myPublicMethod(); ``` An alternative is to declare the method as `static`, which will cause alt to expose the method on the store: ```js // does the same thing as above except in a more magical way class LocationStore { static myPublicMethod() { const internalInstanceState = this.getState(); return internalInstanceState; } } ``` #### Canceling An Event If you don't want the store to inform the view of an action you can call `this.preventDefault()` (or you can return false) from inside an action handler method. ```js class LocationStore { constructor() { this.bindAction(locationActions.updateCity, this.onUpdateCity); this.state = { city: 'Portland', country: 'US' }; } onUpdateCity(city) { this.setState({ city }); // ensure the view never finds out this.preventDefault(); } } const locationStore = alt.createStore(LocationStore); ``` #### Constants I thought you said there were no constants? Well, yeah, sort of. The thing is, they're automagically created for you. Feel free to use them to bind your actions or use the method itself, whatever reads better in your opinion. ```js class LocationStore { constructor() { this.bindAction(locationActions.UPDATE_CITY, this.onUpdateCity); this.state = { city: '', country: '' }; } } const locationStore = alt.createStore(LocationStore); ``` #### Listening To Multiple Actions ```js class LocationActions { constructor() { this.generateActions('updateCity', 'updateCountry'); } } const locationActions = alt.createActions(LocationActions); ``` Using the function `bindListeners` you're able to specify which action handlers belong to which actions this way you have ultimate control over what gets called and handled. The function `bindListeners` is the inverse of `bindAction`. `bindListeners` takes an object of action handlers as keys and actions as a value. ```js class LocationStore { constructor() { this.bindListeners({ handleCity: locationActions.updateCity, handleCountry: [locationActions.updateCountry, locationActions.updateLatLng] }); } handleCity(data) { // will only be called by locationActions.updateCity() } handleCountry(data) { // will be called by locationActions.updateCountry() and locationActions.updateLatLng() } } ``` Alternatively, you can bind all the actions inside `locationActions` using the shortcut `bindActions` ```js class LocationStore { constructor() { this.bindActions(locationActions); this.state = { city: 'Austin', country: 'US' }; } onUpdateCity(city) { this.setState({ city }); } onUpdateCountry(country) { this.setState({ country }); } } const locationStore = alt.createStore(LocationStore); ``` Actions who have a `onCamelCasedAction` method or an `actionName` method available in the store will be bound. In this example `locationActions.updateCity` will be handled by `onUpdateCity`. There is no difference between calling the action handler `updateCity` or `onUpdateCity` it's just a matter of aesthetic preference. #### Managing Store Data Dependencies `waitFor` is mostly an alias to Flux's Dispatcher waitFor. Here's an excerpt from the flux docs on what waitFor is designed for: > As an application grows, dependencies across different stores are a near certainty. Store A will inevitably need Store B to update itself first, so that Store A can know how to update itself. We need the dispatcher to be able to invoke the callback for Store B, and finish that callback, before moving forward with Store A. To declaratively assert this dependency, a store needs to be able to say to the dispatcher, "I need to wait for Store B to finish processing this action." The dispatcher provides this functionality through its waitFor() method. You can use waitFor like so: ```js const dependingStore = alt.createStore(class DependingStore { constructor() { this.bindActions(someActions); this.state = { answer: 42 }; } onRandom(answer) { this.setState({ answer }); } }) const locationStore = alt.createStore(class LocationStore { constructor() { this.bindActions(someOtherActions) this.state = { meaningOfLife: null }; } onThings() { this.waitFor(dependingStore.dispatchToken); this.setState({ meaningOfLife: dependingStore.getState().answer }); } }) ``` You can also `waitFor` multiple stores by passing in an Array: `this.waitFor([store1.dispatchToken, store2.dispatchToken])` ### Views Your choice of view isn't important to alt. What's important is to know how the view consumes the store's data, and that is via event listeners. In this example I'll be using React, but you're free to use your library of choice. ```js class LocationView extends React.Component { // these are methods that work with `connectToStores` which connects // one or many stores to your component passing the state in as props. // you're free to choose how the state from the store is passed into the // component as props. // this automatically does the listening/unlistening for you as well as // handles the state changes static getStores() { return [locationStore]; } static getPropsFromStores() { return locationStore.getState(); } render() { return ( <div> <p> City {this.props.city} </p> <p> Country {this.props.country} </p> </div> ) } } // just make sure to wrap your component with connectToStores() export default connectToStores(LocationView); ``` ### Full Circle Restart the loop by making your views kick off new actions. ## Alt Features ### Snapshots `takeSnapshot :: ?...string -> string` Snapshots are a core component of alt. The idea is that at any given point in time you can `takeSnapshot` and have your entire application's state serialized for persistence, transferring, logging, or debugging. Taking a snapshot is as easy as calling `alt.takeSnapshot()`. It can also take an optional number of arguments as strings which correspond to the store names you would like to include in the snapshot. This allows you to take a snapshot of a subset of your app's data. ### Bootstrapping `bootstrap :: string -> undefined` Bootstrapping can be done as many times as you wish, but it is common to use when initializing your application. The `alt.bootstrap()` function takes in a snapshot (JSON string) you've saved and reloads all the state with that snapshot, no events will be emitted to your components during this process, so again, it's best to do this on init before the view has even rendered. If you need to emit a change event, you can use `this.emitChange` inside of your `bootstrap` life cycle method. Bootstrap is great if you're running an isomorphic app, or if you're persisting state to localstorage and then retrieving it on init later on. You can save a snapshot on the server side, send it down, and then bootstrap it back on the client. If you're bootstrapping then it is recommended you pass in a unique Identifier, name of the class is good enough, to createStore so that it can be referenced later for bootstrapping. ```js alt.createStore(LocationStore, 'LocationStore') ``` ### Rollback `rollback :: undefined` If you've screwed up the state, or you just feel like rolling back you can call `alt.rollback()`. Rollback is pretty dumb in the sense that it's not automatic in case of errors, and it only rolls back to the last saved snapshot, meaning you have to save a snapshot first in order to roll back. ### Flushing `flush :: string` Flush takes a snapshot of the current state and then resets all the stores back to their original initial state. This is useful if you're using alt stores as singletons and doing server side rendering because of concurrency. In this particular scenario you would load the data in via `bootstrap` and then use `flush` to take a snapshot, render the data, and reset your stores so they are ready for the next request. ### Recycling `recycle :: ?...string -> undefined` If you wish to reset a particular, or all, store's state back to their original initial state you would call `recycle`. Recycle takes an optional number of arguments as strings which correspond to the store's names you would like reset. If no argument is provided then all stores are reset. ### Lifecycle Methods When bootstrapping, snapshotting, or recycling there are special methods you can assign to your store to ensure any bookeeping that needs to be done. You would place these in your store's constructor. `bootstrap` is called after the store has been bootstrapped. Here you can add some logic to take your bootstrapped data and manipulate it. ```js class Store { constructor() { this.on('bootstrap', () => { // do something here }) } } ``` `init` is called when the store is initialized as well as whenever a store is recycled. ```js class Store { constructor() { this.on('init', () => { // do something here }) } } ``` `rollback` is called whenever all the stores are rolled back. ```js class Store { constructor() { this.on('rollback', () => { // do something here }) } } ``` `error` is called whenever an error occurs in your store during a dispatch. You can use this listener to catch errors and perform any cleanup tasks. ```js class Store { constructor() { this.on('error', (err, actionName, payloadData, currentState) => { if (actionName === MyActions.fire) { logError(err, payloadData); } }); this.bindListeners({ handleFire: MyActions.fire }); } handleFire() { throw new Error('Something is broken'); } } ``` [See all the lifecycle methods](http://alt.js.org/docs/lifecycleListeners/) ### Single Dispatcher A single dispatcher instance is made available for listening to all events passing through. You can access this via the `dispatcher` property: `alt.dispatcher` and listening to all events is as easy as ```js alt.dispatcher.register(console.log.bind(console)) ``` Each store has a reference to the dispatcher as well ```js alt.createStore(class MyStore { constructor() { this.dispatcher.register(console.log.bind(console)) } }) ``` ### Flexibility You can choose to use alt in many ways just like you'd use flux. This means your asynchronous data fetching can live in the actions, or they can live in the stores. Stores may also be traditional singletons as in flux, or you can create an instance and have multiple store copies. This leads us into server side rendering. ### Server Side Rendering Alt was built with isomorphism in mind. This means that you can run full flux server-side and pick back up on the client-side. There are two options for using flux on the server: * Keep stores as singletons, keep data loading synchronous, bootstrap, and flush. * Create multiple instances of flux and inject the context into your app. #### Stores as Singletons With this approach your stores are singletons. Any actions that load data must be synchronous, meaning you can fetch your data outside of actions and stores, and once done you fire off a synchronous action which loads the store. Alternatively, you can gather all of your data, and once complete, you call `bootstrap()` which seeds all the stores with some initial data. Once you've completed loading the stores with data you call `flush()` which takes a snapshot to send to the client and then resets all the stores' state back to their initial state. This allows the stores to be ready for the next server request. #### Flux Instances Creating separate instances of flux rather than relying on singletons can help when building isomorphic applications. The problem with singletons is that you need to manage them by clearing out all their state and reloading them with new state on every request because requests happen concurrently. This isn't a problem if you already have your data and just need to load it into flux, or if you don't want to share your data fetching logic with the client -- in which case you can just load all your data at once on the server and render once that is all complete. Singletons only become a problem if you wish to share data fetching with client and server, don't want to use something like [Render](/src/utils/Render) to define your data fetching at the component level, or if you have a really complex data fetching scheme where some fetches depend on the result of other ones. In these cases creating separate instances (or copies) keeps flux sandboxed to each request so other async requests won't mutate the state in the stores. Taking this approach means you're making the trade-off of injecting the flux instance into your application in order to retrieve the stores and use the actions. This approach is similar to how [fluxible](https://github.com/yahoo/fluxible) solves isomorphic applications. Creating a new alt instances is fairly simple. ```js class Flux extends Alt { constructor() { super(); this.addActions('myActions', ActionCreators); this.addStore('storeName', Store); } } const flux = new Flux(); ``` ```js // client.js React.render( <App flux={flux} />, document.body ); ``` ```js // server.js React.renderToString(<App flux={flux} />); ``` ```js // retrieving stores flux.getStore('storeName').getState(); // actions flux.getActions('myActions'); ``` #### Picking back up on the client To help facilitate with isomorphism alt recommends you use [iso](https://github.com/goatslacker/iso), a helper function which serializes the data on the server into markup and then parses that data back into usable JavaScript on the client. Iso is a great complement to alt for a full-stack flux approach. ## Examples * [todomvc](https://github.com/goatslacker/alt/blob/master/examples/todomvc) * [chat](https://github.com/goatslacker/alt/tree/master/examples/chat) ## Converting a flux application to alt 1. [Importing the chat project](https://github.com/goatslacker/alt/commit/1a54de1064fe5bd252979380e47b0409d1306773). 2. [Adding alt and removing boilerplate](https://github.com/goatslacker/alt/commit/75ffdb53420dc32bdc2d99b5cf534cd0949331d8). 3. [Converting some actions](https://github.com/goatslacker/alt/commit/6f8cf22ba6b36c6ae91a794fad75473c9436b683) and [the last action](https://github.com/goatslacker/alt/commit/58ea1418ecd2af25b578cd0f4b77c3d4d8631518). 4. Converting the stores [MessageStore](https://github.com/goatslacker/alt/commit/f4c7bb4bb9027b53c380f98ed99a2e1b6ba5fa0b), [ThreadStore](https://github.com/goatslacker/alt/commit/bce2aadbb52981f934b4281b3a6244d4f2c4a7a9), and [UnreadThreadStore](https://github.com/goatslacker/alt/commit/0129baa5bd505ef26228e30cfa15a6ac4503a22d). 5. [Finishing touches](https://github.com/goatslacker/alt/commit/e05a4e02f3f13831361136a21cd757416b69b4d8). ## Differences Example Flux has constants, the dispatcher is also pretty dumb as in it just takes what you passed in the action and pipes it through to the store. This is completely fine but not something you should be expected to write. The nice thing about constants is that you can easily grep for them in your application and see where all the actions are being called, with alt you get the same benefit without having to manage them. #### Before: Flux ```js var keyMirror = require('keymirror'); var actionConstants = keyMirror({ HANDLE_ACTION: null }); var action = { foo() { AppDispatcher.handleAction({ type: actionConstants.HANDLE_ACTION, data: 'foo' }) } }; var AppDispatcher = Object.assign(new Dispatcher(), { handleAction(payload) { this.dispatch(payload); } }); ``` #### After: Alt ```js class Action { handleAction() { return 'foo'; } } const action = alt.createActions(Action); ``` ## TL;DR * Isomorphic * Pure Flux * No constants * No static string checking * No giant switch statement * Save state snapshots * Rollbacks * Bootstrap components on app load * Light-weight and terse * ES6 Syntax, code your actions and stores with classes * Flexible * No direct setters on stores * Single dispatcher * Global listening for debugging * Small library ## License [![MIT](https://img.shields.io/npm/l/alt.svg?style=flat)](http://josh.mit-license.org)
{ "content_hash": "ca4e925968eba31e6cb27cb04def96c1", "timestamp": "", "source": "github", "line_count": 882, "max_line_length": 557, "avg_line_length": 33.81972789115646, "alnum_prop": 0.7384759797512488, "repo_name": "BenjamH/post-it-react", "id": "de7ed33a45f9c2a7dc3ad1b1c9f7a8ff105bc1f8", "size": "29836", "binary": false, "copies": "5", "ref": "refs/heads/master", "path": "node_modules/alt/README.md", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "1747" }, { "name": "HTML", "bytes": "2302" }, { "name": "JavaScript", "bytes": "4954" } ], "symlink_target": "" }
<?php namespace Bowhead\Http\Controllers; use Bowhead\Traits\Mapper; use Illuminate\Http\Request; use Dingo\Api\Routing\Helpers; use Illuminate\Routing\Controller; /** * Class Accounts * @package Bowhead\Http\Controllers */ class Accounts extends Controller { /** * @var */ protected $dataArray; /** * @var array */ protected $broker_list; /** * @var */ protected $errors = []; use Mapper; public function __construct(Request $request) { $this->dataArray = $request->all(); $this->broker_list = $this->mapped_brokers_list; // from Mapper... $brokers = join(', ', $this->broker_list); if (empty($this->dataArray['source'])) { $this->errors[] = "'source' cannot be empty, select a brokerage: [$brokers]"; } } function __debugInfo() { // TODO: Implement __debugInfo() method. } public function getAccountsAction() { if (!empty($this->errors)) { return $this->errors; } $data = $this->dataArray; $action = 'accounts_all'; $ret = $this->mapperAccounts($data['source'], ['action' => $action]); return $ret; } /** retrieve orders and accounts */ public function getAccountAction() { $data = $this->dataArray; if (empty($data['id'])) { $this->errors[] = 'id is a requried field for getting an account'; } if (!empty($this->errors)) { return $this->errors; } return []; } /** * place orders and such */ public function posttAccountAction() { } /** modify orders */ public function patchAccountAction() { } /** close positions */ public function deleteAccountAction() { } }
{ "content_hash": "bfe2111c3cbfd5d17fe4709bf1737431", "timestamp": "", "source": "github", "line_count": 97, "max_line_length": 89, "avg_line_length": 19.061855670103093, "alnum_prop": 0.5392103839913467, "repo_name": "maximerchrd/bowhead", "id": "b98ebcb558230040b698b27f1c253829dbe10faa", "size": "1849", "binary": false, "copies": "3", "ref": "refs/heads/master", "path": "app/Http/Controllers/Accounts.php", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "ApacheConf", "bytes": "553" }, { "name": "HTML", "bytes": "2746" }, { "name": "Nginx", "bytes": "665" }, { "name": "PHP", "bytes": "489375" }, { "name": "Python", "bytes": "7122" }, { "name": "Shell", "bytes": "2577" }, { "name": "Vue", "bytes": "563" } ], "symlink_target": "" }
$:.unshift "#{File.dirname(__FILE__)}/lib" require 'amqp_listener'
{ "content_hash": "8af451701264a29a4353482d01a3f2a8", "timestamp": "", "source": "github", "line_count": 2, "max_line_length": 42, "avg_line_length": 33, "alnum_prop": 0.6666666666666666, "repo_name": "brontes3d/amqp_listener", "id": "8463bc18c3a1cfb22551064c4e82c162655a67d9", "size": "66", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "init.rb", "mode": "33188", "license": "mit", "language": [ { "name": "Ruby", "bytes": "30480" } ], "symlink_target": "" }
<?xml version='1.0' encoding='UTF-8' standalone='no'?> <doxygen xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="compound.xsd" version="1.8.2"> <compounddef id="df/da0/struct_label_map" kind="struct" prot="public"> <compoundname>LabelMap</compoundname> <sectiondef kind="public-attrib"> <memberdef kind="variable" id="df/da0/struct_label_map_1a8e4084d4e2e1ce2b69c7e8138caedb50" prot="public" static="no" mutable="no"> <type>const char *</type> <definition>const char* LabelMap::name</definition> <argsstring></argsstring> <name>name</name> <briefdescription> </briefdescription> <detaileddescription> </detaileddescription> <inbodydescription> </inbodydescription> <location file="C:/Users/Mat/Projects/doxygraph/examples/doxygen-1.8.4/src/debug.cpp" line="30" bodyfile="C:/Users/Mat/Projects/doxygraph/examples/doxygen-1.8.4/src/debug.cpp" bodystart="30" bodyend="-1"/> </memberdef> <memberdef kind="variable" id="df/da0/struct_label_map_1af76882a09bbc3fd8ecc779f612446c52" prot="public" static="no" mutable="no"> <type>Debug::DebugMask</type> <definition>Debug::DebugMask LabelMap::event</definition> <argsstring></argsstring> <name>event</name> <briefdescription> </briefdescription> <detaileddescription> </detaileddescription> <inbodydescription> </inbodydescription> <location file="C:/Users/Mat/Projects/doxygraph/examples/doxygen-1.8.4/src/debug.cpp" line="31" bodyfile="C:/Users/Mat/Projects/doxygraph/examples/doxygen-1.8.4/src/debug.cpp" bodystart="31" bodyend="-1"/> </memberdef> </sectiondef> <briefdescription> <para>Helper struct representing a mapping from debug label to a debug ID. </para> </briefdescription> <detaileddescription> </detaileddescription> <location file="C:/Users/Mat/Projects/doxygraph/examples/doxygen-1.8.4/src/debug.cpp" line="29" bodyfile="C:/Users/Mat/Projects/doxygraph/examples/doxygen-1.8.4/src/debug.cpp" bodystart="28" bodyend="32"/> <listofallmembers> <member refid="df/da0/struct_label_map_1af76882a09bbc3fd8ecc779f612446c52" prot="public" virt="non-virtual"><scope>LabelMap</scope><name>event</name></member> <member refid="df/da0/struct_label_map_1a8e4084d4e2e1ce2b69c7e8138caedb50" prot="public" virt="non-virtual"><scope>LabelMap</scope><name>name</name></member> </listofallmembers> </compounddef> </doxygen>
{ "content_hash": "115da265b7fb57ab532989888512155a", "timestamp": "", "source": "github", "line_count": 43, "max_line_length": 213, "avg_line_length": 59.44186046511628, "alnum_prop": 0.6948356807511737, "repo_name": "seguijoaquin/taller2-appserver", "id": "8515855aa3b308bfe9725e6bf99832aade2030f6", "size": "2556", "binary": false, "copies": "19", "ref": "refs/heads/master", "path": "Documentacion/doxygraph/examples/doxygen/xml/df/da0/struct_label_map.xml", "mode": "33188", "license": "mit", "language": [ { "name": "C", "bytes": "99679" }, { "name": "C++", "bytes": "10237477" }, { "name": "CMake", "bytes": "144910" }, { "name": "CSS", "bytes": "43601" }, { "name": "HTML", "bytes": "14331186" }, { "name": "Java", "bytes": "790366" }, { "name": "JavaScript", "bytes": "651118" }, { "name": "M4", "bytes": "25387" }, { "name": "Makefile", "bytes": "217222" }, { "name": "Objective-C", "bytes": "9308" }, { "name": "PHP", "bytes": "38694" }, { "name": "Perl", "bytes": "54513" }, { "name": "PostScript", "bytes": "331209" }, { "name": "PowerShell", "bytes": "9458" }, { "name": "Python", "bytes": "2144821" }, { "name": "Ruby", "bytes": "1562" }, { "name": "Shell", "bytes": "158255" }, { "name": "TeX", "bytes": "950289" }, { "name": "XSLT", "bytes": "1290" } ], "symlink_target": "" }
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <!-- NewPage --> <html lang="en"> <head> <!-- Generated by javadoc (1.8.0_151) on Wed Jul 17 13:50:50 MST 2019 --> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>Uses of Interface org.wildfly.swarm.config.elytron.CustomModifiableRealmSupplier (BOM: * : All 2.5.0.Final API)</title> <meta name="date" content="2019-07-17"> <link rel="stylesheet" type="text/css" href="../../../../../../stylesheet.css" title="Style"> <script type="text/javascript" src="../../../../../../script.js"></script> </head> <body> <script type="text/javascript"><!-- try { if (location.href.indexOf('is-external=true') == -1) { parent.document.title="Uses of Interface org.wildfly.swarm.config.elytron.CustomModifiableRealmSupplier (BOM: * : All 2.5.0.Final API)"; } } catch(err) { } //--> </script> <noscript> <div>JavaScript is disabled on your browser.</div> </noscript> <!-- ========= START OF TOP NAVBAR ======= --> <div class="topNav"><a name="navbar.top"> <!-- --> </a> <div class="skipNav"><a href="#skip.navbar.top" title="Skip navigation links">Skip navigation links</a></div> <a name="navbar.top.firstrow"> <!-- --> </a> <ul class="navList" title="Navigation"> <li><a href="../../../../../../overview-summary.html">Overview</a></li> <li><a href="../package-summary.html">Package</a></li> <li><a href="../../../../../../org/wildfly/swarm/config/elytron/CustomModifiableRealmSupplier.html" title="interface in org.wildfly.swarm.config.elytron">Class</a></li> <li class="navBarCell1Rev">Use</li> <li><a href="../../../../../../overview-tree.html">Tree</a></li> <li><a href="../../../../../../deprecated-list.html">Deprecated</a></li> <li><a href="../../../../../../index-all.html">Index</a></li> <li><a href="../../../../../../help-doc.html">Help</a></li> </ul> <div class="aboutLanguage">Thorntail API, 2.5.0.Final</div> </div> <div class="subNav"> <ul class="navList"> <li>Prev</li> <li>Next</li> </ul> <ul class="navList"> <li><a href="../../../../../../index.html?org/wildfly/swarm/config/elytron/class-use/CustomModifiableRealmSupplier.html" target="_top">Frames</a></li> <li><a href="CustomModifiableRealmSupplier.html" target="_top">No&nbsp;Frames</a></li> </ul> <ul class="navList" id="allclasses_navbar_top"> <li><a href="../../../../../../allclasses-noframe.html">All&nbsp;Classes</a></li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_top"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } //--> </script> </div> <a name="skip.navbar.top"> <!-- --> </a></div> <!-- ========= END OF TOP NAVBAR ========= --> <div class="header"> <h2 title="Uses of Interface org.wildfly.swarm.config.elytron.CustomModifiableRealmSupplier" class="title">Uses of Interface<br>org.wildfly.swarm.config.elytron.CustomModifiableRealmSupplier</h2> </div> <div class="classUseContainer"> <ul class="blockList"> <li class="blockList"> <table class="useSummary" border="0" cellpadding="3" cellspacing="0" summary="Use table, listing packages, and an explanation"> <caption><span>Packages that use <a href="../../../../../../org/wildfly/swarm/config/elytron/CustomModifiableRealmSupplier.html" title="interface in org.wildfly.swarm.config.elytron">CustomModifiableRealmSupplier</a></span><span class="tabEnd">&nbsp;</span></caption> <tr> <th class="colFirst" scope="col">Package</th> <th class="colLast" scope="col">Description</th> </tr> <tbody> <tr class="altColor"> <td class="colFirst"><a href="#org.wildfly.swarm.config">org.wildfly.swarm.config</a></td> <td class="colLast">&nbsp;</td> </tr> </tbody> </table> </li> <li class="blockList"> <ul class="blockList"> <li class="blockList"><a name="org.wildfly.swarm.config"> <!-- --> </a> <h3>Uses of <a href="../../../../../../org/wildfly/swarm/config/elytron/CustomModifiableRealmSupplier.html" title="interface in org.wildfly.swarm.config.elytron">CustomModifiableRealmSupplier</a> in <a href="../../../../../../org/wildfly/swarm/config/package-summary.html">org.wildfly.swarm.config</a></h3> <table class="useSummary" border="0" cellpadding="3" cellspacing="0" summary="Use table, listing methods, and an explanation"> <caption><span>Methods in <a href="../../../../../../org/wildfly/swarm/config/package-summary.html">org.wildfly.swarm.config</a> with parameters of type <a href="../../../../../../org/wildfly/swarm/config/elytron/CustomModifiableRealmSupplier.html" title="interface in org.wildfly.swarm.config.elytron">CustomModifiableRealmSupplier</a></span><span class="tabEnd">&nbsp;</span></caption> <tr> <th class="colFirst" scope="col">Modifier and Type</th> <th class="colLast" scope="col">Method and Description</th> </tr> <tbody> <tr class="altColor"> <td class="colFirst"><code><a href="../../../../../../org/wildfly/swarm/config/Elytron.html" title="type parameter in Elytron">T</a></code></td> <td class="colLast"><span class="typeNameLabel">Elytron.</span><code><span class="memberNameLink"><a href="../../../../../../org/wildfly/swarm/config/Elytron.html#customModifiableRealm-org.wildfly.swarm.config.elytron.CustomModifiableRealmSupplier-">customModifiableRealm</a></span>(<a href="../../../../../../org/wildfly/swarm/config/elytron/CustomModifiableRealmSupplier.html" title="interface in org.wildfly.swarm.config.elytron">CustomModifiableRealmSupplier</a>&nbsp;supplier)</code> <div class="block">Install a supplied CustomModifiableRealm object to the list of subresources</div> </td> </tr> </tbody> </table> </li> </ul> </li> </ul> </div> <!-- ======= START OF BOTTOM NAVBAR ====== --> <div class="bottomNav"><a name="navbar.bottom"> <!-- --> </a> <div class="skipNav"><a href="#skip.navbar.bottom" title="Skip navigation links">Skip navigation links</a></div> <a name="navbar.bottom.firstrow"> <!-- --> </a> <ul class="navList" title="Navigation"> <li><a href="../../../../../../overview-summary.html">Overview</a></li> <li><a href="../package-summary.html">Package</a></li> <li><a href="../../../../../../org/wildfly/swarm/config/elytron/CustomModifiableRealmSupplier.html" title="interface in org.wildfly.swarm.config.elytron">Class</a></li> <li class="navBarCell1Rev">Use</li> <li><a href="../../../../../../overview-tree.html">Tree</a></li> <li><a href="../../../../../../deprecated-list.html">Deprecated</a></li> <li><a href="../../../../../../index-all.html">Index</a></li> <li><a href="../../../../../../help-doc.html">Help</a></li> </ul> <div class="aboutLanguage">Thorntail API, 2.5.0.Final</div> </div> <div class="subNav"> <ul class="navList"> <li>Prev</li> <li>Next</li> </ul> <ul class="navList"> <li><a href="../../../../../../index.html?org/wildfly/swarm/config/elytron/class-use/CustomModifiableRealmSupplier.html" target="_top">Frames</a></li> <li><a href="CustomModifiableRealmSupplier.html" target="_top">No&nbsp;Frames</a></li> </ul> <ul class="navList" id="allclasses_navbar_bottom"> <li><a href="../../../../../../allclasses-noframe.html">All&nbsp;Classes</a></li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_bottom"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } //--> </script> </div> <a name="skip.navbar.bottom"> <!-- --> </a></div> <!-- ======== END OF BOTTOM NAVBAR ======= --> <p class="legalCopy"><small>Copyright &#169; 2019 <a href="http://www.jboss.org">JBoss by Red Hat</a>. All rights reserved.</small></p> </body> </html>
{ "content_hash": "45f6152fc50ab7d55514cab4916ff7eb", "timestamp": "", "source": "github", "line_count": 171, "max_line_length": 488, "avg_line_length": 44.92397660818713, "alnum_prop": 0.6528247852121843, "repo_name": "wildfly-swarm/wildfly-swarm-javadocs", "id": "4299f73f1db11cb39c155c816523f331b4b51a2f", "size": "7682", "binary": false, "copies": "1", "ref": "refs/heads/gh-pages", "path": "2.5.0.Final/apidocs/org/wildfly/swarm/config/elytron/class-use/CustomModifiableRealmSupplier.html", "mode": "33188", "license": "apache-2.0", "language": [], "symlink_target": "" }
from django.conf.urls import url from api import views urlpatterns = [ url(r'^search/$', views.package_search, name='package_search'), url(r'^info/$', views.package_info, name='package_info'), url(r'^register/$', views.package_register, name='package_register'), url(r'^remove/$', views.package_remove, name='package_remove'), url(r'^remove_build/$', views.remove_build, name='remove_build'), url(r'^cleanup/$', views.cleanup, name='cleanup'), url(r'^cleanup_all/$', views.cleanup_all, name='cleanup_all'), url(r'^build/$', views.package_build, name='package_build'), url(r'^build_all/$', views.package_build_all, name='package_build_all'), url(r'^install/$', views.package_install, name='package_install'), url(r'^toggle_ignore/$', views.toggle_ignore, name='toggle_ignore'), ]
{ "content_hash": "1e1887fb0a854903621dca6b64870071", "timestamp": "", "source": "github", "line_count": 17, "max_line_length": 76, "avg_line_length": 48.529411764705884, "alnum_prop": 0.6654545454545454, "repo_name": "colajam93/aurpackager", "id": "741d45cb7412725b9f06bd0839f9ac31bb10a5ed", "size": "825", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "api/urls.py", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "352" }, { "name": "HTML", "bytes": "35879" }, { "name": "JavaScript", "bytes": "1347" }, { "name": "Python", "bytes": "53001" }, { "name": "Shell", "bytes": "776" } ], "symlink_target": "" }
package org.apereo.cas.adaptors.gauth; import org.apereo.cas.config.CasCoreAuthenticationConfiguration; import org.apereo.cas.config.CasCoreAuthenticationHandlersConfiguration; import org.apereo.cas.config.CasCoreAuthenticationMetadataConfiguration; import org.apereo.cas.config.CasCoreAuthenticationPolicyConfiguration; import org.apereo.cas.config.CasCoreAuthenticationPrincipalConfiguration; import org.apereo.cas.config.CasCoreAuthenticationServiceSelectionStrategyConfiguration; import org.apereo.cas.config.CasCoreAuthenticationSupportConfiguration; import org.apereo.cas.config.CasCoreConfiguration; import org.apereo.cas.config.CasCoreHttpConfiguration; import org.apereo.cas.config.CasCoreServicesAuthenticationConfiguration; import org.apereo.cas.config.CasCoreServicesConfiguration; import org.apereo.cas.config.CasCoreTicketCatalogConfiguration; import org.apereo.cas.config.CasCoreTicketsConfiguration; import org.apereo.cas.config.CasCoreUtilConfiguration; import org.apereo.cas.config.CasCoreWebConfiguration; import org.apereo.cas.config.CasPersonDirectoryConfiguration; import org.apereo.cas.config.GoogleAuthenticatorJpaConfiguration; import org.apereo.cas.config.support.CasWebApplicationServiceFactoryConfiguration; import org.apereo.cas.config.support.EnvironmentConversionServiceInitializer; import org.apereo.cas.config.support.authentication.GoogleAuthenticatorAuthenticationEventExecutionPlanConfiguration; import org.apereo.cas.logout.config.CasCoreLogoutConfiguration; import org.apereo.cas.otp.repository.credentials.OneTimeTokenAccount; import org.apereo.cas.otp.repository.credentials.OneTimeTokenCredentialRepository; import org.apereo.cas.util.SchedulingUtils; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.boot.autoconfigure.aop.AopAutoConfiguration; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.test.context.TestConfiguration; import org.springframework.cloud.autoconfigure.RefreshAutoConfiguration; import org.springframework.context.ApplicationContext; import org.springframework.context.annotation.EnableAspectJAutoProxy; import org.springframework.scheduling.annotation.EnableScheduling; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringRunner; import org.springframework.transaction.annotation.EnableTransactionManagement; import javax.annotation.PostConstruct; import java.util.Arrays; import static org.junit.Assert.*; /** * Test cases for {@link JpaGoogleAuthenticatorTokenCredentialRepository}. * * @author Misagh Moayyed * @since 5.0.0 */ @RunWith(SpringRunner.class) @SpringBootTest(classes = { JpaGoogleAuthenticatorTokenCredentialRepositoryTests.JpaTestConfiguration.class, GoogleAuthenticatorJpaConfiguration.class, CasCoreTicketsConfiguration.class, CasCoreTicketCatalogConfiguration.class, CasCoreLogoutConfiguration.class, CasCoreHttpConfiguration.class, CasCoreAuthenticationConfiguration.class, CasCoreServicesAuthenticationConfiguration.class, CasCoreAuthenticationMetadataConfiguration.class, CasCoreAuthenticationPolicyConfiguration.class, CasCoreAuthenticationPrincipalConfiguration.class, CasCoreAuthenticationHandlersConfiguration.class, CasCoreAuthenticationSupportConfiguration.class, CasPersonDirectoryConfiguration.class, CasCoreServicesConfiguration.class, CasWebApplicationServiceFactoryConfiguration.class, GoogleAuthenticatorAuthenticationEventExecutionPlanConfiguration.class, CasCoreUtilConfiguration.class, CasCoreConfiguration.class, CasCoreAuthenticationServiceSelectionStrategyConfiguration.class, AopAutoConfiguration.class, RefreshAutoConfiguration.class, CasCoreWebConfiguration.class}) @EnableTransactionManagement(proxyTargetClass = true) @EnableAspectJAutoProxy(proxyTargetClass = true) @EnableScheduling @ContextConfiguration(initializers = EnvironmentConversionServiceInitializer.class) public class JpaGoogleAuthenticatorTokenCredentialRepositoryTests { @Autowired @Qualifier("googleAuthenticatorAccountRegistry") private OneTimeTokenCredentialRepository registry; @TestConfiguration public static class JpaTestConfiguration { @Autowired protected ApplicationContext applicationContext; @PostConstruct public void init() { SchedulingUtils.prepScheduledAnnotationBeanPostProcessor(applicationContext); } } @Test public void verifySave() { registry.save("uid", "secret", 143211, Arrays.asList(1, 2, 3, 4, 5, 6)); final OneTimeTokenAccount s = registry.get("uid"); assertEquals(s.getSecretKey(), "secret"); } }
{ "content_hash": "358c9cf6bdf9987ee731a5b13b087cf8", "timestamp": "", "source": "github", "line_count": 105, "max_line_length": 117, "avg_line_length": 47.39047619047619, "alnum_prop": 0.8263665594855305, "repo_name": "Unicon/cas", "id": "07294db1e1562b8daea64b78a70181a9af711444", "size": "4976", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "support/cas-server-support-gauth-jpa/src/test/java/org/apereo/cas/adaptors/gauth/JpaGoogleAuthenticatorTokenCredentialRepositoryTests.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "281434" }, { "name": "Groovy", "bytes": "4742" }, { "name": "HTML", "bytes": "249429" }, { "name": "Java", "bytes": "7882824" }, { "name": "JavaScript", "bytes": "171051" }, { "name": "Shell", "bytes": "15678" }, { "name": "TypeScript", "bytes": "254507" } ], "symlink_target": "" }
// Copyright 2020, Google LLC // // 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 // // https://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 Google.Cloud.Functions.Testing; using System; using System.Text.Json; using System.Threading.Tasks; using Xunit; namespace Google.Cloud.Functions.Examples.IntegrationTests; public class AdvancedDependencyInjectionTest : FunctionTestBase<AdvancedDependencyInjection.Function> { [Fact] public async Task SingletonOperationIdRemainsStable() { // Make two requests to the function. They should both return the same SingletonOperationId value. var response1 = await CallFunctionAsync(); var response2 = await CallFunctionAsync(); Assert.Equal(response1.SingletonOperationId, response2.SingletonOperationId); } [Fact] public async Task ScopedOperationIdChangesPerRequest() { // Make two requests to the function. They should provide different ScopedOperationId values. var response1 = await CallFunctionAsync(); var response2 = await CallFunctionAsync(); Assert.NotEqual(response1.ScopedOperationId, response2.ScopedOperationId); } private async Task<ResponseModel> CallFunctionAsync() { var content = await ExecuteHttpGetRequestAsync(); return JsonSerializer.Deserialize<ResponseModel>(content); } private class ResponseModel { public Guid SingletonOperationId { get; set; } public Guid ScopedOperationId { get; set; } } }
{ "content_hash": "1022b9fb60ab2eb53820536b48f8e7df", "timestamp": "", "source": "github", "line_count": 56, "max_line_length": 106, "avg_line_length": 35.25, "alnum_prop": 0.7330293819655522, "repo_name": "GoogleCloudPlatform/functions-framework-dotnet", "id": "a28bf15deb273539342e992f85ec5a30b1180dcf", "size": "1976", "binary": false, "copies": "1", "ref": "refs/heads/main", "path": "examples/Google.Cloud.Functions.Examples.IntegrationTests/AdvancedDependencyInjectionTest.cs", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Batchfile", "bytes": "110" }, { "name": "C#", "bytes": "240562" }, { "name": "F#", "bytes": "4651" }, { "name": "Shell", "bytes": "14174" }, { "name": "Visual Basic .NET", "bytes": "4715" } ], "symlink_target": "" }
<?xml version="1.0" encoding="UTF-8"?> <project version="4"> <component name="ProjectModuleManager"> <modules> <module fileurl="file://$PROJECT_DIR$/.idea/flask_tdd.iml" filepath="$PROJECT_DIR$/.idea/flask_tdd.iml" /> </modules> </component> </project>
{ "content_hash": "547ada038de3a502f97e15dab3c77612", "timestamp": "", "source": "github", "line_count": 8, "max_line_length": 112, "avg_line_length": 33.75, "alnum_prop": 0.6555555555555556, "repo_name": "UrangUrang/flask-tdd-with-testing-goat", "id": "74a60251811a7b63c8f444ac64a251c21dded897", "size": "270", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": ".idea/modules.xml", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "148" }, { "name": "HTML", "bytes": "1710" }, { "name": "JavaScript", "bytes": "484" }, { "name": "Python", "bytes": "12014" } ], "symlink_target": "" }
package com.google.thirdparty.publicsuffix; import com.google.common.annotations.GwtCompatible; /** * Specifies the type of a top-level domain definition. */ @GwtCompatible enum PublicSuffixType { /** private definition of a top-level domain */ PRIVATE(':', ','), /** ICANN definition of a top-level domain */ ICANN('!', '?'); /** The character used for an inner node in the trie encoding */ private final char innerNodeCode; /** The character used for a leaf node in the trie encoding */ private final char leafNodeCode; private PublicSuffixType(char innerNodeCode, char leafNodeCode) { this.innerNodeCode = innerNodeCode; this.leafNodeCode = leafNodeCode; } char getLeafNodeCode() { return leafNodeCode; } char getInnerNodeCode() { return innerNodeCode; } /** Returns a PublicSuffixType of the right type according to the given code */ static PublicSuffixType fromCode(char code) { for (PublicSuffixType value : values()) { if (value.getInnerNodeCode() == code || value.getLeafNodeCode() == code) { return value; } } throw new IllegalArgumentException("No enum corresponding to given code: " + code); } static PublicSuffixType fromIsPrivate(boolean isPrivate) { return isPrivate ? PRIVATE : ICANN; } }
{ "content_hash": "7f9bc33e1ce096cf8c0a3135d4a5843e", "timestamp": "", "source": "github", "line_count": 50, "max_line_length": 87, "avg_line_length": 26.16, "alnum_prop": 0.6964831804281345, "repo_name": "jakubmalek/guava", "id": "ab6fd1a0132732bb9b787c7c2cb4c9936f575203", "size": "1902", "binary": false, "copies": "4", "ref": "refs/heads/master", "path": "guava/src/com/google/thirdparty/publicsuffix/PublicSuffixType.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "11478" }, { "name": "Java", "bytes": "12479725" }, { "name": "Shell", "bytes": "1128" } ], "symlink_target": "" }
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <!-- NewPage --> <html lang="en"> <head> <!-- Generated by javadoc (version 1.7.0) on Mon Jan 13 19:53:38 EST 2014 --> <title>Uses of Class org.drip.service.env.CDSManager</title> <meta name="date" content="2014-01-13"> <link rel="stylesheet" type="text/css" href="../../../../../stylesheet.css" title="Style"> </head> <body> <script type="text/javascript"><!-- if (location.href.indexOf('is-external=true') == -1) { parent.document.title="Uses of Class org.drip.service.env.CDSManager"; } //--> </script> <noscript> <div>JavaScript is disabled on your browser.</div> </noscript> <!-- ========= START OF TOP NAVBAR ======= --> <div class="topNav"><a name="navbar_top"> <!-- --> </a><a href="#skip-navbar_top" title="Skip navigation links"></a><a name="navbar_top_firstrow"> <!-- --> </a> <ul class="navList" title="Navigation"> <li><a href="../../../../../overview-summary.html">Overview</a></li> <li><a href="../package-summary.html">Package</a></li> <li><a href="../../../../../org/drip/service/env/CDSManager.html" title="class in org.drip.service.env">Class</a></li> <li class="navBarCell1Rev">Use</li> <li><a href="../package-tree.html">Tree</a></li> <li><a href="../../../../../deprecated-list.html">Deprecated</a></li> <li><a href="../../../../../index-files/index-1.html">Index</a></li> <li><a href="../../../../../help-doc.html">Help</a></li> </ul> </div> <div class="subNav"> <ul class="navList"> <li>Prev</li> <li>Next</li> </ul> <ul class="navList"> <li><a href="../../../../../index.html?org/drip/service/env/\class-useCDSManager.html" target="_top">Frames</a></li> <li><a href="CDSManager.html" target="_top">No Frames</a></li> </ul> <ul class="navList" id="allclasses_navbar_top"> <li><a href="../../../../../allclasses-noframe.html">All Classes</a></li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_top"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } //--> </script> </div> <a name="skip-navbar_top"> <!-- --> </a></div> <!-- ========= END OF TOP NAVBAR ========= --> <div class="header"> <h2 title="Uses of Class org.drip.service.env.CDSManager" class="title">Uses of Class<br>org.drip.service.env.CDSManager</h2> </div> <div class="classUseContainer">No usage of org.drip.service.env.CDSManager</div> <!-- ======= START OF BOTTOM NAVBAR ====== --> <div class="bottomNav"><a name="navbar_bottom"> <!-- --> </a><a href="#skip-navbar_bottom" title="Skip navigation links"></a><a name="navbar_bottom_firstrow"> <!-- --> </a> <ul class="navList" title="Navigation"> <li><a href="../../../../../overview-summary.html">Overview</a></li> <li><a href="../package-summary.html">Package</a></li> <li><a href="../../../../../org/drip/service/env/CDSManager.html" title="class in org.drip.service.env">Class</a></li> <li class="navBarCell1Rev">Use</li> <li><a href="../package-tree.html">Tree</a></li> <li><a href="../../../../../deprecated-list.html">Deprecated</a></li> <li><a href="../../../../../index-files/index-1.html">Index</a></li> <li><a href="../../../../../help-doc.html">Help</a></li> </ul> </div> <div class="subNav"> <ul class="navList"> <li>Prev</li> <li>Next</li> </ul> <ul class="navList"> <li><a href="../../../../../index.html?org/drip/service/env/\class-useCDSManager.html" target="_top">Frames</a></li> <li><a href="CDSManager.html" target="_top">No Frames</a></li> </ul> <ul class="navList" id="allclasses_navbar_bottom"> <li><a href="../../../../../allclasses-noframe.html">All Classes</a></li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_bottom"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } //--> </script> </div> <a name="skip-navbar_bottom"> <!-- --> </a></div> <!-- ======== END OF BOTTOM NAVBAR ======= --> </body> </html>
{ "content_hash": "a672e5b9eff2562f21733c7d8f65a94e", "timestamp": "", "source": "github", "line_count": 115, "max_line_length": 125, "avg_line_length": 36.504347826086956, "alnum_prop": 0.5898046688899476, "repo_name": "tectronics/creditsuite", "id": "9760cd362bc609aca502039b59579a4a6fcbc7cd", "size": "4198", "binary": false, "copies": "3", "ref": "refs/heads/master", "path": "2.3/docs/Javadoc/org/drip/service/env/class-use/CDSManager.html", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "34839" }, { "name": "HTML", "bytes": "74424756" }, { "name": "Java", "bytes": "29185529" } ], "symlink_target": "" }
package io.mandrel.requests.http; import java.io.Serializable; import com.fasterxml.jackson.annotation.JsonProperty; import lombok.Data; import lombok.experimental.Accessors; @Data @Accessors(chain = true, fluent = true) public class Cookie implements Serializable { private static final long serialVersionUID = -5911842148311031909L; @JsonProperty("name") private String name; @JsonProperty("value") private String value; @JsonProperty("domain") private String domain; @JsonProperty("path") private String path; @JsonProperty("expires") private long expires; @JsonProperty("max_age") private int maxAge; @JsonProperty("secure") private boolean secure; @JsonProperty("http_only") private boolean httpOnly; public Cookie(String name, String value, String domain, String path, long expires, int maxAge, boolean secure, boolean httpOnly) { super(); this.name = name; this.value = value; this.domain = domain; this.path = path; this.expires = expires; this.maxAge = maxAge; this.secure = secure; this.httpOnly = httpOnly; } }
{ "content_hash": "4b4cd7eebd6eab12d78aea0d1ac6a356", "timestamp": "", "source": "github", "line_count": 53, "max_line_length": 131, "avg_line_length": 20.28301886792453, "alnum_prop": 0.7423255813953489, "repo_name": "Treydone/mandrel", "id": "e97e4a4064ceefdfd412c660ea0bdd32dfa290fb", "size": "1851", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "mandrel-core/src/main/java/io/mandrel/requests/http/Cookie.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "20155" }, { "name": "FreeMarker", "bytes": "97664" }, { "name": "HTML", "bytes": "623016" }, { "name": "Java", "bytes": "950600" }, { "name": "JavaScript", "bytes": "251264" }, { "name": "Shell", "bytes": "3573" } ], "symlink_target": "" }
create table ACT_RU_TIMER_JOB ( ID_ NVARCHAR2(64) NOT NULL, REV_ INTEGER, TYPE_ NVARCHAR2(255) NOT NULL, LOCK_EXP_TIME_ TIMESTAMP(6), LOCK_OWNER_ NVARCHAR2(255), EXCLUSIVE_ NUMBER(1,0) CHECK (EXCLUSIVE_ IN (1,0)), EXECUTION_ID_ NVARCHAR2(64), PROCESS_INSTANCE_ID_ NVARCHAR2(64), PROC_DEF_ID_ NVARCHAR2(64), RETRIES_ INTEGER, EXCEPTION_STACK_ID_ NVARCHAR2(64), EXCEPTION_MSG_ NVARCHAR2(2000), DUEDATE_ TIMESTAMP(6), REPEAT_ NVARCHAR2(255), HANDLER_TYPE_ NVARCHAR2(255), HANDLER_CFG_ NVARCHAR2(2000), TENANT_ID_ NVARCHAR2(255) DEFAULT '', primary key (ID_) ); create table ACT_RU_SUSPENDED_JOB ( ID_ NVARCHAR2(64) NOT NULL, REV_ INTEGER, TYPE_ NVARCHAR2(255) NOT NULL, EXCLUSIVE_ NUMBER(1,0) CHECK (EXCLUSIVE_ IN (1,0)), EXECUTION_ID_ NVARCHAR2(64), PROCESS_INSTANCE_ID_ NVARCHAR2(64), PROC_DEF_ID_ NVARCHAR2(64), RETRIES_ INTEGER, EXCEPTION_STACK_ID_ NVARCHAR2(64), EXCEPTION_MSG_ NVARCHAR2(2000), DUEDATE_ TIMESTAMP(6), REPEAT_ NVARCHAR2(255), HANDLER_TYPE_ NVARCHAR2(255), HANDLER_CFG_ NVARCHAR2(2000), TENANT_ID_ NVARCHAR2(255) DEFAULT '', primary key (ID_) ); create table ACT_RU_DEADLETTER_JOB ( ID_ NVARCHAR2(64) NOT NULL, REV_ INTEGER, TYPE_ NVARCHAR2(255) NOT NULL, EXCLUSIVE_ NUMBER(1,0) CHECK (EXCLUSIVE_ IN (1,0)), EXECUTION_ID_ NVARCHAR2(64), PROCESS_INSTANCE_ID_ NVARCHAR2(64), PROC_DEF_ID_ NVARCHAR2(64), EXCEPTION_STACK_ID_ NVARCHAR2(64), EXCEPTION_MSG_ NVARCHAR2(2000), DUEDATE_ TIMESTAMP(6), REPEAT_ NVARCHAR2(255), HANDLER_TYPE_ NVARCHAR2(255), HANDLER_CFG_ NVARCHAR2(2000), TENANT_ID_ NVARCHAR2(255) DEFAULT '', primary key (ID_) ); create index ACT_IDX_JOB_EXECUTION_ID on ACT_RU_JOB(EXECUTION_ID_); alter table ACT_RU_JOB add constraint ACT_FK_JOB_EXECUTION foreign key (EXECUTION_ID_) references ACT_RU_EXECUTION (ID_); create index ACT_IDX_JOB_PROC_INST_ID on ACT_RU_JOB(PROCESS_INSTANCE_ID_); alter table ACT_RU_JOB add constraint ACT_FK_JOB_PROCESS_INSTANCE foreign key (PROCESS_INSTANCE_ID_) references ACT_RU_EXECUTION (ID_); create index ACT_IDX_JOB_PROC_DEF_ID on ACT_RU_JOB(PROC_DEF_ID_); alter table ACT_RU_JOB add constraint ACT_FK_JOB_PROC_DEF foreign key (PROC_DEF_ID_) references ACT_RE_PROCDEF (ID_); create index ACT_IDX_TJOB_EXECUTION_ID on ACT_RU_TIMER_JOB(EXECUTION_ID_); alter table ACT_RU_TIMER_JOB add constraint ACT_FK_TJOB_EXECUTION foreign key (EXECUTION_ID_) references ACT_RU_EXECUTION (ID_); create index ACT_IDX_TJOB_PROC_INST_ID on ACT_RU_TIMER_JOB(PROCESS_INSTANCE_ID_); alter table ACT_RU_TIMER_JOB add constraint ACT_FK_TJOB_PROCESS_INSTANCE foreign key (PROCESS_INSTANCE_ID_) references ACT_RU_EXECUTION (ID_); create index ACT_IDX_TJOB_PROC_DEF_ID on ACT_RU_TIMER_JOB(PROC_DEF_ID_); alter table ACT_RU_TIMER_JOB add constraint ACT_FK_TJOB_PROC_DEF foreign key (PROC_DEF_ID_) references ACT_RE_PROCDEF (ID_); create index ACT_IDX_TJOB_EXCEPTION on ACT_RU_TIMER_JOB(EXCEPTION_STACK_ID_); alter table ACT_RU_TIMER_JOB add constraint ACT_FK_TJOB_EXCEPTION foreign key (EXCEPTION_STACK_ID_) references ACT_GE_BYTEARRAY (ID_); create index ACT_IDX_SJOB_EXECUTION_ID on ACT_RU_SUSPENDED_JOB(EXECUTION_ID_); alter table ACT_RU_SUSPENDED_JOB add constraint ACT_FK_SJOB_EXECUTION foreign key (EXECUTION_ID_) references ACT_RU_EXECUTION (ID_); create index ACT_IDX_SJOB_PROC_INST_ID on ACT_RU_SUSPENDED_JOB(PROCESS_INSTANCE_ID_); alter table ACT_RU_SUSPENDED_JOB add constraint ACT_FK_SJOB_PROCESS_INSTANCE foreign key (PROCESS_INSTANCE_ID_) references ACT_RU_EXECUTION (ID_); create index ACT_IDX_SJOB_PROC_DEF_ID on ACT_RU_SUSPENDED_JOB(PROC_DEF_ID_); alter table ACT_RU_SUSPENDED_JOB add constraint ACT_FK_SJOB_PROC_DEF foreign key (PROC_DEF_ID_) references ACT_RE_PROCDEF (ID_); create index ACT_IDX_SJOB_EXCEPTION on ACT_RU_SUSPENDED_JOB(EXCEPTION_STACK_ID_); alter table ACT_RU_SUSPENDED_JOB add constraint ACT_FK_SJOB_EXCEPTION foreign key (EXCEPTION_STACK_ID_) references ACT_GE_BYTEARRAY (ID_); create index ACT_IDX_DJOB_EXECUTION_ID on ACT_RU_DEADLETTER_JOB(EXECUTION_ID_); alter table ACT_RU_DEADLETTER_JOB add constraint ACT_FK_DJOB_EXECUTION foreign key (EXECUTION_ID_) references ACT_RU_EXECUTION (ID_); create index ACT_IDX_DJOB_PROC_INST_ID on ACT_RU_DEADLETTER_JOB(PROCESS_INSTANCE_ID_); alter table ACT_RU_DEADLETTER_JOB add constraint ACT_FK_DJOB_PROCESS_INSTANCE foreign key (PROCESS_INSTANCE_ID_) references ACT_RU_EXECUTION (ID_); create index ACT_IDX_DJOB_PROC_DEF_ID on ACT_RU_DEADLETTER_JOB(PROC_DEF_ID_); alter table ACT_RU_DEADLETTER_JOB add constraint ACT_FK_DJOB_PROC_DEF foreign key (PROC_DEF_ID_) references ACT_RE_PROCDEF (ID_); create index ACT_IDX_DJOB_EXCEPTION on ACT_RU_DEADLETTER_JOB(EXCEPTION_STACK_ID_); alter table ACT_RU_DEADLETTER_JOB add constraint ACT_FK_DJOB_EXCEPTION foreign key (EXCEPTION_STACK_ID_) references ACT_GE_BYTEARRAY (ID_); -- Moving jobs with retries <= 0 to ACT_RU_DEADLETTER_JOB INSERT INTO ACT_RU_DEADLETTER_JOB (ID_, REV_, TYPE_, EXCLUSIVE_, EXECUTION_ID_, PROCESS_INSTANCE_ID_, PROC_DEF_ID_, EXCEPTION_STACK_ID_, EXCEPTION_MSG_, DUEDATE_, REPEAT_, HANDLER_TYPE_, HANDLER_CFG_, TENANT_ID_) (SELECT ID_, REV_, TYPE_, EXCLUSIVE_, EXECUTION_ID_, PROCESS_INSTANCE_ID_, PROC_DEF_ID_, EXCEPTION_STACK_ID_, EXCEPTION_MSG_, DUEDATE_, REPEAT_, HANDLER_TYPE_, HANDLER_CFG_, TENANT_ID_ from ACT_RU_JOB WHERE RETRIES_ <= 0); DELETE FROM ACT_RU_JOB WHERE RETRIES_ <= 0; -- Moving suspended jobs to ACT_RU_SUSPENDED_JOB INSERT INTO ACT_RU_SUSPENDED_JOB (ID_, REV_, TYPE_, EXCLUSIVE_, EXECUTION_ID_, PROCESS_INSTANCE_ID_, PROC_DEF_ID_, RETRIES_, EXCEPTION_STACK_ID_, EXCEPTION_MSG_, DUEDATE_, REPEAT_, HANDLER_TYPE_, HANDLER_CFG_, TENANT_ID_) (SELECT job.ID_, job.REV_, job.TYPE_, job.EXCLUSIVE_, job.EXECUTION_ID_, job.PROCESS_INSTANCE_ID_, job.PROC_DEF_ID_, job.RETRIES_, job.EXCEPTION_STACK_ID_, job.EXCEPTION_MSG_, job.DUEDATE_, job.REPEAT_, job.HANDLER_TYPE_, job.HANDLER_CFG_, job.TENANT_ID_ from ACT_RU_JOB job INNER JOIN ACT_RU_EXECUTION execution on execution.ID_ = job.PROCESS_INSTANCE_ID_ where execution.SUSPENSION_STATE_ = 2); DELETE FROM ACT_RU_JOB WHERE PROCESS_INSTANCE_ID_ IN (SELECT ID_ FROM ACT_RU_EXECUTION execution WHERE execution.PARENT_ID_ is null and execution.SUSPENSION_STATE_ = 2); -- Moving timer jobs to ACT_RU_TIMER_JOB INSERT INTO ACT_RU_TIMER_JOB (ID_, REV_, TYPE_, LOCK_EXP_TIME_, LOCK_OWNER_, EXCLUSIVE_, EXECUTION_ID_, PROCESS_INSTANCE_ID_, PROC_DEF_ID_, RETRIES_, EXCEPTION_STACK_ID_, EXCEPTION_MSG_, DUEDATE_, REPEAT_, HANDLER_TYPE_, HANDLER_CFG_, TENANT_ID_) (SELECT ID_, REV_, TYPE_, LOCK_EXP_TIME_, LOCK_OWNER_, EXCLUSIVE_, EXECUTION_ID_, PROCESS_INSTANCE_ID_, PROC_DEF_ID_, RETRIES_, EXCEPTION_STACK_ID_, EXCEPTION_MSG_, DUEDATE_, REPEAT_, HANDLER_TYPE_, HANDLER_CFG_, TENANT_ID_ from ACT_RU_JOB WHERE (HANDLER_TYPE_ = 'activate-processdefinition' or HANDLER_TYPE_ = 'suspend-processdefinition' or HANDLER_TYPE_ = 'timer-intermediate-transition' or HANDLER_TYPE_ = 'timer-start-event' or HANDLER_TYPE_ = 'timer-transition') and LOCK_EXP_TIME_ is null); DELETE FROM ACT_RU_JOB WHERE (HANDLER_TYPE_ = 'activate-processdefinition' or HANDLER_TYPE_ = 'suspend-processdefinition' or HANDLER_TYPE_ = 'timer-intermediate-transition' or HANDLER_TYPE_ = 'timer-start-event' or HANDLER_TYPE_ = 'timer-transition') and LOCK_EXP_TIME_ is null; alter table ACT_RU_EXECUTION add START_TIME_ TIMESTAMP(6); alter table ACT_RU_EXECUTION add START_USER_ID_ NVARCHAR2(255); alter table ACT_RU_TASK add CLAIM_TIME_ TIMESTAMP(6); alter table ACT_RE_DEPLOYMENT add KEY_ NVARCHAR2(255); -- Upgrade added in upgradestep.52001.to.52002.engine, which is not applied when already on beta2 update ACT_RU_EVENT_SUBSCR set PROC_DEF_ID_ = CONFIGURATION_ where EVENT_TYPE_ = 'message' and PROC_INST_ID_ is null and EXECUTION_ID_ is null and PROC_DEF_ID_ is null; -- Adding count columns for execution relationship count feature alter table ACT_RU_EXECUTION add IS_COUNT_ENABLED_ NUMBER(1,0) CHECK (IS_COUNT_ENABLED_ IN (1,0)); alter table ACT_RU_EXECUTION add EVT_SUBSCR_COUNT_ INTEGER; alter table ACT_RU_EXECUTION add TASK_COUNT_ INTEGER; alter table ACT_RU_EXECUTION add JOB_COUNT_ INTEGER; alter table ACT_RU_EXECUTION add TIMER_JOB_COUNT_ INTEGER; alter table ACT_RU_EXECUTION add SUSP_JOB_COUNT_ INTEGER; alter table ACT_RU_EXECUTION add DEADLETTER_JOB_COUNT_ INTEGER; alter table ACT_RU_EXECUTION add VAR_COUNT_ INTEGER; alter table ACT_RU_EXECUTION add ID_LINK_COUNT_ INTEGER; update ACT_GE_PROPERTY set VALUE_ = '6.0.0.2' where NAME_ = 'schema.version';
{ "content_hash": "7c2f6d771017434a69e3b4d61c3242e2", "timestamp": "", "source": "github", "line_count": 213, "max_line_length": 168, "avg_line_length": 41.93427230046948, "alnum_prop": 0.7083519928347515, "repo_name": "yvoswillens/flowable-engine", "id": "84d674a574af8d0f9c9d9fcc4fc2da152ee82ddb", "size": "8932", "binary": false, "copies": "12", "ref": "refs/heads/master", "path": "distro/sql/upgrade/bpmn/flowable.oracle.upgradestep.6001.to.6002.engine.sql", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Batchfile", "bytes": "166" }, { "name": "CSS", "bytes": "689397" }, { "name": "Dockerfile", "bytes": "6459" }, { "name": "Groovy", "bytes": "482" }, { "name": "HTML", "bytes": "1128913" }, { "name": "Java", "bytes": "35207622" }, { "name": "JavaScript", "bytes": "12438694" }, { "name": "PLSQL", "bytes": "109354" }, { "name": "PLpgSQL", "bytes": "11691" }, { "name": "SQLPL", "bytes": "1265" }, { "name": "Shell", "bytes": "19286" } ], "symlink_target": "" }
import * as React from "react"; import { CarbonIconProps } from "../../"; declare const Person16: React.ForwardRefExoticComponent< CarbonIconProps & React.RefAttributes<SVGSVGElement> >; export default Person16;
{ "content_hash": "ee2a1738ceacf5cc04d89c365c790e35", "timestamp": "", "source": "github", "line_count": 6, "max_line_length": 56, "avg_line_length": 35.666666666666664, "alnum_prop": 0.7663551401869159, "repo_name": "mcliment/DefinitelyTyped", "id": "e13a2b958217e34582fd462486be3e497dd36c42", "size": "214", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "types/carbon__icons-react/es/person/16.d.ts", "mode": "33188", "license": "mit", "language": [ { "name": "CoffeeScript", "bytes": "15" }, { "name": "Protocol Buffer", "bytes": "678" }, { "name": "TypeScript", "bytes": "17214021" } ], "symlink_target": "" }
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <!-- NewPage --> <html lang="en"> <head> <!-- Generated by javadoc (1.8.0_111) on Wed Jan 04 22:31:35 EST 2017 --> <title>Uses of Package org.drip.measure.continuousjoint</title> <meta name="date" content="2017-01-04"> <link rel="stylesheet" type="text/css" href="../../../../stylesheet.css" title="Style"> <script type="text/javascript" src="../../../../script.js"></script> </head> <body> <script type="text/javascript"><!-- try { if (location.href.indexOf('is-external=true') == -1) { parent.document.title="Uses of Package org.drip.measure.continuousjoint"; } } catch(err) { } //--> </script> <noscript> <div>JavaScript is disabled on your browser.</div> </noscript> <!-- ========= START OF TOP NAVBAR ======= --> <div class="topNav"><a name="navbar.top"> <!-- --> </a> <div class="skipNav"><a href="#skip.navbar.top" title="Skip navigation links">Skip navigation links</a></div> <a name="navbar.top.firstrow"> <!-- --> </a> <ul class="navList" title="Navigation"> <li><a href="../../../../overview-summary.html">Overview</a></li> <li><a href="package-summary.html">Package</a></li> <li>Class</li> <li class="navBarCell1Rev">Use</li> <li><a href="package-tree.html">Tree</a></li> <li><a href="../../../../deprecated-list.html">Deprecated</a></li> <li><a href="../../../../index-files/index-1.html">Index</a></li> <li><a href="../../../../help-doc.html">Help</a></li> </ul> </div> <div class="subNav"> <ul class="navList"> <li>Prev</li> <li>Next</li> </ul> <ul class="navList"> <li><a href="../../../../index.html?org/drip/measure/continuousjoint/package-use.html" target="_top">Frames</a></li> <li><a href="package-use.html" target="_top">No&nbsp;Frames</a></li> </ul> <ul class="navList" id="allclasses_navbar_top"> <li><a href="../../../../allclasses-noframe.html">All&nbsp;Classes</a></li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_top"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } //--> </script> </div> <a name="skip.navbar.top"> <!-- --> </a></div> <!-- ========= END OF TOP NAVBAR ========= --> <div class="header"> <h1 title="Uses of Package org.drip.measure.continuousjoint" class="title">Uses of Package<br>org.drip.measure.continuousjoint</h1> </div> <div class="contentContainer"> <ul class="blockList"> <li class="blockList"> <table class="useSummary" border="0" cellpadding="3" cellspacing="0" summary="Use table, listing packages, and an explanation"> <caption><span>Packages that use <a href="../../../../org/drip/measure/continuousjoint/package-summary.html">org.drip.measure.continuousjoint</a></span><span class="tabEnd">&nbsp;</span></caption> <tr> <th class="colFirst" scope="col">Package</th> <th class="colLast" scope="col">Description</th> </tr> <tbody> <tr class="altColor"> <td class="colFirst"><a href="#org.drip.learning.regularization">org.drip.learning.regularization</a></td> <td class="colLast">&nbsp;</td> </tr> <tr class="rowColor"> <td class="colFirst"><a href="#org.drip.learning.rxtor1">org.drip.learning.rxtor1</a></td> <td class="colLast">&nbsp;</td> </tr> <tr class="altColor"> <td class="colFirst"><a href="#org.drip.measure.bayesian">org.drip.measure.bayesian</a></td> <td class="colLast">&nbsp;</td> </tr> <tr class="rowColor"> <td class="colFirst"><a href="#org.drip.measure.continuousjoint">org.drip.measure.continuousjoint</a></td> <td class="colLast">&nbsp;</td> </tr> <tr class="altColor"> <td class="colFirst"><a href="#org.drip.measure.gaussian">org.drip.measure.gaussian</a></td> <td class="colLast">&nbsp;</td> </tr> <tr class="rowColor"> <td class="colFirst"><a href="#org.drip.portfolioconstruction.asset">org.drip.portfolioconstruction.asset</a></td> <td class="colLast">&nbsp;</td> </tr> </tbody> </table> </li> <li class="blockList"><a name="org.drip.learning.regularization"> <!-- --> </a> <table class="useSummary" border="0" cellpadding="3" cellspacing="0" summary="Use table, listing classes, and an explanation"> <caption><span>Classes in <a href="../../../../org/drip/measure/continuousjoint/package-summary.html">org.drip.measure.continuousjoint</a> used by <a href="../../../../org/drip/learning/regularization/package-summary.html">org.drip.learning.regularization</a></span><span class="tabEnd">&nbsp;</span></caption> <tr> <th class="colOne" scope="col">Class and Description</th> </tr> <tbody> <tr class="altColor"> <td class="colOne"><a href="../../../../org/drip/measure/continuousjoint/class-use/R1R1.html#org.drip.learning.regularization">R1R1</a> <div class="block">R1R1 implements the Base Abstract Class behind Bivariate R^1 Distributions.</div> </td> </tr> <tr class="rowColor"> <td class="colOne"><a href="../../../../org/drip/measure/continuousjoint/class-use/RdR1.html#org.drip.learning.regularization">RdR1</a> <div class="block">Rd implements the Base Abstract Class behind R^d X R^1 Distributions.</div> </td> </tr> </tbody> </table> </li> <li class="blockList"><a name="org.drip.learning.rxtor1"> <!-- --> </a> <table class="useSummary" border="0" cellpadding="3" cellspacing="0" summary="Use table, listing classes, and an explanation"> <caption><span>Classes in <a href="../../../../org/drip/measure/continuousjoint/package-summary.html">org.drip.measure.continuousjoint</a> used by <a href="../../../../org/drip/learning/rxtor1/package-summary.html">org.drip.learning.rxtor1</a></span><span class="tabEnd">&nbsp;</span></caption> <tr> <th class="colOne" scope="col">Class and Description</th> </tr> <tbody> <tr class="altColor"> <td class="colOne"><a href="../../../../org/drip/measure/continuousjoint/class-use/R1R1.html#org.drip.learning.rxtor1">R1R1</a> <div class="block">R1R1 implements the Base Abstract Class behind Bivariate R^1 Distributions.</div> </td> </tr> <tr class="rowColor"> <td class="colOne"><a href="../../../../org/drip/measure/continuousjoint/class-use/RdR1.html#org.drip.learning.rxtor1">RdR1</a> <div class="block">Rd implements the Base Abstract Class behind R^d X R^1 Distributions.</div> </td> </tr> </tbody> </table> </li> <li class="blockList"><a name="org.drip.measure.bayesian"> <!-- --> </a> <table class="useSummary" border="0" cellpadding="3" cellspacing="0" summary="Use table, listing classes, and an explanation"> <caption><span>Classes in <a href="../../../../org/drip/measure/continuousjoint/package-summary.html">org.drip.measure.continuousjoint</a> used by <a href="../../../../org/drip/measure/bayesian/package-summary.html">org.drip.measure.bayesian</a></span><span class="tabEnd">&nbsp;</span></caption> <tr> <th class="colOne" scope="col">Class and Description</th> </tr> <tbody> <tr class="altColor"> <td class="colOne"><a href="../../../../org/drip/measure/continuousjoint/class-use/MultivariateMeta.html#org.drip.measure.bayesian">MultivariateMeta</a> <div class="block">MultivariateMeta holds a Group of Variable Names - each of which separately is a Valid Single R^1/R^d Variable.</div> </td> </tr> <tr class="rowColor"> <td class="colOne"><a href="../../../../org/drip/measure/continuousjoint/class-use/R1Multivariate.html#org.drip.measure.bayesian">R1Multivariate</a> <div class="block">R1Multivariate contains the Generalized Joint Multivariate R^1 Distributions.</div> </td> </tr> </tbody> </table> </li> <li class="blockList"><a name="org.drip.measure.continuousjoint"> <!-- --> </a> <table class="useSummary" border="0" cellpadding="3" cellspacing="0" summary="Use table, listing classes, and an explanation"> <caption><span>Classes in <a href="../../../../org/drip/measure/continuousjoint/package-summary.html">org.drip.measure.continuousjoint</a> used by <a href="../../../../org/drip/measure/continuousjoint/package-summary.html">org.drip.measure.continuousjoint</a></span><span class="tabEnd">&nbsp;</span></caption> <tr> <th class="colOne" scope="col">Class and Description</th> </tr> <tbody> <tr class="altColor"> <td class="colOne"><a href="../../../../org/drip/measure/continuousjoint/class-use/MultivariateMeta.html#org.drip.measure.continuousjoint">MultivariateMeta</a> <div class="block">MultivariateMeta holds a Group of Variable Names - each of which separately is a Valid Single R^1/R^d Variable.</div> </td> </tr> </tbody> </table> </li> <li class="blockList"><a name="org.drip.measure.gaussian"> <!-- --> </a> <table class="useSummary" border="0" cellpadding="3" cellspacing="0" summary="Use table, listing classes, and an explanation"> <caption><span>Classes in <a href="../../../../org/drip/measure/continuousjoint/package-summary.html">org.drip.measure.continuousjoint</a> used by <a href="../../../../org/drip/measure/gaussian/package-summary.html">org.drip.measure.gaussian</a></span><span class="tabEnd">&nbsp;</span></caption> <tr> <th class="colOne" scope="col">Class and Description</th> </tr> <tbody> <tr class="altColor"> <td class="colOne"><a href="../../../../org/drip/measure/continuousjoint/class-use/MultivariateMeta.html#org.drip.measure.gaussian">MultivariateMeta</a> <div class="block">MultivariateMeta holds a Group of Variable Names - each of which separately is a Valid Single R^1/R^d Variable.</div> </td> </tr> <tr class="rowColor"> <td class="colOne"><a href="../../../../org/drip/measure/continuousjoint/class-use/R1Multivariate.html#org.drip.measure.gaussian">R1Multivariate</a> <div class="block">R1Multivariate contains the Generalized Joint Multivariate R^1 Distributions.</div> </td> </tr> </tbody> </table> </li> <li class="blockList"><a name="org.drip.portfolioconstruction.asset"> <!-- --> </a> <table class="useSummary" border="0" cellpadding="3" cellspacing="0" summary="Use table, listing classes, and an explanation"> <caption><span>Classes in <a href="../../../../org/drip/measure/continuousjoint/package-summary.html">org.drip.measure.continuousjoint</a> used by <a href="../../../../org/drip/portfolioconstruction/asset/package-summary.html">org.drip.portfolioconstruction.asset</a></span><span class="tabEnd">&nbsp;</span></caption> <tr> <th class="colOne" scope="col">Class and Description</th> </tr> <tbody> <tr class="altColor"> <td class="colOne"><a href="../../../../org/drip/measure/continuousjoint/class-use/MultivariateMeta.html#org.drip.portfolioconstruction.asset">MultivariateMeta</a> <div class="block">MultivariateMeta holds a Group of Variable Names - each of which separately is a Valid Single R^1/R^d Variable.</div> </td> </tr> </tbody> </table> </li> </ul> </div> <!-- ======= START OF BOTTOM NAVBAR ====== --> <div class="bottomNav"><a name="navbar.bottom"> <!-- --> </a> <div class="skipNav"><a href="#skip.navbar.bottom" title="Skip navigation links">Skip navigation links</a></div> <a name="navbar.bottom.firstrow"> <!-- --> </a> <ul class="navList" title="Navigation"> <li><a href="../../../../overview-summary.html">Overview</a></li> <li><a href="package-summary.html">Package</a></li> <li>Class</li> <li class="navBarCell1Rev">Use</li> <li><a href="package-tree.html">Tree</a></li> <li><a href="../../../../deprecated-list.html">Deprecated</a></li> <li><a href="../../../../index-files/index-1.html">Index</a></li> <li><a href="../../../../help-doc.html">Help</a></li> </ul> </div> <div class="subNav"> <ul class="navList"> <li>Prev</li> <li>Next</li> </ul> <ul class="navList"> <li><a href="../../../../index.html?org/drip/measure/continuousjoint/package-use.html" target="_top">Frames</a></li> <li><a href="package-use.html" target="_top">No&nbsp;Frames</a></li> </ul> <ul class="navList" id="allclasses_navbar_bottom"> <li><a href="../../../../allclasses-noframe.html">All&nbsp;Classes</a></li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_bottom"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } //--> </script> </div> <a name="skip.navbar.bottom"> <!-- --> </a></div> <!-- ======== END OF BOTTOM NAVBAR ======= --> </body> </html>
{ "content_hash": "e6385e1c0f2836efef091642050efcbc", "timestamp": "", "source": "github", "line_count": 288, "max_line_length": 318, "avg_line_length": 42.15277777777778, "alnum_prop": 0.6754530477759473, "repo_name": "lakshmiDRIP/DRIP", "id": "f928247564a3e9ab73cf63d3bced040c969e8a69", "size": "12140", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "Javadoc/org/drip/measure/continuousjoint/package-use.html", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "19869" }, { "name": "HTML", "bytes": "5974" }, { "name": "Java", "bytes": "20814325" }, { "name": "JavaScript", "bytes": "16520" } ], "symlink_target": "" }
import React, {Component, PropTypes} from 'react'; import Drawer from 'material-ui/Drawer'; import {List, ListItem, MakeSelectable} from 'material-ui/List'; import Divider from 'material-ui/Divider'; import Subheader from 'material-ui/Subheader'; import DropDownMenu from 'material-ui/DropDownMenu'; import MenuItem from 'material-ui/MenuItem'; import {spacing, typography, zIndex} from 'material-ui/styles'; import {cyan500} from 'material-ui/styles/colors'; const SelectableList = MakeSelectable(List); const styles = { logo: { cursor: 'pointer', fontSize: 24, color: typography.textFullWhite, lineHeight: `${spacing.desktopKeylineIncrement}px`, fontWeight: typography.fontWeightLight, backgroundColor: cyan500, paddingLeft: spacing.desktopGutter, marginBottom: 8, }, version: { paddingLeft: spacing.desktopGutterLess, fontSize: 16, }, }; class AppNavDrawer extends Component { static propTypes = { docked: PropTypes.bool.isRequired, location: PropTypes.object.isRequired, onChangeList: PropTypes.func.isRequired, onRequestChangeNavDrawer: PropTypes.func.isRequired, open: PropTypes.bool.isRequired, style: PropTypes.object, }; static contextTypes = { muiTheme: PropTypes.object.isRequired, router: PropTypes.object.isRequired, }; state = { muiVersions: [], }; componentDidMount() { const self = this; const url = '/versions.json'; const request = new XMLHttpRequest(); request.onreadystatechange = function() { if (request.readyState === 4 && request.status === 200) { self.setState({ muiVersions: JSON.parse(request.responseText), version: JSON.parse(request.responseText)[0], }); } }; request.open('GET', url, true); request.send(); } firstNonPreReleaseVersion() { let version; for (let i = 0; i < this.state.muiVersions.length; i++) { version = this.state.muiVersions[i]; // If the version doesn't contain '-' and isn't 'HEAD' if (!/-/.test(version) && version !== 'HEAD') { break; } } return version; } handleVersionChange = (event, index, value) => { if (value === this.firstNonPreReleaseVersion()) { window.location = 'http://www.material-ui.com/'; } else { window.location = `http://www.material-ui.com/${value}`; } }; currentVersion() { if (window.location.hostname === 'localhost') return this.state.muiVersions[0]; if (window.location.pathname === '/') { return this.firstNonPreReleaseVersion(); } else { return window.location.pathname.replace(/\//g, ''); } } handleRequestChangeLink = (event, value) => { window.location = value; }; handleTouchTapHeader = () => { this.context.router.push('/'); this.props.onRequestChangeNavDrawer(false); }; render() { const { location, docked, onRequestChangeNavDrawer, onChangeList, open, style, } = this.props; return ( <Drawer style={style} docked={docked} open={open} onRequestChange={onRequestChangeNavDrawer} containerStyle={{zIndex: zIndex.drawer - 100}} > <div style={styles.logo} onTouchTap={this.handleTouchTapHeader}> Material-UI </div> <span style={styles.version}>Version:</span> <DropDownMenu value={this.currentVersion()} onChange={this.handleVersionChange} maxHeight={300} style={{width: 181}} > {this.state.muiVersions.map((version) => ( <MenuItem key={version} value={version} primaryText={version} /> ))} </DropDownMenu> <SelectableList value={location.pathname} onChange={onChangeList} > <ListItem primaryText="Get Started" primaryTogglesNestedList={true} nestedItems={[ <ListItem primaryText="Prerequisites" value="/get-started/prerequisites" />, <ListItem primaryText="Installation" value="/get-started/installation" />, <ListItem primaryText="Usage" value="/get-started/usage" />, <ListItem primaryText="Server Rendering" value="/get-started/server-rendering" />, <ListItem primaryText="Examples" value="/get-started/examples" />, ]} /> <ListItem primaryText="Customization" primaryTogglesNestedList={true} nestedItems={[ <ListItem primaryText="Themes" value="/customization/themes" />, <ListItem primaryText="Inline Styles" value="/customization/inline-styles" />, <ListItem primaryText="Colors" value="/customization/colors" />, ]} /> <ListItem primaryText="Components" primaryTogglesNestedList={true} nestedItems={[ <ListItem primaryText="App Bar" value="/components/app-bar" href="#/components/app-bar" />, <ListItem primaryText="Auto Complete" value="/components/auto-complete" href="#/components/auto-complete" />, <ListItem primaryText="Avatar" value="/components/avatar" href="#/components/avatar" />, <ListItem primaryText="Badge" value="/components/badge" href="#/components/badge" />, <ListItem primaryText="Buttons" primaryTogglesNestedList={true} nestedItems={[ <ListItem primaryText="Flat Button" value="/components/flat-button" href="#/components/flat-button" />, <ListItem primaryText="Raised Button" value="/components/raised-button" href="#/components/raised-button" />, <ListItem primaryText="Floating Action Button" value="/components/floating-action-button" href="#/components/floating-action-button" />, <ListItem primaryText="Icon Button" value="/components/icon-button" href="#/components/icon-button" />, ]} />, <ListItem primaryText="Card" value="/components/card" href="#/components/card" />, <ListItem primaryText="Chip" value="/components/chip" href="#/components/chip" />, <ListItem primaryText="Date Picker" value="/components/date-picker" href="#/components/date-picker" />, <ListItem primaryText="Dialog" value="/components/dialog" href="#/components/dialog" />, <ListItem primaryText="Divider" value="/components/divider" href="#/components/divider" />, <ListItem primaryText="Drawer" value="/components/drawer" href="#/components/drawer" />, <ListItem primaryText="Grid List" value="/components/grid-list" href="#/components/grid-list" />, <ListItem primaryText="Icons" primaryTogglesNestedList={true} nestedItems={[ <ListItem primaryText="Font Icon" value="/components/font-icon" href="#/components/font-icon" />, <ListItem primaryText="SVG Icon" value="/components/svg-icon" href="#/components/svg-icon" />, ]} />, <ListItem primaryText="List" value="/components/list" href="#/components/list" />, <ListItem primaryText="Menus" primaryTogglesNestedList={true} nestedItems={[ <ListItem primaryText="Menu" value="/components/menu" href="#/components/menu" />, <ListItem primaryText="Icon Menu" value="/components/icon-menu" href="#/components/icon-menu" />, <ListItem primaryText="DropDown Menu" value="/components/dropdown-menu" href="#/components/dropdown-menu" />, ]} />, <ListItem primaryText="Paper" value="/components/paper" href="#/components/paper" />, <ListItem primaryText="Popover" value="/components/popover" href="#/components/popover" />, <ListItem primaryText="Progress" primaryTogglesNestedList={true} nestedItems={[ <ListItem primaryText="Circular Progress" value="/components/circular-progress" href="#/components/circular-progress" />, <ListItem primaryText="Linear Progress" value="/components/linear-progress" href="#/components/linear-progress" />, <ListItem primaryText="Refresh Indicator" value="/components/refresh-indicator" href="#/components/refresh-indicator" />, ]} />, <ListItem primaryText="Select Field" value="/components/select-field" href="#/components/select-field" />, <ListItem primaryText="Slider" value="/components/slider" href="#/components/slider" />, <ListItem primaryText="Switches" primaryTogglesNestedList={true} nestedItems={[ <ListItem primaryText="Checkbox" value="/components/checkbox" href="#/components/checkbox" />, <ListItem primaryText="Radio Button" value="/components/radio-button" href="#/components/radio-button" />, <ListItem primaryText="Toggle" value="/components/toggle" href="#/components/toggle" />, ]} />, <ListItem primaryText="Snackbar" value="/components/snackbar" href="#/components/snackbar" />, <ListItem primaryText="Stepper" value="/components/stepper" href="#/components/stepper" />, <ListItem primaryText="Subheader" value="/components/subheader" href="#/components/subheader" />, <ListItem primaryText="Table" value="/components/table" href="#/components/table" />, <ListItem primaryText="Tabs" value="/components/tabs" href="#/components/tabs" />, <ListItem primaryText="Text Field" value="/components/text-field" href="#/components/text-field" />, <ListItem primaryText="Time Picker" value="/components/time-picker" href="#/components/time-picker" />, <ListItem primaryText="Toolbar" value="/components/toolbar" href="#/components/toolbar" />, ]} /> <ListItem primaryText="Discover More" primaryTogglesNestedList={true} nestedItems={[ <ListItem primaryText="Community" value="/discover-more/community" />, <ListItem primaryText="Contributing" value="/discover-more/contributing" />, <ListItem primaryText="Showcase" value="/discover-more/showcase" />, <ListItem primaryText="Related projects" value="/discover-more/related-projects" />, ]} /> </SelectableList> <Divider /> <SelectableList value="" onChange={this.handleRequestChangeLink} > <Subheader>Resources</Subheader> <ListItem primaryText="GitHub" value="https://github.com/callemall/material-ui" /> <ListItem primaryText="React" value="http://facebook.github.io/react" /> <ListItem primaryText="Material Design" value="https://www.google.com/design/spec/material-design/introduction.html" /> </SelectableList> </Drawer> ); } } export default AppNavDrawer;
{ "content_hash": "91030dd44105c4f367ccbc934582e970", "timestamp": "", "source": "github", "line_count": 425, "max_line_length": 98, "avg_line_length": 33.31294117647059, "alnum_prop": 0.48742760276875263, "repo_name": "andrejunges/material-ui", "id": "967b11bf37c4d8e30b6d6434ed554171be37402a", "size": "14158", "binary": false, "copies": "3", "ref": "refs/heads/master", "path": "docs/src/app/components/AppNavDrawer.js", "mode": "33188", "license": "mit", "language": [ { "name": "JavaScript", "bytes": "1382602" }, { "name": "Shell", "bytes": "277" } ], "symlink_target": "" }
''' pb_statsfofn_ucd.py generate read stats from pacbio fofn file fofn format input, one line per fasta file /share/dnat/rs2/161028_448/D02_1/Analysis_Results/m161031_221844_42145_c101058752550000001823247401061784_s1_p0.2.subreads.fasta /share/dnat/rs2/161028_448/D02_1/Analysis_Results/m161031_221844_42145_c101058752550000001823247401061784_s1_p0.3.subreads.fasta stats output file is in json format ''' import sys import os import glob import time import re import json from collections import OrderedDict from optparse import OptionParser # http://docs.python.org/library/optparse.html version = "1.0" usage = "usage: %prog [options] -o output_filename fofn_file" epilog = "The fofn_file can be provided as stdin. \ Specifying -o stdout can be used to put the ou tput to stdout." parser = OptionParser(usage=usage, version="%prog " + str(version), epilog=epilog) parser.add_option('-o', '--output', help="output filename, stdout is acceptable [default: %default]", action="store", type="str", dest="output", default="input.fofn.stats") parser.add_option('-d', '--id', help="ID for the stats output [default: %default]", action="store", type="str", dest="id", default=None) (options, args) = parser.parse_args() def remove_comment(str1): loc = str1.find("#") # identify if and where a # occurs if loc == -1: return str1 # if # not found return str1 as is str1 = str1[0:loc] # trim of comment return str1.rstrip() # remove any trailing whitespace and return result def parse_pacbio_readid_rs2(str1): # >m160924_114322_42145_c101087062550000001823245703091787_s1_p0/8/0_35815 RQ=0.849 rid, rq = str1.strip().split(' RQ=') # strip out read quality rid, zmw, rlen = rid.split("/") rlen = rlen.split("_") rstart = int(rlen[0]) rend = int(rlen[1]) rlen = rend-rstart return (rid[1:], int(zmw), rstart, rend, rlen, float(rq)) if len(args) > 1: sys.stderr.write("program requires at most 1 argument\n") sys.stderr.write(usage + '\n') sys.exit() elif len(args) == 1: infile = args[0] # Start opening input/output files: if not os.path.exists(infile): sys.stderr.write("Error, can't find input file %s\n" % infile) sys.exit() infofn = open(infile, 'r') else: # reading from stdin infofn = sys.stdin output = options.output if output == "stdout": out = sys.stdout else: out = open(output, 'w') sid = options.id fasta_files = 0 all_data = [] for line in infofn: # each line in the fofn file is one fasta file line = remove_comment(line) line = line.strip() if len(line) == 0: continue if not os.path.exists(line): sys.stderr.write("Error, can't find fasta file %s\n" % line) sys.exit() # process a fasta file fasta = open(line, 'r') sys.stderr.write("Processing file: %s\n" % line) # parse out run and cell position and cell barcode from file name pf = line.split("/Analysis_Results/") if len(pf) == 2: # agrees with UCD DNA Tech Core file path expectations pr = pf[0].split('/') run = pr[-2] m = re.match("m\d+_\d+_\d+_(c\d+)_s1_p0.\d.subreads.fasta",pf[1]) if m: cell_position = pr[-1] cell_barcode = m.group(1) else: sys.stderr.write("Error, can't identify cell barcode in either filename, or first read\n") sys.exit() elif len(pf) == 1: run = None # try and extract cell_id from filename m = re.match(".+/m\d+_\d+_\d+_(c\d+)_s1_p0.\d.subreads.fasta",pf[0]) if m: cell_position = None cell_barcode = m.group(1) else: # get cell id from first read id l1 = fasta.readline() m = re.match(">m\d+_\d+_\d+_(c\d+)_s1_p0/\d+/\d+_\d+ RQ=\d.\d+",l1) if m: cell_position = None cell_barcode = m.group(1) else: sys.stderr.write("Error, can't identify cell barcode in either filename, or first read\n") sys.exit() fasta.seek(0) # seek back to beginning of file else: sys.stderr.write("Error, can't identify cell barcode in either filename, or first read\n") sys.exit() rcount = 0 # read count zmw = [] rstart = [] rend = [] rlen = [] rq =[] try: for read in fasta: if read[0] == '>': rstats = parse_pacbio_readid_rs2(read) zmw.append(rstats[1]) rstart.append(rstats[2]) rend.append(rstats[3]) rlen.append(rstats[4]) rq.append(rstats[5]) rcount += 1 else: continue finally: fasta.close() file_data = OrderedDict([("run_id", run), ("cell_position", cell_position), ("cell_barcode", cell_barcode), ("filename", line), ("read_count", rcount), ("zmw", zmw), ("read_starts", rstart), ("read_ends", rend), ("read_lengths", rlen), ("read_qualiies", rq)]) all_data.append(file_data) file_data = None fasta_files += 1 file_keys = ["run_id","cell_position","cell_barcode","filename","read_count","zmw","read_starts","read_ends","read_lengths","read_qualities"] stats_json = OrderedDict([ ("id", sid), ("format", "UCD Pac Bio Fasta stats %s" % version), ("format_url", "https://github.com/ucdavis-bioinformatics/PacBio_GenomeStats"), ("generated_by", "pb_statsfofn_ucd.py"), ("date", time.strftime("%Y-%m-%dT%H:%M:%S")), ("type", "ucd pb stats"), ("source", "fasta"), ("number_of_files", fasta_files), ("file_keys", file_keys), ("file_data", all_data)]) sys.stderr.write("Writing JSON output to: %s\n" % output ) json.dump(stats_json, out) infofn.close() out.close()
{ "content_hash": "1c0064fd3e30507751b645f6f047a8c3", "timestamp": "", "source": "github", "line_count": 187, "max_line_length": 141, "avg_line_length": 32.844919786096256, "alnum_prop": 0.5695213285574732, "repo_name": "ucdavis-bioinformatics-training/Bioinformatics-Genome-Assembly-and-Analysis-Workshop-Pac-Bio-and-10x-Genomics-", "id": "077b954527868716222c6b636b5ef682b61238a8", "size": "6165", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "PacBio-Experimental-Design/pb_statsfofn_ucd.py", "mode": "33261", "license": "apache-2.0", "language": [ { "name": "Python", "bytes": "6165" }, { "name": "R", "bytes": "4943" }, { "name": "Shell", "bytes": "2029" } ], "symlink_target": "" }
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>fermat4: 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 / released</a></li> <li class="active"><a href="">8.11.2 / fermat4 - 8.5.0</a></li> </ul> </div> </div> </div> <div class="article"> <div class="row"> <div class="col-md-12"> <a href="../..">« Up</a> <h1> fermat4 <small> 8.5.0 <span class="label label-info">Not compatible 👼</span> </small> </h1> <p>📅 <em><script>document.write(moment("2022-03-17 22:59:49 +0000", "YYYY-MM-DD HH:mm:ss Z").fromNow());</script> (2022-03-17 22:59:49 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 coq 8.11.2 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.9.3 A library manager for OCaml # opam file: opam-version: &quot;2.0&quot; maintainer: &quot;matej.kosik@inria.fr&quot; homepage: &quot;https://github.com/coq-contribs/fermat4&quot; license: &quot;Proprietary&quot; build: [make &quot;-j%{jobs}%&quot;] install: [make &quot;install&quot;] remove: [&quot;rm&quot; &quot;-R&quot; &quot;%{lib}%/coq/user-contrib/Fermat4&quot;] depends: [ &quot;ocaml&quot; &quot;coq&quot; {&gt;= &quot;8.5&quot; &amp; &lt; &quot;8.6~&quot;} ] tags: [ &quot;keyword:Diophantus&quot; &quot;keyword:Fermat&quot; &quot;keyword:arithmetic&quot; &quot;keyword:infinite descent&quot; &quot;category:Mathematics/Arithmetic and Number Theory/Number theory&quot; &quot;date:2005-07&quot; ] authors: [ &quot;David Delahaye &lt;&gt;&quot; &quot;Micaela Mayero &lt;&gt;&quot; ] bug-reports: &quot;https://github.com/coq-contribs/fermat4/issues&quot; dev-repo: &quot;git+https://github.com/coq-contribs/fermat4.git&quot; synopsis: &quot;Diophantus&#39; 20th Problem and Fermat&#39;s Last Theorem for n = 4&quot; description: &quot;&quot;&quot; This contribution presents the formalization of Fermat&#39;s proofs of Diophantus&#39; 20th Problem and Fermat&#39;s Last Theorem for n = 4. The proofs are completed using Fermat&#39;s &quot;wonderful&quot; method of infinite descent.&quot;&quot;&quot; flags: light-uninstall url { src: &quot;https://github.com/coq-contribs/fermat4/archive/v8.5.0.tar.gz&quot; checksum: &quot;md5=8df337811ec5022a8e99900af7798f75&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-fermat4.8.5.0 coq.8.11.2</code></dd> <dt>Return code</dt> <dd>5120</dd> <dt>Output</dt> <dd><pre>[NOTE] Package coq is already installed (current version is 8.11.2). The following dependencies couldn&#39;t be met: - coq-fermat4 -&gt; coq &lt; 8.6~ -&gt; ocaml &lt; 4.03.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-fermat4.8.5.0</code></dd> <dt>Return code</dt> <dd>0</dd> </dl> <h2>Install dependencies</h2> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>true</code></dd> <dt>Return code</dt> <dd>0</dd> <dt>Duration</dt> <dd>0 s</dd> </dl> <h2>Install 🚀</h2> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>true</code></dd> <dt>Return code</dt> <dd>0</dd> <dt>Duration</dt> <dd>0 s</dd> </dl> <h2>Installation size</h2> <p>No files were installed.</p> <h2>Uninstall 🧹</h2> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>true</code></dd> <dt>Return code</dt> <dd>0</dd> <dt>Missing removes</dt> <dd> none </dd> <dt>Wrong removes</dt> <dd> none </dd> </dl> </div> </div> </div> <hr/> <div class="footer"> <p class="text-center"> Sources are on <a href="https://github.com/coq-bench">GitHub</a> © Guillaume Claret 🐣 </p> </div> </div> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <script src="../../../../../bootstrap.min.js"></script> </body> </html>
{ "content_hash": "73007f150643bbf95b275d766dba9d3e", "timestamp": "", "source": "github", "line_count": 173, "max_line_length": 159, "avg_line_length": 41.31791907514451, "alnum_prop": 0.5488248461108002, "repo_name": "coq-bench/coq-bench.github.io", "id": "4476df7c45d6ef173952bd107cd9c0307d75dd94", "size": "7173", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "clean/Linux-x86_64-4.05.0-2.0.1/released/8.11.2/fermat4/8.5.0.html", "mode": "33188", "license": "mit", "language": [], "symlink_target": "" }
namespace GafferScene { /// The SceneNode class is the base class for all Nodes which are capable of generating /// or processing scene graphs. class GAFFERSCENE_API SceneNode : public Gaffer::ComputeNode { public : SceneNode( const std::string &name=defaultName<SceneNode>() ); ~SceneNode() override; IE_CORE_DECLARERUNTIMETYPEDEXTENSION( GafferScene::SceneNode, SceneNodeTypeId, Gaffer::ComputeNode ); /// All SceneNodes have at least one output ScenePlug for passing on their result. More /// may be added by derived classes if necessary. ScenePlug *outPlug(); const ScenePlug *outPlug() const; /// The enabled plug provides a mechanism for turning the effect of the node on and off. Gaffer::BoolPlug *enabledPlug() override; const Gaffer::BoolPlug *enabledPlug() const override; /// Implemented so that enabledPlug() affects outPlug(). void affects( const Gaffer::Plug *input, AffectedPlugsContainer &outputs ) const override; protected : typedef ScenePlug::ScenePath ScenePath; /// Implemented to call the hash*() methods below whenever output is part of a ScenePlug and the node is enabled. void hash( const Gaffer::ValuePlug *output, const Gaffer::Context *context, IECore::MurmurHash &h ) const override; /// Hash methods for the individual children of outPlug(). A derived class must either : /// /// * Implement the method to call the base class implementation and then append to the hash. /// /// or : /// /// * Implement the method to assign directly to the hash from some input hash to signify that /// an input will be passed through unchanged by the corresponding compute*() method. Note /// that if you wish to pass through an input unconditionally, regardless of context, it is /// faster to use a connection as described below. /// /// or : /// /// * Make an input connection into the corresponding plug, so that the hash and compute methods /// are never called for it. virtual void hashBound( const ScenePath &path, const Gaffer::Context *context, const ScenePlug *parent, IECore::MurmurHash &h ) const; virtual void hashTransform( const ScenePath &path, const Gaffer::Context *context, const ScenePlug *parent, IECore::MurmurHash &h ) const; virtual void hashAttributes( const ScenePath &path, const Gaffer::Context *context, const ScenePlug *parent, IECore::MurmurHash &h ) const; virtual void hashObject( const ScenePath &path, const Gaffer::Context *context, const ScenePlug *parent, IECore::MurmurHash &h ) const; virtual void hashChildNames( const ScenePath &path, const Gaffer::Context *context, const ScenePlug *parent, IECore::MurmurHash &h ) const; virtual void hashGlobals( const Gaffer::Context *context, const ScenePlug *parent, IECore::MurmurHash &h ) const; virtual void hashSetNames( const Gaffer::Context *context, const ScenePlug *parent, IECore::MurmurHash &h ) const; virtual void hashSet( const IECore::InternedString &setName, const Gaffer::Context *context, const ScenePlug *parent, IECore::MurmurHash &h ) const; /// Implemented to call the compute*() methods below whenever output is part of a ScenePlug and the node is enabled. void compute( Gaffer::ValuePlug *output, const Gaffer::Context *context ) const override; /// Compute methods for the individual children of outPlug() - these must be implemented by derived classes, or /// an input connection must be made to the plug, so that the method is not called. virtual Imath::Box3f computeBound( const ScenePath &path, const Gaffer::Context *context, const ScenePlug *parent ) const; virtual Imath::M44f computeTransform( const ScenePath &path, const Gaffer::Context *context, const ScenePlug *parent ) const; virtual IECore::ConstCompoundObjectPtr computeAttributes( const ScenePath &path, const Gaffer::Context *context, const ScenePlug *parent ) const; virtual IECore::ConstObjectPtr computeObject( const ScenePath &path, const Gaffer::Context *context, const ScenePlug *parent ) const; virtual IECore::ConstInternedStringVectorDataPtr computeChildNames( const ScenePath &path, const Gaffer::Context *context, const ScenePlug *parent ) const; virtual IECore::ConstCompoundObjectPtr computeGlobals( const Gaffer::Context *context, const ScenePlug *parent ) const; virtual IECore::ConstInternedStringVectorDataPtr computeSetNames( const Gaffer::Context *context, const ScenePlug *parent ) const; /// Implementations of computeSet() must return an empty PathMatcherData when the setName would not be present /// in the result of computeSetNames(), and the corresponding hashSet() method also needs to take this into /// account. The rationale for this is that it frees other nodes from checking that a set exists before accessing /// it, and that makes computation quicker, as we don't need to access setNamesPlug() at all in many common cases. virtual IECore::ConstPathMatcherDataPtr computeSet( const IECore::InternedString &setName, const Gaffer::Context *context, const ScenePlug *parent ) const; /// Convenience function to compute the correct bounding box for a path from the bounding box and transforms of its /// children. Using this from computeBound() should be a last resort, as it implies peeking inside children to determine /// information about the parent - the last thing we want to be doing when defining large scenes procedurally. If /// `out->childNames()` has been computed already for some reason, then it may be passed to avoid recomputing it /// internally. Imath::Box3f unionOfTransformedChildBounds( const ScenePath &path, const ScenePlug *out, const IECore::InternedStringVectorData *childNames = nullptr ) const; /// A hash for the result of the computation in unionOfTransformedChildBounds(). IECore::MurmurHash hashOfTransformedChildBounds( const ScenePath &path, const ScenePlug *out, const IECore::InternedStringVectorData *childNames = nullptr ) const; private : static size_t g_firstPlugIndex; }; IE_CORE_DECLAREPTR( SceneNode ) } // namespace GafferScene #endif // GAFFERSCENE_SCENENODE_H
{ "content_hash": "e6c313b27dce1c017856efea99892d1f", "timestamp": "", "source": "github", "line_count": 96, "max_line_length": 165, "avg_line_length": 63.541666666666664, "alnum_prop": 0.7585245901639345, "repo_name": "ivanimanishi/gaffer", "id": "f30858614869f36c4080803d940870f6c82daa01", "size": "8160", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "include/GafferScene/SceneNode.h", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "C", "bytes": "39753" }, { "name": "C++", "bytes": "6086015" }, { "name": "CMake", "bytes": "83446" }, { "name": "CSS", "bytes": "28027" }, { "name": "GLSL", "bytes": "6236" }, { "name": "Python", "bytes": "6120483" }, { "name": "Shell", "bytes": "13049" }, { "name": "Slash", "bytes": "2870" } ], "symlink_target": "" }
<h3><strong>Referrals</strong></h3> <div class="inner-addon left-addon filterInput"> <i class="fa fa-filter"></i> <input type="text" class="form-control" placeholder="Filter..." ng-model="query" /> </div> <table class="table table-bordered table-striped table-hover"> <thead> <tr> <th>Date of Referral</th> <th>Referral From</th> <th>Referral To</th> <th>Source</th> </tr> </thead> <tbody> <tr dir-paginate="referral in referrals | filter:search | itemsPerPage: 9" current-page="currentPage" ng-click="go('{{referral.sourceId}}', '{{referral.source}}')" ng-class="{info: selected(referral.sourceId)}"> <td class="dateTime">{{ referral.dateOfReferral | date:'dd/MM/yyyy'}}</td> <td>{{ referral.referralFrom }}</td> <td>{{ referral.referralTo }}</td> <td>{{ referral.source }}</td> </tr> <tr ng-if="!referrals.length"> <td colspan="4"><span class="label label-default">No referrals</span></td> </tr> </tbody> </table> <div class="row"> <div class="col-md-12"> <span class="patientSummary-spinner" us-spinner="{radius:20, width:8, length: 16}" spinner-key="patientSummary-spinner" spinner-start-active="true"></span> </div> </div>
{ "content_hash": "61342420e1f43a5b634e5966dc479b0f", "timestamp": "", "source": "github", "line_count": 36, "max_line_length": 216, "avg_line_length": 34.25, "alnum_prop": 0.6277372262773723, "repo_name": "RippleOSI/NE-HSCIE-Core", "id": "df7896d396b8d5e691cdf558a7f600f4356feec6", "size": "1233", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "webapp/app/views/referrals/referrals-list.html", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "ApacheConf", "bytes": "48278" }, { "name": "CSS", "bytes": "66003" }, { "name": "HTML", "bytes": "781059" }, { "name": "Java", "bytes": "408040" }, { "name": "JavaScript", "bytes": "246111" } ], "symlink_target": "" }
package org.xbill.DNS; import static org.junit.jupiter.api.Assertions.assertEquals; import java.io.IOException; import org.junit.jupiter.api.Test; class ISDNRecordTest { Name n = Name.fromConstantString("my.name."); @Test void ctor_5arg() { ISDNRecord record = new ISDNRecord(n, DClass.IN, 0, "foo", "bar"); assertEquals("foo", record.getAddress()); assertEquals("bar", record.getSubAddress()); } @Test void rdataFromString() throws IOException { Tokenizer t = new Tokenizer("150862028003217 004"); ISDNRecord record = new ISDNRecord(); record.rdataFromString(t, null); assertEquals("150862028003217", record.getAddress()); assertEquals("004", record.getSubAddress()); } }
{ "content_hash": "e60e023a51ba73701b077db5f52b1725", "timestamp": "", "source": "github", "line_count": 27, "max_line_length": 70, "avg_line_length": 26.85185185185185, "alnum_prop": 0.7048275862068966, "repo_name": "dnsjava/dnsjava", "id": "f5c3e2131a5b8b9013beaa2333f8f10638a07e87", "size": "766", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/test/java/org/xbill/DNS/ISDNRecordTest.java", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "Java", "bytes": "1817433" } ], "symlink_target": "" }
package io.luna.game.model.mob.inter; /** * An enumerated type whose elements represent all possible states for an interface to be in. * * @author lare96 <http://github.com/lare96> */ public enum InterfaceState { /** * The idle state. Idle is the default state for all interface instances when they are first * created. */ IDLE, /** * The open state. The interface instance is open and viewable on the Player's screen. */ OPEN, /** * The closed state. The interface instance was taken off the Player's screen. */ CLOSED }
{ "content_hash": "0369e83ac7c730d1b3a9a2a643dd5f25", "timestamp": "", "source": "github", "line_count": 25, "max_line_length": 96, "avg_line_length": 23.52, "alnum_prop": 0.6496598639455783, "repo_name": "lare96/luna", "id": "74f818ebc573ed6fec9d9742465e81cb30c9fb3c", "size": "588", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/main/java/io/luna/game/model/mob/inter/InterfaceState.java", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "129" }, { "name": "Java", "bytes": "651745" }, { "name": "Scala", "bytes": "84292" } ], "symlink_target": "" }
redis-server /etc/redis.conf
{ "content_hash": "2f3a3061e7ec9bb805ec71b2a3201340", "timestamp": "", "source": "github", "line_count": 1, "max_line_length": 28, "avg_line_length": 28, "alnum_prop": 0.8214285714285714, "repo_name": "24HOURSMEDIA/docker-dxstack1-synced", "id": "84dc6162812841d50acf3e9d0d088d35cab72bcd", "size": "46", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "docker/redis/start.sh", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "ApacheConf", "bytes": "304" }, { "name": "Batchfile", "bytes": "6467" }, { "name": "CSS", "bytes": "50079" }, { "name": "Groff", "bytes": "29" }, { "name": "HTML", "bytes": "1138810" }, { "name": "JavaScript", "bytes": "5389070" }, { "name": "Makefile", "bytes": "7342" }, { "name": "Nginx", "bytes": "1276" }, { "name": "PHP", "bytes": "9666203" }, { "name": "Python", "bytes": "16289" }, { "name": "Shell", "bytes": "8571" } ], "symlink_target": "" }
require 'test_helper' class ReadTest < Test::Unit::TestCase context "Read mode on standard connection: " do setup do @read = :secondary @client = MongoClient.new('localhost', 27017, :read => @read, :connect => false) end end context "Read preferences on replica set connection: " do setup do @read = :secondary_preferred @acceptable_latency = 100 @tags = {"dc" => "Tyler", "rack" => "Brock"} @bad_tags = {"wow" => "cool"} @client = MongoReplicaSetClient.new( ['localhost:27017'], :read => @read, :tag_sets => @tags, :secondary_acceptable_latency_ms => @acceptable_latency, :connect => false ) end should "store read preference on MongoClient" do assert_equal @read, @client.read assert_equal @tags, @client.tag_sets assert_equal @acceptable_latency, @client.acceptable_latency end should "propogate to DB" do db = @client['foo'] assert_equal @read, db.read assert_equal @tags, db.tag_sets assert_equal @acceptable_latency, db.acceptable_latency db = @client.db('foo') assert_equal @read, db.read assert_equal @tags, db.tag_sets assert_equal @acceptable_latency, db.acceptable_latency db = DB.new('foo', @client) assert_equal @read, db.read assert_equal @tags, db.tag_sets assert_equal @acceptable_latency, db.acceptable_latency end should "allow db override" do db = DB.new('foo', @client, :read => :primary, :tag_sets => @bad_tags, :acceptable_latency => 25) assert_equal :primary, db.read assert_equal @bad_tags, db.tag_sets assert_equal 25, db.acceptable_latency db = @client.db('foo', :read => :primary, :tag_sets => @bad_tags, :acceptable_latency => 25) assert_equal :primary, db.read assert_equal @bad_tags, db.tag_sets assert_equal 25, db.acceptable_latency end context "on DB: " do setup do @db = @client['foo'] end should "propogate to collection" do col = @db.collection('bar') assert_equal @read, col.read assert_equal @tags, col.tag_sets assert_equal @acceptable_latency, col.acceptable_latency col = @db['bar'] assert_equal @read, col.read assert_equal @tags, col.tag_sets assert_equal @acceptable_latency, col.acceptable_latency col = Collection.new('bar', @db) assert_equal @read, col.read assert_equal @tags, col.tag_sets assert_equal @acceptable_latency, col.acceptable_latency end should "allow override on collection" do col = @db.collection('bar', :read => :primary, :tag_sets => @bad_tags, :acceptable_latency => 25) assert_equal :primary, col.read assert_equal @bad_tags, col.tag_sets assert_equal 25, col.acceptable_latency col = Collection.new('bar', @db, :read => :primary, :tag_sets => @bad_tags, :acceptable_latency => 25) assert_equal :primary, col.read assert_equal @bad_tags, col.tag_sets assert_equal 25, col.acceptable_latency end end context "on read mode ops" do setup do @col = @client['foo']['bar'] @mock_socket = new_mock_socket end should "use default value on query" do @cursor = @col.find({:a => 1}) sock = new_mock_socket read_pool = stub(:checkin => true) @client.stubs(:read_pool).returns(read_pool) primary_pool = stub(:checkin => true) sock.stubs(:pool).returns(primary_pool) @client.stubs(:primary_pool).returns(primary_pool) @client.expects(:checkout_reader).returns(sock) @client.expects(:receive_message).with do |o, m, l, s, c, r| r == nil end.returns([[], 0, 0]) @cursor.next end should "allow override default value on query" do @cursor = @col.find({:a => 1}, :read => :primary) sock = new_mock_socket primary_pool = stub(:checkin => true) sock.stubs(:pool).returns(primary_pool) @client.stubs(:primary_pool).returns(primary_pool) @client.expects(:checkout_reader).returns(sock) @client.expects(:receive_message).with do |o, m, l, s, c, r| r == nil end.returns([[], 0, 0]) @cursor.next end should "allow override alternate value on query" do assert_raise MongoArgumentError do @col.find_one({:a => 1}, :read => {:dc => "ny"}) end end end end end
{ "content_hash": "5d757ce8a1878a20f9caa7ffe69669aa", "timestamp": "", "source": "github", "line_count": 141, "max_line_length": 110, "avg_line_length": 32.51063829787234, "alnum_prop": 0.5962041884816754, "repo_name": "pcarrier-packaging/deb-ruby-mongo", "id": "a6818dd10c9466440abda0ec1aa233d9bb86eac0", "size": "4584", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "test/unit/read_test.rb", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "C", "bytes": "47934" }, { "name": "Java", "bytes": "36640" }, { "name": "JavaScript", "bytes": "106797" }, { "name": "Perl", "bytes": "329" }, { "name": "Ruby", "bytes": "661223" } ], "symlink_target": "" }
require "gds_api/content_store" require "gds_api/publishing_api" module Services def self.content_store @content_store ||= GdsApi::ContentStore.new( Plek.new.find("content-store"), ) end def self.publishing_api @publishing_api ||= GdsApi::PublishingApi.new( Plek.new.find("publishing-api"), bearer_token: ENV["PUBLISHING_API_BEARER_TOKEN"] || "example", ) end end
{ "content_hash": "dee80ca6ff30b23ae74f194fcc8fc5b9", "timestamp": "", "source": "github", "line_count": 17, "max_line_length": 68, "avg_line_length": 24, "alnum_prop": 0.6691176470588235, "repo_name": "alphagov/calendars", "id": "b33b3c1fe090206ab71cab9fe246a5528aefb8dc", "size": "408", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "lib/services.rb", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "2886" }, { "name": "Dockerfile", "bytes": "514" }, { "name": "HTML", "bytes": "12482" }, { "name": "JavaScript", "bytes": "55" }, { "name": "Ruby", "bytes": "109158" }, { "name": "Shell", "bytes": "2065" } ], "symlink_target": "" }
package org.nibiru.ui.core.api; import org.nibiru.model.core.api.Value; public interface CheckBox extends ValueWidget<Boolean>, HasEnabled, Focusable { Value<String> getTextLabel(); }
{ "content_hash": "270326508238cd685c87f705a854fa68", "timestamp": "", "source": "github", "line_count": 9, "max_line_length": 61, "avg_line_length": 22.11111111111111, "alnum_prop": 0.7386934673366834, "repo_name": "AAJTechnologies/ui", "id": "c0843246d8af881c77ffe8e971e713a98798531e", "size": "199", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "org.nibiru.ui.core/src/main/java/org/nibiru/ui/core/api/CheckBox.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "180" }, { "name": "Java", "bytes": "127449" } ], "symlink_target": "" }
/** * @fileoverview Utility methods to deal with CSS3 transitions * programmatically. */ goog.provide('goog.style.transition'); goog.provide('goog.style.transition.Css3Property'); goog.require('goog.array'); goog.require('goog.asserts'); goog.require('goog.dom'); goog.require('goog.dom.TagName'); goog.require('goog.dom.safe'); goog.require('goog.dom.vendor'); goog.require('goog.functions'); goog.require('goog.html.SafeHtml'); goog.require('goog.style'); goog.require('goog.userAgent'); /** * A typedef to represent a CSS3 transition property. Duration and delay * are both in seconds. Timing is CSS3 timing function string, such as * 'easein', 'linear'. * * Alternatively, specifying string in the form of '[property] [duration] * [timing] [delay]' as specified in CSS3 transition is fine too. * * @typedef { { * property: string, * duration: number, * timing: string, * delay: number * } | string } */ goog.style.transition.Css3Property; /** * Sets the element CSS3 transition to properties. * @param {Element} element The element to set transition on. * @param {goog.style.transition.Css3Property| * Array<goog.style.transition.Css3Property>} properties A single CSS3 * transition property or array of properties. * @suppress {strictMissingProperties} Part of the go/strict_warnings_migration */ goog.style.transition.set = function(element, properties) { 'use strict'; if (!Array.isArray(properties)) { properties = [properties]; } goog.asserts.assert( properties.length > 0, 'At least one Css3Property should be specified.'); var values = goog.array.map(properties, function(p) { 'use strict'; if (typeof p === 'string') { return p; } else { goog.asserts.assertObject(p, 'Expected css3 property to be an object.'); var propString = p.property + ' ' + p.duration + 's ' + p.timing + ' ' + p.delay + 's'; goog.asserts.assert( p.property && typeof p.duration === 'number' && p.timing && typeof p.delay === 'number', 'Unexpected css3 property value: %s', propString); return propString; } }); goog.style.transition.setPropertyValue_(element, values.join(',')); }; /** * Removes any programmatically-added CSS3 transition in the given element. * @param {Element} element The element to remove transition from. */ goog.style.transition.removeAll = function(element) { 'use strict'; goog.style.transition.setPropertyValue_(element, ''); }; /** * @return {boolean} Whether CSS3 transition is supported. */ goog.style.transition.isSupported = goog.functions.cacheReturnValue(function() { 'use strict'; // Since IE would allow any attribute, we need to explicitly check the // browser version here instead. if (goog.userAgent.IE) { return goog.userAgent.isVersionOrHigher('10.0'); } // We create a test element with style=-vendor-transition // We then detect whether those style properties are recognized and // available from js. var el = goog.dom.createElement(goog.dom.TagName.DIV); var transition = 'opacity 1s linear'; var vendorPrefix = goog.dom.vendor.getVendorPrefix(); var style = {'transition': transition}; if (vendorPrefix) { style[vendorPrefix + '-transition'] = transition; } goog.dom.safe.setInnerHtml( el, goog.html.SafeHtml.create('div', {'style': style})); var testElement = /** @type {Element} */ (el.firstChild); goog.asserts.assert(testElement.nodeType == Node.ELEMENT_NODE); return goog.style.getStyle(testElement, 'transition') != ''; }); /** * Sets CSS3 transition property value to the given value. * @param {Element} element The element to set transition on. * @param {string} transitionValue The CSS3 transition property value. * @private */ goog.style.transition.setPropertyValue_ = function(element, transitionValue) { 'use strict'; goog.style.setStyle(element, 'transition', transitionValue); };
{ "content_hash": "92ecf8af64295b63fe70b1da2e0e57f9", "timestamp": "", "source": "github", "line_count": 126, "max_line_length": 80, "avg_line_length": 31.46031746031746, "alnum_prop": 0.6904641775983855, "repo_name": "googlechromelabs/chromeos_smart_card_connector", "id": "666a052414f5b21db8e79cba76793397b69e795c", "size": "4064", "binary": false, "copies": "2", "ref": "refs/heads/main", "path": "third_party/closure-library/src/closure/goog/style/transition.js", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "C", "bytes": "4254" }, { "name": "C++", "bytes": "722639" }, { "name": "CSS", "bytes": "9725" }, { "name": "HTML", "bytes": "17393" }, { "name": "JavaScript", "bytes": "361786" }, { "name": "Lua", "bytes": "1704" }, { "name": "Makefile", "bytes": "116814" }, { "name": "Python", "bytes": "27331" }, { "name": "Shell", "bytes": "12794" } ], "symlink_target": "" }
package logic import ( "github.com/outbrain/golib/log" "github.com/outbrain/orchestrator/go/agent" "github.com/outbrain/orchestrator/go/config" "github.com/outbrain/orchestrator/go/inst" "time" ) const ( maxConcurrency = 5 ) // discoveryInstanceKeys is a channel of instanceKey-s that were requested for discovery. // It can be continuously updated as discovery process progresses. var discoveryInstanceKeys chan inst.InstanceKey = make(chan inst.InstanceKey, maxConcurrency) // handleDiscoveryRequests iterates the discoveryInstanceKeys channel and calls upon // instance discovery per entry. func handleDiscoveryRequests(pendingTokens chan bool, completedTokens chan bool) { for instanceKey := range discoveryInstanceKeys { AccountedDiscoverInstance(instanceKey, pendingTokens, completedTokens) } } // AccountedDiscoverInstance will call upon DiscoverInstance and will keep track of // discovery tokens such that management of multiple discoveries can figure out // whether all instances in a topology are accounted for. func AccountedDiscoverInstance(instanceKey inst.InstanceKey, pendingTokens chan bool, completedTokens chan bool) { if pendingTokens != nil { pendingTokens <- true } go func() { DiscoverInstance(instanceKey) if completedTokens != nil { completedTokens <- true } }() } // DiscoverInstance will attempt discovering an instance (unless it is already up to date) and will // list down its master and slaves (if any) for further discovery. func DiscoverInstance(instanceKey inst.InstanceKey) { instanceKey.Formalize() if !instanceKey.IsValid() { return } instance, found, err := inst.ReadInstance(&instanceKey) if found && instance.IsUpToDate && instance.IsLastCheckValid { // we've already discovered this one. Skip! goto Cleanup } // First we've ever heard of this instance. Continue investigation: instance, err = inst.ReadTopologyInstance(&instanceKey) // panic can occur (IO stuff). Therefore it may happen // that instance is nil. Check it. if err != nil || instance == nil { log.Warningf("instance is nil in DiscoverInstance. key=%+v, error=%+v", instanceKey, err) goto Cleanup } log.Debugf("Discovered host: %+v, master: %+v", instance.Key, instance.MasterKey) // Investigate slaves: for _, slaveKey := range instance.SlaveHosts.GetInstanceKeys() { discoveryInstanceKeys <- slaveKey } // Investigate master: discoveryInstanceKeys <- instance.MasterKey Cleanup: } // Start discovery begins a one time asynchronuous discovery process for the given // instance and all of its topology connected instances. // That is, the instance will be investigated for master and slaves, and the routines will follow on // each and every such found master/slave. // In essense, assuming all slaves in a replication topology are running, and given a single instance // in such topology, this function will detect the entire topology. func StartDiscovery(instanceKey inst.InstanceKey) { log.Infof("Starting discovery at %+v", instanceKey) pendingTokens := make(chan bool, maxConcurrency) completedTokens := make(chan bool, maxConcurrency) AccountedDiscoverInstance(instanceKey, pendingTokens, completedTokens) go handleDiscoveryRequests(pendingTokens, completedTokens) // Block until all are complete for { select { case <-pendingTokens: <-completedTokens default: inst.AuditOperation("start-discovery", &instanceKey, "") return } } } // ContinuousDiscovery starts an asynchronuous infinite discovery process where instances are // periodically investigated and their status captured, and long since unseen instances are // purged and forgotten. func ContinuousDiscovery() { log.Infof("Starting continuous discovery") inst.LoadHostnameResolveCacheFromDatabase() go handleDiscoveryRequests(nil, nil) tick := time.Tick(time.Duration(config.Config.DiscoveryPollSeconds) * time.Second) forgetUnseenTick := time.Tick(time.Minute) recoverTick := time.Tick(10 * time.Second) var snapshotTopologiesTick <-chan time.Time if config.Config.SnapshotTopologiesIntervalHours > 0 { snapshotTopologiesTick = time.Tick(time.Duration(config.Config.SnapshotTopologiesIntervalHours) * time.Hour) } elected := false _ = CreateElectionAnchor(false) for { select { case <-tick: if elected, _ = AttemptElection(); elected { instanceKeys, _ := inst.ReadOutdatedInstanceKeys() log.Debugf("outdated keys: %+v", instanceKeys) for _, instanceKey := range instanceKeys { discoveryInstanceKeys <- instanceKey } } else { log.Debugf("Not elected as active node; polling") } case <-forgetUnseenTick: // See if we should also forget objects (lower frequency) go func() { if elected { inst.ForgetLongUnseenInstances() inst.ForgetUnseenInstancesDifferentlyResolved() inst.ForgetExpiredHostnameResolves() inst.DeleteInvalidHostnameResolves() inst.ReviewUnseenInstances() inst.InjectUnseenMasters() inst.ResolveUnknownMasterHostnameResolves() inst.ExpireMaintenance() inst.ExpireDowntime() inst.ExpireCandidateInstances() inst.ExpireHostnameUnresolve() inst.ExpireClusterDomainName() } if !elected { // Take this opportunity to refresh yourself inst.LoadHostnameResolveCacheFromDatabase() } inst.ReadClusterAliases() HealthTest() }() case <-recoverTick: go func() { if elected { ClearActiveFailureDetections() ClearActiveRecoveries() CheckAndRecover(nil, nil, false, false) } }() case <-snapshotTopologiesTick: go func() { inst.SnapshotTopologies() }() } } } func pollAgent(hostname string) error { polledAgent, err := agent.GetAgent(hostname) agent.UpdateAgentLastChecked(hostname) if err != nil { return log.Errore(err) } err = agent.UpdateAgentInfo(hostname, polledAgent) if err != nil { return log.Errore(err) } return nil } // ContinuousAgentsPoll starts an asynchronuous infinite process where agents are // periodically investigated and their status captured, and long since unseen agents are // purged and forgotten. func ContinuousAgentsPoll() { log.Infof("Starting continuous agents poll") go discoverSeededAgents() tick := time.Tick(time.Duration(config.Config.DiscoveryPollSeconds) * time.Second) forgetUnseenTick := time.Tick(time.Hour) for _ = range tick { agentsHosts, _ := agent.ReadOutdatedAgentsHosts() log.Debugf("outdated agents hosts: %+v", agentsHosts) for _, hostname := range agentsHosts { go pollAgent(hostname) } // See if we should also forget agents (lower frequency) select { case <-forgetUnseenTick: agent.ForgetLongUnseenAgents() agent.FailStaleSeeds() default: } } } func discoverSeededAgents() { for seededAgent := range agent.SeededAgents { instanceKey := inst.InstanceKey{Hostname: seededAgent.Hostname, Port: int(seededAgent.MySQLPort)} go StartDiscovery(instanceKey) } }
{ "content_hash": "b23217e564877648e93c8316aa12475a", "timestamp": "", "source": "github", "line_count": 222, "max_line_length": 114, "avg_line_length": 31.24774774774775, "alnum_prop": 0.748306184229494, "repo_name": "ruo91/orchestrator", "id": "10cc851ede1ab6c4ea88db539ff2489fc2287378", "size": "7526", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "go/logic/orchestrator.go", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "8314" }, { "name": "Go", "bytes": "525140" }, { "name": "JavaScript", "bytes": "134426" }, { "name": "Shell", "bytes": "3722" } ], "symlink_target": "" }
package com.hortonworks.streamline.common; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; import com.hortonworks.streamline.common.exception.WrappedWebApplicationException; import javax.ws.rs.WebApplicationException; import javax.ws.rs.client.Entity; import javax.ws.rs.client.WebTarget; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.MultivaluedMap; import javax.ws.rs.core.Response; import java.util.ArrayList; import java.util.Iterator; import java.util.List; public class JsonClientUtil { public static final MediaType DEFAULT_MEDIA_TYPE = MediaType.APPLICATION_JSON_TYPE; public static <T> T getEntity(WebTarget target, Class<T> clazz) { return getEntity(target, DEFAULT_MEDIA_TYPE, clazz); } public static <T> T getEntity(WebTarget target, MediaType mediaType, Class<T> clazz) { try { String response = target.request(mediaType).get(String.class); ObjectMapper mapper = new ObjectMapper(); JsonNode node = mapper.readTree(response); return mapper.treeToValue(node, clazz); } catch (WebApplicationException e) { throw WrappedWebApplicationException.of(e); } catch (Exception ex) { throw new RuntimeException(ex); } } public static <T> T getEntity(WebTarget target, String fieldName, Class<T> clazz) { return getEntity(target, fieldName, DEFAULT_MEDIA_TYPE, clazz); } public static <T> T getEntity(WebTarget target, String fieldName, MediaType mediaType, Class<T> clazz) { try { String response = target.request(MediaType.APPLICATION_JSON_TYPE).get(String.class); ObjectMapper mapper = new ObjectMapper(); JsonNode node = mapper.readTree(response); return mapper.treeToValue(node.get(fieldName), clazz); } catch (WebApplicationException e) { throw WrappedWebApplicationException.of(e); } catch (Exception ex) { throw new RuntimeException(ex); } } public static <T> List<T> getEntities(WebTarget target, Class<T> clazz) { return getEntities(target, DEFAULT_MEDIA_TYPE, clazz); } public static <T> List<T> getEntities(WebTarget target, MediaType mediaType, Class<T> clazz) { List<T> entities = new ArrayList<>(); try { String response = target.request(mediaType).get(String.class); ObjectMapper mapper = new ObjectMapper(); JsonNode node = mapper.readTree(response); Iterator<JsonNode> it = node.elements(); while (it.hasNext()) { entities.add(mapper.treeToValue(it.next(), clazz)); } return entities; } catch (WebApplicationException e) { throw WrappedWebApplicationException.of(e); } catch (Exception ex) { throw new RuntimeException(ex); } } public static <T> List<T> getEntities(WebTarget target, String fieldName, Class<T> clazz) { return getEntities(target, fieldName, DEFAULT_MEDIA_TYPE, clazz); } public static <T> List<T> getEntities(WebTarget target, String fieldName, MediaType mediaType, Class<T> clazz) { List<T> entities = new ArrayList<>(); try { String response = target.request(mediaType).get(String.class); ObjectMapper mapper = new ObjectMapper(); JsonNode node = mapper.readTree(response); Iterator<JsonNode> it = node.get(fieldName).elements(); while (it.hasNext()) { entities.add(mapper.treeToValue(it.next(), clazz)); } return entities; } catch (WebApplicationException e) { throw WrappedWebApplicationException.of(e); } catch (Exception ex) { throw new RuntimeException(ex); } } public static <T> T postForm(WebTarget target, MultivaluedMap<String, String> form, Class<T> clazz) { return postForm(target, form, DEFAULT_MEDIA_TYPE, clazz); } public static <T> T postForm(WebTarget target, MultivaluedMap<String, String> form, MediaType mediaType, Class<T> clazz) { return target.request(mediaType).post(Entity.form(form), clazz); } }
{ "content_hash": "8462887bfca7ad4c52008f1e027e9404", "timestamp": "", "source": "github", "line_count": 107, "max_line_length": 126, "avg_line_length": 40.28971962616822, "alnum_prop": 0.6527487821851079, "repo_name": "hmcl/Streams", "id": "213d4c2ca2c5cc935b61e8e4d6a8117a20b30d5a", "size": "4913", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "common/src/main/java/com/hortonworks/streamline/common/JsonClientUtil.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "80322" }, { "name": "Groovy", "bytes": "647" }, { "name": "HTML", "bytes": "1783" }, { "name": "Java", "bytes": "3454129" }, { "name": "JavaScript", "bytes": "1167391" }, { "name": "Python", "bytes": "8744" }, { "name": "Shell", "bytes": "57287" } ], "symlink_target": "" }
package vitessdriver import ( "database/sql/driver" "fmt" "time" "github.com/youtube/vitess/go/sqltypes" querypb "github.com/youtube/vitess/go/vt/proto/query" ) type converter struct { location *time.Location } func (cv *converter) ToNative(v sqltypes.Value) (interface{}, error) { switch v.Type() { case sqltypes.Datetime: return DatetimeToNative(v, cv.location) case sqltypes.Date: return DateToNative(v, cv.location) } return sqltypes.ToNative(v) } func (cv *converter) BuildBindVariable(v interface{}) (*querypb.BindVariable, error) { if t, ok := v.(time.Time); ok { return sqltypes.ValueBindVariable(NewDatetime(t, cv.location)), nil } return sqltypes.BuildBindVariable(v) } // populateRow populates a row of data using the table's field descriptions. // The returned types for "dest" include the list from the interface // specification at https://golang.org/pkg/database/sql/driver/#Value // and in addition the type "uint64" for unsigned BIGINT MySQL records. func (cv *converter) populateRow(dest []driver.Value, row []sqltypes.Value) (err error) { for i := range dest { dest[i], err = cv.ToNative(row[i]) if err != nil { return } } return } func (cv *converter) buildBindVars(args []driver.Value) (map[string]*querypb.BindVariable, error) { bindVars := make(map[string]*querypb.BindVariable, len(args)) for i, v := range args { bv, err := cv.BuildBindVariable(v) if err != nil { return nil, err } bindVars[fmt.Sprintf("v%d", i+1)] = bv } return bindVars, nil } func (cv *converter) bindVarsFromNamedValues(args []driver.NamedValue) (map[string]*querypb.BindVariable, error) { bindVars := make(map[string]*querypb.BindVariable, len(args)) nameUsed := false for i, v := range args { bv, err := cv.BuildBindVariable(v.Value) if err != nil { return nil, err } if i == 0 { // Determine if args are based on names or ordinals. if v.Name != "" { nameUsed = true } } else { // Verify that there's no intermixing. if nameUsed && v.Name == "" { return nil, errNoIntermixing } if !nameUsed && v.Name != "" { return nil, errNoIntermixing } } if v.Name == "" { bindVars[fmt.Sprintf("v%d", i+1)] = bv } else { if v.Name[0] == ':' || v.Name[0] == '@' { bindVars[v.Name[1:]] = bv } else { bindVars[v.Name] = bv } } } return bindVars, nil } func newConverter(cfg *Configuration) (c *converter, err error) { c = &converter{ location: time.UTC, } if cfg.DefaultLocation != "" { c.location, err = time.LoadLocation(cfg.DefaultLocation) } return }
{ "content_hash": "27282146f5401382b9a4f62b06410d17", "timestamp": "", "source": "github", "line_count": 104, "max_line_length": 114, "avg_line_length": 24.865384615384617, "alnum_prop": 0.6655065738592421, "repo_name": "sougou/vitess", "id": "792c02a4bfbc851cb4e77ea2e0757eea904e8140", "size": "3142", "binary": false, "copies": "3", "ref": "refs/heads/master", "path": "go/vt/vitessdriver/convert.go", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "79101" }, { "name": "Go", "bytes": "7772535" }, { "name": "HTML", "bytes": "59824" }, { "name": "Java", "bytes": "1158315" }, { "name": "JavaScript", "bytes": "42815" }, { "name": "Liquid", "bytes": "7030" }, { "name": "Makefile", "bytes": "9629" }, { "name": "Python", "bytes": "1118992" }, { "name": "Ruby", "bytes": "3580" }, { "name": "Shell", "bytes": "60920" }, { "name": "Smarty", "bytes": "28688" }, { "name": "TypeScript", "bytes": "152741" }, { "name": "Yacc", "bytes": "50251" } ], "symlink_target": "" }
package com.intellij.openapi.externalSystem.model.project; import com.intellij.openapi.externalSystem.model.ProjectSystemId; import org.jetbrains.annotations.NotNull; /** * @author Denis Zhdanov */ public abstract class AbstractExternalEntityData implements ExternalEntityData { private static final long serialVersionUID = 1L; @NotNull private final ProjectSystemId myOwner; public AbstractExternalEntityData(@NotNull ProjectSystemId owner) { myOwner = owner; } @Override @NotNull public ProjectSystemId getOwner() { return myOwner; } @Override public int hashCode() { return myOwner.hashCode(); } @Override public boolean equals(Object obj) { if (obj == this) { return true; } if (getClass() != obj.getClass()) { return false; } AbstractExternalEntityData that = (AbstractExternalEntityData)obj; return myOwner.equals(that.myOwner); } }
{ "content_hash": "1bc5faf790055beb81c9cdcae062a241", "timestamp": "", "source": "github", "line_count": 41, "max_line_length": 80, "avg_line_length": 22.658536585365855, "alnum_prop": 0.7179763186221744, "repo_name": "mdanielwork/intellij-community", "id": "9e53f4706b41094a28d406102ceaf7098484db76", "size": "929", "binary": false, "copies": "3", "ref": "refs/heads/master", "path": "platform/external-system-api/src/com/intellij/openapi/externalSystem/model/project/AbstractExternalEntityData.java", "mode": "33188", "license": "apache-2.0", "language": [], "symlink_target": "" }
set -e -u -x ## Vars ---------------------------------------------------------------------- export ANSIBLE_GIT_RELEASE=${ANSIBLE_GIT_RELEASE:-"v1.9.3-1"} export ANSIBLE_GIT_REPO=${ANSIBLE_GIT_REPO:-"https://github.com/ansible/ansible"} export ANSIBLE_ROLE_FILE=${ANSIBLE_ROLE_FILE:-"ansible-role-requirements.yml"} export ANSIBLE_WORKING_DIR=${ANSIBLE_WORKING_DIR:-/opt/ansible_${ANSIBLE_GIT_RELEASE}} export GET_PIP_URL=${GET_PIP_URL:-"https://bootstrap.pypa.io/get-pip.py"} export SSH_DIR=${SSH_DIR:-"/root/.ssh"} export UPDATE_ANSIBLE_REQUIREMENTS=${UPDATE_ANSIBLE_REQUIREMENTS:-"yes"} export DEBIAN_FRONTEND=${DEBIAN_FRONTEND:-"noninteractive"} ## Functions ----------------------------------------------------------------- info_block "Checking for required libraries." 2> /dev/null || source $(dirname ${0})/scripts-library.sh ## Main ---------------------------------------------------------------------- info_block "Bootstrapping System with Ansible" # Create the ssh dir if needed ssh_key_create # Install the base packages apt-get update && apt-get -y install git python-all python-dev curl autoconf g++ python2.7-dev # If the working directory exists remove it if [ -d "${ANSIBLE_WORKING_DIR}" ];then rm -rf "${ANSIBLE_WORKING_DIR}" fi # Clone down the base ansible source git clone "${ANSIBLE_GIT_REPO}" "${ANSIBLE_WORKING_DIR}" pushd "${ANSIBLE_WORKING_DIR}" git checkout "${ANSIBLE_GIT_RELEASE}" git submodule update --init --recursive popd # Install pip if [ ! "$(which pip)" ];then curl ${GET_PIP_URL} > /opt/get-pip.py python2 /opt/get-pip.py || python /opt/get-pip.py fi # Install requirements if there are any if [ -f "requirements.txt" ];then pip2 install -r requirements.txt || pip install -r requirements.txt fi # Install ansible pip2 install "${ANSIBLE_WORKING_DIR}" || pip install "${ANSIBLE_WORKING_DIR}" # Update dependent roles if [ -f "${ANSIBLE_ROLE_FILE}" ];then # Update or create the roles manifest if [ "${UPDATE_ANSIBLE_REQUIREMENTS}" == "yes" ];then ./scripts/os-ansible-role-requirements.py --requirement-file ${ANSIBLE_ROLE_FILE} update fi # Pull all required roles. ansible-galaxy install --role-file=${ANSIBLE_ROLE_FILE} \ --ignore-errors \ --force fi # Create openstack ansible wrapper tool cat > /usr/local/bin/openstack-ansible <<EOF #!/usr/bin/env bash # Copyright 2014, Rackspace US, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # # (c) 2014, Kevin Carter <kevin.carter@rackspace.com> # OpenStack wrapper tool to ease the use of ansible with multiple variable files. export PATH="/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:${PATH}" function info() { echo -e "\e[0;35m\${@}\e[0m" } # Discover the variable files. VAR1="\$(for i in \$(ls /etc/openstack_deploy/user_*.yml); do echo -ne "-e @\$i "; done)" # Provide information on the discovered variables. info "Variable files: \"\${VAR1}\"" # Run the ansible playbook command. \$(which ansible-playbook) \${VAR1} \$@ EOF # Ensure wrapper tool is executable chmod +x /usr/local/bin/openstack-ansible echo "openstack-ansible script created." echo "System is bootstrapped and ready for use."
{ "content_hash": "5c58a5b4787216394e7ad0149c46c655", "timestamp": "", "source": "github", "line_count": 108, "max_line_length": 103, "avg_line_length": 34.611111111111114, "alnum_prop": 0.6629213483146067, "repo_name": "manuelfelipe/openstack-ansible", "id": "a62e2abc25f761009560c663afd873a974117a10", "size": "4477", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "scripts/bootstrap-ansible.sh", "mode": "33261", "license": "apache-2.0", "language": [ { "name": "HTML", "bytes": "666" }, { "name": "Python", "bytes": "247532" }, { "name": "Shell", "bytes": "104608" } ], "symlink_target": "" }
class MainWindow : public QMainWindow { Q_OBJECT public: explicit MainWindow(QWidget *parent = 0); ~MainWindow(); private: Ui::MainWindow *ui; }; #endif // MAINWINDOW_H
{ "content_hash": "f138215f5425dba4495890fdb0feea00", "timestamp": "", "source": "github", "line_count": 12, "max_line_length": 45, "avg_line_length": 15.916666666666666, "alnum_prop": 0.6492146596858639, "repo_name": "przemir/EnvelopeCollide", "id": "2478d6a8cbb3fbd8def6b82d7db9ab394afa9f36", "size": "318", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "example2/MainWindow.h", "mode": "33188", "license": "mit", "language": [ { "name": "C", "bytes": "89869" }, { "name": "C++", "bytes": "221758" }, { "name": "Objective-C", "bytes": "16119" }, { "name": "Prolog", "bytes": "3726" } ], "symlink_target": "" }
<body> The water package contains the implementation of H2O's core. </body>
{ "content_hash": "b3021b5528ac6e924c4a53a50a70efe0", "timestamp": "", "source": "github", "line_count": 5, "max_line_length": 60, "avg_line_length": 15.6, "alnum_prop": 0.7435897435897436, "repo_name": "eg-zhang/h2o-2", "id": "2da2b3092989ba79923f61b728cb0e0ce579f5d4", "size": "78", "binary": false, "copies": "11", "ref": "refs/heads/master", "path": "src/main/java/water/package.html", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Batchfile", "bytes": "7065" }, { "name": "C", "bytes": "2461" }, { "name": "CSS", "bytes": "216906" }, { "name": "CoffeeScript", "bytes": "205094" }, { "name": "Emacs Lisp", "bytes": "7446" }, { "name": "Groovy", "bytes": "518" }, { "name": "HTML", "bytes": "177967" }, { "name": "Java", "bytes": "5177683" }, { "name": "JavaScript", "bytes": "42958" }, { "name": "Makefile", "bytes": "50927" }, { "name": "PHP", "bytes": "8490" }, { "name": "Perl", "bytes": "22594" }, { "name": "Python", "bytes": "3244626" }, { "name": "R", "bytes": "1631216" }, { "name": "Ruby", "bytes": "299" }, { "name": "Scala", "bytes": "39365" }, { "name": "Shell", "bytes": "189829" } ], "symlink_target": "" }
package org.apache.tika.batch.fs; import static java.nio.charset.StandardCharsets.UTF_8; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.util.List; import java.util.Map; import org.apache.tika.batch.BatchProcess; import org.apache.tika.batch.BatchProcessDriverCLI; import org.junit.Test; public class BatchProcessTest extends FSBatchTestBase { @Test(timeout = 15000) public void oneHeavyHangTest() throws Exception { Path outputDir = getNewOutputDir("one_heavy_hang-"); Map<String, String> args = getDefaultArgs("one_heavy_hang", outputDir); BatchProcessTestExecutor ex = new BatchProcessTestExecutor(args); StreamStrings streamStrings = ex.execute(); assertEquals(5, countChildren(outputDir)); Path hvyHang = outputDir.resolve("test0_heavy_hang.xml.xml"); assertTrue(Files.exists(hvyHang)); assertEquals(0, Files.size(hvyHang)); assertNotContained(BatchProcess.BATCH_CONSTANTS.BATCH_PROCESS_FATAL_MUST_RESTART.toString(), streamStrings.getErrString()); } @Test(timeout = 15000) public void allHeavyHangsTest() throws Exception { //each of the three threads hits a heavy hang. The BatchProcess runs into //all timedouts and shuts down. Path outputDir = getNewOutputDir("allHeavyHangs-"); Map<String, String> args = getDefaultArgs("heavy_heavy_hangs", outputDir); BatchProcessTestExecutor ex = new BatchProcessTestExecutor(args); StreamStrings streamStrings = ex.execute(); assertEquals(3, countChildren(outputDir)); for (Path hvyHang : listPaths(outputDir)){ assertTrue(Files.exists(hvyHang)); assertEquals("file length for "+hvyHang.getFileName()+" should be 0, but is: " + Files.size(hvyHang), 0, Files.size(hvyHang)); } assertContains(BatchProcess.BATCH_CONSTANTS.BATCH_PROCESS_FATAL_MUST_RESTART.toString(), streamStrings.getErrString()); } @Test(timeout = 30000) public void allHeavyHangsTestWithCrazyNumberConsumersTest() throws Exception { Path outputDir = getNewOutputDir("allHeavyHangsCrazyNumberConsumers-"); Map<String, String> args = getDefaultArgs("heavy_heavy_hangs", outputDir); args.put("numConsumers", "100"); BatchProcessTestExecutor ex = new BatchProcessTestExecutor(args); StreamStrings streamStrings = ex.execute(); assertEquals(7, countChildren(outputDir)); for (int i = 0; i < 6; i++){ Path hvyHang = outputDir.resolve("test"+i+"_heavy_hang.xml.xml"); assertTrue(Files.exists(hvyHang)); assertEquals(0, Files.size(hvyHang)); } assertContains("This is tika-batch's first test file", readFileToString(outputDir.resolve("test6_ok.xml.xml"), UTF_8)); //key that the process realize that there were no more processable files //in the queue and does not ask for a restart! assertNotContained(BatchProcess.BATCH_CONSTANTS.BATCH_PROCESS_FATAL_MUST_RESTART.toString(), streamStrings.getErrString()); } @Test(timeout = 30000) public void allHeavyHangsTestWithStarvedCrawler() throws Exception { //this tests that if all consumers are hung and the crawler is //waiting to add to the queue, there isn't deadlock. The batchrunner should //shutdown and ask to be restarted. Path outputDir = getNewOutputDir("allHeavyHangsStarvedCrawler-"); Map<String, String> args = getDefaultArgs("heavy_heavy_hangs", outputDir); args.put("numConsumers", "2"); args.put("maxQueueSize", "2"); args.put("timeoutThresholdMillis", "100000000");//make sure that the batch process doesn't time out BatchProcessTestExecutor ex = new BatchProcessTestExecutor(args); StreamStrings streamStrings = ex.execute(); assertEquals(2, countChildren(outputDir)); for (int i = 0; i < 2; i++){ Path hvyHang = outputDir.resolve("test"+i+"_heavy_hang.xml.xml"); assertTrue(Files.exists(hvyHang)); assertEquals(0, Files.size(hvyHang)); } assertContains(BatchProcess.BATCH_CONSTANTS.BATCH_PROCESS_FATAL_MUST_RESTART.toString(), streamStrings.getErrString()); assertContains("Crawler timed out", streamStrings.getErrString()); } @Test(timeout = 15000) public void outOfMemory() throws Exception { //the first consumer should sleep for 10 seconds //the second should be tied up in a heavy hang //the third one should hit the oom after processing test2_ok.xml //no consumers should process test2-4.txt! //i.e. the first consumer will finish in 10 seconds and //then otherwise would be looking for more, but the oom should prevent that Path outputDir = getNewOutputDir("oom-"); Map<String, String> args = getDefaultArgs("oom", outputDir); args.put("numConsumers", "3"); args.put("timeoutThresholdMillis", "30000"); BatchProcessTestExecutor ex = new BatchProcessTestExecutor(args); StreamStrings streamStrings = ex.execute(); assertEquals(4, countChildren(outputDir)); assertContains("This is tika-batch's first test file", readFileToString(outputDir.resolve("test2_ok.xml.xml"), UTF_8)); assertContains(BatchProcess.BATCH_CONSTANTS.BATCH_PROCESS_FATAL_MUST_RESTART.toString(), streamStrings.getErrString()); } @Test(timeout = 15000) public void noRestart() throws Exception { Path outputDir = getNewOutputDir("no_restart"); Map<String, String> args = getDefaultArgs("no_restart", outputDir); args.put("numConsumers", "1"); BatchProcessTestExecutor ex = new BatchProcessTestExecutor(args); StreamStrings streamStrings = ex.execute(); Path test2 = outputDir.resolve("test2_norestart.xml.xml"); assertTrue("test2_norestart.xml", Files.exists(test2)); Path test3 = outputDir.resolve("test3_ok.xml.xml"); assertFalse("test3_ok.xml", Files.exists(test3)); assertContains("exitStatus="+ BatchProcessDriverCLI.PROCESS_NO_RESTART_EXIT_CODE, streamStrings.getOutString()); assertContains("causeForTermination='MAIN_LOOP_EXCEPTION_NO_RESTART'", streamStrings.getOutString()); } /** * This tests to make sure that BatchProcess waits the appropriate * amount of time on an early termination before stopping. * * If this fails, then interruptible parsers (e.g. those with * nio channels) will be interrupted and there will be corrupted data. */ @Test(timeout = 60000) public void testWaitAfterEarlyTermination() throws Exception { Path outputDir = getNewOutputDir("wait_after_early_termination"); Map<String, String> args = getDefaultArgs("wait_after_early_termination", outputDir); args.put("numConsumers", "1"); args.put("maxAliveTimeSeconds", "5");//main process loop should stop after 5 seconds args.put("timeoutThresholdMillis", "300000");//effectively never args.put("pauseOnEarlyTerminationMillis", "20000");//let the parser have up to 20 seconds BatchProcessTestExecutor ex = new BatchProcessTestExecutor(args); StreamStrings streamStrings = ex.execute(); assertEquals(1, countChildren(outputDir)); assertContains("<p>some content</p>", readFileToString(outputDir.resolve("test0_sleep.xml.xml"), UTF_8)); assertContains("exitStatus="+BatchProcessDriverCLI.PROCESS_RESTART_EXIT_CODE, streamStrings.getOutString()); assertContains("causeForTermination='BATCH_PROCESS_ALIVE_TOO_LONG'", streamStrings.getOutString()); } @Test(timeout = 60000) public void testTimeOutAfterBeingAskedToShutdown() throws Exception { Path outputDir = getNewOutputDir("timeout_after_early_termination"); Map<String, String> args = getDefaultArgs("timeout_after_early_termination", outputDir); args.put("numConsumers", "1"); args.put("maxAliveTimeSeconds", "5");//main process loop should stop after 5 seconds args.put("timeoutThresholdMillis", "10000"); args.put("pauseOnEarlyTerminationMillis", "20000");//let the parser have up to 20 seconds BatchProcessTestExecutor ex = new BatchProcessTestExecutor(args); StreamStrings streamStrings = ex.execute(); List<Path> paths = listPaths(outputDir); assertEquals(1, paths.size()); assertEquals(0, Files.size(paths.get(0))); assertContains("exitStatus="+BatchProcessDriverCLI.PROCESS_RESTART_EXIT_CODE, streamStrings.getOutString()); assertContains("causeForTermination='BATCH_PROCESS_ALIVE_TOO_LONG'", streamStrings.getOutString()); } @Test(timeout = 10000) public void testRedirectionOfStreams() throws Exception { //test redirection of system.err to system.out Path outputDir = getNewOutputDir("noisy_parsers"); Map<String, String> args = getDefaultArgs("noisy_parsers", outputDir); args.put("numConsumers", "1"); args.put("maxAliveTimeSeconds", "20");//main process loop should stop after 5 seconds BatchProcessTestExecutor ex = new BatchProcessTestExecutor(args); StreamStrings streamStrings = ex.execute(); assertEquals(1, countChildren(outputDir)); assertContains("System.out", streamStrings.getOutString()); assertContains("System.err", streamStrings.getOutString()); assertEquals(0, streamStrings.getErrString().length()); } @Test(timeout = 10000) public void testConsumersManagerInitHang() throws Exception { Path outputDir = getNewOutputDir("init_hang"); Map<String, String> args = getDefaultArgs("noisy_parsers", outputDir); args.put("numConsumers", "1"); args.put("hangOnInit", "true"); BatchProcessTestExecutor ex = new BatchProcessTestExecutor(args, "/tika-batch-config-MockConsumersBuilder.xml"); StreamStrings streamStrings = ex.execute(); assertEquals(BatchProcessDriverCLI.PROCESS_NO_RESTART_EXIT_CODE, ex.getExitValue()); assertContains("causeForTermination='CONSUMERS_MANAGER_DIDNT_INIT_IN_TIME_NO_RESTART'", streamStrings.getOutString()); } @Test(timeout = 10000) public void testConsumersManagerShutdownHang() throws Exception { Path outputDir = getNewOutputDir("shutdown_hang"); Map<String, String> args = getDefaultArgs("noisy_parsers", outputDir); args.put("numConsumers", "1"); args.put("hangOnShutdown", "true"); BatchProcessTestExecutor ex = new BatchProcessTestExecutor(args, "/tika-batch-config-MockConsumersBuilder.xml"); StreamStrings streamStrings = ex.execute(); assertEquals(BatchProcessDriverCLI.PROCESS_NO_RESTART_EXIT_CODE, ex.getExitValue()); assertContains("ConsumersManager did not shutdown within", streamStrings.getOutString()); } @Test public void testHierarchicalWFileList() throws Exception { //tests to make sure that hierarchy is maintained when reading from //file list //also tests that list actually works. Path outputDir = getNewOutputDir("hierarchical_file_list"); Map<String, String> args = getDefaultArgs("hierarchical", outputDir); args.put("numConsumers", "1"); args.put("fileList", Paths.get(this.getClass().getResource("/testFileList.txt").toURI()).toString()); args.put("recursiveParserWrapper", "true"); args.put("basicHandlerType", "text"); BatchProcessTestExecutor ex = new BatchProcessTestExecutor(args, "/tika-batch-config-MockConsumersBuilder.xml"); ex.execute(); Path test1 = outputDir.resolve("test1.xml.json"); Path test2 = outputDir.resolve("sub1a/test2.xml.json"); Path test3 = outputDir.resolve("sub1a/sub2a/test3.xml.json"); assertTrue("test1 exists", Files.exists(test1)); assertTrue("test1 length > 10", Files.size(test1) > 10); assertTrue(Files.exists(test3) && Files.size(test3) > 10); Path test2Dir = outputDir.resolve("sub1a"); //should be just the subdirectory, no actual test2 file assertEquals(1, countChildren(test2Dir)); assertFalse(Files.exists(test2)); } @Test public void testHandlingOfIllegalXMLCharsInException() throws Exception { //tests to make sure that hierarchy is maintained when reading from //file list //also tests that list actually works. Path outputDir = getNewOutputDir("illegal_xml_chars_in_exception"); Map<String, String> args = getDefaultArgs("illegal_xml_chars_in_exception", outputDir); args.put("numConsumers", "1"); args.put("recursiveParserWrapper", "true"); args.put("basicHandlerType", "text"); BatchProcessTestExecutor ex = new BatchProcessTestExecutor(args, "/tika-batch-config-MockConsumersBuilder.xml", "/log4j-on.properties"); StreamStrings ss = ex.execute(); assertFalse(ss.getOutString().contains("error writing xml stream for")); assertContains("parse_ex resourceId=\"test0_bad_chars.xml\"", ss.getOutString()); } @Test public void testOverrideOutputSuffix() throws Exception { Path outputDir = getNewOutputDir("outputSuffixTest"); Map<String, String> args = getDefaultArgs("basic", outputDir); args.put("numConsumers", "1"); args.put("recursiveParserWrapper", "true"); args.put("basicHandlerType", "text"); BatchProcessTestExecutor ex = new BatchProcessTestExecutor(args, "/tika-batch-config-test-suffix-override.xml", "/log4j-on.properties"); ex.execute(); Path targ = outputDir.resolve("test0.xml.mysuffix"); assertTrue(Files.isRegularFile(targ)); } private class BatchProcessTestExecutor { private final Map<String, String> args; private final String configPath; private final String loggerProps; private int exitValue = Integer.MIN_VALUE; public BatchProcessTestExecutor(Map<String, String> args) { this(args, "/tika-batch-config-test.xml"); } public BatchProcessTestExecutor(Map<String, String> args, String configPath) { this(args, configPath, "/log4j_process.properties"); } public BatchProcessTestExecutor(Map<String, String> args, String configPath, String loggerProps) { this.args = args; this.configPath = configPath; this.loggerProps = loggerProps; } private StreamStrings execute() { Process p = null; try { ProcessBuilder b = getNewBatchRunnerProcess(configPath, loggerProps, args); p = b.start(); StringStreamGobbler errorGobbler = new StringStreamGobbler(p.getErrorStream()); StringStreamGobbler outGobbler = new StringStreamGobbler(p.getInputStream()); Thread errorThread = new Thread(errorGobbler); Thread outThread = new Thread(outGobbler); errorThread.start(); outThread.start(); while (true) { try { exitValue = p.exitValue(); break; } catch (IllegalThreadStateException e) { //still going; } } errorGobbler.stopGobblingAndDie(); outGobbler.stopGobblingAndDie(); errorThread.interrupt(); outThread.interrupt(); return new StreamStrings(outGobbler.toString(), errorGobbler.toString()); } catch (IOException e) { fail(); } finally { destroyProcess(p); } return null; } private int getExitValue() { return exitValue; } } private class StreamStrings { private final String outString; private final String errString; private StreamStrings(String outString, String errString) { this.outString = outString; this.errString = errString; } private String getOutString() { return outString; } private String getErrString() { return errString; } @Override public String toString() { return "OUT>>"+outString+"<<\n"+ "ERR>>"+errString+"<<\n"; } } }
{ "content_hash": "f7c6d0b6546c91b2cf48a79e7af5142e", "timestamp": "", "source": "github", "line_count": 398, "max_line_length": 126, "avg_line_length": 43.163316582914575, "alnum_prop": 0.6512020490133302, "repo_name": "icirellik/tika", "id": "d623afb9f748554986969dab6aedc9176bf7ad5b", "size": "17980", "binary": false, "copies": "3", "ref": "refs/heads/master", "path": "tika-batch/src/test/java/org/apache/tika/batch/fs/BatchProcessTest.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "C", "bytes": "145" }, { "name": "C++", "bytes": "171" }, { "name": "CSS", "bytes": "1363" }, { "name": "Groovy", "bytes": "4400" }, { "name": "HTML", "bytes": "180150" }, { "name": "Java", "bytes": "6226178" }, { "name": "JavaScript", "bytes": "4417" }, { "name": "Matlab", "bytes": "19803" }, { "name": "Python", "bytes": "34010" }, { "name": "SAS", "bytes": "576" }, { "name": "Shell", "bytes": "1460" }, { "name": "TeX", "bytes": "1124" }, { "name": "XSLT", "bytes": "252" } ], "symlink_target": "" }
"""Metrics to assess performance on regression task. Functions named as ``*_score`` return a scalar value to maximize: the higher the better. Function named as ``*_error`` or ``*_loss`` return a scalar value to minimize: the lower the better. """ # Authors: Alexandre Gramfort <alexandre.gramfort@inria.fr> # Mathieu Blondel <mathieu@mblondel.org> # Olivier Grisel <olivier.grisel@ensta.org> # Arnaud Joly <a.joly@ulg.ac.be> # Jochen Wersdorfer <jochen@wersdoerfer.de> # Lars Buitinck # Joel Nothman <joel.nothman@gmail.com> # Karan Desai <karandesai281196@gmail.com> # Noel Dawe <noel@dawe.me> # Manoj Kumar <manojkumarsivaraj334@gmail.com> # Michael Eickenberg <michael.eickenberg@gmail.com> # Konstantin Shmelkov <konstantin.shmelkov@polytechnique.edu> # Christian Lorentzen <lorentzen.ch@googlemail.com> # Ashutosh Hathidara <ashutoshhathidara98@gmail.com> # Uttam kumar <bajiraouttamsinha@gmail.com> # License: BSD 3 clause import warnings import numpy as np from .._loss.glm_distribution import TweedieDistribution from ..exceptions import UndefinedMetricWarning from ..utils.validation import ( check_array, check_consistent_length, _num_samples, column_or_1d, _check_sample_weight, _deprecate_positional_args, ) from ..utils.stats import _weighted_percentile __ALL__ = [ "max_error", "mean_absolute_error", "mean_squared_error", "mean_squared_log_error", "median_absolute_error", "mean_absolute_percentage_error", "mean_pinball_loss", "r2_score", "explained_variance_score", "mean_tweedie_deviance", "mean_poisson_deviance", "mean_gamma_deviance", ] def _check_reg_targets(y_true, y_pred, multioutput, dtype="numeric"): """Check that y_true and y_pred belong to the same regression task. Parameters ---------- y_true : array-like y_pred : array-like multioutput : array-like or string in ['raw_values', uniform_average', 'variance_weighted'] or None None is accepted due to backward compatibility of r2_score(). Returns ------- type_true : one of {'continuous', continuous-multioutput'} The type of the true target data, as output by 'utils.multiclass.type_of_target'. y_true : array-like of shape (n_samples, n_outputs) Ground truth (correct) target values. y_pred : array-like of shape (n_samples, n_outputs) Estimated target values. multioutput : array-like of shape (n_outputs) or string in ['raw_values', uniform_average', 'variance_weighted'] or None Custom output weights if ``multioutput`` is array-like or just the corresponding argument if ``multioutput`` is a correct keyword. dtype : str or list, default="numeric" the dtype argument passed to check_array. """ check_consistent_length(y_true, y_pred) y_true = check_array(y_true, ensure_2d=False, dtype=dtype) y_pred = check_array(y_pred, ensure_2d=False, dtype=dtype) if y_true.ndim == 1: y_true = y_true.reshape((-1, 1)) if y_pred.ndim == 1: y_pred = y_pred.reshape((-1, 1)) if y_true.shape[1] != y_pred.shape[1]: raise ValueError( "y_true and y_pred have different number of output ({0}!={1})".format( y_true.shape[1], y_pred.shape[1] ) ) n_outputs = y_true.shape[1] allowed_multioutput_str = ("raw_values", "uniform_average", "variance_weighted") if isinstance(multioutput, str): if multioutput not in allowed_multioutput_str: raise ValueError( "Allowed 'multioutput' string values are {}. " "You provided multioutput={!r}".format( allowed_multioutput_str, multioutput ) ) elif multioutput is not None: multioutput = check_array(multioutput, ensure_2d=False) if n_outputs == 1: raise ValueError("Custom weights are useful only in multi-output cases.") elif n_outputs != len(multioutput): raise ValueError( "There must be equally many custom weights (%d) as outputs (%d)." % (len(multioutput), n_outputs) ) y_type = "continuous" if n_outputs == 1 else "continuous-multioutput" return y_type, y_true, y_pred, multioutput def mean_absolute_error( y_true, y_pred, *, sample_weight=None, multioutput="uniform_average" ): """Mean absolute error regression loss. Read more in the :ref:`User Guide <mean_absolute_error>`. Parameters ---------- y_true : array-like of shape (n_samples,) or (n_samples, n_outputs) Ground truth (correct) target values. y_pred : array-like of shape (n_samples,) or (n_samples, n_outputs) Estimated target values. sample_weight : array-like of shape (n_samples,), default=None Sample weights. multioutput : {'raw_values', 'uniform_average'} or array-like of shape \ (n_outputs,), default='uniform_average' Defines aggregating of multiple output values. Array-like value defines weights used to average errors. 'raw_values' : Returns a full set of errors in case of multioutput input. 'uniform_average' : Errors of all outputs are averaged with uniform weight. Returns ------- loss : float or ndarray of floats If multioutput is 'raw_values', then mean absolute error is returned for each output separately. If multioutput is 'uniform_average' or an ndarray of weights, then the weighted average of all output errors is returned. MAE output is non-negative floating point. The best value is 0.0. Examples -------- >>> from sklearn.metrics import mean_absolute_error >>> y_true = [3, -0.5, 2, 7] >>> y_pred = [2.5, 0.0, 2, 8] >>> mean_absolute_error(y_true, y_pred) 0.5 >>> y_true = [[0.5, 1], [-1, 1], [7, -6]] >>> y_pred = [[0, 2], [-1, 2], [8, -5]] >>> mean_absolute_error(y_true, y_pred) 0.75 >>> mean_absolute_error(y_true, y_pred, multioutput='raw_values') array([0.5, 1. ]) >>> mean_absolute_error(y_true, y_pred, multioutput=[0.3, 0.7]) 0.85... """ y_type, y_true, y_pred, multioutput = _check_reg_targets( y_true, y_pred, multioutput ) check_consistent_length(y_true, y_pred, sample_weight) output_errors = np.average(np.abs(y_pred - y_true), weights=sample_weight, axis=0) if isinstance(multioutput, str): if multioutput == "raw_values": return output_errors elif multioutput == "uniform_average": # pass None as weights to np.average: uniform mean multioutput = None return np.average(output_errors, weights=multioutput) def mean_pinball_loss( y_true, y_pred, *, sample_weight=None, alpha=0.5, multioutput="uniform_average" ): """Pinball loss for quantile regression. Read more in the :ref:`User Guide <pinball_loss>`. Parameters ---------- y_true : array-like of shape (n_samples,) or (n_samples, n_outputs) Ground truth (correct) target values. y_pred : array-like of shape (n_samples,) or (n_samples, n_outputs) Estimated target values. sample_weight : array-like of shape (n_samples,), default=None Sample weights. alpha: float, slope of the pinball loss, default=0.5, this loss is equivalent to :ref:`mean_absolute_error` when `alpha=0.5`, `alpha=0.95` is minimized by estimators of the 95th percentile. multioutput : {'raw_values', 'uniform_average'} or array-like of shape \ (n_outputs,), default='uniform_average' Defines aggregating of multiple output values. Array-like value defines weights used to average errors. 'raw_values' : Returns a full set of errors in case of multioutput input. 'uniform_average' : Errors of all outputs are averaged with uniform weight. Returns ------- loss : float or ndarray of floats If multioutput is 'raw_values', then mean absolute error is returned for each output separately. If multioutput is 'uniform_average' or an ndarray of weights, then the weighted average of all output errors is returned. The pinball loss output is a non-negative floating point. The best value is 0.0. Examples -------- >>> from sklearn.metrics import mean_pinball_loss >>> y_true = [1, 2, 3] >>> mean_pinball_loss(y_true, [0, 2, 3], alpha=0.1) 0.03... >>> mean_pinball_loss(y_true, [1, 2, 4], alpha=0.1) 0.3... >>> mean_pinball_loss(y_true, [0, 2, 3], alpha=0.9) 0.3... >>> mean_pinball_loss(y_true, [1, 2, 4], alpha=0.9) 0.03... >>> mean_pinball_loss(y_true, y_true, alpha=0.1) 0.0 >>> mean_pinball_loss(y_true, y_true, alpha=0.9) 0.0 """ y_type, y_true, y_pred, multioutput = _check_reg_targets( y_true, y_pred, multioutput ) check_consistent_length(y_true, y_pred, sample_weight) diff = y_true - y_pred sign = (diff >= 0).astype(diff.dtype) loss = alpha * sign * diff - (1 - alpha) * (1 - sign) * diff output_errors = np.average(loss, weights=sample_weight, axis=0) if isinstance(multioutput, str): if multioutput == "raw_values": return output_errors elif multioutput == "uniform_average": # pass None as weights to np.average: uniform mean multioutput = None else: raise ValueError( "multioutput is expected to be 'raw_values' " "or 'uniform_average' but we got %r" " instead." % multioutput ) return np.average(output_errors, weights=multioutput) @_deprecate_positional_args(version="1.1") def mean_absolute_percentage_error( y_true, y_pred, *, sample_weight=None, multioutput="uniform_average" ): """Mean absolute percentage error (MAPE) regression loss. Note here that the output is not a percentage in the range [0, 100] and a value of 100 does not mean 100% but 1e2. Furthermore, the output can be arbitrarily high when `y_true` is small (which is specific to the metric) or when `abs(y_true - y_pred)` is large (which is common for most regression metrics). Read more in the :ref:`User Guide <mean_absolute_percentage_error>`. .. versionadded:: 0.24 Parameters ---------- y_true : array-like of shape (n_samples,) or (n_samples, n_outputs) Ground truth (correct) target values. y_pred : array-like of shape (n_samples,) or (n_samples, n_outputs) Estimated target values. sample_weight : array-like of shape (n_samples,), default=None Sample weights. multioutput : {'raw_values', 'uniform_average'} or array-like Defines aggregating of multiple output values. Array-like value defines weights used to average errors. If input is list then the shape must be (n_outputs,). 'raw_values' : Returns a full set of errors in case of multioutput input. 'uniform_average' : Errors of all outputs are averaged with uniform weight. Returns ------- loss : float or ndarray of floats If multioutput is 'raw_values', then mean absolute percentage error is returned for each output separately. If multioutput is 'uniform_average' or an ndarray of weights, then the weighted average of all output errors is returned. MAPE output is non-negative floating point. The best value is 0.0. But note that bad predictions can lead to arbitrarily large MAPE values, especially if some `y_true` values are very close to zero. Note that we return a large value instead of `inf` when `y_true` is zero. Examples -------- >>> from sklearn.metrics import mean_absolute_percentage_error >>> y_true = [3, -0.5, 2, 7] >>> y_pred = [2.5, 0.0, 2, 8] >>> mean_absolute_percentage_error(y_true, y_pred) 0.3273... >>> y_true = [[0.5, 1], [-1, 1], [7, -6]] >>> y_pred = [[0, 2], [-1, 2], [8, -5]] >>> mean_absolute_percentage_error(y_true, y_pred) 0.5515... >>> mean_absolute_percentage_error(y_true, y_pred, multioutput=[0.3, 0.7]) 0.6198... >>> # the value when some element of the y_true is zero is arbitrarily high because >>> # of the division by epsilon >>> y_true = [1., 0., 2.4, 7.] >>> y_pred = [1.2, 0.1, 2.4, 8.] >>> mean_absolute_percentage_error(y_true, y_pred) 112589990684262.48 """ y_type, y_true, y_pred, multioutput = _check_reg_targets( y_true, y_pred, multioutput ) check_consistent_length(y_true, y_pred, sample_weight) epsilon = np.finfo(np.float64).eps mape = np.abs(y_pred - y_true) / np.maximum(np.abs(y_true), epsilon) output_errors = np.average(mape, weights=sample_weight, axis=0) if isinstance(multioutput, str): if multioutput == "raw_values": return output_errors elif multioutput == "uniform_average": # pass None as weights to np.average: uniform mean multioutput = None return np.average(output_errors, weights=multioutput) def mean_squared_error( y_true, y_pred, *, sample_weight=None, multioutput="uniform_average", squared=True ): """Mean squared error regression loss. Read more in the :ref:`User Guide <mean_squared_error>`. Parameters ---------- y_true : array-like of shape (n_samples,) or (n_samples, n_outputs) Ground truth (correct) target values. y_pred : array-like of shape (n_samples,) or (n_samples, n_outputs) Estimated target values. sample_weight : array-like of shape (n_samples,), default=None Sample weights. multioutput : {'raw_values', 'uniform_average'} or array-like of shape \ (n_outputs,), default='uniform_average' Defines aggregating of multiple output values. Array-like value defines weights used to average errors. 'raw_values' : Returns a full set of errors in case of multioutput input. 'uniform_average' : Errors of all outputs are averaged with uniform weight. squared : bool, default=True If True returns MSE value, if False returns RMSE value. Returns ------- loss : float or ndarray of floats A non-negative floating point value (the best value is 0.0), or an array of floating point values, one for each individual target. Examples -------- >>> from sklearn.metrics import mean_squared_error >>> y_true = [3, -0.5, 2, 7] >>> y_pred = [2.5, 0.0, 2, 8] >>> mean_squared_error(y_true, y_pred) 0.375 >>> y_true = [3, -0.5, 2, 7] >>> y_pred = [2.5, 0.0, 2, 8] >>> mean_squared_error(y_true, y_pred, squared=False) 0.612... >>> y_true = [[0.5, 1],[-1, 1],[7, -6]] >>> y_pred = [[0, 2],[-1, 2],[8, -5]] >>> mean_squared_error(y_true, y_pred) 0.708... >>> mean_squared_error(y_true, y_pred, squared=False) 0.822... >>> mean_squared_error(y_true, y_pred, multioutput='raw_values') array([0.41666667, 1. ]) >>> mean_squared_error(y_true, y_pred, multioutput=[0.3, 0.7]) 0.825... """ y_type, y_true, y_pred, multioutput = _check_reg_targets( y_true, y_pred, multioutput ) check_consistent_length(y_true, y_pred, sample_weight) output_errors = np.average((y_true - y_pred) ** 2, axis=0, weights=sample_weight) if not squared: output_errors = np.sqrt(output_errors) if isinstance(multioutput, str): if multioutput == "raw_values": return output_errors elif multioutput == "uniform_average": # pass None as weights to np.average: uniform mean multioutput = None return np.average(output_errors, weights=multioutput) def mean_squared_log_error( y_true, y_pred, *, sample_weight=None, multioutput="uniform_average", squared=True ): """Mean squared logarithmic error regression loss. Read more in the :ref:`User Guide <mean_squared_log_error>`. Parameters ---------- y_true : array-like of shape (n_samples,) or (n_samples, n_outputs) Ground truth (correct) target values. y_pred : array-like of shape (n_samples,) or (n_samples, n_outputs) Estimated target values. sample_weight : array-like of shape (n_samples,), default=None Sample weights. multioutput : {'raw_values', 'uniform_average'} or array-like of shape \ (n_outputs,), default='uniform_average' Defines aggregating of multiple output values. Array-like value defines weights used to average errors. 'raw_values' : Returns a full set of errors when the input is of multioutput format. 'uniform_average' : Errors of all outputs are averaged with uniform weight. squared : bool, default=True If True returns MSLE (mean squared log error) value. If False returns RMSLE (root mean squared log error) value. Returns ------- loss : float or ndarray of floats A non-negative floating point value (the best value is 0.0), or an array of floating point values, one for each individual target. Examples -------- >>> from sklearn.metrics import mean_squared_log_error >>> y_true = [3, 5, 2.5, 7] >>> y_pred = [2.5, 5, 4, 8] >>> mean_squared_log_error(y_true, y_pred) 0.039... >>> mean_squared_log_error(y_true, y_pred, squared=False) 0.199... >>> y_true = [[0.5, 1], [1, 2], [7, 6]] >>> y_pred = [[0.5, 2], [1, 2.5], [8, 8]] >>> mean_squared_log_error(y_true, y_pred) 0.044... >>> mean_squared_log_error(y_true, y_pred, multioutput='raw_values') array([0.00462428, 0.08377444]) >>> mean_squared_log_error(y_true, y_pred, multioutput=[0.3, 0.7]) 0.060... """ y_type, y_true, y_pred, multioutput = _check_reg_targets( y_true, y_pred, multioutput ) check_consistent_length(y_true, y_pred, sample_weight) if (y_true < 0).any() or (y_pred < 0).any(): raise ValueError( "Mean Squared Logarithmic Error cannot be used when " "targets contain negative values." ) return mean_squared_error( np.log1p(y_true), np.log1p(y_pred), sample_weight=sample_weight, multioutput=multioutput, squared=squared, ) def median_absolute_error( y_true, y_pred, *, multioutput="uniform_average", sample_weight=None ): """Median absolute error regression loss. Median absolute error output is non-negative floating point. The best value is 0.0. Read more in the :ref:`User Guide <median_absolute_error>`. Parameters ---------- y_true : array-like of shape = (n_samples) or (n_samples, n_outputs) Ground truth (correct) target values. y_pred : array-like of shape = (n_samples) or (n_samples, n_outputs) Estimated target values. multioutput : {'raw_values', 'uniform_average'} or array-like of shape \ (n_outputs,), default='uniform_average' Defines aggregating of multiple output values. Array-like value defines weights used to average errors. 'raw_values' : Returns a full set of errors in case of multioutput input. 'uniform_average' : Errors of all outputs are averaged with uniform weight. sample_weight : array-like of shape (n_samples,), default=None Sample weights. .. versionadded:: 0.24 Returns ------- loss : float or ndarray of floats If multioutput is 'raw_values', then mean absolute error is returned for each output separately. If multioutput is 'uniform_average' or an ndarray of weights, then the weighted average of all output errors is returned. Examples -------- >>> from sklearn.metrics import median_absolute_error >>> y_true = [3, -0.5, 2, 7] >>> y_pred = [2.5, 0.0, 2, 8] >>> median_absolute_error(y_true, y_pred) 0.5 >>> y_true = [[0.5, 1], [-1, 1], [7, -6]] >>> y_pred = [[0, 2], [-1, 2], [8, -5]] >>> median_absolute_error(y_true, y_pred) 0.75 >>> median_absolute_error(y_true, y_pred, multioutput='raw_values') array([0.5, 1. ]) >>> median_absolute_error(y_true, y_pred, multioutput=[0.3, 0.7]) 0.85 """ y_type, y_true, y_pred, multioutput = _check_reg_targets( y_true, y_pred, multioutput ) if sample_weight is None: output_errors = np.median(np.abs(y_pred - y_true), axis=0) else: sample_weight = _check_sample_weight(sample_weight, y_pred) output_errors = _weighted_percentile( np.abs(y_pred - y_true), sample_weight=sample_weight ) if isinstance(multioutput, str): if multioutput == "raw_values": return output_errors elif multioutput == "uniform_average": # pass None as weights to np.average: uniform mean multioutput = None return np.average(output_errors, weights=multioutput) def explained_variance_score( y_true, y_pred, *, sample_weight=None, multioutput="uniform_average" ): """Explained variance regression score function. Best possible score is 1.0, lower values are worse. Read more in the :ref:`User Guide <explained_variance_score>`. Parameters ---------- y_true : array-like of shape (n_samples,) or (n_samples, n_outputs) Ground truth (correct) target values. y_pred : array-like of shape (n_samples,) or (n_samples, n_outputs) Estimated target values. sample_weight : array-like of shape (n_samples,), default=None Sample weights. multioutput : {'raw_values', 'uniform_average', 'variance_weighted'} or \ array-like of shape (n_outputs,), default='uniform_average' Defines aggregating of multiple output scores. Array-like value defines weights used to average scores. 'raw_values' : Returns a full set of scores in case of multioutput input. 'uniform_average' : Scores of all outputs are averaged with uniform weight. 'variance_weighted' : Scores of all outputs are averaged, weighted by the variances of each individual output. Returns ------- score : float or ndarray of floats The explained variance or ndarray if 'multioutput' is 'raw_values'. Notes ----- This is not a symmetric function. Examples -------- >>> from sklearn.metrics import explained_variance_score >>> y_true = [3, -0.5, 2, 7] >>> y_pred = [2.5, 0.0, 2, 8] >>> explained_variance_score(y_true, y_pred) 0.957... >>> y_true = [[0.5, 1], [-1, 1], [7, -6]] >>> y_pred = [[0, 2], [-1, 2], [8, -5]] >>> explained_variance_score(y_true, y_pred, multioutput='uniform_average') 0.983... """ y_type, y_true, y_pred, multioutput = _check_reg_targets( y_true, y_pred, multioutput ) check_consistent_length(y_true, y_pred, sample_weight) y_diff_avg = np.average(y_true - y_pred, weights=sample_weight, axis=0) numerator = np.average( (y_true - y_pred - y_diff_avg) ** 2, weights=sample_weight, axis=0 ) y_true_avg = np.average(y_true, weights=sample_weight, axis=0) denominator = np.average((y_true - y_true_avg) ** 2, weights=sample_weight, axis=0) nonzero_numerator = numerator != 0 nonzero_denominator = denominator != 0 valid_score = nonzero_numerator & nonzero_denominator output_scores = np.ones(y_true.shape[1]) output_scores[valid_score] = 1 - (numerator[valid_score] / denominator[valid_score]) output_scores[nonzero_numerator & ~nonzero_denominator] = 0.0 if isinstance(multioutput, str): if multioutput == "raw_values": # return scores individually return output_scores elif multioutput == "uniform_average": # passing to np.average() None as weights results is uniform mean avg_weights = None elif multioutput == "variance_weighted": avg_weights = denominator else: avg_weights = multioutput return np.average(output_scores, weights=avg_weights) def r2_score(y_true, y_pred, *, sample_weight=None, multioutput="uniform_average"): """:math:`R^2` (coefficient of determination) regression score function. Best possible score is 1.0 and it can be negative (because the model can be arbitrarily worse). A constant model that always predicts the expected value of y, disregarding the input features, would get a :math:`R^2` score of 0.0. Read more in the :ref:`User Guide <r2_score>`. Parameters ---------- y_true : array-like of shape (n_samples,) or (n_samples, n_outputs) Ground truth (correct) target values. y_pred : array-like of shape (n_samples,) or (n_samples, n_outputs) Estimated target values. sample_weight : array-like of shape (n_samples,), default=None Sample weights. multioutput : {'raw_values', 'uniform_average', 'variance_weighted'}, \ array-like of shape (n_outputs,) or None, default='uniform_average' Defines aggregating of multiple output scores. Array-like value defines weights used to average scores. Default is "uniform_average". 'raw_values' : Returns a full set of scores in case of multioutput input. 'uniform_average' : Scores of all outputs are averaged with uniform weight. 'variance_weighted' : Scores of all outputs are averaged, weighted by the variances of each individual output. .. versionchanged:: 0.19 Default value of multioutput is 'uniform_average'. Returns ------- z : float or ndarray of floats The :math:`R^2` score or ndarray of scores if 'multioutput' is 'raw_values'. Notes ----- This is not a symmetric function. Unlike most other scores, :math:`R^2` score may be negative (it need not actually be the square of a quantity R). This metric is not well-defined for single samples and will return a NaN value if n_samples is less than two. References ---------- .. [1] `Wikipedia entry on the Coefficient of determination <https://en.wikipedia.org/wiki/Coefficient_of_determination>`_ Examples -------- >>> from sklearn.metrics import r2_score >>> y_true = [3, -0.5, 2, 7] >>> y_pred = [2.5, 0.0, 2, 8] >>> r2_score(y_true, y_pred) 0.948... >>> y_true = [[0.5, 1], [-1, 1], [7, -6]] >>> y_pred = [[0, 2], [-1, 2], [8, -5]] >>> r2_score(y_true, y_pred, ... multioutput='variance_weighted') 0.938... >>> y_true = [1, 2, 3] >>> y_pred = [1, 2, 3] >>> r2_score(y_true, y_pred) 1.0 >>> y_true = [1, 2, 3] >>> y_pred = [2, 2, 2] >>> r2_score(y_true, y_pred) 0.0 >>> y_true = [1, 2, 3] >>> y_pred = [3, 2, 1] >>> r2_score(y_true, y_pred) -3.0 """ y_type, y_true, y_pred, multioutput = _check_reg_targets( y_true, y_pred, multioutput ) check_consistent_length(y_true, y_pred, sample_weight) if _num_samples(y_pred) < 2: msg = "R^2 score is not well-defined with less than two samples." warnings.warn(msg, UndefinedMetricWarning) return float("nan") if sample_weight is not None: sample_weight = column_or_1d(sample_weight) weight = sample_weight[:, np.newaxis] else: weight = 1.0 numerator = (weight * (y_true - y_pred) ** 2).sum(axis=0, dtype=np.float64) denominator = ( weight * (y_true - np.average(y_true, axis=0, weights=sample_weight)) ** 2 ).sum(axis=0, dtype=np.float64) nonzero_denominator = denominator != 0 nonzero_numerator = numerator != 0 valid_score = nonzero_denominator & nonzero_numerator output_scores = np.ones([y_true.shape[1]]) output_scores[valid_score] = 1 - (numerator[valid_score] / denominator[valid_score]) # arbitrary set to zero to avoid -inf scores, having a constant # y_true is not interesting for scoring a regression anyway output_scores[nonzero_numerator & ~nonzero_denominator] = 0.0 if isinstance(multioutput, str): if multioutput == "raw_values": # return scores individually return output_scores elif multioutput == "uniform_average": # passing None as weights results is uniform mean avg_weights = None elif multioutput == "variance_weighted": avg_weights = denominator # avoid fail on constant y or one-element arrays if not np.any(nonzero_denominator): if not np.any(nonzero_numerator): return 1.0 else: return 0.0 else: avg_weights = multioutput return np.average(output_scores, weights=avg_weights) def max_error(y_true, y_pred): """ The max_error metric calculates the maximum residual error. Read more in the :ref:`User Guide <max_error>`. Parameters ---------- y_true : array-like of shape (n_samples,) Ground truth (correct) target values. y_pred : array-like of shape (n_samples,) Estimated target values. Returns ------- max_error : float A positive floating point value (the best value is 0.0). Examples -------- >>> from sklearn.metrics import max_error >>> y_true = [3, 2, 7, 1] >>> y_pred = [4, 2, 7, 1] >>> max_error(y_true, y_pred) 1 """ y_type, y_true, y_pred, _ = _check_reg_targets(y_true, y_pred, None) if y_type == "continuous-multioutput": raise ValueError("Multioutput not supported in max_error") return np.max(np.abs(y_true - y_pred)) def mean_tweedie_deviance(y_true, y_pred, *, sample_weight=None, power=0): """Mean Tweedie deviance regression loss. Read more in the :ref:`User Guide <mean_tweedie_deviance>`. Parameters ---------- y_true : array-like of shape (n_samples,) Ground truth (correct) target values. y_pred : array-like of shape (n_samples,) Estimated target values. sample_weight : array-like of shape (n_samples,), default=None Sample weights. power : float, default=0 Tweedie power parameter. Either power <= 0 or power >= 1. The higher `p` the less weight is given to extreme deviations between true and predicted targets. - power < 0: Extreme stable distribution. Requires: y_pred > 0. - power = 0 : Normal distribution, output corresponds to mean_squared_error. y_true and y_pred can be any real numbers. - power = 1 : Poisson distribution. Requires: y_true >= 0 and y_pred > 0. - 1 < p < 2 : Compound Poisson distribution. Requires: y_true >= 0 and y_pred > 0. - power = 2 : Gamma distribution. Requires: y_true > 0 and y_pred > 0. - power = 3 : Inverse Gaussian distribution. Requires: y_true > 0 and y_pred > 0. - otherwise : Positive stable distribution. Requires: y_true > 0 and y_pred > 0. Returns ------- loss : float A non-negative floating point value (the best value is 0.0). Examples -------- >>> from sklearn.metrics import mean_tweedie_deviance >>> y_true = [2, 0, 1, 4] >>> y_pred = [0.5, 0.5, 2., 2.] >>> mean_tweedie_deviance(y_true, y_pred, power=1) 1.4260... """ y_type, y_true, y_pred, _ = _check_reg_targets( y_true, y_pred, None, dtype=[np.float64, np.float32] ) if y_type == "continuous-multioutput": raise ValueError("Multioutput not supported in mean_tweedie_deviance") check_consistent_length(y_true, y_pred, sample_weight) if sample_weight is not None: sample_weight = column_or_1d(sample_weight) sample_weight = sample_weight[:, np.newaxis] dist = TweedieDistribution(power=power) dev = dist.unit_deviance(y_true, y_pred, check_input=True) return np.average(dev, weights=sample_weight) def mean_poisson_deviance(y_true, y_pred, *, sample_weight=None): """Mean Poisson deviance regression loss. Poisson deviance is equivalent to the Tweedie deviance with the power parameter `power=1`. Read more in the :ref:`User Guide <mean_tweedie_deviance>`. Parameters ---------- y_true : array-like of shape (n_samples,) Ground truth (correct) target values. Requires y_true >= 0. y_pred : array-like of shape (n_samples,) Estimated target values. Requires y_pred > 0. sample_weight : array-like of shape (n_samples,), default=None Sample weights. Returns ------- loss : float A non-negative floating point value (the best value is 0.0). Examples -------- >>> from sklearn.metrics import mean_poisson_deviance >>> y_true = [2, 0, 1, 4] >>> y_pred = [0.5, 0.5, 2., 2.] >>> mean_poisson_deviance(y_true, y_pred) 1.4260... """ return mean_tweedie_deviance(y_true, y_pred, sample_weight=sample_weight, power=1) def mean_gamma_deviance(y_true, y_pred, *, sample_weight=None): """Mean Gamma deviance regression loss. Gamma deviance is equivalent to the Tweedie deviance with the power parameter `power=2`. It is invariant to scaling of the target variable, and measures relative errors. Read more in the :ref:`User Guide <mean_tweedie_deviance>`. Parameters ---------- y_true : array-like of shape (n_samples,) Ground truth (correct) target values. Requires y_true > 0. y_pred : array-like of shape (n_samples,) Estimated target values. Requires y_pred > 0. sample_weight : array-like of shape (n_samples,), default=None Sample weights. Returns ------- loss : float A non-negative floating point value (the best value is 0.0). Examples -------- >>> from sklearn.metrics import mean_gamma_deviance >>> y_true = [2, 0.5, 1, 4] >>> y_pred = [0.5, 0.5, 2., 2.] >>> mean_gamma_deviance(y_true, y_pred) 1.0568... """ return mean_tweedie_deviance(y_true, y_pred, sample_weight=sample_weight, power=2) def d2_tweedie_score(y_true, y_pred, *, sample_weight=None, power=0): """D^2 regression score function, percentage of Tweedie deviance explained. Best possible score is 1.0 and it can be negative (because the model can be arbitrarily worse). A model that always uses the empirical mean of `y_true` as constant prediction, disregarding the input features, gets a D^2 score of 0.0. Read more in the :ref:`User Guide <d2_tweedie_score>`. .. versionadded:: 1.0 Parameters ---------- y_true : array-like of shape (n_samples,) Ground truth (correct) target values. y_pred : array-like of shape (n_samples,) Estimated target values. sample_weight : array-like of shape (n_samples,), optional Sample weights. power : float, default=0 Tweedie power parameter. Either power <= 0 or power >= 1. The higher `p` the less weight is given to extreme deviations between true and predicted targets. - power < 0: Extreme stable distribution. Requires: y_pred > 0. - power = 0 : Normal distribution, output corresponds to r2_score. y_true and y_pred can be any real numbers. - power = 1 : Poisson distribution. Requires: y_true >= 0 and y_pred > 0. - 1 < p < 2 : Compound Poisson distribution. Requires: y_true >= 0 and y_pred > 0. - power = 2 : Gamma distribution. Requires: y_true > 0 and y_pred > 0. - power = 3 : Inverse Gaussian distribution. Requires: y_true > 0 and y_pred > 0. - otherwise : Positive stable distribution. Requires: y_true > 0 and y_pred > 0. Returns ------- z : float or ndarray of floats The D^2 score. Notes ----- This is not a symmetric function. Like R^2, D^2 score may be negative (it need not actually be the square of a quantity D). This metric is not well-defined for single samples and will return a NaN value if n_samples is less than two. References ---------- .. [1] Eq. (3.11) of Hastie, Trevor J., Robert Tibshirani and Martin J. Wainwright. "Statistical Learning with Sparsity: The Lasso and Generalizations." (2015). https://trevorhastie.github.io Examples -------- >>> from sklearn.metrics import d2_tweedie_score >>> y_true = [0.5, 1, 2.5, 7] >>> y_pred = [1, 1, 5, 3.5] >>> d2_tweedie_score(y_true, y_pred) 0.285... >>> d2_tweedie_score(y_true, y_pred, power=1) 0.487... >>> d2_tweedie_score(y_true, y_pred, power=2) 0.630... >>> d2_tweedie_score(y_true, y_true, power=2) 1.0 """ y_type, y_true, y_pred, _ = _check_reg_targets( y_true, y_pred, None, dtype=[np.float64, np.float32] ) if y_type == "continuous-multioutput": raise ValueError("Multioutput not supported in d2_tweedie_score") check_consistent_length(y_true, y_pred, sample_weight) if _num_samples(y_pred) < 2: msg = "D^2 score is not well-defined with less than two samples." warnings.warn(msg, UndefinedMetricWarning) return float("nan") if sample_weight is not None: sample_weight = column_or_1d(sample_weight) sample_weight = sample_weight[:, np.newaxis] dist = TweedieDistribution(power=power) dev = dist.unit_deviance(y_true, y_pred, check_input=True) numerator = np.average(dev, weights=sample_weight) y_avg = np.average(y_true, weights=sample_weight) dev = dist.unit_deviance(y_true, y_avg, check_input=True) denominator = np.average(dev, weights=sample_weight) return 1 - numerator / denominator
{ "content_hash": "a055faad58d6e3bd381010e4bd1e6764", "timestamp": "", "source": "github", "line_count": 1108, "max_line_length": 88, "avg_line_length": 34.66335740072202, "alnum_prop": 0.6139766188455229, "repo_name": "sergeyf/scikit-learn", "id": "ffa2b0b8218aaa0821d9fe1979f180295abd4f69", "size": "38407", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "sklearn/metrics/_regression.py", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "C", "bytes": "42335" }, { "name": "C++", "bytes": "147316" }, { "name": "Cython", "bytes": "718114" }, { "name": "Makefile", "bytes": "1711" }, { "name": "Python", "bytes": "9906683" }, { "name": "Shell", "bytes": "49565" } ], "symlink_target": "" }
using System; using System.Collections.Generic; using System.IO; using System.Linq; using Windows.ApplicationModel; using Windows.ApplicationModel.Activation; using Windows.Foundation; using Windows.Foundation.Collections; using Windows.UI.Xaml; using Windows.UI.Xaml.Controls; using Windows.UI.Xaml.Controls.Primitives; using Windows.UI.Xaml.Data; using Windows.UI.Xaml.Input; using Windows.UI.Xaml.Media; using Windows.UI.Xaml.Navigation; // The Blank Application template is documented at http://go.microsoft.com/fwlink/?LinkId=234227 namespace WinrtTester { /// <summary> /// Provides application-specific behavior to supplement the default Application class. /// </summary> sealed partial class App : Application { /// <summary> /// Initializes the singleton application object. This is the first line of authored code /// executed, and as such is the logical equivalent of main() or WinMain(). /// </summary> public App() { this.InitializeComponent(); this.Suspending += OnSuspending; } /// <summary> /// Invoked when the application is launched normally by the end user. Other entry points /// will be used when the application is launched to open a specific file, to display /// search results, and so forth. /// </summary> /// <param name="args">Details about the launch request and process.</param> protected override void OnLaunched(LaunchActivatedEventArgs args) { Frame rootFrame = Window.Current.Content as Frame; // Do not repeat app initialization when the Window already has content, // just ensure that the window is active if (rootFrame == null) { // Create a Frame to act as the navigation context and navigate to the first page rootFrame = new Frame(); if (args.PreviousExecutionState == ApplicationExecutionState.Terminated) { //TODO: Load state from previously suspended application } // Place the frame in the current Window Window.Current.Content = rootFrame; } if (rootFrame.Content == null) { // When the navigation stack isn't restored navigate to the first page, // configuring the new page by passing required information as a navigation // parameter if (!rootFrame.Navigate(typeof(MainPage), args.Arguments)) { throw new Exception("Failed to create initial page"); } } // Ensure the current window is active Window.Current.Activate(); } /// <summary> /// Invoked when application execution is being suspended. Application state is saved /// without knowing whether the application will be terminated or resumed with the contents /// of memory still intact. /// </summary> /// <param name="sender">The source of the suspend request.</param> /// <param name="e">Details about the suspend request.</param> private void OnSuspending(object sender, SuspendingEventArgs e) { var deferral = e.SuspendingOperation.GetDeferral(); //TODO: Save application state and stop any background activity deferral.Complete(); } } }
{ "content_hash": "042d051f393a69c9bb7bb2de5d5392e8", "timestamp": "", "source": "github", "line_count": 90, "max_line_length": 99, "avg_line_length": 39.18888888888889, "alnum_prop": 0.6200737170399773, "repo_name": "bbowyersmyth/WMF2WPF", "id": "26fa2305129e62750ca8a01c25c965d54c1bd390", "size": "3529", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "WINRT/WinrtTester/App.xaml.cs", "mode": "33188", "license": "mit", "language": [ { "name": "C#", "bytes": "169033" } ], "symlink_target": "" }
#ifndef LEPTONICA_ENVIRON_H #define LEPTONICA_ENVIRON_H /*------------------------------------------------------------------------* * Defines and includes differ for Unix and Windows. Also for Windows, * * differentiate between conditionals based on platform and compiler. * * For platforms: * * _WIN32 => Windows, 32- or 64-bit * * _WIN64 => Windows, 64-bit only * * __CYGWIN__ => Cygwin * * For compilers: * * __GNUC__ => gcc * * _MSC_VER => msvc * *------------------------------------------------------------------------*/ /* MS VC++ does not provide stdint.h, so define the missing types here */ #ifndef _MSC_VER #include <stdint.h> #else /* Note that _WIN32 is defined for both 32 and 64 bit applications, whereas _WIN64 is defined only for the latter */ #ifdef _WIN64 typedef __int64 intptr_t; typedef unsigned __int64 uintptr_t; #else typedef int intptr_t; typedef unsigned int uintptr_t; #endif /* VC++6 doesn't seem to have powf, expf. */ #if (_MSC_VER < 1400) #define powf(x, y) (float)pow((double)(x), (double)(y)) #define expf(x) (float)exp((double)(x)) #endif #endif /* _MSC_VER */ /* Windows specifics */ #ifdef _WIN32 /* DLL EXPORTS and IMPORTS: * Important: LEPTONLIB_* is deprected. It is retained here only for * compatibility with tesseract 3.00. In your project files, use * LIBLEPT_EXPORTS and LIBLEPT_IMPORTS */ #if defined(LIBLEPT_EXPORTS) || defined(LEPTONLIB_EXPORTS) #define LEPT_DLL __declspec(dllexport) #elif defined(LIBLEPT_IMPORTS) || defined(LEPTONLIB_IMPORTS) #define LEPT_DLL __declspec(dllimport) #else #define LEPT_DLL #endif #else /* non-WINDOWS-SPECIFICS */ #include <stdint.h> #define LEPT_DLL #endif /* _WIN32 */ typedef intptr_t l_intptr_t; typedef uintptr_t l_uintptr_t; typedef void *L_TIMER; /*--------------------------------------------------------------------* * !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!* * USER CONFIGURABLE * * !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!* * Environ variables with I/O libraries * * Manual Configuration Only: NOT AUTO_CONF * *--------------------------------------------------------------------*/ /* * Leptonica provides interfaces to link to five external image I/O * libraries, plus zlib. Setting any of these to 0 here causes * non-functioning stubs to be linked. */ #ifndef HAVE_CONFIG_H #define HAVE_LIBJPEG 1 #define HAVE_LIBTIFF 1 #define HAVE_LIBPNG 1 #define HAVE_LIBZ 1 #define HAVE_LIBGIF 1 #define HAVE_LIBUNGIF 0 #define HAVE_LIBWEBP 0 #endif /* ~HAVE_CONFIG_H */ /* * On linux systems, you can do I/O between Pix and memory. Specifically, * you can compress (write compressed data to memory from a Pix) and * uncompress (read from compressed data in memory to a Pix). * For jpeg, png, pnm and bmp, these use the non-posix GNU functions * fmemopen() and open_memstream(). These functions are not * available on other systems. To use these functions in linux, * you must define HAVE_FMEMOPEN to be 1 here. */ #ifndef HAVE_CONFIG_H #define HAVE_FMEMOPEN 0 #endif /* ~HAVE_CONFIG_H */ /*--------------------------------------------------------------------* * !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!* * USER CONFIGURABLE * * !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!* * Environ variables for uncompressed formatted image I/O * *--------------------------------------------------------------------*/ /* * Leptonica supplies image I/O for pnm, bmp, ps, and pdf. * Setting any of these to 0 causes non-functioning stubs to be linked. */ #define USE_BMPIO 1 #define USE_PNMIO 1 #define USE_PSIO 1 #define USE_PDFIO 1 /*--------------------------------------------------------------------* * Built-in types * *--------------------------------------------------------------------*/ typedef signed char l_int8; typedef unsigned char l_uint8; typedef short l_int16; typedef unsigned short l_uint16; typedef int l_int32; typedef unsigned int l_uint32; typedef float l_float32; typedef double l_float64; /*------------------------------------------------------------------------* * Standard macros * *------------------------------------------------------------------------*/ #ifndef L_MIN #define L_MIN(x,y) (((x) < (y)) ? (x) : (y)) #endif #ifndef L_MAX #define L_MAX(x,y) (((x) > (y)) ? (x) : (y)) #endif #ifndef L_ABS #define L_ABS(x) (((x) < 0) ? (-1 * (x)) : (x)) #endif #ifndef L_SIGN #define L_SIGN(x) (((x) < 0) ? -1 : 1) #endif #ifndef UNDEF #define UNDEF -1 #endif #ifndef NULL #define NULL 0 #endif #ifndef TRUE #define TRUE 1 #endif #ifndef FALSE #define FALSE 0 #endif /*--------------------------------------------------------------------* * Environ variables used within compiler invocation * *--------------------------------------------------------------------*/ /* * To control conditional compilation, one of two variables * * L_LITTLE_ENDIAN (e.g., for Intel X86) * L_BIG_ENDIAN (e.g., for Sun SPARC, Mac Power PC) * * is defined when the GCC compiler is invoked. * All code should compile properly for both hardware architectures. */ /*------------------------------------------------------------------------* * Simple search state variables * *------------------------------------------------------------------------*/ enum { L_NOT_FOUND = 0, L_FOUND = 1 }; /*------------------------------------------------------------------------* * Standard memory allocation * * * These specify the memory management functions that are used * on all heap data except for Pix. Memory management for Pix * also defaults to malloc and free. See pix1.c for details. *------------------------------------------------------------------------*/ #define MALLOC(blocksize) malloc(blocksize) #define CALLOC(numelem, elemsize) calloc(numelem, elemsize) #define REALLOC(ptr, blocksize) realloc(ptr, blocksize) #define FREE(ptr) free(ptr) /*------------------------------------------------------------------------* * Control printing of error, warning, and info messages * * * * (Use -DNO_CONSOLE_IO on compiler line to prevent text output) * *------------------------------------------------------------------------*/ #ifdef NO_CONSOLE_IO #define PROCNAME(name) #define ERROR_PTR(a,b,c) ((void *)(c)) #define ERROR_INT(a,b,c) ((l_int32)(c)) #define ERROR_FLOAT(a,b,c) ((l_float32)(c)) #define L_ERROR(a,b) #define L_ERROR_STRING(a,b,c) #define L_ERROR_INT(a,b,c) #define L_ERROR_FLOAT(a,b,c) #define L_WARNING(a,b) #define L_WARNING_STRING(a,b,c) #define L_WARNING_INT(a,b,c) #define L_WARNING_INT2(a,b,c,d) #define L_WARNING_FLOAT(a,b,c) #define L_WARNING_FLOAT2(a,b,c,d) #define L_INFO(a,b) #define L_INFO_STRING(a,b,c) #define L_INFO_INT(a,b,c) #define L_INFO_INT2(a,b,c,d) #define L_INFO_FLOAT(a,b,c) #define L_INFO_FLOAT2(a,b,c,d) #else #define PROCNAME(name) static const char procName[] = name #define ERROR_PTR(a,b,c) returnErrorPtr((a),(b),(c)) #define ERROR_INT(a,b,c) returnErrorInt((a),(b),(c)) #define ERROR_FLOAT(a,b,c) returnErrorFloat((a),(b),(c)) #define L_ERROR(a,b) l_error((a),(b)) #define L_ERROR_STRING(a,b,c) l_errorString((a),(b),(c)) #define L_ERROR_INT(a,b,c) l_errorInt((a),(b),(c)) #define L_ERROR_FLOAT(a,b,c) l_errorFloat((a),(b),(c)) #define L_WARNING(a,b) l_warning((a),(b)) #define L_WARNING_STRING(a,b,c) l_warningString((a),(b),(c)) #define L_WARNING_INT(a,b,c) l_warningInt((a),(b),(c)) #define L_WARNING_INT2(a,b,c,d) l_warningInt2((a),(b),(c),(d)) #define L_WARNING_FLOAT(a,b,c) l_warningFloat((a),(b),(c)) #define L_WARNING_FLOAT2(a,b,c,d) l_warningFloat2((a),(b),(c),(d)) #define L_INFO(a,b) l_info((a),(b)) #define L_INFO_STRING(a,b,c) l_infoString((a),(b),(c)) #define L_INFO_INT(a,b,c) l_infoInt((a),(b),(c)) #define L_INFO_INT2(a,b,c,d) l_infoInt2((a),(b),(c),(d)) #define L_INFO_FLOAT(a,b,c) l_infoFloat((a),(b),(c)) #define L_INFO_FLOAT2(a,b,c,d) l_infoFloat2((a),(b),(c),(d)) #endif /* NO_CONSOLE_IO */ /*------------------------------------------------------------------------* * snprintf() renamed in MSVC * *------------------------------------------------------------------------*/ #ifdef _MSC_VER #define snprintf(buf, size, ...) _snprintf_s(buf, size, _TRUNCATE, __VA_ARGS__) #endif #endif /* LEPTONICA_ENVIRON_H */
{ "content_hash": "e8c588c21e60a1d8aed9ecad702b9547", "timestamp": "", "source": "github", "line_count": 268, "max_line_length": 80, "avg_line_length": 36.0634328358209, "alnum_prop": 0.4595964821520952, "repo_name": "0359xiaodong/tess-two", "id": "7961f4ac6c116312ab38cf4cdbd9bc60847a5ccf", "size": "10588", "binary": false, "copies": "7", "ref": "refs/heads/master", "path": "tess-two/external/tesseract-3.01/vs2010/include/leptonica/environ.h", "mode": "33188", "license": "apache-2.0", "language": [], "symlink_target": "" }
extern crate ffigen; extern crate msbuild_util; use std::process::Command; use std::fs; use std::env; fn main() { let mut context = ffigen::Context::new(); context.set_root("../../scaffold".to_string()); context.add_lang(ffigen::Lang::Cpp, &[ffigen::Config::Output(".".to_string()), ffigen::Config::StaticOnly]); ffigen::gen(&context); //Build C# parts let config = match env::var("PROFILE").unwrap_or_else(|e| panic!("Count not get confing from env {}", e)).as_ref() { "debug" => "debug", "release" => "release", cfg => panic!("Unknown config {}", cfg) }; build(&config.to_string()); //Run cargo let mut cargo = Command::new("cargo"); cargo.current_dir("../../scaffold") .arg("build"); if config == "release" { cargo.arg("--release"); } let cargo_result = cargo.output() .unwrap_or_else(|e| panic!("Unable to run cargo {}", e)); if !cargo_result.status.success() { panic!("Unable to run cargo {} {}", String::from_utf8_lossy(&cargo_result.stderr), String::from_utf8_lossy(&cargo_result.stdout)); } let target = format!("../../scaffold/target/{}/libffi_test_scaffold.rlib", config); let dest = format!("x64/{}/libffi_test_scaffold.rlib", config); fs::copy(&target, &dest) .unwrap_or_else(|e| panic!("Unable to copy file from {} to {}, {}", target, dest, e)); //Make sure we know what version we should run println!("cargo:rustc-cfg=config_{}", config); } #[cfg(target_os = "windows")] fn build(config: &String) { let msbuild = msbuild_util::MSBuild::new() .project("CppStatic.vcxproj") .platform(msbuild_util::Platform::X64) .config(match config.as_ref() { "debug" => msbuild_util::Config::Debug, "release" => msbuild_util::Config::Release, cfg => panic!("Unknown config {}", cfg) }) .build(); if let Err(e) = msbuild { match e { msbuild_util::InvokeError::MSBuildNotFound => panic!("Failed to find MSBuild"), msbuild_util::InvokeError::BuildFailure(s) => panic!("Build Failed {}", s) } } } #[cfg(not(target_os = "windows"))] fn build(config: &String) { }
{ "content_hash": "e1cab4ad9bbd669d8382a2b63d44b7bf", "timestamp": "", "source": "github", "line_count": 74, "max_line_length": 138, "avg_line_length": 30.43243243243243, "alnum_prop": 0.577708703374778, "repo_name": "vvanders/ffigen", "id": "52000d8b0723a1a7b14cf8739792686a4432c8bb", "size": "2252", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "test/Cpp/static/build.rs", "mode": "33188", "license": "mit", "language": [ { "name": "C", "bytes": "1103" }, { "name": "C#", "bytes": "6002" }, { "name": "C++", "bytes": "6938" }, { "name": "Makefile", "bytes": "136" }, { "name": "Rust", "bytes": "55088" } ], "symlink_target": "" }
import six from sahara.api import acl from sahara.service.api import v10 as api from sahara.service import validation as v from sahara.service.validations import cluster_template_schema as ct_schema from sahara.service.validations import cluster_templates as v_ct from sahara.service.validations import clusters as v_c from sahara.service.validations import clusters_scaling as v_c_s from sahara.service.validations import clusters_schema as v_c_schema from sahara.service.validations import images as v_images from sahara.service.validations import node_group_template_schema as ngt_schema from sahara.service.validations import node_group_templates as v_ngt from sahara.service.validations import plugins as v_p import sahara.utils.api as u rest = u.Rest('v10', __name__) # Cluster ops @rest.get('/clusters') @acl.enforce("data-processing:clusters:get_all") @v.check_exists(api.get_cluster, 'marker') @v.validate(None, v.validate_pagination_limit, v.validate_sorting_clusters) def clusters_list(): result = api.get_clusters(**u.get_request_args().to_dict()) return u.render(res=result, name='clusters') @rest.post('/clusters') @acl.enforce("data-processing:clusters:create") @v.validate(v_c_schema.CLUSTER_SCHEMA, v_c.check_cluster_create) def clusters_create(data): return u.render(api.create_cluster(data).to_wrapped_dict()) @rest.post('/clusters/multiple') @acl.enforce("data-processing:clusters:create") @v.validate( v_c_schema.MULTIPLE_CLUSTER_SCHEMA, v_c.check_multiple_clusters_create) def clusters_create_multiple(data): return u.render(api.create_multiple_clusters(data)) @rest.put('/clusters/<cluster_id>') @acl.enforce("data-processing:clusters:scale") @v.check_exists(api.get_cluster, 'cluster_id') @v.validate(v_c_schema.CLUSTER_SCALING_SCHEMA, v_c_s.check_cluster_scaling) def clusters_scale(cluster_id, data): return u.to_wrapped_dict(api.scale_cluster, cluster_id, data) @rest.get('/clusters/<cluster_id>') @acl.enforce("data-processing:clusters:get") @v.check_exists(api.get_cluster, 'cluster_id') def clusters_get(cluster_id): data = u.get_request_args() show_events = six.text_type( data.get('show_progress', 'false')).lower() == 'true' return u.to_wrapped_dict(api.get_cluster, cluster_id, show_events) @rest.patch('/clusters/<cluster_id>') @acl.enforce("data-processing:clusters:modify") @v.check_exists(api.get_cluster, 'cluster_id') @v.validate(v_c_schema.CLUSTER_UPDATE_SCHEMA, v_c.check_cluster_update) def clusters_update(cluster_id, data): return u.to_wrapped_dict(api.update_cluster, cluster_id, data) @rest.delete('/clusters/<cluster_id>') @acl.enforce("data-processing:clusters:delete") @v.check_exists(api.get_cluster, 'cluster_id') @v.validate(None, v_c.check_cluster_delete) def clusters_delete(cluster_id): api.terminate_cluster(cluster_id) return u.render() # ClusterTemplate ops @rest.get('/cluster-templates') @acl.enforce("data-processing:cluster-templates:get_all") @v.check_exists(api.get_cluster_template, 'marker') @v.validate(None, v.validate_pagination_limit, v.validate_sorting_cluster_templates) def cluster_templates_list(): result = api.get_cluster_templates( **u.get_request_args().to_dict()) return u.render(res=result, name='cluster_templates') @rest.post('/cluster-templates') @acl.enforce("data-processing:cluster-templates:create") @v.validate(ct_schema.CLUSTER_TEMPLATE_SCHEMA, v_ct.check_cluster_template_create) def cluster_templates_create(data): return u.render(api.create_cluster_template(data).to_wrapped_dict()) @rest.get('/cluster-templates/<cluster_template_id>') @acl.enforce("data-processing:cluster-templates:get") @v.check_exists(api.get_cluster_template, 'cluster_template_id') def cluster_templates_get(cluster_template_id): return u.to_wrapped_dict(api.get_cluster_template, cluster_template_id) @rest.put('/cluster-templates/<cluster_template_id>') @acl.enforce("data-processing:cluster-templates:modify") @v.check_exists(api.get_cluster_template, 'cluster_template_id') @v.validate(ct_schema.CLUSTER_TEMPLATE_UPDATE_SCHEMA, v_ct.check_cluster_template_update) def cluster_templates_update(cluster_template_id, data): return u.to_wrapped_dict( api.update_cluster_template, cluster_template_id, data) @rest.delete('/cluster-templates/<cluster_template_id>') @acl.enforce("data-processing:cluster-templates:delete") @v.check_exists(api.get_cluster_template, 'cluster_template_id') @v.validate(None, v_ct.check_cluster_template_usage) def cluster_templates_delete(cluster_template_id): api.terminate_cluster_template(cluster_template_id) return u.render() # NodeGroupTemplate ops @rest.get('/node-group-templates') @acl.enforce("data-processing:node-group-templates:get_all") @v.check_exists(api.get_node_group_template, 'marker') @v.validate(None, v.validate_pagination_limit, v.validate_sorting_node_group_templates) def node_group_templates_list(): result = api.get_node_group_templates( **u.get_request_args().to_dict()) return u.render(res=result, name='node_group_templates') @rest.post('/node-group-templates') @acl.enforce("data-processing:node-group-templates:create") @v.validate(ngt_schema.NODE_GROUP_TEMPLATE_SCHEMA, v_ngt.check_node_group_template_create) def node_group_templates_create(data): return u.render(api.create_node_group_template(data).to_wrapped_dict()) @rest.get('/node-group-templates/<node_group_template_id>') @acl.enforce("data-processing:node-group-templates:get") @v.check_exists(api.get_node_group_template, 'node_group_template_id') def node_group_templates_get(node_group_template_id): return u.to_wrapped_dict( api.get_node_group_template, node_group_template_id) @rest.put('/node-group-templates/<node_group_template_id>') @acl.enforce("data-processing:node-group-templates:modify") @v.check_exists(api.get_node_group_template, 'node_group_template_id') @v.validate(ngt_schema.NODE_GROUP_TEMPLATE_UPDATE_SCHEMA, v_ngt.check_node_group_template_update) def node_group_templates_update(node_group_template_id, data): return u.to_wrapped_dict( api.update_node_group_template, node_group_template_id, data) @rest.delete('/node-group-templates/<node_group_template_id>') @acl.enforce("data-processing:node-group-templates:delete") @v.check_exists(api.get_node_group_template, 'node_group_template_id') @v.validate(None, v_ngt.check_node_group_template_usage) def node_group_templates_delete(node_group_template_id): api.terminate_node_group_template(node_group_template_id) return u.render() # Plugins ops @rest.get('/plugins') @acl.enforce("data-processing:plugins:get_all") def plugins_list(): return u.render(plugins=[p.dict for p in api.get_plugins()]) @rest.get('/plugins/<plugin_name>') @acl.enforce("data-processing:plugins:get") @v.check_exists(api.get_plugin, plugin_name='plugin_name') def plugins_get(plugin_name): return u.render(api.get_plugin(plugin_name).wrapped_dict) @rest.get('/plugins/<plugin_name>/<version>') @acl.enforce("data-processing:plugins:get_version") @v.check_exists(api.get_plugin, plugin_name='plugin_name', version='version') def plugins_get_version(plugin_name, version): return u.render(api.get_plugin(plugin_name, version).wrapped_dict) @rest.patch('/plugins/<plugin_name>') @acl.enforce("data-processing:plugins:patch") @v.check_exists(api.get_plugin, plugin_name='plugin_name') @v.validate(v_p.plugin_update_validation_jsonschema(), v_p.check_plugin_update) def plugins_update(plugin_name, data): return u.render(api.update_plugin(plugin_name, data).wrapped_dict) @rest.post_file('/plugins/<plugin_name>/<version>/convert-config/<name>') @acl.enforce("data-processing:plugins:convert_config") @v.check_exists(api.get_plugin, plugin_name='plugin_name', version='version') @v.validate(None, v_p.check_convert_to_template) def plugins_convert_to_cluster_template(plugin_name, version, name, data): # There is no plugins that supports converting to cluster template # The last plugin with support of that is no longer supported pass # Image Registry ops @rest.get('/images') @acl.enforce("data-processing:images:get_all") def images_list(): tags = u.get_request_args().getlist('tags') name = u.get_request_args().get('name', None) return u.render(images=[i.dict for i in api.get_images(name, tags)]) @rest.get('/images/<image_id>') @acl.enforce("data-processing:images:get") @v.check_exists(api.get_image, id='image_id') def images_get(image_id): return u.render(api.get_registered_image(image_id=image_id).wrapped_dict) @rest.post('/images/<image_id>') @acl.enforce("data-processing:images:register") @v.check_exists(api.get_image, id='image_id') @v.validate(v_images.image_register_schema, v_images.check_image_register) def images_set(image_id, data): return u.render(api.register_image(image_id, **data).wrapped_dict) @rest.delete('/images/<image_id>') @acl.enforce("data-processing:images:unregister") @v.check_exists(api.get_image, id='image_id') def images_unset(image_id): api.unregister_image(image_id) return u.render() @rest.post('/images/<image_id>/tag') @acl.enforce("data-processing:images:add_tags") @v.check_exists(api.get_image, id='image_id') @v.validate(v_images.image_tags_schema, v_images.check_tags) def image_tags_add(image_id, data): return u.render(api.add_image_tags(image_id, **data).wrapped_dict) @rest.post('/images/<image_id>/untag') @acl.enforce("data-processing:images:remove_tags") @v.check_exists(api.get_image, id='image_id') @v.validate(v_images.image_tags_schema) def image_tags_delete(image_id, data): return u.render(api.remove_image_tags(image_id, **data).wrapped_dict)
{ "content_hash": "d9a08d0eed5b240b71b99a020fb43ab6", "timestamp": "", "source": "github", "line_count": 265, "max_line_length": 79, "avg_line_length": 37.033962264150944, "alnum_prop": 0.7381292031791319, "repo_name": "tellesnobrega/sahara", "id": "e4e5730c45489bcfdd3059089b44ca7d0bec638b", "size": "10397", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "sahara/api/v10.py", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Mako", "bytes": "952" }, { "name": "Python", "bytes": "3354711" }, { "name": "Shell", "bytes": "56856" } ], "symlink_target": "" }
// Type definitions for Incremetal DOM // Project: https://github.com/google/incremental-dom // Definitions by: Basarat Ali Syed <https://github.com/basarat>, Markus Lanthaler <https://github.com/lanthaler> // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped declare module "incremental-dom" { /** * Patches the document starting at el with the provided function. This function * may be called during an existing patch operation. * @param {!Element} el the element to patch * @param {!function(T)} fn A function containing elementOpen/elementClose/etc. * calls that describe the DOM. * @param {?T} data An argument passed to fn to represent DOM state. */ export var patch: <T>(el: Node, fn: (data: T) => void, data?: T) => void; /** * Declares a virtual Element at the current location in the document. This * corresponds to an opening tag and a elementClose tag is required. * @param {string} tag The element's tag. * @param {?string} key The key used to identify this element. This can be an * empty string, but performance may be better if a unique value is used * when iterating over an array of items. * @param {?Array<*>} statics An array of attribute name/value pairs of the * static attributes for the Element. These will only be set once when the * Element is created. * @param {...*} var_args Attribute name/value pairs of the dynamic attributes * for the Element. */ export var elementOpen: (tag: string, key?: string, statics?: any[], ...var_args: any[]) => HTMLElement; /** * Declares a virtual Element at the current location in the document. This * corresponds to an opening tag and a elementClose tag is required. This is * like elementOpen, but the attributes are defined using the attr function * rather than being passed as arguments. Must be folllowed by 0 or more calls * to attr, then a call to elementOpenEnd. * @param {string} tag The element's tag. * @param {?string} key The key used to identify this element. This can be an * empty string, but performance may be better if a unique value is used * when iterating over an array of items. * @param {?Array<*>} statics An array of attribute name/value pairs of the * static attributes for the Element. These will only be set once when the * Element is created. */ export var elementOpenStart: (tag: string, key?: any, ...statics: any[]) => void; /*** * Defines a virtual attribute at this point of the DOM. This is only valid * when called between elementOpenStart and elementOpenEnd. * * @param {string} name * @param {*} value */ export var attr: (name: string, value: any) => void; /** * Closes an open tag started with elementOpenStart. */ export var elementOpenEnd: () => HTMLElement; /** * Closes an open virtual Element. */ export var elementClose: (tag: string) => HTMLElement; /** * Declares a virtual Element at the current location in the document that has * no children. * @param {string} tag The element's tag. * @param {?string} key The key used to identify this element. This can be an * empty string, but performance may be better if a unique value is used * when iterating over an array of items. * @param {?Array<*>} statics An array of attribute name/value pairs of the * static attributes for the Element. These will only be set once when the * Element is created. * @param {...*} var_args Attribute name/value pairs of the dynamic attributes * for the Element. */ export var elementVoid: (tag: string, key?: string, statics?: any, ...var_args: any[]) => HTMLElement; /** * Declares a virtual Text at this point in the document. * * @param {string} value The text of the Text. */ export var text: (value: string) => Text; }
{ "content_hash": "79b3fda1054fd59d09f78645915de9b6", "timestamp": "", "source": "github", "line_count": 82, "max_line_length": 113, "avg_line_length": 49.3780487804878, "alnum_prop": 0.6557174611015065, "repo_name": "slavomirvojacek/DefinitelyTyped", "id": "5a80e82d70443e7ebd221ad174d0b9085188e80f", "size": "4049", "binary": false, "copies": "17", "ref": "refs/heads/master", "path": "incremental-dom/incremental-dom.d.ts", "mode": "33188", "license": "mit", "language": [ { "name": "HTML", "bytes": "308" }, { "name": "Protocol Buffer", "bytes": "678" }, { "name": "TypeScript", "bytes": "23358650" } ], "symlink_target": "" }
void SLAP_init( UBYTE *bitmap, SLONG bitmap_size); // Power of 2 max of SLAP_MAX_BITMAP_SIZE // // Adds an outline edge given in 8-bit fixed point. // void SLAP_add_edge( SLONG x1, SLONG y1, SLONG x2, SLONG y2); // // Renders the bitmap. The image is clipped to the bitmap. // void SLAP_render(void); #endif
{ "content_hash": "f5bfadecb8bb8202b26cb872b17e62ad", "timestamp": "", "source": "github", "line_count": 24, "max_line_length": 64, "avg_line_length": 13.625, "alnum_prop": 0.6605504587155964, "repo_name": "kstuedem/MuckyFoot-UrbanChaos", "id": "ed5828c06d14bb3a00b01787f45c6e41f1d2706f", "size": "611", "binary": false, "copies": "4", "ref": "refs/heads/master", "path": "thrust/slap.h", "mode": "33188", "license": "mit", "language": [ { "name": "Batchfile", "bytes": "9399" }, { "name": "C", "bytes": "10011346" }, { "name": "C++", "bytes": "15708662" }, { "name": "CMake", "bytes": "112300" }, { "name": "HTML", "bytes": "39488" }, { "name": "Java", "bytes": "64859" }, { "name": "JavaScript", "bytes": "17803" }, { "name": "M4", "bytes": "43658" }, { "name": "Makefile", "bytes": "23934" }, { "name": "Objective-C", "bytes": "939315" }, { "name": "Objective-C++", "bytes": "144120" }, { "name": "Perl", "bytes": "41246" }, { "name": "PowerShell", "bytes": "12011" }, { "name": "Python", "bytes": "2053" }, { "name": "Roff", "bytes": "3003" }, { "name": "Scala", "bytes": "238" }, { "name": "Shell", "bytes": "362230" }, { "name": "SuperCollider", "bytes": "4285" } ], "symlink_target": "" }
In here are code snippets, examples, and other ways to help teach some of the concepts and tricks in Python. ##Suggested Learning Progression If you're new to Python you may wonder what you should learn and when you should learn it. I recommend this order seen below. **Each section below has its own folder above; each bullet point has its own file within that folder.** So if you wanted to learn more about variable assignment, go to the folder **section_01_(basics)** and open up **variable_assignment.py** #### Section 1: General Programming Basics - Simple Math - Variable Assignment - Basic Syntax and Logic - Data Types: int, float, bool, str #### Section 2: Strings - Identifying and using strings - String slicing - String formatting - String methods - - str.replace() - - str.find() - - str.count() - - str.lower() #### Section 3: Conditionals - Logical control; changing the behavior of your programs - and keyword, or keyword - if / else structure - if / elif ... / else structure - Nesting conditionals #### Section 4: Lists - Containers for data types - First In, Last Out (Stack) - Accessing specific list items through index (slice notation) - List methods - - list.append() - - list.insert() - - list.pop() - - list.extend() - Finding items in list (in keyword) - Deduplicating a list using list(set(list_to_deduplicate)) #### Section 5: Loops - for loop (for each item in a list: ...) - enumerate() - zip() - range() - while loop (ask each time: is this still true?) #### Section 6: Strings to Lists and Vice-Versa - str.join() (create a string from a list) - str.split() (create a list from a string) #### Section 7: File handling - with open(filename) as textfile: ... - file.read() - Reading text files - Reading CSV files - File handling flags (r, w, b, +) - Writing to files #### Section 8: Python's Most Commonly Used Built-in Functions - - Types (used primarily for converting one type to another) - int() - float() - str() - bool() - list() - set() - dict() - - Comparison and Calculation - abs() - len() - max() - min() - round() - sum() - - Loop (Sequence) Control - enumerate() - range() / xrange() - reversed() - sorted() - zip() #### Section 9: Functions - def keyword - arguments - default arguments - *args - **kwargs - return keyword - sequence unpacking (return and receive multiple values) - namespaces #### Section 10: Dictionaries - Accessing specific dictionary items through key (looks like a slice) - Accessing all keys as a list using .keys() - Faking a sorted dictionary by using sorted() on the .keys() - Accessing all values as a list using .values() - Accessing all key, value pairs as a list using .items() - Adding new items through .fromkeys() - Checking for whether a key exists with .has_key - Using .get() to safely get a key's value if it exists without getting an error if not - Adding new items with direct assignment and .update() #### Section 11: Dictionaries and Lists, together - Accessing specific items in a nested list - Accessing specific items in a nested dictionary - Accessing specific items in a nested list within a dictionary - Accessing specific items in a nested dictionary within a list - If you can do those four above, you can handle receiving JSON API returns #### Section 12: Standard Library - import keyword - from ... import ... as ... structure - time - random - math - re (regular expressions) - os - sys - json #### Section 13: External Libraries (Not necessarily in order; keep these in mind) - Installing external libraries with easy_install - Using easy_install to install pip (an easier / better way to install external libraries) - requests (web crawling made easy) - BeautifulSoup (parsing HTML) - xlrd (Read Excel .xls files) - xlwt (Write to Excel .xls files) - xlsxwriter (Write to Excel .xls and .xlsx files, with additional functionality beyond xlwt) - cherrypy (Simple, lightweight framework for serving web pages) - psycopg2 (Connect to and issue SQL commands to your postgresql database) #### Section 14: Exception Handling - try / except syntax - Using multiple excepts - Recognizing the different error types - Exception, the generic exception type (use sparingly) - Nesting exception handling - try / except / else syntax #### Section 15: Intermediate Concepts - List Comprehensions - Inline Conditionals - Generators #### Section 16: Classes - Classes - Magic Methods
{ "content_hash": "da0ace8ba683fe099c769503acf51f57", "timestamp": "", "source": "github", "line_count": 151, "max_line_length": 231, "avg_line_length": 29.072847682119207, "alnum_prop": 0.721867881548975, "repo_name": "keum/python-lessons", "id": "c59ba99e8f13fa1537752da216007c915c649380", "size": "4550", "binary": false, "copies": "3", "ref": "refs/heads/master", "path": "README.md", "mode": "33188", "license": "mit", "language": [], "symlink_target": "" }
<html> <head> <link type="text/css" rel="stylesheet" href="../../../build/logger/assets/logger.css" /> <link type="text/css" rel="stylesheet" href="../../../build/yuitest/assets/testlogger.css" /> <style> .everything { position:relative; height:420px; } .everything div { border:1px solid #888; } .topmain { position:absolute; top:10px; left:120px; height:75px; width:100px; } .duo1 { position:absolute; top:130px; left:20px; height:67px; width:100px; } #duo1 { background-image:url('http://developer.yahoo.com/yui/docs/assets/examples/exampleimages/small/uluru.jpg'); } .duo2 { position:absolute; top:130px; left:220px; height:53px; width:100px; } .src { position:absolute; top:220px; left:120px; height:72px; width:100px; } .trigger { position:absolute; top:330px; left:120px; height:75px; width:100px; } .sizer { position:absolute; top:450px; left:20px; height:150px; width:200px; } .sharedTrigger1 { position:absolute; top:10px; left:420px; height:72px; width:100px; } .sharedTrigger2 { position:absolute; top:10px; left:550px; height:67px; width:100px; } .fold-top { position:absolute; top:130px; left:420px; height:75px; width:100px; } .fold-bottom { position:absolute; top:500px; left:420px; height:75px; width:100px; } .customTrigger { position:absolute; top:330px; left:420px; height:67px; width:100px; } .yui-imgload { background:none !important; } </style> </head> <body> <div class='everything' id='everything'> <div class='topmain' id='topmain'></div> <div class='duo1 yui-imgload' id='duo1'></div> <div class='duo2'> <img class='yui-imgload' id='duo2' style='background-image:url("http://developer.yahoo.com/yui/docs/assets/examples/exampleimages/small/katatjuta.jpg");' width='100' height='53' /> </div> <div class='src' id='srcImgCont'> <img id='srcImg' /> </div> <div class='trigger' id='addlTrigger'></div> <div class='sizer'> <img id='sizerImg' style='visibility:hidden;' /> </div> <div class='sharedTrigger1' id='sharedTrigger1'></div> <div class='sharedTrigger2' id='sharedTrigger2'></div> <div class='fold-top'> <img id='foldImgTop' /> </div> <div class='fold-bottom'> <img id='foldImgBottom' /> </div> <div class='customTrigger' id='customTrigger'></div> </div> <script type="text/javascript" src="../../../build/yahoo/yahoo.js"></script> <script type="text/javascript" src="../../../build/dom/dom.js"></script> <script type="text/javascript" src="../../../build/event/event.js"></script> <script type="text/javascript" src="../../../build/logger/logger.js"></script> <script type="text/javascript" src="../../../build/yuitest/yuitest.js"></script> <script type="text/javascript" src="../../../build/event-simulate/event-simulate.js"></script> <script type="text/javascript" src="../../../build/imageloader/imageloader-min.js"></script> <script> var imgUrlsTestCase = new YAHOO.tool.TestCase({ /* * Test case to check the URL setting in the different types of image objects */ name: 'Setting Urls', setUp: function() { // background-image group this.bgImgUrl = 'http://developer.yahoo.com/yui/docs/assets/examples/exampleimages/small/museum.jpg'; this.mainGroup = new YAHOO.util.ImageLoader.group('topmain', 'mouseover'); this.mainGroup.registerBgImage('topmain', this.bgImgUrl); this.mainGroup.name = 'imgUrlsTestBgImg'; this.mainGroupImage = document.getElementById('topmain'); // src-image group this.srcImgUrl = 'http://developer.yahoo.com/yui/docs/assets/examples/exampleimages/small/morraine.jpg'; this.srcGroup = new YAHOO.util.ImageLoader.group('srcImgCont', 'click'); this.srcGroup.registerSrcImage('srcImg', this.srcImgUrl); this.srcGroup.name = 'imgUrlsTestSrcImg'; this.srcGroupImage = document.getElementById('srcImg'); }, testBgImg: function() { YAHOO.util.UserAction.mouseover('topmain'); // style.bgImg is "url('...')", but we can't rely on those quotes across browsers. indexOf is sufficient YAHOO.util.Assert.areNotEqual(this.mainGroupImage.style.backgroundImage.indexOf(this.bgImgUrl), -1); }, testSrcImg: function() { YAHOO.util.UserAction.click('srcImgCont'); YAHOO.util.Assert.areEqual(this.srcGroupImage.src, this.srcImgUrl); } }); var classNameTestCase = new YAHOO.tool.TestCase({ /* * Test case to check fetching by CSS class name */ name: 'Class Name Fetching', setUp: function() { this.duo1Url = 'http://developer.yahoo.com/yui/docs/assets/examples/exampleimages/small/uluru.jpg'; this.duo2Url = 'http://developer.yahoo.com/yui/docs/assets/examples/exampleimages/small/katatjuta.jpg'; this.duo1Image = document.getElementById('duo1'); this.duo2Image = document.getElementById('duo2'); // classname group this.classGroup = new YAHOO.util.ImageLoader.group('duo1', 'mouseover'); this.classGroup.className = 'yui-imgload'; this.classGroup.name = 'classNameTest'; }, testClassNames: function() { // We have to just check for the classname. Nothing else in the element will indicate the difference between before and after url application YAHOO.util.Assert.areEqual(this.duo1Image.className, 'duo1 yui-imgload'); YAHOO.util.Assert.areEqual(this.duo2Image.className, 'yui-imgload'); YAHOO.util.UserAction.mouseover('duo1'); YAHOO.util.Assert.areEqual(this.duo1Image.className, 'duo1'); YAHOO.util.Assert.areEqual(this.duo2Image.className, ''); } }); var addTriggerTestCase = new YAHOO.tool.TestCase({ /* * Test case for checking the addTrigger method */ name: 'addTrigger test', setUp: function() { this.imageUrl = 'http://developer.yahoo.com/yui/docs/assets/examples/exampleimages/small/museum.jpg'; this.triggerGroup = new YAHOO.util.ImageLoader.group('topmain', 'dblclick'); this.triggerGroup.registerBgImage('addlTrigger', this.imageUrl); this.triggerGroup.addTrigger('addlTrigger', 'click'); this.triggerGroup.name = 'addTriggerGroup'; this.triggerImage = document.getElementById('addlTrigger'); }, testAddTrigger: function() { YAHOO.util.Assert.areEqual(this.triggerImage.style.backgroundImage, ''); YAHOO.util.UserAction.click('addlTrigger'); YAHOO.util.Assert.areNotEqual(this.triggerImage.style.backgroundImage.indexOf(this.imageUrl), -1); } }); var customTriggerTestCase = new YAHOO.tool.TestCase({ /* * Test case for checking adding custom event triggers to a group */ name: 'custom trigger test', setUp: function() { this.imageUrl = 'http://developer.yahoo.com/yui/docs/assets/examples/exampleimages/small/uluru.jpg'; this.customEvent = new YAHOO.util.CustomEvent('imageloader_unit_test_for_custom_trigger'); this.triggerGroup = new YAHOO.util.ImageLoader.group(); this.triggerGroup.addCustomTrigger(this.customEvent); this.triggerGroup.registerBgImage('customTrigger', this.imageUrl); this.triggerGroup.name = 'customTriggerGroup'; this.triggerImage = document.getElementById('customTrigger'); }, testCustomTrigger: function() { YAHOO.util.Assert.areEqual(this.triggerImage.style.backgroundImage, ''); this.customEvent.fire(); YAHOO.util.Assert.areNotEqual(this.triggerImage.style.backgroundImage.indexOf(this.imageUrl), -1); } }); var imgSizingTestCase = new YAHOO.tool.TestCase({ /* * Test case to check post-fetch resizing of image, as well as 'visibility' setting */ name: 'Image Sizing', setUp: function() { this.imageUrl = 'http://developer.yahoo.com/yui/docs/assets/examples/exampleimages/small/japan.jpg'; this.sizerGroup = new YAHOO.util.ImageLoader.group('sizerImg', 'mouseover'); this.sizerGroup.name = 'imgSizingGroup'; var sizerILImg = this.sizerGroup.registerSrcImage('sizerImg', this.imageUrl, 200, 150); sizerILImg.setVisible = true; this.sizerImage = document.getElementById('sizerImg'); }, testImageVisibility: function() { YAHOO.util.UserAction.mouseover('sizerImg'); YAHOO.util.Assert.areEqual(this.sizerImage.style.visibility, 'visible'); }, testImageSizing: function() { // not sure if we can trust order, so make sure trigger was fired YAHOO.util.UserAction.mouseover('sizerImg'); YAHOO.util.Assert.areEqual(this.sizerImage.height, 150); YAHOO.util.Assert.areEqual(this.sizerImage.width, 200); } }); var triggerRemovalTestCase = new YAHOO.tool.TestCase({ /* * Test case to check removing the trigger from groups that share the same trigger. * During development, there was an initial problem of when one group fired, the other group's trigger was removed. * This was due to the way the fetch() methods were passed to Event's addListener(); fixed by wrapping the fetch calls. * More details available in js code comments, in addTrigger() method */ name: "Trigger Removal for Competing Groups' Triggers", setUp: function() { this.imageAUrl = 'http://developer.yahoo.com/yui/docs/assets/examples/exampleimages/small/morraine.jpg'; this.imageZUrl = 'http://developer.yahoo.com/yui/docs/assets/examples/exampleimages/small/uluru.jpg'; this.groupA = new YAHOO.util.ImageLoader.group('sharedTrigger1', 'click'); this.groupA.registerBgImage('sharedTrigger1', this.imageAUrl); this.groupA.name = 'triggerRemovalGroup(A)'; this.groupZ = new YAHOO.util.ImageLoader.group('sharedTrigger1', 'click'); this.groupZ.registerBgImage('sharedTrigger2', this.imageZUrl); this.groupZ.addTrigger('sharedTrigger2', 'click'); this.groupZ.name = 'triggerRemovalGroup(Z)'; this.groupAImage = document.getElementById('sharedTrigger1'); this.groupZImage = document.getElementById('sharedTrigger2'); }, testCompetingTriggers: function() { YAHOO.util.UserAction.click('sharedTrigger2'); YAHOO.util.Assert.areNotEqual(this.groupZImage.style.backgroundImage.indexOf(this.imageZUrl), -1); YAHOO.util.Assert.areEqual(this.groupAImage.style.backgroundImage, ''); YAHOO.util.UserAction.click('sharedTrigger1'); YAHOO.util.Assert.areNotEqual(this.groupAImage.style.backgroundImage.indexOf(this.imageAUrl), -1); } }); var foldConditionalTestCase = new YAHOO.tool.TestCase({ /* * Test case to check fold-conditional loading of a group * We're faking the viewport size and fold determination so that everything will be dependable in any situation (including automated runs) */ name: "Fold Conditional Loading", setUp: function() { this.imageTopUrl = 'http://developer.yahoo.com/yui/docs/assets/examples/exampleimages/small/japan.jpg'; this.imageBotUrl = 'http://developer.yahoo.com/yui/docs/assets/examples/exampleimages/small/japan.jpg'; this.foldGroup = new YAHOO.util.ImageLoader.group(); this.foldGroup.registerSrcImage('foldImgTop', this.imageTopUrl); this.foldGroup.registerSrcImage('foldImgBottom', this.imageBotUrl); this.foldGroup.foldConditional = true; this.foldGroup.name = 'foldConditionalGroup'; this.groupTopImage = document.getElementById('foldImgTop'); this.groupBotImage = document.getElementById('foldImgBottom'); // override the foldCheck function of this group, because we'll need to fake things to make them dependable this.foldGroup._foldCheck = function() { var hLimit = 300; var wLimit = 1000; for (var id in this._imgObjs) { if (YAHOO.lang.hasOwnProperty(this._imgObjs, id)) { var elPos = YAHOO.util.Dom.getXY(this._imgObjs[id].domId); if (elPos[1] < hLimit && elPos[0] < wLimit) { this._imgObjs[id].fetch(); } } } }; }, testFoldCheck: function() { this.foldGroup._foldCheck(); YAHOO.util.Assert.areEqual(this.groupTopImage.src, this.imageTopUrl); YAHOO.util.Assert.areEqual(this.groupBotImage.src, ''); } }); var imageLoaderTestSuite = new YAHOO.tool.TestSuite('YUI ImageLoader Utility'); imageLoaderTestSuite.add(imgUrlsTestCase); imageLoaderTestSuite.add(classNameTestCase); imageLoaderTestSuite.add(addTriggerTestCase); imageLoaderTestSuite.add(customTriggerTestCase); imageLoaderTestSuite.add(imgSizingTestCase); imageLoaderTestSuite.add(triggerRemovalTestCase); imageLoaderTestSuite.add(foldConditionalTestCase); YAHOO.tool.TestRunner.add(imageLoaderTestSuite); YAHOO.util.Event.onDOMReady(function() { var logger = new YAHOO.tool.TestLogger(); if (parent && parent != window) { YAHOO.tool.TestManager.load(); } else { YAHOO.tool.TestRunner.run(); } }); </script> </body> </html>
{ "content_hash": "0f32db9bef15545fcfa6b5fc1197ff06", "timestamp": "", "source": "github", "line_count": 310, "max_line_length": 182, "avg_line_length": 39.31612903225806, "alnum_prop": 0.7333442730554643, "repo_name": "sashakames/COG", "id": "18b90f23d32c93398a2d8cbae3bb51083af2605c", "size": "12188", "binary": false, "copies": "6", "ref": "refs/heads/master", "path": "cog/static/js/yui/tests/imageloader/tests/imageloader.html", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "Batchfile", "bytes": "270" }, { "name": "CSS", "bytes": "877048" }, { "name": "Classic ASP", "bytes": "48011" }, { "name": "HTML", "bytes": "95868889" }, { "name": "Java", "bytes": "483882" }, { "name": "JavaScript", "bytes": "13215509" }, { "name": "MATLAB", "bytes": "30087" }, { "name": "PHP", "bytes": "80287" }, { "name": "Python", "bytes": "852780" }, { "name": "Rich Text Format", "bytes": "6112" }, { "name": "Shell", "bytes": "10602" } ], "symlink_target": "" }
Shine is a blog engine for `rails` apps that uses contentful.com as a CMS. ## Installation Add this line to your application's Gemfile: ```ruby gem 'shine' ``` And then execute: $ bundle Or install it yourself as: $ gem install shine ## Setup Shine uses `figaro` to set environment variables, and it uses postgres to cache content for two reasons, 1) so that you get an nice AR interface to your data, and 2) to cut down on API calls to contentful.com. To set up the required `application.yml` and database migrations, do `rails generate shine` Then `rake db:migrate` Now you're ready to import your content into your rails blog, which you can do with a rake task: `rake shine:sync_all` If you've put the correct credentials and ids into `config/application.yml`, then this rake task will sync all of your entries and assets into postgres. ## Development After checking out the repo, run `bin/setup` to install dependencies. Then, run `rake spec` to run the tests. You can also run `bin/console` for an interactive prompt that will allow you to experiment. To install this gem onto your local machine, run `bundle exec rake install`. To release a new version, update the version number in `version.rb`, and then run `bundle exec rake release`, which will create a git tag for the version, push git commits and tags, and push the `.gem` file to [rubygems.org](https://rubygems.org). ## Contributing Bug reports and pull requests are welcome on GitHub at https://github.com/jonstokes/shine.
{ "content_hash": "7f5a3d69e3f21880ae9236f55a6aa9b0", "timestamp": "", "source": "github", "line_count": 46, "max_line_length": 324, "avg_line_length": 33.02173913043478, "alnum_prop": 0.7511520737327189, "repo_name": "jonstokes/shine", "id": "1c068ca97a2e26d45923f7365f285e95dcd33b16", "size": "1528", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "README.md", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "5351" }, { "name": "HTML", "bytes": "36121" }, { "name": "JavaScript", "bytes": "242366" }, { "name": "Ruby", "bytes": "60263" } ], "symlink_target": "" }
package script const ScriptExt = ""
{ "content_hash": "7a47ccbfe0d7e7bddc80ec28d5da7311", "timestamp": "", "source": "github", "line_count": 3, "max_line_length": 20, "avg_line_length": 12.333333333333334, "alnum_prop": 0.7297297297297297, "repo_name": "cloudfoundry/bosh-agent", "id": "f088c0957358af34586b02b7b0640ba6671eeb04", "size": "77", "binary": false, "copies": "1", "ref": "refs/heads/main", "path": "agent/script/ext_unix.go", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Dockerfile", "bytes": "1009" }, { "name": "Go", "bytes": "2394908" }, { "name": "PowerShell", "bytes": "5664" }, { "name": "Shell", "bytes": "26112" } ], "symlink_target": "" }
FROM maven:3.5.3-jdk-10-slim as maven WORKDIR /servlet COPY src src COPY pom.xml pom.xml RUN mvn compile war:war -q -P mysql FROM openjdk:10-jdk WORKDIR /resin RUN curl -sL http://caucho.com/download/resin-4.0.56.tar.gz | tar xz --strip-components=1 RUN rm -rf webapps/* COPY --from=maven /servlet/target/servlet.war webapps/ROOT.war COPY resin.xml conf/resin.xml CMD ["java", "-jar", "lib/resin.jar", "console"]
{ "content_hash": "4d3803dc2eead9dfc65e198ebefa9115", "timestamp": "", "source": "github", "line_count": 13, "max_line_length": 89, "avg_line_length": 31.846153846153847, "alnum_prop": 0.7318840579710145, "repo_name": "nbrady-techempower/FrameworkBenchmarks", "id": "d84d6f04c347b4d9a74904c76afa1c2092ab7585", "size": "414", "binary": false, "copies": "5", "ref": "refs/heads/master", "path": "frameworks/Java/servlet/servlet-mysql.dockerfile", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "ASP", "bytes": "104" }, { "name": "Batchfile", "bytes": "2088" }, { "name": "C", "bytes": "166050" }, { "name": "C#", "bytes": "410352" }, { "name": "C++", "bytes": "155116" }, { "name": "CMake", "bytes": "16633" }, { "name": "CSS", "bytes": "17457" }, { "name": "Clojure", "bytes": "78516" }, { "name": "Common Lisp", "bytes": "2653" }, { "name": "Crystal", "bytes": "27119" }, { "name": "D", "bytes": "78626" }, { "name": "Dart", "bytes": "52130" }, { "name": "Dockerfile", "bytes": "307178" }, { "name": "Elixir", "bytes": "14368" }, { "name": "Erlang", "bytes": "41222" }, { "name": "F#", "bytes": "89877" }, { "name": "Go", "bytes": "167865" }, { "name": "Groovy", "bytes": "21834" }, { "name": "HTML", "bytes": "139914" }, { "name": "Hack", "bytes": "1945" }, { "name": "Haskell", "bytes": "70225" }, { "name": "Java", "bytes": "638166" }, { "name": "JavaScript", "bytes": "173049" }, { "name": "Kotlin", "bytes": "52983" }, { "name": "Lua", "bytes": "14508" }, { "name": "Makefile", "bytes": "3053" }, { "name": "Meson", "bytes": "846" }, { "name": "MoonScript", "bytes": "2396" }, { "name": "Nim", "bytes": "1290" }, { "name": "PHP", "bytes": "583493" }, { "name": "PLpgSQL", "bytes": "3446" }, { "name": "Perl", "bytes": "15376" }, { "name": "Python", "bytes": "337122" }, { "name": "QMake", "bytes": "2301" }, { "name": "Ruby", "bytes": "82702" }, { "name": "Rust", "bytes": "71551" }, { "name": "Scala", "bytes": "90999" }, { "name": "Shell", "bytes": "53625" }, { "name": "Smarty", "bytes": "436" }, { "name": "Swift", "bytes": "101317" }, { "name": "TypeScript", "bytes": "13551" }, { "name": "UrWeb", "bytes": "4453" }, { "name": "Vala", "bytes": "1579" }, { "name": "Visual Basic", "bytes": "27087" }, { "name": "Volt", "bytes": "511" } ], "symlink_target": "" }
var assert = require("assert"); var Class = require("cls"); var Node = require("./types").namedTypes.Node; var slice = Array.prototype.slice; var removeRequests = []; var Visitor = exports.Visitor = Class.extend({ visit: function(node) { var self = this; if (!node) { // pass } else if (node instanceof Array) { node = self.visitArray(node); } else if (Node.check(node)) { var methodName = "visit" + node.type, method = self[methodName] || self.genericVisit; node = method.call(this, node); } else if (typeof node === "object") { // Some AST node types contain ad-hoc (non-AST) objects that // may contain nested AST nodes. self.genericVisit(node); } return node; }, visitArray: function(arr, noUpdate) { for (var elem, result, undef, i = 0, len = arr.length; i < len; i += 1) { if (i in arr) elem = arr[i]; else continue; var requesters = []; removeRequests.push(requesters); // Make sure we don't accidentally reuse a previous result // when this.visit throws an exception. result = undef; try { result = this.visit(elem); } finally { assert.strictEqual( removeRequests.pop(), requesters); } if (requesters.length > 0 || result === null) { // This hole will be elided by the compaction loop below. delete arr[i]; } else if (result !== undef) { arr[i] = result; } } // Compact the array to eliminate holes. for (var dst = 0, src = dst, // The length of the array might have changed during the // iteration performed above. len = arr.length; src < len; src += 1) if (src in arr) arr[dst++] = arr[src]; arr.length = dst; return arr; }, remove: function() { var len = removeRequests.length, requesters = removeRequests[len - 1]; if (requesters) requesters.push(this); }, genericVisit: function(node) { var field, oldValue, newValue; for (field in node) { if (!node.hasOwnProperty(field)) continue; oldValue = node[field]; if (oldValue instanceof Array) { this.visitArray(oldValue); } else if (Node.check(oldValue)) { newValue = this.visit(oldValue); if (typeof newValue === "undefined") { // Keep oldValue. } else { node[field] = newValue; } } else if (typeof oldValue === "object") { this.genericVisit(oldValue); } } return node; } });
{ "content_hash": "b73b0be6e6812dda91a76d7393473aa2", "timestamp": "", "source": "github", "line_count": 118, "max_line_length": 73, "avg_line_length": 27.076271186440678, "alnum_prop": 0.46071987480438187, "repo_name": "M3kH/tire-bouchon", "id": "2942187a8f2feb7a6898d6d8c2dd4b8591dc0f16", "size": "3195", "binary": false, "copies": "9", "ref": "refs/heads/master", "path": "node_modules/grunt-react/node_modules/react-tools/node_modules/commoner/node_modules/recast/lib/visitor.js", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "29029" }, { "name": "JavaScript", "bytes": "2324160" }, { "name": "PHP", "bytes": "419835" }, { "name": "Shell", "bytes": "192" } ], "symlink_target": "" }
<?xml version="1.0" encoding="utf-8" standalone="yes" ?> <rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom"> <channel> <title>Categories on Keep Moving</title> <link>https://sanghunka.github.io/categories/</link> <description>Recent content in Categories on Keep Moving</description> <generator>Hugo -- gohugo.io</generator> <language>en-us</language> <lastBuildDate>Mon, 25 Dec 2017 00:00:00 +0000</lastBuildDate> <atom:link href="https://sanghunka.github.io/categories/index.xml" rel="self" type="application/rss+xml" /> <item> <title>Blockchain</title> <link>https://sanghunka.github.io/categories/blockchain/</link> <pubDate>Mon, 25 Dec 2017 00:00:00 +0000</pubDate> <guid>https://sanghunka.github.io/categories/blockchain/</guid> <description></description> </item> <item> <title>Cryptocurency</title> <link>https://sanghunka.github.io/categories/cryptocurency/</link> <pubDate>Mon, 25 Dec 2017 00:00:00 +0000</pubDate> <guid>https://sanghunka.github.io/categories/cryptocurency/</guid> <description></description> </item> <item> <title>Dev</title> <link>https://sanghunka.github.io/categories/dev/</link> <pubDate>Mon, 22 Jan 2018 00:00:00 +0000</pubDate> <guid>https://sanghunka.github.io/categories/dev/</guid> <description></description> </item> <item> <title>Marketing</title> <link>https://sanghunka.github.io/categories/marketing/</link> <pubDate>Mon, 22 Jan 2018 00:00:00 +0000</pubDate> <guid>https://sanghunka.github.io/categories/marketing/</guid> <description></description> </item> <item> <title>Translations</title> <link>https://sanghunka.github.io/categories/translations/</link> <pubDate>Sun, 09 Jul 2017 00:00:00 +0000</pubDate> <guid>https://sanghunka.github.io/categories/translations/</guid> <description></description> </item> </channel> </rss>
{ "content_hash": "85f8e71d56029eabbeaeb8f9ad51dae6", "timestamp": "", "source": "github", "line_count": 60, "max_line_length": 108, "avg_line_length": 34.56666666666667, "alnum_prop": 0.6388621022179364, "repo_name": "sanghkaang/sanghkaang.github.io", "id": "5037d5ee651832c980776f95c30be67a4472acf6", "size": "2074", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "categories/index.xml", "mode": "33188", "license": "mit", "language": [ { "name": "HTML", "bytes": "4281175" } ], "symlink_target": "" }
using FredrikScript.Core; using FredrikScript.Core.Expressions; using FredrikScript.Core.Types; using FredrikScript.ParserFS; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace FredrikScript.Parser { public class ParseExpressionVisitor : CompilerVisitorBase { public ParseExpressionVisitor(Context context) : base(context) { } private Stack<Dictionary<string, IType>> _localVariableStack = new Stack<Dictionary<string, IType>>(); private Stack<Expression> _expressionStack = new Stack<Expression>(); private SourceInformation GetSourceInformation(Ast.ContextInfo ci) { return new SourceInformation(ci.StreamName, ci.Line, ci.Column); } private IType GetLocalVariable(string name) { foreach(var scope in _localVariableStack.Reverse()) { if (scope.ContainsKey(name)) return scope[name]; } return null; } private void VisitExpression(Ast.Expression expr) { switch(expr.Tag) { case Ast.Expression.Tags.Integer: var intExpr = expr as Ast.Expression.Integer; _expressionStack.Push(new IntegerExpression(_context, GetSourceInformation(intExpr.Item1), intExpr.Item2)); break; case Ast.Expression.Tags.Long: var longExpr = expr as Ast.Expression.Long; _expressionStack.Push(new LongExpression(_context, GetSourceInformation(longExpr.Item1), longExpr.Item2)); break; case Ast.Expression.Tags.Boolean: var boolExpr = expr as Ast.Expression.Boolean; _expressionStack.Push(new BooleanExpression(_context, GetSourceInformation(boolExpr.Item1), boolExpr.Item2)); break; case Ast.Expression.Tags.Float: var floatExpr = expr as Ast.Expression.Float; _expressionStack.Push(new FloatExpression(_context, GetSourceInformation(floatExpr.Item1), floatExpr.Item2)); break; case Ast.Expression.Tags.Char: var charExpr = expr as Ast.Expression.Char; _expressionStack.Push(new CharExpression(_context, GetSourceInformation(charExpr.Item1), charExpr.Item2)); break; case Ast.Expression.Tags.String: var strExpr = expr as Ast.Expression.String; _expressionStack.Push(new StringExpression(_context, GetSourceInformation(strExpr.Item1), strExpr.Item2)); break; case Ast.Expression.Tags.Add: var addExpr = expr as Ast.Expression.Add; VisitExpression(addExpr.Item3); VisitExpression(addExpr.Item2); var lhs = _expressionStack.Pop(); var rhs = _expressionStack.Pop(); _expressionStack.Push(new AddExpression(_context, GetSourceInformation(addExpr.Item1), lhs, rhs)); break; case Ast.Expression.Tags.Subtract: var subExpr = expr as Ast.Expression.Subtract; VisitExpression(subExpr.Item3); VisitExpression(subExpr.Item2); _expressionStack.Push(new SubtractExpression(_context, GetSourceInformation(subExpr.Item1), _expressionStack.Pop(), _expressionStack.Pop())); break; case Ast.Expression.Tags.Multiply: var mulExpr = expr as Ast.Expression.Multiply; VisitExpression(mulExpr.Item3); VisitExpression(mulExpr.Item2); _expressionStack.Push(new MultiplyExpression(_context, GetSourceInformation(mulExpr.Item1), _expressionStack.Pop(), _expressionStack.Pop())); break; case Ast.Expression.Tags.Divide: var divExpr = expr as Ast.Expression.Divide; VisitExpression(divExpr.Item3); VisitExpression(divExpr.Item2); _expressionStack.Push(new DivideExpression(_context, GetSourceInformation(divExpr.Item1), _expressionStack.Pop(), _expressionStack.Pop())); break; case Ast.Expression.Tags.Modulus: var modExpr = expr as Ast.Expression.Modulus; VisitExpression(modExpr.Item3); VisitExpression(modExpr.Item2); _expressionStack.Push(new ModulusExpression(_context, GetSourceInformation(modExpr.Item1), _expressionStack.Pop(), _expressionStack.Pop())); break; case Ast.Expression.Tags.BitwiseAnd: var bandExpr = expr as Ast.Expression.BitwiseAnd; VisitExpression(bandExpr.Item3); VisitExpression(bandExpr.Item2); _expressionStack.Push(new BitwiseAndExpression(_context, GetSourceInformation(bandExpr.Item1), _expressionStack.Pop(), _expressionStack.Pop())); break; case Ast.Expression.Tags.BitwiseOr: var borExpr = expr as Ast.Expression.BitwiseOr; VisitExpression(borExpr.Item3); VisitExpression(borExpr.Item2); _expressionStack.Push(new BitwiseOrExpression(_context, GetSourceInformation(borExpr.Item1), _expressionStack.Pop(), _expressionStack.Pop())); break; case Ast.Expression.Tags.BitwiseXor: var bxorExpr = expr as Ast.Expression.BitwiseXor; VisitExpression(bxorExpr.Item3); VisitExpression(bxorExpr.Item2); _expressionStack.Push(new BitwiseXorExpression(_context, GetSourceInformation(bxorExpr.Item1), _expressionStack.Pop(), _expressionStack.Pop())); break; case Ast.Expression.Tags.BitshiftLeft: var bslExpr = expr as Ast.Expression.BitshiftLeft; VisitExpression(bslExpr.Item3); VisitExpression(bslExpr.Item2); _expressionStack.Push(new BitshiftLeftExpression(_context, GetSourceInformation(bslExpr.Item1), _expressionStack.Pop(), _expressionStack.Pop())); break; case Ast.Expression.Tags.BitshiftRight: var bsrExpr = expr as Ast.Expression.BitshiftRight; VisitExpression(bsrExpr.Item3); VisitExpression(bsrExpr.Item2); _expressionStack.Push(new BitshiftRightExpression(_context, GetSourceInformation(bsrExpr.Item1), _expressionStack.Pop(), _expressionStack.Pop())); break; case Ast.Expression.Tags.Equals: var equalsExpr = expr as Ast.Expression.Equals; VisitExpression(equalsExpr.Item3); VisitExpression(equalsExpr.Item2); _expressionStack.Push(new EqualsExpression(_context, GetSourceInformation(equalsExpr.Item1), _expressionStack.Pop(), _expressionStack.Pop())); break; case Ast.Expression.Tags.NotEqual: var neExpr = expr as Ast.Expression.NotEqual; VisitExpression(neExpr.Item3); VisitExpression(neExpr.Item2); _expressionStack.Push(new NotEqualExpression(_context, GetSourceInformation(neExpr.Item1), _expressionStack.Pop(), _expressionStack.Pop())); break; case Ast.Expression.Tags.Or: var lorExpr = expr as Ast.Expression.Or; VisitExpression(lorExpr.Item3); VisitExpression(lorExpr.Item2); _expressionStack.Push(new OrExpression(_context, GetSourceInformation(lorExpr.Item1), _expressionStack.Pop(), _expressionStack.Pop())); break; case Ast.Expression.Tags.And: var landExpr = expr as Ast.Expression.And; VisitExpression(landExpr.Item3); VisitExpression(landExpr.Item2); _expressionStack.Push(new AndExpression(_context, GetSourceInformation(landExpr.Item1), _expressionStack.Pop(), _expressionStack.Pop())); break; case Ast.Expression.Tags.LowerThan: var ltExpr = expr as Ast.Expression.LowerThan; VisitExpression(ltExpr.Item3); VisitExpression(ltExpr.Item2); _expressionStack.Push(new LowerThanExpression(_context, GetSourceInformation(ltExpr.Item1), _expressionStack.Pop(), _expressionStack.Pop())); break; case Ast.Expression.Tags.LowerThanEquals: var lteExpr = expr as Ast.Expression.LowerThanEquals; VisitExpression(lteExpr.Item3); VisitExpression(lteExpr.Item2); _expressionStack.Push(new LowerThanEqualsExpression(_context, GetSourceInformation(lteExpr.Item1), _expressionStack.Pop(), _expressionStack.Pop())); break; case Ast.Expression.Tags.GreaterThan: var gtExpr = expr as Ast.Expression.GreaterThan; VisitExpression(gtExpr.Item3); VisitExpression(gtExpr.Item2); _expressionStack.Push(new GreaterThanExpression(_context, GetSourceInformation(gtExpr.Item1), _expressionStack.Pop(), _expressionStack.Pop())); break; case Ast.Expression.Tags.GreaterThanEquals: var gteExpr = expr as Ast.Expression.GreaterThanEquals; VisitExpression(gteExpr.Item3); VisitExpression(gteExpr.Item2); _expressionStack.Push(new GreaterThanEqualsExpression(_context, GetSourceInformation(gteExpr.Item1), _expressionStack.Pop(), _expressionStack.Pop())); break; case Ast.Expression.Tags.Symbol: var symExpr = expr as Ast.Expression.Symbol; var localVar = GetLocalVariable(symExpr.Item2); if (localVar != null) { _expressionStack.Push(new VariableExpression(_context, GetSourceInformation(symExpr.Item1), symExpr.Item2, localVar)); } else throw new NotImplementedException(); break; } } private bool IsLocalVariable(string varName) { foreach(var varScope in _localVariableStack) { if(varScope.ContainsKey(varName)) { return true; } } throw new NotImplementedException(); } private void VisitStatement(Ast.Statement statement) { switch(statement.Tag) { case Ast.Statement.Tags.Break: var breakStatement = statement as Ast.Statement.Break; var breakExpr = new BreakExpression(_context, GetSourceInformation(breakStatement.Item)); _expressionStack.Push(breakExpr); break; case Ast.Statement.Tags.Continue: var continueStatement = statement as Ast.Statement.Continue; var continueExpr = new ContinueExpression(_context, GetSourceInformation(continueStatement.Item)); _expressionStack.Push(continueExpr); break; case Ast.Statement.Tags.DoWhile: var doWhileStatement = statement as Ast.Statement.DoWhile; var doWhileExpr = new DoWhileExpression(_context, GetSourceInformation(doWhileStatement.Item1)); var oldStack = _expressionStack; _expressionStack = new Stack<Expression>(); foreach(var subStatement in doWhileStatement.Item2) VisitStatement(subStatement); var results = _expressionStack.Reverse().ToArray(); _expressionStack = oldStack; var blockInfo = results.Length > 0 ? results[0].SourceInformation : doWhileExpr.SourceInformation; var blockExpression = new BlockExpression(_context, blockInfo, results); _expressionStack.Push(doWhileExpr); break; case Ast.Statement.Tags.Empty: break; case Ast.Statement.Tags.Expression: VisitExpression((statement as Ast.Statement.Expression).Item2); break; case Ast.Statement.Tags.For: var forStatement = statement as Ast.Statement.For; VisitStatement(forStatement.Item2); VisitExpression(forStatement.Item3); VisitExpression(forStatement.Item4); var lastExpr = _expressionStack.Pop(); var middleExpr = _expressionStack.Pop(); var firstExpr = _expressionStack.Pop(); var forOldStack = _expressionStack; _expressionStack = new Stack<Expression>(); foreach (var st in forStatement.Item5) VisitStatement(st); var statementExpressions = _expressionStack.Reverse().ToArray(); _expressionStack = forOldStack; var forBlockExpression = new BlockExpression(_context, statementExpressions.Length > 0 ? statementExpressions[0].SourceInformation : lastExpr.SourceInformation, statementExpressions); _expressionStack.Push(new ForExpression(_context, GetSourceInformation(forStatement.Item1), firstExpr, middleExpr, lastExpr, forBlockExpression)); break; case Ast.Statement.Tags.ForEach: break; case Ast.Statement.Tags.If: break; case Ast.Statement.Tags.Return: var returnStatement = statement as Ast.Statement.Return; Expression returnExpression; if (Utilities.TryGetValue(returnStatement.Item2, out var returnValueExpression)) { VisitExpression(returnValueExpression); returnExpression = new ReturnValueExpression(_context, GetSourceInformation(returnStatement.Item1), _expressionStack.Pop()); } else returnExpression = new ReturnExpression(_context, GetSourceInformation(returnStatement.Item1)); _expressionStack.Push(returnExpression); break; case Ast.Statement.Tags.VariableDeclaration: var varStatement = statement as Ast.Statement.VariableDeclaration; Ast.TypeName varTypeName = null; IType varType = null; ; if (Utilities.TryGetValue(varStatement.Item3, out varTypeName)) varType = _context.ResolveType(varTypeName.Item1, Namespace, UsingDirectives); if (Utilities.TryGetValue(varStatement.Item4, out var initExpression)) { VisitExpression(initExpression); varType = _expressionStack.Peek().ExpressionType; _expressionStack.Push(new DeclareAssignVariableExpression(_context, GetSourceInformation(varStatement.Item1), varStatement.Item2, varType, _expressionStack.Pop())); } else if (varType != null) _expressionStack.Push(new DeclareVariableExpression(_context, GetSourceInformation(varStatement.Item1), varStatement.Item2, varType)); else throw new Exception("Variable declaration must have either a type annotation or a initializer"); _localVariableStack.Peek().Add(varStatement.Item2, varType); break; case Ast.Statement.Tags.While: break; } } private void VisitMethod(Ast.TypeMember.Method method, string n) { _expressionStack.Clear(); var declaringTypeName = n; var declaringTypeNamespace = Namespace; var declaringTypeFqn = string.IsNullOrWhiteSpace(Namespace) ? declaringTypeName : Namespace + "." + n; var declaringType = _context.Types[declaringTypeFqn]; var parameterTypes = method.Item5.Select(x => ResolveType(x.Item3)).ToArray(); var parameterNamesMangled = string.Join(",", parameterTypes.Select(parameterType => parameterType.FullyQualifiedName)); var storageClass = StorageClassFromAst(method.Item3); var separator = storageClass == StorageClass.Instance ? "::" : "."; var methodName = $"{declaringTypeFqn}{separator}{method.Item4.Item}({parameterNamesMangled})"; _localVariableStack.Push(new Dictionary<string, IType>()); for(int i = 0; i < parameterTypes.Length; i++) _localVariableStack.Peek().Add(method.Item5[i].Item2.Item, parameterTypes[i]); foreach(var statement in method.Item7) VisitStatement(statement); _localVariableStack.Pop(); var results = _expressionStack.Reverse().ToArray(); var result = results.Length > 1 ? new BlockExpression(_context, results[0].SourceInformation, results) : results.Length == 0 ? new BlockExpression(_context, GetSourceInformation(method.Item1), new Expression[] { }) : results[0]; _expressionStack.Clear(); if (declaringType is ClassBuilder) (declaringType as ClassBuilder).GetMethodFromSymbol(methodName).SetMethodBody(result); else (declaringType as StructBuilder).GetMethodFromSymbol(methodName).SetMethodBody(result); } protected override void VisitClassMethod(Ast.TypeMember.Method method) { VisitMethod(method, CurrentClass.Item3.Item); } protected override void VisitStructMethod(Ast.TypeMember.Method method) { VisitMethod(method, CurrentStruct.Item3.Item); } } }
{ "content_hash": "01bea5ece3beae54ea69329d08121f1f", "timestamp": "", "source": "github", "line_count": 340, "max_line_length": 188, "avg_line_length": 55.93235294117647, "alnum_prop": 0.5793237629489404, "repo_name": "FredrikAleksander/FredrikScript", "id": "e98c14347e6a49e6f7751b5914dbb870e4420eac", "size": "19019", "binary": false, "copies": "1", "ref": "refs/heads/develop", "path": "FredrikScript.Parser/ParseExpressionVisitor.cs", "mode": "33188", "license": "mit", "language": [ { "name": "C#", "bytes": "158738" }, { "name": "F#", "bytes": "46856" } ], "symlink_target": "" }
// Generated by the protocol buffer compiler. DO NOT EDIT! // source: google/devtools/clouddebugger/v2/data.proto package com.google.devtools.clouddebugger.v2; /** * * * <pre> * Represents the debugged application. The application may include one or more * replicated processes executing the same code. Each of these processes is * attached with a debugger agent, carrying out the debugging commands. * Agents attached to the same debuggee identify themselves as such by using * exactly the same Debuggee message value when registering. * </pre> * * Protobuf type {@code google.devtools.clouddebugger.v2.Debuggee} */ public final class Debuggee extends com.google.protobuf.GeneratedMessageV3 implements // @@protoc_insertion_point(message_implements:google.devtools.clouddebugger.v2.Debuggee) DebuggeeOrBuilder { private static final long serialVersionUID = 0L; // Use Debuggee.newBuilder() to construct. private Debuggee(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) { super(builder); } private Debuggee() { id_ = ""; project_ = ""; uniquifier_ = ""; description_ = ""; agentVersion_ = ""; sourceContexts_ = java.util.Collections.emptyList(); extSourceContexts_ = java.util.Collections.emptyList(); } @java.lang.Override @SuppressWarnings({"unused"}) protected java.lang.Object newInstance(UnusedPrivateParameter unused) { return new Debuggee(); } @java.lang.Override public final com.google.protobuf.UnknownFieldSet getUnknownFields() { return this.unknownFields; } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.devtools.clouddebugger.v2.DataProto .internal_static_google_devtools_clouddebugger_v2_Debuggee_descriptor; } @SuppressWarnings({"rawtypes"}) @java.lang.Override protected com.google.protobuf.MapField internalGetMapField(int number) { switch (number) { case 11: return internalGetLabels(); default: throw new RuntimeException("Invalid map field number: " + number); } } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.devtools.clouddebugger.v2.DataProto .internal_static_google_devtools_clouddebugger_v2_Debuggee_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.devtools.clouddebugger.v2.Debuggee.class, com.google.devtools.clouddebugger.v2.Debuggee.Builder.class); } public static final int ID_FIELD_NUMBER = 1; private volatile java.lang.Object id_; /** * * * <pre> * Unique identifier for the debuggee generated by the controller service. * </pre> * * <code>string id = 1;</code> * * @return The id. */ @java.lang.Override public java.lang.String getId() { java.lang.Object ref = id_; if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); id_ = s; return s; } } /** * * * <pre> * Unique identifier for the debuggee generated by the controller service. * </pre> * * <code>string id = 1;</code> * * @return The bytes for id. */ @java.lang.Override public com.google.protobuf.ByteString getIdBytes() { java.lang.Object ref = id_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); id_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } public static final int PROJECT_FIELD_NUMBER = 2; private volatile java.lang.Object project_; /** * * * <pre> * Project the debuggee is associated with. * Use project number or id when registering a Google Cloud Platform project. * </pre> * * <code>string project = 2;</code> * * @return The project. */ @java.lang.Override public java.lang.String getProject() { java.lang.Object ref = project_; if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); project_ = s; return s; } } /** * * * <pre> * Project the debuggee is associated with. * Use project number or id when registering a Google Cloud Platform project. * </pre> * * <code>string project = 2;</code> * * @return The bytes for project. */ @java.lang.Override public com.google.protobuf.ByteString getProjectBytes() { java.lang.Object ref = project_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); project_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } public static final int UNIQUIFIER_FIELD_NUMBER = 3; private volatile java.lang.Object uniquifier_; /** * * * <pre> * Uniquifier to further distinguish the application. * It is possible that different applications might have identical values in * the debuggee message, thus, incorrectly identified as a single application * by the Controller service. This field adds salt to further distinguish the * application. Agents should consider seeding this field with value that * identifies the code, binary, configuration and environment. * </pre> * * <code>string uniquifier = 3;</code> * * @return The uniquifier. */ @java.lang.Override public java.lang.String getUniquifier() { java.lang.Object ref = uniquifier_; if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); uniquifier_ = s; return s; } } /** * * * <pre> * Uniquifier to further distinguish the application. * It is possible that different applications might have identical values in * the debuggee message, thus, incorrectly identified as a single application * by the Controller service. This field adds salt to further distinguish the * application. Agents should consider seeding this field with value that * identifies the code, binary, configuration and environment. * </pre> * * <code>string uniquifier = 3;</code> * * @return The bytes for uniquifier. */ @java.lang.Override public com.google.protobuf.ByteString getUniquifierBytes() { java.lang.Object ref = uniquifier_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); uniquifier_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } public static final int DESCRIPTION_FIELD_NUMBER = 4; private volatile java.lang.Object description_; /** * * * <pre> * Human readable description of the debuggee. * Including a human-readable project name, environment name and version * information is recommended. * </pre> * * <code>string description = 4;</code> * * @return The description. */ @java.lang.Override public java.lang.String getDescription() { java.lang.Object ref = description_; if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); description_ = s; return s; } } /** * * * <pre> * Human readable description of the debuggee. * Including a human-readable project name, environment name and version * information is recommended. * </pre> * * <code>string description = 4;</code> * * @return The bytes for description. */ @java.lang.Override public com.google.protobuf.ByteString getDescriptionBytes() { java.lang.Object ref = description_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); description_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } public static final int IS_INACTIVE_FIELD_NUMBER = 5; private boolean isInactive_; /** * * * <pre> * If set to `true`, indicates that Controller service does not detect any * activity from the debuggee agents and the application is possibly stopped. * </pre> * * <code>bool is_inactive = 5;</code> * * @return The isInactive. */ @java.lang.Override public boolean getIsInactive() { return isInactive_; } public static final int AGENT_VERSION_FIELD_NUMBER = 6; private volatile java.lang.Object agentVersion_; /** * * * <pre> * Version ID of the agent. * Schema: `domain/language-platform/vmajor.minor` (for example * `google.com/java-gcp/v1.1`). * </pre> * * <code>string agent_version = 6;</code> * * @return The agentVersion. */ @java.lang.Override public java.lang.String getAgentVersion() { java.lang.Object ref = agentVersion_; if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); agentVersion_ = s; return s; } } /** * * * <pre> * Version ID of the agent. * Schema: `domain/language-platform/vmajor.minor` (for example * `google.com/java-gcp/v1.1`). * </pre> * * <code>string agent_version = 6;</code> * * @return The bytes for agentVersion. */ @java.lang.Override public com.google.protobuf.ByteString getAgentVersionBytes() { java.lang.Object ref = agentVersion_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); agentVersion_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } public static final int IS_DISABLED_FIELD_NUMBER = 7; private boolean isDisabled_; /** * * * <pre> * If set to `true`, indicates that the agent should disable itself and * detach from the debuggee. * </pre> * * <code>bool is_disabled = 7;</code> * * @return The isDisabled. */ @java.lang.Override public boolean getIsDisabled() { return isDisabled_; } public static final int STATUS_FIELD_NUMBER = 8; private com.google.devtools.clouddebugger.v2.StatusMessage status_; /** * * * <pre> * Human readable message to be displayed to the user about this debuggee. * Absence of this field indicates no status. The message can be either * informational or an error status. * </pre> * * <code>.google.devtools.clouddebugger.v2.StatusMessage status = 8;</code> * * @return Whether the status field is set. */ @java.lang.Override public boolean hasStatus() { return status_ != null; } /** * * * <pre> * Human readable message to be displayed to the user about this debuggee. * Absence of this field indicates no status. The message can be either * informational or an error status. * </pre> * * <code>.google.devtools.clouddebugger.v2.StatusMessage status = 8;</code> * * @return The status. */ @java.lang.Override public com.google.devtools.clouddebugger.v2.StatusMessage getStatus() { return status_ == null ? com.google.devtools.clouddebugger.v2.StatusMessage.getDefaultInstance() : status_; } /** * * * <pre> * Human readable message to be displayed to the user about this debuggee. * Absence of this field indicates no status. The message can be either * informational or an error status. * </pre> * * <code>.google.devtools.clouddebugger.v2.StatusMessage status = 8;</code> */ @java.lang.Override public com.google.devtools.clouddebugger.v2.StatusMessageOrBuilder getStatusOrBuilder() { return getStatus(); } public static final int SOURCE_CONTEXTS_FIELD_NUMBER = 9; private java.util.List<com.google.devtools.source.v1.SourceContext> sourceContexts_; /** * * * <pre> * References to the locations and revisions of the source code used in the * deployed application. * </pre> * * <code>repeated .google.devtools.source.v1.SourceContext source_contexts = 9;</code> */ @java.lang.Override public java.util.List<com.google.devtools.source.v1.SourceContext> getSourceContextsList() { return sourceContexts_; } /** * * * <pre> * References to the locations and revisions of the source code used in the * deployed application. * </pre> * * <code>repeated .google.devtools.source.v1.SourceContext source_contexts = 9;</code> */ @java.lang.Override public java.util.List<? extends com.google.devtools.source.v1.SourceContextOrBuilder> getSourceContextsOrBuilderList() { return sourceContexts_; } /** * * * <pre> * References to the locations and revisions of the source code used in the * deployed application. * </pre> * * <code>repeated .google.devtools.source.v1.SourceContext source_contexts = 9;</code> */ @java.lang.Override public int getSourceContextsCount() { return sourceContexts_.size(); } /** * * * <pre> * References to the locations and revisions of the source code used in the * deployed application. * </pre> * * <code>repeated .google.devtools.source.v1.SourceContext source_contexts = 9;</code> */ @java.lang.Override public com.google.devtools.source.v1.SourceContext getSourceContexts(int index) { return sourceContexts_.get(index); } /** * * * <pre> * References to the locations and revisions of the source code used in the * deployed application. * </pre> * * <code>repeated .google.devtools.source.v1.SourceContext source_contexts = 9;</code> */ @java.lang.Override public com.google.devtools.source.v1.SourceContextOrBuilder getSourceContextsOrBuilder( int index) { return sourceContexts_.get(index); } public static final int EXT_SOURCE_CONTEXTS_FIELD_NUMBER = 13; private java.util.List<com.google.devtools.source.v1.ExtendedSourceContext> extSourceContexts_; /** * * * <pre> * References to the locations and revisions of the source code used in the * deployed application. * </pre> * * <code> * repeated .google.devtools.source.v1.ExtendedSourceContext ext_source_contexts = 13 [deprecated = true]; * </code> */ @java.lang.Override @java.lang.Deprecated public java.util.List<com.google.devtools.source.v1.ExtendedSourceContext> getExtSourceContextsList() { return extSourceContexts_; } /** * * * <pre> * References to the locations and revisions of the source code used in the * deployed application. * </pre> * * <code> * repeated .google.devtools.source.v1.ExtendedSourceContext ext_source_contexts = 13 [deprecated = true]; * </code> */ @java.lang.Override @java.lang.Deprecated public java.util.List<? extends com.google.devtools.source.v1.ExtendedSourceContextOrBuilder> getExtSourceContextsOrBuilderList() { return extSourceContexts_; } /** * * * <pre> * References to the locations and revisions of the source code used in the * deployed application. * </pre> * * <code> * repeated .google.devtools.source.v1.ExtendedSourceContext ext_source_contexts = 13 [deprecated = true]; * </code> */ @java.lang.Override @java.lang.Deprecated public int getExtSourceContextsCount() { return extSourceContexts_.size(); } /** * * * <pre> * References to the locations and revisions of the source code used in the * deployed application. * </pre> * * <code> * repeated .google.devtools.source.v1.ExtendedSourceContext ext_source_contexts = 13 [deprecated = true]; * </code> */ @java.lang.Override @java.lang.Deprecated public com.google.devtools.source.v1.ExtendedSourceContext getExtSourceContexts(int index) { return extSourceContexts_.get(index); } /** * * * <pre> * References to the locations and revisions of the source code used in the * deployed application. * </pre> * * <code> * repeated .google.devtools.source.v1.ExtendedSourceContext ext_source_contexts = 13 [deprecated = true]; * </code> */ @java.lang.Override @java.lang.Deprecated public com.google.devtools.source.v1.ExtendedSourceContextOrBuilder getExtSourceContextsOrBuilder( int index) { return extSourceContexts_.get(index); } public static final int LABELS_FIELD_NUMBER = 11; private static final class LabelsDefaultEntryHolder { static final com.google.protobuf.MapEntry<java.lang.String, java.lang.String> defaultEntry = com.google.protobuf.MapEntry.<java.lang.String, java.lang.String>newDefaultInstance( com.google.devtools.clouddebugger.v2.DataProto .internal_static_google_devtools_clouddebugger_v2_Debuggee_LabelsEntry_descriptor, com.google.protobuf.WireFormat.FieldType.STRING, "", com.google.protobuf.WireFormat.FieldType.STRING, ""); } private com.google.protobuf.MapField<java.lang.String, java.lang.String> labels_; private com.google.protobuf.MapField<java.lang.String, java.lang.String> internalGetLabels() { if (labels_ == null) { return com.google.protobuf.MapField.emptyMapField(LabelsDefaultEntryHolder.defaultEntry); } return labels_; } public int getLabelsCount() { return internalGetLabels().getMap().size(); } /** * * * <pre> * A set of custom debuggee properties, populated by the agent, to be * displayed to the user. * </pre> * * <code>map&lt;string, string&gt; labels = 11;</code> */ @java.lang.Override public boolean containsLabels(java.lang.String key) { if (key == null) { throw new NullPointerException("map key"); } return internalGetLabels().getMap().containsKey(key); } /** Use {@link #getLabelsMap()} instead. */ @java.lang.Override @java.lang.Deprecated public java.util.Map<java.lang.String, java.lang.String> getLabels() { return getLabelsMap(); } /** * * * <pre> * A set of custom debuggee properties, populated by the agent, to be * displayed to the user. * </pre> * * <code>map&lt;string, string&gt; labels = 11;</code> */ @java.lang.Override public java.util.Map<java.lang.String, java.lang.String> getLabelsMap() { return internalGetLabels().getMap(); } /** * * * <pre> * A set of custom debuggee properties, populated by the agent, to be * displayed to the user. * </pre> * * <code>map&lt;string, string&gt; labels = 11;</code> */ @java.lang.Override public java.lang.String getLabelsOrDefault(java.lang.String key, java.lang.String defaultValue) { if (key == null) { throw new NullPointerException("map key"); } java.util.Map<java.lang.String, java.lang.String> map = internalGetLabels().getMap(); return map.containsKey(key) ? map.get(key) : defaultValue; } /** * * * <pre> * A set of custom debuggee properties, populated by the agent, to be * displayed to the user. * </pre> * * <code>map&lt;string, string&gt; labels = 11;</code> */ @java.lang.Override public java.lang.String getLabelsOrThrow(java.lang.String key) { if (key == null) { throw new NullPointerException("map key"); } java.util.Map<java.lang.String, java.lang.String> map = internalGetLabels().getMap(); if (!map.containsKey(key)) { throw new java.lang.IllegalArgumentException(); } return map.get(key); } private byte memoizedIsInitialized = -1; @java.lang.Override public final boolean isInitialized() { byte isInitialized = memoizedIsInitialized; if (isInitialized == 1) return true; if (isInitialized == 0) return false; memoizedIsInitialized = 1; return true; } @java.lang.Override public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException { if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(id_)) { com.google.protobuf.GeneratedMessageV3.writeString(output, 1, id_); } if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(project_)) { com.google.protobuf.GeneratedMessageV3.writeString(output, 2, project_); } if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(uniquifier_)) { com.google.protobuf.GeneratedMessageV3.writeString(output, 3, uniquifier_); } if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(description_)) { com.google.protobuf.GeneratedMessageV3.writeString(output, 4, description_); } if (isInactive_ != false) { output.writeBool(5, isInactive_); } if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(agentVersion_)) { com.google.protobuf.GeneratedMessageV3.writeString(output, 6, agentVersion_); } if (isDisabled_ != false) { output.writeBool(7, isDisabled_); } if (status_ != null) { output.writeMessage(8, getStatus()); } for (int i = 0; i < sourceContexts_.size(); i++) { output.writeMessage(9, sourceContexts_.get(i)); } com.google.protobuf.GeneratedMessageV3.serializeStringMapTo( output, internalGetLabels(), LabelsDefaultEntryHolder.defaultEntry, 11); for (int i = 0; i < extSourceContexts_.size(); i++) { output.writeMessage(13, extSourceContexts_.get(i)); } getUnknownFields().writeTo(output); } @java.lang.Override public int getSerializedSize() { int size = memoizedSize; if (size != -1) return size; size = 0; if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(id_)) { size += com.google.protobuf.GeneratedMessageV3.computeStringSize(1, id_); } if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(project_)) { size += com.google.protobuf.GeneratedMessageV3.computeStringSize(2, project_); } if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(uniquifier_)) { size += com.google.protobuf.GeneratedMessageV3.computeStringSize(3, uniquifier_); } if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(description_)) { size += com.google.protobuf.GeneratedMessageV3.computeStringSize(4, description_); } if (isInactive_ != false) { size += com.google.protobuf.CodedOutputStream.computeBoolSize(5, isInactive_); } if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(agentVersion_)) { size += com.google.protobuf.GeneratedMessageV3.computeStringSize(6, agentVersion_); } if (isDisabled_ != false) { size += com.google.protobuf.CodedOutputStream.computeBoolSize(7, isDisabled_); } if (status_ != null) { size += com.google.protobuf.CodedOutputStream.computeMessageSize(8, getStatus()); } for (int i = 0; i < sourceContexts_.size(); i++) { size += com.google.protobuf.CodedOutputStream.computeMessageSize(9, sourceContexts_.get(i)); } for (java.util.Map.Entry<java.lang.String, java.lang.String> entry : internalGetLabels().getMap().entrySet()) { com.google.protobuf.MapEntry<java.lang.String, java.lang.String> labels__ = LabelsDefaultEntryHolder.defaultEntry .newBuilderForType() .setKey(entry.getKey()) .setValue(entry.getValue()) .build(); size += com.google.protobuf.CodedOutputStream.computeMessageSize(11, labels__); } for (int i = 0; i < extSourceContexts_.size(); i++) { size += com.google.protobuf.CodedOutputStream.computeMessageSize(13, extSourceContexts_.get(i)); } size += getUnknownFields().getSerializedSize(); memoizedSize = size; return size; } @java.lang.Override public boolean equals(final java.lang.Object obj) { if (obj == this) { return true; } if (!(obj instanceof com.google.devtools.clouddebugger.v2.Debuggee)) { return super.equals(obj); } com.google.devtools.clouddebugger.v2.Debuggee other = (com.google.devtools.clouddebugger.v2.Debuggee) obj; if (!getId().equals(other.getId())) return false; if (!getProject().equals(other.getProject())) return false; if (!getUniquifier().equals(other.getUniquifier())) return false; if (!getDescription().equals(other.getDescription())) return false; if (getIsInactive() != other.getIsInactive()) return false; if (!getAgentVersion().equals(other.getAgentVersion())) return false; if (getIsDisabled() != other.getIsDisabled()) return false; if (hasStatus() != other.hasStatus()) return false; if (hasStatus()) { if (!getStatus().equals(other.getStatus())) return false; } if (!getSourceContextsList().equals(other.getSourceContextsList())) return false; if (!getExtSourceContextsList().equals(other.getExtSourceContextsList())) return false; if (!internalGetLabels().equals(other.internalGetLabels())) return false; if (!getUnknownFields().equals(other.getUnknownFields())) return false; return true; } @java.lang.Override public int hashCode() { if (memoizedHashCode != 0) { return memoizedHashCode; } int hash = 41; hash = (19 * hash) + getDescriptor().hashCode(); hash = (37 * hash) + ID_FIELD_NUMBER; hash = (53 * hash) + getId().hashCode(); hash = (37 * hash) + PROJECT_FIELD_NUMBER; hash = (53 * hash) + getProject().hashCode(); hash = (37 * hash) + UNIQUIFIER_FIELD_NUMBER; hash = (53 * hash) + getUniquifier().hashCode(); hash = (37 * hash) + DESCRIPTION_FIELD_NUMBER; hash = (53 * hash) + getDescription().hashCode(); hash = (37 * hash) + IS_INACTIVE_FIELD_NUMBER; hash = (53 * hash) + com.google.protobuf.Internal.hashBoolean(getIsInactive()); hash = (37 * hash) + AGENT_VERSION_FIELD_NUMBER; hash = (53 * hash) + getAgentVersion().hashCode(); hash = (37 * hash) + IS_DISABLED_FIELD_NUMBER; hash = (53 * hash) + com.google.protobuf.Internal.hashBoolean(getIsDisabled()); if (hasStatus()) { hash = (37 * hash) + STATUS_FIELD_NUMBER; hash = (53 * hash) + getStatus().hashCode(); } if (getSourceContextsCount() > 0) { hash = (37 * hash) + SOURCE_CONTEXTS_FIELD_NUMBER; hash = (53 * hash) + getSourceContextsList().hashCode(); } if (getExtSourceContextsCount() > 0) { hash = (37 * hash) + EXT_SOURCE_CONTEXTS_FIELD_NUMBER; hash = (53 * hash) + getExtSourceContextsList().hashCode(); } if (!internalGetLabels().getMap().isEmpty()) { hash = (37 * hash) + LABELS_FIELD_NUMBER; hash = (53 * hash) + internalGetLabels().hashCode(); } hash = (29 * hash) + getUnknownFields().hashCode(); memoizedHashCode = hash; return hash; } public static com.google.devtools.clouddebugger.v2.Debuggee parseFrom(java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.devtools.clouddebugger.v2.Debuggee parseFrom( java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.devtools.clouddebugger.v2.Debuggee parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.devtools.clouddebugger.v2.Debuggee parseFrom( com.google.protobuf.ByteString data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.devtools.clouddebugger.v2.Debuggee parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.devtools.clouddebugger.v2.Debuggee parseFrom( byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.devtools.clouddebugger.v2.Debuggee parseFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); } public static com.google.devtools.clouddebugger.v2.Debuggee parseFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException( PARSER, input, extensionRegistry); } public static com.google.devtools.clouddebugger.v2.Debuggee parseDelimitedFrom( java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input); } public static com.google.devtools.clouddebugger.v2.Debuggee parseDelimitedFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException( PARSER, input, extensionRegistry); } public static com.google.devtools.clouddebugger.v2.Debuggee parseFrom( com.google.protobuf.CodedInputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); } public static com.google.devtools.clouddebugger.v2.Debuggee parseFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException( PARSER, input, extensionRegistry); } @java.lang.Override public Builder newBuilderForType() { return newBuilder(); } public static Builder newBuilder() { return DEFAULT_INSTANCE.toBuilder(); } public static Builder newBuilder(com.google.devtools.clouddebugger.v2.Debuggee prototype) { return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype); } @java.lang.Override public Builder toBuilder() { return this == DEFAULT_INSTANCE ? new Builder() : new Builder().mergeFrom(this); } @java.lang.Override protected Builder newBuilderForType(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { Builder builder = new Builder(parent); return builder; } /** * * * <pre> * Represents the debugged application. The application may include one or more * replicated processes executing the same code. Each of these processes is * attached with a debugger agent, carrying out the debugging commands. * Agents attached to the same debuggee identify themselves as such by using * exactly the same Debuggee message value when registering. * </pre> * * Protobuf type {@code google.devtools.clouddebugger.v2.Debuggee} */ public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder> implements // @@protoc_insertion_point(builder_implements:google.devtools.clouddebugger.v2.Debuggee) com.google.devtools.clouddebugger.v2.DebuggeeOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.devtools.clouddebugger.v2.DataProto .internal_static_google_devtools_clouddebugger_v2_Debuggee_descriptor; } @SuppressWarnings({"rawtypes"}) protected com.google.protobuf.MapField internalGetMapField(int number) { switch (number) { case 11: return internalGetLabels(); default: throw new RuntimeException("Invalid map field number: " + number); } } @SuppressWarnings({"rawtypes"}) protected com.google.protobuf.MapField internalGetMutableMapField(int number) { switch (number) { case 11: return internalGetMutableLabels(); default: throw new RuntimeException("Invalid map field number: " + number); } } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.devtools.clouddebugger.v2.DataProto .internal_static_google_devtools_clouddebugger_v2_Debuggee_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.devtools.clouddebugger.v2.Debuggee.class, com.google.devtools.clouddebugger.v2.Debuggee.Builder.class); } // Construct using com.google.devtools.clouddebugger.v2.Debuggee.newBuilder() private Builder() {} private Builder(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { super(parent); } @java.lang.Override public Builder clear() { super.clear(); id_ = ""; project_ = ""; uniquifier_ = ""; description_ = ""; isInactive_ = false; agentVersion_ = ""; isDisabled_ = false; if (statusBuilder_ == null) { status_ = null; } else { status_ = null; statusBuilder_ = null; } if (sourceContextsBuilder_ == null) { sourceContexts_ = java.util.Collections.emptyList(); } else { sourceContexts_ = null; sourceContextsBuilder_.clear(); } bitField0_ = (bitField0_ & ~0x00000001); if (extSourceContextsBuilder_ == null) { extSourceContexts_ = java.util.Collections.emptyList(); } else { extSourceContexts_ = null; extSourceContextsBuilder_.clear(); } bitField0_ = (bitField0_ & ~0x00000002); internalGetMutableLabels().clear(); return this; } @java.lang.Override public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return com.google.devtools.clouddebugger.v2.DataProto .internal_static_google_devtools_clouddebugger_v2_Debuggee_descriptor; } @java.lang.Override public com.google.devtools.clouddebugger.v2.Debuggee getDefaultInstanceForType() { return com.google.devtools.clouddebugger.v2.Debuggee.getDefaultInstance(); } @java.lang.Override public com.google.devtools.clouddebugger.v2.Debuggee build() { com.google.devtools.clouddebugger.v2.Debuggee result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } @java.lang.Override public com.google.devtools.clouddebugger.v2.Debuggee buildPartial() { com.google.devtools.clouddebugger.v2.Debuggee result = new com.google.devtools.clouddebugger.v2.Debuggee(this); int from_bitField0_ = bitField0_; result.id_ = id_; result.project_ = project_; result.uniquifier_ = uniquifier_; result.description_ = description_; result.isInactive_ = isInactive_; result.agentVersion_ = agentVersion_; result.isDisabled_ = isDisabled_; if (statusBuilder_ == null) { result.status_ = status_; } else { result.status_ = statusBuilder_.build(); } if (sourceContextsBuilder_ == null) { if (((bitField0_ & 0x00000001) != 0)) { sourceContexts_ = java.util.Collections.unmodifiableList(sourceContexts_); bitField0_ = (bitField0_ & ~0x00000001); } result.sourceContexts_ = sourceContexts_; } else { result.sourceContexts_ = sourceContextsBuilder_.build(); } if (extSourceContextsBuilder_ == null) { if (((bitField0_ & 0x00000002) != 0)) { extSourceContexts_ = java.util.Collections.unmodifiableList(extSourceContexts_); bitField0_ = (bitField0_ & ~0x00000002); } result.extSourceContexts_ = extSourceContexts_; } else { result.extSourceContexts_ = extSourceContextsBuilder_.build(); } result.labels_ = internalGetLabels(); result.labels_.makeImmutable(); onBuilt(); return result; } @java.lang.Override public Builder clone() { return super.clone(); } @java.lang.Override public Builder setField( com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { return super.setField(field, value); } @java.lang.Override public Builder clearField(com.google.protobuf.Descriptors.FieldDescriptor field) { return super.clearField(field); } @java.lang.Override public Builder clearOneof(com.google.protobuf.Descriptors.OneofDescriptor oneof) { return super.clearOneof(oneof); } @java.lang.Override public Builder setRepeatedField( com.google.protobuf.Descriptors.FieldDescriptor field, int index, java.lang.Object value) { return super.setRepeatedField(field, index, value); } @java.lang.Override public Builder addRepeatedField( com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { return super.addRepeatedField(field, value); } @java.lang.Override public Builder mergeFrom(com.google.protobuf.Message other) { if (other instanceof com.google.devtools.clouddebugger.v2.Debuggee) { return mergeFrom((com.google.devtools.clouddebugger.v2.Debuggee) other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom(com.google.devtools.clouddebugger.v2.Debuggee other) { if (other == com.google.devtools.clouddebugger.v2.Debuggee.getDefaultInstance()) return this; if (!other.getId().isEmpty()) { id_ = other.id_; onChanged(); } if (!other.getProject().isEmpty()) { project_ = other.project_; onChanged(); } if (!other.getUniquifier().isEmpty()) { uniquifier_ = other.uniquifier_; onChanged(); } if (!other.getDescription().isEmpty()) { description_ = other.description_; onChanged(); } if (other.getIsInactive() != false) { setIsInactive(other.getIsInactive()); } if (!other.getAgentVersion().isEmpty()) { agentVersion_ = other.agentVersion_; onChanged(); } if (other.getIsDisabled() != false) { setIsDisabled(other.getIsDisabled()); } if (other.hasStatus()) { mergeStatus(other.getStatus()); } if (sourceContextsBuilder_ == null) { if (!other.sourceContexts_.isEmpty()) { if (sourceContexts_.isEmpty()) { sourceContexts_ = other.sourceContexts_; bitField0_ = (bitField0_ & ~0x00000001); } else { ensureSourceContextsIsMutable(); sourceContexts_.addAll(other.sourceContexts_); } onChanged(); } } else { if (!other.sourceContexts_.isEmpty()) { if (sourceContextsBuilder_.isEmpty()) { sourceContextsBuilder_.dispose(); sourceContextsBuilder_ = null; sourceContexts_ = other.sourceContexts_; bitField0_ = (bitField0_ & ~0x00000001); sourceContextsBuilder_ = com.google.protobuf.GeneratedMessageV3.alwaysUseFieldBuilders ? getSourceContextsFieldBuilder() : null; } else { sourceContextsBuilder_.addAllMessages(other.sourceContexts_); } } } if (extSourceContextsBuilder_ == null) { if (!other.extSourceContexts_.isEmpty()) { if (extSourceContexts_.isEmpty()) { extSourceContexts_ = other.extSourceContexts_; bitField0_ = (bitField0_ & ~0x00000002); } else { ensureExtSourceContextsIsMutable(); extSourceContexts_.addAll(other.extSourceContexts_); } onChanged(); } } else { if (!other.extSourceContexts_.isEmpty()) { if (extSourceContextsBuilder_.isEmpty()) { extSourceContextsBuilder_.dispose(); extSourceContextsBuilder_ = null; extSourceContexts_ = other.extSourceContexts_; bitField0_ = (bitField0_ & ~0x00000002); extSourceContextsBuilder_ = com.google.protobuf.GeneratedMessageV3.alwaysUseFieldBuilders ? getExtSourceContextsFieldBuilder() : null; } else { extSourceContextsBuilder_.addAllMessages(other.extSourceContexts_); } } } internalGetMutableLabels().mergeFrom(other.internalGetLabels()); this.mergeUnknownFields(other.getUnknownFields()); onChanged(); return this; } @java.lang.Override public final boolean isInitialized() { return true; } @java.lang.Override public Builder mergeFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { if (extensionRegistry == null) { throw new java.lang.NullPointerException(); } try { boolean done = false; while (!done) { int tag = input.readTag(); switch (tag) { case 0: done = true; break; case 10: { id_ = input.readStringRequireUtf8(); break; } // case 10 case 18: { project_ = input.readStringRequireUtf8(); break; } // case 18 case 26: { uniquifier_ = input.readStringRequireUtf8(); break; } // case 26 case 34: { description_ = input.readStringRequireUtf8(); break; } // case 34 case 40: { isInactive_ = input.readBool(); break; } // case 40 case 50: { agentVersion_ = input.readStringRequireUtf8(); break; } // case 50 case 56: { isDisabled_ = input.readBool(); break; } // case 56 case 66: { input.readMessage(getStatusFieldBuilder().getBuilder(), extensionRegistry); break; } // case 66 case 74: { com.google.devtools.source.v1.SourceContext m = input.readMessage( com.google.devtools.source.v1.SourceContext.parser(), extensionRegistry); if (sourceContextsBuilder_ == null) { ensureSourceContextsIsMutable(); sourceContexts_.add(m); } else { sourceContextsBuilder_.addMessage(m); } break; } // case 74 case 90: { com.google.protobuf.MapEntry<java.lang.String, java.lang.String> labels__ = input.readMessage( LabelsDefaultEntryHolder.defaultEntry.getParserForType(), extensionRegistry); internalGetMutableLabels() .getMutableMap() .put(labels__.getKey(), labels__.getValue()); break; } // case 90 case 106: { com.google.devtools.source.v1.ExtendedSourceContext m = input.readMessage( com.google.devtools.source.v1.ExtendedSourceContext.parser(), extensionRegistry); if (extSourceContextsBuilder_ == null) { ensureExtSourceContextsIsMutable(); extSourceContexts_.add(m); } else { extSourceContextsBuilder_.addMessage(m); } break; } // case 106 default: { if (!super.parseUnknownField(input, extensionRegistry, tag)) { done = true; // was an endgroup tag } break; } // default: } // switch (tag) } // while (!done) } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.unwrapIOException(); } finally { onChanged(); } // finally return this; } private int bitField0_; private java.lang.Object id_ = ""; /** * * * <pre> * Unique identifier for the debuggee generated by the controller service. * </pre> * * <code>string id = 1;</code> * * @return The id. */ public java.lang.String getId() { java.lang.Object ref = id_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); id_ = s; return s; } else { return (java.lang.String) ref; } } /** * * * <pre> * Unique identifier for the debuggee generated by the controller service. * </pre> * * <code>string id = 1;</code> * * @return The bytes for id. */ public com.google.protobuf.ByteString getIdBytes() { java.lang.Object ref = id_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); id_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** * * * <pre> * Unique identifier for the debuggee generated by the controller service. * </pre> * * <code>string id = 1;</code> * * @param value The id to set. * @return This builder for chaining. */ public Builder setId(java.lang.String value) { if (value == null) { throw new NullPointerException(); } id_ = value; onChanged(); return this; } /** * * * <pre> * Unique identifier for the debuggee generated by the controller service. * </pre> * * <code>string id = 1;</code> * * @return This builder for chaining. */ public Builder clearId() { id_ = getDefaultInstance().getId(); onChanged(); return this; } /** * * * <pre> * Unique identifier for the debuggee generated by the controller service. * </pre> * * <code>string id = 1;</code> * * @param value The bytes for id to set. * @return This builder for chaining. */ public Builder setIdBytes(com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); id_ = value; onChanged(); return this; } private java.lang.Object project_ = ""; /** * * * <pre> * Project the debuggee is associated with. * Use project number or id when registering a Google Cloud Platform project. * </pre> * * <code>string project = 2;</code> * * @return The project. */ public java.lang.String getProject() { java.lang.Object ref = project_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); project_ = s; return s; } else { return (java.lang.String) ref; } } /** * * * <pre> * Project the debuggee is associated with. * Use project number or id when registering a Google Cloud Platform project. * </pre> * * <code>string project = 2;</code> * * @return The bytes for project. */ public com.google.protobuf.ByteString getProjectBytes() { java.lang.Object ref = project_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); project_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** * * * <pre> * Project the debuggee is associated with. * Use project number or id when registering a Google Cloud Platform project. * </pre> * * <code>string project = 2;</code> * * @param value The project to set. * @return This builder for chaining. */ public Builder setProject(java.lang.String value) { if (value == null) { throw new NullPointerException(); } project_ = value; onChanged(); return this; } /** * * * <pre> * Project the debuggee is associated with. * Use project number or id when registering a Google Cloud Platform project. * </pre> * * <code>string project = 2;</code> * * @return This builder for chaining. */ public Builder clearProject() { project_ = getDefaultInstance().getProject(); onChanged(); return this; } /** * * * <pre> * Project the debuggee is associated with. * Use project number or id when registering a Google Cloud Platform project. * </pre> * * <code>string project = 2;</code> * * @param value The bytes for project to set. * @return This builder for chaining. */ public Builder setProjectBytes(com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); project_ = value; onChanged(); return this; } private java.lang.Object uniquifier_ = ""; /** * * * <pre> * Uniquifier to further distinguish the application. * It is possible that different applications might have identical values in * the debuggee message, thus, incorrectly identified as a single application * by the Controller service. This field adds salt to further distinguish the * application. Agents should consider seeding this field with value that * identifies the code, binary, configuration and environment. * </pre> * * <code>string uniquifier = 3;</code> * * @return The uniquifier. */ public java.lang.String getUniquifier() { java.lang.Object ref = uniquifier_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); uniquifier_ = s; return s; } else { return (java.lang.String) ref; } } /** * * * <pre> * Uniquifier to further distinguish the application. * It is possible that different applications might have identical values in * the debuggee message, thus, incorrectly identified as a single application * by the Controller service. This field adds salt to further distinguish the * application. Agents should consider seeding this field with value that * identifies the code, binary, configuration and environment. * </pre> * * <code>string uniquifier = 3;</code> * * @return The bytes for uniquifier. */ public com.google.protobuf.ByteString getUniquifierBytes() { java.lang.Object ref = uniquifier_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); uniquifier_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** * * * <pre> * Uniquifier to further distinguish the application. * It is possible that different applications might have identical values in * the debuggee message, thus, incorrectly identified as a single application * by the Controller service. This field adds salt to further distinguish the * application. Agents should consider seeding this field with value that * identifies the code, binary, configuration and environment. * </pre> * * <code>string uniquifier = 3;</code> * * @param value The uniquifier to set. * @return This builder for chaining. */ public Builder setUniquifier(java.lang.String value) { if (value == null) { throw new NullPointerException(); } uniquifier_ = value; onChanged(); return this; } /** * * * <pre> * Uniquifier to further distinguish the application. * It is possible that different applications might have identical values in * the debuggee message, thus, incorrectly identified as a single application * by the Controller service. This field adds salt to further distinguish the * application. Agents should consider seeding this field with value that * identifies the code, binary, configuration and environment. * </pre> * * <code>string uniquifier = 3;</code> * * @return This builder for chaining. */ public Builder clearUniquifier() { uniquifier_ = getDefaultInstance().getUniquifier(); onChanged(); return this; } /** * * * <pre> * Uniquifier to further distinguish the application. * It is possible that different applications might have identical values in * the debuggee message, thus, incorrectly identified as a single application * by the Controller service. This field adds salt to further distinguish the * application. Agents should consider seeding this field with value that * identifies the code, binary, configuration and environment. * </pre> * * <code>string uniquifier = 3;</code> * * @param value The bytes for uniquifier to set. * @return This builder for chaining. */ public Builder setUniquifierBytes(com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); uniquifier_ = value; onChanged(); return this; } private java.lang.Object description_ = ""; /** * * * <pre> * Human readable description of the debuggee. * Including a human-readable project name, environment name and version * information is recommended. * </pre> * * <code>string description = 4;</code> * * @return The description. */ public java.lang.String getDescription() { java.lang.Object ref = description_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); description_ = s; return s; } else { return (java.lang.String) ref; } } /** * * * <pre> * Human readable description of the debuggee. * Including a human-readable project name, environment name and version * information is recommended. * </pre> * * <code>string description = 4;</code> * * @return The bytes for description. */ public com.google.protobuf.ByteString getDescriptionBytes() { java.lang.Object ref = description_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); description_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** * * * <pre> * Human readable description of the debuggee. * Including a human-readable project name, environment name and version * information is recommended. * </pre> * * <code>string description = 4;</code> * * @param value The description to set. * @return This builder for chaining. */ public Builder setDescription(java.lang.String value) { if (value == null) { throw new NullPointerException(); } description_ = value; onChanged(); return this; } /** * * * <pre> * Human readable description of the debuggee. * Including a human-readable project name, environment name and version * information is recommended. * </pre> * * <code>string description = 4;</code> * * @return This builder for chaining. */ public Builder clearDescription() { description_ = getDefaultInstance().getDescription(); onChanged(); return this; } /** * * * <pre> * Human readable description of the debuggee. * Including a human-readable project name, environment name and version * information is recommended. * </pre> * * <code>string description = 4;</code> * * @param value The bytes for description to set. * @return This builder for chaining. */ public Builder setDescriptionBytes(com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); description_ = value; onChanged(); return this; } private boolean isInactive_; /** * * * <pre> * If set to `true`, indicates that Controller service does not detect any * activity from the debuggee agents and the application is possibly stopped. * </pre> * * <code>bool is_inactive = 5;</code> * * @return The isInactive. */ @java.lang.Override public boolean getIsInactive() { return isInactive_; } /** * * * <pre> * If set to `true`, indicates that Controller service does not detect any * activity from the debuggee agents and the application is possibly stopped. * </pre> * * <code>bool is_inactive = 5;</code> * * @param value The isInactive to set. * @return This builder for chaining. */ public Builder setIsInactive(boolean value) { isInactive_ = value; onChanged(); return this; } /** * * * <pre> * If set to `true`, indicates that Controller service does not detect any * activity from the debuggee agents and the application is possibly stopped. * </pre> * * <code>bool is_inactive = 5;</code> * * @return This builder for chaining. */ public Builder clearIsInactive() { isInactive_ = false; onChanged(); return this; } private java.lang.Object agentVersion_ = ""; /** * * * <pre> * Version ID of the agent. * Schema: `domain/language-platform/vmajor.minor` (for example * `google.com/java-gcp/v1.1`). * </pre> * * <code>string agent_version = 6;</code> * * @return The agentVersion. */ public java.lang.String getAgentVersion() { java.lang.Object ref = agentVersion_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); agentVersion_ = s; return s; } else { return (java.lang.String) ref; } } /** * * * <pre> * Version ID of the agent. * Schema: `domain/language-platform/vmajor.minor` (for example * `google.com/java-gcp/v1.1`). * </pre> * * <code>string agent_version = 6;</code> * * @return The bytes for agentVersion. */ public com.google.protobuf.ByteString getAgentVersionBytes() { java.lang.Object ref = agentVersion_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); agentVersion_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** * * * <pre> * Version ID of the agent. * Schema: `domain/language-platform/vmajor.minor` (for example * `google.com/java-gcp/v1.1`). * </pre> * * <code>string agent_version = 6;</code> * * @param value The agentVersion to set. * @return This builder for chaining. */ public Builder setAgentVersion(java.lang.String value) { if (value == null) { throw new NullPointerException(); } agentVersion_ = value; onChanged(); return this; } /** * * * <pre> * Version ID of the agent. * Schema: `domain/language-platform/vmajor.minor` (for example * `google.com/java-gcp/v1.1`). * </pre> * * <code>string agent_version = 6;</code> * * @return This builder for chaining. */ public Builder clearAgentVersion() { agentVersion_ = getDefaultInstance().getAgentVersion(); onChanged(); return this; } /** * * * <pre> * Version ID of the agent. * Schema: `domain/language-platform/vmajor.minor` (for example * `google.com/java-gcp/v1.1`). * </pre> * * <code>string agent_version = 6;</code> * * @param value The bytes for agentVersion to set. * @return This builder for chaining. */ public Builder setAgentVersionBytes(com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); agentVersion_ = value; onChanged(); return this; } private boolean isDisabled_; /** * * * <pre> * If set to `true`, indicates that the agent should disable itself and * detach from the debuggee. * </pre> * * <code>bool is_disabled = 7;</code> * * @return The isDisabled. */ @java.lang.Override public boolean getIsDisabled() { return isDisabled_; } /** * * * <pre> * If set to `true`, indicates that the agent should disable itself and * detach from the debuggee. * </pre> * * <code>bool is_disabled = 7;</code> * * @param value The isDisabled to set. * @return This builder for chaining. */ public Builder setIsDisabled(boolean value) { isDisabled_ = value; onChanged(); return this; } /** * * * <pre> * If set to `true`, indicates that the agent should disable itself and * detach from the debuggee. * </pre> * * <code>bool is_disabled = 7;</code> * * @return This builder for chaining. */ public Builder clearIsDisabled() { isDisabled_ = false; onChanged(); return this; } private com.google.devtools.clouddebugger.v2.StatusMessage status_; private com.google.protobuf.SingleFieldBuilderV3< com.google.devtools.clouddebugger.v2.StatusMessage, com.google.devtools.clouddebugger.v2.StatusMessage.Builder, com.google.devtools.clouddebugger.v2.StatusMessageOrBuilder> statusBuilder_; /** * * * <pre> * Human readable message to be displayed to the user about this debuggee. * Absence of this field indicates no status. The message can be either * informational or an error status. * </pre> * * <code>.google.devtools.clouddebugger.v2.StatusMessage status = 8;</code> * * @return Whether the status field is set. */ public boolean hasStatus() { return statusBuilder_ != null || status_ != null; } /** * * * <pre> * Human readable message to be displayed to the user about this debuggee. * Absence of this field indicates no status. The message can be either * informational or an error status. * </pre> * * <code>.google.devtools.clouddebugger.v2.StatusMessage status = 8;</code> * * @return The status. */ public com.google.devtools.clouddebugger.v2.StatusMessage getStatus() { if (statusBuilder_ == null) { return status_ == null ? com.google.devtools.clouddebugger.v2.StatusMessage.getDefaultInstance() : status_; } else { return statusBuilder_.getMessage(); } } /** * * * <pre> * Human readable message to be displayed to the user about this debuggee. * Absence of this field indicates no status. The message can be either * informational or an error status. * </pre> * * <code>.google.devtools.clouddebugger.v2.StatusMessage status = 8;</code> */ public Builder setStatus(com.google.devtools.clouddebugger.v2.StatusMessage value) { if (statusBuilder_ == null) { if (value == null) { throw new NullPointerException(); } status_ = value; onChanged(); } else { statusBuilder_.setMessage(value); } return this; } /** * * * <pre> * Human readable message to be displayed to the user about this debuggee. * Absence of this field indicates no status. The message can be either * informational or an error status. * </pre> * * <code>.google.devtools.clouddebugger.v2.StatusMessage status = 8;</code> */ public Builder setStatus( com.google.devtools.clouddebugger.v2.StatusMessage.Builder builderForValue) { if (statusBuilder_ == null) { status_ = builderForValue.build(); onChanged(); } else { statusBuilder_.setMessage(builderForValue.build()); } return this; } /** * * * <pre> * Human readable message to be displayed to the user about this debuggee. * Absence of this field indicates no status. The message can be either * informational or an error status. * </pre> * * <code>.google.devtools.clouddebugger.v2.StatusMessage status = 8;</code> */ public Builder mergeStatus(com.google.devtools.clouddebugger.v2.StatusMessage value) { if (statusBuilder_ == null) { if (status_ != null) { status_ = com.google.devtools.clouddebugger.v2.StatusMessage.newBuilder(status_) .mergeFrom(value) .buildPartial(); } else { status_ = value; } onChanged(); } else { statusBuilder_.mergeFrom(value); } return this; } /** * * * <pre> * Human readable message to be displayed to the user about this debuggee. * Absence of this field indicates no status. The message can be either * informational or an error status. * </pre> * * <code>.google.devtools.clouddebugger.v2.StatusMessage status = 8;</code> */ public Builder clearStatus() { if (statusBuilder_ == null) { status_ = null; onChanged(); } else { status_ = null; statusBuilder_ = null; } return this; } /** * * * <pre> * Human readable message to be displayed to the user about this debuggee. * Absence of this field indicates no status. The message can be either * informational or an error status. * </pre> * * <code>.google.devtools.clouddebugger.v2.StatusMessage status = 8;</code> */ public com.google.devtools.clouddebugger.v2.StatusMessage.Builder getStatusBuilder() { onChanged(); return getStatusFieldBuilder().getBuilder(); } /** * * * <pre> * Human readable message to be displayed to the user about this debuggee. * Absence of this field indicates no status. The message can be either * informational or an error status. * </pre> * * <code>.google.devtools.clouddebugger.v2.StatusMessage status = 8;</code> */ public com.google.devtools.clouddebugger.v2.StatusMessageOrBuilder getStatusOrBuilder() { if (statusBuilder_ != null) { return statusBuilder_.getMessageOrBuilder(); } else { return status_ == null ? com.google.devtools.clouddebugger.v2.StatusMessage.getDefaultInstance() : status_; } } /** * * * <pre> * Human readable message to be displayed to the user about this debuggee. * Absence of this field indicates no status. The message can be either * informational or an error status. * </pre> * * <code>.google.devtools.clouddebugger.v2.StatusMessage status = 8;</code> */ private com.google.protobuf.SingleFieldBuilderV3< com.google.devtools.clouddebugger.v2.StatusMessage, com.google.devtools.clouddebugger.v2.StatusMessage.Builder, com.google.devtools.clouddebugger.v2.StatusMessageOrBuilder> getStatusFieldBuilder() { if (statusBuilder_ == null) { statusBuilder_ = new com.google.protobuf.SingleFieldBuilderV3< com.google.devtools.clouddebugger.v2.StatusMessage, com.google.devtools.clouddebugger.v2.StatusMessage.Builder, com.google.devtools.clouddebugger.v2.StatusMessageOrBuilder>( getStatus(), getParentForChildren(), isClean()); status_ = null; } return statusBuilder_; } private java.util.List<com.google.devtools.source.v1.SourceContext> sourceContexts_ = java.util.Collections.emptyList(); private void ensureSourceContextsIsMutable() { if (!((bitField0_ & 0x00000001) != 0)) { sourceContexts_ = new java.util.ArrayList<com.google.devtools.source.v1.SourceContext>(sourceContexts_); bitField0_ |= 0x00000001; } } private com.google.protobuf.RepeatedFieldBuilderV3< com.google.devtools.source.v1.SourceContext, com.google.devtools.source.v1.SourceContext.Builder, com.google.devtools.source.v1.SourceContextOrBuilder> sourceContextsBuilder_; /** * * * <pre> * References to the locations and revisions of the source code used in the * deployed application. * </pre> * * <code>repeated .google.devtools.source.v1.SourceContext source_contexts = 9;</code> */ public java.util.List<com.google.devtools.source.v1.SourceContext> getSourceContextsList() { if (sourceContextsBuilder_ == null) { return java.util.Collections.unmodifiableList(sourceContexts_); } else { return sourceContextsBuilder_.getMessageList(); } } /** * * * <pre> * References to the locations and revisions of the source code used in the * deployed application. * </pre> * * <code>repeated .google.devtools.source.v1.SourceContext source_contexts = 9;</code> */ public int getSourceContextsCount() { if (sourceContextsBuilder_ == null) { return sourceContexts_.size(); } else { return sourceContextsBuilder_.getCount(); } } /** * * * <pre> * References to the locations and revisions of the source code used in the * deployed application. * </pre> * * <code>repeated .google.devtools.source.v1.SourceContext source_contexts = 9;</code> */ public com.google.devtools.source.v1.SourceContext getSourceContexts(int index) { if (sourceContextsBuilder_ == null) { return sourceContexts_.get(index); } else { return sourceContextsBuilder_.getMessage(index); } } /** * * * <pre> * References to the locations and revisions of the source code used in the * deployed application. * </pre> * * <code>repeated .google.devtools.source.v1.SourceContext source_contexts = 9;</code> */ public Builder setSourceContexts(int index, com.google.devtools.source.v1.SourceContext value) { if (sourceContextsBuilder_ == null) { if (value == null) { throw new NullPointerException(); } ensureSourceContextsIsMutable(); sourceContexts_.set(index, value); onChanged(); } else { sourceContextsBuilder_.setMessage(index, value); } return this; } /** * * * <pre> * References to the locations and revisions of the source code used in the * deployed application. * </pre> * * <code>repeated .google.devtools.source.v1.SourceContext source_contexts = 9;</code> */ public Builder setSourceContexts( int index, com.google.devtools.source.v1.SourceContext.Builder builderForValue) { if (sourceContextsBuilder_ == null) { ensureSourceContextsIsMutable(); sourceContexts_.set(index, builderForValue.build()); onChanged(); } else { sourceContextsBuilder_.setMessage(index, builderForValue.build()); } return this; } /** * * * <pre> * References to the locations and revisions of the source code used in the * deployed application. * </pre> * * <code>repeated .google.devtools.source.v1.SourceContext source_contexts = 9;</code> */ public Builder addSourceContexts(com.google.devtools.source.v1.SourceContext value) { if (sourceContextsBuilder_ == null) { if (value == null) { throw new NullPointerException(); } ensureSourceContextsIsMutable(); sourceContexts_.add(value); onChanged(); } else { sourceContextsBuilder_.addMessage(value); } return this; } /** * * * <pre> * References to the locations and revisions of the source code used in the * deployed application. * </pre> * * <code>repeated .google.devtools.source.v1.SourceContext source_contexts = 9;</code> */ public Builder addSourceContexts(int index, com.google.devtools.source.v1.SourceContext value) { if (sourceContextsBuilder_ == null) { if (value == null) { throw new NullPointerException(); } ensureSourceContextsIsMutable(); sourceContexts_.add(index, value); onChanged(); } else { sourceContextsBuilder_.addMessage(index, value); } return this; } /** * * * <pre> * References to the locations and revisions of the source code used in the * deployed application. * </pre> * * <code>repeated .google.devtools.source.v1.SourceContext source_contexts = 9;</code> */ public Builder addSourceContexts( com.google.devtools.source.v1.SourceContext.Builder builderForValue) { if (sourceContextsBuilder_ == null) { ensureSourceContextsIsMutable(); sourceContexts_.add(builderForValue.build()); onChanged(); } else { sourceContextsBuilder_.addMessage(builderForValue.build()); } return this; } /** * * * <pre> * References to the locations and revisions of the source code used in the * deployed application. * </pre> * * <code>repeated .google.devtools.source.v1.SourceContext source_contexts = 9;</code> */ public Builder addSourceContexts( int index, com.google.devtools.source.v1.SourceContext.Builder builderForValue) { if (sourceContextsBuilder_ == null) { ensureSourceContextsIsMutable(); sourceContexts_.add(index, builderForValue.build()); onChanged(); } else { sourceContextsBuilder_.addMessage(index, builderForValue.build()); } return this; } /** * * * <pre> * References to the locations and revisions of the source code used in the * deployed application. * </pre> * * <code>repeated .google.devtools.source.v1.SourceContext source_contexts = 9;</code> */ public Builder addAllSourceContexts( java.lang.Iterable<? extends com.google.devtools.source.v1.SourceContext> values) { if (sourceContextsBuilder_ == null) { ensureSourceContextsIsMutable(); com.google.protobuf.AbstractMessageLite.Builder.addAll(values, sourceContexts_); onChanged(); } else { sourceContextsBuilder_.addAllMessages(values); } return this; } /** * * * <pre> * References to the locations and revisions of the source code used in the * deployed application. * </pre> * * <code>repeated .google.devtools.source.v1.SourceContext source_contexts = 9;</code> */ public Builder clearSourceContexts() { if (sourceContextsBuilder_ == null) { sourceContexts_ = java.util.Collections.emptyList(); bitField0_ = (bitField0_ & ~0x00000001); onChanged(); } else { sourceContextsBuilder_.clear(); } return this; } /** * * * <pre> * References to the locations and revisions of the source code used in the * deployed application. * </pre> * * <code>repeated .google.devtools.source.v1.SourceContext source_contexts = 9;</code> */ public Builder removeSourceContexts(int index) { if (sourceContextsBuilder_ == null) { ensureSourceContextsIsMutable(); sourceContexts_.remove(index); onChanged(); } else { sourceContextsBuilder_.remove(index); } return this; } /** * * * <pre> * References to the locations and revisions of the source code used in the * deployed application. * </pre> * * <code>repeated .google.devtools.source.v1.SourceContext source_contexts = 9;</code> */ public com.google.devtools.source.v1.SourceContext.Builder getSourceContextsBuilder(int index) { return getSourceContextsFieldBuilder().getBuilder(index); } /** * * * <pre> * References to the locations and revisions of the source code used in the * deployed application. * </pre> * * <code>repeated .google.devtools.source.v1.SourceContext source_contexts = 9;</code> */ public com.google.devtools.source.v1.SourceContextOrBuilder getSourceContextsOrBuilder( int index) { if (sourceContextsBuilder_ == null) { return sourceContexts_.get(index); } else { return sourceContextsBuilder_.getMessageOrBuilder(index); } } /** * * * <pre> * References to the locations and revisions of the source code used in the * deployed application. * </pre> * * <code>repeated .google.devtools.source.v1.SourceContext source_contexts = 9;</code> */ public java.util.List<? extends com.google.devtools.source.v1.SourceContextOrBuilder> getSourceContextsOrBuilderList() { if (sourceContextsBuilder_ != null) { return sourceContextsBuilder_.getMessageOrBuilderList(); } else { return java.util.Collections.unmodifiableList(sourceContexts_); } } /** * * * <pre> * References to the locations and revisions of the source code used in the * deployed application. * </pre> * * <code>repeated .google.devtools.source.v1.SourceContext source_contexts = 9;</code> */ public com.google.devtools.source.v1.SourceContext.Builder addSourceContextsBuilder() { return getSourceContextsFieldBuilder() .addBuilder(com.google.devtools.source.v1.SourceContext.getDefaultInstance()); } /** * * * <pre> * References to the locations and revisions of the source code used in the * deployed application. * </pre> * * <code>repeated .google.devtools.source.v1.SourceContext source_contexts = 9;</code> */ public com.google.devtools.source.v1.SourceContext.Builder addSourceContextsBuilder(int index) { return getSourceContextsFieldBuilder() .addBuilder(index, com.google.devtools.source.v1.SourceContext.getDefaultInstance()); } /** * * * <pre> * References to the locations and revisions of the source code used in the * deployed application. * </pre> * * <code>repeated .google.devtools.source.v1.SourceContext source_contexts = 9;</code> */ public java.util.List<com.google.devtools.source.v1.SourceContext.Builder> getSourceContextsBuilderList() { return getSourceContextsFieldBuilder().getBuilderList(); } private com.google.protobuf.RepeatedFieldBuilderV3< com.google.devtools.source.v1.SourceContext, com.google.devtools.source.v1.SourceContext.Builder, com.google.devtools.source.v1.SourceContextOrBuilder> getSourceContextsFieldBuilder() { if (sourceContextsBuilder_ == null) { sourceContextsBuilder_ = new com.google.protobuf.RepeatedFieldBuilderV3< com.google.devtools.source.v1.SourceContext, com.google.devtools.source.v1.SourceContext.Builder, com.google.devtools.source.v1.SourceContextOrBuilder>( sourceContexts_, ((bitField0_ & 0x00000001) != 0), getParentForChildren(), isClean()); sourceContexts_ = null; } return sourceContextsBuilder_; } private java.util.List<com.google.devtools.source.v1.ExtendedSourceContext> extSourceContexts_ = java.util.Collections.emptyList(); private void ensureExtSourceContextsIsMutable() { if (!((bitField0_ & 0x00000002) != 0)) { extSourceContexts_ = new java.util.ArrayList<com.google.devtools.source.v1.ExtendedSourceContext>( extSourceContexts_); bitField0_ |= 0x00000002; } } private com.google.protobuf.RepeatedFieldBuilderV3< com.google.devtools.source.v1.ExtendedSourceContext, com.google.devtools.source.v1.ExtendedSourceContext.Builder, com.google.devtools.source.v1.ExtendedSourceContextOrBuilder> extSourceContextsBuilder_; /** * * * <pre> * References to the locations and revisions of the source code used in the * deployed application. * </pre> * * <code> * repeated .google.devtools.source.v1.ExtendedSourceContext ext_source_contexts = 13 [deprecated = true]; * </code> */ @java.lang.Deprecated public java.util.List<com.google.devtools.source.v1.ExtendedSourceContext> getExtSourceContextsList() { if (extSourceContextsBuilder_ == null) { return java.util.Collections.unmodifiableList(extSourceContexts_); } else { return extSourceContextsBuilder_.getMessageList(); } } /** * * * <pre> * References to the locations and revisions of the source code used in the * deployed application. * </pre> * * <code> * repeated .google.devtools.source.v1.ExtendedSourceContext ext_source_contexts = 13 [deprecated = true]; * </code> */ @java.lang.Deprecated public int getExtSourceContextsCount() { if (extSourceContextsBuilder_ == null) { return extSourceContexts_.size(); } else { return extSourceContextsBuilder_.getCount(); } } /** * * * <pre> * References to the locations and revisions of the source code used in the * deployed application. * </pre> * * <code> * repeated .google.devtools.source.v1.ExtendedSourceContext ext_source_contexts = 13 [deprecated = true]; * </code> */ @java.lang.Deprecated public com.google.devtools.source.v1.ExtendedSourceContext getExtSourceContexts(int index) { if (extSourceContextsBuilder_ == null) { return extSourceContexts_.get(index); } else { return extSourceContextsBuilder_.getMessage(index); } } /** * * * <pre> * References to the locations and revisions of the source code used in the * deployed application. * </pre> * * <code> * repeated .google.devtools.source.v1.ExtendedSourceContext ext_source_contexts = 13 [deprecated = true]; * </code> */ @java.lang.Deprecated public Builder setExtSourceContexts( int index, com.google.devtools.source.v1.ExtendedSourceContext value) { if (extSourceContextsBuilder_ == null) { if (value == null) { throw new NullPointerException(); } ensureExtSourceContextsIsMutable(); extSourceContexts_.set(index, value); onChanged(); } else { extSourceContextsBuilder_.setMessage(index, value); } return this; } /** * * * <pre> * References to the locations and revisions of the source code used in the * deployed application. * </pre> * * <code> * repeated .google.devtools.source.v1.ExtendedSourceContext ext_source_contexts = 13 [deprecated = true]; * </code> */ @java.lang.Deprecated public Builder setExtSourceContexts( int index, com.google.devtools.source.v1.ExtendedSourceContext.Builder builderForValue) { if (extSourceContextsBuilder_ == null) { ensureExtSourceContextsIsMutable(); extSourceContexts_.set(index, builderForValue.build()); onChanged(); } else { extSourceContextsBuilder_.setMessage(index, builderForValue.build()); } return this; } /** * * * <pre> * References to the locations and revisions of the source code used in the * deployed application. * </pre> * * <code> * repeated .google.devtools.source.v1.ExtendedSourceContext ext_source_contexts = 13 [deprecated = true]; * </code> */ @java.lang.Deprecated public Builder addExtSourceContexts(com.google.devtools.source.v1.ExtendedSourceContext value) { if (extSourceContextsBuilder_ == null) { if (value == null) { throw new NullPointerException(); } ensureExtSourceContextsIsMutable(); extSourceContexts_.add(value); onChanged(); } else { extSourceContextsBuilder_.addMessage(value); } return this; } /** * * * <pre> * References to the locations and revisions of the source code used in the * deployed application. * </pre> * * <code> * repeated .google.devtools.source.v1.ExtendedSourceContext ext_source_contexts = 13 [deprecated = true]; * </code> */ @java.lang.Deprecated public Builder addExtSourceContexts( int index, com.google.devtools.source.v1.ExtendedSourceContext value) { if (extSourceContextsBuilder_ == null) { if (value == null) { throw new NullPointerException(); } ensureExtSourceContextsIsMutable(); extSourceContexts_.add(index, value); onChanged(); } else { extSourceContextsBuilder_.addMessage(index, value); } return this; } /** * * * <pre> * References to the locations and revisions of the source code used in the * deployed application. * </pre> * * <code> * repeated .google.devtools.source.v1.ExtendedSourceContext ext_source_contexts = 13 [deprecated = true]; * </code> */ @java.lang.Deprecated public Builder addExtSourceContexts( com.google.devtools.source.v1.ExtendedSourceContext.Builder builderForValue) { if (extSourceContextsBuilder_ == null) { ensureExtSourceContextsIsMutable(); extSourceContexts_.add(builderForValue.build()); onChanged(); } else { extSourceContextsBuilder_.addMessage(builderForValue.build()); } return this; } /** * * * <pre> * References to the locations and revisions of the source code used in the * deployed application. * </pre> * * <code> * repeated .google.devtools.source.v1.ExtendedSourceContext ext_source_contexts = 13 [deprecated = true]; * </code> */ @java.lang.Deprecated public Builder addExtSourceContexts( int index, com.google.devtools.source.v1.ExtendedSourceContext.Builder builderForValue) { if (extSourceContextsBuilder_ == null) { ensureExtSourceContextsIsMutable(); extSourceContexts_.add(index, builderForValue.build()); onChanged(); } else { extSourceContextsBuilder_.addMessage(index, builderForValue.build()); } return this; } /** * * * <pre> * References to the locations and revisions of the source code used in the * deployed application. * </pre> * * <code> * repeated .google.devtools.source.v1.ExtendedSourceContext ext_source_contexts = 13 [deprecated = true]; * </code> */ @java.lang.Deprecated public Builder addAllExtSourceContexts( java.lang.Iterable<? extends com.google.devtools.source.v1.ExtendedSourceContext> values) { if (extSourceContextsBuilder_ == null) { ensureExtSourceContextsIsMutable(); com.google.protobuf.AbstractMessageLite.Builder.addAll(values, extSourceContexts_); onChanged(); } else { extSourceContextsBuilder_.addAllMessages(values); } return this; } /** * * * <pre> * References to the locations and revisions of the source code used in the * deployed application. * </pre> * * <code> * repeated .google.devtools.source.v1.ExtendedSourceContext ext_source_contexts = 13 [deprecated = true]; * </code> */ @java.lang.Deprecated public Builder clearExtSourceContexts() { if (extSourceContextsBuilder_ == null) { extSourceContexts_ = java.util.Collections.emptyList(); bitField0_ = (bitField0_ & ~0x00000002); onChanged(); } else { extSourceContextsBuilder_.clear(); } return this; } /** * * * <pre> * References to the locations and revisions of the source code used in the * deployed application. * </pre> * * <code> * repeated .google.devtools.source.v1.ExtendedSourceContext ext_source_contexts = 13 [deprecated = true]; * </code> */ @java.lang.Deprecated public Builder removeExtSourceContexts(int index) { if (extSourceContextsBuilder_ == null) { ensureExtSourceContextsIsMutable(); extSourceContexts_.remove(index); onChanged(); } else { extSourceContextsBuilder_.remove(index); } return this; } /** * * * <pre> * References to the locations and revisions of the source code used in the * deployed application. * </pre> * * <code> * repeated .google.devtools.source.v1.ExtendedSourceContext ext_source_contexts = 13 [deprecated = true]; * </code> */ @java.lang.Deprecated public com.google.devtools.source.v1.ExtendedSourceContext.Builder getExtSourceContextsBuilder( int index) { return getExtSourceContextsFieldBuilder().getBuilder(index); } /** * * * <pre> * References to the locations and revisions of the source code used in the * deployed application. * </pre> * * <code> * repeated .google.devtools.source.v1.ExtendedSourceContext ext_source_contexts = 13 [deprecated = true]; * </code> */ @java.lang.Deprecated public com.google.devtools.source.v1.ExtendedSourceContextOrBuilder getExtSourceContextsOrBuilder(int index) { if (extSourceContextsBuilder_ == null) { return extSourceContexts_.get(index); } else { return extSourceContextsBuilder_.getMessageOrBuilder(index); } } /** * * * <pre> * References to the locations and revisions of the source code used in the * deployed application. * </pre> * * <code> * repeated .google.devtools.source.v1.ExtendedSourceContext ext_source_contexts = 13 [deprecated = true]; * </code> */ @java.lang.Deprecated public java.util.List<? extends com.google.devtools.source.v1.ExtendedSourceContextOrBuilder> getExtSourceContextsOrBuilderList() { if (extSourceContextsBuilder_ != null) { return extSourceContextsBuilder_.getMessageOrBuilderList(); } else { return java.util.Collections.unmodifiableList(extSourceContexts_); } } /** * * * <pre> * References to the locations and revisions of the source code used in the * deployed application. * </pre> * * <code> * repeated .google.devtools.source.v1.ExtendedSourceContext ext_source_contexts = 13 [deprecated = true]; * </code> */ @java.lang.Deprecated public com.google.devtools.source.v1.ExtendedSourceContext.Builder addExtSourceContextsBuilder() { return getExtSourceContextsFieldBuilder() .addBuilder(com.google.devtools.source.v1.ExtendedSourceContext.getDefaultInstance()); } /** * * * <pre> * References to the locations and revisions of the source code used in the * deployed application. * </pre> * * <code> * repeated .google.devtools.source.v1.ExtendedSourceContext ext_source_contexts = 13 [deprecated = true]; * </code> */ @java.lang.Deprecated public com.google.devtools.source.v1.ExtendedSourceContext.Builder addExtSourceContextsBuilder( int index) { return getExtSourceContextsFieldBuilder() .addBuilder( index, com.google.devtools.source.v1.ExtendedSourceContext.getDefaultInstance()); } /** * * * <pre> * References to the locations and revisions of the source code used in the * deployed application. * </pre> * * <code> * repeated .google.devtools.source.v1.ExtendedSourceContext ext_source_contexts = 13 [deprecated = true]; * </code> */ @java.lang.Deprecated public java.util.List<com.google.devtools.source.v1.ExtendedSourceContext.Builder> getExtSourceContextsBuilderList() { return getExtSourceContextsFieldBuilder().getBuilderList(); } private com.google.protobuf.RepeatedFieldBuilderV3< com.google.devtools.source.v1.ExtendedSourceContext, com.google.devtools.source.v1.ExtendedSourceContext.Builder, com.google.devtools.source.v1.ExtendedSourceContextOrBuilder> getExtSourceContextsFieldBuilder() { if (extSourceContextsBuilder_ == null) { extSourceContextsBuilder_ = new com.google.protobuf.RepeatedFieldBuilderV3< com.google.devtools.source.v1.ExtendedSourceContext, com.google.devtools.source.v1.ExtendedSourceContext.Builder, com.google.devtools.source.v1.ExtendedSourceContextOrBuilder>( extSourceContexts_, ((bitField0_ & 0x00000002) != 0), getParentForChildren(), isClean()); extSourceContexts_ = null; } return extSourceContextsBuilder_; } private com.google.protobuf.MapField<java.lang.String, java.lang.String> labels_; private com.google.protobuf.MapField<java.lang.String, java.lang.String> internalGetLabels() { if (labels_ == null) { return com.google.protobuf.MapField.emptyMapField(LabelsDefaultEntryHolder.defaultEntry); } return labels_; } private com.google.protobuf.MapField<java.lang.String, java.lang.String> internalGetMutableLabels() { onChanged(); ; if (labels_ == null) { labels_ = com.google.protobuf.MapField.newMapField(LabelsDefaultEntryHolder.defaultEntry); } if (!labels_.isMutable()) { labels_ = labels_.copy(); } return labels_; } public int getLabelsCount() { return internalGetLabels().getMap().size(); } /** * * * <pre> * A set of custom debuggee properties, populated by the agent, to be * displayed to the user. * </pre> * * <code>map&lt;string, string&gt; labels = 11;</code> */ @java.lang.Override public boolean containsLabels(java.lang.String key) { if (key == null) { throw new NullPointerException("map key"); } return internalGetLabels().getMap().containsKey(key); } /** Use {@link #getLabelsMap()} instead. */ @java.lang.Override @java.lang.Deprecated public java.util.Map<java.lang.String, java.lang.String> getLabels() { return getLabelsMap(); } /** * * * <pre> * A set of custom debuggee properties, populated by the agent, to be * displayed to the user. * </pre> * * <code>map&lt;string, string&gt; labels = 11;</code> */ @java.lang.Override public java.util.Map<java.lang.String, java.lang.String> getLabelsMap() { return internalGetLabels().getMap(); } /** * * * <pre> * A set of custom debuggee properties, populated by the agent, to be * displayed to the user. * </pre> * * <code>map&lt;string, string&gt; labels = 11;</code> */ @java.lang.Override public java.lang.String getLabelsOrDefault( java.lang.String key, java.lang.String defaultValue) { if (key == null) { throw new NullPointerException("map key"); } java.util.Map<java.lang.String, java.lang.String> map = internalGetLabels().getMap(); return map.containsKey(key) ? map.get(key) : defaultValue; } /** * * * <pre> * A set of custom debuggee properties, populated by the agent, to be * displayed to the user. * </pre> * * <code>map&lt;string, string&gt; labels = 11;</code> */ @java.lang.Override public java.lang.String getLabelsOrThrow(java.lang.String key) { if (key == null) { throw new NullPointerException("map key"); } java.util.Map<java.lang.String, java.lang.String> map = internalGetLabels().getMap(); if (!map.containsKey(key)) { throw new java.lang.IllegalArgumentException(); } return map.get(key); } public Builder clearLabels() { internalGetMutableLabels().getMutableMap().clear(); return this; } /** * * * <pre> * A set of custom debuggee properties, populated by the agent, to be * displayed to the user. * </pre> * * <code>map&lt;string, string&gt; labels = 11;</code> */ public Builder removeLabels(java.lang.String key) { if (key == null) { throw new NullPointerException("map key"); } internalGetMutableLabels().getMutableMap().remove(key); return this; } /** Use alternate mutation accessors instead. */ @java.lang.Deprecated public java.util.Map<java.lang.String, java.lang.String> getMutableLabels() { return internalGetMutableLabels().getMutableMap(); } /** * * * <pre> * A set of custom debuggee properties, populated by the agent, to be * displayed to the user. * </pre> * * <code>map&lt;string, string&gt; labels = 11;</code> */ public Builder putLabels(java.lang.String key, java.lang.String value) { if (key == null) { throw new NullPointerException("map key"); } if (value == null) { throw new NullPointerException("map value"); } internalGetMutableLabels().getMutableMap().put(key, value); return this; } /** * * * <pre> * A set of custom debuggee properties, populated by the agent, to be * displayed to the user. * </pre> * * <code>map&lt;string, string&gt; labels = 11;</code> */ public Builder putAllLabels(java.util.Map<java.lang.String, java.lang.String> values) { internalGetMutableLabels().getMutableMap().putAll(values); return this; } @java.lang.Override public final Builder setUnknownFields(final com.google.protobuf.UnknownFieldSet unknownFields) { return super.setUnknownFields(unknownFields); } @java.lang.Override public final Builder mergeUnknownFields( final com.google.protobuf.UnknownFieldSet unknownFields) { return super.mergeUnknownFields(unknownFields); } // @@protoc_insertion_point(builder_scope:google.devtools.clouddebugger.v2.Debuggee) } // @@protoc_insertion_point(class_scope:google.devtools.clouddebugger.v2.Debuggee) private static final com.google.devtools.clouddebugger.v2.Debuggee DEFAULT_INSTANCE; static { DEFAULT_INSTANCE = new com.google.devtools.clouddebugger.v2.Debuggee(); } public static com.google.devtools.clouddebugger.v2.Debuggee getDefaultInstance() { return DEFAULT_INSTANCE; } private static final com.google.protobuf.Parser<Debuggee> PARSER = new com.google.protobuf.AbstractParser<Debuggee>() { @java.lang.Override public Debuggee parsePartialFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { Builder builder = newBuilder(); try { builder.mergeFrom(input, extensionRegistry); } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.setUnfinishedMessage(builder.buildPartial()); } catch (com.google.protobuf.UninitializedMessageException e) { throw e.asInvalidProtocolBufferException().setUnfinishedMessage(builder.buildPartial()); } catch (java.io.IOException e) { throw new com.google.protobuf.InvalidProtocolBufferException(e) .setUnfinishedMessage(builder.buildPartial()); } return builder.buildPartial(); } }; public static com.google.protobuf.Parser<Debuggee> parser() { return PARSER; } @java.lang.Override public com.google.protobuf.Parser<Debuggee> getParserForType() { return PARSER; } @java.lang.Override public com.google.devtools.clouddebugger.v2.Debuggee getDefaultInstanceForType() { return DEFAULT_INSTANCE; } }
{ "content_hash": "63d9cb6c9d23a3b313b3226d187b7ff5", "timestamp": "", "source": "github", "line_count": 3317, "max_line_length": 110, "avg_line_length": 31.35725052758517, "alnum_prop": 0.62637003422682, "repo_name": "googleapis/google-cloud-java", "id": "b965cb26816cb41935aaa2b88ec0a892c90677bd", "size": "104606", "binary": false, "copies": "2", "ref": "refs/heads/main", "path": "java-debugger-client/proto-google-cloud-debugger-client-v2/src/main/java/com/google/devtools/clouddebugger/v2/Debuggee.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Dockerfile", "bytes": "2614" }, { "name": "HCL", "bytes": "28592" }, { "name": "Java", "bytes": "826434232" }, { "name": "Jinja", "bytes": "2292" }, { "name": "Python", "bytes": "200408" }, { "name": "Shell", "bytes": "97954" } ], "symlink_target": "" }
package org.elasticsearch.client.transport; import org.elasticsearch.Version; import org.elasticsearch.action.ActionListener; import org.elasticsearch.action.admin.cluster.node.liveness.LivenessResponse; import org.elasticsearch.action.admin.cluster.node.liveness.TransportLivenessAction; import org.elasticsearch.action.admin.cluster.state.ClusterStateAction; import org.elasticsearch.action.admin.cluster.state.ClusterStateRequest; import org.elasticsearch.action.admin.cluster.state.ClusterStateResponse; import org.elasticsearch.action.support.PlainActionFuture; import org.elasticsearch.cluster.ClusterName; import org.elasticsearch.cluster.ClusterState; import org.elasticsearch.cluster.node.DiscoveryNode; import org.elasticsearch.cluster.node.DiscoveryNodes; import org.elasticsearch.common.UUIDs; import org.elasticsearch.common.io.stream.StreamInput; import org.elasticsearch.common.settings.Settings; import org.elasticsearch.common.transport.TransportAddress; import org.elasticsearch.common.unit.TimeValue; import org.elasticsearch.node.Node; import org.elasticsearch.test.ESTestCase; import org.elasticsearch.test.transport.MockTransportService; import org.elasticsearch.threadpool.TestThreadPool; import org.elasticsearch.threadpool.ThreadPool; import org.elasticsearch.transport.Transport; import org.elasticsearch.transport.TransportChannel; import org.elasticsearch.transport.TransportException; import org.elasticsearch.transport.TransportInterceptor; import org.elasticsearch.transport.TransportRequest; import org.elasticsearch.transport.TransportRequestHandler; import org.elasticsearch.transport.TransportRequestOptions; import org.elasticsearch.transport.TransportResponse; import org.elasticsearch.transport.TransportResponseHandler; import org.hamcrest.CustomMatcher; import java.io.Closeable; import java.io.IOException; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.concurrent.CopyOnWriteArrayList; import java.util.concurrent.CountDownLatch; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicReference; import static org.elasticsearch.test.transport.MockTransportService.createNewService; import static org.hamcrest.CoreMatchers.equalTo; import static org.hamcrest.CoreMatchers.everyItem; import static org.hamcrest.CoreMatchers.hasItem; import static org.hamcrest.CoreMatchers.instanceOf; import static org.hamcrest.CoreMatchers.not; import static org.hamcrest.CoreMatchers.nullValue; import static org.hamcrest.CoreMatchers.startsWith; import static org.hamcrest.Matchers.lessThanOrEqualTo; import static org.hamcrest.Matchers.notNullValue; public class TransportClientNodesServiceTests extends ESTestCase { private static class TestIteration implements Closeable { private final ThreadPool threadPool; private final FailAndRetryMockTransport<TestResponse> transport; private final MockTransportService transportService; private final TransportClientNodesService transportClientNodesService; private final int listNodesCount; private final int sniffNodesCount; private TransportAddress livenessAddress = buildNewFakeTransportAddress(); final List<TransportAddress> listNodeAddresses; // map for each address of the nodes a cluster state request should respond with final Map<TransportAddress, DiscoveryNodes> nodeMap; TestIteration() { this(Settings.EMPTY); } TestIteration(Settings extraSettings) { Settings settings = Settings.builder().put(extraSettings).put("cluster.name", "test").build(); ClusterName clusterName = ClusterName.CLUSTER_NAME_SETTING.get(settings); List<TransportAddress> listNodes = new ArrayList<>(); Map<TransportAddress, DiscoveryNodes> nodeMap = new HashMap<>(); this.listNodesCount = randomIntBetween(1, 10); int sniffNodesCount = 0; for (int i = 0; i < listNodesCount; i++) { TransportAddress transportAddress = buildNewFakeTransportAddress(); listNodes.add(transportAddress); DiscoveryNodes.Builder discoNodes = DiscoveryNodes.builder(); discoNodes.add(new DiscoveryNode("#list-node#-" + transportAddress, transportAddress, Version.CURRENT)); if (TransportClient.CLIENT_TRANSPORT_SNIFF.get(settings)) { final int numSniffNodes = randomIntBetween(0, 3); for (int j = 0; j < numSniffNodes; ++j) { TransportAddress sniffAddress = buildNewFakeTransportAddress(); DiscoveryNode sniffNode = new DiscoveryNode("#sniff-node#-" + sniffAddress, sniffAddress, Version.CURRENT); discoNodes.add(sniffNode); // also allow sniffing of the sniff node itself nodeMap.put(sniffAddress, DiscoveryNodes.builder().add(sniffNode).build()); ++sniffNodesCount; } } nodeMap.put(transportAddress, discoNodes.build()); } listNodeAddresses = listNodes; this.nodeMap = nodeMap; this.sniffNodesCount = sniffNodesCount; threadPool = new TestThreadPool("transport-client-nodes-service-tests"); transport = new FailAndRetryMockTransport<TestResponse>(random(), clusterName) { @Override public List<String> getLocalAddresses() { return Collections.emptyList(); } @Override protected TestResponse newResponse() { return new TestResponse(); } @Override protected ClusterState getMockClusterState(DiscoveryNode node) { return ClusterState.builder(clusterName).nodes(TestIteration.this.nodeMap.get(node.getAddress())).build(); } }; transportService = new MockTransportService(settings, transport, threadPool, new TransportInterceptor() { @Override public AsyncSender interceptSender(AsyncSender sender) { return new AsyncSender() { @Override public <T extends TransportResponse> void sendRequest(Transport.Connection connection, String action, TransportRequest request, TransportRequestOptions options, TransportResponseHandler<T> handler) { if (TransportLivenessAction.NAME.equals(action)) { sender.sendRequest(connection, action, request, options, wrapLivenessResponseHandler(handler, connection.getNode(), clusterName)); } else { sender.sendRequest(connection, action, request, options, handler); } } }; } }, (addr) -> { assert addr == null : "boundAddress: " + addr; return DiscoveryNode.createLocal(settings, buildNewFakeTransportAddress(), UUIDs.randomBase64UUID()); }, null, Collections.emptySet()); transportService.addNodeConnectedBehavior((connectionManager, discoveryNode) -> false); transportService.addGetConnectionBehavior((connectionManager, discoveryNode) -> { // The FailAndRetryTransport does not use the connection profile PlainActionFuture<Transport.Connection> future = PlainActionFuture.newFuture(); transport.openConnection(discoveryNode, null, future); return future.actionGet(); }); transportService.start(); transportService.acceptIncomingRequests(); transportClientNodesService = new TransportClientNodesService(settings, transportService, threadPool, (a, b) -> {}); transportClientNodesService.addTransportAddresses(listNodeAddresses.toArray(new TransportAddress[0])); } private <T extends TransportResponse> TransportResponseHandler wrapLivenessResponseHandler(TransportResponseHandler<T> handler, DiscoveryNode node, ClusterName clusterName) { return new TransportResponseHandler<T>() { @Override public T read(StreamInput in) throws IOException { return handler.read(in); } @Override @SuppressWarnings("unchecked") public void handleResponse(T response) { LivenessResponse livenessResponse = new LivenessResponse(clusterName, new DiscoveryNode(node.getName(), node.getId(), node.getEphemeralId(), "liveness-hostname" + node.getId(), "liveness-hostaddress" + node.getId(), livenessAddress, node.getAttributes(), node.getRoles(), node.getVersion())); handler.handleResponse((T)livenessResponse); } @Override public void handleException(TransportException exp) { handler.handleException(exp); } @Override public String executor() { return handler.executor(); } }; } @Override public void close() { transport.endConnectMode(); transportService.stop(); transportClientNodesService.close(); terminate(threadPool); } } @AwaitsFix(bugUrl = "https://github.com/elastic/elasticsearch/issues/37567") public void testListenerFailures() throws InterruptedException { int iters = iterations(10, 100); for (int i = 0; i <iters; i++) { try(TestIteration iteration = new TestIteration()) { iteration.transport.endConnectMode(); // stop transport from responding early final CountDownLatch latch = new CountDownLatch(1); final AtomicInteger finalFailures = new AtomicInteger(); final AtomicReference<Throwable> finalFailure = new AtomicReference<>(); final AtomicReference<TestResponse> response = new AtomicReference<>(); ActionListener<TestResponse> actionListener = new ActionListener<TestResponse>() { @Override public void onResponse(TestResponse testResponse) { response.set(testResponse); latch.countDown(); } @Override public void onFailure(Exception e) { finalFailures.incrementAndGet(); finalFailure.set(e); latch.countDown(); } }; final AtomicInteger preSendFailures = new AtomicInteger(); iteration.transportClientNodesService.execute((node, retryListener) -> { if (rarely()) { preSendFailures.incrementAndGet(); //throw whatever exception that is not a subclass of ConnectTransportException throw new IllegalArgumentException(); } iteration.transportService.sendRequest(node, "action", new TestRequest(), TransportRequestOptions.EMPTY, new TransportResponseHandler<TestResponse>() { @Override public TestResponse read(StreamInput in) { return new TestResponse(in); } @Override public void handleResponse(TestResponse response1) { retryListener.onResponse(response1); } @Override public void handleException(TransportException exp) { retryListener.onFailure(exp); } @Override public String executor() { return randomBoolean() ? ThreadPool.Names.SAME : ThreadPool.Names.GENERIC; } }); }, actionListener); latch.await(); //there can be only either one failure that causes the request to fail straightaway or success assertThat(preSendFailures.get() + iteration.transport.failures() + iteration.transport.successes(), lessThanOrEqualTo(1)); if (iteration.transport.successes() == 1) { assertThat(finalFailures.get(), equalTo(0)); assertThat(finalFailure.get(), nullValue()); assertThat(response.get(), notNullValue()); } else { assertThat(finalFailures.get(), equalTo(1)); assertThat(finalFailure.get(), notNullValue()); assertThat(response.get(), nullValue()); if (preSendFailures.get() == 0 && iteration.transport.failures() == 0) { assertThat(finalFailure.get(), instanceOf(NoNodeAvailableException.class)); } } assertThat(iteration.transport.triedNodes().size(), lessThanOrEqualTo(iteration.listNodesCount)); assertThat(iteration.transport.triedNodes().size(), equalTo(iteration.transport.connectTransportExceptions() + iteration.transport.failures() + iteration.transport.successes())); } } } public void testConnectedNodes() { int iters = iterations(10, 100); for (int i = 0; i <iters; i++) { try(TestIteration iteration = new TestIteration()) { assertThat(iteration.transportClientNodesService.connectedNodes().size(), lessThanOrEqualTo(iteration.listNodesCount)); for (DiscoveryNode discoveryNode : iteration.transportClientNodesService.connectedNodes()) { assertThat(discoveryNode.getHostName(), startsWith("liveness-")); assertThat(discoveryNode.getHostAddress(), startsWith("liveness-")); assertNotEquals(discoveryNode.getAddress(), iteration.livenessAddress); assertThat(iteration.listNodeAddresses, hasItem(discoveryNode.getAddress())); } } } } public void testRemoveAddressSniff() { checkRemoveAddress(true); } public void testRemoveAddressSimple() { checkRemoveAddress(false); } private void checkRemoveAddress(boolean sniff) { Settings extraSettings = Settings.builder().put(TransportClient.CLIENT_TRANSPORT_SNIFF.getKey(), sniff).build(); try(TestIteration iteration = new TestIteration(extraSettings)) { final TransportClientNodesService service = iteration.transportClientNodesService; assertEquals(iteration.listNodesCount + iteration.sniffNodesCount, service.connectedNodes().size()); final TransportAddress addressToRemove = randomFrom(iteration.listNodeAddresses); service.removeTransportAddress(addressToRemove); assertThat(service.connectedNodes(), everyItem(not(new CustomMatcher<DiscoveryNode>("removed address") { @Override public boolean matches(Object item) { return item instanceof DiscoveryNode && ((DiscoveryNode)item).getAddress().equals(addressToRemove); } }))); assertEquals(iteration.listNodesCount + iteration.sniffNodesCount - 1, service.connectedNodes().size()); } } public void testSniffNodesSamplerClosesConnections() throws Exception { final TestThreadPool threadPool = new TestThreadPool("testSniffNodesSamplerClosesConnections"); Settings remoteSettings = Settings.builder().put(Node.NODE_NAME_SETTING.getKey(), "remote").build(); try (MockTransportService remoteService = createNewService(remoteSettings, Version.CURRENT, threadPool, null)) { final MockHandler handler = new MockHandler(remoteService); remoteService.registerRequestHandler(ClusterStateAction.NAME, ClusterStateRequest::new, ThreadPool.Names.SAME, handler); remoteService.start(); remoteService.acceptIncomingRequests(); Settings clientSettings = Settings.builder() .put(TransportClient.CLIENT_TRANSPORT_SNIFF.getKey(), true) .put(TransportClient.CLIENT_TRANSPORT_PING_TIMEOUT.getKey(), TimeValue.timeValueSeconds(1)) .put(TransportClient.CLIENT_TRANSPORT_NODES_SAMPLER_INTERVAL.getKey(), TimeValue.timeValueSeconds(30)) .build(); try (MockTransportService clientService = createNewService(clientSettings, Version.CURRENT, threadPool, null)) { final List<Transport.Connection> establishedConnections = new CopyOnWriteArrayList<>(); clientService.addConnectBehavior(remoteService, (transport, discoveryNode, profile, listener) -> transport.openConnection(discoveryNode, profile, new ActionListener<Transport.Connection>() { @Override public void onResponse(Transport.Connection connection) { establishedConnections.add(connection); listener.onResponse(connection); } @Override public void onFailure(Exception e) { listener.onFailure(e); } })); clientService.start(); clientService.acceptIncomingRequests(); try (TransportClientNodesService transportClientNodesService = new TransportClientNodesService(clientSettings, clientService, threadPool, (a, b) -> {})) { assertEquals(0, transportClientNodesService.connectedNodes().size()); assertEquals(0, establishedConnections.size()); transportClientNodesService.addTransportAddresses(remoteService.getLocalDiscoNode().getAddress()); assertEquals(1, transportClientNodesService.connectedNodes().size()); assertEquals(1, clientService.connectionManager().size()); transportClientNodesService.doSample(); assertEquals(1, clientService.connectionManager().size()); establishedConnections.clear(); handler.blockRequest(); Thread thread = new Thread(transportClientNodesService::doSample); thread.start(); assertBusy(() -> assertTrue(establishedConnections.size() >= 1)); assertFalse("Temporary ping connection must be opened", establishedConnections.get(0).isClosed()); handler.releaseRequest(); thread.join(); assertTrue(establishedConnections.get(0).isClosed()); } } } finally { terminate(threadPool); } } class MockHandler implements TransportRequestHandler<ClusterStateRequest> { private final AtomicBoolean block = new AtomicBoolean(false); private final CountDownLatch release = new CountDownLatch(1); private final MockTransportService transportService; MockHandler(MockTransportService transportService) { this.transportService = transportService; } @Override public void messageReceived(ClusterStateRequest request, TransportChannel channel) throws Exception { if (block.get()) { release.await(); return; } DiscoveryNodes discoveryNodes = DiscoveryNodes.builder().add(transportService.getLocalDiscoNode()).build(); ClusterState build = ClusterState.builder(ClusterName.DEFAULT).nodes(discoveryNodes).build(); channel.sendResponse(new ClusterStateResponse(ClusterName.DEFAULT, build, 0L, false)); } void blockRequest() { if (block.compareAndSet(false, true) == false) { throw new AssertionError("Request handler is already marked as blocking"); } } void releaseRequest() { release.countDown(); } } public static class TestRequest extends TransportRequest { } private static class TestResponse extends TransportResponse { private TestResponse() {} private TestResponse(StreamInput in) {} } }
{ "content_hash": "c9a224ea521f24bc66fd15b39e5d3901", "timestamp": "", "source": "github", "line_count": 435, "max_line_length": 139, "avg_line_length": 49.94942528735632, "alnum_prop": 0.6123895434462445, "repo_name": "vroyer/elassandra", "id": "ecdf56d0d8b9298ec86f14a6f284fae3a50ac45f", "size": "22516", "binary": false, "copies": "2", "ref": "refs/heads/v6.8.4-strapdata", "path": "server/src/test/java/org/elasticsearch/client/transport/TransportClientNodesServiceTests.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Batchfile", "bytes": "23801" }, { "name": "Java", "bytes": "17417097" }, { "name": "PowerShell", "bytes": "39789" }, { "name": "Python", "bytes": "96620" }, { "name": "Shell", "bytes": "64293" } ], "symlink_target": "" }
package org.apache.jmeter.protocol.java.config.gui; import java.awt.BorderLayout; import java.awt.Color; import java.awt.Font; import java.util.ArrayList; import java.util.Arrays; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import javax.swing.ImageIcon; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.SwingConstants; import javax.swing.event.ChangeEvent; import javax.swing.event.ChangeListener; import org.apache.commons.lang3.ArrayUtils; import org.apache.jmeter.config.Argument; import org.apache.jmeter.config.Arguments; import org.apache.jmeter.config.gui.AbstractConfigGui; import org.apache.jmeter.config.gui.ArgumentsPanel; import org.apache.jmeter.gui.util.VerticalPanel; import org.apache.jmeter.protocol.java.config.JavaConfig; import org.apache.jmeter.protocol.java.sampler.JavaSampler; import org.apache.jmeter.protocol.java.sampler.JavaSamplerClient; import org.apache.jmeter.testelement.TestElement; import org.apache.jmeter.testelement.property.JMeterProperty; import org.apache.jmeter.util.JMeterUtils; import org.apache.jorphan.gui.JLabeledChoice; import org.apache.jorphan.reflect.ClassFinder; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * The <code>JavaConfigGui</code> class provides the user interface for the * {@link JavaConfig} object. * */ public class JavaConfigGui extends AbstractConfigGui implements ChangeListener { private static final long serialVersionUID = 241L; /** Logging */ private static final Logger log = LoggerFactory.getLogger(JavaConfigGui.class); /** A combo box allowing the user to choose a test class. */ private JLabeledChoice classNameLabeledChoice; /** * Indicates whether or not the name of this component should be displayed * as part of the GUI. If true, this is a standalone component. If false, it * is embedded in some other component. */ private boolean displayName = true; /** A panel allowing the user to set arguments for this test. */ private ArgumentsPanel argsPanel; /** * Used in case the referenced class is not in classpath or does not implement {@link JavaSamplerClient} */ private final JLabel warningLabel; /** * Create a new JavaConfigGui as a standalone component. */ public JavaConfigGui() { this(true); } /** * Create a new JavaConfigGui as either a standalone or an embedded * component. * * @param displayNameField * tells whether the component name should be displayed with the * GUI. If true, this is a standalone component. If false, this * component is embedded in some other component. */ public JavaConfigGui(boolean displayNameField) { this.displayName = displayNameField; ImageIcon image = JMeterUtils.getImage("warning.png"); warningLabel = new JLabel(JMeterUtils.getResString("java_request_warning"), image, SwingConstants.LEFT); // $NON-NLS-1$ init(); } /** {@inheritDoc} */ @Override public String getLabelResource() { return "java_request_defaults"; // $NON-NLS-1$ } /** * Initialize the GUI components and layout. */ private final void init() {// called from ctor, so must not be overridable setLayout(new BorderLayout(0, 5)); if (displayName) { setBorder(makeBorder()); add(makeTitlePanel(), BorderLayout.NORTH); } JPanel classnameRequestPanel = new JPanel(new BorderLayout(0, 5)); classnameRequestPanel.add(createClassnamePanel(), BorderLayout.NORTH); classnameRequestPanel.add(createParameterPanel(), BorderLayout.CENTER); add(classnameRequestPanel, BorderLayout.CENTER); } /** * Create a panel with GUI components allowing the user to select a test * class. * * @return a panel containing the relevant components */ private JPanel createClassnamePanel() { List<String> possibleClasses = new ArrayList<>(); try { // Find all the classes which implement the JavaSamplerClient // interface. possibleClasses = ClassFinder.findClassesThatExtend(JMeterUtils.getSearchPaths(), new Class[] { JavaSamplerClient.class }); // Remove the JavaConfig class from the list since it only // implements the interface for error conditions. possibleClasses.remove(JavaSampler.class.getName() + "$ErrorSamplerClient"); } catch (Exception e) { log.debug("Exception getting interfaces.", e); } classNameLabeledChoice = new JLabeledChoice(JMeterUtils.getResString("protocol_java_classname"), possibleClasses.toArray(ArrayUtils.EMPTY_STRING_ARRAY), true, false); classNameLabeledChoice.addChangeListener(this); warningLabel.setForeground(Color.RED); Font font = warningLabel.getFont(); warningLabel.setFont(new Font(font.getFontName(), Font.BOLD, (int)(font.getSize()*1.1))); warningLabel.setVisible(false); VerticalPanel panel = new VerticalPanel(); panel.add(classNameLabeledChoice); panel.add(warningLabel); return panel; } /** * Handle change events for this component. This method currently handles * events for the classname JLabeledChoice * * @param evt * the ActionEvent to be handled */ @Override public void stateChanged(ChangeEvent evt) { if (evt.getSource() == classNameLabeledChoice) { configureClassName(); } } /** * */ private void configureClassName() { String className = classNameLabeledChoice.getText().trim(); try { JavaSamplerClient client = (JavaSamplerClient) Class.forName(className, true, Thread.currentThread().getContextClassLoader()).newInstance(); Arguments currArgs = new Arguments(); argsPanel.modifyTestElement(currArgs); Map<String, String> currArgsMap = currArgs.getArgumentsAsMap(); Arguments newArgs = new Arguments(); Arguments testParams = null; try { testParams = client.getDefaultParameters(); } catch (AbstractMethodError e) { log.warn("JavaSamplerClient doesn't implement " + "getDefaultParameters. Default parameters won't " + "be shown. Please update your client class: " + className); } if (testParams != null) { for (JMeterProperty jMeterProperty : testParams.getArguments()) { Argument arg = (Argument) jMeterProperty.getObjectValue(); String name = arg.getName(); String value = arg.getValue(); // If a user has set parameters in one test, and then // selects a different test which supports the same // parameters, those parameters should have the same // values that they did in the original test. if (currArgsMap.containsKey(name)) { String newVal = currArgsMap.get(name); if (newVal != null && newVal.length() > 0) { value = newVal; } } newArgs.addArgument(name, value); } } argsPanel.configure(newArgs); warningLabel.setVisible(false); } catch (Exception e) { log.error("Error getting argument list for " + className, e); warningLabel.setVisible(true); } } /** * Create a panel containing components allowing the user to provide * arguments to be passed to the test class instance. * * @return a panel containing the relevant components */ private JPanel createParameterPanel() { argsPanel = new ArgumentsPanel(JMeterUtils.getResString("paramtable")); // $NON-NLS-1$ return argsPanel; } /** {@inheritDoc} */ @Override public void configure(TestElement config) { super.configure(config); argsPanel.configure((Arguments) config.getProperty(JavaSampler.ARGUMENTS).getObjectValue()); String className = config.getPropertyAsString(JavaSampler.CLASSNAME); if(!checkContainsClassName(classNameLabeledChoice, className)) { classNameLabeledChoice.addValue(className); } warningLabel.setVisible(!classOk(className)); classNameLabeledChoice.setText(className); configureClassName(); } /** * * @param className String class name * @return true if class is ok (exist in classpath and instanceof {@link JavaSamplerClient} */ private boolean classOk(String className) { try { JavaSamplerClient client = (JavaSamplerClient) Class.forName(className, true, Thread.currentThread().getContextClassLoader()).newInstance(); // Just to use client return client != null; } catch (Exception ex) { log.error("Error creating class:'"+className+"' in JavaSampler "+getName() +", check for a missing jar in your jmeter 'search_paths' and 'plugin_dependency_paths' properties", ex); return false; } } /** * Check combo contains className * @param classnameChoice ComboBoxModel * @param className String class name * @return boolean */ private static boolean checkContainsClassName(JLabeledChoice classnameChoice, String className) { Set<String> set = new HashSet<>(Arrays.asList(classnameChoice.getItems())); return set.contains(className); } /** {@inheritDoc} */ @Override public TestElement createTestElement() { JavaConfig config = new JavaConfig(); modifyTestElement(config); return config; } /** {@inheritDoc} */ @Override public void modifyTestElement(TestElement config) { configureTestElement(config); ((JavaConfig) config).setArguments((Arguments) argsPanel.createTestElement()); ((JavaConfig) config).setClassname(classNameLabeledChoice.getText().trim()); } /* (non-Javadoc) * @see org.apache.jmeter.gui.AbstractJMeterGuiComponent#clearGui() */ @Override public void clearGui() { super.clearGui(); this.displayName = true; this.warningLabel.setVisible(false); argsPanel.clearGui(); classNameLabeledChoice.setSelectedIndex(0); } }
{ "content_hash": "bd5323087679b00ebcd2833e6a73dfbe", "timestamp": "", "source": "github", "line_count": 303, "max_line_length": 174, "avg_line_length": 35.7986798679868, "alnum_prop": 0.6420208352539872, "repo_name": "max3163/jmeter", "id": "d2372da530bc2480516c0f4a8f6f0e496299d85a", "size": "11649", "binary": false, "copies": "1", "ref": "refs/heads/trunk", "path": "src/protocol/java/org/apache/jmeter/protocol/java/config/gui/JavaConfigGui.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Batchfile", "bytes": "21389" }, { "name": "CSS", "bytes": "29590" }, { "name": "Groovy", "bytes": "1083" }, { "name": "HTML", "bytes": "93493" }, { "name": "Java", "bytes": "7980227" }, { "name": "JavaScript", "bytes": "41135" }, { "name": "Shell", "bytes": "17917" }, { "name": "XSLT", "bytes": "59384" } ], "symlink_target": "" }
require 'faraday' require 'json' module PanamaxAgent module Response class ListifyJson < Faraday::Response::Middleware def on_complete(env) body = env[:body] return if valid_json?(body) body = body.chomp.gsub("\n", ',') env[:body] = "[#{body}]" end private def valid_json?(string) JSON.parse(string) true rescue StandardError false end end Faraday.register_middleware :response, listify_json: -> { ListifyJson } end end
{ "content_hash": "33af779e5f45be82b00a7a55ba1b83ac", "timestamp": "", "source": "github", "line_count": 30, "max_line_length": 75, "avg_line_length": 17.866666666666667, "alnum_prop": 0.5839552238805971, "repo_name": "xirun/panamax-api", "id": "3217e8749bc41f49139c750658fcf7733bd14854", "size": "536", "binary": false, "copies": "6", "ref": "refs/heads/master", "path": "lib/panamax_agent/middleware/response/listify_json.rb", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "546" }, { "name": "JavaScript", "bytes": "599" }, { "name": "Ruby", "bytes": "320161" }, { "name": "Shell", "bytes": "387" } ], "symlink_target": "" }
<h4>Basic Information</h4> <hr> <form action="add.php" method="post"> <label>Name</label><span>*</span> <input type="text" name="name" /></br> <button type="submit" align="right">Submit</button> </form>
{ "content_hash": "ed1e1b0555672f083ebe3f4d84a19062", "timestamp": "", "source": "github", "line_count": 11, "max_line_length": 55, "avg_line_length": 19.818181818181817, "alnum_prop": 0.6192660550458715, "repo_name": "WakilaFarzan/CRUD01", "id": "df64919608b98c846e2835b4da95963de0709935", "size": "218", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "personal_info/create.html", "mode": "33261", "license": "mit", "language": [ { "name": "PHP", "bytes": "7175" } ], "symlink_target": "" }
/* TEMPLATE GENERATED TESTCASE FILE Filename: CWE122_Heap_Based_Buffer_Overflow__cpp_CWE805_char_loop_74a.cpp Label Definition File: CWE122_Heap_Based_Buffer_Overflow__cpp_CWE805.string.label.xml Template File: sources-sink-74a.tmpl.cpp */ /* * @description * CWE: 122 Heap Based Buffer Overflow * BadSource: Allocate using new[] and set data pointer to a small buffer * GoodSource: Allocate using new[] and set data pointer to a large buffer * Sinks: loop * BadSink : Copy string to data using a loop * Flow Variant: 74 Data flow: data passed in a map from one function to another in different source files * * */ #include "std_testcase.h" #include <map> #include <wchar.h> using namespace std; namespace CWE122_Heap_Based_Buffer_Overflow__cpp_CWE805_char_loop_74 { #ifndef OMITBAD /* bad function declaration */ void badSink(map<int, char *> dataMap); void bad() { char * data; map<int, char *> dataMap; data = NULL; /* FLAW: Allocate using new[] and point data to a small buffer that is smaller than the large buffer used in the sinks */ data = new char[50]; data[0] = '\0'; /* null terminate */ /* Put data in a map */ dataMap[0] = data; dataMap[1] = data; dataMap[2] = data; badSink(dataMap); } #endif /* OMITBAD */ #ifndef OMITGOOD /* good function declarations */ /* goodG2B uses the GoodSource with the BadSink */ void goodG2BSink(map<int, char *> dataMap); static void goodG2B() { char * data; map<int, char *> dataMap; data = NULL; /* FIX: Allocate using new[] and point data to a large buffer that is at least as large as the large buffer used in the sink */ data = new char[100]; data[0] = '\0'; /* null terminate */ /* Put data in a map */ dataMap[0] = data; dataMap[1] = data; dataMap[2] = data; goodG2BSink(dataMap); } void good() { goodG2B(); } #endif /* OMITGOOD */ } /* close namespace */ /* Below is the main(). It is only used when building this testcase on its own for testing or for building a binary to use in testing binary analysis tools. It is not used when compiling all the testcases as one application, which is how source code analysis tools are tested. */ #ifdef INCLUDEMAIN using namespace CWE122_Heap_Based_Buffer_Overflow__cpp_CWE805_char_loop_74; /* so that we can use good and bad easily */ int main(int argc, char * argv[]) { /* seed randomness */ srand( (unsigned)time(NULL) ); #ifndef OMITGOOD printLine("Calling good()..."); good(); printLine("Finished good()"); #endif /* OMITGOOD */ #ifndef OMITBAD printLine("Calling bad()..."); bad(); printLine("Finished bad()"); #endif /* OMITBAD */ return 0; } #endif
{ "content_hash": "29537d992e9ac04c0f0faf97520a2ef0", "timestamp": "", "source": "github", "line_count": 106, "max_line_length": 131, "avg_line_length": 26.641509433962263, "alnum_prop": 0.6430594900849859, "repo_name": "JianpingZeng/xcc", "id": "a4b66f474ec979c0e8c66858c2bb699132bedee0", "size": "2824", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "xcc/test/juliet/testcases/CWE122_Heap_Based_Buffer_Overflow/s02/CWE122_Heap_Based_Buffer_Overflow__cpp_CWE805_char_loop_74a.cpp", "mode": "33188", "license": "bsd-3-clause", "language": [], "symlink_target": "" }
// ASM: a very small and fast Java bytecode manipulation framework // Copyright (c) 2000-2011 INRIA, France Telecom // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // 1. Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // 2. Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // 3. Neither the name of the copyright holders nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF // THE POSSIBILITY OF SUCH DAMAGE. package org.objectweb.asm.tree; import java.util.Map; import org.objectweb.asm.Handle; import org.objectweb.asm.MethodVisitor; import org.objectweb.asm.Opcodes; /** * A node that represents an invokedynamic instruction. * * @author Remi Forax */ public class InvokeDynamicInsnNode extends AbstractInsnNode { /** The method's name. */ public String name; /** The method's descriptor (see {@link org.objectweb.asm.Type}). */ public String desc; /** The bootstrap method. */ public Handle bsm; /** The bootstrap method constant arguments. */ public Object[] bsmArgs; /** * Constructs a new {@link InvokeDynamicInsnNode}. * * @param name the method's name. * @param descriptor the method's descriptor (see {@link org.objectweb.asm.Type}). * @param bootstrapMethodHandle the bootstrap method. * @param bootstrapMethodArguments the bootstrap method constant arguments. Each argument must be * an {@link Integer}, {@link Float}, {@link Long}, {@link Double}, {@link String}, {@link * org.objectweb.asm.Type} or {@link Handle} value. This method is allowed to modify the * content of the array so a caller should expect that this array may change. */ public InvokeDynamicInsnNode( final String name, final String descriptor, final Handle bootstrapMethodHandle, final Object... bootstrapMethodArguments) { // NOPMD(ArrayIsStoredDirectly): public field. super(Opcodes.INVOKEDYNAMIC); this.name = name; this.desc = descriptor; this.bsm = bootstrapMethodHandle; this.bsmArgs = bootstrapMethodArguments; } @Override public int getType() { return INVOKE_DYNAMIC_INSN; } @Override public void accept(final MethodVisitor methodVisitor) { methodVisitor.visitInvokeDynamicInsn(name, desc, bsm, bsmArgs); acceptAnnotations(methodVisitor); } @Override public AbstractInsnNode clone(final Map<LabelNode, LabelNode> clonedLabels) { return new InvokeDynamicInsnNode(name, desc, bsm, bsmArgs).cloneAnnotations(this); } }
{ "content_hash": "f99309e26d73f1519cf22157c80741bb", "timestamp": "", "source": "github", "line_count": 92, "max_line_length": 99, "avg_line_length": 40.26086956521739, "alnum_prop": 0.740280777537797, "repo_name": "JReFrameworker/JReFrameworker", "id": "8bb87124bd628f32c408420601e7cbccec139ba6", "size": "3704", "binary": false, "copies": "4", "ref": "refs/heads/master", "path": "plugin/org.objectweb.asm.core/src/org/objectweb/asm/tree/InvokeDynamicInsnNode.java", "mode": "33188", "license": "mit", "language": [ { "name": "HTML", "bytes": "39004" }, { "name": "Java", "bytes": "4359603" }, { "name": "Ruby", "bytes": "4515" } ], "symlink_target": "" }
package pgm; // Intended for use alongside the VariableCollectionType. Thus things are stored // as variable IDs and values from domains only! public interface EvidenceCollectionType { public String toString(); public boolean contains(VariableType v); public boolean contains(Integer vID); public Integer get(VariableType v); public Integer get(Integer vID); public boolean set(VariableType v, Integer e); public boolean set(Integer vID, Integer e); public boolean add(VariableType v, Integer e); public boolean add(Integer vID, Integer e); public boolean remove(VariableType v); public boolean remove(Integer vID); public int size(); public boolean isEmpty(); }
{ "content_hash": "cb93d2a4cfc1cb6759cb5e726e056c7b", "timestamp": "", "source": "github", "line_count": 26, "max_line_length": 80, "avg_line_length": 27.346153846153847, "alnum_prop": 0.7412095639943741, "repo_name": "gsteelman/utd", "id": "5fe211918671d9f8a1f74d147524529cb63dc467", "size": "711", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "cs6301-probabilistic-graphical-models/homework3/src/pgm/EvidenceCollectionType.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Arduino", "bytes": "596" }, { "name": "C", "bytes": "149459" }, { "name": "C++", "bytes": "851953" }, { "name": "CSS", "bytes": "43006" }, { "name": "FLUX", "bytes": "5154" }, { "name": "Java", "bytes": "363012" }, { "name": "JavaScript", "bytes": "67059" }, { "name": "Objective-C", "bytes": "582" }, { "name": "Python", "bytes": "2518" }, { "name": "Shell", "bytes": "5699" }, { "name": "TeX", "bytes": "193155" } ], "symlink_target": "" }
<!DOCTYPE html> <html> <head> <title>Welcome to the Open Weather Map</title> <!-- <link rel="stylesheet" href="style.css"> --> </head> <body> <center> <h1>Welcome to the Open Weather Maps API</h1> <hr> <div> <h2>Current Weather in New York City</h2> <div id="nyc-weather"></div> </div> <hr> <div> <form id="weather-form"> <h2>Find Weather in Your Area</h2> <label for="city">City</label> <input name="city" type="text" id="city" placeholder="City"> <label for="state">State</label> <input name="state" type="text" id="state" placeholder="State"> <button>Get Weather</button> </form> <div id="weather-output"></div> </div> <script id="weather-template" type="text/x-handlebars-template"> <p>City: {{city}}</p> <p>Temperature: {{temp}}</p> <p>Humidity: {{humidity}}</p> <p>Wind Speed: {{windSpeed}}</p> </script> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script> <script src="handlebars.js"></script> <script src="main.js" type="text/javascript" charset="utf-8" async defer></script> </center> </body> </html>
{ "content_hash": "39d93d86adc74af58b4d639b2df80f4c", "timestamp": "", "source": "github", "line_count": 44, "max_line_length": 91, "avg_line_length": 26.431818181818183, "alnum_prop": 0.6061908856405847, "repo_name": "streetrader/streetrader.github.io", "id": "8e03f08f392fcf550b2bd73f3019c1bb3640ad78", "size": "1163", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "jsd920_class_repo/week5/homework/open_weather_map_solution/index.html", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "874899" }, { "name": "HTML", "bytes": "385676" }, { "name": "JavaScript", "bytes": "2844367" }, { "name": "PHP", "bytes": "1312" } ], "symlink_target": "" }
package hudson.model; import hudson.Extension; import hudson.ExtensionList; import hudson.ExtensionPoint; import java.util.Collection; import java.util.Collections; /** * Extension point for inserting transient {@link Action}s into {@link User}s. * * To register your implementation, put {@link Extension} on your subtype. * * @author Vincent Latombe * @since 1.477 * @see Action */ public abstract class TransientUserActionFactory implements ExtensionPoint { /** * Creates actions for the given user. * * @param target for which the action objects are requested. Never null. * @return Can be empty but must not be null. */ public Collection<? extends Action> createFor(User target) { return Collections.emptyList(); } /** * Returns all the registered {@link TransientUserActionFactory}s. */ public static ExtensionList<TransientUserActionFactory> all() { return ExtensionList.lookup(TransientUserActionFactory.class); } }
{ "content_hash": "ff05e6de9636fbc1c62702f05a7eb9b7", "timestamp": "", "source": "github", "line_count": 38, "max_line_length": 78, "avg_line_length": 26.605263157894736, "alnum_prop": 0.7091988130563798, "repo_name": "Vlatombe/jenkins", "id": "d042afb490879bf1ac088840c0923b558444a30f", "size": "2154", "binary": false, "copies": "10", "ref": "refs/heads/master", "path": "core/src/main/java/hudson/model/TransientUserActionFactory.java", "mode": "33188", "license": "mit", "language": [ { "name": "Batchfile", "bytes": "1023" }, { "name": "C", "bytes": "2091" }, { "name": "CSS", "bytes": "316538" }, { "name": "Dockerfile", "bytes": "1147" }, { "name": "GAP", "bytes": "6289" }, { "name": "Groovy", "bytes": "73150" }, { "name": "HTML", "bytes": "976775" }, { "name": "Java", "bytes": "10397127" }, { "name": "JavaScript", "bytes": "376558" }, { "name": "Perl", "bytes": "14718" }, { "name": "Ruby", "bytes": "19375" }, { "name": "Shell", "bytes": "10545" } ], "symlink_target": "" }
This project implements a very simple frequency generator for testing CNC, stepper motor or stepper driver when putting in charge. It is written in C using the arduino IDE and applies the Arduino Nano platform. The implementation provides a potentiometer and six push buttons for reading the requested signal to be generated at the specified output/axis YAFG is useful when putting a CNC mechanics, stepper motors or stepper driver in charge. ### Basic Information: * applies the Arduino Nano platform (ATMega328P) * generates pulses for up to three stepper driver * two press buttons per driver (left/right motor turn direction) * potentiometer for adjusting speed/signal freqeuncy (approximately 100Hz to 6KHz). ### Example Usage * ![demonstration video](https://raw.githubusercontent.com/rubienr/yafg/master/meta/cnc-motor-driver-test.mov) ![example usage](https://github.com/rubienr/yafg/blob/master/meta/yafg-sketch.jpg) ![hardware implementation](https://github.com/rubienr/yafg/blob/master/meta/hw-example.jpg)
{ "content_hash": "f041961072bc0c81e0d34be549a9e7b1", "timestamp": "", "source": "github", "line_count": 16, "max_line_length": 142, "avg_line_length": 63.8125, "alnum_prop": 0.801175318315377, "repo_name": "rubienr/yafg", "id": "b122c027015c04532bd078f679bb376fc4687e16", "size": "1062", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "README.md", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Arduino", "bytes": "8231" } ], "symlink_target": "" }
package androidx.appcompat.demo.receivecontent; import android.annotation.SuppressLint; import android.net.Uri; import android.os.Bundle; import android.util.Log; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.appcompat.app.AppCompatActivity; import androidx.appcompat.widget.AppCompatEditText; import androidx.appcompat.widget.LinearLayoutCompat; import androidx.appcompat.widget.Toolbar; import androidx.core.view.ViewCompat; import androidx.recyclerview.widget.RecyclerView; import com.google.common.collect.ImmutableList; import com.google.common.util.concurrent.FutureCallback; import com.google.common.util.concurrent.Futures; import com.google.common.util.concurrent.ListenableFuture; /** Main activity for the app. */ public class MainActivity extends AppCompatActivity { private AttachmentsRepo mAttachmentsRepo; private AttachmentsRecyclerViewAdapter mAttachmentsRecyclerViewAdapter; @Override protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); Toolbar toolbar = findViewById(R.id.app_toolbar); setSupportActionBar(toolbar); mAttachmentsRepo = new AttachmentsRepo(this); ImmutableList<Uri> attachments = mAttachmentsRepo.getAllUris(); RecyclerView attachmentsRecyclerView = findViewById(R.id.attachments_recycler_view); attachmentsRecyclerView.setHasFixedSize(true); mAttachmentsRecyclerViewAdapter = new AttachmentsRecyclerViewAdapter(attachments); attachmentsRecyclerView.setAdapter(mAttachmentsRecyclerViewAdapter); MyReceiver receiver = new MyReceiver(mAttachmentsRepo, mAttachmentsRecyclerViewAdapter); LinearLayoutCompat container = findViewById(R.id.container); ViewCompat.setOnReceiveContentListener(container, MyReceiver.SUPPORTED_MIME_TYPES, receiver); AppCompatEditText textInput = findViewById(R.id.text_input); ViewCompat.setOnReceiveContentListener(textInput, MyReceiver.SUPPORTED_MIME_TYPES, receiver); } @Override public boolean onCreateOptionsMenu(@NonNull Menu menu) { MenuInflater inflater = getMenuInflater(); inflater.inflate(R.menu.app_menu, menu); return true; } @Override public boolean onOptionsItemSelected(@NonNull MenuItem item) { if (item.getItemId() == R.id.action_clear_attachments) { deleteAllAttachments(); return true; } return false; } private void deleteAllAttachments() { ListenableFuture<Void> deleteAllFuture = MyExecutors.bg().submit(() -> { mAttachmentsRepo.deleteAll(); return null; }); Futures.addCallback(deleteAllFuture, new FutureCallback<Void>() { @SuppressLint("SyntheticAccessor") @Override public void onSuccess(@Nullable Void result) { mAttachmentsRecyclerViewAdapter.clearAttachments(); mAttachmentsRecyclerViewAdapter.notifyDataSetChanged(); } @Override public void onFailure(@NonNull Throwable t) { Log.e(Logcat.TAG, "Error deleting attachments", t); } }, MyExecutors.main()); } }
{ "content_hash": "0b42334b010220566cd3edc0b8558264", "timestamp": "", "source": "github", "line_count": 90, "max_line_length": 96, "avg_line_length": 38.24444444444445, "alnum_prop": 0.7187681580476467, "repo_name": "androidx/androidx", "id": "9ea18923d50ce815fc3300a8693faf6f7438fcf9", "size": "4057", "binary": false, "copies": "3", "ref": "refs/heads/androidx-main", "path": "appcompat/integration-tests/receive-content-testapp/src/main/java/androidx/appcompat/demo/receivecontent/MainActivity.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "AIDL", "bytes": "263978" }, { "name": "ANTLR", "bytes": "19860" }, { "name": "C", "bytes": "4764" }, { "name": "C++", "bytes": "9020585" }, { "name": "CMake", "bytes": "11999" }, { "name": "HTML", "bytes": "21175" }, { "name": "Java", "bytes": "59499889" }, { "name": "JavaScript", "bytes": "1343" }, { "name": "Kotlin", "bytes": "66123157" }, { "name": "Python", "bytes": "292398" }, { "name": "Shell", "bytes": "167367" }, { "name": "Swift", "bytes": "3153" }, { "name": "TypeScript", "bytes": "7599" } ], "symlink_target": "" }
<?php defined('BASEPATH') OR exit('No direct script access allowed'); class Query extends MY_Controller { private $user_id; public function __construct() { parent::__construct(); if ($this->session_check() != 1) { echo '认证失败, 请重新登录'; sleep(0.3); redirect('/user/login', 'location', 301); } $this->load->model('user'); $this->load->model('query_model'); $this->config->load('search_type'); $this->user_id = $this->user->get_user_id($this->session->userdata('user_id')); } public function to_timestamp($unix_time) { return date("Y-m-d H:m:s", $unix_time); } public function index() { $this->load->view('user/header', array( 'username' => $this->session->userdata('user_id'), )); if ($this->user->has_privilege($this->user_id, 'is_query') != 1) { $this->load->view('user/error'); } else { $search_type = $this->config->item('search_type'); $search_type_reverse = $this->config->item('search_type_reverse'); $this->load->view('user/query', array( 'search_type' => $search_type, 'search_type_reverse' => $search_type_reverse, )); } $this->load->view('user/footer'); } public function search($offset_page = 0) { $per_page = 15; $offset = $offset_page * $per_page; $conditions = array( 'startDate' => $this->to_timestamp($this->input->post('startDate')), 'endDate' => $this->to_timestamp($this->input->post('endDate')), 'location' => $this->input->post('location'), 'qq' => $this->input->post('qq'), 'weixin' => $this->input->post('wechat'), 'type' => $this->input->post('search-type'), 'keyword' => $this->input->post('keyword') ); $results = $this->query_model->search($conditions, $per_page, $offset)->result(); echo json_encode($results); } public function get_search_nums() { $conditions = array( 'startDate' => $this->to_timestamp($this->input->post('startDate')), 'endDate' => $this->to_timestamp($this->input->post('endDate')), 'location' => $this->input->post('location'), 'qq' => $this->input->post('qq'), 'weixin' => $this->input->post('wechat'), 'type' => $this->input->post('search-type'), 'keyword' => $this->input->post('keyword') ); echo json_encode(array( "nums" => $this->query_model->search_row_num($conditions) )); } public function data_import() { $salt = md5(sha1('import')); $post_salt = $this->input->post('salt'); $data = array( 'type' => $this->input->post('type'), 'city' => $this->input->post('city'), 'qq' => $this->input->post('qq'), 'weixin' => $this->input->post('weixin'), 'mobile' => $this->input->post('mobile'), 'phone' => $this->input->post('phone'), 'real_name' => $this->input->post('real_name'), 'id_card' => $this->input->post('id_card'), 'content' => $this->input->post('content'), 'source_url' => $this->input->post('source_url'), 'gmt_create' => $this->input->post('gmt_create'), 'gmt_modify' => $this->input->post('gmt_modify') ); if ($post_salt == $salt) { $this->query_model->inserts($data); echo json_encode(array( 'status' => '1' )); } else { echo json_encode(array( 'salt' => $post_salt, 'status' => '0', )); } } public function test() { // $results = $this->query_model->search(array( // 'startDate' => $this->to_timestamp('2736000'), // 'endDate' => $this->to_timestamp('1492790400'), // 'location' => $this->input->post('location'), // 'qq' => $this->input->post('qq'), // 'weixin' => $this->input->post('wechat'), // 'type' => $this->input->post('search-type'), // 'keyword' => $this->input->post('keyword') // )); // data是从数据库查询到的数据 // $rows_num = 0; // foreach ($results as $key => $val) { // $rows_num++; // } // $this->load->library('pagination'); // $config['base_url'] = $_SERVER['PHP_SELF']; // $config['total_rows'] = $rows_num; // $config['per_page'] = 15; // $config['uri_segment'] = 3; // $config['use_page_numbers'] = TRUE; // $config['full_tag_open'] = '<ul class=pagination>'; // $config['full_tag_close'] = '</ul>'; // $this->pagination->initialize($config); // echo $this->pagination->create_links(); } }
{ "content_hash": "8bba63019547155913f72cda0eb2283f", "timestamp": "", "source": "github", "line_count": 144, "max_line_length": 83, "avg_line_length": 28.9375, "alnum_prop": 0.576193904487641, "repo_name": "a1exlism/7wadata", "id": "67d253a684c79bb59f9766cd8551cd810461af3e", "size": "4207", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "user/controllers/Query.php", "mode": "33261", "license": "apache-2.0", "language": [ { "name": "ApacheConf", "bytes": "370" }, { "name": "CSS", "bytes": "1236819" }, { "name": "HTML", "bytes": "148404" }, { "name": "JavaScript", "bytes": "2963085" }, { "name": "PHP", "bytes": "1877337" } ], "symlink_target": "" }
(function () { 'use strict'; angular .module('app.core') .controller('MsWidgetController', MsWidgetController) .directive('msWidget', msWidgetDirective) .directive('msWidgetFront', msWidgetFrontDirective) .directive('msWidgetBack', msWidgetBackDirective); /** @ngInject */ function MsWidgetController($scope, $element) { var vm = this; // Data vm.flipped = false; // Methods vm.flip = flip; ////////// /** * Flip the widget */ function flip() { if ( !isFlippable() ) { return; } // Toggle flipped status vm.flipped = !vm.flipped; // Toggle the 'flipped' class $element.toggleClass('flipped', vm.flipped); } /** * Check if widget is flippable * * @returns {boolean} */ function isFlippable() { return (angular.isDefined($scope.flippable) && $scope.flippable === true); } } /** @ngInject */ function msWidgetDirective() { return { restrict : 'E', scope : { flippable: '=?' }, controller: 'MsWidgetController', transclude: true, compile : function (tElement) { tElement.addClass('ms-widget'); return function postLink(scope, iElement, iAttrs, MsWidgetCtrl, transcludeFn) { // Custom transclusion transcludeFn(function (clone) { iElement.empty(); iElement.append(clone); }); ////////// }; } }; } /** @ngInject */ function msWidgetFrontDirective() { return { restrict : 'E', require : '^msWidget', transclude: true, compile : function (tElement) { tElement.addClass('ms-widget-front'); return function postLink(scope, iElement, iAttrs, MsWidgetCtrl, transcludeFn) { // Custom transclusion transcludeFn(function (clone) { iElement.empty(); iElement.append(clone); }); // Methods scope.flipWidget = MsWidgetCtrl.flip; }; } }; } /** @ngInject */ function msWidgetBackDirective() { return { restrict : 'E', require : '^msWidget', transclude: true, compile : function (tElement) { tElement.addClass('ms-widget-back'); return function postLink(scope, iElement, iAttrs, MsWidgetCtrl, transcludeFn) { // Custom transclusion transcludeFn(function (clone) { iElement.empty(); iElement.append(clone); }); // Methods scope.flipWidget = MsWidgetCtrl.flip; }; } }; } })();
{ "content_hash": "afe0429db9fe6630b39c3d5ff7e754b4", "timestamp": "", "source": "github", "line_count": 136, "max_line_length": 93, "avg_line_length": 25.433823529411764, "alnum_prop": 0.4200636021971668, "repo_name": "UCSC-LK/CV-APP", "id": "3727bbc645f5c3f7b6c2dc34f0d132f3151addcb", "size": "3459", "binary": false, "copies": "12", "ref": "refs/heads/master", "path": "client/src/app/core/directives/ms-widget/ms-widget.directive.js", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "270349" }, { "name": "HTML", "bytes": "101849" }, { "name": "JavaScript", "bytes": "311205" } ], "symlink_target": "" }
package org.postgresql.test.jdbc2; import java.sql.*; import java.util.Arrays; import junit.framework.TestCase; import java.io.InputStream; import java.io.ByteArrayInputStream; import java.io.Reader; import java.io.StringReader; import java.io.UnsupportedEncodingException; import java.util.TimeZone; import org.postgresql.test.TestUtil; public class UpdateableResultTest extends TestCase { private Connection con; public UpdateableResultTest( String name ) { super( name ); try { Class.forName("org.postgresql.Driver"); } catch( Exception ex ){} } protected void setUp() throws Exception { con = TestUtil.openDB(); TestUtil.createTable(con, "updateable", "id int primary key, name text, notselected text, ts timestamp with time zone, intarr int[]", true); TestUtil.createTable(con, "second", "id1 int primary key, name1 text"); TestUtil.createTable(con, "stream", "id int primary key, asi text, chr text, bin bytea"); TestUtil.createTable(con, "multicol", "id1 int not null, id2 int not null, val text"); Statement st2 = con.createStatement(); // create pk for multicol table st2.execute("ALTER TABLE multicol ADD CONSTRAINT multicol_pk PRIMARY KEY (id1, id2)"); // put some dummy data into second st2.execute( "insert into second values (1,'anyvalue' )"); st2.close(); } protected void tearDown() throws Exception { TestUtil.dropTable(con, "updateable"); TestUtil.dropTable(con, "second"); TestUtil.dropTable(con, "stream"); TestUtil.closeDB(con); } public void testDeleteRows() throws SQLException { Statement st = con.createStatement(); st.executeUpdate("INSERT INTO second values (2,'two')"); st.executeUpdate("INSERT INTO second values (3,'three')"); st.executeUpdate("INSERT INTO second values (4,'four')"); st.close(); st = con.createStatement( ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_UPDATABLE ); ResultSet rs = st.executeQuery( "select id1,name1 from second order by id1"); assertTrue(rs.next()); assertEquals(1, rs.getInt("id1")); rs.deleteRow(); assertTrue(rs.isBeforeFirst()); assertTrue(rs.next()); assertTrue(rs.next()); assertEquals(3, rs.getInt("id1")); rs.deleteRow(); assertEquals(2, rs.getInt("id1")); rs.close(); st.close(); } public void testCancelRowUpdates() throws Exception { Statement st = con.createStatement( ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_UPDATABLE ); ResultSet rs = st.executeQuery( "select * from second"); // make sure we're dealing with the correct row. rs.first(); assertEquals(1, rs.getInt(1)); assertEquals("anyvalue", rs.getString(2)); // update, cancel and make sure nothings changed. rs.updateInt(1, 99); rs.cancelRowUpdates(); assertEquals(1, rs.getInt(1)); assertEquals("anyvalue", rs.getString(2)); // real update rs.updateInt(1, 999); rs.updateRow(); assertEquals(999, rs.getInt(1)); assertEquals("anyvalue", rs.getString(2)); // scroll some and make sure the update is still there rs.beforeFirst(); rs.next(); assertEquals(999, rs.getInt(1)); assertEquals("anyvalue", rs.getString(2)); // make sure the update got to the db and the driver isn't lying to us. rs.close(); rs = st.executeQuery( "select * from second"); rs.first(); assertEquals(999, rs.getInt(1)); assertEquals("anyvalue", rs.getString(2)); rs.close(); st.close(); } private void checkPositioning(ResultSet rs) throws SQLException { try { rs.getInt(1); fail("Can't use an incorrectly positioned result set."); } catch (SQLException sqle) { } try { rs.updateInt(1, 2); fail("Can't use an incorrectly positioned result set."); } catch (SQLException sqle) { } try { rs.updateRow(); fail("Can't use an incorrectly positioned result set."); } catch (SQLException sqle) { } try { rs.deleteRow(); fail("Can't use an incorrectly positioned result set."); } catch (SQLException sqle) { } } public void testPositioning() throws SQLException { Statement stmt = con.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_UPDATABLE); ResultSet rs = stmt.executeQuery("SELECT id1,name1 FROM second"); checkPositioning(rs); assertTrue(rs.next()); rs.beforeFirst(); checkPositioning(rs); rs.afterLast(); checkPositioning(rs); rs.beforeFirst(); assertTrue(rs.next()); assertTrue(!rs.next()); checkPositioning(rs); rs.afterLast(); assertTrue(rs.previous()); assertTrue(!rs.previous()); checkPositioning(rs); rs.close(); stmt.close(); } public void testUpdateTimestamp() throws SQLException { TimeZone origTZ = TimeZone.getDefault(); try { // We choose a timezone which has a partial hour portion // Asia/Tehran is +3:30 TimeZone.setDefault(TimeZone.getTimeZone("Asia/Tehran")); Timestamp ts = Timestamp.valueOf("2006-11-20 16:17:18"); Statement stmt = con.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_UPDATABLE); ResultSet rs = stmt.executeQuery("SELECT id, ts FROM updateable"); rs.moveToInsertRow(); rs.updateInt(1,1); rs.updateTimestamp(2,ts); rs.insertRow(); rs.first(); assertEquals(ts, rs.getTimestamp(2)); } finally { TimeZone.setDefault(origTZ); } } public void testUpdateStreams() throws SQLException, UnsupportedEncodingException { String string = "Hello"; byte[] bytes = new byte[]{0,'\\',(byte) 128,(byte) 255}; Statement stmt = con.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_UPDATABLE); ResultSet rs = stmt.executeQuery("SELECT id, asi, chr, bin FROM stream"); rs.moveToInsertRow(); rs.updateInt(1, 1); rs.updateAsciiStream("asi", null, 17); rs.updateCharacterStream("chr", null, 81); rs.updateBinaryStream("bin", null, 0); rs.insertRow(); rs.moveToInsertRow(); rs.updateInt(1, 3); rs.updateAsciiStream("asi", new ByteArrayInputStream(string.getBytes("US-ASCII")), 5); rs.updateCharacterStream("chr", new StringReader(string), 5); rs.updateBinaryStream("bin", new ByteArrayInputStream(bytes), bytes.length); rs.insertRow(); rs.beforeFirst(); rs.next(); assertEquals(1, rs.getInt(1)); assertNull(rs.getString(2)); assertNull(rs.getString(3)); assertNull(rs.getBytes(4)); rs.updateInt("id", 2); rs.updateAsciiStream("asi", new ByteArrayInputStream(string.getBytes("US-ASCII")), 5); rs.updateCharacterStream("chr", new StringReader(string), 5); rs.updateBinaryStream("bin", new ByteArrayInputStream(bytes), bytes.length); rs.updateRow(); assertEquals(2, rs.getInt(1)); assertEquals(string, rs.getString(2)); assertEquals(string, rs.getString(3)); assertTrue(Arrays.equals(bytes, rs.getBytes(4))); rs.refreshRow(); assertEquals(2, rs.getInt(1)); assertEquals(string, rs.getString(2)); assertEquals(string, rs.getString(3)); assertTrue(Arrays.equals(bytes, rs.getBytes(4))); rs.next(); assertEquals(3, rs.getInt(1)); assertEquals(string, rs.getString(2)); assertEquals(string, rs.getString(3)); assertTrue(Arrays.equals(bytes, rs.getBytes(4))); rs.close(); stmt.close(); } public void testZeroRowResult() throws SQLException { Statement st = con.createStatement( ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_UPDATABLE ); ResultSet rs = st.executeQuery( "select * from updateable WHERE 0 > 1"); assertTrue(!rs.next()); rs.moveToInsertRow(); rs.moveToCurrentRow(); } public void testUpdateable() throws SQLException { Statement st = con.createStatement( ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_UPDATABLE ); ResultSet rs = st.executeQuery( "select * from updateable"); assertNotNull( rs ); rs.moveToInsertRow(); rs.updateInt( 1, 1 ); rs.updateString( 2, "jake" ); rs.updateString( 3, "avalue" ); rs.insertRow(); rs.first(); rs.updateInt( "id", 2 ); rs.updateString( "name", "dave" ); rs.updateRow(); assertEquals(2, rs.getInt("id")); assertEquals("dave", rs.getString("name")); assertEquals("avalue", rs.getString("notselected")); rs.deleteRow(); rs.moveToInsertRow(); rs.updateInt("id", 3); rs.updateString("name", "paul"); rs.insertRow(); try { rs.refreshRow(); fail("Can't refresh when on the insert row."); } catch (SQLException sqle) { } assertEquals(3, rs.getInt("id")); assertEquals("paul", rs.getString("name")); assertNull(rs.getString("notselected")); rs.close(); rs = st.executeQuery("select id1, id, name, name1 from updateable, second" ); try { while ( rs.next() ) { rs.updateInt( "id", 2 ); rs.updateString( "name", "dave" ); rs.updateRow(); } fail("should not get here, update should fail"); } catch (SQLException ex) { } rs = st.executeQuery("select oid,* from updateable"); assertTrue(rs.first()); rs.updateInt( "id", 3 ); rs.updateString( "name", "dave3"); rs.updateRow(); assertEquals(3, rs.getInt("id")); assertEquals("dave3", rs.getString("name")); rs.moveToInsertRow(); rs.updateInt( "id", 4 ); rs.updateString( "name", "dave4" ); rs.insertRow(); rs.updateInt("id", 5 ); rs.updateString( "name", "dave5" ); rs.insertRow(); rs.moveToCurrentRow(); assertEquals(3, rs.getInt("id")); assertEquals("dave3", rs.getString("name")); assertTrue( rs.next() ); assertEquals(4, rs.getInt("id")); assertEquals("dave4", rs.getString("name")); assertTrue( rs.next() ); assertEquals(5, rs.getInt("id")); assertEquals("dave5", rs.getString("name")); rs.close(); st.close(); } public void testInsertRowIllegalMethods() throws Exception { Statement st = con.createStatement( ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_UPDATABLE ); ResultSet rs = st.executeQuery( "select * from updateable"); assertNotNull(rs); rs.moveToInsertRow(); try { rs.cancelRowUpdates(); fail("expected an exception when calling cancelRowUpdates() on the insert row"); } catch (SQLException e) {} try { rs.updateRow(); fail("expected an exception when calling updateRow() on the insert row"); } catch (SQLException e) {} try { rs.deleteRow(); fail("expected an exception when calling deleteRow() on the insert row"); } catch (SQLException e) {} try { rs.refreshRow(); fail("expected an exception when calling refreshRow() on the insert row"); } catch (SQLException e) {} rs.close(); st.close(); } public void testUpdateablePreparedStatement() throws Exception { // No args. PreparedStatement st = con.prepareStatement("select * from updateable", ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_UPDATABLE); ResultSet rs = st.executeQuery(); rs.moveToInsertRow(); rs.close(); st.close(); // With args. st = con.prepareStatement("select * from updateable where id = ?", ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_UPDATABLE); st.setInt(1, 1); rs = st.executeQuery(); rs.moveToInsertRow(); rs.close(); st.close(); } public void testUpdateSelectOnly() throws Exception { Statement st = con.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_UPDATABLE); ResultSet rs = st.executeQuery( "select * from only second"); assertTrue(rs.next()); rs.updateInt(1, 2); rs.updateRow(); } public void testUpdateReadOnlyResultSet() throws Exception { Statement st = con.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY); ResultSet rs = st.executeQuery( "select * from updateable"); try { rs.moveToInsertRow(); fail("expected an exception when calling moveToInsertRow() on a read-only resultset"); } catch (SQLException e) {} } public void testBadColumnIndexes() throws Exception { Statement st = con.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_UPDATABLE); ResultSet rs = st.executeQuery( "select * from updateable"); rs.moveToInsertRow(); try { rs.updateInt(0,1); fail("Should have thrown an exception on bad column index."); } catch (SQLException sqle) { } try { rs.updateString(1000,"hi"); fail("Should have thrown an exception on bad column index."); } catch (SQLException sqle) { } try { rs.updateNull(1000); fail("Should have thrown an exception on bad column index."); } catch (SQLException sqle) { } } public void testArray() throws SQLException { Statement stmt = con.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_UPDATABLE); stmt.executeUpdate("INSERT INTO updateable (id, intarr) VALUES (1, '{1,2,3}'::int4[])"); ResultSet rs = stmt.executeQuery("SELECT id, intarr FROM updateable"); assertTrue(rs.next()); rs.updateObject(2, rs.getArray(2)); rs.updateRow(); Array arr = rs.getArray(2); assertEquals(Types.INTEGER, arr.getBaseType()); Integer intarr[] = (Integer[])arr.getArray(); assertEquals(3, intarr.length); assertEquals(1, intarr[0].intValue()); assertEquals(2, intarr[1].intValue()); assertEquals(3, intarr[2].intValue()); rs.close(); rs = stmt.executeQuery("SELECT id,intarr FROM updateable"); assertTrue(rs.next()); arr = rs.getArray(2); assertEquals(Types.INTEGER, arr.getBaseType()); intarr = (Integer[])arr.getArray(); assertEquals(3, intarr.length); assertEquals(1, intarr[0].intValue()); assertEquals(2, intarr[1].intValue()); assertEquals(3, intarr[2].intValue()); rs.close(); stmt.close(); } public void testMultiColumnUpdateWithoutAllColumns() throws Exception { Statement st = con.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_UPDATABLE); ResultSet rs = st.executeQuery( "select id1,val from multicol"); try { rs.moveToInsertRow(); } catch (SQLException sqle) { // Ensure we're reporting that the RS is not updatable. assertEquals("24000", sqle.getSQLState()); } } public void testMultiColumnUpdate() throws Exception { Statement st = con.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_UPDATABLE); st.executeUpdate("INSERT INTO multicol (id1,id2,val) VALUES (1,2,'val')"); ResultSet rs = st.executeQuery("SELECT id1, id2, val FROM multicol"); assertTrue(rs.next()); assertEquals("val", rs.getString("val")); rs.updateString("val", "newval"); rs.updateRow(); rs.close(); rs = st.executeQuery("SELECT id1, id2, val FROM multicol"); assertTrue(rs.next()); assertEquals("newval", rs.getString("val")); rs.close(); st.close(); } }
{ "content_hash": "1a0627cb4fed754e773bec2164aaa1e0", "timestamp": "", "source": "github", "line_count": 533, "max_line_length": 148, "avg_line_length": 32.43339587242026, "alnum_prop": 0.5771967374327529, "repo_name": "alexismeneses/pgjdbc", "id": "4651910c13862f5bfe663d569e81630dd54e2738", "size": "17509", "binary": false, "copies": "9", "ref": "refs/heads/master", "path": "org/postgresql/test/jdbc2/UpdateableResultTest.java", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "Java", "bytes": "2381620" }, { "name": "Shell", "bytes": "412" }, { "name": "XSLT", "bytes": "74068" } ], "symlink_target": "" }
require 'rails_helper' describe PhoneImporter do let(:invalid_content) { Rails.root.join('spec/support/fixtures/invalid_phone.csv') } let(:valid_content) { Rails.root.join('spec/support/fixtures/valid_location_phone.csv') } let(:valid_service_phone) { Rails.root.join('spec/support/fixtures/valid_service_phone.csv') } let(:valid_org_phone) { Rails.root.join('spec/support/fixtures/valid_org_phone.csv') } let(:valid_contact_phone) { Rails.root.join('spec/support/fixtures/valid_contact_phone.csv') } let(:no_parent) { Rails.root.join('spec/support/fixtures/phone_with_no_parent.csv') } before(:all) do DatabaseCleaner.clean_with(:truncation) create(:location) end after(:all) do Organization.find_each(&:destroy) end subject(:importer) { PhoneImporter.new(content) } describe '#valid?' do context 'when the phone content is invalid' do let(:content) { invalid_content } it { is_expected.not_to be_valid } end context 'when the content is valid' do let(:content) { valid_content } it { is_expected.to be_valid } end end describe '#errors' do context 'when the phone content is not valid' do let(:content) { invalid_content } errors = ["Line 2: Number type can't be blank for Phone"] its(:errors) { is_expected.to eq(errors) } end context 'when a parent does not exist' do let(:content) { no_parent } errors = ['Line 2: Phone is missing a parent: Location or Contact or ' \ 'Service or Organization'] its(:errors) { is_expected.to eq(errors) } end end describe '#import' do context 'with all the required fields to create a phone' do let(:content) { valid_content } it 'creates a phone' do expect { importer.import }.to change(Phone, :count).by(1) end describe 'the phone' do before { importer.import } subject { Phone.first } its(:id) { is_expected.to eq 2 } its(:department) { is_expected.to eq 'Food Pantry' } its(:extension) { is_expected.to eq '123' } its(:number) { is_expected.to eq '703-555-1212' } its(:number_type) { is_expected.to eq 'voice' } its(:vanity_number) { is_expected.to eq '703-555-FOOD' } its(:country_prefix) { is_expected.to eq '1' } its(:location_id) { is_expected.to eq 1 } end end context 'when the phone belongs to a service' do before do DatabaseCleaner.clean_with(:truncation) create(:service) end let(:content) { valid_service_phone } describe 'the phone' do before { importer.import } subject { Phone.first } its(:service_id) { is_expected.to eq 1 } end end context 'when the phone belongs to an organization' do let(:content) { valid_org_phone } describe 'the phone' do before { importer.import } subject { Phone.first } its(:organization_id) { is_expected.to eq 1 } end end context 'when the phone belongs to a contact' do before do DatabaseCleaner.clean_with(:truncation) create(:location).contacts.create!(attributes_for(:contact)) end let(:content) { valid_contact_phone } describe 'the phone' do before { importer.import } subject { Phone.first } its(:contact_id) { is_expected.to eq 1 } end end context 'when one of the fields required for a phone is blank' do let(:content) { invalid_content } it 'saves the valid entries and skips invalid ones' do expect { importer.import }.to change(Phone, :count).by(1) end end context 'when the phone already exists' do before do importer.import end let(:content) { valid_content } it 'does not create a new phone' do expect { importer.import }.to_not change(Phone, :count) end it 'does not generate errors' do expect(importer.errors).to eq [] end end end describe '.check_and_import_file' do it 'calls FileChecker' do path = Rails.root.join('spec/support/fixtures/valid_location_phone.csv') file = double('FileChecker') allow(file).to receive(:validate).and_return true expect(Kernel).to receive(:puts). with("\n===> Importing valid_location_phone.csv") expect(FileChecker).to receive(:new). with(path, PhoneImporter.required_headers).and_return(file) PhoneImporter.check_and_import_file(path) end context 'with invalid data' do it 'outputs error message' do expect(Kernel).to receive(:puts). with("\n===> Importing invalid_phone.csv") expect(Kernel).to receive(:puts). with("Line 2: Number type can't be blank for Phone") path = Rails.root.join('spec/support/fixtures/invalid_phone.csv') PhoneImporter.check_and_import_file(path) end end end describe '.required_headers' do it 'matches required headers in Wiki' do expect(PhoneImporter.required_headers). to eq %w(id location_id organization_id service_id contact_id department extension number number_type vanity_number country_prefix) end end end
{ "content_hash": "6d2d8c478090a5c02dcb8d169f7dec72", "timestamp": "", "source": "github", "line_count": 187, "max_line_length": 96, "avg_line_length": 28.299465240641712, "alnum_prop": 0.6290627362055934, "repo_name": "tannerj/ohana-api", "id": "d42d37b0665afcba2d96b95299461d1bb2bfa4a1", "size": "5292", "binary": false, "copies": "4", "ref": "refs/heads/master", "path": "spec/lib/phone_importer_spec.rb", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "CSS", "bytes": "4824" }, { "name": "CoffeeScript", "bytes": "872" }, { "name": "HTML", "bytes": "57672" }, { "name": "JavaScript", "bytes": "4152" }, { "name": "PLpgSQL", "bytes": "35488" }, { "name": "Ruby", "bytes": "628809" }, { "name": "Shell", "bytes": "3366" } ], "symlink_target": "" }
/** * A client to Bare Metal Solution API * * <p>The interfaces provided are listed below, along with usage samples. * * <p>======================= BareMetalSolutionClient ======================= * * <p>Service Description: Performs management operations on Bare Metal Solution servers. * * <p>The `baremetalsolution.googleapis.com` service provides management capabilities for Bare Metal * Solution servers. To access the API methods, you must assign Bare Metal Solution IAM roles * containing the desired permissions to your staff in your Google Cloud project. You must also * enable the Bare Metal Solution API. Once enabled, the methods act upon specific servers in your * Bare Metal Solution environment. * * <p>Sample for BareMetalSolutionClient: * * <pre>{@code * // This snippet has been automatically generated and should be regarded as a code template only. * // It will require modifications to work: * // - It may require correct/in-range values for request initialization. * // - It may require specifying regional endpoints when creating the service client as shown in * // https://cloud.google.com/java/docs/setup#configure_endpoints_for_the_client_library * try (BareMetalSolutionClient bareMetalSolutionClient = BareMetalSolutionClient.create()) { * InstanceName name = InstanceName.of("[PROJECT]", "[LOCATION]", "[INSTANCE]"); * Instance response = bareMetalSolutionClient.getInstance(name); * } * }</pre> */ @Generated("by gapic-generator-java") package com.google.cloud.baremetalsolution.v2; import javax.annotation.Generated;
{ "content_hash": "3736e4b68b6bc468a10e5af7e065fd4b", "timestamp": "", "source": "github", "line_count": 35, "max_line_length": 100, "avg_line_length": 45.2, "alnum_prop": 0.7338811630847029, "repo_name": "googleapis/java-bare-metal-solution", "id": "b02c05c2cf8e1e5577a6c4c1b9b3a7a35292d5b0", "size": "2177", "binary": false, "copies": "2", "ref": "refs/heads/main", "path": "google-cloud-bare-metal-solution/src/main/java/com/google/cloud/baremetalsolution/v2/package-info.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Batchfile", "bytes": "801" }, { "name": "Java", "bytes": "2686083" }, { "name": "Python", "bytes": "787" }, { "name": "Shell", "bytes": "20480" } ], "symlink_target": "" }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace OpskinsDll.TO { public class DepositFilter { public string appid { get; set; } public string contextid { get; set; } public string assetid { get; set; } } }
{ "content_hash": "09cdbc7970934b678d92a4e4cea3763f", "timestamp": "", "source": "github", "line_count": 15, "max_line_length": 45, "avg_line_length": 21.4, "alnum_prop": 0.6697819314641744, "repo_name": "AndradePT/Opskins", "id": "eeaac4a669bb4d8c5bec7c5484706a432fc1ddfe", "size": "323", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "OpskinsDll/OpskinsDll/TO/DepositFilter.cs", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "C#", "bytes": "59368" }, { "name": "PowerShell", "bytes": "3737" } ], "symlink_target": "" }
/** * @file * @brief */ #ifndef COMPRESS_CRC_H #define COMPRESS_CRC_H #include "typedefs.h" #include "compress_service_library.h" #ifdef __cplusplus extern "C" { #endif /* Update a running crc with the bytes buf[0..len-1] and return the updated crc. The crc should be initialized to zero. Pre- and post-conditioning (one's complement) is performed within this function so it shouldn't be done by the caller. Usage example: unsigned long crc = 0L; while (read_buffer(buffer, length) != EOF) { crc = update_crc(crc, buffer, length); } if (crc != original_crc) error(); */ COMPRESS_SERVICE_LOCAL uint32 UpdateCRC (uint32 crc, const uint8 *buffer_p, size_t len); /* Return the CRC of the bytes buf[0..len-1]. */ COMPRESS_SERVICE_LOCAL uint32 GetCRC (const uint8 *buffer_p, size_t len); #ifdef __cplusplus } #endif #endif /* #ifndef COMPRESS_CRC_H */
{ "content_hash": "bb9da716d883c4adb2984667967189b2", "timestamp": "", "source": "github", "line_count": 43, "max_line_length": 88, "avg_line_length": 20.6046511627907, "alnum_prop": 0.6839729119638827, "repo_name": "TGAC/grassroots-api", "id": "619719e53ba383ba913ba627cf2726eee3433709", "size": "1497", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "server/src/services/compress/include/crc.h", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "C", "bytes": "2036429" }, { "name": "C++", "bytes": "542132" }, { "name": "CSS", "bytes": "441675" }, { "name": "HTML", "bytes": "93210" }, { "name": "JavaScript", "bytes": "3086648" }, { "name": "Makefile", "bytes": "833142" }, { "name": "QMake", "bytes": "7283" }, { "name": "Shell", "bytes": "693" }, { "name": "XSLT", "bytes": "34917" } ], "symlink_target": "" }
@interface FZEasyFileTests : XCTestCase @end static NSString *file = @"Documents/a/b.txt"; static NSString *folder = @"Documents/aFolder"; @implementation FZEasyFileTests - (void)setUp { [super setUp]; // Put setup code here. This method is called before the invocation of each test method in the class. } - (void)tearDown { // Put teardown code here. This method is called after the invocation of each test method in the class. [super tearDown]; } - (void)testExample { //////////using short file name NSString *fullName = [FZEasyFile fullFileName:file]; NSLog(@"fullName of %@ is:%@", file, fullName); NSAssert(fullName && fullName.length > file.length, @"convert full file name failed!"); [FZEasyFile createFile:file overwrite:YES]; NSAssert([FZEasyFile isFileExists:file], @"create file failed!"); [FZEasyFile writeFile:file contents:[@"a" dataUsingEncoding:NSUTF8StringEncoding] append:NO]; NSString *contents = [NSString stringWithContentsOfFile:fullName encoding:NSUTF8StringEncoding error:nil]; NSAssert([@"a" isEqualToString:contents], @"write file failed"); [FZEasyFile writeFile:file contents:[@"b" dataUsingEncoding:NSUTF8StringEncoding] append:YES]; contents = [NSString stringWithContentsOfFile:fullName encoding:NSUTF8StringEncoding error:nil]; NSAssert([@"ab" isEqualToString:contents], @"append file failed"); [FZEasyFile removeFile:file]; NSAssert(![FZEasyFile isFileExists:file], @"remove file failed!"); [FZEasyFile removeFile:@""]; NSAssert([FZEasyFile isFileExists:@""], @"Home directory is removed, It's dangerous!"); [FZEasyFile createFolder:folder]; NSAssert([FZEasyFile isFolderExists:folder], @"create folder failed!"); [FZEasyFile removeFile:folder]; NSAssert(![FZEasyFile isFolderExists:folder], @"remove folder failed!"); ////////////using file url NSURL *fileUrl = [NSURL fileURLWithPath:fullName]; [FZEasyFile createFileWithFileUrl:fileUrl overwrite:YES]; NSAssert([FZEasyFile isFileExists:file], @"create file failed!"); [FZEasyFile writeFileWithFileUrl:fileUrl contents:[@"a" dataUsingEncoding:NSUTF8StringEncoding] append:NO]; contents = [NSString stringWithContentsOfFile:fullName encoding:NSUTF8StringEncoding error:nil]; NSAssert([@"a" isEqualToString:contents], @"write file failed"); [FZEasyFile writeFileWithFileUrl:fileUrl contents:[@"b" dataUsingEncoding:NSUTF8StringEncoding] append:YES]; contents = [NSString stringWithContentsOfFile:fullName encoding:NSUTF8StringEncoding error:nil]; NSAssert([@"ab" isEqualToString:contents], @"append file failed"); [FZEasyFile removeFileWithFileUrl:fileUrl]; NSAssert(![FZEasyFile isFileUrlExists:fileUrl], @"remove file failed!"); NSURL *folderUrl = [NSURL fileURLWithPath:folder isDirectory:YES]; [FZEasyFile createFolderWithFileUrl:folderUrl]; NSAssert([FZEasyFile isFolderUrlExists:folderUrl], @"create folder failed!"); [FZEasyFile removeFileWithFileUrl:folderUrl]; NSAssert(![FZEasyFile isFolderUrlExists:folderUrl], @"remove folder failed!"); } @end
{ "content_hash": "275c202819c3a0df840cabe3f887a7c6", "timestamp": "", "source": "github", "line_count": 78, "max_line_length": 112, "avg_line_length": 40.743589743589745, "alnum_prop": 0.723725613593455, "repo_name": "jiecao-fm/FZEasyFile", "id": "b2cef0198ec06f8561634437a679233707c36bee", "size": "3376", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "FZEasyFile/FZEasyFileTests/FZEasyFileTests.m", "mode": "33188", "license": "mit", "language": [ { "name": "Objective-C", "bytes": "10936" }, { "name": "Ruby", "bytes": "983" } ], "symlink_target": "" }
Rez manages packages. You request a list of packages from rez, and it resolves this request, if possible. If the resolution is not possible, the system supplies you with the relevant information to determine why this is so. You typically want to resolve a list of packages because you want to create an environment in which you can use them in combination, without conflicts occurring. A conflict occurs when there is a request for two or more different versions of the same package - a version clash. Rez lets you describe the environment you want in a natural way. For example, you can say: “I want an environment with...” * “...the latest version of houdini” * “...maya-2009.1” * “...the latest rv and the latest maya and houdini-11.something” * “...rv-3.something or greater” * “...the latest houdini which works with boost-1.37.0” * “...PyQt-2.2 or greater, but less than PyQt-4.5.3” In many examples in this documentation we will use the [rez-env](Command-Line-Tools#rez-env) command line tool. This tool takes a list of package requests and creates the resulting configured environment. It places you in a subshell - simply exit the shell to return to a non-configured environment. ## Versions Rez version numbers are alphanumeric - they support any combination of numbers, letters and underscores. A version number is a set of *tokens*, separated by either dot or dash. For example, here is a list of valid package version numbers: * 1 * 1.0.0 * 3.2.build_13 * 4.rc1 * 10a-5 Version number tokens follow a strict ordering schema and are case sensitive. Underscore is the smallest character, followed by letters (a-z and A-Z), followed by numbers. The ordering rules are like so: * Underscore before everything else; * Letters alphabetical, and before numbers; * Lowercase letters before uppercase; * Zero-padded numbers before equivalent non-padded (or less padded) number ('01' is < '1'); * If a token contains a combination of numbers and letters, it is internally split into groups containing only numbers or only letters, and the resulting list is compared using the same rules as above. The following table shows some example version token comparisons: smaller token | larger token --------------|------------- 0 | 1 a | b a | A a | 3 _5 | 2 ham | hamster alpha | beta alpha | bob 02 | 2 002 | 02 13 | 043 3 | 3a beta3 | 3beta Versions are compared by their token lists. The token delimiter (usually dot, but can also be dash) is ignored for comparison purposes - thus the versions '1.0.0' and '1-0.0' are equivalent. If two versions share the same token list prefix, the longer version is greater - thus '1.0.0' is a higher version than '1.0'. Note that no special importance is given to specific characters or letters in Rez version numbers - the terms 'alpha' and 'beta' for example have no special meaning. Similarly, the number of tokens in a version number doesn't matter, you can have as many as you like. While you are encouraged to use semantic versioning (see <a href="http://semver.org/">here</a>), it is not enforced. ## Packages A *package* is a versioned piece of software, that may have dependencies on other packages. Packages are self-contained - they have a single package definition file (typically *package.py*), which describes everything we need to know about the package in order to use it. Rez manages any kind of package, whether it be a python package, compiled package, or simply build code or configuration data. Here is an example package definition file (see [here](Package-Definition-Guide) for further details of each attribute): name = "foo" version = "1.0.0" description = "Something that does foo-like things." requires = [ "python-2.6", "utils-1.1+<2" ] tools = [ "fooify" ] def commands(): env.PYTHONPATH.append("{root}/python") env.PATH.append("{root}/bin") The *requires* section defines the requirements of the package. The *commands* section describes what happens when this package is added to an environment. Here, the *bin* directory in the package installation is appended to *PATH*, and similarly the *python* subdirectory is appended to *PYTHONPATH*. ## Package Repositories Packages are installed into package repositories. A package repository is a directory on disk, with packages and their versions laid out in a known structure underneath. Going on with our (foo, bah, eek) example, here is how the package repository might look: /packages/inhouse/foo/1.1 /1.2 /1.3 /packages/inhouse/bah/2 /3 /4 /packages/inhouse/eek/2.5 /2.6 /2.7 # more detailed example of foo-1.1 /packages/inhouse/foo/1.1/package.py /python/<PYTHON FILES> /bin/<EXECUTABLES> Here we have a package repository under the directory */packages/inhouse*. The actual package content (files, executables etc) is installed into each leaf-node version directory, as shown for *foo-1.1*. The package definition file, in this case *package.py*, is always stored at the root of the package - right under the version directory for that package. Rez only requires that the package's *package.py* file is at the root of the package installation. The layout of the rest of the package - for example, the *python* and *bin* directories - is completely up to the package's own build to determine. You should expect to see a package's *commands* section match up with its installation though. For example, notice how the path for foo's python files and binaries match what its package commands specified from earlier - "{root}/python" and "{root}/bin" will expand to these paths respectively. ## Package Search Path Rez finds packages using a search path in much the same way that python finds python modules using PYTHONPATH. You can find out what the search path is, using the rez command line tool rez-config (which you can also use to find any other rez setting): ]$ rez-config packages_path - /home/ajohns/packages - /packages/inhouse - /packages/vendor If the same package appears in two or more repositories on the search path, the earlier package is used in preference. This happens at the version level - an earlier package "foo-1.0.0" will hide a later package "foo-1.0.0", but not "foo-1.2.0". The example search path shown is a typical setting. There are some central repositories later in the search path, where packages are released to so everyone can use them. But there is also a local package path at the front of the search path. This is where packages go that are being locally developed by a user. Having this at the start of the searchpath allows developers to resolve environments that pull in test packages in preference to released ones, so they can test a package before releasing it for general use. You can change the packages search path in several ways. A common way is to set the REZ_PACKAGES_PATH environment variable; see [Configuring Rez](Configuring-Rez) for more configuration options. ## Package Commands The *commands* section of the package definition determines how the environment is configured in order to use it. It is a python function, but note that if any imports are used, they must appear within the body of this function. Consider this commands example: def commands(): env.PYTHONPATH.append("{root}/python") env.PATH.append("{root}/bin") This is a typical example, where a package adds its source path to *PYTHONPATH*, and its tools to *PATH*. See [here](Package-Commands) for details on what can be done within the *commands* section, as well as details on what order package commands are executed in. ## Package Requests A *package request* is a string with a special syntax which matches a number of possible package versions. You use package requests in the requires section of a package definition file, and also when creating your own configured environment directly using tools such as *rez-env*. For example, here is a request (using the *rez-env* tool) to create an environment containing *python* version 2.6 or greater, and *my_py_utils* version 5.4 or greater, but less than 6: ]$ rez-env 'python-2.6+' 'my_py_utils-5.4+<6' Here are some example package requests: package request | description | example versions within request ----------------|-------------------------------------|-------------------------------- foo | Any version of foo. | foo-1, foo-0.4, foo-5.0, foo-2.0.alpha foo-1 | Any version of foo-1[.x.x...x]. | foo-1, foo-1.0, foo-1.2.3 foo-1+ | foo-1 or greater. | foo-1, foo-1.0, foo-1.2.3, foo-7.0.0 foo-1.2+<2 | foo-1.2 or greater, but less than 2 | foo-1.2.0, foo-1.6.4, foo-1.99 foo<2 | Any version of foo less than 2 | foo-1, foo-1.0.4 foo==2.0.0 | Only version 2.0.0 exactly | foo-2.0.0 foo-1.3\|5+ | OR'd requests | foo-1.3.0, foo-6.0.0 ### The Conflict Operator The '!' operator is called the *conflict* operator, and is used to define an incompatibility between packages, or to specify that you do *not* want a package version present. For example, consider the command: ]$ rez-env maya_utils '!maya-2015.6' This specifies that you require any version of *maya_utils*, but that any version of *maya* within 2015.6 (and this includes 2015.6.1 and so on) is not acceptable. ### Weak References The '~' operator is called the *weak reference* operator. It forces a package version to be within the specified range if present, but does not actually require the package. For example, consider the command: ]$ rez-env foo '~nuke-9.rc2' This request may or may not pull in the *nuke* package, depending on the requirements of *foo*; however, if nuke *is* present, it must be within the version 9.rc2. Weak references are useful in certain cases. For example, applications such as *nuke* and *maya* sometimes ship with their own version of *python*. Their rez packages don't have a requirement on *python* (they have their own embedded version already). However often other python libraries are used both inside and outside of these applications, and those packages *do* have a python requirement. So, to make sure that they're using a compatible python version when used within the app, the app may define a *weak package reference* to their relevant python version, like so: # in maya's package.py requires = [ "~python-2.7.3" ] This example ensures that any package that uses python, will use the version compatible with maya when maya is present in the environment. ## Implicit Packages The *implicit packages* are a list of package requests that are automatically added to every rez request (for example, when you use *rez-env*). They are set by the configuration setting *implicit_packages*. The default setting looks like so: implicit_packages = [ "~platform=={system.platform}", "~arch=={system.arch}", "~os=={system.os}", ] Rez models the current system - the platform, architecture and operating systems - as packages themselves. The default implicits are a set of *weak requirements* on each of *platform*, *arch* and *os*. This ensures that if any platform-dependent package is requested, the platform, architecture and/or operating system it depends on, matches the current system. The list of implicits that were used in a request are printed by *rez-env* when you enter the newly configured subshell, and are also printed by the *rez-context* tool. ## Dependency Resolving Rez contains a solving algorithm that takes a *request* - a list of package requests - and produces a *resolve* - a final list of packages that satisfy the request. The algorithm avoids version conflicts - two or more different versions of the same package at once. When you submit a request to rez, it finds a solution for that request that aims to give you the latest possible version of each package. If this is not possible, it will give you the next latest version, and so on. Consider the following example (the arrows indicate dependencies): <p align="center"> <a href="media/rez_deps_simple_eg.png"> <img src="media/rez_deps_simple_eg.png"> </a></p> Here we have three packages - 'foo', 'bah' and 'eek', where both foo and bah have dependencies on eek. For example, package "bah-4" might have a package definition file that looks something like this (some entries skipped for succinctness): name = "bah" version = "4" requires = [ "eek-2.6" ] A request for "foo-1.3" is going to result in the resolve ("foo-1.3", "eek-2.7"). A request for "foo" will give the same result - we are asking for "any version of foo", but rez will prefer the latest. However, if we request ("foo", "bah"), we are not going to get the latest of both - they depend on different versions of eek, and that would cause a version conflict. Instead, our resolve is going to be ("foo-1.2", "bah-4", "eek-2.6"). Rez has given you the latest possible versions of packages, that do not cause a conflict. Sometimes your request is impossible to fulfill. For example, the request ("foo-1.3", "bah-4") is not possible. In this case, the resolve will fail, and rez will inform you of the conflict. ## Resolving An Environment A user can create a resolved environment using the command line tool *rez-env* (also via the API - practically everything in rez can be done in python). When you create the environment, the current environment is not changed - you are placed into a sub-shell instead. Here is an example of using rez-env, assuming that the package repository is from our earlier (foo, bah, eek) example: ]$ rez-env foo bah You are now in a rez-configured environment. resolved by ajohns@14jun01.methodstudios.com, on Wed Oct 22 12:44:00 2014, using Rez v2.0.rc1.10 requested packages: foo bah resolved packages: eek-2.6 /packages/inhouse/eek/2.6 foo-1.2 /packages/inhouse/foo/1.2 bah-4 /packages/inhouse/bah/4 > ]$ █ The output of rez-env shows the original request, along with the matching resolve. It's the resolve that tells you what actual package versions are present in the newly resolved environment. Notice the '**>**' character in the prompt - this is a visual cue telling you that you have been placed into a rez-resolved environment. ### Putting It All Together Let's go through what happens when an environment is resolved, using a new (and slightly more realistic) example. Let us assume that the following packages are available: * maya-2014.sp2; * nuke-8.0v3; * 3 versions of a maya plugin "mplugin"; * 2 versions of a nuke plugin "nplugin"; * 3 versions of a common base library "lib". The following diagram shows what happens when the command *"rez-env mplugin-1.3.0"* is run: <p align="center"> <a href="media/rez_env.png"> <img src="media/rez_env.png"> </a></p> The digram shows the following operations occurring: * Rez takes the user's request, and runs it through the dependency solver. The solver reads packages from the package repositories in order to complete the solve; * This results in a list of resolved packages. These are the packages that are used in the configured environment; * The commands from each package are concatenated together; * This master list of commands is then translated into the target shell language (in this example that is *bash*); * A sub-shell is created and the translated command code is sourced within this environment, creating the final configured environment. The order of package command execution depends on package dependencies, and the order that packages were requested in. See [here](Package-Commands#order-of-command-execution) for more details.
{ "content_hash": "9978f52a066abbf2c36f5574da9169ce", "timestamp": "", "source": "github", "line_count": 367, "max_line_length": 102, "avg_line_length": 43.94822888283379, "alnum_prop": 0.7187054374108748, "repo_name": "instinct-vfx/rez", "id": "1168a7dbcb588fdac43b427f23cae695c3228cf8", "size": "16172", "binary": false, "copies": "4", "ref": "refs/heads/master", "path": "wiki/pages/Basic-Concepts.md", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Batchfile", "bytes": "13" }, { "name": "CMake", "bytes": "61812" }, { "name": "Dockerfile", "bytes": "3668" }, { "name": "PowerShell", "bytes": "1390" }, { "name": "Python", "bytes": "1950470" }, { "name": "Shell", "bytes": "3185" } ], "symlink_target": "" }
using bv.common.Core; using bv.model.BLToolkit; using eidss.model.Reports.Common; using EIDSS.Reports.Factory; namespace EIDSS.Reports.BaseControls.Report { public partial class BaseIntervalReport : BaseReport { public BaseIntervalReport() { InitializeComponent(); } public virtual void SetParameters(BaseIntervalModel model, DbManagerProxy manager, DbManagerProxy archiveManager) { Utils.CheckNotNullOrEmpty(model.Language, "model.Language"); ReportRebinder rebinder = this.GetDateRebinder(model.Language); cellInputStartDate.Text = rebinder.ToDateString(model.StartDate); cellInputEndDate.Text = rebinder.ToDateString(model.EndDate); tableInterval.Left = lblReportName.Left; tableInterval.Width = lblReportName.Width; SetLanguage(model, manager); ShowWarningIfDataInArchive(manager, model.StartDate, model.UseArchive); ReportRtlHelper.SetRTL(this); } } }
{ "content_hash": "850f2fadf1ad32f8423bd3d63a01c9d1", "timestamp": "", "source": "github", "line_count": 33, "max_line_length": 121, "avg_line_length": 32.57575757575758, "alnum_prop": 0.6613953488372093, "repo_name": "EIDSS/EIDSS-Legacy", "id": "8d2014ec0dcb7f468f2c2b70b68f935c0ff2f46c", "size": "1075", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "EIDSS v6.1/vb/EIDSS/EIDSS.Reports/BaseControls/Report/BaseIntervalReport.cs", "mode": "33188", "license": "bsd-2-clause", "language": [ { "name": "ASP", "bytes": "256377" }, { "name": "Batchfile", "bytes": "30009" }, { "name": "C#", "bytes": "106160789" }, { "name": "CSS", "bytes": "833586" }, { "name": "HTML", "bytes": "7507" }, { "name": "Java", "bytes": "2188690" }, { "name": "JavaScript", "bytes": "17000221" }, { "name": "PLSQL", "bytes": "2499" }, { "name": "PLpgSQL", "bytes": "6422" }, { "name": "Pascal", "bytes": "159898" }, { "name": "PowerShell", "bytes": "339522" }, { "name": "Puppet", "bytes": "3758" }, { "name": "SQLPL", "bytes": "12198" }, { "name": "Smalltalk", "bytes": "301266" }, { "name": "Visual Basic", "bytes": "20819564" }, { "name": "XSLT", "bytes": "4253600" } ], "symlink_target": "" }
#include <modules/opengl/openglutils.h> #include <algorithm> namespace inviwo { namespace utilgl { std::array<GLint, 4> convertSwizzleMaskToGL(const SwizzleMask& mask) { auto convertToGL = [](ImageChannel channel) { switch (channel) { case ImageChannel::Red: return GL_RED; case ImageChannel::Green: return GL_GREEN; case ImageChannel::Blue: return GL_BLUE; case ImageChannel::Alpha: return GL_ALPHA; case ImageChannel::Zero: return GL_ZERO; case ImageChannel::One: return GL_ONE; default: return GL_ZERO; } }; std::array<GLint, 4> swizzleMaskGL; std::transform(mask.begin(), mask.end(), swizzleMaskGL.begin(), convertToGL); return swizzleMaskGL; } SwizzleMask convertSwizzleMaskFromGL(const std::array<GLint, 4>& maskGL) { auto convertFromGL = [](GLint channel) { switch (channel) { case GL_RED: return ImageChannel::Red; case GL_GREEN: return ImageChannel::Green; case GL_BLUE: return ImageChannel::Blue; case GL_ALPHA: return ImageChannel::Alpha; case GL_ZERO: return ImageChannel::Zero; case GL_ONE: return ImageChannel::One; default: return ImageChannel::Zero; } }; SwizzleMask mask; std::transform(maskGL.begin(), maskGL.end(), mask.begin(), convertFromGL); return mask; } PolygonModeState& PolygonModeState::operator=(PolygonModeState&& that) { if (this != &that) { mode_ = that.mode_; lineWidth_ = that.lineWidth_; pointSize_ = that.pointSize_; oldMode_ = that.oldMode_; oldLineWidth_ = that.oldLineWidth_; oldPointSize_ = that.oldPointSize_; that.mode_ = GL_NONE; } return *this; } PolygonModeState::PolygonModeState(PolygonModeState&& rhs) : mode_(rhs.mode_) , lineWidth_(rhs.lineWidth_) , pointSize_(rhs.pointSize_) , oldMode_(rhs.oldMode_) , oldLineWidth_(rhs.oldLineWidth_) , oldPointSize_(rhs.oldPointSize_) { rhs.mode_ = GL_NONE; } PolygonModeState::PolygonModeState(GLenum mode, GLfloat lineWidth, GLfloat pointSize) : mode_(mode) , lineWidth_(lineWidth) , pointSize_(pointSize) , oldMode_(0) , oldLineWidth_(0.0f) , oldPointSize_(0.0f) { // Only GL_FRONT_AND_BACK in core profile. glGetIntegerv(GL_POLYGON_MODE, &oldMode_); if (static_cast<int>(mode) != oldMode_) glPolygonMode(GL_FRONT_AND_BACK, mode); switch (mode_) { case GL_POINT: { glGetFloatv(GL_POINT_SIZE, &oldPointSize_); if (pointSize_ != oldPointSize_) { glPointSize(pointSize_); } break; } case GL_LINE: { glGetFloatv(GL_LINE_WIDTH, &oldLineWidth_); if (lineWidth_ != oldLineWidth_) { glLineWidth(lineWidth_); } break; } case GL_FILL: default: break; } } PolygonModeState::~PolygonModeState() { if (mode_ != GL_NONE) { switch (mode_) { case GL_POINT: { if (pointSize_ != oldPointSize_) { glPointSize(oldPointSize_); } break; } case GL_LINE: { if (lineWidth_ != oldLineWidth_) { glLineWidth(oldLineWidth_); } break; } case GL_FILL: default: break; } if (mode_ != oldMode_) glPolygonMode(GL_FRONT_AND_BACK, oldMode_); } } CullFaceState& CullFaceState::operator=(CullFaceState&& that) { if (this != &that) { GlBoolState::operator=(std::move(that)); mode_ = that.mode_; oldMode_ = that.oldMode_; that.mode_ = that.oldMode_; } return *this; } CullFaceState::CullFaceState(CullFaceState&& rhs) : GlBoolState(std::move(rhs)), mode_(rhs.mode_), oldMode_(rhs.oldMode_) { rhs.mode_ = rhs.oldMode_; } CullFaceState::CullFaceState(GLint mode) : GlBoolState(GL_CULL_FACE, mode != GL_NONE), mode_(mode) { if (state_) { glGetIntegerv(GL_CULL_FACE_MODE, &oldMode_); if (oldMode_ != mode) { glCullFace(mode); } } } CullFaceState::~CullFaceState() { if (state_ && oldMode_ != mode_) { glCullFace(oldMode_); } } GLint CullFaceState::getMode() { return mode_; } GlBoolState& GlBoolState::operator=(GlBoolState&& that) { if (this != &that) { target_ = 0; std::swap(target_, that.target_); state_ = that.oldState_; std::swap(state_, that.state_); oldState_ = that.oldState_; } return *this; } GlBoolState::GlBoolState(GlBoolState&& rhs) : target_(rhs.target_), oldState_(rhs.oldState_), state_(rhs.state_) { rhs.state_ = rhs.oldState_; } GlBoolState::GlBoolState(GLenum target, bool state) : target_(target), oldState_{}, state_(state) { oldState_ = (glIsEnabled(target_) == GL_TRUE); if (oldState_ != state_) { if (state) glEnable(target_); else glDisable(target_); } } GlBoolState::operator bool() { return state_; } GlBoolState::~GlBoolState() { if (oldState_ != state_) { if (oldState_) glEnable(target_); else glDisable(target_); } } TexParameter& TexParameter::operator=(TexParameter&& that) { if (this != &that) { unit_ = 0; std::swap(unit_, that.unit_); target_ = 0; std::swap(target_, that.target_); name_ = that.name_; oldValue_ = that.oldValue_; } return *this; } TexParameter::TexParameter(TexParameter&& rhs) : unit_(rhs.unit_), target_(rhs.target_), name_(rhs.name_), oldValue_(rhs.oldValue_) { rhs.target_ = 0; } TexParameter::TexParameter(const TextureUnit& unit, GLenum target, GLenum name, GLint value) : unit_(unit.getEnum()), target_(target), name_(name), oldValue_{} { glActiveTexture(unit_); glGetTexParameteriv(target_, name_, &oldValue_); glTexParameteri(target_, name_, value); TextureUnit::setZeroUnit(); } TexParameter::~TexParameter() { if (unit_ != 0 && target_ != 0) { glActiveTexture(unit_); glTexParameteri(target_, name_, oldValue_); TextureUnit::setZeroUnit(); } } TexEnv& TexEnv::operator=(TexEnv&& that) { if (this != &that) { unit_ = 0; std::swap(unit_, that.unit_); target_ = 0; std::swap(target_, that.target_); name_ = that.name_; oldValue_ = that.oldValue_; } return *this; } TexEnv::TexEnv(TexEnv&& rhs) : unit_(rhs.unit_), target_(rhs.target_), name_(rhs.name_), oldValue_(rhs.oldValue_) { rhs.target_ = 0; } TexEnv::TexEnv(const TextureUnit& unit, GLenum target, GLenum name, GLint value) : unit_(unit.getEnum()), target_(target), name_(name), oldValue_{} { glGetTexEnviv(target_, name_, &oldValue_); glTexEnvi(target_, name_, value); TextureUnit::setZeroUnit(); } TexEnv::~TexEnv() { if (unit_ != 0 && target_ != 0) { glActiveTexture(unit_); glTexEnvi(target_, name_, oldValue_); TextureUnit::setZeroUnit(); } } BlendModeState::BlendModeState(GLenum smode, GLenum dmode) : GlBoolState(GL_BLEND, smode != GL_NONE), smode_(smode), dmode_(dmode) { if (state_) { glGetIntegerv(GL_BLEND_SRC, &oldsMode_); glGetIntegerv(GL_BLEND_DST, &olddMode_); if (oldsMode_ != smode_ || olddMode_ != dmode_) { glBlendFunc(smode_, dmode_); } } } BlendModeState& BlendModeState::operator=(BlendModeState&& that) { if (this != &that) { GlBoolState::operator=(std::move(that)); smode_ = that.smode_; oldsMode_ = that.oldsMode_; that.smode_ = that.oldsMode_; dmode_ = that.dmode_; olddMode_ = that.olddMode_; that.dmode_ = that.olddMode_; } return *this; } BlendModeState::BlendModeState(BlendModeState&& rhs) : GlBoolState(std::move(rhs)) , smode_(rhs.smode_) , dmode_(rhs.dmode_) , oldsMode_(rhs.oldsMode_) , olddMode_(rhs.olddMode_) { rhs.smode_ = rhs.oldsMode_; rhs.dmode_ = rhs.olddMode_; } BlendModeState::~BlendModeState() { if (state_ && (oldsMode_ != smode_ || olddMode_ != dmode_)) { glBlendFunc(oldsMode_, olddMode_); } } BlendModeEquationState::BlendModeEquationState(GLenum smode, GLenum dmode, GLenum eqn) : BlendModeState(smode, dmode), eqn_(eqn) { if (state_) { glGetIntegerv(GL_BLEND_EQUATION_RGB, &oldEqn_); if (oldEqn_ != eqn_) { glBlendEquation(eqn_); } } } BlendModeEquationState& BlendModeEquationState::operator=(BlendModeEquationState&& that) { if (this != &that) { BlendModeState::operator=(std::move(that)); eqn_ = that.eqn_; oldEqn_ = that.oldEqn_; that.eqn_ = that.oldEqn_; } return *this; } BlendModeEquationState::BlendModeEquationState(BlendModeEquationState&& rhs) : BlendModeState(std::move(rhs)), eqn_(rhs.eqn_), oldEqn_(rhs.oldEqn_) { rhs.eqn_ = rhs.oldEqn_; } BlendModeEquationState::~BlendModeEquationState() { if (state_ && (oldEqn_ != eqn_)) { glBlendEquation(oldEqn_); } } ClearColor::ClearColor(vec4 color) : color_(color) { glGetFloatv(GL_COLOR_CLEAR_VALUE, glm::value_ptr(oldColor_)); if (oldColor_ != color_) { glClearColor(color_.x, color_.y, color_.z, color_.w); } } ClearColor::ClearColor(ClearColor&& rhs) : color_(rhs.color_), oldColor_(rhs.oldColor_) { rhs.color_ = rhs.oldColor_; } ClearColor& ClearColor::operator=(ClearColor&& that) { if (this != &that) { color_ = that.color_; oldColor_ = that.oldColor_; that.color_ = that.oldColor_; } return *this; } ClearColor::~ClearColor() { if (oldColor_ != color_) { glClearColor(oldColor_.x, oldColor_.y, oldColor_.z, oldColor_.w); } } ClearDepth::ClearDepth(float depth) : depth_(depth) { glGetFloatv(GL_DEPTH_CLEAR_VALUE, &oldDepth_); if (oldDepth_ != depth_) { glClearDepth(depth_); } } ClearDepth::ClearDepth(ClearDepth&& rhs) : depth_(rhs.depth_), oldDepth_(rhs.oldDepth_) { rhs.depth_ = rhs.oldDepth_; } ClearDepth& ClearDepth::operator=(ClearDepth&& that) { if (this != &that) { depth_ = that.depth_; oldDepth_ = that.oldDepth_; that.depth_ = that.oldDepth_; } return *this; } ClearDepth::~ClearDepth() { if (oldDepth_ != depth_) { glClearDepth(oldDepth_); } } ViewportState& ViewportState::operator=(ViewportState&& that) { if (this != &that) { coords_ = {0, 0, 0, 0}; std::swap(coords_, that.coords_); oldCoords_ = {0, 0, 0, 0}; std::swap(oldCoords_, that.oldCoords_); } return *this; } ViewportState::ViewportState(ViewportState&& rhs) : coords_(rhs.coords_), oldCoords_(rhs.oldCoords_) {} ViewportState::ViewportState(GLint x, GLint y, GLsizei width, GLsizei height) : coords_{x, y, width, height}, oldCoords_{} { oldCoords_.get(); coords_.set(); } ViewportState::ViewportState(const ivec4& coords) : coords_{coords.x, coords.y, coords.z, coords.w}, oldCoords_{} { oldCoords_.get(); coords_.set(); } ViewportState::~ViewportState() { if (coords_ != oldCoords_) { oldCoords_.set(); } } void Viewport::get() { glGetIntegerv(GL_VIEWPORT, view_.data()); } void Viewport::set() { glViewport(x(), y(), width(), height()); } ScissorState& ScissorState::operator=(ScissorState&& that) { if (this != &that) { box_ = {0, 0, 0, 0}; std::swap(box_, that.box_); oldBox_ = {0, 0, 0, 0}; std::swap(oldBox_, that.oldBox_); } return *this; } ScissorState::ScissorState(ScissorState&& rhs) : box_(rhs.box_), oldBox_(rhs.oldBox_) {} ScissorState::ScissorState(GLint x, GLint y, GLsizei width, GLsizei height) : box_{x, y, width, height}, oldBox_{} { oldBox_.get(); box_.set(); } ScissorState::ScissorState(const ivec4& coords) : box_{coords.x, coords.y, coords.z, coords.w}, oldBox_{} { oldBox_.get(); box_.set(); } ScissorState::~ScissorState() { if (box_ != oldBox_) { oldBox_.set(); } } void ScissorBox::get() { glGetIntegerv(GL_SCISSOR_BOX, box_.data()); } void ScissorBox::set() { glScissor(x(), y(), width(), height()); } ColorMaskState& ColorMaskState::operator=(ColorMaskState&& that) { if (this != &that) { mask_ = {GL_TRUE, GL_TRUE, GL_TRUE, GL_TRUE}; std::swap(mask_, that.mask_); oldMask_ = {GL_TRUE, GL_TRUE, GL_TRUE, GL_TRUE}; std::swap(oldMask_, that.oldMask_); } return *this; } ColorMaskState::ColorMaskState(ColorMaskState&& rhs) : mask_(rhs.mask_), oldMask_(rhs.oldMask_) {} ColorMaskState::ColorMaskState(GLboolean red, GLboolean green, GLboolean blue, GLboolean alpha) : mask_{red, green, blue, alpha}, oldMask_{} { oldMask_.get(); mask_.set(); } ColorMaskState::ColorMaskState(const bvec4& mask) : mask_{mask.x, mask.y, mask.z, mask.w}, oldMask_{} { oldMask_.get(); mask_.set(); } ColorMaskState::~ColorMaskState() { if (mask_ != oldMask_) { oldMask_.set(); } } void ColorMask::get() { glGetBooleanv(GL_COLOR_WRITEMASK, mask_.data()); } void ColorMask::set() { glColorMask(red(), green(), blue(), alpha()); } ColorMaskiState& ColorMaskiState::operator=(ColorMaskiState&& that) { if (this != &that) { buf_ = that.buf_; mask_ = {GL_TRUE, GL_TRUE, GL_TRUE, GL_TRUE}; std::swap(mask_, that.mask_); oldMask_ = {GL_TRUE, GL_TRUE, GL_TRUE, GL_TRUE}; std::swap(oldMask_, that.oldMask_); } return *this; } ColorMaskiState::ColorMaskiState(ColorMaskiState&& rhs) : buf_(rhs.buf_), mask_(rhs.mask_), oldMask_(rhs.oldMask_) {} ColorMaskiState::ColorMaskiState(GLuint buf, GLboolean red, GLboolean green, GLboolean blue, GLboolean alpha) : buf_{buf}, mask_{red, green, blue, alpha}, oldMask_{} { oldMask_.get(); mask_.set(); } ColorMaskiState::ColorMaskiState(GLuint buf, const bvec4& mask) : buf_{buf}, mask_{mask.x, mask.y, mask.z, mask.w}, oldMask_{} { oldMask_.get(); mask_.set(); } ColorMaskiState::~ColorMaskiState() { if (mask_ != oldMask_) { oldMask_.set(); } } void ColorMaski::get() { // save the state of all draw buffers GLint maxDrawBuffers = 8; glGetIntegerv(GL_MAX_DRAW_BUFFERS, &maxDrawBuffers); std::vector<GLenum> drawBuffers(static_cast<size_t>(maxDrawBuffers), GL_NONE); for (int i = 0; i < maxDrawBuffers; ++i) { GLint value; glGetIntegerv(GL_DRAW_BUFFER0 + i, &value); drawBuffers[i] = static_cast<GLenum>(value); } glDrawBuffer(buf_); glGetBooleanv(GL_COLOR_WRITEMASK, mask_.data()); // restore draw buffers glDrawBuffers(maxDrawBuffers, drawBuffers.data()); } void ColorMaski::set() { glColorMaski(buf_, red(), green(), blue(), alpha()); } IVW_MODULE_OPENGL_API GLfloat validateLineWidth(GLfloat width) { float s_sizes[2]; glGetFloatv(GL_SMOOTH_LINE_WIDTH_RANGE, s_sizes); width = std::max(width, s_sizes[0]); width = std::min(width, s_sizes[1]); return width; } } // namespace utilgl } // namespace inviwo
{ "content_hash": "6f00f839d9f51e4fd8124099a7b721d8", "timestamp": "", "source": "github", "line_count": 562, "max_line_length": 100, "avg_line_length": 27.848754448398576, "alnum_prop": 0.5822631141780078, "repo_name": "Sparkier/inviwo", "id": "f3e37233349dccf09d2ac84d6693ce4c4c1be000", "size": "17234", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "modules/opengl/src/openglutils.cpp", "mode": "33188", "license": "bsd-2-clause", "language": [ { "name": "C", "bytes": "146426" }, { "name": "C++", "bytes": "11871087" }, { "name": "CMake", "bytes": "574616" }, { "name": "CSS", "bytes": "18058" }, { "name": "GLSL", "bytes": "504032" }, { "name": "Groovy", "bytes": "11430" }, { "name": "HTML", "bytes": "79818" }, { "name": "JavaScript", "bytes": "173791" }, { "name": "Mathematica", "bytes": "109319" }, { "name": "Python", "bytes": "1817954" }, { "name": "QMake", "bytes": "172" }, { "name": "TeX", "bytes": "5813" } ], "symlink_target": "" }
package in.twizmwaz.cardinal.module.modules.armorKeep; import in.twizmwaz.cardinal.event.CardinalSpawnEvent; import in.twizmwaz.cardinal.module.Module; import org.bukkit.Material; import org.bukkit.entity.Player; import org.bukkit.event.EventHandler; import org.bukkit.event.EventPriority; import org.bukkit.event.HandlerList; import org.bukkit.event.entity.PlayerDeathEvent; import org.bukkit.inventory.ItemStack; import org.bukkit.inventory.PlayerInventory; import java.util.HashMap; public class ArmorKeep implements Module { private final Material type; private final int damageValue; private HashMap<Player, ItemStack> helmet; private HashMap<Player, ItemStack> chestplate; private HashMap<Player, ItemStack> leggings; private HashMap<Player, ItemStack> boots; protected ArmorKeep(Material type, int damageValue) { this.type = type; this.damageValue = damageValue; this.helmet = new HashMap<>(); this.chestplate = new HashMap<>(); this.leggings = new HashMap<>(); this.boots = new HashMap<>(); } @Override public void unload() { HandlerList.unregisterAll(this); helmet.clear(); chestplate.clear(); leggings.clear(); boots.clear(); } @EventHandler public void onPlayerDeath(PlayerDeathEvent event) { Player player = event.getEntity(); PlayerInventory inventory = player.getInventory(); HashMap<Integer, ItemStack> itemsToKeep = new HashMap<>(); if (inventory.getHelmet() != null) { if (inventory.getHelmet().getType().equals(type) && inventory.getHelmet().getDurability() == damageValue) { helmet.put(player, inventory.getHelmet()); } } if (inventory.getChestplate() != null) { if (inventory.getChestplate().getType().equals(type) && inventory.getChestplate().getDurability() == damageValue) { chestplate.put(player, inventory.getChestplate()); } } if (inventory.getLeggings() != null) { if (inventory.getLeggings().getType().equals(type) && inventory.getLeggings().getDurability() == damageValue) { leggings.put(player, inventory.getLeggings()); } } if (inventory.getBoots() != null) { if (inventory.getBoots().getType().equals(type) && inventory.getBoots().getDurability() == damageValue) { boots.put(player, inventory.getBoots()); } } } @EventHandler(priority = EventPriority.HIGHEST) public void onPgmSpawn(CardinalSpawnEvent event) { Player player = event.getPlayer(); PlayerInventory inventory = player.getInventory(); if (helmet.containsKey(player)) { if (helmet.get(player) != null) { inventory.setHelmet(helmet.get(player)); } } if (chestplate.containsKey(player)) { if (chestplate.get(player) != null) { inventory.setChestplate(chestplate.get(player)); } } if (leggings.containsKey(player)) { if (leggings.get(player) != null) { inventory.setLeggings(leggings.get(player)); } } if (boots.containsKey(player)) { if (boots.get(player) != null) { inventory.setBoots(boots.get(player)); } } } }
{ "content_hash": "4017165bc777201bc8c5dafcb48c0c3a", "timestamp": "", "source": "github", "line_count": 98, "max_line_length": 127, "avg_line_length": 35.295918367346935, "alnum_prop": 0.6169413125180688, "repo_name": "TeamDDG/AvicusScrimmage", "id": "8b93f0bf499d80490e1e5ee451279379a1cc0149", "size": "3459", "binary": false, "copies": "8", "ref": "refs/heads/master", "path": "src/main/java/in/twizmwaz/cardinal/module/modules/armorKeep/ArmorKeep.java", "mode": "33188", "license": "mit", "language": [ { "name": "Java", "bytes": "983434" } ], "symlink_target": "" }
namespace Proto.Persistence.RavenDB { class Event { public Event(string actorName, long index, object data) { ActorName = actorName; Index = index; Data = data; Id = $"{actorName}-event-{index}"; } public string ActorName { get; } public long Index { get; } public object Data { get; } public string Id { get; } } }
{ "content_hash": "6291b88959bcbca7124fc81366cad311", "timestamp": "", "source": "github", "line_count": 18, "max_line_length": 63, "avg_line_length": 24.055555555555557, "alnum_prop": 0.5127020785219399, "repo_name": "AsynkronIT/protoactor-dotnet", "id": "44d5217b1b0564d3073f9cfe3380a0f342c7b78f", "size": "435", "binary": false, "copies": "1", "ref": "refs/heads/dev", "path": "src/Proto.Persistence.RavenDB/Event.cs", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Batchfile", "bytes": "282" }, { "name": "C#", "bytes": "626451" }, { "name": "Dockerfile", "bytes": "916" } ], "symlink_target": "" }
<?php namespace PSX\Framework\Config; use ArrayIterator; /** * Simple config class which uses a simple array to store all values. Here an * example howto use the class * <code> * $config = Config::fromFile('configuration.php'); * * echo $config['psx_url']; * </code> * * @author Christoph Kappestein <christoph.kappestein@gmail.com> * @license http://www.apache.org/licenses/LICENSE-2.0 * @link http://phpsx.org */ class Config extends ArrayIterator { public function __construct(array $config) { parent::__construct($config); } public function set(string $key, mixed $value): void { $this->offsetSet($key, $value); } public function get(string $key): mixed { return $this->offsetGet($key); } public function has(string $key): bool { return $this->offsetExists($key); } public function merge(Config $config): self { return new static(array_merge($this->getArrayCopy(), $config->getArrayCopy())); } public function offsetGet(mixed $key): mixed { return $this->offsetExists($key) ? parent::offsetGet($key) : null; } /** * @throws NotFoundException */ public static function fromFile(string $file): self { $config = include($file); if (is_array($config)) { return new static($config); } else { throw new NotFoundException('Config file must return an array'); } } }
{ "content_hash": "3670862181c433d96c4b95ccd4d47250", "timestamp": "", "source": "github", "line_count": 66, "max_line_length": 87, "avg_line_length": 22.59090909090909, "alnum_prop": 0.6056338028169014, "repo_name": "apioo/psx-framework", "id": "7ebf78c00106cdf2d35ed9abe63dccbd86587c09", "size": "2268", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/Config/Config.php", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "HTML", "bytes": "334" }, { "name": "PHP", "bytes": "715075" } ], "symlink_target": "" }
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>AMZNRegion Constants Reference</title> <link rel="stylesheet" href="../css/style.css"> <meta name="viewport" content="initial-scale=1, maximum-scale=1.4"> <meta name="generator" content="appledoc 2.2.1 (build 1333)"> </head> <body class="appledoc"> <header> <div class="container" class="hide-in-xcode"> <h1 id="library-title"> <a href="../index.html">LoginWithAmazon </a> </h1> <p id="developer-home"> <a href="../index.html">Amazon.com, Inc</a> </p> </div> </header> <aside> <div class="container"> <nav> <ul id="header-buttons" role="toolbar"> <li><a href="../index.html">Index</a></li> <li><a href="../hierarchy.html">Hierarchy</a></li> <li id="on-this-page" role="navigation"> <label> On This Page <div class="chevron"> <div class="chevy chevron-left"></div> <div class="chevy chevron-right"></div> </div> <select id="jump-to"> <option value="top">Jump To&#133;</option> </select> </label> </li> </ul> </nav> </div> </aside> <article> <div id="overview_contents" class="container"> <div id="content"> <main role="main"> <h1 class="title">AMZNRegion Constants Reference</h1> <div class="section section-specification"><table cellspacing="0"><tbody> <tr> <th>Declared in</th> <td>AMZNAuthorizationManager.h</td> </tr><tr> <th>Availability</th> <td>3.0</td> </tr> </tbody></table></div> <h3 class="subsubtitle method-title">AMZNRegion</h3> <div class="section section-overview"> <p>These constants will be used to identify what global end-points the SDK connects to. Set the <code>region</code> property to one of the following values</p> </div> <div class="section"> <!-- display enum values --> <h4 class="method-subtitle">Definition</h4> <code>typedef NS_ENUM(NSUInteger, AMZNRegion ) {<br> &nbsp;&nbsp; <a href="">AMZNRegionAuto</a> = 0,<br> &nbsp;&nbsp; <a href="">AMZNRegionNA</a> = 1,<br> &nbsp;&nbsp; <a href="">AMZNRegionEU</a> = 2,<br> &nbsp;&nbsp; <a href="">AMZNRegionFE</a> = 3,<br> };</code> </div> <div class="section section-methods"> <h4 class="method-subtitle">Constants</h4> <dl class="termdef"> <dt><a name="" title="AMZNRegionAuto"></a><code>AMZNRegionAuto</code></dt> <dd> <p>Setting region property to this value causes the SDK to determine the best end-points to connect to. This will be the default value in case you don&rsquo;t set region property explicitly</p> <p> Declared In <code class="declared-in-ref">AMZNAuthorizationManager.h</code>. </p> </dd> <dt><a name="" title="AMZNRegionNA"></a><code>AMZNRegionNA</code></dt> <dd> <p>Setting region property to this value causes the SDK to connect to end-points in North America.</p> <p> Declared In <code class="declared-in-ref">AMZNAuthorizationManager.h</code>. </p> </dd> <dt><a name="" title="AMZNRegionEU"></a><code>AMZNRegionEU</code></dt> <dd> <p>Setting region property to this value causes the SDK to connect to end-points in Europe.</p> <p> Declared In <code class="declared-in-ref">AMZNAuthorizationManager.h</code>. </p> </dd> <dt><a name="" title="AMZNRegionFE"></a><code>AMZNRegionFE</code></dt> <dd> <p>Setting region property to this value causes the SDK to connect to end-points in far East.</p> <p> Declared In <code class="declared-in-ref">AMZNAuthorizationManager.h</code>. </p> </dd> </dl> </div> <div class="method-subsection availability"> <h4 class="method-subtitle parameter-title">Availability</h4> <p>3.0</p> </div> <div class="method-subsection declared-in-section"> <h4 class="method-subtitle">Declared In</h4> <p><code class="declared-in-ref">AMZNAuthorizationManager.h</code></p> </div> </main> <footer> <div class="footer-copyright"> <p class="copyright">Copyright &copy; 2016 Amazon.com, Inc. All rights reserved. Updated: 2016-11-01</p> <p class="generator">Generated by <a href="http://appledoc.gentlebytes.com">appledoc 2.2.1 (build 1333)</a>.</p> </div> </footer> </div> </div> </article> <script src="../js/script.js"></script> </body> </html>
{ "content_hash": "30fd4ad87b9238d9b4a30d8bfa2f2055", "timestamp": "", "source": "github", "line_count": 219, "max_line_length": 193, "avg_line_length": 25.589041095890412, "alnum_prop": 0.4853675945753034, "repo_name": "gcmcnutt/Sensor2", "id": "6d80a8c76dda74b890453d7617a843ec6a3c7ff1", "size": "5604", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "LoginWithAmazon/docs/Contents/Resources/Documents/Constants/AMZNRegion.html", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "17121" }, { "name": "HTML", "bytes": "161095" }, { "name": "JavaScript", "bytes": "2765" }, { "name": "Objective-C", "bytes": "319939" }, { "name": "Swift", "bytes": "56090" } ], "symlink_target": "" }
package org.apache.flex.compiler.tree.properties; import org.apache.flex.compiler.internal.tree.as.ExpressionNodeBase; import org.apache.flex.compiler.internal.tree.as.LiteralNode; import org.apache.flex.compiler.tree.as.IASNode; /** * Node that represents a key-value pair in a properties file */ public interface IResourceBundleEntryNode extends IASNode { /** * Returns the key node * * @return key node */ LiteralNode getKeyNode(); /** * Returns the value node * * @return value node */ ExpressionNodeBase getValueNode(); }
{ "content_hash": "b532e282f670d9cfeff95d7b11107c0e", "timestamp": "", "source": "github", "line_count": 27, "max_line_length": 68, "avg_line_length": 21.925925925925927, "alnum_prop": 0.6908783783783784, "repo_name": "greg-dove/flex-falcon", "id": "e50de68cdf006530022130401b567d8bc0ad5b83", "size": "1411", "binary": false, "copies": "2", "ref": "refs/heads/develop", "path": "compiler/src/main/java/org/apache/flex/compiler/tree/properties/IResourceBundleEntryNode.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "ActionScript", "bytes": "106801" }, { "name": "Batchfile", "bytes": "12393" }, { "name": "GAP", "bytes": "131951" }, { "name": "HTML", "bytes": "103352" }, { "name": "Java", "bytes": "15702614" }, { "name": "JavaScript", "bytes": "157084" }, { "name": "Lex", "bytes": "37784" }, { "name": "Shell", "bytes": "19121" } ], "symlink_target": "" }
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <parent> <groupId>com.itranswarp.recurring</groupId> <artifactId>project</artifactId> <version>PROJECT-SNAPSHOT</version> <relativePath>../project/pom.xml</relativePath> </parent> <modelVersion>4.0.0</modelVersion> <artifactId>account</artifactId> <version>${project.version}</version> <packaging>jar</packaging> <dependencies> <dependency> <groupId>com.itranswarp.recurring</groupId> <artifactId>base</artifactId> <version>${project.version}</version> </dependency> </dependencies> </project>
{ "content_hash": "55c44f9409f8f256763cc6951e190f58", "timestamp": "", "source": "github", "line_count": 22, "max_line_length": 104, "avg_line_length": 33.22727272727273, "alnum_prop": 0.7291381668946648, "repo_name": "changsure/recurring", "id": "f5b16992b556f621546b7f38ab30724c78d6403d", "size": "731", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "account/pom.xml", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "321789" } ], "symlink_target": "" }
<?php declare(strict_types=1); namespace Sphp\Tests\DateTime\Constraints; use PHPUnit\Framework\TestCase; use Sphp\DateTime\Constraints\{ ConstraintsAggregate }; use Sphp\DateTime\ImmutableDate; /** * Class ConstraintsAggregate * * @author Sami Holck <sami.holck@gmail.com> * @license https://opensource.org/licenses/MIT MIT License * @link https://github.com/samhol/SPHP-framework Github repository * @filesource */ class ConstraintsAggregateTest extends TestCase { public function testCase1(): void { $c = new ConstraintsAggregate(); $c->isAnyOf() ->annual(1, 1) ->annual(1, 2) ->annual(1, 3); $c->isAnyOf() ->annual(1, 1) ->weekdays(1, 2); $c->isNot()->after('2001-1-1'); $c->is()->after('1999-1-2'); $this->assertTrue($c->isValid(ImmutableDate::from('2000-1-1'))); //$this->assertTrue($c->isValid(ImmutableDate::from('last monday'))); $this->assertFalse($c->isValid(ImmutableDate::from('2001-2-1'))); $this->assertFalse($c->isValid(ImmutableDate::from('2000-2-2'))); $this->assertFalse($c->isValid(ImmutableDate::from('1998-2-1'))); } public function testIs(): void { $c = new ConstraintsAggregate(); $c->is() ->date('2021-5 first sunday'); $this->assertTrue($c->isValid(ImmutableDate::from('2021-5-2'))); $this->assertFalse($c->isValid(ImmutableDate::from('2021-5-1'))); $this->assertFalse($c->isValid(ImmutableDate::from('2021-5-3'))); } public function testNot(): void { $c = new ConstraintsAggregate(); $c->isNot() ->date('2021-1-3') ->date('2001-2 first monday') ->date('today'); $c->isNot()->before('2021-1-1'); $this->assertTrue($c->isValid(ImmutableDate::from('2021-1-2'))); $this->assertFalse($c->isValid(ImmutableDate::from('today'))); } }
{ "content_hash": "92bd74a8895b7ce769b07dd255fa99ac", "timestamp": "", "source": "github", "line_count": 65, "max_line_length": 73, "avg_line_length": 28.907692307692308, "alnum_prop": 0.613092070250133, "repo_name": "samhol/SPHP-framework", "id": "6299adb9853e4e43a27ac7e4eb6be685a69277db", "size": "2169", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "sphp/php/tests/classes/Sphp/Tests/DateTime/Constraints/ConstraintsAggregateTest.php", "mode": "33188", "license": "mit", "language": [ { "name": "Hack", "bytes": "19" }, { "name": "JavaScript", "bytes": "22252" }, { "name": "PHP", "bytes": "3138045" }, { "name": "SCSS", "bytes": "34618" } ], "symlink_target": "" }
namespace media { namespace vaapi_test { // This class manages the lifetime of a VADisplay in a RAII fashion from // vaGetDisplayDRM() to vaTerminate(). Decoders may use the display() method to // access the VADisplay and issue direct libva calls. class VaapiDevice { public: // Initializes the VADisplay. Success is ASSERTed. VaapiDevice(); VaapiDevice(const VaapiDevice&) = delete; VaapiDevice& operator=(const VaapiDevice&) = delete; ~VaapiDevice(); VADisplay display() const { return display_; } private: base::File display_file_; VADisplay display_; }; } // namespace vaapi_test } // namespace media #endif // MEDIA_GPU_VAAPI_TEST_VAAPI_DEVICE_H_
{ "content_hash": "277eb5945e3e057a3ed558f666d70a89", "timestamp": "", "source": "github", "line_count": 26, "max_line_length": 79, "avg_line_length": 26.115384615384617, "alnum_prop": 0.7231222385861561, "repo_name": "nwjs/chromium.src", "id": "2b0e1ad1d5cf29f68ddcf5c8d488613f82bc44d8", "size": "964", "binary": false, "copies": "7", "ref": "refs/heads/nw70", "path": "media/gpu/vaapi/test/vaapi_device.h", "mode": "33188", "license": "bsd-3-clause", "language": [], "symlink_target": "" }
<?php /** * 评论 */ class FeedbackViewModel extends BaseViewModel { protected $pk = 'feedback_id'; protected $viewFields = array( 'Feedback' => array( 'feedback_id', 'feedback_aid', 'feedback_uid', 'feedback_username', 'feedback_moblie_model', 'feedback_moblie_imei', 'feedback_arctitle', 'feedback_ip', 'feedback_added', 'feedback_mid', 'feedback_msg', 'feedback_status', 'feedback_admin', 'feedback_quote', 'feedback_star', 'feedback_good', 'feedback_type', '_type' => 'LEFT', ), 'Customer' => array( //'`id`', 'name', //'`from`', 'nickname', 'realname', //'password', 'head', 'sex', //'birthday', //'score', //'comment', //'reply', //'collect', //'attention', //'description', //'mobile_imei', //'mobile_model', //'ctime', //'utime', //'status', '_on' => 'Feedback.feedback_uid = Customer.id', ), ); //获取评论列表 public function queryList($params) { $where = $this->_makeListWhere($params); $field = $this->makeFieldByParams($params); $limit = $this->_makeListLimit($params, C('DJGAME.FEEDBACK_LIST_DEFAULT_COUNT')); $this->where($where); $this->field($field); $this->limit($limit); $this->order('feedback_added DESC'); $this->cache(true, C('DJGAME.CACHE_SHORT_TIME')); $list = $this->select(); return $list; }//end queryList() //获取评论列表总数 public function countList($params) { $where = $this->_makeListWhere($params); $count = $this->where($where)->cache(true, C('DJGAME.CACHE_SHORT_TIME'))->count(); return $count; }//end countList() private function _makeListWhere($params) { return array( 'feedback_aid' => $params['id'], 'feedback_type' => $params['feedback_type'], 'feedback_status' => 1, ); }//end _makeListWhere() private function _makeListLimit($params, $defaultCount) { $start = isset($params['start']) ? $params['start'] : 0; $count = isset($params['count']) ? $params['count'] : $defaultCount; return "{$start},{$count}"; }//end _makeListLimit() }
{ "content_hash": "c2eea68f87f10748773329ffae8bbc15", "timestamp": "", "source": "github", "line_count": 91, "max_line_length": 84, "avg_line_length": 22.615384615384617, "alnum_prop": 0.5942662779397473, "repo_name": "UDBIAWDIF/5ihzp", "id": "0609a80501f2b4c3aef8665eed0483c641b4bfce", "size": "2090", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "Home/Lib/Model/FeedbackViewModel.class.php", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "C", "bytes": "10209" }, { "name": "CSS", "bytes": "470262" }, { "name": "JavaScript", "bytes": "943356" }, { "name": "PHP", "bytes": "4722164" } ], "symlink_target": "" }
import piglow from multiprocessing import Process, Queue from Queue import Full, Empty from time import sleep # # Piglow UI utils for piglow-sys library. # def start(clear=True): """ Start PiGlow UI updates """ if _enabled: return if clear: _change_task("_clear_all") _change_task("_enable") _start_updater() def stop(clear=True): """ Stop any PiGlow UI updates """ if clear: _change_task("_clear_all") _change_task("_disable") def clear_all(): """ Clear all LEDs """ _change_task("_clear_all") def pulse_color(color, speed=10, low=64, high=255): """ Pulse each LED of the defined color at the defined speed. """ _change_task("_pulse_color", [color, speed, low, high], True) def set_color(color, value): """ Set the value of the defined color """ _change_task("_set_color", [color, value]) def cycle(leds, speed=10, low=0, high=255): """ Cycle each LED from low to high in order """ _change_task("_cycle", [leds, speed, low, high], True) def dim(led, speed=2, high=255, low=0): """ Dims the LED from high to low at the given speed """ _change_task("_dim", [led, speed, high, low], True) def set(leds, value): """ Sets the value of each led """ _change_task("_set", [leds, value]) def pulse(led, speed=2, low=0, high=255): """ Pulse the LED from low to high at the given speed """ _change_task("_pulse", [led, speed, low, high], True) # # Private functions to drive the UI (ie, PiGlow updates) # _enabled = False _task_queue = Queue() _updater_process = None _NOTASK_SLEEP_INTERVAL = 1 def _enable(): """ Enable the PiGlow UI updates """ global _enabled _enabled = True def _disable(): """ Disable the PiGlow UI updates """ global _enabled _enabled = False def _change_task(task, args=[], repeat=False, interval=0): """ Change the current task """ try: _task_queue.put([task, args, repeat, interval]) except Full: print "Task ", task, " failed. Task queue full" return def _handle_tasks(tasks): """ Perform the UI update for the current task """ global _enabled task = None _enabled = True while _enabled: try: task = tasks.get(False) except Empty: # Do nothing, this is a valid state pass # If we have no task, just sleep for an interval and read again if task is None: sleep(_NOTASK_SLEEP_INTERVAL) continue # Get and exec the task method task_method = globals()[task[0]] if task_method is None: sleep(task[3]) continue else: task_method(*task[1]) if not task[2]: task = None def _start_updater(): """ Start an updater process if there isn't already one """ global _updater_process # If already enabled, just return if _enabled: return _updater_process = Process(target=_handle_tasks, args=(_task_queue,)) _updater_process.start() # # API drawing task functions # def _clear_all(): """ Clear all LEDs """ for l in range(0, 18): piglow.set(l, 0) piglow.show() def _set_color(color, value): """ Set the value of the defined color """ color_setter = getattr(piglow, color) color_setter(value) piglow.show() def _pulse_color(color, speed, low, high): """ Pulse each LED of the defined color at the given speed """ color_setter = getattr(piglow, color) pulse_range = range(low, high) wait_for = 1/speed for c in pulse_range: color_setter(c) piglow.show() sleep(wait_for) for c in reversed(pulse_range): color_setter(c) piglow.show() sleep(wait_for) def _pulse(led, speed, low, high): """ Pulse the LED from low to high """ pulse_range = range(low, high) wait_for = 1/speed for c in pulse_range: piglow.set(led, c) piglow.show() sleep(wait_for) for c in reversed(pulse_range): piglow.set(led, c) piglow.show() sleep(wait_for) def _set(leds, value): """ Sets the value of each led """ for led in leds: piglow.set(led, value) piglow.show() def _dim(led, speed, high, low): """ Dims the led from high to low at the given speed """ dim_range = range(low, high) wait_for = 1/speed for c in reversed(dim_range): piglow.set(led, c) piglow.show() sleep(wait_for) def _cycle(leds, speed, low, high): """ Cycle each LED from low to high in order """ pulse_range = range(low, high) wait_for = 1/speed # Set each LED to the LOW state _set(leds, low) for i in range(0, len(leds)): for c in pulse_range: # Increase the LED to HIGH piglow.set(leds[i], c) piglow.show() sleep(wait_for) # Decrease the previous LED back to LOW at same rate if i > 0: piglow.set(leds[i-1], high-(c-low)) piglow.show() sleep(wait_for) # Decrease the final LED back to LOW state _dim(leds[-1], speed, high, low) # Set each LED to the LOW state _set(leds, low)
{ "content_hash": "6c0ac8c81eba9d786ea880b44d94dbfa", "timestamp": "", "source": "github", "line_count": 216, "max_line_length": 73, "avg_line_length": 24.48611111111111, "alnum_prop": 0.5802609188882587, "repo_name": "deanydean/py-piglow-sys", "id": "37a1f41b8202995a02a239b975ab1754c6252166", "size": "5904", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/piglowui.py", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Python", "bytes": "11839" }, { "name": "Shell", "bytes": "95" } ], "symlink_target": "" }
using EndlessClient.Controllers; using EndlessClient.GameExecution; using EOLib.Domain.Map; using Microsoft.Xna.Framework.Input; using Optional; namespace EndlessClient.Input { public class ArrowKeyHandler : InputHandlerBase { private readonly IArrowKeyController _arrowKeyController; public ArrowKeyHandler(IEndlessGameProvider endlessGameProvider, IUserInputProvider userInputProvider, IUserInputTimeRepository userInputTimeRepository, IArrowKeyController arrowKeyController, ICurrentMapStateRepository currentMapStateRepository) : base(endlessGameProvider, userInputProvider, userInputTimeRepository, currentMapStateRepository) { _arrowKeyController = arrowKeyController; } protected override Option<Keys> HandleInput() { if (IsKeyHeld(Keys.Left) && _arrowKeyController.MoveLeft()) return Option.Some(Keys.Left); if (IsKeyHeld(Keys.Right) && _arrowKeyController.MoveRight()) return Option.Some(Keys.Right); if (IsKeyHeld(Keys.Up) && _arrowKeyController.MoveUp()) return Option.Some(Keys.Up); if (IsKeyHeld(Keys.Down) && _arrowKeyController.MoveDown()) return Option.Some(Keys.Down); return Option.None<Keys>(); } } }
{ "content_hash": "d0a4660e6c19172b32e241ba5a3b7ffd", "timestamp": "", "source": "github", "line_count": 37, "max_line_length": 110, "avg_line_length": 39.5945945945946, "alnum_prop": 0.6341296928327645, "repo_name": "ethanmoffat/EndlessClient", "id": "18dd4c06d3af2b497f844821b8c4302d5324118f", "size": "1467", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "EndlessClient/Input/ArrowKeyHandler.cs", "mode": "33188", "license": "mit", "language": [ { "name": "C#", "bytes": "2416390" }, { "name": "HLSL", "bytes": "292" } ], "symlink_target": "" }