text
stringlengths
2
1.04M
meta
dict
import path from 'path'; import test from 'ava'; import gulpUtil from 'gulp-util'; import fn from './'; test.cb(t => { const stream = fn(); stream.once('data', file => { t.is(file.contents.toString(), 'unicorns'); t.end(); }); stream.write(new gulpUtil.File({ base: __dirname, path: path.join(__dirname, 'file.ext'), contents: new Buffer("unicorns") })); stream.end(); });
{ "content_hash": "73bbe22474d84279c0fa9fa5ce8b71ef", "timestamp": "", "source": "github", "line_count": 21, "max_line_length": 45, "avg_line_length": 18.714285714285715, "alnum_prop": 0.6183206106870229, "repo_name": "Maximaximum/gulp-vb2ts", "id": "6a0f7b0b1b0fae0bf48764fa56913026ff51da4f", "size": "393", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "test.js", "mode": "33188", "license": "mit", "language": [ { "name": "JavaScript", "bytes": "990" } ], "symlink_target": "" }
import { async, ComponentFixture, TestBed } from '@angular/core/testing'; import { Child1Component } from './child1.component'; describe('Child1Component', () => { let component: Child1Component; let fixture: ComponentFixture<Child1Component>; beforeEach(async(() => { TestBed.configureTestingModule({ declarations: [ Child1Component ] }) .compileComponents(); })); beforeEach(() => { fixture = TestBed.createComponent(Child1Component); component = fixture.componentInstance; fixture.detectChanges(); }); it('should be created', () => { expect(component).toBeTruthy(); }); });
{ "content_hash": "7b33f680858c1a1311e7a7d1cb5f932a", "timestamp": "", "source": "github", "line_count": 25, "max_line_length": 73, "avg_line_length": 25.28, "alnum_prop": 0.6708860759493671, "repo_name": "pusgs/materijali", "id": "cdc3d7695057dc10ee9d01acaf728d928d7be53f", "size": "632", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "AngularExamples/routing/src/app/child1/child1.component.spec.ts", "mode": "33188", "license": "mit", "language": [ { "name": "ASP", "bytes": "316" }, { "name": "C#", "bytes": "502591" }, { "name": "CSS", "bytes": "9092" }, { "name": "HTML", "bytes": "22592" }, { "name": "JavaScript", "bytes": "557466" }, { "name": "Shell", "bytes": "735" }, { "name": "TypeScript", "bytes": "51681" } ], "symlink_target": "" }
<!DOCTYPE html> <html lang="en" id="webstandardssherpa_com"> <head> <meta charset="utf-8"> <meta http-equiv="Content-Language" content="en"/> <title>Log In - Web Standards Sherpa</title> <meta name="robots" content="index,follow,archive" /> <meta name='description' content='Web Standards Sherpa&rsquo;s experts provide helpful, pragmatic and up-to-date advice on best practices for web professionals everywhere.' /> <meta name='DC.description' content='Web Standards Sherpa&rsquo;s experts provide helpful, pragmatic and up-to-date advice on best practices for web professionals everywhere.' /> <meta name='keywords' content='web standards,best practices,web design,web development' /> <meta name='DC.subject' content='web standards,best practices,web design,web development' /> <link rel="schema.DC" href="http://purl.org/dc/elements/1.1/" /> <link rel="schema.DCTERMS" href="http://purl.org/dc/terms/" /> <meta name="DC.title" content="Log In - Web Standards Sherpa" /> <meta name="DC.creator" content="Web Standards Sherpa" /> <meta name="DC.publisher" content="The Web Standards Project" /> <meta name="DC.date.created" scheme="DCTERMS.W3CDTF" content="2015-12-07T14:49:30-05:00" /> <meta name="DC.date.modified" scheme="DCTERMS.W3CDTF" content="1453-05-18T17:00:00-05:00" /> <meta name="DC.date.valid" scheme="DCTERMS.W3CDTF" content="2015-12-13T16:49:30-05:00" /> <meta name="DC.type" scheme="DCTERMS.DCMIType" content="Text" /> <meta name="DC.rights" scheme="DCTERMS.URI" content="(cc) Creative Commons Attribution-NonCommercial-ShareAlike 3.0 Unported License"> <meta name="Copyright" content="(cc) Creative Commons Attribution-NonCommercial-ShareAlike 3.0 Unported License"/> <meta name="DC.format" content="text/html" /> <meta name="DC.identifier" scheme="DCTERMS.URI" content="http://webstandardssherpa.com/log-in" /> <meta name="MSSmartTagsPreventParsing" content="true"/> <meta name="Rating" content="General"/> <meta name="viewport" content="width=device-width, initial-scale=1"/> <link rel="home" href="../index.html"/> <link rel="copyright" href="index.html%3Freturn=%252Fask-the-sherpas%252Fcoding-resources%252F.html#license"/> <link rel="shortcut icon" type="image/png" href="../favicon.png"/> <link rel="author" type="text/plain" href="../humans.txt.html"/> <!--[if lte IE 8]><script src="http://html5shiv.googlecode.com/svn/trunk/html5.js"></script><![endif]--> <!--[if (lte IE 8)&(!IEMobile)]> <link rel="stylesheet" href="/c/old-ie.css" media="screen"> <![endif]--> <!--[if gt IE 8]><!--> <link rel="stylesheet" type="text/css" href="../c/main.css" media="screen"/> <!--<![endif]--> <!--[if IEMobile 7]> <link rel="stylesheet" href="/c/main.css" media="screen"> <link rel="stylesheet" href="/c/windows7-mobile.css" media="screen"> <![endif]--> <link rel="alternate" type="application/rss+xml" title="Web Standards Sherpa Reviews (Summary)" href="http://feeds.feedburner.com/Web-Standards-Sherpa-Reviews-Summary"/> <link rel="alternate" type="application/rss+xml" title="Web Standards Sherpa Reviews (Full Text)" href="http://feeds.feedburner.com/Web-Standards-Sherpa-Reviews"/> <link rel="alternate" type="application/rss+xml" title="Web Standards Sherpa Discussions" href="http://feeds.feedburner.com/Web-Standards-Sherpa-Discussions"/> <script type="text/javascript"> var _gaq = _gaq || []; _gaq.push(['_setAccount', 'UA-176472-9']); _gaq.push(['_trackPageview']); (function() { var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true; ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s); })(); </script> <script type="text/javascript"> var WRInitTime=(new Date()).getTime(); </script> </head> <body id="log-in" class="form"> <header role="banner" id="page-header"> <h4 id="logo"><a href="../index.html" title="Return to the homepage">Web Standards Sherpa</a></h4> </header> <nav id="nav-primary" role="navigation"> <ul><li id="nav-home"><a href="../index.html">Home</a></li><li id="nav-reviews"><a href="../reviews/index.html">Reviews</a></li><li id="nav-ask-the-sherpas"><a href="../ask-the-sherpas/index.html">Ask the Sherpas</a></li> </ul> </nav> <div id="content"> <nav id="crumbs"> <ol> <li><em>Log In</em></li> </ol> </nav> <article> <header> <h1>Log In</h1> </header> <p class="buttons" id="social-login"><a class="rpxnow" onclick="return false;" href="https://wasp.rpxnow.com/openid/v2/signin?token_url=http%3A%2F%2Fwebstandardssherpa.com%2Fopenid-login%2F%3Freturn%3DL2Fzay10aGUtc2hlcnBhcy9jb2RpbmctcmVzb3VyY2VzLw%3D%3D"> Login via OpenID or oAuth </a><img src="../c/i/rpxnow.png" title="You can log in using and existing Twitter, Facebook, OpenID, Google, Yahoo, or AOL account" alt=""/></p> <p class="rule"><em>or</em></p> <form method="post" action="../index.html" > <div class='hiddenFields'> <input type="hidden" name="XID" value="b965b16d2c7d66369a07ff20917f05f0df7c8f68" /> <input type="hidden" name="ACT" value="14" /> <input type="hidden" name="RET" value="/ask-the-sherpas/coding-resources/" /> <input type="hidden" name="site_id" value="1" /> </div> <fieldset> <p>Log in with your Web Standards Sherpa&nbsp;account.</p> <ol> <li> <label for="login-email">Email or Username</label> <input type="text" id="login-email" name="username" required="required" aria-required="true"/> </li> <li> <label for="login-password">Password</label> <input type="password" id="login-password" name="password" required="required" aria-required="true"/> </li> <li class="confirm"> <label for="login-auto"><input type="checkbox" name="auto_login" value="1"/> Remember Me</label> <a id="forgot-pass" href="../forgot-password/index.html">Forgot your password?</a> </li> <li class="submit buttons"> <button type="submit" name="submit" value="Submit">Log In</button> </li> </ol> </fieldset> </form> </article> </div> <form style="display: none" id="search-form" method="post" action="../index.html" > <div class='hiddenFields'> <input type="hidden" name="ACT" value="6" /> <input type="hidden" name="XID" value="151fd7526e1801ffc47e105450dafb776d3295fd" /> <input type="hidden" name="RES" value="10" /> <input type="hidden" name="meta" value="vJed+IEhaFn3W7jNVVY8C6VK4KKB0doGerxtt+3TXJkJkrK5M3OFhLNfv7UrH+uJhVYy/SM2Y8CEBzxS9ZAY+5Ry234MoWdF0KwpptDKKX/rJJg1NP4Y7SntDPwMKWd0mrV/+nbWgdpLXyGAXHtWDd/W8QMHWePL8qfhqCpJzaK4pU2LxFEhOj26ZDN4P+8d8hXffYqEVMiMRDrkUYAlZAa+r08a/igafmWKpfXqcmFAHWq/qsh+zoaTz9V6wiUJl2MMAdfHTEZ76nZbWvE5NUZpcvtxRexke8gSzhsFUK46dJJ8pJfmOvPccKB8bfwmBU4cgAZ668OleVhPUZRHiYhGfX21C2DodUFydLdhuEPR2Upj1jdw5RfdVF8nWXwA5G5T4DRd4xKMtKvVvr1BpJKZ37Gid+DBZjiqIcAhYCY=" /> <input type="hidden" name="site_id" value="1" /> </div> <p role="search"> <label for="query">Looking for something?</label> <input type="search" name="keywords" id="query" value=""/> <button type="submit">Search</button> </p> </form> <nav id="nav-account" style="display: none" role="navigation"> <ul class="buttons"> <li><a href="../sign-up/index.html" style="display: none">Sign up</a></li> </ul> </nav> <footer role="contentinfo" id="page-footer"> <div id="site-info"> <div id="elevator-pitch" class="footer-item"> <p>Web Standards Sherpa&rsquo;s experts provide helpful, pragmatic and up-to-date advice on best practices for web professionals everywhere.</p> <ul class="more"> <li><a href="../about/index.html">More about us</a></li> <li><a href="../contact/index.html" style="display: none">Contact us</a></li> </ul> </div> <nav id="nav-complete" role="navigation"> <section class="participate" style="display: none"> <h1>Participate</h1> <ul> <li><a href="../submit-a-site/index.html">Submit a site</a></li> <li><a href="../submit-a-question/index.html">Submit a question</a></li> <li><a href="../sign-up/index.html" style="display: none">Sign up</a><mark><a href="index.html" style="display: none">Log in</a></mark></li> </ul> </section> <section class="learn"> <h1>Learn</h1> <ul> <li><a href="../reviews/index.html">Reviews</a></li> <li><a href="../ask-the-sherpas/index.html">Ask Sherpas</a></li> <li><a href="../about/authors/index.html">Authors</a></li> <li><a href="../glossary/index.html">Glossary</a></li> </ul> </section> </nav> <section id="sponsors" class="footer-item"> <h1>We thank our sponsors</h1> <ol class="partners"> <li> <a href="http://www.microsoft.com"><img src="../i/p/microsoft-mono.png" alt="Microsoft"/></a> </li> <li> <a href="http://mailchimp.com"><img src="../i/p/mc-mono.png" alt="MailChimp"/></a> </li> <li> <a href="http://developer.mozilla.org"><img src="../i/p/mozilla-mono.png" alt="Mozilla"/></a> </li> <li> <a href="http://mediatemple.net"><img src="../i/p/mt-mono.png" alt="Media Temple"/></a> </li> </ol> </section> </div> <div id="terms" class="source-org vcard"> <p id="ownership"><a xmlns:dct="http://purl.org/dc/terms/" href="../index.html" property="dct:title" rel="cc:attributionURL">Web Standards Sherpa</a> is an outreach effort by the <a class="org fn url" xmlns:cc="http://creativecommons.org/ns#" href="http://webstandards.org" property="cc:attributionName">Web Standards Project (WaSP)<img src="../i/WaSP-logo-mono.png" alt="" /></a>.</p> <!-- <p id="network">This site is a proud member of the <a rel="license" href="http://network.smashingmagazine.com/">Smashing Network<img src="/i/p/smashing-mono.png" alt="" /></a>.</p> --> <p id="license">The content of this site is licensed under <a rel="license" href="http://creativecommons.org/licenses/by-nc-sa/3.0/">Creative Commons<img src="../i/license.png" alt="" /></a>.</p> </div> </footer> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js"></script> <script>window.jQuery || document.write("<script src='../j/jquery.js'>\x3C/script>")</script> <script src="../j/main.js"></script> <!-- Just to see if this works --> <!--[if lte IE 6]><script src="/j/ie6.js"></script><![endif]--> <script type="text/javascript"> var rpxJsHost = (("https:" == document.location.protocol) ? "https://" : "http://static."); document.write(unescape("%3Cscript src='" + rpxJsHost + "rpxnow.com/js/lib/rpx.js' type='text/javascript'%3E%3C/script%3E")); </script> <script type="text/javascript"> RPXNOW.overlay = true; RPXNOW.language_preference = "en"; RPXNOW.init({appId: 'cdnifhbomckchfhfgbpl', xdReceiver: '/rpx_xdcomm.html'}); </script> <div id="ClickTaleDiv" style="display: none;"></div> <script type="text/javascript"> if ( document.location.protocol!='https:' ) { $.getScript('http://s.clicktale.net/WRb6.js',function(){ if ( typeof ClickTale=='function' ) {ClickTale(16473,0.1,"www02");} }); } </script> </body> </html>
{ "content_hash": "22b9a99541ffe337632dbbaab559c862", "timestamp": "", "source": "github", "line_count": 274, "max_line_length": 472, "avg_line_length": 41.36496350364963, "alnum_prop": 0.6574025057349567, "repo_name": "WebStandardsSherpa/webstandardssherpa.com", "id": "e88cd48f774ebd4192f2dda4f66612a541b7d382", "size": "11334", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "log-in/index.html?return=%2Fask-the-sherpas%2Fcoding-resources%2F.html", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "589844" }, { "name": "HTML", "bytes": "11527081" }, { "name": "JavaScript", "bytes": "17408" } ], "symlink_target": "" }
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="wrap_content" android:orientation="vertical" > <TextView android:id="@+id/contactitem_catalog" style="@style/MMListCatalog" android:layout_height="wrap_content" android:layout_marginLeft="10dp" android:paddingRight="5.0dip" /> <LinearLayout style="@style/MMListItem" android:layout_height="50dp" android:background="@drawable/setting_item_selector" android:paddingLeft="15dp" > <CheckBox android:id="@+id/checkbox" android:layout_width="wrap_content" android:layout_height="wrap_content" android:visibility="gone" android:button="@drawable/jy_checkbox_selector" android:focusable="false" /> <ImageView android:id="@+id/contactitem_avatar_iv" android:layout_width="40.0dip" android:layout_height="40.0dip"/> <RelativeLayout android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_weight="1.0" android:gravity="center_vertical" android:paddingLeft="8.0dip" > <TextView android:id="@+id/contactitem_nick" style="@style/MMFontTitleInList" android:layout_width="wrap_content" android:layout_height="wrap_content" android:maxLines="1" /> </RelativeLayout> </LinearLayout> <View android:layout_width="match_parent" android:layout_height="1dp" android:background="@color/black2" /> </LinearLayout>
{ "content_hash": "cf0148d5a071e178a3eaccb43717be12", "timestamp": "", "source": "github", "line_count": 55, "max_line_length": 72, "avg_line_length": 34.25454545454546, "alnum_prop": 0.5759023354564756, "repo_name": "zhujunxxxxx/SportsPage", "id": "cb9335e39edb869fc7ec8b069deb0a3d900bd4a9", "size": "1884", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "andriod/SportPage/app/src/main/res/layout/item_contact.xml", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "C", "bytes": "2598" }, { "name": "HTML", "bytes": "5571" }, { "name": "Java", "bytes": "1001409" }, { "name": "Objective-C", "bytes": "3916052" }, { "name": "Ruby", "bytes": "43" }, { "name": "Shell", "bytes": "8237" } ], "symlink_target": "" }
<?php namespace PHPExiftool\Driver\Tag\MXF; use JMS\Serializer\Annotation\ExclusionPolicy; use PHPExiftool\Driver\AbstractTag; /** * @ExclusionPolicy("all") */ class Bitrate extends AbstractTag { protected $Id = '060e2b34.0101.0105.04010602.010b0000'; protected $Name = 'Bitrate'; protected $FullName = 'MXF::Main'; protected $GroupName = 'MXF'; protected $g0 = 'MXF'; protected $g1 = 'MXF'; protected $g2 = 'Video'; protected $Type = 'int32u'; protected $Writable = false; protected $Description = 'Bitrate'; }
{ "content_hash": "f23bbe5e2164062fe881ab506f028323", "timestamp": "", "source": "github", "line_count": 36, "max_line_length": 59, "avg_line_length": 15.833333333333334, "alnum_prop": 0.6578947368421053, "repo_name": "bburnichon/PHPExiftool", "id": "6b8d605aacc1f563336c61566b05ab2b8766d958", "size": "794", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "lib/PHPExiftool/Driver/Tag/MXF/Bitrate.php", "mode": "33188", "license": "mit", "language": [ { "name": "PHP", "bytes": "22076400" } ], "symlink_target": "" }
update user_accounts set password_hash = ? where username = ?
{ "content_hash": "1bcbb34f29b8baf601905aaa73025404", "timestamp": "", "source": "github", "line_count": 3, "max_line_length": 21, "avg_line_length": 20.666666666666668, "alnum_prop": 0.7419354838709677, "repo_name": "perfect-idiots/b6fb", "id": "3451a06cb3bbdfe4942ddc77390ec52328bfa098", "size": "62", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/model/db-queries/update-user-password.sql", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "26010" }, { "name": "JavaScript", "bytes": "17444" }, { "name": "PHP", "bytes": "213338" } ], "symlink_target": "" }
package ERDBTypeImage; use strict; use Tracer; use ERDB; use GD; use MIME::Base64; use ERDBExtras; use base qw(ERDBType); =head1 ERDB Image Type Definition =head2 Introduction This object represents the data type for images stored in the database. Each image must be a PERL B<GD> object. It is stored in the database as a base64 MIME string computed from the PNG file format. =head3 new my $et = ERDBTypeImage->new(); Construct a new ERDBTypeImage descriptor. =cut sub new { # Get the parameters. my ($class) = @_; # Create the ERDBTypeImage object. my $retVal = { }; # Bless and return it. bless $retVal, $class; return $retVal; } =head3 NewSessionID my $id = ERDBTypeImage::NewSessionID(); Generate a new session ID for the current user. =cut sub NewSessionID { # Declare the return variable. my $retVal; # Get a digest encoder. Trace("Retrieving digest encoder.") if T(3); my $md5 = Digest::MD5->new(); # Add the PID, the IP, and the time stamp. Note that the time stamp is # actually two numbers, and we get them both because we're in list # context. Trace("Assembling pieces.") if T(3); $md5->add($$, $ENV{REMOTE_ADDR}, $ENV{REMOTE_PORT}, gettimeofday()); # Hash up all this identifying data. Trace("Producing result.") if T(3); $retVal = $md5->hexdigest(); # Return the result. return $retVal; } =head2 Virtual Methods =head3 averageLength my $value = $et->averageLength(); Return the average length of a data item of this field type when it is stored in the database. This value is used to compute the expected size of a database table. =cut sub averageLength { return 50000; } =head3 prettySortValue my $value = $et->prettySortValue(); Number indicating where fields of this type should go in relation to other fields. The value should be somewhere between C<1> and C<5>. A value outside that range will make terrible things happen. =cut sub prettySortValue() { return 5; } =head3 validate my $okFlag = $et->validate($value); Return an error message if the specified value is invalid for this field type. The parameters are as follows. =over 4 =item value Value of this type, for validation. =item RETURN Returns an empty string if the specified field is valid, and an error message otherwise. =back =cut sub validate { # Get the parameters. my ($self, $value) = @_; # Assume it's valid until we prove otherwise. my $retVal = ""; # Only a real GD object is valid. if (! UNIVERSAL::isa($value, 'GD::Image')) { $retVal = "Invalid image value."; } # Return the determination. return $retVal; } =head3 encode my $string = $et->encode($value, $mode); Encode a value of this field type for storage in the database (or in a database load file.) The parameters are as follows. =over 4 =item value Value of this type, for encoding. =item mode TRUE if the value is being encoding for placement in a load file, FALSE if it is being encoded for use as an SQL statement parameter. In most cases, the encoding is the same for both modes. =back =cut sub encode { # Get the parameters. my ($self, $value, $mode) = @_; # Encode the value. my $retVal = encode_base64($value->png(), ""); # Return the result. return $retVal; } =head3 decode my $value = $et->decode($string); Decode a string from the database into a value of this field type. The parameters are as follows. =over 4 =item string String from the database to be decoded. =item RETURN Returns a value of the desired type. =back =cut sub decode { # Get the parameters. my ($self, $string) = @_; # Decode the value. my $pngData = decode_base64($string); my $retVal = GD::Image->newFromPngData($pngData); # Return the result. return $retVal; } =head3 sqlType my $typeString = $et->sqlType($dbh); Return the SQL data type for this field type. =over 4 =item dbh Open L<DBKernel> handle for the database in question. This is used when the datatype may be different depending on the DBMS used. =item RETURN Returns the datatype string to be used when creating a field of this type in an SQL table. =back =cut sub sqlType { my ($self, $dbh) = @_; my $retVal = "TEXT"; if ($dbh->dbms eq 'mysql') { $retVal = "LONGTEXT"; } return $retVal; } =head3 indexMod my $length = $et->indexMod(); Return the index modifier for this field type. The index modifier is the number of characters to be indexed. If it is undefined, the field cannot be indexed. If it is an empty string, the entire field is indexed. The default is an empty string. =cut sub indexMod { return undef; } =head3 sortType my $letter = $et->sortType(); Return the sorting type for this field type. The sorting type is C<n> for integers, C<g> for floating-point numbers, and the empty string for character fields. The default is the empty string. =cut sub sortType { return ""; } =head3 documentation my $docText = $et->documentation(); Return the documentation text for this field type. This should be in TWiki markup format, though HTML will also work. =cut sub documentation() { return 'PNG format graphical image'; } =head3 name my $name = $et->name(); Return the name of this type, as it will appear in the XML database definition. =cut sub name() { return "image"; } =head3 default my $defaultValue = $et->default(); Default value to be used for fields of this type if no default value is specified in the database definition or in an L<ERDBLoadGroup/Put> call during a loader operation. The default is undefined, which means an error will be thrown during the load. =cut sub default { return undef; } =head3 align my $alignment = $et->align(); Return the display alignment for fields of this type: either C<left>, C<right>, or C<center>. The default is C<left>. =cut sub align { return 'center'; } =head3 html my $html = $et->html($value); Return the HTML for displaying the content of a field of this type in an output table. The default is the raw value, html-escaped. =cut sub html { my ($self, $value) = @_; # The incoming value here is a GD graphic image. We need to store it # to a temporary file. my $sessionID = NewSessionID(); my $fileName = $sessionID . "image$$.png"; my $oh = Open(undef, ">$ERDBExtras::temp/$fileName"); print $oh $value->png(); close $oh; my $retVal = CGI::img({ src => "$ERDBExtras::temp_url/$fileName" }); return $retVal; } =head3 objectType my $type = $et->objectType(); Return the PERL type for fields of this type. An undefined value means it's a scalar; otherwise, it should be the package name (suitable for a C<use> clause). =cut sub objectType { return "GD::Image"; } 1;
{ "content_hash": "c3eabecaf574bbb914ddb732adbaad82", "timestamp": "", "source": "github", "line_count": 342, "max_line_length": 84, "avg_line_length": 20.210526315789473, "alnum_prop": 0.6772280092592593, "repo_name": "kbase/kb_seed", "id": "b5bcb8af4a66810835762d84ee9c3b1fccf93b07", "size": "7536", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "lib/ERDBTypeImage.pm", "mode": "33188", "license": "mit", "language": [ { "name": "Makefile", "bytes": "7127" }, { "name": "Perl", "bytes": "23376361" }, { "name": "Perl 6", "bytes": "195228" }, { "name": "Ruby", "bytes": "271749" }, { "name": "Shell", "bytes": "3091" } ], "symlink_target": "" }
package org.apache.cassandra.repair; import java.util.Arrays; import java.util.HashSet; import java.util.Set; import java.util.UUID; import java.util.concurrent.TimeUnit; import com.google.common.collect.Iterables; import com.google.common.collect.Lists; import org.junit.BeforeClass; import org.junit.Test; import org.apache.cassandra.SchemaLoader; import org.apache.cassandra.config.DatabaseDescriptor; import org.apache.cassandra.db.ColumnFamilyStore; import org.apache.cassandra.db.Keyspace; import org.apache.cassandra.dht.IPartitioner; import org.apache.cassandra.dht.Murmur3Partitioner; import org.apache.cassandra.dht.Range; import org.apache.cassandra.dht.Token; import org.apache.cassandra.locator.InetAddressAndPort; import org.apache.cassandra.schema.KeyspaceParams; import org.apache.cassandra.schema.Schema; import org.apache.cassandra.schema.TableId; import org.apache.cassandra.service.ActiveRepairService; import org.apache.cassandra.streaming.StreamCoordinator; import org.apache.cassandra.streaming.DefaultConnectionFactory; import org.apache.cassandra.streaming.StreamPlan; import org.apache.cassandra.streaming.PreviewKind; import org.apache.cassandra.streaming.StreamSession; import org.apache.cassandra.utils.FBUtilities; import org.apache.cassandra.utils.MerkleTree; import org.apache.cassandra.utils.MerkleTrees; import org.apache.cassandra.utils.UUIDGen; import static org.apache.cassandra.service.ActiveRepairService.NO_PENDING_REPAIR; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; public class LocalSyncTaskTest extends AbstractRepairTest { private static final IPartitioner partitioner = Murmur3Partitioner.instance; private static final InetAddressAndPort local = FBUtilities.getBroadcastAddressAndPort(); public static final String KEYSPACE1 = "DifferencerTest"; public static final String CF_STANDARD = "Standard1"; public static ColumnFamilyStore cfs; @BeforeClass public static void defineSchema() { SchemaLoader.prepareServer(); SchemaLoader.createKeyspace(KEYSPACE1, KeyspaceParams.simple(1), SchemaLoader.standardCFMD(KEYSPACE1, CF_STANDARD)); TableId tid = Schema.instance.getTableMetadata(KEYSPACE1, CF_STANDARD).id; cfs = Schema.instance.getColumnFamilyStoreInstance(tid); } /** * When there is no difference between two, SymmetricLocalSyncTask should return stats with 0 difference. */ @Test public void testNoDifference() throws Throwable { final InetAddressAndPort ep2 = InetAddressAndPort.getByName("127.0.0.2"); Range<Token> range = new Range<>(partitioner.getMinimumToken(), partitioner.getRandomToken()); RepairJobDesc desc = new RepairJobDesc(UUID.randomUUID(), UUID.randomUUID(), KEYSPACE1, "Standard1", Arrays.asList(range)); MerkleTrees tree1 = createInitialTree(desc); MerkleTrees tree2 = createInitialTree(desc); // difference the trees // note: we reuse the same endpoint which is bogus in theory but fine here TreeResponse r1 = new TreeResponse(local, tree1); TreeResponse r2 = new TreeResponse(ep2, tree2); LocalSyncTask task = new LocalSyncTask(desc, r1, r2, NO_PENDING_REPAIR, true, true, PreviewKind.NONE); task.run(); assertEquals(0, task.get().numberOfDifferences); } @Test public void testDifference() throws Throwable { Range<Token> range = new Range<>(partitioner.getMinimumToken(), partitioner.getRandomToken()); UUID parentRepairSession = UUID.randomUUID(); Keyspace keyspace = Keyspace.open(KEYSPACE1); ColumnFamilyStore cfs = keyspace.getColumnFamilyStore("Standard1"); ActiveRepairService.instance.registerParentRepairSession(parentRepairSession, FBUtilities.getBroadcastAddressAndPort(), Arrays.asList(cfs), Arrays.asList(range), false, ActiveRepairService.UNREPAIRED_SSTABLE, false, PreviewKind.NONE); RepairJobDesc desc = new RepairJobDesc(parentRepairSession, UUID.randomUUID(), KEYSPACE1, "Standard1", Arrays.asList(range)); MerkleTrees tree1 = createInitialTree(desc); MerkleTrees tree2 = createInitialTree(desc); // change a range in one of the trees Token token = partitioner.midpoint(range.left, range.right); tree1.invalidate(token); MerkleTree.TreeRange changed = tree1.get(token); changed.hash("non-empty hash!".getBytes()); Set<Range<Token>> interesting = new HashSet<>(); interesting.add(changed); // difference the trees // note: we reuse the same endpoint which is bogus in theory but fine here TreeResponse r1 = new TreeResponse(local, tree1); TreeResponse r2 = new TreeResponse(InetAddressAndPort.getByName("127.0.0.2"), tree2); LocalSyncTask task = new LocalSyncTask(desc, r1, r2, NO_PENDING_REPAIR, true, true, PreviewKind.NONE); DefaultConnectionFactory.MAX_CONNECT_ATTEMPTS = 1; DefaultConnectionFactory.MAX_WAIT_TIME_NANOS = TimeUnit.SECONDS.toNanos(2); try { task.run(); } finally { DefaultConnectionFactory.MAX_WAIT_TIME_NANOS = TimeUnit.SECONDS.toNanos(30); DefaultConnectionFactory.MAX_CONNECT_ATTEMPTS = 3; } // ensure that the changed range was recorded assertEquals("Wrong differing ranges", interesting.size(), task.stat.numberOfDifferences); } @Test public void fullRepairStreamPlan() throws Exception { UUID sessionID = registerSession(cfs, true, true); ActiveRepairService.ParentRepairSession prs = ActiveRepairService.instance.getParentRepairSession(sessionID); RepairJobDesc desc = new RepairJobDesc(sessionID, UUIDGen.getTimeUUID(), KEYSPACE1, CF_STANDARD, prs.getRanges()); TreeResponse r1 = new TreeResponse(local, createInitialTree(desc, DatabaseDescriptor.getPartitioner())); TreeResponse r2 = new TreeResponse(PARTICIPANT2, createInitialTree(desc, DatabaseDescriptor.getPartitioner())); LocalSyncTask task = new LocalSyncTask(desc, r1, r2, NO_PENDING_REPAIR, true, true, PreviewKind.NONE); StreamPlan plan = task.createStreamPlan(local, Lists.newArrayList(RANGE1)); assertEquals(NO_PENDING_REPAIR, plan.getPendingRepair()); assertTrue(plan.getFlushBeforeTransfer()); } private static void assertNumInOut(StreamPlan plan, int expectedIncoming, int expectedOutgoing) { StreamCoordinator coordinator = plan.getCoordinator(); StreamSession session = Iterables.getOnlyElement(coordinator.getAllStreamSessions()); assertEquals(expectedIncoming, session.getNumRequests()); assertEquals(expectedOutgoing, session.getNumTransfers()); } @Test public void incrementalRepairStreamPlan() throws Exception { UUID sessionID = registerSession(cfs, true, true); ActiveRepairService.ParentRepairSession prs = ActiveRepairService.instance.getParentRepairSession(sessionID); RepairJobDesc desc = new RepairJobDesc(sessionID, UUIDGen.getTimeUUID(), KEYSPACE1, CF_STANDARD, prs.getRanges()); TreeResponse r1 = new TreeResponse(local, createInitialTree(desc, DatabaseDescriptor.getPartitioner())); TreeResponse r2 = new TreeResponse(PARTICIPANT2, createInitialTree(desc, DatabaseDescriptor.getPartitioner())); LocalSyncTask task = new LocalSyncTask(desc, r1, r2, desc.parentSessionId, true, true, PreviewKind.NONE); StreamPlan plan = task.createStreamPlan(local, Lists.newArrayList(RANGE1)); assertEquals(desc.parentSessionId, plan.getPendingRepair()); assertFalse(plan.getFlushBeforeTransfer()); assertNumInOut(plan, 1, 1); } /** * Don't reciprocate streams if the other endpoint is a transient replica */ @Test public void transientRemoteStreamPlan() { UUID sessionID = registerSession(cfs, true, true); ActiveRepairService.ParentRepairSession prs = ActiveRepairService.instance.getParentRepairSession(sessionID); RepairJobDesc desc = new RepairJobDesc(sessionID, UUIDGen.getTimeUUID(), KEYSPACE1, CF_STANDARD, prs.getRanges()); TreeResponse r1 = new TreeResponse(local, createInitialTree(desc, DatabaseDescriptor.getPartitioner())); TreeResponse r2 = new TreeResponse(PARTICIPANT2, createInitialTree(desc, DatabaseDescriptor.getPartitioner())); LocalSyncTask task = new LocalSyncTask(desc, r1, r2, desc.parentSessionId, true, false, PreviewKind.NONE); StreamPlan plan = task.createStreamPlan(local, Lists.newArrayList(RANGE1)); assertNumInOut(plan, 1, 0); } /** * Don't request streams if the other endpoint is a transient replica */ @Test public void transientLocalStreamPlan() { UUID sessionID = registerSession(cfs, true, true); ActiveRepairService.ParentRepairSession prs = ActiveRepairService.instance.getParentRepairSession(sessionID); RepairJobDesc desc = new RepairJobDesc(sessionID, UUIDGen.getTimeUUID(), KEYSPACE1, CF_STANDARD, prs.getRanges()); TreeResponse r1 = new TreeResponse(local, createInitialTree(desc, DatabaseDescriptor.getPartitioner())); TreeResponse r2 = new TreeResponse(PARTICIPANT2, createInitialTree(desc, DatabaseDescriptor.getPartitioner())); LocalSyncTask task = new LocalSyncTask(desc, r1, r2, desc.parentSessionId, false, true, PreviewKind.NONE); StreamPlan plan = task.createStreamPlan(local, Lists.newArrayList(RANGE1)); assertNumInOut(plan, 0, 1); } private MerkleTrees createInitialTree(RepairJobDesc desc, IPartitioner partitioner) { MerkleTrees tree = new MerkleTrees(partitioner); tree.addMerkleTrees((int) Math.pow(2, 15), desc.ranges); tree.init(); for (MerkleTree.TreeRange r : tree.invalids()) { r.ensureHashInitialised(); } return tree; } private MerkleTrees createInitialTree(RepairJobDesc desc) { return createInitialTree(desc, partitioner); } }
{ "content_hash": "0014599ab2ea53d25b01759ad6e99f2c", "timestamp": "", "source": "github", "line_count": 233, "max_line_length": 133, "avg_line_length": 44.98283261802575, "alnum_prop": 0.7127182520751837, "repo_name": "spodkowinski/cassandra", "id": "6e691f528ff08819c47cee5465369cb31387afed", "size": "11286", "binary": false, "copies": "1", "ref": "refs/heads/trunk", "path": "test/unit/org/apache/cassandra/repair/LocalSyncTaskTest.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "AMPL", "bytes": "801" }, { "name": "Batchfile", "bytes": "37520" }, { "name": "GAP", "bytes": "86159" }, { "name": "HTML", "bytes": "264240" }, { "name": "Java", "bytes": "21272486" }, { "name": "Lex", "bytes": "10151" }, { "name": "PowerShell", "bytes": "39040" }, { "name": "Python", "bytes": "517189" }, { "name": "Shell", "bytes": "84205" } ], "symlink_target": "" }
description: Describes how to manage users in the Auth0 Dashboard. crews: crew-2 topics: - dashboard - users contentType: how-to useCase: - manage-users v2: True --- # Manage Users Using the Dashboard You can use the Dashboard to manage your users. To begin, go to [Dashboard > Users](${manage_url}/#/users). This is where you'll go to create, view, modify, or delete users. ::: note User Management is included as part of the **Developer** subscription plan. You may need to [upgrade your plan](${manage_url}/#/tenant/billing/subscription) to access these features. ::: ::: warning <%= include('../../_includes/_users_update_normalized_profile_attributes') %> ::: ![User Profile Dashboard](/media/articles/user-profile/user1.png) ## Keep reading * [User Profiles](/users/concepts/overview-user-profile) * [View Users](/users/guides/view-users) * [Manage User Access to Applications](/users/guides/manage-user-access-to-applications) * [Manage Users Using the Management API](/users/guides/manage-users-using-the-management-api) * [Update User Profiles Using Your Database](/users/guides/update-user-profiles-using-your-database) * [User Search](/users/search)
{ "content_hash": "bf524c34e56e36e13b0d78bd6d7204d3", "timestamp": "", "source": "github", "line_count": 33, "max_line_length": 182, "avg_line_length": 35.57575757575758, "alnum_prop": 0.7402044293015332, "repo_name": "auth0/docs", "id": "865cef7e1b9884fbc2b07bf11017ee8414863f30", "size": "1178", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "articles/users/guides/manage-users-using-the-dashboard.md", "mode": "33188", "license": "mit", "language": [ { "name": "HTML", "bytes": "42938" }, { "name": "JavaScript", "bytes": "446576" }, { "name": "Shell", "bytes": "2592" } ], "symlink_target": "" }
Contributing to conda-build-all In proposing contributions to this project, you are agreeing to the following contribution terms. Grant of Copyright Licence. Subject to the terms and conditions of this Agreement, You hereby grant to the Met Office and to recipients of software distributed by the Met Office a perpetual, worldwide, non-exclusive, royalty-free, irrevocable copyright licence to reproduce, prepare derivative works of, publicly display, publicly perform, sublicence, and distribute Your Contributions and such derivative works under the terms of the BSD 3-Clause licence: http://opensource.org/licenses/BSD-3-Clause Intellectual Property Infringement. If any third party makes any claim against You or any other entity, alleging that your Contribution, or the Work to which you have contributed, infringes the intellectual property rights of that third party , then You shall inform the Met Office within 5 Working Days of such claim in order for the Met Office to take all appropriate action it deems necessary in relation to the claim. You represent that you are legally entitled to grant the above licence. If your employer(s) has rights to intellectual property that you create that includes your Contributions, you represent that you have received permission to make Contributions on behalf of that employer, or that your employer has waived such rights for your Contributions to the Met Office. You represent that each of Your Contributions is Your original creation and that you have not assigned or otherwise given up your interest in the Contribution to any third party. You represent that Your Contribution submissions include complete details of any third-party licence or other restriction (including, but not limited to, related patents and trademarks) of which you are personally aware and which are associated with any part of Your Contributions. You (or Your employer(s)) agree to fully indemnify the Met Office in the event that either of the above representations are untrue. Definitions: "You" (or "Your") shall mean the copyright owner or legal entity authorised by the copyright owner that is making this Agreement with the Met Office. For legal entities, the entity making a Contribution and all other entities that control, are controlled by, or are under common control with that entity are considered to be a single Contributor. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. "Contribution" shall mean any original work of authorship, including any modifications or additions to an existing work, that is intentionally submitted by You to the Met Office for inclusion in, or documentation of, any of the products owned or managed by the Met Office (the "Work"). For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Met Office or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Met Office for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by You as "Not a Contribution." "Parties" shall mean The Met Office and You. "Met Office" shall mean the Met Office, an Executive Agency of the Department of Business, Innovation and Skills of the United Kingdom of Great Britain and Northern Ireland ("BIS"), whose principal place of business is situated at FitzRoy Road, Exeter, Devon EX1 3PB, United Kingdom, for an on behalf of BIS. "Working Day" shall mean a day other than a Saturday, Sunday or public holiday in England when banks in London are open for business. "Data" shall have the same meaning as set out in the Data Protection Act 1998.
{ "content_hash": "08f2fe85f1b0c2efaaacacc7dc7cc9d8", "timestamp": "", "source": "github", "line_count": 48, "max_line_length": 500, "avg_line_length": 84.41666666666667, "alnum_prop": 0.8077492596248766, "repo_name": "pelson/conda-build-all", "id": "0b73655c36a1c9b8af89878dcd100209cac87cc1", "size": "4052", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "CONTRIBUTING.md", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "Python", "bytes": "169415" } ], "symlink_target": "" }
require 'rails_helper' describe CourseRepository do let (:hash) { { department: "CS", number: "135", section: "005", term: "1149", instructor: "Brad Lushman" } } let! (:book) { FactoryGirl.create :book } let! (:course) do temp = FactoryGirl.build :course, department: "CS", number: "777", term: "1149", section: "002" temp.books << book temp.save $course = temp end let! (:bogus_book) { FactoryGirl.create :book } let! (:bogus_course) do temp = FactoryGirl.create :course, department: "AFM", number: "101", term: "1151", section: "004" temp.books << bogus_book temp.save $bogus_course = temp end context "#where_course" do it "correctly filters by term" do Course.create(hash) actual = CourseRepository.where_course(term: "1149") expect(actual.length).to eq(2) end it "correctly filters by section" do course_2 = Course.create(hash) actual = CourseRepository.where_course(section: "005") expect(actual.length).to eq(1) expect(actual).to eq([course_2]) end it "correctly applies multiple filters" do course_2 = FactoryGirl.build :course, term: 1149, section: "003" course_2.books << bogus_book course_2.save actual = CourseRepository.where_course(term: 1149, section: "003") expect(actual.length).to eq(1) expect(actual.first.books).to eq([bogus_book]) expect(actual).to eq([course_2]) end it "has no false positives" do actual = CourseRepository.where_course(section: "010") expect(actual.length).to eq(0) end end it "finds all books for a given course; department is case insensitive" do actual = CourseRepository.find_by_course("cS", "777") expect(actual.length).to eq(1) expect(actual.first).to eq(course) expect(actual.first.books.length).to eq(1) expect(actual.first.books).to eq([book]) end it "correctly finds an equivalent course" do new_course = Course.create (hash) actual = CourseRepository.find(hash) expect(actual).to eq(new_course) end it "correctly sees if a record exists" do Course.create(hash) expect(CourseRepository.exists? hash).to be_truthy end context "creation" do it "raises an error if an incomplete hash is given" do expect { CourseRepository.new_record hash.excluding("section") }.to raise_error end it "correctly creates a new record" do expect { CourseRepository.new_record hash }.to change { Course.count }.by(1) end it "returns the required array" do expect(CourseRepository.required).to eq( [:department, :number, :section, :instructor, :term] ) end end end
{ "content_hash": "d23ba72dc6db66741ff460264bff9940", "timestamp": "", "source": "github", "line_count": 82, "max_line_length": 112, "avg_line_length": 32.68292682926829, "alnum_prop": 0.6619402985074627, "repo_name": "lime-green/uw_books", "id": "fada0780d1dca39fd2299b221531ddf9ac0848a9", "size": "2680", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "spec/repositories/course_repository_spec.rb", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "683" }, { "name": "JavaScript", "bytes": "664" }, { "name": "Ruby", "bytes": "78925" } ], "symlink_target": "" }
export default function reducer (state = {mode: 'IDLE', step: 0}, action = {type: 'MODE_CHANGE', payload: name}) { const newState = {mode: state.mode, step: state.step}; switch (action.type) { case 'MODE_CHANGE': newState.mode = action.payload; newState.step = 0; break; case 'NAV': switch (action.payload) { case 'BACK': newState.step -= 1; break; case 'START': case 'NEXT': newState.step += 1; break; case 'SKIP': newState.step = 7; break; case 'END': newState.step = 0; break; } } return newState; }
{ "content_hash": "9996cbd5c1a7a60d2e85124fada06f19", "timestamp": "", "source": "github", "line_count": 27, "max_line_length": 81, "avg_line_length": 26, "alnum_prop": 0.48575498575498577, "repo_name": "hexrcs/MIMAviz", "id": "b9c7b7114049b5999e0ce4e52fed9efc33a7023e", "size": "702", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/js/reducers/index.js", "mode": "33188", "license": "mit", "language": [ { "name": "HTML", "bytes": "596" }, { "name": "JavaScript", "bytes": "39981" } ], "symlink_target": "" }
package com.example.android.sunshine.app.data; import android.content.Context; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteOpenHelper; import com.example.android.sunshine.app.data.WeatherContract.LocationEntry; import com.example.android.sunshine.app.data.WeatherContract.WeatherEntry; /** * Manages a local database for weather data. */ public class WeatherDbHelper extends SQLiteOpenHelper { // If you change the database schema, you must increment the database version. private static final int DATABASE_VERSION = 2; static final String DATABASE_NAME = "weather.db"; public WeatherDbHelper(Context context) { super(context, DATABASE_NAME, null, DATABASE_VERSION); } @Override public void onCreate(SQLiteDatabase sqLiteDatabase) { final String SQL_CREATE_WEATHER_TABLE = "CREATE TABLE " + WeatherEntry.TABLE_NAME + " (" + // Why AutoIncrement here, and not above? // Unique keys will be auto-generated in either case. But for weather // forecasting, it's reasonable to assume the user will want information // for a certain date and all dates *following*, so the forecast data // should be sorted accordingly. WeatherEntry._ID + " INTEGER PRIMARY KEY AUTOINCREMENT," + // the ID of the location entry associated with this weather data WeatherEntry.COLUMN_LOC_KEY + " INTEGER NOT NULL, " + WeatherEntry.COLUMN_DATE + " INTEGER NOT NULL, " + WeatherEntry.COLUMN_SHORT_DESC + " TEXT NOT NULL, " + WeatherEntry.COLUMN_WEATHER_ID + " INTEGER NOT NULL," + WeatherEntry.COLUMN_MIN_TEMP + " REAL NOT NULL, " + WeatherEntry.COLUMN_MAX_TEMP + " REAL NOT NULL, " + WeatherEntry.COLUMN_HUMIDITY + " REAL NOT NULL, " + WeatherEntry.COLUMN_PRESSURE + " REAL NOT NULL, " + WeatherEntry.COLUMN_WIND_SPEED + " REAL NOT NULL, " + WeatherEntry.COLUMN_DEGREES + " REAL NOT NULL, " + // Set up the location column as a foreign key to location table. " FOREIGN KEY (" + WeatherEntry.COLUMN_LOC_KEY + ") REFERENCES " + LocationEntry.TABLE_NAME + " (" + LocationEntry._ID + "), " + // To assure the application have just one weather entry per day // per location, it's created a UNIQUE constraint with REPLACE strategy " UNIQUE (" + WeatherEntry.COLUMN_DATE + ", " + WeatherEntry.COLUMN_LOC_KEY + ") ON CONFLICT REPLACE);"; final String SQL_CREATE_LOCATION_TABLE = "CREATE TABLE " + LocationEntry.TABLE_NAME + "(" + LocationEntry._ID + " INTEGER PRIMARY KEY," + LocationEntry.COLUMN_COORD_LAT + " REAL NOT NULL, " + LocationEntry.COLUMN_COORD_LONG + " REAL NOT NULL, " + LocationEntry.COLUMN_LOCATION_SETTING + " TEXT UNIQUE NOT NULL, " + LocationEntry.COLUMN_CITY_NAME + " TEXT NOT NULL );"; sqLiteDatabase.execSQL(SQL_CREATE_LOCATION_TABLE); sqLiteDatabase.execSQL(SQL_CREATE_WEATHER_TABLE); } @Override public void onUpgrade(SQLiteDatabase sqLiteDatabase, int oldVersion, int newVersion) { // This database is only a cache for online data, so its upgrade policy is // to simply to discard the data and start over // Note that this only fires if you change the version number for your database. // It does NOT depend on the version number for your application. // If you want to update the schema without wiping data, commenting out the next 2 lines // should be your top priority before modifying this method. sqLiteDatabase.execSQL("DROP TABLE IF EXISTS " + LocationEntry.TABLE_NAME); sqLiteDatabase.execSQL("DROP TABLE IF EXISTS " + WeatherEntry.TABLE_NAME); onCreate(sqLiteDatabase); } }
{ "content_hash": "f3db7e10accb1e18172f9c295e8a1c45", "timestamp": "", "source": "github", "line_count": 81, "max_line_length": 99, "avg_line_length": 50.01234567901235, "alnum_prop": 0.6393483090594915, "repo_name": "EstalillaJ/SunshineApp-Udacity", "id": "2a5e5ab3f2f73fe8be2567dc70ccb79ef0132abc", "size": "4670", "binary": false, "copies": "1", "ref": "refs/heads/1.01_hello_world", "path": "app/src/main/java/com/example/android/sunshine/app/data/WeatherDbHelper.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "51834" } ], "symlink_target": "" }
__author__ = "Christian Kongsgaard" __license__ = 'MIT' # -------------------------------------------------------------------------------------------------------------------- # # IMPORTS # Modules import os # RiBuild Modules from delphin_6_automation.database_interactions.db_templates import delphin_entry from delphin_6_automation.database_interactions.db_templates import sample_entry from delphin_6_automation.database_interactions.db_templates import material_entry from delphin_6_automation.database_interactions import mongo_setup from delphin_6_automation.database_interactions.auth import auth_dict from delphin_6_automation.database_interactions import simulation_interactions # -------------------------------------------------------------------------------------------------------------------- # # RIBuild if __name__ == "__main__": server = mongo_setup.global_init(auth_dict) material_id = 286 data = material_entry.Material.objects(material_id=material_id).only("material_data.IDENTIFICATION-CATEGORY").first() print(data["material_data"]["IDENTIFICATION-CATEGORY"]) mongo_setup.global_end_ssh(server)
{ "content_hash": "8fe1b0aaabc9430fca71a6638fb0c07c", "timestamp": "", "source": "github", "line_count": 29, "max_line_length": 121, "avg_line_length": 39.44827586206897, "alnum_prop": 0.6136363636363636, "repo_name": "thp44/delphin_6_automation", "id": "1dc0a088275d84c8899b092d0f5eeb47f60960f5", "size": "1144", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "data_process/wp6_run/db_thomas.py", "mode": "33188", "license": "mit", "language": [ { "name": "Python", "bytes": "137563" } ], "symlink_target": "" }
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; namespace BinbinDotNetOpenAuth.Samples.Controllers { public class HomeController : Controller { public ActionResult Index() { ViewBag.Message = "Modify this template to jump-start your ASP.NET MVC application."; return View(); } public ActionResult About() { ViewBag.Message = "Your app description page."; return View(); } public ActionResult Contact() { ViewBag.Message = "Your contact page."; return View(); } } }
{ "content_hash": "da82c21788233640e80fb18566255e0a", "timestamp": "", "source": "github", "line_count": 32, "max_line_length": 97, "avg_line_length": 22.46875, "alnum_prop": 0.5577190542420027, "repo_name": "lotosbin/BinbinDotNetOpenAuthClients", "id": "a0dadb4b3c50e6fc882c6abd359eec98135f748c", "size": "721", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "BinbinDotNetOpenAuth.Samples/Controllers/HomeController.cs", "mode": "33261", "license": "mit", "language": [ { "name": "ASP", "bytes": "120" }, { "name": "C#", "bytes": "135959" }, { "name": "CSS", "bytes": "54254" }, { "name": "HTML", "bytes": "149281" }, { "name": "JavaScript", "bytes": "288" } ], "symlink_target": "" }
require "test/cask/dsl/shared_examples/base" require "test/cask/dsl/shared_examples/staged" describe Cask::DSL::Postflight, :cask do let(:cask) { Cask::CaskLoader.load(cask_path("basic-cask")) } let(:dsl) { described_class.new(cask, FakeSystemCommand) } it_behaves_like Cask::DSL::Base it_behaves_like Cask::Staged do let(:staged) { dsl } end end
{ "content_hash": "84024ae795fd17ec75aa59f42381af9b", "timestamp": "", "source": "github", "line_count": 13, "max_line_length": 63, "avg_line_length": 28, "alnum_prop": 0.7087912087912088, "repo_name": "mahori/brew", "id": "edb411f312c3495667166903a3a2220931aab366", "size": "395", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "Library/Homebrew/test/cask/dsl/postflight_spec.rb", "mode": "33188", "license": "bsd-2-clause", "language": [ { "name": "Dockerfile", "bytes": "1460" }, { "name": "HTML", "bytes": "12438" }, { "name": "PostScript", "bytes": "485" }, { "name": "Roff", "bytes": "72771" }, { "name": "Ruby", "bytes": "2188228" }, { "name": "Shell", "bytes": "124249" }, { "name": "Swift", "bytes": "1788" } ], "symlink_target": "" }
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package edu.columbia.tjw.item.util.random; import edu.columbia.tjw.item.util.ByteTool; import edu.columbia.tjw.item.util.HashTool; import java.security.NoSuchAlgorithmException; import java.security.SecureRandom; import java.util.Random; /** * @author tyler */ public class RandomTool { private static final SecureRandom CORE; static { //Should fix the occasional hang on start glitch. Caused by the linux /dev/random blocking (I still say this // is a bug in Linux). System.setProperty("securerandom.source", "file:/dev/urandom"); CORE = new SecureRandom(); CORE.setSeed(CORE.generateSeed(32)); } private RandomTool() { } public static void main(final String[] args_) { for (int i = 0; i < 100; i++) { final long next = CORE.nextLong(); System.out.println(next + "L, 0x" + Long.toHexString(next) + "L"); } } public synchronized static String randomString(final int length_) { final int longLength = 1 + (length_ / 8); final StringBuilder builder = new StringBuilder(); for (int i = 0; i < longLength; i++) { builder.append(Long.toHexString(CORE.nextLong())); } final String output = builder.substring(0, length_); return output; } public synchronized static double nextDouble() { return CORE.nextDouble(); } /** * @param max_ The max (exclusive) of the range * @return An integer in the range [0, max_), uniformly distributed */ public static int nextInt(final int max_) { return nextInt(max_, CORE); } /** * Generates an integer in the range [0, max_) * * @param max_ The max (exclusive) of the range * @param rand_ The PRNG used to generate these random numbers * @return An integer in the range [0, max_), uniformly distributed */ public static int nextInt(final int max_, final Random rand_) { if (max_ <= 0) { throw new IllegalArgumentException("Max must be positive."); } final double selector = rand_.nextDouble(); final int selected = (int) (selector * max_); return selected; } /** * @param input_ The array to be shuffled */ public static void shuffle(final int[] input_) { shuffle(input_, CORE); } /** * @param input_ The array to be shuffled * @param rand_ The PRNG to use for the shuffle */ public static void shuffle(final int[] input_, final Random rand_) { for (int i = 0; i < input_.length; i++) { final int swapIndex = nextInt(input_.length, rand_); final int a = input_[i]; final int b = input_[swapIndex]; input_[swapIndex] = a; input_[i] = b; } } public synchronized static int nextInt() { final int output = CORE.nextInt(); return output; } public synchronized static byte[] getStrong(final int bytes_) { final byte[] output = new byte[bytes_]; CORE.nextBytes(output); return output; } public static Random getRandom() { return getRandom(PrngType.STANDARD); } public static Random getRandom(final PrngType type_) { final byte[] seed = getStrong(32); final Random output = getRandom(type_, seed); return output; } public static Random getRandom(final PrngType type_, final long seed_) { return getRandom(type_, ByteTool.longToBytes(seed_)); } public static Random getRandom(final PrngType type_, final byte[] seed_) { final byte[] whitened = HashTool.hash(seed_); final Random output; switch (type_) { case STANDARD: output = new Random(ByteTool.bytesToLong(whitened, 0)); break; case SECURE: try { output = SecureRandom.getInstance("SHA1PRNG"); output.setSeed(ByteTool.bytesToLong(whitened, 0)); } catch (final NoSuchAlgorithmException e) { throw new RuntimeException(e); } //output = new SecureRandom(whitened); break; default: throw new IllegalArgumentException("Unknown PRNG type."); } return output; } }
{ "content_hash": "60c52c9083b834fb36c3c8bca393ba39", "timestamp": "", "source": "github", "line_count": 178, "max_line_length": 116, "avg_line_length": 26.640449438202246, "alnum_prop": 0.5700126528890763, "repo_name": "tyward/item", "id": "fc1b7471b6d4426756cabb4c64d8252786d65d57", "size": "4742", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/main/java/edu/columbia/tjw/item/util/random/RandomTool.java", "mode": "33261", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "671675" } ], "symlink_target": "" }
<?php namespace test\o\o; class n { }
{ "content_hash": "523b4a7a228ad7b92b7436a8f0f961a4", "timestamp": "", "source": "github", "line_count": 3, "max_line_length": 19, "avg_line_length": 12.333333333333334, "alnum_prop": 0.6486486486486487, "repo_name": "theosyspe/levent_01", "id": "4471f355ae0da3ae0b9ed1d343257443e4145cf5", "size": "37", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "vendor/ZF2/bin/test/o/o/n.php", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "CSS", "bytes": "1045" }, { "name": "PHP", "bytes": "11366" } ], "symlink_target": "" }
<!DOCTYPE html> <html lang="en"> <head> <title>NSFetchRequest Extension Reference</title> <link rel="stylesheet" type="text/css" href="../css/jazzy.css" /> <link rel="stylesheet" type="text/css" href="../css/highlight.css" /> <meta charset='utf-8'> <script src="../js/jquery.min.js" defer></script> <script src="../js/jazzy.js" defer></script> </head> <body> <a name="//apple_ref/swift/Extension/NSFetchRequest" class="dashAnchor"></a> <a title="NSFetchRequest Extension Reference"></a> <header> <div class="content-wrapper"> <p><a href="../index.html"> Docs</a> (89% documented)</p> </div> </header> <div class="content-wrapper"> <p id="breadcrumbs"> <a href="../index.html"> Reference</a> <img id="carat" src="../img/carat.png" /> NSFetchRequest Extension Reference </p> </div> <div class="content-wrapper"> <nav class="sidebar"> <ul class="nav-groups"> <li class="nav-group-name"> <a href="../Enums.html">Enumerations</a> <ul class="nav-group-tasks"> <li class="nav-group-task"> <a href="../Enums/CoreDataPlusError.html">CoreDataPlusError</a> </li> </ul> </li> <li class="nav-group-name"> <a href="../Extensions.html">Extensions</a> <ul class="nav-group-tasks"> <li class="nav-group-task"> <a href="../Extensions/Collection.html">Collection</a> </li> <li class="nav-group-task"> <a href="../Extensions/NSFetchRequest.html">NSFetchRequest</a> </li> <li class="nav-group-task"> <a href="../Extensions/NSFetchRequestResult.html">NSFetchRequestResult</a> </li> <li class="nav-group-task"> <a href="../Extensions/NSManagedObject.html">NSManagedObject</a> </li> <li class="nav-group-task"> <a href="../Extensions/NSManagedObjectContext.html">NSManagedObjectContext</a> </li> </ul> </li> <li class="nav-group-name"> <a href="../Protocols.html">Protocols</a> <ul class="nav-group-tasks"> <li class="nav-group-task"> <a href="../Protocols/DelayedDeletable.html">DelayedDeletable</a> </li> <li class="nav-group-task"> <a href="../Protocols/FetchConfigurable.html">FetchConfigurable</a> </li> <li class="nav-group-task"> <a href="../Protocols/ModelVersion.html">ModelVersion</a> </li> <li class="nav-group-task"> <a href="../Protocols/RemoteDeletable.html">RemoteDeletable</a> </li> <li class="nav-group-task"> <a href="../Protocols/UpdateTimestampable.html">UpdateTimestampable</a> </li> </ul> </li> </ul> </nav> <article class="main-content"> <section> <section class="section"> <h1>NSFetchRequest</h1> </section> <section class="section task-group-section"> <div class="task-group"> <ul> <li class="item"> <div> <code> <a name="/c:@CM@CoreDataPlus@@objc(cs)NSFetchRequest(im)initWithEntity:predicate:batchSize:"></a> <a name="//apple_ref/swift/Method/init(entity:predicate:batchSize:)" class="dashAnchor"></a> <a class="token" href="#/c:@CM@CoreDataPlus@@objc(cs)NSFetchRequest(im)initWithEntity:predicate:batchSize:">init(entity:predicate:batchSize:)</a> </code> </div> <div class="height-container"> <div class="pointer-container"></div> <section class="section"> <div class="pointer"></div> <div class="abstract"> <p><strong>CoreDataPlus</strong></p> <p>Creates a NSFetchRequest.</p> </div> <div class="declaration"> <h4>Declaration</h4> <div class="language"> <p class="aside-title">Swift</p> <pre class="highlight"><code><span class="kd">public</span> <span class="n">convenience</span> <span class="nf">init</span><span class="p">(</span><span class="nv">entity</span><span class="p">:</span> <span class="kt">NSEntityDescription</span><span class="p">,</span> <span class="nv">predicate</span><span class="p">:</span> <span class="kt">NSPredicate</span><span class="p">?</span> <span class="o">=</span> <span class="kc">nil</span><span class="p">,</span> <span class="nv">batchSize</span><span class="p">:</span> <span class="kt">Int</span> <span class="o">=</span> <span class="mi">0</span><span class="p">)</span></code></pre> </div> </div> <div> <h4>Parameters</h4> <table class="graybox"> <tbody> <tr> <td> <code> <em>entity</em> </code> </td> <td> <div> <p>Core Data entity description.</p> </div> </td> </tr> <tr> <td> <code> <em>predicate</em> </code> </td> <td> <div> <p>Fetch request predicate.</p> </div> </td> </tr> <tr> <td> <code> <em>batchSize</em> </code> </td> <td> <div> <p>Breaks the result set into batches.</p> </div> </td> </tr> </tbody> </table> </div> <div> <h4>Return Value</h4> <p>a <code>new</code> NSFetchRequest.</p> </div> </section> </div> </li> <li class="item"> <div> <code> <a name="/c:@CM@CoreDataPlus@@objc(cs)NSFetchRequest(im)andPredicate:"></a> <a name="//apple_ref/swift/Method/andPredicate(_:)" class="dashAnchor"></a> <a class="token" href="#/c:@CM@CoreDataPlus@@objc(cs)NSFetchRequest(im)andPredicate:">andPredicate(_:)</a> </code> </div> <div class="height-container"> <div class="pointer-container"></div> <section class="section"> <div class="pointer"></div> <div class="abstract"> <p><strong>CoreDataPlus</strong></p> </div> <div class="declaration"> <h4>Declaration</h4> <div class="language"> <p class="aside-title">Swift</p> <pre class="highlight"><code><span class="kd">public</span> <span class="kd">func</span> <span class="nf">andPredicate</span><span class="p">(</span><span class="n">_</span> <span class="nv">predicate</span><span class="p">:</span> <span class="kt">NSPredicate</span><span class="p">)</span></code></pre> </div> </div> <div> <h4>Parameters</h4> <table class="graybox"> <tbody> <tr> <td> <code> <em>predicate</em> </code> </td> <td> <div> <p>A NSPredicate object. Associates to <code>self</code> a <code>new</code> compound NSPredicate formed by <strong>AND</strong>-ing the current predicate with a given <code>predicate</code>.</p> </div> </td> </tr> </tbody> </table> </div> </section> </div> </li> <li class="item"> <div> <code> <a name="/c:@CM@CoreDataPlus@@objc(cs)NSFetchRequest(im)orPredicate:"></a> <a name="//apple_ref/swift/Method/orPredicate(_:)" class="dashAnchor"></a> <a class="token" href="#/c:@CM@CoreDataPlus@@objc(cs)NSFetchRequest(im)orPredicate:">orPredicate(_:)</a> </code> </div> <div class="height-container"> <div class="pointer-container"></div> <section class="section"> <div class="pointer"></div> <div class="abstract"> <p><strong>CoreDataPlus</strong></p> </div> <div class="declaration"> <h4>Declaration</h4> <div class="language"> <p class="aside-title">Swift</p> <pre class="highlight"><code><span class="kd">public</span> <span class="kd">func</span> <span class="nf">orPredicate</span><span class="p">(</span><span class="n">_</span> <span class="nv">predicate</span><span class="p">:</span> <span class="kt">NSPredicate</span><span class="p">)</span></code></pre> </div> </div> <div> <h4>Parameters</h4> <table class="graybox"> <tbody> <tr> <td> <code> <em>predicate</em> </code> </td> <td> <div> <p>A NSPredicate object. Associates to <code>self</code> a <code>new</code> compound NSPredicate formed by <strong>OR</strong>-ing the current predicate with a given <code>predicate</code>.</p> </div> </td> </tr> </tbody> </table> </div> </section> </div> </li> <li class="item"> <div> <code> <a name="/c:@CM@CoreDataPlus@@objc(cs)NSFetchRequest(im)addSortDescriptors:"></a> <a name="//apple_ref/swift/Method/addSortDescriptors(_:)" class="dashAnchor"></a> <a class="token" href="#/c:@CM@CoreDataPlus@@objc(cs)NSFetchRequest(im)addSortDescriptors:">addSortDescriptors(_:)</a> </code> </div> <div class="height-container"> <div class="pointer-container"></div> <section class="section"> <div class="pointer"></div> <div class="abstract"> <p><strong>CoreDataPlus</strong></p> </div> <div class="declaration"> <h4>Declaration</h4> <div class="language"> <p class="aside-title">Swift</p> <pre class="highlight"><code><span class="kd">public</span> <span class="kd">func</span> <span class="nf">addSortDescriptors</span><span class="p">(</span><span class="n">_</span> <span class="nv">descriptors</span><span class="p">:</span> <span class="p">[</span><span class="kt">NSSortDescriptor</span><span class="p">])</span></code></pre> </div> </div> <div> <h4>Parameters</h4> <table class="graybox"> <tbody> <tr> <td> <code> <em>descriptors</em> </code> </td> <td> <div> <p>An array of NSSortDescriptor objects. Appends to the current sort descriptors an array of <code>descriptors</code>.</p> </div> </td> </tr> </tbody> </table> </div> </section> </div> </li> </ul> </div> </section> </section> <section id="footer"> <p>&copy; 2017 <a class="link" href="" target="_blank" rel="external"></a>. All rights reserved. (Last updated: 2017-10-28)</p> <p>Generated by <a class="link" href="https://github.com/realm/jazzy" target="_blank" rel="external">jazzy ♪♫ v0.8.4</a>, a <a class="link" href="http://realm.io" target="_blank" rel="external">Realm</a> project.</p> </section> </article> </div> </body> </div> </html>
{ "content_hash": "8d6f74430693bd5f352dd8559b4d1e41", "timestamp": "", "source": "github", "line_count": 318, "max_line_length": 664, "avg_line_length": 46.484276729559745, "alnum_prop": 0.3960898389933703, "repo_name": "tinrobots/CoreDataPlus", "id": "078349b21d881e75ac97316e284d046401b02f4c", "size": "14786", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "docs/docsets/.docset/Contents/Resources/Documents/Extensions/NSFetchRequest.html", "mode": "33188", "license": "mit", "language": [ { "name": "Objective-C", "bytes": "1507" }, { "name": "Ruby", "bytes": "836" }, { "name": "Swift", "bytes": "416957" } ], "symlink_target": "" }
\input{front.tex} \input{doc.tex} \input{back.tex}
{ "content_hash": "d241d7b4683e768d47e09bf6396d5013", "timestamp": "", "source": "github", "line_count": 3, "max_line_length": 17, "avg_line_length": 16.666666666666668, "alnum_prop": 0.72, "repo_name": "mvhaen/Murdoc", "id": "d187eb8404c0c9c9820d5ffb8bbaac1892d41bb3", "size": "50", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "templates/latex/main.tex", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "91684" }, { "name": "HTML", "bytes": "1376" }, { "name": "JavaScript", "bytes": "15189" }, { "name": "Ruby", "bytes": "2843" }, { "name": "TeX", "bytes": "2706" } ], "symlink_target": "" }
<!DOCTYPE html><html lang="en"> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <meta name="viewport" content="width=device-width; initial-scale=1.0; maximum-scale=1.0; user-scalable=0;"> <meta charset="utf-8"> <title>phpDocumentor » SelfService\Entity\Provisionable\MetaInputs</title> <meta name="author" content="Mike van Riel"> <meta name="description" content=""> <link href="../css/template.css" rel="stylesheet" media="all"> <script src="../js/jquery-1.7.1.min.js" type="text/javascript"></script><script src="../js/jquery-ui-1.8.2.custom.min.js" type="text/javascript"></script><script src="../js/jquery.mousewheel.min.js" type="text/javascript"></script><script src="../js/bootstrap.js" type="text/javascript"></script><script src="../js/template.js" type="text/javascript"></script><script src="../js/prettify/prettify.min.js" type="text/javascript"></script><link rel="shortcut icon" href="../img/favicon.ico"> <link rel="apple-touch-icon" href="../img/apple-touch-icon.png"> <link rel="apple-touch-icon" sizes="72x72" href="../img/apple-touch-icon-72x72.png"> <link rel="apple-touch-icon" sizes="114x114" href="../img/apple-touch-icon-114x114.png"> </head> <body> <div class="navbar navbar-fixed-top"> <div class="navbar-inner"><div class="container"> <a class="btn btn-navbar" data-toggle="collapse" data-target=".nav-collapse"><span class="icon-bar"></span><span class="icon-bar"></span><span class="icon-bar"></span></a><a class="brand" href="../index.html">phpDocumentor</a><div class="nav-collapse"><ul class="nav"> <li class="dropdown"> <a href="#api" class="dropdown-toggle" data-toggle="dropdown"> API Documentation <b class="caret"></b></a><ul class="dropdown-menu"> <li><a>Namespaces</a></li> <li><a href="../namespaces/SelfService.html"><i class="icon-th"></i> SelfService</a></li> <li><a href="../namespaces/SelfServiceTest.html"><i class="icon-th"></i> SelfServiceTest</a></li> <li><a href="../namespaces/global.html"><i class="icon-th"></i> global</a></li> </ul> </li> <li class="dropdown" id="charts-menu"> <a href="#charts" class="dropdown-toggle" data-toggle="dropdown"> Charts <b class="caret"></b></a><ul class="dropdown-menu"><li><a href="../graph_class.html"><i class="icon-list-alt"></i> Class hierarchy diagram</a></li></ul> </li> <li class="dropdown" id="reports-menu"> <a href="#reports" class="dropdown-toggle" data-toggle="dropdown"> Reports <b class="caret"></b></a><ul class="dropdown-menu"> <li><a href="../errors.html"><i class="icon-remove-sign"></i> Errors  <span class="label label-info">440</span></a></li> <li><a href="../markers.html"><i class="icon-map-marker"></i> Markers  <ul><li>todo  <span class="label label-info">1</span> </li></ul></a></li> <li><a href="../deprecated.html"><i class="icon-stop"></i> Deprecated elements  <span class="label label-info">0</span></a></li> </ul> </li> </ul></div> </div></div> <div class="go_to_top"><a href="#___" style="color: inherit">Back to top  <i class="icon-upload icon-white"></i></a></div> </div> <div id="___" class="container"> <noscript><div class="alert alert-warning"> Javascript is disabled; several features are only available if Javascript is enabled. </div></noscript> <div class="row"> <div class="span4"> <div class="btn-group view pull-right" data-toggle="buttons-radio"> <button class="btn details" title="Show descriptions and method names"><i class="icon-list"></i></button><button class="btn simple" title="Show only method names"><i class="icon-align-justify"></i></button> </div> <ul class="side-nav nav nav-list"> <li class="nav-header"> <i class="icon-map-marker"></i> Namespaces</li> <li> <a href="../namespaces/SelfService.Entity.Provisionable.MetaInputs.html" title="MetaInputs"><i class="icon-th"></i>MetaInputs</a><ul class="nav nav-list nav-namespaces"></ul> </li> </ul> </div> <div class="span8 namespace-contents"> <ul class="breadcrumb"> <li> <a href="../index.html"><i class="icon-th"></i></a><span class="divider">\</span> </li> <li><a href="../namespaces/SelfService.html">SelfService</a></li> <li> <span class="divider">\</span><a href="../namespaces/SelfService.Entity.html">Entity</a> </li> <li> <span class="divider">\</span><a href="../namespaces/SelfService.Entity.Provisionable.html">Provisionable</a> </li> <li class="active"> <span class="divider">\</span><a href="../namespaces/SelfService.Entity.Provisionable.MetaInputs.html">MetaInputs</a> </li> </ul> <div class="namespace-indent"> <h3> <i class="icon-custom icon-class"></i> Classes and interfaces</h3> <div id="CloudProductMetaInput" class="element ajax clickable class"> <h1>CloudProductMetaInput<a href="../classes/SelfService.Entity.Provisionable.MetaInputs.CloudProductMetaInput.html">¶</a> </h1> <p class="short_description"></p> <div class="details collapse"></div> <a href="../classes/SelfService.Entity.Provisionable.MetaInputs.CloudProductMetaInput.html" class="more">« More »</a> </div> <div id="InputProductMetaInput" class="element ajax clickable class"> <h1>InputProductMetaInput<a href="../classes/SelfService.Entity.Provisionable.MetaInputs.InputProductMetaInput.html">¶</a> </h1> <p class="short_description">An</p> <div class="details collapse"></div> <a href="../classes/SelfService.Entity.Provisionable.MetaInputs.InputProductMetaInput.html" class="more">« More »</a> </div> <div id="InstanceTypeProductMetaInput" class="element ajax clickable class"> <h1>InstanceTypeProductMetaInput<a href="../classes/SelfService.Entity.Provisionable.MetaInputs.InstanceTypeProductMetaInput.html">¶</a> </h1> <p class="short_description"></p> <div class="details collapse"></div> <a href="../classes/SelfService.Entity.Provisionable.MetaInputs.InstanceTypeProductMetaInput.html" class="more">« More »</a> </div> <div id="NumberProductMetaInput" class="element ajax clickable class"> <h1>NumberProductMetaInput<a href="../classes/SelfService.Entity.Provisionable.MetaInputs.NumberProductMetaInput.html">¶</a> </h1> <p class="short_description"></p> <div class="details collapse"></div> <a href="../classes/SelfService.Entity.Provisionable.MetaInputs.NumberProductMetaInput.html" class="more">« More »</a> </div> <div id="ProductMetaInputBase" class="element ajax clickable class"> <h1>ProductMetaInputBase<a href="../classes/SelfService.Entity.Provisionable.MetaInputs.ProductMetaInputBase.html">¶</a> </h1> <p class="short_description"></p> <div class="details collapse"></div> <a href="../classes/SelfService.Entity.Provisionable.MetaInputs.ProductMetaInputBase.html" class="more">« More »</a> </div> <div id="TextProductMetaInput" class="element ajax clickable class"> <h1>TextProductMetaInput<a href="../classes/SelfService.Entity.Provisionable.MetaInputs.TextProductMetaInput.html">¶</a> </h1> <p class="short_description"></p> <div class="details collapse"></div> <a href="../classes/SelfService.Entity.Provisionable.MetaInputs.TextProductMetaInput.html" class="more">« More »</a> </div> </div> </div> </div> <div class="row"><footer class="span12"> Template is built using <a href="http://twitter.github.com/bootstrap/">Twitter Bootstrap 2</a> and icons provided by <a href="http://glyphicons.com/">Glyphicons</a>.<br> Documentation is powered by <a href="http://www.phpdoc.org/">phpDocumentor 2.0.0a12</a> and<br> generated on 2013-04-04T20:59:28-07:00.<br></footer></div> </div> </body> </html>
{ "content_hash": "80eeb2afa83357cac88dff666379f311", "timestamp": "", "source": "github", "line_count": 137, "max_line_length": 489, "avg_line_length": 55.605839416058394, "alnum_prop": 0.6856130217904962, "repo_name": "rgeyer/rs_selfservice", "id": "cb2e96a609ae939023c7de81c438e129b99a5769", "size": "7650", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "docs/namespaces/SelfService.Entity.Provisionable.MetaInputs.html", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "181339" }, { "name": "JavaScript", "bytes": "93856" }, { "name": "PHP", "bytes": "581460" }, { "name": "Python", "bytes": "529" }, { "name": "Ruby", "bytes": "4551" }, { "name": "Shell", "bytes": "1190" } ], "symlink_target": "" }
<?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:id="@+id/activity_main" android:layout_width="match_parent" android:layout_height="match_parent" android:paddingBottom="@dimen/activity_vertical_margin" android:paddingLeft="@dimen/activity_horizontal_margin" android:paddingRight="@dimen/activity_horizontal_margin" android:paddingTop="@dimen/activity_vertical_margin" android:background="#303030" tools:context="com.moctavio.app.bluetoothcontroller.MainActivity"> <TextView android:id="@+id/textStatus" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Status : Not connected" android:textSize="12sp" android:textColor="#dcdcdc" android:layout_alignParentBottom="true" android:layout_alignStart="@+id/linearLayout1" /> <RelativeLayout android:id="@+id/layout_joystick" android:layout_width="250dp" android:layout_height="250dp" android:background="@drawable/joystick_area" android:layout_marginEnd="71dp" android:layout_centerVertical="true" android:layout_alignParentEnd="true"> <RelativeLayout android:id="@+id/layout_logo" android:layout_width="30dp" android:layout_height="30dp" android:background="@drawable/logo" android:layout_marginRight="10dp" android:layout_centerVertical="true" android:layout_centerHorizontal="true"> </RelativeLayout> </RelativeLayout> <LinearLayout android:id="@+id/linearLayout1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:orientation="vertical" android:layout_marginLeft="39dp" android:layout_marginStart="76dp" android:layout_centerVertical="true" android:layout_alignParentStart="true"> <TextView android:id="@+id/textView1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentLeft="true" android:layout_alignParentTop="true" android:text="X:" android:textColor="#dcdcdc" android:textSize="20dp" /> <TextView android:id="@+id/textView2" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentLeft="true" android:layout_below="@+id/textView1" android:text="Y:" android:textColor="#dcdcdc" android:textSize="20dp" /> <TextView android:id="@+id/textView3" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentLeft="true" android:layout_below="@+id/textView2" android:text="Angle:" android:textColor="#dcdcdc" android:textSize="20dp" /> <TextView android:id="@+id/textView4" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentLeft="true" android:layout_below="@+id/textView3" android:text="Distance:" android:textColor="#dcdcdc" android:textSize="20dp" /> <TextView android:id="@+id/textView5" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentLeft="true" android:layout_below="@+id/textView3" android:text="Direction:" android:textColor="#dcdcdc" android:textSize="20dp" /> </LinearLayout> </RelativeLayout>
{ "content_hash": "96ec94595668fd0d512c1f4a8994a805", "timestamp": "", "source": "github", "line_count": 101, "max_line_length": 74, "avg_line_length": 39, "alnum_prop": 0.6169078446306169, "repo_name": "MOctavio/BluetoothJoystickController", "id": "7f003973b44ea5cecd50bcca95f0474d036c79c9", "size": "3939", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "app/src/main/res/layout-land/activity_main.xml", "mode": "33188", "license": "mit", "language": [ { "name": "Java", "bytes": "16673" } ], "symlink_target": "" }
package org.compass.core.lucene.util; import java.io.IOException; import java.util.ArrayList; import org.apache.lucene.document.Document; import org.apache.lucene.index.Term; import org.apache.lucene.index.TermEnum; import org.apache.lucene.index.TermFreqVector; import org.apache.lucene.search.Filter; import org.apache.lucene.search.Query; import org.apache.lucene.store.Directory; import org.compass.core.Compass; import org.compass.core.CompassHits; import org.compass.core.CompassQuery; import org.compass.core.CompassQueryFilter; import org.compass.core.CompassSession; import org.compass.core.Resource; import org.compass.core.engine.SearchEngineException; import org.compass.core.engine.SearchEngineQuery; import org.compass.core.engine.SearchEngineQueryFilter; import org.compass.core.impl.DefaultCompassHits; import org.compass.core.impl.DefaultCompassQuery; import org.compass.core.impl.DefaultCompassQueryFilter; import org.compass.core.lucene.LuceneResource; import org.compass.core.lucene.engine.LuceneSearchEngineFactory; import org.compass.core.lucene.engine.LuceneSearchEngineHits; import org.compass.core.lucene.engine.LuceneSearchEngineInternalSearch; import org.compass.core.lucene.engine.LuceneSearchEngineQuery; import org.compass.core.lucene.engine.LuceneSearchEngineQueryFilter; import org.compass.core.lucene.engine.analyzer.LuceneAnalyzerManager; import org.compass.core.lucene.engine.manager.LuceneSearchEngineIndexManager; import org.compass.core.spi.InternalCompass; import org.compass.core.spi.InternalCompassQuery; import org.compass.core.spi.InternalCompassSession; import org.compass.core.spi.InternalResource; /** * Allows to create Compass related objects based on external (internally no supported by Compass) * Lucene objects. * * @author kimchy */ public abstract class LuceneHelper { /** * Creates a new {@link CompassQuery} based on a Lucene {@link Query}. * * <p>Allows to create {@link CompassQuery} based on external Lucene {@link Query} that is not supported * by one of Compass query builders. * * @param compass Compass instance * @param query The lucene query to wrap * @return A compass query wrapping the lucene query */ public static CompassQuery createCompassQuery(Compass compass, Query query) { InternalCompass internalCompass = (InternalCompass) compass; SearchEngineQuery searchEngineQuery = new LuceneSearchEngineQuery((LuceneSearchEngineFactory) internalCompass.getSearchEngineFactory(), query); return new DefaultCompassQuery(searchEngineQuery, internalCompass); } /** * Creates a new {@link CompassQuery} based on a Lucene {@link Query}. * * <p>Allows to create {@link CompassQuery} based on external Lucene {@link Query} that is not supported * by one of Compass query builders. * * @param session Compass session * @param query The lucene query to wrap * @return A compass query wrapping the lucene query */ public static CompassQuery createCompassQuery(CompassSession session, Query query) { InternalCompassSession internalCompassSession = (InternalCompassSession) session; SearchEngineQuery searchEngineQuery = new LuceneSearchEngineQuery((LuceneSearchEngineFactory) internalCompassSession.getCompass().getSearchEngineFactory(), query); InternalCompassQuery compassQuery = new DefaultCompassQuery(searchEngineQuery, internalCompassSession.getCompass()); compassQuery.attach(session); return compassQuery; } /** * Returns the underlying {@link LuceneSearchEngineQuery} of the given {@link CompassQuery}. * <p/> * Can be used for example to add custom Sorting using * {@link LuceneSearchEngineQuery#addSort(org.apache.lucene.search.SortField)}, or get the actual lucene query * using {@link org.compass.core.lucene.engine.LuceneSearchEngineQuery#getQuery()}. * * @param query The compass query to extract the lucene search engine query from * @return The lucene search engine query extracted from the compass query */ public static LuceneSearchEngineQuery getLuceneSearchEngineQuery(CompassQuery query) { return (LuceneSearchEngineQuery) ((DefaultCompassQuery) query).getSearchEngineQuery(); } /** * Creates a new {@link CompassQueryFilter} based on a Lucene {@link Filter}. * <p/> * Allows to create {@link CompassQueryFilter} based on external Lucene {@link Filter} that is not supported * by one fo Comapss query filter builders. * * @param session Comapss session * @param filter The lucene filter to wrap * @return A compass query filter wrapping lucene query. */ public static CompassQueryFilter createCompassQueryFilter(CompassSession session, Filter filter) { SearchEngineQueryFilter searchEngineQueryFilter = new LuceneSearchEngineQueryFilter(filter); return new DefaultCompassQueryFilter(searchEngineQueryFilter); } /** * Returns the underlying {@link LuceneSearchEngineQueryFilter} of the given {@link CompassQueryFilter}. * <p/> * Can be used to get the actual Lucene {@link Filter} using * {@link org.compass.core.lucene.engine.LuceneSearchEngineQueryFilter#getFilter()}. * * @param filter The compass query filter to extract the lucene search engine query filter from * @return The lucene search engine query filter extracted from the compass query filter */ public static LuceneSearchEngineQueryFilter getLuceneSearchEngineQueryFilter(CompassQueryFilter filter) { return (LuceneSearchEngineQueryFilter) ((DefaultCompassQueryFilter) filter).getFilter(); } /** * Returns the underlying {@link LuceneSearchEngineHits} of the given {@link CompassHits}. * <p/> * Used mainly to access the actual Lucene {@link org.apache.lucene.search.Hits}, or get * Lucene {@link org.apache.lucene.search.Explanation}. */ public static LuceneSearchEngineHits getLuceneSearchEngineHits(CompassHits hits) { return (LuceneSearchEngineHits) ((DefaultCompassHits) hits).getSearchEngineHits(); } /** * Returns Compass own internal <code>LuceneAnalyzerManager</code>. Can be used * to access Lucene {@link org.apache.lucene.analysis.Analyzer} at runtime. */ public static LuceneAnalyzerManager getLuceneAnalyzerManager(Compass compass) { return ((LuceneSearchEngineFactory) ((InternalCompass) compass).getSearchEngineFactory()).getAnalyzerManager(); } /** * Returns the given search engine "internals" used for search. For Lucene, returns * {@link LuceneSearchEngineInternalSearch} which allows to access Lucene * {@link org.apache.lucene.index.IndexReader} and {@link org.apache.lucene.search.Searcher}. * <p/> * The search intenrals will be ones that are executed against the whole index. In order to search on * specific aliases or sub indexes, please use {@link #getLuceneInternalSearch(org.compass.core.CompassSession,String[],String[])} . * * @param session A compass session within a transaction * @return Lucene search "internals" */ public static LuceneSearchEngineInternalSearch getLuceneInternalSearch(CompassSession session) { return (LuceneSearchEngineInternalSearch) ((InternalCompassSession) session).getSearchEngine().internalSearch(null, null); } /** * Returns the given search engine "internals" used for search. For Lucene, returns * {@link LuceneSearchEngineInternalSearch} which allows to access Lucene * {@link org.apache.lucene.index.IndexReader} and {@link org.apache.lucene.search.Searcher}. * <p/> * The search can be narrowed down to specific sub indexes or aliases. A <code>null</code> value * means all the sub indexes/aliases. * * @param session A compass sessino within a transaction * @param subIndexes A set of sub indexes to narrow down the index scope * @param aliases A set of aliases to narrow down the index scope * @return Lucene search "internals" */ public static LuceneSearchEngineInternalSearch getLuceneInternalSearch(CompassSession session, String[] subIndexes, String[] aliases) { return (LuceneSearchEngineInternalSearch) ((InternalCompassSession) session).getSearchEngine().internalSearch(subIndexes, aliases); } /** * Returns the actual Lucene {@link Document} that the {@link Resource} wraps. * * @param resource The resource to get the document from * @return The Lucene document that resource wraps */ public static Document getDocument(Resource resource) { return ((LuceneResource) resource).getDocument(); } /** * Returns Lucene {@link TermFreqVector} using the given Compass session and {@link Resource}. * * @param session Compass session * @param resource The resource to get the term freq vector for * @return The term infos freq vector for the given resource * @throws SearchEngineException */ public static TermFreqVector[] getTermFreqVectors(CompassSession session, Resource resource) throws SearchEngineException { resource = ((InternalCompassSession) session).getResourceByIdResourceNoCache(resource); String subIndex = ((InternalResource) resource).getSubIndex(); LuceneSearchEngineInternalSearch internalSearch = getLuceneInternalSearch(session, new String[]{subIndex}, null); try { return internalSearch.getReader().getTermFreqVectors(((LuceneResource) resource).getDocNum()); } catch (IOException e) { throw new SearchEngineException("Failed to fetch term info for resource [" + resource + "]", e); } } /** * Returns Lucene {@link TermFreqVector} for the given property and resource, using the session. * * @param session Compass session * @param resource The resource to get the term freq vector for * @param propertyName Theh property name (Lucene field name) to get the term freq vector for * @return Teh term info freq vector for the given resource and property * @throws SearchEngineException */ public static TermFreqVector getTermFreqVector(CompassSession session, Resource resource, String propertyName) throws SearchEngineException { resource = ((InternalCompassSession) session).getResourceByIdResourceNoCache(resource); String subIndex = ((InternalResource) resource).getSubIndex(); LuceneSearchEngineInternalSearch internalSearch = getLuceneInternalSearch(session, new String[]{subIndex}, null); try { return internalSearch.getReader().getTermFreqVector(((LuceneResource) resource).getDocNum(), propertyName); } catch (IOException e) { throw new SearchEngineException("Failed to fetch term info for resource [" + resource + "]", e); } } /** * Returns the lucene {@link org.apache.lucene.store.Directory} associated with the given sub index. */ public static Directory getDirectory(Compass compass, String subIndex) { return ((LuceneSearchEngineIndexManager) ((InternalCompass) compass).getSearchEngineIndexManager()).getStore().openDirectory(subIndex); } /** * Returns all the values of for the given propery name. */ public static String[] findPropertyValues(CompassSession session, String propertyName) throws SearchEngineException { LuceneSearchEngineInternalSearch internalSearch = getLuceneInternalSearch(session); ArrayList<String> list = new ArrayList<String>(); try { TermEnum te = internalSearch.getReader().terms(new Term(propertyName, "")); while (propertyName.equals(te.term().field())) { String value = te.term().text(); list.add(value); if (!te.next()) { break; } } } catch (IOException e) { throw new SearchEngineException("Failed to read property values for property [" + propertyName + "]"); } return list.toArray(new String[list.size()]); } }
{ "content_hash": "9ca7a309591ccf34a23280c3ca432b35", "timestamp": "", "source": "github", "line_count": 254, "max_line_length": 143, "avg_line_length": 48.488188976377955, "alnum_prop": 0.7213380967846703, "repo_name": "guaxinim/compass", "id": "310cd9e145b11a47835298432a21621cc3cf98fb", "size": "12936", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/main/src/org/compass/core/lucene/util/LuceneHelper.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "6950075" } ], "symlink_target": "" }
// Copyright 2017 DAIMTO ([Linda Lawton](https://twitter.com/LindaLawtonDK)) : [www.daimto.com](http://www.daimto.com/) // // 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. //------------------------------------------------------------------------------ // <auto-generated> // This code was generated by DAIMTO-Google-apis-Sample-generator 1.0.0 // Template File Name: Oauth2Authentication.tt // Build date: 2017-10-08 // C# generater version: 1.0.0 // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ // About // // Unoffical sample for the Bigquery v2 API for C#. // This sample is designed to be used with the Google .Net client library. (https://github.com/google/google-api-dotnet-client) // // API Description: A data platform for customers to create, manage, share and query data. // API Documentation Link https://cloud.google.com/bigquery/ // // Discovery Doc https://www.googleapis.com/discovery/v1/apis/Bigquery/v2/rest // //------------------------------------------------------------------------------ // Installation // // This sample code uses the Google .Net client library (https://github.com/google/google-api-dotnet-client) // // NuGet package: // // Location: https://www.nuget.org/packages/Google.Apis.Bigquery.v2/ // Install Command: PM> Install-Package Google.Apis.Bigquery.v2 // //------------------------------------------------------------------------------ using Google.Apis.Auth.OAuth2; using Google.Apis.Bigquery.v2; using Google.Apis.Services; using Google.Apis.Util.Store; using System; using System.IO; using System.Threading; namespace GoogleSamplecSharpSample.Bigqueryv2.Auth { public static class Oauth2Example { /// <summary> /// ** Installed Aplication only ** /// This method requests Authentcation from a user using Oauth2. /// </summary> /// <param name="clientSecretJson">Path to the client secret json file from Google Developers console.</param> /// <param name="userName">Identifying string for the user who is being authentcated.</param> /// <param name="scopes">Array of Google scopes</param> /// <returns>BigqueryService used to make requests against the Bigquery API</returns> public static BigqueryService GetBigqueryService(string clientSecretJson, string userName, string[] scopes) { try { if (string.IsNullOrEmpty(userName)) throw new ArgumentNullException("userName"); if (string.IsNullOrEmpty(clientSecretJson)) throw new ArgumentNullException("clientSecretJson"); if (!File.Exists(clientSecretJson)) throw new Exception("clientSecretJson file does not exist."); var cred = GetUserCredential(clientSecretJson, userName, scopes); return GetService(cred); } catch (Exception ex) { throw new Exception("Get Bigquery service failed.", ex); } } /// <summary> /// ** Installed Aplication only ** /// This method requests Authentcation from a user using Oauth2. /// Credentials are stored in System.Environment.SpecialFolder.Personal /// Documentation https://developers.google.com/accounts/docs/OAuth2 /// </summary> /// <param name="clientSecretJson">Path to the client secret json file from Google Developers console.</param> /// <param name="userName">Identifying string for the user who is being authentcated.</param> /// <param name="scopes">Array of Google scopes</param> /// <returns>authencated UserCredential</returns> private static UserCredential GetUserCredential(string clientSecretJson, string userName, string[] scopes) { try { if (string.IsNullOrEmpty(userName)) throw new ArgumentNullException("userName"); if (string.IsNullOrEmpty(clientSecretJson)) throw new ArgumentNullException("clientSecretJson"); if (!File.Exists(clientSecretJson)) throw new Exception("clientSecretJson file does not exist."); // These are the scopes of permissions you need. It is best to request only what you need and not all of them using (var stream = new FileStream(clientSecretJson, FileMode.Open, FileAccess.Read)) { string credPath = System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal); credPath = Path.Combine(credPath, ".credentials/", System.Reflection.Assembly.GetExecutingAssembly().GetName().Name); // Requesting Authentication or loading previously stored authentication for userName var credential = GoogleWebAuthorizationBroker.AuthorizeAsync(GoogleClientSecrets.Load(stream).Secrets, scopes, userName, CancellationToken.None, new FileDataStore(credPath, true)).Result; credential.GetAccessTokenForRequestAsync(); return credential; } } catch (Exception ex) { throw new Exception("Get user credentials failed.", ex); } } /// <summary> /// This method get a valid service /// </summary> /// <param name="credential">Authecated user credentail</param> /// <returns>BigqueryService used to make requests against the Bigquery API</returns> private static BigqueryService GetService(UserCredential credential) { try { if (credential == null) throw new ArgumentNullException("credential"); // Create Bigquery API service. return new BigqueryService(new BaseClientService.Initializer() { HttpClientInitializer = credential, ApplicationName = "Bigquery Oauth2 Authentication Sample" }); } catch (Exception ex) { throw new Exception("Get Bigquery service failed.", ex); } } } }
{ "content_hash": "20849c83142c6aacd163585f104f4c3a", "timestamp": "", "source": "github", "line_count": 153, "max_line_length": 140, "avg_line_length": 47.588235294117645, "alnum_prop": 0.5793160280181294, "repo_name": "LindaLawton/Google-Dotnet-Samples", "id": "1117f4a8623046566373bdebd272ad760df2ad3c", "size": "7283", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "Samples/BigQuery API/v2/Oauth2Authentication.cs", "mode": "33188", "license": "apache-2.0", "language": [], "symlink_target": "" }
package org.apache.pluto.testsuite.test; import java.util.Enumeration; import java.util.HashMap; import java.util.Map; import javax.portlet.PortletRequest; import org.apache.pluto.testsuite.TestResult; import org.apache.pluto.testsuite.TestUtils; /** */ public class RenderParameterTest extends AbstractReflectivePortletTest { private static final String ACTION_KEY = "org.apache.pluto.testsuite.PARAM_ACTION_KEY"; private static final String RENDER_KEY = "org.apache.pluto.testsuite.PARAM_RENDER_KEY"; private static final String RENDER_VALUE = "org.apache.pluto.testsuite.RENDER_VALUE"; public Map<String, String[]> getRenderParameters(PortletRequest request) { Map<String, String[]> parameterMap = new HashMap<String, String[]>(); parameterMap.put(RENDER_KEY, new String[] { RENDER_VALUE }); return parameterMap; } // Test Methods ------------------------------------------------------------ protected TestResult checkActionParametersNotHere(PortletRequest request) { TestResult result = new TestResult(); result.setDescription("Ensure that action parameters are not available " + "in the following render request."); String value = request.getParameter(ACTION_KEY); if (value == null) { result.setReturnCode(TestResult.PASSED); } else { TestUtils.failOnAssertion("parameter", value, null, result); } return result; } protected TestResult checkRenderParameterValue(PortletRequest request) { TestResult result = new TestResult(); result.setDescription("Ensure that render parameters set in action " + "response are available in the following render request."); String value = request.getParameter(RENDER_KEY); if (RENDER_VALUE.equals(value)) { result.setReturnCode(TestResult.PASSED); } else { TestUtils.failOnAssertion("parameter", value, RENDER_VALUE, result); } return result; } protected TestResult checkRenderParameterValues(PortletRequest request) { TestResult result = new TestResult(); result.setDescription("Ensure that render parameters set in action " + "response are available in the following render request."); String[] values = request.getParameterValues(RENDER_KEY); if (values != null && values.length == 1 && RENDER_VALUE.equals(values[0])) { result.setReturnCode(TestResult.PASSED); } else { TestUtils.failOnAssertion("parameter values", values, new String[] { RENDER_VALUE }, result); } return result; } protected TestResult checkParameterMap(PortletRequest request) { TestResult result = new TestResult(); result.setDescription("Ensure that render request returns the correct " + "parameter map."); Map<String, String[]> parameterMap = request.getParameterMap(); String[] values = (String[]) parameterMap.get(RENDER_KEY); if (values != null && values.length == 1 && RENDER_VALUE.equals(values[0]) && !parameterMap.containsKey(ACTION_KEY)) { result.setReturnCode(TestResult.PASSED); } else { if (parameterMap.containsKey(ACTION_KEY)) { result.setReturnCode(TestResult.FAILED); result.setResultMessage("Action parameter " + ACTION_KEY + " was found in render request with value(s): " + parameterMap.get(ACTION_KEY)); } else { TestUtils.failOnAssertion("parameter values", values, new String[] { RENDER_VALUE }, result); } } return result; } protected TestResult checkParameterNames(PortletRequest request) { TestResult result = new TestResult(); result.setDescription("Ensure that render request returns the correct " + "parameter names enumeration."); boolean hasActionParameter = false; boolean hasRenderParameter = false; for (Enumeration<String> en = request.getParameterNames(); en.hasMoreElements(); ) { String name = en.nextElement(); if (ACTION_KEY.equals(name)) { hasActionParameter = true; } if (RENDER_KEY.equals(name)) { hasRenderParameter = true; } } if (!hasActionParameter && hasRenderParameter) { result.setReturnCode(TestResult.PASSED); } else { result.setReturnCode(TestResult.FAILED); StringBuffer buffer = new StringBuffer(); if (!hasRenderParameter) { buffer.append("Render parameter not found. "); } if (!hasActionParameter) { buffer.append("Action parameter found. "); } result.setResultMessage(buffer.toString()); } return result; } }
{ "content_hash": "cd5baa9b7f6d40fc272d2ea226bf03d5", "timestamp": "", "source": "github", "line_count": 135, "max_line_length": 91, "avg_line_length": 36.785185185185185, "alnum_prop": 0.6270640354409988, "repo_name": "apache/portals-pluto", "id": "144550c2f40bbae47aa6c21821d840da629c4dcd", "size": "5768", "binary": false, "copies": "3", "ref": "refs/heads/master", "path": "pluto-testsuite/src/main/java/org/apache/pluto/testsuite/test/RenderParameterTest.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Batchfile", "bytes": "898" }, { "name": "CSS", "bytes": "38272" }, { "name": "HTML", "bytes": "17705" }, { "name": "Java", "bytes": "16436890" }, { "name": "JavaScript", "bytes": "629755" }, { "name": "XSLT", "bytes": "14962" } ], "symlink_target": "" }
<?xml version="1.0" encoding="utf-8"?> <doctrine-mapping xmlns="http://doctrine-project.org/schemas/orm/doctrine-mapping" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://doctrine-project.org/schemas/orm/doctrine-mapping http://doctrine-project.org/schemas/orm/doctrine-mapping.xsd"> <entity repository-class="AppBundle\Repository\DataAttachmentsRepository" name="AppBundle\Entity\DataAttachments" inheritance-type="JOINED"> <discriminator-column name="discr" type="string" /> <discriminator-map> <discriminator-mapping value="company" class="AppBundle\Entity\Company" /> <discriminator-mapping value="afterCourse" class="AppBundle\Entity\AfterCourse" /> <discriminator-mapping value="tutor" class="AppBundle\Entity\Tutor" /> </discriminator-map> <id name="id" type="integer" column="id"> <generator strategy="AUTO"/> </id> <many-to-one target-entity="AppBundle\Entity\Application" field="application" inversed-by="dataAttachments"/> </entity> </doctrine-mapping>
{ "content_hash": "8963edbc114fa6dad88f619bb275a37c", "timestamp": "", "source": "github", "line_count": 17, "max_line_length": 276, "avg_line_length": 61.76470588235294, "alnum_prop": 0.7390476190476191, "repo_name": "jeremiebernard/suivi_alternants", "id": "8606daf8a282e6b14a2131b4799af26afce888c8", "size": "1050", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/AppBundle/Resources/config/doctrine/DataAttachments.orm.xml", "mode": "33188", "license": "mit", "language": [ { "name": "ApacheConf", "bytes": "3605" }, { "name": "CSS", "bytes": "849" }, { "name": "HTML", "bytes": "149227" }, { "name": "JavaScript", "bytes": "1652" }, { "name": "PHP", "bytes": "246333" } ], "symlink_target": "" }
Suppose an array sorted in ascending order is rotated at some pivot unknown to you beforehand. (i.e., [0,0,1,2,2,5,6] might become [2,5,6,0,0,1,2]). You are given a target value to search. If found in the array return true, otherwise return false. ### Example 1: ``` Input: nums = [2,5,6,0,0,1,2], target = 0 Output: true ``` ### Example 2: ``` Input: nums = [2,5,6,0,0,1,2], target = 3 Output: false ``` ### Follow up: - This is a follow up problem to Search in Rotated Sorted Array, where nums may contain duplicates. - Would this affect the run-time complexity? How and why? #Array #Binary Search #Similar questions [#33](../p033m/README.md) [#81](../p081m/README.md) [#153](../p153m/README.md)
{ "content_hash": "462bc3c593a700114fdf21fce5cdf61f", "timestamp": "", "source": "github", "line_count": 28, "max_line_length": 99, "avg_line_length": 25.285714285714285, "alnum_prop": 0.672316384180791, "repo_name": "l33tdaima/l33tdaima", "id": "8116ad1342129689a372dc5278bb17627cea8c3e", "size": "758", "binary": false, "copies": "1", "ref": "refs/heads/main", "path": "p081m/README.md", "mode": "33188", "license": "mit", "language": [ { "name": "C++", "bytes": "214858" }, { "name": "CMake", "bytes": "185" }, { "name": "Go", "bytes": "3918" }, { "name": "JavaScript", "bytes": "357357" }, { "name": "Kotlin", "bytes": "893" }, { "name": "OCaml", "bytes": "11241" }, { "name": "Python", "bytes": "534124" } ], "symlink_target": "" }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. // Code generated by Microsoft (R) AutoRest Code Generator. package com.azure.resourcemanager.mysql.fluent; import com.azure.core.annotation.ReturnType; import com.azure.core.annotation.ServiceMethod; import com.azure.core.http.rest.Response; import com.azure.core.management.polling.PollResult; import com.azure.core.util.Context; import com.azure.core.util.polling.SyncPoller; import com.azure.resourcemanager.mysql.fluent.models.ConfigurationListResultInner; import reactor.core.publisher.Mono; /** An instance of this class provides access to all the operations defined in ServerParametersClient. */ public interface ServerParametersClient { /** * Update a list of configurations in a given server. * * @param resourceGroupName The name of the resource group. The name is case insensitive. * @param serverName The name of the server. * @param value The parameters for updating a list of server configuration. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. * @return a list of server configurations along with {@link Response} on successful completion of {@link Mono}. */ @ServiceMethod(returns = ReturnType.LONG_RUNNING_OPERATION) SyncPoller<PollResult<ConfigurationListResultInner>, ConfigurationListResultInner> beginListUpdateConfigurations( String resourceGroupName, String serverName, ConfigurationListResultInner value); /** * Update a list of configurations in a given server. * * @param resourceGroupName The name of the resource group. The name is case insensitive. * @param serverName The name of the server. * @param value The parameters for updating a list of server configuration. * @param context The context to associate with this operation. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. * @return a list of server configurations along with {@link Response} on successful completion of {@link Mono}. */ @ServiceMethod(returns = ReturnType.LONG_RUNNING_OPERATION) SyncPoller<PollResult<ConfigurationListResultInner>, ConfigurationListResultInner> beginListUpdateConfigurations( String resourceGroupName, String serverName, ConfigurationListResultInner value, Context context); /** * Update a list of configurations in a given server. * * @param resourceGroupName The name of the resource group. The name is case insensitive. * @param serverName The name of the server. * @param value The parameters for updating a list of server configuration. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. * @return a list of server configurations. */ @ServiceMethod(returns = ReturnType.SINGLE) ConfigurationListResultInner listUpdateConfigurations( String resourceGroupName, String serverName, ConfigurationListResultInner value); /** * Update a list of configurations in a given server. * * @param resourceGroupName The name of the resource group. The name is case insensitive. * @param serverName The name of the server. * @param value The parameters for updating a list of server configuration. * @param context The context to associate with this operation. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. * @return a list of server configurations. */ @ServiceMethod(returns = ReturnType.SINGLE) ConfigurationListResultInner listUpdateConfigurations( String resourceGroupName, String serverName, ConfigurationListResultInner value, Context context); }
{ "content_hash": "9bb6076839de27d17a822fb7e766545b", "timestamp": "", "source": "github", "line_count": 79, "max_line_length": 117, "avg_line_length": 58.278481012658226, "alnum_prop": 0.7634665508253693, "repo_name": "Azure/azure-sdk-for-java", "id": "aacd5a01462a6c9fe2c1216eef0e6eb2ac5c3ed9", "size": "4604", "binary": false, "copies": "1", "ref": "refs/heads/main", "path": "sdk/mysql/azure-resourcemanager-mysql/src/main/java/com/azure/resourcemanager/mysql/fluent/ServerParametersClient.java", "mode": "33188", "license": "mit", "language": [ { "name": "Batchfile", "bytes": "8762" }, { "name": "Bicep", "bytes": "15055" }, { "name": "CSS", "bytes": "7676" }, { "name": "Dockerfile", "bytes": "2028" }, { "name": "Groovy", "bytes": "3237482" }, { "name": "HTML", "bytes": "42090" }, { "name": "Java", "bytes": "432409546" }, { "name": "JavaScript", "bytes": "36557" }, { "name": "Jupyter Notebook", "bytes": "95868" }, { "name": "PowerShell", "bytes": "737517" }, { "name": "Python", "bytes": "240542" }, { "name": "Scala", "bytes": "1143898" }, { "name": "Shell", "bytes": "18488" }, { "name": "XSLT", "bytes": "755" } ], "symlink_target": "" }
ACCEPTED #### According to The Catalogue of Life, 3rd January 2011 #### Published in null #### Original name null ### Remarks null
{ "content_hash": "15f9662bdfe28fcca6980f0600cc05b4", "timestamp": "", "source": "github", "line_count": 13, "max_line_length": 39, "avg_line_length": 10.307692307692308, "alnum_prop": 0.6940298507462687, "repo_name": "mdoering/backbone", "id": "7ca8b3c101a0563bdef5aebe96c3c221ed77b921", "size": "187", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "life/Plantae/Magnoliophyta/Magnoliopsida/Myrtales/Melastomataceae/Memecylon/Memecylon thouarsianum/README.md", "mode": "33188", "license": "apache-2.0", "language": [], "symlink_target": "" }
require_relative '../../spec_helper' require_relative 'fixtures/classes' describe 'TracePoint#self' do it 'return the trace object from event' do trace = nil TracePoint.new(:line) { |tp| next unless TracePointSpec.target_thread? trace = tp.self }.enable do trace.equal?(self).should be_true end end it 'return the class object from a class event' do trace = nil TracePoint.new(:class) { |tp| next unless TracePointSpec.target_thread? trace = tp.self }.enable do class TracePointSpec::C end end trace.should equal TracePointSpec::C end end
{ "content_hash": "b2d3553280434524f4e10e20100481c1", "timestamp": "", "source": "github", "line_count": 26, "max_line_length": 52, "avg_line_length": 24.115384615384617, "alnum_prop": 0.6555023923444976, "repo_name": "nobu/rubyspec", "id": "2098860e59221ddec4be4e53368b22a6b4486d9e", "size": "627", "binary": false, "copies": "4", "ref": "refs/heads/master", "path": "core/tracepoint/self_spec.rb", "mode": "33188", "license": "mit", "language": [ { "name": "C", "bytes": "145966" }, { "name": "Ruby", "bytes": "6187303" }, { "name": "Shell", "bytes": "65" } ], "symlink_target": "" }
/* * angular-loading-bar * * intercepts XHR requests and creates a loading bar. * Based on the excellent nprogress work by rstacruz (more info in readme) * * (c) 2013 Wes Cruver * License: MIT */ (function() { 'use strict'; // Alias the loading bar for various backwards compatibilities since the project has matured: angular.module('angular-loading-bar', ['cfp.loadingBarInterceptor']); angular.module('chieffancypants.loadingBar', ['cfp.loadingBarInterceptor']); /** * loadingBarInterceptor service * * Registers itself as an Angular interceptor and listens for XHR requests. */ angular.module('cfp.loadingBarInterceptor', ['cfp.loadingBar']) .config(['$httpProvider', function ($httpProvider) { var interceptor = ['$q', '$cacheFactory', '$timeout', '$rootScope', '$log', 'cfpLoadingBar', function ($q, $cacheFactory, $timeout, $rootScope, $log, cfpLoadingBar) { /** * The total number of requests made */ var reqsTotal = 0; /** * The number of requests completed (either successfully or not) */ var reqsCompleted = 0; /** * The amount of time spent fetching before showing the loading bar */ var latencyThreshold = cfpLoadingBar.latencyThreshold; /** * $timeout handle for latencyThreshold */ var startTimeout; /** * calls cfpLoadingBar.complete() which removes the * loading bar from the DOM. */ function setComplete() { $timeout.cancel(startTimeout); cfpLoadingBar.complete(); reqsCompleted = 0; reqsTotal = 0; } /** * Determine if the response has already been cached * @param {Object} config the config option from the request * @return {Boolean} retrns true if cached, otherwise false */ function isCached(config) { var cache; var defaultCache = $cacheFactory.get('$http'); var defaults = $httpProvider.defaults; // Choose the proper cache source. Borrowed from angular: $http service if ((config.cache || defaults.cache) && config.cache !== false && (config.method === 'GET' || config.method === 'JSONP')) { cache = angular.isObject(config.cache) ? config.cache : angular.isObject(defaults.cache) ? defaults.cache : defaultCache; } var cached = cache !== undefined ? cache.get(config.url) !== undefined : false; if (config.cached !== undefined && cached !== config.cached) { return config.cached; } config.cached = cached; return cached; } return { 'request': function(config) { // Check to make sure this request hasn't already been cached and that // the requester didn't explicitly ask us to ignore this request: if (!config.ignoreLoadingBar && !isCached(config)) { $rootScope.$broadcast('cfpLoadingBar:loading', {url: config.url}); if (reqsTotal === 0) { startTimeout = $timeout(function() { cfpLoadingBar.start(); }, latencyThreshold); } reqsTotal++; cfpLoadingBar.set(reqsCompleted / reqsTotal); } return config; }, 'response': function(response) { if (!response || !response.config) { $log.error('Broken interceptor detected: Config object not supplied in response:\n https://github.com/chieffancypants/angular-loading-bar/pull/50'); return response; } if (!response.config.ignoreLoadingBar && !isCached(response.config)) { reqsCompleted++; $rootScope.$broadcast('cfpLoadingBar:loaded', {url: response.config.url, result: response}); if (reqsCompleted >= reqsTotal) { setComplete(); } else { cfpLoadingBar.set(reqsCompleted / reqsTotal); } } return response; }, 'responseError': function(rejection) { if (!rejection || !rejection.config) { $log.error('Broken interceptor detected: Config object not supplied in rejection:\n https://github.com/chieffancypants/angular-loading-bar/pull/50'); return $q.reject(rejection); } if (!rejection.config.ignoreLoadingBar && !isCached(rejection.config)) { reqsCompleted++; $rootScope.$broadcast('cfpLoadingBar:loaded', {url: rejection.config.url, result: rejection}); if (reqsCompleted >= reqsTotal) { setComplete(); } else { cfpLoadingBar.set(reqsCompleted / reqsTotal); } } return $q.reject(rejection); } }; }]; $httpProvider.interceptors.push(interceptor); }]); /** * Loading Bar * * This service handles adding and removing the actual element in the DOM. * Generally, best practices for DOM manipulation is to take place in a * directive, but because the element itself is injected in the DOM only upon * XHR requests, and it's likely needed on every view, the best option is to * use a service. */ angular.module('cfp.loadingBar', []) .provider('cfpLoadingBar', function() { this.includeSpinner = true; this.includeBar = true; this.latencyThreshold = 100; this.startSize = 0.02; this.parentSelector = 'body'; this.spinnerTemplate = '<div id="loading-bar-spinner"><div class="spinner-icon"></div></div>'; this.loadingBarTemplate = '<div id="loading-bar"><div class="bar"><div class="peg"></div></div></div>'; this.$get = ['$injector', '$document', '$timeout', '$rootScope', function ($injector, $document, $timeout, $rootScope) { var $animate; var $parentSelector = this.parentSelector, loadingBarContainer = angular.element(this.loadingBarTemplate), loadingBar = loadingBarContainer.find('div').eq(0), spinner = angular.element(this.spinnerTemplate); var incTimeout, completeTimeout, started = false, status = 0; var includeSpinner = this.includeSpinner; var includeBar = this.includeBar; var startSize = this.startSize; /** * Inserts the loading bar element into the dom, and sets it to 2% */ function _start() { if (!$animate) { $animate = $injector.get('$animate'); } var $parent = $document.find($parentSelector).eq(0); $timeout.cancel(completeTimeout); // do not continually broadcast the started event: if (started) { return; } $rootScope.$broadcast('cfpLoadingBar:started'); started = true; if (includeBar) { $animate.enter(loadingBarContainer, $parent, angular.element($parent[0].lastChild)); } if (includeSpinner) { $animate.enter(spinner, $parent, angular.element($parent[0].lastChild)); } _set(startSize); } /** * Set the loading bar's width to a certain percent. * * @param n any value between 0 and 1 */ function _set(n) { if (!started) { return; } var pct = (n * 100) + '%'; loadingBar.css('width', pct); status = n; // increment loadingbar to give the illusion that there is always // progress but make sure to cancel the previous timeouts so we don't // have multiple incs running at the same time. $timeout.cancel(incTimeout); incTimeout = $timeout(function() { _inc(); }, 250); } /** * Increments the loading bar by a random amount * but slows down as it progresses */ function _inc() { if (_status() >= 1) { return; } var rnd = 0; // TODO: do this mathmatically instead of through conditions var stat = _status(); if (stat >= 0 && stat < 0.25) { // Start out between 3 - 6% increments rnd = (Math.random() * (5 - 3 + 1) + 3) / 100; } else if (stat >= 0.25 && stat < 0.65) { // increment between 0 - 3% rnd = (Math.random() * 3) / 100; } else if (stat >= 0.65 && stat < 0.9) { // increment between 0 - 2% rnd = (Math.random() * 2) / 100; } else if (stat >= 0.9 && stat < 0.99) { // finally, increment it .5 % rnd = 0.005; } else { // after 99%, don't increment: rnd = 0; } var pct = _status() + rnd; _set(pct); } function _status() { return status; } function _completeAnimation() { status = 0; started = false; } function _complete() { if (!$animate) { $animate = $injector.get('$animate'); } $rootScope.$broadcast('cfpLoadingBar:completed'); _set(1); $timeout.cancel(completeTimeout); // Attempt to aggregate any start/complete calls within 500ms: completeTimeout = $timeout(function() { var promise = $animate.leave(loadingBarContainer, _completeAnimation); if (promise && promise.then) { promise.then(_completeAnimation); } $animate.leave(spinner); }, 500); } return { start : _start, set : _set, status : _status, inc : _inc, complete : _complete, includeSpinner : this.includeSpinner, latencyThreshold : this.latencyThreshold, parentSelector : this.parentSelector, startSize : this.startSize }; }]; // }); // wtf javascript. srsly })(); //
{ "content_hash": "ca20144c91526e0e9983da9a74793eb1", "timestamp": "", "source": "github", "line_count": 319, "max_line_length": 170, "avg_line_length": 31.031347962382444, "alnum_prop": 0.565208606929993, "repo_name": "uttapong/thalinterpreter", "id": "8401fe466c80e0aca114e7a9e4cae198a97f026c", "size": "10042", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "public/lib/angular-loading-bar/build/loading-bar.js", "mode": "33188", "license": "mit", "language": [ { "name": "Batchfile", "bytes": "103" }, { "name": "CSS", "bytes": "236005" }, { "name": "CoffeeScript", "bytes": "83757" }, { "name": "HTML", "bytes": "3220127" }, { "name": "JavaScript", "bytes": "6094670" }, { "name": "Shell", "bytes": "1674" } ], "symlink_target": "" }
ACCEPTED #### According to Index Fungorum #### Published in Enum. pl. (Kjbenhavn) 2: 270 (1803) #### Original name Agaricus inodorus Bull. ### Remarks null
{ "content_hash": "63a3cc0ea09c64fd782d73f9e9dd6c24", "timestamp": "", "source": "github", "line_count": 13, "max_line_length": 35, "avg_line_length": 12.23076923076923, "alnum_prop": 0.6855345911949685, "repo_name": "mdoering/backbone", "id": "b53ed87a055740d3cba62b2ba8b7b16fb2513f7e", "size": "206", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "life/Fungi/Basidiomycota/Agaricomycetes/Agaricales/Agaricaceae/Agaricus/Agaricus inodorus/README.md", "mode": "33188", "license": "apache-2.0", "language": [], "symlink_target": "" }
class BrowserStatusMonitor::LocalWebContentsObserver : public content::WebContentsObserver { public: LocalWebContentsObserver(content::WebContents* contents, BrowserStatusMonitor* monitor) : content::WebContentsObserver(contents), monitor_(monitor) {} ~LocalWebContentsObserver() override {} // content::WebContentsObserver void DidNavigateMainFrame( const content::LoadCommittedDetails& details, const content::FrameNavigateParams& params) override { ChromeLauncherController::AppState state = ChromeLauncherController::APP_STATE_INACTIVE; Browser* browser = chrome::FindBrowserWithWebContents(web_contents()); // Don't assume that |browser| still exists. if (browser) { if (browser->window()->IsActive() && browser->tab_strip_model()->GetActiveWebContents() == web_contents()) state = ChromeLauncherController::APP_STATE_WINDOW_ACTIVE; else if (browser->window()->IsActive()) state = ChromeLauncherController::APP_STATE_ACTIVE; } monitor_->UpdateAppItemState(web_contents(), state); monitor_->UpdateBrowserItemState(); // Navigating may change the ShelfID associated with the WebContents. if (browser && browser->tab_strip_model()->GetActiveWebContents() == web_contents()) { monitor_->SetShelfIDForBrowserWindowContents(browser, web_contents()); } } void WebContentsDestroyed() override { // We can only come here when there was a non standard termination like // an app got un-installed while running, etc. monitor_->WebContentsDestroyed(web_contents()); // |this| is gone now. } private: BrowserStatusMonitor* monitor_; DISALLOW_COPY_AND_ASSIGN(LocalWebContentsObserver); }; // Observes any new settings windows and sets their shelf icon (since they // are excluded from BrowserShortcutLauncherItem). class BrowserStatusMonitor::SettingsWindowObserver : public chrome::SettingsWindowManagerObserver { public: SettingsWindowObserver() {} ~SettingsWindowObserver() override {} // SettingsWindowManagerObserver void OnNewSettingsWindow(Browser* settings_browser) override { ash::SetShelfItemDetailsForDialogWindow( settings_browser->window()->GetNativeWindow(), IDR_ASH_SHELF_ICON_SETTINGS, l10n_util::GetStringUTF16(IDS_SETTINGS_TITLE)); } private: DISALLOW_COPY_AND_ASSIGN(SettingsWindowObserver); }; BrowserStatusMonitor::BrowserStatusMonitor( ChromeLauncherController* launcher_controller) : launcher_controller_(launcher_controller), observed_activation_clients_(this), observed_root_windows_(this), settings_window_observer_(new SettingsWindowObserver), browser_tab_strip_tracker_(this, this, this) { DCHECK(launcher_controller_); chrome::SettingsWindowManager::GetInstance()->AddObserver( settings_window_observer_.get()); // This check needs for win7_aura. Without this, all tests in // ChromeLauncherController will fail in win7_aura. if (ash::Shell::HasInstance()) { // We can't assume all RootWindows have the same ActivationClient. // Add a RootWindow and its ActivationClient to the observed list. aura::Window::Windows root_windows = ash::Shell::GetAllRootWindows(); aura::Window::Windows::const_iterator iter = root_windows.begin(); for (; iter != root_windows.end(); ++iter) { // |observed_activation_clients_| can have the same activation client // multiple times - which would be handled by the used // |ScopedObserverWithDuplicatedSources|. observed_activation_clients_.Add( aura::client::GetActivationClient(*iter)); observed_root_windows_.Add(static_cast<aura::Window*>(*iter)); } gfx::Screen::GetScreen()->AddObserver(this); } browser_tab_strip_tracker_.Init( BrowserTabStripTracker::InitWith::ALL_BROWERS); } BrowserStatusMonitor::~BrowserStatusMonitor() { // This check needs for win7_aura. Without this, all tests in // ChromeLauncherController will fail in win7_aura. if (ash::Shell::HasInstance()) gfx::Screen::GetScreen()->RemoveObserver(this); chrome::SettingsWindowManager::GetInstance()->RemoveObserver( settings_window_observer_.get()); browser_tab_strip_tracker_.StopObservingAndSendOnBrowserRemoved(); STLDeleteContainerPairSecondPointers(webcontents_to_observer_map_.begin(), webcontents_to_observer_map_.end()); } void BrowserStatusMonitor::UpdateAppItemState( content::WebContents* contents, ChromeLauncherController::AppState app_state) { DCHECK(contents); // It is possible to come here from Browser::SwapTabContent where the contents // cannot be associated with a browser. A removal however should be properly // processed. Browser* browser = chrome::FindBrowserWithWebContents(contents); if (app_state == ChromeLauncherController::APP_STATE_REMOVED || (browser && launcher_controller_->IsBrowserFromActiveUser(browser))) launcher_controller_->UpdateAppState(contents, app_state); } void BrowserStatusMonitor::UpdateBrowserItemState() { launcher_controller_->GetBrowserShortcutLauncherItemController()-> UpdateBrowserItemState(); } void BrowserStatusMonitor::OnWindowActivated( aura::client::ActivationChangeObserver::ActivationReason reason, aura::Window* gained_active, aura::Window* lost_active) { Browser* browser = NULL; content::WebContents* contents_from_gained = NULL; content::WebContents* contents_from_lost = NULL; // Update active webcontents's app item state of |lost_active|, if existed. if (lost_active) { browser = chrome::FindBrowserWithWindow(lost_active); if (browser) contents_from_lost = browser->tab_strip_model()->GetActiveWebContents(); if (contents_from_lost) { UpdateAppItemState( contents_from_lost, ChromeLauncherController::APP_STATE_INACTIVE); } } // Update active webcontents's app item state of |gained_active|, if existed. if (gained_active) { browser = chrome::FindBrowserWithWindow(gained_active); if (browser) contents_from_gained = browser->tab_strip_model()->GetActiveWebContents(); if (contents_from_gained) { UpdateAppItemState( contents_from_gained, ChromeLauncherController::APP_STATE_WINDOW_ACTIVE); } } if (contents_from_lost || contents_from_gained) UpdateBrowserItemState(); } void BrowserStatusMonitor::OnWindowDestroyed(aura::Window* window) { // Remove RootWindow and its ActivationClient from observed list. observed_root_windows_.Remove(window); observed_activation_clients_.Remove( aura::client::GetActivationClient(window)); } bool BrowserStatusMonitor::ShouldTrackBrowser(Browser* browser) { return browser->host_desktop_type() == chrome::HOST_DESKTOP_TYPE_ASH; } void BrowserStatusMonitor::OnBrowserAdded(Browser* browser) { if (browser->is_type_popup() && browser->is_app()) { // Note: A V1 application will set the tab strip observer when the app gets // added to the shelf. This makes sure that in the multi user case we will // only set the observer while the app item exists in the shelf. AddV1AppToShelf(browser); } } void BrowserStatusMonitor::OnBrowserRemoved(Browser* browser) { if (browser->is_type_popup() && browser->is_app()) RemoveV1AppFromShelf(browser); UpdateBrowserItemState(); } void BrowserStatusMonitor::OnDisplayAdded(const gfx::Display& new_display) { // Add a new RootWindow and its ActivationClient to observed list. aura::Window* root_window = ash::Shell::GetInstance() ->window_tree_host_manager() ->GetRootWindowForDisplayId(new_display.id()); // When the primary root window's display get removed, the existing root // window is taken over by the new display and the observer is already set. if (!observed_root_windows_.IsObserving(root_window)) { observed_root_windows_.Add(static_cast<aura::Window*>(root_window)); observed_activation_clients_.Add( aura::client::GetActivationClient(root_window)); } } void BrowserStatusMonitor::OnDisplayRemoved(const gfx::Display& old_display) { // When this is called, RootWindow of |old_display| is already removed. // Instead, we can remove RootWindow and its ActivationClient in the // OnWindowRemoved(). // Do nothing here. } void BrowserStatusMonitor::OnDisplayMetricsChanged(const gfx::Display&, uint32_t) { // Do nothing here. } void BrowserStatusMonitor::ActiveTabChanged(content::WebContents* old_contents, content::WebContents* new_contents, int index, int reason) { Browser* browser = NULL; // Use |new_contents|. |old_contents| could be NULL. DCHECK(new_contents); browser = chrome::FindBrowserWithWebContents(new_contents); if (browser && browser->host_desktop_type() != chrome::HOST_DESKTOP_TYPE_ASH) return; ChromeLauncherController::AppState state = ChromeLauncherController::APP_STATE_INACTIVE; // Update immediately on a tab change. if (old_contents && (TabStripModel::kNoTab != browser->tab_strip_model()->GetIndexOfWebContents(old_contents))) UpdateAppItemState(old_contents, state); if (new_contents) { state = browser->window()->IsActive() ? ChromeLauncherController::APP_STATE_WINDOW_ACTIVE : ChromeLauncherController::APP_STATE_ACTIVE; UpdateAppItemState(new_contents, state); UpdateBrowserItemState(); SetShelfIDForBrowserWindowContents(browser, new_contents); } } void BrowserStatusMonitor::TabReplacedAt(TabStripModel* tab_strip_model, content::WebContents* old_contents, content::WebContents* new_contents, int index) { DCHECK(old_contents && new_contents); Browser* browser = chrome::FindBrowserWithWebContents(new_contents); if (browser && browser->host_desktop_type() != chrome::HOST_DESKTOP_TYPE_ASH) return; UpdateAppItemState(old_contents, ChromeLauncherController::APP_STATE_REMOVED); RemoveWebContentsObserver(old_contents); ChromeLauncherController::AppState state = ChromeLauncherController::APP_STATE_ACTIVE; if (browser->window()->IsActive() && (tab_strip_model->GetActiveWebContents() == new_contents)) state = ChromeLauncherController::APP_STATE_WINDOW_ACTIVE; UpdateAppItemState(new_contents, state); UpdateBrowserItemState(); if (tab_strip_model->GetActiveWebContents() == new_contents) SetShelfIDForBrowserWindowContents(browser, new_contents); AddWebContentsObserver(new_contents); } void BrowserStatusMonitor::TabInsertedAt(content::WebContents* contents, int index, bool foreground) { // An inserted tab is not active - ActiveTabChanged() will be called to // activate. We initialize therefore with |APP_STATE_INACTIVE|. UpdateAppItemState(contents, ChromeLauncherController::APP_STATE_INACTIVE); AddWebContentsObserver(contents); } void BrowserStatusMonitor::TabClosingAt(TabStripModel* tab_strip_mode, content::WebContents* contents, int index) { UpdateAppItemState(contents, ChromeLauncherController::APP_STATE_REMOVED); RemoveWebContentsObserver(contents); } void BrowserStatusMonitor::WebContentsDestroyed( content::WebContents* contents) { UpdateAppItemState(contents, ChromeLauncherController::APP_STATE_REMOVED); RemoveWebContentsObserver(contents); } void BrowserStatusMonitor::AddV1AppToShelf(Browser* browser) { DCHECK(browser->is_type_popup() && browser->is_app()); std::string app_id = web_app::GetExtensionIdFromApplicationName(browser->app_name()); if (!app_id.empty()) { browser_to_app_id_map_[browser] = app_id; launcher_controller_->LockV1AppWithID(app_id); } } void BrowserStatusMonitor::RemoveV1AppFromShelf(Browser* browser) { DCHECK(browser->is_type_popup() && browser->is_app()); if (browser_to_app_id_map_.find(browser) != browser_to_app_id_map_.end()) { launcher_controller_->UnlockV1AppWithID(browser_to_app_id_map_[browser]); browser_to_app_id_map_.erase(browser); } } bool BrowserStatusMonitor::IsV1AppInShelf(Browser* browser) { return browser_to_app_id_map_.find(browser) != browser_to_app_id_map_.end(); } void BrowserStatusMonitor::AddWebContentsObserver( content::WebContents* contents) { if (webcontents_to_observer_map_.find(contents) == webcontents_to_observer_map_.end()) { webcontents_to_observer_map_[contents] = new LocalWebContentsObserver(contents, this); } } void BrowserStatusMonitor::RemoveWebContentsObserver( content::WebContents* contents) { DCHECK(webcontents_to_observer_map_.find(contents) != webcontents_to_observer_map_.end()); delete webcontents_to_observer_map_[contents]; webcontents_to_observer_map_.erase(contents); } ash::ShelfID BrowserStatusMonitor::GetShelfIDForWebContents( content::WebContents* contents) { return launcher_controller_->GetShelfIDForWebContents(contents); } void BrowserStatusMonitor::SetShelfIDForBrowserWindowContents( Browser* browser, content::WebContents* web_contents) { launcher_controller_->GetBrowserShortcutLauncherItemController()-> SetShelfIDForBrowserWindowContents(browser, web_contents); }
{ "content_hash": "53e9c435d9c7c0d92fac6baffac3afb9", "timestamp": "", "source": "github", "line_count": 358, "max_line_length": 80, "avg_line_length": 38.49441340782123, "alnum_prop": 0.6984979319352732, "repo_name": "ds-hwang/chromium-crosswalk", "id": "efbe50e754d4eccf628d39dc9fe6bfe722d5e255", "size": "15287", "binary": false, "copies": "3", "ref": "refs/heads/master", "path": "chrome/browser/ui/ash/launcher/browser_status_monitor.cc", "mode": "33188", "license": "bsd-3-clause", "language": [], "symlink_target": "" }
# postcss-copy [![Build Status](https://travis-ci.org/geut/postcss-copy.svg?branch=master)](https://travis-ci.org/geut/postcss-copy) > An **async** postcss plugin to copy all assets referenced in CSS files to a custom destination folder and updating the URLs. ## Install With [npm](https://npmjs.com/package/postcss-copy) do: ``` npm install postcss-copy ``` ## Quick Start ### Using [Gulp](https://github.com/postcss/gulp-postcss) ```js var gulp = require('gulp'); var postcss = require('gulp-postcss'); var postcssCopy = require('postcss-copy'); gulp.task('buildCss', function () { var processors = [ postcssCopy({ src: 'src', dest: 'dist' }) ]; return gulp .src('src/**/*.css') .pipe(postcss(processors)) .pipe(gulp.dest('dist')); }); ``` ## Options ##### src ({string|array} required) Define the base src path of your CSS files. ##### dest ({string} required) Define the dest path of your CSS files and assets. ##### template (default = 'assets/[hash].[ext]') Define a template name for your final url assets. * **[hash]**: Let you use a hash name based on the contents of the file. * **[name]**: Real name of your asset. * **[path]**: Original relative path of your asset. * **[ext]**: Extension of the asset. ##### hashFunction Define a custom function to create the hash name. ```js var copyOpts = { ..., hashFunction(contents) { // borschik return crypto.createHash('sha1') .update(contents) .digest('base64') .replace(/\+/g, '-') .replace(/\//g, '_') .replace(/=/g, '') .replace(/^[+-]+/g, ''); } }; ``` ##### keepRelativePath (default = true) By default the copy process keep the relative path between each ```asset``` and the path of his ```CSS file```. You can change this behavior setting the option in false and each ```asset``` will define the path based only in the ```dest``` path option (see [Using copy with postcss-import](#using-postcss-import)) ##### transform Extend the copy method to apply a transform in the contents (e.g: optimize images). **IMPORTANT:** The function must return the fileMeta (modified) or a promise using ```resolve(fileMeta)```. ```js var Imagemin = require('imagemin'); var copyOpts = { ..., transform(fileMeta) { return new Promise((resolve, reject) => { if (['jpg', 'png'].indexOf(fileMeta.ext) === -1) { return fileMeta; } new Imagemin() .src(fileMeta.contents) .use(Imagemin.jpegtran({ progressive: true })) .run((err, files) => { if (err) { reject(err); } fileMeta.contents = files[0].contents; resolve(fileMeta); // <- important }); }); } }; ``` ## <a name="using-postcss-import"></a> Using copy with postcss-import [postcss-import](https://github.com/postcss/postcss-import) is a great plugin that allow us work our css files in a modular way with the same behavior of CommonJS. Since this plugin create at the end only one file with all your CSS files inline (loaded with the @import keyword) you need disabled in ```copy``` the option ```keepRelativePath```. One thing more... postcss-import has the ability of load files from node_modules. If your src folder is at the same level of node_modules like this: ``` myProject/ |-- node_modules/ |-- dest/ |-- src/ ``` In this case you need define ```a multiple src``` ```js var gulp = require('gulp'); var postcss = require('gulp-postcss'); var postcssCopy = require('postcss-copy'); var postcssImport = require('postcss-import'); gulp.task('buildCss', function () { var processors = [ postcssImport(), postcssCopy({ src: ['src', 'node_modules'], dest: 'dist', keepRelativePath: false // required to work with postcss-import }) ]; return gulp .src('src/index.css') .pipe(postcss(processors)) .pipe(gulp.dest('dist')); }); ``` ## On roadmap nothing for now :) ## Credits * Thanks to @conradz and his rework plugin [rework-assets](https://github.com/conradz/rework-assets) my inspiration in this plugin. * Thanks to @MoOx for let me create the copy function in his [postcss-url](https://github.com/postcss/postcss-url) plugin. * Thanks to @webpack, i take the idea of define templates from his awesome [file-loader](https://github.com/webpack/file-loader) ## License MIT
{ "content_hash": "da19a3bbe3ff4698dd63b8de9412554b", "timestamp": "", "source": "github", "line_count": 152, "max_line_length": 314, "avg_line_length": 30.638157894736842, "alnum_prop": 0.60833154391239, "repo_name": "wbinnssmith/postcss-copy", "id": "4c1292dbf13063e48b3f9ebd885427054d62a9d0", "size": "4657", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "README.md", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "605" }, { "name": "JavaScript", "bytes": "17303" } ], "symlink_target": "" }
module InitializerEnhancer def initialize(callback_method:) # Class including this one must define the callback method define_singleton_method(callback_method) { super("banana") # <- Works just like you hoped it would. } super() end end class SillyMonkey prepend InitializerEnhancer def initialize puts "LOL Nothing happened." end def eat_thing(thing) raise RuntimeError, "I ate a #{thing}" end end class HappyMonkey < SillyMonkey def eat_thing(thing) puts "Dreaming about #{thing}" end end # >> a = HappyMonkey.new(callback_method: "eat_thing") # LOL Nothing happened. # => #<HappyMonkey:0x007f901b877528> # # >> a.eat_thing # Dreaming about banana # => nil # # >> b = SillyMonkey.new(callback_method: "eat_thing") # LOL Nothing happened. # => #<SillyMonkey:0x007f90199199b0> # # >> b.eat_thing # RuntimeError: I ate a banana # from (irb):22:in `eat_thing' # from (irb):6:in `block in initialize'
{ "content_hash": "a6fe444869a6b53f0c3c0841bdfb3fca", "timestamp": "", "source": "github", "line_count": 50, "max_line_length": 62, "avg_line_length": 19.48, "alnum_prop": 0.675564681724846, "repo_name": "pboling/celluloid-io-pg-listener", "id": "56669c42730e231531ac2a6d94eda886885e8a7d", "size": "974", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "lib/celluloid-io-pg-listener/examples/double_super_example.rb", "mode": "33188", "license": "mit", "language": [ { "name": "PLpgSQL", "bytes": "5994" }, { "name": "Ruby", "bytes": "49526" }, { "name": "Shell", "bytes": "689" } ], "symlink_target": "" }
// Npgsql.NpgsqlError.cs // // Author: // Francisco Jr. ([email protected]) // // Copyright (C) 2002 The Npgsql Development Team // [email protected] // http://gborg.postgresql.org/project/npgsql/projdisplay.php // // Permission to use, copy, modify, and distribute this software and its // documentation for any purpose, without fee, and without a written // agreement is hereby granted, provided that the above copyright notice // and this paragraph and the following two paragraphs appear in all copies. // // IN NO EVENT SHALL THE NPGSQL DEVELOPMENT TEAM BE LIABLE TO ANY PARTY // FOR DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES, // INCLUDING LOST PROFITS, ARISING OUT OF THE USE OF THIS SOFTWARE AND ITS // DOCUMENTATION, EVEN IF THE NPGSQL DEVELOPMENT TEAM HAS BEEN ADVISED OF // THE POSSIBILITY OF SUCH DAMAGE. // // THE NPGSQL DEVELOPMENT TEAM SPECIFICALLY DISCLAIMS ANY WARRANTIES, // INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY // AND FITNESS FOR A PARTICULAR PURPOSE. THE SOFTWARE PROVIDED HEREUNDER IS // ON AN "AS IS" BASIS, AND THE NPGSQL DEVELOPMENT TEAM HAS NO OBLIGATIONS // TO PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS. using System; using System.Collections.Generic; using System.IO; using System.Text; namespace Revenj.DatabasePersistence.Postgres.Npgsql { /// <summary> /// EventArgs class to send Notice parameters, which are just NpgsqlError's in a lighter context. /// </summary> public class NpgsqlNoticeEventArgs : EventArgs { /// <summary> /// Notice information. /// </summary> public NpgsqlError Notice = null; internal NpgsqlNoticeEventArgs(NpgsqlError eNotice) { Notice = eNotice; } } /// <summary> /// This class represents the ErrorResponse and NoticeResponse /// message sent from PostgreSQL server. /// </summary> [Serializable] public sealed class NpgsqlError { private readonly string _severity = string.Empty; private readonly string _code = string.Empty; private readonly string _message = string.Empty; private readonly string _detail = string.Empty; private readonly string _hint = string.Empty; private readonly string _position = string.Empty; private readonly string _internalPosition = string.Empty; private readonly string _internalQuery = string.Empty; private readonly string _where = string.Empty; private readonly string _file = string.Empty; private readonly string _line = string.Empty; private readonly string _routine = string.Empty; private readonly string _schemaName = string.Empty; private readonly string _tableName = string.Empty; private readonly string _columnName = string.Empty; private readonly string _datatypeName = string.Empty; private readonly string _constraintName = string.Empty; /// <summary> /// Severity code. All versions. /// </summary> public string Severity { get { return _severity; } } /// <summary> /// Error code. PostgreSQL 7.4 and up. /// </summary> public string Code { get { return _code; } } /// <summary> /// Terse error message. All versions. /// </summary> public string Message { get { return _message; } } /// <summary> /// Detailed error message. PostgreSQL 7.4 and up. /// </summary> public string Detail { get { return _detail; } } /// <summary> /// Suggestion to help resolve the error. PostgreSQL 7.4 and up. /// </summary> public string Hint { get { return _hint; } } /// <summary> /// Position (one based) within the query string where the error was encounterd. PostgreSQL 7.4 and up. /// </summary> public string Position { get { return _position; } } /// <summary> /// Position (one based) within the query string where the error was encounterd. This position refers to an internal command executed for example inside a PL/pgSQL function. PostgreSQL 7.4 and up. /// </summary> public string InternalPosition { get { return _internalPosition; } } /// <summary> /// Internal query string where the error was encounterd. This position refers to an internal command executed for example inside a PL/pgSQL function. PostgreSQL 7.4 and up. /// </summary> public string InternalQuery { get { return _internalQuery; } } /// <summary> /// Trace back information. PostgreSQL 7.4 and up. /// </summary> public string Where { get { return _where; } } /// <summary> /// Source file (in backend) reporting the error. PostgreSQL 7.4 and up. /// </summary> public string File { get { return _file; } } /// <summary> /// Source file line number (in backend) reporting the error. PostgreSQL 7.4 and up. /// </summary> public string Line { get { return _line; } } /// <summary> /// Source routine (in backend) reporting the error. PostgreSQL 7.4 and up. /// </summary> public string Routine { get { return _routine; } } /// <summary> /// Schema name which relates to the error. PostgreSQL 9.3 and up. /// </summary> public string SchemaName { get { return _schemaName; } } /// <summary> /// Table name which relates to the error. PostgreSQL 9.3 and up. /// </summary> public string TableName { get { return _tableName; } } /// <summary> /// Column name which relates to the error. PostgreSQL 9.3 and up. /// </summary> public string ColumnName { get { return _columnName; } } /// <summary> /// Data type of column which relates to the error. PostgreSQL 9.3 and up. /// </summary> public string DataTypeName { get { return _datatypeName; } } /// <summary> /// Constraint name which relates to the error. PostgreSQL 9.3 and up. /// </summary> public string ConstraintName { get { return _constraintName; } } /// <summary> /// String containing the sql sent which produced this error. /// </summary> public string ErrorSql { get; set; } /// <summary> /// Return a string representation of this error object. /// </summary> public override String ToString() { StringBuilder B = new StringBuilder(); if (Severity.Length > 0) { B.AppendFormat("{0}: ", Severity); } if (Code.Length > 0) { B.AppendFormat("{0}: ", Code); } B.AppendFormat("{0}", Message); // CHECKME - possibly multi-line, that is yucky // if (Hint.Length > 0) { // B.AppendFormat(" ({0})", Hint); // } return B.ToString(); } internal NpgsqlError(Stream stream, byte[] buffer, ByteBuffer queue) { // Check the messageLength value. If it is 1178686529, this would be the // "FATA" string, which would mean a protocol 2.0 error string. if (PGUtil.ReadInt32(stream, buffer) == 1178686529) { string[] v2Parts = ("FATA" + PGUtil.ReadString(stream, queue)).Split(new char[] { ':' }, 2); if (v2Parts.Length == 2) { _severity = v2Parts[0].Trim(); _message = v2Parts[1].Trim(); } else { _severity = string.Empty; _message = v2Parts[0].Trim(); } } else { for (char field = (char)stream.ReadByte(); field != 0; field = (char)stream.ReadByte()) { switch (field) { case 'S': _severity = PGUtil.ReadString(stream, queue); break; case 'C': _code = PGUtil.ReadString(stream, queue); break; case 'M': _message = PGUtil.ReadString(stream, queue); break; case 'D': _detail = PGUtil.ReadString(stream, queue); break; case 'H': _hint = PGUtil.ReadString(stream, queue); break; case 'P': _position = PGUtil.ReadString(stream, queue); break; case 'p': _internalPosition = PGUtil.ReadString(stream, queue); break; case 'q': _internalQuery = PGUtil.ReadString(stream, queue); break; case 'W': _where = PGUtil.ReadString(stream, queue); break; case 'F': _file = PGUtil.ReadString(stream, queue); break; case 'L': _line = PGUtil.ReadString(stream, queue); break; case 'R': _routine = PGUtil.ReadString(stream, queue); break; case 's': _schemaName = PGUtil.ReadString(stream, queue); break; case 't': _tableName = PGUtil.ReadString(stream, queue); break; case 'c': _columnName = PGUtil.ReadString(stream, queue); break; case 'd': _datatypeName = PGUtil.ReadString(stream, queue); break; case 'n': _constraintName = PGUtil.ReadString(stream, queue); break; default: // Unknown error field; consume and discard. PGUtil.ReadString(stream, queue); break; } } } } internal NpgsqlError(string errorMessage) { _message = errorMessage; } } }
{ "content_hash": "28584f67a86dc49ce21759798f7a194e", "timestamp": "", "source": "github", "line_count": 329, "max_line_length": 199, "avg_line_length": 28.033434650455927, "alnum_prop": 0.6200802341971159, "repo_name": "ngs-doo/revenj", "id": "d62854376f42b91e519ae232a9af867eaf7957c4", "size": "9257", "binary": false, "copies": "4", "ref": "refs/heads/master", "path": "csharp/Core/Revenj.Core/DatabasePersistence/Postgres/Npgsql/NpgsqlError.cs", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "ASL", "bytes": "38510" }, { "name": "ASP.NET", "bytes": "195" }, { "name": "C#", "bytes": "5377444" }, { "name": "CSS", "bytes": "24978" }, { "name": "HTML", "bytes": "16282" }, { "name": "Java", "bytes": "969607" }, { "name": "JavaScript", "bytes": "93515" }, { "name": "Scala", "bytes": "449459" }, { "name": "TypeScript", "bytes": "503890" } ], "symlink_target": "" }
// // NSLayoutConstraint+PureLayout.m // v1.0.0 // https://github.com/smileyborg/PureLayout // // Copyright (c) 2013-2014 Tyler Fox // // This code is distributed under the terms and conditions of the MIT license. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to // deal in the Software without restriction, including without limitation the // rights to use, copy, modify, merge, publish, distribute, sublicense, and/or // sell copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS // IN THE SOFTWARE. // #import "NSLayoutConstraint+PureLayout.h" #import "ALView+PureLayout.h" #import "PureLayout+Internal.h" #pragma mark - NSLayoutConstraint+PureLayout @implementation NSLayoutConstraint (PureLayout) /** Adds the constraint to the appropriate view. */ - (void)autoInstall { NSAssert(self.firstItem || self.secondItem, @"Can't install a constraint with nil firstItem and secondItem."); if (self.firstItem) { if (self.secondItem) { NSAssert([self.firstItem isKindOfClass:[ALView class]] && [self.secondItem isKindOfClass:[ALView class]], @"Can only automatically install a constraint if both items are views."); ALView *commonSuperview = [self.firstItem al_commonSuperviewWithView:self.secondItem]; [commonSuperview al_addConstraintUsingGlobalPriority:self]; } else { NSAssert([self.firstItem isKindOfClass:[ALView class]], @"Can only automatically install a constraint if the item is a view."); [self.firstItem al_addConstraintUsingGlobalPriority:self]; } } else { NSAssert([self.secondItem isKindOfClass:[ALView class]], @"Can only automatically install a constraint if the item is a view."); [self.secondItem al_addConstraintUsingGlobalPriority:self]; } } /** Removes the constraint from the view it has been added to. */ - (void)autoRemove { [ALView autoRemoveConstraint:self]; } @end
{ "content_hash": "d6a291189b2abf0384135cc616655483", "timestamp": "", "source": "github", "line_count": 67, "max_line_length": 191, "avg_line_length": 40.701492537313435, "alnum_prop": 0.7271727172717272, "repo_name": "kiokoo/YaleMobile", "id": "6d693b45b47b50a7290ed9ff11f3d4ca6fc45049", "size": "2727", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "Pods/PureLayout/Source/NSLayoutConstraint+PureLayout.m", "mode": "33261", "license": "mit", "language": [ { "name": "Objective-C", "bytes": "480237" }, { "name": "Ruby", "bytes": "186" } ], "symlink_target": "" }
<html> <body> Technology-neutral RSF definitions relating to Entities (defined as objects referenced by unique IDs). </body> </html>
{ "content_hash": "53b8ce776de8e70c453971bd8b28feff", "timestamp": "", "source": "github", "line_count": 8, "max_line_length": 75, "avg_line_length": 18.125, "alnum_prop": 0.7034482758620689, "repo_name": "rsf/RSFUtil", "id": "d82170f6ef5cf613c2c436f419b9f81a971e17f1", "size": "145", "binary": false, "copies": "4", "ref": "refs/heads/master", "path": "src/uk/org/ponder/rsf/state/entity/package.html", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "HTML", "bytes": "11966" }, { "name": "Java", "bytes": "849548" } ], "symlink_target": "" }
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical"> <android.support.v7.widget.RecyclerView android:id="@+id/NearbyStopsFragment_StopList" android:layout_width="match_parent" android:layout_height="match_parent" /> </LinearLayout>
{ "content_hash": "a5471ad4e2dce3e330da51927219e1f1", "timestamp": "", "source": "github", "line_count": 14, "max_line_length": 62, "avg_line_length": 35.5, "alnum_prop": 0.7022132796780685, "repo_name": "jbatonnet/tramurway", "id": "120ac71b706297335ffb8a3040100f09b8433674", "size": "497", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "TramUrWay.Android/Resources/layout/NearbyStopsFragment.xml", "mode": "33188", "license": "mit", "language": [ { "name": "Batchfile", "bytes": "132" }, { "name": "C#", "bytes": "304209" } ], "symlink_target": "" }
/// <summary> /// This is a script that simply also listens to the ExampleMessage /// If a kill message is sent, it kills itself /// </summary> public class ExtraListener : MonoBehaviourEx, IHandle<KillMessage>, IHandle<ExampleMessage> { /// <summary> /// When we get the kill message, destroy ourself /// </summary> public void Handle(KillMessage message) { Destroy(gameObject); } /// <summary> /// When we get the example message, happily report it! /// </summary> public void Handle(ExampleMessage message) { print("Hello from extra listener!\n" + message.CrazyReason); } }
{ "content_hash": "ca5921fd4a454a543c60b492fd003e61", "timestamp": "", "source": "github", "line_count": 22, "max_line_length": 91, "avg_line_length": 29.181818181818183, "alnum_prop": 0.6510903426791277, "repo_name": "Temaran/TemaranUnityMessenger", "id": "48d1daeab051e42db5cbfd39d4309d4acadf435f", "size": "644", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "Assets/TemaranMessenger/Examples/ASimpleExample/ExtraListener.cs", "mode": "33188", "license": "mit", "language": [ { "name": "C#", "bytes": "63006" } ], "symlink_target": "" }
/*! @file verilog_parser.h @brief A nice interface for the whole verilog parser. @details Provides wrappers around the awkward yylex and yyparse functions, as well as an easy way to change the input stream. @note Functions declared in this file are defined in verilog_parser_wrapper.c */ #include "stdio.h" // Essential to make sure we have access to all of the yy functions. #include "verilog_preprocessor.h" #ifndef H_VERILOG_PARSER #define H_VERILOG_PARSER #ifndef YY_TYPEDEF_YY_SIZE_T #define YY_TYPEDEF_YY_SIZE_T typedef size_t yy_size_t; #endif #ifndef YY_BUF_SIZE #define YY_BUF_SIZE 16384 #endif typedef struct yy_buffer_state *YY_BUFFER_STATE; extern void yyrestart (FILE *input_file ); extern void yy_switch_to_buffer (YY_BUFFER_STATE new_buffer ); extern YY_BUFFER_STATE yy_create_buffer (FILE *file,int size ); extern YY_BUFFER_STATE yy_scan_buffer (char *base,yy_size_t size ); extern YY_BUFFER_STATE yy_scan_bytes (const char *bytes,int len ); extern void yy_delete_buffer (YY_BUFFER_STATE b ); /*! @defgroup parser-api Verilog Parser API @{ @brief Describes the top level, programmer facing parser API. */ /*! @brief Sets up the parsing environment ready for input. @details Makes sure that there is a vaild preprocessor context and source tree object ready to store any parsed constructs. @pre The yy_preproc and yy_verilog_source_tree objects are in an unknown state @post The yy_preproc and yy_verilog_source_tree objects are not NULL, and are certain to be either new or existing contexts ready for parsing. @note Calling this function, parsing a file, and then calling this function again, does *not* destroy the original preprocessor context or source tree. */ void verilog_parser_init(); /*! @brief Perform a parsing operation on the supplied file. @details Parses the supplied file object, adding any parsed constructs to the existing yy_verilog_source_tree object, and using the existing yy_preproc preprocessor context. @param [in] to_parse - The open file object to be parsed. @pre yy_init has been called atleast once, and to_parse is an open and valid file to be read. @post Any valid verilog constructs have been added to the yy_verilog_source_tree global object. @returns An integer describing the result of the parse operation. If the return value is a zero, the file was parsed successfully. If it takes any other value, the file parsed was syntactically invalid. @note In the event of an invalid file being parsed, then the yy_verilog_source_tree object will only contain upto, but not including, the most recently valid parsed object. For example, when the following source is parsed: module valid_module(); initial begin $display("This module is valid"); end endmodule module invalid_module(); initial begin $display("This module is syntactically invalid"); endmodule then the first "valid_module" object will be added to the source tree, but the second will not. */ int verilog_parse_file(FILE * to_parse); /*! @brief Perform a parsing operation on the supplied in-memory string. @details Parses the supplied string, reading at most "length" bytes, adding any parsed constructs to the existing yy_verilog_source_tree object, and using the existing yy_preproc preprocessor context. @param [in] to_parse - The string to be parsed. @param [in] length - How many characters of to_parse to process. @pre yy_init has been called atleast once, and to_parse is an accessible array of characters. @post Any valid verilog constructs have been added to the yy_verilog_source_tree global object. @returns An integer describing the result of the parse operation. If the return value is a zero, the file was parsed successfully. If it takes any other value, the file parsed was syntactically invalid. @warning This function will create a copy of to_parse, and so is not destructive to the originally passed variable. If you would rather not create a copy, then use the verilog_parse_buffer function. @note In the event of an invalid file being parsed, then the yy_verilog_source_tree object will only contain upto, but not including, the most recently valid parsed object. For example, when the following source is parsed: module valid_module(); initial begin $display("This module is valid"); end endmodule module invalid_module(); initial begin $display("This module is syntactically invalid"); endmodule then the first "valid_module" object will be added to the source tree, but the second will not. */ int verilog_parse_string(char * to_parse, int length); /*! @brief Perform a parsing operation on the supplied in-memory string. @details Parses the supplied string, reading at most "length" bytes, adding any parsed constructs to the existing yy_verilog_source_tree object, and using the existing yy_preproc preprocessor context. @param [in] to_parse - The string to be parsed. @param [in] length - How many characters of to_parse to process. @pre yy_init has been called atleast once, and to_parse is an accessible array of characters. @post Any valid verilog constructs have been added to the yy_verilog_source_tree global object. @returns An integer describing the result of the parse operation. If the return value is a zero, the file was parsed successfully. If it takes any other value, the file parsed was syntactically invalid. @warning This function does not create a copy of the to_parse data, and will destroy the contents of the buffer. If you would rather the function operate on a copy of the data instead, please use the verilog_parse_string function. @note In the event of an invalid file being parsed, then the yy_verilog_source_tree object will only contain upto, but not including, the most recently valid parsed object. For example, when the following source is parsed: module valid_module(); initial begin $display("This module is valid"); end endmodule module invalid_module(); initial begin $display("This module is syntactically invalid"); endmodule then the first "valid_module" object will be added to the source tree, but the second will not. */ int verilog_parse_buffer(char * to_parse, int length); /*! }@ */ #endif
{ "content_hash": "001cbf188d0ce41098c19d98ef799e84", "timestamp": "", "source": "github", "line_count": 166, "max_line_length": 80, "avg_line_length": 38.08433734939759, "alnum_prop": 0.7505536222714331, "repo_name": "ben-marshall/verilog-parser", "id": "83a65e1724b71b4860e06fe02c8422db4bbb1cba", "size": "6322", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/verilog_parser.h", "mode": "33188", "license": "mit", "language": [ { "name": "C", "bytes": "247192" }, { "name": "C++", "bytes": "9757" }, { "name": "CMake", "bytes": "4301" }, { "name": "Lex", "bytes": "24509" }, { "name": "Makefile", "bytes": "1047" }, { "name": "Shell", "bytes": "8221" }, { "name": "Verilog", "bytes": "10985" }, { "name": "Yacc", "bytes": "147366" } ], "symlink_target": "" }
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("ExampleCommon")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("ExampleCommon")] [assembly: AssemblyCopyright("Copyright © 2013")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("6af9ca57-eca5-4c65-8fbe-7a00f00f9721")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
{ "content_hash": "b62f76af54a777d2bc793196c9e5af07", "timestamp": "", "source": "github", "line_count": 36, "max_line_length": 84, "avg_line_length": 38.861111111111114, "alnum_prop": 0.7455325232308792, "repo_name": "martindevans/AlchemyApiSharp", "id": "57c96562cbf50687ce01a86468a405258047ec15", "size": "1402", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "ExampleCommon/Properties/AssemblyInfo.cs", "mode": "33188", "license": "mit", "language": [ { "name": "C#", "bytes": "75853" } ], "symlink_target": "" }
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <!--NewPage--> <HTML> <HEAD> <!-- Generated by javadoc (build 1.6.0_24) on Fri Feb 22 14:06:13 EET 2013 --> <META http-equiv="Content-Type" content="text/html; charset=UTF-8"> <TITLE> Uses of Class javalabra.chess.core.impl.MoveDirectorImpl (Chess 0.0.1-SNAPSHOT API) </TITLE> <META NAME="date" CONTENT="2013-02-22"> <LINK REL ="stylesheet" TYPE="text/css" HREF="../../../../../stylesheet.css" TITLE="Style"> <SCRIPT type="text/javascript"> function windowTitle() { if (location.href.indexOf('is-external=true') == -1) { parent.document.title="Uses of Class javalabra.chess.core.impl.MoveDirectorImpl (Chess 0.0.1-SNAPSHOT API)"; } } </SCRIPT> <NOSCRIPT> </NOSCRIPT> </HEAD> <BODY BGCOLOR="white" onload="windowTitle();"> <HR> <!-- ========= START OF TOP NAVBAR ======= --> <A NAME="navbar_top"><!-- --></A> <A HREF="#skip-navbar_top" title="Skip navigation links"></A> <TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0" SUMMARY=""> <TR> <TD COLSPAN=2 BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A NAME="navbar_top_firstrow"><!-- --></A> <TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3" SUMMARY=""> <TR ALIGN="center" VALIGN="top"> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../overview-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../package-summary.html"><FONT CLASS="NavBarFont1"><B>Package</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../javalabra/chess/core/impl/MoveDirectorImpl.html" title="class in javalabra.chess.core.impl"><FONT CLASS="NavBarFont1"><B>Class</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> &nbsp;<FONT CLASS="NavBarFont1Rev"><B>Use</B></FONT>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../package-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../index-all.html"><FONT CLASS="NavBarFont1"><B>Index</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A>&nbsp;</TD> </TR> </TABLE> </TD> <TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM> </EM> </TD> </TR> <TR> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> &nbsp;PREV&nbsp; &nbsp;NEXT</FONT></TD> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> <A HREF="../../../../../index.html?javalabra/chess/core/impl//class-useMoveDirectorImpl.html" target="_top"><B>FRAMES</B></A> &nbsp; &nbsp;<A HREF="MoveDirectorImpl.html" target="_top"><B>NO FRAMES</B></A> &nbsp; &nbsp;<SCRIPT type="text/javascript"> <!-- if(window==top) { document.writeln('<A HREF="../../../../../allclasses-noframe.html"><B>All Classes</B></A>'); } //--> </SCRIPT> <NOSCRIPT> <A HREF="../../../../../allclasses-noframe.html"><B>All Classes</B></A> </NOSCRIPT> </FONT></TD> </TR> </TABLE> <A NAME="skip-navbar_top"></A> <!-- ========= END OF TOP NAVBAR ========= --> <HR> <CENTER> <H2> <B>Uses of Class<br>javalabra.chess.core.impl.MoveDirectorImpl</B></H2> </CENTER> No usage of javalabra.chess.core.impl.MoveDirectorImpl <P> <HR> <!-- ======= START OF BOTTOM NAVBAR ====== --> <A NAME="navbar_bottom"><!-- --></A> <A HREF="#skip-navbar_bottom" title="Skip navigation links"></A> <TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0" SUMMARY=""> <TR> <TD COLSPAN=2 BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A NAME="navbar_bottom_firstrow"><!-- --></A> <TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3" SUMMARY=""> <TR ALIGN="center" VALIGN="top"> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../overview-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../package-summary.html"><FONT CLASS="NavBarFont1"><B>Package</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../javalabra/chess/core/impl/MoveDirectorImpl.html" title="class in javalabra.chess.core.impl"><FONT CLASS="NavBarFont1"><B>Class</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> &nbsp;<FONT CLASS="NavBarFont1Rev"><B>Use</B></FONT>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../package-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../index-all.html"><FONT CLASS="NavBarFont1"><B>Index</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A>&nbsp;</TD> </TR> </TABLE> </TD> <TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM> </EM> </TD> </TR> <TR> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> &nbsp;PREV&nbsp; &nbsp;NEXT</FONT></TD> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> <A HREF="../../../../../index.html?javalabra/chess/core/impl//class-useMoveDirectorImpl.html" target="_top"><B>FRAMES</B></A> &nbsp; &nbsp;<A HREF="MoveDirectorImpl.html" target="_top"><B>NO FRAMES</B></A> &nbsp; &nbsp;<SCRIPT type="text/javascript"> <!-- if(window==top) { document.writeln('<A HREF="../../../../../allclasses-noframe.html"><B>All Classes</B></A>'); } //--> </SCRIPT> <NOSCRIPT> <A HREF="../../../../../allclasses-noframe.html"><B>All Classes</B></A> </NOSCRIPT> </FONT></TD> </TR> </TABLE> <A NAME="skip-navbar_bottom"></A> <!-- ======== END OF BOTTOM NAVBAR ======= --> <HR> Copyright &#169; 2013. All Rights Reserved. </BODY> </HTML>
{ "content_hash": "0233c07b1b52ae7d461ee79435f38a1f", "timestamp": "", "source": "github", "line_count": 145, "max_line_length": 224, "avg_line_length": 42.13103448275862, "alnum_prop": 0.6200687510230807, "repo_name": "nfrolov/useless-chess", "id": "6a33847b899bf2c8db9236907d9d62ebd4430871", "size": "6109", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "javadoc/javalabra/chess/core/impl/class-use/MoveDirectorImpl.html", "mode": "33188", "license": "mit", "language": [ { "name": "Java", "bytes": "83246" } ], "symlink_target": "" }
package mywebsocket import ( "net/http" "github.com/gorilla/websocket" ) // Server websocket type Server struct { clientCount int clients map[int]*Client // channels addClientCh chan *Client removeClientCh chan *Client messageCh chan *message } type message struct { Room string `json:"-"` Type string `json:"type"` Body interface{} `json:"body"` } var upgrader = websocket.Upgrader{ ReadBufferSize: 1024, WriteBufferSize: 1024, } // NewServer websocket func NewServer() *Server { return &Server{ clientCount: 0, clients: map[int]*Client{}, addClientCh: make(chan *Client), removeClientCh: make(chan *Client), messageCh: make(chan *message), } } func (server *Server) addClient(client *Client) { server.clientCount++ client.ID = server.clientCount server.clients[client.ID] = client } func (server *Server) removeClient(client *Client) { delete(server.clients, client.ID) } func (server *Server) sendMessage(message *message) { for _, client := range server.clients { if client.Room != message.Room { continue } client.sendCh <- message } } // Send roomに居るユーザーに対し,bodyを配信する func (server *Server) Send(room, typeStr string, body interface{}) { message := &message{Room: room, Type: typeStr, Body: body} server.messageCh <- message } // Start websocket待受 func (server *Server) Start() { for { select { case client := <-server.addClientCh: server.addClient(client) case client := <-server.removeClientCh: server.removeClient(client) case message := <-server.messageCh: server.sendMessage(message) } } } // WebsocketServe websocket func (server *Server) WebsocketServe(room string, w http.ResponseWriter, r *http.Request) { conn, err := upgrader.Upgrade(w, r, nil) if err != nil { return } client := NewClient(room, conn, server) server.addClientCh <- client go client.writePump() } // WebsocketServeHandler websocket func (server *Server) WebsocketServeHandler(room string) func(http.ResponseWriter, *http.Request) { return func(w http.ResponseWriter, r *http.Request) { server.WebsocketServe(room, w, r) } }
{ "content_hash": "80b3211383478ef33eee24488357fd83", "timestamp": "", "source": "github", "line_count": 96, "max_line_length": 99, "avg_line_length": 22.239583333333332, "alnum_prop": 0.7002341920374707, "repo_name": "misoten-iw-g2/lovechan", "id": "305bee3c61269f16090e282bc97d41c4d3aa0bdf", "size": "2169", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "go/src/app/mywebsocket/server.go", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "18915" }, { "name": "Go", "bytes": "91499" }, { "name": "HTML", "bytes": "33713" }, { "name": "JavaScript", "bytes": "2949075" }, { "name": "Makefile", "bytes": "6784" }, { "name": "Shell", "bytes": "630" } ], "symlink_target": "" }
<?xml version="1.0" encoding="UTF-8"?> <!-- ~ Copyright 2018 NAVER Corp. ~ ~ Licensed under the Apache License, Version 2.0 (the "License"); ~ you may not use this file except in compliance with the License. ~ You may obtain a copy of the License at ~ ~ http://www.apache.org/licenses/LICENSE-2.0 ~ ~ Unless required by applicable law or agreed to in writing, software ~ distributed under the License is distributed on an "AS IS" BASIS, ~ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ~ See the License for the specific language governing permissions and ~ limitations under the License. --> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd"> <modelVersion>4.0.0</modelVersion> <parent> <groupId>com.navercorp.pinpoint</groupId> <artifactId>pinpoint-plugins-it</artifactId> <version>2.0.3-SNAPSHOT</version> </parent> <artifactId>pinpoint-grpc-plugin-it</artifactId> <packaging>jar</packaging> <properties> <jdk.version>1.7</jdk.version> <jdk.home>${env.JAVA_7_HOME}</jdk.home> <grpc.version>1.14.0</grpc.version> <protoc.version>3.5.1-1</protoc.version> </properties> <dependencies> <dependency> <groupId>io.grpc</groupId> <artifactId>grpc-protobuf</artifactId> <version>${grpc.version}</version> <scope>test</scope> </dependency> <dependency> <groupId>io.grpc</groupId> <artifactId>grpc-stub</artifactId> <version>${grpc.version}</version> <scope>test</scope> </dependency> <dependency> <groupId>io.grpc</groupId> <artifactId>grpc-netty</artifactId> <version>${grpc.version}</version> <scope>test</scope> </dependency> <!-- netty.io --> <dependency> <groupId>io.netty</groupId> <artifactId>netty-all</artifactId> <!-- Use 'netty-all' for 4.0 or above --> <version>${netty4.version}</version> <scope>test</scope> </dependency> <dependency> <groupId>com.navercorp.pinpoint</groupId> <artifactId>pinpoint-plugin-it-utils</artifactId> <version>${project.version}</version> </dependency> </dependencies> <build> <plugins> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-surefire-plugin</artifactId> <configuration> <skip>true</skip> </configuration> </plugin> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-failsafe-plugin</artifactId> </plugin> <plugin> <groupId>org.xolstice.maven.plugins</groupId> <artifactId>protobuf-maven-plugin</artifactId> <version>0.5.1</version> <configuration> <protocArtifact>com.google.protobuf:protoc:${protoc.version}:exe:${os.detected.classifier}</protocArtifact> <pluginId>grpc-java</pluginId> <pluginArtifact>io.grpc:protoc-gen-grpc-java:${grpc.version}:exe:${os.detected.classifier}</pluginArtifact> </configuration> <executions> <execution> <goals> <goal>test-compile</goal> <goal>test-compile-custom</goal> </goals> </execution> </executions> </plugin> </plugins> </build> </project>
{ "content_hash": "582eb965fab74cacccecf6f0e2dc637a", "timestamp": "", "source": "github", "line_count": 107, "max_line_length": 127, "avg_line_length": 36.794392523364486, "alnum_prop": 0.5595631191262382, "repo_name": "suraj-raturi/pinpoint", "id": "daaa23d656d912e60b24db6cc68aeda98acd7cab", "size": "3937", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "plugins-it/google-grpc-it/pom.xml", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Batchfile", "bytes": "22853" }, { "name": "CSS", "bytes": "133944" }, { "name": "CoffeeScript", "bytes": "10124" }, { "name": "Groovy", "bytes": "1423" }, { "name": "HTML", "bytes": "473809" }, { "name": "Java", "bytes": "8699243" }, { "name": "JavaScript", "bytes": "2277035" }, { "name": "Makefile", "bytes": "5246" }, { "name": "PLSQL", "bytes": "4156" }, { "name": "Python", "bytes": "3523" }, { "name": "Ruby", "bytes": "943" }, { "name": "Shell", "bytes": "30663" }, { "name": "Thrift", "bytes": "7543" } ], "symlink_target": "" }
package com.lugia.timetable; import java.util.ArrayList; import java.util.List; import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.HttpStatus; import org.apache.http.NameValuePair; import org.apache.http.client.entity.UrlEncodedFormEntity; import org.apache.http.client.methods.HttpGet; import org.apache.http.client.methods.HttpPost; import org.apache.http.message.BasicNameValuePair; import org.apache.http.util.EntityUtils; import android.os.Bundle; import android.app.Activity; import android.app.AlertDialog; import android.app.ProgressDialog; import android.content.Context; import android.content.DialogInterface; import android.text.Editable; import android.text.TextWatcher; import android.util.Log; import android.view.View; import android.view.View.OnClickListener; import android.view.inputmethod.InputMethodManager; import android.widget.Button; import android.widget.EditText; import android.widget.Toast; /** * Activity that allow user to enter MMU ID and password to retrieve their course data. */ public class LoginActivity extends Activity implements OnClickListener, TextWatcher { private Button mContinueButton; private EditText mMmuIdInput; private EditText mPasswordInput; private ProgressDialog mProgressDialog; public static final String LOGIN_URL = "https://icems.mmu.edu.my/sic/vlogin.jsp"; public static final String COURSE_URL = "https://icems.mmu.edu.my/sic/courses/crdetails_02.jsp"; public static final String LOGIN_ID_NAME = "id"; public static final String LOGIN_PASSWORD_NAME = "pwd"; private static final String TAG = "LoginActivity"; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_login); mMmuIdInput = (EditText)findViewById(R.id.input_mmu_id); mMmuIdInput.addTextChangedListener(LoginActivity.this); mPasswordInput = (EditText)findViewById(R.id.input_password); mPasswordInput.addTextChangedListener(LoginActivity.this); mContinueButton = (Button)findViewById(R.id.button_continue); mContinueButton.setOnClickListener(this); } public void onClick(View v) { // not continue button? i really not sure what you have clicked. if (v.getId() != R.id.button_continue) return; String mmuid = mMmuIdInput.getText().toString(); String password = mPasswordInput.getText().toString(); InputMethodManager imm = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE); imm.hideSoftInputFromWindow(v.getApplicationWindowToken(), 0); mProgressDialog = ProgressDialog.show(LoginActivity.this, "", "Please wait...", true, false); mProgressDialog.setCancelable(false); LoginThread thread = new LoginThread(mmuid, password); thread.start(); } public void afterTextChanged(Editable s) { // only enable Continue button when both input is not empty if (mMmuIdInput.getText().length() > 0 && mPasswordInput.getText().length() > 0) mContinueButton.setEnabled(true); else mContinueButton.setEnabled(false); } public void beforeTextChanged(CharSequence s, int start, int count, int after) { /* Do Nothing */ } public void onTextChanged(CharSequence s, int start, int before, int count) { /* Do Nothing */ } private void setProgressMessage(final CharSequence message) { runOnUiThread(new Runnable() { public void run() { mProgressDialog.setMessage(message); } }); } private void dismissProgressDialog() { runOnUiThread(new Runnable() { public void run() { mProgressDialog.dismiss(); } }); } private void displayLoginFailDialog() { runOnUiThread(new Runnable() { public void run() { // notify user new AlertDialog.Builder(LoginActivity.this) .setTitle("Opps!") .setMessage("Fail to download course data, please make sure you have entered a correct MMU ID and password.") .setPositiveButton("Close", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { } }) .create() .show(); } }); } private void showSuccessToast() { runOnUiThread(new Runnable() { public void run() { Toast.makeText(LoginActivity.this, "Course detail downloaded successfully.", Toast.LENGTH_SHORT).show(); } }); } private final class LoginThread extends Thread { private String mMmuId; private String mPassword; public LoginThread(String mmuId, String password) { mMmuId = mmuId; mPassword = password; } public void run() { try { SSLHttpClient client = SSLHttpClient.getHttpClient(); List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2); nameValuePairs.add(new BasicNameValuePair(LOGIN_ID_NAME, mMmuId )); nameValuePairs.add(new BasicNameValuePair(LOGIN_PASSWORD_NAME, mPassword)); HttpPost loginPost = new HttpPost(LOGIN_URL); loginPost.setEntity(new UrlEncodedFormEntity(nameValuePairs)); setProgressMessage("Logging in..."); // try to login client.executeResponse(loginPost); setProgressMessage("Getting course detail..."); HttpGet courseGet = new HttpGet(COURSE_URL); HttpResponse response = client.executeResponse(courseGet); // try to get the course detail if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK) { Log.d(TAG, String.format("HTTP Status: %d", response.getStatusLine().getStatusCode())); return; } HttpEntity entity = response.getEntity(); if (entity == null) { Log.d(TAG, "HTTP Entity is null!"); return; } setProgressMessage("Reading course detail..."); String content = EntityUtils.toString(entity); ArrayList<Subject> temp = CourseParser.tryParse(content); dismissProgressDialog(); // subject list is null? there must be a problem if (temp == null) { displayLoginFailDialog(); return; } SubjectList subjectList = SubjectList.getInstance(LoginActivity.this); subjectList.replace(temp); // for debug purpose subjectList.displaySubjectListContent(); subjectList.saveToFile(LoginActivity.this); showSuccessToast(); setResult(RESULT_OK); finish(); } catch (Exception e) { // Something went wrong Log.e(TAG, "Error on fetching data!", e); } } } }
{ "content_hash": "f4e25e98ffa55278bd925300a4611870", "timestamp": "", "source": "github", "line_count": 239, "max_line_length": 129, "avg_line_length": 34.63179916317991, "alnum_prop": 0.5564818170834843, "repo_name": "Lugia0529/MMUTimeTable", "id": "020cd0a06bbdc2a023093b6fa6c6145e28892ef5", "size": "8894", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "app/src/main/java/com/lugia/timetable/LoginActivity.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "181995" } ], "symlink_target": "" }
sap.ui.define([ "sap/ui/core/UIComponent" ], function (UIComponent) { "use strict"; return UIComponent.extend("sap.m.sample.TableSelectDialog.Component", { metadata: { manifest: "json" } }); });
{ "content_hash": "1ecb11ee65c01af855e1f481e350f6e3", "timestamp": "", "source": "github", "line_count": 13, "max_line_length": 72, "avg_line_length": 16, "alnum_prop": 0.6634615384615384, "repo_name": "SAP/openui5", "id": "f2048a7864a9056aa7f3ea51966615bd35dda574", "size": "208", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/sap.m/test/sap/m/demokit/sample/TableSelectDialog/Component.js", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "294216" }, { "name": "Gherkin", "bytes": "17201" }, { "name": "HTML", "bytes": "6443688" }, { "name": "Java", "bytes": "83398" }, { "name": "JavaScript", "bytes": "109546491" }, { "name": "Less", "bytes": "8741757" }, { "name": "TypeScript", "bytes": "20918" } ], "symlink_target": "" }
name: Alice Harpole ---
{ "content_hash": "229621e7f31538bf18d9230fe438a833", "timestamp": "", "source": "github", "line_count": 2, "max_line_length": 19, "avg_line_length": 12, "alnum_prop": 0.6666666666666666, "repo_name": "PyconUK/2017.pyconuk.org", "id": "2287aefa9e626c79856dbed5fd1ec7d6c19425cc", "size": "24", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "speakers/alice-harpole.md", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "22262" }, { "name": "HTML", "bytes": "12130" }, { "name": "Makefile", "bytes": "537" }, { "name": "Python", "bytes": "30010" }, { "name": "Shell", "bytes": "2377" } ], "symlink_target": "" }
package xparam import "fmt" //------------------------------------------------------------ // Xparam access for string maps //------------------------------------------------------------ // Gets parameter as map of string to sting. func (xp XP) As_MapString(key string) (data map[string]string) { if val, ok := xp[key]; ok && val != nil { if amap, ok := val.(map[string]interface{}); ok { data = map[string]string{} for k, v := range amap { if v != nil { data[k] = fmt.Sprint(v) } } return } } return }
{ "content_hash": "4c85fc0376f3d9fbd634d1ac52da8612", "timestamp": "", "source": "github", "line_count": 24, "max_line_length": 64, "avg_line_length": 22.458333333333332, "alnum_prop": 0.45269016697588127, "repo_name": "deze333/xparam", "id": "536ab4adaf8ed2fd31a1e6cb9b24ffd3657eb908", "size": "539", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "xp_map_string.go", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Go", "bytes": "14695" } ], "symlink_target": "" }
<?php namespace Brasa\ContabilidadBundle\Entity; use Doctrine\ORM\Mapping as ORM; use Symfony\Component\Validator\Constraints as Assert; /** * @ORM\Table(name="ctb_asiento") * @ORM\Entity(repositoryClass="Brasa\ContabilidadBundle\Repository\CtbAsientoRepository") */ class CtbAsiento { /** * @ORM\Id * @ORM\Column(name="codigo_asiento_pk", type="integer") * @ORM\GeneratedValue(strategy="AUTO") */ private $codigoAsientoPk; /** * @ORM\Column(name="numero_asiento", type="string", length=30, nullable=true) */ private $numeroAsiento; /** * @ORM\Column(name="soporte", type="string", length=30, nullable=true) */ private $soporte; /** * @ORM\Column(name="fecha", type="date", nullable=true) */ private $fecha; /** * @ORM\Column(name="fecha_creacion", type="date", nullable=true) */ private $fecha_creacion; /** * @ORM\Column(name="codigo_comprobante_fk", type="integer", nullable=true) */ private $codigoComprobanteFk; /** * @ORM\Column(name="estado_autorizado", type="boolean") */ private $estadoAutorizado = 0; /** * @ORM\Column(name="estado_impreso", type="boolean") */ private $estadoImpreso = 0; /** * @ORM\Column(name="estado_aprobado", type="boolean") */ private $estadoAprobado = 0; /** * @ORM\Column(name="estado_anulado", type="boolean") */ private $estadoAnulado = 0; /** * @ORM\Column(name="estado_contabilizado", type="boolean") */ private $estadoContabilizado = 0; /** * @ORM\Column(name="total_debito", type="float") */ private $totalDebito = 0; /** * @ORM\Column(name="total_credito", type="float") */ private $totalCredito = 0; /** * @ORM\Column(name="diferencia", type="float") */ private $diferencia = 0; /** * @ORM\Column(name="comentarios", type="string", length=200, nullable=true) */ private $comentarios; /** * @ORM\ManyToOne(targetEntity="CtbComprobante", inversedBy="asientosComprobanteRel") * @ORM\JoinColumn(name="codigo_comprobante_fk", referencedColumnName="codigo_comprobante_pk") */ protected $comprobanteRel; /** * @ORM\OneToMany(targetEntity="CtbAsientoDetalle", mappedBy="asientoRel") */ protected $asientosDetallesAsientoRel; /** * Constructor */ public function __construct() { $this->asientosDetallesAsientoRel = new \Doctrine\Common\Collections\ArrayCollection(); } /** * Get codigoAsientoPk * * @return integer */ public function getCodigoAsientoPk() { return $this->codigoAsientoPk; } /** * Set numeroAsiento * * @param string $numeroAsiento * * @return CtbAsiento */ public function setNumeroAsiento($numeroAsiento) { $this->numeroAsiento = $numeroAsiento; return $this; } /** * Get numeroAsiento * * @return string */ public function getNumeroAsiento() { return $this->numeroAsiento; } /** * Set soporte * * @param string $soporte * * @return CtbAsiento */ public function setSoporte($soporte) { $this->soporte = $soporte; return $this; } /** * Get soporte * * @return string */ public function getSoporte() { return $this->soporte; } /** * Set fecha * * @param \DateTime $fecha * * @return CtbAsiento */ public function setFecha($fecha) { $this->fecha = $fecha; return $this; } /** * Get fecha * * @return \DateTime */ public function getFecha() { return $this->fecha; } /** * Set fechaCreacion * * @param \DateTime $fechaCreacion * * @return CtbAsiento */ public function setFechaCreacion($fechaCreacion) { $this->fecha_creacion = $fechaCreacion; return $this; } /** * Get fechaCreacion * * @return \DateTime */ public function getFechaCreacion() { return $this->fecha_creacion; } /** * Set codigoComprobanteFk * * @param integer $codigoComprobanteFk * * @return CtbAsiento */ public function setCodigoComprobanteFk($codigoComprobanteFk) { $this->codigoComprobanteFk = $codigoComprobanteFk; return $this; } /** * Get codigoComprobanteFk * * @return integer */ public function getCodigoComprobanteFk() { return $this->codigoComprobanteFk; } /** * Set estadoAutorizado * * @param boolean $estadoAutorizado * * @return CtbAsiento */ public function setEstadoAutorizado($estadoAutorizado) { $this->estadoAutorizado = $estadoAutorizado; return $this; } /** * Get estadoAutorizado * * @return boolean */ public function getEstadoAutorizado() { return $this->estadoAutorizado; } /** * Set estadoImpreso * * @param boolean $estadoImpreso * * @return CtbAsiento */ public function setEstadoImpreso($estadoImpreso) { $this->estadoImpreso = $estadoImpreso; return $this; } /** * Get estadoImpreso * * @return boolean */ public function getEstadoImpreso() { return $this->estadoImpreso; } /** * Set estadoAprobado * * @param boolean $estadoAprobado * * @return CtbAsiento */ public function setEstadoAprobado($estadoAprobado) { $this->estadoAprobado = $estadoAprobado; return $this; } /** * Get estadoAprobado * * @return boolean */ public function getEstadoAprobado() { return $this->estadoAprobado; } /** * Set estadoAnulado * * @param boolean $estadoAnulado * * @return CtbAsiento */ public function setEstadoAnulado($estadoAnulado) { $this->estadoAnulado = $estadoAnulado; return $this; } /** * Get estadoAnulado * * @return boolean */ public function getEstadoAnulado() { return $this->estadoAnulado; } /** * Set estadoContabilizado * * @param boolean $estadoContabilizado * * @return CtbAsiento */ public function setEstadoContabilizado($estadoContabilizado) { $this->estadoContabilizado = $estadoContabilizado; return $this; } /** * Get estadoContabilizado * * @return boolean */ public function getEstadoContabilizado() { return $this->estadoContabilizado; } /** * Set totalDebito * * @param float $totalDebito * * @return CtbAsiento */ public function setTotalDebito($totalDebito) { $this->totalDebito = $totalDebito; return $this; } /** * Get totalDebito * * @return float */ public function getTotalDebito() { return $this->totalDebito; } /** * Set totalCredito * * @param float $totalCredito * * @return CtbAsiento */ public function setTotalCredito($totalCredito) { $this->totalCredito = $totalCredito; return $this; } /** * Get totalCredito * * @return float */ public function getTotalCredito() { return $this->totalCredito; } /** * Set diferencia * * @param float $diferencia * * @return CtbAsiento */ public function setDiferencia($diferencia) { $this->diferencia = $diferencia; return $this; } /** * Get diferencia * * @return float */ public function getDiferencia() { return $this->diferencia; } /** * Set comentarios * * @param string $comentarios * * @return CtbAsiento */ public function setComentarios($comentarios) { $this->comentarios = $comentarios; return $this; } /** * Get comentarios * * @return string */ public function getComentarios() { return $this->comentarios; } /** * Set comprobanteRel * * @param \Brasa\ContabilidadBundle\Entity\CtbComprobante $comprobanteRel * * @return CtbAsiento */ public function setComprobanteRel(\Brasa\ContabilidadBundle\Entity\CtbComprobante $comprobanteRel = null) { $this->comprobanteRel = $comprobanteRel; return $this; } /** * Get comprobanteRel * * @return \Brasa\ContabilidadBundle\Entity\CtbComprobante */ public function getComprobanteRel() { return $this->comprobanteRel; } /** * Add asientosDetallesAsientoRel * * @param \Brasa\ContabilidadBundle\Entity\CtbAsientoDetalle $asientosDetallesAsientoRel * * @return CtbAsiento */ public function addAsientosDetallesAsientoRel(\Brasa\ContabilidadBundle\Entity\CtbAsientoDetalle $asientosDetallesAsientoRel) { $this->asientosDetallesAsientoRel[] = $asientosDetallesAsientoRel; return $this; } /** * Remove asientosDetallesAsientoRel * * @param \Brasa\ContabilidadBundle\Entity\CtbAsientoDetalle $asientosDetallesAsientoRel */ public function removeAsientosDetallesAsientoRel(\Brasa\ContabilidadBundle\Entity\CtbAsientoDetalle $asientosDetallesAsientoRel) { $this->asientosDetallesAsientoRel->removeElement($asientosDetallesAsientoRel); } /** * Get asientosDetallesAsientoRel * * @return \Doctrine\Common\Collections\Collection */ public function getAsientosDetallesAsientoRel() { return $this->asientosDetallesAsientoRel; } }
{ "content_hash": "8ae193c2b9718b4af88b44c9a3e73cb8", "timestamp": "", "source": "github", "line_count": 515, "max_line_length": 132, "avg_line_length": 19.924271844660193, "alnum_prop": 0.5646623136146575, "repo_name": "wariox3/brasa", "id": "16620bf0b1d1a53be711333cb682bb221982b056", "size": "10261", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/Brasa/ContabilidadBundle/Entity/CtbAsiento.php", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "122817" }, { "name": "HTML", "bytes": "3724591" }, { "name": "JavaScript", "bytes": "382852" }, { "name": "PHP", "bytes": "12584043" }, { "name": "Shell", "bytes": "4440" }, { "name": "TSQL", "bytes": "1403931" } ], "symlink_target": "" }
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <!--NewPage--> <HTML> <HEAD> <!-- Generated by javadoc (build 1.6.0_26) on Tue May 08 20:32:57 UTC 2012 --> <TITLE> org.apache.hadoop.mapreduce.lib.partition (Hadoop 1.0.3 API) </TITLE> <META NAME="date" CONTENT="2012-05-08"> <LINK REL ="stylesheet" TYPE="text/css" HREF="../../../../../../stylesheet.css" TITLE="Style"> </HEAD> <BODY BGCOLOR="white"> <FONT size="+1" CLASS="FrameTitleFont"> <A HREF="../../../../../../org/apache/hadoop/mapreduce/lib/partition/package-summary.html" target="classFrame">org.apache.hadoop.mapreduce.lib.partition</A></FONT> <TABLE BORDER="0" WIDTH="100%" SUMMARY=""> <TR> <TD NOWRAP><FONT size="+1" CLASS="FrameHeadingFont"> Interfaces</FONT>&nbsp; <FONT CLASS="FrameItemFont"> <BR> <A HREF="InputSampler.Sampler.html" title="interface in org.apache.hadoop.mapreduce.lib.partition" target="classFrame"><I>InputSampler.Sampler</I></A></FONT></TD> </TR> </TABLE> <TABLE BORDER="0" WIDTH="100%" SUMMARY=""> <TR> <TD NOWRAP><FONT size="+1" CLASS="FrameHeadingFont"> Classes</FONT>&nbsp; <FONT CLASS="FrameItemFont"> <BR> <A HREF="BinaryPartitioner.html" title="class in org.apache.hadoop.mapreduce.lib.partition" target="classFrame">BinaryPartitioner</A> <BR> <A HREF="HashPartitioner.html" title="class in org.apache.hadoop.mapreduce.lib.partition" target="classFrame">HashPartitioner</A> <BR> <A HREF="InputSampler.html" title="class in org.apache.hadoop.mapreduce.lib.partition" target="classFrame">InputSampler</A> <BR> <A HREF="InputSampler.IntervalSampler.html" title="class in org.apache.hadoop.mapreduce.lib.partition" target="classFrame">InputSampler.IntervalSampler</A> <BR> <A HREF="InputSampler.RandomSampler.html" title="class in org.apache.hadoop.mapreduce.lib.partition" target="classFrame">InputSampler.RandomSampler</A> <BR> <A HREF="InputSampler.SplitSampler.html" title="class in org.apache.hadoop.mapreduce.lib.partition" target="classFrame">InputSampler.SplitSampler</A> <BR> <A HREF="KeyFieldBasedComparator.html" title="class in org.apache.hadoop.mapreduce.lib.partition" target="classFrame">KeyFieldBasedComparator</A> <BR> <A HREF="KeyFieldBasedPartitioner.html" title="class in org.apache.hadoop.mapreduce.lib.partition" target="classFrame">KeyFieldBasedPartitioner</A> <BR> <A HREF="TotalOrderPartitioner.html" title="class in org.apache.hadoop.mapreduce.lib.partition" target="classFrame">TotalOrderPartitioner</A></FONT></TD> </TR> </TABLE> </BODY> </HTML>
{ "content_hash": "5d0a1381e65d825290c559fc6f0dca65", "timestamp": "", "source": "github", "line_count": 59, "max_line_length": 163, "avg_line_length": 42.813559322033896, "alnum_prop": 0.7387173396674585, "repo_name": "zxqt223/hadoop-ha.1.0.3", "id": "be5b87b3e5fb5035e5dcb75d22a214bff046cac6", "size": "2526", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "docs/api/org/apache/hadoop/mapreduce/lib/partition/package-frame.html", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "C", "bytes": "401082" }, { "name": "C++", "bytes": "403118" }, { "name": "Java", "bytes": "16207871" }, { "name": "JavaScript", "bytes": "94382" }, { "name": "Objective-C", "bytes": "119767" }, { "name": "PHP", "bytes": "152555" }, { "name": "Perl", "bytes": "149888" }, { "name": "Python", "bytes": "1129211" }, { "name": "Ruby", "bytes": "28485" }, { "name": "Shell", "bytes": "1287838" }, { "name": "Smalltalk", "bytes": "56562" }, { "name": "XML", "bytes": "217046" } ], "symlink_target": "" }
$LOAD_PATH.unshift File.dirname(__FILE__) $LOAD_PATH.unshift File.dirname(__FILE__) + "/rubyrep" require 'rubygems' require 'yaml' require 'logger' gem 'activerecord', '>= 3.0.5' require 'active_record' require 'version' require 'configuration' require 'initializer' require 'session' require 'connection_extenders/connection_extenders' require 'table_scan_helper' require 'table_scan' require 'type_casting_cursor' require 'proxy_cursor' require 'proxy_block_cursor' require 'proxy_row_cursor' require 'direct_table_scan' require 'proxied_table_scan' require 'database_proxy' require 'command_runner' require 'proxy_runner' require 'proxy_connection' require 'table_spec_resolver' require 'scan_report_printers/scan_report_printers' require 'scan_report_printers/scan_summary_reporter' require 'scan_report_printers/scan_detail_reporter' require 'scan_progress_printers/scan_progress_printers' require 'scan_progress_printers/progress_bar' require 'base_runner' require 'scan_runner' require 'committers/committers' require 'committers/buffered_committer' require 'log_helper' require 'sync_helper' require 'table_sorter' require 'table_sync' require 'syncers/syncers' require 'syncers/two_way_syncer' require 'sync_runner' require 'trigger_mode_switcher' require 'logged_change_loader' require 'logged_change' require 'replication_difference' require 'replication_helper' require 'replicators/replicators' require 'replicators/two_way_replicator' require 'task_sweeper' require 'replication_run' require 'replication_runner' require 'uninstall_runner' require 'generate_runner' require 'noisy_connection' module RR # Returns the logger used by RubyRep. It logs to STDOUT by default if # nothing else is specified via the RR_LOGFILE env variable. The log level # defaults to INFO, but it can also be set via the RR_LOGLEVEL env variable. def self.logger @logger ||= begin file = (ENV['RR_LOGFILE'] && File.expand_path(ENV['RR_LOGFILE'])) || STDOUT level = Logger::INFO if ENV['RR_LOGLEVEL'] # Try to get the correct constant from the logger class env_level = ENV['RR_LOGLEVEL'].upcase level = Logger.const_get(env_level) if Logger.constants.include?(env_level.to_sym) end # Create new logger and return it Logger.new(file).tap do |l| l.level = level l.progname = 'RubyRep' end end end end Dir["#{File.dirname(__FILE__)}/rubyrep/connection_extenders/*.rb"].each do |extender| # jdbc_extender.rb is only loaded if we are running on jruby require extender unless extender =~ /jdbc/ and not RUBY_PLATFORM =~ /java/ end require 'replication_initializer' require 'replication_extenders/replication_extenders' Dir["#{File.dirname(__FILE__)}/rubyrep/replication_extenders/*.rb"].each do |extender| require extender end module RR end
{ "content_hash": "5470b3db4d6f821608d0f981c3785402", "timestamp": "", "source": "github", "line_count": 97, "max_line_length": 90, "avg_line_length": 29.422680412371133, "alnum_prop": 0.7410651716888578, "repo_name": "ncoders/rubyrep", "id": "336003a4065434ce5ebddec5bd96a24a3a53eb08", "size": "2854", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "lib/rubyrep.rb", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "2276" }, { "name": "JavaScript", "bytes": "25082" }, { "name": "Ruby", "bytes": "654490" }, { "name": "Shell", "bytes": "315" } ], "symlink_target": "" }
package org.geogit.api.plumbing; import static com.google.common.base.Preconditions.checkState; import java.util.Iterator; import java.util.List; import javax.annotation.Nullable; import org.geogit.api.AbstractGeoGitOp; import org.geogit.api.ObjectId; import org.geogit.api.RevTree; import org.geogit.api.plumbing.diff.DiffCounter; import org.geogit.api.plumbing.diff.DiffEntry; import org.geogit.api.plumbing.diff.DiffTreeWalk; import org.geogit.storage.StagingDatabase; import com.google.common.base.Optional; import com.google.common.collect.Lists; import com.google.inject.Inject; /** * A faster alternative to count the number of diffs between two trees than walking a * {@link DiffTreeWalk} iterator. * * @see DiffCounter */ public class DiffCount extends AbstractGeoGitOp<Long> { private StagingDatabase index; private final List<String> pathFilters = Lists.newLinkedList(); private String oldRefSpec; private String newRefSpec; private boolean reportTrees; @Inject public DiffCount(StagingDatabase index) { this.index = index; } public DiffCount setOldVersion(@Nullable String refSpec) { this.oldRefSpec = refSpec; return this; } public DiffCount setNewVersion(@Nullable String refSpec) { this.newRefSpec = refSpec; return this; } /** * @param path the path filter to use during the diff operation * @return {@code this} */ public DiffCount addFilter(@Nullable String path) { if (path != null) { pathFilters.add(path); } return this; } /** * @param paths list of paths to filter by, if {@code null} or empty, then no filtering is done, * otherwise the list must not contain null elements. */ public DiffCount setFilter(@Nullable List<String> paths) { pathFilters.clear(); if (paths != null) { pathFilters.addAll(paths); } return this; } @Override public Long call() { checkState(oldRefSpec != null, "old ref spec not provided"); checkState(newRefSpec != null, "new ref spec not provided"); final RevTree oldTree = getTree(oldRefSpec); final RevTree newTree = getTree(newRefSpec); Long diffCount; if (pathFilters.isEmpty()) { DiffCounter counter = new DiffCounter(index, oldTree, newTree); diffCount = counter.get(); } else { DiffTreeWalk treeWalk = new DiffTreeWalk(index, oldTree, newTree); for (String path : pathFilters) { treeWalk.addFilter(path); } treeWalk.setReportTrees(reportTrees); Iterator<DiffEntry> iterator = treeWalk.get(); long count = 0; while (iterator.hasNext()) { iterator.next(); count++; } diffCount = Long.valueOf(count); } return diffCount; } /** * @return the tree referenced by the old ref, or the head of the index. */ private RevTree getTree(String refSpec) { Optional<ObjectId> resolved = command(ResolveTreeish.class).setTreeish(refSpec).call(); if (!resolved.isPresent()) { return RevTree.EMPTY; } ObjectId headTreeId = resolved.get(); final RevTree headTree; if (headTreeId.isNull()) { headTree = RevTree.EMPTY; } else { headTree = command(RevObjectParse.class).setObjectId(headTreeId).call(RevTree.class) .get(); } return headTree; } public DiffCount setReportTrees(boolean reportTrees) { this.reportTrees = reportTrees; return this; } }
{ "content_hash": "1cb83f2528a20500e4e75bb94c200906", "timestamp": "", "source": "github", "line_count": 136, "max_line_length": 100, "avg_line_length": 27.78676470588235, "alnum_prop": 0.6263561788833024, "repo_name": "rouault/GeoGit", "id": "96bd521065b2f49d9e9be9ba2038ef449afe8785", "size": "3936", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/core/src/main/java/org/geogit/api/plumbing/DiffCount.java", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "Java", "bytes": "2837662" }, { "name": "JavaScript", "bytes": "38442" }, { "name": "Python", "bytes": "18719" }, { "name": "Shell", "bytes": "6363" } ], "symlink_target": "" }
RFuzz::HttpClient.class_eval do def self.read_from_path_to_proc(path, proc_callback) uri = URI.parse path FileStorage.log.info "reading from mogilefs '#{path}'" cl = RFuzz::HttpClient.new(uri.host, uri.port) cl.write_to_this_proc = Proc.new do |to_write| proc_callback.call(to_write) end begin resp = cl.send_request(:GET, uri.path, {}) rescue IOError => e raise IOError, "Error reading from '#{path}': #{e.message}" end unless resp.http_status == "200" raise IOError, "mogilefs backend request to GET '#{path}' failed with '#{resp.http_status}'" end FileStorage.log.debug "reading from mogilefs '#{path}' complete" end attr_accessor :write_to_this_proc def read_response resp = RFuzz::HttpResponse.new notify :read_header do resp = read_parsed_header end notify :read_body do if resp.chunked_encoding? raise ArgumentError, "(FileStorage Plugin) Rfuzz Overrides does not support handling responses with chunked encoding" elsif resp[RFuzz::HttpClient::CONTENT_LENGTH] content_length = resp[RFuzz::HttpClient::CONTENT_LENGTH].to_i body_length = resp.http_body.length needs = content_length - body_length #Not doing this # Some requests can actually give a content length, and then not have content # so we ignore HttpClientError exceptions and pray that's good enough # resp.http_body += @sock.read(needs) if needs > 0 rescue RFuzz::HttpClientError #Doing this instead if(resp.http_body.length > 0) self.write_to_this_proc.call(resp.http_body) end total_read_so_far = 0 left_to_read = needs while(left_to_read > 0) amount_to_read = if left_to_read < FileStorage.max_read_size left_to_read else FileStorage.max_read_size end before_read = Time.now before_write = Time.now after_write = Time.now all_time_diffs ||= [] begin if @last_read_completed all_time_diffs << "time size last read completed #{Time.now - @last_read_completed}" end if @last_read_began all_time_diffs << "time size last read began #{Time.now - @last_read_began}" end before_read = Time.now @last_read_began = Time.now next_data_read = @sock.read(amount_to_read) @last_read_completed = Time.now before_write = Time.now self.write_to_this_proc.call(next_data_read) after_write = Time.now @last_time_diff = "#{before_write - before_read} to #{after_write - before_write} (#{Time.now - before_read})" # puts " so far #{needs - left_to_read}. still need #{left_to_read}. Expect block of #{amount_to_read}. total size #{needs}." # puts "time diff on write #{after_write - before_write}" left_to_read -= amount_to_read rescue RFuzz::HttpClientError => e raise IOError, "Mogile Not Responding? Total read so far #{needs - left_to_read}. still need to read #{left_to_read}. " + "Expecting to read a block of #{amount_to_read}. total size to read #{needs}. " + "content_length #{content_length}. body length #{body_length}. "+ "response: #{resp.inspect} " + "\n last time diff: #{@last_time_diff}" + "\n time diff: (#{before_write - before_read} to #{after_write - before_write}) (#{Time.now - before_read})" + "\n all time diffs: #{all_time_diffs.join("\n")}"+ "\n(#{e.backtrace.join("\n")})" # ensure # FileStorage.log.debug{ "Rfuzz read completed #{amount_to_read}, left_to_read: #{left_to_read}, needs: #{needs}" } end end else raise ArgumentError, "(FileStorage Plugin) Rfuzz Overrides does not support handling responses that don't provide a CONTENT_LENGTH header" end end store_cookies(resp) return resp end end
{ "content_hash": "7b9e484cbfaede92c787a66f1246887d", "timestamp": "", "source": "github", "line_count": 103, "max_line_length": 146, "avg_line_length": 41.57281553398058, "alnum_prop": 0.5733302195235871, "repo_name": "brontes3d/file_storage", "id": "95b30d7a8e59aee1d9e906e7b176bb2ffa40d8a3", "size": "4282", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "lib/file_storage/overrides/rfuzz_http_client.rb", "mode": "33188", "license": "mit", "language": [ { "name": "Ruby", "bytes": "108544" } ], "symlink_target": "" }
namespace viz { class AggregatedFrame; class AggregatedRenderPass; // Draws a red outline around the root RenderPasses damage rect. class DamageFrameAnnotator : public SurfaceAggregator::FrameAnnotator { public: DamageFrameAnnotator(); DamageFrameAnnotator(const DamageFrameAnnotator&) = delete; DamageFrameAnnotator& operator=(const DamageFrameAnnotator&) = delete; ~DamageFrameAnnotator() override; // SurfaceAggregator::FrameAnnotator implementation. void AnnotateAggregatedFrame(AggregatedFrame* frame) override; private: struct Highlight { SkColor4f color; int width; }; struct AnnotationData { gfx::Rect rect; gfx::Transform transform; Highlight highlight; }; void AnnotateRootRenderPass(AggregatedRenderPass* render_pass); std::vector<AnnotationData> annotations_; }; } // namespace viz #endif // COMPONENTS_VIZ_SERVICE_DISPLAY_DAMAGE_FRAME_ANNOTATOR_H_
{ "content_hash": "71b643e750835d31f3088e6bb6d5ff86", "timestamp": "", "source": "github", "line_count": 38, "max_line_length": 72, "avg_line_length": 24.210526315789473, "alnum_prop": 0.7641304347826087, "repo_name": "chromium/chromium", "id": "2854968c677665685dd3baffa5c778e8431f10d2", "size": "1402", "binary": false, "copies": "6", "ref": "refs/heads/main", "path": "components/viz/service/display/damage_frame_annotator.h", "mode": "33188", "license": "bsd-3-clause", "language": [], "symlink_target": "" }
<!-- Copyright (C) 2015 The Gravitee team (http://gravitee.io) 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. --> <div class="contextual-doc-container" ng-class="{ open: $ctrl.isOpen }" ng-if="$ctrl.$state.current.name !== 'user'"> <div style="position: fixed"> <div class="contextual-doc-header"> <div class="contextual-doc-header-title"> <h3>Documentation</h3> </div> <div> <a ng-click="$ctrl.openDocumentation()" ><ng-md-icon icon="close" style="fill: rgba(0, 0, 0, 0.54)" size="20" style="top: 0"></ng-md-icon ></a> </div> </div> <div class="contextual-doc-content" markdown-to-html="$ctrl.page.content" class="markdown-page"></div> </div> </div>
{ "content_hash": "5fdf1010ba116da6467b2101f4422c25", "timestamp": "", "source": "github", "line_count": 33, "max_line_length": 117, "avg_line_length": 37.878787878787875, "alnum_prop": 0.6552, "repo_name": "gravitee-io/gravitee-management-webui", "id": "d02607128a8cb4c7e815e417c74b214e836a9c03", "size": "1250", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/components/contextual/contextual-doc.component.html", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "88928" }, { "name": "HTML", "bytes": "831483" }, { "name": "JavaScript", "bytes": "39748" }, { "name": "TypeScript", "bytes": "1091169" } ], "symlink_target": "" }
// // This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, vJAXB 2.1.3 in JDK 1.6 // See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a> // Any modifications to this file will be lost upon recompilation of the source schema. // Generated on: 2009.04.15 at 10:20:40 AM BST // package net.sourceforge.segment.srx.io.bind; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlAttribute; import javax.xml.bind.annotation.XmlRootElement; import javax.xml.bind.annotation.XmlType; /** * <p>Java class for anonymous complex type. * * <p>The following schema fragment specifies the expected content contained within this class. * * <pre> * &lt;complexType> * &lt;complexContent> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * &lt;attribute name="languagerulename" use="required" type="{http://www.w3.org/2001/XMLSchema}string" /> * &lt;attribute name="languagepattern" use="required" type="{http://www.w3.org/2001/XMLSchema}string" /> * &lt;/restriction> * &lt;/complexContent> * &lt;/complexType> * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "") @XmlRootElement(name = "languagemap") public class Languagemap { @XmlAttribute(required = true) protected String languagerulename; @XmlAttribute(required = true) protected String languagepattern; /** * Gets the value of the languagerulename property. * * @return * possible object is * {@link String } * */ public String getLanguagerulename() { return languagerulename; } /** * Sets the value of the languagerulename property. * * @param value * allowed object is * {@link String } * */ public void setLanguagerulename(String value) { this.languagerulename = value; } /** * Gets the value of the languagepattern property. * * @return * possible object is * {@link String } * */ public String getLanguagepattern() { return languagepattern; } /** * Sets the value of the languagepattern property. * * @param value * allowed object is * {@link String } * */ public void setLanguagepattern(String value) { this.languagepattern = value; } }
{ "content_hash": "7d520186a813aae4d7bc5ce7611047f7", "timestamp": "", "source": "github", "line_count": 94, "max_line_length": 125, "avg_line_length": 26.872340425531913, "alnum_prop": 0.6377672209026128, "repo_name": "icenlp/segment", "id": "a49a5ed1bc3ee536b7a67f4459441b91d16f237c", "size": "2526", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/main/java/net/sourceforge/segment/srx/io/bind/Languagemap.java", "mode": "33188", "license": "mit", "language": [ { "name": "Java", "bytes": "175482" } ], "symlink_target": "" }
<!-- The edit article view --> <section data-ng-controller="SchedulesController" data-ng-init="findOne()"> <h1>Edit Article</h1> <a href="/#!/">Home</a> <!-- The edited article form --> <form data-ng-submit="update()" novalidate> <div class="row"> <div class="col-sm-2"> <h2>New Schedule</h2> </div> <div class="col-sm-2"> <a href="/#!/">Home</a> </div> <div class="col-sm-2"> <input class="form-control btn btn-info" type="submit"> </div> </div> <!--Row 1 START--> <div class="row"> <div class="col-sm-2"><label for="did">Schedule ID</label> <input class="form-control" type="text" data-ng-model="schedule.schid" id="did" placeholder="Schedule Id" required/> </div> <div class="col-sm-2"><label for="name">Name</label> <input class="form-control" type="text" data-ng-model="schedule.name" id="name" placeholder="Name"/> </div> <div class="col-sm-2"><label for="name">Type</label> <input class="form-control" type="text" data-ng-model="schedule.type" id="type" placeholder="Type"/> </div> </div> <!--Row 1 END--> <!--Row 2 START--> <div class="row"> <div class="col-sm-2"><label for="start">Start Time</label> <input class="form-control" ng-click="getClock1()" type="text" data-ng-model="schedule.start" readonly> <timepicker-directive ng-show="clockVisible1" input-model="start"></timepicker-directive> </div> <div class="col-sm-2"><label for="end">End Time</label> <input class="form-control" ng-click="getClock2()" type="schedule.text" data-ng-model="end" readonly> <timepicker-directive ng-show="clockVisible2" input-model="end"></timepicker-directive> </div> <div class="col-sm-2"><label for="end">Days</label> <div class="btn-group"> <button data-toggle="dropdown" class="btn dropdown-toggle" data-placeholder="Please select">Checked option <span class="caret"></span></button> <ul class="dropdown-menu"> <li><input type="checkbox" data-ng-model="day1" ng-click="" id="Monday"><label for="Monday" name="Monday" value="Monday">Monday</label></li> <li><input type="checkbox" data-ng-model="day2" ng-click="" id="Tuesday"><label for="Tuesday" name="Tuesday" value="Tuesday">Tuesday</label></li> <li><input type="checkbox" data-ng-model="day3" ng-click="" id="Wednesday"><label for="Wednesday" name="Wednesday" value="Wednesday">Wednesday</label></li> <li><input type="checkbox" data-ng-model="day4" ng-click="" id="Thursday"><label for="Thursday" name="Thursday" value="Thursday">Thursday</label></li> <li><input type="checkbox" data-ng-model="day5" ng-click="" id="Friday"><label for="Friday" name="Friday" value="Friday">Friday</label></li> <li><input type="checkbox" data-ng-model="day6" ng-click="" id="Saturday"><label for="Saturday" name="Saturday" value="Saturday">Saturday</label></li> <li><input type="checkbox" data-ng-model="day7" ng-click="" id="Sunday"><label for="Sunday" name="Sunday" value="Sunday">Sunday</label></li> <!-- Other items --> </ul> </div> </div> </div> <!--Row 2 END--> <!--Row 3 START--> <div class="row"> <div class="col-sm-1"><label for="condition">Condition</label> <select class="form-control" data-ng-model="schedule.switchon" ng-options="sm.feature for sm in switch"></select> </div> <!--<div class="col-sm-1"><label for="random">Random</label> <label class="form-control "><input type="checkbox" value=""></label> </div>--> <div class="col-sm-1"><label for="daily">Daily</label> <label class="form-control "><input type="checkbox" data-ng-model="schedule.daily" value=""></label> </div> <div class="col-sm-2"><label for="daily">Devices</label> <select class="form-control" data-ng-model="schedule.devices" ng-options="sm.name for sm in deviceList"> </select> </div> <div class="col-sm-2"><label for="daily">Smart Plug</label> <select class="form-control" data-ng-model="schedule.smartplugs" ng-options="sm.name for sm in smartplugList"></select> </div> </div> <!--Row 3 END--> <!--Row 4 START--> <div class="row"> <div class="col-sm-6"><label for="condition">Description</label> <textarea class="form-control" rows="2" data-ng-model="description" id="description" placeholder="Description"/> </div> </div> <!--Row 4 END--> <!-- The error message element --> <div data-ng-show="error"> <strong data-ng-bind="error"></strong> </div> </form> </div> </section>
{ "content_hash": "1d7f67a878758b43a9cab0cc8a980b7c", "timestamp": "", "source": "github", "line_count": 147, "max_line_length": 165, "avg_line_length": 34.65986394557823, "alnum_prop": 0.5634936211972522, "repo_name": "vibhatha/mean", "id": "18efa1e4f045db97ed6a38f46fc39294932fae49", "size": "5095", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "App_25/public/schedules/views/edit-schedule.client.view.html", "mode": "33188", "license": "mit", "language": [], "symlink_target": "" }
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <!--NewPage--> <HTML> <HEAD> <!-- Generated by javadoc (build 1.6.0_20) on Thu Jan 26 13:33:44 PST 2012 --> <TITLE> Uses of Class org.apache.hadoop.util.PureJavaCrc32 (Hadoop 0.20.2-cdh3u3 API) </TITLE> <META NAME="date" CONTENT="2012-01-26"> <LINK REL ="stylesheet" TYPE="text/css" HREF="../../../../../stylesheet.css" TITLE="Style"> <SCRIPT type="text/javascript"> function windowTitle() { if (location.href.indexOf('is-external=true') == -1) { parent.document.title="Uses of Class org.apache.hadoop.util.PureJavaCrc32 (Hadoop 0.20.2-cdh3u3 API)"; } } </SCRIPT> <NOSCRIPT> </NOSCRIPT> </HEAD> <BODY BGCOLOR="white" onload="windowTitle();"> <HR> <!-- ========= START OF TOP NAVBAR ======= --> <A NAME="navbar_top"><!-- --></A> <A HREF="#skip-navbar_top" title="Skip navigation links"></A> <TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0" SUMMARY=""> <TR> <TD COLSPAN=2 BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A NAME="navbar_top_firstrow"><!-- --></A> <TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3" SUMMARY=""> <TR ALIGN="center" VALIGN="top"> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../overview-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../package-summary.html"><FONT CLASS="NavBarFont1"><B>Package</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../org/apache/hadoop/util/PureJavaCrc32.html" title="class in org.apache.hadoop.util"><FONT CLASS="NavBarFont1"><B>Class</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> &nbsp;<FONT CLASS="NavBarFont1Rev"><B>Use</B></FONT>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../package-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../index-all.html"><FONT CLASS="NavBarFont1"><B>Index</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A>&nbsp;</TD> </TR> </TABLE> </TD> <TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM> </EM> </TD> </TR> <TR> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> &nbsp;PREV&nbsp; &nbsp;NEXT</FONT></TD> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> <A HREF="../../../../../index.html?org/apache/hadoop/util//class-usePureJavaCrc32.html" target="_top"><B>FRAMES</B></A> &nbsp; &nbsp;<A HREF="PureJavaCrc32.html" target="_top"><B>NO FRAMES</B></A> &nbsp; &nbsp;<SCRIPT type="text/javascript"> <!-- if(window==top) { document.writeln('<A HREF="../../../../../allclasses-noframe.html"><B>All Classes</B></A>'); } //--> </SCRIPT> <NOSCRIPT> <A HREF="../../../../../allclasses-noframe.html"><B>All Classes</B></A> </NOSCRIPT> </FONT></TD> </TR> </TABLE> <A NAME="skip-navbar_top"></A> <!-- ========= END OF TOP NAVBAR ========= --> <HR> <CENTER> <H2> <B>Uses of Class<br>org.apache.hadoop.util.PureJavaCrc32</B></H2> </CENTER> No usage of org.apache.hadoop.util.PureJavaCrc32 <P> <HR> <!-- ======= START OF BOTTOM NAVBAR ====== --> <A NAME="navbar_bottom"><!-- --></A> <A HREF="#skip-navbar_bottom" title="Skip navigation links"></A> <TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0" SUMMARY=""> <TR> <TD COLSPAN=2 BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A NAME="navbar_bottom_firstrow"><!-- --></A> <TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3" SUMMARY=""> <TR ALIGN="center" VALIGN="top"> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../overview-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../package-summary.html"><FONT CLASS="NavBarFont1"><B>Package</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../org/apache/hadoop/util/PureJavaCrc32.html" title="class in org.apache.hadoop.util"><FONT CLASS="NavBarFont1"><B>Class</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> &nbsp;<FONT CLASS="NavBarFont1Rev"><B>Use</B></FONT>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../package-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../index-all.html"><FONT CLASS="NavBarFont1"><B>Index</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A>&nbsp;</TD> </TR> </TABLE> </TD> <TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM> </EM> </TD> </TR> <TR> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> &nbsp;PREV&nbsp; &nbsp;NEXT</FONT></TD> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> <A HREF="../../../../../index.html?org/apache/hadoop/util//class-usePureJavaCrc32.html" target="_top"><B>FRAMES</B></A> &nbsp; &nbsp;<A HREF="PureJavaCrc32.html" target="_top"><B>NO FRAMES</B></A> &nbsp; &nbsp;<SCRIPT type="text/javascript"> <!-- if(window==top) { document.writeln('<A HREF="../../../../../allclasses-noframe.html"><B>All Classes</B></A>'); } //--> </SCRIPT> <NOSCRIPT> <A HREF="../../../../../allclasses-noframe.html"><B>All Classes</B></A> </NOSCRIPT> </FONT></TD> </TR> </TABLE> <A NAME="skip-navbar_bottom"></A> <!-- ======== END OF BOTTOM NAVBAR ======= --> <HR> Copyright &copy; 2009 The Apache Software Foundation </BODY> </HTML>
{ "content_hash": "c9bac6c66fa115b84134eca5a2d32aff", "timestamp": "", "source": "github", "line_count": 144, "max_line_length": 215, "avg_line_length": 41.59722222222222, "alnum_prop": 0.6158597662771286, "repo_name": "koven2049/hdfs-cloudera-cdh3u3-production", "id": "b9b9c4d12a7beb2f85645896b1d2433e1fb7530b", "size": "5990", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "docs/api/org/apache/hadoop/util/class-use/PureJavaCrc32.html", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "C", "bytes": "357798" }, { "name": "C++", "bytes": "456142" }, { "name": "Java", "bytes": "15422691" }, { "name": "JavaScript", "bytes": "59122" }, { "name": "Objective-C", "bytes": "118273" }, { "name": "PHP", "bytes": "152555" }, { "name": "Perl", "bytes": "140392" }, { "name": "Python", "bytes": "1163804" }, { "name": "Ruby", "bytes": "28485" }, { "name": "Shell", "bytes": "3755838" }, { "name": "Smalltalk", "bytes": "56562" } ], "symlink_target": "" }
define([ "Backbone", "jQuery", "./subviews/TeachView", "./subviews/TeachView2", "./subviews/EmptyView" ], function( Backbone, $, TeachView, TeachView2, EmptyView ) { var MainView = Backbone.View.extend({ initialize: function() { this.subviews = []; }, render: function() { var schema = this.options.teachSchema.attributes; var view; // TODO: В будущем заменить данные костыли на парсинг схемы от сервера. // Сейчас смотрим какое имя схемы пришло, и грузим определённое Вью. // В будущем нужно создавать вью на основе схемы!! if (schema.name == "matrix mult") { view = new TeachView({ teachSchema: schema }); } else if (schema.name == "transport") { view = new TeachView2({ teachSchema: schema }); } else { view = new EmptyView({ teachSchema: schema }); } this.$el.append(view.render().el); this.subviews.push(view); return this; } }); return MainView; });
{ "content_hash": "7c2e5dd206afd44cf2f5634fffba010d", "timestamp": "", "source": "github", "line_count": 44, "max_line_length": 83, "avg_line_length": 26.65909090909091, "alnum_prop": 0.514919011082694, "repo_name": "DrDoodlez/Algoteacher", "id": "120c4a104af7fee01b7aee9a165aa499980abe8f", "size": "1317", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/Public/js/apps/teach/views/MainView.js", "mode": "33188", "license": "mit", "language": [ { "name": "ASP", "bytes": "99" }, { "name": "C#", "bytes": "45247" }, { "name": "CSS", "bytes": "31241" }, { "name": "HTML", "bytes": "409610" }, { "name": "JavaScript", "bytes": "10780277" }, { "name": "Shell", "bytes": "2002" } ], "symlink_target": "" }
// Copyright (c) ppy Pty Ltd <[email protected]>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using System; using osu.Framework.Allocation; using osu.Framework.Bindables; using osu.Framework.Extensions.Color4Extensions; using osu.Framework.Graphics; using osu.Framework.Graphics.Colour; using osu.Framework.Graphics.Containers; using osu.Framework.Graphics.Shapes; using osu.Framework.Graphics.UserInterface; using osu.Framework.Input.Events; using osu.Game.Graphics; using osuTK; using osuTK.Graphics; namespace osu.Game.Overlays.Volume { public class MuteButton : Container, IHasCurrentValue<bool> { private readonly Bindable<bool> current = new Bindable<bool>(); public Bindable<bool> Current { get => current; set { if (value == null) throw new ArgumentNullException(nameof(value)); current.UnbindBindings(); current.BindTo(value); } } private Color4 hoveredColour, unhoveredColour; private const float width = 100; public const float HEIGHT = 35; public MuteButton() { Masking = true; BorderThickness = 3; CornerRadius = HEIGHT / 2; Size = new Vector2(width, HEIGHT); } [BackgroundDependencyLoader] private void load(OsuColour colours) { hoveredColour = colours.YellowDark; BorderColour = unhoveredColour = colours.Gray1.Opacity(0.9f); SpriteIcon icon; AddRange(new Drawable[] { new Box { RelativeSizeAxes = Axes.Both, Colour = colours.Gray1, Alpha = 0.9f, }, icon = new SpriteIcon { Anchor = Anchor.CentreLeft, Origin = Anchor.CentreLeft, Size = new Vector2(20), } }); Current.ValueChanged += muted => { icon.Icon = muted.NewValue ? FontAwesome.fa_volume_off : FontAwesome.fa_volume_up; icon.Margin = new MarginPadding { Left = muted.NewValue ? width / 2 - 15 : width / 2 - 10 }; //Magic numbers to line up both icons because they're different widths }; Current.TriggerChange(); } protected override bool OnHover(HoverEvent e) { this.TransformTo<MuteButton, SRGBColour>("BorderColour", hoveredColour, 500, Easing.OutQuint); return false; } protected override void OnHoverLost(HoverLostEvent e) { this.TransformTo<MuteButton, SRGBColour>("BorderColour", unhoveredColour, 500, Easing.OutQuint); } protected override bool OnClick(ClickEvent e) { Current.Value = !Current.Value; return true; } } }
{ "content_hash": "71f9ecb30171a8e29b8f6418006a1b6a", "timestamp": "", "source": "github", "line_count": 97, "max_line_length": 179, "avg_line_length": 31.50515463917526, "alnum_prop": 0.569371727748691, "repo_name": "naoey/osu", "id": "6061ead2da01f820dda6e53da58838eca4cd8a06", "size": "3058", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "osu.Game/Overlays/Volume/MuteButton.cs", "mode": "33188", "license": "mit", "language": [ { "name": "C#", "bytes": "4122627" }, { "name": "PowerShell", "bytes": "2550" }, { "name": "Ruby", "bytes": "6173" }, { "name": "Shell", "bytes": "1031" } ], "symlink_target": "" }
'use strict'; // sample-metadata: // title: Quickstart // description: A quick introduction to using the Pub/Sub client library. // usage: node quickstart.js <project-id> <topic-name-or-id> <subscription-name-or-id> // [START pubsub_quickstart_create_topic] // Imports the Google Cloud client library const {PubSub} = require('@google-cloud/pubsub'); async function quickstart( projectId = 'your-project-id', // Your Google Cloud Platform project ID topicNameOrId = 'my-topic', // Name for the new topic to create subscriptionName = 'my-sub' // Name for the new subscription to create ) { // Instantiates a client const pubsub = new PubSub({projectId}); // Creates a new topic const [topic] = await pubsub.createTopic(topicNameOrId); console.log(`Topic ${topic.name} created.`); // Creates a subscription on that new topic const [subscription] = await topic.createSubscription(subscriptionName); // Receive callbacks for new messages on the subscription subscription.on('message', message => { console.log('Received message:', message.data.toString()); process.exit(0); }); // Receive callbacks for errors on the subscription subscription.on('error', error => { console.error('Received error:', error); process.exit(1); }); // Send a message to the topic topic.publish(Buffer.from('Test message!')); } // [END pubsub_quickstart_create_topic] process.on('unhandledRejection', err => { console.error(err.message); process.exitCode = 1; }); quickstart(...process.argv.slice(2));
{ "content_hash": "789f9c01aee689dcd4027c56580341bd", "timestamp": "", "source": "github", "line_count": 48, "max_line_length": 88, "avg_line_length": 32.229166666666664, "alnum_prop": 0.7052359405300582, "repo_name": "googleapis/nodejs-pubsub", "id": "9ef357afe9e529ab9df27b3d260710d91e1a7fdc", "size": "2136", "binary": false, "copies": "1", "ref": "refs/heads/main", "path": "samples/quickstart.js", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "JavaScript", "bytes": "6910" }, { "name": "Python", "bytes": "749" }, { "name": "TypeScript", "bytes": "1111157" } ], "symlink_target": "" }
""" Deuce OpenStack Authentication API """ import datetime import logging import time # What we want to do: # import keystoneclient.client # What we have to do: import keystoneclient.v2_0.client as client_v2 import deuceclient.auth class OpenStackAuthentication(deuceclient.auth.AuthenticationBase): """OpenStack Keystone Authentication Support Basic OpenStack Keystone Support for Token management """ def __init__(self, userid=None, usertype=None, credentials=None, auth_method=None, datacenter=None, auth_url=None): if auth_url is None: raise deuceclient.auth.AuthenticationError( 'Required Parameter, auth_url, not specified.') super().__init__(userid=userid, usertype=usertype, credentials=credentials, auth_method=auth_method, datacenter=datacenter, auth_url=auth_url) self.__client = None self.__access = None def get_client(self): """Retrieve the OpenStack Keystone Client """ auth_args = { 'auth_url': self.authurl, 'region_name': self.datacenter } # Extract the User Information if self.usertype in ('user_name', 'user_id'): auth_args['username'] = self.userid elif self.usertype == 'tenant_name': auth_args['tenant_name'] = self.userid elif self.usertype == 'tenant_id': auth_args['tenant_id'] = self.userid else: raise deuceclient.auth.AuthenticationError( 'Invalid usertype ({0:}) for OpenStackAuthentication' .format(self.usertype)) # Extract the User's Credential Information if self.authmethod in ('apikey', 'password'): auth_args['password'] = self.credentials elif self.authmethod == 'token': auth_args['token'] = self.credentials else: raise deuceclient.auth.AuthenticationError( 'Invalid auth_method ({0:}) for OpenStackAuthentication' .format(self.authmethod)) # What we want to do: # return keystoneclient.client.Client(**auth_args) # What we have to do: return client_v2.Client(**auth_args) def GetToken(self, retry=5): """Retrieve a token from OpenStack Keystone """ if self.__client is None: try: self.__client = self.get_client() except: raise deuceclient.auth.AuthenticationError( 'Unable to retrieve the Authentication Client') try: if self.authmethod in ('apikey', 'password'): self.__access = \ self.__client.get_raw_token_from_identity_service( auth_url=self.authurl, username=self.userid, password=self.credentials) else: self.__access = \ self.__client.get_raw_token_from_identity_service( auth_url=self.authurl, project_id=self.userid, token=self.credentials) return self.__access.auth_token except Exception as ex: if retry is 0: self.__access = None raise deuceclient.auth.AuthenticationError( 'Unable to retrieve the Auth Token: {0}'.format(ex)) else: return self.GetToken(retry=retry - 1) def IsExpired(self, fuzz=0): if self.__access is None: return True else: return self.__access.will_expire_soon(stale_duration=fuzz) def _AuthToken(self): if self.IsExpired(): return self.GetToken() elif self.IsExpired(fuzz=2): time.sleep(3) return self.GetToken() else: return self.__access.auth_token def _AuthExpirationTime(self): try: return self.__access.expires except Exception as ex: print('Error: {0}'.format(ex)) return datetime.datetime.utcnow() def _AuthTenantId(self): """Return the Tenant Id """ try: return self.__access.tenant_id except: return None @property def AuthTenantName(self): """Return the Tenant Name """ try: return self.__access.tenant_name except: return None @property def AuthUserId(self): """Return the User Id """ try: return self.__access.user_id except: return None @property def AuthUserName(self): """Return the User Name """ try: return self.__access.username except: return None
{ "content_hash": "fd66b4f3ec64bbe716be359dc613aa2d", "timestamp": "", "source": "github", "line_count": 172, "max_line_length": 74, "avg_line_length": 28.476744186046513, "alnum_prop": 0.5487954267047774, "repo_name": "rackerlabs/deuce-client", "id": "fa0ee760cb646cdbd0e1d9a6672d06c548ab01a5", "size": "4898", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "deuceclient/auth/openstackauth.py", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Python", "bytes": "362823" } ], "symlink_target": "" }
package eu.bcvsolutions.idm.core.api.dto.filter; import java.util.UUID; import org.springframework.util.LinkedMultiValueMap; import org.springframework.util.MultiValueMap; import eu.bcvsolutions.idm.core.api.domain.OperationState; import eu.bcvsolutions.idm.core.api.domain.RequestOperationType; import eu.bcvsolutions.idm.core.api.dto.IdmExportImportDto; import eu.bcvsolutions.idm.core.api.utils.DtoUtils; /** * Filter for import log * * @author Vít Švanda * */ public class IdmImportLogFilter extends DataFilter { public static final String PARAMETER_BATCH_ID = "batchId"; public static final String PARAMETER_PARENT = "parent"; public static final String PARAMETER_DTO_ID = "dtoId"; public static final String PARAMETER_ROOTS = "roots"; public static final String PARAMETER_OPERATION = "operation"; public static final String PARAMETER_OPERATION_STATE = "operationState"; public UUID getBatchId() { return DtoUtils.toUuid(data.getFirst(PARAMETER_BATCH_ID)); } public void setBatchId(UUID batchId) { data.set(PARAMETER_BATCH_ID, batchId); } public UUID getParent() { return DtoUtils.toUuid(data.getFirst(PARAMETER_PARENT)); } public void setParent(UUID parentId) { data.set(PARAMETER_PARENT, parentId); } public UUID getDtoId() { return DtoUtils.toUuid(data.getFirst(PARAMETER_DTO_ID)); } public void setDtoId(UUID dtoId) { data.set(PARAMETER_DTO_ID, dtoId); } public Boolean getRoots() { return getParameterConverter().toBoolean(data, PARAMETER_ROOTS); } public void setRoots(Boolean roots) { data.set(PARAMETER_ROOTS, roots); } public void setOperationState(OperationState operation) { data.set(PARAMETER_OPERATION_STATE, operation); } public OperationState getOperationState() { return getParameterConverter().toEnum(data, PARAMETER_OPERATION_STATE, OperationState.class); } public void setOperation(RequestOperationType operation) { data.set(PARAMETER_OPERATION, operation); } public RequestOperationType getOperation() { return getParameterConverter().toEnum(data, PARAMETER_OPERATION, RequestOperationType.class); } public IdmImportLogFilter() { this(new LinkedMultiValueMap<>()); } public IdmImportLogFilter(MultiValueMap<String, Object> data) { super(IdmExportImportDto.class, data); } }
{ "content_hash": "2108c5ad6c4112f9f4f9b93b2ccf2be0", "timestamp": "", "source": "github", "line_count": 86, "max_line_length": 95, "avg_line_length": 26.697674418604652, "alnum_prop": 0.764808362369338, "repo_name": "bcvsolutions/CzechIdMng", "id": "1cbccf9471ba974b5123d1ca238463268157db04", "size": "2298", "binary": false, "copies": "1", "ref": "refs/heads/develop", "path": "Realization/backend/core/core-api/src/main/java/eu/bcvsolutions/idm/core/api/dto/filter/IdmImportLogFilter.java", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "20553" }, { "name": "HTML", "bytes": "1826" }, { "name": "Java", "bytes": "17776464" }, { "name": "JavaScript", "bytes": "4985617" }, { "name": "Less", "bytes": "56975" }, { "name": "Shell", "bytes": "2793" }, { "name": "TSQL", "bytes": "114398" } ], "symlink_target": "" }
#ifdef HAVE_CONFIG_H # include <config.h> #endif #include <alloca.h> #include <ctype.h> #include <errno.h> #include <getopt.h> #include <stdio.h> #include <time.h> #include <stdlib.h> #include <stdbool.h> #include <string.h> #include <locale.h> #include <limits.h> #include "xgettext.h" #include "closeout.h" #include "dir-list.h" #include "file-list.h" #include "str-list.h" #include "error.h" #include "error-progname.h" #include "progname.h" #include "relocatable.h" #include "basename.h" #include "xerror.h" #include "xalloc.h" #include "xallocsa.h" #include "strstr.h" #include "xerror.h" #include "exit.h" #include "pathname.h" #include "c-strcase.h" #include "stpcpy.h" #include "open-po.h" #include "read-po-abstract.h" #include "message.h" #include "po-charset.h" #include "msgl-iconv.h" #include "msgl-ascii.h" #include "po-time.h" #include "write-po.h" #include "format.h" #include "gettext.h" /* A convenience macro. I don't like writing gettext() every time. */ #define _(str) gettext (str) #ifdef __cplusplus extern "C" { #endif #include "x-c.h" #include "x-po.h" #include "x-sh.h" #include "x-python.h" #include "x-lisp.h" #include "x-elisp.h" #include "x-librep.h" #include "x-scheme.h" #include "x-smalltalk.h" #include "x-java.h" #include "x-properties.h" #include "x-csharp.h" #include "x-awk.h" #include "x-ycp.h" #include "x-tcl.h" #include "x-perl.h" #include "x-php.h" #include "x-stringtable.h" #include "x-rst.h" #include "x-glade.h" #ifdef __cplusplus } #endif /* If nonzero add all comments immediately preceding one of the keywords. */ static bool add_all_comments = false; /* Tag used in comment of prevailing domain. */ static char *comment_tag; /* Name of default domain file. If not set defaults to messages.po. */ static const char *default_domain; /* If called with --debug option the output reflects whether format string recognition is done automatically or forced by the user. */ static int do_debug; /* Content of .po files with symbols to be excluded. */ message_list_ty *exclude; /* Force output of PO file even if empty. */ static int force_po; /* Copyright holder of the output file and the translations. */ static const char *copyright_holder = "THE PACKAGE'S COPYRIGHT HOLDER"; /* Email address or URL for reports of bugs in msgids. */ static const char *msgid_bugs_address = NULL; /* String used as prefix for msgstr. */ static const char *msgstr_prefix; /* String used as suffix for msgstr. */ static const char *msgstr_suffix; /* Directory in which output files are created. */ static char *output_dir; /* The output syntax: .pot or .properties or .strings. */ static input_syntax_ty output_syntax = syntax_po; /* If nonzero omit header with information about this run. */ int xgettext_omit_header; /* Table of flag_context_list_ty tables. */ static flag_context_list_table_ty flag_table_c; static flag_context_list_table_ty flag_table_objc; static flag_context_list_table_ty flag_table_gcc_internal; static flag_context_list_table_ty flag_table_sh; static flag_context_list_table_ty flag_table_python; static flag_context_list_table_ty flag_table_lisp; static flag_context_list_table_ty flag_table_elisp; static flag_context_list_table_ty flag_table_librep; static flag_context_list_table_ty flag_table_scheme; static flag_context_list_table_ty flag_table_java; static flag_context_list_table_ty flag_table_csharp; static flag_context_list_table_ty flag_table_awk; static flag_context_list_table_ty flag_table_ycp; static flag_context_list_table_ty flag_table_tcl; static flag_context_list_table_ty flag_table_perl; static flag_context_list_table_ty flag_table_php; /* If true, recognize Qt format strings. */ static bool recognize_format_qt; /* Canonicalized encoding name for all input files. */ const char *xgettext_global_source_encoding; #if HAVE_ICONV /* Converter from xgettext_global_source_encoding to UTF-8 (except from ASCII or UTF-8, when this conversion is a no-op). */ iconv_t xgettext_global_source_iconv; #endif /* Canonicalized encoding name for the current input file. */ const char *xgettext_current_source_encoding; #if HAVE_ICONV /* Converter from xgettext_current_source_encoding to UTF-8 (except from ASCII or UTF-8, when this conversion is a no-op). */ iconv_t xgettext_current_source_iconv; #endif /* Long options. */ static const struct option long_options[] = { { "add-comments", optional_argument, NULL, 'c' }, { "add-location", no_argument, &line_comment, 1 }, { "c++", no_argument, NULL, 'C' }, { "copyright-holder", required_argument, NULL, CHAR_MAX + 1 }, { "debug", no_argument, &do_debug, 1 }, { "default-domain", required_argument, NULL, 'd' }, { "directory", required_argument, NULL, 'D' }, { "escape", no_argument, NULL, 'E' }, { "exclude-file", required_argument, NULL, 'x' }, { "extract-all", no_argument, NULL, 'a' }, { "files-from", required_argument, NULL, 'f' }, { "flag", required_argument, NULL, CHAR_MAX + 8 }, { "force-po", no_argument, &force_po, 1 }, { "foreign-user", no_argument, NULL, CHAR_MAX + 2 }, { "from-code", required_argument, NULL, CHAR_MAX + 3 }, { "help", no_argument, NULL, 'h' }, { "indent", no_argument, NULL, 'i' }, { "join-existing", no_argument, NULL, 'j' }, { "keyword", optional_argument, NULL, 'k' }, { "language", required_argument, NULL, 'L' }, { "msgid-bugs-address", required_argument, NULL, CHAR_MAX + 5 }, { "msgstr-prefix", optional_argument, NULL, 'm' }, { "msgstr-suffix", optional_argument, NULL, 'M' }, { "no-escape", no_argument, NULL, 'e' }, { "no-location", no_argument, &line_comment, 0 }, { "no-wrap", no_argument, NULL, CHAR_MAX + 4 }, { "omit-header", no_argument, &xgettext_omit_header, 1 }, { "output", required_argument, NULL, 'o' }, { "output-dir", required_argument, NULL, 'p' }, { "properties-output", no_argument, NULL, CHAR_MAX + 6 }, { "qt", no_argument, NULL, CHAR_MAX + 9 }, { "sort-by-file", no_argument, NULL, 'F' }, { "sort-output", no_argument, NULL, 's' }, { "strict", no_argument, NULL, 'S' }, { "string-limit", required_argument, NULL, 'l' }, { "stringtable-output", no_argument, NULL, CHAR_MAX + 7 }, { "trigraphs", no_argument, NULL, 'T' }, { "version", no_argument, NULL, 'V' }, { "width", required_argument, NULL, 'w', }, { NULL, 0, NULL, 0 } }; /* The extractors must all be functions returning void and taking three arguments designating the input stream and one message domain list argument in which to add the messages. */ typedef void (*extractor_func) (FILE *fp, const char *real_filename, const char *logical_filename, flag_context_list_table_ty *flag_table, msgdomain_list_ty *mdlp); typedef struct extractor_ty extractor_ty; struct extractor_ty { extractor_func func; flag_context_list_table_ty *flag_table; struct formatstring_parser *formatstring_parser1; struct formatstring_parser *formatstring_parser2; }; /* Forward declaration of local functions. */ static void usage (int status) #if defined __GNUC__ && ((__GNUC__ == 2 && __GNUC_MINOR__ > 4) || __GNUC__ > 2) __attribute__ ((noreturn)) #endif ; static void read_exclusion_file (char *file_name); static void extract_from_file (const char *file_name, extractor_ty extractor, msgdomain_list_ty *mdlp); static message_ty *construct_header (void); static void finalize_header (msgdomain_list_ty *mdlp); static extractor_ty language_to_extractor (const char *name); static const char *extension_to_language (const char *extension); int main (int argc, char *argv[]) { int cnt; int optchar; bool do_help = false; bool do_version = false; msgdomain_list_ty *mdlp; bool join_existing = false; bool no_default_keywords = false; bool some_additional_keywords = false; bool sort_by_msgid = false; bool sort_by_filepos = false; const char *file_name; const char *files_from = NULL; string_list_ty *file_list; char *output_file = NULL; const char *language = NULL; extractor_ty extractor = { NULL, NULL, NULL, NULL }; /* Set program name for messages. */ set_program_name (argv[0]); error_print_progname = maybe_print_progname; #ifdef HAVE_SETLOCALE /* Set locale via LC_ALL. */ setlocale (LC_ALL, ""); #endif /* Set the text message domain. */ bindtextdomain (PACKAGE, relocate (LOCALEDIR)); textdomain (PACKAGE); /* Ensure that write errors on stdout are detected. */ atexit (close_stdout); /* Set initial value of variables. */ default_domain = MESSAGE_DOMAIN_DEFAULT; xgettext_global_source_encoding = po_charset_ascii; init_flag_table_c (); init_flag_table_objc (); init_flag_table_gcc_internal (); init_flag_table_sh (); init_flag_table_python (); init_flag_table_lisp (); init_flag_table_elisp (); init_flag_table_librep (); init_flag_table_scheme (); init_flag_table_java (); init_flag_table_csharp (); init_flag_table_awk (); init_flag_table_ycp (); init_flag_table_tcl (); init_flag_table_perl (); init_flag_table_php (); while ((optchar = getopt_long (argc, argv, "ac::Cd:D:eEf:Fhijk::l:L:m::M::no:p:sTVw:x:", long_options, NULL)) != EOF) switch (optchar) { case '\0': /* Long option. */ break; case 'a': x_c_extract_all (); x_sh_extract_all (); x_python_extract_all (); x_lisp_extract_all (); x_elisp_extract_all (); x_librep_extract_all (); x_scheme_extract_all (); x_java_extract_all (); x_csharp_extract_all (); x_awk_extract_all (); x_tcl_extract_all (); x_perl_extract_all (); x_php_extract_all (); x_glade_extract_all (); break; case 'c': if (optarg == NULL) { add_all_comments = true; comment_tag = NULL; } else { add_all_comments = false; comment_tag = optarg; /* We ignore leading white space. */ while (isspace ((unsigned char) *comment_tag)) ++comment_tag; } break; case 'C': language = "C++"; break; case 'd': default_domain = optarg; break; case 'D': dir_list_append (optarg); break; case 'e': message_print_style_escape (false); break; case 'E': message_print_style_escape (true); break; case 'f': files_from = optarg; break; case 'F': sort_by_filepos = true; break; case 'h': do_help = true; break; case 'i': message_print_style_indent (); break; case 'j': join_existing = true; break; case 'k': if (optarg == NULL || *optarg != '\0') { x_c_keyword (optarg); x_objc_keyword (optarg); x_sh_keyword (optarg); x_python_keyword (optarg); x_lisp_keyword (optarg); x_elisp_keyword (optarg); x_librep_keyword (optarg); x_scheme_keyword (optarg); x_java_keyword (optarg); x_csharp_keyword (optarg); x_awk_keyword (optarg); x_tcl_keyword (optarg); x_perl_keyword (optarg); x_php_keyword (optarg); x_glade_keyword (optarg); if (optarg == NULL) no_default_keywords = true; else some_additional_keywords = true; } break; case 'l': /* Accepted for backward compatibility with 0.10.35. */ break; case 'L': language = optarg; break; case 'm': /* -m takes an optional argument. If none is given "" is assumed. */ msgstr_prefix = optarg == NULL ? "" : optarg; break; case 'M': /* -M takes an optional argument. If none is given "" is assumed. */ msgstr_suffix = optarg == NULL ? "" : optarg; break; case 'n': line_comment = 1; break; case 'o': output_file = optarg; break; case 'p': { size_t len = strlen (optarg); if (output_dir != NULL) free (output_dir); if (optarg[len - 1] == '/') output_dir = xstrdup (optarg); else output_dir = xasprintf ("%s/", optarg); } break; case 's': sort_by_msgid = true; break; case 'S': message_print_style_uniforum (); break; case 'T': x_c_trigraphs (); break; case 'V': do_version = true; break; case 'w': { int value; char *endp; value = strtol (optarg, &endp, 10); if (endp != optarg) message_page_width_set (value); } break; case 'x': read_exclusion_file (optarg); break; case CHAR_MAX + 1: /* --copyright-holder */ copyright_holder = optarg; break; case CHAR_MAX + 2: /* --foreign-user */ copyright_holder = ""; break; case CHAR_MAX + 3: /* --from-code */ xgettext_global_source_encoding = po_charset_canonicalize (optarg); if (xgettext_global_source_encoding == NULL) xgettext_global_source_encoding = po_charset_ascii; break; case CHAR_MAX + 4: /* --no-wrap */ message_page_width_ignore (); break; case CHAR_MAX + 5: /* --msgid-bugs-address */ msgid_bugs_address = optarg; break; case CHAR_MAX + 6: /* --properties-output */ message_print_syntax_properties (); output_syntax = syntax_properties; break; case CHAR_MAX + 7: /* --stringtable-output */ message_print_syntax_stringtable (); output_syntax = syntax_stringtable; break; case CHAR_MAX + 8: /* --flag */ xgettext_record_flag (optarg); break; case CHAR_MAX + 9: /* --qt */ recognize_format_qt = true; break; default: usage (EXIT_FAILURE); /* NOTREACHED */ } /* Version information requested. */ if (do_version) { printf ("%s (GNU %s) %s\n", basename (program_name), PACKAGE, VERSION); /* xgettext: no-wrap */ printf (_("Copyright (C) %s Free Software Foundation, Inc.\n\ This is free software; see the source for copying conditions. There is NO\n\ warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.\n\ "), "1995-1998, 2000-2005"); printf (_("Written by %s.\n"), "Ulrich Drepper"); exit (EXIT_SUCCESS); } /* Help is requested. */ if (do_help) usage (EXIT_SUCCESS); /* Verify selected options. */ if (!line_comment && sort_by_filepos) error (EXIT_FAILURE, 0, _("%s and %s are mutually exclusive"), "--no-location", "--sort-by-file"); if (sort_by_msgid && sort_by_filepos) error (EXIT_FAILURE, 0, _("%s and %s are mutually exclusive"), "--sort-output", "--sort-by-file"); if (join_existing && strcmp (default_domain, "-") == 0) error (EXIT_FAILURE, 0, _("\ --join-existing cannot be used when output is written to stdout")); if (no_default_keywords && !some_additional_keywords) { error (0, 0, _("\ xgettext cannot work without keywords to look for")); usage (EXIT_FAILURE); } /* Test whether we have some input files given. */ if (files_from == NULL && optind >= argc) { error (EXIT_SUCCESS, 0, _("no input file given")); usage (EXIT_FAILURE); } /* Determine extractor from language. */ if (language != NULL) extractor = language_to_extractor (language); /* Canonize msgstr prefix/suffix. */ if (msgstr_prefix != NULL && msgstr_suffix == NULL) msgstr_suffix = ""; else if (msgstr_prefix == NULL && msgstr_suffix != NULL) msgstr_prefix = ""; /* Default output directory is the current directory. */ if (output_dir == NULL) output_dir = "."; /* Construct the name of the output file. If the default domain has the special name "-" we write to stdout. */ if (output_file) { if (IS_ABSOLUTE_PATH (output_file) || strcmp (output_file, "-") == 0) file_name = xstrdup (output_file); else /* Please do NOT add a .po suffix! */ file_name = concatenated_pathname (output_dir, output_file, NULL); } else if (strcmp (default_domain, "-") == 0) file_name = "-"; else file_name = concatenated_pathname (output_dir, default_domain, ".po"); /* Determine list of files we have to process. */ if (files_from != NULL) file_list = read_names_from_file (files_from); else file_list = string_list_alloc (); /* Append names from command line. */ for (cnt = optind; cnt < argc; ++cnt) string_list_append_unique (file_list, argv[cnt]); /* Allocate converter from xgettext_global_source_encoding to UTF-8 (except from ASCII or UTF-8, when this conversion is a no-op). */ if (xgettext_global_source_encoding != po_charset_ascii && xgettext_global_source_encoding != po_charset_utf8) { #if HAVE_ICONV iconv_t cd; /* Avoid glibc-2.1 bug with EUC-KR. */ # if (__GLIBC__ - 0 == 2 && __GLIBC_MINOR__ - 0 <= 1) && !defined _LIBICONV_VERSION if (strcmp (xgettext_global_source_encoding, "EUC-KR") == 0) cd = (iconv_t)(-1); else # endif cd = iconv_open (po_charset_utf8, xgettext_global_source_encoding); if (cd == (iconv_t)(-1)) error (EXIT_FAILURE, 0, _("\ Cannot convert from \"%s\" to \"%s\". %s relies on iconv(), \ and iconv() does not support this conversion."), xgettext_global_source_encoding, po_charset_utf8, basename (program_name)); xgettext_global_source_iconv = cd; #else error (EXIT_FAILURE, 0, _("\ Cannot convert from \"%s\" to \"%s\". %s relies on iconv(). \ This version was built without iconv()."), xgettext_global_source_encoding, po_charset_utf8, basename (program_name)); #endif } /* Allocate a message list to remember all the messages. */ mdlp = msgdomain_list_alloc (true); /* Generate a header, so that we know how and when this PO file was created. */ if (!xgettext_omit_header) message_list_append (mdlp->item[0]->messages, construct_header ()); /* Read in the old messages, so that we can add to them. */ if (join_existing) { /* Temporarily reset the directory list to empty, because file_name is an output file and therefore should not be searched for. */ void *saved_directory_list = dir_list_save_reset (); extractor_ty po_extractor = { extract_po, NULL, NULL, NULL }; extract_from_file (file_name, po_extractor, mdlp); if (!is_ascii_msgdomain_list (mdlp)) mdlp = iconv_msgdomain_list (mdlp, "UTF-8", file_name); dir_list_restore (saved_directory_list); } /* Process all input files. */ for (cnt = 0; cnt < file_list->nitems; ++cnt) { const char *filename; extractor_ty this_file_extractor; filename = file_list->item[cnt]; if (extractor.func) this_file_extractor = extractor; else { const char *base; char *reduced; const char *extension; const char *language; base = strrchr (filename, '/'); if (!base) base = filename; reduced = xstrdup (base); /* Remove a trailing ".in" - it's a generic suffix. */ if (strlen (reduced) >= 3 && memcmp (reduced + strlen (reduced) - 3, ".in", 3) == 0) reduced[strlen (reduced) - 3] = '\0'; /* Work out what the file extension is. */ extension = strrchr (reduced, '.'); if (extension) ++extension; else extension = ""; /* Derive the language from the extension, and the extractor function from the language. */ language = extension_to_language (extension); if (language == NULL) { error (0, 0, _("\ warning: file `%s' extension `%s' is unknown; will try C"), filename, extension); language = "C"; } this_file_extractor = language_to_extractor (language); free (reduced); } /* Extract the strings from the file. */ extract_from_file (filename, this_file_extractor, mdlp); } string_list_free (file_list); /* Finalize the constructed header. */ if (!xgettext_omit_header) finalize_header (mdlp); /* Free the allocated converter. */ #if HAVE_ICONV if (xgettext_global_source_encoding != po_charset_ascii && xgettext_global_source_encoding != po_charset_utf8) iconv_close (xgettext_global_source_iconv); #endif /* Sorting the list of messages. */ if (sort_by_filepos) msgdomain_list_sort_by_filepos (mdlp); else if (sort_by_msgid) msgdomain_list_sort_by_msgid (mdlp); /* Write the PO file. */ msgdomain_list_print (mdlp, file_name, force_po, do_debug); exit (EXIT_SUCCESS); } /* Display usage information and exit. */ static void usage (int status) { if (status != EXIT_SUCCESS) fprintf (stderr, _("Try `%s --help' for more information.\n"), program_name); else { printf (_("\ Usage: %s [OPTION] [INPUTFILE]...\n\ "), program_name); printf ("\n"); printf (_("\ Extract translatable strings from given input files.\n\ ")); printf ("\n"); /* xgettext: no-wrap */ printf (_("\ Mandatory arguments to long options are mandatory for short options too.\n\ Similarly for optional arguments.\n\ ")); printf ("\n"); printf (_("\ Input file location:\n")); printf (_("\ INPUTFILE ... input files\n")); printf (_("\ -f, --files-from=FILE get list of input files from FILE\n")); printf (_("\ -D, --directory=DIRECTORY add DIRECTORY to list for input files search\n")); printf (_("\ If input file is -, standard input is read.\n")); printf ("\n"); printf (_("\ Output file location:\n")); printf (_("\ -d, --default-domain=NAME use NAME.po for output (instead of messages.po)\n")); printf (_("\ -o, --output=FILE write output to specified file\n")); printf (_("\ -p, --output-dir=DIR output files will be placed in directory DIR\n")); printf (_("\ If output file is -, output is written to standard output.\n")); printf ("\n"); printf (_("\ Choice of input file language:\n")); printf (_("\ -L, --language=NAME recognise the specified language\n\ (C, C++, ObjectiveC, PO, Shell, Python, Lisp,\n\ EmacsLisp, librep, Scheme, Smalltalk, Java,\n\ JavaProperties, C#, awk, YCP, Tcl, Perl, PHP,\n\ GCC-source, NXStringTable, RST, Glade)\n")); printf (_("\ -C, --c++ shorthand for --language=C++\n")); printf (_("\ By default the language is guessed depending on the input file name extension.\n")); printf ("\n"); printf (_("\ Input file interpretation:\n")); printf (_("\ --from-code=NAME encoding of input files\n\ (except for Python, Tcl, Glade)\n")); printf (_("\ By default the input files are assumed to be in ASCII.\n")); printf ("\n"); printf (_("\ Operation mode:\n")); printf (_("\ -j, --join-existing join messages with existing file\n")); printf (_("\ -x, --exclude-file=FILE.po entries from FILE.po are not extracted\n")); printf (_("\ -c, --add-comments[=TAG] place comment block with TAG (or those\n\ preceding keyword lines) in output file\n")); printf ("\n"); printf (_("\ Language specific options:\n")); printf (_("\ -a, --extract-all extract all strings\n")); printf (_("\ (only languages C, C++, ObjectiveC, Shell,\n\ Python, Lisp, EmacsLisp, librep, Scheme, Java,\n\ C#, awk, Tcl, Perl, PHP, GCC-source, Glade)\n")); printf (_("\ -k, --keyword[=WORD] additional keyword to be looked for (without\n\ WORD means not to use default keywords)\n")); printf (_("\ (only languages C, C++, ObjectiveC, Shell,\n\ Python, Lisp, EmacsLisp, librep, Scheme, Java,\n\ C#, awk, Tcl, Perl, PHP, GCC-source, Glade)\n")); printf (_("\ --flag=WORD:ARG:FLAG additional flag for strings inside the argument\n\ number ARG of keyword WORD\n")); printf (_("\ (only languages C, C++, ObjectiveC, Shell,\n\ Python, Lisp, EmacsLisp, librep, Scheme, Java,\n\ C#, awk, YCP, Tcl, Perl, PHP, GCC-source)\n")); printf (_("\ -T, --trigraphs understand ANSI C trigraphs for input\n")); printf (_("\ (only languages C, C++, ObjectiveC)\n")); printf (_("\ --qt recognize Qt format strings\n")); printf (_("\ (only language C++)\n")); printf (_("\ --debug more detailed formatstring recognition result\n")); printf ("\n"); printf (_("\ Output details:\n")); printf (_("\ -e, --no-escape do not use C escapes in output (default)\n")); printf (_("\ -E, --escape use C escapes in output, no extended chars\n")); printf (_("\ --force-po write PO file even if empty\n")); printf (_("\ -i, --indent write the .po file using indented style\n")); printf (_("\ --no-location do not write '#: filename:line' lines\n")); printf (_("\ -n, --add-location generate '#: filename:line' lines (default)\n")); printf (_("\ --strict write out strict Uniforum conforming .po file\n")); printf (_("\ --properties-output write out a Java .properties file\n")); printf (_("\ --stringtable-output write out a NeXTstep/GNUstep .strings file\n")); printf (_("\ -w, --width=NUMBER set output page width\n")); printf (_("\ --no-wrap do not break long message lines, longer than\n\ the output page width, into several lines\n")); printf (_("\ -s, --sort-output generate sorted output\n")); printf (_("\ -F, --sort-by-file sort output by file location\n")); printf (_("\ --omit-header don't write header with `msgid \"\"' entry\n")); printf (_("\ --copyright-holder=STRING set copyright holder in output\n")); printf (_("\ --foreign-user omit FSF copyright in output for foreign user\n")); printf (_("\ --msgid-bugs-address=EMAIL@ADDRESS set report address for msgid bugs\n")); printf (_("\ -m, --msgstr-prefix[=STRING] use STRING or \"\" as prefix for msgstr entries\n")); printf (_("\ -M, --msgstr-suffix[=STRING] use STRING or \"\" as suffix for msgstr entries\n")); printf ("\n"); printf (_("\ Informative output:\n")); printf (_("\ -h, --help display this help and exit\n")); printf (_("\ -V, --version output version information and exit\n")); printf ("\n"); fputs (_("Report bugs to <[email protected]>.\n"), stdout); } exit (status); } static void exclude_directive_domain (abstract_po_reader_ty *pop, char *name) { po_gram_error_at_line (&gram_pos, _("this file may not contain domain directives")); } static void exclude_directive_message (abstract_po_reader_ty *pop, char *msgid, lex_pos_ty *msgid_pos, char *msgid_plural, char *msgstr, size_t msgstr_len, lex_pos_ty *msgstr_pos, bool force_fuzzy, bool obsolete) { message_ty *mp; /* See if this message ID has been seen before. */ if (exclude == NULL) exclude = message_list_alloc (true); mp = message_list_search (exclude, msgid); if (mp != NULL) free (msgid); else { mp = message_alloc (msgid, msgid_plural, "", 1, msgstr_pos); /* Do not free msgid. */ message_list_append (exclude, mp); } /* All we care about is the msgid. Throw the msgstr away. Don't even check for duplicate msgids. */ free (msgstr); } /* So that the one parser can be used for multiple programs, and also use good data hiding and encapsulation practices, an object oriented approach has been taken. An object instance is allocated, and all actions resulting from the parse will be through invocations of method functions of that object. */ static abstract_po_reader_class_ty exclude_methods = { sizeof (abstract_po_reader_ty), NULL, /* constructor */ NULL, /* destructor */ NULL, /* parse_brief */ NULL, /* parse_debrief */ exclude_directive_domain, exclude_directive_message, NULL, /* comment */ NULL, /* comment_dot */ NULL, /* comment_filepos */ NULL, /* comment_special */ }; static void read_exclusion_file (char *filename) { char *real_filename; FILE *fp = open_po_file (filename, &real_filename, true); abstract_po_reader_ty *pop; pop = po_reader_alloc (&exclude_methods); po_scan (pop, fp, real_filename, filename, input_syntax); po_reader_free (pop); if (fp != stdin) fclose (fp); } void split_keywordspec (const char *spec, const char **endp, int *argnum1p, int *argnum2p) { const char *p; /* Start parsing from the end. */ p = spec + strlen (spec); if (p > spec && isdigit ((unsigned char) p[-1])) { const char *last_arg; do p--; while (p > spec && isdigit ((unsigned char) p[-1])); last_arg = p; if (p > spec && p[-1] == ',') { p--; if (p > spec && isdigit ((unsigned char) p[-1])) { const char *first_arg; do p--; while (p > spec && isdigit ((unsigned char) p[-1])); first_arg = p; if (p > spec && p[-1] == ':') { /* Parsed "KEYWORD:ARGNUM1,ARGNUM2". */ char *dummy; *endp = p - 1; *argnum1p = strtol (first_arg, &dummy, 10); *argnum2p = strtol (last_arg, &dummy, 10); return; } } } else if (p > spec && p[-1] == ':') { /* Parsed "KEYWORD:ARGNUM1. */ char *dummy; *endp = p - 1; *argnum1p = strtol (last_arg, &dummy, 10); *argnum2p = 0; return; } } /* Parsed "KEYWORD". */ *endp = p + strlen (p); *argnum1p = 0; *argnum2p = 0; } /* Null context. */ flag_context_ty null_context = { undecided, false, undecided, false }; /* Transparent context. */ flag_context_ty passthrough_context = { undecided, true, undecided, true }; flag_context_ty inherited_context (flag_context_ty outer_context, flag_context_ty modifier_context) { flag_context_ty result = modifier_context; if (result.pass_format1) { result.is_format1 = outer_context.is_format1; result.pass_format1 = false; } if (result.pass_format2) { result.is_format2 = outer_context.is_format2; result.pass_format2 = false; } return result; } /* Null context list iterator. */ flag_context_list_iterator_ty null_context_list_iterator = { 1, NULL }; /* Transparent context list iterator. */ static flag_context_list_ty passthrough_context_circular_list = { 1, { undecided, true, undecided, true }, &passthrough_context_circular_list }; flag_context_list_iterator_ty passthrough_context_list_iterator = { 1, &passthrough_context_circular_list }; flag_context_list_iterator_ty flag_context_list_iterator (flag_context_list_ty *list) { flag_context_list_iterator_ty result; result.argnum = 1; result.head = list; return result; } flag_context_ty flag_context_list_iterator_advance (flag_context_list_iterator_ty *iter) { if (iter->head == NULL) return null_context; if (iter->argnum == iter->head->argnum) { flag_context_ty result = iter->head->flags; /* Special casing of circular list. */ if (iter->head != iter->head->next) { iter->head = iter->head->next; iter->argnum++; } return result; } else { iter->argnum++; return null_context; } } flag_context_list_ty * flag_context_list_table_lookup (flag_context_list_table_ty *flag_table, const void *key, size_t keylen) { void *entry; if (flag_table->table != NULL && find_entry (flag_table, key, keylen, &entry) == 0) return (flag_context_list_ty *) entry; else return NULL; } static void flag_context_list_table_insert (flag_context_list_table_ty *table, unsigned int index, const char *name_start, const char *name_end, int argnum, enum is_format value, bool pass) { char *allocated_name = NULL; if (table == &flag_table_lisp) { /* Convert NAME to upper case. */ size_t name_len = name_end - name_start; char *name = allocated_name = (char *) xallocsa (name_len); size_t i; for (i = 0; i < name_len; i++) name[i] = (name_start[i] >= 'a' && name_start[i] <= 'z' ? name_start[i] - 'a' + 'A' : name_start[i]); name_start = name; name_end = name + name_len; } else if (table == &flag_table_tcl) { /* Remove redundant "::" prefix. */ if (name_end - name_start > 2 && name_start[0] == ':' && name_start[1] == ':') name_start += 2; } /* Insert the pair (VALUE, PASS) at INDEX in the element numbered ARGNUM of the list corresponding to NAME in the TABLE. */ if (table->table == NULL) init_hash (table, 100); { void *entry; if (find_entry (table, name_start, name_end - name_start, &entry) != 0) { /* Create new hash table entry. */ flag_context_list_ty *list = (flag_context_list_ty *) xmalloc (sizeof (flag_context_list_ty)); list->argnum = argnum; memset (&list->flags, '\0', sizeof (list->flags)); switch (index) { case 0: list->flags.is_format1 = value; list->flags.pass_format1 = pass; break; case 1: list->flags.is_format2 = value; list->flags.pass_format2 = pass; break; default: abort (); } list->next = NULL; insert_entry (table, name_start, name_end - name_start, list); } else { flag_context_list_ty *list = (flag_context_list_ty *)entry; flag_context_list_ty **lastp = NULL; while (list != NULL && list->argnum < argnum) { lastp = &list->next; list = *lastp; } if (list != NULL && list->argnum == argnum) { /* Add this flag to the current argument number. */ switch (index) { case 0: list->flags.is_format1 = value; list->flags.pass_format1 = pass; break; case 1: list->flags.is_format2 = value; list->flags.pass_format2 = pass; break; default: abort (); } } else if (lastp != NULL) { /* Add a new list entry for this argument number. */ list = (flag_context_list_ty *) xmalloc (sizeof (flag_context_list_ty)); list->argnum = argnum; memset (&list->flags, '\0', sizeof (list->flags)); switch (index) { case 0: list->flags.is_format1 = value; list->flags.pass_format1 = pass; break; case 1: list->flags.is_format2 = value; list->flags.pass_format2 = pass; break; default: abort (); } list->next = *lastp; *lastp = list; } else { /* Add a new list entry for this argument number, at the beginning of the list. Since we don't have an API for replacing the value of a key in the hash table, we have to copy the first list element. */ flag_context_list_ty *copy = (flag_context_list_ty *) xmalloc (sizeof (flag_context_list_ty)); *copy = *list; list->argnum = argnum; memset (&list->flags, '\0', sizeof (list->flags)); switch (index) { case 0: list->flags.is_format1 = value; list->flags.pass_format1 = pass; break; case 1: list->flags.is_format2 = value; list->flags.pass_format2 = pass; break; default: abort (); } list->next = copy; } } } if (allocated_name != NULL) freesa (allocated_name); } void xgettext_record_flag (const char *optionstring) { /* Check the string has at least two colons. (Colons in the name are allowed, needed for the Lisp and the Tcl backends.) */ const char *colon1; const char *colon2; for (colon2 = optionstring + strlen (optionstring); ; ) { if (colon2 == optionstring) goto err; colon2--; if (*colon2 == ':') break; } for (colon1 = colon2; ; ) { if (colon1 == optionstring) goto err; colon1--; if (*colon1 == ':') break; } { const char *name_start = optionstring; const char *name_end = colon1; const char *argnum_start = colon1 + 1; const char *argnum_end = colon2; const char *flag = colon2 + 1; int argnum; /* Check the parts' syntax. */ if (name_end == name_start) goto err; if (argnum_end == argnum_start) goto err; { char *endp; argnum = strtol (argnum_start, &endp, 10); if (endp != argnum_end) goto err; } if (argnum <= 0) goto err; /* Analyze the flag part. */ { bool pass; pass = false; if (strlen (flag) >= 5 && memcmp (flag, "pass-", 5) == 0) { pass = true; flag += 5; } /* Unlike po_parse_comment_special(), we don't accept "fuzzy" or "wrap" here - it has no sense. */ if (strlen (flag) >= 7 && memcmp (flag + strlen (flag) - 7, "-format", 7) == 0) { const char *p; size_t n; enum is_format value; size_t type; p = flag; n = strlen (flag) - 7; if (n >= 3 && memcmp (p, "no-", 3) == 0) { p += 3; n -= 3; value = no; } else if (n >= 9 && memcmp (p, "possible-", 9) == 0) { p += 9; n -= 9; value = possible; } else if (n >= 11 && memcmp (p, "impossible-", 11) == 0) { p += 11; n -= 11; value = impossible; } else value = yes_according_to_context; for (type = 0; type < NFORMATS; type++) if (strlen (format_language[type]) == n && memcmp (format_language[type], p, n) == 0) { switch (type) { case format_c: flag_context_list_table_insert (&flag_table_c, 0, name_start, name_end, argnum, value, pass); flag_context_list_table_insert (&flag_table_objc, 0, name_start, name_end, argnum, value, pass); break; case format_objc: flag_context_list_table_insert (&flag_table_objc, 1, name_start, name_end, argnum, value, pass); break; case format_sh: flag_context_list_table_insert (&flag_table_sh, 0, name_start, name_end, argnum, value, pass); break; case format_python: flag_context_list_table_insert (&flag_table_python, 0, name_start, name_end, argnum, value, pass); break; case format_lisp: flag_context_list_table_insert (&flag_table_lisp, 0, name_start, name_end, argnum, value, pass); break; case format_elisp: flag_context_list_table_insert (&flag_table_elisp, 0, name_start, name_end, argnum, value, pass); break; case format_librep: flag_context_list_table_insert (&flag_table_librep, 0, name_start, name_end, argnum, value, pass); break; case format_scheme: flag_context_list_table_insert (&flag_table_scheme, 0, name_start, name_end, argnum, value, pass); break; case format_smalltalk: break; case format_java: flag_context_list_table_insert (&flag_table_java, 0, name_start, name_end, argnum, value, pass); break; case format_csharp: flag_context_list_table_insert (&flag_table_csharp, 0, name_start, name_end, argnum, value, pass); break; case format_awk: flag_context_list_table_insert (&flag_table_awk, 0, name_start, name_end, argnum, value, pass); break; case format_pascal: break; case format_ycp: flag_context_list_table_insert (&flag_table_ycp, 0, name_start, name_end, argnum, value, pass); break; case format_tcl: flag_context_list_table_insert (&flag_table_tcl, 0, name_start, name_end, argnum, value, pass); break; case format_perl: flag_context_list_table_insert (&flag_table_perl, 0, name_start, name_end, argnum, value, pass); break; case format_perl_brace: flag_context_list_table_insert (&flag_table_perl, 1, name_start, name_end, argnum, value, pass); break; case format_php: flag_context_list_table_insert (&flag_table_php, 0, name_start, name_end, argnum, value, pass); break; case format_gcc_internal: flag_context_list_table_insert (&flag_table_gcc_internal, 0, name_start, name_end, argnum, value, pass); break; case format_qt: flag_context_list_table_insert (&flag_table_c, 0, name_start, name_end, argnum, value, pass); break; default: abort (); } return; } /* If the flag is not among the valid values, the optionstring is invalid. */ } } } err: error (EXIT_FAILURE, 0, _("\ A --flag argument doesn't have the <keyword>:<argnum>:[pass-]<flag> syntax: %s"), optionstring); } static string_list_ty *comment; void xgettext_comment_add (const char *str) { if (comment == NULL) comment = string_list_alloc (); string_list_append (comment, str); } const char * xgettext_comment (size_t n) { if (comment == NULL || n >= comment->nitems) return NULL; return comment->item[n]; } void xgettext_comment_reset () { if (comment != NULL) { string_list_free (comment); comment = NULL; } } refcounted_string_list_ty *savable_comment; void savable_comment_add (const char *str) { if (savable_comment == NULL) { savable_comment = (refcounted_string_list_ty *) xmalloc (sizeof (*savable_comment)); savable_comment->refcount = 1; string_list_init (&savable_comment->contents); } else if (savable_comment->refcount > 1) { /* Unshare the list by making copies. */ struct string_list_ty *oldcontents; size_t i; savable_comment->refcount--; oldcontents = &savable_comment->contents; savable_comment = (refcounted_string_list_ty *) xmalloc (sizeof (*savable_comment)); savable_comment->refcount = 1; string_list_init (&savable_comment->contents); for (i = 0; i < oldcontents->nitems; i++) string_list_append (&savable_comment->contents, oldcontents->item[i]); } string_list_append (&savable_comment->contents, str); } void savable_comment_reset () { drop_reference (savable_comment); savable_comment = NULL; } void savable_comment_to_xgettext_comment (refcounted_string_list_ty *rslp) { xgettext_comment_reset (); if (rslp != NULL) { size_t i; for (i = 0; i < rslp->contents.nitems; i++) xgettext_comment_add (rslp->contents.item[i]); } } static FILE * xgettext_open (const char *fn, char **logical_file_name_p, char **real_file_name_p) { FILE *fp; char *new_name; char *logical_file_name; if (strcmp (fn, "-") == 0) { new_name = xstrdup (_("standard input")); logical_file_name = xstrdup (new_name); fp = stdin; } else if (IS_ABSOLUTE_PATH (fn)) { new_name = xstrdup (fn); fp = fopen (fn, "r"); if (fp == NULL) error (EXIT_FAILURE, errno, _("\ error while opening \"%s\" for reading"), fn); logical_file_name = xstrdup (new_name); } else { int j; for (j = 0; ; ++j) { const char *dir = dir_list_nth (j); if (dir == NULL) error (EXIT_FAILURE, ENOENT, _("\ error while opening \"%s\" for reading"), fn); new_name = concatenated_pathname (dir, fn, NULL); fp = fopen (new_name, "r"); if (fp != NULL) break; if (errno != ENOENT) error (EXIT_FAILURE, errno, _("\ error while opening \"%s\" for reading"), new_name); free (new_name); } /* Note that the NEW_NAME variable contains the actual file name and the logical file name is what is reported by xgettext. In this case NEW_NAME is set to the file which was found along the directory search path, and LOGICAL_FILE_NAME is is set to the file name which was searched for. */ logical_file_name = xstrdup (fn); } *logical_file_name_p = logical_file_name; *real_file_name_p = new_name; return fp; } /* Language dependent format string parser. NULL if the language has no notion of format strings. */ static struct formatstring_parser *current_formatstring_parser1; static struct formatstring_parser *current_formatstring_parser2; static void extract_from_file (const char *file_name, extractor_ty extractor, msgdomain_list_ty *mdlp) { char *logical_file_name; char *real_file_name; FILE *fp = xgettext_open (file_name, &logical_file_name, &real_file_name); /* Set the default for the source file encoding. May be overridden by the extractor function. */ xgettext_current_source_encoding = xgettext_global_source_encoding; #if HAVE_ICONV xgettext_current_source_iconv = xgettext_global_source_iconv; #endif current_formatstring_parser1 = extractor.formatstring_parser1; current_formatstring_parser2 = extractor.formatstring_parser2; extractor.func (fp, real_file_name, logical_file_name, extractor.flag_table, mdlp); if (fp != stdin) fclose (fp); free (logical_file_name); free (real_file_name); } #if !HAVE_ICONV /* If we don't have iconv(), the only supported values for xgettext_global_source_encoding and thus also for xgettext_current_source_encoding are ASCII and UTF-8. convert_string() should not be called in this case. */ #define convert_string(cd,string) (abort (), (string)) #endif /* Convert the given string from xgettext_current_source_encoding to the output file encoding (i.e. ASCII or UTF-8). The resulting string is either the argument string, or freshly allocated. The file_name and line_number are only used for error message purposes. */ char * from_current_source_encoding (const char *string, const char *file_name, size_t line_number) { if (xgettext_current_source_encoding == po_charset_ascii) { if (!is_ascii_string (string)) { char buffer[21]; if (line_number == (size_t)(-1)) buffer[0] = '\0'; else sprintf (buffer, ":%ld", (long) line_number); multiline_error (xstrdup (""), xasprintf (_("\ Non-ASCII string at %s%s.\n\ Please specify the source encoding through --from-code.\n"), file_name, buffer)); exit (EXIT_FAILURE); } } else if (xgettext_current_source_encoding != po_charset_utf8) string = convert_string (xgettext_current_source_iconv, string); return (char *) string; } #define CONVERT_STRING(string) \ string = from_current_source_encoding (string, pos->file_name, \ pos->line_number); /* Update the is_format[] flags depending on the information given in the context. */ static void set_format_flags_from_context (enum is_format is_format[NFORMATS], flag_context_ty context, const char *string, lex_pos_ty *pos, const char *pretty_msgstr) { size_t i; if (context.is_format1 != undecided || context.is_format2 != undecided) for (i = 0; i < NFORMATS; i++) { if (is_format[i] == undecided) { if (formatstring_parsers[i] == current_formatstring_parser1 && context.is_format1 != undecided) is_format[i] = (enum is_format) context.is_format1; if (formatstring_parsers[i] == current_formatstring_parser2 && context.is_format2 != undecided) is_format[i] = (enum is_format) context.is_format2; } if (possible_format_p (is_format[i])) { struct formatstring_parser *parser = formatstring_parsers[i]; char *invalid_reason = NULL; void *descr = parser->parse (string, false, &invalid_reason); if (descr != NULL) parser->free (descr); else { /* The string is not a valid format string. */ if (is_format[i] != possible) { char buffer[21]; error_with_progname = false; if (pos->line_number == (size_t)(-1)) buffer[0] = '\0'; else sprintf (buffer, ":%ld", (long) pos->line_number); multiline_warning (xasprintf (_("%s%s: warning: "), pos->file_name, buffer), xasprintf (is_format[i] == yes_according_to_context ? _("Although being used in a format string position, the %s is not a valid %s format string. Reason: %s\n") : _("Although declared as such, the %s is not a valid %s format string. Reason: %s\n"), pretty_msgstr, format_language_pretty[i], invalid_reason)); error_with_progname = true; } is_format[i] = impossible; free (invalid_reason); } } } } message_ty * remember_a_message (message_list_ty *mlp, char *string, flag_context_ty context, lex_pos_ty *pos) { enum is_format is_format[NFORMATS]; enum is_wrap do_wrap; char *msgid; message_ty *mp; char *msgstr; size_t i; msgid = string; /* See whether we shall exclude this message. */ if (exclude != NULL && message_list_search (exclude, msgid) != NULL) { /* Tell the lexer to reset its comment buffer, so that the next message gets the correct comments. */ xgettext_comment_reset (); return NULL; } for (i = 0; i < NFORMATS; i++) is_format[i] = undecided; do_wrap = undecided; CONVERT_STRING (msgid); if (msgid[0] == '\0' && !xgettext_omit_header) { char buffer[21]; error_with_progname = false; if (pos->line_number == (size_t)(-1)) buffer[0] = '\0'; else sprintf (buffer, ":%ld", (long) pos->line_number); multiline_warning (xasprintf (_("%s%s: warning: "), pos->file_name, buffer), xstrdup (_("\ Empty msgid. It is reserved by GNU gettext:\n\ gettext(\"\") returns the header entry with\n\ meta information, not the empty string.\n"))); error_with_progname = true; } /* See if we have seen this message before. */ mp = message_list_search (mlp, msgid); if (mp != NULL) { free (msgid); for (i = 0; i < NFORMATS; i++) is_format[i] = mp->is_format[i]; do_wrap = mp->do_wrap; } else { static lex_pos_ty dummypos = { __FILE__, __LINE__ }; /* Construct the msgstr from the prefix and suffix, otherwise use the empty string. */ if (msgstr_prefix) { msgstr = (char *) xmalloc (strlen (msgstr_prefix) + strlen (msgid) + strlen (msgstr_suffix) + 1); stpcpy (stpcpy (stpcpy (msgstr, msgstr_prefix), msgid), msgstr_suffix); } else msgstr = ""; /* Allocate a new message and append the message to the list. */ mp = message_alloc (msgid, NULL, msgstr, strlen (msgstr) + 1, &dummypos); /* Do not free msgid. */ message_list_append (mlp, mp); } /* Determine whether the context specifies that the msgid is a format string. */ set_format_flags_from_context (is_format, context, mp->msgid, pos, "msgid"); /* Ask the lexer for the comments it has seen. */ { size_t nitems_before; size_t nitems_after; int j; bool add_all_remaining_comments; nitems_before = (mp->comment_dot != NULL ? mp->comment_dot->nitems : 0); add_all_remaining_comments = add_all_comments; for (j = 0; ; ++j) { const char *s = xgettext_comment (j); const char *t; if (s == NULL) break; CONVERT_STRING (s); /* To reduce the possibility of unwanted matches we do a two step match: the line must contain `xgettext:' and one of the possible format description strings. */ if ((t = strstr (s, "xgettext:")) != NULL) { bool tmp_fuzzy; enum is_format tmp_format[NFORMATS]; enum is_wrap tmp_wrap; bool interesting; t += strlen ("xgettext:"); po_parse_comment_special (t, &tmp_fuzzy, tmp_format, &tmp_wrap); interesting = false; for (i = 0; i < NFORMATS; i++) if (tmp_format[i] != undecided) { is_format[i] = tmp_format[i]; interesting = true; } if (tmp_wrap != undecided) { do_wrap = tmp_wrap; interesting = true; } /* If the "xgettext:" marker was followed by an interesting keyword, and we updated our is_format/do_wrap variables, we don't print the comment as a #. comment. */ if (interesting) continue; } /* When the comment tag is seen, it drags in not only the line which it starts, but all remaining comment lines. */ if (add_all_remaining_comments || (add_all_remaining_comments = (comment_tag != NULL && strncmp (s, comment_tag, strlen (comment_tag)) == 0))) message_comment_dot_append (mp, s); } nitems_after = (mp->comment_dot != NULL ? mp->comment_dot->nitems : 0); /* Don't add the comments if they are a repetition of the tail of the already present comments. This avoids unneeded duplication if the same message appears several times, each time with the same comment. */ if (nitems_before < nitems_after) { size_t added = nitems_after - nitems_before; if (added <= nitems_before) { bool repeated = true; for (i = 0; i < added; i++) if (strcmp (mp->comment_dot->item[nitems_before - added + i], mp->comment_dot->item[nitems_before + i]) != 0) { repeated = false; break; } if (repeated) { for (i = 0; i < added; i++) free ((char *) mp->comment_dot->item[nitems_before + i]); mp->comment_dot->nitems = nitems_before; } } } } /* If it is not already decided, through programmer comments, whether the msgid is a format string, examine the msgid. This is a heuristic. */ for (i = 0; i < NFORMATS; i++) { if (is_format[i] == undecided && (formatstring_parsers[i] == current_formatstring_parser1 || formatstring_parsers[i] == current_formatstring_parser2) /* But avoid redundancy: objc-format is stronger than c-format. */ && !(i == format_c && possible_format_p (is_format[format_objc])) && !(i == format_objc && possible_format_p (is_format[format_c]))) { struct formatstring_parser *parser = formatstring_parsers[i]; char *invalid_reason = NULL; void *descr = parser->parse (mp->msgid, false, &invalid_reason); if (descr != NULL) { /* msgid is a valid format string. We mark only those msgids as format strings which contain at least one format directive and thus are format strings with a high probability. We don't mark strings without directives as format strings, because that would force the programmer to add "xgettext: no-c-format" anywhere where a translator wishes to use a percent sign. So, the msgfmt checking will not be perfect. Oh well. */ if (parser->get_number_of_directives (descr) > 0) is_format[i] = possible; parser->free (descr); } else { /* msgid is not a valid format string. */ is_format[i] = impossible; free (invalid_reason); } } mp->is_format[i] = is_format[i]; } mp->do_wrap = do_wrap == no ? no : yes; /* By default we wrap. */ /* Remember where we saw this msgid. */ if (line_comment) message_comment_filepos (mp, pos->file_name, pos->line_number); /* Tell the lexer to reset its comment buffer, so that the next message gets the correct comments. */ xgettext_comment_reset (); return mp; } void remember_a_message_plural (message_ty *mp, char *string, flag_context_ty context, lex_pos_ty *pos) { char *msgid_plural; char *msgstr1; size_t msgstr1_len; char *msgstr; size_t i; msgid_plural = string; CONVERT_STRING (msgid_plural); /* See if the message is already a plural message. */ if (mp->msgid_plural == NULL) { mp->msgid_plural = msgid_plural; /* Construct the first plural form from the prefix and suffix, otherwise use the empty string. The translator will have to provide additional plural forms. */ if (msgstr_prefix) { msgstr1 = (char *) xmalloc (strlen (msgstr_prefix) + strlen (msgid_plural) + strlen (msgstr_suffix) + 1); stpcpy (stpcpy (stpcpy (msgstr1, msgstr_prefix), msgid_plural), msgstr_suffix); } else msgstr1 = ""; msgstr1_len = strlen (msgstr1) + 1; msgstr = (char *) xmalloc (mp->msgstr_len + msgstr1_len); memcpy (msgstr, mp->msgstr, mp->msgstr_len); memcpy (msgstr + mp->msgstr_len, msgstr1, msgstr1_len); mp->msgstr = msgstr; mp->msgstr_len = mp->msgstr_len + msgstr1_len; /* Determine whether the context specifies that the msgid_plural is a format string. */ set_format_flags_from_context (mp->is_format, context, mp->msgid_plural, pos, "msgid_plural"); /* If it is not already decided, through programmer comments or the msgid, whether the msgid is a format string, examine the msgid_plural. This is a heuristic. */ for (i = 0; i < NFORMATS; i++) if ((formatstring_parsers[i] == current_formatstring_parser1 || formatstring_parsers[i] == current_formatstring_parser2) && (mp->is_format[i] == undecided || mp->is_format[i] == possible) /* But avoid redundancy: objc-format is stronger than c-format. */ && !(i == format_c && possible_format_p (mp->is_format[format_objc])) && !(i == format_objc && possible_format_p (mp->is_format[format_c]))) { struct formatstring_parser *parser = formatstring_parsers[i]; char *invalid_reason = NULL; void *descr = parser->parse (mp->msgid_plural, false, &invalid_reason); if (descr != NULL) { /* Same heuristic as in remember_a_message. */ if (parser->get_number_of_directives (descr) > 0) mp->is_format[i] = possible; parser->free (descr); } else { /* msgid_plural is not a valid format string. */ mp->is_format[i] = impossible; free (invalid_reason); } } } else free (msgid_plural); } static message_ty * construct_header () { time_t now; char *timestring; message_ty *mp; char *msgstr; static lex_pos_ty pos = { __FILE__, __LINE__ }; if (msgid_bugs_address != NULL && msgid_bugs_address[0] == '\0') multiline_warning (xasprintf (_("warning: ")), xstrdup (_("\ The option --msgid-bugs-address was not specified.\n\ If you are using a `Makevars' file, please specify\n\ the MSGID_BUGS_ADDRESS variable there; otherwise please\n\ specify an --msgid-bugs-address command line option.\n\ "))); time (&now); timestring = po_strftime (&now); msgstr = xasprintf ("\ Project-Id-Version: PACKAGE VERSION\n\ Report-Msgid-Bugs-To: %s\n\ POT-Creation-Date: %s\n\ PO-Revision-Date: YEAR-MO-DA HO:MI+ZONE\n\ Last-Translator: FULL NAME <EMAIL@ADDRESS>\n\ Language-Team: LANGUAGE <[email protected]>\n\ MIME-Version: 1.0\n\ Content-Type: text/plain; charset=CHARSET\n\ Content-Transfer-Encoding: 8bit\n", msgid_bugs_address != NULL ? msgid_bugs_address : "", timestring); free (timestring); mp = message_alloc ("", NULL, msgstr, strlen (msgstr) + 1, &pos); message_comment_append (mp, copyright_holder[0] != '\0' ? xasprintf ("\ SOME DESCRIPTIVE TITLE.\n\ Copyright (C) YEAR %s\n\ This file is distributed under the same license as the PACKAGE package.\n\ FIRST AUTHOR <EMAIL@ADDRESS>, YEAR.\n", copyright_holder) : "\ SOME DESCRIPTIVE TITLE.\n\ This file is put in the public domain.\n\ FIRST AUTHOR <EMAIL@ADDRESS>, YEAR.\n"); mp->is_fuzzy = true; return mp; } static void finalize_header (msgdomain_list_ty *mdlp) { /* If the generated PO file has plural forms, add a Plural-Forms template to the constructed header. */ { bool has_plural; size_t i, j; has_plural = false; for (i = 0; i < mdlp->nitems; i++) { message_list_ty *mlp = mdlp->item[i]->messages; for (j = 0; j < mlp->nitems; j++) { message_ty *mp = mlp->item[j]; if (mp->msgid_plural != NULL) { has_plural = true; break; } } if (has_plural) break; } if (has_plural) { message_ty *header = message_list_search (mdlp->item[0]->messages, ""); if (header != NULL && strstr (header->msgstr, "Plural-Forms:") == NULL) { size_t insertpos = strlen (header->msgstr); const char *suffix; size_t suffix_len; char *new_msgstr; suffix = "\nPlural-Forms: nplurals=INTEGER; plural=EXPRESSION;\n"; if (insertpos == 0 || header->msgstr[insertpos-1] == '\n') suffix++; suffix_len = strlen (suffix); new_msgstr = (char *) xmalloc (header->msgstr_len + suffix_len); memcpy (new_msgstr, header->msgstr, insertpos); memcpy (new_msgstr + insertpos, suffix, suffix_len); memcpy (new_msgstr + insertpos + suffix_len, header->msgstr + insertpos, header->msgstr_len - insertpos); header->msgstr = new_msgstr; header->msgstr_len = header->msgstr_len + suffix_len; } } } /* If not all the strings were plain ASCII, or if the output syntax requires a charset conversion, set the charset in the header to UTF-8. All messages have already been converted to UTF-8 in remember_a_message and remember_a_message_plural. */ { bool has_nonascii = false; size_t i; for (i = 0; i < mdlp->nitems; i++) { message_list_ty *mlp = mdlp->item[i]->messages; if (!is_ascii_message_list (mlp)) has_nonascii = true; } if (has_nonascii || output_syntax == syntax_properties || output_syntax == syntax_stringtable) { message_list_ty *mlp = mdlp->item[0]->messages; iconv_message_list (mlp, po_charset_utf8, po_charset_utf8, NULL); } } } #define SIZEOF(a) (sizeof(a) / sizeof(a[0])) #define ENDOF(a) ((a) + SIZEOF(a)) static extractor_ty language_to_extractor (const char *name) { struct table_ty { const char *name; extractor_func func; flag_context_list_table_ty *flag_table; struct formatstring_parser *formatstring_parser1; struct formatstring_parser *formatstring_parser2; }; typedef struct table_ty table_ty; static table_ty table[] = { SCANNERS_C SCANNERS_PO SCANNERS_SH SCANNERS_PYTHON SCANNERS_LISP SCANNERS_ELISP SCANNERS_LIBREP SCANNERS_SCHEME SCANNERS_SMALLTALK SCANNERS_JAVA SCANNERS_PROPERTIES SCANNERS_CSHARP SCANNERS_AWK SCANNERS_YCP SCANNERS_TCL SCANNERS_PERL SCANNERS_PHP SCANNERS_STRINGTABLE SCANNERS_RST SCANNERS_GLADE /* Here may follow more languages and their scanners: pike, etc... Make sure new scanners honor the --exclude-file option. */ }; table_ty *tp; for (tp = table; tp < ENDOF(table); ++tp) if (c_strcasecmp (name, tp->name) == 0) { extractor_ty result; result.func = tp->func; result.flag_table = tp->flag_table; result.formatstring_parser1 = tp->formatstring_parser1; result.formatstring_parser2 = tp->formatstring_parser2; /* Handle --qt. It's preferrable to handle this facility here rather than through an option --language=C++/Qt because the latter would conflict with the language "C++" regarding the file extensions. */ if (recognize_format_qt && strcmp (tp->name, "C++") == 0) result.formatstring_parser2 = &formatstring_qt; return result; } error (EXIT_FAILURE, 0, _("language `%s' unknown"), name); /* NOTREACHED */ { extractor_ty result = { NULL, NULL, NULL, NULL }; return result; } } static const char * extension_to_language (const char *extension) { struct table_ty { const char *extension; const char *language; }; typedef struct table_ty table_ty; static table_ty table[] = { EXTENSIONS_C EXTENSIONS_PO EXTENSIONS_SH EXTENSIONS_PYTHON EXTENSIONS_LISP EXTENSIONS_ELISP EXTENSIONS_LIBREP EXTENSIONS_SCHEME EXTENSIONS_SMALLTALK EXTENSIONS_JAVA EXTENSIONS_PROPERTIES EXTENSIONS_CSHARP EXTENSIONS_AWK EXTENSIONS_YCP EXTENSIONS_TCL EXTENSIONS_PERL EXTENSIONS_PHP EXTENSIONS_STRINGTABLE EXTENSIONS_RST EXTENSIONS_GLADE /* Here may follow more file extensions... */ }; table_ty *tp; for (tp = table; tp < ENDOF(table); ++tp) if (strcmp (extension, tp->extension) == 0) return tp->language; return NULL; }
{ "content_hash": "aa8c958efbd482504ef6755c714ce5ea", "timestamp": "", "source": "github", "line_count": 2296, "max_line_length": 259, "avg_line_length": 27.96254355400697, "alnum_prop": 0.6081586243419208, "repo_name": "execunix/vinos", "id": "eb035f91b5efd7b3971c70555ca8162bef5637c1", "size": "65104", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "gnu/dist/gettext/gettext-tools/src/xgettext.c", "mode": "33188", "license": "apache-2.0", "language": [], "symlink_target": "" }
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("SalesApp.Web")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("SalesApp.Web")] [assembly: AssemblyCopyright("Copyright © 2015")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("d1f30c3e-0a31-4ba2-852b-e9ed205aac8e")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Revision and Build Numbers // by using the '*' as shown below: [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
{ "content_hash": "3095683dc72ea5fe63946d95153f8cca", "timestamp": "", "source": "github", "line_count": 35, "max_line_length": 84, "avg_line_length": 39.628571428571426, "alnum_prop": 0.7310742609949531, "repo_name": "huanlin/Examples", "id": "a49fe41b92b0e4ddfbdd2cb631fa8890543f47bb", "size": "1390", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "DotNet/Web/CQRS Demo/SalesApp.Web/Properties/AssemblyInfo.cs", "mode": "33188", "license": "mit", "language": [ { "name": "ASP.NET", "bytes": "7864" }, { "name": "C", "bytes": "7229" }, { "name": "C#", "bytes": "815053" }, { "name": "C++", "bytes": "360577" }, { "name": "CSS", "bytes": "27580" }, { "name": "HTML", "bytes": "65651" }, { "name": "JavaScript", "bytes": "4859624" }, { "name": "Pascal", "bytes": "38856" }, { "name": "Pawn", "bytes": "911" }, { "name": "PowerShell", "bytes": "846" }, { "name": "QMake", "bytes": "7744" }, { "name": "Ruby", "bytes": "5958" }, { "name": "VBA", "bytes": "5920" } ], "symlink_target": "" }
import * as tf from '../index'; import {CHROME_ENVS, describeWithFlags} from '../jasmine_util'; import {deleteDatabase} from './indexed_db'; import {purgeLocalStorageArtifacts} from './local_storage'; // Disabled for non-Chrome browsers due to: // https://github.com/tensorflow/tfjs/issues/427 describeWithFlags('ModelManagement', CHROME_ENVS, () => { // Test data. const modelTopology1: {} = { 'class_name': 'Sequential', 'keras_version': '2.1.4', 'config': [{ 'class_name': 'Dense', 'config': { 'kernel_initializer': { 'class_name': 'VarianceScaling', 'config': { 'distribution': 'uniform', 'scale': 1.0, 'seed': null, 'mode': 'fan_avg' } }, 'name': 'dense', 'kernel_constraint': null, 'bias_regularizer': null, 'bias_constraint': null, 'dtype': 'float32', 'activation': 'linear', 'trainable': true, 'kernel_regularizer': null, 'bias_initializer': {'class_name': 'Zeros', 'config': {}}, 'units': 1, 'batch_input_shape': [null, 3], 'use_bias': true, 'activity_regularizer': null } }], 'backend': 'tensorflow' }; const weightSpecs1: tf.io.WeightsManifestEntry[] = [ { name: 'dense/kernel', shape: [3, 1], dtype: 'float32', }, { name: 'dense/bias', shape: [1], dtype: 'float32', } ]; const weightData1 = new ArrayBuffer(16); const artifacts1: tf.io.ModelArtifacts = { modelTopology: modelTopology1, weightSpecs: weightSpecs1, weightData: weightData1, }; beforeEach(done => { purgeLocalStorageArtifacts(); deleteDatabase().then(() => { done(); }); }); afterEach(done => { purgeLocalStorageArtifacts(); deleteDatabase().then(() => { done(); }); }); // TODO(cais): Reenable this test once we fix // https://github.com/tensorflow/tfjs/issues/1198 // tslint:disable-next-line:ban xit('List models: 0 result', done => { // Before any model is saved, listModels should return empty result. tf.io.listModels() .then(out => { expect(out).toEqual({}); done(); }) .catch(err => done.fail(err.stack)); }); // TODO(cais): Reenable this test once we fix // https://github.com/tensorflow/tfjs/issues/1198 // tslint:disable-next-line:ban xit('List models: 1 result', done => { const url = 'localstorage://baz/QuxModel'; const handler = tf.io.getSaveHandlers(url)[0]; handler.save(artifacts1) .then(saveResult => { // After successful saving, there should be one model. tf.io.listModels() .then(out => { expect(Object.keys(out).length).toEqual(1); expect(out[url].modelTopologyType) .toEqual(saveResult.modelArtifactsInfo.modelTopologyType); expect(out[url].modelTopologyBytes) .toEqual(saveResult.modelArtifactsInfo.modelTopologyBytes); expect(out[url].weightSpecsBytes) .toEqual(saveResult.modelArtifactsInfo.weightSpecsBytes); expect(out[url].weightDataBytes) .toEqual(saveResult.modelArtifactsInfo.weightDataBytes); done(); }) .catch(err => done.fail(err.stack)); }) .catch(err => done.fail(err.stack)); }); // TODO(cais): Reenable this test once we fix // https://github.com/tensorflow/tfjs/issues/1198 // tslint:disable-next-line:ban xit('Manager: List models: 2 results in 2 mediums', done => { const url1 = 'localstorage://QuxModel'; const url2 = 'indexeddb://QuxModel'; // First, save a model in Local Storage. const handler1 = tf.io.getSaveHandlers(url1)[0]; handler1.save(artifacts1) .then(saveResult1 => { // Then, save the model in IndexedDB. const handler2 = tf.io.getSaveHandlers(url2)[0]; handler2.save(artifacts1) .then(saveResult2 => { // After successful saving, there should be two models. tf.io.listModels() .then(out => { expect(Object.keys(out).length).toEqual(2); expect(out[url1].modelTopologyType) .toEqual( saveResult1.modelArtifactsInfo.modelTopologyType); expect(out[url1].modelTopologyBytes) .toEqual(saveResult1.modelArtifactsInfo .modelTopologyBytes); expect(out[url1].weightSpecsBytes) .toEqual( saveResult1.modelArtifactsInfo.weightSpecsBytes); expect(out[url1].weightDataBytes) .toEqual( saveResult1.modelArtifactsInfo.weightDataBytes); expect(out[url2].modelTopologyType) .toEqual( saveResult2.modelArtifactsInfo.modelTopologyType); expect(out[url2].modelTopologyBytes) .toEqual(saveResult2.modelArtifactsInfo .modelTopologyBytes); expect(out[url2].weightSpecsBytes) .toEqual( saveResult2.modelArtifactsInfo.weightSpecsBytes); expect(out[url2].weightDataBytes) .toEqual( saveResult2.modelArtifactsInfo.weightDataBytes); done(); }) .catch(err => done.fail(err.stack)); }) .catch(err => done.fail(err.stack)); }) .catch(err => done.fail(err.stack)); }); // TODO(cais): Reenable this test once we fix // https://github.com/tensorflow/tfjs/issues/1198 // tslint:disable-next-line:ban xit('Successful removeModel', done => { // First, save a model. const handler1 = tf.io.getSaveHandlers('localstorage://QuxModel')[0]; handler1.save(artifacts1) .then(saveResult1 => { // Then, save the model under another path. const handler2 = tf.io.getSaveHandlers('indexeddb://repeat/QuxModel')[0]; handler2.save(artifacts1) .then(saveResult2 => { // After successful saving, delete the first save, and then // `listModel` should give only one result. // Delete a model specified with a path that includes the // indexeddb:// scheme prefix should work. tf.io.removeModel('indexeddb://repeat/QuxModel') .then(deletedInfo => { tf.io.listModels() .then(out => { expect(Object.keys(out)).toEqual([ 'localstorage://QuxModel' ]); tf.io.removeModel('localstorage://QuxModel') .then(out => { // The delete the remaining model. tf.io.listModels() .then(out => { expect(Object.keys(out)).toEqual([]); done(); }) .catch(err => done.fail(err)); }) .catch(err => done.fail(err)); }) .catch(err => done.fail(err)); }) .catch(err => done.fail(err.stack)); }) .catch(err => done.fail(err.stack)); }) .catch(err => done.fail(err.stack)); }); // TODO(cais): Reenable this test once we fix // https://github.com/tensorflow/tfjs/issues/1198 // tslint:disable-next-line:ban xit('Successful copyModel between mediums', done => { const url1 = 'localstorage://a1/FooModel'; const url2 = 'indexeddb://a1/FooModel'; // First, save a model. const handler1 = tf.io.getSaveHandlers(url1)[0]; handler1.save(artifacts1) .then(saveResult => { // Once model is saved, copy the model to another path. tf.io.copyModel(url1, url2) .then(modelInfo => { tf.io.listModels().then(out => { expect(Object.keys(out).length).toEqual(2); expect(out[url1].modelTopologyType) .toEqual(saveResult.modelArtifactsInfo.modelTopologyType); expect(out[url1].modelTopologyBytes) .toEqual( saveResult.modelArtifactsInfo.modelTopologyBytes); expect(out[url1].weightSpecsBytes) .toEqual(saveResult.modelArtifactsInfo.weightSpecsBytes); expect(out[url1].weightDataBytes) .toEqual(saveResult.modelArtifactsInfo.weightDataBytes); expect(out[url2].modelTopologyType) .toEqual(saveResult.modelArtifactsInfo.modelTopologyType); expect(out[url2].modelTopologyBytes) .toEqual( saveResult.modelArtifactsInfo.modelTopologyBytes); expect(out[url2].weightSpecsBytes) .toEqual(saveResult.modelArtifactsInfo.weightSpecsBytes); expect(out[url2].weightDataBytes) .toEqual(saveResult.modelArtifactsInfo.weightDataBytes); // Load the copy and verify the content. const handler2 = tf.io.getLoadHandlers(url2)[0]; handler2.load() .then(loaded => { expect(loaded.modelTopology).toEqual(modelTopology1); expect(loaded.weightSpecs).toEqual(weightSpecs1); expect(new Uint8Array(loaded.weightData)) .toEqual(new Uint8Array(weightData1)); done(); }) .catch(err => done.fail(err.stack)); }); }) .catch(err => done.fail(err.stack)); }) .catch(err => done.fail(err.stack)); }); // TODO(cais): Reenable this test once we fix // https://github.com/tensorflow/tfjs/issues/1198 // tslint:disable-next-line:ban xit('Successful moveModel between mediums', done => { const url1 = 'localstorage://a1/FooModel'; const url2 = 'indexeddb://a1/FooModel'; // First, save a model. const handler1 = tf.io.getSaveHandlers(url1)[0]; handler1.save(artifacts1) .then(saveResult => { // Once model is saved, move the model to another path. tf.io.moveModel(url1, url2) .then(modelInfo => { tf.io.listModels().then(out => { expect(Object.keys(out)).toEqual([url2]); expect(out[url2].modelTopologyType) .toEqual(saveResult.modelArtifactsInfo.modelTopologyType); expect(out[url2].modelTopologyBytes) .toEqual( saveResult.modelArtifactsInfo.modelTopologyBytes); expect(out[url2].weightSpecsBytes) .toEqual(saveResult.modelArtifactsInfo.weightSpecsBytes); expect(out[url2].weightDataBytes) .toEqual(saveResult.modelArtifactsInfo.weightDataBytes); // Load the copy and verify the content. const handler2 = tf.io.getLoadHandlers(url2)[0]; handler2.load() .then(loaded => { expect(loaded.modelTopology).toEqual(modelTopology1); expect(loaded.weightSpecs).toEqual(weightSpecs1); expect(new Uint8Array(loaded.weightData)) .toEqual(new Uint8Array(weightData1)); done(); }) .catch(err => { done.fail(err.stack); }); }); }) .catch(err => done.fail(err.stack)); }) .catch(err => done.fail(err.stack)); }); it('Failed copyModel to invalid source URL', done => { const url1 = 'invalidurl'; const url2 = 'localstorage://a1/FooModel'; tf.io.copyModel(url1, url2) .then(out => { done.fail('Copying from invalid URL succeeded unexpectedly.'); }) .catch(err => { expect(err.message) .toEqual( 'Copying failed because no load handler is found for ' + 'source URL invalidurl.'); done(); }); }); it('Failed copyModel to invalid destination URL', done => { const url1 = 'localstorage://a1/FooModel'; const url2 = 'invalidurl'; // First, save a model. const handler1 = tf.io.getSaveHandlers(url1)[0]; handler1.save(artifacts1) .then(saveResult => { // Once model is saved, copy the model to another path. tf.io.copyModel(url1, url2) .then(out => { done.fail('Copying to invalid URL succeeded unexpectedly.'); }) .catch(err => { expect(err.message) .toEqual( 'Copying failed because no save handler is found for ' + 'destination URL invalidurl.'); done(); }); }) .catch(err => done.fail(err.stack)); }); it('Failed moveModel to invalid destination URL', done => { const url1 = 'localstorage://a1/FooModel'; const url2 = 'invalidurl'; // First, save a model. const handler1 = tf.io.getSaveHandlers(url1)[0]; handler1.save(artifacts1) .then(saveResult => { // Once model is saved, copy the model to an invalid path, which // should fail. tf.io.moveModel(url1, url2) .then(out => { done.fail('Copying to invalid URL succeeded unexpectedly.'); }) .catch(err => { expect(err.message) .toEqual( 'Copying failed because no save handler is found for ' + 'destination URL invalidurl.'); // Verify that the source has not been removed. tf.io.listModels() .then(out => { expect(Object.keys(out)).toEqual([url1]); done(); }) .catch(err => done.fail(err.stack)); }); }) .catch(err => done.fail(err.stack)); }); it('Failed deletedModel: Absent scheme', done => { // Attempt to delete a nonexistent model is expected to fail. tf.io.removeModel('foo') .then(out => { done.fail( 'Removing model with missing scheme succeeded unexpectedly.'); }) .catch(err => { expect(err.message) .toMatch(/The url string provided does not contain a scheme/); expect(err.message.indexOf('localstorage')).toBeGreaterThan(0); expect(err.message.indexOf('indexeddb')).toBeGreaterThan(0); done(); }); }); it('Failed deletedModel: Invalid scheme', done => { // Attempt to delete a nonexistent model is expected to fail. tf.io.removeModel('invalidscheme://foo') .then(out => { done.fail('Removing nonexistent model succeeded unexpectedly.'); }) .catch(err => { expect(err.message) .toEqual( 'Cannot find model manager for scheme \'invalidscheme\''); done(); }); }); it('Failed deletedModel: Nonexistent model', done => { // Attempt to delete a nonexistent model is expected to fail. tf.io.removeModel('indexeddb://nonexistent') .then(out => { done.fail('Removing nonexistent model succeeded unexpectedly.'); }) .catch(err => { expect(err.message) .toEqual( 'Cannot find model with path \'nonexistent\' in IndexedDB.'); done(); }); }); it('Failed copyModel', done => { // Attempt to copy a nonexistent model should fail. tf.io.copyModel('indexeddb://nonexistent', 'indexeddb://destination') .then(out => { done.fail('Copying nonexistent model succeeded unexpectedly.'); }) .catch(err => { expect(err.message) .toEqual( 'Cannot find model with path \'nonexistent\' in IndexedDB.'); done(); }); }); it('copyModel: Identical oldPath and newPath leads to Error', done => { tf.io.copyModel('a/1', 'a/1') .then(out => { done.fail( 'Copying with identical old & new paths succeeded unexpectedly.'); }) .catch(err => { expect(err.message) .toEqual('Old path and new path are the same: \'a/1\''); done(); }); }); it('moveModel: Identical oldPath and newPath leads to Error', done => { tf.io.moveModel('a/1', 'a/1') .then(out => { done.fail( 'Copying with identical old & new paths succeeded unexpectedly.'); }) .catch(err => { expect(err.message) .toEqual('Old path and new path are the same: \'a/1\''); done(); }); }); });
{ "content_hash": "ef9008be336d30e8887373ffc34504fc", "timestamp": "", "source": "github", "line_count": 466, "max_line_length": 80, "avg_line_length": 38.667381974248926, "alnum_prop": 0.513680004439758, "repo_name": "tensorflow/tfjs-core", "id": "be29c7bdff08286623ff5ea41a688eff945049de", "size": "18721", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "tfjs-core/src/io/model_management_test.ts", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "C++", "bytes": "8700" }, { "name": "HTML", "bytes": "18822" }, { "name": "JavaScript", "bytes": "47350" }, { "name": "Python", "bytes": "1065" }, { "name": "Shell", "bytes": "11363" }, { "name": "TypeScript", "bytes": "3469230" } ], "symlink_target": "" }
(function($) { 'use strict'; $.jCarousel.plugin('jcarouselAutoscroll', { _options: { target: '+=1', interval: 3000, autostart: true }, _timer: null, _init: function () { this.onDestroy = $.proxy(function() { this._destroy(); this.carousel() .one('jcarousel:createend', $.proxy(this._create, this)); }, this); this.onAnimateEnd = $.proxy(this.start, this); }, _create: function() { this.carousel() .one('jcarousel:destroy', this.onDestroy); if (this.options('autostart')) { this.start(); } }, _destroy: function() { this.stop(); this.carousel() .off('jcarousel:destroy', this.onDestroy); }, start: function() { this.stop(); this.carousel() .one('jcarousel:animateend', this.onAnimateEnd); this._timer = setTimeout($.proxy(function() { this.carousel().jcarousel('scroll', this.options('target')); }, this), this.options('interval')); return this; }, stop: function() { if (this._timer) { this._timer = clearTimeout(this._timer); } this.carousel() .off('jcarousel:animateend', this.onAnimateEnd); return this; } }); }(jQuery));
{ "content_hash": "ed56eccf342deac7cf2b365e202f5db1", "timestamp": "", "source": "github", "line_count": 57, "max_line_length": 77, "avg_line_length": 27.333333333333332, "alnum_prop": 0.444801026957638, "repo_name": "margaritis/jcarousel", "id": "2fbba2e9823f6b630c02e941784a62cc2dc3c1a8", "size": "1676", "binary": false, "copies": "3", "ref": "refs/heads/master", "path": "dist/jquery.jcarousel-autoscroll.js", "mode": "33188", "license": "mit", "language": [], "symlink_target": "" }
package Google::Ads::AdWords::v201409::LabelService::mutateResponse; use strict; use warnings; { # BLOCK to scope variables sub get_xmlns { 'https://adwords.google.com/api/adwords/cm/v201409' } __PACKAGE__->__set_name('mutateResponse'); __PACKAGE__->__set_nillable(); __PACKAGE__->__set_minOccurs(); __PACKAGE__->__set_maxOccurs(); __PACKAGE__->__set_ref(); use base qw( SOAP::WSDL::XSD::Typelib::Element Google::Ads::SOAP::Typelib::ComplexType ); our $XML_ATTRIBUTE_CLASS; undef $XML_ATTRIBUTE_CLASS; sub __get_attr_class { return $XML_ATTRIBUTE_CLASS; } use Class::Std::Fast::Storable constructor => 'none'; use base qw(Google::Ads::SOAP::Typelib::ComplexType); { # BLOCK to scope variables my %rval_of :ATTR(:get<rval>); __PACKAGE__->_factory( [ qw( rval ) ], { 'rval' => \%rval_of, }, { 'rval' => 'Google::Ads::AdWords::v201409::LabelReturnValue', }, { 'rval' => 'rval', } ); } # end BLOCK } # end of BLOCK 1; =pod =head1 NAME Google::Ads::AdWords::v201409::LabelService::mutateResponse =head1 DESCRIPTION Perl data type class for the XML Schema defined element mutateResponse from the namespace https://adwords.google.com/api/adwords/cm/v201409. =head1 PROPERTIES The following properties may be accessed using get_PROPERTY / set_PROPERTY methods: =over =item * rval $element->set_rval($data); $element->get_rval(); =back =head1 METHODS =head2 new my $element = Google::Ads::AdWords::v201409::LabelService::mutateResponse->new($data); Constructor. The following data structure may be passed to new(): { rval => $a_reference_to, # see Google::Ads::AdWords::v201409::LabelReturnValue }, =head1 AUTHOR Generated by SOAP::WSDL =cut
{ "content_hash": "da77536b5236ab1b1283e89ccac98232", "timestamp": "", "source": "github", "line_count": 117, "max_line_length": 87, "avg_line_length": 15.136752136752136, "alnum_prop": 0.655561829474873, "repo_name": "gitpan/Google-Ads-AdWords-Client", "id": "6e7205778672c1553f05994befc4b29f82cc81dc", "size": "1772", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "lib/Google/Ads/AdWords/v201409/LabelService/mutateResponse.pm", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Perl", "bytes": "18425492" } ], "symlink_target": "" }
package org.apache.avro.path; /** * Returns items by their position (string key under which they are stored) in a * map */ public class MapKeyPredicate implements PositionalPathPredicate { private final String key; public MapKeyPredicate(String key) { this.key = key; } public String getKey() { return key; } @Override public String toString() { if (key == null) { return ""; } return "[\"" + key + "\"]"; } }
{ "content_hash": "6d9d18faf9dece2f6d97aa3491fb72ec", "timestamp": "", "source": "github", "line_count": 27, "max_line_length": 80, "avg_line_length": 17.074074074074073, "alnum_prop": 0.6247288503253796, "repo_name": "apache/avro", "id": "b183d8459d3d6d8f781388404fa2679f7ef47c6b", "size": "1267", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "lang/java/avro/src/main/java/org/apache/avro/path/MapKeyPredicate.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Batchfile", "bytes": "1510" }, { "name": "C", "bytes": "971770" }, { "name": "C#", "bytes": "1556714" }, { "name": "C++", "bytes": "782233" }, { "name": "CMake", "bytes": "28974" }, { "name": "CSS", "bytes": "3564" }, { "name": "Dockerfile", "bytes": "8920" }, { "name": "HTML", "bytes": "109383" }, { "name": "Java", "bytes": "4059696" }, { "name": "JavaScript", "bytes": "351520" }, { "name": "LLVM", "bytes": "7847" }, { "name": "M4", "bytes": "29412" }, { "name": "Makefile", "bytes": "2320" }, { "name": "PHP", "bytes": "267747" }, { "name": "Perl", "bytes": "116488" }, { "name": "Python", "bytes": "412833" }, { "name": "Ruby", "bytes": "248021" }, { "name": "Rust", "bytes": "702593" }, { "name": "Shell", "bytes": "60162" }, { "name": "Thrift", "bytes": "1559" }, { "name": "Vim Script", "bytes": "2765" }, { "name": "Yacc", "bytes": "5195" } ], "symlink_target": "" }
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package team.util; /** * * @author team3574 */ public class Location { private double heading, xLocation, yLocation; public Location(double x, double y, double heading){ this.heading = heading; this.xLocation = x; this.yLocation = y; } public void setHeading(double heading) { this.heading = heading; } public void setXLocation(double xLocation) { this.xLocation = xLocation; } public void setYLocation(double yLocation) { this.yLocation = yLocation; } public double getHeading() { return heading; } public double getXLocation() { return xLocation; } public double getYLocation() { return yLocation; } }
{ "content_hash": "13c7bbd4fca76dd5c656c06320fa7d3f", "timestamp": "", "source": "github", "line_count": 46, "max_line_length": 56, "avg_line_length": 19.130434782608695, "alnum_prop": 0.5954545454545455, "repo_name": "Team3574/RKellyBot", "id": "4ddb6b67fa5669b7d7a8723b3622130a77ea44e7", "size": "880", "binary": false, "copies": "3", "ref": "refs/heads/master", "path": "src/team/util/Location.java", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "Arduino", "bytes": "5920" }, { "name": "Java", "bytes": "92730" } ], "symlink_target": "" }
```sh $ defaults write com.apple.python DisablePythonAlert True ``` ## Prevent system from sleeping Prefix commands with `caffeinate` or `caffeinate -i` to prevent the idle sleep. There are other options to prevent other forms of sleep. ```sh man caffeinate ``` # end: misc.md
{ "content_hash": "d29455c2290115e443b7590772c634fe", "timestamp": "", "source": "github", "line_count": 14, "max_line_length": 79, "avg_line_length": 20.071428571428573, "alnum_prop": 0.7402135231316725, "repo_name": "jpitblado/dotfiles", "id": "60e0af4f988156de7adc580021dbd56987a65ef0", "size": "344", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "Mac/misc.md", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "376" }, { "name": "Shell", "bytes": "29237" }, { "name": "sed", "bytes": "344" } ], "symlink_target": "" }
from __future__ import absolute_import, division, print_function, unicode_literals from azure_common import BaseTest, arm_template class ResourceGroupTest(BaseTest): def setUp(self): super(ResourceGroupTest, self).setUp() def test_resource_group_schema_validate(self): with self.sign_out_patch(): p = self.load_policy({ 'name': 'test-resource-group', 'resource': 'azure.resourcegroup', 'filters': [ {'type': 'empty-group'} ], 'actions': [ {'type': 'delete'} ] }, validate=True) self.assertTrue(p) @arm_template('emptyrg.json') def test_empty_group(self): p = self.load_policy({ 'name': 'test-azure-resource-group', 'resource': 'azure.resourcegroup', 'filters': [ {'type': 'value', 'key': 'name', 'op': 'eq', 'value': 'test_emptyrg'}, {'type': 'empty-group'}]}) resources = p.run() self.assertEqual(len(resources), 1) self.assertEqual(resources[0]['name'], 'test_emptyrg')
{ "content_hash": "c0410346d9bc03928967eeed124252a5", "timestamp": "", "source": "github", "line_count": 37, "max_line_length": 82, "avg_line_length": 33.2972972972973, "alnum_prop": 0.4967532467532468, "repo_name": "ewbankkit/cloud-custodian", "id": "8b8175fc4d21b81b9c68b99ff1e9ec7d58a1718d", "size": "1822", "binary": false, "copies": "3", "ref": "refs/heads/master", "path": "tools/c7n_azure/tests/test_resourcegroup.py", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Dockerfile", "bytes": "7986" }, { "name": "Go", "bytes": "145643" }, { "name": "HTML", "bytes": "31" }, { "name": "Makefile", "bytes": "9857" }, { "name": "PowerShell", "bytes": "1749" }, { "name": "Python", "bytes": "4913354" }, { "name": "Shell", "bytes": "7277" } ], "symlink_target": "" }
using System; using UnityEngine; using System.Collections.Generic; using DG.Tweening; using Match3Core; // ReSharper disable once CheckNamespace public class BoardRenderer : MonoBehaviour { public delegate void LaserShotHandler(); public static event LaserShotHandler LaserShot; public Pool pool; public float swapAnimationDuration = 0.2f; public float lightningAnimationDuration = 0.5f; public float disappearanceAnimationDuration = 0.3f; public float laserAnimationDuration = 0.5f; public float fallingAnimationDurationByBlock = 0.1f; public float shuffleAnimationDuration = 0.5f; public float creationAnimationDuration = 0.2f; private readonly Dictionary<int, GameObject> blockObjects = new Dictionary<int, GameObject>(); private Match3Game match3Game; private float cellWidth; private float cellHeight; private int rowCount; private int columnCount; private int scoreIncreaseNormalDestruction; private int scoreIncreaseDestructionByBombExplosion; private int scoreIncreaseDestructionByCrossExplosion; private int scoreIncreaseDestructionByLaserBlock; private string scoreIncreaseNormalDestructionString; private string scoreIncreaseDestructionByBombExplosionString; private string scoreIncreaseDestructionByCrossExplosionString; private string scoreIncreaseDestructionByLaserBlockString; public delegate void BlockRemovedHandler(int score); public static event BlockRemovedHandler OnScoreIncreased = delegate { }; public void SetGame(Match3Game game) { match3Game = game; rowCount = game.RowCount; columnCount = game.ColumnCount; } public void Awake() { var boardSettings = GetComponent<BoardSettings>(); cellWidth = boardSettings.cellWidth; cellHeight = boardSettings.cellHeight; scoreIncreaseNormalDestruction = boardSettings.scoreIncreaseNormalDestruction; scoreIncreaseDestructionByBombExplosion = boardSettings.scoreIncreaseDestructionByBombExplosion; scoreIncreaseDestructionByCrossExplosion = boardSettings.scoreIncreaseDestructionByCrossExplosion; scoreIncreaseDestructionByLaserBlock = boardSettings.scoreIncreaseDestructionByLaserBlock; scoreIncreaseNormalDestructionString = Convert.ToString(scoreIncreaseNormalDestruction); scoreIncreaseDestructionByBombExplosionString = Convert.ToString(scoreIncreaseDestructionByBombExplosion); scoreIncreaseDestructionByCrossExplosionString = Convert.ToString(scoreIncreaseDestructionByCrossExplosion); scoreIncreaseDestructionByLaserBlockString = Convert.ToString(scoreIncreaseDestructionByLaserBlock); } public void Render() { for (int row = 0; row < rowCount; row++) { for (int column = 0; column < columnCount; column++) { var block = match3Game[row, column]; if (block.color == BlockColor.Empty) { continue; } var blockObj = GetOrCreateBlockGameObject(block); blockObj.transform.localPosition = GetLocalPosition(row, column); } } } private Vector3 GetLocalPosition(int row, int column) { return new Vector3(column - (columnCount - 1)/2f*cellWidth, (rowCount - 1)/2f*cellHeight - row); } private GameObject GetOrCreateBlockGameObject(Block block) { GameObject blockObj; if (!blockObjects.TryGetValue(block.id, out blockObj)) { blockObj = pool.GetBlock(block.color, block.type); blockObj.SetActive(true); blockObjects.Add(block.id, blockObj); } return blockObj; } private GameObject GetBlockGameObject(Block block) { return GetBlockGameObject(block.id); } private GameObject GetBlockGameObject(int id) { GameObject blockGameObject; blockObjects.TryGetValue(id, out blockGameObject); return blockGameObject; } public Tween AnimateSwap(int row0, int column0, int row1, int column1, bool pingPong) { var block0 = match3Game[row0, column0]; var block1 = match3Game[row1, column1]; var block0Obj = GetBlockGameObject(block0); var block1Obj = GetBlockGameObject(block1); var block0InitialPosition = block0Obj.transform.localPosition; var block1InitialPosition = block1Obj.transform.localPosition; var doMove0 = block0Obj.transform.DOLocalMove(block1InitialPosition, swapAnimationDuration); var doMove1 = block1Obj.transform.DOLocalMove(block0InitialPosition, swapAnimationDuration); Sequence sequence = DOTween.Sequence(); sequence.InsertAtBegin(doMove0).InsertAtBegin(doMove1); if (pingPong) { var doMove0Reverse = block0Obj.transform.DOLocalMove(block0InitialPosition, swapAnimationDuration); var doMove1Reverse = block1Obj.transform.DOLocalMove(block1InitialPosition, swapAnimationDuration); Sequence reverseAnimation = DOTween.Sequence(); reverseAnimation.InsertAtBegin(doMove0Reverse); reverseAnimation.InsertAtBegin(doMove1Reverse); sequence.Append(reverseAnimation); } return sequence; } public Tween AnimateRemoval(List<SpecialBlockActivation> blockActivations, List<BlockRemoval> removeBlocks) { Sequence removalSequence = DOTween.Sequence(); Vector3 laserStartPosition = new Vector3(); for (int i = 0; i < blockActivations.Count; i++) { var blockActiviation = blockActivations[i]; if (blockActiviation.type == BlockType.Mega) { laserStartPosition = GetLocalPosition(blockActiviation.row, blockActiviation.column); var sequence = DOTween.Sequence().OnStart(() => { if (LaserShot != null) { LaserShot(); } }); removalSequence.InsertAtBegin(sequence); } else if (blockActiviation.type == BlockType.Bomb) { var sequence = DOTween.Sequence().OnStart(() => { var explosionObj = pool.GetExplosion(); explosionObj.SetActive(true); explosionObj.transform.localPosition = GetLocalPosition(blockActiviation.row, blockActiviation.column); var animator = explosionObj.GetComponent<Animator>(); animator.Play("Explosion"); }); removalSequence.InsertAtBegin(sequence); } else if (blockActiviation.type == BlockType.Cross) { var temp = DOTween.Sequence().OnStart(() => { var localPosition = GetLocalPosition(blockActiviation.row, blockActiviation.column); var verticalLightning = pool.GetLightning(); verticalLightning.SetActive(true); verticalLightning.transform.localPosition = new Vector3(localPosition.x, 0, 0); verticalLightning.GetComponent<LightningController>().StartAnimation(lightningAnimationDuration); var horizontalLightning = pool.GetLightning(); horizontalLightning.SetActive(true); horizontalLightning.transform.rotation = Quaternion.Euler(0, 0, 90); horizontalLightning.transform.localPosition = new Vector3(0, localPosition.y, 0); horizontalLightning.GetComponent<LightningController>().StartAnimation(lightningAnimationDuration); }); removalSequence.InsertAtBegin(temp); } } for (int i = 0; i < removeBlocks.Count; i++) { var removedBlock = removeBlocks[i]; if (removedBlock.block.type != BlockType.Normal) { Debug.Log("Remove type: " + removedBlock.block.type + " position: " + removedBlock.destinationRow + "," + removedBlock.destinationColumn + " reason: " + removedBlock.removalReason); } var blockGameObject = GetBlockGameObject(removedBlock.block); if (blockGameObject == null) { continue; } blockObjects.Remove(removedBlock.block.id); switch (removedBlock.removalReason) { case BlockRemovalReason.DestroyedByMatching: { var scaleTween = CreateDisappearanceTween(blockGameObject, scoreIncreaseNormalDestructionString); OnScoreIncreased(scoreIncreaseNormalDestruction); removalSequence.InsertAtBegin(scaleTween); break; } case BlockRemovalReason.DestroyedByBombExplosion: { var scaleTween = CreateDisappearanceTween(blockGameObject, scoreIncreaseDestructionByBombExplosionString); OnScoreIncreased(scoreIncreaseDestructionByBombExplosion); removalSequence.InsertAtBegin(scaleTween); break; } case BlockRemovalReason.DestroyedByCrossExplosion: { var scaleTween = CreateDisappearanceTween(blockGameObject, scoreIncreaseDestructionByCrossExplosionString); OnScoreIncreased(scoreIncreaseDestructionByCrossExplosion); removalSequence.InsertAtBegin(scaleTween); break; } case BlockRemovalReason.DestroyedByLaserBurst: { var scaleTween = blockGameObject.transform.DOScale(Vector3.zero, disappearanceAnimationDuration).OnComplete(() => { blockGameObject.SetActive(false); blockGameObject.transform.localScale = Vector3.one; }).OnStart(() => { var laser = pool.GetLaser(); laser.SetActive(true); laser.GetComponent<LaserController>().Draw(laserStartPosition, blockGameObject.transform.localPosition, laserAnimationDuration); }).OnComplete(() => { var textPopup = pool.GetTextPopup(); textPopup.SetActive(true); textPopup.GetComponent<PopupController>().ShowPopup(blockGameObject.transform.localPosition, scoreIncreaseDestructionByLaserBlockString); OnScoreIncreased(scoreIncreaseDestructionByLaserBlock); }); removalSequence.InsertAtBegin(scaleTween); break; } } } return removalSequence; } private Tweener CreateDisappearanceTween(GameObject blockGameObject, string scoreText) { var scaleTween = blockGameObject.transform.DOScale(Vector3.zero, disappearanceAnimationDuration).OnComplete(() => { blockGameObject.SetActive(false); blockGameObject.transform.localScale = Vector3.one; var textPopup = pool.GetTextPopup(); textPopup.SetActive(true); textPopup.GetComponent<PopupController>().ShowPopup(blockGameObject.transform.localPosition, scoreText); }); return scaleTween; } public Tween AnimateFalling(List<BlockAndMovement> activeBlocks) { Sequence fallingSequence = DOTween.Sequence(); foreach (var activeBlock in activeBlocks) { var blockObj = GetOrCreateBlockGameObject(activeBlock.block); blockObj.transform.localPosition = GetLocalPosition(activeBlock.initialRow, activeBlock.initialColumn); var moveTween = blockObj.transform.DOLocalMove(GetLocalPosition(activeBlock.destionationRow, activeBlock.initialColumn), fallingAnimationDurationByBlock*(activeBlock.destionationRow - activeBlock.initialRow)); moveTween.SetEase(Ease.InQuad); fallingSequence.InsertAtBegin(moveTween); } return fallingSequence; } public Tween AnimateShuffle() { Sequence shufflingSequence = DOTween.Sequence(); for (int row = 0; row < match3Game.RowCount; row++) { for (int column = 0; column < match3Game.ColumnCount; column++) { var block = match3Game[row, column]; if (block.color == BlockColor.Empty) { continue; } var blockObj = GetOrCreateBlockGameObject(block); var moveTween = blockObj.transform.DOLocalMove(GetLocalPosition(row, column), shuffleAnimationDuration); shufflingSequence.InsertAtBegin(moveTween); } } return shufflingSequence; } public void AnimateMerging(List<BlockAndPosition> mergedBlocks) { for (int i = 0; i < mergedBlocks.Count; i++) { var blockAndPosition = mergedBlocks[i]; var blockObj = GetOrCreateBlockGameObject(blockAndPosition.block); blockObj.transform.localPosition = GetLocalPosition(blockAndPosition.row, blockAndPosition.column); } } public Tween AnimateCreation(List<BlockAndPosition> createdBlocks) { Sequence creationSequence = DOTween.Sequence(); for (int i = 0; i < createdBlocks.Count; i++) { var blockAndPosition = createdBlocks[i]; var blockObj = GetOrCreateBlockGameObject(blockAndPosition.block); blockObj.transform.localPosition = GetLocalPosition(blockAndPosition.row, blockAndPosition.column); blockObj.transform.localScale = Vector3.zero; var tween = blockObj.transform.DOScale(Vector3.one, creationAnimationDuration); creationSequence.InsertAtBegin(tween); } return creationSequence; } }
{ "content_hash": "825be63cd4d3329cb2bdd778077e6528", "timestamp": "", "source": "github", "line_count": 333, "max_line_length": 168, "avg_line_length": 42.885885885885884, "alnum_prop": 0.6354597017015615, "repo_name": "alexander-mironov/UnityMatch3Sample", "id": "5b50c40c835ec1582be3463d605de3143c5a43b5", "size": "14283", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "Assets/Scripts/BoardRenderer.cs", "mode": "33188", "license": "mit", "language": [ { "name": "C#", "bytes": "99092" }, { "name": "GLSL", "bytes": "2037" } ], "symlink_target": "" }
/* * Created: Nov 8, 2011 * By: kmurdoff */ /** * */ package com.livescribe.aws.tokensvc.exception; /** * <p></p> * * @author <a href="mailto:[email protected]">Kevin F. Murdoff</a> * @version 1.0 */ public class LSDSClientException extends Exception { /** * <p></p> * */ public LSDSClientException() { } /** * <p></p> * * @param message */ public LSDSClientException(String message) { super(message); } /** * <p></p> * * @param cause */ public LSDSClientException(Throwable cause) { super(cause); } /** * <p></p> * * @param message * @param cause */ public LSDSClientException(String message, Throwable cause) { super(message, cause); } }
{ "content_hash": "9d5f4e260de8ade48c08b4693ac009bd", "timestamp": "", "source": "github", "line_count": 53, "max_line_length": 72, "avg_line_length": 13.679245283018869, "alnum_prop": 0.5779310344827586, "repo_name": "jackstraw66/web", "id": "c89795197654eb3166eac852cd4d95d95dd330d5", "size": "725", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "livescribe/lstokenservice/src/main/java/com/livescribe/aws/tokensvc/exception/LSDSClientException.java", "mode": "33188", "license": "bsd-2-clause", "language": [ { "name": "CSS", "bytes": "12519" }, { "name": "FreeMarker", "bytes": "586195" }, { "name": "HTML", "bytes": "8445" }, { "name": "Java", "bytes": "3072798" }, { "name": "JavaScript", "bytes": "6722" }, { "name": "Shell", "bytes": "16332" } ], "symlink_target": "" }
package digitalocean import ( "context" doCapi "pharmer.dev/pharmer/apis/v1alpha1/digitalocean" "github.com/go-logr/logr" "k8s.io/client-go/tools/record" "k8s.io/klog/klogr" "k8s.io/kubernetes/cmd/kubeadm/app/apis/kubeadm/v1beta1" clusterapi "sigs.k8s.io/cluster-api/pkg/apis/cluster/v1alpha1" "sigs.k8s.io/cluster-api/pkg/controller/cluster" "sigs.k8s.io/controller-runtime/pkg/client" "sigs.k8s.io/controller-runtime/pkg/manager" ) func init() { // AddToManagerFuncs is a list of functions to create controllers and add them to a manager. AddToManagerFuncs = append(AddToManagerFuncs, func(cm *ClusterManager, m manager.Manager) error { actuator := NewClusterActuator(m, ClusterActuatorParams{ EventRecorder: m.GetEventRecorderFor(Recorder), cm: cm, }) return cluster.AddWithActuator(m, actuator) }) } type ClusterActuator struct { client client.Client eventRecorder record.EventRecorder cm *ClusterManager logr.Logger } type ClusterActuatorParams struct { EventRecorder record.EventRecorder cm *ClusterManager } func NewClusterActuator(m manager.Manager, params ClusterActuatorParams) *ClusterActuator { params.cm.Logger = params.cm.Logger.WithName("[cluster-actuator]") return &ClusterActuator{ client: m.GetClient(), eventRecorder: params.EventRecorder, cm: params.cm, Logger: klogr.New().WithName("[cluster-actuator]"). WithValues("cluster-name", params.cm.Cluster.Name), } } func (ca *ClusterActuator) Reconcile(cluster *clusterapi.Cluster) error { log := ca.Logger log.Info("Reconciling cluster") lb, err := ca.cm.conn.lbByName(context.Background(), ca.cm.conn.namer.LoadBalancerName()) if err == errLBNotFound { lb, err = ca.cm.conn.createLoadBalancer(context.Background(), ca.cm.conn.namer.LoadBalancerName()) if err != nil { log.Error(err, "error creating load balancer") return err } log.Info("created load balancer", "lb-name", ca.cm.conn.namer.LoadBalancerName()) cluster.Status.APIEndpoints = []clusterapi.APIEndpoint{ { Host: lb.IP, Port: v1beta1.DefaultAPIBindPort, }, } } else if err != nil { log.Error(err, "error finding load balancer") return err } updated := ca.cm.conn.loadBalancerUpdated(lb) if updated { log.Info("Load balancer specs changed, updating lb") defaultSpecs := ca.cm.conn.buildLoadBalancerRequest(ca.cm.conn.namer.LoadBalancerName()) lb, _, err = ca.cm.conn.client.LoadBalancers.Update(context.Background(), lb.ID, defaultSpecs) if err != nil { log.Error(err, "Error updating load balancer") return err } } status, err := doCapi.ClusterStatusFromProviderStatus(cluster.Status.ProviderStatus) if err != nil { log.Error(err, "Error getting provider status") return err } status.APIServerLB = doCapi.DescribeLoadBalancer(lb) if err := ca.updateClusterStatus(cluster, status); err != nil { log.Error(err, "Error updating cluster status for cluster") return err } log.Info("Reconciled cluster successfully") return nil } func (ca *ClusterActuator) Delete(cluster *clusterapi.Cluster) error { ca.Logger.Info("Delete cluster not implemented") return nil } func (ca *ClusterActuator) updateClusterStatus(cluster *clusterapi.Cluster, status *doCapi.DigitalOceanClusterProviderStatus) error { raw, err := doCapi.EncodeClusterStatus(status) if err != nil { ca.Logger.Error(err, "Error encoding cluster status") return err } cluster.Status.ProviderStatus = raw return ca.client.Status().Update(context.Background(), cluster) }
{ "content_hash": "fbe5de99019ee1e2d738946da36af9c7", "timestamp": "", "source": "github", "line_count": 123, "max_line_length": 133, "avg_line_length": 28.991869918699187, "alnum_prop": 0.730790802019069, "repo_name": "appscode/pharmer", "id": "4bddffe017b2acb4d927de4eaa39a8c529fdfb1b", "size": "4127", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "cloud/providers/digitalocean/cluster_actuator.go", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Go", "bytes": "1067743" }, { "name": "Makefile", "bytes": "6149" }, { "name": "Python", "bytes": "31934" }, { "name": "Ruby", "bytes": "295" }, { "name": "Shell", "bytes": "31683" } ], "symlink_target": "" }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. // Code generated by Microsoft (R) AutoRest Code Generator. package com.azure.resourcemanager.monitor.models; import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonValue; /** the type of action that should occur when the scale rule fires. */ public enum ScaleType { /** Enum value ChangeCount. */ CHANGE_COUNT("ChangeCount"), /** Enum value PercentChangeCount. */ PERCENT_CHANGE_COUNT("PercentChangeCount"), /** Enum value ExactCount. */ EXACT_COUNT("ExactCount"), /** Enum value ServiceAllowedNextValue. */ SERVICE_ALLOWED_NEXT_VALUE("ServiceAllowedNextValue"); /** The actual serialized value for a ScaleType instance. */ private final String value; ScaleType(String value) { this.value = value; } /** * Parses a serialized value to a ScaleType instance. * * @param value the serialized value to parse. * @return the parsed ScaleType object, or null if unable to parse. */ @JsonCreator public static ScaleType fromString(String value) { if (value == null) { return null; } ScaleType[] items = ScaleType.values(); for (ScaleType item : items) { if (item.toString().equalsIgnoreCase(value)) { return item; } } return null; } /** {@inheritDoc} */ @JsonValue @Override public String toString() { return this.value; } }
{ "content_hash": "1cb8c50bfdb5ce754935c361c54c2864", "timestamp": "", "source": "github", "line_count": 57, "max_line_length": 71, "avg_line_length": 27.912280701754387, "alnum_prop": 0.6379635449402892, "repo_name": "Azure/azure-sdk-for-java", "id": "eb63d766a2f3a28ebaefff63d655fe59e6681f45", "size": "1591", "binary": false, "copies": "1", "ref": "refs/heads/main", "path": "sdk/resourcemanager/azure-resourcemanager-monitor/src/main/java/com/azure/resourcemanager/monitor/models/ScaleType.java", "mode": "33188", "license": "mit", "language": [ { "name": "Batchfile", "bytes": "8762" }, { "name": "Bicep", "bytes": "15055" }, { "name": "CSS", "bytes": "7676" }, { "name": "Dockerfile", "bytes": "2028" }, { "name": "Groovy", "bytes": "3237482" }, { "name": "HTML", "bytes": "42090" }, { "name": "Java", "bytes": "432409546" }, { "name": "JavaScript", "bytes": "36557" }, { "name": "Jupyter Notebook", "bytes": "95868" }, { "name": "PowerShell", "bytes": "737517" }, { "name": "Python", "bytes": "240542" }, { "name": "Scala", "bytes": "1143898" }, { "name": "Shell", "bytes": "18488" }, { "name": "XSLT", "bytes": "755" } ], "symlink_target": "" }
module Apigee class API module Oauth2 # Get count of Access Tokens def access_token_count get("/oauth2/accesstokens") end # Approve an Access Token def approve_access_token(token) get("/oauth2/accesstokens/#{token}?action=approve") end # Revoke an Access Token def revoke_access_token(token) post("/oauth2/accesstokens/#{token}?action=revoke") end # Get an Access Token def access_token(token) get("/oauth2/accesstokens/#{token}") end # Delete an Access Token def delete_access_token(token) delete("/oauth2/accesstokens/#{token}") end # Delete an Access Token and return true/false on success/failure def delete_access_token!(token) request(:delete, "/oauth2/accesstokens/#{token}", {}, true).status == 200 end # Update Access Token def update_access_token(token, params) put("/oauth2/accesstokens/#{token}", params) end # List Authorization Codes def auth_codes get("/oauth2/authorizationcodes") end # Get Authorization Code def auth_code(token) get("/oauth2/authorizationcodes/#{token}") end # Delete Authorization Code def delete_auth_code(token) delete("/oauth2/authorizationcodes/#{token}") end end end end
{ "content_hash": "1604e44d1db62d12812079a717006b32", "timestamp": "", "source": "github", "line_count": 57, "max_line_length": 81, "avg_line_length": 24.473684210526315, "alnum_prop": 0.6100358422939068, "repo_name": "tradier/apigee", "id": "d90eb3775733eeaeaec164a9e093e0925ee8756a", "size": "1395", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "lib/apigee/api/oauth2.rb", "mode": "33188", "license": "mit", "language": [ { "name": "Ruby", "bytes": "44807" } ], "symlink_target": "" }
algorithm in java study algorithms 4, and do practice
{ "content_hash": "96e8d20bcf13414854f8e0444e481bee", "timestamp": "", "source": "github", "line_count": 3, "max_line_length": 35, "avg_line_length": 18, "alnum_prop": 0.8148148148148148, "repo_name": "jt120/algorithm", "id": "e896ac06ad3e41d643711fdcbadd097f3c937a4f", "size": "66", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "README.md", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "1067775" } ], "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_60-ea) on Wed Jan 04 17:08:16 EST 2017 --> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>org.wildfly.swarm.cdi.config.deployment Class Hierarchy (Public javadocs 2017.1.1 API)</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="org.wildfly.swarm.cdi.config.deployment Class Hierarchy (Public javadocs 2017.1.1 API)"; } } catch(err) { } //--> </script> <noscript> <div>JavaScript is disabled on your browser.</div> </noscript> <!-- ========= START OF TOP NAVBAR ======= --> <div class="topNav"><a name="navbar.top"> <!-- --> </a> <div class="skipNav"><a href="#skip.navbar.top" title="Skip navigation links">Skip navigation links</a></div> <a name="navbar.top.firstrow"> <!-- --> </a> <ul class="navList" title="Navigation"> <li><a href="../../../../../../overview-summary.html">Overview</a></li> <li><a href="package-summary.html">Package</a></li> <li>Class</li> <li>Use</li> <li class="navBarCell1Rev">Tree</li> <li><a href="../../../../../../deprecated-list.html">Deprecated</a></li> <li><a href="../../../../../../index-all.html">Index</a></li> <li><a href="../../../../../../help-doc.html">Help</a></li> </ul> <div class="aboutLanguage">WildFly Swarm API, 2017.1.1</div> </div> <div class="subNav"> <ul class="navList"> <li><a href="../../../../../../org/wildfly/swarm/cdi/config/package-tree.html">Prev</a></li> <li><a href="../../../../../../org/wildfly/swarm/cdi/jaxrsapi/package-tree.html">Next</a></li> </ul> <ul class="navList"> <li><a href="../../../../../../index.html?org/wildfly/swarm/cdi/config/deployment/package-tree.html" target="_top">Frames</a></li> <li><a href="package-tree.html" target="_top">No&nbsp;Frames</a></li> </ul> <ul class="navList" id="allclasses_navbar_top"> <li><a href="../../../../../../allclasses-noframe.html">All&nbsp;Classes</a></li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_top"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } //--> </script> </div> <a name="skip.navbar.top"> <!-- --> </a></div> <!-- ========= END OF TOP NAVBAR ========= --> <div class="header"> <h1 class="title">Hierarchy For Package org.wildfly.swarm.cdi.config.deployment</h1> <span class="packageHierarchyLabel">Package Hierarchies:</span> <ul class="horizontal"> <li><a href="../../../../../../overview-tree.html">All Packages</a></li> </ul> </div> <div class="contentContainer"> <h2 title="Class Hierarchy">Class Hierarchy</h2> <ul> <li type="circle">java.lang.<a href="http://docs.oracle.com/javase/8/docs/api/java/lang/Object.html?is-external=true" title="class or interface in java.lang"><span class="typeNameLink">Object</span></a> <ul> <li type="circle">org.wildfly.swarm.cdi.config.deployment.<a href="../../../../../../org/wildfly/swarm/cdi/config/deployment/InjectStageConfigExtension.html" title="class in org.wildfly.swarm.cdi.config.deployment"><span class="typeNameLink">InjectStageConfigExtension</span></a></li> <li type="circle">org.wildfly.swarm.cdi.config.deployment.<a href="../../../../../../org/wildfly/swarm/cdi/config/deployment/StageConfigBean.html" title="class in org.wildfly.swarm.cdi.config.deployment"><span class="typeNameLink">StageConfigBean</span></a></li> </ul> </li> </ul> </div> <!-- ======= START OF BOTTOM NAVBAR ====== --> <div class="bottomNav"><a name="navbar.bottom"> <!-- --> </a> <div class="skipNav"><a href="#skip.navbar.bottom" title="Skip navigation links">Skip navigation links</a></div> <a name="navbar.bottom.firstrow"> <!-- --> </a> <ul class="navList" title="Navigation"> <li><a href="../../../../../../overview-summary.html">Overview</a></li> <li><a href="package-summary.html">Package</a></li> <li>Class</li> <li>Use</li> <li class="navBarCell1Rev">Tree</li> <li><a href="../../../../../../deprecated-list.html">Deprecated</a></li> <li><a href="../../../../../../index-all.html">Index</a></li> <li><a href="../../../../../../help-doc.html">Help</a></li> </ul> <div class="aboutLanguage">WildFly Swarm API, 2017.1.1</div> </div> <div class="subNav"> <ul class="navList"> <li><a href="../../../../../../org/wildfly/swarm/cdi/config/package-tree.html">Prev</a></li> <li><a href="../../../../../../org/wildfly/swarm/cdi/jaxrsapi/package-tree.html">Next</a></li> </ul> <ul class="navList"> <li><a href="../../../../../../index.html?org/wildfly/swarm/cdi/config/deployment/package-tree.html" target="_top">Frames</a></li> <li><a href="package-tree.html" target="_top">No&nbsp;Frames</a></li> </ul> <ul class="navList" id="allclasses_navbar_bottom"> <li><a href="../../../../../../allclasses-noframe.html">All&nbsp;Classes</a></li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_bottom"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } //--> </script> </div> <a name="skip.navbar.bottom"> <!-- --> </a></div> <!-- ======== END OF BOTTOM NAVBAR ======= --> <p class="legalCopy"><small>Copyright &#169; 2017 <a href="http://www.jboss.org">JBoss by Red Hat</a>. All rights reserved.</small></p> </body> </html>
{ "content_hash": "446fb8b712d6d223fe5f7947d9e29fbd", "timestamp": "", "source": "github", "line_count": 142, "max_line_length": 284, "avg_line_length": 40.33098591549296, "alnum_prop": 0.6245852977125895, "repo_name": "wildfly-swarm/wildfly-swarm-javadocs", "id": "843806ab936361e7ba0e47e6a6ebdb38f8db7ea4", "size": "5727", "binary": false, "copies": "1", "ref": "refs/heads/gh-pages", "path": "2017.1.1/apidocs/org/wildfly/swarm/cdi/config/deployment/package-tree.html", "mode": "33188", "license": "apache-2.0", "language": [], "symlink_target": "" }
<form [formGroup]="formGroup"> <ul class="list-group list-group-flush"> <li *ngFor="let item of this.meta" class="list-group-item"> <ng-container [ngSwitch]="item.type"> <div form-text-input *ngSwitchCase="'text'" [meta]="item" [form]="formGroup" style="width:100%;"> </div> <div form-long-text-input *ngSwitchCase="'longText'" [meta]="item" [form]="formGroup" style="width:100%;"> </div> <div form-checkbox-input *ngSwitchCase="'checkbox'" [meta]="item" [form]="formGroup" style="width:100%;"> </div> <div form-single-selection-input *ngSwitchCase="'singleSelection'" [meta]="item" [form]="formGroup" style="width:100%;"> </div> </ng-container> </li> </ul> </form>
{ "content_hash": "88235c0a861a866d2bb2540007e847e9", "timestamp": "", "source": "github", "line_count": 12, "max_line_length": 143, "avg_line_length": 64.75, "alnum_prop": 0.5842985842985843, "repo_name": "junkerm/specmate", "id": "3099653303e312de418f54569d9cbcd96e21112e", "size": "777", "binary": false, "copies": "1", "ref": "refs/heads/develop", "path": "web/src/app/modules/forms/modules/generic-form/components/generic-form.component.html", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "7101" }, { "name": "Dockerfile", "bytes": "854" }, { "name": "GAP", "bytes": "254786" }, { "name": "HTML", "bytes": "83420" }, { "name": "Java", "bytes": "5874840" }, { "name": "Python", "bytes": "74602" }, { "name": "Ruby", "bytes": "17086" }, { "name": "TypeScript", "bytes": "559148" }, { "name": "Xtend", "bytes": "7445" } ], "symlink_target": "" }
// source: package nl.esciencecenter.xnattool; import java.util.ArrayList; import java.util.List; import nl.esciencecenter.medim.ImageDirScanner; import nl.esciencecenter.medim.ScanSetInfo; import nl.esciencecenter.medim.ScanSetInfo.FileDescriptor; import nl.esciencecenter.medim.StudyInfo; import nl.esciencecenter.medim.SubjectInfo; import nl.esciencecenter.ptk.csv.CSVData; public class MetaDataWriter { private ImageDirScanner imageSource; private DBMapping dbMapping; private CSVData csvData; public MetaDataWriter(ImageDirScanner imageSource, DBMapping mappings) { this.imageSource = imageSource; this.dbMapping = mappings; } public CSVData toCSV() throws Exception { this.csvData = new CSVData(true); switch (imageSource.getDataSetType()) { case DICOM_SCANSET: return createDicomCSV(csvData); case NIFTI_SCANSET: return createNiftiCSV(csvData); case NIFTI_ATLASSET: return createNiftiAtlasCSV(csvData); } throw new Exception("Couldn't determine DataSetType:" + imageSource.getDataSetType()); } protected CSVData createDicomCSV(CSVData csvData) throws Exception { List<String> scanSetKeys = dbMapping.getAllScanSetKeys(); // [CSV HEADER] String headers[] = new String[] { "subject.label", "session.label", "dicom.patient.id", "dicom.patient.name", "dicom.patient.gender", "dicom.patient.ageString", "dicom.patient.birthdate", "dicom.study.id", "dicom.study.uid", "dicom.study.date", "dicom.scan.description" // "dicom.scan.description" }; csvData.setHeaders(headers); for (String scanSetKey : scanSetKeys) { ScanSetInfo scanSet = imageSource.getScanSet(scanSetKey); assertNotNull(scanSet, "ScanSet not found:" + scanSetKey); String sessionKey = dbMapping.getSessionKeyOfScanSetKey(scanSetKey); assertNotNull(sessionKey, "Could not find SesionKey of ScanSet:" + scanSetKey); String subjectKey = dbMapping.getSubjectKeyOfSessionKey(sessionKey); assertNotNull(subjectKey, "Could not find SubjectKey of Session:" + scanSetKey); // Subject: String subjectLabel = dbMapping.getXnatSubjectLabel(subjectKey); assertNotNull(subjectLabel, "Could not find SubjectLabel of Subject:" + subjectKey); // Session/Study StudyInfo studyInfo = scanSet.getStudyInfo(); assertNotNull(scanSet, "Could not find SessionKey of ScanSet:" + scanSetKey); String sessionLabel = dbMapping.getXnatSessionLabel(subjectKey, sessionKey); assertNotNull(sessionLabel, "Could not find SessionLabel of Subject:" + subjectKey); SubjectInfo subjInfo = scanSet.getSubjectInfo(); // [ CSV Entry ] String row[] = new String[headers.length]; int index = 0; row[index++] = subjectLabel; row[index++] = sessionLabel; row[index++] = subjInfo.getPatientID(); row[index++] = subjInfo.getPatientName(); row[index++] = subjInfo.getPatientGender(); row[index++] = subjInfo.getPatientAgeString(); row[index++] = csvData.toCSVDateString(subjInfo.getPatientBirthDate()); row[index++] = studyInfo.getStudyId(); row[index++] = studyInfo.getStudyInstanceUID(); row[index++] = csvData.toCSVDateString(studyInfo.getStudyDate()); // Srow[10]=scanSet.getScanUID(); row[index++] = scanSet.getSeriesDescription(); csvData.addRow(row); } return csvData; } protected CSVData createNiftiCSV(CSVData csvData) throws Exception { List<String> scanSetKeys = dbMapping.getAllScanSetKeys(); // [CSV HEADER] String headers[] = new String[] { "subject.label", "session.label", "nifti.subject.id", "nifti.session.id", // "nifti.scan.uid", "nifti.scan.id" }; csvData.setHeaders(headers); for (String scanSetKey : scanSetKeys) { ScanSetInfo scanSet = imageSource.getScanSet(scanSetKey); assertNotNull(scanSet, "ScanSet not found:" + scanSetKey); String sessionKey = dbMapping.getSessionKeyOfScanSetKey(scanSetKey); assertNotNull(sessionKey, "Could not find SesionKey of ScanSet:" + scanSetKey); String subjectKey = dbMapping.getSubjectKeyOfSessionKey(sessionKey); assertNotNull(subjectKey, "Could not find SubjectKey of Session:" + scanSetKey); // Subject: String subjectLabel = dbMapping.getXnatSubjectLabel(subjectKey); assertNotNull(subjectLabel, "Could not find SubjectLabel of Subject:" + subjectKey); // Session/Study StudyInfo studyInfo = scanSet.getStudyInfo(); assertNotNull(scanSet, "Could not find SessionKey of ScanSet:" + scanSetKey); String sessionLabel = dbMapping.getXnatSessionLabel(subjectKey, sessionKey); assertNotNull(sessionLabel, "Could not find SessionLabel of Subject:" + subjectKey); SubjectInfo subjInfo = scanSet.getSubjectInfo(); // [ CSV Entry ] String row[] = new String[headers.length]; int index = 0; row[index++] = subjectLabel; row[index++] = sessionLabel; row[index++] = subjInfo.getPatientID(); row[index++] = studyInfo.getStudyId(); // row[index++]=scanSet.getScanUID(); row[index++] = scanSet.getScanLabel(); csvData.addRow(row); } return csvData; } protected CSVData createNiftiAtlasCSV(CSVData csvData) throws Exception { List<String> scanSetKeys = dbMapping.getAllScanSetKeys(); // [CSV HEADER] String headers[] = new String[] { "subject.label", "session.label", "nifti.subject.id", "nifti.session.id", "nifti.scan.id", "atlas.label" }; csvData.setHeaders(headers); for (String scanSetKey : scanSetKeys) { ScanSetInfo scanSet = imageSource.getScanSet(scanSetKey); assertNotNull(scanSet, "ScanSet not found:" + scanSetKey); String sessionKey = dbMapping.getSessionKeyOfScanSetKey(scanSetKey); assertNotNull(sessionKey, "Could not find SesionKey of ScanSet:" + scanSetKey); String subjectKey = dbMapping.getSubjectKeyOfSessionKey(sessionKey); assertNotNull(subjectKey, "Could not find SubjectKey of Session:" + scanSetKey); // Subject: String subjectLabel = dbMapping.getXnatSubjectLabel(subjectKey); assertNotNull(subjectLabel, "Could not find SubjectLabel of Subject:" + subjectKey); // Session/Study StudyInfo studyInfo = scanSet.getStudyInfo(); assertNotNull(scanSet, "Could not find SessionKey of ScanSet:" + scanSetKey); String sessionLabel = dbMapping.getXnatSessionLabel(subjectKey, sessionKey); assertNotNull(sessionLabel, "Could not find SessionLabel of Subject:" + subjectKey); SubjectInfo subjInfo = scanSet.getSubjectInfo(); ArrayList<FileDescriptor> files = scanSet.getFileDescriptors(); for (int i = 0; i < files.size(); i++) { // [ CSV Entry ] String row[] = new String[headers.length]; int index = 0; row[index++] = subjectLabel; row[index++] = sessionLabel; row[index++] = subjInfo.getPatientID(); row[index++] = studyInfo.getStudyId(); // row[index++]=scanSet.getScanUID(); row[index++] = scanSet.getScanLabel(); row[index++] = files.get(i).fileLabel; csvData.addRow(row); } } return csvData; } public StringBuilder toCSV(StringBuilder sb) throws Exception { CSVData data = toCSV(); data.toString(sb, ";", "\n"); return sb; } private void assertNotNull(Object value, String message) throws Exception { if (value == null) throw new Exception(message); } }
{ "content_hash": "cbf92fbdb83ff44a45b60ee3c02361e3", "timestamp": "", "source": "github", "line_count": 245, "max_line_length": 96, "avg_line_length": 35.71836734693878, "alnum_prop": 0.5966175294252085, "repo_name": "NLeSC/escxnat", "id": "a005d2aa6b9dd1b4f6dd8061976d2668a16698ac", "size": "9496", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "nl.esciencecenter.xnattool/src/nl/esciencecenter/xnattool/MetaDataWriter.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Batchfile", "bytes": "114" }, { "name": "Java", "bytes": "821141" }, { "name": "Shell", "bytes": "2564" } ], "symlink_target": "" }
struct Particle { Particle(); void update(sf::RenderTexture& window); void draw(sf::RenderTexture& window); std::array<sf::Vertex, 2> getLine(); sf::Vertex current; sf::Vertex previous; sf::Vector2f velocity; sf::Vector2f acceleration; };
{ "content_hash": "614b8a551ac275fdbfa8563e35582658", "timestamp": "", "source": "github", "line_count": 13, "max_line_length": 43, "avg_line_length": 21, "alnum_prop": 0.6483516483516484, "repo_name": "bikefrivolously/perlin-noise-art", "id": "65a8cc9780ebc03d461996c927dddd15f5cafa38", "size": "339", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "particle.h", "mode": "33188", "license": "mit", "language": [ { "name": "C++", "bytes": "13783" }, { "name": "Makefile", "bytes": "705" } ], "symlink_target": "" }
<?php /** * InvoiceItems class * * @package activeCollab.modules.invoicing * @subpackage models */ class InvoiceItems extends BaseInvoiceItems { /** * Return items by invoice * * @param Invoice $invoice * @return array */ function findByInvoice($invoice) { return InvoiceItems::find(array( 'conditions' => array('invoice_id = ?', $invoice->getId()), 'order' => 'position' )); } // findByInvoice /** * Return number of items that user $rate tax rate * * @param TaxRate $tax_rate * @return integer */ function countByTaxRate($tax_rate) { return InvoiceItems::count(array('tax_rate_id = ?', $tax_rate->getId())); } // countByTaxRate /** * Delete all items for a invoice * * @param Invoice $invoice * @return null */ function deleteByInvoice($invoice) { db_begin_work(); $execute = db_execute('DELETE FROM ' . TABLE_PREFIX . 'invoice_time_records WHERE invoice_id = ?', $invoice->getId()); if ($execute && !is_error($execute)) { $delete = InvoiceItems::delete(array('invoice_id = ?', $invoice->getId())); if ($delete && !is_error($delete)) { db_commit(); } else { db_rollback(); } // if return $delete; } else { db_rollback(); return $execute; } // if } // deleteByInvoice } // class ?>
{ "content_hash": "89810da2d26851cac3ff2c8650908799", "timestamp": "", "source": "github", "line_count": 59, "max_line_length": 124, "avg_line_length": 24.915254237288135, "alnum_prop": 0.5408163265306123, "repo_name": "hammadalinaqvi/bookstoregenie", "id": "76553f2bb50dfcf38ff8230ce8a05bd53e98bd91", "size": "1470", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "projMan/activecollab/application/modules/invoicing/models/invoice_items/InvoiceItems.class.php", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "C", "bytes": "7164" }, { "name": "CSS", "bytes": "1707795" }, { "name": "Frege", "bytes": "285235" }, { "name": "JavaScript", "bytes": "4892721" }, { "name": "PHP", "bytes": "34467676" }, { "name": "Perl", "bytes": "121014" }, { "name": "Python", "bytes": "10525" }, { "name": "Ruby", "bytes": "294210" }, { "name": "SQL", "bytes": "2429" }, { "name": "Shell", "bytes": "1458" } ], "symlink_target": "" }
.. _`bootstrap api`: =================================== API Bootstrap =================================== .. automodule:: crispy_forms.bootstrap :members:
{ "content_hash": "f8762837caec1deba900554a5daa1586", "timestamp": "", "source": "github", "line_count": 9, "max_line_length": 38, "avg_line_length": 18, "alnum_prop": 0.3765432098765432, "repo_name": "django-crispy-forms/django-crispy-forms", "id": "3bea596f60cb015af336677b18e90c92e282a1c5", "size": "162", "binary": false, "copies": "1", "ref": "refs/heads/main", "path": "docs/api_bootstrap.rst", "mode": "33188", "license": "mit", "language": [ { "name": "HTML", "bytes": "151107" }, { "name": "Makefile", "bytes": "179" }, { "name": "Python", "bytes": "235674" } ], "symlink_target": "" }
module Tincanz class ConversationPolicy def initialize(user, conversation) @user = user @conversation = conversation end def can_read? if @user.can_manage_tincanz? true else Conversation.involving(@user).where(id: @conversation.id).count > 0 end end def can_reply? can_read? end end end
{ "content_hash": "c44fb4b7a5b841b70ef107280f365996", "timestamp": "", "source": "github", "line_count": 20, "max_line_length": 75, "avg_line_length": 18.4, "alnum_prop": 0.6114130434782609, "repo_name": "robodisco/tincanz", "id": "2c2419a66cd00e3a1f8f0b8d72e9e31f918d6a86", "size": "368", "binary": false, "copies": "2", "ref": "refs/heads/develop", "path": "app/policies/tincanz/conversation_policy.rb", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "3081" }, { "name": "HTML", "bytes": "12485" }, { "name": "JavaScript", "bytes": "1639" }, { "name": "Ruby", "bytes": "80747" } ], "symlink_target": "" }
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with this * work for additional information regarding copyright ownership. The ASF * licenses this file to You under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. * * INCLUDES MODIFICATIONS BY GOOGLE. */ /** author Elena Semukhina */ package com.google.j2cl.jre.java.math; import com.google.j2cl.jre.java.util.EmulTestBase; import java.math.BigInteger; /** * Class: java.math.BigInteger Method: add. */ public class BigIntegerAddTest extends EmulTestBase { /** * Add two positive numbers of the same length. */ public void testCase1() { byte aBytes[] = {1, 2, 3, 4, 5, 6, 7, 1, 2, 3}; byte bBytes[] = {10, 20, 30, 40, 50, 60, 70, 10, 20, 30}; int aSign = 1; int bSign = 1; byte rBytes[] = {11, 22, 33, 44, 55, 66, 77, 11, 22, 33}; BigInteger aNumber = new BigInteger(aSign, aBytes); BigInteger bNumber = new BigInteger(bSign, bBytes); BigInteger result = aNumber.add(bNumber); byte resBytes[] = new byte[rBytes.length]; resBytes = result.toByteArray(); for (int i = 0; i < resBytes.length; i++) { assertTrue(resBytes[i] == rBytes[i]); } assertEquals("incorrect sign", 1, result.signum()); } /** * Add two negative numbers of the same length. */ public void testCase2() { byte aBytes[] = {1, 2, 3, 4, 5, 6, 7, 1, 2, 3}; byte bBytes[] = {10, 20, 30, 40, 50, 60, 70, 10, 20, 30}; int aSign = -1; int bSign = -1; byte rBytes[] = {-12, -23, -34, -45, -56, -67, -78, -12, -23, -33}; BigInteger aNumber = new BigInteger(aSign, aBytes); BigInteger bNumber = new BigInteger(bSign, bBytes); BigInteger result = aNumber.add(bNumber); byte resBytes[] = new byte[rBytes.length]; resBytes = result.toByteArray(); for (int i = 0; i < resBytes.length; i++) { assertTrue(resBytes[i] == rBytes[i]); } assertEquals("incorrect sign", -1, result.signum()); } /** * Add two numbers of the same length. The first one is positive and the * second is negative. The first one is greater in absolute value. */ public void testCase3() { byte aBytes[] = {3, 4, 5, 6, 7, 8, 9}; byte bBytes[] = {1, 2, 3, 4, 5, 6, 7}; byte rBytes[] = {2, 2, 2, 2, 2, 2, 2}; int aSign = 1; int bSign = -1; BigInteger aNumber = new BigInteger(aSign, aBytes); BigInteger bNumber = new BigInteger(bSign, bBytes); BigInteger result = aNumber.add(bNumber); byte resBytes[] = new byte[rBytes.length]; resBytes = result.toByteArray(); for (int i = 0; i < resBytes.length; i++) { assertTrue(resBytes[i] == rBytes[i]); } assertEquals("incorrect sign", 1, result.signum()); } /** * Add two numbers of the same length. The first one is negative and the * second is positive. The first one is greater in absolute value. */ public void testCase4() { byte aBytes[] = {3, 4, 5, 6, 7, 8, 9}; byte bBytes[] = {1, 2, 3, 4, 5, 6, 7}; byte rBytes[] = {-3, -3, -3, -3, -3, -3, -2}; int aSign = -1; int bSign = 1; BigInteger aNumber = new BigInteger(aSign, aBytes); BigInteger bNumber = new BigInteger(bSign, bBytes); BigInteger result = aNumber.add(bNumber); byte resBytes[] = new byte[rBytes.length]; resBytes = result.toByteArray(); for (int i = 0; i < resBytes.length; i++) { assertTrue(resBytes[i] == rBytes[i]); } assertEquals("incorrect sign", -1, result.signum()); } /** * Add two numbers of the same length. The first is positive and the second is * negative. The first is less in absolute value. */ public void testCase5() { byte aBytes[] = {1, 2, 3, 4, 5, 6, 7}; byte bBytes[] = {3, 4, 5, 6, 7, 8, 9}; byte rBytes[] = {-3, -3, -3, -3, -3, -3, -2}; int aSign = 1; int bSign = -1; BigInteger aNumber = new BigInteger(aSign, aBytes); BigInteger bNumber = new BigInteger(bSign, bBytes); BigInteger result = aNumber.add(bNumber); byte resBytes[] = new byte[rBytes.length]; resBytes = result.toByteArray(); for (int i = 0; i < resBytes.length; i++) { assertTrue(resBytes[i] == rBytes[i]); } assertEquals("incorrect sign", -1, result.signum()); } /** * Add two numbers of the same length. The first one is negative and the * second is positive. The first one is less in absolute value. */ public void testCase6() { byte aBytes[] = {1, 2, 3, 4, 5, 6, 7}; byte bBytes[] = {3, 4, 5, 6, 7, 8, 9}; byte rBytes[] = {2, 2, 2, 2, 2, 2, 2}; int aSign = -1; int bSign = 1; BigInteger aNumber = new BigInteger(aSign, aBytes); BigInteger bNumber = new BigInteger(bSign, bBytes); BigInteger result = aNumber.add(bNumber); byte resBytes[] = new byte[rBytes.length]; resBytes = result.toByteArray(); for (int i = 0; i < resBytes.length; i++) { assertTrue(resBytes[i] == rBytes[i]); } assertEquals("incorrect sign", 1, result.signum()); } /** * Add two positive numbers of different length. The first is longer. */ public void testCase7() { byte aBytes[] = {1, 2, 3, 4, 5, 6, 7, 1, 2, 3, 4, 5, 6, 7}; byte bBytes[] = {10, 20, 30, 40, 50, 60, 70, 10, 20, 30}; int aSign = 1; int bSign = 1; byte rBytes[] = {1, 2, 3, 4, 15, 26, 37, 41, 52, 63, 74, 15, 26, 37}; BigInteger aNumber = new BigInteger(aSign, aBytes); BigInteger bNumber = new BigInteger(bSign, bBytes); BigInteger result = aNumber.add(bNumber); byte resBytes[] = new byte[rBytes.length]; resBytes = result.toByteArray(); for (int i = 0; i < resBytes.length; i++) { assertTrue(resBytes[i] == rBytes[i]); } assertEquals("incorrect sign", 1, result.signum()); } /** * Add two positive numbers of different length. The second is longer. */ public void testCase8() { byte aBytes[] = {10, 20, 30, 40, 50, 60, 70, 10, 20, 30}; byte bBytes[] = {1, 2, 3, 4, 5, 6, 7, 1, 2, 3, 4, 5, 6, 7}; byte rBytes[] = {1, 2, 3, 4, 15, 26, 37, 41, 52, 63, 74, 15, 26, 37}; BigInteger aNumber = new BigInteger(aBytes); BigInteger bNumber = new BigInteger(bBytes); BigInteger result = aNumber.add(bNumber); byte resBytes[] = new byte[rBytes.length]; resBytes = result.toByteArray(); for (int i = 0; i < resBytes.length; i++) { assertTrue(resBytes[i] == rBytes[i]); } assertEquals("incorrect sign", 1, result.signum()); } /** * Add two negative numbers of different length. The first is longer. */ public void testCase9() { byte aBytes[] = {1, 2, 3, 4, 5, 6, 7, 1, 2, 3, 4, 5, 6, 7}; byte bBytes[] = {10, 20, 30, 40, 50, 60, 70, 10, 20, 30}; int aSign = -1; int bSign = -1; byte rBytes[] = { -2, -3, -4, -5, -16, -27, -38, -42, -53, -64, -75, -16, -27, -37}; BigInteger aNumber = new BigInteger(aSign, aBytes); BigInteger bNumber = new BigInteger(bSign, bBytes); BigInteger result = aNumber.add(bNumber); byte resBytes[] = new byte[rBytes.length]; resBytes = result.toByteArray(); for (int i = 0; i < resBytes.length; i++) { assertTrue(resBytes[i] == rBytes[i]); } assertEquals("incorrect sign", -1, result.signum()); } /** * Add two negative numbers of different length. The second is longer. */ public void testCase10() { byte aBytes[] = {10, 20, 30, 40, 50, 60, 70, 10, 20, 30}; byte bBytes[] = {1, 2, 3, 4, 5, 6, 7, 1, 2, 3, 4, 5, 6, 7}; int aSign = -1; int bSign = -1; byte rBytes[] = { -2, -3, -4, -5, -16, -27, -38, -42, -53, -64, -75, -16, -27, -37}; BigInteger aNumber = new BigInteger(aSign, aBytes); BigInteger bNumber = new BigInteger(bSign, bBytes); BigInteger result = aNumber.add(bNumber); byte resBytes[] = new byte[rBytes.length]; resBytes = result.toByteArray(); for (int i = 0; i < resBytes.length; i++) { assertTrue(resBytes[i] == rBytes[i]); } assertEquals("incorrect sign", -1, result.signum()); } /** * Add two numbers of different length and sign. The first is positive. The * first is longer. */ public void testCase11() { byte aBytes[] = {1, 2, 3, 4, 5, 6, 7, 1, 2, 3, 4, 5, 6, 7}; byte bBytes[] = {10, 20, 30, 40, 50, 60, 70, 10, 20, 30}; int aSign = 1; int bSign = -1; byte rBytes[] = {1, 2, 3, 3, -6, -15, -24, -40, -49, -58, -67, -6, -15, -23}; BigInteger aNumber = new BigInteger(aSign, aBytes); BigInteger bNumber = new BigInteger(bSign, bBytes); BigInteger result = aNumber.add(bNumber); byte resBytes[] = new byte[rBytes.length]; resBytes = result.toByteArray(); for (int i = 0; i < resBytes.length; i++) { assertTrue(resBytes[i] == rBytes[i]); } assertEquals("incorrect sign", 1, result.signum()); } /** * Add two numbers of different length and sign. The first is positive. The * second is longer. */ public void testCase12() { byte aBytes[] = {10, 20, 30, 40, 50, 60, 70, 10, 20, 30}; byte bBytes[] = {1, 2, 3, 4, 5, 6, 7, 1, 2, 3, 4, 5, 6, 7}; int aSign = 1; int bSign = -1; byte rBytes[] = {-2, -3, -4, -4, 5, 14, 23, 39, 48, 57, 66, 5, 14, 23}; BigInteger aNumber = new BigInteger(aSign, aBytes); BigInteger bNumber = new BigInteger(bSign, bBytes); BigInteger result = aNumber.add(bNumber); byte resBytes[] = new byte[rBytes.length]; resBytes = result.toByteArray(); for (int i = 0; i < resBytes.length; i++) { assertTrue(resBytes[i] == rBytes[i]); } assertEquals("incorrect sign", -1, result.signum()); } /** * Add two numbers of different length and sign. The first is negative. The * first is longer. */ public void testCase13() { byte aBytes[] = {1, 2, 3, 4, 5, 6, 7, 1, 2, 3, 4, 5, 6, 7}; byte bBytes[] = {10, 20, 30, 40, 50, 60, 70, 10, 20, 30}; int aSign = -1; int bSign = 1; byte rBytes[] = {-2, -3, -4, -4, 5, 14, 23, 39, 48, 57, 66, 5, 14, 23}; BigInteger aNumber = new BigInteger(aSign, aBytes); BigInteger bNumber = new BigInteger(bSign, bBytes); BigInteger result = aNumber.add(bNumber); byte resBytes[] = new byte[rBytes.length]; resBytes = result.toByteArray(); for (int i = 0; i < resBytes.length; i++) { assertTrue(resBytes[i] == rBytes[i]); } assertEquals("incorrect sign", -1, result.signum()); } /** * Add two numbers of different length and sign. The first is negative. The * second is longer. */ public void testCase14() { byte aBytes[] = {10, 20, 30, 40, 50, 60, 70, 10, 20, 30}; byte bBytes[] = {1, 2, 3, 4, 5, 6, 7, 1, 2, 3, 4, 5, 6, 7}; int aSign = -1; int bSign = 1; byte rBytes[] = {1, 2, 3, 3, -6, -15, -24, -40, -49, -58, -67, -6, -15, -23}; BigInteger aNumber = new BigInteger(aSign, aBytes); BigInteger bNumber = new BigInteger(bSign, bBytes); BigInteger result = aNumber.add(bNumber); byte resBytes[] = new byte[rBytes.length]; resBytes = result.toByteArray(); for (int i = 0; i < resBytes.length; i++) { assertTrue(resBytes[i] == rBytes[i]); } assertEquals("incorrect sign", 1, result.signum()); } /** * Add two equal numbers of different signs. */ public void testCase15() { byte aBytes[] = {1, 2, 3, 4, 5, 6, 7}; byte bBytes[] = {1, 2, 3, 4, 5, 6, 7}; byte rBytes[] = {0}; int aSign = -1; int bSign = 1; BigInteger aNumber = new BigInteger(aSign, aBytes); BigInteger bNumber = new BigInteger(bSign, bBytes); BigInteger result = aNumber.add(bNumber); byte resBytes[] = new byte[rBytes.length]; for (int i = 0; i < resBytes.length; i++) { assertTrue(resBytes[i] == rBytes[i]); } assertEquals("incorrect sign", 0, result.signum()); } /** * Add zero to a number. */ public void testCase16() { byte aBytes[] = {1, 2, 3, 4, 5, 6, 7}; byte bBytes[] = {0}; byte rBytes[] = {1, 2, 3, 4, 5, 6, 7}; int aSign = 1; int bSign = 1; BigInteger aNumber = new BigInteger(aSign, aBytes); BigInteger bNumber = new BigInteger(bSign, bBytes); BigInteger result = aNumber.add(bNumber); byte resBytes[] = new byte[rBytes.length]; resBytes = result.toByteArray(); for (int i = 0; i < resBytes.length; i++) { assertTrue(resBytes[i] == rBytes[i]); } assertEquals("incorrect sign", 1, result.signum()); } /** * Add a number to zero. */ public void testCase17() { byte aBytes[] = {0}; byte bBytes[] = {1, 2, 3, 4, 5, 6, 7}; byte rBytes[] = {1, 2, 3, 4, 5, 6, 7}; int aSign = 1; int bSign = 1; BigInteger aNumber = new BigInteger(aSign, aBytes); BigInteger bNumber = new BigInteger(bSign, bBytes); BigInteger result = aNumber.add(bNumber); byte resBytes[] = new byte[rBytes.length]; resBytes = result.toByteArray(); for (int i = 0; i < resBytes.length; i++) { assertTrue(resBytes[i] == rBytes[i]); } assertEquals("incorrect sign", 1, result.signum()); } /** * Add zero to zero. */ public void testCase18() { byte aBytes[] = {0}; byte bBytes[] = {0}; byte rBytes[] = {0}; int aSign = 1; int bSign = 1; BigInteger aNumber = new BigInteger(aSign, aBytes); BigInteger bNumber = new BigInteger(bSign, bBytes); BigInteger result = aNumber.add(bNumber); byte resBytes[] = new byte[rBytes.length]; resBytes = result.toByteArray(); for (int i = 0; i < resBytes.length; i++) { assertTrue(resBytes[i] == rBytes[i]); } assertEquals("incorrect sign", 0, result.signum()); } /** * Add ZERO to a number. */ public void testCase19() { byte aBytes[] = {1, 2, 3, 4, 5, 6, 7}; byte rBytes[] = {1, 2, 3, 4, 5, 6, 7}; int aSign = 1; BigInteger aNumber = new BigInteger(aSign, aBytes); BigInteger bNumber = BigInteger.ZERO; BigInteger result = aNumber.add(bNumber); byte resBytes[] = new byte[rBytes.length]; resBytes = result.toByteArray(); for (int i = 0; i < resBytes.length; i++) { assertTrue(resBytes[i] == rBytes[i]); } assertEquals("incorrect sign", 1, result.signum()); } /** * Add a number to zero. */ public void testCase20() { byte bBytes[] = {1, 2, 3, 4, 5, 6, 7}; byte rBytes[] = {1, 2, 3, 4, 5, 6, 7}; int bSign = 1; BigInteger aNumber = BigInteger.ZERO; BigInteger bNumber = new BigInteger(bSign, bBytes); BigInteger result = aNumber.add(bNumber); byte resBytes[] = new byte[rBytes.length]; resBytes = result.toByteArray(); for (int i = 0; i < resBytes.length; i++) { assertTrue(resBytes[i] == rBytes[i]); } assertEquals("incorrect sign", 1, result.signum()); } /** * Add ZERO to ZERO. */ public void testCase21() { byte rBytes[] = {0}; BigInteger aNumber = BigInteger.ZERO; BigInteger bNumber = BigInteger.ZERO; BigInteger result = aNumber.add(bNumber); byte resBytes[] = new byte[rBytes.length]; resBytes = result.toByteArray(); for (int i = 0; i < resBytes.length; i++) { assertTrue(resBytes[i] == rBytes[i]); } assertEquals("incorrect sign", 0, result.signum()); } /** * Add ONE to ONE. */ public void testCase22() { byte rBytes[] = {2}; BigInteger aNumber = BigInteger.ONE; BigInteger bNumber = BigInteger.ONE; BigInteger result = aNumber.add(bNumber); byte resBytes[] = new byte[rBytes.length]; resBytes = result.toByteArray(); for (int i = 0; i < resBytes.length; i++) { assertTrue(resBytes[i] == rBytes[i]); } assertEquals("incorrect sign", 1, result.signum()); } /** * Add two numbers so that carry is 1. */ public void testCase23() { byte aBytes[] = {-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}; byte bBytes[] = {-1, -1, -1, -1, -1, -1, -1, -1}; int aSign = 1; int bSign = 1; byte rBytes[] = {1, 0, 0, 0, 0, 0, 0, -1, -1, -1, -1, -1, -1, -1, -2}; BigInteger aNumber = new BigInteger(aSign, aBytes); BigInteger bNumber = new BigInteger(bSign, bBytes); BigInteger result = aNumber.add(bNumber); byte resBytes[] = new byte[rBytes.length]; resBytes = result.toByteArray(); for (int i = 0; i < resBytes.length; i++) { assertTrue(resBytes[i] == rBytes[i]); } assertEquals("incorrect sign", 1, result.signum()); } }
{ "content_hash": "1edabf9272e2d4a623d792c3893f7240", "timestamp": "", "source": "github", "line_count": 486, "max_line_length": 81, "avg_line_length": 34.718106995884774, "alnum_prop": 0.5938481597819001, "repo_name": "google/j2cl", "id": "d0ef5279664851dc8c4f95e96e60cc553f7a5836", "size": "17463", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "jre/javatests/com/google/j2cl/jre/java/math/BigIntegerAddTest.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "9170080" }, { "name": "JavaScript", "bytes": "133627" }, { "name": "Kotlin", "bytes": "152617" }, { "name": "Python", "bytes": "29340" }, { "name": "Shell", "bytes": "7548" }, { "name": "Starlark", "bytes": "352448" } ], "symlink_target": "" }
<template name="search"> <input type="search" name="search-box" id="main-search" placeholder="Type to search..."> </template>
{ "content_hash": "9ca219e27bdc18005636c7a3d6c6c348", "timestamp": "", "source": "github", "line_count": 3, "max_line_length": 92, "avg_line_length": 43, "alnum_prop": 0.689922480620155, "repo_name": "nicoTrygub/meteor-contact-book", "id": "a9201b954d53b7b51bf25efae802a89b3bfe5837", "size": "129", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "client/views/search/search.html", "mode": "33188", "license": "mit", "language": [ { "name": "JavaScript", "bytes": "13013" } ], "symlink_target": "" }
package org.eclipse.californium.core.network; import java.io.IOException; import java.net.InetAddress; import java.net.NetworkInterface; import java.net.SocketException; import java.util.Collection; import java.util.Enumeration; import java.util.LinkedList; import java.util.logging.Level; import java.util.logging.Logger; import org.eclipse.californium.core.CoapServer; import org.eclipse.californium.core.coap.Request; import org.eclipse.californium.core.coap.Response; import org.eclipse.californium.core.server.MessageDeliverer; /** * A factory for {@link Endpoint}s that can be used by clients for sending * outbound CoAP requests. * * The EndpointManager contains the default endpoint for coap (on port 5683) and * coaps (CoAP over DTLS). When an application serves only as client but not * server it can just use the default endpoint to send requests. When the * application sends a request by calling {@link Request#send()} the send method * sends itself over the default endpoint. * <p> * To make a server listen for requests on the default endpoint, call * <pre>{@code * CoapServer server = new CoapServer(); * }</pre> * or more explicit * <pre>{@code * Endpoint endpoint = EndpointManager.getEndpointManager().getDefaultEndpoint(); * CoapServer server = new CoapServer(); * server.addEndpoint(endpoint); * }</pre> */ public class EndpointManager { /** The logger */ private final static Logger LOGGER = Logger.getLogger(EndpointManager.class.getCanonicalName()); /** The singleton manager instance */ private static EndpointManager manager = new EndpointManager(); /** * Gets the singleton manager. * * @return the endpoint manager */ public static EndpointManager getEndpointManager() { return manager; } /** The default endpoint for CoAP */ private Endpoint default_endpoint; /** The default endpoint for secure CoAP */ private Endpoint default_secure_endpoint; /** * Gets the default endpoint for implicit use by clients. By default, the * endpoint has a single-threaded executor and is started. It is possible to * send requests over the endpoint and receive responses. It is not possible * to receive requests by default. If a request arrives at the endpoint, the * {@link ClientMessageDeliverer} rejects it. To receive requests, the * endpoint must be added to an instance of {@link CoapServer}. Be careful with * stopping or destroying the default endpoint as it affects all messages * that are supposed to be sent over it. * * @return the default endpoint */ public Endpoint getDefaultEndpoint() { if (default_endpoint == null) { createDefaultEndpoint(); } return default_endpoint; } /* * Creates an endpoint with the wildcard adress (::0) and an ephemeral port. * The new endpoint gets a client message deliverer and is started. * To listen on specific interfaces or ports, set the default endpoint manually. * To distinguish different interfaces, one endpoint per interface must be added. */ private synchronized void createDefaultEndpoint() { if (default_endpoint != null) return; default_endpoint = new CoapEndpoint(); try { default_endpoint.start(); LOGGER.log(Level.INFO, "Created implicit default endpoint " + default_endpoint.getAddress()); } catch (IOException e) { LOGGER.log(Level.SEVERE, "Could not create default endpoint", e); } } /** * Configures a new default endpoint. Any old default endpoint is destroyed. * @param endpoint the new default endpoint */ public void setDefaultEndpoint(Endpoint endpoint) { if (this.default_endpoint!=null) { this.default_endpoint.destroy(); } LOGGER.config(endpoint.getAddress()+" becomes default endpoint"); this.default_endpoint = endpoint; if (!this.default_endpoint.isStarted()) { try { default_endpoint.start(); } catch (IOException e) { LOGGER.log(Level.SEVERE, "Could not start new default endpoint", e); } } } /** * Gets the default endpoint for coaps for implicit use by clients. * By default, the endpoint has a single-threaded executor and is started. * It is possible to send requests over the endpoint and receive responses. * It is not possible to receive requests by default. If a request arrives * at the endpoint, the {@link ClientMessageDeliverer} rejects it. To * receive requests, the endpoint must be added to an instance of * {@link CoapServer}. Be careful with stopping or destroying the default * endpoint as it affects all messages that are supposed to be sent over it. * * @return the default endpoint */ public Endpoint getDefaultSecureEndpoint() { try { if (default_secure_endpoint == null) { createDefaultSecureEndpoint(); } } catch (Exception e) { LOGGER.log(Level.SEVERE, "Exception while getting the default secure endpoint", e); } return default_secure_endpoint; } private synchronized void createDefaultSecureEndpoint() { if (default_secure_endpoint != null) return; LOGGER.config("Secure endpoint must be injected via setDefaultSecureEndpoint()"); } /** * Configures a new default secure endpoint. Any old default endpoint is destroyed. * @param endpoint the new default endpoint */ public void setDefaultSecureEndpoint(Endpoint endpoint) { if (this.default_secure_endpoint!=null) { this.default_secure_endpoint.destroy(); } this.default_secure_endpoint = endpoint; if (!this.default_secure_endpoint.isStarted()) { try { default_secure_endpoint.start(); LOGGER.log(Level.INFO, "Started new default secure endpoint " + default_secure_endpoint.getAddress()); } catch (IOException e) { LOGGER.log(Level.SEVERE, "Could not start new default secure endpoint", e); } } } public Collection<InetAddress> getNetworkInterfaces() { Collection<InetAddress> interfaces = new LinkedList<InetAddress>(); try { Enumeration<NetworkInterface> nets = NetworkInterface.getNetworkInterfaces(); while (nets.hasMoreElements()) { Enumeration<InetAddress> inetAddresses = nets.nextElement().getInetAddresses(); while (inetAddresses.hasMoreElements()) { interfaces.add(inetAddresses.nextElement()); } } } catch (SocketException e) { LOGGER.log(Level.SEVERE, "Could not fetch all interface addresses", e); } return interfaces; } // Needed for JUnit Tests to remove state for deduplication /** * Clear the state for deduplication in both default endpoints. */ public static void clear() { EndpointManager it = getEndpointManager(); if (it.default_endpoint != null) it.default_endpoint.clear(); if (it.default_secure_endpoint != null) it.default_secure_endpoint.clear(); } /** * ClientMessageDeliverer is a simple implementation of the interface * {@link MessageDeliverer}. When a response arrives it adds it to the * corresponding request. If requests arrive, however, the * ClientMessageDeliverer rejects them. */ public static class ClientMessageDeliverer implements MessageDeliverer { /* (non-Javadoc) * @see ch.inf.vs.californium.MessageDeliverer#deliverRequest(ch.inf.vs.californium.network.Exchange) */ @Override public void deliverRequest(Exchange exchange) { LOGGER.severe("Default endpoint without CoapServer has received a request."); exchange.sendReject(); } /* (non-Javadoc) * @see ch.inf.vs.californium.MessageDeliverer#deliverResponse(ch.inf.vs.californium.network.Exchange, ch.inf.vs.californium.coap.Response) */ @Override public void deliverResponse(Exchange exchange, Response response) { if (exchange == null) throw new NullPointerException(); if (exchange.getRequest() == null) throw new NullPointerException(); if (response == null) throw new NullPointerException(); exchange.getRequest().setResponse(response); } } }
{ "content_hash": "cf90ac9cc7a119aad14aafb91bb0578b", "timestamp": "", "source": "github", "line_count": 231, "max_line_length": 141, "avg_line_length": 33.98701298701299, "alnum_prop": 0.7298433320596103, "repo_name": "iotoasis/SI", "id": "6290b75bd0397b5035bddc0dabcd44a54bcb88f8", "size": "9048", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "si-onem2m-src/IITP_IoT_2_7/src/extlib/java/org/eclipse/californium/core/network/EndpointManager.java", "mode": "33188", "license": "bsd-2-clause", "language": [ { "name": "CSS", "bytes": "231568" }, { "name": "HTML", "bytes": "43861" }, { "name": "Java", "bytes": "7148552" }, { "name": "JavaScript", "bytes": "1336196" } ], "symlink_target": "" }
layout: post title: Text Revealer git: https://github.com/jamigibbs/text-revealer-js site: https://jamigibbs.github.io/text-revealer-js/ --- Text Revealer is a browser script to assist in revealing deeper information about highlighted text on a page. When text is selected or highlighted, a popover displays useful details about the text such as Wikipedia entires and dictionary definition. Available as a standalone script or Chrome Extension. Built using Vanilla Javascript.
{ "content_hash": "dfb0e2316ac754c31e81ee41efaef789", "timestamp": "", "source": "github", "line_count": 9, "max_line_length": 303, "avg_line_length": 53.22222222222222, "alnum_prop": 0.8079331941544885, "repo_name": "jamigibbs/portfolio", "id": "fd81194eaf6af4ade727e14a3895b4fe8f8f8c20", "size": "483", "binary": false, "copies": "1", "ref": "refs/heads/gh-pages", "path": "_posts/2020-02-02-text-revealer.md", "mode": "33188", "license": "mit", "language": [ { "name": "HTML", "bytes": "6197" }, { "name": "Ruby", "bytes": "49" }, { "name": "SCSS", "bytes": "13172" } ], "symlink_target": "" }
package org.arquillian.cube.istio.impl; import io.fabric8.kubernetes.api.model.v4_0.ObjectMeta; import java.io.InputStream; import java.util.Arrays; import me.snowdrop.istio.api.IstioResource; import me.snowdrop.istio.client.IstioClient; import org.arquillian.cube.istio.api.RestoreIstioResource; import org.jboss.arquillian.test.spi.event.suite.AfterClass; import org.jboss.arquillian.test.spi.event.suite.BeforeClass; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mock; import org.mockito.runners.MockitoJUnitRunner; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Matchers.any; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; @RunWith(MockitoJUnitRunner.class) public class IstioResourcesApplierTest { @Mock private IstioClient istioClient; @Mock private IstioResource istioResource; @Mock private IstioResource istioResource2; @Mock private ObjectMeta meta; @Mock private ObjectMeta meta2; @Test public void should_apply_tests_with_istio_resources() { // Given final BeforeClass beforeClass = new BeforeClass(TestWithIstioResource.class); final IstioResourcesApplier istioResourceApplier = createIstioResourceApplier(); when(istioClient.registerCustomResources(any(InputStream.class))) .thenReturn(Arrays.asList(istioResource)); // When istioResourceApplier.applyIstioResourcesAtClassScope(beforeClass, istioClient); // Then verify(istioClient, times(1)).registerCustomResources(any(InputStream.class)); assertThat(istioResourceApplier.getResourcesMap()) .hasSize(1) .containsValue(Arrays.asList(istioResource)); assertThat(istioResourceApplier.getRestoredResourcesMap()) .hasSize(0); } @Test public void should_apply_tests_with_istio_resources_and_restore() { // Given final BeforeClass beforeClass = new BeforeClass(TestWithIstioResourceAndRestore.class); final IstioResourcesApplier istioResourceApplier = createIstioResourceApplier(); when(istioClient.registerCustomResources(any(InputStream.class))) .thenReturn(Arrays.asList(istioResource)); // When istioResourceApplier.applyIstioResourcesAtClassScope(beforeClass, istioClient); // Then verify(istioClient, times(1)).registerCustomResources(any(InputStream.class)); assertThat(istioResourceApplier.getResourcesMap()) .hasSize(1) .containsValue(Arrays.asList(istioResource)); assertThat(istioResourceApplier.getRestoredResourcesMap()) .hasSize(0); } @Test public void should_delete_registered_istio_resources() { // Given final BeforeClass beforeClass = new BeforeClass(TestWithIstioResource.class); final IstioResourcesApplier istioResourceApplier = createIstioResourceApplier(); when(istioClient.registerCustomResources(any(InputStream.class))) .thenReturn(Arrays.asList(istioResource)); istioResourceApplier.applyIstioResourcesAtClassScope(beforeClass, istioClient); // When istioResourceApplier.removeIstioResourcesAtClassScope(new AfterClass(TestWithIstioResource.class), istioClient); // Then verify(istioClient, times(1)).unregisterCustomResource(istioResource); } @Test public void should_delete_registered_istio_resources_and_restore() { // Given final BeforeClass beforeClass = new BeforeClass(TestWithIstioResourceAndRestore.class); final IstioResourcesApplier istioResourceApplier = createIstioResourceApplier(); when(istioClient.registerCustomResources(any(InputStream.class))) .thenReturn(Arrays.asList(istioResource)); istioResourceApplier.applyIstioResourcesAtClassScope(beforeClass, istioClient); // When istioResourceApplier.removeIstioResourcesAtClassScope(new AfterClass(TestWithIstioResourceAndRestore.class), istioClient); // Then verify(istioClient, times(2)).registerCustomResources(any(InputStream.class)); verify(istioClient, times(0)).unregisterCustomResource(istioResource); } @Test public void should_delete_registered_istio_resources_and_not_restore_if_resource_is_different() { // Given final BeforeClass beforeClass = new BeforeClass(TestWithIstioResourceAndRestore.class); final IstioResourcesApplier istioResourceApplier = createIstioResourceApplier(); when(istioClient.registerCustomResources(any(InputStream.class))) .thenReturn(Arrays.asList(istioResource), Arrays.asList(istioResource2)); istioResourceApplier.applyIstioResourcesAtClassScope(beforeClass, istioClient); // When istioResourceApplier.removeIstioResourcesAtClassScope(new AfterClass(TestWithIstioResourceAndRestore.class), istioClient); // Then verify(istioClient, times(2)).registerCustomResources(any(InputStream.class)); verify(istioClient, times(1)).unregisterCustomResource(istioResource); } private IstioResourcesApplier createIstioResourceApplier() { when(istioResource.getMetadata()).thenReturn(meta); when(meta.getName()).thenReturn("recommendation"); when(meta.getNamespace()).thenReturn("tutorial"); when(istioResource2.getMetadata()).thenReturn(meta2); when(meta2.getName()).thenReturn("different"); when(meta2.getNamespace()).thenReturn("tutorial"); when(istioClient.registerCustomResources(any(InputStream.class))) .thenReturn(Arrays.asList(istioResource), Arrays.asList(istioResource2)); return new IstioResourcesApplier(); } @org.arquillian.cube.istio.api.IstioResource("classpath:virtual-service.yml") class TestWithIstioResource { } @org.arquillian.cube.istio.api.IstioResource("classpath:virtual-service.yml") @RestoreIstioResource("classpath:virtual-service.yml") class TestWithIstioResourceAndRestore { } }
{ "content_hash": "3b016decf244dd997ebd34e44d862c8e", "timestamp": "", "source": "github", "line_count": 170, "max_line_length": 130, "avg_line_length": 36.53529411764706, "alnum_prop": 0.7328932539043632, "repo_name": "AndyGee/arquillian-cube", "id": "2a2db131438eff7118bf8f1549a699f37f241a2e", "size": "6211", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "kubernetes/istio/istio/src/test/java/org/arquillian/cube/istio/impl/IstioResourcesApplierTest.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Dockerfile", "bytes": "3483" }, { "name": "Groovy", "bytes": "20485" }, { "name": "Java", "bytes": "2151396" }, { "name": "JavaScript", "bytes": "161" }, { "name": "Shell", "bytes": "8859" } ], "symlink_target": "" }
package mysql // Code generated by xo. DO NOT EDIT. import ( "context" "database/sql" ) // Employee represents a row from 'northwind.employees'. type Employee struct { EmployeeID int16 `json:"employee_id"` // employee_id LastName string `json:"last_name"` // last_name FirstName string `json:"first_name"` // first_name Title sql.NullString `json:"title"` // title TitleOfCourtesy sql.NullString `json:"title_of_courtesy"` // title_of_courtesy BirthDate sql.NullTime `json:"birth_date"` // birth_date HireDate sql.NullTime `json:"hire_date"` // hire_date Address sql.NullString `json:"address"` // address City sql.NullString `json:"city"` // city Region sql.NullString `json:"region"` // region PostalCode sql.NullString `json:"postal_code"` // postal_code Country sql.NullString `json:"country"` // country HomePhone sql.NullString `json:"home_phone"` // home_phone Extension sql.NullString `json:"extension"` // extension Photo []byte `json:"photo"` // photo Notes sql.NullString `json:"notes"` // notes ReportsTo sql.NullInt64 `json:"reports_to"` // reports_to PhotoPath sql.NullString `json:"photo_path"` // photo_path // xo fields _exists, _deleted bool } // Exists returns true when the Employee exists in the database. func (e *Employee) Exists() bool { return e._exists } // Deleted returns true when the Employee has been marked for deletion from // the database. func (e *Employee) Deleted() bool { return e._deleted } // Insert inserts the Employee to the database. func (e *Employee) Insert(ctx context.Context, db DB) error { switch { case e._exists: // already exists return logerror(&ErrInsertFailed{ErrAlreadyExists}) case e._deleted: // deleted return logerror(&ErrInsertFailed{ErrMarkedForDeletion}) } // insert (manual) const sqlstr = `INSERT INTO northwind.employees (` + `employee_id, last_name, first_name, title, title_of_courtesy, birth_date, hire_date, address, city, region, postal_code, country, home_phone, extension, photo, notes, reports_to, photo_path` + `) VALUES (` + `?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?` + `)` // run logf(sqlstr, e.EmployeeID, e.LastName, e.FirstName, e.Title, e.TitleOfCourtesy, e.BirthDate, e.HireDate, e.Address, e.City, e.Region, e.PostalCode, e.Country, e.HomePhone, e.Extension, e.Photo, e.Notes, e.ReportsTo, e.PhotoPath) if _, err := db.ExecContext(ctx, sqlstr, e.EmployeeID, e.LastName, e.FirstName, e.Title, e.TitleOfCourtesy, e.BirthDate, e.HireDate, e.Address, e.City, e.Region, e.PostalCode, e.Country, e.HomePhone, e.Extension, e.Photo, e.Notes, e.ReportsTo, e.PhotoPath); err != nil { return logerror(err) } // set exists e._exists = true return nil } // Update updates a Employee in the database. func (e *Employee) Update(ctx context.Context, db DB) error { switch { case !e._exists: // doesn't exist return logerror(&ErrUpdateFailed{ErrDoesNotExist}) case e._deleted: // deleted return logerror(&ErrUpdateFailed{ErrMarkedForDeletion}) } // update with primary key const sqlstr = `UPDATE northwind.employees SET ` + `last_name = ?, first_name = ?, title = ?, title_of_courtesy = ?, birth_date = ?, hire_date = ?, address = ?, city = ?, region = ?, postal_code = ?, country = ?, home_phone = ?, extension = ?, photo = ?, notes = ?, reports_to = ?, photo_path = ? ` + `WHERE employee_id = ?` // run logf(sqlstr, e.LastName, e.FirstName, e.Title, e.TitleOfCourtesy, e.BirthDate, e.HireDate, e.Address, e.City, e.Region, e.PostalCode, e.Country, e.HomePhone, e.Extension, e.Photo, e.Notes, e.ReportsTo, e.PhotoPath, e.EmployeeID) if _, err := db.ExecContext(ctx, sqlstr, e.LastName, e.FirstName, e.Title, e.TitleOfCourtesy, e.BirthDate, e.HireDate, e.Address, e.City, e.Region, e.PostalCode, e.Country, e.HomePhone, e.Extension, e.Photo, e.Notes, e.ReportsTo, e.PhotoPath, e.EmployeeID); err != nil { return logerror(err) } return nil } // Save saves the Employee to the database. func (e *Employee) Save(ctx context.Context, db DB) error { if e.Exists() { return e.Update(ctx, db) } return e.Insert(ctx, db) } // Upsert performs an upsert for Employee. func (e *Employee) Upsert(ctx context.Context, db DB) error { switch { case e._deleted: // deleted return logerror(&ErrUpsertFailed{ErrMarkedForDeletion}) } // upsert const sqlstr = `INSERT INTO northwind.employees (` + `employee_id, last_name, first_name, title, title_of_courtesy, birth_date, hire_date, address, city, region, postal_code, country, home_phone, extension, photo, notes, reports_to, photo_path` + `) VALUES (` + `?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?` + `)` + ` ON DUPLICATE KEY UPDATE ` + `employee_id = VALUES(employee_id), last_name = VALUES(last_name), first_name = VALUES(first_name), title = VALUES(title), title_of_courtesy = VALUES(title_of_courtesy), birth_date = VALUES(birth_date), hire_date = VALUES(hire_date), address = VALUES(address), city = VALUES(city), region = VALUES(region), postal_code = VALUES(postal_code), country = VALUES(country), home_phone = VALUES(home_phone), extension = VALUES(extension), photo = VALUES(photo), notes = VALUES(notes), reports_to = VALUES(reports_to), photo_path = VALUES(photo_path)` // run logf(sqlstr, e.EmployeeID, e.LastName, e.FirstName, e.Title, e.TitleOfCourtesy, e.BirthDate, e.HireDate, e.Address, e.City, e.Region, e.PostalCode, e.Country, e.HomePhone, e.Extension, e.Photo, e.Notes, e.ReportsTo, e.PhotoPath) if _, err := db.ExecContext(ctx, sqlstr, e.EmployeeID, e.LastName, e.FirstName, e.Title, e.TitleOfCourtesy, e.BirthDate, e.HireDate, e.Address, e.City, e.Region, e.PostalCode, e.Country, e.HomePhone, e.Extension, e.Photo, e.Notes, e.ReportsTo, e.PhotoPath); err != nil { return logerror(err) } // set exists e._exists = true return nil } // Delete deletes the Employee from the database. func (e *Employee) Delete(ctx context.Context, db DB) error { switch { case !e._exists: // doesn't exist return nil case e._deleted: // deleted return nil } // delete with single primary key const sqlstr = `DELETE FROM northwind.employees ` + `WHERE employee_id = ?` // run logf(sqlstr, e.EmployeeID) if _, err := db.ExecContext(ctx, sqlstr, e.EmployeeID); err != nil { return logerror(err) } // set deleted e._deleted = true return nil } // EmployeeByEmployeeID retrieves a row from 'northwind.employees' as a Employee. // // Generated from index 'employees_employee_id_pkey'. func EmployeeByEmployeeID(ctx context.Context, db DB, employeeID int16) (*Employee, error) { // query const sqlstr = `SELECT ` + `employee_id, last_name, first_name, title, title_of_courtesy, birth_date, hire_date, address, city, region, postal_code, country, home_phone, extension, photo, notes, reports_to, photo_path ` + `FROM northwind.employees ` + `WHERE employee_id = ?` // run logf(sqlstr, employeeID) e := Employee{ _exists: true, } if err := db.QueryRowContext(ctx, sqlstr, employeeID).Scan(&e.EmployeeID, &e.LastName, &e.FirstName, &e.Title, &e.TitleOfCourtesy, &e.BirthDate, &e.HireDate, &e.Address, &e.City, &e.Region, &e.PostalCode, &e.Country, &e.HomePhone, &e.Extension, &e.Photo, &e.Notes, &e.ReportsTo, &e.PhotoPath); err != nil { return nil, logerror(err) } return &e, nil } // EmployeesByReportsTo retrieves a row from 'northwind.employees' as a Employee. // // Generated from index 'reports_to'. func EmployeesByReportsTo(ctx context.Context, db DB, reportsTo sql.NullInt64) ([]*Employee, error) { // query const sqlstr = `SELECT ` + `employee_id, last_name, first_name, title, title_of_courtesy, birth_date, hire_date, address, city, region, postal_code, country, home_phone, extension, photo, notes, reports_to, photo_path ` + `FROM northwind.employees ` + `WHERE reports_to = ?` // run logf(sqlstr, reportsTo) rows, err := db.QueryContext(ctx, sqlstr, reportsTo) if err != nil { return nil, logerror(err) } defer rows.Close() // process var res []*Employee for rows.Next() { e := Employee{ _exists: true, } // scan if err := rows.Scan(&e.EmployeeID, &e.LastName, &e.FirstName, &e.Title, &e.TitleOfCourtesy, &e.BirthDate, &e.HireDate, &e.Address, &e.City, &e.Region, &e.PostalCode, &e.Country, &e.HomePhone, &e.Extension, &e.Photo, &e.Notes, &e.ReportsTo, &e.PhotoPath); err != nil { return nil, logerror(err) } res = append(res, &e) } if err := rows.Err(); err != nil { return nil, logerror(err) } return res, nil } // Employee returns the Employee associated with the Employee's (ReportsTo). // // Generated from foreign key 'employees_ibfk_1'. func (e *Employee) Employee(ctx context.Context, db DB) (*Employee, error) { return EmployeeByEmployeeID(ctx, db, int16(e.ReportsTo.Int64)) }
{ "content_hash": "1717530f79de64147b98baaf6ee4524a", "timestamp": "", "source": "github", "line_count": 201, "max_line_length": 546, "avg_line_length": 44.950248756218905, "alnum_prop": 0.666961815163254, "repo_name": "knq/xo", "id": "b9ebd6552470a821f9cfb8c6d22f08be823872ac", "size": "9035", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "_examples/northwind/mysql/employee.xo.go", "mode": "33188", "license": "mit", "language": [ { "name": "Go", "bytes": "136137" }, { "name": "Python", "bytes": "620" }, { "name": "Shell", "bytes": "20481" }, { "name": "Smarty", "bytes": "26306" } ], "symlink_target": "" }
You're free to contribute to this project or open issue if you have one.
{ "content_hash": "9ec690661377f90411c6efb0d724bbcc", "timestamp": "", "source": "github", "line_count": 1, "max_line_length": 72, "avg_line_length": 72, "alnum_prop": 0.7916666666666666, "repo_name": "dorian-delorme/video-player", "id": "f7ea781ab5368e7bc8481fe801aaa7b7f3bdde5a", "size": "88", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "CONTRIBUTING.md", "mode": "33261", "license": "mit", "language": [ { "name": "CSS", "bytes": "7509" }, { "name": "HTML", "bytes": "547" }, { "name": "JavaScript", "bytes": "24013" } ], "symlink_target": "" }
package org.mpilone.hazelcastmq.camel; import static java.lang.String.format; import static org.mpilone.hazelcastmq.camel.HazelcastMQCamelEndpoint.toHazelcastMQDestination; import java.util.*; import java.util.concurrent.*; import java.util.concurrent.atomic.AtomicLong; import org.apache.camel.*; import org.apache.camel.impl.DefaultProducer; import org.mpilone.hazelcastmq.camel.MessageConverter; import org.mpilone.hazelcastmq.core.*; /** * An Apache Camel producer that can produce messages into an HzMq endpoint such * as a queue or a topic. The producer supports one way requests (InOnly) and * two way request/reply (InOut) patterns. * * @author mpilone */ public class HazelcastMQCamelProducer extends DefaultProducer { /** * The header in the Camel "in" message that specifies the destination for the * specific message being sent. If this value is set in the message, the * destination configured for the endpoint will be ignored and the message * specific destination will be used instead. */ public static final String CAMEL_HZMQ_DESTINATION = "CamelHzMqDestination"; private final HazelcastMQCamelConfig config; private final MessageConverter messageConverter; private final String destination; private final ReplyManager replyManager; private HazelcastMQContext mqContext; private HazelcastMQProducer mqProducer; /** * Constructs the producer which will produce messages to the given endpoint * destination. * * @param endpoint the endpoint that this instance is producing into */ public HazelcastMQCamelProducer(HazelcastMQCamelEndpoint endpoint) { super(endpoint); this.config = endpoint.getConfiguration(); this.messageConverter = config.getMessageConverter(); this.destination = endpoint.getDestination(); // Load the reply-to destination from the config first and then allow the // reply manager to fallback to temporary queue. this.replyManager = new ReplyManager(config.getReplyTo(), config. getHazelcastMQInstance()); } @Override protected void doStart() throws Exception { super.doStart(); if (mqContext == null) { mqContext = config.getHazelcastMQInstance().createContext(); mqProducer = mqContext.createProducer(); } replyManager.start(); } @Override protected void doStop() throws Exception { super.doStop(); if (mqContext != null) { mqProducer = null; mqContext.stop(); mqContext = null; } replyManager.stop(); } @Override protected void doShutdown() throws Exception { super.doShutdown(); replyManager.shutdown(); } @Override public void process(Exchange exchange) throws Exception { Message camelMsg = exchange.getIn(); // Handle a message specific destination if set in the headers; otherwise // use the destination configured in the endpoint. String msgDest = camelMsg.getHeader(CAMEL_HZMQ_DESTINATION) != null ? toHazelcastMQDestination(camelMsg.getHeader(CAMEL_HZMQ_DESTINATION). toString()) : destination; HazelcastMQMessage msg = messageConverter.fromCamelMessage(camelMsg); try { if (exchange.getPattern().isOutCapable()) { processInOut(msgDest, msg, exchange, mqProducer); } else { processInOnly(msgDest, msg, exchange, mqProducer); } } catch (Throwable e) { exchange.setException(e); } } /** * Processes an InOnly exchange by converting the message in the exchange and * sending it to the configured endpoint destination. * * @param destination the destination to send the message to * @param msg the HzMq message to be sent * @param exchange the exchange to process * @param mqProducer the producer to use for sending * * @throws Exception if there is an error producing the message to the * exchange */ private void processInOnly(String destination, HazelcastMQMessage msg, Exchange exchange, HazelcastMQProducer mqProducer) throws Exception { int timeToLive = config.getTimeToLive(); mqProducer.send(destination, msg, timeToLive); } /** * <p> * Processes an InOut exchange by converting the message in the exchange and * sending it to the configured endpoint destination. A replyTo destination * will be set on the produced message as well as a correlation ID if one * isn't already present on the message. This method will block for the * configured reply timeout or until a reply is received, which ever comes * first. * </p> * <p> * The producer only supports exclusive or temporary reply queues. Because * HzMq doesn't support selectors, shared reply queues cannot be used. An * unique (and therefore exclusive) reply queue must be configured per * endpoint for proper request/reply support. If no reply queue is configured, * a temporary queue will be automatically created and used. There is very * little overhead with temporary queues in HzMq so a temporary reply queue is * a good default option; however an exclusive reply queue may be easier to * debug in the event of a problem. * </p> * * @param destination the destination to send the message to * @param msg the HzMq message to be sent * @param exchange the exchange to process * @param mqProducer the producer to use for sending * * @throws Exception if there is an error producing the message to the * exchange */ private void processInOut(String destination, HazelcastMQMessage msg, Exchange exchange, HazelcastMQProducer mqProducer) throws Exception { int timeToLive = config.getTimeToLive(); int requestTimeout = config.getRequestTimeout(); BlockingQueue<HazelcastMQMessage> replyQueue = new ArrayBlockingQueue<>(1); String replyToDestination = replyManager.getReplyToDestination(); msg.setReplyTo(replyToDestination); if (msg.getCorrelationId() == null) { msg.setCorrelationId("CamelHzMq-" + UUID.randomUUID().toString()); } // Add the pending reply before sending the message to prevent a race // condition if the reply arrived before we're ready. replyManager.addPendingReply(msg.getCorrelationId(), requestTimeout, replyQueue); // Send the message. mqProducer.send(destination, msg, timeToLive); // Wait for the reply. HazelcastMQMessage replyMsg = replyQueue.poll(requestTimeout, TimeUnit.MILLISECONDS); if (replyMsg == null) { throw new RuntimeCamelException(format( "No reply received for correlation ID %s on reply to " + "destination %s after %d milliseconds.", msg.getCorrelationId(), replyToDestination, requestTimeout)); } else if (replyMsg == ReplyManager.SENTINAL) { // This is expected if we're shutting down. No reply will be processed. } else { exchange.setOut(messageConverter.toCamelMessage(replyMsg)); } } /** * A reply manager that can listener for replies on a given destination. The * replies are correlated with producers pending a reply via the message * correlation ID. */ private static class ReplyManager implements HazelcastMQMessageListener, ShutdownableService { private final HazelcastMQContext mqContext; private final HazelcastMQConsumer mqConsumer; private final Map<String, PendingReply> pendingReplyMap; private final AtomicLong nextExpiration; private final String replyToDestination; public final static HazelcastMQMessage SENTINAL = new HazelcastMQMessage(); /** * Constructs the reply manager which will listen for replies on the given * destination. If the destination is null, a temporary reply queue will be * created and managed by the reply manager. * * @param replyToDest the reply to destination or null * @param mqInstance the HzMq instance brokering all replies */ public ReplyManager(String replyToDest, HazelcastMQInstance mqInstance) { this.pendingReplyMap = new ConcurrentHashMap<>(); this.nextExpiration = new AtomicLong(Long.MAX_VALUE); this.mqContext = mqInstance.createContext(); mqContext.setAutoStart(false); // If we don't have an exclusive reply queue, create a temporary queue. this.replyToDestination = replyToDest == null ? mqContext.createTemporaryQueue() : replyToDest; this.mqConsumer = mqContext.createConsumer(this.replyToDestination); mqConsumer.setMessageListener(this); } @Override public void start() { mqContext.start(); } @Override public void stop() { mqContext.stop(); } @Override public void shutdown() { mqConsumer.close(); mqContext.close(); // Send a sentinal value to all pending producers. for (Iterator<PendingReply> iter = pendingReplyMap.values().iterator(); iter.hasNext();) { PendingReply pendingReply = iter.next(); iter.remove(); pendingReply.getReplyQueue().offer(SENTINAL); } } /** * Returns the replyTo destination that should be used for all messages to * be handled by this reply manager instance. * * @return the replyTo destination */ public String getReplyToDestination() { return replyToDestination; } /** * Adds a pending reply to be tracked for the given correlation ID. * * @param correlationId the ID of the expected reply * @param timeout the number of milliseconds to wait for the reply before * dropping the pending reply * @param replyQueue the queue to write the reply to once received */ public void addPendingReply(String correlationId, long timeout, Queue<HazelcastMQMessage> replyQueue) { long expiration = System.currentTimeMillis() + timeout; PendingReply pendingReply = new PendingReply(correlationId, expiration, replyQueue); pendingReplyMap.put(correlationId, pendingReply); setIfLess(nextExpiration, expiration); } @Override public void onMessage(HazelcastMQMessage msg) { long now = System.currentTimeMillis(); PendingReply pendingReply = null; // Cleanup expired pending replies. if (nextExpiration.get() <= now) { nextExpiration.set(Long.MAX_VALUE); for (Iterator<PendingReply> iter = pendingReplyMap.values().iterator(); iter.hasNext();) { pendingReply = iter.next(); if (pendingReply.getExpiration() <= now) { iter.remove(); } else { setIfLess(nextExpiration, pendingReply.getExpiration()); } } } // Process the incoming reply. String correlationId = msg.getCorrelationId(); if (correlationId != null) { pendingReply = pendingReplyMap.remove(correlationId); } if (pendingReply != null) { pendingReply.getReplyQueue().offer(msg); } else { // TODO: log this } } /** * Sets the value of the current long if the given update value is less than * the current value. * * @param current the current value * @param update the potential update value * * @return true if the value is set */ private boolean setIfLess(AtomicLong current, long update) { while (true) { long cur = current.get(); if (update < cur) { if (current.compareAndSet(cur, update)) { return true; } } else { return false; } } } } /** * A pending reply for a producer. The pending reply is correlated via the * correlation ID and will expire at some point in time. */ private static class PendingReply { private final String correlationId; private final long expiration; private final Queue<HazelcastMQMessage> replyQueue; /** * Constructs the pending reply. * * @param correlationId the correlation ID used to correlate this reply with * incoming reply messages * @param expiration the expiration date of this pending reply in unix time * milliseconds * @param replyQueue the reply queue to offer the reply message to when it * arrives */ public PendingReply(String correlationId, long expiration, Queue<HazelcastMQMessage> replyQueue) { this.correlationId = correlationId; this.expiration = expiration; this.replyQueue = replyQueue; } /** * Returns the correlation ID used to correlate this reply with incoming * reply messages. * * @return the correlation ID */ public String getCorrelationId() { return correlationId; } /** * Returns the expiration date of this pending reply in unix time * milliseconds. * * @return the expiration date */ public long getExpiration() { return expiration; } /** * Returns the reply queue to offer the reply message to when it arrives. * * @return the reply queue */ public Queue<HazelcastMQMessage> getReplyQueue() { return replyQueue; } } }
{ "content_hash": "bd0a212b41c6ee014fc9f3c843b2d10a", "timestamp": "", "source": "github", "line_count": 420, "max_line_length": 94, "avg_line_length": 31.533333333333335, "alnum_prop": 0.6836303231652069, "repo_name": "mpilone/hazelcastmq", "id": "d67bc70de70bba6853b64c04f9a410ee7ed1deb7", "size": "13244", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "hazelcastmq-camel/src/main/java/org/mpilone/hazelcastmq/camel/HazelcastMQCamelProducer.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "568376" } ], "symlink_target": "" }
// Generated by the protocol buffer compiler. DO NOT EDIT! // source: google/ads/googleads/v10/services/account_budget_proposal_service.proto package com.google.ads.googleads.v10.services; public interface MutateAccountBudgetProposalResultOrBuilder extends // @@protoc_insertion_point(interface_extends:google.ads.googleads.v10.services.MutateAccountBudgetProposalResult) com.google.protobuf.MessageOrBuilder { /** * <pre> * Returned for successful operations. * </pre> * * <code>string resource_name = 1 [(.google.api.resource_reference) = { ... }</code> * @return The resourceName. */ java.lang.String getResourceName(); /** * <pre> * Returned for successful operations. * </pre> * * <code>string resource_name = 1 [(.google.api.resource_reference) = { ... }</code> * @return The bytes for resourceName. */ com.google.protobuf.ByteString getResourceNameBytes(); }
{ "content_hash": "8a491ec4479ab7e21f80a0cac3cc65b6", "timestamp": "", "source": "github", "line_count": 29, "max_line_length": 118, "avg_line_length": 32.206896551724135, "alnum_prop": 0.6991434689507494, "repo_name": "googleads/google-ads-java", "id": "83db3f179b04491bdbf8b2ad42bdac2e1fee1d16", "size": "934", "binary": false, "copies": "1", "ref": "refs/heads/main", "path": "google-ads-stubs-v10/src/main/java/com/google/ads/googleads/v10/services/MutateAccountBudgetProposalResultOrBuilder.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "28701198" } ], "symlink_target": "" }
// // Copyright (c) 2015 Oliver Lehmann <[email protected]> // 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. // // THIS SOFTWARE IS PROVIDED BY THE AUTHOR 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 AUTHOR 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.laladev.moneyjinn.service.api; import java.util.List; import java.util.Set; import org.laladev.moneyjinn.model.access.Group; import org.laladev.moneyjinn.model.access.GroupID; import org.laladev.moneyjinn.model.exception.BusinessException; import org.laladev.moneyjinn.model.validation.ValidationResult; /** * <p> * GroupService is the Core Service handling everything around an {@link Group}. * </p> * * <p> * GroupService is the Domain Service handling operations around an {@link Group} like getting, * creating, updating, deleting. Before a {@link Group} is created or updated, the {@link Group} is * validated for correctness. * </p> * <p> * The main datasource is the Table <code>access</code>. * </p> * * @author Oliver Lehmann * @since 0.0.1 * */ public interface IGroupService { /** * Checks the validity of the given {@link Group} * * @param user * the {@link Group} * @return {@link ValidationResult} */ ValidationResult validateGroup(Group group); /** * Returns the {@link Group} for the given {@link GroupID}. * * @param groupId * the {@link GroupID} * @return */ Group getGroupById(GroupID groupId); /** * This Service returns the distinct initials of all groupnames in the database in uppercase. * * @return all uppercased initials */ Set<Character> getAllGroupInitials(); /** * This Service returns the number of all existing groups * * @return number of {@link Group}s */ Integer countAllGroups(); /** * This Service returns all existing {@link Group}s * * @return list of all {@link Group}s */ List<Group> getAllGroups(); /** * This Service returns all existing {@link Group}s which name start with the specified initial * case-insensitive * * @param initial * the first letter of the {@link Group}s name * @return a list of {@link Group}s */ List<Group> getAllGroupsByInitial(Character initial); /** * This Service returns the {@link Group} for the specified name * * @param name * the Group-Name * @return {@link Group} */ Group getGroupByName(String name); /** * This service creates a {@link Group}. Before the {@link Group} is created it is validated for * correctness. * * @param group * the {@link Group} to be created * @throws BusinessException * If the validation of the given {@link Group} failed. */ void createGroup(Group group); /** * This service changes a {@link Group}. Before the {@link Group} is changed, the new values are * validated for correctness. * * @param user * the new {@link Group} attributes * @throws BusinessException * If the validation of the given {@link Group} failed. */ void updateGroup(Group group); /** * This service deletes a {@link Group} from the system * * @param groupId * The {@link GroupID} of the to-be-deleted {@link Group} * @throws BusinessException * If the deletion fails an error is throws. It is always assumed that it fails * because of a Foreign Key Constraint Violation on the DB level */ void deleteGroup(GroupID groupId); }
{ "content_hash": "fcf70ed1735582850d70134e5d9761a5", "timestamp": "", "source": "github", "line_count": 147, "max_line_length": 99, "avg_line_length": 31.14965986394558, "alnum_prop": 0.6955667176239354, "repo_name": "OlliL/moneyjinn-server", "id": "12638abaeb5a3ad970d53fcb1e6b2bda1e0bfd91", "size": "4579", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "moneyjinn-service-api/src/main/java/org/laladev/moneyjinn/service/api/IGroupService.java", "mode": "33188", "license": "bsd-2-clause", "language": [ { "name": "HTML", "bytes": "9" }, { "name": "Java", "bytes": "2070670" }, { "name": "Shell", "bytes": "3428" } ], "symlink_target": "" }
package net.mgsx.game.examples.openworld.systems; import java.io.ByteArrayInputStream; import java.io.InputStream; import java.io.StringWriter; import com.badlogic.ashley.core.EntitySystem; import com.badlogic.gdx.graphics.Camera; import com.badlogic.gdx.utils.Array; import com.badlogic.gdx.utils.Json; import com.badlogic.gdx.utils.ObjectMap; import com.badlogic.gdx.utils.ObjectMap.Entry; import com.badlogic.gdx.utils.ObjectSet; import net.mgsx.game.core.GamePipeline; import net.mgsx.game.core.PostInitializationListener; import net.mgsx.game.core.annotations.Editable; import net.mgsx.game.core.annotations.EditableSystem; import net.mgsx.game.core.annotations.Inject; import net.mgsx.game.examples.openworld.model.GameAction; import net.mgsx.game.examples.openworld.model.OpenWorldElement; import net.mgsx.game.examples.openworld.model.OpenWorldGame; import net.mgsx.game.examples.openworld.model.OpenWorldGameEventListener; import net.mgsx.game.examples.openworld.model.OpenWorldGameEventManager; import net.mgsx.game.examples.openworld.model.OpenWorldModel; import net.mgsx.game.examples.openworld.model.OpenWorldPlayer; import net.mgsx.game.examples.openworld.model.OpenWorldQuestModel; import net.mgsx.game.examples.openworld.model.OpenWorldQuestModel.Requirement; import net.mgsx.game.services.gapi.GAPI; import net.mgsx.game.services.gapi.SavedGame; /** * Saving is done synchronously while loading is done on this system update in order to * properly load other systems and avoid glitches. * * TODO add threading support and callback. * * some quests are realtime based (distance, time ...) and is checked at each frames. * Other quests are event based and don't have to be checked every time, just * when player performs some actions or when world spawn something. * * @author mgsx * */ @EditableSystem public class OpenWorldGameSystem extends EntitySystem implements PostInitializationListener, OpenWorldGameEventManager { @Inject OpenWorldSpawnSystem spawnSystem; @Inject OpenWorldCameraSystem cameraSystem; @Inject OpenWorldGeneratorSystem generator; @Inject OpenWorldManagerSystem manager; @Inject UserObjectSystem userObjectSystem; @Inject OpenWorldHUDSystem hudSystem; @Inject OpenWorldEnvSystem env; @Editable(realtime=true, readonly=true) public transient boolean diving, walking, flying, swimming; @Editable public boolean playerLogic = true; @Editable public transient boolean eventsLogic = false; public Array<OpenWorldElement> backpack = new Array<OpenWorldElement>(); private SavedGame gameToLoad; private ObjectSet<OpenWorldGameEventListener> gameEventListeners = new ObjectSet<OpenWorldGameEventListener>(); // TODO move player logic to dedicated system ? only keep game loading/saving logic here. // things need environement system to be computed first (specially at loading time) // , then player logic can apply, then HUD can display correct values. public OpenWorldPlayer player; public OpenWorldGameSystem() { super(GamePipeline.FIRST); } @Override public void onPostInitialization() { player = new OpenWorldPlayer(); computePlayerStats(); // compute inital values player.energy = player.energyMax; player.life = player.lifeMax; player.oxygen = player.oxygenMax; // TODO some values should be updated in realtime } @Override public void addGameEventListener(OpenWorldGameEventListener listener) { gameEventListeners.add(listener); } @Override public void removeGameEventListener(OpenWorldGameEventListener listener) { gameEventListeners.remove(listener); } /** * compute level based on XP (see {@link #experience(int)} * @param experience * @return */ public static int level(long experience){ return (int)Math.sqrt(experience/100 + 0.5) + 1; } /** * compute XP based on level. * Common gaming is to use square to have linear delta between level. * Values are : * LV1 : 0 XP * LV2 : 100 XP (+100) * LV3 : 400 XP (+300) (++200) * LV4 : 900 XP (+500) (++200) * LV5 : 1600 XP (+700) (++200) * LV6 : 2500 XP (+900) (++200) * ... * @param level * @return */ public static long experience(int level){ long base = (long)level - 1; return 100L * base * base; } private void computePlayerStats() { // first compute level based on experience player.level = level(player.experience); // TODO maybe adjust base to have something realistic ? (oxygen ...) // derived max values from level player.energyMax = player.level + 3; player.lifeMax = player.level + 3; player.oxygenMax = player.level + 3; // init basics values // these values are based not based on scientific stuff and limits depends // on exposure time, air/water ...etc. But we could consider that // player loose 1 life point every hour : // * per degree below 10° // * per degree above 50° player.temperatureMax = 50; player.temperatureMin = 10; // TODO modify basic values based on equipment (iterate from backpack). // XXX reset stats player.life = player.lifeMax; player.energy = player.energyMax; player.oxygen = player.oxygenMax; player.temperature = 37.2; // compute quests based on achievements (already completed quests) // and quests revealed from model ObjectSet<String> unlocked = new ObjectSet<String>(); Array<String> toProcess = new Array<String>(); for(String qid : player.achievements){ toProcess.add(qid); } while(toProcess.size > 0){ String qid = toProcess.pop(); if(unlocked.add(qid)){ OpenWorldQuestModel quest = OpenWorldModel.quest(qid); for(String reveal : quest.unlocking()){ if(!unlocked.contains(reveal)){ if(isUnlocked(reveal)){ unlocked.add(reveal); }else{ player.pendingQuests.add(reveal); } } } for(String itemId : quest.knowledges()){ player.knownSecrets.add(itemId); } } } // update completed since model may have changed between last save (migration) for(String id : unlocked) player.completedQuests.add(id); // load history for(String code : player.history){ String [] codes = code.split("\\|"); ObjectMap<String, Integer> act = player.actions.get(codes[0]); if(act == null) player.actions.put(codes[0], act = new ObjectMap<String, Integer>()); act.put(codes[1], Integer.valueOf(codes[2])); } } private boolean isUnlocked(String qid) { Array<Requirement> requirements = OpenWorldModel.quest(qid).requirements(); for(Requirement requirement : requirements){ ObjectMap<String, Integer> act = player.actions.get(requirement.action); if(act == null) return false; Integer count = act.get(requirement.type); if(count == null) return false; if(count < requirement.count) return false; } return true; } private void load(SavedGame game) { InputStream stream = GAPI.service.loadGame(game); Json json = new Json(); OpenWorldGame gameData = json.fromJson(OpenWorldGame.class, stream); cameraSystem.setPosition(gameData.position); generator.seed = gameData.seed; generator.reset(); manager.clear(); spawnSystem.clear(); userObjectSystem.removeAllElements(); if(gameData.objects != null){ for(OpenWorldElement element : gameData.objects){ OpenWorldModel.generateElement(element); userObjectSystem.appendObject(element); } } backpack.clear(); if(gameData.backpack != null){ for(OpenWorldElement element : gameData.backpack){ OpenWorldModel.generateElement(element); backpack.add(element); } } player = gameData.player; if(player == null){ player = new OpenWorldPlayer(); } computePlayerStats(); // finally invalidate GUI hudSystem.hudMain.resetState(); } public void save(SavedGame game){ OpenWorldGame gameData = new OpenWorldGame(); // store camera position and seed gameData.position.set(cameraSystem.getCamera().position); gameData.seed = generator.seed; // store objects gameData.objects = new OpenWorldElement[userObjectSystem.allUserObjects.size]; for(int i=0 ; i<gameData.objects.length ; i++){ gameData.objects[i] = userObjectSystem.allUserObjects.get(i).element; } gameData.backpack = new OpenWorldElement[backpack.size]; for(int i=0 ; i<gameData.backpack.length ; i++){ gameData.backpack[i] = backpack.get(i); } gameData.player = player; gameData.player.achievements = new String[player.completedQuests.size]; for(int i=0 ; i<gameData.player.achievements.length ; i++){ gameData.player.achievements[i] = player.completedQuests.get(i); } Array<String> history = new Array<String>(String.class); for(Entry<String, ObjectMap<String, Integer>> act : player.actions){ for(Entry<String, Integer> type : act.value){ history.add(act.key + "|" + type.key + "|" + type.value); } } gameData.player.history = history.toArray(); // serialize Json json = new Json(); StringWriter writer = new StringWriter(); json.toJson(gameData, writer); InputStream data = new ByteArrayInputStream(writer.toString().getBytes()); GAPI.service.saveGame(game, data); } public void loadRequest(SavedGame game) { gameToLoad = game; } @Override public void update(float deltaTime) { if(gameToLoad != null){ load(gameToLoad); gameToLoad = null; }else{ if(!playerLogic) return; Camera camera = cameraSystem.getCamera(); if(camera == null) return; // offset from ground to camera is the player's tall final float footsToEyeHeight = 1.7f; // head offset when swimming (limit : cannot fly up to this value above sea) float headOffset = .2f; // TODO replace by enum : states are mutually exclusive ! // flying is just a case we'll see later (falling or planning or bird mode ...) // we reset all status flying = false; walking = false; diving = false; swimming = false; // this is the ground level based on procedural lands float altitude = generator.getAltitude(camera.position.x, camera.position.z); // walking status is when ground below the sea is no more than player tall float waterDepth = env.waterLevel - altitude; if(waterDepth < footsToEyeHeight){ walking = true; } else { // diving status is easy, it is when camera is below water level. if(camera.position.y < env.waterLevel){ diving = true; } // all other cases, the player is swimming else { swimming = true; } } // enable flying mode in case of diving or swimming only if(diving || swimming){ cameraSystem.flyingMode = true; // in this case, we limit to palyer's head above the sea. float altitudeMax = env.waterLevel + headOffset; if(camera.position.y > altitudeMax){ camera.position.y = altitudeMax; } // in this case, camera offset in small, player is not vertical. // to avoid camera clipping we offset to 1 meter; cameraSystem.offset = 1.5f; // TODO maybe less depends on near camera clipping ... } else{ cameraSystem.flyingMode = false; // in this case, camera offset is player tall cameraSystem.offset = footsToEyeHeight; } // update player logic float currentMove = cameraSystem.currentMove; // TODO use scentific values : nb km per hour, ...Etc. // in water then update oxygen if(diving){ player.oxygen -= deltaTime * 0.5; if(player.oxygen < 0){ player.oxygen = 0; player.life -= deltaTime * 1; } }else{ player.oxygen += deltaTime * 2; if(player.oxygen > player.oxygenMax){ player.oxygen = player.oxygenMax; } } // update temperature from environement and time ... player.temperature += (env.temperature - player.temperature) * deltaTime * 0.05; if(player.temperature < player.temperatureMin){ player.energy -= deltaTime * 0.1; } if(player.temperature > player.temperatureMax){ player.energy -= deltaTime * 0.1; } // lose more energy by moving if(walking){ player.energy -= currentMove * 0.001; }else if(swimming || diving){ player.energy -= currentMove * 0.01; }else if(flying){ player.energy -= currentMove * 0.005; }else{ // loose energy in all cases player.energy -= deltaTime * 0.0000001; } if(player.energy < 0){ player.energy = 0; player.life -= deltaTime * 0.01; }else if(player.energy / player.energyMax > 0.9){ // recuperation at 90% since energy can't get at 100% player.life += deltaTime * 0.01; if(player.life > player.lifeMax) player.life = player.lifeMax; } if(player.life < 0){ player.life = 0; // TODO death sequence ... } // increment stats if(flying) player.distanceFly += currentMove; if(swimming || diving) player.distanceSwim += currentMove; if(walking) player.distanceWalk += currentMove; player.timePlay += deltaTime; if(!eventsLogic) return; // case of game beginning : reveal the first quest and drop a machete // just in front of player. if(player.completedQuests.size == 0 && player.pendingQuests.size == 0){ revealQuest("intro"); OpenWorldElement item = OpenWorldModel.generateNewElement("machete"); item.position.set(camera.position).mulAdd(camera.direction, 2); // 2m item.rotation.idt(); userObjectSystem.appendObject(item); } // TODO check some realtime achievements here. } } @Override public void actionReport(GameAction action, String type) { String actionName; switch(action){ case CRAFT: actionName = "build"; break; case DESTROY: actionName = "destroy"; break; case DROP: actionName = "drop"; break; case EAT: actionName = "eat"; break; case GRAB: actionName = "grab"; break; case LOOK: actionName = "look"; break; case SLEEP: actionName = "sleep"; break; case USE: actionName = "use"; break; default: actionName = "unknown"; break; } if(action == GameAction.SLEEP){ player.timeSleep += 8; // TODO 8 is defined in HUD should be handled differently } increment(actionName, type, 1); checkQuestsStatus(); } private void increment(String action, String type, int count){ ObjectMap<String, Integer> act = player.actions.get(action); if(act == null) player.actions.put(action, act = new ObjectMap<String, Integer>()); Integer counter = act.get(type); if(counter == null) counter = 0; counter += count; act.put(type, counter); } private void revealQuest(String qid) { player.pendingQuests.add(qid); for(OpenWorldGameEventListener listener : gameEventListeners) listener.onQuestRevealed(qid); checkQuestsStatus(); } private void checkQuestsStatus() { // Iterate for removal for(int i=0 ; i<player.pendingQuests.size ; ){ String qid = player.pendingQuests.get(i); if(isUnlocked(qid)){ player.pendingQuests.removeIndex(i); unlockQuest(qid); continue; } i++; } } private void unlockQuest(String qid) { player.completedQuests.add(qid); for(OpenWorldGameEventListener listener : gameEventListeners) listener.onQuestUnlocked(qid); OpenWorldQuestModel quest = OpenWorldModel.quest(qid); for(String itemId : quest.knowledges()){ if(player.knownSecrets.add(itemId)){ for(OpenWorldGameEventListener listener : gameEventListeners) listener.onSecretUnlocked(itemId); } } for(String newQid : quest.unlocking()){ revealQuest(newQid); } } @Override public void questAck(String qid) { player.acknowledgedQuests.add(qid); checkQuestsStatus(); } public int getAvailableSpaceInBackpack() { return getTotalSpaceInBackpack() - getUsedSpaceInBackpack(); } public int getUsedSpaceInBackpack() { int sum = 0; for(OpenWorldElement item : backpack){ sum += OpenWorldModel.space(item.type); } return sum; } public int getTotalSpaceInBackpack() { // TODO this value could be upgraded in some way ... return 16; } }
{ "content_hash": "da0578f56aec41e9ff85b339b35899af", "timestamp": "", "source": "github", "line_count": 567, "max_line_length": 118, "avg_line_length": 28.292768959435627, "alnum_prop": 0.6970452562024685, "repo_name": "mgsx-dev/gdx-kit", "id": "c2c760745ff847c78a1cd69c63d476efa76fef7d", "size": "16044", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "openworld-core/src/net/mgsx/game/examples/openworld/systems/OpenWorldGameSystem.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "GLSL", "bytes": "183944" }, { "name": "Java", "bytes": "2354150" }, { "name": "JavaScript", "bytes": "10151" }, { "name": "OpenEdge ABL", "bytes": "10496" } ], "symlink_target": "" }
class Projects::ArtifactsController < Projects::ApplicationController include ExtractsPath include RendersBlob layout 'project' before_action :authorize_read_build! before_action :authorize_update_build!, only: [:keep] before_action :extract_ref_name_and_path before_action :validate_artifacts! before_action :set_path_and_entry, only: [:file, :raw] def download if artifacts_file.file_storage? send_file artifacts_file.path, disposition: 'attachment' else redirect_to artifacts_file.url end end def browse @path = params[:path] directory = @path ? "#{@path}/" : '' @entry = build.artifacts_metadata_entry(directory) render_404 unless @entry.exists? end def file blob = @entry.blob override_max_blob_size(blob) respond_to do |format| format.html do render 'file' end format.json do render_blob_json(blob) end end end def raw send_artifacts_entry(build, @entry) end def keep build.keep_artifacts! redirect_to namespace_project_build_path(project.namespace, project, build) end def latest_succeeded target_path = artifacts_action_path(@path, project, build) if target_path redirect_to(target_path) else render_404 end end private def extract_ref_name_and_path return unless params[:ref_name_and_path] @ref_name, @path = extract_ref(params[:ref_name_and_path]) end def validate_artifacts! render_404 unless build && build.artifacts? end def build @build ||= begin build = build_from_id || build_from_ref build&.present(current_user: current_user) end end def build_from_id project.builds.find_by(id: params[:build_id]) if params[:build_id] end def build_from_ref return unless @ref_name builds = project.latest_successful_builds_for(@ref_name) builds.find_by(name: params[:job]) end def artifacts_file @artifacts_file ||= build.artifacts_file end def set_path_and_entry @path = params[:path] @entry = build.artifacts_metadata_entry(@path) render_404 unless @entry.exists? end end
{ "content_hash": "ce0eb28b5e24dc754888905e576c925d", "timestamp": "", "source": "github", "line_count": 102, "max_line_length": 79, "avg_line_length": 21.264705882352942, "alnum_prop": 0.6680497925311203, "repo_name": "htve/GitlabForChinese", "id": "1224e9503c93d12ccc3b14032ccb83148e6aba3b", "size": "2169", "binary": false, "copies": "1", "ref": "refs/heads/9-2-zh", "path": "app/controllers/projects/artifacts_controller.rb", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "499575" }, { "name": "Gherkin", "bytes": "140955" }, { "name": "HTML", "bytes": "979335" }, { "name": "JavaScript", "bytes": "1909827" }, { "name": "Ruby", "bytes": "10590735" }, { "name": "Shell", "bytes": "26903" }, { "name": "Vue", "bytes": "81150" } ], "symlink_target": "" }
void LogWindowStream::log(std::string output) { windowStream << output <<std::endl; if (!buffered || windowStream.tellp() > bufferSize) { flush(); } } void LogWindowStream::flush() { std::cout << windowStream.rdbuf(); } int LogWindowStream::open() { return 1; } void LogWindowStream::close() { flush(); }
{ "content_hash": "599da5f7fd625a74f26d53c567c300e9", "timestamp": "", "source": "github", "line_count": 22, "max_line_length": 52, "avg_line_length": 15.409090909090908, "alnum_prop": 0.6194690265486725, "repo_name": "pike4/CORE-Dev-Build-1.0", "id": "b73d16d3de3256e6189f9f2eb85645a2455959b3", "size": "369", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "CORE/Source/Subsystems/Logging/LogWindowStream.cpp", "mode": "33188", "license": "mit", "language": [ { "name": "C", "bytes": "1963842" }, { "name": "C++", "bytes": "683074" }, { "name": "CSS", "bytes": "3013" }, { "name": "HTML", "bytes": "369218" }, { "name": "Lua", "bytes": "272" }, { "name": "Makefile", "bytes": "10458" }, { "name": "Python", "bytes": "3468" }, { "name": "Roff", "bytes": "5493" } ], "symlink_target": "" }
using System.Text.Json; using Azure.Core; namespace Azure.ResourceManager.HDInsight.Models { internal partial class EncryptionInTransitProperties : IUtf8JsonSerializable { void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) { writer.WriteStartObject(); if (Optional.IsDefined(IsEncryptionInTransitEnabled)) { writer.WritePropertyName("isEncryptionInTransitEnabled"); writer.WriteBooleanValue(IsEncryptionInTransitEnabled.Value); } writer.WriteEndObject(); } internal static EncryptionInTransitProperties DeserializeEncryptionInTransitProperties(JsonElement element) { Optional<bool> isEncryptionInTransitEnabled = default; foreach (var property in element.EnumerateObject()) { if (property.NameEquals("isEncryptionInTransitEnabled")) { if (property.Value.ValueKind == JsonValueKind.Null) { property.ThrowNonNullablePropertyIsNull(); continue; } isEncryptionInTransitEnabled = property.Value.GetBoolean(); continue; } } return new EncryptionInTransitProperties(Optional.ToNullable(isEncryptionInTransitEnabled)); } } }
{ "content_hash": "37c407fce784926b298aa49009fb256a", "timestamp": "", "source": "github", "line_count": 38, "max_line_length": 115, "avg_line_length": 37.68421052631579, "alnum_prop": 0.6012569832402235, "repo_name": "Azure/azure-sdk-for-net", "id": "34e195f21e908f9cfc92a110f06e3f1fbeb9e302", "size": "1570", "binary": false, "copies": "1", "ref": "refs/heads/main", "path": "sdk/hdinsight/Azure.ResourceManager.HDInsight/src/Generated/Models/EncryptionInTransitProperties.Serialization.cs", "mode": "33188", "license": "mit", "language": [], "symlink_target": "" }