text
stringlengths
4
5.48M
meta
stringlengths
14
6.54k
layout: post title: "Tools of a Developer" modified: categories: blog excerpt: "These are my tools. Hopefully, they're always improving." tags: [setup,tools] --- One thing I'm always on the lookout for when someone opens up their laptop in front of me is what are the tools they use. This could be anything from their mail client to their terminal emulator. I check their operating system version. I look at all the icons on their screen and the windows that are open. I don't do this to be a creep. I do it because I want to know the latest and greatest tools people use and see if it's better than what I'm using at that moment. So in that vain, here's what I'm using at the moment. This is likely to change (frequently) because of what I just said above, but I think it's always a useful snapshot to keep track of these things. I'll probably write more detailed posts about a lot of them later. ### Hardware * [Early 2015 MacBook Pro 13" Retina](https://support.apple.com/kb/sp715?locale=en_US) * I've been using a Mac since I started grad school and I've never looked back. When I was an undergrad with nothing but time, I had a Linux box as my main development workstation, but at some point I got tired of doing more system administration than software development and gave a Mac a try. Ever since, Apple has done a great job of making new hardware (albeit sometimes pricy) and I'll keep buying it as far out as I can see. Windows has never been an option for me as I can't develop most of the software I work on directly on the machine so I'd always either have to be in a VM or an SSH session. * [Code Keyboard](https://codekeyboards.com/) * After reading for years about how great mechanical keyboards are, I finally gave this keyboard a shot. I won't say that it's changing my life. I didn't get the one with the super clacky keys so my co-workers wouldn't throw things at me, but I can't really tell a massive difference between this and a regular old rubber dome keyboard. I'd still like to try out the new Apple keyboards with the butterfly springs, but it's hard to justify buying another new one. * [Magic Trackpad 2](https://www.apple.com/shop/product/MJ2R2LL/A/magic-trackpad-2) * I love thing thing. It's got lots of nice gesture shortcuts that work well with the Mac (for things like starting Expose or Mission Control or whatever it's called now). 3-finger dragging is a must for quick selection. It also doesn't cramp up your hand the way a mouse can. I won't be doing any gaming on this thing, but I have a real mouse for that at home. * [Fellowes Memory Foam Wrist Rest](https://www.amazon.com/gp/product/B0013CEY0Q) * If you're going to use a keyboard, you need a place to put your wrists. I picked this one up on Amazon because it was the right size and it was cheap. No complaints. * BenQ GW2765 27" Monitor * I didn't really get to pick my monitor at work. I had the option of two low-res Dell monitors or this higher resolution one. I picked this one because I've never really gotten my workflow to do well with two monitors. I have the one big monitor in the center of my desk and the laptop to the side for extra windows that I can push over there (documentation, etc.). * Laptop holder from bathroom stall as laptop stand * This was literally a curved piece of metal sitting in a closet somewhere. Turns out it's hung on the back of bathroom stalls for people to put their laptops in while using the bathroom. Here's hoping this one wasn't in there long. * [Plantronics Backbeat PRO Bluetooth Headphones](http://a.co/2jMNcX9) * I don't have great things to say about these. I love the fact that they're bluetooth so I stop accidentally pulling the wires out of the headphones and/or the computer. However, there's an awful lot of interference that results in a clicking/skipping sound when listening to music. At some point, I might try using some Bose QC 35's to see if they have the same problem. * Pen and notebook * I take notes. This is where they go. I've tried lots of digital note-taking apps, but on the iPad, the writing fidelity is horrible. When typing, I often can't keep up with what's going on or I get distracted. The downside is that I have to carry a physical thing around though. * [Fellowes Monitor Stand](https://www.amazon.com/dp/B00006B8J2) * I'm pretty tall so having something to get my monitor up to the right height is important. They had a bunch of these sitting around at work and it does the job. To be fair though, if these weren't around, I would have just used a stack of books or something. ### Communication * Mail * Mail.app * I've gone back and forth with just about every mail client for Mac. In the end, the reason I keep ending up back with the stock app is mostly the fault of where I work. It's hard for me to use the non-stock mail app on my phone which means I lose a lot of the benefit of the kinds of apps that let you "snooze" emails. I'd love to have that ability, but until I can get it everywhere, it's not as useful. * [Outlook for Mac](https://products.office.com/en-us/outlook/email-and-calendar-software-microsoft-outlook) * From time to time, I have to fire up Outlook for work. Usually because I want to schedule a meeting and need to be able to best integrate with the Exchange server. I don't use this as a daily driver. * Calendar * Calendar.app * I've tried a few different alternatives here too, but end up going back to the default calendar app because I keep using the default mail app. It's very nice to have a mail and calendar app that work together well. * Instant Messaging * [Slack](www.slack.com) * Depending on who I need to talk to, I have to use different chat clients/servers. In the end though, this is my favorite. It's available everywhere. The clients do a good job of exposing features. Notifications are good. Lots of integrations. It pretty much does it all. * [Rocket.Chat](https://rocket.chat/) * Rocket.Chat isn't too bad. It's a poor man's Slack. The reason I use it is because we need to have a self-hosted chat client for work and this is pretty much all there is. Our install is somewhat crippled due to firewall restrictions or I might like it better. * Messages.app * This is pretty much just used for texting. If you use iMessages, you use this. * [Skype for Business](https://www.skype.com/en/business/skype-for-business/) * This is my least favorite. I have to use it because of work, but I get out of it as much as possible. It is still not feature complete (compared to the Lync client that it replaced) even after a 1.0 release. It drops connections from time to time. It's a **huge** battery hog. It has terrible syncing between the desktop and mobile clients. This is a last resort. ### Music * [Spotify (Paid)](https://www.spotify.com/us/) * I've tried Amazon Music and Apple Music and I keep coming back to Spotify. For me, the differentiator is the curated playlist selection. I like to listen to music while at work and I don't want to spend a bunch of time picking the next song. Apple and Amazon's playlists are too short and I have to pick a new playlist every hour or two. Pandora requires that I know more about what I want to listen to before I start (need to "seed" my playlists well). I like that Spotify has lots of ambient lists that I can trust to not get in my way while I'm trying to work. ### Browser * [Chrome](https://www.google.com/chrome/) * I recently built a Windows PC at home so I decided to switch back to Chrome to have a cross-platform browser. I like that Safari is more integrated with the OS, but I've also found that Chrome tends to work with more websites, especially those that are said to be "IE-only" at work. ### Command Line * [Neovim](https://neovim.io/) * I'm a Vim diehard. Mostly because I never learned Emacs. It's not that I have a good argument why Vim is better. I'm just lazy. That being said, I did switch over hardcore to Neovim. The big winner here over regular Vim is asynchronous background threads for plugins. I use tons of plugins (probably discuss that in a different post) and some of them, like linters are pretty painful if they block the main thread. Imagine typing and your linter kicks in for 2 seconds. You can't get any response from the UI until it's done compiling. That's not ok. Don't be that guy. Use Neovim. * [iTerm2](https://www.iterm2.com/) * This is a big improvement over the default Terminal app in MacOS. I'll admit that it's been a long time since I"ve use the default app, but at least when I switched, iTerm2 had much better handling of splits and windows. Since then, the killer feature has been built-in support for remote tmux sessions. I can now create and manipulate my splits and windows seamlessly. It's awesome. * [tmux](https://tmux.github.io/) * In my last job, I was able to use mosh. It was awesome. I loved it. My sessions just never died. I'd lose a connection. Go home. Get on a plane. Doesn't matter. The ssh connection was always there. Fast forward to my new job and mosh is no longer an option. Next best thing, I use tmux. Sessions always stay alive even when I go home for the day. Combined with the integration with iTerm2, this makes working much easier. I no longer fear putting my laptop to sleep. * [bash](https://www.gnu.org/software/bash/) * I've tried a few different shells. In the end, I've found them all to be pretty similar. Fish was pretty cool, but not really supported everywhere (as in, not installed by default) which meant I had to maintain two different versions of my environment setup depending on the shell. I gave up on that and decided to go with the old standby so I wouldn't have to worry about where I was. ### Utilities * [Alfred 3 (w/ Powerpack)](https://www.alfredapp.com/) * This is a great shortcut tool. I use it to search for files on my computer, launch applications, open ssh connections, remember passwords, do quick calculations, put my computer to sleep, open system preferences, and probably a bunch more. * [KeepingYouAwake](https://github.com/newmarcel/KeepingYouAwake) * This is a handy little tool to keep your computer from going to sleep. It's really nice when presenting or sitting in a meeting where you're doing something (like Powerpoint) that wouldn't otherwise force your computer to stay awake. * [Parallels](https://www.parallels.com/) * I haven't tried that many virtualization options on the Mac because I've usually had access to Parallels through work and it's always been a pretty good solution for me. I work in here very sparingly so I don't have a lot to say either way about it. * [Reeder](http://reederapp.com/mac/) * I subscribe to a **lot** of different RSS feeds and Reeder (synced via Feedly) is a great way to track and read all of them. It works with lots of different services (I use Instapaper for things I don't read immediately) and has a pretty good way of displaying articles by default and a good browser fallback when necessary. * [LastPass](https://www.lastpass.com/) * This is a must have at this point as I have way too many passwords to remember. At one point, we could all just use that one password for everything but now a combination of security and password requirements make it hard to continue that model. LastPass does a great job of both creating new passwords and remembering all of them for you. It will even do an analysis and tell you where you have a bunch of duplicated passwords and change (many) of them for you automatically. I also have an Alfred plugin so I can access these things in any application.
{'content_hash': '75c7efec3b6e16c62051fdd62714f4b9', 'timestamp': '', 'source': 'github', 'line_count': 203, 'max_line_length': 110, 'avg_line_length': 59.59605911330049, 'alnum_prop': 0.7329310629856175, 'repo_name': 'wesbland/wesbland.github.io', 'id': 'e5d78026947a661c7b78b629f04e56ea73289c85', 'size': '12102', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': '_posts/blog/2017-04-17-development-tools.md', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'HTML', 'bytes': '19428'}, {'name': 'JavaScript', 'bytes': '78211'}, {'name': 'Ruby', 'bytes': '190'}, {'name': 'SCSS', 'bytes': '50755'}]}
package birdz.lib.environment; import java.awt.Color; import java.awt.Graphics; import java.awt.Point; public class Goal extends EnvObject { private int size = 50; public Goal(int x, int y, int size) { this.setPosition(x,y); this.size = size; } @Override public boolean isTouching(Point p) { if(p.x >= this.getRoundedPosition().x && p.x < this.getRoundedPosition().x + size && p.y >= this.getRoundedPosition().y && p.y < this.getRoundedPosition().y + size) return true; return false; } @Override public Point[] getHitbox() { // TODO Auto-generated method stub return new Point[]{new Point(this.getRoundedPosition().x + (size/2), this.getRoundedPosition().y + (size/2))}; } @Override public void paint(Graphics g, int x, int y) { g.setColor(Color.CYAN); g.fillRect(this.getRoundedPosition().x, this.getRoundedPosition().y, size, size); } @Override public EnvObject copy() { return new Goal(this.getRoundedPosition().x, this.getRoundedPosition().y, size); } }
{'content_hash': 'b4ed8a5db9a64a194ddb2727a1ea0b2d', 'timestamp': '', 'source': 'github', 'line_count': 41, 'max_line_length': 112, 'avg_line_length': 24.5609756097561, 'alnum_prop': 0.6911618669314796, 'repo_name': 'SpyGuyIan/Birdz', 'id': 'f85dd1c3969c789bfdf70b4616da5e69070239c6', 'size': '1007', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'src/birdz/lib/environment/Goal.java', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'Java', 'bytes': '42609'}]}
'use strict' const path = require('path') const os = require('os') const test = require('tape') const { GelfFactory } = require(path.resolve('lib/gelf/index.js')) test('GELFMessageFactory should create basic gelf message with short and detailed message', (t) => { t.plan(1) const gelfJson = GelfFactory({source: os.hostname(), }, '5') const gelfRequiredFields = { 'version': '1.1', 'host': os.hostname(), 'level': 5, 'short_message': 'short_message not set' } t.deepEqual(gelfRequiredFields, gelfJson) }) test('GELFMessageFactory should create gelf message with data', (t) => { t.plan(1) const gelfJson = GelfFactory({source: os.hostname(), facility: 'some facility', full_message: 'some full message', short_message: 'some short message'}, 'notice') const gelfExpectedJson = { 'version': '1.1', 'host': os.hostname(), 'level': 5, 'short_message': 'some short message', 'full_message': 'some full message', '_facility': 'some facility' } t.deepEqual(gelfJson, gelfExpectedJson) }) test('GELFMessageFactory should delete id key', (t) => { t.plan(1) const gelfJson = GelfFactory({source: os.hostname(), facility: 'some facility', full_message: 'some full message', id: '1', short_message: 'some short message'}, 'notice') const gelfExpectedJson = { 'version': '1.1', 'host': os.hostname(), 'level': 5, 'short_message': 'some short message', 'full_message': 'some full message', '_facility': 'some facility' } t.deepEqual(gelfJson, gelfExpectedJson) }) test('Testing tags', (t) => { t.plan(8) const gelfJsonEmergency = GelfFactory({source: os.hostname(), }, 'emergency') const gelfExpectedJsonEmergency = { 'version': '1.1', 'host': os.hostname(), 'level': 0, 'short_message': 'short_message not set', } const gelfJsonAlert = GelfFactory({source: os.hostname(), }, 'alert') const gelfExpectedJsonAlert = { 'version': '1.1', 'host': os.hostname(), 'level': 1, 'short_message': 'short_message not set', } const gelfJsonCritical = GelfFactory({source: os.hostname(), }, 'critical') const gelfExpectedJsonCritical = { 'version': '1.1', 'host': os.hostname(), 'level': 2, 'short_message': 'short_message not set', } const gelfJsonError = GelfFactory({source: os.hostname(), }, 'error') const gelfExpectedJsonError = { 'version': '1.1', 'host': os.hostname(), 'level': 3, 'short_message': 'short_message not set', } const gelfJsonWarning = GelfFactory({source: os.hostname(), }, 'warning') const gelfExpectedJsonWarning= { 'version': '1.1', 'host': os.hostname(), 'level': 4, 'short_message': 'short_message not set', } const gelfJsonNotice = GelfFactory({source: os.hostname(), }, 'notice') const gelfExpectedJsonNotice= { 'version': '1.1', 'host': os.hostname(), 'level': 5, 'short_message': 'short_message not set', } const gelfJsonInfo = GelfFactory({source: os.hostname(), }, 'info') const gelfExpectedJsonInfo= { 'version': '1.1', 'host': os.hostname(), 'level': 6, 'short_message': 'short_message not set', } const gelfJsonDebug = GelfFactory({source: os.hostname(), }, 'debug') const gelfExpectedJsonDebug= { 'version': '1.1', 'host': os.hostname(), 'level': 7, 'short_message': 'short_message not set', } t.deepEqual(gelfJsonEmergency, gelfExpectedJsonEmergency) t.deepEqual(gelfJsonAlert, gelfExpectedJsonAlert) t.deepEqual(gelfJsonCritical, gelfExpectedJsonCritical) t.deepEqual(gelfJsonError, gelfExpectedJsonError) t.deepEqual(gelfJsonWarning, gelfExpectedJsonWarning) t.deepEqual(gelfJsonNotice, gelfExpectedJsonNotice) t.deepEqual(gelfJsonInfo, gelfExpectedJsonInfo) t.deepEqual(gelfJsonDebug, gelfExpectedJsonDebug) })
{'content_hash': 'ce55ee53f580a777969dc684d14a9f0b', 'timestamp': '', 'source': 'github', 'line_count': 114, 'max_line_length': 173, 'avg_line_length': 33.5, 'alnum_prop': 0.6598586017282011, 'repo_name': 'ubirajaramneto/hapi-graylog', 'id': '51c6bce850d1f9a9b0a11ace474d71467954393b', 'size': '3819', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'test/unit/gelf.js', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'JavaScript', 'bytes': '16318'}]}
@font-face { font-family: 'Gibson'; src: url('Gibson-Regular-webfonteccb.eot?3'); src: url('Gibson-Regular-webfont95c6.eot?3?#iefix') format('embedded-opentype'), url('Gibson-Regular-webfonteccb.woff?3') format('woff'), url('Gibson-Regular-webfonteccb.ttf?3') format('truetype'), url('Gibson-Regular-webfonteccb.svg?3#GibsonRegular') format('svg'); font-weight: normal; font-style: normal; } @font-face { font-family: 'Gibson'; src: url('Gibson-SemiBold-webfonteccb.eot?3'); src: url('Gibson-SemiBold-webfont95c6.eot?3?#iefix') format('embedded-opentype'), url('Gibson-SemiBold-webfonteccb.woff?3') format('woff'), url('Gibson-SemiBold-webfonteccb.ttf?3') format('truetype'), url('Gibson-SemiBold-webfonteccb.svg?3#GibsonLightBold') format('svg'); font-weight: bold; font-style: normal; } @font-face { font-family: 'Gibson'; src: url('Gibson-Italic-webfonteccb.eot?3'); src: url('Gibson-Italic-webfont95c6.eot?3?#iefix') format('embedded-opentype'), url('Gibson-Italic-webfonteccb.woff?3') format('woff'), url('Gibson-Italic-webfonteccb.ttf?3') format('truetype'), url('Gibson-Italic-webfonteccb.svg?3#GibsonItalic') format('svg'); font-weight: normal; font-style: italic; } @font-face { font-family: 'Gibson'; src: url('Gibson-SemiBoldItalic-webfonteccb.eot?3'); src: url('Gibson-SemiBoldItalic-webfont95c6.eot?3?#iefix') format('embedded-opentype'), url('Gibson-SemiBoldItalic-webfonteccb.woff?3') format('woff'), url('Gibson-SemiBoldItalic-webfonteccb.ttf?3') format('truetype'), url('Gibson-SemiBoldItalic-webfonteccb.svg?3#GibsonLightBoldItalic') format('svg'); font-weight: bold; font-style: italic; }
{'content_hash': 'bd9f355eb65887e58b65fbec28cf3d3e', 'timestamp': '', 'source': 'github', 'line_count': 49, 'max_line_length': 92, 'avg_line_length': 36.83673469387755, 'alnum_prop': 0.6648199445983379, 'repo_name': 'misfit-inc/christian-aid.tumblr.com', 'id': '15c001cc33fd7109a9ad228770f6ea365fb90288', 'size': '2510', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'assets.tumblr.com/fonts/gibson/stylesheet30f4.css', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'CSS', 'bytes': '10704'}, {'name': 'HTML', 'bytes': '1262319'}, {'name': 'JavaScript', 'bytes': '9898'}]}
'use strict'; module.exports = function(grunt) { var path = require('path'); // These plugins provide necessary tasks. grunt.loadNpmTasks('grunt-contrib-clean'); grunt.loadNpmTasks('grunt-execute'); grunt.loadNpmTasks('amber-dev'); // Default task. grunt.registerTask('default', ['amberc:all']); grunt.registerTask('test', ['amberc:test_runner', 'execute:test_runner', 'clean:test_runner']); // Project configuration. grunt.initConfig({ // Metadata. // pkg: grunt.file.readJSON(''), banner: '\n', // task configuration amberc: { options: { amber_dir: path.join(__dirname, "bower_components", "amber"), library_dirs: ['src'], closure_jar: '' }, all: { src: [ 'src/Ephestos.st', // list all sources in dependency order 'src/Ephestos-Tests.st' // list all tests in dependency order ], libraries: ['SUnit', 'Web'] }, test_runner: { src: ['node_modules/amber-dev/lib/Test.st'], libraries: [ /* add dependencies packages here */ 'Ephestos', /* add other code-to-test packages here */ 'SUnit', 'Ephestos-Tests' /* add other test packages here */ ], main_class: 'NodeTestRunner', output_name: 'test_runner' } }, execute: { test_runner: { src: ['test_runner.js'] } }, clean: { test_runner: ['test_runner.js'] } }); };
{'content_hash': '6ae6eab05c0d2e174522c78463418475', 'timestamp': '', 'source': 'github', 'line_count': 58, 'max_line_length': 97, 'avg_line_length': 25.724137931034484, 'alnum_prop': 0.5542895442359249, 'repo_name': 'kilon/kilon.github.io', 'id': 'a3797e28081e40fec8d0b675f874182ec2219064', 'size': '1825', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'Gruntfile.js', 'mode': '33188', 'license': 'mit', 'language': []}
<?php /* @var $this yii\web\View */ $this->title = 'My Yii Application'; ?> <div class="site-index"> <div class="jumbotron"> <h1>Congratulations!</h1> <p class="lead">You have successfully created your Yii-powered application.</p> </div> </div>
{'content_hash': 'eec7c207a925fa937ac1045201d69527', 'timestamp': '', 'source': 'github', 'line_count': 10, 'max_line_length': 87, 'avg_line_length': 26.9, 'alnum_prop': 0.6171003717472119, 'repo_name': 'yii2mod/base', 'id': '3d904c16d68b0a44751baa95554dea150992ecbc', 'size': '269', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'views/site/index.php', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'Batchfile', 'bytes': '1548'}, {'name': 'CSS', 'bytes': '3695'}, {'name': 'Dockerfile', 'bytes': '3682'}, {'name': 'PHP', 'bytes': '94078'}, {'name': 'Shell', 'bytes': '512'}]}
const adjetiveisor = require('../adjetiveisor') const adjet = adjetiveisor() test('fails if no configured', () => { expect(adjet.translate('any text')).toBe('missing config') }) test('fails if no text string provided', () => { adjet.config({ ms: 'puto', mp: 'putos', fs: 'puta', fp: 'putas' }) expect(adjet.translate()).toBe('missing text') }) test('translates "perro" into "puto perro"', () => { adjet.config({ ms: 'puto', mp: 'putos', fs: 'puta', fp: 'putas' }) expect(adjet.translate('perro')).toBe('puto perro') }) test('translates "el coche" into "el puto coche"', () => { adjet.config({ ms: 'puto', mp: 'putos', fs: 'puta', fp: 'putas' }) expect(adjet.translate('el coche')).toBe('el puto coche') }) test('does a correct translation on verbose config provided', () => { adjet.config({ ms: 'puto', mp: 'putos', fs: 'puta', fp: 'putas' }) expect(adjet.translate('tengo mi coche en la acera')).toBe('tengo mi coche en la puta acera') adjet.verbose(true) expect(adjet.translate('tengo mi coche en la acera')).toBe('tengo mi puto coche en la puta acera') adjet.verbose(false) }) test('removes duplicates', () => { adjet.config({ ms: 'puto', mp: 'putos', fs: 'puta', fp: 'putas' }) expect(adjet.translate('el puto coche')).toBe('el puto coche') })
{'content_hash': '4875906a4160bcd8f2833714fe9607ad', 'timestamp': '', 'source': 'github', 'line_count': 34, 'max_line_length': 100, 'avg_line_length': 37.705882352941174, 'alnum_prop': 0.6380655226209049, 'repo_name': 'agm-dev/adjetiveisor', 'id': 'ade984308d3e6e02a4f9e699dfa6979f309c9e19', 'size': '1282', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'tests/adjetiveisor.translate.test.js', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'JavaScript', 'bytes': '7789'}]}
<!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_07) on Tue Sep 01 20:57:03 UTC 2009 --> <TITLE> Uses of Package org.apache.hadoop.filecache (Hadoop 0.20.1 API) </TITLE> <META NAME="date" CONTENT="2009-09-01"> <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 Package org.apache.hadoop.filecache (Hadoop 0.20.1 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"> <FONT CLASS="NavBarFont1">Class</FONT>&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/filecache/package-use.html" target="_top"><B>FRAMES</B></A> &nbsp; &nbsp;<A HREF="package-use.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 Package<br>org.apache.hadoop.filecache</B></H2> </CENTER> No usage of org.apache.hadoop.filecache <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"> <FONT CLASS="NavBarFont1">Class</FONT>&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/filecache/package-use.html" target="_top"><B>FRAMES</B></A> &nbsp; &nbsp;<A HREF="package-use.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': 'b019fc25bda3971a256ed43e89d206c1', 'timestamp': '', 'source': 'github', 'line_count': 144, 'max_line_length': 156, 'avg_line_length': 39.13194444444444, 'alnum_prop': 0.6181011535048803, 'repo_name': 'koichi626/hadoop-gpu', 'id': '027df7797038f37992cd3323f928f58bfd29bf24', 'size': '5635', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'hadoop-gpu-0.20.1/docs/api/org/apache/hadoop/filecache/package-use.html', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'C', 'bytes': '285734'}, {'name': 'C++', 'bytes': '417284'}, {'name': 'CSS', 'bytes': '104496'}, {'name': 'Java', 'bytes': '10388425'}, {'name': 'JavaScript', 'bytes': '82001'}, {'name': 'Objective-C', 'bytes': '118273'}, {'name': 'PHP', 'bytes': '152555'}, {'name': 'Perl', 'bytes': '149888'}, {'name': 'Python', 'bytes': '1530597'}, {'name': 'Ruby', 'bytes': '28485'}, {'name': 'Shell', 'bytes': '1204612'}, {'name': 'Smalltalk', 'bytes': '56562'}, {'name': 'XSLT', 'bytes': '235055'}]}
(function (window) { "use strict"; var console = window.console, $ = window.jQuery, gui = window.gui, old = $.fn.guiNav; $.fn.guiNav = function (option) { var defaults = { styleName: "", itemFadeIn: true, animationDuration: 500 }; option = $.extend(defaults, option); this.each(function () { var $guiNav = $(this), isVertical = $guiNav.hasClass("gui-nav-vertical"); if (option.styleName) { $guiNav.addClass(option.styleName); } $guiNav.find("li").mouseenter(function () { var $navItem = $(this), $$subMenu = $navItem.children("ul"); $$subMenu.css("left", (isVertical || !$navItem.parent().hasClass("gui-nav")) ? $navItem.width() : 0); if (option.itemFadeIn) { $$subMenu.css("opacity", 0).animate({opacity: 1}, option.animationDuration); } }); }); return gui.plugin.patch($.fn.guiNav, this, option); }; // NO CONFLICT // =============== $.fn.guiNav.noConflict = function () { $.fn.guiNav = old; return this; }; })(window);
{'content_hash': '101bebbb7dc359e5190ee1bb2942b612', 'timestamp': '', 'source': 'github', 'line_count': 50, 'max_line_length': 117, 'avg_line_length': 26.74, 'alnum_prop': 0.45100972326103217, 'repo_name': 'guoyao/gui', 'id': 'cf987cb15a632390a70d584f0706451db0184477', 'size': '2217', 'binary': False, 'copies': '1', 'ref': 'refs/heads/dev', 'path': 'js/nav.js', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'CSS', 'bytes': '140927'}, {'name': 'HTML', 'bytes': '108325'}, {'name': 'JavaScript', 'bytes': '295996'}]}
<html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>Function template wrap_formatter</title> <link rel="stylesheet" href="../../../../../../../doc/src/boostbook.css" type="text/css"> <meta name="generator" content="DocBook XSL Stylesheets V1.79.1"> <link rel="home" href="../../../index.html" title="Chapter 1. Boost.Log v2"> <link rel="up" href="../../../expressions.html#header.boost.log.expressions.formatters.wrap_formatter_hpp" title="Header &lt;boost/log/expressions/formatters/wrap_formatter.hpp&gt;"> <link rel="prev" href="wrapped_formatter_terminal.html" title="Class template wrapped_formatter_terminal"> <link rel="next" href="wrap_for_idm45961920535920.html" title="Function template wrap_formatter"> </head> <body bgcolor="white" text="black" link="#0000FF" vlink="#840084" alink="#0000FF"> <table cellpadding="2" width="100%"><tr><td valign="top"><img alt="Boost C++ Libraries" width="277" height="86" src="../../../../../../../boost.png"></td></tr></table> <hr> <div class="spirit-nav"> <a accesskey="p" href="wrapped_formatter_terminal.html"><img src="../../../../../../../doc/src/images/prev.png" alt="Prev"></a><a accesskey="u" href="../../../expressions.html#header.boost.log.expressions.formatters.wrap_formatter_hpp"><img src="../../../../../../../doc/src/images/up.png" alt="Up"></a><a accesskey="h" href="../../../index.html"><img src="../../../../../../../doc/src/images/home.png" alt="Home"></a><a accesskey="n" href="wrap_for_idm45961920535920.html"><img src="../../../../../../../doc/src/images/next.png" alt="Next"></a> </div> <div class="refentry"> <a name="boost.log.expressions.wrap_for_idm45961920540112"></a><div class="titlepage"></div> <div class="refnamediv"> <h2><span class="refentrytitle">Function template wrap_formatter</span></h2> <p>boost::log::expressions::wrap_formatter</p> </div> <h2 xmlns:rev="http://www.cs.rpi.edu/~gregod/boost/tools/doc/revision" class="refsynopsisdiv-title">Synopsis</h2> <div xmlns:rev="http://www.cs.rpi.edu/~gregod/boost/tools/doc/revision" class="refsynopsisdiv"><pre class="synopsis"><span class="comment">// In header: &lt;<a class="link" href="../../../expressions.html#header.boost.log.expressions.formatters.wrap_formatter_hpp" title="Header &lt;boost/log/expressions/formatters/wrap_formatter.hpp&gt;">boost/log/expressions/formatters/wrap_formatter.hpp</a>&gt; </span> <span class="keyword">template</span><span class="special">&lt;</span><span class="keyword">typename</span> FunT<span class="special">&gt;</span> <span class="emphasis"><em><span class="identifier">unspecified</span></em></span> <span class="identifier">wrap_formatter</span><span class="special">(</span><span class="identifier">FunT</span> <span class="keyword">const</span> <span class="special">&amp;</span> fun<span class="special">)</span><span class="special">;</span></pre></div> <div class="refsect1"> <a name="idm46846468567072"></a><h2>Description</h2> <p>The function wraps a function object in order it to be able to participate in formatting expressions. The wrapped function object must be compatible with the following signature:</p> <pre class="programlisting"> void (record_view const&amp;, basic_formatting_ostream&lt; CharT &gt;&amp;) </pre> <p>where <code class="computeroutput">CharT</code> is the character type of the formatting expression. </p> </div> </div> <table xmlns:rev="http://www.cs.rpi.edu/~gregod/boost/tools/doc/revision" width="100%"><tr> <td align="left"></td> <td align="right"><div class="copyright-footer">Copyright © 2007-2021 Andrey Semashev<p> Distributed under the Boost Software License, Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at <a href="http://www.boost.org/LICENSE_1_0.txt" target="_top">http://www.boost.org/LICENSE_1_0.txt</a>). </p> </div></td> </tr></table> <hr> <div class="spirit-nav"> <a accesskey="p" href="wrapped_formatter_terminal.html"><img src="../../../../../../../doc/src/images/prev.png" alt="Prev"></a><a accesskey="u" href="../../../expressions.html#header.boost.log.expressions.formatters.wrap_formatter_hpp"><img src="../../../../../../../doc/src/images/up.png" alt="Up"></a><a accesskey="h" href="../../../index.html"><img src="../../../../../../../doc/src/images/home.png" alt="Home"></a><a accesskey="n" href="wrap_for_idm45961920535920.html"><img src="../../../../../../../doc/src/images/next.png" alt="Next"></a> </div> </body> </html>
{'content_hash': 'feffd92c47b26b0afdf26644c80f5050', 'timestamp': '', 'source': 'github', 'line_count': 51, 'max_line_length': 545, 'avg_line_length': 87.07843137254902, 'alnum_prop': 0.6784507993695114, 'repo_name': 'davehorton/drachtio-server', 'id': '9a4899bacfee34cdf62ede15e93f4c5561f805d0', 'size': '4444', 'binary': False, 'copies': '1', 'ref': 'refs/heads/main', 'path': 'deps/boost_1_77_0/libs/log/doc/html/boost/log/expressions/wrap_for_idm45961920540112.html', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'C++', 'bytes': '662596'}, {'name': 'Dockerfile', 'bytes': '1330'}, {'name': 'JavaScript', 'bytes': '60639'}, {'name': 'M4', 'bytes': '35273'}, {'name': 'Makefile', 'bytes': '5960'}, {'name': 'Shell', 'bytes': '47298'}]}
class Profile; class WebRequestPermissions; namespace extension_web_request_api_helpers { struct EventResponseDelta; } namespace net { class URLRequest; } namespace extensions { class RulesRegistryService; typedef linked_ptr<extension_web_request_api_helpers::EventResponseDelta> LinkedPtrEventResponseDelta; typedef DeclarativeRule<WebRequestCondition, WebRequestAction> WebRequestRule; // The WebRequestRulesRegistry is responsible for managing // the internal representation of rules for the Declarative Web Request API. // // Here is the high level overview of this functionality: // // RulesRegistry::Rule consists of Conditions and Actions, these are // represented as a WebRequestRule with WebRequestConditions and // WebRequestRuleActions. // // WebRequestConditions represent JSON dictionaries as the following: // { // 'instanceType': 'URLMatcher', // 'host_suffix': 'example.com', // 'path_prefix': '/query', // 'scheme': 'http' // } // // The evaluation of URL related condition attributes (host_suffix, path_prefix) // is delegated to a URLMatcher, because this is capable of evaluating many // of such URL related condition attributes in parallel. // // For this, the URLRequestCondition has a URLMatcherConditionSet, which // represents the {'host_suffix': 'example.com', 'path_prefix': '/query'} part. // We will then ask the URLMatcher, whether a given URL // "http://www.example.com/query/" has any matches, and the URLMatcher // will respond with the URLMatcherConditionSet::ID. We can map this // to the WebRequestRule and check whether also the other conditions (in this // example 'scheme': 'http') are fulfilled. class WebRequestRulesRegistry : public RulesRegistryWithCache { public: WebRequestRulesRegistry(Profile* profile, Delegate* delegate); // TODO(battre): This will become an implementation detail, because we need // a way to also execute the actions of the rules. std::set<const WebRequestRule*> GetMatches( const WebRequestData& request_data_without_ids) const; // Returns which modifications should be executed on the network request // according to the rules registered in this registry. std::list<LinkedPtrEventResponseDelta> CreateDeltas( const ExtensionInfoMap* extension_info_map, const WebRequestData& request_data, bool crosses_incognito); // Implementation of RulesRegistryWithCache: virtual std::string AddRulesImpl( const std::string& extension_id, const std::vector<linked_ptr<RulesRegistry::Rule> >& rules) OVERRIDE; virtual std::string RemoveRulesImpl( const std::string& extension_id, const std::vector<std::string>& rule_identifiers) OVERRIDE; virtual std::string RemoveAllRulesImpl( const std::string& extension_id) OVERRIDE; virtual content::BrowserThread::ID GetOwnerThread() const OVERRIDE; // Returns true if this object retains no allocated data. Only for debugging. bool IsEmpty() const; protected: virtual ~WebRequestRulesRegistry(); // Virtual for testing: virtual base::Time GetExtensionInstallationTime( const std::string& extension_id) const; virtual void ClearCacheOnNavigation(); const std::set<const WebRequestRule*>& rules_with_untriggered_conditions_for_test() const { return rules_with_untriggered_conditions_; } private: // Checks whether the set of |conditions| and |actions| are consistent, // meaning for example that we do not allow combining an |action| that needs // to be executed before the |condition| can be fulfilled. // Returns true in case of consistency and MUST set |error| otherwise. static bool CheckConsistency(const WebRequestConditionSet* conditions, const WebRequestActionSet* actions, std::string* error); typedef std::map<URLMatcherConditionSet::ID, WebRequestRule*> RuleTriggers; typedef std::map<WebRequestRule::GlobalRuleId, linked_ptr<WebRequestRule> > RulesMap; typedef std::set<URLMatcherConditionSet::ID> URLMatches; typedef std::set<const WebRequestRule*> RuleSet; // This is a helper function to GetMatches. Rules triggered by |url_matches| // get added to |result| if one of their conditions is fulfilled. // |request_data| gets passed to IsFulfilled of the rules' condition sets. void AddTriggeredRules(const URLMatches& url_matches, const WebRequestCondition::MatchData& request_data, RuleSet* result) const; // Map that tells us which WebRequestRule may match under the condition that // the URLMatcherConditionSet::ID was returned by the |url_matcher_|. RuleTriggers rule_triggers_; // These rules contain condition sets with conditions without URL attributes. // Such conditions are not triggered by URL matcher, so we need to test them // separately. std::set<const WebRequestRule*> rules_with_untriggered_conditions_; RulesMap webrequest_rules_; URLMatcher url_matcher_; scoped_refptr<ExtensionInfoMap> extension_info_map_; DISALLOW_COPY_AND_ASSIGN(WebRequestRulesRegistry); }; } // namespace extensions #endif // CHROME_BROWSER_EXTENSIONS_API_DECLARATIVE_WEBREQUEST_WEBREQUEST_RULES_REGISTRY_H_
{'content_hash': 'bf00411bb01aa5467efb197fa4de3560', 'timestamp': '', 'source': 'github', 'line_count': 133, 'max_line_length': 92, 'avg_line_length': 39.2406015037594, 'alnum_prop': 0.7432458325349683, 'repo_name': 'timopulkkinen/BubbleFish', 'id': '4924522bb78300abd92423ec10cb8666ed7a5687', 'size': '6263', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'chrome/browser/extensions/api/declarative_webrequest/webrequest_rules_registry.h', 'mode': '33188', 'license': 'bsd-3-clause', 'language': [{'name': 'ASP', 'bytes': '853'}, {'name': 'AppleScript', 'bytes': '6973'}, {'name': 'Arduino', 'bytes': '464'}, {'name': 'Assembly', 'bytes': '1174304'}, {'name': 'Awk', 'bytes': '9519'}, {'name': 'C', 'bytes': '75801820'}, {'name': 'C#', 'bytes': '1132'}, {'name': 'C++', 'bytes': '161884021'}, {'name': 'DOT', 'bytes': '1559'}, {'name': 'F#', 'bytes': '381'}, {'name': 'Java', 'bytes': '3531849'}, {'name': 'JavaScript', 'bytes': '18556005'}, {'name': 'Logos', 'bytes': '4517'}, {'name': 'Matlab', 'bytes': '5234'}, {'name': 'Objective-C', 'bytes': '7254742'}, {'name': 'PHP', 'bytes': '97817'}, {'name': 'Perl', 'bytes': '933011'}, {'name': 'Python', 'bytes': '8808682'}, {'name': 'R', 'bytes': '262'}, {'name': 'Ragel in Ruby Host', 'bytes': '3621'}, {'name': 'Shell', 'bytes': '1537764'}, {'name': 'Tcl', 'bytes': '277077'}, {'name': 'XML', 'bytes': '13493'}]}
package org.shaf.core.net; /** * The {@code NetworkRequestException} occurs, when a network request is failed. * * @author Mykola Galushka */ @SuppressWarnings("serial") public class NetworkRequestException extends NetworkException { /** * Constructs a new {@code NetworkRequestException} object. * * @param uri * the requesting URI. * @param message * the message. * @param cause * the cause. */ public NetworkRequestException(final String message, final Throwable cause) { super(message, cause); } /** * Constructs a new {@code NetworkRequestException} object. * * @param uri * the requesting URI. * @param message * the message. */ public NetworkRequestException(final String message) { super(message); } }
{'content_hash': '79555e6e14dddb14edd13e9a219ba929', 'timestamp': '', 'source': 'github', 'line_count': 37, 'max_line_length': 80, 'avg_line_length': 22.10810810810811, 'alnum_prop': 0.6466992665036675, 'repo_name': 'SHAF-WORK/shaf', 'id': 'e57e8ee2e98293a57862513b141ca45cb3b5a4e2', 'size': '1419', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'core/src/main/java/org/shaf/core/net/NetworkRequestException.java', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'CSS', 'bytes': '9550'}, {'name': 'Java', 'bytes': '1471340'}, {'name': 'JavaScript', 'bytes': '7370'}, {'name': 'Shell', 'bytes': '6433'}]}
import { isStandardRule, ruleMessages, validateOptions, } from "../../utils" import { checkRuleEmptyLineBefore } from "../rule-non-nested-empty-line-before" export const ruleName = "rule-nested-empty-line-before" export const messages = ruleMessages(ruleName, { expected: "Expected empty line before nested rule", rejected: "Unexpected empty line before nested rule", }) export default function (expectation, options) { return (root, result) => { const validOptions = validateOptions(result, ruleName, { actual: expectation, possible: [ "always", "never", "always-multi-line", "never-multi-line", ], }, { actual: options, possible: { ignore: [ "after-comment", ], except: [ "first-nested", "after-comment", ], }, optional: true, }) if (!validOptions) { return } root.walkRules(rule => { if (!isStandardRule(rule)) { return } // Only attend to nested rule sets if (rule.parent === root) { return } checkRuleEmptyLineBefore({ rule, expectation, options, result, messages, checkedRuleName: ruleName }) }) } }
{'content_hash': 'f0873fad287901f884dbe4f7b4f2b3d2', 'timestamp': '', 'source': 'github', 'line_count': 51, 'max_line_length': 107, 'avg_line_length': 23.764705882352942, 'alnum_prop': 0.5981848184818482, 'repo_name': 'mghak/mghak.github.io', 'id': '191908c03054357f2f7cafdf91b9964ffc3da2f9', 'size': '1212', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'node_modules/stylelint/src/rules/rule-nested-empty-line-before/index.js', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'CSS', 'bytes': '4176'}, {'name': 'HTML', 'bytes': '11740'}, {'name': 'JavaScript', 'bytes': '7882'}, {'name': 'TypeScript', 'bytes': '17729'}]}
function legcoeffs = chebcoeffs2legcoeffs(chebcoeffs) %CHEBCOEFFS2LEGCOEFFS Convert Chebyshev coefficients to Legendre coefficients. % C_LEG = CHEBCOEFFS2LEGCOEFFS(C_CHEB) converts the vector C_CHEB of Chebyshev % coefficients to a vector C_LEG of Legendre coefficients such that % C_CHEB(1)*T0 + ... + C_CHEB(N)*T{N-1} = ... % C_LEG(1)*P0 + ... + C_LEG(N)*P{N-1}, % where P{k} is the degree k Legendre polynomial normalized so that % max(|P{k}|) = 1. % % See also CHEB2LEG. % Copyright 2015 by The University of Oxford and The Chebfun Developers. % See http://www.chebfun.org/ for Chebfun information. % This command is a wrapper for cheb2leg. legcoeffs = cheb2leg(chebcoeffs); end
{'content_hash': '2952e6cda1f4e67758632734aad5dcc2', 'timestamp': '', 'source': 'github', 'line_count': 18, 'max_line_length': 80, 'avg_line_length': 39.666666666666664, 'alnum_prop': 0.7030812324929971, 'repo_name': 'ilovejs/chebfun', 'id': 'a3b83c9abd4154977274148e91047a878fe1215a', 'size': '714', 'binary': False, 'copies': '1', 'ref': 'refs/heads/development', 'path': 'chebcoeffs2legcoeffs.m', 'mode': '33188', 'license': 'bsd-3-clause', 'language': [{'name': 'M', 'bytes': '2040'}, {'name': 'Matlab', 'bytes': '4427792'}]}
package org.apache.hadoop.hive.ql; import org.apache.commons.io.FileUtils; import org.apache.hadoop.fs.FileUtil; import org.apache.hadoop.fs.Path; import org.apache.hadoop.hive.conf.HiveConf; import org.apache.hadoop.hive.metastore.txn.TxnDbUtil; import org.apache.hadoop.hive.ql.io.AcidUtils; import org.apache.hadoop.hive.ql.io.orc.FileDump; import org.apache.hadoop.hive.ql.processors.CommandProcessorResponse; import org.apache.hadoop.hive.ql.session.SessionState; import org.junit.After; import org.junit.Assert; import org.junit.Before; import org.junit.Ignore; import org.junit.Rule; import org.junit.Test; import org.junit.rules.TestName; import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.FilenameFilter; import java.util.ArrayList; import java.util.Arrays; import java.util.Comparator; import java.util.List; /** * TODO: this should be merged with TestTxnCommands once that is checked in * specifically the tests; the supporting code here is just a clone of TestTxnCommands */ public class TestTxnCommands2 { private static final String TEST_DATA_DIR = new File(System.getProperty("java.io.tmpdir") + File.separator + TestTxnCommands2.class.getCanonicalName() + "-" + System.currentTimeMillis() ).getPath().replaceAll("\\\\", "/"); private static final String TEST_WAREHOUSE_DIR = TEST_DATA_DIR + "/warehouse"; //bucket count for test tables; set it to 1 for easier debugging private static int BUCKET_COUNT = 2; @Rule public TestName testName = new TestName(); private HiveConf hiveConf; private Driver d; private static enum Table { ACIDTBL("acidTbl"), ACIDTBLPART("acidTblPart"), NONACIDORCTBL("nonAcidOrcTbl"), NONACIDPART("nonAcidPart"); private final String name; @Override public String toString() { return name; } Table(String name) { this.name = name; } } @Before public void setUp() throws Exception { tearDown(); hiveConf = new HiveConf(this.getClass()); hiveConf.set(HiveConf.ConfVars.PREEXECHOOKS.varname, ""); hiveConf.set(HiveConf.ConfVars.POSTEXECHOOKS.varname, ""); hiveConf.set(HiveConf.ConfVars.HIVE_SUPPORT_CONCURRENCY.varname, "false"); hiveConf.set(HiveConf.ConfVars.METASTOREWAREHOUSE.varname, TEST_WAREHOUSE_DIR); TxnDbUtil.setConfValues(hiveConf); hiveConf.setBoolVar(HiveConf.ConfVars.HIVEENFORCEBUCKETING, true); TxnDbUtil.prepDb(); File f = new File(TEST_WAREHOUSE_DIR); if (f.exists()) { FileUtil.fullyDelete(f); } if (!(new File(TEST_WAREHOUSE_DIR).mkdirs())) { throw new RuntimeException("Could not create " + TEST_WAREHOUSE_DIR); } SessionState.start(new SessionState(hiveConf)); d = new Driver(hiveConf); dropTables(); runStatementOnDriver("create table " + Table.ACIDTBL + "(a int, b int) clustered by (a) into " + BUCKET_COUNT + " buckets stored as orc TBLPROPERTIES ('transactional'='true')"); runStatementOnDriver("create table " + Table.ACIDTBLPART + "(a int, b int) partitioned by (p string) clustered by (a) into " + BUCKET_COUNT + " buckets stored as orc TBLPROPERTIES ('transactional'='true')"); runStatementOnDriver("create table " + Table.NONACIDORCTBL + "(a int, b int) clustered by (a) into " + BUCKET_COUNT + " buckets stored as orc TBLPROPERTIES ('transactional'='false')"); runStatementOnDriver("create table " + Table.NONACIDPART + "(a int, b int) partitioned by (p string) stored as orc TBLPROPERTIES ('transactional'='false')"); } private void dropTables() throws Exception { for(Table t : Table.values()) { runStatementOnDriver("drop table if exists " + t); } } @After public void tearDown() throws Exception { try { if (d != null) { // runStatementOnDriver("set autocommit true"); dropTables(); d.destroy(); d.close(); d = null; } TxnDbUtil.cleanDb(); } finally { FileUtils.deleteDirectory(new File(TEST_DATA_DIR)); } } @Ignore("not needed but useful for testing") @Test public void testNonAcidInsert() throws Exception { runStatementOnDriver("insert into " + Table.NONACIDORCTBL + " values(1,2)"); List<String> rs = runStatementOnDriver("select a,b from " + Table.NONACIDORCTBL); runStatementOnDriver("insert into " + Table.NONACIDORCTBL + " values(2,3)"); List<String> rs1 = runStatementOnDriver("select a,b from " + Table.NONACIDORCTBL); } @Test public void testUpdateMixedCase() throws Exception { int[][] tableData = {{1,2},{3,3},{5,3}}; runStatementOnDriver("insert into " + Table.ACIDTBL + " " + makeValuesClause(tableData)); runStatementOnDriver("update " + Table.ACIDTBL + " set B = 7 where A=1"); List<String> rs = runStatementOnDriver("select a,b from " + Table.ACIDTBL + " order by a,b"); int[][] updatedData = {{1,7},{3,3},{5,3}}; Assert.assertEquals("Update failed", stringifyValues(updatedData), rs); runStatementOnDriver("update " + Table.ACIDTBL + " set B = B + 1 where A=1"); List<String> rs2 = runStatementOnDriver("select a,b from " + Table.ACIDTBL + " order by a,b"); int[][] updatedData2 = {{1,8},{3,3},{5,3}}; Assert.assertEquals("Update failed", stringifyValues(updatedData2), rs2); } /** * https://issues.apache.org/jira/browse/HIVE-10151 */ @Test public void testBucketizedInputFormat() throws Exception { int[][] tableData = {{1,2}}; runStatementOnDriver("insert into " + Table.ACIDTBLPART + " partition(p=1) " + makeValuesClause(tableData)); runStatementOnDriver("insert into " + Table.ACIDTBL + " select a,b from " + Table.ACIDTBLPART + " where p = 1"); List<String> rs = runStatementOnDriver("select a,b from " + Table.ACIDTBL);//no order by as it's just 1 row Assert.assertEquals("Insert into " + Table.ACIDTBL + " didn't match:", stringifyValues(tableData), rs); runStatementOnDriver("insert into " + Table.NONACIDORCTBL + " select a,b from " + Table.ACIDTBLPART + " where p = 1"); List<String> rs2 = runStatementOnDriver("select a,b from " + Table.NONACIDORCTBL);//no order by as it's just 1 row Assert.assertEquals("Insert into " + Table.NONACIDORCTBL + " didn't match:", stringifyValues(tableData), rs2); } @Test public void testInsertOverwriteWithSelfJoin() throws Exception { int[][] part1Data = {{1,7}}; runStatementOnDriver("insert into " + Table.NONACIDORCTBL + " " + makeValuesClause(part1Data)); //this works because logically we need S lock on NONACIDORCTBL to read and X lock to write, but //LockRequestBuilder dedups locks on the same entity to only keep the highest level lock requested runStatementOnDriver("insert overwrite table " + Table.NONACIDORCTBL + " select 2, 9 from " + Table.NONACIDORCTBL + " T inner join " + Table.NONACIDORCTBL + " S on T.a=S.a"); List<String> rs = runStatementOnDriver("select a,b from " + Table.NONACIDORCTBL + " order by a,b"); int[][] joinData = {{2,9}}; Assert.assertEquals("Self join non-part insert overwrite failed", stringifyValues(joinData), rs); int[][] part2Data = {{1,8}}; runStatementOnDriver("insert into " + Table.NONACIDPART + " partition(p=1) " + makeValuesClause(part1Data)); runStatementOnDriver("insert into " + Table.NONACIDPART + " partition(p=2) " + makeValuesClause(part2Data)); //here we need X lock on p=1 partition to write and S lock on 'table' to read which should //not block each other since they are part of the same txn runStatementOnDriver("insert overwrite table " + Table.NONACIDPART + " partition(p=1) select a,b from " + Table.NONACIDPART); List<String> rs2 = runStatementOnDriver("select a,b from " + Table.NONACIDPART + " order by a,b"); int[][] updatedData = {{1,7},{1,8},{1,8}}; Assert.assertEquals("Insert overwrite partition failed", stringifyValues(updatedData), rs2); //insert overwrite not supported for ACID tables } /** * takes raw data and turns it into a string as if from Driver.getResults() * sorts rows in dictionary order */ private List<String> stringifyValues(int[][] rowsIn) { assert rowsIn.length > 0; int[][] rows = rowsIn.clone(); Arrays.sort(rows, new RowComp()); List<String> rs = new ArrayList<String>(); for(int[] row : rows) { assert row.length > 0; StringBuilder sb = new StringBuilder(); for(int value : row) { sb.append(value).append("\t"); } sb.setLength(sb.length() - 1); rs.add(sb.toString()); } return rs; } private static final class RowComp implements Comparator<int[]> { public int compare(int[] row1, int[] row2) { assert row1 != null && row2 != null && row1.length == row2.length; for(int i = 0; i < row1.length; i++) { int comp = Integer.compare(row1[i], row2[i]); if(comp != 0) { return comp; } } return 0; } } private String makeValuesClause(int[][] rows) { assert rows.length > 0; StringBuilder sb = new StringBuilder("values"); for(int[] row : rows) { assert row.length > 0; if(row.length > 1) { sb.append("("); } for(int value : row) { sb.append(value).append(","); } sb.setLength(sb.length() - 1);//remove trailing comma if(row.length > 1) { sb.append(")"); } sb.append(","); } sb.setLength(sb.length() - 1);//remove trailing comma return sb.toString(); } private List<String> runStatementOnDriver(String stmt) throws Exception { CommandProcessorResponse cpr = d.run(stmt); if(cpr.getResponseCode() != 0) { throw new RuntimeException(stmt + " failed: " + cpr); } List<String> rs = new ArrayList<String>(); d.getResults(rs); return rs; } }
{'content_hash': '541e6d1ecc891126cfff3837c3572516', 'timestamp': '', 'source': 'github', 'line_count': 228, 'max_line_length': 211, 'avg_line_length': 43.04385964912281, 'alnum_prop': 0.6719991848379866, 'repo_name': 'wangbin83-gmail-com/hive-1.1.0-cdh5.4.8', 'id': 'f5140c4b69d6e49690209c029dbd9665b33096dd', 'size': '9814', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'ql/src/test/org/apache/hadoop/hive/ql/TestTxnCommands2.java', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'Batchfile', 'bytes': '48158'}, {'name': 'C', 'bytes': '120921'}, {'name': 'C++', 'bytes': '163950'}, {'name': 'CSS', 'bytes': '1372'}, {'name': 'GAP', 'bytes': '117068'}, {'name': 'Groff', 'bytes': '5379'}, {'name': 'HTML', 'bytes': '22057'}, {'name': 'Java', 'bytes': '24439585'}, {'name': 'M', 'bytes': '2173'}, {'name': 'Makefile', 'bytes': '6963'}, {'name': 'PHP', 'bytes': '1717937'}, {'name': 'PLpgSQL', 'bytes': '43781'}, {'name': 'Perl', 'bytes': '316328'}, {'name': 'PigLatin', 'bytes': '12333'}, {'name': 'Protocol Buffer', 'bytes': '6353'}, {'name': 'Python', 'bytes': '268109'}, {'name': 'SQLPL', 'bytes': '1414'}, {'name': 'Shell', 'bytes': '152105'}, {'name': 'Thrift', 'bytes': '93411'}, {'name': 'XSLT', 'bytes': '7619'}]}
"use strict"; var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { if (k2 === undefined) k2 = k; Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } }); }) : (function(o, m, k, k2) { if (k2 === undefined) k2 = k; o[k2] = m[k]; })); var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { Object.defineProperty(o, "default", { enumerable: true, value: v }); }) : function(o, v) { o["default"] = v; }); var __importStar = (this && this.__importStar) || function (mod) { if (mod && mod.__esModule) return mod; var result = {}; if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); __setModuleDefault(result, mod); return result; }; Object.defineProperty(exports, "__esModule", { value: true }); const ts = __importStar(require("typescript")); const experimental_utils_1 = require("@typescript-eslint/experimental-utils"); const tsutils = __importStar(require("tsutils")); const util = __importStar(require("../util")); const FUNCTION_CONSTRUCTOR = 'Function'; const GLOBAL_CANDIDATES = new Set(['global', 'window', 'globalThis']); const EVAL_LIKE_METHODS = new Set([ 'setImmediate', 'setInterval', 'setTimeout', 'execScript', ]); exports.default = util.createRule({ name: 'no-implied-eval', meta: { docs: { description: 'Disallow the use of `eval()`-like methods', category: 'Best Practices', recommended: 'error', extendsBaseRule: true, requiresTypeChecking: true, }, messages: { noImpliedEvalError: 'Implied eval. Consider passing a function.', noFunctionConstructor: 'Implied eval. Do not use the Function constructor to create functions.', }, schema: [], type: 'suggestion', }, defaultOptions: [], create(context) { const parserServices = util.getParserServices(context); const program = parserServices.program; const checker = parserServices.program.getTypeChecker(); function getCalleeName(node) { if (node.type === experimental_utils_1.AST_NODE_TYPES.Identifier) { return node.name; } if (node.type === experimental_utils_1.AST_NODE_TYPES.MemberExpression && node.object.type === experimental_utils_1.AST_NODE_TYPES.Identifier && GLOBAL_CANDIDATES.has(node.object.name)) { if (node.property.type === experimental_utils_1.AST_NODE_TYPES.Identifier) { return node.property.name; } if (node.property.type === experimental_utils_1.AST_NODE_TYPES.Literal && typeof node.property.value === 'string') { return node.property.value; } } return null; } function isFunctionType(node) { var _a; const tsNode = parserServices.esTreeNodeToTSNodeMap.get(node); const type = checker.getTypeAtLocation(tsNode); const symbol = type.getSymbol(); if (symbol && tsutils.isSymbolFlagSet(symbol, ts.SymbolFlags.Function | ts.SymbolFlags.Method)) { return true; } if (symbol && symbol.escapedName === FUNCTION_CONSTRUCTOR) { const declarations = (_a = symbol.getDeclarations()) !== null && _a !== void 0 ? _a : []; for (const declaration of declarations) { const sourceFile = declaration.getSourceFile(); if (program.isSourceFileDefaultLibrary(sourceFile)) { return true; } } } const signatures = checker.getSignaturesOfType(type, ts.SignatureKind.Call); return signatures.length > 0; } function isBind(node) { return node.type === experimental_utils_1.AST_NODE_TYPES.MemberExpression ? isBind(node.property) : node.type === experimental_utils_1.AST_NODE_TYPES.Identifier && node.name === 'bind'; } function isFunction(node) { switch (node.type) { case experimental_utils_1.AST_NODE_TYPES.ArrowFunctionExpression: case experimental_utils_1.AST_NODE_TYPES.FunctionDeclaration: case experimental_utils_1.AST_NODE_TYPES.FunctionExpression: return true; case experimental_utils_1.AST_NODE_TYPES.Literal: case experimental_utils_1.AST_NODE_TYPES.TemplateLiteral: return false; case experimental_utils_1.AST_NODE_TYPES.CallExpression: return isBind(node.callee) || isFunctionType(node); default: return isFunctionType(node); } } function checkImpliedEval(node) { var _a; const tsNode = parserServices.esTreeNodeToTSNodeMap.get(node.callee); const type = checker.getTypeAtLocation(tsNode); const calleeName = getCalleeName(node.callee); if (calleeName === null) { return; } if (calleeName === FUNCTION_CONSTRUCTOR) { const symbol = type.getSymbol(); if (symbol) { const declarations = (_a = symbol.getDeclarations()) !== null && _a !== void 0 ? _a : []; for (const declaration of declarations) { const sourceFile = declaration.getSourceFile(); if (program.isSourceFileDefaultLibrary(sourceFile)) { context.report({ node, messageId: 'noFunctionConstructor' }); return; } } } else { context.report({ node, messageId: 'noFunctionConstructor' }); return; } } if (node.arguments.length === 0) { return; } const [handler] = node.arguments; if (EVAL_LIKE_METHODS.has(calleeName) && !isFunction(handler)) { context.report({ node: handler, messageId: 'noImpliedEvalError' }); } } return { NewExpression: checkImpliedEval, CallExpression: checkImpliedEval, }; }, }); //# sourceMappingURL=no-implied-eval.js.map
{'content_hash': 'ae087277db5539b03578a3ac0ce6b222', 'timestamp': '', 'source': 'github', 'line_count': 153, 'max_line_length': 141, 'avg_line_length': 43.928104575163395, 'alnum_prop': 0.5493230174081238, 'repo_name': 'thomasoboyle/Exercism', 'id': 'c18ca152af4fb17e901c49c918eb7116b0b38f8d', 'size': '6721', 'binary': False, 'copies': '3', 'ref': 'refs/heads/master', 'path': 'typescript/hello-world/node_modules/@typescript-eslint/eslint-plugin/dist/rules/no-implied-eval.js', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'JavaScript', 'bytes': '781'}, {'name': 'Ruby', 'bytes': '96197'}, {'name': 'TypeScript', 'bytes': '218'}]}
package org.jbehave.core.model; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; /** * <p> * Represents a tabular structure to hold example data for parameters named via the headers: * <p/> * <pre> * |header 1|header 2| .... |header n| * |value 11|value 12| .... |value 1n| * ... * |value m1|value m2| .... |value mn| * </pre> * <p>Different header and value column separators can be specified to replace the default separator "|":</p> * <pre> * !!header 1!!header 2!! .... !!header n!! * !value 11!value 12! .... !value 1n! * ... * !value m1!value m2| .... !value mn! * </pre> */ public class ExamplesTable { private static final String NEWLINE = "\n"; private static final String HEADER_SEPARATOR = "|"; private static final String VALUE_SEPARATOR = "|"; private final List<Map<String, String>> data = new ArrayList<Map<String, String>>(); private final String tableAsString; private final String headerSeparator; private final String valueSeparator; private final List<String> headers = new ArrayList<String>(); public ExamplesTable(String tableAsString) { this(tableAsString, HEADER_SEPARATOR, VALUE_SEPARATOR); } public ExamplesTable(String tableAsString, String headerSeparator, String valueSeparator) { this.tableAsString = tableAsString; this.headerSeparator = headerSeparator; this.valueSeparator = valueSeparator; parse(); } private void parse() { data.clear(); String[] rows = tableAsString.trim().split(NEWLINE); headers.clear(); for (int row = 0; row < rows.length; row++) { if (row == 0) { List<String> columns = columnsFor(rows[row], headerSeparator); headers.addAll(columns); } else { List<String> columns = columnsFor(rows[row], valueSeparator); Map<String, String> map = new HashMap<String, String>(); for (int column = 0; column < columns.size(); column++) { map.put(headers.get(column), columns.get(column)); } data.add(map); } } } private List<String> columnsFor(String row, String separator) { List<String> columns = new ArrayList<String>(); for (String column : row.split(buildRegex(separator))) { columns.add(column.trim()); } int size = columns.size(); if (size > 0) { columns.remove(0); } return columns; } private String buildRegex(String separator) { char[] chars = separator.toCharArray(); StringBuffer sb = new StringBuffer(); for ( char c : chars ){ sb.append("\\").append(c); } return sb.toString(); } public List<String> getHeaders() { return headers; } public Map<String, String> getRow(int row) { return data.get(row); } public int getRowCount() { return data.size(); } public List<Map<String, String>> getRows() { return data; } public String getHeaderSeparator() { return headerSeparator; } public String getValueSeparator() { return valueSeparator; } @Override public String toString() { return tableAsString; } }
{'content_hash': '3f804c0c997cc5e6f460bb00e1e27c8a', 'timestamp': '', 'source': 'github', 'line_count': 117, 'max_line_length': 109, 'avg_line_length': 29.085470085470085, 'alnum_prop': 0.5903614457831325, 'repo_name': 'codehaus/jbehave-git', 'id': '410f8a6b3148e3f37831b96186d219d053397587', 'size': '3403', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'jbehave-core/src/main/java/org/jbehave/core/model/ExamplesTable.java', 'mode': '33188', 'license': 'bsd-3-clause', 'language': [{'name': 'Java', 'bytes': '484308'}, {'name': 'JavaScript', 'bytes': '581'}, {'name': 'Shell', 'bytes': '735'}]}
import functools import inspect from nova.db import base from nova import exception from nova.network import model as network_model from nova.network import rpcapi as network_rpcapi from nova.openstack.common import log as logging from nova.openstack.common import rpc LOG = logging.getLogger(__name__) def refresh_cache(f): """ Decorator to update the instance_info_cache Requires context and instance as function args """ argspec = inspect.getargspec(f) @functools.wraps(f) def wrapper(self, context, *args, **kwargs): res = f(self, context, *args, **kwargs) try: # get the instance from arguments (or raise ValueError) instance = kwargs.get('instance') if not instance: instance = args[argspec.args.index('instance') - 2] except ValueError: msg = _('instance is a required argument to use @refresh_cache') raise Exception(msg) # get nw_info from return if possible, otherwise call for it nw_info = res if isinstance(res, network_model.NetworkInfo) else None update_instance_cache_with_nw_info(self, context, instance, nw_info, *args, **kwargs) # return the original function's return value return res return wrapper def update_instance_cache_with_nw_info(api, context, instance, nw_info=None, *args, **kwargs): try: nw_info = nw_info or api._get_instance_nw_info(context, instance) # update cache cache = {'network_info': nw_info.json()} api.db.instance_info_cache_update(context, instance['uuid'], cache) except Exception as e: LOG.exception(_('Failed storing info cache'), instance=instance) LOG.debug(_('args: %s') % (args or {})) LOG.debug(_('kwargs: %s') % (kwargs or {})) class API(base.Base): """API for interacting with the network manager.""" def __init__(self, **kwargs): self.network_rpcapi = network_rpcapi.NetworkAPI() super(API, self).__init__(**kwargs) def get_all(self, context): return self.network_rpcapi.get_all_networks(context) def get(self, context, network_uuid): return self.network_rpcapi.get_network(context, network_uuid) def create(self, context, **kwargs): return self.network_rpcapi.create_networks(context, **kwargs) def delete(self, context, network_uuid): return self.network_rpcapi.delete_network(context, network_uuid, None) def disassociate(self, context, network_uuid): return self.network_rpcapi.disassociate_network(context, network_uuid) def get_fixed_ip(self, context, id): return self.network_rpcapi.get_fixed_ip(context, id) def get_fixed_ip_by_address(self, context, address): return self.network_rpcapi.get_fixed_ip_by_address(context, address) def get_floating_ip(self, context, id): return self.network_rpcapi.get_floating_ip(context, id) def get_floating_ip_pools(self, context): return self.network_rpcapi.get_floating_pools(context) def get_floating_ip_by_address(self, context, address): return self.network_rpcapi.get_floating_ip_by_address(context, address) def get_floating_ips_by_project(self, context): return self.network_rpcapi.get_floating_ips_by_project(context) def get_floating_ips_by_fixed_address(self, context, fixed_address): return self.network_rpcapi.get_floating_ips_by_fixed_address(context, fixed_address) def get_backdoor_port(self, context, host): return self.network_rpcapi.get_backdoor_port(context, host) def get_instance_id_by_floating_address(self, context, address): # NOTE(tr3buchet): i hate this return self.network_rpcapi.get_instance_id_by_floating_address(context, address) def get_vifs_by_instance(self, context, instance): return self.network_rpcapi.get_vifs_by_instance(context, instance['id']) def get_vif_by_mac_address(self, context, mac_address): return self.network_rpcapi.get_vif_by_mac_address(context, mac_address) def allocate_floating_ip(self, context, pool=None): """Adds a floating ip to a project from a pool. (allocates)""" # NOTE(vish): We don't know which network host should get the ip # when we allocate, so just send it to any one. This # will probably need to move into a network supervisor # at some point. return self.network_rpcapi.allocate_floating_ip(context, context.project_id, pool, False) def release_floating_ip(self, context, address, affect_auto_assigned=False): """Removes floating ip with address from a project. (deallocates)""" return self.network_rpcapi.deallocate_floating_ip(context, address, affect_auto_assigned) @refresh_cache def associate_floating_ip(self, context, instance, floating_address, fixed_address, affect_auto_assigned=False): """Associates a floating ip with a fixed ip. ensures floating ip is allocated to the project in context """ orig_instance_uuid = self.network_rpcapi.associate_floating_ip(context, floating_address, fixed_address, affect_auto_assigned) if orig_instance_uuid: msg_dict = dict(address=floating_address, instance_id=orig_instance_uuid) LOG.info(_('re-assign floating IP %(address)s from ' 'instance %(instance_id)s') % msg_dict) orig_instance = self.db.instance_get_by_uuid(context, orig_instance_uuid) # purge cached nw info for the original instance update_instance_cache_with_nw_info(self, context, orig_instance) @refresh_cache def disassociate_floating_ip(self, context, instance, address, affect_auto_assigned=False): """Disassociates a floating ip from fixed ip it is associated with.""" self.network_rpcapi.disassociate_floating_ip(context, address, affect_auto_assigned) @refresh_cache def allocate_for_instance(self, context, instance, vpn, requested_networks): """Allocates all network structures for an instance. :returns: network info as from get_instance_nw_info() below """ args = {} args['vpn'] = vpn args['requested_networks'] = requested_networks args['instance_id'] = instance['id'] args['instance_uuid'] = instance['uuid'] args['project_id'] = instance['project_id'] args['host'] = instance['host'] args['rxtx_factor'] = instance['instance_type']['rxtx_factor'] nw_info = self.network_rpcapi.allocate_for_instance(context, **args) return network_model.NetworkInfo.hydrate(nw_info) def deallocate_for_instance(self, context, instance): """Deallocates all network structures related to instance.""" args = {} args['instance_id'] = instance['id'] args['project_id'] = instance['project_id'] args['host'] = instance['host'] self.network_rpcapi.deallocate_for_instance(context, **args) @refresh_cache def add_fixed_ip_to_instance(self, context, instance, network_id): """Adds a fixed ip to instance from specified network.""" args = {'instance_id': instance['id'], 'host': instance['host'], 'network_id': network_id} self.network_rpcapi.add_fixed_ip_to_instance(context, **args) @refresh_cache def remove_fixed_ip_from_instance(self, context, instance, address): """Removes a fixed ip from instance from specified network.""" args = {'instance_id': instance['uuid'], 'host': instance['host'], 'address': address} self.network_rpcapi.remove_fixed_ip_from_instance(context, **args) def add_network_to_project(self, context, project_id, network_uuid=None): """Force adds another network to a project.""" self.network_rpcapi.add_network_to_project(context, project_id, network_uuid) @refresh_cache def get_instance_nw_info(self, context, instance): """Returns all network info related to an instance.""" return self._get_instance_nw_info(context, instance) def _get_instance_nw_info(self, context, instance): """Returns all network info related to an instance.""" args = {'instance_id': instance['id'], 'instance_uuid': instance['uuid'], 'rxtx_factor': instance['instance_type']['rxtx_factor'], 'host': instance['host'], 'project_id': instance['project_id']} nw_info = self.network_rpcapi.get_instance_nw_info(context, **args) return network_model.NetworkInfo.hydrate(nw_info) def validate_networks(self, context, requested_networks): """validate the networks passed at the time of creating the server """ return self.network_rpcapi.validate_networks(context, requested_networks) def get_instance_uuids_by_ip_filter(self, context, filters): """Returns a list of dicts in the form of {'instance_uuid': uuid, 'ip': ip} that matched the ip_filter """ return self.network_rpcapi.get_instance_uuids_by_ip_filter(context, filters) def get_dns_domains(self, context): """Returns a list of available dns domains. These can be used to create DNS entries for floating ips. """ return self.network_rpcapi.get_dns_domains(context) def add_dns_entry(self, context, address, name, dns_type, domain): """Create specified DNS entry for address""" args = {'address': address, 'name': name, 'dns_type': dns_type, 'domain': domain} return self.network_rpcapi.add_dns_entry(context, **args) def modify_dns_entry(self, context, name, address, domain): """Create specified DNS entry for address""" args = {'address': address, 'name': name, 'domain': domain} return self.network_rpcapi.modify_dns_entry(context, **args) def delete_dns_entry(self, context, name, domain): """Delete the specified dns entry.""" args = {'name': name, 'domain': domain} return self.network_rpcapi.delete_dns_entry(context, **args) def delete_dns_domain(self, context, domain): """Delete the specified dns domain.""" return self.network_rpcapi.delete_dns_domain(context, domain=domain) def get_dns_entries_by_address(self, context, address, domain): """Get entries for address and domain""" args = {'address': address, 'domain': domain} return self.network_rpcapi.get_dns_entries_by_address(context, **args) def get_dns_entries_by_name(self, context, name, domain): """Get entries for name and domain""" args = {'name': name, 'domain': domain} return self.network_rpcapi.get_dns_entries_by_name(context, **args) def create_private_dns_domain(self, context, domain, availability_zone): """Create a private DNS domain with nova availability zone.""" args = {'domain': domain, 'av_zone': availability_zone} return self.network_rpcapi.create_private_dns_domain(context, **args) def create_public_dns_domain(self, context, domain, project=None): """Create a public DNS domain with optional nova project.""" args = {'domain': domain, 'project': project} return self.network_rpcapi.create_public_dns_domain(context, **args) def setup_networks_on_host(self, context, instance, host=None, teardown=False): """Setup or teardown the network structures on hosts related to instance""" host = host or instance['host'] # NOTE(tr3buchet): host is passed in cases where we need to setup # or teardown the networks on a host which has been migrated to/from # and instance['host'] is not yet or is no longer equal to args = {'instance_id': instance['id'], 'host': host, 'teardown': teardown} self.network_rpcapi.setup_networks_on_host(context, **args) def _is_multi_host(self, context, instance): try: fixed_ips = self.db.fixed_ip_get_by_instance(context, instance['uuid']) except exception.FixedIpNotFoundForInstance: return False network = self.db.network_get(context, fixed_ips[0]['network_id'], project_only='allow_none') return network['multi_host'] def _get_floating_ip_addresses(self, context, instance): floating_ips = self.db.instance_floating_address_get_all(context, instance['uuid']) return [floating_ip['address'] for floating_ip in floating_ips] def migrate_instance_start(self, context, instance, migration): """Start to migrate the network of an instance""" args = dict( instance_uuid=instance['uuid'], rxtx_factor=instance['instance_type']['rxtx_factor'], project_id=instance['project_id'], source_compute=migration['source_compute'], dest_compute=migration['dest_compute'], floating_addresses=None, ) if self._is_multi_host(context, instance): args['floating_addresses'] = \ self._get_floating_ip_addresses(context, instance) args['host'] = migration['source_compute'] self.network_rpcapi.migrate_instance_start(context, **args) def migrate_instance_finish(self, context, instance, migration): """Finish migrating the network of an instance""" args = dict( instance_uuid=instance['uuid'], rxtx_factor=instance['instance_type']['rxtx_factor'], project_id=instance['project_id'], source_compute=migration['source_compute'], dest_compute=migration['dest_compute'], floating_addresses=None, ) if self._is_multi_host(context, instance): args['floating_addresses'] = \ self._get_floating_ip_addresses(context, instance) args['host'] = migration['dest_compute'] self.network_rpcapi.migrate_instance_finish(context, **args)
{'content_hash': '8085a326382f047a9181e6f92466df5e', 'timestamp': '', 'source': 'github', 'line_count': 359, 'max_line_length': 79, 'avg_line_length': 42.16434540389972, 'alnum_prop': 0.6067252427825858, 'repo_name': 'aristanetworks/arista-ovs-nova', 'id': 'db8b872680e60ab9430494ac41c81f8f1b59088a', 'size': '15976', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'nova/network/api.py', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'JavaScript', 'bytes': '7403'}, {'name': 'Python', 'bytes': '6938504'}, {'name': 'Shell', 'bytes': '16524'}]}
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>statsmodels.duration.hazard_regression.PHReg.score_residuals &#8212; statsmodels 0.8.0 documentation</title> <link rel="stylesheet" href="../_static/nature.css" type="text/css" /> <link rel="stylesheet" href="../_static/pygments.css" type="text/css" /> <script type="text/javascript"> var DOCUMENTATION_OPTIONS = { URL_ROOT: '../', VERSION: '0.8.0', COLLAPSE_INDEX: false, FILE_SUFFIX: '.html', HAS_SOURCE: true, SOURCELINK_SUFFIX: '.txt' }; </script> <script type="text/javascript" src="../_static/jquery.js"></script> <script type="text/javascript" src="../_static/underscore.js"></script> <script type="text/javascript" src="../_static/doctools.js"></script> <link rel="shortcut icon" href="../_static/statsmodels_hybi_favico.ico"/> <link rel="author" title="About these documents" href="../about.html" /> <link rel="index" title="Index" href="../genindex.html" /> <link rel="search" title="Search" href="../search.html" /> <link rel="next" title="statsmodels.duration.hazard_regression.PHReg.weighted_covariate_averages" href="statsmodels.duration.hazard_regression.PHReg.weighted_covariate_averages.html" /> <link rel="prev" title="statsmodels.duration.hazard_regression.PHReg.score" href="statsmodels.duration.hazard_regression.PHReg.score.html" /> <link rel="stylesheet" href="../_static/examples.css" type="text/css" /> <link rel="stylesheet" href="../_static/facebox.css" type="text/css" /> <script type="text/javascript" src="../_static/scripts.js"> </script> <script type="text/javascript" src="../_static/facebox.js"> </script> </head> <body role="document"> <div class="headerwrap"> <div class = "header"> <a href = "../index.html"> <img src="../_static/statsmodels_hybi_banner.png" alt="Logo" style="padding-left: 15px"/></a> </div> </div> <div class="related" role="navigation" aria-label="related navigation"> <h3>Navigation</h3> <ul> <li class="right" style="margin-right: 10px"> <a href="../genindex.html" title="General Index" accesskey="I">index</a></li> <li class="right" > <a href="../py-modindex.html" title="Python Module Index" >modules</a> |</li> <li class="right" > <a href="statsmodels.duration.hazard_regression.PHReg.weighted_covariate_averages.html" title="statsmodels.duration.hazard_regression.PHReg.weighted_covariate_averages" accesskey="N">next</a> |</li> <li class="right" > <a href="statsmodels.duration.hazard_regression.PHReg.score.html" title="statsmodels.duration.hazard_regression.PHReg.score" accesskey="P">previous</a> |</li> <li><a href ="../install.html">Install</a></li> &nbsp;|&nbsp; <li><a href="https://groups.google.com/group/pystatsmodels?hl=en">Support</a></li> &nbsp;|&nbsp; <li><a href="https://github.com/statsmodels/statsmodels/issues">Bugs</a></li> &nbsp;|&nbsp; <li><a href="../dev/index.html">Develop</a></li> &nbsp;|&nbsp; <li><a href="../examples/index.html">Examples</a></li> &nbsp;|&nbsp; <li><a href="../faq.html">FAQ</a></li> &nbsp;|&nbsp; <li class="nav-item nav-item-1"><a href="../duration.html" >Methods for Survival and Duration Analysis</a> |</li> <li class="nav-item nav-item-2"><a href="statsmodels.duration.hazard_regression.PHReg.html" accesskey="U">statsmodels.duration.hazard_regression.PHReg</a> |</li> </ul> </div> <div class="document"> <div class="documentwrapper"> <div class="bodywrapper"> <div class="body" role="main"> <div class="section" id="statsmodels-duration-hazard-regression-phreg-score-residuals"> <h1>statsmodels.duration.hazard_regression.PHReg.score_residuals<a class="headerlink" href="#statsmodels-duration-hazard-regression-phreg-score-residuals" title="Permalink to this headline">¶</a></h1> <dl class="method"> <dt id="statsmodels.duration.hazard_regression.PHReg.score_residuals"> <code class="descclassname">PHReg.</code><code class="descname">score_residuals</code><span class="sig-paren">(</span><em>params</em><span class="sig-paren">)</span><a class="reference internal" href="../_modules/statsmodels/duration/hazard_regression.html#PHReg.score_residuals"><span class="viewcode-link">[source]</span></a><a class="headerlink" href="#statsmodels.duration.hazard_regression.PHReg.score_residuals" title="Permalink to this definition">¶</a></dt> <dd><p>Returns the score residuals calculated at a given vector of parameters.</p> <table class="docutils field-list" frame="void" rules="none"> <col class="field-name" /> <col class="field-body" /> <tbody valign="top"> <tr class="field-odd field"><th class="field-name">Parameters:</th><td class="field-body"><p class="first"><strong>params</strong> : ndarray</p> <blockquote> <div><p>The parameter vector at which the score residuals are calculated.</p> </div></blockquote> </td> </tr> <tr class="field-even field"><th class="field-name">Returns:</th><td class="field-body"><p class="first">The score residuals, returned as a ndarray having the same</p> <p class="last">shape as <cite>exog</cite>.</p> </td> </tr> </tbody> </table> <p class="rubric">Notes</p> <p>Observations in a stratum with no observed events have undefined score residuals, and contain NaN in the returned matrix.</p> </dd></dl> </div> </div> </div> </div> <div class="sphinxsidebar" role="navigation" aria-label="main navigation"> <div class="sphinxsidebarwrapper"> <h4>Previous topic</h4> <p class="topless"><a href="statsmodels.duration.hazard_regression.PHReg.score.html" title="previous chapter">statsmodels.duration.hazard_regression.PHReg.score</a></p> <h4>Next topic</h4> <p class="topless"><a href="statsmodels.duration.hazard_regression.PHReg.weighted_covariate_averages.html" title="next chapter">statsmodels.duration.hazard_regression.PHReg.weighted_covariate_averages</a></p> <div role="note" aria-label="source link"> <h3>This Page</h3> <ul class="this-page-menu"> <li><a href="../_sources/generated/statsmodels.duration.hazard_regression.PHReg.score_residuals.rst.txt" rel="nofollow">Show Source</a></li> </ul> </div> <div id="searchbox" style="display: none" role="search"> <h3>Quick search</h3> <form class="search" action="../search.html" method="get"> <div><input type="text" name="q" /></div> <div><input type="submit" value="Go" /></div> <input type="hidden" name="check_keywords" value="yes" /> <input type="hidden" name="area" value="default" /> </form> </div> <script type="text/javascript">$('#searchbox').show(0);</script> </div> </div> <div class="clearer"></div> </div> <div class="footer" role="contentinfo"> &#169; Copyright 2009-2017, Josef Perktold, Skipper Seabold, Jonathan Taylor, statsmodels-developers. Created using <a href="http://sphinx-doc.org/">Sphinx</a> 1.5.3. </div> </body> </html>
{'content_hash': '1dc9b8d566f923841d3378d45ef3a9c9', 'timestamp': '', 'source': 'github', 'line_count': 160, 'max_line_length': 465, 'avg_line_length': 46.4625, 'alnum_prop': 0.6546946462200699, 'repo_name': 'statsmodels/statsmodels.github.io', 'id': 'e342741ffff699a9b2d663ae880c06b5a9dde98e', 'size': '7437', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': '0.8.0/generated/statsmodels.duration.hazard_regression.PHReg.score_residuals.html', 'mode': '33188', 'license': 'bsd-3-clause', 'language': []}
<?php /* Unsafe sample input : get the field userData from the variable $_GET via an object, which store it in a array sanitize : use of the function htmlentities. Sanitizes the query but has a high chance to produce unexpected results construction : concatenation with simple quote */ /*Copyright 2015 Bertrand STIVALET Permission is hereby granted, without written agreement or royalty fee, to use, copy, modify, and distribute this software and its documentation for any purpose, provided that the above copyright notice and the following three paragraphs appear in all copies of this software. IN NO EVENT SHALL AUTHORS BE LIABLE TO ANY PARTY FOR DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF AUTHORS HAVE BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. AUTHORS SPECIFICALLY DISCLAIM ANY WARRANTIES INCLUDING, BUT NOT LIMITED TO THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, AND NON-INFRINGEMENT. THE SOFTWARE IS PROVIDED ON AN "AS-IS" BASIS AND AUTHORS HAVE NO OBLIGATION TO PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.*/ class Input{ private $input; public function getInput(){ return $this->input['realOne']; } public function __construct(){ $this->input = array(); $this->input['test']= 'safe' ; $this->input['realOne']= $_GET['UserData'] ; $this->input['trap']= 'safe' ; } } $temp = new Input(); $tainted = $temp->getInput(); $tainted = htmlentities($tainted, ENT_QUOTES); $query = "(&(objectCategory=person)(objectClass=user)(cn='". $tainted . "'))"; //flaw $ds=ldap_connect("localhost"); $r=ldap_bind($ds); $sr=ldap_search($ds,"o=My Company, c=US", $query); ldap_close($ds); ?>
{'content_hash': '5667d7ad8642d24467c5a0d514fca775', 'timestamp': '', 'source': 'github', 'line_count': 72, 'max_line_length': 116, 'avg_line_length': 25.0, 'alnum_prop': 0.7277777777777777, 'repo_name': 'stivalet/PHP-Vulnerability-test-suite', 'id': '3709120fb5048d4302b320ed3841672042b76e18', 'size': '1800', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'Injection/CWE_90/unsafe/CWE_90__object-indexArray__func_htmlentities__userByCN-concatenation_simple_quote.php', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'PHP', 'bytes': '64184004'}]}
import re # Each definition can be one of the following: # - a string # - a regex string # - a function that takes source as a parameter and returns an array or a string. (You may assume that re and urllib are already imported.) # If you comment out a parameter, it will use the default defined in __init__.py # identifier (default = name of this plugin after "plugin_") : If there's a match, we'll attempt to download images using this plugin. # title: parses the gallery page for a title. This will be the folder name of the output gallery. title = r'<title>(.*?)</title>' # redirect: if the links in the gallery page go to an html instead of an image, use this to parse the gallery page. redirect = r'href=["\']([^<]+?)["\'][^<]*?><img' # direct_links: if redirect is non-empty, this parses each redirect page for a single image. Otherwise, this parses the gallery page for all images. def direct_links(source): matcher = re.compile(r'src=[\"\'](.+?\.jpe?g)[\"\']',re.I) links = matcher.findall(source) links = filter(lambda x: not "thumb" in x.lower(), links) # exclude thumbnails return links # same_filename (default=False): if True, uses filename specified on remote link. Otherwise, creates own filename with incremental index. same_filename = True
{'content_hash': 'c9d18344adc302e979126ae9dd3d3535', 'timestamp': '', 'source': 'github', 'line_count': 25, 'max_line_length': 149, 'avg_line_length': 51.36, 'alnum_prop': 0.705607476635514, 'repo_name': 'regosen/gallery_get', 'id': 'd7dd6be544dc8017f4bdc71fabad9a317e0db260', 'size': '1310', 'binary': False, 'copies': '2', 'ref': 'refs/heads/master', 'path': 'gallery_plugins/plugin_generic.py', 'mode': '33261', 'license': 'mit', 'language': [{'name': 'Python', 'bytes': '66870'}]}
module Stattleship class BasketballGameLog < Stattleship::GameLog def stats [ "#{field_goals_made.to_i} FGM", "#{(field_goals_pct.to_f * 100).round(1)} FG%", "#{points.to_i} PTS", "#{rebounds_total.to_i} RBD", "#{assists.to_i} A", "#{steals.to_i} STL", "#{blocks.to_i} BLK" ] end def to_sentence "#{player_name} #{stats.join(', ')} (#{game.name})" end end class BasketballGameLogs < Stattleship::GameLogs BASKETBALL_GAME_LOGS = 'basketball/nba/game_logs'.freeze def self.fetch(params:) super(path: BASKETBALL_GAME_LOGS, params: params) end end module BasketballGameLogsRepresenter include Roar::JSON include Roar::Coercion include Stattleship::GameLogsRepresenter include Virtus.model collection :game_logs, class: Stattleship::BasketballGameLog do [ :away_team_outcome, :home_team_outcome, :team_outcome, :opponent_outcome, ].each do |attribute| property attribute end [ :field_goals_pct, :free_throws_pct, :three_pointers_pct, ].each do |attribute| property attribute, type: BigDecimal end [ :game_played, :game_started, :home_team_score, :away_team_score, :team_score, :opponent_score, :assists, :field_goals_attempted, :field_goals_made, :free_throws_attempted, :free_throws_made, :points, :three_pointers_attempted, :three_pointers_made, :turnovers, :steals, :blocks, :personal_fouls, :technical_fouls, :time_played_total, :plus_minus, :disqualifications, :rebounds_defensive, :rebounds_offensive, :rebounds_total, :double_double, :double_triple_double, :double_twenty, :five_by_five, :five_by_seven, :five_by_six, :five_by_steals_blocks, :quadruple_double, :quintuple_double, :thirty_thirty, :triple_double, ].each do |attribute| property attribute, type: Integer end [ :is_home_team, :is_away_team, ].each do |attribute| property attribute, type: Boolean, default: false end [ :player_id, :game_id, :team_id ].each do |relationship| property relationship end end end end
{'content_hash': '473eed4a6bb87346b0c37839625d3b3f', 'timestamp': '', 'source': 'github', 'line_count': 111, 'max_line_length': 67, 'avg_line_length': 23.045045045045047, 'alnum_prop': 0.5461297888975762, 'repo_name': 'stattleship/stattleship-ruby', 'id': '67c5e71fc5b66a4026b6b1e7d95add6fd830acf4', 'size': '2558', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'lib/stattleship/basketball_game_logs.rb', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'Ruby', 'bytes': '522762'}, {'name': 'Shell', 'bytes': '115'}]}
To run example code in this directory, invoke your python interpreter in the top-level directory with following arguments: ``` python -m chapter_03.main ```
{'content_hash': '369a8590531cbc2f4e6c1dcd5c205053', 'timestamp': '', 'source': 'github', 'line_count': 6, 'max_line_length': 76, 'avg_line_length': 26.333333333333332, 'alnum_prop': 0.7721518987341772, 'repo_name': 'MillionIntegrals/ESL', 'id': '3341067a14ad44d31fd76b2b76934c7a2afeb70a', 'size': '191', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'chapter_03/Readme.md', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'Python', 'bytes': '21292'}]}
SYNONYM #### According to The Catalogue of Life, 3rd January 2011 #### Published in null #### Original name null ### Remarks null
{'content_hash': 'b89c7fe0be027cd770489966dd8ccc01', 'timestamp': '', 'source': 'github', 'line_count': 13, 'max_line_length': 39, 'avg_line_length': 10.23076923076923, 'alnum_prop': 0.6917293233082706, 'repo_name': 'mdoering/backbone', 'id': '2a25bd012f3bb610c37ac988f32a0fd176a7e92f', 'size': '205', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'life/Plantae/Magnoliophyta/Liliopsida/Asparagales/Orchidaceae/Deiregyne/Deiregyne densiflora/ Syn. Stenorrhynchos densiflorum/README.md', 'mode': '33188', 'license': 'apache-2.0', 'language': []}
<?php namespace Pilulka\Database; class Hydrator { public static function hydrate($class, $row) { $model = (new \ReflectionClass($class))->newInstance(); $property = new \ReflectionProperty($class, 'row'); $property->setAccessible(true); $property->setValue($model, $row); return $model; } }
{'content_hash': '0bcfb16386b0c67f042adbc83c4012bf', 'timestamp': '', 'source': 'github', 'line_count': 17, 'max_line_length': 63, 'avg_line_length': 20.470588235294116, 'alnum_prop': 0.6063218390804598, 'repo_name': 'pilulkacz/database', 'id': 'e7afc7040df3244619266dd3d4d8b8644f432a5c', 'size': '348', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'src/Hydrator.php', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'PHP', 'bytes': '15264'}]}
package com.capitalone.dashboard.repository; import java.util.List; import org.bson.types.ObjectId; import org.springframework.data.mongodb.repository.Query; import com.capitalone.dashboard.model.TeamCollectorItem; /** * CollectorItem repository for {@link TeamCollectorItem}. */ public interface TeamRepository extends BaseCollectorItemRepository<TeamCollectorItem> { @Query(value = "{ 'collectorId' : ?0, options.teamId : ?1, options.name : ?2}") TeamCollectorItem findTeamCollector(ObjectId collectorId, String teamId, String name); @Query(value = "{ 'collectorId' : ?0, options.teamId : ?1, enabled: true}") List<TeamCollectorItem> findEnabledTeamCollectors(ObjectId collectorId, String teamId); @Query(value = "{ $query: { 'collectorId' : ?0, 'options.changeDate' : {$gt: ?1}, '_class' : 'com.capitalone.dashboard.model.TeamCollectorItem'}, $orderby: { 'options.changeDate' :-1 }}", fields = "{'options.changeDate' : 1, '_id' : 0}") List<TeamCollectorItem> getTeamMaxChangeDate(ObjectId collectorId, String lastChangeDate); @Query(value = "{'options.teamId' : ?0}") List<TeamCollectorItem> getTeamIdById(String teamId); }
{'content_hash': '666f29e8a8d5e877b606f004629e1b53', 'timestamp': '', 'source': 'github', 'line_count': 29, 'max_line_length': 238, 'avg_line_length': 39.827586206896555, 'alnum_prop': 0.7402597402597403, 'repo_name': 'jimzucker/hygieia-temp', 'id': '5975856f46783533311c0595b38610fcc63de231', 'size': '1155', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'jira-feature-collector/src/main/java/com/capitalone/dashboard/repository/TeamRepository.java', 'mode': '33261', 'license': 'apache-2.0', 'language': [{'name': 'Batchfile', 'bytes': '5186'}, {'name': 'CSS', 'bytes': '76286'}, {'name': 'HTML', 'bytes': '91997'}, {'name': 'Java', 'bytes': '794189'}, {'name': 'JavaScript', 'bytes': '190816'}, {'name': 'Shell', 'bytes': '8755'}]}
<?php /** * Logos public part. */ // File Security Check if ( ! defined( 'ABSPATH' ) ) { exit; } class Presscore_Mod_Logos_Public { public function register_shortcodes() { foreach ( array( 'logos' ) as $shortcode_name ) { include_once plugin_dir_path( __FILE__ ) . "shortcodes/{$shortcode_name}/{$shortcode_name}.php"; } } public function load_shortcodes_vc_bridge() { include_once plugin_dir_path( __FILE__ ) . "shortcodes/mod-logos-shortcodes-bridge.php"; } public function init_widgets() { register_widget( 'Presscore_Inc_Widgets_Logos' ); } }
{'content_hash': '9aca566d2719702be3205aea621e73c5', 'timestamp': '', 'source': 'github', 'line_count': 24, 'max_line_length': 99, 'avg_line_length': 23.791666666666668, 'alnum_prop': 0.6619964973730298, 'repo_name': 'ZloVolk/TQ', 'id': '48a95352cf19ec3708e93cc89e94ffcb617fa019', 'size': '571', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'wp-content/themes/dt-the7/inc/mods/logos/public/class-mod-logos-public.php', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'CSS', 'bytes': '103126077'}, {'name': 'HTML', 'bytes': '230730'}, {'name': 'JavaScript', 'bytes': '10865050'}, {'name': 'PHP', 'bytes': '34845446'}, {'name': 'PLSQL', 'bytes': '558884'}]}
OpenCV-Face-andmore-Tracker =========================== OpenCV based face (and eye, nose, mouth) detection example application. The tutorial is provided as ready to compile/run Windows Visual Studio project (C#, .NET, EmguCV). Just download, compile and have fun with it. Or use the provided binary setup and play webcam face tracking right away.
{'content_hash': 'd7ee9b61fa3a322e909d89245366ea34', 'timestamp': '', 'source': 'github', 'line_count': 4, 'max_line_length': 290, 'avg_line_length': 87.0, 'alnum_prop': 0.7270114942528736, 'repo_name': 'A9T9/OpenCV-Face-andmore-Tracker', 'id': 'bc63f07168accd0a9c4edc98decc540240d0cd20', 'size': '348', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'README.md', 'mode': '33188', 'license': 'bsd-3-clause', 'language': [{'name': 'C#', 'bytes': '39023'}, {'name': 'Inno Setup', 'bytes': '4585'}]}
import React from 'react' import CalloutSection from '~/components/callout'; import MainCarousel from '~/components/main-carousel'; import { ServicesSection } from '~/components/services'; import { NewsSection } from '~/components/news'; import Icon from "~/components/icon"; import { Box, Flex } from 'rebass'; import Heading from '~/components/heading'; import PageSection from "~/components/page-section"; import { Circle } from 'rebass'; import { darken, lighten } from 'polished'; import styled, { withTheme } from 'styled-components'; const VisaLink = styled.a` display:block; text-decoration:none; &:hover { ${ Box }{ background-color: ${ ({theme}) => theme.colors.primaryAccent }; transition: all 0.3s ease-in-out; border-color: ${({ theme }) => darken(0.1, theme.colors.primaryAccent )}; } ${ Icon }{ color: ${({ theme }) => darken(0.35, theme.colors.primaryAccent )}; } ${ Heading }{ color: ${ ({theme}) => theme.colors.primaryAccent }; } }; width:100%; height:100%; ` const StyledBox = styled(Box)` line-height: 1em; width: 1em; height: 1em; font-size:6em; border-radius: 10px; border:solid 2px ${ ({theme}) => darken(0.05, theme.colors.light ) }; display: inline-flex; border-radius: 50%; background-color: ${ ({ theme }) => theme.colors.light }; ` const StyledIcon = styled(Icon)` display:block; width:100%; height:100%; font-size: 0.5em; margin-top:-5px; color: ${({theme}) => theme.colors.dark }; ` const Visa = withTheme(({title, slug, icon, theme}) => { return ( <Box w={[1, 1/2, 1/3, 1/5]} mb={[5, 6]} style={{ textAlign: "center"}}> <VisaLink href={slug}> <StyledBox ><StyledIcon color="dark" icon={icon}></StyledIcon></StyledBox> <Heading f={[1, 2, 3, 4]}>{title}</Heading> </VisaLink> </Box> ) }); const VisaSection = withTheme(({visas, theme}) =>{ const children = visas.map(visa => (<Visa key={visa.id} {...visa}/>)); return (<Flex style={{ borderTop: "solid 1px " + darken(0.1, theme.colors.light ) }} wrap pt={6}> {children} </Flex>) }); export default ({data}) => { const services = data.services.edges.map(x => ({ ...x.node.frontmatter, id:x.node.id, slug: x.node.fields.slug })); const news = data.news.edges.map(x => ({ ...x.node.frontmatter, id:x.node.id, slug: x.node.fields.slug, excerpt: x.node.excerpt })); const visas = data.visas.edges.concat(data.citizenship.edges).map(x => ({ ...x.node.frontmatter, id:x.node.id, slug: x.node.fields.slug })); return ( <div> <MainCarousel/> <ServicesSection services={services}/> <VisaSection visas={visas} /> <CalloutSection/> <NewsSection news={news} py={5} /> </div> ) } export const pageQuery = graphql` fragment Content on MarkdownRemarkEdge{ node{ fields{ area, slug }, id, frontmatter{ title, caption, extract, image, thumb, tags, date, order, icon, thumbPosition } } } query LandingQuery { services:allMarkdownRemark( limit: 100 filter:{ fields: { area: { eq: "services" } }} sort: { fields: [frontmatter___order], order: ASC } ) { edges { ...Content } }, visas:allMarkdownRemark( limit: 100 filter:{ fields: { area: { eq: "visas" } }} sort: { fields: [frontmatter___order], order: ASC } ) { edges { ...Content } }, citizenship: allMarkdownRemark( limit: 100 filter:{ fields: { area: { eq: "citizenship" } }} sort: { fields: [frontmatter___order], order: ASC } ) { edges { ...Content } }, news:allMarkdownRemark( limit: 100 filter:{ fields: { area: { eq: "news" } }} sort: { fields: [frontmatter___date], order: DESC } ) { edges { ...Content, node{ excerpt(pruneLength: 350) } } } }`;
{'content_hash': '8e35a1515775c1ced06d049dcdcf11ec', 'timestamp': '', 'source': 'github', 'line_count': 155, 'max_line_length': 143, 'avg_line_length': 25.883870967741935, 'alnum_prop': 0.5765204386839482, 'repo_name': 'adrienlozano/stephaniewebsite', 'id': '1a7f855072390a3e58318426830f6c20e1d26307', 'size': '4012', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'src/pages/index.js', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'HTML', 'bytes': '459'}, {'name': 'JavaScript', 'bytes': '76652'}]}
layout: post name: "Invoice" title: "Invoice – August 2019" date: 2019-08-31 10:00:00 invoice_number: "naluri-2019-8-31-CG" period: "August 2019" pdf_url: "/pdfs/2019-08-31-invoice.pdf" invoice_currency: RM hourly_rate: 1500 person_name: Code Hero Enterprise person_email: [email protected] client: Naluri Sdn Bhd note: excerpt_separator: "" invoice_line_items: - title: August 2019 (Tech / Infra support / advice) amount: 1500 invoice_payment_info: | __Account Name:__ CODE HERO ENTERPRISE \\ __Account Bank Name:__ MAYBANK MALAYSIA \\ __Account Number:__ ‎562106693095 \\ __Account Country:__ Malaysia \\ __Account Address:__ \\ SA1-8-3A Vista Alam, \\ Jalan Ikhtisas, Seksyen 14, \\ 40000 Shah Alam, \\ Selangor, Malaysia. exchange_rate: 0.0 exchange_currency: address: ... --- # {{page.title}} <a class="pdf-link" href="{{page.pdf_url}}" target="_blank"><span class="mega-octicon octicon-file-pdf"></span></a> ## Description This invoice is for work performed by _{{page.person_name}}_ for _{{page.client}}_. __Invoice Number:__ {{ page.invoice_number }} \\ __Date:__ {{ page.date | date_to_string }} \\ __For period:__ {{ page.period }} {{page.note}} ## Line items {% assign total = 0 %} |__Description__|__Total__| |---|---:|{% for item in page.invoice_line_items %}{% assign total = total | plus:item.amount %} |{{item.title}}|{{item.amount}}|{% endfor %} ||__{{total}} {{page.invoice_currency}}__| {% if page.exchange_rate > 0 %} Exchange Rate {{page.exchange_rate}}, total payable in {{page.exchange_currency}}, **{{total | times:page.exchange_rate | round}} {{page.exchange_currency}}** {% endif %} ## Bank Information {{page.invoice_payment_info}}
{'content_hash': '9c31393e00301596f37cdc9e385d4d26', 'timestamp': '', 'source': 'github', 'line_count': 65, 'max_line_length': 158, 'avg_line_length': 26.353846153846153, 'alnum_prop': 0.647985989492119, 'repo_name': 'codegarageco/cg_invoice', 'id': '3ea02feb36dd7a527b406127bfc89f3580cd3add', 'size': '1721', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': '_posts/2019-08-31-invoice.markdown', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'CSS', 'bytes': '3226'}, {'name': 'HTML', 'bytes': '1303'}, {'name': 'Less', 'bytes': '11744'}, {'name': 'Ruby', 'bytes': '4648'}]}
::ApplicationController.class_eval do around_filter :scope_current_patron def current_patron if user_signed_in? @current_patron ||= begin patron_id = warden.user(:scope => :patron) #|| (current_user.patron_id if current_user) Nimbos::Patron.find(patron_id) end end end helper_method :current_patron def current_user if user_signed_in? @current_user ||= begin user_id = warden.user(:scope => :user) Nimbos::User.unscoped.find(user_id) end end end helper_method :current_user def user_signed_in? warden.authenticated?(:user) end helper_method :user_signed_in? def require_login unless user_signed_in? session[:return_to_url] = request.url if request.get? not_authenticated else if current_user.is_guest session[:return_to_url] = nil warden.logout redirect_to main_app.root_url end end end def force_authentication!(patron, user) warden.set_user(user.id, :scope => :user) warden.set_user(patron.id, :scope => :patron) end def generate_group(parent, user_ids) #user_ids << current_user.id Nimbos::Group.add_group(current_user.id, parent, user_ids) end private def not_authenticated redirect_to nimbos.login_path, :alert => "Please login first." end def warden env['warden'] end def scope_current_patron Nimbos::Patron.current_id = current_patron.id if current_patron yield ensure Nimbos::Patron.current_id = nil end end
{'content_hash': '01566105be0dec354c3ff92137c38f2f', 'timestamp': '', 'source': 'github', 'line_count': 68, 'max_line_length': 91, 'avg_line_length': 21.720588235294116, 'alnum_prop': 0.6790792146242384, 'repo_name': 'farukca/nimbos', 'id': '8719a58845a75237ff9d1b6e3b3f209302147fba', 'size': '1477', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'app/extenders/controllers/application_controller_extender.rb', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'CSS', 'bytes': '6478'}, {'name': 'CoffeeScript', 'bytes': '842'}, {'name': 'HTML', 'bytes': '139106'}, {'name': 'JavaScript', 'bytes': '4835'}, {'name': 'Ruby', 'bytes': '142043'}]}
// Next default values for new objects // #ifdef APSTUDIO_INVOKED #ifndef APSTUDIO_READONLY_SYMBOLS #define _APS_NEXT_RESOURCE_VALUE 139 #define _APS_NEXT_COMMAND_VALUE 32778 #define _APS_NEXT_CONTROL_VALUE 1043 #define _APS_NEXT_SYMED_VALUE 110 #endif #endif
{'content_hash': '6800b8194ae65b2d3bb5d132b4b84845', 'timestamp': '', 'source': 'github', 'line_count': 11, 'max_line_length': 45, 'avg_line_length': 27.818181818181817, 'alnum_prop': 0.6633986928104575, 'repo_name': 'johanlantz/headsetpresenter', 'id': 'eac1cf3804c286383d2ea10d35236b3035cb2c24', 'size': '2971', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'HeadsetPresenter_Bluetools/Microsoft Speech SDK 5.1/Samples/CPP/Reco/resource.h', 'mode': '33261', 'license': 'mit', 'language': [{'name': 'Assembly', 'bytes': '7004'}, {'name': 'Batchfile', 'bytes': '2489'}, {'name': 'C', 'bytes': '16452971'}, {'name': 'C#', 'bytes': '1393901'}, {'name': 'C++', 'bytes': '19851472'}, {'name': 'Clarion', 'bytes': '4450'}, {'name': 'HTML', 'bytes': '50191'}, {'name': 'Makefile', 'bytes': '51937'}, {'name': 'NSIS', 'bytes': '68365'}, {'name': 'Objective-C', 'bytes': '1800430'}, {'name': 'PHP', 'bytes': '10905'}, {'name': 'Visual Basic', 'bytes': '823951'}]}
package io.tvcalendar.security; import org.springframework.security.core.AuthenticationException; /** * This exception is throw in case of a not activated user trying to authenticate. */ public class UserNotActivatedException extends AuthenticationException { public UserNotActivatedException(String message) { super(message); } public UserNotActivatedException(String message, Throwable t) { super(message, t); } }
{'content_hash': 'd2e1f6b4a1d7224fd6c20b64314e5075', 'timestamp': '', 'source': 'github', 'line_count': 17, 'max_line_length': 82, 'avg_line_length': 26.705882352941178, 'alnum_prop': 0.748898678414097, 'repo_name': 'raphaelrodrigues/tvcalendar', 'id': '78ce2e206c2a4fe748864a6baa52775f46f35377', 'size': '454', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'src/main/java/io/tvcalendar/security/UserNotActivatedException.java', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'ApacheConf', 'bytes': '24139'}, {'name': 'Batchfile', 'bytes': '5006'}, {'name': 'CSS', 'bytes': '6151'}, {'name': 'Cucumber', 'bytes': '161'}, {'name': 'HTML', 'bytes': '119939'}, {'name': 'Java', 'bytes': '298008'}, {'name': 'JavaScript', 'bytes': '167265'}, {'name': 'Shell', 'bytes': '7058'}]}
package com.example.fraud.model; import com.fasterxml.jackson.annotation.JsonProperty; public class FraudCheckResult { private FraudCheckStatus fraudCheckStatus; @JsonProperty("rejection.reason") private String rejectionReason; public FraudCheckResult() { } public FraudCheckResult(FraudCheckStatus fraudCheckStatus, String rejectionReason) { this.fraudCheckStatus = fraudCheckStatus; this.rejectionReason = rejectionReason; } public FraudCheckStatus getFraudCheckStatus() { return fraudCheckStatus; } public void setFraudCheckStatus(FraudCheckStatus fraudCheckStatus) { this.fraudCheckStatus = fraudCheckStatus; } public String getRejectionReason() { return rejectionReason; } public void setRejectionReason(String rejectionReason) { this.rejectionReason = rejectionReason; } }
{'content_hash': '2a72423c8e78c633efaedcbdc1178088', 'timestamp': '', 'source': 'github', 'line_count': 38, 'max_line_length': 85, 'avg_line_length': 21.55263157894737, 'alnum_prop': 0.800976800976801, 'repo_name': 'spring-cloud/spring-cloud-contract', 'id': 'c908038d0af398144e36b72937e441186cada86b', 'size': '1440', 'binary': False, 'copies': '1', 'ref': 'refs/heads/main', 'path': 'samples/standalone/dsl/http-server/src/main/java/com/example/fraud/model/FraudCheckResult.java', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'CSS', 'bytes': '37240'}, {'name': 'Dockerfile', 'bytes': '2829'}, {'name': 'Groovy', 'bytes': '1312232'}, {'name': 'Java', 'bytes': '2319249'}, {'name': 'Kotlin', 'bytes': '131929'}, {'name': 'Shell', 'bytes': '39490'}, {'name': 'Vim Snippet', 'bytes': '1421'}]}
using System; using System.Collections.Generic; namespace Web_API_Service.Models { // Models returned by AccountController actions. public class ExternalLoginViewModel { public string Name { get; set; } public string Url { get; set; } public string State { get; set; } } public class ManageInfoViewModel { public string LocalLoginProvider { get; set; } public string Email { get; set; } public IEnumerable<UserLoginInfoViewModel> Logins { get; set; } public IEnumerable<ExternalLoginViewModel> ExternalLoginProviders { get; set; } } public class UserInfoViewModel { public string Email { get; set; } public bool HasRegistered { get; set; } public string LoginProvider { get; set; } } public class UserLoginInfoViewModel { public string LoginProvider { get; set; } public string ProviderKey { get; set; } } }
{'content_hash': 'c85a40e3a4301256ded04b3d35722bcd', 'timestamp': '', 'source': 'github', 'line_count': 43, 'max_line_length': 87, 'avg_line_length': 22.558139534883722, 'alnum_prop': 0.6371134020618556, 'repo_name': 'x-danma/Texas', 'id': 'abbf100685f8afb99792e6242a3db9a35c0cccfa', 'size': '972', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'ConsoleApplication1/Web API Service/Models/AccountViewModels.cs', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'ASP', 'bytes': '109'}, {'name': 'C#', 'bytes': '241802'}, {'name': 'CSS', 'bytes': '2626'}, {'name': 'HTML', 'bytes': '6656'}, {'name': 'JavaScript', 'bytes': '10918'}]}
<?php header("Content-Type: application/json"); //Set header for outputing the JSON information require_once $_SERVER['DOCUMENT_ROOT'] . '/includes/autoload.php'; $request = file_get_contents('php://input'); $data = json_decode($request); $notification_id = $data->notification_id; //$notification_id = 36; $user = User::get_current_user(); try { if (is_numeric($notification_id) && $user instanceof CurrentUser) { $notification = new Notification(array( 'notification_id' => $notification_id) ); $result = $user->mark_notification_as_read($notification); http_response_code(200); } else { throw new UnexpectedValueException('UnexpectedValueException occured on request because the input parameters are invalid'); } } catch (Exception $e) { http_response_code(400); Database::print_exception($e); }
{'content_hash': 'd56d129ca8a4e6597ea11704598fa24e', 'timestamp': '', 'source': 'github', 'line_count': 24, 'max_line_length': 125, 'avg_line_length': 34.041666666666664, 'alnum_prop': 0.7184822521419829, 'repo_name': 'kuroware/UoftBaddy', 'id': '5ac07c7de4565312206a0756318bb5bc037d9e31', 'size': '817', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'postRequests/user/MarkNotificationAsRead.php', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'CSS', 'bytes': '5338'}, {'name': 'HTML', 'bytes': '205929'}, {'name': 'JavaScript', 'bytes': '8846'}, {'name': 'PHP', 'bytes': '1416008'}]}
package org.tecunhuman; import org.tecunhuman.jni.SoundStretch; public class AndroidJNI { public final static SoundStretch soundStretch = new SoundStretch(); }
{'content_hash': '245c8791b32a1a5d447dd9b30fd4bc37', 'timestamp': '', 'source': 'github', 'line_count': 7, 'max_line_length': 71, 'avg_line_length': 23.714285714285715, 'alnum_prop': 0.7891566265060241, 'repo_name': 'happyhugo/mask', 'id': 'a6bb28b8c900d54ad79c626eda039d03da65eaba', 'size': '166', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'soundtouch/src/org/tecunhuman/AndroidJNI.java', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'C', 'bytes': '343077'}, {'name': 'C++', 'bytes': '331168'}, {'name': 'D', 'bytes': '429692'}, {'name': 'Java', 'bytes': '129742'}, {'name': 'JavaScript', 'bytes': '1004'}, {'name': 'Pascal', 'bytes': '17208'}, {'name': 'Shell', 'bytes': '1697'}]}
{-# LANGUAGE TemplateHaskell, DeriveGeneric, DeriveDataTypeable #-} module Master.Master ( run , remoteTable ) where import Control.Distributed.Process ( Process, NodeId, RemoteTable , NodeMonitorNotification (..) , ProcessMonitorNotification (..) , DiedReason (..), ProcessId (..) , say, spawnSupervised, spawnLocal , getSelfPid, send, nsend, expect , receiveWait , match, monitorNode , register ) import Control.Distributed.Process.Closure import Control.Distributed.Process.Backend.SimpleLocalnet ( Backend , findSlaves , terminateAllSlaves ) import Control.Monad (forever) import Data.List ((\\)) import Data.Binary import Data.Typeable import Text.Printf (printf) import GHC.Generics import Slave.Slave (Request (..), Response (..), slaveProc, slaveProc__static) data NodeDetected = NodeDetected !NodeId deriving (Generic, Typeable) instance Binary NodeDetected data ProcessUp = ProcessUp !ProcessId deriving (Generic, Typeable) instance Binary ProcessUp data ProcessDown = ProcessDown !ProcessId deriving (Generic, Typeable) instance Binary ProcessDown nodeDetector :: Backend -> Process () nodeDetector backend = loop [] where loop :: [NodeId] -> Process () loop nodes = do nodes' <- map processNodeId `fmap` findSlaves backend mapM_ (nsend "supervisor" . NodeDetected) $ nodes' \\ nodes loop nodes' supervisor :: Process () supervisor = do register "supervisor" =<< getSelfPid forever $ receiveWait [ match nodeDetected , match nodeMonitorNotification , match processMonitorNotification ] taskMaster :: Process () taskMaster = do say "taskMaster" taskMaster' [] [1..100] [] taskMaster' :: [ProcessId] -> [Int] -> [Int] -> Process () taskMaster' [] xs ys = do -- No processes are available, wait infinitely for one process to -- show up. say "Waiting for procs" ProcessUp processId <- expect say "Got proc" taskMaster' [processId] xs ys taskMaster' procs [] ys | length ys == 100 = do say "Work is done!" return () | otherwise = do -- We still have to receive responses from processes. say "Waiting for the last response(s)" Response y <- expect say $ printf "Got response: %d" y taskMaster' procs [] (y:ys) taskMaster' procs@(p:ps) s@(x:xs) ys | length s + length ys < 80 = do -- Too many in flight, don't send more. say "Too many in flight. Waiting for various responses" (procs', s', ys') <- receiveWait [ match $ \(ProcessDown pid) -> do say $ printf "Lost process %s" (show pid) return $ (filter (pid /=) procs, s, ys) , match $ \(ProcessUp pid) -> do say $ printf "Got process %s" (show pid) return $ ((pid:procs), s, ys) , match $ \(Response y) -> do say $ printf "Got response %d" y return $ (procs, s, (y:ys)) ] taskMaster' procs' s' ys' | otherwise = do say "Send one request" self <- getSelfPid send p $ Request self x taskMaster' (ps ++ [p]) xs ys nodeDetected :: NodeDetected -> Process () nodeDetected (NodeDetected nodeId) = do say $ "Detected node: " ++ show nodeId _ <- monitorNode nodeId (newProc, _) <- spawnSupervised nodeId $(mkStaticClosure 'slaveProc) nsend "taskmaster" $ ProcessUp newProc say $ printf "Create process %s at node %s" (show newProc) (show nodeId) return () nodeMonitorNotification :: NodeMonitorNotification -> Process () nodeMonitorNotification (NodeMonitorNotification _ nodeId reason) = say $ printf "Node %s died because of %s" (show nodeId) (show reason) processMonitorNotification :: ProcessMonitorNotification -> Process () processMonitorNotification (ProcessMonitorNotification _ processId reason) = case reason of (DiedException _) -> do say $ printf "Process %s crashed and will be restarted" (show processId) nsend "taskmaster" $ ProcessDown processId (newProc, _) <- spawnSupervised (processNodeId processId) $(mkStaticClosure 'slaveProc) nsend "taskmaster" $ ProcessUp newProc _ -> do say $ printf "Process %s died because of %s" (show processId) (show reason) nsend "taskmaster" $ ProcessDown processId remotable [] remoteTable :: (RemoteTable -> RemoteTable) remoteTable = __remoteTable run :: Backend -> [NodeId] -> Process () run backend _ = do register "taskmaster" =<< getSelfPid _ <- spawnLocal supervisor _ <- spawnLocal (nodeDetector backend) taskMaster terminateAllSlaves backend
{'content_hash': 'd56e85bd7332c5f318ab49c02f74e654', 'timestamp': '', 'source': 'github', 'line_count': 154, 'max_line_length': 80, 'avg_line_length': 36.22727272727273, 'alnum_prop': 0.5463344685427496, 'repo_name': 'SneakingCat/distributed-nonsense', 'id': '4627ec6d9c405d33b6d28578ffb51d45c8add44d', 'size': '5579', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'src/Master/Master.hs', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'Haskell', 'bytes': '7552'}]}
/* $NetBSD: l2cap_misc.c,v 1.7 2009/09/13 18:45:11 pooka Exp $ */ /*- * Copyright (c) 2005 Iain Hibbert. * Copyright (c) 2006 Itronix Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. The name of Itronix Inc. may not be used to endorse * or promote products derived from this software without specific * prior written permission. * * THIS SOFTWARE IS PROVIDED BY ITRONIX INC. ``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 ITRONIX INC. 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. */ #include <sys/cdefs.h> __KERNEL_RCSID(0, "$NetBSD: l2cap_misc.c,v 1.7 2009/09/13 18:45:11 pooka Exp $"); #include <sys/param.h> #include <sys/kernel.h> #include <sys/mbuf.h> #include <sys/proc.h> #include <sys/queue.h> #include <sys/systm.h> #include <netbt/bluetooth.h> #include <netbt/hci.h> #include <netbt/l2cap.h> struct l2cap_channel_list l2cap_active_list = LIST_HEAD_INITIALIZER(l2cap_active_list); struct l2cap_channel_list l2cap_listen_list = LIST_HEAD_INITIALIZER(l2cap_listen_list); struct pool l2cap_req_pool, l2cap_pdu_pool; const l2cap_qos_t l2cap_default_qos = { 0, /* flags */ L2CAP_QOS_BEST_EFFORT, /* service type */ 0x00000000, /* token rate */ 0x00000000, /* token bucket size */ 0x00000000, /* peak bandwidth */ 0xffffffff, /* latency */ 0xffffffff /* delay variation */ }; /* * L2CAP request timeouts */ int l2cap_response_timeout = 30; /* seconds */ int l2cap_response_extended_timeout = 180; /* seconds */ void l2cap_init(void) { pool_init(&l2cap_req_pool, sizeof(struct l2cap_req), 0, 0, 0, "l2cap_req", NULL, IPL_SOFTNET); pool_init(&l2cap_pdu_pool, sizeof(struct l2cap_pdu), 0, 0, 0, "l2cap_pdu", NULL, IPL_SOFTNET); } /* * Set Link Mode on channel */ int l2cap_setmode(struct l2cap_channel *chan) { KASSERT(chan != NULL); KASSERT(chan->lc_link != NULL); DPRINTF("CID #%d, auth %s, encrypt %s, secure %s\n", chan->lc_lcid, (chan->lc_mode & L2CAP_LM_AUTH ? "yes" : "no"), (chan->lc_mode & L2CAP_LM_ENCRYPT ? "yes" : "no"), (chan->lc_mode & L2CAP_LM_SECURE ? "yes" : "no")); if (chan->lc_mode & L2CAP_LM_AUTH) chan->lc_link->hl_flags |= HCI_LINK_AUTH_REQ; if (chan->lc_mode & L2CAP_LM_ENCRYPT) chan->lc_link->hl_flags |= HCI_LINK_ENCRYPT_REQ; if (chan->lc_mode & L2CAP_LM_SECURE) chan->lc_link->hl_flags |= HCI_LINK_SECURE_REQ; return hci_acl_setmode(chan->lc_link); } /* * Allocate a new Request structure & ID and set the timer going */ int l2cap_request_alloc(struct l2cap_channel *chan, uint8_t code) { struct hci_link *link = chan->lc_link; struct l2cap_req *req; int next_id; if (link == NULL) return ENETDOWN; /* find next ID (0 is not allowed) */ next_id = link->hl_lastid + 1; if (next_id > 0xff) next_id = 1; /* Ouroboros check */ req = TAILQ_FIRST(&link->hl_reqs); if (req && req->lr_id == next_id) return ENFILE; req = pool_get(&l2cap_req_pool, PR_NOWAIT); if (req == NULL) return ENOMEM; req->lr_id = link->hl_lastid = next_id; req->lr_code = code; req->lr_chan = chan; req->lr_link = link; callout_init(&req->lr_rtx, 0); callout_setfunc(&req->lr_rtx, l2cap_rtx, req); callout_schedule(&req->lr_rtx, l2cap_response_timeout * hz); TAILQ_INSERT_TAIL(&link->hl_reqs, req, lr_next); return 0; } /* * Find a running request for this link */ struct l2cap_req * l2cap_request_lookup(struct hci_link *link, uint8_t id) { struct l2cap_req *req; TAILQ_FOREACH(req, &link->hl_reqs, lr_next) { if (req->lr_id == id) return req; } return NULL; } /* * Halt and free a request */ void l2cap_request_free(struct l2cap_req *req) { struct hci_link *link = req->lr_link; callout_stop(&req->lr_rtx); if (callout_invoking(&req->lr_rtx)) return; callout_destroy(&req->lr_rtx); TAILQ_REMOVE(&link->hl_reqs, req, lr_next); pool_put(&l2cap_req_pool, req); } /* * Response Timeout eXpired * * No response to our request, so deal with it as best we can. * * XXX should try again at least with ertx? */ void l2cap_rtx(void *arg) { struct l2cap_req *req = arg; struct l2cap_channel *chan; mutex_enter(bt_lock); callout_ack(&req->lr_rtx); chan = req->lr_chan; l2cap_request_free(req); DPRINTF("cid %d, ident %d\n", (chan ? chan->lc_lcid : 0), req->lr_id); if (chan && chan->lc_state != L2CAP_CLOSED) l2cap_close(chan, ETIMEDOUT); mutex_exit(bt_lock); } /* * Allocate next available CID to channel. We keep a single * ordered list of channels, so find the first gap. * * If this turns out to be not enough (!), could use a * list per HCI unit.. */ int l2cap_cid_alloc(struct l2cap_channel *chan) { struct l2cap_channel *used, *prev = NULL; uint16_t cid = L2CAP_FIRST_CID; if (chan->lc_lcid != L2CAP_NULL_CID || chan->lc_state != L2CAP_CLOSED) return EISCONN; LIST_FOREACH(used, &l2cap_active_list, lc_ncid) { if (used->lc_lcid > cid) break; /* found our gap */ KASSERT(used->lc_lcid == cid); cid++; if (cid == L2CAP_LAST_CID) return ENFILE; prev = used; /* for insert after */ } chan->lc_lcid = cid; if (prev) LIST_INSERT_AFTER(prev, chan, lc_ncid); else LIST_INSERT_HEAD(&l2cap_active_list, chan, lc_ncid); return 0; } /* * Find channel with CID */ struct l2cap_channel * l2cap_cid_lookup(uint16_t cid) { struct l2cap_channel *chan; LIST_FOREACH(chan, &l2cap_active_list, lc_ncid) { if (chan->lc_lcid == cid) return chan; if (chan->lc_lcid > cid) return NULL; } return NULL; }
{'content_hash': '59a5d3906d6796873cda8627d879c63e', 'timestamp': '', 'source': 'github', 'line_count': 266, 'max_line_length': 81, 'avg_line_length': 24.43609022556391, 'alnum_prop': 0.6741538461538461, 'repo_name': 'execunix/vinos', 'id': '2bcf64614cb4fe7cdf32f2177ba4f1c096e40736', 'size': '6500', 'binary': False, 'copies': '2', 'ref': 'refs/heads/master', 'path': 'sys/netbt/l2cap_misc.c', 'mode': '33188', 'license': 'apache-2.0', 'language': []}
Playing around with resource based routing in MVC 6/ASP.NET 5
{'content_hash': 'd06e0e89344211338b0c92eb90bababf', 'timestamp': '', 'source': 'github', 'line_count': 1, 'max_line_length': 61, 'avg_line_length': 62.0, 'alnum_prop': 0.8064516129032258, 'repo_name': 'yishaigalatzer/ResourceController', 'id': 'fd7c0d6c399934aba1457513680cb4073977d8b5', 'size': '83', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'README.md', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'C#', 'bytes': '8511'}]}
<?php namespace app; require_once __DIR__ . '/../composer_modules/autoload.php'; class ClasseTwigExtension extends \Slim\Views\TwigExtension { public function getName() { return 'classe-twig-extension'; } public function getFilters() { return array( new \Twig_SimpleFilter('md5', 'md5_file'), ); } } //EOF
{'content_hash': 'ae9137c15f5838b42bb28e4a8767cac1', 'timestamp': '', 'source': 'github', 'line_count': 21, 'max_line_length': 61, 'avg_line_length': 17.333333333333332, 'alnum_prop': 0.6071428571428571, 'repo_name': 'GregDesplaces/classe-1914', 'id': '9f0d483649436e9a04a8b54df1b36cca46f68615', 'size': '364', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'app/filters.php', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'ApacheConf', 'bytes': '312'}, {'name': 'CSS', 'bytes': '162196'}, {'name': 'CoffeeScript', 'bytes': '288644'}, {'name': 'HTML', 'bytes': '54170'}, {'name': 'JavaScript', 'bytes': '12279'}, {'name': 'Makefile', 'bytes': '108'}, {'name': 'PHP', 'bytes': '44160'}]}
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % RESULTS %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%% % FraCaS INTRO %%%%%%%%%%%%%%%%%%% \begin{frame}{Experiments} \hh{FraCaS Textual Entailment Suite:} \begin{itemize} \item Used in MacCartney and Manning (2007; 2008). \item RTE-style problems: is the hypothesis entailed from the premise? \\ \vspace{0.1cm} P: At least three commissioners spend a lot of time at home. \\ H: \true{At least three commissioners spend time at home.} \\ \vspace{0.1cm} P: At most ten commissioners spend a lot of time at home. \\ H: \false{At most ten commissioners spend time at home.} \vspace{0.1cm} \item 9 focused sections; 3 in scope for this work. \end{itemize} \vspace{0.5cm} \pause \hh{\textbf{Not} a blind test set!} \begin{itemize} \item ``Can we make deep inferences without knowing the premise \textit{a priori}?'' \end{itemize} \end{frame} %%%%%%%%%%%%%%%%%%% % FraCaS RESULTS %%%%%%%%%%%%%%%%%%% \def\a#1{#1} \def\b#1{\textbf{#1}} \begin{frame}{FraCaS Results} \hh{Systems} \begin{itemize} \item[] \textbf{M07}: MacCartney and Manning (2007) \item[] \textbf{M08}: MacCartney and Manning (2008) \begin{itemize} \item \textit{Classify} entailment after aligning premise and hypothesis. \end{itemize} \item[] \darkblue{\textbf{N}: NaturalLI (this work)} \begin{itemize} \item \textit{Search} blindly from hypothesis for the premise. \end{itemize} \end{itemize} \pause \begin{center} \begin{tabular}{llccc} \hline $\mathsection$ & Category & \multicolumn{3}{c}{Accuracy} \\ & & M07 & M08 & \darkblue{N} \\ \hline % Pme P07 Rme R08 Ame A07 A08 \a{1} & \a{Quantifiers} & \a{84} & \a{97} & \a{\darkblue{95}} \\ \a{5} & \a{Adjectives} & \a{60} & \a{80} & \a{\darkblue{73}} \\ \a{6} & \a{Comparatives} & \a{69} & \a{81} & \a{\darkblue{87}} \pause \\ \hline \multicolumn{2}{l}{\b{Applicable (1,5,6)}} & \b{76} & \b{90} & \b{\darkblue{89}} \\ \hline \end{tabular} \end{center} \end{frame} %%%%%%%%%%%%%%%%%%% % ConceptNet INTRO %%%%%%%%%%%%%%%%%%% \begin{frame}{Experiments} \hh{ConceptNet:} \begin{itemize} \item A semi-curated collection of common-sense facts. \\ \vspace{0.1cm} \true{not all birds can fly} \\ \true{noses are used to smell} \\ \true{nobody wants to die} \\ \true{music is used for pleasure} \vspace{0.1cm} \item Negatives: ReVerb extractions marked false by Turkers. \item Small (1378 train / 1080 test), but fairly broad coverage. \end{itemize} \vspace{0.5cm} \pause \hh{Our Knowledge Base:} \begin{itemize} \item 270 million lemmatized Ollie extractions. \end{itemize} \end{frame} %%%%%%%%%%%%%%%%%%% % ConceptNet RESULTS %%%%%%%%%%%%%%%%%%% \begin{frame}{ConceptNet Results} \hh{Systems} \begin{itemize} \item[] \textbf{Direct Lookup}: Lookup by lemmas. \item[] \textbf{NaturalLI}: Our system. \pause \item[] \textbf{NaturalLI Only}: Use only inference (prohibit exact matches). \end{itemize} \pause \begin{center} \begin{tabular}{lcc} System & P & R \\ \hline Direct Lookup & 100.0 & \textbf<5-5>{12.1} \\ \pause NaturalLI Only & 88.8 & 40.1 \\ NaturalLI & 90.6 & \textbf<5-5>{49.1} \\ \end{tabular} \end{center} \pause \begin{itemize} \item 4x improvement in recall. \end{itemize} \end{frame}
{'content_hash': '06c982b263a8896ae700084537904a35', 'timestamp': '', 'source': 'github', 'line_count': 123, 'max_line_length': 87, 'avg_line_length': 29.056910569105693, 'alnum_prop': 0.5707890318970341, 'repo_name': 'gangeli/NaturalLI', 'id': 'd1a75d8985a5e43abb7b3b4565578fe4da7c61e4', 'size': '3574', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'pub/emnlp2014/talk/results.tex', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'C', 'bytes': '183643'}, {'name': 'C++', 'bytes': '1713021'}, {'name': 'Gnuplot', 'bytes': '38536'}, {'name': 'HTML', 'bytes': '16689'}, {'name': 'Java', 'bytes': '286686'}, {'name': 'JavaScript', 'bytes': '21399'}, {'name': 'M4', 'bytes': '21276'}, {'name': 'Makefile', 'bytes': '25489'}, {'name': 'Python', 'bytes': '74592'}, {'name': 'Roff', 'bytes': '2511'}, {'name': 'Ruby', 'bytes': '21826'}, {'name': 'Shell', 'bytes': '95934'}, {'name': 'TeX', 'bytes': '1160929'}]}
This application makes use of the following third party libraries: ## Realm TABLE OF CONTENTS 1. Apache License version 2.0 2. Realm Components 3. Export Compliance ------------------------------------------------------------------------------- Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 1. Definitions. "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. 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. "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor 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 Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and (b) You must cause any modified files to carry prominent notices stating that You changed the files; and (c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and (d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. REALM COMPONENTS This software contains components with separate copyright and license terms. Your use of these components is subject to the terms and conditions of the following licenses. For the Realm Core component Realm Core Binary License Copyright (c) 2011-2016 Realm Inc All rights reserved Redistribution and use in binary form, with or without modification, is permitted provided that the following conditions are met: 1. You agree not to attempt to decompile, disassemble, reverse engineer or otherwise discover the source code from which the binary code was derived. You may, however, access and obtain a separate license for most of the source code from which this Software was created, at http://realm.io/pricing/. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER 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. EXPORT COMPLIANCE You understand that the Software may contain cryptographic functions that may be subject to export restrictions, and you represent and warrant that you are not (i) located in a jurisdiction that is subject to United States economic sanctions (“Prohibited Jurisdiction”), including Cuba, Iran, North Korea, Sudan, Syria or the Crimea region, (ii) a person listed on any U.S. government blacklist (to include the List of Specially Designated Nationals and Blocked Persons or the Consolidated Sanctions List administered by the U.S. Department of the Treasury’s Office of Foreign Assets Control, or the Denied Persons List or Entity List administered by the U.S. Department of Commerce) (“Sanctioned Person”), or (iii) controlled or 50% or more owned by a Sanctioned Person. You agree to comply with all export, re-export and import restrictions and regulations of the U.S. Department of Commerce or other agency or authority of the United States or other applicable countries. You also agree not to transfer, or authorize the transfer of, directly or indirectly, of the Software to any Prohibited Jurisdiction, or otherwise in violation of any such restrictions or regulations. Generated by CocoaPods - http://cocoapods.org
{'content_hash': '0bf1fa83a71fe3ba1955ef75d0808808', 'timestamp': '', 'source': 'github', 'line_count': 250, 'max_line_length': 80, 'avg_line_length': 54.312, 'alnum_prop': 0.742966563558698, 'repo_name': 'sajeel/GoEuro', 'id': 'd3e3e4256c24d8df3a6139db577b4a0ca49c3fd0', 'size': '13607', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'GoEuro/Pods/Target Support Files/Pods-GoEuroTests/Pods-GoEuroTests-acknowledgements.markdown', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'C', 'bytes': '69850'}, {'name': 'C++', 'bytes': '2450416'}, {'name': 'DTrace', 'bytes': '412'}, {'name': 'Objective-C', 'bytes': '1418779'}, {'name': 'Objective-C++', 'bytes': '413147'}, {'name': 'Ruby', 'bytes': '385'}, {'name': 'Shell', 'bytes': '63363'}, {'name': 'Swift', 'bytes': '7664'}]}
class hsfcStatistic { public: hsfcStatistic(void); ~hsfcStatistic(void); void Initialise(); void AddObservation(double Value); double Average(); double StdDev(); double Count; double Sum; double Sum2; protected: private: }; //============================================================================= // CLASS: hsfcLexicon //============================================================================= class hsfcLexicon { public: hsfcLexicon(void); ~hsfcLexicon(void); void Initialise(hsfcParameters* Parameters); unsigned int Index(const char* Value); unsigned int RelationIndex(const char* Value, bool Add); unsigned int RelationIndex(unsigned int NameID); unsigned int GDLIndex(unsigned int ID); unsigned int NewRigidNameID(int Arity); void Parse(const char* Text, vector<hsfcTuple>& Reference); bool Match(unsigned int ID, const char* Text); bool PartialMatch(unsigned int ID, const char* Text); bool MatchText(unsigned int ID, const char* Text); bool IsVariable(unsigned int ID); bool IsUsed(const char* Letter, bool IgnoreComments); const char* Text(unsigned int ID); char* Copy(unsigned int ID, bool WithArity); const char* Relation(unsigned int ID); unsigned int Size(); unsigned int TrueFrom(unsigned int RelationIndex); unsigned int NextFrom(unsigned int RelationIndex); unsigned int InitFrom(unsigned int RelationIndex); void Print(); hsfcIO* IO; protected: private: unsigned int AddTerm(const char* Value); unsigned int AddName(const char* Value); vector<string> Term; vector<unsigned int> TermIndex; vector<string> RelationName; vector<unsigned int> RelationNameID; vector<bool> RelationIsRigid; int UniqueNum; };
{'content_hash': 'f76c3831d0f5e8da2cfd1fe190a183c9', 'timestamp': '', 'source': 'github', 'line_count': 68, 'max_line_length': 79, 'avg_line_length': 24.794117647058822, 'alnum_prop': 0.6856465005931198, 'repo_name': 'AbdallahS/ggp-hsfc', 'id': 'f2e6d3b12859af4daf38d563a1b8de95d3a467e3', 'size': '2297', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'libhsfc/src/hsfcLexicon.h', 'mode': '33188', 'license': 'bsd-2-clause', 'language': [{'name': 'C', 'bytes': '25158'}, {'name': 'C++', 'bytes': '629133'}, {'name': 'CMake', 'bytes': '3754'}, {'name': 'Makefile', 'bytes': '466'}, {'name': 'Objective-C', 'bytes': '309'}, {'name': 'Python', 'bytes': '25958'}, {'name': 'Shell', 'bytes': '1139'}]}
/* vim: set ts=2 et sw=2 tw=80: */ /* Any copyright is dedicated to the Public Domain. http://creativecommons.org/publicdomain/zero/1.0/ */ let tempScope = {}; Cu.import("resource:///modules/devtools/CssRuleView.jsm", tempScope); let CssRuleView = tempScope.CssRuleView; let _ElementStyle = tempScope._ElementStyle; let _editableField = tempScope._editableField; let inplaceEditor = tempScope._getInplaceEditorForSpan; let doc; let ruleDialog; let ruleView; var gRuleViewChanged = false; function ruleViewChanged() { gRuleViewChanged = true; } function expectChange() { ok(gRuleViewChanged, "Rule view should have fired a change event."); gRuleViewChanged = false; } function startTest() { let style = '' + '#testid {' + ' background-color: blue;' + '} ' + '.testclass {' + ' background-color: green;' + '}'; let styleNode = addStyle(doc, style); doc.body.innerHTML = '<div id="testid" class="testclass">Styled Node</div>'; let testElement = doc.getElementById("testid"); ruleDialog = openDialog("chrome://browser/content/devtools/cssruleview.xul", "cssruleviewtest", "width=200,height=350"); ruleDialog.addEventListener("load", function onLoad(evt) { ruleDialog.removeEventListener("load", onLoad, true); let doc = ruleDialog.document; ruleView = new CssRuleView(doc); doc.documentElement.appendChild(ruleView.element); ruleView.element.addEventListener("CssRuleViewChanged", ruleViewChanged, false); ruleView.highlight(testElement); waitForFocus(testCancelNew, ruleDialog); }, true); } function testCancelNew() { // Start at the beginning: start to add a rule to the element's style // declaration, but leave it empty. let elementRuleEditor = ruleView.element.children[0]._ruleEditor; waitForEditorFocus(elementRuleEditor.element, function onNewElement(aEditor) { is(inplaceEditor(elementRuleEditor.newPropSpan), aEditor, "Next focused editor should be the new property editor."); let input = aEditor.input; waitForEditorBlur(aEditor, function () { ok(!gRuleViewChanged, "Shouldn't get a change event after a cancel."); is(elementRuleEditor.rule.textProps.length, 0, "Should have canceled creating a new text property."); ok(!elementRuleEditor.propertyList.hasChildNodes(), "Should not have any properties."); testCreateNew(); }); aEditor.input.blur(); }); EventUtils.synthesizeMouse(elementRuleEditor.closeBrace, 1, 1, { }, ruleDialog); } function testCreateNew() { // Create a new property. let elementRuleEditor = ruleView.element.children[0]._ruleEditor; waitForEditorFocus(elementRuleEditor.element, function onNewElement(aEditor) { is(inplaceEditor(elementRuleEditor.newPropSpan), aEditor, "Next focused editor should be the new property editor."); let input = aEditor.input; input.value = "background-color"; waitForEditorFocus(elementRuleEditor.element, function onNewValue(aEditor) { expectChange(); is(elementRuleEditor.rule.textProps.length, 1, "Should have created a new text property."); is(elementRuleEditor.propertyList.children.length, 1, "Should have created a property editor."); let textProp = elementRuleEditor.rule.textProps[0]; is(aEditor, inplaceEditor(textProp.editor.valueSpan), "Should be editing the value span now."); aEditor.input.value = "#XYZ"; waitForEditorBlur(aEditor, function() { expectChange(); is(textProp.value, "#XYZ", "Text prop should have been changed."); is(textProp.editor._validate(), false, "#XYZ should not be a valid entry"); testEditProperty(); }); aEditor.input.blur(); }); EventUtils.synthesizeKey("VK_RETURN", {}, ruleDialog); }); EventUtils.synthesizeMouse(elementRuleEditor.closeBrace, 1, 1, { }, ruleDialog); } function testEditProperty() { let idRuleEditor = ruleView.element.children[1]._ruleEditor; let propEditor = idRuleEditor.rule.textProps[0].editor; waitForEditorFocus(propEditor.element, function onNewElement(aEditor) { is(inplaceEditor(propEditor.nameSpan), aEditor, "Next focused editor should be the name editor."); let input = aEditor.input; waitForEditorFocus(propEditor.element, function onNewName(aEditor) { expectChange(); input = aEditor.input; is(inplaceEditor(propEditor.valueSpan), aEditor, "Focus should have moved to the value."); waitForEditorBlur(aEditor, function() { expectChange(); let value = idRuleEditor.rule.style.getPropertyValue("border-color"); is(value, "red", "border-color should have been set."); is(propEditor._validate(), true, "red should be a valid entry"); finishTest(); }); for each (let ch in "red;") { EventUtils.sendChar(ch, ruleDialog); } }); for each (let ch in "border-color:") { EventUtils.sendChar(ch, ruleDialog); } }); EventUtils.synthesizeMouse(propEditor.nameSpan, 1, 1, { }, ruleDialog);} function finishTest() { ruleView.element.removeEventListener("CssRuleViewChanged", ruleViewChanged, false); ruleView.clear(); ruleDialog.close(); ruleDialog = ruleView = null; doc = null; gBrowser.removeCurrentTab(); finish(); } function test() { waitForExplicitFinish(); gBrowser.selectedTab = gBrowser.addTab(); gBrowser.selectedBrowser.addEventListener("load", function changedValues_load(evt) { gBrowser.selectedBrowser.removeEventListener(evt.type, changedValues_load, true); doc = content.document; waitForFocus(startTest, content); }, true); content.location = "data:text/html,test rule view user changes"; }
{'content_hash': '20651aec6bed0faf331c62345a9962a1', 'timestamp': '', 'source': 'github', 'line_count': 166, 'max_line_length': 120, 'avg_line_length': 35.475903614457835, 'alnum_prop': 0.6809305484802174, 'repo_name': 'sergecodd/FireFox-OS', 'id': 'aed4c6dd886c1dd6f96469613f8abad8c2e31a1c', 'size': '5889', 'binary': False, 'copies': '2', 'ref': 'refs/heads/master', 'path': 'B2G/gecko/browser/devtools/styleinspector/test/browser_ruleview_editor_changedvalues.js', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'Ada', 'bytes': '443'}, {'name': 'ApacheConf', 'bytes': '85'}, {'name': 'Assembly', 'bytes': '5123438'}, {'name': 'Awk', 'bytes': '46481'}, {'name': 'Batchfile', 'bytes': '56250'}, {'name': 'C', 'bytes': '101720951'}, {'name': 'C#', 'bytes': '38531'}, {'name': 'C++', 'bytes': '148896543'}, {'name': 'CMake', 'bytes': '23541'}, {'name': 'CSS', 'bytes': '2758664'}, {'name': 'DIGITAL Command Language', 'bytes': '56757'}, {'name': 'Emacs Lisp', 'bytes': '12694'}, {'name': 'Erlang', 'bytes': '889'}, {'name': 'FLUX', 'bytes': '34449'}, {'name': 'GLSL', 'bytes': '26344'}, {'name': 'Gnuplot', 'bytes': '710'}, {'name': 'Groff', 'bytes': '447012'}, {'name': 'HTML', 'bytes': '43343468'}, {'name': 'IDL', 'bytes': '1455122'}, {'name': 'Java', 'bytes': '43261012'}, {'name': 'JavaScript', 'bytes': '46646658'}, {'name': 'Lex', 'bytes': '38358'}, {'name': 'Logos', 'bytes': '21054'}, {'name': 'Makefile', 'bytes': '2733844'}, {'name': 'Matlab', 'bytes': '67316'}, {'name': 'Max', 'bytes': '3698'}, {'name': 'NSIS', 'bytes': '421625'}, {'name': 'Objective-C', 'bytes': '877657'}, {'name': 'Objective-C++', 'bytes': '737713'}, {'name': 'PHP', 'bytes': '17415'}, {'name': 'Pascal', 'bytes': '6780'}, {'name': 'Perl', 'bytes': '1153180'}, {'name': 'Perl6', 'bytes': '1255'}, {'name': 'PostScript', 'bytes': '1139'}, {'name': 'PowerShell', 'bytes': '8252'}, {'name': 'Protocol Buffer', 'bytes': '26553'}, {'name': 'Python', 'bytes': '8453201'}, {'name': 'Ragel in Ruby Host', 'bytes': '3481'}, {'name': 'Ruby', 'bytes': '5116'}, {'name': 'Scilab', 'bytes': '7'}, {'name': 'Shell', 'bytes': '3383832'}, {'name': 'SourcePawn', 'bytes': '23661'}, {'name': 'TeX', 'bytes': '879606'}, {'name': 'WebIDL', 'bytes': '1902'}, {'name': 'XSLT', 'bytes': '13134'}, {'name': 'Yacc', 'bytes': '112744'}]}
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>FST - Gabe Kling</title> <meta name="description" content="Keep track of the statistics from Gabe Kling. Average heat score, heat wins, heat wins percentage, epic heats road to the final"> <meta name="author" content=""> <link rel="apple-touch-icon" sizes="57x57" href="/favicon/apple-icon-57x57.png"> <link rel="apple-touch-icon" sizes="60x60" href="/favicon/apple-icon-60x60.png"> <link rel="apple-touch-icon" sizes="72x72" href="/favicon/apple-icon-72x72.png"> <link rel="apple-touch-icon" sizes="76x76" href="/favicon/apple-icon-76x76.png"> <link rel="apple-touch-icon" sizes="114x114" href="/favicon/apple-icon-114x114.png"> <link rel="apple-touch-icon" sizes="120x120" href="/favicon/apple-icon-120x120.png"> <link rel="apple-touch-icon" sizes="144x144" href="/favicon/apple-icon-144x144.png"> <link rel="apple-touch-icon" sizes="152x152" href="/favicon/apple-icon-152x152.png"> <link rel="apple-touch-icon" sizes="180x180" href="/favicon/apple-icon-180x180.png"> <link rel="icon" type="image/png" sizes="192x192" href="/favicon/android-icon-192x192.png"> <link rel="icon" type="image/png" sizes="32x32" href="/favicon/favicon-32x32.png"> <link rel="icon" type="image/png" sizes="96x96" href="/favicon/favicon-96x96.png"> <link rel="icon" type="image/png" sizes="16x16" href="/favicon/favicon-16x16.png"> <link rel="manifest" href="/manifest.json"> <meta name="msapplication-TileColor" content="#ffffff"> <meta name="msapplication-TileImage" content="/ms-icon-144x144.png"> <meta name="theme-color" content="#ffffff"> <meta property="og:title" content="Fantasy Surfing tips"/> <meta property="og:image" content="https://fantasysurfingtips.com/img/just_waves.png"/> <meta property="og:description" content="See how great Gabe Kling is surfing this year"/> <!-- Bootstrap Core CSS - Uses Bootswatch Flatly Theme: https://bootswatch.com/flatly/ --> <link href="https://fantasysurfingtips.com/css/bootstrap.css" rel="stylesheet"> <!-- Custom CSS --> <link href="https://fantasysurfingtips.com/css/freelancer.css" rel="stylesheet"> <link href="https://cdn.datatables.net/plug-ins/1.10.7/integration/bootstrap/3/dataTables.bootstrap.css" rel="stylesheet" /> <!-- Custom Fonts --> <link href="https://fantasysurfingtips.com/font-awesome/css/font-awesome.min.css" rel="stylesheet" type="text/css"> <link href="https://fonts.googleapis.com/css?family=Montserrat:400,700" rel="stylesheet" type="text/css"> <link href="https://fonts.googleapis.com/css?family=Lato:400,700,400italic,700italic" rel="stylesheet" type="text/css"> <link rel="stylesheet" href="//cdnjs.cloudflare.com/ajax/libs/morris.js/0.5.1/morris.css"> <script src="https://code.jquery.com/jquery-2.x-git.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-ujs/1.2.1/rails.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/raphael/2.1.0/raphael-min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/morris.js/0.5.1/morris.min.js"></script> <script src="https://www.w3schools.com/lib/w3data.js"></script> <script async src="//pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"></script> <script> (adsbygoogle = window.adsbygoogle || []).push({ google_ad_client: "ca-pub-2675412311042802", enable_page_level_ads: true }); </script> </head> <body> <div id="fb-root"></div> <script>(function(d, s, id) { var js, fjs = d.getElementsByTagName(s)[0]; if (d.getElementById(id)) return; js = d.createElement(s); js.id = id; js.src = "//connect.facebook.net/en_GB/sdk.js#xfbml=1&version=v2.6"; fjs.parentNode.insertBefore(js, fjs); }(document, 'script', 'facebook-jssdk'));</script> <!-- Navigation --> <div w3-include-html="https://fantasysurfingtips.com/layout/header.html"></div> <!-- Header --> <div w3-include-html="https://fantasysurfingtips.com/layout/sponsor.html"></div> <section > <div class="container"> <div class="row"> <div class="col-sm-3 "> <div class="col-sm-2 "> </div> <div class="col-sm-8 "> <!-- <img src="http://fantasysurfingtips.com/img/surfers/gkli.png" class="img-responsive" alt=""> --> <h3 style="text-align:center;">Gabe Kling</h3> <a href="https://twitter.com/share" class="" data-via="fansurfingtips"><i class="fa fa-twitter"></i> Share on Twitter</i></a> <br/> <a class="fb-xfbml-parse-ignore" target="_blank" href="https://www.facebook.com/sharer/sharer.php?u=http%3A%2F%2Ffantasysurfingtips.com%2Fsurfers%2Fgkli&amp;src=sdkpreparse"><i class="fa fa-facebook"></i> Share on Facebook</a> </div> <div class="col-sm-2 "> </div> </div> <div class="col-sm-3 portfolio-item"> </div> <div class="col-sm-3 portfolio-item"> <h6 style="text-align:center;">Avg Heat Score (FST DATA)</h6> <h1 style="text-align:center;">12.0</h1> </div> </div> <h4 style="text-align:center;" >Epic Battles</h4> <div class="row"> <div class="col-sm-6 "> <p style="text-align:center;">Surfed <b>1</b> heats against <a href="http://fantasysurfingtips.com/surfers/mqs/ksch.html"> Kevin Schulz</a> <br/> <b>won 1</b> and <b>lost 0</b></p> </div> <div class="col-sm-6 "> <p style="text-align:center;">Surfed <b>4</b> heats against <a href="http://fantasysurfingtips.com/surfers/mqs/egat.html"> Elijah Gates</a> <br/> <b>won 0</b> and <b>lost 4</b></p> </div> </div> <hr/> <h4 style="text-align:center;" >Heat Stats (FST data)</h4> <div class="row"> <div class="col-sm-4 portfolio-item"> <h6 style="text-align:center;">Heats</h6> <h2 style="text-align:center;">52</h2> </div> <div class="col-sm-4 portfolio-item"> <h6 style="text-align:center;">Heat wins</h6> <h2 style="text-align:center;">3</h2> </div> <div class="col-sm-4 portfolio-item"> <h6 style="text-align:center;">HEAT WINS PERCENTAGE</h6> <h2 style="text-align:center;">5.77%</h2> </div> </div> <hr/> <h4 style="text-align:center;">Avg Heat Score progression</h4> <div id="avg_chart" style="height: 250px;"></div> <hr/> <h4 style="text-align:center;">Heat stats progression</h4> <div id="heat_chart" style="height: 250px;"></div> <hr/> <style type="text/css"> .heats-all{ z-index: 3; margin-left: 5px; cursor: pointer; } </style> <div class="container"> <div id="disqus_thread"></div> <script> /** * RECOMMENDED CONFIGURATION VARIABLES: EDIT AND UNCOMMENT THE SECTION BELOW TO INSERT DYNAMIC VALUES FROM YOUR PLATFORM OR CMS. * LEARN WHY DEFINING THESE VARIABLES IS IMPORTANT: https://disqus.com/admin/universalcode/#configuration-variables*/ var disqus_config = function () { this.page.url = "http://fantasysurfingtips.com/surfers/gkli"; // Replace PAGE_URL with your page's canonical URL variable this.page.identifier = '1233'; // Replace PAGE_IDENTIFIER with your page's unique identifier variable }; (function() { // DON'T EDIT BELOW THIS LINE var d = document, s = d.createElement('script'); s.src = '//fantasysurfingtips.disqus.com/embed.js'; s.setAttribute('data-timestamp', +new Date()); (d.head || d.body).appendChild(s); })(); </script> <noscript>Please enable JavaScript to view the <a href="https://disqus.com/?ref_noscript">comments powered by Disqus.</a></noscript> </div> </section> <script type="text/javascript"> $('.heats-all').click(function(){ $('.heats-all-stat').css('display', 'none') $('#'+$(this).attr('id')+'-stat').css('display', 'block') }); $('.heats-2016').click(function(){ $('.heats-2016-stat').css('display', 'none') $('#'+$(this).attr('id')+'-stat').css('display', 'block') }); $('document').ready(function(){ new Morris.Line({ // ID of the element in which to draw the chart. element: 'avg_chart', // Chart data records -- each entry in this array corresponds to a point on // the chart. data: [], // The name of the data record attribute that contains x-values. xkey: 'year', // A list of names of data record attributes that contain y-values. ykeys: ['avg', 'avg_all'], // Labels for the ykeys -- will be displayed when you hover over the // chart. labels: ['Avg score in year', 'Avg score FST DATA'] }); new Morris.Bar({ // ID of the element in which to draw the chart. element: 'heat_chart', // Chart data records -- each entry in this array corresponds to a point on // the chart. data: [], // The name of the data record attribute that contains x-values. xkey: 'year', // A list of names of data record attributes that contain y-values. ykeys: ['heats', 'wins', 'percs'], // Labels for the ykeys -- will be displayed when you hover over the // chart. labels: ['Heats surfed', 'Heats won', 'Winning percentage'] }); }); </script> <script>!function(d,s,id){var js,fjs=d.getElementsByTagName(s)[0],p=/^http:/.test(d.location)?'http':'https';if(!d.getElementById(id)){js=d.createElement(s);js.id=id;js.src=p+'://platform.twitter.com/widgets.js';fjs.parentNode.insertBefore(js,fjs);}}(document, 'script', 'twitter-wjs');</script> <!-- Footer --> <div w3-include-html="https://fantasysurfingtips.com/layout/footer.html"></div> <script type="text/javascript"> (function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){ (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o), m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m) })(window,document,'script','//www.google-analytics.com/analytics.js','ga'); ga('create', 'UA-74337819-1', 'auto'); // Replace with your property ID. ga('send', 'pageview'); </script> <script> w3IncludeHTML(); </script> <!-- jQuery --> <script src="https://fantasysurfingtips.com/js/jquery.js"></script> <script src="https://cdn.datatables.net/1.10.7/js/jquery.dataTables.min.js"></script> <!-- Bootstrap Core JavaScript --> <script src="https://fantasysurfingtips.com/js/bootstrap.min.js"></script> <!-- Plugin JavaScript --> <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-easing/1.3/jquery.easing.min.js"></script> <script src="https://fantasysurfingtips.com/js/classie.js"></script> <script src="https://fantasysurfingtips.com/js/cbpAnimatedHeader.js"></script> <!-- Contact Form JavaScript --> <script src="https://fantasysurfingtips.com/js/jqBootstrapValidation.js"></script> <script src="https://fantasysurfingtips.com/js/contact_me.js"></script> <!-- Custom Theme JavaScript --> <script src="https://fantasysurfingtips.com/js/freelancer.js"></script> <script type="https://cdn.datatables.net/1.10.12/js/jquery.dataTables.min.js"></script> <script type="https://cdn.datatables.net/1.10.12/js/dataTables.bootstrap.min.js"></script> </body> </html>
{'content_hash': '43c8a11dfb3300514647e6a5723fb092', 'timestamp': '', 'source': 'github', 'line_count': 294, 'max_line_length': 295, 'avg_line_length': 40.1156462585034, 'alnum_prop': 0.6247244361539765, 'repo_name': 'chicofilho/fst', 'id': '0a4eef9465221007571ce993b25e2e1f400d3b75', 'size': '11794', 'binary': False, 'copies': '1', 'ref': 'refs/heads/gh-pages', 'path': 'surfers/mqs/gkli.html', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'CSS', 'bytes': '25157'}, {'name': 'HTML', 'bytes': '114679577'}, {'name': 'JavaScript', 'bytes': '43263'}, {'name': 'PHP', 'bytes': '1097'}]}
package org.ovirt.mobile.movirt.rest.dto.v4; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import org.ovirt.mobile.movirt.model.enums.SnapshotType; @JsonIgnoreProperties(ignoreUnknown = true) public class Snapshot extends org.ovirt.mobile.movirt.rest.dto.Snapshot { public SnapshotVm vm; public String snapshot_type; public Snapshot() { } public Snapshot(String description, boolean persistMemoryState) { super(description, persistMemoryState); } public org.ovirt.mobile.movirt.model.Snapshot toEntity(String accountId) { org.ovirt.mobile.movirt.model.Snapshot snapshot = super.toEntity(accountId); snapshot.setType(SnapshotType.fromString(snapshot_type)); if (vm != null) { vm.snapshotId = snapshot.getId(); snapshot.setVm(vm.toEntity(accountId)); } return snapshot; } }
{'content_hash': '22d7892177c4f5d5a5bd16cecf2c4edb', 'timestamp': '', 'source': 'github', 'line_count': 30, 'max_line_length': 84, 'avg_line_length': 30.0, 'alnum_prop': 0.7066666666666667, 'repo_name': 'matobet/moVirt', 'id': '054f289c18687370efc676bcf91c0f5f3c9a7828', 'size': '900', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'moVirt/src/main/java/org/ovirt/mobile/movirt/rest/dto/v4/Snapshot.java', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'Batchfile', 'bytes': '86'}, {'name': 'Java', 'bytes': '826816'}]}
\section{Abstract} Rossby waves are a way to conceptualize large scale, time-dependent motion in the atmosphere and ocean. Analytically we expect Rossby waves to travel westwards, and this was tested numerically with different time-stepping methods for a periodic and finite domain. \\ The numerical results show that Rossby waves travel westwards. For the finite domain the Rossby wave hits the wall and is reflected backwards to the east. This results in some resonance for the finite case. For the periodic case only regular sinusoidal shaped waves of constant amplitude was observed. \section{Introduction} In this project I will study Rossby waves. Rossby waves are a way to conceptualize large scale, time-dependent motion in the atmosphere and ocean. These waves typically have scales of hundreds to thousands of kilometers. Two examples of phenomenon that we try to understand with Rossby waves is the meandering of the atmospheric Jet Stream, and the adjustment of the ocean to changes in wind forcing, also called geostrophic adjustment.\cite{geofludyn} Rossby waves exist because of the Coriolis acceleration, which acts perpendicular to the velocity of a fluid parcel. In the Northern Hemisphere we have positive Coriolis acceleration, and in the Southern Hemisphere we have negative Coriolis. The Coriolis acceleration varies with latitude, strengthens towards the poles and weakens towards the equator. This is also why Rossby waves are treated a bit differently around the equator, and most of the time examined in mid- or high- latitudes. \cite{rossby} Around the equator we usually apply the equatorial beta plane approximation ($f=\beta y$, where $\beta$ is the variation of Coriolis in the y-direction(north-south) given by $\beta = df/dy$), where we may study equatorial Kelvin waves, which are lightning bolts compared to Rossby waves. Without a mean flow, equatorial Rossby waves (slow waves propagating with speeds on order of cm/s) are observed to travel west and Kelvin waves travel east (propagation speeds on order of m/s) around the equator.\cite{equator}\\ The variation in Coriolis acceleration with latitude causes fluid parcels to change their spin, in context of a continuum called the vorticity \cite{vorticity}, as they move to different latitudes.\\ Introducing short hand notations for derivatives in as shown below:\\ $\partial_t = \frac{\partial}{\partial t}$\\ $\partial_x = \frac{\partial}{\partial x}$\\ $\partial_{xx} = \frac{\partial^2}{\partial x^2}$\\ The vorticity equation is then given as:\\ \begin{equation} \partial_t\zeta + \beta\partial_x\psi = 0 \end{equation}\\ Where $\zeta$ is the vorticity, $\beta$ comes from the $\beta$-plane approximation explained below and $\psi$ is the streamfunction determining the velocities:\\ \begin{equation} u = -\partial_y\psi \\\ , \\\ v = \partial_x\psi \end{equation}\\ Where u is the east-west velocity and v is the north-south velocity.\\ Vorticity is defined as the curl, and the horizontal Laplacian of the streamfunction:\\ \begin{equation} \zeta = \partial_xv - \partial_yu = \nabla^2_H\psi \end{equation}\\ The Coriolis parameter is defined by:\\ \begin{equation} f = 2\Omega sin(\theta) \end{equation}\\ where $\theta$ is the latitude and $\Omega$ is the rotation rate of the earth, $\Omega = 2\pi/day$. As hinted at before, we often approximate f as a linear function centered on a latitude $\theta_0$:\\ \begin{equation} f\approx f_0 + \beta y \end{equation}\\ where $f_0 = 2\Omega sin(\theta_0)$, $\beta = 2\Omega cos(\theta_0)/R_e$ and $y = R_e(\theta - \theta_0)$, if $R_e$ is the Earth's radius. This linear representation is called the $\beta$-plane approximation and is the $\beta$ term in equation (1). Using the definition of vorticity we can rewrite the vorticity equation (1) in terms of only one variable, the streamfunction:\\ \begin{equation} \partial_t\nabla^2_H\psi + \beta\partial_x\psi = 0 \end{equation}\\ This is the barotropic Rossby wave equation, barotropic meaning that the density variations are only dependent on the change in pressure.\\ We will examine solutions of the vorticity equation in a periodic and closed domain, both analytically and numerically. For the periodic case we can consider a re-entrant domain, like going around the Earth's atmosphere. For a closed domain we can think of continents acting as walls bounding the ocean. \section{Methods} \subsection{Analytical solutions} My calculations are mainly based on the lecture notes from geophysical fluid dynamics: \cite{geofludyn}\\ \subsubsection{Solution to the Rossby equation in a periodic domain} Consider the vorticity equation from (6) in one dimension. Assuming the periodic domain in x = [0,L] I can propose a wave solution on the form:\\ \begin{equation} \psi = Acos(\frac{2n\pi x}{L}-\omega t) \end{equation}\\ , where n is an integer, $\omega$ is the wave frequency and A is the amplitude.\\ I need to show that the solution on the two boundaries are the same, satisfying periodic domain, and then solve for $\omega$ to find the dispersion relation. Using the proposed wave solution in (7) I have the following:\\ \begin{equation} \begin{gathered} \zeta = \partial_xv = \partial_{xx}\psi\\ \partial_x\psi = -A\frac{2n\pi}{L}sin(\frac{2n\pi x}{L}-\omega t)\\ \zeta = \partial_{xx}\psi = -A(\frac{2n\pi}{L})^2cos(\frac{2n\pi x}{L}-\omega t)\\ \zeta(x=0,t) = -A(\frac{2n\pi}{L})^2cos(-\omega t)\\ \zeta(x=L,t) = -A(\frac{2n\pi}{L})^2cos(\frac{2n\pi L}{L}-\omega t) = -A(\frac{2n\pi}{L})^2cos(2n\pi-\omega t) = -A(\frac{2n\pi}{L})^2cos(-\omega t)\\ \end{gathered} \end{equation} Equation 8 shows that periodic boundary conditions are ok. Inserting $\zeta$ into equation (6) yields:\\ \begin{equation} \begin{gathered} \partial_t\nabla^2_H\psi + \beta\partial_x\psi = \partial_t\zeta + \beta\partial_x\psi =\\ -A(\frac{2n\pi}{L})^2\omega \sin(\frac{2n\pi x}{L}-\omega t) - \beta A\frac{2n\pi}{L}\sin(\frac{2n\pi x}{L}-\omega t)\\ \implies A\frac{2n\pi}{L}(\frac{2n\pi \omega}{L}+\beta)\sin(\frac{2n\pi x}{L}-\omega t) = 0\\ \implies \omega = -\frac{\beta L}{2\pi n} \end{gathered} \end{equation} This is the dispersion relation of the wave. The phase speed is the speed at which Rossby waves move. Consider the phase of the wave as:\\ $\theta = \frac{n\pi x}{L}-\omega t$\\ If we choose $\theta = 2\pi$ we get $\psi = Acos(2\pi) = A$, which means that we have a high pressure point with amplitude A. Solving for x we can find how this point moves, and taking the time derivative of that expression gives us an expression for the phase speed:\\ $x = \frac{\theta L}{2n\pi} + \frac{\omega tL}{2n\pi}$\\ $c = \frac{dx}{dt} = \frac{\omega L}{2n\pi}$\\ Inserting my expression for $\omega$ I get the Rossby phase speed in the x direction:\\ $c_x = \frac{\omega L}{2n\pi} = -\beta(\frac{L}{2n\pi})^2$\\ Thus, I find that the Rossby wave is moving westwards.\\ \subsubsection{Solution to the Rossby equation with solid boundaries} In the ocean it's more appropriate to apply boundary conditions of no flow at the two end points. This can be enforced with Dirichlet conditions: $\psi = 0$ at $x=0$ and $x=L$. Proposing a wave solution of the form:\\ \begin{equation} \psi = A(x)cos(kx-\omega t) \end{equation}\\ , where A(x) indicates that the amplitude has a structure which must be solved for the boundary conditions. Inserting the wave solution above into equation (6) I get the following:\\ \begin{equation} \begin{gathered} \psi(x=0,t) = \psi(x=L,t)=0\\ \psi(x,t)=A(x)cos(kx-\omega t)\\ \partial_x\psi = A'(x)cos(kx-\omega t) - A(x)ksin(kx-\omega t)\\ \zeta = \partial_{xx}\psi = A''(x)cos(kx-\omega t)-A'(x)ksin(kx-\omega t) - A'(x)ksin(kx-\omega t) - A(x)k^2cos(kx-\omega t) =\\ (A''(x)-A(x)k^2)cos(kx-\omega t)-2A'(x)ksin(kx-\omega t)\\ \implies \partial_t\zeta + \beta\partial_x\psi =\\ (A''(x)-A(x)k^2)\omega sin(kx-\omega t)+2A'(x)k\omega cos(kx-\omega t) + \beta(A'(x)cos(kx-\omega t) - A(x)ksin(kx-\omega t))\\ \implies ((A''(x)-A(x)k^2)\omega - \beta A(x)k)sin(kx-\omega t) + A'(x)(2k\omega + \beta)cos(kx-\omega t) = 0 \end{gathered} \end{equation}\\ This holds if:\\ $(A''(x)-A(x)k^2)\omega - \beta A(x)k = 0$\\ and solving for $\omega$ I find an initial expression for the dispersion relation. \\ $2k\omega + \beta = 0$\\ $\implies \omega = \frac{-\beta}{2k}$\\ and $c_x = \frac{\omega}{k} = \frac{-\beta}{2k^2}$\\ Solving for the structure:\\ \begin{equation} \begin{gathered} A''(x) - A(x)(k^2+\frac{\beta k}{\omega} = 0\\ r^2-(k^2+\frac{\beta k}{\omega})=0\\ r = \pm k\sqrt{1+\frac{\beta}{k\omega}}\\ = \pm k\sqrt{1-\frac{\beta}{k\beta/2k}} = \pm k\sqrt{1-2} = \pm ik\\ \implies A(x) = C\cos(kx) + D\sin(kx) \end{gathered} \end{equation}\\ Need to satisfy Dirichlet conditions:\\ \begin{equation} \begin{gathered} \psi(x=0,t) = A(0)\cos(-\omega t) = 0\\ \implies C + D\sin(0) = 0 \implies C = 0\\ \psi(x=L,t) = A(L)\cos(kL-\omega t) = 0\\ \implies A(L) = D\sin(kL) = 0\\ \implies kL = n\pi\\ \implies k_n = \frac{n\pi}{L}\\ \end{gathered} \end{equation}\\ I find that the allowed frequencies given by the dispersion relation becomes:\\ $\omega_n = \frac{-\beta L}{2\pi n}$\\ and the Rossby phase speed:\\ $c_x = \frac{\omega_n}{k_n} = \frac{\beta}{2}(\frac{L}{n\pi})^2$\\ The full wave solution becomes:\\ \begin{equation} \psi(x,t) = D\sin(\frac{n\pi x}{L})\cos(\frac{n\pi x}{L}+\frac{\beta Lt}{2\pi n}) \end{equation} , where D must be determined from the initial conditions for a specific problem. \subsection{Method for solving the barotropic Rossby wave equation numerically} A numerical solution to equation (6), involves two steps. If we know the velocity or streamfunction initially, we can advance the vorticity in time to a new time. Then the streamfunction at the new time is found by inverting equation (3). This process is repeated to find a complete numerical solution.\\ Since the vorticity does not vary with change in y-direction for the one dimensional case I have:\\ \begin{equation} \zeta = \partial_{xx}\psi \end{equation} This is a specification of equation (3), which is solved as the Poisson equation, the same way as used in project 1. We have the same form:\\ $u''(x) = f(x)$ , the Poisson structure is recognized as:\\ $\partial_{xx} \psi = \zeta$\\ which, for the rigid boundary conditions can be solved the exact same way: To discretize the equations, we assume a grid of equally-spaced points: \begin{equation} x_j = j\Delta x \end{equation} where $\Delta x$ is the grid spacing. We discretize time in a similar way: \begin{equation} t^n = n\Delta t \end{equation} where $\Delta t$ is the time step. Thus $t^0=0$, $t^1=\Delta t$, and so on.\\ We then approximate the derivatives by finite differences. For the spatial derivatives, we use centered-differences: \begin{align} \partial_x\psi &\approx \frac{\psi_{j+1}^{n} - \psi_{j-1}^{n}}{2\Delta x}, \\ \partial_{xx}\psi &\approx \frac{\psi_{j+1}^{n} - 2\psi_{j}^{n} + \psi_{j-1}^{n}}{\Delta x^2}, \end{align} Thus the discretized 1D Poisson equation becomes a set of algebraic equations:\\ \begin{align} \implies \psi_{j+1}^{n} - 2\psi_{j}^{n} + \psi_{j-1}^{n} = \zeta_j^n {\Delta x^2} \end{align} , where j is the space step j = 1,2,...,$j_{max}$\\ For periodic boundary conditions it's much more difficult to satisfy the boundary conditions. The boundary at x=0 we must be carefully handled with an extra imaginary point $x_{-1}$, since we have that the last step should be the first step for the next cycle. For j = 0 I get:\\ \begin{align} \psi_{1}^{n} - 2\psi_{0}^{n} + \psi_{-1}^{n} = \zeta_0^n {\Delta x^2} \end{align}\\ , where $\psi_{-1}^{n}$ is the problem term. To solve it I utilize equation (18), by saying that\\ \begin{align} \partial_x \psi_{0}^{n} = \frac{\psi_{1}^{n} - \psi_{-1}^{n}}{2\Delta x} \end{align}\\ Rearranging and solving the equation in regards to $\psi_{-1}^{n}$ I get:\\ \begin{align} \psi_{-1}^{n} = \psi_{1}^{n} - 2\Delta x \partial_x \psi_{0}^{n} \end{align}\\ Substituting this expression into the previous equation (21) I get:\\ \begin{align} \psi_{1}^{n} - 2\psi_{0}^{n} + \psi_{1}^{n} - 2\Delta x \partial_x \psi_{0}^{n} = \zeta_0^n {\Delta x^2} \end{align} Rearranging again I get the result of the boundary condition:\\ \begin{align} \psi_{1}^{n} - \psi_{0}^{n} = \frac{\zeta_0^n {\Delta x^2} + 2\Delta x \partial_x \psi_{0}^{n}}{2} \end{align}\\ Now we can introduce the vector $\mathbf{F}$, as done in equation 5 of \cite{poisson}. The elements of $\mathbf{F}$ are $F_j$ defined by:\\ \begin{equation} \begin{gathered} F_0 = \frac{\zeta_0^n {\Delta x^2}}{2} + \Delta x \partial_x\psi_0\\ F_{j_{max}} = \Delta x^2 \zeta_{j_{max}} - \psi_0\\ F_j = \Delta x^2 \zeta_j \end{gathered} \end{equation} , where j = 1, 2, ..., $j_{max}-1$\\ I obtain the following matrix equation:\\ \[ \begin{bmatrix} -1& 1& 0 &\dots & \dots &0 \\ 1 & -2 & 1 &0 &\dots &\dots \\ 0&1 &-2 & 1 & 0 & \dots \\ & \dots & \dots &\dots &\dots & \dots \\ 0&\dots & &1 &-2& 1 \\ 0&\dots & & 0 &1 & -1 \\ \end{bmatrix} \begin{bmatrix} \psi_0 \\ \psi_1 \\ \psi_2 \\ \vdots \\ \psi_{j_{max}-1} \\ \psi_{j_{max}} \\ \end{bmatrix} = \Delta x^2 \begin{bmatrix} \zeta_0 \\ \zeta_1 \\ \zeta_3 \\ \vdots \\ \zeta_{j_{max}-1} \\ \zeta_{j_{max}} \\ \end{bmatrix} \]\\ This tridiagonal matrix is then solved numerically with the Thomas algorithm as prescribed in \cite{trisolve} or chapter 6.4 in \cite{lecturenote}.\\ Equation (6) is a prognostic equation, which will be solved numerically by using a time-stepping method. For the time stepping, we will test two methods. One involves a forward difference: \begin{equation} \label{eq:Rossby3} \partial_t\psi \approx \frac{\psi_{j}^{n+1} - \psi_{j}^{n}}{\Delta t} , \end{equation} while the second involves a centered difference: \begin{align} \label{eq:Rossby4} \partial_t\psi &\approx \frac{\psi_{j}^{n+1} - \psi_{j}^{n-1}}{2\Delta t}. \end{align}\\ The forward method is rearranged to be solved using the following algorithm\\ \begin{align} \zeta_j^{n+1} = \Delta t(\frac{\psi_{j+1}^n-\psi_{0}^n}{\Delta x})+\zeta_j^{n} \end{align}\\ and the central method is rearranged to:\\ \begin{align} \zeta_j^{n+1} = 2\Delta t(\frac{\psi_{j+1}^n-\psi_{j-1}^n}{2\Delta x})+\zeta_j^{n-1} \end{align}\\ \newpage \section{Implementation} For all programs, see:\\ $\href{https://github.com/larsjbro/FYS4150/tree/master/project_5/source}{https://github.com/larsjbro/FYS4150/tree/master/project_5/source}$ \subsection{Tridiagonal matrix solver} The Thomas method is implemented to find an expression for the vorticity. This method is implemented in the functions \begin{verbatim} tridiagonal_solve_specific \end{verbatim} is used for solving the finite domain and \begin{verbatim} tridiagonal_solve \end{verbatim} is used to solve for the periodic domain. The result from the solver is then inserted into the Rossby wave equation and solved with time stepping methods. \subsection{Rossby wave solution for finite and periodic domain} A solver for the barotropic Rossby wave equation for finite and perodic domain is implemented with the functions \begin{verbatim} solve_rossby_with_walls \end{verbatim} and \begin{verbatim} solve_rossby_periodic \end{verbatim} respectively. %*Code/Implementations/test: Readability of code, implementation, testing and discussion of benchmarks. Total number of possible points 20* \section{Results} %*Analysis: of results and the effectiveness of their selection and presentation. Are the results well understood and discussed? Total number of possible points: 20* \subsection{Agreement between analytical and numerical simulations} Theoretically we expect the Rossby wave to travel westwards barring a strong mean flow to the east. From figure 1 and 2 I see that this case is confirmed, as I can see the wave moving westwards with increasing time. I can also see that the waves are interfering as the amplitude of the waves are changed with time for the finite domain! \subsubsection{Finite domain} Figure 1 and 2 shows the Rossby wave propagation going westwards and also showing some change in amplitude due to the finite boundaries resulting in reflection of waves. \FloatBarrier \begin{figure}[!ht] \centering \FloatBarrier \includegraphics[width=0.70\textwidth]{task_5c_psi_Wall_central1000.png} \caption{Plot of streamfunction for finite domain with central method, for three different times} \label{fig:Earth_orbit_sun_Forward_Euler_k_2} \end{figure} \FloatBarrier \FloatBarrier \begin{figure}[!ht] \centering \FloatBarrier \includegraphics[width=0.70\textwidth]{task_5c_psi_Wall_forward1000.png} \caption{Plot of streamfunction for finite domain with forward stepping method, for three different times.} \label{fig:Earth_orbit_sun_Forward_Euler_k_2} \end{figure} \FloatBarrier \subsubsection{Periodic domain} Figure 3 and 4 show that also the periodic waves travel westwards but are are not distorted in their shape, which is because there is no reflection at a wall. \FloatBarrier \begin{figure}[!ht] \centering \FloatBarrier \includegraphics[width=0.70\textwidth]{task_5c_psi_Periodic_central1000.png} \caption{Plot of streamfunction for periodic domain with central stepping method, for three different times.} \label{fig:Earth_orbit_sun_Forward_Euler_k_2} \end{figure} \FloatBarrier \FloatBarrier \begin{figure}[!ht] \centering \FloatBarrier \includegraphics[width=0.70\textwidth]{task_5c_psi_Periodic_forward1000.png} \caption{Plot of streamfunction for periodic domain with forward stepping method, for three different times.} \label{fig:Earth_orbit_sun_Forward_Euler_k_2} \end{figure} \FloatBarrier \section{Conclusion} Barotropic Rossby waves travel in the western direction, but the numerical solution to the problem is quite difficult. Especially for the case of a periodic domain, when the boundary conditions introduced a stepping problem. I find that the central method was slightly better as a numerical method. I also find that the Rossby waves travel westwards for both the periodic and the finite domain. In the finite domain I can see that the amplitude of the wave is distorted which is a sign that there is reflection of waves at the walls resulting in resonance. %*Conclusions, discussions and critical comments: on what was learned about the method used and on the results obtained. Possible directions and future improvements? Total number of possible points: 10* \begin{thebibliography}{99} \bibitem{lecturenote}$\href{https://github.com/CompPhysics/ComputationalPhysics/blob/gh-pages/doc/Lectures/lectures2015.pdf}{https://github.com/CompPhysics/ComputationalPhysics/blob/gh-pages/doc/Lectures/lectures2015.pdf}$, November 19 2017\\ \bibitem{equator}$\href{https://en.wikipedia.org/wiki/Equatorial\_wave}{https://en.wikipedia.org/wiki/Equatorial\_wave}$ \bibitem{geofludyn}$\href{http://folk.uio.no/josepl/papers/dynbook7.pdf}{http://folk.uio.no/josepl/papers/dynbook7.pdf}$ \bibitem{rossby}$\href{https://en.wikipedia.org/wiki/Rossby\_wave}{https://en.wikipedia.org/wiki/Rossby\_wave}$ \bibitem{poisson}$\href{http://file.scirp.org/pdf/JEMAA_2014092510103331.pdf}{http://file.scirp.org/pdf/JEMAA_2014092510103331.pdf}$ \bibitem{vorticity}$\href{https://en.wikipedia.org/wiki/Vorticity}{https://en.wikipedia.org/wiki/Vorticity}$ \bibitem{trisolve}$\href{https://www.cfd-online.com/Wiki/Tridiagonal\_matrix\_algorithm\_-\_TDMA\_(Thomas\_algorithm)}{https://www.cfd-online.com/Wiki/Tridiagonal\_matrix\_algorithm\_-\_TDMA\_(Thomas\_algorithm)}$ \end{thebibliography} %\FloatBarrier %\begin{figure}[!ht] %\centering %\FloatBarrier %\includegraphics[width=0.45\textwidth]{eigenvector_rho29n128omega500.png} % %\caption{Normalized energy for the three lowest eigenvalues for repulsive Coulomb interaction with n=128 and $\omega_r$=5} %\label{fig:Eigenvalue_states_n_320_omega_500} %\end{figure} %\FloatBarrier
{'content_hash': '503b543e1660bd551c78341930468f63', 'timestamp': '', 'source': 'github', 'line_count': 515, 'max_line_length': 516, 'avg_line_length': 38.87766990291262, 'alnum_prop': 0.7120667266007392, 'repo_name': 'larsjbro/FYS4150', 'id': '48ce04613235ef461742751a985408a94cb2a507', 'size': '20024', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'project_5/1.tex', 'mode': '33188', 'license': 'bsd-2-clause', 'language': [{'name': 'C++', 'bytes': '3835'}, {'name': 'Python', 'bytes': '169901'}, {'name': 'Shell', 'bytes': '369'}, {'name': 'TeX', 'bytes': '81829'}]}
namespace ct_common { // Class mapping typeid to class name. class ClassNameMap final { public: ClassNameMap() = default; ~ClassNameMap() = default; template <typename T> static const std::string& GetClassName(const T& obj) { return GetInstance().GetClassNameInternal(typeid(obj)); } static void Register(const std::type_index& info, const std::string& name) { GetInstance().RegisterInternal(info, name); } private: static ClassNameMap& GetInstance(); const std::string& GetClassNameInternal(const std::type_index& idx) const; void RegisterInternal(const std::type_index& info, const std::string& name); using NameMap = std::unordered_map<std::type_index, std::string>; NameMap name_map_; }; class GlobalInitializer { public: using FuncType = std::function<void()>; explicit GlobalInitializer(FuncType func) { func(); } }; } // namespace ct_common #define REGISTER_CLASS_NAME(name) \ namespace { \ const ct_common::GlobalInitializer sClassNameRegisterer##name( \ std::bind(ClassNameMap::Register, \ std::type_index(typeid(name)), #name)); \ } #endif // CT_COMMON_BASE_CLASS_NAME_UTILS_H_
{'content_hash': '65a2fe2adaee3e072e1436f8d722a9bd', 'timestamp': '', 'source': 'github', 'line_count': 45, 'max_line_length': 78, 'avg_line_length': 29.42222222222222, 'alnum_prop': 0.6140483383685801, 'repo_name': 'xxyzzzq/ct_common', 'id': 'f98689c4472f0cdf4e01eb7139f3fd8c2a541154', 'size': '1586', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'src/ct_common/base/class_name_utils.h', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'C', 'bytes': '413'}, {'name': 'C++', 'bytes': '192453'}, {'name': 'CMake', 'bytes': '2053'}, {'name': 'PAWN', 'bytes': '2945'}, {'name': 'Shell', 'bytes': '3050'}]}
Compiled example ---------------- ![Example](topology-cube-divided.png)
{'content_hash': 'd2759ecabe2e32b4f08dd64158bb1ccc', 'timestamp': '', 'source': 'github', 'line_count': 3, 'max_line_length': 37, 'avg_line_length': 24.0, 'alnum_prop': 0.6111111111111112, 'repo_name': 'MartinThoma/LaTeX-examples', 'id': '09150f4fee41583e9ea73de64e16dcbda9dcfd0b', 'size': '72', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'tikz/topology-cube-divided/README.md', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'Assembly', 'bytes': '104'}, {'name': 'Asymptote', 'bytes': '16054'}, {'name': 'Batchfile', 'bytes': '187'}, {'name': 'C', 'bytes': '7885'}, {'name': 'Gnuplot', 'bytes': '383'}, {'name': 'HTML', 'bytes': '10585'}, {'name': 'Haskell', 'bytes': '9401'}, {'name': 'Java', 'bytes': '95574'}, {'name': 'JavaScript', 'bytes': '33665'}, {'name': 'Jupyter Notebook', 'bytes': '15400'}, {'name': 'Makefile', 'bytes': '403103'}, {'name': 'Prolog', 'bytes': '4515'}, {'name': 'Python', 'bytes': '58056'}, {'name': 'Raku', 'bytes': '357'}, {'name': 'Scala', 'bytes': '6990'}, {'name': 'Shell', 'bytes': '2783'}, {'name': 'ShellSession', 'bytes': '3837'}, {'name': 'Smarty', 'bytes': '572'}, {'name': 'Tcl', 'bytes': '250'}, {'name': 'TeX', 'bytes': '5244843'}, {'name': 'X10', 'bytes': '2354'}]}
import datetime import os import re import tempfile import urllib2 from lxml import etree from optparse import make_option from tempfile import gettempdir from django.core.files import File from django.core.management.base import BaseCommand, CommandError from django.utils.timezone import utc from airmozilla.main.models import Category, Event, Tag, Template DEFAULT_VIDLY_TEMPLATE = """ <video controls width="100%" controls preload="none" poster="https://d3fenhwk93s16g.cloudfront.net/{{ tag }}/poster.jpg"> <source src="http://cf.cdn.vid.ly/{{ tag }}/mp4.mp4" type="video/mp4"> <source src="http://cf.cdn.vid.ly/{{ tag }}/webm.webm" type="video/webm"> <source src="http://cf.cdn.vid.ly/{{ tag }}/ogv.ogv" type="video/ogg"> <a target="_blank" href="http://vid.ly/{{ tag }}"><img src="https://d3fenhwk93s16g.cloudfront.net/{{ tag }}/poster.jpg" width="500" alt="Video"></a> </video> """ DEFAULT_VIDLY_NAME = "Vid.ly" DEFAULT_OGG_TEMPLATE = """ <video width="620" height="350" controls="controls"> <source src="{{ url }}" type="video/ogg" /> </video> """ DEFAULT_OGG_NAME = "Ogg Video" class Command(BaseCommand): args = '<wordpress_xml_dump.xml> <default_thumb>' option_list = BaseCommand.option_list + ( make_option('--clear', action='store_true', dest='clear', default=False, help='Clear all events before running the migration.'), ) nsmap = { 'wp': 'http://wordpress.org/export/1.2/', 'dc': 'http://purl.org/dc/elements/1.1/', 'content': 'http://purl.org/rss/1.0/modules/content/', 'excerpt': 'http://wordpress.org/export/1.2/excerpt/' } import_cache = tempfile.gettempdir() def _check_video_templates(self): # make sure we have some assumed Video templates in the database try: Template.objects.get(name=DEFAULT_VIDLY_NAME) except Template.DoesNotExist: Template.objects.create( name=DEFAULT_VIDLY_NAME, content=DEFAULT_VIDLY_TEMPLATE ) try: Template.objects.get(name=DEFAULT_OGG_NAME) except Template.DoesNotExist: Template.objects.create( name=DEFAULT_OGG_NAME, content=DEFAULT_OGG_TEMPLATE ) def handle(self, *args, **options): if options['clear']: for e in Event.objects.all(): e.delete() self._check_video_templates() attachments = {} try: wordpress_xml_dump = args[0] item_parser = etree.iterparse(wordpress_xml_dump, tag='item') except IndexError: raise CommandError('Please provide an XML dump.') except IOError: raise CommandError('The provided file does not exist or is not' ' a valid Wordpress XML dump') try: self.default_thumb_path = args[1] self.default_thumb = open(self.default_thumb_path, 'rb') except IOError: raise CommandError('Please provide a valid default thumbnail.') for _, element in item_parser: fields = { 'title': 'title', 'status': 'wp:status', 'start_time': 'pubDate', 'description': 'content:encoded', 'short_description': 'excerpt:encoded', 'created': 'wp:post_date', 'slug': 'wp:post_name', 'type': 'wp:post_type', 'attachment': 'wp:attachment_url', 'post_id': 'wp:post_id' } item = self.extract_item(element, fields) if Event.objects.filter(slug=item['slug']).exists(): self.stdout.write( 'Event %s already exists, skipping.\n' % item['slug'] ) continue if item['type'] == 'attachment': # The item is a thumbnail attachment; save for later attachments[item['post_id']] = item['attachment'] elif item['type'] == 'post': # Create and initiate a new event event = Event() event.title = item['title'] event.slug = item['slug'] try: event.start_time = datetime.datetime.strptime( item['start_time'], '%a, %d %b %Y %H:%M:%S +0000' ).replace(tzinfo=utc) except ValueError: event.start_time = datetime.datetime.strptime( item['created'], '%Y-%m-%d %H:%M:%S' ).replace(tzinfo=utc) event.archive_time = ( event.start_time + datetime.timedelta(hours=1) ) # Set status & public status from WP metadata event.status = Event.STATUS_INITIATED event.public = False if item['status'] == 'publish': event.status = Event.STATUS_SCHEDULED event.public = True elif item['status'] == 'private': event.status = Event.STATUS_SCHEDULED elif item['status'] == 'trash': event.status = Event.STATUS_REMOVED # Parse out the video from the event description event.description = 'n/a' if item['description']: self.parse_description(event, item['description']) event.short_description = item['short_description'] or '' # Add categories and tags event.save() for category in element.findall('category'): domain = category.attrib['domain'] text = category.text if domain == 'category' and not event.category: cat, _ = Category.objects.get_or_create(name=text) event.category = cat else: tag = text.lower().strip() tag_add, _ = Tag.objects.get_or_create(name=tag) event.tags.add(tag_add) # Add thumbnail and save thumbnail_id = 0 for meta in element.findall('wp:postmeta', namespaces=self.nsmap): meta_key, meta_val = meta.getchildren() if meta_key.text == '_thumbnail_id': thumbnail_id = meta_val.text if thumbnail_id in attachments: self.attach_thumbnail(event, attachments[thumbnail_id]) else: self.attach_thumbnail(event) self.stdout.write( 'No thumb found for %s, used default.\n' % event.slug ) event.save() self.stdout.write('Saved event %s\n' % event.slug) def extract_item(self, element, fields): """Returns a shortcut dictionary of element's children parsed according to fields (destination_key: source_child_tag).""" item = {} for name, tag in fields.iteritems(): child = element.find(tag, namespaces=self.nsmap) try: item[name] = child.text.encode('utf-8').strip() except AttributeError: item[name] = None return item def parse_description(self, event, description_raw): """Parse out video embeds from the description, correctly set templates and their environments; leave descriptions clean.""" vidly_tag = re.compile('\[vidly code="(\w+)?"\]') vidly_template = Template.objects.get(name='Vid.ly') ogg_tag = re.compile('<video src="([^"]*)".*?>') ogg_template = Template.objects.get(name='Ogg Video') event.description = description_raw vidly_search = vidly_tag.search(description_raw) ogg_search = ogg_tag.search(description_raw) if vidly_search: event.description = event.description.replace( vidly_search.group(0), '' ) event.template = vidly_template event.template_environment = {'tag': vidly_search.group(1)} elif ogg_search: event.description = event.description.replace( ogg_search.group(0), '' ) event.template = ogg_template event.template_environment = {'url': ogg_search.group(1)} else: event.status = Event.STATUS_REMOVED event.description = event.description.strip() def attach_thumbnail(self, event, url=None): """Download, cache, and attach an event's placeholder image.""" if not url: # Use a default image, provided _, ext = os.path.splitext(self.default_thumb_path) img_temp = File(self.default_thumb) else: _, ext = os.path.splitext(url) cache_path = os.path.join(self.import_cache, event.slug) + ext try: # Read a cached image img_temp = File( open(cache_path, 'rb') ) except IOError: # Download and create the image img_temp = File( open(cache_path, 'wb+') ) img_temp.write(urllib2.urlopen(url).read()) img_temp.flush() event.placeholder_img.save('img%s' % ext, img_temp)
{'content_hash': '6eee4b1df86f795e424d5e91f0423b09', 'timestamp': '', 'source': 'github', 'line_count': 235, 'max_line_length': 152, 'avg_line_length': 41.276595744680854, 'alnum_prop': 0.5261855670103093, 'repo_name': 'peterbe/airmozilla', 'id': 'e425491abf0a0084e37b60ca7ab86a09de60e97b', 'size': '9700', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'airmozilla/manage/management/commands/wp_import.py', 'mode': '33188', 'license': 'bsd-3-clause', 'language': [{'name': 'CSS', 'bytes': '70585'}, {'name': 'JavaScript', 'bytes': '10192'}, {'name': 'Puppet', 'bytes': '6677'}, {'name': 'Python', 'bytes': '1235514'}, {'name': 'Shell', 'bytes': '3672'}]}
using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Reflection; using System.Text; namespace SpecAid.Helper { public static class AssemblyEntryFinderInUnitTests { // Because Assembly.GetEntryAssembly() doesn't work in UnitTests... public static Assembly Go() { var specAidAssembly = Assembly.GetExecutingAssembly(); StackTrace stackTrace = new StackTrace(); // get call stack StackFrame[] stackFrames = stackTrace.GetFrames(); // get method calls (frames) Assembly assembly = null; foreach (var stackFrame in stackFrames) { try { var dType = stackFrame.GetMethod().DeclaringType; if (dType == null) continue; assembly = dType.Assembly; if (specAidAssembly.FullName != assembly.FullName) { return assembly; } } // ReSharper disable EmptyGeneralCatchClause catch // ReSharper restore EmptyGeneralCatchClause { // Throw away the exception... // Either we have the assembly in the Stack or we don't... } } return assembly; } } }
{'content_hash': '286a83a123f0f81a4853868b55021068', 'timestamp': '', 'source': 'github', 'line_count': 49, 'max_line_length': 92, 'avg_line_length': 30.448979591836736, 'alnum_prop': 0.5073726541554959, 'repo_name': 'ITAGroup/SpecAid', 'id': '063750ad2b71e3ba743cb776422c32dedb8c4aeb', 'size': '1494', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'src/SpecAid/Helper/AssemblyEntryFinderInUnitTests.cs', 'mode': '33188', 'license': 'bsd-3-clause', 'language': [{'name': 'C#', 'bytes': '275005'}, {'name': 'Cucumber', 'bytes': '37215'}]}
LongishDark Theme for Linux
{'content_hash': '2241282cb7d721abd1f8b57743b3e7e3', 'timestamp': '', 'source': 'github', 'line_count': 1, 'max_line_length': 27, 'avg_line_length': 28.0, 'alnum_prop': 0.8571428571428571, 'repo_name': 'akalongman/linux-longishdark-theme', 'id': 'bb74ffcc94938570e8ac218014c65283f0810af1', 'size': '54', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'README.md', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'CSS', 'bytes': '324528'}]}
struct PapayaMemory; struct Profile; enum PapayaUndoOp_ { PapayaUndoOp_Brush, PapayaUndoOp_COUNT }; struct UndoData { // TODO: Convert into a union of structs once multiple types of undo ops are required u8 op_code; // Stores enum of type PapayaUndoOp_ UndoData* prev, *next; Vec2i pos, size; // Position and size of the suffixed data block bool IsSubRect; // If true, then the suffixed image data contains two subrects - before and after the brush Vec2 line_segment_start_uv; // Image data goes after this }; struct UndoBuffer { void* start; // Pointer to beginning of undo buffer memory block // TODO: Change pointer types to i8*? void* top; // Pointer to the top of the undo stack UndoData* base; // Pointer to the base of the undo stack UndoData* current; // Pointer to the current location in the undo stack. Goes back and forth during undo-redo. UndoData* last; // Last undo data block in the buffer. Should be located just before Top. size_t size; // Size of the undo buffer in bytes size_t count; // Number of undo ops in buffer size_t current_index; // Index of the current undo data block from the beginning }; namespace undo { void init(PapayaMemory* mem); void destroy(PapayaMemory* mem); void push(UndoBuffer* undo, Profile* profile, Vec2i pos, Vec2i size, i8* pre_brush_img, Vec2 line_segment_start_uv); void pop(PapayaMemory* mem, bool load_pre_brush_image); void visualize_undo_buffer(PapayaMemory* mem); }
{'content_hash': '11628ec7346622c95a9b77667de2c033', 'timestamp': '', 'source': 'github', 'line_count': 38, 'max_line_length': 114, 'avg_line_length': 40.63157894736842, 'alnum_prop': 0.697538860103627, 'repo_name': 'ApoorvaJ/Papaya', 'id': 'f0c2a3002353757385ab5404f5b8a4f4a4b84421', 'size': '1583', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'src/ui/components/undo.h', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'C', 'bytes': '518645'}, {'name': 'C++', 'bytes': '1028862'}, {'name': 'Makefile', 'bytes': '1110'}]}
/* Authenticating with Persona. */ api.onLoginRequired = function() { var R = Route.replace(), self = this; R["persona/page"]({ button: function(R) { R.$[0].onclick = function() { navigator.id.get(function(assertion){ self.AUTH('people/auth/persona', {assertion:assertion}, function(r){ Route.dispatch(); }); },{ siteName: i18n.title }); }; }}); R.show(); };
{'content_hash': 'd8bf7535feccd9694f7bf18672cc73af', 'timestamp': '', 'source': 'github', 'line_count': 17, 'max_line_length': 70, 'avg_line_length': 24.058823529411764, 'alnum_prop': 0.5794621026894865, 'repo_name': 'RunOrg/RunOrg', 'id': '00d49c5aedfdd5ebf6c3c9bcbafe2c630e58d405', 'size': '409', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'sites/default/persona/persona.js', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'CSS', 'bytes': '15641'}, {'name': 'HTML', 'bytes': '7273'}, {'name': 'JavaScript', 'bytes': '183305'}, {'name': 'Makefile', 'bytes': '1416'}, {'name': 'OCaml', 'bytes': '626227'}, {'name': 'Shell', 'bytes': '681'}, {'name': 'Standard ML', 'bytes': '369'}]}
<?xml version="1.0" encoding="utf-8"?> <!-- $Revision: 336244 $ --> <refentry xml:id="pdo.errorcode" xmlns="http://docbook.org/ns/docbook"> <refnamediv> <refname>PDO::errorCode</refname> <refpurpose> Fetch the SQLSTATE associated with the last operation on the database handle </refpurpose> </refnamediv> <refsect1 role="description"> &reftitle.description; <methodsynopsis> <modifier>public</modifier> <type>mixed</type><methodname>PDO::errorCode</methodname> <void/> </methodsynopsis> </refsect1> <refsect1 role="returnvalues"> &reftitle.returnvalues; <para> Returns an SQLSTATE, a five characters alphanumeric identifier defined in the ANSI SQL-92 standard. Briefly, an SQLSTATE consists of a two characters class value followed by a three characters subclass value. A class value of 01 indicates a warning and is accompanied by a return code of SQL_SUCCESS_WITH_INFO. Class values other than '01', except for the class 'IM', indicate an error. The class 'IM' is specific to warnings and errors that derive from the implementation of PDO (or perhaps ODBC, if you're using the ODBC driver) itself. The subclass value '000' in any class indicates that there is no subclass for that SQLSTATE. </para> <para> <function>PDO::errorCode</function> only retrieves error codes for operations performed directly on the database handle. If you create a PDOStatement object through <function>PDO::prepare</function> or <function>PDO::query</function> and invoke an error on the statement handle, <function>PDO::errorCode</function> will not reflect that error. You must call <function>PDOStatement::errorCode</function> to return the error code for an operation performed on a particular statement handle. </para> <para> Returns &null; if no operation has been run on the database handle. </para> </refsect1> <refsect1 role="examples"> &reftitle.examples; <para> <example><title>Retrieving an SQLSTATE code</title> <programlisting role="php"> <![CDATA[ <?php /* Provoke an error -- the BONES table does not exist */ $dbh->exec("INSERT INTO bones(skull) VALUES ('lucy')"); echo "\nPDO::errorCode(): ", $dbh->errorCode(); ?> ]]> </programlisting> &example.outputs; <screen> <![CDATA[ PDO::errorCode(): 42S02 ]]> </screen> </example> </para> </refsect1> <refsect1 role="seealso"> &reftitle.seealso; <para> <simplelist> <member><function>PDO::errorInfo</function></member> <member><function>PDOStatement::errorCode</function></member> <member><function>PDOStatement::errorInfo</function></member> </simplelist> </para> </refsect1> </refentry> <!-- Keep this comment at the end of the file Local variables: mode: sgml sgml-omittag:t sgml-shorttag:t sgml-minimize-attributes:nil sgml-always-quote-attributes:t sgml-indent-step:1 sgml-indent-data:t indent-tabs-mode:nil sgml-parent-document:nil sgml-default-dtd-file:"~/.phpdoc/manual.ced" sgml-exposed-tags:nil sgml-local-catalogs:nil sgml-local-ecat-files:nil End: vim600: syn=xml fen fdm=syntax fdl=2 si vim: et tw=78 syn=sgml vi: ts=1 sw=1 -->
{'content_hash': '73d8d946771fdcc14cf6998b1bd95cbc', 'timestamp': '', 'source': 'github', 'line_count': 102, 'max_line_length': 88, 'avg_line_length': 30.823529411764707, 'alnum_prop': 0.7178753180661578, 'repo_name': 'mziyut/.vim', 'id': 'ea49883a4a97a97df6871d8a3b0796ed54f52e3e', 'size': '3144', 'binary': False, 'copies': '3', 'ref': 'refs/heads/master', 'path': 'dict/.neocomplete-php/phpdoc/en/reference/pdo/pdo/errorcode.xml', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'HTML', 'bytes': '2223'}, {'name': 'Ruby', 'bytes': '939'}, {'name': 'Shell', 'bytes': '582'}, {'name': 'Vim script', 'bytes': '22415'}]}
@class DBTEAMLOGShowcaseChangeEnabledPolicyDetails; @class DBTEAMLOGShowcaseEnabledPolicy; NS_ASSUME_NONNULL_BEGIN #pragma mark - API Object /// /// The `ShowcaseChangeEnabledPolicyDetails` struct. /// /// Enabled/disabled Dropbox Showcase for team. /// /// This class implements the `DBSerializable` protocol (serialize and /// deserialize instance methods), which is required for all Obj-C SDK API route /// objects. /// @interface DBTEAMLOGShowcaseChangeEnabledPolicyDetails : NSObject <DBSerializable, NSCopying> #pragma mark - Instance fields /// New Dropbox Showcase policy. @property (nonatomic, readonly) DBTEAMLOGShowcaseEnabledPolicy *dNewValue; /// Previous Dropbox Showcase policy. @property (nonatomic, readonly) DBTEAMLOGShowcaseEnabledPolicy *previousValue; #pragma mark - Constructors /// /// Full constructor for the struct (exposes all instance variables). /// /// @param dNewValue New Dropbox Showcase policy. /// @param previousValue Previous Dropbox Showcase policy. /// /// @return An initialized instance. /// - (instancetype)initWithDNewValue:(DBTEAMLOGShowcaseEnabledPolicy *)dNewValue previousValue:(DBTEAMLOGShowcaseEnabledPolicy *)previousValue; - (instancetype)init NS_UNAVAILABLE; @end #pragma mark - Serializer Object /// /// The serialization class for the `ShowcaseChangeEnabledPolicyDetails` struct. /// @interface DBTEAMLOGShowcaseChangeEnabledPolicyDetailsSerializer : NSObject /// /// Serializes `DBTEAMLOGShowcaseChangeEnabledPolicyDetails` instances. /// /// @param instance An instance of the /// `DBTEAMLOGShowcaseChangeEnabledPolicyDetails` API object. /// /// @return A json-compatible dictionary representation of the /// `DBTEAMLOGShowcaseChangeEnabledPolicyDetails` API object. /// + (nullable NSDictionary<NSString *, id> *)serialize:(DBTEAMLOGShowcaseChangeEnabledPolicyDetails *)instance; /// /// Deserializes `DBTEAMLOGShowcaseChangeEnabledPolicyDetails` instances. /// /// @param dict A json-compatible dictionary representation of the /// `DBTEAMLOGShowcaseChangeEnabledPolicyDetails` API object. /// /// @return An instantiation of the /// `DBTEAMLOGShowcaseChangeEnabledPolicyDetails` object. /// + (DBTEAMLOGShowcaseChangeEnabledPolicyDetails *)deserialize:(NSDictionary<NSString *, id> *)dict; @end NS_ASSUME_NONNULL_END
{'content_hash': '7cada704aa20edb2aaf6eaa74265757f', 'timestamp': '', 'source': 'github', 'line_count': 75, 'max_line_length': 109, 'avg_line_length': 30.84, 'alnum_prop': 0.7803718115002162, 'repo_name': 'dropbox/dropbox-sdk-obj-c', 'id': '4194d7d885826347bfae1c3a7df01dd0018d3a11', 'size': '2499', 'binary': False, 'copies': '2', 'ref': 'refs/heads/master', 'path': 'Source/ObjectiveDropboxOfficial/Shared/Generated/ApiObjects/TeamLog/Headers/DBTEAMLOGShowcaseChangeEnabledPolicyDetails.h', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'C', 'bytes': '1288'}, {'name': 'CSS', 'bytes': '6608'}, {'name': 'Objective-C', 'bytes': '18903013'}, {'name': 'Python', 'bytes': '7087'}, {'name': 'Ruby', 'bytes': '1819'}, {'name': 'Shell', 'bytes': '4527'}]}
Colocation API ============== The colocation API wraps the [TransIP colocation SOAP service](https://api.transip.nl/wsdl/?service=ColocationService). ### General The colocation API is available through the `Client` and can be accessed by calling `colocation()` or `api('colocation')`. ### Methods #### Request access to the data-center. ````php $visitors = [ 'Firstname Lastname', ]; $client->colocation()->requestAccess('2012-12-23 00:00:00', 60, $visitors, '+31612312399'); ```` #### Request remote hands. ````php $client->colocation()->requestRemoteHands('colocationFoo', 'Firstname Lastname', '+31612312399', 60, 'Instructions'); ```` #### Get colocation names. ````php $client->colocation()->getColocationNames(); ```` #### Get active IP addresses for a colocation. ````php $client->colocation()->getIpAddresses('colocationFoo'); ```` #### Get IP ranges for a colocation. ````php $client->colocation()->getIpRanges('colocationFoo'); ```` #### Create a new ipv4 or ipv6 address. ````php $client->colocation()->createIpAddress('127.0.0.1', '127.0.0.1.in-addr.arpa'); ```` #### Delete an IP address. ````php $client->colocation()->deleteIpAddress('127.0.0.1'); ```` #### Get Reverse DNS for an IP address. ````php $client->colocation()->getReverseDns('127.0.0.1'); ```` #### Set Reverse DNS for an IP address. ````php $client->colocation()->setReverseDns('127.0.0.1', '127.0.0.1.in-addr.arpa'); ````
{'content_hash': '3081602bc39969c3a6b0d85f0a71ef14', 'timestamp': '', 'source': 'github', 'line_count': 57, 'max_line_length': 122, 'avg_line_length': 24.87719298245614, 'alnum_prop': 0.6600846262341326, 'repo_name': 'hiddeco/transip', 'id': 'cee6da357547f79bbf8580cadd64ca9ac297c4f0', 'size': '1418', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'doc/colocation.md', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'PHP', 'bytes': '106376'}]}
In the interest of fostering an open and welcoming environment, we as contributors and maintainers pledge to making participation in our project and our community a harassment-free experience for everyone, regardless of age, body size, disability, ethnicity, gender identity and expression, level of experience, nationality, personal appearance, race, religion, or sexual identity and orientation. ## Our Standards Examples of behavior that contributes to creating a positive environment include: * Using welcoming and inclusive language * Being respectful of differing viewpoints and experiences * Gracefully accepting constructive criticism * Focusing on what is best for the community * Showing empathy towards other community members Examples of unacceptable behavior by participants include: * The use of sexualized language or imagery and unwelcome sexual attention or advances * Trolling, insulting/derogatory comments, and personal or political attacks * Public or private harassment * Publishing others' private information, such as a physical or electronic address, without explicit permission * Other conduct which could reasonably be considered inappropriate in a professional setting ## Our Responsibilities Project maintainers are responsible for clarifying the standards of acceptable behavior and are expected to take appropriate and fair corrective action in response to any instances of unacceptable behavior. Project maintainers have the right and responsibility to remove, edit, or reject comments, commits, code, wiki edits, issues, and other contributions that are not aligned to this Code of Conduct, or to ban temporarily or permanently any contributor for other behaviors that they deem inappropriate, threatening, offensive, or harmful. ## Scope This Code of Conduct applies both within project spaces and in public spaces when an individual is representing the project or its community. Examples of representing a project or community include using an official project e-mail address, posting via an official social media account, or acting as an appointed representative at an online or offline event. Representation of a project may be further defined and clarified by project maintainers. ## Enforcement Instances of abusive, harassing, or otherwise unacceptable behavior may be reported by contacting the project team at [email protected]. All complaints will be reviewed and investigated and will result in a response that is deemed necessary and appropriate to the circumstances. The project team is obligated to maintain confidentiality with regard to the reporter of an incident. Further details of specific enforcement policies may be posted separately. Project maintainers who do not follow or enforce the Code of Conduct in good faith may face temporary or permanent repercussions as determined by other members of the project's leadership. ## Attribution This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4, available at https://www.contributor-covenant.org/version/1/4/code-of-conduct.html [homepage]: https://www.contributor-covenant.org
{'content_hash': '07b054ce31c8b22baf2186e437aae8e1', 'timestamp': '', 'source': 'github', 'line_count': 70, 'max_line_length': 87, 'avg_line_length': 44.885714285714286, 'alnum_prop': 0.8220878421387651, 'repo_name': 'neon-bindings/neon', 'id': '8d9ce17b0b061c2e65523438d2e02c0458115ef5', 'size': '3197', 'binary': False, 'copies': '4', 'ref': 'refs/heads/main', 'path': 'CODE_OF_CONDUCT.md', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'HTML', 'bytes': '535'}, {'name': 'Handlebars', 'bytes': '878'}, {'name': 'JavaScript', 'bytes': '76759'}, {'name': 'Rust', 'bytes': '376937'}, {'name': 'TypeScript', 'bytes': '12138'}]}
<!DOCTYPE html > <html> <head> <meta http-equiv="X-UA-Compatible" content="IE=edge" /> <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no" /> <title>ScalaTest 3.0.6 - org.scalatest.enablers.Futuristic</title> <meta name="description" content="ScalaTest 3.0.6 - org.scalatest.enablers.Futuristic" /> <meta name="keywords" content="ScalaTest 3.0.6 org.scalatest.enablers.Futuristic" /> <meta http-equiv="content-type" content="text/html; charset=UTF-8" /> <link href="../../../lib/index.css" media="screen" type="text/css" rel="stylesheet" /> <link href="../../../lib/template.css" media="screen" type="text/css" rel="stylesheet" /> <link href="../../../lib/diagrams.css" media="screen" type="text/css" rel="stylesheet" id="diagrams-css" /> <script type="text/javascript" src="../../../lib/jquery.js"></script> <script type="text/javascript" src="../../../lib/jquery.panzoom.min.js"></script> <script type="text/javascript" src="../../../lib/jquery.mousewheel.min.js"></script> <script type="text/javascript" src="../../../lib/index.js"></script> <script type="text/javascript" src="../../../index.js"></script> <script type="text/javascript" src="../../../lib/scheduler.js"></script> <script type="text/javascript" src="../../../lib/template.js"></script> <script type="text/javascript" src="../../../lib/tools.tooltip.js"></script> <script type="text/javascript"> /* this variable can be used by the JS to determine the path to the root document */ var toRoot = '../../../'; </script> <!-- gtag [javascript] --> <script async src="https://www.googletagmanager.com/gtag/js?id=UA-71294502-1"></script> <script defer> window.dataLayer = window.dataLayer || []; function gtag(){dataLayer.push(arguments);} gtag('js', new Date()); gtag('config', 'UA-71294502-1'); </script> </head> <body> <div id="search"> <span id="doc-title">ScalaTest 3.0.6<span id="doc-version"></span></span> <span class="close-results"><span class="left">&lt;</span> Back</span> <div id="textfilter"> <span class="input"> <input autocapitalize="none" placeholder="Search" id="index-input" type="text" accesskey="/" /> <i class="clear material-icons"></i> <i id="search-icon" class="material-icons"></i> </span> </div> </div> <div id="search-results"> <div id="search-progress"> <div id="progress-fill"></div> </div> <div id="results-content"> <div id="entity-results"></div> <div id="member-results"></div> </div> </div> <div id="content-scroll-container" style="-webkit-overflow-scrolling: touch;"> <div id="content-container" style="-webkit-overflow-scrolling: touch;"> <div id="subpackage-spacer"> <div id="packages"> <h1>Packages</h1> <ul> <li name="_root_.root" visbl="pub" class="indented0 " data-isabs="false" fullComment="yes" group="Ungrouped"> <a id="_root_"></a><a id="root:_root_"></a> <span class="permalink"> <a href="index.html#_root_" title="Permalink"> <i class="material-icons"></i> </a> </span> <span class="modifier_kind"> <span class="modifier"></span> <span class="kind">package</span> </span> <span class="symbol"> <a title="" href="../../../index.html"><span class="name">root</span></a> </span> <div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd><a href="../../../index.html" class="extype" name="_root_">root</a></dd></dl></div> </li><li name="_root_.org" visbl="pub" class="indented1 " data-isabs="false" fullComment="yes" group="Ungrouped"> <a id="org"></a><a id="org:org"></a> <span class="permalink"> <a href="index.html#org" title="Permalink"> <i class="material-icons"></i> </a> </span> <span class="modifier_kind"> <span class="modifier"></span> <span class="kind">package</span> </span> <span class="symbol"> <a title="" href="../../index.html"><span class="name">org</span></a> </span> <div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd><a href="../../../index.html" class="extype" name="_root_">root</a></dd></dl></div> </li><li name="org.scalatest" visbl="pub" class="indented2 " data-isabs="false" fullComment="yes" group="Ungrouped"> <a id="scalatest"></a><a id="scalatest:scalatest"></a> <span class="permalink"> <a href="../org/index.html#scalatest" title="Permalink"> <i class="material-icons"></i> </a> </span> <span class="modifier_kind"> <span class="modifier"></span> <span class="kind">package</span> </span> <span class="symbol"> <a title="ScalaTest's main traits, classes, and other members, including members supporting ScalaTest's DSL for the Scala interpreter." href="../index.html"><span class="name">scalatest</span></a> </span> <p class="shortcomment cmt">ScalaTest's main traits, classes, and other members, including members supporting ScalaTest's DSL for the Scala interpreter.</p><div class="fullcomment"><div class="comment cmt"><p>ScalaTest's main traits, classes, and other members, including members supporting ScalaTest's DSL for the Scala interpreter. </p></div><dl class="attributes block"> <dt>Definition Classes</dt><dd><a href="../../index.html" class="extype" name="org">org</a></dd></dl></div> </li><li name="org.scalatest.enablers" visbl="pub" class="indented3 " data-isabs="false" fullComment="yes" group="Ungrouped"> <a id="enablers"></a><a id="enablers:enablers"></a> <span class="permalink"> <a href="../../org/scalatest/index.html#enablers" title="Permalink"> <i class="material-icons"></i> </a> </span> <span class="modifier_kind"> <span class="modifier"></span> <span class="kind">package</span> </span> <span class="symbol"> <a title="" href="index.html"><span class="name">enablers</span></a> </span> <div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd><a href="../index.html" class="extype" name="org.scalatest">scalatest</a></dd></dl></div> </li><li class="current-entities indented3"> <a class="object" href="Aggregating$.html" title="Companion object for Aggregating that provides implicit implementations for the following types:"></a> <a class="trait" href="Aggregating.html" title="Typeclass that enables for aggregations certain contain syntax in the ScalaTest matchers DSL."></a> <a href="Aggregating.html" title="Typeclass that enables for aggregations certain contain syntax in the ScalaTest matchers DSL.">Aggregating</a> </li><li class="current-entities indented3"> <span class="separator"></span> <a class="trait" href="AggregatingHighPriorityImplicits.html" title=""></a> <a href="AggregatingHighPriorityImplicits.html" title="">AggregatingHighPriorityImplicits</a> </li><li class="current-entities indented3"> <span class="separator"></span> <a class="trait" href="AggregatingImpls.html" title=""></a> <a href="AggregatingImpls.html" title="">AggregatingImpls</a> </li><li class="current-entities indented3"> <span class="separator"></span> <a class="trait" href="AggregatingJavaImplicits.html" title=""></a> <a href="AggregatingJavaImplicits.html" title="">AggregatingJavaImplicits</a> </li><li class="current-entities indented3"> <span class="separator"></span> <a class="trait" href="AggregatingStandardImplicits.html" title=""></a> <a href="AggregatingStandardImplicits.html" title="">AggregatingStandardImplicits</a> </li><li class="current-entities indented3"> <a class="object" href="CheckerAsserting$.html" title="Companion object to CheckerAsserting that provides two implicit providers, a higher priority one for passed functions that have result type Assertion, which also yields result type Assertion, and one for any other type, which yields result type Unit."></a> <a class="trait" href="CheckerAsserting.html" title="Supertrait for CheckerAsserting typeclasses, which are used to implement and determine the result type of GeneratorDrivenPropertyChecks's apply and forAll method."></a> <a href="CheckerAsserting.html" title="Supertrait for CheckerAsserting typeclasses, which are used to implement and determine the result type of GeneratorDrivenPropertyChecks's apply and forAll method.">CheckerAsserting</a> </li><li class="current-entities indented3"> <a class="object" href="Collecting$.html" title="Companion object for Collecting that provides implicit implementations for the following types:"></a> <a class="trait" href="Collecting.html" title="Supertrait for typeclasses that enable loneElement and inspectors syntax for collections."></a> <a href="Collecting.html" title="Supertrait for typeclasses that enable loneElement and inspectors syntax for collections.">Collecting</a> </li><li class="current-entities indented3"> <a class="object" href="Containing$.html" title="Companion object for Containing that provides implicit implementations for the following types:"></a> <a class="trait" href="Containing.html" title="Supertrait for typeclasses that enable certain contain matcher syntax for containers."></a> <a href="Containing.html" title="Supertrait for typeclasses that enable certain contain matcher syntax for containers.">Containing</a> </li><li class="current-entities indented3"> <span class="separator"></span> <a class="trait" href="ContainingHighPriorityImplicits.html" title=""></a> <a href="ContainingHighPriorityImplicits.html" title="">ContainingHighPriorityImplicits</a> </li><li class="current-entities indented3"> <span class="separator"></span> <a class="trait" href="ContainingImpls.html" title=""></a> <a href="ContainingImpls.html" title="">ContainingImpls</a> </li><li class="current-entities indented3"> <span class="separator"></span> <a class="trait" href="ContainingStandardImplicits.html" title=""></a> <a href="ContainingStandardImplicits.html" title="">ContainingStandardImplicits</a> </li><li class="current-entities indented3"> <a class="object" href="Definition$.html" title="Companion object for Definition that provides implicit implementations for the following types:"></a> <a class="trait" href="Definition.html" title="Supertrait for typeclasses that enable the be defined matcher syntax."></a> <a href="Definition.html" title="Supertrait for typeclasses that enable the be defined matcher syntax.">Definition</a> </li><li class="current-entities indented3"> <a class="object" href="Emptiness$.html" title="Companion object for Emptiness that provides implicit implementations for the following types:"></a> <a class="trait" href="Emptiness.html" title="Supertrait for typeclasses that enable be empty matcher syntax."></a> <a href="Emptiness.html" title="Supertrait for typeclasses that enable be empty matcher syntax.">Emptiness</a> </li><li class="current-entities indented3"> <a class="object" href="Existence$.html" title="Companion object for Existence that provides implicit implementations for java.io.File."></a> <a class="trait" href="Existence.html" title="Supertrait for typeclasses that enable the exist matcher syntax."></a> <a href="Existence.html" title="Supertrait for typeclasses that enable the exist matcher syntax.">Existence</a> </li><li class="current-entities indented3"> <a class="object" href="" title="Companion object for trait Futuristic that contains implicit Futuristic providers for FutureOutcome and Future[T] for any type T."></a> <a class="trait" href="Futuristic.html" title="Supertrait for Futureistic typeclasses."></a> <a href="Futuristic.html" title="Supertrait for Futureistic typeclasses.">Futuristic</a> </li><li class="current-entities indented3"> <a class="object" href="InspectorAsserting$.html" title="Companion object to InspectorAsserting that provides two implicit providers, a higher priority one for passed functions that have result type Assertion, which also yields result type Assertion, and one for any other type, which yields result type Unit."></a> <a class="trait" href="InspectorAsserting.html" title="Supertrait for InspectorAsserting typeclasses, which are used to implement and determine the result type of Inspectors methods such as forAll, forBetween, etc."></a> <a href="InspectorAsserting.html" title="Supertrait for InspectorAsserting typeclasses, which are used to implement and determine the result type of Inspectors methods such as forAll, forBetween, etc.">InspectorAsserting</a> </li><li class="current-entities indented3"> <span class="separator"></span> <a class="trait" href="JavaContainingImplicits.html" title=""></a> <a href="JavaContainingImplicits.html" title="">JavaContainingImplicits</a> </li><li class="current-entities indented3"> <a class="object" href="KeyMapping$.html" title="Companion object for KeyMapping that provides implicit implementations for scala.collection.GenMap and java.util.Map."></a> <a class="trait" href="KeyMapping.html" title="Supertrait for typeclasses that enable contain key matcher syntax."></a> <a href="KeyMapping.html" title="Supertrait for typeclasses that enable contain key matcher syntax.">KeyMapping</a> </li><li class="current-entities indented3"> <a class="object" href="Length$.html" title="Companion object for Length that provides implicit implementations for the following types:"></a> <a class="trait" href="Length.html" title="Supertrait for Length typeclasses."></a> <a href="Length.html" title="Supertrait for Length typeclasses.">Length</a> </li><li class="current-entities indented3"> <a class="object" href="Messaging$.html" title="Companion object for Messaging that provides implicit implementations for the following types:"></a> <a class="trait" href="Messaging.html" title="Supertrait for Messaging typeclasses."></a> <a href="Messaging.html" title="Supertrait for Messaging typeclasses.">Messaging</a> </li><li class="current-entities indented3"> <a class="object" href="Readability$.html" title="Companion object for Readability that provides implicit implementations for the following types:"></a> <a class="trait" href="Readability.html" title="Supertrait for typeclasses that enable the be readable matcher syntax."></a> <a href="Readability.html" title="Supertrait for typeclasses that enable the be readable matcher syntax.">Readability</a> </li><li class="current-entities indented3"> <a class="object" href="Sequencing$.html" title="Companion object for Sequencing that provides implicit implementations for the following types:"></a> <a class="trait" href="Sequencing.html" title="Typeclass that enables for sequencing certain contain syntax in the ScalaTest matchers DSL."></a> <a href="Sequencing.html" title="Typeclass that enables for sequencing certain contain syntax in the ScalaTest matchers DSL.">Sequencing</a> </li><li class="current-entities indented3"> <a class="object" href="Size$.html" title="Companion object for Size that provides implicit implementations for the following types:"></a> <a class="trait" href="Size.html" title="Supertrait for Size typeclasses."></a> <a href="Size.html" title="Supertrait for Size typeclasses.">Size</a> </li><li class="current-entities indented3"> <a class="object" href="Sortable$.html" title="Companion object for Sortable that provides implicit implementations for the following types:"></a> <a class="trait" href="Sortable.html" title="Supertrait for typeclasses that enable the be sorted matcher syntax."></a> <a href="Sortable.html" title="Supertrait for typeclasses that enable the be sorted matcher syntax.">Sortable</a> </li><li class="current-entities indented3"> <a class="object" href="TableAsserting$.html" title="Companion object to TableAsserting that provides two implicit providers, a higher priority one for passed functions that have result type Assertion, which also yields result type Assertion, and one for any other type, which yields result type Unit."></a> <a class="trait" href="TableAsserting.html" title="Supertrait for TableAsserting typeclasses, which are used to implement and determine the result type of TableDrivenPropertyChecks's forAll, forEvery and exists method."></a> <a href="TableAsserting.html" title="Supertrait for TableAsserting typeclasses, which are used to implement and determine the result type of TableDrivenPropertyChecks's forAll, forEvery and exists method.">TableAsserting</a> </li><li class="current-entities indented3"> <a class="object" href="Timed$.html" title="Companion object for Timed typeclass that offers three implicit providers: one for FutureOutcome, one for Future of any type, and one for any other type."></a> <a class="trait" href="Timed.html" title="Trait that provides a timeoutAfter construct, which allows you to specify a timeout for an operation passed as a by-name parameter, as well as a way to signal/interrupt it if the operation exceeds its time limit."></a> <a href="Timed.html" title="Trait that provides a timeoutAfter construct, which allows you to specify a timeout for an operation passed as a by-name parameter, as well as a way to signal/interrupt it if the operation exceeds its time limit.">Timed</a> </li><li class="current-entities indented3"> <span class="separator"></span> <a class="class" href="UnitCheckerAsserting.html" title="Class holding lowest priority CheckerAsserting implicit, which enables GeneratorDrivenPropertyChecks expressions that have result type Unit."></a> <a href="UnitCheckerAsserting.html" title="Class holding lowest priority CheckerAsserting implicit, which enables GeneratorDrivenPropertyChecks expressions that have result type Unit.">UnitCheckerAsserting</a> </li><li class="current-entities indented3"> <span class="separator"></span> <a class="class" href="UnitInspectorAsserting.html" title="Class holding lowest priority InspectorAsserting implicit, which enables inspector expressions that have result type Unit."></a> <a href="UnitInspectorAsserting.html" title="Class holding lowest priority InspectorAsserting implicit, which enables inspector expressions that have result type Unit.">UnitInspectorAsserting</a> </li><li class="current-entities indented3"> <span class="separator"></span> <a class="class" href="UnitTableAsserting.html" title="Class holding lowest priority TableAsserting implicit, which enables TableDrivenPropertyChecks expressions that have result type Unit."></a> <a href="UnitTableAsserting.html" title="Class holding lowest priority TableAsserting implicit, which enables TableDrivenPropertyChecks expressions that have result type Unit.">UnitTableAsserting</a> </li><li class="current-entities indented3"> <span class="separator"></span> <a class="class" href="UnitWheneverAsserting.html" title="Class holding lowest priority WheneverAsserting implicit, which enables Whenever expressions that have result type Unit."></a> <a href="UnitWheneverAsserting.html" title="Class holding lowest priority WheneverAsserting implicit, which enables Whenever expressions that have result type Unit.">UnitWheneverAsserting</a> </li><li class="current-entities indented3"> <a class="object" href="ValueMapping$.html" title="Companion object for ValueMapping that provides implicit implementations for scala.collection.GenMap and java.util.Map."></a> <a class="trait" href="ValueMapping.html" title="Supertrait for typeclasses that enable contain value matcher syntax."></a> <a href="ValueMapping.html" title="Supertrait for typeclasses that enable contain value matcher syntax.">ValueMapping</a> </li><li class="current-entities indented3"> <a class="object" href="WheneverAsserting$.html" title="Companion object to WheneverAsserting that provides two implicit providers, a higher priority one for passed functions that have result type Assertion, which also yields result type Assertion, and one for any other type, which yields result type Unit."></a> <a class="trait" href="WheneverAsserting.html" title="Supertrait for WheneverAsserting typeclasses, which are used to implement and determine the result type of Whenever's whenever method."></a> <a href="WheneverAsserting.html" title="Supertrait for WheneverAsserting typeclasses, which are used to implement and determine the result type of Whenever's whenever method.">WheneverAsserting</a> </li><li class="current-entities indented3"> <a class="object" href="Writability$.html" title="Companion object for Writability that provides implicit implementations for the following types:"></a> <a class="trait" href="Writability.html" title="Supertrait for typeclasses that enable the be writable matcher syntax."></a> <a href="Writability.html" title="Supertrait for typeclasses that enable the be writable matcher syntax.">Writability</a> </li> </ul> </div> </div> <div id="content"> <body class="object value"> <!-- Top of doc.scalatest.org [javascript] --> <script type="text/javascript"> var rnd = window.rnd || Math.floor(Math.random()*10e6); var pid204546 = window.pid204546 || rnd; var plc204546 = window.plc204546 || 0; var abkw = window.abkw || ''; var absrc = 'http://ab167933.adbutler-ikon.com/adserve/;ID=167933;size=468x60;setID=204546;type=js;sw='+screen.width+';sh='+screen.height+';spr='+window.devicePixelRatio+';kw='+abkw+';pid='+pid204546+';place='+(plc204546++)+';rnd='+rnd+';click=CLICK_MACRO_PLACEHOLDER'; document.write('<scr'+'ipt src="'+absrc+'" type="text/javascript"></scr'+'ipt>'); </script> <div id="definition"> <a href="Futuristic.html" title="See companion trait"><div class="big-circle object-companion-trait">o</div></a> <p id="owner"><a href="../../index.html" class="extype" name="org">org</a>.<a href="../index.html" class="extype" name="org.scalatest">scalatest</a>.<a href="index.html" class="extype" name="org.scalatest.enablers">enablers</a></p> <h1><a href="Futuristic.html" title="See companion trait">Futuristic</a><span class="permalink"> <a href="../../../org/scalatest/enablers/Futuristic$.html" title="Permalink"> <i class="material-icons"></i> </a> </span></h1> <h3><span class="morelinks"><div> Companion <a href="Futuristic.html" title="See companion trait">trait Futuristic</a> </div></span></h3> </div> <h4 id="signature" class="signature"> <span class="modifier_kind"> <span class="modifier"></span> <span class="kind">object</span> </span> <span class="symbol"> <span class="name">Futuristic</span> </span> </h4> <div id="comment" class="fullcommenttop"><div class="comment cmt"><p>Companion object for trait <code>Futuristic</code> that contains implicit <code>Futuristic</code> providers for <code>FutureOutcome</code> and <code>Future[T]</code> for any type <code>T</code>. </p></div><dl class="attributes block"> <dt>Source</dt><dd><a href="https://github.com/scalatest/scalatest/tree/release-3.0.6/scalatest//src/main/scala/org/scalatest/enablers/Futuristic.scala" target="_blank">Futuristic.scala</a></dd></dl><div class="toggleContainer block"> <span class="toggle"> Linear Supertypes </span> <div class="superTypes hiddenContent"><span class="extype" name="scala.AnyRef">AnyRef</span>, <span class="extype" name="scala.Any">Any</span></div> </div></div> <div id="mbrsel"> <div class="toggle"></div> <div id="memberfilter"> <i class="material-icons arrow"></i> <span class="input"> <input id="mbrsel-input" placeholder="Filter all members" type="text" accesskey="/" /> </span> <i class="clear material-icons"></i> </div> <div id="filterby"> <div id="order"> <span class="filtertype">Ordering</span> <ol> <li class="alpha in"><span>Alphabetic</span></li> <li class="inherit out"><span>By Inheritance</span></li> </ol> </div> <div class="ancestors"> <span class="filtertype">Inherited<br /> </span> <ol id="linearization"> <li class="in" name="org.scalatest.enablers.Futuristic"><span>Futuristic</span></li><li class="in" name="scala.AnyRef"><span>AnyRef</span></li><li class="in" name="scala.Any"><span>Any</span></li> </ol> </div><div class="ancestors"> <span class="filtertype"></span> <ol> <li class="hideall out"><span>Hide All</span></li> <li class="showall in"><span>Show All</span></li> </ol> </div> <div id="visbl"> <span class="filtertype">Visibility</span> <ol><li class="public in"><span>Public</span></li><li class="all out"><span>All</span></li></ol> </div> </div> </div> <div id="template"> <div id="allMembers"> <div class="values members"> <h3>Value Members</h3> <ol> <li name="scala.AnyRef#!=" visbl="pub" class="indented0 " data-isabs="false" fullComment="yes" group="Ungrouped"> <a id="!=(x$1:Any):Boolean"></a><a id="!=(Any):Boolean"></a> <span class="permalink"> <a href="../../../org/scalatest/enablers/Futuristic$.html#!=(x$1:Any):Boolean" title="Permalink"> <i class="material-icons"></i> </a> </span> <span class="modifier_kind"> <span class="modifier">final </span> <span class="kind">def</span> </span> <span class="symbol"> <span title="gt4s: $bang$eq" class="name">!=</span><span class="params">(<span name="arg0">arg0: <span class="extype" name="scala.Any">Any</span></span>)</span><span class="result">: <span class="extype" name="scala.Boolean">Boolean</span></span> </span> <div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd>AnyRef → Any</dd></dl></div> </li><li name="scala.AnyRef###" visbl="pub" class="indented0 " data-isabs="false" fullComment="yes" group="Ungrouped"> <a id="##():Int"></a> <span class="permalink"> <a href="../../../org/scalatest/enablers/Futuristic$.html###():Int" title="Permalink"> <i class="material-icons"></i> </a> </span> <span class="modifier_kind"> <span class="modifier">final </span> <span class="kind">def</span> </span> <span class="symbol"> <span title="gt4s: $hash$hash" class="name">##</span><span class="params">()</span><span class="result">: <span class="extype" name="scala.Int">Int</span></span> </span> <div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd>AnyRef → Any</dd></dl></div> </li><li name="scala.AnyRef#==" visbl="pub" class="indented0 " data-isabs="false" fullComment="yes" group="Ungrouped"> <a id="==(x$1:Any):Boolean"></a><a id="==(Any):Boolean"></a> <span class="permalink"> <a href="../../../org/scalatest/enablers/Futuristic$.html#==(x$1:Any):Boolean" title="Permalink"> <i class="material-icons"></i> </a> </span> <span class="modifier_kind"> <span class="modifier">final </span> <span class="kind">def</span> </span> <span class="symbol"> <span title="gt4s: $eq$eq" class="name">==</span><span class="params">(<span name="arg0">arg0: <span class="extype" name="scala.Any">Any</span></span>)</span><span class="result">: <span class="extype" name="scala.Boolean">Boolean</span></span> </span> <div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd>AnyRef → Any</dd></dl></div> </li><li name="scala.Any#asInstanceOf" visbl="pub" class="indented0 " data-isabs="false" fullComment="yes" group="Ungrouped"> <a id="asInstanceOf[T0]:T0"></a> <span class="permalink"> <a href="../../../org/scalatest/enablers/Futuristic$.html#asInstanceOf[T0]:T0" title="Permalink"> <i class="material-icons"></i> </a> </span> <span class="modifier_kind"> <span class="modifier">final </span> <span class="kind">def</span> </span> <span class="symbol"> <span class="name">asInstanceOf</span><span class="tparams">[<span name="T0">T0</span>]</span><span class="result">: <span class="extype" name="scala.Any.asInstanceOf.T0">T0</span></span> </span> <div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd>Any</dd></dl></div> </li><li name="scala.AnyRef#clone" visbl="prt" class="indented0 " data-isabs="false" fullComment="yes" group="Ungrouped"> <a id="clone():Object"></a><a id="clone():AnyRef"></a> <span class="permalink"> <a href="../../../org/scalatest/enablers/Futuristic$.html#clone():Object" title="Permalink"> <i class="material-icons"></i> </a> </span> <span class="modifier_kind"> <span class="modifier"></span> <span class="kind">def</span> </span> <span class="symbol"> <span class="name">clone</span><span class="params">()</span><span class="result">: <span class="extype" name="scala.AnyRef">AnyRef</span></span> </span> <div class="fullcomment"><dl class="attributes block"> <dt>Attributes</dt><dd>protected[<a href="../../../java/lang/index.html" class="extype" name="java.lang">java.lang</a>] </dd><dt>Definition Classes</dt><dd>AnyRef</dd><dt>Annotations</dt><dd> <span class="name">@native</span><span class="args">()</span> <span class="name">@throws</span><span class="args">(<span> <span class="defval" name="classOf[java.lang.CloneNotSupportedException]">...</span> </span>)</span> </dd></dl></div> </li><li name="scala.AnyRef#eq" visbl="pub" class="indented0 " data-isabs="false" fullComment="yes" group="Ungrouped"> <a id="eq(x$1:AnyRef):Boolean"></a><a id="eq(AnyRef):Boolean"></a> <span class="permalink"> <a href="../../../org/scalatest/enablers/Futuristic$.html#eq(x$1:AnyRef):Boolean" title="Permalink"> <i class="material-icons"></i> </a> </span> <span class="modifier_kind"> <span class="modifier">final </span> <span class="kind">def</span> </span> <span class="symbol"> <span class="name">eq</span><span class="params">(<span name="arg0">arg0: <span class="extype" name="scala.AnyRef">AnyRef</span></span>)</span><span class="result">: <span class="extype" name="scala.Boolean">Boolean</span></span> </span> <div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd>AnyRef</dd></dl></div> </li><li name="scala.AnyRef#equals" visbl="pub" class="indented0 " data-isabs="false" fullComment="yes" group="Ungrouped"> <a id="equals(x$1:Any):Boolean"></a><a id="equals(Any):Boolean"></a> <span class="permalink"> <a href="../../../org/scalatest/enablers/Futuristic$.html#equals(x$1:Any):Boolean" title="Permalink"> <i class="material-icons"></i> </a> </span> <span class="modifier_kind"> <span class="modifier"></span> <span class="kind">def</span> </span> <span class="symbol"> <span class="name">equals</span><span class="params">(<span name="arg0">arg0: <span class="extype" name="scala.Any">Any</span></span>)</span><span class="result">: <span class="extype" name="scala.Boolean">Boolean</span></span> </span> <div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd>AnyRef → Any</dd></dl></div> </li><li name="scala.AnyRef#finalize" visbl="prt" class="indented0 " data-isabs="false" fullComment="yes" group="Ungrouped"> <a id="finalize():Unit"></a> <span class="permalink"> <a href="../../../org/scalatest/enablers/Futuristic$.html#finalize():Unit" title="Permalink"> <i class="material-icons"></i> </a> </span> <span class="modifier_kind"> <span class="modifier"></span> <span class="kind">def</span> </span> <span class="symbol"> <span class="name">finalize</span><span class="params">()</span><span class="result">: <span class="extype" name="scala.Unit">Unit</span></span> </span> <div class="fullcomment"><dl class="attributes block"> <dt>Attributes</dt><dd>protected[<a href="../../../java/lang/index.html" class="extype" name="java.lang">java.lang</a>] </dd><dt>Definition Classes</dt><dd>AnyRef</dd><dt>Annotations</dt><dd> <span class="name">@throws</span><span class="args">(<span> <span class="symbol">classOf[java.lang.Throwable]</span> </span>)</span> </dd></dl></div> </li><li name="org.scalatest.enablers.Futuristic#futuristicNatureOfFutureOf" visbl="pub" class="indented0 " data-isabs="false" fullComment="yes" group="Ungrouped"> <a id="futuristicNatureOfFutureOf[V](implicitexecutionContext:scala.concurrent.ExecutionContext):org.scalatest.enablers.Futuristic[scala.concurrent.Future[V]]"></a><a id="futuristicNatureOfFutureOf[V](ExecutionContext):Futuristic[Future[V]]"></a> <span class="permalink"> <a href="../../../org/scalatest/enablers/Futuristic$.html#futuristicNatureOfFutureOf[V](implicitexecutionContext:scala.concurrent.ExecutionContext):org.scalatest.enablers.Futuristic[scala.concurrent.Future[V]]" title="Permalink"> <i class="material-icons"></i> </a> </span> <span class="modifier_kind"> <span class="modifier">implicit </span> <span class="kind">def</span> </span> <span class="symbol"> <span class="name">futuristicNatureOfFutureOf</span><span class="tparams">[<span name="V">V</span>]</span><span class="params">(<span class="implicit">implicit </span><span name="executionContext">executionContext: <span class="extype" name="scala.concurrent.ExecutionContext">ExecutionContext</span></span>)</span><span class="result">: <a href="Futuristic.html" class="extype" name="org.scalatest.enablers.Futuristic">Futuristic</a>[<span class="extype" name="scala.concurrent.Future">Future</span>[<span class="extype" name="org.scalatest.enablers.Futuristic.futuristicNatureOfFutureOf.V">V</span>]]</span> </span> <p class="shortcomment cmt">Provides a <code>Futuristic</code> value for <code>Future[V]</code> for any type <code>V</code> that performs cleanup using the implicitly provided execution context.</p><div class="fullcomment"><div class="comment cmt"><p>Provides a <code>Futuristic</code> value for <code>Future[V]</code> for any type <code>V</code> that performs cleanup using the implicitly provided execution context. </p></div><dl class="paramcmts block"><dt class="param">executionContext</dt><dd class="cmt"><p>an execution context that provides a strategy for executing the cleanup function</p></dd><dt>returns</dt><dd class="cmt"><p>a <code>Futuristic</code> instance for <code>Future[V]</code></p></dd></dl></div> </li><li name="org.scalatest.enablers.Futuristic#futuristicNatureOfFutureOutcome" visbl="pub" class="indented0 " data-isabs="false" fullComment="yes" group="Ungrouped"> <a id="futuristicNatureOfFutureOutcome(implicitexecutionContext:scala.concurrent.ExecutionContext):org.scalatest.enablers.Futuristic[org.scalatest.FutureOutcome]"></a><a id="futuristicNatureOfFutureOutcome(ExecutionContext):Futuristic[FutureOutcome]"></a> <span class="permalink"> <a href="../../../org/scalatest/enablers/Futuristic$.html#futuristicNatureOfFutureOutcome(implicitexecutionContext:scala.concurrent.ExecutionContext):org.scalatest.enablers.Futuristic[org.scalatest.FutureOutcome]" title="Permalink"> <i class="material-icons"></i> </a> </span> <span class="modifier_kind"> <span class="modifier">implicit </span> <span class="kind">def</span> </span> <span class="symbol"> <span class="name">futuristicNatureOfFutureOutcome</span><span class="params">(<span class="implicit">implicit </span><span name="executionContext">executionContext: <span class="extype" name="scala.concurrent.ExecutionContext">ExecutionContext</span></span>)</span><span class="result">: <a href="Futuristic.html" class="extype" name="org.scalatest.enablers.Futuristic">Futuristic</a>[<a href="../FutureOutcome.html" class="extype" name="org.scalatest.FutureOutcome">FutureOutcome</a>]</span> </span> <p class="shortcomment cmt">Provides a <code>Futuristic</code> value for <code>FutureOutcome</code> that performs cleanup using the implicitly provided execution context.</p><div class="fullcomment"><div class="comment cmt"><p>Provides a <code>Futuristic</code> value for <code>FutureOutcome</code> that performs cleanup using the implicitly provided execution context. </p></div><dl class="paramcmts block"><dt class="param">executionContext</dt><dd class="cmt"><p>an execution context that provides a strategy for executing the cleanup function</p></dd><dt>returns</dt><dd class="cmt"><p>a <code>Futuristic</code> instance for <code>FutureOutcome</code></p></dd></dl></div> </li><li name="scala.AnyRef#getClass" visbl="pub" class="indented0 " data-isabs="false" fullComment="yes" group="Ungrouped"> <a id="getClass():Class[_]"></a> <span class="permalink"> <a href="../../../org/scalatest/enablers/Futuristic$.html#getClass():Class[_]" title="Permalink"> <i class="material-icons"></i> </a> </span> <span class="modifier_kind"> <span class="modifier">final </span> <span class="kind">def</span> </span> <span class="symbol"> <span class="name">getClass</span><span class="params">()</span><span class="result">: <span class="extype" name="java.lang.Class">Class</span>[_]</span> </span> <div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd>AnyRef → Any</dd><dt>Annotations</dt><dd> <span class="name">@native</span><span class="args">()</span> </dd></dl></div> </li><li name="scala.AnyRef#hashCode" visbl="pub" class="indented0 " data-isabs="false" fullComment="yes" group="Ungrouped"> <a id="hashCode():Int"></a> <span class="permalink"> <a href="../../../org/scalatest/enablers/Futuristic$.html#hashCode():Int" title="Permalink"> <i class="material-icons"></i> </a> </span> <span class="modifier_kind"> <span class="modifier"></span> <span class="kind">def</span> </span> <span class="symbol"> <span class="name">hashCode</span><span class="params">()</span><span class="result">: <span class="extype" name="scala.Int">Int</span></span> </span> <div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd>AnyRef → Any</dd><dt>Annotations</dt><dd> <span class="name">@native</span><span class="args">()</span> </dd></dl></div> </li><li name="scala.Any#isInstanceOf" visbl="pub" class="indented0 " data-isabs="false" fullComment="yes" group="Ungrouped"> <a id="isInstanceOf[T0]:Boolean"></a> <span class="permalink"> <a href="../../../org/scalatest/enablers/Futuristic$.html#isInstanceOf[T0]:Boolean" title="Permalink"> <i class="material-icons"></i> </a> </span> <span class="modifier_kind"> <span class="modifier">final </span> <span class="kind">def</span> </span> <span class="symbol"> <span class="name">isInstanceOf</span><span class="tparams">[<span name="T0">T0</span>]</span><span class="result">: <span class="extype" name="scala.Boolean">Boolean</span></span> </span> <div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd>Any</dd></dl></div> </li><li name="scala.AnyRef#ne" visbl="pub" class="indented0 " data-isabs="false" fullComment="yes" group="Ungrouped"> <a id="ne(x$1:AnyRef):Boolean"></a><a id="ne(AnyRef):Boolean"></a> <span class="permalink"> <a href="../../../org/scalatest/enablers/Futuristic$.html#ne(x$1:AnyRef):Boolean" title="Permalink"> <i class="material-icons"></i> </a> </span> <span class="modifier_kind"> <span class="modifier">final </span> <span class="kind">def</span> </span> <span class="symbol"> <span class="name">ne</span><span class="params">(<span name="arg0">arg0: <span class="extype" name="scala.AnyRef">AnyRef</span></span>)</span><span class="result">: <span class="extype" name="scala.Boolean">Boolean</span></span> </span> <div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd>AnyRef</dd></dl></div> </li><li name="scala.AnyRef#notify" visbl="pub" class="indented0 " data-isabs="false" fullComment="yes" group="Ungrouped"> <a id="notify():Unit"></a> <span class="permalink"> <a href="../../../org/scalatest/enablers/Futuristic$.html#notify():Unit" title="Permalink"> <i class="material-icons"></i> </a> </span> <span class="modifier_kind"> <span class="modifier">final </span> <span class="kind">def</span> </span> <span class="symbol"> <span class="name">notify</span><span class="params">()</span><span class="result">: <span class="extype" name="scala.Unit">Unit</span></span> </span> <div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd>AnyRef</dd><dt>Annotations</dt><dd> <span class="name">@native</span><span class="args">()</span> </dd></dl></div> </li><li name="scala.AnyRef#notifyAll" visbl="pub" class="indented0 " data-isabs="false" fullComment="yes" group="Ungrouped"> <a id="notifyAll():Unit"></a> <span class="permalink"> <a href="../../../org/scalatest/enablers/Futuristic$.html#notifyAll():Unit" title="Permalink"> <i class="material-icons"></i> </a> </span> <span class="modifier_kind"> <span class="modifier">final </span> <span class="kind">def</span> </span> <span class="symbol"> <span class="name">notifyAll</span><span class="params">()</span><span class="result">: <span class="extype" name="scala.Unit">Unit</span></span> </span> <div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd>AnyRef</dd><dt>Annotations</dt><dd> <span class="name">@native</span><span class="args">()</span> </dd></dl></div> </li><li name="scala.AnyRef#synchronized" visbl="pub" class="indented0 " data-isabs="false" fullComment="yes" group="Ungrouped"> <a id="synchronized[T0](x$1:=&gt;T0):T0"></a><a id="synchronized[T0](⇒T0):T0"></a> <span class="permalink"> <a href="../../../org/scalatest/enablers/Futuristic$.html#synchronized[T0](x$1:=&gt;T0):T0" title="Permalink"> <i class="material-icons"></i> </a> </span> <span class="modifier_kind"> <span class="modifier">final </span> <span class="kind">def</span> </span> <span class="symbol"> <span class="name">synchronized</span><span class="tparams">[<span name="T0">T0</span>]</span><span class="params">(<span name="arg0">arg0: ⇒ <span class="extype" name="java.lang.AnyRef.synchronized.T0">T0</span></span>)</span><span class="result">: <span class="extype" name="java.lang.AnyRef.synchronized.T0">T0</span></span> </span> <div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd>AnyRef</dd></dl></div> </li><li name="scala.AnyRef#toString" visbl="pub" class="indented0 " data-isabs="false" fullComment="yes" group="Ungrouped"> <a id="toString():String"></a> <span class="permalink"> <a href="../../../org/scalatest/enablers/Futuristic$.html#toString():String" title="Permalink"> <i class="material-icons"></i> </a> </span> <span class="modifier_kind"> <span class="modifier"></span> <span class="kind">def</span> </span> <span class="symbol"> <span class="name">toString</span><span class="params">()</span><span class="result">: <span class="extype" name="java.lang.String">String</span></span> </span> <div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd>AnyRef → Any</dd></dl></div> </li><li name="scala.AnyRef#wait" visbl="pub" class="indented0 " data-isabs="false" fullComment="yes" group="Ungrouped"> <a id="wait():Unit"></a> <span class="permalink"> <a href="../../../org/scalatest/enablers/Futuristic$.html#wait():Unit" title="Permalink"> <i class="material-icons"></i> </a> </span> <span class="modifier_kind"> <span class="modifier">final </span> <span class="kind">def</span> </span> <span class="symbol"> <span class="name">wait</span><span class="params">()</span><span class="result">: <span class="extype" name="scala.Unit">Unit</span></span> </span> <div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd>AnyRef</dd><dt>Annotations</dt><dd> <span class="name">@throws</span><span class="args">(<span> <span class="defval" name="classOf[java.lang.InterruptedException]">...</span> </span>)</span> </dd></dl></div> </li><li name="scala.AnyRef#wait" visbl="pub" class="indented0 " data-isabs="false" fullComment="yes" group="Ungrouped"> <a id="wait(x$1:Long,x$2:Int):Unit"></a><a id="wait(Long,Int):Unit"></a> <span class="permalink"> <a href="../../../org/scalatest/enablers/Futuristic$.html#wait(x$1:Long,x$2:Int):Unit" title="Permalink"> <i class="material-icons"></i> </a> </span> <span class="modifier_kind"> <span class="modifier">final </span> <span class="kind">def</span> </span> <span class="symbol"> <span class="name">wait</span><span class="params">(<span name="arg0">arg0: <span class="extype" name="scala.Long">Long</span></span>, <span name="arg1">arg1: <span class="extype" name="scala.Int">Int</span></span>)</span><span class="result">: <span class="extype" name="scala.Unit">Unit</span></span> </span> <div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd>AnyRef</dd><dt>Annotations</dt><dd> <span class="name">@throws</span><span class="args">(<span> <span class="defval" name="classOf[java.lang.InterruptedException]">...</span> </span>)</span> </dd></dl></div> </li><li name="scala.AnyRef#wait" visbl="pub" class="indented0 " data-isabs="false" fullComment="yes" group="Ungrouped"> <a id="wait(x$1:Long):Unit"></a><a id="wait(Long):Unit"></a> <span class="permalink"> <a href="../../../org/scalatest/enablers/Futuristic$.html#wait(x$1:Long):Unit" title="Permalink"> <i class="material-icons"></i> </a> </span> <span class="modifier_kind"> <span class="modifier">final </span> <span class="kind">def</span> </span> <span class="symbol"> <span class="name">wait</span><span class="params">(<span name="arg0">arg0: <span class="extype" name="scala.Long">Long</span></span>)</span><span class="result">: <span class="extype" name="scala.Unit">Unit</span></span> </span> <div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd>AnyRef</dd><dt>Annotations</dt><dd> <span class="name">@native</span><span class="args">()</span> <span class="name">@throws</span><span class="args">(<span> <span class="defval" name="classOf[java.lang.InterruptedException]">...</span> </span>)</span> </dd></dl></div> </li> </ol> </div> </div> <div id="inheritedMembers"> <div class="parent" name="scala.AnyRef"> <h3>Inherited from <span class="extype" name="scala.AnyRef">AnyRef</span></h3> </div><div class="parent" name="scala.Any"> <h3>Inherited from <span class="extype" name="scala.Any">Any</span></h3> </div> </div> <div id="groupedMembers"> <div class="group" name="Ungrouped"> <h3>Ungrouped</h3> </div> </div> </div> <div id="tooltip"></div> <div id="footer"> </div> </body> </div> </div> </div> </body> </html>
{'content_hash': 'eeadef58937ad6a35ddd7048ab8de70d', 'timestamp': '', 'source': 'github', 'line_count': 801, 'max_line_length': 617, 'avg_line_length': 65.77153558052434, 'alnum_prop': 0.6138412770723004, 'repo_name': 'scalatest/scalatest-website', 'id': '21fd965f82e513f76bb7a68269f6f12270d9a4b4', 'size': '52761', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'public/scaladoc/3.0.6/org/scalatest/enablers/Futuristic$.html', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'CSS', 'bytes': '8401192'}, {'name': 'HTML', 'bytes': '4508833233'}, {'name': 'JavaScript', 'bytes': '12256885'}, {'name': 'Procfile', 'bytes': '62'}, {'name': 'Scala', 'bytes': '136544'}]}
<?php /** * * @author Alberto 'alb-i986' Scotto */ #namespace BootstraPHPed; #use BootstraPHPed\classes\Persistence; /* spl_autoload_register( function( $class ) { $class_filename = 'models/class-' . strtolower($class) . '.php'; echo '<p>loading class '.$class_filename; require_once $class_filename; }); */ require_once './config.inc.php'; // sets the defaults for the constants that have not been defined in config.inc.php if( !defined('DEBUG_MODE') ) define( 'DEBUG_MODE', false ); if( !defined('HOSTNAME') ) define( 'HOSTNAME', $_SERVER['HTTP_HOST'] ); if( !defined('URL_BASE') ) define( 'URL_BASE', '/' ); if( !defined('SYSTEM_NAME') ) define( 'SYSTEM_NAME', 'BootstraPHPed Web Site' ); if( !defined('WEBMASTER_NAME') ) define( 'WEBMASTER_NAME', 'webmaster' ); if( !defined('WEBMASTER_EMAIL') ) define( 'WEBMASTER_EMAIL', 'webmaster@'.HOSTNAME ); if( !defined('TZ') ) define( 'TZ', 'Europe/Rome' ); // define some paths define( 'ROOT_ABSPATH', realpath(__DIR__ . '/..') ); // absolute path of the root (not exposed by the web server) define( 'PUBLIC_ROOT_ABSPATH', __DIR__ ); // absolute path of the public dir containing PHP scripts exposed by the web server define( 'CLASS_PATH', ROOT_ABSPATH . '/classes/'); define( 'FORM_HANDLERS_RELPATH', './form_handlers/'); define( 'VIEWS_PATH', ROOT_ABSPATH.'/views/'); define( 'LOGS_PATH', ROOT_ABSPATH . '/logs/'); define( 'URL_HOME', 'http://'. $_SERVER['HTTP_HOST'] . URL_BASE); // URL of the home page (useful for redirects) // Now, require all the core PHP scripts // 3rd party libraries require_once ROOT_ABSPATH.'/lib/adodb5/adodb.inc.php'; require_once ROOT_ABSPATH.'/lib/log4php/Logger.php'; require_once ROOT_ABSPATH.'/lib/phpass-0.3/PasswordHash.php'; // CLASSES imports // EXCEPTIONS require_once CLASS_PATH.'class-exception-adodb.php'; require_once CLASS_PATH.'class-exception-illegal-object-state.php'; require_once CLASS_PATH.'class-exception-validation.php'; require_once CLASS_PATH.'models/class-dao_core.php'; require_once CLASS_PATH.'models/class-dao.php'; // MODELS require_once CLASS_PATH.'models/class-model.php'; // ELEMENTS require_once CLASS_PATH.'models/class-element.php'; //require_once CLASS_PATH.'models/class-role.php'; require_once CLASS_PATH.'models/class-user.php'; //require_once CLASS_PATH.'models/class-post.php'; // COLLECTIONS //require_once CLASS_PATH.'models/class-collection.php'; // require_once CLASS_PATH.'models/class-users.php'; require_once './session.inc.php'; $dao = DAO::getInstance(); // default exception handler set_exception_handler( function($ex) { if( DEBUG_MODE == true ) $msg = nl2br("Uncaught exception:\n" . $ex->getMessage() . "\n". $ex->getTraceAsString() . "\n"); else $msg = nl2br("Uncaught exception:\n" . $ex->getMessage() . "\n"); showErr(0, $msg); }); date_default_timezone_set(TZ);
{'content_hash': 'baa426815e318e78755a6878466bca2d', 'timestamp': '', 'source': 'github', 'line_count': 88, 'max_line_length': 127, 'avg_line_length': 32.40909090909091, 'alnum_prop': 0.6875876577840112, 'repo_name': 'alb-i986/BootstraPHPed', 'id': '220758f0f18e16c85dd8d370d9d33c57d139b134', 'size': '2852', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'public/globals.inc.php', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'C', 'bytes': '2283'}, {'name': 'JavaScript', 'bytes': '18698'}, {'name': 'PHP', 'bytes': '1943328'}, {'name': 'XSLT', 'bytes': '28086'}]}
/*Jeu du pendu réalisé par Romain Dauby*/ #ifndef FCT_H_INCLUDED #define FCT_H_INCLUDED int cpt; char lireCaractere(); void afficherCoups(int cpt); char proposezLettre(); void afficherMotSecret(int *table, const char *table2); void initialiser_motTrouve(int *table, int taille); void testLettre(char lettre, int *table1, const char *table2); int testGagne(int *motTrouve, const char *motSecret); #endif // FCT_H_INCLUDED
{'content_hash': '41d70a2b4f3c082da346dc5b85d9c2a0', 'timestamp': '', 'source': 'github', 'line_count': 17, 'max_line_length': 62, 'avg_line_length': 25.058823529411764, 'alnum_prop': 0.7582159624413145, 'repo_name': 'r0mdau/boutsdeCodeBlocks', 'id': '21cf174d834730b1693b8d838fc6186c54597ff0', 'size': '426', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'pendu/fct.h', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'C', 'bytes': '9699'}, {'name': 'C++', 'bytes': '14433'}]}
#nullable enable namespace Gu.Reactive { using System; using System.Collections.ObjectModel; using System.ComponentModel; using System.Linq.Expressions; /// <summary> /// Factory methods for creating trackers for max value. /// </summary> public static class MaxTracker { /// <summary> /// Creates a <see cref="MaxTracker{TValue}"/> for <paramref name="source"/> /// </summary> /// <typeparam name="TItem">The type of the items in <paramref name="source"/></typeparam> /// <typeparam name="TValue">The type of the max value.</typeparam> /// <param name="source">The source collection.</param> /// <param name="selector">The function used when producing a value from an item.</param> /// <returns>A tracker with Value synced with source.Max()</returns> public static MaxTracker<TValue> TrackMax<TItem, TValue>(this ObservableCollection<TItem> source, Expression<Func<TItem, TValue>> selector) where TItem : class, INotifyPropertyChanged where TValue : struct, IComparable<TValue> { return new MaxTracker<TValue>(new NestedChanges<ObservableCollection<TItem>, TItem, TValue>(source, selector)); } /// <summary> /// Creates a <see cref="MaxTracker{TValue}"/> for <paramref name="source"/> /// </summary> /// <typeparam name="TValue">The type of the max value.</typeparam> /// <param name="source">The source collection.</param> /// <returns>A tracker with Value synced with source.Max()</returns> public static MaxTracker<TValue> TrackMax<TValue>(this ObservableCollection<TValue> source) where TValue : struct, IComparable<TValue> { return new MaxTracker<TValue>(new SimpleChanges<ObservableCollection<TValue>, TValue>(source)); } /// <summary> /// Creates a <see cref="MaxTracker{TValue}"/> for <paramref name="source"/> /// </summary> /// <typeparam name="TItem">The type of the items in <paramref name="source"/></typeparam> /// <typeparam name="TValue">The type of the max value.</typeparam> /// <param name="source">The source collection.</param> /// <param name="selector">The function used when producing a value from an item.</param> /// <returns>A tracker with Value synced with source.Max()</returns> public static MaxTracker<TValue> TrackMax<TItem, TValue>(this ReadOnlyObservableCollection<TItem> source, Expression<Func<TItem, TValue>> selector) where TItem : class, INotifyPropertyChanged where TValue : struct, IComparable<TValue> { return new MaxTracker<TValue>(new NestedChanges<ReadOnlyObservableCollection<TItem>, TItem, TValue>(source, selector)); } /// <summary> /// Creates a <see cref="MaxTracker{TValue}"/> for <paramref name="source"/> /// </summary> /// <typeparam name="TValue">The type of the max value.</typeparam> /// <param name="source">The source collection.</param> /// <returns>A tracker with Value synced with source.Max()</returns> public static MaxTracker<TValue> TrackMax<TValue>(this ReadOnlyObservableCollection<TValue> source) where TValue : struct, IComparable<TValue> { return new MaxTracker<TValue>(new SimpleChanges<ReadOnlyObservableCollection<TValue>, TValue>(source)); } /// <summary> /// Creates a <see cref="MaxTracker{TValue}"/> for <paramref name="source"/> /// </summary> /// <typeparam name="TItem">The type of the items in <paramref name="source"/></typeparam> /// <typeparam name="TValue">The type of the max value.</typeparam> /// <param name="source">The source collection.</param> /// <param name="selector">The function used when producing a value from an item.</param> /// <returns>A tracker with Value synced with source.Max()</returns> public static MaxTracker<TValue> TrackMax<TItem, TValue>(this IReadOnlyObservableCollection<TItem> source, Expression<Func<TItem, TValue>> selector) where TItem : class, INotifyPropertyChanged where TValue : struct, IComparable<TValue> { return new MaxTracker<TValue>(new NestedChanges<IReadOnlyObservableCollection<TItem>, TItem, TValue>(source, selector)); } /// <summary> /// Creates a <see cref="MaxTracker{TValue}"/> for <paramref name="source"/> /// </summary> /// <typeparam name="TValue">The type of the max value.</typeparam> /// <param name="source">The source collection.</param> /// <returns>A tracker with Value synced with source.Max()</returns> public static MaxTracker<TValue> TrackMax<TValue>(this IReadOnlyObservableCollection<TValue> source) where TValue : struct, IComparable<TValue> { return new MaxTracker<TValue>(new SimpleChanges<IReadOnlyObservableCollection<TValue>, TValue>(source)); } } }
{'content_hash': '32a893d420758e4b40644752699f601c', 'timestamp': '', 'source': 'github', 'line_count': 95, 'max_line_length': 156, 'avg_line_length': 53.90526315789474, 'alnum_prop': 0.6430384690490138, 'repo_name': 'JohanLarsson/Gu.Reactive', 'id': '239061dad9939fc438c52f2d2f4c921594f1df6a', 'size': '5123', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'Gu.Reactive/Trackers/MaxTracker.generated.cs', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'C#', 'bytes': '1929644'}, {'name': 'PowerShell', 'bytes': '2709'}]}
package com.jetbrains.python.inspections; import com.jetbrains.python.fixtures.PyInspectionTestCase; import org.jetbrains.annotations.NotNull; public class PyTypedDictInspectionTest extends PyInspectionTestCase { public void testUnknownKey() { doTestByText("from typing import TypedDict\n" + "class Movie(TypedDict, total=False):\n" + " name: str\n" + " year: int\n" + "Movie2 = TypedDict('Movie2', {'name': str, 'year': int}, total=False)\n" + "movie = Movie2(name='Blade Runner')\n" + "movie2 = Movie2(name='Blade Runner')\n" + "movie['year'] = 42\n" + "movie2['year'] = 42\n" + "movie[<warning descr=\"TypedDict \\\"Movie2\\\" has no key 'id'\">'id'</warning>] = 43\n" + "movie2[<warning descr=\"TypedDict \\\"Movie2\\\" has no key 'id'\">'id'</warning>] = 43\n"); } public void testMetaclass() { doTestByText("from typing import TypedDict\n" + "\n" + "class Movie(TypedDict, <warning descr=\"Specifying a metaclass is not allowed in TypedDict\">metaclass=Meta</warning>):\n" + " name: str"); } public void testExtraClassDeclarations() { doTestByText("from typing import TypedDict\n" + "class Movie(TypedDict):\n" + " name: str\n" + " def <weak_warning descr=\"Invalid statement in TypedDict definition; expected 'field_name: field_type'\">my_method</weak_warning>(self):\n" + " pass\n" + " class <weak_warning descr=\"Invalid statement in TypedDict definition; expected 'field_name: field_type'\">Horror</weak_warning>:\n" + " def __init__(self):\n" + " ..."); } public void testInitializer() { doTestByText("from typing import TypedDict\n" + "class Movie(TypedDict):\n" + " name: str\n" + " year: int = <warning descr=\"Right-hand side values are not supported in TypedDict\">42</warning>"); } public void testPass() { doTestByText("from typing import TypedDict\n" + "class Movie(TypedDict):\n" + " <weak_warning descr=\"Invalid statement in TypedDict definition; expected 'field_name: field_type'\">...</weak_warning>\n" + "class HorrorMovie(TypedDict):\n" + " pass"); } public void testNonTypedDictAsSuperclass() { doTestByText("from typing import TypedDict, NamedTuple\n" + "class Bastard:\n" + " pass\n" + "class X(TypedDict):\n" + " x: int\n" + "class Y(TypedDict):\n" + " y: str\n" + "class XYZ(X, <warning descr=\"TypedDict cannot inherit from a non-TypedDict base class\">Bastard</warning>):\n" + " z: bool\n" + "class MyNT(NamedTuple):\n" + " a: str"); } public void testNameAndVariableNameDoNotMatch() { doTestByText("from typing import TypedDict\n" + "Movie2 = TypedDict(<warning descr=\"First argument has to match the variable name\">'Movie'</warning>, {'name': str, 'year': int}, total=False)"); } public void testKeyTypesAlternativeSyntax() { doTestByText("from typing import TypedDict, Any, Optional\n" + "Movie = TypedDict('Movie', {'name': Optional[int], 'smth': type, 'smthElse': Any, 'year': <weak_warning descr=\"Value must be a type\">2</weak_warning>}, total=False)"); } public void testKeyTypes() { doTestByText("from typing import TypedDict, Any, Optional\n" + "class Movie(TypedDict):\n" + " name: Optional[int]\n" + " smth: type\n" + " smthElse: Any\n" + " year: <weak_warning descr=\"Value must be a type\">2</weak_warning>"); } public void testFinalKey() { doTestByText("from typing import TypedDict, Final\n" + "class Movie(TypedDict):\n" + " name: str\n" + " year: int\n" + "YEAR: Final = 'year'\n" + "m = Movie(name='Alien', year=1979)\n" + "years_since_epoch = m[YEAR] - 1970"); } public void testStringVariableAsKey() { doTestByText("from typing import TypedDict, Final\n" + "class Movie(TypedDict):\n" + " name: str\n" + " year: int\n" + "year = 'year'\n" + "year2 = year\n" + "m = Movie(name='Alien', year=1979)\n" + "years_since_epoch = m[year2] - 1970\n" + "year = 42\n" + "print(m[<warning descr=\"TypedDict key must be a string literal; expected one of ('name', 'year')\">year</warning>])"); } public void testDelStatement() { doTestByText("from typing import TypedDict\n" + "class Movie(TypedDict):\n" + " name: str\n" + " year: int\n" + "class HorrorMovie(Movie, total=False):\n" + " based_on_book: bool\n" + "year = 'year'\n" + "year2 = year\n" + "m = HorrorMovie(name='Alien', year=1979)\n" + "del (m['based_on_book'], m[<warning descr=\"Key 'name' of TypedDict 'HorrorMovie' cannot be deleted\">'name'</warning>])\n" + "del m[<warning descr=\"Key 'year' of TypedDict 'HorrorMovie' cannot be deleted\">year2</warning>], m['based_on_book']"); } public void testDictModificationMethods() { doTestByText("from typing import TypedDict\n" + "class Movie(TypedDict):\n" + " name: str\n" + " year: int\n" + "class Horror(Movie, total=False):\n" + " based_on_book: bool\n" + "m = Horror(name='Alien', year=1979)\n" + "m.<warning descr=\"This operation might break TypedDict consistency\">clear</warning>()\n" + "name = 'name'\n" + "m.pop('based_on_book')\n" + "m.<warning descr=\"Key 'year' of TypedDict 'Horror' cannot be deleted\">pop</warning>('year')\n" + "m.<weak_warning descr=\"This operation might break TypedDict consistency\">popitem</weak_warning>()\n" + "m.setdefault('based_on_book', <warning descr=\"Expected type 'bool', got 'int' instead\">42</warning>)"); } public void testUpdateMethods() { doTestByText("from typing import TypedDict, Optional\n" + "class Movie(TypedDict):\n" + " name: str\n" + " year: Optional[int]\n" + "class Horror(Movie, total=False):\n" + " based_on_book: bool\n" + "m = Horror(name='Alien', year=1979)\n" + "d={'name':'Garden State', 'year':2004}\n" + "m.update(d)\n" + "m.update({'name':'Garden State', 'year':<warning descr=\"Expected type 'int | None', got 'str' instead\">'2004'</warning>, <warning descr=\"TypedDict \\\"Horror\\\" cannot have key 'based_on'\">'based_on'</warning>: 'book'})\n" + "m.update(name=<warning descr=\"Expected type 'str', got 'int' instead\">1984</warning>, year=1984, based_on_book=<warning descr=\"Expected type 'bool', got 'str' instead\">'yes'</warning>)\n" + "m.update([('name',<warning descr=\"Expected type 'str', got 'int' instead\">1984</warning>), ('year',None)])"); } public void testDocString() { doTestByText("from typing import TypedDict\n" + "class Cinema(TypedDict):\n" + " \"\"\"\n" + " It's doc string\n" + " \"\"\""); } public void testFieldOverwrittenByInheritance() { doTestByText("from typing import TypedDict\n" + "class X(TypedDict):\n" + " y: int\n" + "class Y(TypedDict):\n" + " y: str\n" + "class XYZ<warning descr=\"Cannot overwrite TypedDict field 'y' while merging\">(X, Y)</warning>:\n" + " <warning descr=\"Cannot overwrite TypedDict field\">y</warning>: bool"); } public void testIncorrectTypedDictArguments() { doTestByText("from typing import TypedDict\n" + "c = TypedDict(\"c\", [1, 2, 3])"); } public void testTypedDictNonStringKey() { doTestByText("from typing import TypedDict\n" + "Movie = TypedDict('Movie', {'name': str, 'year': int}, total=False)\n" + "class Movie2(TypedDict, total=False):\n" + " name: str\n" + " year: int\n" + "movie = Movie()\n" + "movie2 = Movie2()\n" + "movie[<warning descr=\"TypedDict key must be a string literal; expected one of ('name', 'year')\">2</warning>]\n" + "movie2[<warning descr=\"TypedDict key must be a string literal; expected one of ('name', 'year')\">2</warning>]"); } public void testTypedDictKeyValueWrite() { doTestByText("from typing import TypedDict\n" + "Movie = TypedDict('Movie', {'name': str, 'year': int}, total=False)\n" + "class Movie2(TypedDict, total=False):\n" + " name: str\n" + " year: int\n" + "movie = Movie()\n" + "movie2 = Movie2()\n" + "movie['year'], movie2['year'] = <warning descr=\"Expected type 'int', got 'str' instead\">'1984'</warning>, " + "<warning descr=\"Expected type 'int', got 'str' instead\">'1984'</warning>\n"); } public void testTypedDictKeyValueWriteToTypedDictField() { doTestByText("from typing import TypedDict\n" + "X = TypedDict('X', {'d': dict}, total=False)\n" + "class X2(TypedDict, total=False):\n" + " d: dict\n" + "x = X()\n" + "x2 = X2()\n" + "x['d']['k'], x2['d']['k'] = 'v', 'v'"); } public void testIncorrectTotalityValue() { doTestByText("from typing import TypedDict\n" + "class X(TypedDict, total=<warning descr=\"Value of 'total' must be True or False\">1</warning>):\n" + " x: int\n"); } public void testIncorrectTotalityValueAlternativeSyntax() { doTestByText("from typing import TypedDict\n" + "X = TypedDict('X', {'x': int}, total=<warning descr=\"Value of 'total' must be True or False\">1</warning>)"); } public void testGetWithIncorrectKeyType() { doTestByText("from typing import TypedDict\n" + "class X(TypedDict):\n" + " x: int\n" + "x = X()\n" + "x.get(<warning descr=\"Key should be string\">42</warning>, 67)"); } public void testGetWithIncorrectKeyValue() { doTestByText("from typing import TypedDict\n" + "class X(TypedDict):\n" + " x: int\n" + "x = X()\n" + "x.get(<warning descr=\"TypedDict \\\"X\\\" has no key 'y'\">'y'</warning>, 67)\n" + "x.get('x', '')"); } // PY-39404 public void testImportedTypedDict() { doMultiFileTest(); } // PY-40906 public void testLiteralAsTypedDictKey() { doTestByText("from typing import TypedDict, Literal, Union\n" + "class Movie(TypedDict):\n" + " name: str\n" + " year: int\n" + "def get_value(movie: Movie, key: Literal['year', 'name']) -> Union[int, str]:\n" + " return movie[key]\n" + "def get_value(movie: Movie, key: Literal['name']) -> Union[int, str]:\n" + " return movie[key]\n" + "def get_value(movie: Movie, key: Literal['name1']) -> Union[int, str]:\n" + " return movie[<warning descr=\"TypedDict \\\"Movie\\\" has no key 'name1'\">key</warning>]\n" + "def get_value(movie: Movie, key: Literal['year', 42]) -> Union[int, str]:\n" + " return movie[<warning descr=\"TypedDict key must be a string literal; expected one of ('name', 'year')\">key</warning>]\n" + "def get_value(movie: Movie, key: Literal['year', 'name1', '42']) -> Union[int, str]:\n" + " return movie[<warning descr=\"TypedDict \\\"Movie\\\" has no keys ('name1', '42')\">key</warning>]\n" + "def get_value(movie: Movie, key: Literal[42]) -> Union[int, str]:\n" + " return movie[<warning descr=\"TypedDict key must be a string literal; expected one of ('name', 'year')\">key</warning>]"); } // PY-44714 public void testNoneAsType() { doTestByText("from typing import TypedDict\n" + "class X(TypedDict):\n" + " n: None\n" + "Y = TypedDict('Y', {'n': None})\n"); } @NotNull @Override protected Class<? extends PyInspection> getInspectionClass() { return PyTypedDictInspection.class; } }
{'content_hash': '4c790b71c1daff47a0426ed91bf2f6b4', 'timestamp': '', 'source': 'github', 'line_count': 279, 'max_line_length': 247, 'avg_line_length': 48.272401433691755, 'alnum_prop': 0.5145530145530145, 'repo_name': 'siosio/intellij-community', 'id': '664124c047672c3023f13eab2e3fc4209858f3c2', 'size': '13609', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'python/testSrc/com/jetbrains/python/inspections/PyTypedDictInspectionTest.java', 'mode': '33188', 'license': 'apache-2.0', 'language': []}
from __future__ import unicode_literals import unittest import sys from bibtexparser.bparser import BibTexParser from bibtexparser.bwriter import BibTexWriter, to_bibtex from bibtexparser.customization import author class TestBibtexWriterList(unittest.TestCase): ########### # ARTICLE ########### def test_article(self): with open('bibtexparser/tests/data/article.bib', 'r') as bibfile: bib = BibTexParser(bibfile.read()) with open('bibtexparser/tests/data/article_output.bib', 'r') as bibfile: expected = bibfile.read() result = to_bibtex(bib) if not sys.version_info >= (3, 0): if isinstance(result, unicode): result = result.encode('utf-8') self.maxDiff = None self.assertEqual(expected, result) ########### # BOOK ########### def test_book(self): with open('bibtexparser/tests/data/book.bib', 'r') as bibfile: bib = BibTexParser(bibfile.read()) with open('bibtexparser/tests/data/book_output.bib', 'r') as bibfile: expected = bibfile.read() result = to_bibtex(bib) self.maxDiff = None self.assertEqual(expected, result) ########### # COMMA FIRST ########### def test_comma_first(self): with open('bibtexparser/tests/data/book.bib', 'r') as bibfile: bib = BibTexParser(bibfile.read()) with open('bibtexparser/tests/data/book_comma_first.bib', 'r') as bibfile: expected = bibfile.read() writer = BibTexWriter() writer.indent = ' ' writer.comma_first = True result = writer.write(bib) self.maxDiff = None self.assertEqual(expected, result) ########### # MULTIPLE ########### def test_multiple(self): with open('bibtexparser/tests/data/multiple_entries.bib', 'r') as bibfile: bib = BibTexParser(bibfile.read()) with open('bibtexparser/tests/data/multiple_entries_output.bib', 'r') as bibfile: expected = bibfile.read() result = to_bibtex(bib) self.maxDiff = None self.assertEqual(expected, result) ########### # Exception ########### def test_exception_typeerror(self): with open('bibtexparser/tests/data/article.bib', 'r') as bibfile: bib = BibTexParser(bibfile.read(), customization=author) self.assertRaises(TypeError, to_bibtex, bib)
{'content_hash': '59641d3fcf1bc8448fe562261846a1ea', 'timestamp': '', 'source': 'github', 'line_count': 78, 'max_line_length': 89, 'avg_line_length': 31.76923076923077, 'alnum_prop': 0.5912025827280064, 'repo_name': 'Juvawa/bib2web', 'id': 'c5d026229b98ae7ce1694845123fe36bb660a0c0', 'size': '2564', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'bib2web/bibtexparser/tests/test_bwriter.py', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'Python', 'bytes': '210786'}, {'name': 'TeX', 'bytes': '8148'}]}
<?php namespace Taskeet\MainBundle\Entity; use Doctrine\ORM\Mapping as ORM; use Symfony\Component\HttpFoundation\File\File; use Symfony\Component\Validator\Constraints as Assert; use Vich\UploaderBundle\Mapping\Annotation as Vich; /** * EventCategory * * @ORM\Table(name="event_category") * @ORM\Entity * @Vich\Uploadable */ class EventCategory { /** * @var integer * * @ORM\Column(name="id", type="integer") * @ORM\Id * @ORM\GeneratedValue(strategy="AUTO") */ private $id; /** * @var string * * @ORM\Column(name="name", type="string", length=32) */ private $name; /** * @Assert\File( * maxSize="1M", * mimeTypes={"image/png", "image/jpeg", "image/pjpeg"} * ) * @Vich\UploadableField(mapping="event_image", fileNameProperty="imageName") * * @var File $image */ private $image; /** * @var string * * @ORM\Column(name="imageName", type="string", length=255) */ private $imageName; /** * Get id * * @return integer */ public function getId() { return $this->id; } /** * Set name * * @param string $name * @return EventCategory */ public function setName($name) { $this->name = $name; return $this; } /** * Get name * * @return string */ public function getName() { return $this->name; } /** * @param \Symfony\Component\HttpFoundation\File\File $image */ public function setImage($image) { $this->image = $image; return $this; } /** * @return \Symfony\Component\HttpFoundation\File\File */ public function getImage() { return $this->image; } /** * Set imageName * * @param string $imageName * @return EventCategory */ public function setImageName($imageName) { $this->imageName = $imageName; return $this; } /** * Get imageName * * @return string */ public function getImageName() { return $this->imageName; } public function __toString() { return $this->name; } }
{'content_hash': '46b9811ccd02f612ac121a192106833f', 'timestamp': '', 'source': 'github', 'line_count': 132, 'max_line_length': 81, 'avg_line_length': 17.272727272727273, 'alnum_prop': 0.5289473684210526, 'repo_name': 'jarmas8611/proyect', 'id': 'd6f37f2abc7c0737544d245d6988d4c000d1091a', 'size': '2280', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'src/Taskeet/MainBundle/Entity/EventCategory.php', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'CSS', 'bytes': '178392'}, {'name': 'HTML', 'bytes': '101934'}, {'name': 'JavaScript', 'bytes': '354584'}, {'name': 'PHP', 'bytes': '209606'}]}
package chapter.sixteen import ExerciseOne._ import org.scalatest._ import org.scalatest.junit.JUnitRunner import org.junit.runner.RunWith @RunWith(classOf[JUnitRunner]) class ExerciseOneSpec extends FlatSpec with Matchers { "function" should "" in { } }
{'content_hash': 'abe33f63c99ef6a840210be198899e9b', 'timestamp': '', 'source': 'github', 'line_count': 14, 'max_line_length': 54, 'avg_line_length': 18.785714285714285, 'alnum_prop': 0.779467680608365, 'repo_name': 'deekim/impatient-scala', 'id': 'dbc16e952ec11621b73119a580f89fba0420dca5', 'size': '263', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'src/test/scala/chapter/sixteen/ExerciseOneSpec.scala', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'Ruby', 'bytes': '317'}, {'name': 'Scala', 'bytes': '130378'}, {'name': 'Shell', 'bytes': '1447'}]}
{% extends "layout/default.html" %} {% set active_page = 'events' %} {% block title %} Events{{ super() }} {% endblock %} {% block main_body %} <div class="row"> <!-- Blog Entries Column --> <div class="col-md-8"> <h2 class="ppage-header"> Upcoming events and presentations </h2> <ul> <li> 26 October 2016, "Speech presentation in 19th century literature: A hands-on approach" as part of the CCR Corpus Training Sessions, Johan de Joode </li> <li> 1 November 2016, Michaela Mahlberg will deliver <a href="https://cardiffdigitalnetwork.org/2016/09/07/cfp-word-image-digital/"/>a keynote</a> at the Cardiff Digital Cultures Network </li> <li> 30 November 2016, "Discourse and dialogue: Annotating and aggregating corpus data" as part of the CCR Corpus Training Sessions, Johan de Joode </li> </ul> <h2 class="ppage-header"> Past events and presentations </h2> <ul> <li> 16-18 September 2016, Michaela Mahlberg gave a keynote at the <a href="https://apling.engl.iastate.edu/conferences/aacl2016/"> American Association for Corpus Linguistics (AACL) Conference</a> </li> <li> 4 July 2016, CLiC Workshop at University of Kent </li> <li> 20-24 June 2016 <a href="http://www.birmingham.ac.uk/research/activity/corpus/events/2016/corpus-linguistics-summer-school.aspx">Corpus Linguistics Summer School at CCR</a> </li> <li> 20 June 2016 Michaela Mahlberg delivers 11th Annual Sinclair Lecture: You can watch a video of the lecture <a href="http://www.birmingham.ac.uk/research/activity/corpus/news/2016/sinclair-lecture-2016.aspx">here</a>. </li> <li> 4 June 2016 - Hay Festival, University of Birmingham series, <a href="https://www.hayfestival.com/p-11096-john-holmes-michaela-mahlberg-will-tattersdill.aspx">‘Hot off the press’</a> John Holmes, Michaela Mahlberg and Will Tattersdill </li> <li> 14 March 2016, CLiC Workshop for the Schools Partnership Gateway, ‘Corpus Stylistics for the English Classroom’, University of Nottingham </li> <li> 16 November 2015, CLiC Workshop hosted jointly organised the CCR and AQA, ‘Corpus Stylistics for A-level Teachers’ – see <a href="https://thedefinitearticle.aqa.org.uk/2016/01/25/corpus-stylistics-workshop-for-a-level-teachers/">here</a> for a review </li> <!-- <li>16 November 2015: <a href="http://www.aqa.org.uk/professional-development/course-details?meta_E=SENGAlevelEnglishWorkshopCorpuslinguisticmethods" class="sys_16">Using corpus linguistic methods in the classroom: A one-day workshop for A level teachers</a></li> --> <li>12 November 2015, <a title="Advanced CLiC - User-defined annotation" href="http://birmingham.ac.uk/schools/edacs/departments/englishlanguage/events/2015/de-joode-advanced-corpus-workshop.aspx" class="sys_0 sys_t1491559">Advanced CLiC &ndash; User-defined annotation</a>, Centre for Advanced Research in English, Johan de Joode</li> <li>29 October 2015, <a title="Using CLiC to study literature" href="http://birmingham.ac.uk/schools/edacs/departments/englishlanguage/events/2015/de-joode-corpus-workshop.aspx" class="sys_0 sys_t1491559">Using CLiC to study literature</a>, Centre for Advanced Research in English, Johan de Joode</li> </ul> </div> <!-- Blog Sidebar Widgets Column --> {% include "blocks/twitter.html" %} </div> <!-- Footer --> {% endblock %} {% block scripts %} {{ super() }} {% endblock %}
{'content_hash': '4baf795a29d4274669b66ab122d60d6f', 'timestamp': '', 'source': 'github', 'line_count': 82, 'max_line_length': 338, 'avg_line_length': 42.1219512195122, 'alnum_prop': 0.7101910828025477, 'repo_name': 'CentreForResearchInAppliedLinguistics/clic', 'id': 'f2649ac96c137a2a0cc22fe60062fad25e754fa2', 'size': '3468', 'binary': False, 'copies': '2', 'ref': 'refs/heads/develop', 'path': 'clic/web/templates/info/events.html', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'CSS', 'bytes': '4449'}, {'name': 'HTML', 'bytes': '167472'}, {'name': 'JavaScript', 'bytes': '45975'}, {'name': 'Mako', 'bytes': '412'}, {'name': 'Python', 'bytes': '144586'}, {'name': 'XSLT', 'bytes': '12605'}]}
/* * drop the SQL schema used by org.apache.slide.impl.rdbms.PostgresAdapter. * Tested with Postgres 7.4. * */ DROP VIEW LOCKS_VIEW; DROP VIEW PERMISSIONS_VIEW; DROP VIEW BINDING_VIEW; DROP VIEW OBJECT_VIEW; DROP TABLE PROPERTIES; DROP TABLE VERSION_CONTENT; DROP TABLE VERSION_PREDS; DROP TABLE VERSION_LABELS; DROP TABLE VERSION_HISTORY; DROP TABLE VERSION; DROP TABLE BINDING; DROP TABLE PARENT_BINDING; DROP TABLE LINKS; DROP TABLE LOCKS; DROP TABLE BRANCH; DROP TABLE LABEL; DROP TABLE PERMISSIONS; DROP TABLE OBJECT; DROP TABLE URI;
{'content_hash': '5a49349cb1560c2c23bb44af82aff019', 'timestamp': '', 'source': 'github', 'line_count': 27, 'max_line_length': 75, 'avg_line_length': 20.444444444444443, 'alnum_prop': 0.7663043478260869, 'repo_name': 'integrated/jakarta-slide-server', 'id': '1d803c82f407aacb3d91d9f1b1a07e4df3a20efc', 'size': '1482', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'src/conf/schema/dropPostgresSchema.sql', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'Java', 'bytes': '7980335'}, {'name': 'XSLT', 'bytes': '19468'}]}
var fs = require('fs'); var gdal = require('gdal'); var in_file = process.argv[2]; var out_base_name = process.argv[3]; var ds = gdal.open(in_file); var wgs84 = gdal.SpatialReference.fromEPSG(4326); gdal.verbose(); gdal.config.set('CPL_DEBUG', 'ON'); gdal.config.set('CPL_LOG_ERRORS', 'ON'); ds.layers.forEach(function (lyr) { console.log('processing: ', lyr.name); var lyr_name = lyr.name.replace(':', ''); //strip invalid filename characters var out_name = out_base_name + '_' + lyr_name + '.geojson'; if (fs.existsSync(out_name)) { fs.unlink(out_name);} var out_ds = gdal.open(out_name, 'w', 'GeoJSON'); var geojson = out_ds.layers.create(lyr_name, wgs84, lyr.geomType); lyr.features.forEach(function (in_feat) { geojson.features.add(in_feat); }) geojson.flush(); out_ds.flush(); out_ds.close(); });
{'content_hash': 'baed8530c9febf2ec665a0162e12d3e2', 'timestamp': '', 'source': 'github', 'line_count': 25, 'max_line_length': 78, 'avg_line_length': 32.68, 'alnum_prop': 0.6682986536107711, 'repo_name': 'BergWerkGIS/detect-corrupt-tiff', 'id': 'ddb31bb428eb3a0b2edf50820a4aab929478ebb3', 'size': '817', 'binary': False, 'copies': '2', 'ref': 'refs/heads/master', 'path': 'nodejs/convert-to-geojson-via-gdal.js', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'JavaScript', 'bytes': '10759'}, {'name': 'Python', 'bytes': '8714'}]}
// Copyright (c) 2009-2010 Satoshi Nakamoto // Copyright (c) 2009-2012 The Bitcoin developers // Copyright (c) 2013 ContinuumCoin developers // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "alert.h" #include "checkpoints.h" #include "db.h" #include "txdb.h" #include "net.h" #include "init.h" #include "ui_interface.h" #include "checkqueue.h" #include "chainparams.h" #include <boost/algorithm/string/replace.hpp> #include <boost/filesystem.hpp> #include <boost/filesystem/fstream.hpp> using namespace std; using namespace boost; // // Global state // CCriticalSection cs_setpwalletRegistered; set<CWallet*> setpwalletRegistered; CCriticalSection cs_main; CTxMemPool mempool; unsigned int nTransactionsUpdated = 0; map<uint256, CBlockIndex*> mapBlockIndex; std::vector<CBlockIndex*> vBlockIndexByHeight; CBlockIndex* pindexGenesisBlock = NULL; int nBestHeight = -1; uint256 nBestChainWork = 0; uint256 nBestInvalidWork = 0; uint256 hashBestChain = 0; CBlockIndex* pindexBest = NULL; set<CBlockIndex*, CBlockIndexWorkComparator> setBlockIndexValid; // may contain all CBlockIndex*'s that have validness >=BLOCK_VALID_TRANSACTIONS, and must contain those who aren't failed int64 nTimeBestReceived = 0; int nScriptCheckThreads = 0; bool fImporting = false; bool fReindex = false; bool fBenchmark = false; bool fTxIndex = false; unsigned int nCoinCacheSize = 5000; bool fHaveGUI = false; /** Fees smaller than this (in satoshi) are considered zero fee (for transaction creation) */ int64 CTransaction::nMinTxFee = 10000; // Override with -mintxfee /** Fees smaller than this (in satoshi) are considered zero fee (for relaying) */ int64 CTransaction::nMinRelayTxFee = 10000; CMedianFilter<int> cPeerBlockCounts(8, 0); // Amount of blocks that other nodes claim to have map<uint256, CBlock*> mapOrphanBlocks; multimap<uint256, CBlock*> mapOrphanBlocksByPrev; map<uint256, CDataStream*> mapOrphanTransactions; map<uint256, map<uint256, CDataStream*> > mapOrphanTransactionsByPrev; // Constant stuff for coinbase transactions we create: CScript COINBASE_FLAGS; const string strMessageMagic = "ContinuumCoin Signed Message:\n"; double dHashesPerSec = 0.0; int64 nHPSTimerStart = 0; // Settings int64 nTransactionFee = 0; ////////////////////////////////////////////////////////////////////////////// // // dispatching functions // // These functions dispatch to one or all registered wallets void RegisterWallet(CWallet* pwalletIn) { { LOCK(cs_setpwalletRegistered); setpwalletRegistered.insert(pwalletIn); } } void UnregisterWallet(CWallet* pwalletIn) { { LOCK(cs_setpwalletRegistered); setpwalletRegistered.erase(pwalletIn); } } void UnregisterAllWallets() { LOCK(cs_setpwalletRegistered); setpwalletRegistered.clear(); } // get the wallet transaction with the given hash (if it exists) bool static GetTransaction(const uint256& hashTx, CWalletTx& wtx) { LOCK(cs_setpwalletRegistered); BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered) if (pwallet->GetTransaction(hashTx,wtx)) return true; return false; } // erases transaction with the given hash from all wallets void static EraseFromWallets(uint256 hash) { LOCK(cs_setpwalletRegistered); BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered) pwallet->EraseFromWallet(hash); } // make sure all wallets know about the given transaction, in the given block void SyncWithWallets(const uint256 &hash, const CTransaction& tx, const CBlock* pblock, bool fUpdate) { LOCK(cs_setpwalletRegistered); BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered) pwallet->AddToWalletIfInvolvingMe(hash, tx, pblock, fUpdate); } // notify wallets about a new best chain void static SetBestChain(const CBlockLocator& loc) { LOCK(cs_setpwalletRegistered); BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered) pwallet->SetBestChain(loc); } // notify wallets about an updated transaction void static UpdatedTransaction(const uint256& hashTx) { LOCK(cs_setpwalletRegistered); BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered) pwallet->UpdatedTransaction(hashTx); } // dump all wallets void static PrintWallets(const CBlock& block) { LOCK(cs_setpwalletRegistered); BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered) pwallet->PrintWallet(block); } // notify wallets about an incoming inventory (for request counts) void static Inventory(const uint256& hash) { LOCK(cs_setpwalletRegistered); BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered) pwallet->Inventory(hash); } // ask wallets to resend their transactions void static ResendWalletTransactions() { LOCK(cs_setpwalletRegistered); BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered) pwallet->ResendWalletTransactions(); } ////////////////////////////////////////////////////////////////////////////// // // Registration of network node signals. // void RegisterNodeSignals(CNodeSignals& nodeSignals) { nodeSignals.ProcessMessages.connect(&ProcessMessages); nodeSignals.SendMessages.connect(&SendMessages); } void UnregisterNodeSignals(CNodeSignals& nodeSignals) { nodeSignals.ProcessMessages.disconnect(&ProcessMessages); nodeSignals.SendMessages.disconnect(&SendMessages); } ////////////////////////////////////////////////////////////////////////////// // // CBlockLocator implementation // CBlockLocator::CBlockLocator(uint256 hashBlock) { std::map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashBlock); if (mi != mapBlockIndex.end()) Set((*mi).second); } void CBlockLocator::Set(const CBlockIndex* pindex) { vHave.clear(); int nStep = 1; while (pindex) { vHave.push_back(pindex->GetBlockHash()); // Exponentially larger steps back for (int i = 0; pindex && i < nStep; i++) pindex = pindex->pprev; if (vHave.size() > 10) nStep *= 2; } vHave.push_back(Params().HashGenesisBlock()); } int CBlockLocator::GetDistanceBack() { // Retrace how far back it was in the sender's branch int nDistance = 0; int nStep = 1; BOOST_FOREACH(const uint256& hash, vHave) { std::map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hash); if (mi != mapBlockIndex.end()) { CBlockIndex* pindex = (*mi).second; if (pindex->IsInMainChain()) return nDistance; } nDistance += nStep; if (nDistance > 10) nStep *= 2; } return nDistance; } CBlockIndex *CBlockLocator::GetBlockIndex() { // Find the first block the caller has in the main chain BOOST_FOREACH(const uint256& hash, vHave) { std::map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hash); if (mi != mapBlockIndex.end()) { CBlockIndex* pindex = (*mi).second; if (pindex->IsInMainChain()) return pindex; } } return pindexGenesisBlock; } uint256 CBlockLocator::GetBlockHash() { // Find the first block the caller has in the main chain BOOST_FOREACH(const uint256& hash, vHave) { std::map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hash); if (mi != mapBlockIndex.end()) { CBlockIndex* pindex = (*mi).second; if (pindex->IsInMainChain()) return hash; } } return Params().HashGenesisBlock(); } int CBlockLocator::GetHeight() { CBlockIndex* pindex = GetBlockIndex(); if (!pindex) return 0; return pindex->nHeight; } ////////////////////////////////////////////////////////////////////////////// // // CCoinsView implementations // bool CCoinsView::GetCoins(const uint256 &txid, CCoins &coins) { return false; } bool CCoinsView::SetCoins(const uint256 &txid, const CCoins &coins) { return false; } bool CCoinsView::HaveCoins(const uint256 &txid) { return false; } CBlockIndex *CCoinsView::GetBestBlock() { return NULL; } bool CCoinsView::SetBestBlock(CBlockIndex *pindex) { return false; } bool CCoinsView::BatchWrite(const std::map<uint256, CCoins> &mapCoins, CBlockIndex *pindex) { return false; } bool CCoinsView::GetStats(CCoinsStats &stats) { return false; } CCoinsViewBacked::CCoinsViewBacked(CCoinsView &viewIn) : base(&viewIn) { } bool CCoinsViewBacked::GetCoins(const uint256 &txid, CCoins &coins) { return base->GetCoins(txid, coins); } bool CCoinsViewBacked::SetCoins(const uint256 &txid, const CCoins &coins) { return base->SetCoins(txid, coins); } bool CCoinsViewBacked::HaveCoins(const uint256 &txid) { return base->HaveCoins(txid); } CBlockIndex *CCoinsViewBacked::GetBestBlock() { return base->GetBestBlock(); } bool CCoinsViewBacked::SetBestBlock(CBlockIndex *pindex) { return base->SetBestBlock(pindex); } void CCoinsViewBacked::SetBackend(CCoinsView &viewIn) { base = &viewIn; } bool CCoinsViewBacked::BatchWrite(const std::map<uint256, CCoins> &mapCoins, CBlockIndex *pindex) { return base->BatchWrite(mapCoins, pindex); } bool CCoinsViewBacked::GetStats(CCoinsStats &stats) { return base->GetStats(stats); } CCoinsViewCache::CCoinsViewCache(CCoinsView &baseIn, bool fDummy) : CCoinsViewBacked(baseIn), pindexTip(NULL) { } bool CCoinsViewCache::GetCoins(const uint256 &txid, CCoins &coins) { if (cacheCoins.count(txid)) { coins = cacheCoins[txid]; return true; } if (base->GetCoins(txid, coins)) { cacheCoins[txid] = coins; return true; } return false; } std::map<uint256,CCoins>::iterator CCoinsViewCache::FetchCoins(const uint256 &txid) { std::map<uint256,CCoins>::iterator it = cacheCoins.lower_bound(txid); if (it != cacheCoins.end() && it->first == txid) return it; CCoins tmp; if (!base->GetCoins(txid,tmp)) return cacheCoins.end(); std::map<uint256,CCoins>::iterator ret = cacheCoins.insert(it, std::make_pair(txid, CCoins())); tmp.swap(ret->second); return ret; } CCoins &CCoinsViewCache::GetCoins(const uint256 &txid) { std::map<uint256,CCoins>::iterator it = FetchCoins(txid); assert(it != cacheCoins.end()); return it->second; } bool CCoinsViewCache::SetCoins(const uint256 &txid, const CCoins &coins) { cacheCoins[txid] = coins; return true; } bool CCoinsViewCache::HaveCoins(const uint256 &txid) { return FetchCoins(txid) != cacheCoins.end(); } CBlockIndex *CCoinsViewCache::GetBestBlock() { if (pindexTip == NULL) pindexTip = base->GetBestBlock(); return pindexTip; } bool CCoinsViewCache::SetBestBlock(CBlockIndex *pindex) { pindexTip = pindex; return true; } bool CCoinsViewCache::BatchWrite(const std::map<uint256, CCoins> &mapCoins, CBlockIndex *pindex) { for (std::map<uint256, CCoins>::const_iterator it = mapCoins.begin(); it != mapCoins.end(); it++) cacheCoins[it->first] = it->second; pindexTip = pindex; return true; } bool CCoinsViewCache::Flush() { bool fOk = base->BatchWrite(cacheCoins, pindexTip); if (fOk) cacheCoins.clear(); return fOk; } unsigned int CCoinsViewCache::GetCacheSize() { return cacheCoins.size(); } /** CCoinsView that brings transactions from a memorypool into view. It does not check for spendings by memory pool transactions. */ CCoinsViewMemPool::CCoinsViewMemPool(CCoinsView &baseIn, CTxMemPool &mempoolIn) : CCoinsViewBacked(baseIn), mempool(mempoolIn) { } bool CCoinsViewMemPool::GetCoins(const uint256 &txid, CCoins &coins) { if (base->GetCoins(txid, coins)) return true; if (mempool.exists(txid)) { const CTransaction &tx = mempool.lookup(txid); coins = CCoins(tx, MEMPOOL_HEIGHT); return true; } return false; } bool CCoinsViewMemPool::HaveCoins(const uint256 &txid) { return mempool.exists(txid) || base->HaveCoins(txid); } CCoinsViewCache *pcoinsTip = NULL; CBlockTreeDB *pblocktree = NULL; ////////////////////////////////////////////////////////////////////////////// // // mapOrphanTransactions // bool AddOrphanTx(const CDataStream& vMsg) { CTransaction tx; CDataStream(vMsg) >> tx; uint256 hash = tx.GetHash(); if (mapOrphanTransactions.count(hash)) return false; CDataStream* pvMsg = new CDataStream(vMsg); // Ignore big transactions, to avoid a // send-big-orphans memory exhaustion attack. If a peer has a legitimate // large transaction with a missing parent then we assume // it will rebroadcast it later, after the parent transaction(s) // have been mined or received. // 10,000 orphans, each of which is at most 5,000 bytes big is // at most 500 megabytes of orphans: if (pvMsg->size() > 5000) { printf("ignoring large orphan tx (size: %"PRIszu", hash: %s)\n", pvMsg->size(), hash.ToString().c_str()); delete pvMsg; return false; } mapOrphanTransactions[hash] = pvMsg; BOOST_FOREACH(const CTxIn& txin, tx.vin) mapOrphanTransactionsByPrev[txin.prevout.hash].insert(make_pair(hash, pvMsg)); printf("stored orphan tx %s (mapsz %"PRIszu")\n", hash.ToString().c_str(), mapOrphanTransactions.size()); return true; } void static EraseOrphanTx(uint256 hash) { if (!mapOrphanTransactions.count(hash)) return; const CDataStream* pvMsg = mapOrphanTransactions[hash]; CTransaction tx; CDataStream(*pvMsg) >> tx; BOOST_FOREACH(const CTxIn& txin, tx.vin) { mapOrphanTransactionsByPrev[txin.prevout.hash].erase(hash); if (mapOrphanTransactionsByPrev[txin.prevout.hash].empty()) mapOrphanTransactionsByPrev.erase(txin.prevout.hash); } delete pvMsg; mapOrphanTransactions.erase(hash); } unsigned int LimitOrphanTxSize(unsigned int nMaxOrphans) { unsigned int nEvicted = 0; while (mapOrphanTransactions.size() > nMaxOrphans) { // Evict a random orphan: uint256 randomhash = GetRandHash(); map<uint256, CDataStream*>::iterator it = mapOrphanTransactions.lower_bound(randomhash); if (it == mapOrphanTransactions.end()) it = mapOrphanTransactions.begin(); EraseOrphanTx(it->first); ++nEvicted; } return nEvicted; } bool IsStandardTx(const CTransaction& tx, string& reason) { if (tx.nVersion > CTransaction::CURRENT_VERSION) { reason = "version"; return false; } if (!IsFinalTx(tx)) { reason = "non-final"; return false; } // Extremely large transactions with lots of inputs can cost the network // almost as much to process as they cost the sender in fees, because // computing signature hashes is O(ninputs*txsize). Limiting transactions // to MAX_STANDARD_TX_SIZE mitigates CPU exhaustion attacks. unsigned int sz = tx.GetSerializeSize(SER_NETWORK, CTransaction::CURRENT_VERSION); if (sz >= MAX_STANDARD_TX_SIZE) { reason = "tx-size"; return false; } BOOST_FOREACH(const CTxIn& txin, tx.vin) { // Biggest 'standard' txin is a 3-signature 3-of-3 CHECKMULTISIG // pay-to-script-hash, which is 3 ~80-byte signatures, 3 // ~65-byte public keys, plus a few script ops. if (txin.scriptSig.size() > 500) { reason = "scriptsig-size"; return false; } if (!txin.scriptSig.IsPushOnly()) { reason = "scriptsig-not-pushonly"; return false; } } BOOST_FOREACH(const CTxOut& txout, tx.vout) { if (!::IsStandard(txout.scriptPubKey)) { reason = "scriptpubkey"; return false; } if (txout.IsDust(CTransaction::nMinRelayTxFee)) { reason = "dust"; return false; } } return true; } bool IsFinalTx(const CTransaction &tx, int nBlockHeight, int64 nBlockTime) { // Time based nLockTime implemented in 0.1.6 if (tx.nLockTime == 0) return true; if (nBlockHeight == 0) nBlockHeight = nBestHeight; if (nBlockTime == 0) nBlockTime = GetAdjustedTime(); if ((int64)tx.nLockTime < ((int64)tx.nLockTime < LOCKTIME_THRESHOLD ? (int64)nBlockHeight : nBlockTime)) return true; BOOST_FOREACH(const CTxIn& txin, tx.vin) if (!txin.IsFinal()) return false; return true; } /** Amount of bitcoins spent by the transaction. @return sum of all outputs (note: does not include fees) */ int64 GetValueOut(const CTransaction& tx) { int64 nValueOut = 0; BOOST_FOREACH(const CTxOut& txout, tx.vout) { nValueOut += txout.nValue; if (!MoneyRange(txout.nValue) || !MoneyRange(nValueOut)) throw std::runtime_error("GetValueOut() : value out of range"); } return nValueOut; } // // Check transaction inputs, and make sure any // pay-to-script-hash transactions are evaluating IsStandard scripts // // Why bother? To avoid denial-of-service attacks; an attacker // can submit a standard HASH... OP_EQUAL transaction, // which will get accepted into blocks. The redemption // script can be anything; an attacker could use a very // expensive-to-check-upon-redemption script like: // DUP CHECKSIG DROP ... repeated 100 times... OP_1 // bool AreInputsStandard(const CTransaction& tx, CCoinsViewCache& mapInputs) { if (tx.IsCoinBase()) return true; // Coinbases don't use vin normally for (unsigned int i = 0; i < tx.vin.size(); i++) { const CTxOut& prev = mapInputs.GetOutputFor(tx.vin[i]); vector<vector<unsigned char> > vSolutions; txnouttype whichType; // get the scriptPubKey corresponding to this input: const CScript& prevScript = prev.scriptPubKey; if (!Solver(prevScript, whichType, vSolutions)) return false; int nArgsExpected = ScriptSigArgsExpected(whichType, vSolutions); if (nArgsExpected < 0) return false; // Transactions with extra stuff in their scriptSigs are // non-standard. Note that this EvalScript() call will // be quick, because if there are any operations // beside "push data" in the scriptSig the // IsStandard() call returns false vector<vector<unsigned char> > stack; if (!EvalScript(stack, tx.vin[i].scriptSig, tx, i, false, 0)) return false; if (whichType == TX_SCRIPTHASH) { if (stack.empty()) return false; CScript subscript(stack.back().begin(), stack.back().end()); vector<vector<unsigned char> > vSolutions2; txnouttype whichType2; if (!Solver(subscript, whichType2, vSolutions2)) return false; if (whichType2 == TX_SCRIPTHASH) return false; int tmpExpected; tmpExpected = ScriptSigArgsExpected(whichType2, vSolutions2); if (tmpExpected < 0) return false; nArgsExpected += tmpExpected; } if (stack.size() != (unsigned int)nArgsExpected) return false; } return true; } unsigned int GetLegacySigOpCount(const CTransaction& tx) { unsigned int nSigOps = 0; BOOST_FOREACH(const CTxIn& txin, tx.vin) { nSigOps += txin.scriptSig.GetSigOpCount(false); } BOOST_FOREACH(const CTxOut& txout, tx.vout) { nSigOps += txout.scriptPubKey.GetSigOpCount(false); } return nSigOps; } unsigned int GetP2SHSigOpCount(const CTransaction& tx, CCoinsViewCache& inputs) { if (tx.IsCoinBase()) return 0; unsigned int nSigOps = 0; for (unsigned int i = 0; i < tx.vin.size(); i++) { const CTxOut &prevout = inputs.GetOutputFor(tx.vin[i]); if (prevout.scriptPubKey.IsPayToScriptHash()) nSigOps += prevout.scriptPubKey.GetSigOpCount(tx.vin[i].scriptSig); } return nSigOps; } int CMerkleTx::SetMerkleBranch(const CBlock* pblock) { CBlock blockTmp; if (pblock == NULL) { CCoins coins; if (pcoinsTip->GetCoins(GetHash(), coins)) { CBlockIndex *pindex = FindBlockByHeight(coins.nHeight); if (pindex) { if (!ReadBlockFromDisk(blockTmp, pindex)) return 0; pblock = &blockTmp; } } } if (pblock) { // Update the tx's hashBlock hashBlock = pblock->GetHash(); // Locate the transaction for (nIndex = 0; nIndex < (int)pblock->vtx.size(); nIndex++) if (pblock->vtx[nIndex] == *(CTransaction*)this) break; if (nIndex == (int)pblock->vtx.size()) { vMerkleBranch.clear(); nIndex = -1; printf("ERROR: SetMerkleBranch() : couldn't find tx in block\n"); return 0; } // Fill in merkle branch vMerkleBranch = pblock->GetMerkleBranch(nIndex); } // Is the tx in a block that's in the main chain map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashBlock); if (mi == mapBlockIndex.end()) return 0; CBlockIndex* pindex = (*mi).second; if (!pindex || !pindex->IsInMainChain()) return 0; return pindexBest->nHeight - pindex->nHeight + 1; } bool CheckTransaction(const CTransaction& tx, CValidationState &state) { // Basic checks that don't depend on any context if (tx.vin.empty()) return state.DoS(10, error("CheckTransaction() : vin empty")); if (tx.vout.empty()) return state.DoS(10, error("CheckTransaction() : vout empty")); // Size limits if (::GetSerializeSize(tx, SER_NETWORK, PROTOCOL_VERSION) > MAX_BLOCK_SIZE) return state.DoS(100, error("CTransaction::CheckTransaction() : size limits failed")); // Check for negative or overflow output values int64 nValueOut = 0; BOOST_FOREACH(const CTxOut& txout, tx.vout) { if (txout.nValue < 0) return state.DoS(100, error("CheckTransaction() : txout.nValue negative")); if (txout.nValue > MAX_MONEY) return state.DoS(100, error("CheckTransaction() : txout.nValue too high")); nValueOut += txout.nValue; if (!MoneyRange(nValueOut)) return state.DoS(100, error("CTransaction::CheckTransaction() : txout total out of range")); } // Check for duplicate inputs set<COutPoint> vInOutPoints; BOOST_FOREACH(const CTxIn& txin, tx.vin) { if (vInOutPoints.count(txin.prevout)) return state.DoS(100, error("CTransaction::CheckTransaction() : duplicate inputs")); vInOutPoints.insert(txin.prevout); } if (tx.IsCoinBase()) { if (tx.vin[0].scriptSig.size() < 2 || tx.vin[0].scriptSig.size() > 100) return state.DoS(100, error("CheckTransaction() : coinbase script size")); } else { BOOST_FOREACH(const CTxIn& txin, tx.vin) if (txin.prevout.IsNull()) return state.DoS(10, error("CheckTransaction() : prevout is null")); } return true; } int64 GetMinFee(const CTransaction& tx, bool fAllowFree, enum GetMinFee_mode mode) { // Base fee is either nMinTxFee or nMinRelayTxFee int64 nBaseFee = (mode == GMF_RELAY) ? tx.nMinRelayTxFee : tx.nMinTxFee; unsigned int nBytes = ::GetSerializeSize(tx, SER_NETWORK, PROTOCOL_VERSION); int64 nMinFee = (1 + (int64)nBytes / 1000) * nBaseFee; if (fAllowFree) { // There is a free transaction area in blocks created by most miners, // * If we are relaying we allow transactions up to DEFAULT_BLOCK_PRIORITY_SIZE - 1000 // to be considered to fall into this category // * If we are creating a transaction we allow transactions up to DEFAULT_BLOCK_PRIORITY_SIZE - 17000 // (= 10000) to be considered safe and assume they can likely make it into this section if (nBytes < (mode == GMF_SEND ? (DEFAULT_BLOCK_PRIORITY_SIZE - 17000) : (DEFAULT_BLOCK_PRIORITY_SIZE - 1000))) nMinFee = 0; } // To limit dust spam, require base fee if any output is less than 0.01 if (nMinFee < nBaseFee) { BOOST_FOREACH(const CTxOut& txout, tx.vout) if (txout.nValue < CENT) nMinFee = nBaseFee; } if (!MoneyRange(nMinFee)) nMinFee = MAX_MONEY; return nMinFee; } void CTxMemPool::pruneSpent(const uint256 &hashTx, CCoins &coins) { LOCK(cs); std::map<COutPoint, CInPoint>::iterator it = mapNextTx.lower_bound(COutPoint(hashTx, 0)); // iterate over all COutPoints in mapNextTx whose hash equals the provided hashTx while (it != mapNextTx.end() && it->first.hash == hashTx) { coins.Spend(it->first.n); // and remove those outputs from coins it++; } } bool CTxMemPool::accept(CValidationState &state, CTransaction &tx, bool fLimitFree, bool* pfMissingInputs) { if (pfMissingInputs) *pfMissingInputs = false; if (!CheckTransaction(tx, state)) return error("CTxMemPool::accept() : CheckTransaction failed"); // Coinbase is only valid in a block, not as a loose transaction if (tx.IsCoinBase()) return state.DoS(100, error("CTxMemPool::accept() : coinbase as individual tx")); // To help v0.1.5 clients who would see it as a negative number if ((int64)tx.nLockTime > std::numeric_limits<int>::max()) return error("CTxMemPool::accept() : not accepting nLockTime beyond 2038 yet"); // Rather not work on nonstandard transactions (unless -testnet) string reason; if (!TestNet() && !IsStandardTx(tx, reason)) return error("CTxMemPool::accept() : nonstandard transaction: %s", reason.c_str()); // is it already in the memory pool? uint256 hash = tx.GetHash(); { LOCK(cs); if (mapTx.count(hash)) return false; } // Check for conflicts with in-memory transactions CTransaction* ptxOld = NULL; for (unsigned int i = 0; i < tx.vin.size(); i++) { COutPoint outpoint = tx.vin[i].prevout; if (mapNextTx.count(outpoint)) { // Disable replacement feature for now return false; // Allow replacing with a newer version of the same transaction if (i != 0) return false; ptxOld = mapNextTx[outpoint].ptx; if (IsFinalTx(*ptxOld)) return false; if (!tx.IsNewerThan(*ptxOld)) return false; for (unsigned int i = 0; i < tx.vin.size(); i++) { COutPoint outpoint = tx.vin[i].prevout; if (!mapNextTx.count(outpoint) || mapNextTx[outpoint].ptx != ptxOld) return false; } break; } } { CCoinsView dummy; CCoinsViewCache view(dummy); { LOCK(cs); CCoinsViewMemPool viewMemPool(*pcoinsTip, *this); view.SetBackend(viewMemPool); // do we already have it? if (view.HaveCoins(hash)) return false; // do all inputs exist? // Note that this does not check for the presence of actual outputs (see the next check for that), // only helps filling in pfMissingInputs (to determine missing vs spent). BOOST_FOREACH(const CTxIn txin, tx.vin) { if (!view.HaveCoins(txin.prevout.hash)) { if (pfMissingInputs) *pfMissingInputs = true; return false; } } // are the actual inputs available? if (!view.HaveInputs(tx)) return state.Invalid(error("CTxMemPool::accept() : inputs already spent")); // Bring the best block into scope view.GetBestBlock(); // we have all inputs cached now, so switch back to dummy, so we don't need to keep lock on mempool view.SetBackend(dummy); } // Check for non-standard pay-to-script-hash in inputs if (!TestNet() && !AreInputsStandard(tx, view)) return error("CTxMemPool::accept() : nonstandard transaction input"); // Note: if you modify this code to accept non-standard transactions, then // you should add code here to check that the transaction does a // reasonable number of ECDSA signature verifications. int64 nFees = view.GetValueIn(tx)-GetValueOut(tx); unsigned int nSize = ::GetSerializeSize(tx, SER_NETWORK, PROTOCOL_VERSION); // Don't accept it if it can't get into a block int64 txMinFee = GetMinFee(tx, true, GMF_RELAY); if (fLimitFree && nFees < txMinFee) return error("CTxMemPool::accept() : not enough fees %s, %"PRI64d" < %"PRI64d, hash.ToString().c_str(), nFees, txMinFee); // Continuously rate-limit free transactions // This mitigates 'penny-flooding' -- sending thousands of free transactions just to // be annoying or make others' transactions take longer to confirm. if (fLimitFree && nFees < CTransaction::nMinRelayTxFee) { static double dFreeCount; static int64 nLastTime; int64 nNow = GetTime(); LOCK(cs); // Use an exponentially decaying ~10-minute window: dFreeCount *= pow(1.0 - 1.0/600.0, (double)(nNow - nLastTime)); nLastTime = nNow; // -limitfreerelay unit is thousand-bytes-per-minute // At default rate it would take over a month to fill 1GB if (dFreeCount >= GetArg("-limitfreerelay", 15)*10*1000) return error("CTxMemPool::accept() : free transaction rejected by rate limiter"); if (fDebug) printf("Rate limit dFreeCount: %g => %g\n", dFreeCount, dFreeCount+nSize); dFreeCount += nSize; } // Check against previous transactions // This is done last to help prevent CPU exhaustion denial-of-service attacks. if (!CheckInputs(tx, state, view, true, SCRIPT_VERIFY_P2SH | SCRIPT_VERIFY_STRICTENC)) { return error("CTxMemPool::accept() : ConnectInputs failed %s", hash.ToString().c_str()); } } // Store transaction in memory { LOCK(cs); if (ptxOld) { printf("CTxMemPool::accept() : replacing tx %s with new version\n", ptxOld->GetHash().ToString().c_str()); remove(*ptxOld); } addUnchecked(hash, tx); } ///// are we sure this is ok when loading transactions or restoring block txes // If updated, erase old tx from wallet if (ptxOld) EraseFromWallets(ptxOld->GetHash()); SyncWithWallets(hash, tx, NULL, true); printf("CTxMemPool::accept() : accepted %s (poolsz %"PRIszu")\n", hash.ToString().c_str(), mapTx.size()); return true; } bool CTxMemPool::addUnchecked(const uint256& hash, CTransaction &tx) { // Add to memory pool without checking anything. Don't call this directly, // call CTxMemPool::accept to properly check the transaction first. { mapTx[hash] = tx; for (unsigned int i = 0; i < tx.vin.size(); i++) mapNextTx[tx.vin[i].prevout] = CInPoint(&mapTx[hash], i); nTransactionsUpdated++; } return true; } bool CTxMemPool::remove(const CTransaction &tx, bool fRecursive) { // Remove transaction from memory pool { LOCK(cs); uint256 hash = tx.GetHash(); if (mapTx.count(hash)) { if (fRecursive) { for (unsigned int i = 0; i < tx.vout.size(); i++) { std::map<COutPoint, CInPoint>::iterator it = mapNextTx.find(COutPoint(hash, i)); if (it != mapNextTx.end()) remove(*it->second.ptx, true); } } BOOST_FOREACH(const CTxIn& txin, tx.vin) mapNextTx.erase(txin.prevout); mapTx.erase(hash); nTransactionsUpdated++; } } return true; } bool CTxMemPool::removeConflicts(const CTransaction &tx) { // Remove transactions which depend on inputs of tx, recursively LOCK(cs); BOOST_FOREACH(const CTxIn &txin, tx.vin) { std::map<COutPoint, CInPoint>::iterator it = mapNextTx.find(txin.prevout); if (it != mapNextTx.end()) { const CTransaction &txConflict = *it->second.ptx; if (txConflict != tx) remove(txConflict, true); } } return true; } void CTxMemPool::clear() { LOCK(cs); mapTx.clear(); mapNextTx.clear(); ++nTransactionsUpdated; } void CTxMemPool::queryHashes(std::vector<uint256>& vtxid) { vtxid.clear(); LOCK(cs); vtxid.reserve(mapTx.size()); for (map<uint256, CTransaction>::iterator mi = mapTx.begin(); mi != mapTx.end(); ++mi) vtxid.push_back((*mi).first); } int CMerkleTx::GetDepthInMainChain(CBlockIndex* &pindexRet) const { if (hashBlock == 0 || nIndex == -1) return 0; // Find the block it claims to be in map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashBlock); if (mi == mapBlockIndex.end()) return 0; CBlockIndex* pindex = (*mi).second; if (!pindex || !pindex->IsInMainChain()) return 0; // Make sure the merkle branch connects to this block if (!fMerkleVerified) { if (CBlock::CheckMerkleBranch(GetHash(), vMerkleBranch, nIndex) != pindex->hashMerkleRoot) return 0; fMerkleVerified = true; } pindexRet = pindex; return pindexBest->nHeight - pindex->nHeight + 1; } int CMerkleTx::GetBlocksToMaturity() const { if (!IsCoinBase()) return 0; return max(0, (COINBASE_MATURITY+20) - GetDepthInMainChain()); } bool CMerkleTx::AcceptToMemoryPool(bool fLimitFree) { CValidationState state; return mempool.accept(state, *this, fLimitFree, NULL); } bool CWalletTx::AcceptWalletTransaction() { { LOCK(mempool.cs); // Add previous supporting transactions first BOOST_FOREACH(CMerkleTx& tx, vtxPrev) { if (!tx.IsCoinBase()) { uint256 hash = tx.GetHash(); if (!mempool.exists(hash) && pcoinsTip->HaveCoins(hash)) tx.AcceptToMemoryPool(false); } } return AcceptToMemoryPool(false); } return false; } // Return transaction in tx, and if it was found inside a block, its hash is placed in hashBlock bool GetTransaction(const uint256 &hash, CTransaction &txOut, uint256 &hashBlock, bool fAllowSlow) { CBlockIndex *pindexSlow = NULL; { LOCK(cs_main); { LOCK(mempool.cs); if (mempool.exists(hash)) { txOut = mempool.lookup(hash); return true; } } if (fTxIndex) { CDiskTxPos postx; if (pblocktree->ReadTxIndex(hash, postx)) { CAutoFile file(OpenBlockFile(postx, true), SER_DISK, CLIENT_VERSION); CBlockHeader header; try { file >> header; fseek(file, postx.nTxOffset, SEEK_CUR); file >> txOut; } catch (std::exception &e) { return error("%s() : deserialize or I/O error", __PRETTY_FUNCTION__); } hashBlock = header.GetHash(); if (txOut.GetHash() != hash) return error("%s() : txid mismatch", __PRETTY_FUNCTION__); return true; } } if (fAllowSlow) { // use coin database to locate block that contains transaction, and scan it int nHeight = -1; { CCoinsViewCache &view = *pcoinsTip; CCoins coins; if (view.GetCoins(hash, coins)) nHeight = coins.nHeight; } if (nHeight > 0) pindexSlow = FindBlockByHeight(nHeight); } } if (pindexSlow) { CBlock block; if (ReadBlockFromDisk(block, pindexSlow)) { BOOST_FOREACH(const CTransaction &tx, block.vtx) { if (tx.GetHash() == hash) { txOut = tx; hashBlock = pindexSlow->GetBlockHash(); return true; } } } } return false; } ////////////////////////////////////////////////////////////////////////////// // // CBlock and CBlockIndex // static CBlockIndex* pblockindexFBBHLast; CBlockIndex* FindBlockByHeight(int nHeight) { if (nHeight >= (int)vBlockIndexByHeight.size()) return NULL; return vBlockIndexByHeight[nHeight]; } bool WriteBlockToDisk(CBlock& block, CDiskBlockPos& pos) { // Open history file to append CAutoFile fileout = CAutoFile(OpenBlockFile(pos), SER_DISK, CLIENT_VERSION); if (!fileout) return error("WriteBlockToDisk() : OpenBlockFile failed"); // Write index header unsigned int nSize = fileout.GetSerializeSize(block); fileout << FLATDATA(Params().MessageStart()) << nSize; // Write block long fileOutPos = ftell(fileout); if (fileOutPos < 0) return error("WriteBlockToDisk() : ftell failed"); pos.nPos = (unsigned int)fileOutPos; fileout << block; // Flush stdio buffers and commit to disk before returning fflush(fileout); if (!IsInitialBlockDownload()) FileCommit(fileout); return true; } bool ReadBlockFromDisk(CBlock& block, const CDiskBlockPos& pos) { block.SetNull(); // Open history file to read CAutoFile filein = CAutoFile(OpenBlockFile(pos, true), SER_DISK, CLIENT_VERSION); if (!filein) return error("ReadBlockFromDisk(CBlock&, CDiskBlockPos&) : OpenBlockFile failed"); // Read block try { filein >> block; } catch (std::exception &e) { return error("%s() : deserialize or I/O error", __PRETTY_FUNCTION__); } // Check the header if (!CheckProofOfWork(block.GetHash(), block.nBits)) return error("ReadBlockFromDisk(CBlock&, CDiskBlockPos&) : errors in block header"); return true; } bool ReadBlockFromDisk(CBlock& block, const CBlockIndex* pindex) { if (!ReadBlockFromDisk(block, pindex->GetBlockPos())) return false; if (block.GetHash() != pindex->GetBlockHash()) return error("ReadBlockFromDisk(CBlock&, CBlockIndex*) : GetHash() doesn't match index"); return true; } uint256 static GetOrphanRoot(const CBlockHeader* pblock) { // Work back to the first block in the orphan chain while (mapOrphanBlocks.count(pblock->hashPrevBlock)) pblock = mapOrphanBlocks[pblock->hashPrevBlock]; return pblock->GetHash(); } static const int64 nStartSubsidy = 524288 * COIN; static const int64 nMinSubsidy = 1 * COIN; int64 static GetBlockValue(int nHeight, int64 nFees) { int64 nSubsidy = nStartSubsidy; if(nHeight < 121) {nSubsidy = 1 * COIN;} //minimal rewards for 1 diff change // Mining phase: Subsidy is cut in half every SubsidyHalvingInterval nSubsidy >>= (nHeight / Params().SubsidyHalvingInterval()); // Inflation phase: Subsidy reaches minimum subsidy // Network is rewarded for transaction processing with transaction fees and // the inflationary subsidy if (nSubsidy < nMinSubsidy) { nSubsidy = nMinSubsidy; } return nSubsidy + nFees; } static const int64 nTargetTimespan = 60 * 60; // 1 hour static const int64 nTargetSpacing = 30; // 30 seconds static const int64 nInterval = nTargetTimespan / nTargetSpacing; // 120 blocks static const int64 nAveragingInterval = nInterval * 20; // 40 blocks static const int64 nAveragingTargetTimespan = nAveragingInterval * nTargetSpacing; // 40 minutes static const int64 nMaxAdjustDown = 400; // max of 400% adjustment down static const int64 nMaxAdjustUp = 400; // max of 400% adjustment up static const int64 nTargetTimespanAdjDown = nTargetTimespan * (100 + nMaxAdjustDown) / 100; // // minimum amount of work that could possibly be required nTime after // minimum work required was nBase // unsigned int ComputeMinWork(unsigned int nBase, int64 nTime) { const CBigNum &bnLimit = Params().ProofOfWorkLimit(); // Testnet has min-difficulty blocks // after nTargetSpacing*2 time between blocks: if (TestNet() && nTime > nTargetSpacing*2) return bnLimit.GetCompact(); CBigNum bnResult; bnResult.SetCompact(nBase); while (nTime > 0 && bnResult < bnLimit) { // Maximum adjustment... bnResult *= (100 + nMaxAdjustDown); bnResult /= 100; // ... in best-case exactly adjustment times-normal target time nTime -= nTargetTimespanAdjDown; } if (bnResult > bnLimit) bnResult = bnLimit; return bnResult.GetCompact(); } //////////////////////////////////////////////////////////////////////////////////////////////////// static const int64 nMinActualTimespan = nAveragingTargetTimespan * (100 - nMaxAdjustUp) / 100; static const int64 nMaxActualTimespan = nAveragingTargetTimespan * (100 + nMaxAdjustDown) / 100; // legacy diff-mode unsigned int static GetNextWorkRequired_V1(const CBlockIndex* pindexLast, const CBlockHeader *pblock) { unsigned int nProofOfWorkLimit = Params().ProofOfWorkLimit().GetCompact(); // Genesis block if (pindexLast == NULL) return nProofOfWorkLimit; if (pindexLast->nHeight+1 < nAveragingInterval) return nProofOfWorkLimit; // Only change once per interval if ((pindexLast->nHeight+1) % nInterval != 0) { if (TestNet()) { // Special difficulty rule for testnet: // If the new block's timestamp is more than 2* 10 minutes // then allow mining of a min-difficulty block. if (pblock->nTime > pindexLast->nTime + nTargetSpacing*2) return nProofOfWorkLimit; else { // Return the last non-special-min-difficulty-rules-block const CBlockIndex* pindex = pindexLast; while (pindex->pprev && pindex->nHeight % nInterval != 0 && pindex->nBits == nProofOfWorkLimit) pindex = pindex->pprev; return pindex->nBits; } } return pindexLast->nBits; } // This fixes an issue where a 51% attack can change difficulty at will. // Go back the full period unless it's the first retarget after genesis. Code courtesy of Art Forz int blockstogoback = nInterval-1; if ((pindexLast->nHeight+1) != nInterval) blockstogoback = nInterval; // Go back by what we want to be nAveragingInterval blocks const CBlockIndex* pindexFirst = pindexLast; for (int i = 0; pindexFirst && i < nAveragingInterval-1; i++) pindexFirst = pindexFirst->pprev; assert(pindexFirst); // Limit adjustment step int64 nActualTimespan = pindexLast->GetBlockTime() - pindexFirst->GetBlockTime(); printf(" nActualTimespan = %"PRI64d" before bounds\n", nActualTimespan); if (nActualTimespan < nMinActualTimespan) nActualTimespan = nMinActualTimespan; if (nActualTimespan > nMaxActualTimespan) nActualTimespan = nMaxActualTimespan; // Retarget CBigNum bnNew; bnNew.SetCompact(pindexLast->nBits); bnNew *= nActualTimespan; bnNew /= nAveragingTargetTimespan; if (bnNew > Params().ProofOfWorkLimit()) bnNew = Params().ProofOfWorkLimit(); /// debug print printf("GetNextWorkRequired (legacy)RETARGET\n"); printf("nTargetTimespan = %"PRI64d" nActualTimespan = %"PRI64d"\n", nAveragingTargetTimespan, nActualTimespan); printf("Before: %08x %s\n", pindexLast->nBits, CBigNum().SetCompact(pindexLast->nBits).getuint256().ToString().c_str()); printf("After: %08x %s\n", bnNew.GetCompact(), bnNew.getuint256().ToString().c_str()); return bnNew.GetCompact(); } unsigned int static KimotoGravityWell(const CBlockIndex* pindexLast, const CBlockHeader *pblock, uint64 TargetBlocksSpacingSeconds, uint64 PastBlocksMin, uint64 PastBlocksMax) { /* current difficulty formula - kimoto gravity well */ const CBlockIndex *BlockLastSolved = pindexLast; const CBlockIndex *BlockReading = pindexLast; const CBlockHeader *BlockCreating = pblock; BlockCreating = BlockCreating; uint64 PastBlocksMass = 0; int64 PastRateActualSeconds = 0; int64 PastRateTargetSeconds = 0; double PastRateAdjustmentRatio = double(1); CBigNum PastDifficultyAverage; CBigNum PastDifficultyAveragePrev; double EventHorizonDeviation; double EventHorizonDeviationFast; double EventHorizonDeviationSlow; if (BlockLastSolved == NULL || BlockLastSolved->nHeight == 0 || (uint64)BlockLastSolved->nHeight < PastBlocksMin) { return Params().ProofOfWorkLimit().GetCompact(); } for (unsigned int i = 1; BlockReading && BlockReading->nHeight > 0; i++) { if (PastBlocksMax > 0 && i > PastBlocksMax) { break; } PastBlocksMass++; if (i == 1) { PastDifficultyAverage.SetCompact(BlockReading->nBits); } else { PastDifficultyAverage = ((CBigNum().SetCompact(BlockReading->nBits) - PastDifficultyAveragePrev) / i) + PastDifficultyAveragePrev; } PastDifficultyAveragePrev = PastDifficultyAverage; PastRateActualSeconds = BlockLastSolved->GetBlockTime() - BlockReading->GetBlockTime(); PastRateTargetSeconds = TargetBlocksSpacingSeconds * PastBlocksMass; PastRateAdjustmentRatio = double(1); if (PastRateActualSeconds < 0) { PastRateActualSeconds = 0; } if (PastRateActualSeconds != 0 && PastRateTargetSeconds != 0) { PastRateAdjustmentRatio = double(PastRateTargetSeconds) / double(PastRateActualSeconds); } EventHorizonDeviation = 1 + (0.7084 * pow((double(PastBlocksMass)/double(144)), -1.228)); EventHorizonDeviationFast = EventHorizonDeviation; EventHorizonDeviationSlow = 1 / EventHorizonDeviation; if (PastBlocksMass >= PastBlocksMin) { if ((PastRateAdjustmentRatio <= EventHorizonDeviationSlow) || (PastRateAdjustmentRatio >= EventHorizonDeviationFast)) { assert(BlockReading); break; } } if (BlockReading->pprev == NULL) { assert(BlockReading); break; } BlockReading = BlockReading->pprev; } CBigNum bnNew(PastDifficultyAverage); if (PastRateActualSeconds != 0 && PastRateTargetSeconds != 0) { bnNew *= PastRateActualSeconds; bnNew /= PastRateTargetSeconds; } if (bnNew > Params().ProofOfWorkLimit()) { bnNew = Params().ProofOfWorkLimit(); } /// debug print (commented out due to spamming logs when the loop above breaks) printf("Difficulty Retarget - Kimoto Gravity Well\n"); printf("PastRateAdjustmentRatio = %g\n", PastRateAdjustmentRatio); printf("Before: %08x %s\n", BlockLastSolved->nBits, CBigNum().SetCompact(BlockLastSolved->nBits).getuint256().ToString().c_str()); printf("After: %08x %s\n", bnNew.GetCompact(), bnNew.getuint256().ToString().c_str()); return bnNew.GetCompact(); } // Using KGW unsigned int static GetNextWorkRequired_V2(const CBlockIndex* pindexLast, const CBlockHeader *pblock) { static const int64 BlocksTargetSpacing = 0.5 *60; // 30 sec unsigned int TimeDaySeconds = 60 * 60 * 24; int64 PastSecondsMin = TimeDaySeconds * 0.25; int64 PastSecondsMax = TimeDaySeconds * 7; uint64 PastBlocksMin = PastSecondsMin / BlocksTargetSpacing; uint64 PastBlocksMax = PastSecondsMax / BlocksTargetSpacing; return KimotoGravityWell(pindexLast, pblock, BlocksTargetSpacing, PastBlocksMin, PastBlocksMax); } unsigned int static GetNextWorkRequired(const CBlockIndex* pindexLast, const CBlockHeader *pblock) { //Choose the right diffMode int DiffMode = 1; // legacy diff-mode if (TestNet()) { if (pindexLast->nHeight+1 >= 179) { DiffMode = 2; } //legacy } else { if (pindexLast->nHeight+1 >= 36000) { DiffMode = 2; } //kimoto } if (DiffMode == 1) { return GetNextWorkRequired_V1(pindexLast, pblock); } //legacy diff mode else if (DiffMode == 2) { return GetNextWorkRequired_V2(pindexLast, pblock); } // KGW return GetNextWorkRequired_V2(pindexLast, pblock); // KGW } //////////////////////////////////////////////////////////////////////////////////////////////////// bool CheckProofOfWork(uint256 hash, unsigned int nBits) { CBigNum bnTarget; bnTarget.SetCompact(nBits); // Check range if (bnTarget <= 0 || bnTarget > Params().ProofOfWorkLimit()) return error("CheckProofOfWork() : nBits below minimum work"); // Check proof of work matches claimed amount if (hash > bnTarget.getuint256()) return error("CheckProofOfWork() : hash doesn't match nBits"); return true; } // Return maximum amount of blocks that other nodes claim to have int GetNumBlocksOfPeers() { return std::max(cPeerBlockCounts.median(), Checkpoints::GetTotalBlocksEstimate()); } bool IsInitialBlockDownload() { if (pindexBest == NULL || fImporting || fReindex || nBestHeight < Checkpoints::GetTotalBlocksEstimate()) return true; static int64 nLastUpdate; static CBlockIndex* pindexLastBest; if (pindexBest != pindexLastBest) { pindexLastBest = pindexBest; nLastUpdate = GetTime(); } return (GetTime() - nLastUpdate < 10 && pindexBest->GetBlockTime() < GetTime() - 24 * 60 * 60); } void static InvalidChainFound(CBlockIndex* pindexNew) { if (pindexNew->nChainWork > nBestInvalidWork) { nBestInvalidWork = pindexNew->nChainWork; pblocktree->WriteBestInvalidWork(CBigNum(nBestInvalidWork)); uiInterface.NotifyBlocksChanged(); } printf("InvalidChainFound: invalid block=%s height=%d log2_work=%.8g date=%s\n", pindexNew->GetBlockHash().ToString().c_str(), pindexNew->nHeight, log(pindexNew->nChainWork.getdouble())/log(2.0), DateTimeStrFormat("%Y-%m-%d %H:%M:%S", pindexNew->GetBlockTime()).c_str()); printf("InvalidChainFound: current best=%s height=%d log2_work=%.8g date=%s\n", hashBestChain.ToString().c_str(), nBestHeight, log(nBestChainWork.getdouble())/log(2.0), DateTimeStrFormat("%Y-%m-%d %H:%M:%S", pindexBest->GetBlockTime()).c_str()); if (pindexBest && nBestInvalidWork > nBestChainWork + (pindexBest->GetBlockWork() * 6).getuint256()) printf("InvalidChainFound: Warning: Displayed transactions may not be correct! You may need to upgrade, or other nodes may need to upgrade.\n"); } void static InvalidBlockFound(CBlockIndex *pindex) { pindex->nStatus |= BLOCK_FAILED_VALID; pblocktree->WriteBlockIndex(CDiskBlockIndex(pindex)); setBlockIndexValid.erase(pindex); InvalidChainFound(pindex); if (pindex->GetNextInMainChain()) { CValidationState stateDummy; ConnectBestBlock(stateDummy); // reorganise away from the failed block } } bool ConnectBestBlock(CValidationState &state) { do { CBlockIndex *pindexNewBest; { std::set<CBlockIndex*,CBlockIndexWorkComparator>::reverse_iterator it = setBlockIndexValid.rbegin(); if (it == setBlockIndexValid.rend()) return true; pindexNewBest = *it; } if (pindexNewBest == pindexBest || (pindexBest && pindexNewBest->nChainWork == pindexBest->nChainWork)) return true; // nothing to do // check ancestry CBlockIndex *pindexTest = pindexNewBest; std::vector<CBlockIndex*> vAttach; do { if (pindexTest->nStatus & BLOCK_FAILED_MASK) { // mark descendants failed CBlockIndex *pindexFailed = pindexNewBest; while (pindexTest != pindexFailed) { pindexFailed->nStatus |= BLOCK_FAILED_CHILD; setBlockIndexValid.erase(pindexFailed); pblocktree->WriteBlockIndex(CDiskBlockIndex(pindexFailed)); pindexFailed = pindexFailed->pprev; } InvalidChainFound(pindexNewBest); break; } if (pindexBest == NULL || pindexTest->nChainWork > pindexBest->nChainWork) vAttach.push_back(pindexTest); if (pindexTest->pprev == NULL || pindexTest->GetNextInMainChain()) { reverse(vAttach.begin(), vAttach.end()); BOOST_FOREACH(CBlockIndex *pindexSwitch, vAttach) { boost::this_thread::interruption_point(); try { if (!SetBestChain(state, pindexSwitch)) return false; } catch(std::runtime_error &e) { return state.Abort(_("System error: ") + e.what()); } } return true; } pindexTest = pindexTest->pprev; } while(true); } while(true); } void UpdateTime(CBlockHeader& block, const CBlockIndex* pindexPrev) { block.nTime = max(pindexPrev->GetMedianTimePast()+1, GetAdjustedTime()); // Updating time can change work required on testnet: if (TestNet()) block.nBits = GetNextWorkRequired(pindexPrev, &block); } const CTxOut &CCoinsViewCache::GetOutputFor(const CTxIn& input) { const CCoins &coins = GetCoins(input.prevout.hash); assert(coins.IsAvailable(input.prevout.n)); return coins.vout[input.prevout.n]; } int64 CCoinsViewCache::GetValueIn(const CTransaction& tx) { if (tx.IsCoinBase()) return 0; int64 nResult = 0; for (unsigned int i = 0; i < tx.vin.size(); i++) nResult += GetOutputFor(tx.vin[i]).nValue; return nResult; } void UpdateCoins(const CTransaction& tx, CValidationState &state, CCoinsViewCache &inputs, CTxUndo &txundo, int nHeight, const uint256 &txhash) { // mark inputs spent if (!tx.IsCoinBase()) { BOOST_FOREACH(const CTxIn &txin, tx.vin) { CCoins &coins = inputs.GetCoins(txin.prevout.hash); CTxInUndo undo; assert(coins.Spend(txin.prevout, undo)); txundo.vprevout.push_back(undo); } } // add outputs assert(inputs.SetCoins(txhash, CCoins(tx, nHeight))); } bool CCoinsViewCache::HaveInputs(const CTransaction& tx) { if (!tx.IsCoinBase()) { // first check whether information about the prevout hash is available for (unsigned int i = 0; i < tx.vin.size(); i++) { const COutPoint &prevout = tx.vin[i].prevout; if (!HaveCoins(prevout.hash)) return false; } // then check whether the actual outputs are available for (unsigned int i = 0; i < tx.vin.size(); i++) { const COutPoint &prevout = tx.vin[i].prevout; const CCoins &coins = GetCoins(prevout.hash); if (!coins.IsAvailable(prevout.n)) return false; } } return true; } bool CScriptCheck::operator()() const { const CScript &scriptSig = ptxTo->vin[nIn].scriptSig; if (!VerifyScript(scriptSig, scriptPubKey, *ptxTo, nIn, nFlags, nHashType)) return error("CScriptCheck() : %s VerifySignature failed", ptxTo->GetHash().ToString().c_str()); return true; } bool VerifySignature(const CCoins& txFrom, const CTransaction& txTo, unsigned int nIn, unsigned int flags, int nHashType) { return CScriptCheck(txFrom, txTo, nIn, flags, nHashType)(); } bool CheckInputs(const CTransaction& tx, CValidationState &state, CCoinsViewCache &inputs, bool fScriptChecks, unsigned int flags, std::vector<CScriptCheck> *pvChecks) { if (!tx.IsCoinBase()) { if (pvChecks) pvChecks->reserve(tx.vin.size()); // This doesn't trigger the DoS code on purpose; if it did, it would make it easier // for an attacker to attempt to split the network. if (!inputs.HaveInputs(tx)) return state.Invalid(error("CheckInputs() : %s inputs unavailable", tx.GetHash().ToString().c_str())); // While checking, GetBestBlock() refers to the parent block. // This is also true for mempool checks. int nSpendHeight = inputs.GetBestBlock()->nHeight + 1; int64 nValueIn = 0; int64 nFees = 0; for (unsigned int i = 0; i < tx.vin.size(); i++) { const COutPoint &prevout = tx.vin[i].prevout; const CCoins &coins = inputs.GetCoins(prevout.hash); // If prev is coinbase, check that it's matured if (coins.IsCoinBase()) { if (nSpendHeight - coins.nHeight < COINBASE_MATURITY) return state.Invalid(error("CheckInputs() : tried to spend coinbase at depth %d", nSpendHeight - coins.nHeight)); } // Check for negative or overflow input values nValueIn += coins.vout[prevout.n].nValue; if (!MoneyRange(coins.vout[prevout.n].nValue) || !MoneyRange(nValueIn)) return state.DoS(100, error("CheckInputs() : txin values out of range")); } if (nValueIn < GetValueOut(tx)) return state.DoS(100, error("CheckInputs() : %s value in < value out", tx.GetHash().ToString().c_str())); // Tally transaction fees int64 nTxFee = nValueIn - GetValueOut(tx); if (nTxFee < 0) return state.DoS(100, error("CheckInputs() : %s nTxFee < 0", tx.GetHash().ToString().c_str())); nFees += nTxFee; if (!MoneyRange(nFees)) return state.DoS(100, error("CheckInputs() : nFees out of range")); // The first loop above does all the inexpensive checks. // Only if ALL inputs pass do we perform expensive ECDSA signature checks. // Helps prevent CPU exhaustion attacks. // Skip ECDSA signature verification when connecting blocks // before the last block chain checkpoint. This is safe because block merkle hashes are // still computed and checked, and any change will be caught at the next checkpoint. if (fScriptChecks) { for (unsigned int i = 0; i < tx.vin.size(); i++) { const COutPoint &prevout = tx.vin[i].prevout; const CCoins &coins = inputs.GetCoins(prevout.hash); // Verify signature CScriptCheck check(coins, tx, i, flags, 0); if (pvChecks) { pvChecks->push_back(CScriptCheck()); check.swap(pvChecks->back()); } else if (!check()) { if (flags & SCRIPT_VERIFY_STRICTENC) { // For now, check whether the failure was caused by non-canonical // encodings or not; if so, don't trigger DoS protection. CScriptCheck check(coins, tx, i, flags & (~SCRIPT_VERIFY_STRICTENC), 0); if (check()) return state.Invalid(); } return state.DoS(100,false); } } } } return true; } bool DisconnectBlock(CBlock& block, CValidationState& state, CBlockIndex* pindex, CCoinsViewCache& view, bool* pfClean) { assert(pindex == view.GetBestBlock()); if (pfClean) *pfClean = false; bool fClean = true; CBlockUndo blockUndo; CDiskBlockPos pos = pindex->GetUndoPos(); if (pos.IsNull()) return error("DisconnectBlock() : no undo data available"); if (!blockUndo.ReadFromDisk(pos, pindex->pprev->GetBlockHash())) return error("DisconnectBlock() : failure reading undo data"); if (blockUndo.vtxundo.size() + 1 != block.vtx.size()) return error("DisconnectBlock() : block and undo data inconsistent"); // undo transactions in reverse order for (int i = block.vtx.size() - 1; i >= 0; i--) { const CTransaction &tx = block.vtx[i]; uint256 hash = tx.GetHash(); // check that all outputs are available if (!view.HaveCoins(hash)) { fClean = fClean && error("DisconnectBlock() : outputs still spent? database corrupted"); view.SetCoins(hash, CCoins()); } CCoins &outs = view.GetCoins(hash); CCoins outsBlock = CCoins(tx, pindex->nHeight); if (outs != outsBlock) fClean = fClean && error("DisconnectBlock() : added transaction mismatch? database corrupted"); // remove outputs outs = CCoins(); // restore inputs if (i > 0) { // not coinbases const CTxUndo &txundo = blockUndo.vtxundo[i-1]; if (txundo.vprevout.size() != tx.vin.size()) return error("DisconnectBlock() : transaction and undo data inconsistent"); for (unsigned int j = tx.vin.size(); j-- > 0;) { const COutPoint &out = tx.vin[j].prevout; const CTxInUndo &undo = txundo.vprevout[j]; CCoins coins; view.GetCoins(out.hash, coins); // this can fail if the prevout was already entirely spent if (undo.nHeight != 0) { // undo data contains height: this is the last output of the prevout tx being spent if (!coins.IsPruned()) fClean = fClean && error("DisconnectBlock() : undo data overwriting existing transaction"); coins = CCoins(); coins.fCoinBase = undo.fCoinBase; coins.nHeight = undo.nHeight; coins.nVersion = undo.nVersion; } else { if (coins.IsPruned()) fClean = fClean && error("DisconnectBlock() : undo data adding output to missing transaction"); } if (coins.IsAvailable(out.n)) fClean = fClean && error("DisconnectBlock() : undo data overwriting existing output"); if (coins.vout.size() < out.n+1) coins.vout.resize(out.n+1); coins.vout[out.n] = undo.txout; if (!view.SetCoins(out.hash, coins)) return error("DisconnectBlock() : cannot restore coin inputs"); } } } // move best block pointer to prevout block view.SetBestBlock(pindex->pprev); if (pfClean) { *pfClean = fClean; return true; } else { return fClean; } } void static FlushBlockFile(bool fFinalize = false) { LOCK(cs_LastBlockFile); CDiskBlockPos posOld(nLastBlockFile, 0); FILE *fileOld = OpenBlockFile(posOld); if (fileOld) { if (fFinalize) TruncateFile(fileOld, infoLastBlockFile.nSize); FileCommit(fileOld); fclose(fileOld); } fileOld = OpenUndoFile(posOld); if (fileOld) { if (fFinalize) TruncateFile(fileOld, infoLastBlockFile.nUndoSize); FileCommit(fileOld); fclose(fileOld); } } bool FindUndoPos(CValidationState &state, int nFile, CDiskBlockPos &pos, unsigned int nAddSize); static CCheckQueue<CScriptCheck> scriptcheckqueue(128); void ThreadScriptCheck() { RenameThread("bitcoin-scriptch"); scriptcheckqueue.Thread(); } bool ConnectBlock(CBlock& block, CValidationState& state, CBlockIndex* pindex, CCoinsViewCache& view, bool fJustCheck) { // Check it again in case a previous version let a bad block in if (!CheckBlock(block, state, !fJustCheck, !fJustCheck)) return false; // verify that the view's current state corresponds to the previous block assert(pindex->pprev == view.GetBestBlock()); // Special case for the genesis block, skipping connection of its transactions // (its coinbase is unspendable) if (block.GetHash() == Params().HashGenesisBlock()) { view.SetBestBlock(pindex); pindexGenesisBlock = pindex; return true; } bool fScriptChecks = pindex->nHeight >= Checkpoints::GetTotalBlocksEstimate(); // Do not allow blocks that contain transactions which 'overwrite' older transactions, // unless those are already completely spent. // If such overwrites are allowed, coinbases and transactions depending upon those // can be duplicated to remove the ability to spend the first instance -- even after // being sent to another address. // See BIP30 and http://r6.ca/blog/20120206T005236Z.html for more information. // This logic is not necessary for memory pool transactions, as AcceptToMemoryPool // already refuses previously-known transaction ids entirely. // This rule was originally applied all blocks whose timestamp was after March 15, 2012, 0:00 UTC. // Now that the whole chain is irreversibly beyond that time it is applied to all blocks except the // two in the chain that violate it. This prevents exploiting the issue against nodes in their // initial block download. for (unsigned int i = 0; i < block.vtx.size(); i++) { uint256 hash = block.GetTxHash(i); if (view.HaveCoins(hash) && !view.GetCoins(hash).IsPruned()) return state.DoS(100, error("ConnectBlock() : tried to overwrite transaction")); } // BIP16 didn't become active until Apr 1 2012 int64 nBIP16SwitchTime = 1333238400; bool fStrictPayToScriptHash = (pindex->nTime >= nBIP16SwitchTime); unsigned int flags = SCRIPT_VERIFY_NOCACHE | (fStrictPayToScriptHash ? SCRIPT_VERIFY_P2SH : SCRIPT_VERIFY_NONE); CBlockUndo blockundo; CCheckQueueControl<CScriptCheck> control(fScriptChecks && nScriptCheckThreads ? &scriptcheckqueue : NULL); int64 nStart = GetTimeMicros(); int64 nFees = 0; int nInputs = 0; unsigned int nSigOps = 0; CDiskTxPos pos(pindex->GetBlockPos(), GetSizeOfCompactSize(block.vtx.size())); std::vector<std::pair<uint256, CDiskTxPos> > vPos; vPos.reserve(block.vtx.size()); for (unsigned int i = 0; i < block.vtx.size(); i++) { const CTransaction &tx = block.vtx[i]; nInputs += tx.vin.size(); nSigOps += GetLegacySigOpCount(tx); if (nSigOps > MAX_BLOCK_SIGOPS) return state.DoS(100, error("ConnectBlock() : too many sigops")); if (!tx.IsCoinBase()) { if (!view.HaveInputs(tx)) return state.DoS(100, error("ConnectBlock() : inputs missing/spent")); if (fStrictPayToScriptHash) { // Add in sigops done by pay-to-script-hash inputs; // this is to prevent a "rogue miner" from creating // an incredibly-expensive-to-validate block. nSigOps += GetP2SHSigOpCount(tx, view); if (nSigOps > MAX_BLOCK_SIGOPS) return state.DoS(100, error("ConnectBlock() : too many sigops")); } nFees += view.GetValueIn(tx)-GetValueOut(tx); std::vector<CScriptCheck> vChecks; if (!CheckInputs(tx, state, view, fScriptChecks, flags, nScriptCheckThreads ? &vChecks : NULL)) return false; control.Add(vChecks); } CTxUndo txundo; UpdateCoins(tx, state, view, txundo, pindex->nHeight, block.GetTxHash(i)); if (!tx.IsCoinBase()) blockundo.vtxundo.push_back(txundo); vPos.push_back(std::make_pair(block.GetTxHash(i), pos)); pos.nTxOffset += ::GetSerializeSize(tx, SER_DISK, CLIENT_VERSION); } int64 nTime = GetTimeMicros() - nStart; if (fBenchmark) printf("- Connect %u transactions: %.2fms (%.3fms/tx, %.3fms/txin)\n", (unsigned)block.vtx.size(), 0.001 * nTime, 0.001 * nTime / block.vtx.size(), nInputs <= 1 ? 0 : 0.001 * nTime / (nInputs-1)); if (GetValueOut(block.vtx[0]) > GetBlockValue(pindex->nHeight, nFees)) return state.DoS(100, error("ConnectBlock() : coinbase pays too much (actual=%"PRI64d" vs limit=%"PRI64d")", GetValueOut(block.vtx[0]), GetBlockValue(pindex->nHeight, nFees))); if (!control.Wait()) return state.DoS(100, false); int64 nTime2 = GetTimeMicros() - nStart; if (fBenchmark) printf("- Verify %u txins: %.2fms (%.3fms/txin)\n", nInputs - 1, 0.001 * nTime2, nInputs <= 1 ? 0 : 0.001 * nTime2 / (nInputs-1)); if (fJustCheck) return true; // Write undo information to disk if (pindex->GetUndoPos().IsNull() || (pindex->nStatus & BLOCK_VALID_MASK) < BLOCK_VALID_SCRIPTS) { if (pindex->GetUndoPos().IsNull()) { CDiskBlockPos pos; if (!FindUndoPos(state, pindex->nFile, pos, ::GetSerializeSize(blockundo, SER_DISK, CLIENT_VERSION) + 40)) return error("ConnectBlock() : FindUndoPos failed"); if (!blockundo.WriteToDisk(pos, pindex->pprev->GetBlockHash())) return state.Abort(_("Failed to write undo data")); // update nUndoPos in block index pindex->nUndoPos = pos.nPos; pindex->nStatus |= BLOCK_HAVE_UNDO; } pindex->nStatus = (pindex->nStatus & ~BLOCK_VALID_MASK) | BLOCK_VALID_SCRIPTS; CDiskBlockIndex blockindex(pindex); if (!pblocktree->WriteBlockIndex(blockindex)) return state.Abort(_("Failed to write block index")); } if (fTxIndex) if (!pblocktree->WriteTxIndex(vPos)) return state.Abort(_("Failed to write transaction index")); // add this block to the view's block chain assert(view.SetBestBlock(pindex)); // Watch for transactions paying to me for (unsigned int i = 0; i < block.vtx.size(); i++) SyncWithWallets(block.GetTxHash(i), block.vtx[i], &block, true); return true; } bool SetBestChain(CValidationState &state, CBlockIndex* pindexNew) { // All modifications to the coin state will be done in this cache. // Only when all have succeeded, we push it to pcoinsTip. CCoinsViewCache view(*pcoinsTip, true); // Find the fork (typically, there is none) CBlockIndex* pfork = view.GetBestBlock(); CBlockIndex* plonger = pindexNew; while (pfork && pfork != plonger) { while (plonger->nHeight > pfork->nHeight) { plonger = plonger->pprev; assert(plonger != NULL); } if (pfork == plonger) break; pfork = pfork->pprev; assert(pfork != NULL); } // List of what to disconnect (typically nothing) vector<CBlockIndex*> vDisconnect; for (CBlockIndex* pindex = view.GetBestBlock(); pindex != pfork; pindex = pindex->pprev) vDisconnect.push_back(pindex); // List of what to connect (typically only pindexNew) vector<CBlockIndex*> vConnect; for (CBlockIndex* pindex = pindexNew; pindex != pfork; pindex = pindex->pprev) vConnect.push_back(pindex); reverse(vConnect.begin(), vConnect.end()); if (vDisconnect.size() > 0) { printf("REORGANIZE: Disconnect %"PRIszu" blocks; %s..\n", vDisconnect.size(), pfork->GetBlockHash().ToString().c_str()); printf("REORGANIZE: Connect %"PRIszu" blocks; ..%s\n", vConnect.size(), pindexNew->GetBlockHash().ToString().c_str()); } // Disconnect shorter branch vector<CTransaction> vResurrect; BOOST_FOREACH(CBlockIndex* pindex, vDisconnect) { CBlock block; if (!ReadBlockFromDisk(block, pindex)) return state.Abort(_("Failed to read block")); int64 nStart = GetTimeMicros(); if (!DisconnectBlock(block, state, pindex, view)) return error("SetBestBlock() : DisconnectBlock %s failed", pindex->GetBlockHash().ToString().c_str()); if (fBenchmark) printf("- Disconnect: %.2fms\n", (GetTimeMicros() - nStart) * 0.001); // Queue memory transactions to resurrect. // We only do this for blocks after the last checkpoint (reorganisation before that // point should only happen with -reindex/-loadblock, or a misbehaving peer. BOOST_FOREACH(const CTransaction& tx, block.vtx) if (!tx.IsCoinBase() && pindex->nHeight > Checkpoints::GetTotalBlocksEstimate()) vResurrect.push_back(tx); } // Connect longer branch vector<CTransaction> vDelete; BOOST_FOREACH(CBlockIndex *pindex, vConnect) { CBlock block; if (!ReadBlockFromDisk(block, pindex)) return state.Abort(_("Failed to read block")); int64 nStart = GetTimeMicros(); if (!ConnectBlock(block, state, pindex, view)) { if (state.IsInvalid()) { InvalidChainFound(pindexNew); InvalidBlockFound(pindex); } return error("SetBestBlock() : ConnectBlock %s failed", pindex->GetBlockHash().ToString().c_str()); } if (fBenchmark) printf("- Connect: %.2fms\n", (GetTimeMicros() - nStart) * 0.001); // Queue memory transactions to delete BOOST_FOREACH(const CTransaction& tx, block.vtx) vDelete.push_back(tx); } // Flush changes to global coin state int64 nStart = GetTimeMicros(); int nModified = view.GetCacheSize(); assert(view.Flush()); int64 nTime = GetTimeMicros() - nStart; if (fBenchmark) printf("- Flush %i transactions: %.2fms (%.4fms/tx)\n", nModified, 0.001 * nTime, 0.001 * nTime / nModified); // Make sure it's successfully written to disk before changing memory structure bool fIsInitialDownload = IsInitialBlockDownload(); if (!fIsInitialDownload || pcoinsTip->GetCacheSize() > nCoinCacheSize) { // Typical CCoins structures on disk are around 100 bytes in size. // Pushing a new one to the database can cause it to be written // twice (once in the log, and once in the tables). This is already // an overestimation, as most will delete an existing entry or // overwrite one. Still, use a conservative safety factor of 2. if (!CheckDiskSpace(100 * 2 * 2 * pcoinsTip->GetCacheSize())) return state.Error(); FlushBlockFile(); pblocktree->Sync(); if (!pcoinsTip->Flush()) return state.Abort(_("Failed to write to coin database")); } // At this point, all changes have been done to the database. // Proceed by updating the memory structures. // Register new best chain vBlockIndexByHeight.resize(pindexNew->nHeight + 1); BOOST_FOREACH(CBlockIndex* pindex, vConnect) vBlockIndexByHeight[pindex->nHeight] = pindex; // Resurrect memory transactions that were in the disconnected branch BOOST_FOREACH(CTransaction& tx, vResurrect) { // ignore validation errors in resurrected transactions CValidationState stateDummy; mempool.accept(stateDummy, tx, false, NULL); } // Delete redundant memory transactions that are in the connected branch BOOST_FOREACH(CTransaction& tx, vDelete) { mempool.remove(tx); mempool.removeConflicts(tx); } // Update best block in wallet (so we can detect restored wallets) if ((pindexNew->nHeight % 20160) == 0 || (!fIsInitialDownload && (pindexNew->nHeight % 144) == 0)) { const CBlockLocator locator(pindexNew); ::SetBestChain(locator); } // New best block hashBestChain = pindexNew->GetBlockHash(); pindexBest = pindexNew; pblockindexFBBHLast = NULL; nBestHeight = pindexBest->nHeight; nBestChainWork = pindexNew->nChainWork; nTimeBestReceived = GetTime(); nTransactionsUpdated++; printf("SetBestChain: new best=%s height=%d log2_work=%.8g tx=%lu date=%s progress=%f\n", hashBestChain.ToString().c_str(), nBestHeight, log(nBestChainWork.getdouble())/log(2.0), (unsigned long)pindexNew->nChainTx, DateTimeStrFormat("%Y-%m-%d %H:%M:%S", pindexBest->GetBlockTime()).c_str(), Checkpoints::GuessVerificationProgress(pindexBest)); // Check the version of the last 100 blocks to see if we need to upgrade: if (!fIsInitialDownload) { int nUpgraded = 0; const CBlockIndex* pindex = pindexBest; for (int i = 0; i < 100 && pindex != NULL; i++) { if (pindex->nVersion > CBlock::CURRENT_VERSION) ++nUpgraded; pindex = pindex->pprev; } if (nUpgraded > 0) printf("SetBestChain: %d of last 100 blocks above version %d\n", nUpgraded, CBlock::CURRENT_VERSION); if (nUpgraded > 100/2) // strMiscWarning is read by GetWarnings(), called by Qt and the JSON-RPC code to warn the user: strMiscWarning = _("Warning: This version is obsolete, upgrade required!"); } std::string strCmd = GetArg("-blocknotify", ""); if (!fIsInitialDownload && !strCmd.empty()) { boost::replace_all(strCmd, "%s", hashBestChain.GetHex()); boost::thread t(runCommand, strCmd); // thread runs free } return true; } bool AddToBlockIndex(CBlock& block, CValidationState& state, const CDiskBlockPos& pos) { // Check for duplicate uint256 hash = block.GetHash(); if (mapBlockIndex.count(hash)) return state.Invalid(error("AddToBlockIndex() : %s already exists", hash.ToString().c_str())); // Construct new block index object CBlockIndex* pindexNew = new CBlockIndex(block); assert(pindexNew); map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.insert(make_pair(hash, pindexNew)).first; pindexNew->phashBlock = &((*mi).first); map<uint256, CBlockIndex*>::iterator miPrev = mapBlockIndex.find(block.hashPrevBlock); if (miPrev != mapBlockIndex.end()) { pindexNew->pprev = (*miPrev).second; pindexNew->nHeight = pindexNew->pprev->nHeight + 1; } pindexNew->nTx = block.vtx.size(); pindexNew->nChainWork = (pindexNew->pprev ? pindexNew->pprev->nChainWork : 0) + pindexNew->GetBlockWork().getuint256(); pindexNew->nChainTx = (pindexNew->pprev ? pindexNew->pprev->nChainTx : 0) + pindexNew->nTx; pindexNew->nFile = pos.nFile; pindexNew->nDataPos = pos.nPos; pindexNew->nUndoPos = 0; pindexNew->nStatus = BLOCK_VALID_TRANSACTIONS | BLOCK_HAVE_DATA; setBlockIndexValid.insert(pindexNew); if (!pblocktree->WriteBlockIndex(CDiskBlockIndex(pindexNew))) return state.Abort(_("Failed to write block index")); // New best? if (!ConnectBestBlock(state)) return false; if (pindexNew == pindexBest) { // Notify UI to display prev block's coinbase if it was ours static uint256 hashPrevBestCoinBase; UpdatedTransaction(hashPrevBestCoinBase); hashPrevBestCoinBase = block.GetTxHash(0); } if (!pblocktree->Flush()) return state.Abort(_("Failed to sync block index")); uiInterface.NotifyBlocksChanged(); return true; } bool FindBlockPos(CValidationState &state, CDiskBlockPos &pos, unsigned int nAddSize, unsigned int nHeight, uint64 nTime, bool fKnown = false) { bool fUpdatedLast = false; LOCK(cs_LastBlockFile); if (fKnown) { if (nLastBlockFile != pos.nFile) { nLastBlockFile = pos.nFile; infoLastBlockFile.SetNull(); pblocktree->ReadBlockFileInfo(nLastBlockFile, infoLastBlockFile); fUpdatedLast = true; } } else { while (infoLastBlockFile.nSize + nAddSize >= MAX_BLOCKFILE_SIZE) { printf("Leaving block file %i: %s\n", nLastBlockFile, infoLastBlockFile.ToString().c_str()); FlushBlockFile(true); nLastBlockFile++; infoLastBlockFile.SetNull(); pblocktree->ReadBlockFileInfo(nLastBlockFile, infoLastBlockFile); // check whether data for the new file somehow already exist; can fail just fine fUpdatedLast = true; } pos.nFile = nLastBlockFile; pos.nPos = infoLastBlockFile.nSize; } infoLastBlockFile.nSize += nAddSize; infoLastBlockFile.AddBlock(nHeight, nTime); if (!fKnown) { unsigned int nOldChunks = (pos.nPos + BLOCKFILE_CHUNK_SIZE - 1) / BLOCKFILE_CHUNK_SIZE; unsigned int nNewChunks = (infoLastBlockFile.nSize + BLOCKFILE_CHUNK_SIZE - 1) / BLOCKFILE_CHUNK_SIZE; if (nNewChunks > nOldChunks) { if (CheckDiskSpace(nNewChunks * BLOCKFILE_CHUNK_SIZE - pos.nPos)) { FILE *file = OpenBlockFile(pos); if (file) { printf("Pre-allocating up to position 0x%x in blk%05u.dat\n", nNewChunks * BLOCKFILE_CHUNK_SIZE, pos.nFile); AllocateFileRange(file, pos.nPos, nNewChunks * BLOCKFILE_CHUNK_SIZE - pos.nPos); fclose(file); } } else return state.Error(); } } if (!pblocktree->WriteBlockFileInfo(nLastBlockFile, infoLastBlockFile)) return state.Abort(_("Failed to write file info")); if (fUpdatedLast) pblocktree->WriteLastBlockFile(nLastBlockFile); return true; } bool FindUndoPos(CValidationState &state, int nFile, CDiskBlockPos &pos, unsigned int nAddSize) { pos.nFile = nFile; LOCK(cs_LastBlockFile); unsigned int nNewSize; if (nFile == nLastBlockFile) { pos.nPos = infoLastBlockFile.nUndoSize; nNewSize = (infoLastBlockFile.nUndoSize += nAddSize); if (!pblocktree->WriteBlockFileInfo(nLastBlockFile, infoLastBlockFile)) return state.Abort(_("Failed to write block info")); } else { CBlockFileInfo info; if (!pblocktree->ReadBlockFileInfo(nFile, info)) return state.Abort(_("Failed to read block info")); pos.nPos = info.nUndoSize; nNewSize = (info.nUndoSize += nAddSize); if (!pblocktree->WriteBlockFileInfo(nFile, info)) return state.Abort(_("Failed to write block info")); } unsigned int nOldChunks = (pos.nPos + UNDOFILE_CHUNK_SIZE - 1) / UNDOFILE_CHUNK_SIZE; unsigned int nNewChunks = (nNewSize + UNDOFILE_CHUNK_SIZE - 1) / UNDOFILE_CHUNK_SIZE; if (nNewChunks > nOldChunks) { if (CheckDiskSpace(nNewChunks * UNDOFILE_CHUNK_SIZE - pos.nPos)) { FILE *file = OpenUndoFile(pos); if (file) { printf("Pre-allocating up to position 0x%x in rev%05u.dat\n", nNewChunks * UNDOFILE_CHUNK_SIZE, pos.nFile); AllocateFileRange(file, pos.nPos, nNewChunks * UNDOFILE_CHUNK_SIZE - pos.nPos); fclose(file); } } else return state.Error(); } return true; } bool CheckBlock(const CBlock& block, CValidationState& state, bool fCheckPOW, bool fCheckMerkleRoot) { // These are checks that are independent of context // that can be verified before saving an orphan block. // Size limits if (block.vtx.empty() || block.vtx.size() > MAX_BLOCK_SIZE || ::GetSerializeSize(block, SER_NETWORK, PROTOCOL_VERSION) > MAX_BLOCK_SIZE) return state.DoS(100, error("CheckBlock() : size limits failed")); // Check proof of work matches claimed amount if (fCheckPOW && !CheckProofOfWork(block.GetHash(), block.nBits)) return state.DoS(50, error("CheckBlock() : proof of work failed")); // Check timestamp if (block.GetBlockTime() > GetAdjustedTime() + 2 * 60 * 60) return state.Invalid(error("CheckBlock() : block timestamp too far in the future")); // First transaction must be coinbase, the rest must not be if (block.vtx.empty() || !block.vtx[0].IsCoinBase()) return state.DoS(100, error("CheckBlock() : first tx is not coinbase")); for (unsigned int i = 1; i < block.vtx.size(); i++) if (block.vtx[i].IsCoinBase()) return state.DoS(100, error("CheckBlock() : more than one coinbase")); // Check transactions BOOST_FOREACH(const CTransaction& tx, block.vtx) if (!CheckTransaction(tx, state)) return error("CheckBlock() : CheckTransaction failed"); // Build the merkle tree already. We need it anyway later, and it makes the // block cache the transaction hashes, which means they don't need to be // recalculated many times during this block's validation. block.BuildMerkleTree(); // Check for duplicate txids. This is caught by ConnectInputs(), // but catching it earlier avoids a potential DoS attack: set<uint256> uniqueTx; for (unsigned int i = 0; i < block.vtx.size(); i++) { uniqueTx.insert(block.GetTxHash(i)); } if (uniqueTx.size() != block.vtx.size()) return state.DoS(100, error("CheckBlock() : duplicate transaction")); unsigned int nSigOps = 0; BOOST_FOREACH(const CTransaction& tx, block.vtx) { nSigOps += GetLegacySigOpCount(tx); } if (nSigOps > MAX_BLOCK_SIGOPS) return state.DoS(100, error("CheckBlock() : out-of-bounds SigOpCount")); // Check merkle root if (fCheckMerkleRoot && block.hashMerkleRoot != block.BuildMerkleTree()) return state.DoS(100, error("CheckBlock() : hashMerkleRoot mismatch")); return true; } bool AcceptBlock(CBlock& block, CValidationState& state, CDiskBlockPos* dbp) { // Check for duplicate uint256 hash = block.GetHash(); if (mapBlockIndex.count(hash)) return state.Invalid(error("AcceptBlock() : block already in mapBlockIndex")); // Get prev block index CBlockIndex* pindexPrev = NULL; int nHeight = 0; if (hash != Params().HashGenesisBlock()) { map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(block.hashPrevBlock); if (mi == mapBlockIndex.end()) return state.DoS(10, error("AcceptBlock() : prev block not found")); pindexPrev = (*mi).second; nHeight = pindexPrev->nHeight+1; // Check proof of work if (block.nBits != GetNextWorkRequired(pindexPrev, &block)) return state.DoS(100, error("AcceptBlock() : incorrect proof of work")); // Check timestamp against prev if (block.GetBlockTime() <= pindexPrev->GetMedianTimePast()) return state.Invalid(error("AcceptBlock() : block's timestamp is too early")); // Check that all transactions are finalized BOOST_FOREACH(const CTransaction& tx, block.vtx) if (!IsFinalTx(tx, nHeight, block.GetBlockTime())) return state.DoS(10, error("AcceptBlock() : contains a non-final transaction")); // Check that the block chain matches the known block chain up to a checkpoint if (!Checkpoints::CheckBlock(nHeight, hash)) return state.DoS(100, error("AcceptBlock() : rejected by checkpoint lock-in at %d", nHeight)); // Reject block.nVersion=1 blocks when 95% (75% on testnet) of the network has upgraded: if (block.nVersion < 2) { if ((!TestNet() && CBlockIndex::IsSuperMajority(2, pindexPrev, 950, 1000)) || (TestNet() && CBlockIndex::IsSuperMajority(2, pindexPrev, 75, 100))) { return state.Invalid(error("AcceptBlock() : rejected nVersion=1 block")); } } // Enforce block.nVersion=2 rule that the coinbase starts with serialized block height if (block.nVersion >= 2) { // if 750 of the last 1,000 blocks are version 2 or greater (51/100 if testnet): if ((!TestNet() && CBlockIndex::IsSuperMajority(2, pindexPrev, 750, 1000)) || (TestNet() && CBlockIndex::IsSuperMajority(2, pindexPrev, 51, 100))) { CScript expect = CScript() << nHeight; if (!std::equal(expect.begin(), expect.end(), block.vtx[0].vin[0].scriptSig.begin())) return state.DoS(100, error("AcceptBlock() : block height mismatch in coinbase")); } } } // Write block to history file try { unsigned int nBlockSize = ::GetSerializeSize(block, SER_DISK, CLIENT_VERSION); CDiskBlockPos blockPos; if (dbp != NULL) blockPos = *dbp; if (!FindBlockPos(state, blockPos, nBlockSize+8, nHeight, block.nTime, dbp != NULL)) return error("AcceptBlock() : FindBlockPos failed"); if (dbp == NULL) if (!WriteBlockToDisk(block, blockPos)) return state.Abort(_("Failed to write block")); if (!AddToBlockIndex(block, state, blockPos)) return error("AcceptBlock() : AddToBlockIndex failed"); } catch(std::runtime_error &e) { return state.Abort(_("System error: ") + e.what()); } // Relay inventory, but don't relay old inventory during initial block download int nBlockEstimate = Checkpoints::GetTotalBlocksEstimate(); if (hashBestChain == hash) { LOCK(cs_vNodes); BOOST_FOREACH(CNode* pnode, vNodes) if (nBestHeight > (pnode->nStartingHeight != -1 ? pnode->nStartingHeight - 2000 : nBlockEstimate)) pnode->PushInventory(CInv(MSG_BLOCK, hash)); } return true; } bool CBlockIndex::IsSuperMajority(int minVersion, const CBlockIndex* pstart, unsigned int nRequired, unsigned int nToCheck) { unsigned int nFound = 0; for (unsigned int i = 0; i < nToCheck && nFound < nRequired && pstart != NULL; i++) { if (pstart->nVersion >= minVersion) ++nFound; pstart = pstart->pprev; } return (nFound >= nRequired); } void PushGetBlocks(CNode* pnode, CBlockIndex* pindexBegin, uint256 hashEnd) { // Filter out duplicate requests if (pindexBegin == pnode->pindexLastGetBlocksBegin && hashEnd == pnode->hashLastGetBlocksEnd) return; pnode->pindexLastGetBlocksBegin = pindexBegin; pnode->hashLastGetBlocksEnd = hashEnd; pnode->PushMessage("getblocks", CBlockLocator(pindexBegin), hashEnd); } bool ProcessBlock(CValidationState &state, CNode* pfrom, CBlock* pblock, CDiskBlockPos *dbp) { // Check for duplicate uint256 hash = pblock->GetHash(); if (mapBlockIndex.count(hash)) return state.Invalid(error("ProcessBlock() : already have block %d %s", mapBlockIndex[hash]->nHeight, hash.ToString().c_str())); if (mapOrphanBlocks.count(hash)) return state.Invalid(error("ProcessBlock() : already have block (orphan) %s", hash.ToString().c_str())); // Preliminary checks if (!CheckBlock(*pblock, state)) return error("ProcessBlock() : CheckBlock FAILED"); CBlockIndex* pcheckpoint = Checkpoints::GetLastCheckpoint(mapBlockIndex); if (pcheckpoint && pblock->hashPrevBlock != hashBestChain) { // Extra checks to prevent "fill up memory by spamming with bogus blocks" int64 deltaTime = pblock->GetBlockTime() - pcheckpoint->nTime; if (deltaTime < 0) { return state.DoS(100, error("ProcessBlock() : block with timestamp before last checkpoint")); } CBigNum bnNewBlock; bnNewBlock.SetCompact(pblock->nBits); CBigNum bnRequired; bnRequired.SetCompact(ComputeMinWork(pcheckpoint->nBits, deltaTime)); if (bnNewBlock > bnRequired) { return state.DoS(100, error("ProcessBlock() : block with too little proof-of-work")); } } // If we don't already have its previous block, shunt it off to holding area until we get it if (pblock->hashPrevBlock != 0 && !mapBlockIndex.count(pblock->hashPrevBlock)) { printf("ProcessBlock: ORPHAN BLOCK, prev=%s\n", pblock->hashPrevBlock.ToString().c_str()); // Accept orphans as long as there is a node to request its parents from if (pfrom) { CBlock* pblock2 = new CBlock(*pblock); mapOrphanBlocks.insert(make_pair(hash, pblock2)); mapOrphanBlocksByPrev.insert(make_pair(pblock2->hashPrevBlock, pblock2)); // Ask this guy to fill in what we're missing PushGetBlocks(pfrom, pindexBest, GetOrphanRoot(pblock2)); } return true; } // Store to disk if (!AcceptBlock(*pblock, state, dbp)) return error("ProcessBlock() : AcceptBlock FAILED"); // Recursively process any orphan blocks that depended on this one vector<uint256> vWorkQueue; vWorkQueue.push_back(hash); for (unsigned int i = 0; i < vWorkQueue.size(); i++) { uint256 hashPrev = vWorkQueue[i]; for (multimap<uint256, CBlock*>::iterator mi = mapOrphanBlocksByPrev.lower_bound(hashPrev); mi != mapOrphanBlocksByPrev.upper_bound(hashPrev); ++mi) { CBlock* pblockOrphan = (*mi).second; // Use a dummy CValidationState so someone can't setup nodes to counter-DoS based on orphan resolution (that is, feeding people an invalid block based on LegitBlockX in order to get anyone relaying LegitBlockX banned) CValidationState stateDummy; if (AcceptBlock(*pblockOrphan, stateDummy)) vWorkQueue.push_back(pblockOrphan->GetHash()); mapOrphanBlocks.erase(pblockOrphan->GetHash()); delete pblockOrphan; } mapOrphanBlocksByPrev.erase(hashPrev); } printf("ProcessBlock: ACCEPTED\n"); return true; } CMerkleBlock::CMerkleBlock(const CBlock& block, CBloomFilter& filter) { header = block.GetBlockHeader(); vector<bool> vMatch; vector<uint256> vHashes; vMatch.reserve(block.vtx.size()); vHashes.reserve(block.vtx.size()); for (unsigned int i = 0; i < block.vtx.size(); i++) { uint256 hash = block.vtx[i].GetHash(); if (filter.IsRelevantAndUpdate(block.vtx[i], hash)) { vMatch.push_back(true); vMatchedTxn.push_back(make_pair(i, hash)); } else vMatch.push_back(false); vHashes.push_back(hash); } txn = CPartialMerkleTree(vHashes, vMatch); } uint256 CPartialMerkleTree::CalcHash(int height, unsigned int pos, const std::vector<uint256> &vTxid) { if (height == 0) { // hash at height 0 is the txids themself return vTxid[pos]; } else { // calculate left hash uint256 left = CalcHash(height-1, pos*2, vTxid), right; // calculate right hash if not beyong the end of the array - copy left hash otherwise1 if (pos*2+1 < CalcTreeWidth(height-1)) right = CalcHash(height-1, pos*2+1, vTxid); else right = left; // combine subhashes return Hash(BEGIN(left), END(left), BEGIN(right), END(right)); } } void CPartialMerkleTree::TraverseAndBuild(int height, unsigned int pos, const std::vector<uint256> &vTxid, const std::vector<bool> &vMatch) { // determine whether this node is the parent of at least one matched txid bool fParentOfMatch = false; for (unsigned int p = pos << height; p < (pos+1) << height && p < nTransactions; p++) fParentOfMatch |= vMatch[p]; // store as flag bit vBits.push_back(fParentOfMatch); if (height==0 || !fParentOfMatch) { // if at height 0, or nothing interesting below, store hash and stop vHash.push_back(CalcHash(height, pos, vTxid)); } else { // otherwise, don't store any hash, but descend into the subtrees TraverseAndBuild(height-1, pos*2, vTxid, vMatch); if (pos*2+1 < CalcTreeWidth(height-1)) TraverseAndBuild(height-1, pos*2+1, vTxid, vMatch); } } uint256 CPartialMerkleTree::TraverseAndExtract(int height, unsigned int pos, unsigned int &nBitsUsed, unsigned int &nHashUsed, std::vector<uint256> &vMatch) { if (nBitsUsed >= vBits.size()) { // overflowed the bits array - failure fBad = true; return 0; } bool fParentOfMatch = vBits[nBitsUsed++]; if (height==0 || !fParentOfMatch) { // if at height 0, or nothing interesting below, use stored hash and do not descend if (nHashUsed >= vHash.size()) { // overflowed the hash array - failure fBad = true; return 0; } const uint256 &hash = vHash[nHashUsed++]; if (height==0 && fParentOfMatch) // in case of height 0, we have a matched txid vMatch.push_back(hash); return hash; } else { // otherwise, descend into the subtrees to extract matched txids and hashes uint256 left = TraverseAndExtract(height-1, pos*2, nBitsUsed, nHashUsed, vMatch), right; if (pos*2+1 < CalcTreeWidth(height-1)) right = TraverseAndExtract(height-1, pos*2+1, nBitsUsed, nHashUsed, vMatch); else right = left; // and combine them before returning return Hash(BEGIN(left), END(left), BEGIN(right), END(right)); } } CPartialMerkleTree::CPartialMerkleTree(const std::vector<uint256> &vTxid, const std::vector<bool> &vMatch) : nTransactions(vTxid.size()), fBad(false) { // reset state vBits.clear(); vHash.clear(); // calculate height of tree int nHeight = 0; while (CalcTreeWidth(nHeight) > 1) nHeight++; // traverse the partial tree TraverseAndBuild(nHeight, 0, vTxid, vMatch); } CPartialMerkleTree::CPartialMerkleTree() : nTransactions(0), fBad(true) {} uint256 CPartialMerkleTree::ExtractMatches(std::vector<uint256> &vMatch) { vMatch.clear(); // An empty set will not work if (nTransactions == 0) return 0; // check for excessively high numbers of transactions if (nTransactions > MAX_BLOCK_SIZE / 60) // 60 is the lower bound for the size of a serialized CTransaction return 0; // there can never be more hashes provided than one for every txid if (vHash.size() > nTransactions) return 0; // there must be at least one bit per node in the partial tree, and at least one node per hash if (vBits.size() < vHash.size()) return 0; // calculate height of tree int nHeight = 0; while (CalcTreeWidth(nHeight) > 1) nHeight++; // traverse the partial tree unsigned int nBitsUsed = 0, nHashUsed = 0; uint256 hashMerkleRoot = TraverseAndExtract(nHeight, 0, nBitsUsed, nHashUsed, vMatch); // verify that no problems occured during the tree traversal if (fBad) return 0; // verify that all bits were consumed (except for the padding caused by serializing it as a byte sequence) if ((nBitsUsed+7)/8 != (vBits.size()+7)/8) return 0; // verify that all hashes were consumed if (nHashUsed != vHash.size()) return 0; return hashMerkleRoot; } bool AbortNode(const std::string &strMessage) { strMiscWarning = strMessage; printf("*** %s\n", strMessage.c_str()); uiInterface.ThreadSafeMessageBox(strMessage, "", CClientUIInterface::MSG_ERROR); StartShutdown(); return false; } bool CheckDiskSpace(uint64 nAdditionalBytes) { uint64 nFreeBytesAvailable = filesystem::space(GetDataDir()).available; // Check for nMinDiskSpace bytes (currently 50MB) if (nFreeBytesAvailable < nMinDiskSpace + nAdditionalBytes) return AbortNode(_("Error: Disk space is low!")); return true; } CCriticalSection cs_LastBlockFile; CBlockFileInfo infoLastBlockFile; int nLastBlockFile = 0; FILE* OpenDiskFile(const CDiskBlockPos &pos, const char *prefix, bool fReadOnly) { if (pos.IsNull()) return NULL; boost::filesystem::path path = GetDataDir() / "blocks" / strprintf("%s%05u.dat", prefix, pos.nFile); boost::filesystem::create_directories(path.parent_path()); FILE* file = fopen(path.string().c_str(), "rb+"); if (!file && !fReadOnly) file = fopen(path.string().c_str(), "wb+"); if (!file) { printf("Unable to open file %s\n", path.string().c_str()); return NULL; } if (pos.nPos) { if (fseek(file, pos.nPos, SEEK_SET)) { printf("Unable to seek to position %u of %s\n", pos.nPos, path.string().c_str()); fclose(file); return NULL; } } return file; } FILE* OpenBlockFile(const CDiskBlockPos &pos, bool fReadOnly) { return OpenDiskFile(pos, "blk", fReadOnly); } FILE* OpenUndoFile(const CDiskBlockPos &pos, bool fReadOnly) { return OpenDiskFile(pos, "rev", fReadOnly); } CBlockIndex * InsertBlockIndex(uint256 hash) { if (hash == 0) return NULL; // Return existing map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hash); if (mi != mapBlockIndex.end()) return (*mi).second; // Create new CBlockIndex* pindexNew = new CBlockIndex(); if (!pindexNew) throw runtime_error("LoadBlockIndex() : new CBlockIndex failed"); mi = mapBlockIndex.insert(make_pair(hash, pindexNew)).first; pindexNew->phashBlock = &((*mi).first); return pindexNew; } bool static LoadBlockIndexDB() { if (!pblocktree->LoadBlockIndexGuts()) return false; boost::this_thread::interruption_point(); // Calculate nChainWork vector<pair<int, CBlockIndex*> > vSortedByHeight; vSortedByHeight.reserve(mapBlockIndex.size()); BOOST_FOREACH(const PAIRTYPE(uint256, CBlockIndex*)& item, mapBlockIndex) { CBlockIndex* pindex = item.second; vSortedByHeight.push_back(make_pair(pindex->nHeight, pindex)); } sort(vSortedByHeight.begin(), vSortedByHeight.end()); BOOST_FOREACH(const PAIRTYPE(int, CBlockIndex*)& item, vSortedByHeight) { CBlockIndex* pindex = item.second; pindex->nChainWork = (pindex->pprev ? pindex->pprev->nChainWork : 0) + pindex->GetBlockWork().getuint256(); pindex->nChainTx = (pindex->pprev ? pindex->pprev->nChainTx : 0) + pindex->nTx; if ((pindex->nStatus & BLOCK_VALID_MASK) >= BLOCK_VALID_TRANSACTIONS && !(pindex->nStatus & BLOCK_FAILED_MASK)) setBlockIndexValid.insert(pindex); } // Load block file info pblocktree->ReadLastBlockFile(nLastBlockFile); printf("LoadBlockIndexDB(): last block file = %i\n", nLastBlockFile); if (pblocktree->ReadBlockFileInfo(nLastBlockFile, infoLastBlockFile)) printf("LoadBlockIndexDB(): last block file info: %s\n", infoLastBlockFile.ToString().c_str()); // Load nBestInvalidWork, OK if it doesn't exist CBigNum bnBestInvalidWork; pblocktree->ReadBestInvalidWork(bnBestInvalidWork); nBestInvalidWork = bnBestInvalidWork.getuint256(); // Check whether we need to continue reindexing bool fReindexing = false; pblocktree->ReadReindexing(fReindexing); fReindex |= fReindexing; // Check whether we have a transaction index pblocktree->ReadFlag("txindex", fTxIndex); printf("LoadBlockIndexDB(): transaction index %s\n", fTxIndex ? "enabled" : "disabled"); // Load hashBestChain pointer to end of best chain pindexBest = pcoinsTip->GetBestBlock(); if (pindexBest == NULL) return true; hashBestChain = pindexBest->GetBlockHash(); nBestHeight = pindexBest->nHeight; nBestChainWork = pindexBest->nChainWork; // register best chain CBlockIndex *pindex = pindexBest; vBlockIndexByHeight.resize(pindexBest->nHeight + 1); while(pindex != NULL) { vBlockIndexByHeight[pindex->nHeight] = pindex; pindex = pindex->pprev; } printf("LoadBlockIndexDB(): hashBestChain=%s height=%d date=%s\n", hashBestChain.ToString().c_str(), nBestHeight, DateTimeStrFormat("%Y-%m-%d %H:%M:%S", pindexBest->GetBlockTime()).c_str()); return true; } bool VerifyDB(int nCheckLevel, int nCheckDepth) { if (pindexBest == NULL || pindexBest->pprev == NULL) return true; // Verify blocks in the best chain if (nCheckDepth <= 0) nCheckDepth = 1000000000; // suffices until the year 19000 if (nCheckDepth > nBestHeight) nCheckDepth = nBestHeight; nCheckLevel = std::max(0, std::min(4, nCheckLevel)); printf("Verifying last %i blocks at level %i\n", nCheckDepth, nCheckLevel); CCoinsViewCache coins(*pcoinsTip, true); CBlockIndex* pindexState = pindexBest; CBlockIndex* pindexFailure = NULL; int nGoodTransactions = 0; CValidationState state; for (CBlockIndex* pindex = pindexBest; pindex && pindex->pprev; pindex = pindex->pprev) { boost::this_thread::interruption_point(); if (pindex->nHeight < nBestHeight-nCheckDepth) break; CBlock block; // check level 0: read from disk if (!ReadBlockFromDisk(block, pindex)) return error("VerifyDB() : *** ReadBlockFromDisk failed at %d, hash=%s", pindex->nHeight, pindex->GetBlockHash().ToString().c_str()); // check level 1: verify block validity if (nCheckLevel >= 1 && !CheckBlock(block, state)) return error("VerifyDB() : *** found bad block at %d, hash=%s\n", pindex->nHeight, pindex->GetBlockHash().ToString().c_str()); // check level 2: verify undo validity if (nCheckLevel >= 2 && pindex) { CBlockUndo undo; CDiskBlockPos pos = pindex->GetUndoPos(); if (!pos.IsNull()) { if (!undo.ReadFromDisk(pos, pindex->pprev->GetBlockHash())) return error("VerifyDB() : *** found bad undo data at %d, hash=%s\n", pindex->nHeight, pindex->GetBlockHash().ToString().c_str()); } } // check level 3: check for inconsistencies during memory-only disconnect of tip blocks if (nCheckLevel >= 3 && pindex == pindexState && (coins.GetCacheSize() + pcoinsTip->GetCacheSize()) <= 2*nCoinCacheSize + 32000) { bool fClean = true; if (!DisconnectBlock(block, state, pindex, coins, &fClean)) return error("VerifyDB() : *** irrecoverable inconsistency in block data at %d, hash=%s", pindex->nHeight, pindex->GetBlockHash().ToString().c_str()); pindexState = pindex->pprev; if (!fClean) { nGoodTransactions = 0; pindexFailure = pindex; } else nGoodTransactions += block.vtx.size(); } } if (pindexFailure) return error("VerifyDB() : *** coin database inconsistencies found (last %i blocks, %i good transactions before that)\n", pindexBest->nHeight - pindexFailure->nHeight + 1, nGoodTransactions); // check level 4: try reconnecting blocks if (nCheckLevel >= 4) { CBlockIndex *pindex = pindexState; while (pindex != pindexBest) { boost::this_thread::interruption_point(); pindex = pindex->GetNextInMainChain(); CBlock block; if (!ReadBlockFromDisk(block, pindex)) return error("VerifyDB() : *** ReadBlockFromDisk failed at %d, hash=%s", pindex->nHeight, pindex->GetBlockHash().ToString().c_str()); if (!ConnectBlock(block, state, pindex, coins)) return error("VerifyDB() : *** found unconnectable block at %d, hash=%s", pindex->nHeight, pindex->GetBlockHash().ToString().c_str()); } } printf("No coin database inconsistencies in last %i blocks (%i transactions)\n", pindexBest->nHeight - pindexState->nHeight, nGoodTransactions); return true; } void UnloadBlockIndex() { mapBlockIndex.clear(); setBlockIndexValid.clear(); pindexGenesisBlock = NULL; nBestHeight = 0; nBestChainWork = 0; nBestInvalidWork = 0; hashBestChain = 0; pindexBest = NULL; } bool LoadBlockIndex() { // Load block index from databases if (!fReindex && !LoadBlockIndexDB()) return false; return true; } bool InitBlockIndex() { // Check whether we're already initialized if (pindexGenesisBlock != NULL) return true; // Use the provided setting for -txindex in the new database fTxIndex = GetBoolArg("-txindex", false); pblocktree->WriteFlag("txindex", fTxIndex); printf("Initializing databases...\n"); // Only add the genesis block if not reindexing (in which case we reuse the one already on disk) if (!fReindex) { try { CBlock &block = const_cast<CBlock&>(Params().GenesisBlock()); // Start new block file unsigned int nBlockSize = ::GetSerializeSize(block, SER_DISK, CLIENT_VERSION); CDiskBlockPos blockPos; CValidationState state; if (!FindBlockPos(state, blockPos, nBlockSize+8, 0, block.nTime)) return error("LoadBlockIndex() : FindBlockPos failed"); if (!WriteBlockToDisk(block, blockPos)) return error("LoadBlockIndex() : writing genesis block to disk failed"); if (!AddToBlockIndex(block, state, blockPos)) return error("LoadBlockIndex() : genesis block not accepted"); } catch(std::runtime_error &e) { return error("LoadBlockIndex() : failed to initialize block database: %s", e.what()); } } return true; } void PrintBlockTree() { // pre-compute tree structure map<CBlockIndex*, vector<CBlockIndex*> > mapNext; for (map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.begin(); mi != mapBlockIndex.end(); ++mi) { CBlockIndex* pindex = (*mi).second; mapNext[pindex->pprev].push_back(pindex); // test //while (rand() % 3 == 0) // mapNext[pindex->pprev].push_back(pindex); } vector<pair<int, CBlockIndex*> > vStack; vStack.push_back(make_pair(0, pindexGenesisBlock)); int nPrevCol = 0; while (!vStack.empty()) { int nCol = vStack.back().first; CBlockIndex* pindex = vStack.back().second; vStack.pop_back(); // print split or gap if (nCol > nPrevCol) { for (int i = 0; i < nCol-1; i++) printf("| "); printf("|\\\n"); } else if (nCol < nPrevCol) { for (int i = 0; i < nCol; i++) printf("| "); printf("|\n"); } nPrevCol = nCol; // print columns for (int i = 0; i < nCol; i++) printf("| "); // print item CBlock block; ReadBlockFromDisk(block, pindex); printf("%d (blk%05u.dat:0x%x) %s tx %"PRIszu"", pindex->nHeight, pindex->GetBlockPos().nFile, pindex->GetBlockPos().nPos, DateTimeStrFormat("%Y-%m-%d %H:%M:%S", block.GetBlockTime()).c_str(), block.vtx.size()); PrintWallets(block); // put the main time-chain first vector<CBlockIndex*>& vNext = mapNext[pindex]; for (unsigned int i = 0; i < vNext.size(); i++) { if (vNext[i]->GetNextInMainChain()) { swap(vNext[0], vNext[i]); break; } } // iterate children for (unsigned int i = 0; i < vNext.size(); i++) vStack.push_back(make_pair(nCol+i, vNext[i])); } } bool LoadExternalBlockFile(FILE* fileIn, CDiskBlockPos *dbp) { int64 nStart = GetTimeMillis(); int nLoaded = 0; try { CBufferedFile blkdat(fileIn, 2*MAX_BLOCK_SIZE, MAX_BLOCK_SIZE+8, SER_DISK, CLIENT_VERSION); uint64 nStartByte = 0; if (dbp) { // (try to) skip already indexed part CBlockFileInfo info; if (pblocktree->ReadBlockFileInfo(dbp->nFile, info)) { nStartByte = info.nSize; blkdat.Seek(info.nSize); } } uint64 nRewind = blkdat.GetPos(); while (blkdat.good() && !blkdat.eof()) { boost::this_thread::interruption_point(); blkdat.SetPos(nRewind); nRewind++; // start one byte further next time, in case of failure blkdat.SetLimit(); // remove former limit unsigned int nSize = 0; try { // locate a header unsigned char buf[4]; blkdat.FindByte(Params().MessageStart()[0]); nRewind = blkdat.GetPos()+1; blkdat >> FLATDATA(buf); if (memcmp(buf, Params().MessageStart(), 4)) continue; // read size blkdat >> nSize; if (nSize < 80 || nSize > MAX_BLOCK_SIZE) continue; } catch (std::exception &e) { // no valid block header found; don't complain break; } try { // read block uint64 nBlockPos = blkdat.GetPos(); blkdat.SetLimit(nBlockPos + nSize); CBlock block; blkdat >> block; nRewind = blkdat.GetPos(); // process block if (nBlockPos >= nStartByte) { LOCK(cs_main); if (dbp) dbp->nPos = nBlockPos; CValidationState state; if (ProcessBlock(state, NULL, &block, dbp)) nLoaded++; if (state.IsError()) break; } } catch (std::exception &e) { printf("%s() : Deserialize or I/O error caught during load\n", __PRETTY_FUNCTION__); } } fclose(fileIn); } catch(std::runtime_error &e) { AbortNode(_("Error: system error: ") + e.what()); } if (nLoaded > 0) printf("Loaded %i blocks from external file in %"PRI64d"ms\n", nLoaded, GetTimeMillis() - nStart); return nLoaded > 0; } ////////////////////////////////////////////////////////////////////////////// // // CAlert // extern map<uint256, CAlert> mapAlerts; extern CCriticalSection cs_mapAlerts; string GetWarnings(string strFor) { int nPriority = 0; string strStatusBar; string strRPC; if (GetBoolArg("-testsafemode", false)) strRPC = "test"; if (!CLIENT_VERSION_IS_RELEASE) strStatusBar = _("This is a pre-release test build - use at your own risk - do not use for mining or merchant applications"); // Misc warnings like out of disk space and clock is wrong if (strMiscWarning != "") { nPriority = 1000; strStatusBar = strMiscWarning; } // Longer invalid proof-of-work chain if (pindexBest && nBestInvalidWork > nBestChainWork + (pindexBest->GetBlockWork() * 6).getuint256()) { nPriority = 2000; strStatusBar = strRPC = _("Warning: Displayed transactions may not be correct! You may need to upgrade, or other nodes may need to upgrade."); } // Alerts { LOCK(cs_mapAlerts); BOOST_FOREACH(PAIRTYPE(const uint256, CAlert)& item, mapAlerts) { const CAlert& alert = item.second; if (alert.AppliesToMe() && alert.nPriority > nPriority) { nPriority = alert.nPriority; strStatusBar = alert.strStatusBar; } } } if (strFor == "statusbar") return strStatusBar; else if (strFor == "rpc") return strRPC; assert(!"GetWarnings() : invalid parameter"); return "error"; } ////////////////////////////////////////////////////////////////////////////// // // Messages // bool static AlreadyHave(const CInv& inv) { switch (inv.type) { case MSG_TX: { bool txInMap = false; { LOCK(mempool.cs); txInMap = mempool.exists(inv.hash); } return txInMap || mapOrphanTransactions.count(inv.hash) || pcoinsTip->HaveCoins(inv.hash); } case MSG_BLOCK: return mapBlockIndex.count(inv.hash) || mapOrphanBlocks.count(inv.hash); } // Don't know what it is, just say we already got one return true; } void static ProcessGetData(CNode* pfrom) { std::deque<CInv>::iterator it = pfrom->vRecvGetData.begin(); vector<CInv> vNotFound; while (it != pfrom->vRecvGetData.end()) { // Don't bother if send buffer is too full to respond anyway if (pfrom->nSendSize >= SendBufferSize()) break; const CInv &inv = *it; { boost::this_thread::interruption_point(); it++; if (inv.type == MSG_BLOCK || inv.type == MSG_FILTERED_BLOCK) { // Send block from disk map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(inv.hash); if (mi != mapBlockIndex.end()) { CBlock block; ReadBlockFromDisk(block, (*mi).second); if (inv.type == MSG_BLOCK) pfrom->PushMessage("block", block); else // MSG_FILTERED_BLOCK) { LOCK(pfrom->cs_filter); if (pfrom->pfilter) { CMerkleBlock merkleBlock(block, *pfrom->pfilter); pfrom->PushMessage("merkleblock", merkleBlock); // CMerkleBlock just contains hashes, so also push any transactions in the block the client did not see // This avoids hurting performance by pointlessly requiring a round-trip // Note that there is currently no way for a node to request any single transactions we didnt send here - // they must either disconnect and retry or request the full block. // Thus, the protocol spec specified allows for us to provide duplicate txn here, // however we MUST always provide at least what the remote peer needs typedef std::pair<unsigned int, uint256> PairType; BOOST_FOREACH(PairType& pair, merkleBlock.vMatchedTxn) if (!pfrom->setInventoryKnown.count(CInv(MSG_TX, pair.second))) pfrom->PushMessage("tx", block.vtx[pair.first]); } // else // no response } // Trigger them to send a getblocks request for the next batch of inventory if (inv.hash == pfrom->hashContinue) { // Bypass PushInventory, this must send even if redundant, // and we want it right after the last block so they don't // wait for other stuff first. vector<CInv> vInv; vInv.push_back(CInv(MSG_BLOCK, hashBestChain)); pfrom->PushMessage("inv", vInv); pfrom->hashContinue = 0; } } } else if (inv.IsKnownType()) { // Send stream from relay memory bool pushed = false; { LOCK(cs_mapRelay); map<CInv, CDataStream>::iterator mi = mapRelay.find(inv); if (mi != mapRelay.end()) { pfrom->PushMessage(inv.GetCommand(), (*mi).second); pushed = true; } } if (!pushed && inv.type == MSG_TX) { LOCK(mempool.cs); if (mempool.exists(inv.hash)) { CTransaction tx = mempool.lookup(inv.hash); CDataStream ss(SER_NETWORK, PROTOCOL_VERSION); ss.reserve(1000); ss << tx; pfrom->PushMessage("tx", ss); pushed = true; } } if (!pushed) { vNotFound.push_back(inv); } } // Track requests for our stuff. Inventory(inv.hash); } } pfrom->vRecvGetData.erase(pfrom->vRecvGetData.begin(), it); if (!vNotFound.empty()) { // Let the peer know that we didn't find what it asked for, so it doesn't // have to wait around forever. Currently only SPV clients actually care // about this message: it's needed when they are recursively walking the // dependencies of relevant unconfirmed transactions. SPV clients want to // do that because they want to know about (and store and rebroadcast and // risk analyze) the dependencies of transactions relevant to them, without // having to download the entire memory pool. pfrom->PushMessage("notfound", vNotFound); } } bool static ProcessMessage(CNode* pfrom, string strCommand, CDataStream& vRecv) { RandAddSeedPerfmon(); if (fDebug) printf("received: %s (%"PRIszu" bytes)\n", strCommand.c_str(), vRecv.size()); if (mapArgs.count("-dropmessagestest") && GetRand(atoi(mapArgs["-dropmessagestest"])) == 0) { printf("dropmessagestest DROPPING RECV MESSAGE\n"); return true; } if (strCommand == "version") { // Each connection can only send one version message if (pfrom->nVersion != 0) { pfrom->Misbehaving(1); return false; } int64 nTime; CAddress addrMe; CAddress addrFrom; uint64 nNonce = 1; vRecv >> pfrom->nVersion >> pfrom->nServices >> nTime >> addrMe; if (pfrom->nVersion < MIN_PROTO_VERSION) { // Since February 20, 2012, the protocol is initiated at version 209, // and earlier versions are no longer supported printf("partner %s using obsolete version %i; disconnecting\n", pfrom->addr.ToString().c_str(), pfrom->nVersion); pfrom->fDisconnect = true; return false; } if (pfrom->nVersion == 10300) pfrom->nVersion = 300; if (!vRecv.empty()) vRecv >> addrFrom >> nNonce; if (!vRecv.empty()) vRecv >> pfrom->strSubVer; if (!vRecv.empty()) vRecv >> pfrom->nStartingHeight; if (!vRecv.empty()) vRecv >> pfrom->fRelayTxes; // set to true after we get the first filter* message else pfrom->fRelayTxes = true; if (pfrom->fInbound && addrMe.IsRoutable()) { pfrom->addrLocal = addrMe; SeenLocal(addrMe); } // Disconnect if we connected to ourself if (nNonce == nLocalHostNonce && nNonce > 1) { printf("connected to self at %s, disconnecting\n", pfrom->addr.ToString().c_str()); pfrom->fDisconnect = true; return true; } // Be shy and don't send version until we hear if (pfrom->fInbound) pfrom->PushVersion(); pfrom->fClient = !(pfrom->nServices & NODE_NETWORK); AddTimeData(pfrom->addr, nTime); // Change version pfrom->PushMessage("verack"); pfrom->ssSend.SetVersion(min(pfrom->nVersion, PROTOCOL_VERSION)); if (!pfrom->fInbound) { // Advertise our address if (!fNoListen && !IsInitialBlockDownload()) { CAddress addr = GetLocalAddress(&pfrom->addr); if (addr.IsRoutable()) pfrom->PushAddress(addr); } // Get recent addresses if (pfrom->fOneShot || pfrom->nVersion >= CADDR_TIME_VERSION || addrman.size() < 1000) { pfrom->PushMessage("getaddr"); pfrom->fGetAddr = true; } addrman.Good(pfrom->addr); } else { if (((CNetAddr)pfrom->addr) == (CNetAddr)addrFrom) { addrman.Add(addrFrom, addrFrom); addrman.Good(addrFrom); } } // Relay alerts { LOCK(cs_mapAlerts); BOOST_FOREACH(PAIRTYPE(const uint256, CAlert)& item, mapAlerts) item.second.RelayTo(pfrom); } pfrom->fSuccessfullyConnected = true; printf("receive version message: version %d, blocks=%d, us=%s, them=%s, peer=%s\n", pfrom->nVersion, pfrom->nStartingHeight, addrMe.ToString().c_str(), addrFrom.ToString().c_str(), pfrom->addr.ToString().c_str()); cPeerBlockCounts.input(pfrom->nStartingHeight); } else if (pfrom->nVersion == 0) { // Must have a version message before anything else pfrom->Misbehaving(1); return false; } else if (strCommand == "verack") { pfrom->SetRecvVersion(min(pfrom->nVersion, PROTOCOL_VERSION)); } else if (strCommand == "addr") { vector<CAddress> vAddr; vRecv >> vAddr; // Don't want addr from older versions unless seeding if (pfrom->nVersion < CADDR_TIME_VERSION && addrman.size() > 1000) return true; if (vAddr.size() > 1000) { pfrom->Misbehaving(20); return error("message addr size() = %"PRIszu"", vAddr.size()); } // Store the new addresses vector<CAddress> vAddrOk; int64 nNow = GetAdjustedTime(); int64 nSince = nNow - 10 * 60; BOOST_FOREACH(CAddress& addr, vAddr) { boost::this_thread::interruption_point(); if (addr.nTime <= 100000000 || addr.nTime > nNow + 10 * 60) addr.nTime = nNow - 5 * 24 * 60 * 60; pfrom->AddAddressKnown(addr); bool fReachable = IsReachable(addr); if (addr.nTime > nSince && !pfrom->fGetAddr && vAddr.size() <= 10 && addr.IsRoutable()) { // Relay to a limited number of other nodes { LOCK(cs_vNodes); // Use deterministic randomness to send to the same nodes for 24 hours // at a time so the setAddrKnowns of the chosen nodes prevent repeats static uint256 hashSalt; if (hashSalt == 0) hashSalt = GetRandHash(); uint64 hashAddr = addr.GetHash(); uint256 hashRand = hashSalt ^ (hashAddr<<32) ^ ((GetTime()+hashAddr)/(24*60*60)); hashRand = Hash(BEGIN(hashRand), END(hashRand)); multimap<uint256, CNode*> mapMix; BOOST_FOREACH(CNode* pnode, vNodes) { if (pnode->nVersion < CADDR_TIME_VERSION) continue; unsigned int nPointer; memcpy(&nPointer, &pnode, sizeof(nPointer)); uint256 hashKey = hashRand ^ nPointer; hashKey = Hash(BEGIN(hashKey), END(hashKey)); mapMix.insert(make_pair(hashKey, pnode)); } int nRelayNodes = fReachable ? 2 : 1; // limited relaying of addresses outside our network(s) for (multimap<uint256, CNode*>::iterator mi = mapMix.begin(); mi != mapMix.end() && nRelayNodes-- > 0; ++mi) ((*mi).second)->PushAddress(addr); } } // Do not store addresses outside our network if (fReachable) vAddrOk.push_back(addr); } addrman.Add(vAddrOk, pfrom->addr, 2 * 60 * 60); if (vAddr.size() < 1000) pfrom->fGetAddr = false; if (pfrom->fOneShot) pfrom->fDisconnect = true; } else if (strCommand == "inv") { vector<CInv> vInv; vRecv >> vInv; if (vInv.size() > MAX_INV_SZ) { pfrom->Misbehaving(20); return error("message inv size() = %"PRIszu"", vInv.size()); } // find last block in inv vector unsigned int nLastBlock = (unsigned int)(-1); for (unsigned int nInv = 0; nInv < vInv.size(); nInv++) { if (vInv[vInv.size() - 1 - nInv].type == MSG_BLOCK) { nLastBlock = vInv.size() - 1 - nInv; break; } } for (unsigned int nInv = 0; nInv < vInv.size(); nInv++) { const CInv &inv = vInv[nInv]; boost::this_thread::interruption_point(); pfrom->AddInventoryKnown(inv); bool fAlreadyHave = AlreadyHave(inv); if (fDebug) printf(" got inventory: %s %s\n", inv.ToString().c_str(), fAlreadyHave ? "have" : "new"); if (!fAlreadyHave) { if (!fImporting && !fReindex) pfrom->AskFor(inv); } else if (inv.type == MSG_BLOCK && mapOrphanBlocks.count(inv.hash)) { PushGetBlocks(pfrom, pindexBest, GetOrphanRoot(mapOrphanBlocks[inv.hash])); } else if (nInv == nLastBlock) { // In case we are on a very long side-chain, it is possible that we already have // the last block in an inv bundle sent in response to getblocks. Try to detect // this situation and push another getblocks to continue. PushGetBlocks(pfrom, mapBlockIndex[inv.hash], uint256(0)); if (fDebug) printf("force request: %s\n", inv.ToString().c_str()); } // Track requests for our stuff Inventory(inv.hash); } } else if (strCommand == "getdata") { vector<CInv> vInv; vRecv >> vInv; if (vInv.size() > MAX_INV_SZ) { pfrom->Misbehaving(20); return error("message getdata size() = %"PRIszu"", vInv.size()); } if (fDebugNet || (vInv.size() != 1)) printf("received getdata (%"PRIszu" invsz)\n", vInv.size()); if ((fDebugNet && vInv.size() > 0) || (vInv.size() == 1)) printf("received getdata for: %s\n", vInv[0].ToString().c_str()); pfrom->vRecvGetData.insert(pfrom->vRecvGetData.end(), vInv.begin(), vInv.end()); ProcessGetData(pfrom); } else if (strCommand == "getblocks") { CBlockLocator locator; uint256 hashStop; vRecv >> locator >> hashStop; // Find the last block the caller has in the main chain CBlockIndex* pindex = locator.GetBlockIndex(); // Send the rest of the chain if (pindex) pindex = pindex->GetNextInMainChain(); int nLimit = 500; printf("getblocks %d to %s limit %d\n", (pindex ? pindex->nHeight : -1), hashStop.ToString().c_str(), nLimit); for (; pindex; pindex = pindex->GetNextInMainChain()) { if (pindex->GetBlockHash() == hashStop) { printf(" getblocks stopping at %d %s\n", pindex->nHeight, pindex->GetBlockHash().ToString().c_str()); break; } pfrom->PushInventory(CInv(MSG_BLOCK, pindex->GetBlockHash())); if (--nLimit <= 0) { // When this block is requested, we'll send an inv that'll make them // getblocks the next batch of inventory. printf(" getblocks stopping at limit %d %s\n", pindex->nHeight, pindex->GetBlockHash().ToString().c_str()); pfrom->hashContinue = pindex->GetBlockHash(); break; } } } else if (strCommand == "getheaders") { CBlockLocator locator; uint256 hashStop; vRecv >> locator >> hashStop; CBlockIndex* pindex = NULL; if (locator.IsNull()) { // If locator is null, return the hashStop block map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashStop); if (mi == mapBlockIndex.end()) return true; pindex = (*mi).second; } else { // Find the last block the caller has in the main chain pindex = locator.GetBlockIndex(); if (pindex) pindex = pindex->GetNextInMainChain(); } // we must use CBlocks, as CBlockHeaders won't include the 0x00 nTx count at the end vector<CBlock> vHeaders; int nLimit = 2000; printf("getheaders %d to %s\n", (pindex ? pindex->nHeight : -1), hashStop.ToString().c_str()); for (; pindex; pindex = pindex->GetNextInMainChain()) { vHeaders.push_back(pindex->GetBlockHeader()); if (--nLimit <= 0 || pindex->GetBlockHash() == hashStop) break; } pfrom->PushMessage("headers", vHeaders); } else if (strCommand == "tx") { vector<uint256> vWorkQueue; vector<uint256> vEraseQueue; CDataStream vMsg(vRecv); CTransaction tx; vRecv >> tx; CInv inv(MSG_TX, tx.GetHash()); pfrom->AddInventoryKnown(inv); // Truncate messages to the size of the tx in them unsigned int nSize = ::GetSerializeSize(tx, SER_NETWORK, PROTOCOL_VERSION); unsigned int oldSize = vMsg.size(); if (nSize < oldSize) { vMsg.resize(nSize); printf("truncating oversized TX %s (%u -> %u)\n", tx.GetHash().ToString().c_str(), oldSize, nSize); } bool fMissingInputs = false; CValidationState state; if (mempool.accept(state, tx, true, &fMissingInputs)) { RelayTransaction(tx, inv.hash, vMsg); mapAlreadyAskedFor.erase(inv); vWorkQueue.push_back(inv.hash); vEraseQueue.push_back(inv.hash); // Recursively process any orphan transactions that depended on this one for (unsigned int i = 0; i < vWorkQueue.size(); i++) { uint256 hashPrev = vWorkQueue[i]; for (map<uint256, CDataStream*>::iterator mi = mapOrphanTransactionsByPrev[hashPrev].begin(); mi != mapOrphanTransactionsByPrev[hashPrev].end(); ++mi) { const CDataStream& vMsg = *((*mi).second); CTransaction tx; CDataStream(vMsg) >> tx; CInv inv(MSG_TX, tx.GetHash()); bool fMissingInputs2 = false; // Use a dummy CValidationState so someone can't setup nodes to counter-DoS based on orphan resolution (that is, feeding people an invalid transaction based on LegitTxX in order to get anyone relaying LegitTxX banned) CValidationState stateDummy; if (mempool.accept(stateDummy, tx, true, &fMissingInputs2)) { printf(" accepted orphan tx %s\n", inv.hash.ToString().c_str()); RelayTransaction(tx, inv.hash, vMsg); mapAlreadyAskedFor.erase(inv); vWorkQueue.push_back(inv.hash); vEraseQueue.push_back(inv.hash); } else if (!fMissingInputs2) { // invalid or too-little-fee orphan vEraseQueue.push_back(inv.hash); printf(" removed orphan tx %s\n", inv.hash.ToString().c_str()); } } } BOOST_FOREACH(uint256 hash, vEraseQueue) EraseOrphanTx(hash); } else if (fMissingInputs) { AddOrphanTx(vMsg); // DoS prevention: do not allow mapOrphanTransactions to grow unbounded unsigned int nEvicted = LimitOrphanTxSize(MAX_ORPHAN_TRANSACTIONS); if (nEvicted > 0) printf("mapOrphan overflow, removed %u tx\n", nEvicted); } int nDoS; if (state.IsInvalid(nDoS)) pfrom->Misbehaving(nDoS); } else if (strCommand == "block" && !fImporting && !fReindex) // Ignore blocks received while importing { CBlock block; vRecv >> block; printf("received block %s\n", block.GetHash().ToString().c_str()); // block.print(); CInv inv(MSG_BLOCK, block.GetHash()); pfrom->AddInventoryKnown(inv); CValidationState state; if (ProcessBlock(state, pfrom, &block)) mapAlreadyAskedFor.erase(inv); int nDoS; if (state.IsInvalid(nDoS)) pfrom->Misbehaving(nDoS); } else if (strCommand == "getaddr") { pfrom->vAddrToSend.clear(); vector<CAddress> vAddr = addrman.GetAddr(); BOOST_FOREACH(const CAddress &addr, vAddr) pfrom->PushAddress(addr); } else if (strCommand == "mempool") { std::vector<uint256> vtxid; LOCK2(mempool.cs, pfrom->cs_filter); mempool.queryHashes(vtxid); vector<CInv> vInv; BOOST_FOREACH(uint256& hash, vtxid) { CInv inv(MSG_TX, hash); if ((pfrom->pfilter && pfrom->pfilter->IsRelevantAndUpdate(mempool.lookup(hash), hash)) || (!pfrom->pfilter)) vInv.push_back(inv); if (vInv.size() == MAX_INV_SZ) break; } if (vInv.size() > 0) pfrom->PushMessage("inv", vInv); } else if (strCommand == "ping") { if (pfrom->nVersion > BIP0031_VERSION) { uint64 nonce = 0; vRecv >> nonce; // Echo the message back with the nonce. This allows for two useful features: // // 1) A remote node can quickly check if the connection is operational // 2) Remote nodes can measure the latency of the network thread. If this node // is overloaded it won't respond to pings quickly and the remote node can // avoid sending us more work, like chain download requests. // // The nonce stops the remote getting confused between different pings: without // it, if the remote node sends a ping once per second and this node takes 5 // seconds to respond to each, the 5th ping the remote sends would appear to // return very quickly. pfrom->PushMessage("pong", nonce); } } else if (strCommand == "alert") { CAlert alert; vRecv >> alert; uint256 alertHash = alert.GetHash(); if (pfrom->setKnown.count(alertHash) == 0) { if (alert.ProcessAlert()) { // Relay pfrom->setKnown.insert(alertHash); { LOCK(cs_vNodes); BOOST_FOREACH(CNode* pnode, vNodes) alert.RelayTo(pnode); } } else { // Small DoS penalty so peers that send us lots of // duplicate/expired/invalid-signature/whatever alerts // eventually get banned. // This isn't a Misbehaving(100) (immediate ban) because the // peer might be an older or different implementation with // a different signature key, etc. pfrom->Misbehaving(10); } } } else if (strCommand == "filterload") { CBloomFilter filter; vRecv >> filter; if (!filter.IsWithinSizeConstraints()) // There is no excuse for sending a too-large filter pfrom->Misbehaving(100); else { LOCK(pfrom->cs_filter); delete pfrom->pfilter; pfrom->pfilter = new CBloomFilter(filter); } pfrom->fRelayTxes = true; } else if (strCommand == "filteradd") { vector<unsigned char> vData; vRecv >> vData; // Nodes must NEVER send a data item > 520 bytes (the max size for a script data object, // and thus, the maximum size any matched object can have) in a filteradd message if (vData.size() > MAX_SCRIPT_ELEMENT_SIZE) { pfrom->Misbehaving(100); } else { LOCK(pfrom->cs_filter); if (pfrom->pfilter) pfrom->pfilter->insert(vData); else pfrom->Misbehaving(100); } } else if (strCommand == "filterclear") { LOCK(pfrom->cs_filter); delete pfrom->pfilter; pfrom->pfilter = NULL; pfrom->fRelayTxes = true; } else { // Ignore unknown commands for extensibility } // Update the last seen time for this node's address if (pfrom->fNetworkNode) if (strCommand == "version" || strCommand == "addr" || strCommand == "inv" || strCommand == "getdata" || strCommand == "ping") AddressCurrentlyConnected(pfrom->addr); return true; } // requires LOCK(cs_vRecvMsg) bool ProcessMessages(CNode* pfrom) { //if (fDebug) // printf("ProcessMessages(%zu messages)\n", pfrom->vRecvMsg.size()); // // Message format // (4) message start // (12) command // (4) size // (4) checksum // (x) data // bool fOk = true; if (!pfrom->vRecvGetData.empty()) ProcessGetData(pfrom); std::deque<CNetMessage>::iterator it = pfrom->vRecvMsg.begin(); while (!pfrom->fDisconnect && it != pfrom->vRecvMsg.end()) { // Don't bother if send buffer is too full to respond anyway if (pfrom->nSendSize >= SendBufferSize()) break; // get next message CNetMessage& msg = *it; //if (fDebug) // printf("ProcessMessages(message %u msgsz, %zu bytes, complete:%s)\n", // msg.hdr.nMessageSize, msg.vRecv.size(), // msg.complete() ? "Y" : "N"); // end, if an incomplete message is found if (!msg.complete()) break; // at this point, any failure means we can delete the current message it++; // Scan for message start if (memcmp(msg.hdr.pchMessageStart, Params().MessageStart(), MESSAGE_START_SIZE) != 0) { printf("\n\nPROCESSMESSAGE: INVALID MESSAGESTART\n\n"); fOk = false; break; } // Read header CMessageHeader& hdr = msg.hdr; if (!hdr.IsValid()) { printf("\n\nPROCESSMESSAGE: ERRORS IN HEADER %s\n\n\n", hdr.GetCommand().c_str()); continue; } string strCommand = hdr.GetCommand(); // Message size unsigned int nMessageSize = hdr.nMessageSize; // Checksum CDataStream& vRecv = msg.vRecv; uint256 hash = Hash(vRecv.begin(), vRecv.begin() + nMessageSize); unsigned int nChecksum = 0; memcpy(&nChecksum, &hash, sizeof(nChecksum)); if (nChecksum != hdr.nChecksum) { printf("ProcessMessages(%s, %u bytes) : CHECKSUM ERROR nChecksum=%08x hdr.nChecksum=%08x\n", strCommand.c_str(), nMessageSize, nChecksum, hdr.nChecksum); continue; } // Process message bool fRet = false; try { { LOCK(cs_main); fRet = ProcessMessage(pfrom, strCommand, vRecv); } boost::this_thread::interruption_point(); } catch (std::ios_base::failure& e) { if (strstr(e.what(), "end of data")) { // Allow exceptions from under-length message on vRecv printf("ProcessMessages(%s, %u bytes) : Exception '%s' caught, normally caused by a message being shorter than its stated length\n", strCommand.c_str(), nMessageSize, e.what()); } else if (strstr(e.what(), "size too large")) { // Allow exceptions from over-long size printf("ProcessMessages(%s, %u bytes) : Exception '%s' caught\n", strCommand.c_str(), nMessageSize, e.what()); } else { PrintExceptionContinue(&e, "ProcessMessages()"); } } catch (boost::thread_interrupted) { throw; } catch (std::exception& e) { PrintExceptionContinue(&e, "ProcessMessages()"); } catch (...) { PrintExceptionContinue(NULL, "ProcessMessages()"); } if (!fRet) printf("ProcessMessage(%s, %u bytes) FAILED\n", strCommand.c_str(), nMessageSize); } // In case the connection got shut down, its receive buffer was wiped if (!pfrom->fDisconnect) pfrom->vRecvMsg.erase(pfrom->vRecvMsg.begin(), it); return fOk; } bool SendMessages(CNode* pto, bool fSendTrickle) { TRY_LOCK(cs_main, lockMain); if (lockMain) { // Don't send anything until we get their version message if (pto->nVersion == 0) return true; // Keep-alive ping. We send a nonce of zero because we don't use it anywhere // right now. if (pto->nLastSend && GetTime() - pto->nLastSend > 30 * 60 && pto->vSendMsg.empty()) { uint64 nonce = 0; if (pto->nVersion > BIP0031_VERSION) pto->PushMessage("ping", nonce); else pto->PushMessage("ping"); } // Start block sync if (pto->fStartSync && !fImporting && !fReindex) { pto->fStartSync = false; PushGetBlocks(pto, pindexBest, uint256(0)); } // Resend wallet transactions that haven't gotten in a block yet // Except during reindex, importing and IBD, when old wallet // transactions become unconfirmed and spams other nodes. if (!fReindex && !fImporting && !IsInitialBlockDownload()) { ResendWalletTransactions(); } // Address refresh broadcast static int64 nLastRebroadcast; if (!IsInitialBlockDownload() && (GetTime() - nLastRebroadcast > 24 * 60 * 60)) { { LOCK(cs_vNodes); BOOST_FOREACH(CNode* pnode, vNodes) { // Periodically clear setAddrKnown to allow refresh broadcasts if (nLastRebroadcast) pnode->setAddrKnown.clear(); // Rebroadcast our address if (!fNoListen) { CAddress addr = GetLocalAddress(&pnode->addr); if (addr.IsRoutable()) pnode->PushAddress(addr); } } } nLastRebroadcast = GetTime(); } // // Message: addr // if (fSendTrickle) { vector<CAddress> vAddr; vAddr.reserve(pto->vAddrToSend.size()); BOOST_FOREACH(const CAddress& addr, pto->vAddrToSend) { // returns true if wasn't already contained in the set if (pto->setAddrKnown.insert(addr).second) { vAddr.push_back(addr); // receiver rejects addr messages larger than 1000 if (vAddr.size() >= 1000) { pto->PushMessage("addr", vAddr); vAddr.clear(); } } } pto->vAddrToSend.clear(); if (!vAddr.empty()) pto->PushMessage("addr", vAddr); } // // Message: inventory // vector<CInv> vInv; vector<CInv> vInvWait; { LOCK(pto->cs_inventory); vInv.reserve(pto->vInventoryToSend.size()); vInvWait.reserve(pto->vInventoryToSend.size()); BOOST_FOREACH(const CInv& inv, pto->vInventoryToSend) { if (pto->setInventoryKnown.count(inv)) continue; // trickle out tx inv to protect privacy if (inv.type == MSG_TX && !fSendTrickle) { // 1/4 of tx invs blast to all immediately static uint256 hashSalt; if (hashSalt == 0) hashSalt = GetRandHash(); uint256 hashRand = inv.hash ^ hashSalt; hashRand = Hash(BEGIN(hashRand), END(hashRand)); bool fTrickleWait = ((hashRand & 3) != 0); // always trickle our own transactions if (!fTrickleWait) { CWalletTx wtx; if (GetTransaction(inv.hash, wtx)) if (wtx.fFromMe) fTrickleWait = true; } if (fTrickleWait) { vInvWait.push_back(inv); continue; } } // returns true if wasn't already contained in the set if (pto->setInventoryKnown.insert(inv).second) { vInv.push_back(inv); if (vInv.size() >= 1000) { pto->PushMessage("inv", vInv); vInv.clear(); } } } pto->vInventoryToSend = vInvWait; } if (!vInv.empty()) pto->PushMessage("inv", vInv); // // Message: getdata // vector<CInv> vGetData; int64 nNow = GetTime() * 1000000; while (!pto->mapAskFor.empty() && (*pto->mapAskFor.begin()).first <= nNow) { const CInv& inv = (*pto->mapAskFor.begin()).second; if (!AlreadyHave(inv)) { if (fDebugNet) printf("sending getdata: %s\n", inv.ToString().c_str()); vGetData.push_back(inv); if (vGetData.size() >= 1000) { pto->PushMessage("getdata", vGetData); vGetData.clear(); } } pto->mapAskFor.erase(pto->mapAskFor.begin()); } if (!vGetData.empty()) pto->PushMessage("getdata", vGetData); } return true; } ////////////////////////////////////////////////////////////////////////////// // // BitcoinMiner // int static FormatHashBlocks(void* pbuffer, unsigned int len) { unsigned char* pdata = (unsigned char*)pbuffer; unsigned int blocks = 1 + ((len + 8) / 64); unsigned char* pend = pdata + 64 * blocks; memset(pdata + len, 0, 64 * blocks - len); pdata[len] = 0x80; unsigned int bits = len * 8; pend[-1] = (bits >> 0) & 0xff; pend[-2] = (bits >> 8) & 0xff; pend[-3] = (bits >> 16) & 0xff; pend[-4] = (bits >> 24) & 0xff; return blocks; } static const unsigned int pSHA256InitState[8] = {0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19}; void SHA256Transform(void* pstate, void* pinput, const void* pinit) { SHA256_CTX ctx; unsigned char data[64]; SHA256_Init(&ctx); for (int i = 0; i < 16; i++) ((uint32_t*)data)[i] = ByteReverse(((uint32_t*)pinput)[i]); for (int i = 0; i < 8; i++) ctx.h[i] = ((uint32_t*)pinit)[i]; SHA256_Update(&ctx, data, sizeof(data)); for (int i = 0; i < 8; i++) ((uint32_t*)pstate)[i] = ctx.h[i]; } // // ScanHash scans nonces looking for a hash with at least some zero bits. // It operates on big endian data. Caller does the byte reversing. // All input buffers are 16-byte aligned. nNonce is usually preserved // between calls, but periodically or if nNonce is 0xffff0000 or above, // the block is rebuilt and nNonce starts over at zero. // unsigned int static ScanHash_CryptoPP(char* pmidstate, char* pdata, char* phash1, char* phash, unsigned int& nHashesDone) { unsigned int& nNonce = *(unsigned int*)(pdata + 12); for (;;) { // Crypto++ SHA256 // Hash pdata using pmidstate as the starting state into // pre-formatted buffer phash1, then hash phash1 into phash nNonce++; SHA256Transform(phash1, pdata, pmidstate); SHA256Transform(phash, phash1, pSHA256InitState); // Return the nonce if the hash has at least some zero bits, // caller will check if it has enough to reach the target if (((unsigned short*)phash)[14] == 0) return nNonce; // If nothing found after trying for a while, return -1 if ((nNonce & 0xffff) == 0) { nHashesDone = 0xffff+1; return (unsigned int) -1; } if ((nNonce & 0xfff) == 0) boost::this_thread::interruption_point(); } } // Some explaining would be appreciated class COrphan { public: CTransaction* ptx; set<uint256> setDependsOn; double dPriority; double dFeePerKb; COrphan(CTransaction* ptxIn) { ptx = ptxIn; dPriority = dFeePerKb = 0; } void print() const { printf("COrphan(hash=%s, dPriority=%.1f, dFeePerKb=%.1f)\n", ptx->GetHash().ToString().c_str(), dPriority, dFeePerKb); BOOST_FOREACH(uint256 hash, setDependsOn) printf(" setDependsOn %s\n", hash.ToString().c_str()); } }; uint64 nLastBlockTx = 0; uint64 nLastBlockSize = 0; // We want to sort transactions by priority and fee, so: typedef boost::tuple<double, double, CTransaction*> TxPriority; class TxPriorityCompare { bool byFee; public: TxPriorityCompare(bool _byFee) : byFee(_byFee) { } bool operator()(const TxPriority& a, const TxPriority& b) { if (byFee) { if (a.get<1>() == b.get<1>()) return a.get<0>() < b.get<0>(); return a.get<1>() < b.get<1>(); } else { if (a.get<0>() == b.get<0>()) return a.get<1>() < b.get<1>(); return a.get<0>() < b.get<0>(); } } }; CBlockTemplate* CreateNewBlock(CReserveKey& reservekey) { // Create new block auto_ptr<CBlockTemplate> pblocktemplate(new CBlockTemplate()); if(!pblocktemplate.get()) return NULL; CBlock *pblock = &pblocktemplate->block; // pointer for convenience // Create coinbase tx CTransaction txNew; txNew.vin.resize(1); txNew.vin[0].prevout.SetNull(); txNew.vout.resize(1); CPubKey pubkey; if (!reservekey.GetReservedKey(pubkey)) return NULL; txNew.vout[0].scriptPubKey << pubkey << OP_CHECKSIG; // Add our coinbase tx as first transaction pblock->vtx.push_back(txNew); pblocktemplate->vTxFees.push_back(-1); // updated at end pblocktemplate->vTxSigOps.push_back(-1); // updated at end // Largest block you're willing to create: unsigned int nBlockMaxSize = GetArg("-blockmaxsize", MAX_BLOCK_SIZE_GEN/2); // Limit to betweeen 1K and MAX_BLOCK_SIZE-1K for sanity: nBlockMaxSize = std::max((unsigned int)1000, std::min((unsigned int)(MAX_BLOCK_SIZE-1000), nBlockMaxSize)); // How much of the block should be dedicated to high-priority transactions, // included regardless of the fees they pay unsigned int nBlockPrioritySize = GetArg("-blockprioritysize", DEFAULT_BLOCK_PRIORITY_SIZE); nBlockPrioritySize = std::min(nBlockMaxSize, nBlockPrioritySize); // Minimum block size you want to create; block will be filled with free transactions // until there are no more or the block reaches this size: unsigned int nBlockMinSize = GetArg("-blockminsize", 0); nBlockMinSize = std::min(nBlockMaxSize, nBlockMinSize); // Collect memory pool transactions into the block int64 nFees = 0; { LOCK2(cs_main, mempool.cs); CBlockIndex* pindexPrev = pindexBest; CCoinsViewCache view(*pcoinsTip, true); // Priority order to process transactions list<COrphan> vOrphan; // list memory doesn't move map<uint256, vector<COrphan*> > mapDependers; bool fPrintPriority = GetBoolArg("-printpriority", false); // This vector will be sorted into a priority queue: vector<TxPriority> vecPriority; vecPriority.reserve(mempool.mapTx.size()); for (map<uint256, CTransaction>::iterator mi = mempool.mapTx.begin(); mi != mempool.mapTx.end(); ++mi) { CTransaction& tx = (*mi).second; if (tx.IsCoinBase() || !IsFinalTx(tx)) continue; COrphan* porphan = NULL; double dPriority = 0; int64 nTotalIn = 0; bool fMissingInputs = false; BOOST_FOREACH(const CTxIn& txin, tx.vin) { // Read prev transaction if (!view.HaveCoins(txin.prevout.hash)) { // This should never happen; all transactions in the memory // pool should connect to either transactions in the chain // or other transactions in the memory pool. if (!mempool.mapTx.count(txin.prevout.hash)) { printf("ERROR: mempool transaction missing input\n"); if (fDebug) assert("mempool transaction missing input" == 0); fMissingInputs = true; if (porphan) vOrphan.pop_back(); break; } // Has to wait for dependencies if (!porphan) { // Use list for automatic deletion vOrphan.push_back(COrphan(&tx)); porphan = &vOrphan.back(); } mapDependers[txin.prevout.hash].push_back(porphan); porphan->setDependsOn.insert(txin.prevout.hash); nTotalIn += mempool.mapTx[txin.prevout.hash].vout[txin.prevout.n].nValue; continue; } const CCoins &coins = view.GetCoins(txin.prevout.hash); int64 nValueIn = coins.vout[txin.prevout.n].nValue; nTotalIn += nValueIn; int nConf = pindexPrev->nHeight - coins.nHeight + 1; dPriority += (double)nValueIn * nConf; } if (fMissingInputs) continue; // Priority is sum(valuein * age) / txsize unsigned int nTxSize = ::GetSerializeSize(tx, SER_NETWORK, PROTOCOL_VERSION); dPriority /= nTxSize; // This is a more accurate fee-per-kilobyte than is used by the client code, because the // client code rounds up the size to the nearest 1K. That's good, because it gives an // incentive to create smaller transactions. double dFeePerKb = double(nTotalIn-GetValueOut(tx)) / (double(nTxSize)/1000.0); if (porphan) { porphan->dPriority = dPriority; porphan->dFeePerKb = dFeePerKb; } else vecPriority.push_back(TxPriority(dPriority, dFeePerKb, &(*mi).second)); } // Collect transactions into block uint64 nBlockSize = 1000; uint64 nBlockTx = 0; int nBlockSigOps = 100; bool fSortedByFee = (nBlockPrioritySize <= 0); TxPriorityCompare comparer(fSortedByFee); std::make_heap(vecPriority.begin(), vecPriority.end(), comparer); while (!vecPriority.empty()) { // Take highest priority transaction off the priority queue: double dPriority = vecPriority.front().get<0>(); double dFeePerKb = vecPriority.front().get<1>(); CTransaction& tx = *(vecPriority.front().get<2>()); std::pop_heap(vecPriority.begin(), vecPriority.end(), comparer); vecPriority.pop_back(); // Size limits unsigned int nTxSize = ::GetSerializeSize(tx, SER_NETWORK, PROTOCOL_VERSION); if (nBlockSize + nTxSize >= nBlockMaxSize) continue; // Legacy limits on sigOps: unsigned int nTxSigOps = GetLegacySigOpCount(tx); if (nBlockSigOps + nTxSigOps >= MAX_BLOCK_SIGOPS) continue; // Skip free transactions if we're past the minimum block size: if (fSortedByFee && (dFeePerKb < CTransaction::nMinTxFee) && (nBlockSize + nTxSize >= nBlockMinSize)) continue; // Prioritize by fee once past the priority size or we run out of high-priority // transactions: if (!fSortedByFee && ((nBlockSize + nTxSize >= nBlockPrioritySize) || !AllowFree(dPriority))) { fSortedByFee = true; comparer = TxPriorityCompare(fSortedByFee); std::make_heap(vecPriority.begin(), vecPriority.end(), comparer); } if (!view.HaveInputs(tx)) continue; int64 nTxFees = view.GetValueIn(tx)-GetValueOut(tx); nTxSigOps += GetP2SHSigOpCount(tx, view); if (nBlockSigOps + nTxSigOps >= MAX_BLOCK_SIGOPS) continue; CValidationState state; if (!CheckInputs(tx, state, view, true, SCRIPT_VERIFY_P2SH)) continue; CTxUndo txundo; uint256 hash = tx.GetHash(); UpdateCoins(tx, state, view, txundo, pindexPrev->nHeight+1, hash); // Added pblock->vtx.push_back(tx); pblocktemplate->vTxFees.push_back(nTxFees); pblocktemplate->vTxSigOps.push_back(nTxSigOps); nBlockSize += nTxSize; ++nBlockTx; nBlockSigOps += nTxSigOps; nFees += nTxFees; if (fPrintPriority) { printf("priority %.1f feeperkb %.1f txid %s\n", dPriority, dFeePerKb, tx.GetHash().ToString().c_str()); } // Add transactions that depend on this one to the priority queue if (mapDependers.count(hash)) { BOOST_FOREACH(COrphan* porphan, mapDependers[hash]) { if (!porphan->setDependsOn.empty()) { porphan->setDependsOn.erase(hash); if (porphan->setDependsOn.empty()) { vecPriority.push_back(TxPriority(porphan->dPriority, porphan->dFeePerKb, porphan->ptx)); std::push_heap(vecPriority.begin(), vecPriority.end(), comparer); } } } } } nLastBlockTx = nBlockTx; nLastBlockSize = nBlockSize; printf("CreateNewBlock(): total size %"PRI64u"\n", nBlockSize); pblock->vtx[0].vout[0].nValue = GetBlockValue(pindexPrev->nHeight+1, nFees); pblocktemplate->vTxFees[0] = -nFees; // Fill in header pblock->hashPrevBlock = pindexPrev->GetBlockHash(); UpdateTime(*pblock, pindexPrev); pblock->nBits = GetNextWorkRequired(pindexPrev, pblock); pblock->nNonce = 0; pblock->vtx[0].vin[0].scriptSig = CScript() << OP_0 << OP_0; pblocktemplate->vTxSigOps[0] = GetLegacySigOpCount(pblock->vtx[0]); CBlockIndex indexDummy(*pblock); indexDummy.pprev = pindexPrev; indexDummy.nHeight = pindexPrev->nHeight + 1; CCoinsViewCache viewNew(*pcoinsTip, true); CValidationState state; if (!ConnectBlock(*pblock, state, &indexDummy, viewNew, true)) throw std::runtime_error("CreateNewBlock() : ConnectBlock failed"); } return pblocktemplate.release(); } void IncrementExtraNonce(CBlock* pblock, CBlockIndex* pindexPrev, unsigned int& nExtraNonce) { // Update nExtraNonce static uint256 hashPrevBlock; if (hashPrevBlock != pblock->hashPrevBlock) { nExtraNonce = 0; hashPrevBlock = pblock->hashPrevBlock; } ++nExtraNonce; unsigned int nHeight = pindexPrev->nHeight+1; // Height first in coinbase required for block.version=2 pblock->vtx[0].vin[0].scriptSig = (CScript() << nHeight << CBigNum(nExtraNonce)) + COINBASE_FLAGS; assert(pblock->vtx[0].vin[0].scriptSig.size() <= 100); pblock->hashMerkleRoot = pblock->BuildMerkleTree(); } void FormatHashBuffers(CBlock* pblock, char* pmidstate, char* pdata, char* phash1) { // // Pre-build hash buffers // struct { struct unnamed2 { int nVersion; uint256 hashPrevBlock; uint256 hashMerkleRoot; unsigned int nTime; unsigned int nBits; unsigned int nNonce; } block; unsigned char pchPadding0[64]; uint256 hash1; unsigned char pchPadding1[64]; } tmp; memset(&tmp, 0, sizeof(tmp)); tmp.block.nVersion = pblock->nVersion; tmp.block.hashPrevBlock = pblock->hashPrevBlock; tmp.block.hashMerkleRoot = pblock->hashMerkleRoot; tmp.block.nTime = pblock->nTime; tmp.block.nBits = pblock->nBits; tmp.block.nNonce = pblock->nNonce; FormatHashBlocks(&tmp.block, sizeof(tmp.block)); FormatHashBlocks(&tmp.hash1, sizeof(tmp.hash1)); // Byte swap all the input buffer for (unsigned int i = 0; i < sizeof(tmp)/4; i++) ((unsigned int*)&tmp)[i] = ByteReverse(((unsigned int*)&tmp)[i]); // Precalc the first half of the first hash, which stays constant SHA256Transform(pmidstate, &tmp.block, pSHA256InitState); memcpy(pdata, &tmp.block, 128); memcpy(phash1, &tmp.hash1, 64); } bool CheckWork(CBlock* pblock, CWallet& wallet, CReserveKey& reservekey) { uint256 hash = pblock->GetHash(); uint256 hashTarget = CBigNum().SetCompact(pblock->nBits).getuint256(); if (hash > hashTarget) return false; //// debug print printf("ContinuumCoinMiner:\n"); printf("proof-of-work found \n hash: %s \ntarget: %s\n", hash.GetHex().c_str(), hashTarget.GetHex().c_str()); pblock->print(); printf("generated %s\n", FormatMoney(pblock->vtx[0].vout[0].nValue).c_str()); // Found a solution { LOCK(cs_main); if (pblock->hashPrevBlock != hashBestChain) return error("ContinuumCoinMiner : generated block is stale"); // Remove key from key pool reservekey.KeepKey(); // Track how many getdata requests this block gets { LOCK(wallet.cs_wallet); wallet.mapRequestCount[pblock->GetHash()] = 0; } // Process this block the same as if we had received it from another node CValidationState state; if (!ProcessBlock(state, NULL, pblock)) return error("ContinuumCoinMiner : ProcessBlock, block not accepted"); } return true; } void static BitcoinMiner(CWallet *pwallet) { printf("ContinuumCoinMiner started\n"); SetThreadPriority(THREAD_PRIORITY_LOWEST); RenameThread("bitcoin-miner"); // Each thread has its own key and counter CReserveKey reservekey(pwallet); unsigned int nExtraNonce = 0; try { loop { if (Params().NetworkID() != CChainParams::REGTEST) { // Busy-wait for the network to come online so we don't waste time mining // on an obsolete chain. In regtest mode we expect to fly solo. while (vNodes.empty()) MilliSleep(1000); } // // Create new block // unsigned int nTransactionsUpdatedLast = nTransactionsUpdated; CBlockIndex* pindexPrev = pindexBest; auto_ptr<CBlockTemplate> pblocktemplate(CreateNewBlock(reservekey)); if (!pblocktemplate.get()) return; CBlock *pblock = &pblocktemplate->block; IncrementExtraNonce(pblock, pindexPrev, nExtraNonce); printf("Running ContinuumCoinMiner with %"PRIszu" transactions in block (%u bytes)\n", pblock->vtx.size(), ::GetSerializeSize(*pblock, SER_NETWORK, PROTOCOL_VERSION)); // // Pre-build hash buffers // char pmidstatebuf[32+16]; char* pmidstate = alignup<16>(pmidstatebuf); char pdatabuf[128+16]; char* pdata = alignup<16>(pdatabuf); char phash1buf[64+16]; char* phash1 = alignup<16>(phash1buf); FormatHashBuffers(pblock, pmidstate, pdata, phash1); unsigned int& nBlockTime = *(unsigned int*)(pdata + 64 + 4); unsigned int& nBlockBits = *(unsigned int*)(pdata + 64 + 8); unsigned int& nBlockNonce = *(unsigned int*)(pdata + 64 + 12); // // Search // int64 nStart = GetTime(); uint256 hashTarget = CBigNum().SetCompact(pblock->nBits).getuint256(); uint256 hashbuf[2]; uint256& hash = *alignup<16>(hashbuf); loop { unsigned int nHashesDone = 0; unsigned int nNonceFound; // Crypto++ SHA256 nNonceFound = ScanHash_CryptoPP(pmidstate, pdata + 64, phash1, (char*)&hash, nHashesDone); // Check if something found if (nNonceFound != (unsigned int) -1) { for (unsigned int i = 0; i < sizeof(hash)/4; i++) ((unsigned int*)&hash)[i] = ByteReverse(((unsigned int*)&hash)[i]); if (hash <= hashTarget) { // Found a solution pblock->nNonce = ByteReverse(nNonceFound); assert(hash == pblock->GetHash()); SetThreadPriority(THREAD_PRIORITY_NORMAL); CheckWork(pblock, *pwalletMain, reservekey); SetThreadPriority(THREAD_PRIORITY_LOWEST); // In regression test mode, stop mining after a block is found. This // allows developers to controllably generate a block on demand. if (Params().NetworkID() == CChainParams::REGTEST) throw boost::thread_interrupted(); break; } } // Meter hashes/sec static int64 nHashCounter; if (nHPSTimerStart == 0) { nHPSTimerStart = GetTimeMillis(); nHashCounter = 0; } else nHashCounter += nHashesDone; if (GetTimeMillis() - nHPSTimerStart > 4000) { static CCriticalSection cs; { LOCK(cs); if (GetTimeMillis() - nHPSTimerStart > 4000) { dHashesPerSec = 1000.0 * nHashCounter / (GetTimeMillis() - nHPSTimerStart); nHPSTimerStart = GetTimeMillis(); nHashCounter = 0; static int64 nLogTime; if (GetTime() - nLogTime > 30 * 60) { nLogTime = GetTime(); printf("hashmeter %6.0f khash/s\n", dHashesPerSec/1000.0); } } } } // Check for stop or if block needs to be rebuilt boost::this_thread::interruption_point(); if (vNodes.empty() && Params().NetworkID() != CChainParams::REGTEST) break; if (nBlockNonce >= 0xffff0000) break; if (nTransactionsUpdated != nTransactionsUpdatedLast && GetTime() - nStart > 60) break; if (pindexPrev != pindexBest) break; // Update nTime every few seconds UpdateTime(*pblock, pindexPrev); nBlockTime = ByteReverse(pblock->nTime); if (TestNet()) { // Changing pblock->nTime can change work required on testnet: nBlockBits = ByteReverse(pblock->nBits); hashTarget = CBigNum().SetCompact(pblock->nBits).getuint256(); } } } } catch (boost::thread_interrupted) { printf("ContinuumCoinMiner terminated\n"); throw; } } void GenerateBitcoins(bool fGenerate, CWallet* pwallet) { static boost::thread_group* minerThreads = NULL; int nThreads = GetArg("-genproclimit", -1); if (nThreads < 0) { if (Params().NetworkID() == CChainParams::REGTEST) nThreads = 1; else nThreads = boost::thread::hardware_concurrency(); } if (minerThreads != NULL) { minerThreads->interrupt_all(); delete minerThreads; minerThreads = NULL; } if (nThreads == 0 || !fGenerate) return; minerThreads = new boost::thread_group(); for (int i = 0; i < nThreads; i++) minerThreads->create_thread(boost::bind(&BitcoinMiner, pwallet)); } class CMainCleanup { public: CMainCleanup() {} ~CMainCleanup() { // block headers std::map<uint256, CBlockIndex*>::iterator it1 = mapBlockIndex.begin(); for (; it1 != mapBlockIndex.end(); it1++) delete (*it1).second; mapBlockIndex.clear(); // orphan blocks std::map<uint256, CBlock*>::iterator it2 = mapOrphanBlocks.begin(); for (; it2 != mapOrphanBlocks.end(); it2++) delete (*it2).second; mapOrphanBlocks.clear(); // orphan transactions std::map<uint256, CDataStream*>::iterator it3 = mapOrphanTransactions.begin(); for (; it3 != mapOrphanTransactions.end(); it3++) delete (*it3).second; mapOrphanTransactions.clear(); } } instance_of_cmaincleanup;
{'content_hash': 'bdc8afa52858a5c1f481a39a7c7e0365', 'timestamp': '', 'source': 'github', 'line_count': 4939, 'max_line_length': 237, 'avg_line_length': 35.52237294998988, 'alnum_prop': 0.588514919205449, 'repo_name': 'continuumcoin/CTM', 'id': 'e4774974afd6223375d37020759c2ca980d22e55', 'size': '175445', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'src/main.cpp', 'mode': '33261', 'license': 'mit', 'language': [{'name': 'C', 'bytes': '102674'}, {'name': 'C++', 'bytes': '13319852'}, {'name': 'CSS', 'bytes': '1127'}, {'name': 'IDL', 'bytes': '13858'}, {'name': 'Nu', 'bytes': '264'}, {'name': 'Objective-C', 'bytes': '5711'}, {'name': 'Perl', 'bytes': '12210'}, {'name': 'Python', 'bytes': '3773'}, {'name': 'Shell', 'bytes': '8172'}, {'name': 'TypeScript', 'bytes': '5258516'}]}
<?php //require_once('includes/checksession.php'); require_once('includes/connection.php'); require_once('includes/template.php'); /*require_once('includes/func.getUserID.php'); $id_user = getUserID($connection); if (!$id_user){ echo 'Error: login'; exit(); }*/ openHeader('Project XYZ', '/project-xyz/styles/styles.css'); openBody('Categorias disponibles','mainPage', $connection); $query = <<<EOD SELECT * FROM categories_photos cp, photos p WHERE p.id_photo=cp.id_photo AND p.status_photo=1 ORDER BY cp.id_category_photo ASC EOD; if(!($res = mysql_query($query, $connection))){ echo 'KO'; exit(); } $array_cat_photo = array(); while ($file = mysql_fetch_assoc($res)){ $array_cat_photo[$file['id_category']] = $file['name_photo']; } $query = <<<EOD SELECT * FROM categories WHERE status = 1 ORDER BY name_category EOD; $res = mysql_query($query,$connection); $categoryList = ''; while ($category = mysql_fetch_assoc($res)){ $photo = $array_cat_photo[$category['id_category']]; $id_category = $category['id_category']; $categoryList .= <<<EOD <div class="category"> <a href="categories_games.php?id_category={$id_category}"><img class="image_category" src="images/{$photo}" /><p class="name_category" rel="{$category['id_category']}">{$category['name_category']}</p></a> </div> EOD; } ?> <div id="global_category"> <?php echo $categoryList; ?> </div> <?php closeBody(); ?>
{'content_hash': '18ca79c16374c24b07eaf9ac28155ce5', 'timestamp': '', 'source': 'github', 'line_count': 64, 'max_line_length': 205, 'avg_line_length': 21.75, 'alnum_prop': 0.6745689655172413, 'repo_name': 'csalva/project-XYZ', 'id': 'b503d318b3851f3e4f68a209b405bb2262eb9884', 'size': '1392', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'categories.php', 'mode': '33261', 'license': 'mit', 'language': [{'name': 'CSS', 'bytes': '101093'}, {'name': 'Java', 'bytes': '40505'}, {'name': 'JavaScript', 'bytes': '613372'}, {'name': 'PHP', 'bytes': '1195636'}, {'name': 'Perl', 'bytes': '26'}, {'name': 'Rust', 'bytes': '231'}]}
Currency.create currency: 'USD' Currency.create currency: 'EUR' OptionType.create option_type: 'ETO' OptionType.create option_type: 'OTC' QuoteName.create quote_name: 'IPE Brent' QuoteName.create quote_name: 'IPE Gas Oil' QuoteName.create quote_name: 'NYMEX WTI' QuoteName.create quote_name: 'NYMEX Heat' QuoteName.create quote_name: 'NYMEX Brent' QuoteName.create quote_name: 'NYMEX RBOB' QuoteName.create quote_name: 'ICE WTI' QuoteName.create quote_name: 'ICE RBOB' QuoteName.create quote_name: 'ICE Heat'
{'content_hash': '6fdec2d2a83f183aed7128f53be4c040', 'timestamp': '', 'source': 'github', 'line_count': 16, 'max_line_length': 42, 'avg_line_length': 32.0, 'alnum_prop': 0.775390625, 'repo_name': 'lshift/diffa-rails-adapter-tutorial', 'id': '85ec0065d7930e178f7fe1def7aa09949e7a3d0e', 'size': '855', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'db/seeds.rb', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'JavaScript', 'bytes': '189937'}, {'name': 'Ruby', 'bytes': '47872'}]}
// # Client API // RESTful API for the Client resource var Promise = require('bluebird'), _ = require('lodash'), pipeline = require('../utils/pipeline'), apiUtils = require('./utils'), models = require('../models'), common = require('../lib/common'), docName = 'clients', clients; /** * ### Clients API Methods * * **See:** [API Methods](events.js.html#api%20methods) */ clients = { /** * ## Read * @param {{id}} options * @return {Promise<Client>} Client */ read: function read(options) { var attrs = ['id', 'slug'], tasks; /** * ### Model Query * Make the call to the Model layer * @param {Object} options * @returns {Object} options */ function doQuery(options) { // only User Agent (type = `ua`) clients are available at the moment. options.data = _.extend(options.data, {type: 'ua'}); return models.Client.findOne(options.data, _.omit(options, ['data'])) .then(function onModelResponse(model) { if (!model) { return Promise.reject(new common.errors.NotFoundError({ message: common.i18n.t('common.api.clients.clientNotFound') })); } return { clients: [model.toJSON(options)] }; }); } // Push all of our tasks into a `tasks` array in the correct order tasks = [ apiUtils.validate(docName, {attrs: attrs}), // TODO: add permissions // utils.handlePublicPermissions(docName, 'read'), doQuery ]; // Pipeline calls each task passing the result of one to be the arguments for the next return pipeline(tasks, options); } }; module.exports = clients;
{'content_hash': '42dce0018ae9c1a2b51b6b58ccbf5497', 'timestamp': '', 'source': 'github', 'line_count': 65, 'max_line_length': 94, 'avg_line_length': 29.907692307692308, 'alnum_prop': 0.5108024691358025, 'repo_name': 'kpsuperplane/personal-website', 'id': 'c511da4a618e7a01c1b63f38f421906783a246b8', 'size': '1944', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'versions/1.19.0/core/server/api/clients.js', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'CSS', 'bytes': '18318'}, {'name': 'HTML', 'bytes': '139091'}, {'name': 'Handlebars', 'bytes': '48136'}, {'name': 'JavaScript', 'bytes': '950569'}, {'name': 'Procfile', 'bytes': '14'}, {'name': 'SCSS', 'bytes': '36725'}, {'name': 'Shell', 'bytes': '483'}, {'name': 'TypeScript', 'bytes': '67274'}, {'name': 'XSLT', 'bytes': '7177'}]}
<?xml version="1.0" ?><!DOCTYPE TS><TS language="fr_CA" version="2.0"> <defaultcodec>UTF-8</defaultcodec> <context> <name>AboutDialog</name> <message> <location filename="../forms/aboutdialog.ui" line="+14"/> <source>About potatocoin</source> <translation>A propos de potatocoin</translation> </message> <message> <location line="+39"/> <source>&lt;b&gt;potatocoin&lt;/b&gt; version</source> <translation>&lt;b&gt;potatocoin&lt;/b&gt; version</translation> </message> <message> <location line="+57"/> <source> This is experimental software. Distributed under the MIT/X11 software license, see the accompanying file COPYING or http://www.opensource.org/licenses/mit-license.php. This product includes software developed by the OpenSSL Project for use in the OpenSSL Toolkit (http://www.openssl.org/) and cryptographic software written by Eric Young ([email protected]) and UPnP software written by Thomas Bernard.</source> <translation> Ce logiciel est en phase expérimentale. Distribué sous licence MIT/X11, voir le fichier COPYING ou http://www.opensource.org/licenses/mit-license.php. Ce produit comprend des logiciels développés par le projet OpenSSL pour être utilisés dans la boîte à outils OpenSSL (http://www.openssl.org/), un logiciel cryptographique écrit par Eric Young ([email protected]) et un logiciel UPnP écrit par Thomas Bernard.</translation> </message> <message> <location filename="../aboutdialog.cpp" line="+14"/> <source>Copyright</source> <translation type="unfinished"/> </message> <message> <location line="+0"/> <source>The potatocoin developers</source> <translation type="unfinished"/> </message> </context> <context> <name>AddressBookPage</name> <message> <location filename="../forms/addressbookpage.ui" line="+14"/> <source>Address Book</source> <translation>Carnet d&apos;adresses</translation> </message> <message> <location line="+19"/> <source>Double-click to edit address or label</source> <translation>Double-cliquez afin de modifier l&apos;adress ou l&apos;étiquette</translation> </message> <message> <location line="+27"/> <source>Create a new address</source> <translation>Créer une nouvelle adresse</translation> </message> <message> <location line="+14"/> <source>Copy the currently selected address to the system clipboard</source> <translation>Copier l&apos;adresse surligné a votre presse-papier</translation> </message> <message> <location line="-11"/> <source>&amp;New Address</source> <translation type="unfinished"/> </message> <message> <location filename="../addressbookpage.cpp" line="+63"/> <source>These are your potatocoin addresses for receiving payments. You may want to give a different one to each sender so you can keep track of who is paying you.</source> <translation>Ceux-ci sont vos adresses potatocoin qui vous permettent de recevoir des paiements. Vous pouvez en donner une différente à chaque expédieur afin de savoir qui vous payent.</translation> </message> <message> <location filename="../forms/addressbookpage.ui" line="+14"/> <source>&amp;Copy Address</source> <translation type="unfinished"/> </message> <message> <location line="+11"/> <source>Show &amp;QR Code</source> <translation type="unfinished"/> </message> <message> <location line="+11"/> <source>Sign a message to prove you own a potatocoin address</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Sign &amp;Message</source> <translation type="unfinished"/> </message> <message> <location line="+25"/> <source>Delete the currently selected address from the list</source> <translation type="unfinished"/> </message> <message> <location line="+27"/> <source>Export the data in the current tab to a file</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>&amp;Export</source> <translation type="unfinished"/> </message> <message> <location line="-44"/> <source>Verify a message to ensure it was signed with a specified potatocoin address</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>&amp;Verify Message</source> <translation type="unfinished"/> </message> <message> <location line="+14"/> <source>&amp;Delete</source> <translation>&amp;Supprimer</translation> </message> <message> <location filename="../addressbookpage.cpp" line="-5"/> <source>These are your potatocoin addresses for sending payments. Always check the amount and the receiving address before sending coins.</source> <translation type="unfinished"/> </message> <message> <location line="+13"/> <source>Copy &amp;Label</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>&amp;Edit</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Send &amp;Coins</source> <translation type="unfinished"/> </message> <message> <location line="+260"/> <source>Export Address Book Data</source> <translation>Exporter les données du carnet d&apos;adresses</translation> </message> <message> <location line="+1"/> <source>Comma separated file (*.csv)</source> <translation type="unfinished"/> </message> <message> <location line="+13"/> <source>Error exporting</source> <translation type="unfinished"/> </message> <message> <location line="+0"/> <source>Could not write to file %1.</source> <translation type="unfinished"/> </message> </context> <context> <name>AddressTableModel</name> <message> <location filename="../addresstablemodel.cpp" line="+144"/> <source>Label</source> <translation type="unfinished"/> </message> <message> <location line="+0"/> <source>Address</source> <translation type="unfinished"/> </message> <message> <location line="+36"/> <source>(no label)</source> <translation type="unfinished"/> </message> </context> <context> <name>AskPassphraseDialog</name> <message> <location filename="../forms/askpassphrasedialog.ui" line="+26"/> <source>Passphrase Dialog</source> <translation type="unfinished"/> </message> <message> <location line="+21"/> <source>Enter passphrase</source> <translation type="unfinished"/> </message> <message> <location line="+14"/> <source>New passphrase</source> <translation type="unfinished"/> </message> <message> <location line="+14"/> <source>Repeat new passphrase</source> <translation type="unfinished"/> </message> <message> <location filename="../askpassphrasedialog.cpp" line="+33"/> <source>Enter the new passphrase to the wallet.&lt;br/&gt;Please use a passphrase of &lt;b&gt;10 or more random characters&lt;/b&gt;, or &lt;b&gt;eight or more words&lt;/b&gt;.</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Encrypt wallet</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>This operation needs your wallet passphrase to unlock the wallet.</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <source>Unlock wallet</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>This operation needs your wallet passphrase to decrypt the wallet.</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <source>Decrypt wallet</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Change passphrase</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Enter the old and new passphrase to the wallet.</source> <translation type="unfinished"/> </message> <message> <location line="+46"/> <source>Confirm wallet encryption</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Warning: If you encrypt your wallet and lose your passphrase, you will &lt;b&gt;LOSE ALL OF YOUR DARKCOINS&lt;/b&gt;!</source> <translation type="unfinished"/> </message> <message> <location line="+0"/> <source>Are you sure you wish to encrypt your wallet?</source> <translation type="unfinished"/> </message> <message> <location line="+15"/> <source>IMPORTANT: Any previous backups you have made of your wallet file should be replaced with the newly generated, encrypted wallet file. For security reasons, previous backups of the unencrypted wallet file will become useless as soon as you start using the new, encrypted wallet.</source> <translation type="unfinished"/> </message> <message> <location line="+100"/> <location line="+24"/> <source>Warning: The Caps Lock key is on!</source> <translation type="unfinished"/> </message> <message> <location line="-130"/> <location line="+58"/> <source>Wallet encrypted</source> <translation type="unfinished"/> </message> <message> <location line="-56"/> <source>potatocoin will close now to finish the encryption process. Remember that encrypting your wallet cannot fully protect your potatocoins from being stolen by malware infecting your computer.</source> <translation type="unfinished"/> </message> <message> <location line="+13"/> <location line="+7"/> <location line="+42"/> <location line="+6"/> <source>Wallet encryption failed</source> <translation type="unfinished"/> </message> <message> <location line="-54"/> <source>Wallet encryption failed due to an internal error. Your wallet was not encrypted.</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <location line="+48"/> <source>The supplied passphrases do not match.</source> <translation type="unfinished"/> </message> <message> <location line="-37"/> <source>Wallet unlock failed</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <location line="+11"/> <location line="+19"/> <source>The passphrase entered for the wallet decryption was incorrect.</source> <translation type="unfinished"/> </message> <message> <location line="-20"/> <source>Wallet decryption failed</source> <translation type="unfinished"/> </message> <message> <location line="+14"/> <source>Wallet passphrase was successfully changed.</source> <translation type="unfinished"/> </message> </context> <context> <name>BitcoinGUI</name> <message> <location filename="../bitcoingui.cpp" line="+233"/> <source>Sign &amp;message...</source> <translation type="unfinished"/> </message> <message> <location line="+280"/> <source>Synchronizing with network...</source> <translation type="unfinished"/> </message> <message> <location line="-349"/> <source>&amp;Overview</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Show general overview of wallet</source> <translation type="unfinished"/> </message> <message> <location line="+20"/> <source>&amp;Transactions</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Browse transaction history</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>Edit the list of stored addresses and labels</source> <translation type="unfinished"/> </message> <message> <location line="-14"/> <source>Show the list of addresses for receiving payments</source> <translation type="unfinished"/> </message> <message> <location line="+31"/> <source>E&amp;xit</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Quit application</source> <translation type="unfinished"/> </message> <message> <location line="+4"/> <source>Show information about potatocoin</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>About &amp;Qt</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Show information about Qt</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>&amp;Options...</source> <translation type="unfinished"/> </message> <message> <location line="+6"/> <source>&amp;Encrypt Wallet...</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>&amp;Backup Wallet...</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>&amp;Change Passphrase...</source> <translation type="unfinished"/> </message> <message> <location line="+285"/> <source>Importing blocks from disk...</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Reindexing blocks on disk...</source> <translation type="unfinished"/> </message> <message> <location line="-347"/> <source>Send coins to a potatocoin address</source> <translation type="unfinished"/> </message> <message> <location line="+49"/> <source>Modify configuration options for potatocoin</source> <translation type="unfinished"/> </message> <message> <location line="+9"/> <source>Backup wallet to another location</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Change the passphrase used for wallet encryption</source> <translation type="unfinished"/> </message> <message> <location line="+6"/> <source>&amp;Debug window</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Open debugging and diagnostic console</source> <translation type="unfinished"/> </message> <message> <location line="-4"/> <source>&amp;Verify message...</source> <translation type="unfinished"/> </message> <message> <location line="-165"/> <location line="+530"/> <source>potatocoin</source> <translation type="unfinished"/> </message> <message> <location line="-530"/> <source>Wallet</source> <translation type="unfinished"/> </message> <message> <location line="+101"/> <source>&amp;Send</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>&amp;Receive</source> <translation type="unfinished"/> </message> <message> <location line="+14"/> <source>&amp;Addresses</source> <translation type="unfinished"/> </message> <message> <location line="+22"/> <source>&amp;About potatocoin</source> <translation>&amp;A propos de potatocoin</translation> </message> <message> <location line="+9"/> <source>&amp;Show / Hide</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Show or hide the main Window</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Encrypt the private keys that belong to your wallet</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>Sign messages with your potatocoin addresses to prove you own them</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Verify messages to ensure they were signed with specified potatocoin addresses</source> <translation type="unfinished"/> </message> <message> <location line="+28"/> <source>&amp;File</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>&amp;Settings</source> <translation type="unfinished"/> </message> <message> <location line="+6"/> <source>&amp;Help</source> <translation type="unfinished"/> </message> <message> <location line="+9"/> <source>Tabs toolbar</source> <translation type="unfinished"/> </message> <message> <location line="+17"/> <location line="+10"/> <source>[testnet]</source> <translation type="unfinished"/> </message> <message> <location line="+47"/> <source>potatocoin client</source> <translation type="unfinished"/> </message> <message numerus="yes"> <location line="+141"/> <source>%n active connection(s) to potatocoin network</source> <translation type="unfinished"><numerusform></numerusform><numerusform></numerusform></translation> </message> <message> <location line="+22"/> <source>No block source available...</source> <translation type="unfinished"/> </message> <message> <location line="+12"/> <source>Processed %1 of %2 (estimated) blocks of transaction history.</source> <translation type="unfinished"/> </message> <message> <location line="+4"/> <source>Processed %1 blocks of transaction history.</source> <translation type="unfinished"/> </message> <message numerus="yes"> <location line="+20"/> <source>%n hour(s)</source> <translation type="unfinished"><numerusform></numerusform><numerusform></numerusform></translation> </message> <message numerus="yes"> <location line="+4"/> <source>%n day(s)</source> <translation type="unfinished"><numerusform></numerusform><numerusform></numerusform></translation> </message> <message numerus="yes"> <location line="+4"/> <source>%n week(s)</source> <translation type="unfinished"><numerusform></numerusform><numerusform></numerusform></translation> </message> <message> <location line="+4"/> <source>%1 behind</source> <translation type="unfinished"/> </message> <message> <location line="+14"/> <source>Last received block was generated %1 ago.</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Transactions after this will not yet be visible.</source> <translation type="unfinished"/> </message> <message> <location line="+22"/> <source>Error</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Warning</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Information</source> <translation type="unfinished"/> </message> <message> <location line="+70"/> <source>This transaction is over the size limit. You can still send it for a fee of %1, which goes to the nodes that process your transaction and helps to support the network. Do you want to pay the fee?</source> <translation type="unfinished"/> </message> <message> <location line="-140"/> <source>Up to date</source> <translation type="unfinished"/> </message> <message> <location line="+31"/> <source>Catching up...</source> <translation type="unfinished"/> </message> <message> <location line="+113"/> <source>Confirm transaction fee</source> <translation type="unfinished"/> </message> <message> <location line="+8"/> <source>Sent transaction</source> <translation type="unfinished"/> </message> <message> <location line="+0"/> <source>Incoming transaction</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Date: %1 Amount: %2 Type: %3 Address: %4 </source> <translation type="unfinished"/> </message> <message> <location line="+33"/> <location line="+23"/> <source>URI handling</source> <translation type="unfinished"/> </message> <message> <location line="-23"/> <location line="+23"/> <source>URI can not be parsed! This can be caused by an invalid potatocoin address or malformed URI parameters.</source> <translation type="unfinished"/> </message> <message> <location line="+17"/> <source>Wallet is &lt;b&gt;encrypted&lt;/b&gt; and currently &lt;b&gt;unlocked&lt;/b&gt;</source> <translation type="unfinished"/> </message> <message> <location line="+8"/> <source>Wallet is &lt;b&gt;encrypted&lt;/b&gt; and currently &lt;b&gt;locked&lt;/b&gt;</source> <translation type="unfinished"/> </message> <message> <location filename="../bitcoin.cpp" line="+111"/> <source>A fatal error occurred. potatocoin can no longer continue safely and will quit.</source> <translation type="unfinished"/> </message> </context> <context> <name>ClientModel</name> <message> <location filename="../clientmodel.cpp" line="+104"/> <source>Network Alert</source> <translation type="unfinished"/> </message> </context> <context> <name>EditAddressDialog</name> <message> <location filename="../forms/editaddressdialog.ui" line="+14"/> <source>Edit Address</source> <translation type="unfinished"/> </message> <message> <location line="+11"/> <source>&amp;Label</source> <translation type="unfinished"/> </message> <message> <location line="+10"/> <source>The label associated with this address book entry</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>&amp;Address</source> <translation type="unfinished"/> </message> <message> <location line="+10"/> <source>The address associated with this address book entry. This can only be modified for sending addresses.</source> <translation type="unfinished"/> </message> <message> <location filename="../editaddressdialog.cpp" line="+21"/> <source>New receiving address</source> <translation type="unfinished"/> </message> <message> <location line="+4"/> <source>New sending address</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Edit receiving address</source> <translation type="unfinished"/> </message> <message> <location line="+4"/> <source>Edit sending address</source> <translation type="unfinished"/> </message> <message> <location line="+76"/> <source>The entered address &quot;%1&quot; is already in the address book.</source> <translation type="unfinished"/> </message> <message> <location line="-5"/> <source>The entered address &quot;%1&quot; is not a valid potatocoin address.</source> <translation type="unfinished"/> </message> <message> <location line="+10"/> <source>Could not unlock wallet.</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <source>New key generation failed.</source> <translation type="unfinished"/> </message> </context> <context> <name>GUIUtil::HelpMessageBox</name> <message> <location filename="../guiutil.cpp" line="+424"/> <location line="+12"/> <source>potatocoin-Qt</source> <translation type="unfinished"/> </message> <message> <location line="-12"/> <source>version</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Usage:</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>command-line options</source> <translation type="unfinished"/> </message> <message> <location line="+4"/> <source>UI options</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Set language, for example &quot;de_DE&quot; (default: system locale)</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Start minimized</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Show splash screen on startup (default: 1)</source> <translation type="unfinished"/> </message> </context> <context> <name>OptionsDialog</name> <message> <location filename="../forms/optionsdialog.ui" line="+14"/> <source>Options</source> <translation type="unfinished"/> </message> <message> <location line="+16"/> <source>&amp;Main</source> <translation type="unfinished"/> </message> <message> <location line="+6"/> <source>Optional transaction fee per kB that helps make sure your transactions are processed quickly. Most transactions are 1 kB.</source> <translation type="unfinished"/> </message> <message> <location line="+15"/> <source>Pay transaction &amp;fee</source> <translation type="unfinished"/> </message> <message> <location line="+31"/> <source>Automatically start potatocoin after logging in to the system.</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>&amp;Start potatocoin on system login</source> <translation type="unfinished"/> </message> <message> <location line="+35"/> <source>Reset all client options to default.</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>&amp;Reset Options</source> <translation type="unfinished"/> </message> <message> <location line="+13"/> <source>&amp;Network</source> <translation type="unfinished"/> </message> <message> <location line="+6"/> <source>Automatically open the potatocoin client port on the router. This only works when your router supports UPnP and it is enabled.</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Map port using &amp;UPnP</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>Connect to the potatocoin network through a SOCKS proxy (e.g. when connecting through Tor).</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>&amp;Connect through SOCKS proxy:</source> <translation type="unfinished"/> </message> <message> <location line="+9"/> <source>Proxy &amp;IP:</source> <translation type="unfinished"/> </message> <message> <location line="+19"/> <source>IP address of the proxy (e.g. 127.0.0.1)</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>&amp;Port:</source> <translation type="unfinished"/> </message> <message> <location line="+19"/> <source>Port of the proxy (e.g. 9050)</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>SOCKS &amp;Version:</source> <translation type="unfinished"/> </message> <message> <location line="+13"/> <source>SOCKS version of the proxy (e.g. 5)</source> <translation type="unfinished"/> </message> <message> <location line="+36"/> <source>&amp;Window</source> <translation type="unfinished"/> </message> <message> <location line="+6"/> <source>Show only a tray icon after minimizing the window.</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>&amp;Minimize to the tray instead of the taskbar</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>Minimize instead of exit the application when the window is closed. When this option is enabled, the application will be closed only after selecting Quit in the menu.</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>M&amp;inimize on close</source> <translation type="unfinished"/> </message> <message> <location line="+21"/> <source>&amp;Display</source> <translation type="unfinished"/> </message> <message> <location line="+8"/> <source>User Interface &amp;language:</source> <translation type="unfinished"/> </message> <message> <location line="+13"/> <source>The user interface language can be set here. This setting will take effect after restarting potatocoin.</source> <translation type="unfinished"/> </message> <message> <location line="+11"/> <source>&amp;Unit to show amounts in:</source> <translation type="unfinished"/> </message> <message> <location line="+13"/> <source>Choose the default subdivision unit to show in the interface and when sending coins.</source> <translation type="unfinished"/> </message> <message> <location line="+9"/> <source>Whether to show potatocoin addresses in the transaction list or not.</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>&amp;Display addresses in transaction list</source> <translation type="unfinished"/> </message> <message> <location line="+71"/> <source>&amp;OK</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>&amp;Cancel</source> <translation type="unfinished"/> </message> <message> <location line="+10"/> <source>&amp;Apply</source> <translation type="unfinished"/> </message> <message> <location filename="../optionsdialog.cpp" line="+53"/> <source>default</source> <translation type="unfinished"/> </message> <message> <location line="+130"/> <source>Confirm options reset</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Some settings may require a client restart to take effect.</source> <translation type="unfinished"/> </message> <message> <location line="+0"/> <source>Do you want to proceed?</source> <translation type="unfinished"/> </message> <message> <location line="+42"/> <location line="+9"/> <source>Warning</source> <translation type="unfinished"/> </message> <message> <location line="-9"/> <location line="+9"/> <source>This setting will take effect after restarting potatocoin.</source> <translation type="unfinished"/> </message> <message> <location line="+29"/> <source>The supplied proxy address is invalid.</source> <translation type="unfinished"/> </message> </context> <context> <name>OverviewPage</name> <message> <location filename="../forms/overviewpage.ui" line="+14"/> <source>Form</source> <translation type="unfinished"/> </message> <message> <location line="+50"/> <location line="+166"/> <source>The displayed information may be out of date. Your wallet automatically synchronizes with the potatocoin network after a connection is established, but this process has not completed yet.</source> <translation type="unfinished"/> </message> <message> <location line="-124"/> <source>Balance:</source> <translation type="unfinished"/> </message> <message> <location line="+29"/> <source>Unconfirmed:</source> <translation type="unfinished"/> </message> <message> <location line="-78"/> <source>Wallet</source> <translation type="unfinished"/> </message> <message> <location line="+107"/> <source>Immature:</source> <translation type="unfinished"/> </message> <message> <location line="+13"/> <source>Mined balance that has not yet matured</source> <translation type="unfinished"/> </message> <message> <location line="+46"/> <source>&lt;b&gt;Recent transactions&lt;/b&gt;</source> <translation type="unfinished"/> </message> <message> <location line="-101"/> <source>Your current balance</source> <translation type="unfinished"/> </message> <message> <location line="+29"/> <source>Total of transactions that have yet to be confirmed, and do not yet count toward the current balance</source> <translation type="unfinished"/> </message> <message> <location filename="../overviewpage.cpp" line="+116"/> <location line="+1"/> <source>out of sync</source> <translation type="unfinished"/> </message> </context> <context> <name>PaymentServer</name> <message> <location filename="../paymentserver.cpp" line="+107"/> <source>Cannot start potatocoin: click-to-pay handler</source> <translation type="unfinished"/> </message> </context> <context> <name>QRCodeDialog</name> <message> <location filename="../forms/qrcodedialog.ui" line="+14"/> <source>QR Code Dialog</source> <translation type="unfinished"/> </message> <message> <location line="+59"/> <source>Request Payment</source> <translation type="unfinished"/> </message> <message> <location line="+56"/> <source>Amount:</source> <translation type="unfinished"/> </message> <message> <location line="-44"/> <source>Label:</source> <translation type="unfinished"/> </message> <message> <location line="+19"/> <source>Message:</source> <translation type="unfinished"/> </message> <message> <location line="+71"/> <source>&amp;Save As...</source> <translation type="unfinished"/> </message> <message> <location filename="../qrcodedialog.cpp" line="+62"/> <source>Error encoding URI into QR Code.</source> <translation type="unfinished"/> </message> <message> <location line="+40"/> <source>The entered amount is invalid, please check.</source> <translation type="unfinished"/> </message> <message> <location line="+23"/> <source>Resulting URI too long, try to reduce the text for label / message.</source> <translation type="unfinished"/> </message> <message> <location line="+25"/> <source>Save QR Code</source> <translation type="unfinished"/> </message> <message> <location line="+0"/> <source>PNG Images (*.png)</source> <translation type="unfinished"/> </message> </context> <context> <name>RPCConsole</name> <message> <location filename="../forms/rpcconsole.ui" line="+46"/> <source>Client name</source> <translation type="unfinished"/> </message> <message> <location line="+10"/> <location line="+23"/> <location line="+26"/> <location line="+23"/> <location line="+23"/> <location line="+36"/> <location line="+53"/> <location line="+23"/> <location line="+23"/> <location filename="../rpcconsole.cpp" line="+339"/> <source>N/A</source> <translation type="unfinished"/> </message> <message> <location line="-217"/> <source>Client version</source> <translation type="unfinished"/> </message> <message> <location line="-45"/> <source>&amp;Information</source> <translation type="unfinished"/> </message> <message> <location line="+68"/> <source>Using OpenSSL version</source> <translation type="unfinished"/> </message> <message> <location line="+49"/> <source>Startup time</source> <translation type="unfinished"/> </message> <message> <location line="+29"/> <source>Network</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>Number of connections</source> <translation type="unfinished"/> </message> <message> <location line="+23"/> <source>On testnet</source> <translation type="unfinished"/> </message> <message> <location line="+23"/> <source>Block chain</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>Current number of blocks</source> <translation type="unfinished"/> </message> <message> <location line="+23"/> <source>Estimated total blocks</source> <translation type="unfinished"/> </message> <message> <location line="+23"/> <source>Last block time</source> <translation type="unfinished"/> </message> <message> <location line="+52"/> <source>&amp;Open</source> <translation type="unfinished"/> </message> <message> <location line="+16"/> <source>Command-line options</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>Show the potatocoin-Qt help message to get a list with possible potatocoin command-line options.</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>&amp;Show</source> <translation type="unfinished"/> </message> <message> <location line="+24"/> <source>&amp;Console</source> <translation type="unfinished"/> </message> <message> <location line="-260"/> <source>Build date</source> <translation type="unfinished"/> </message> <message> <location line="-104"/> <source>potatocoin - Debug window</source> <translation type="unfinished"/> </message> <message> <location line="+25"/> <source>potatocoin Core</source> <translation type="unfinished"/> </message> <message> <location line="+279"/> <source>Debug log file</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>Open the potatocoin debug log file from the current data directory. This can take a few seconds for large log files.</source> <translation type="unfinished"/> </message> <message> <location line="+102"/> <source>Clear console</source> <translation type="unfinished"/> </message> <message> <location filename="../rpcconsole.cpp" line="-30"/> <source>Welcome to the potatocoin RPC console.</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Use up and down arrows to navigate history, and &lt;b&gt;Ctrl-L&lt;/b&gt; to clear screen.</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Type &lt;b&gt;help&lt;/b&gt; for an overview of available commands.</source> <translation type="unfinished"/> </message> </context> <context> <name>SendCoinsDialog</name> <message> <location filename="../forms/sendcoinsdialog.ui" line="+14"/> <location filename="../sendcoinsdialog.cpp" line="+124"/> <location line="+5"/> <location line="+5"/> <location line="+5"/> <location line="+6"/> <location line="+5"/> <location line="+5"/> <source>Send Coins</source> <translation type="unfinished"/> </message> <message> <location line="+50"/> <source>Send to multiple recipients at once</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Add &amp;Recipient</source> <translation type="unfinished"/> </message> <message> <location line="+20"/> <source>Remove all transaction fields</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Clear &amp;All</source> <translation type="unfinished"/> </message> <message> <location line="+22"/> <source>Balance:</source> <translation type="unfinished"/> </message> <message> <location line="+10"/> <source>123.456 BTC</source> <translation type="unfinished"/> </message> <message> <location line="+31"/> <source>Confirm the send action</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>S&amp;end</source> <translation type="unfinished"/> </message> <message> <location filename="../sendcoinsdialog.cpp" line="-59"/> <source>&lt;b&gt;%1&lt;/b&gt; to %2 (%3)</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <source>Confirm send coins</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Are you sure you want to send %1?</source> <translation type="unfinished"/> </message> <message> <location line="+0"/> <source> and </source> <translation type="unfinished"/> </message> <message> <location line="+23"/> <source>The recipient address is not valid, please recheck.</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <source>The amount to pay must be larger than 0.</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <source>The amount exceeds your balance.</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <source>The total exceeds your balance when the %1 transaction fee is included.</source> <translation type="unfinished"/> </message> <message> <location line="+6"/> <source>Duplicate address found, can only send to each address once per send operation.</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <source>Error: Transaction creation failed!</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <source>Error: The transaction was rejected. This might happen if some of the coins in your wallet were already spent, such as if you used a copy of wallet.dat and coins were spent in the copy but not marked as spent here.</source> <translation type="unfinished"/> </message> </context> <context> <name>SendCoinsEntry</name> <message> <location filename="../forms/sendcoinsentry.ui" line="+14"/> <source>Form</source> <translation type="unfinished"/> </message> <message> <location line="+15"/> <source>A&amp;mount:</source> <translation type="unfinished"/> </message> <message> <location line="+13"/> <source>Pay &amp;To:</source> <translation type="unfinished"/> </message> <message> <location line="+34"/> <source>The address to send the payment to (e.g. Ler4HNAEfwYhBmGXcFP2Po1NpRUEiK8km2)</source> <translation type="unfinished"/> </message> <message> <location line="+60"/> <location filename="../sendcoinsentry.cpp" line="+26"/> <source>Enter a label for this address to add it to your address book</source> <translation type="unfinished"/> </message> <message> <location line="-78"/> <source>&amp;Label:</source> <translation type="unfinished"/> </message> <message> <location line="+28"/> <source>Choose address from address book</source> <translation type="unfinished"/> </message> <message> <location line="+10"/> <source>Alt+A</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>Paste address from clipboard</source> <translation type="unfinished"/> </message> <message> <location line="+10"/> <source>Alt+P</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>Remove this recipient</source> <translation type="unfinished"/> </message> <message> <location filename="../sendcoinsentry.cpp" line="+1"/> <source>Enter a potatocoin address (e.g. Ler4HNAEfwYhBmGXcFP2Po1NpRUEiK8km2)</source> <translation type="unfinished"/> </message> </context> <context> <name>SignVerifyMessageDialog</name> <message> <location filename="../forms/signverifymessagedialog.ui" line="+14"/> <source>Signatures - Sign / Verify a Message</source> <translation type="unfinished"/> </message> <message> <location line="+13"/> <source>&amp;Sign Message</source> <translation type="unfinished"/> </message> <message> <location line="+6"/> <source>You can sign messages with your addresses to prove you own them. Be careful not to sign anything vague, as phishing attacks may try to trick you into signing your identity over to them. Only sign fully-detailed statements you agree to.</source> <translation type="unfinished"/> </message> <message> <location line="+18"/> <source>The address to sign the message with (e.g. Ler4HNAEfwYhBmGXcFP2Po1NpRUEiK8km2)</source> <translation type="unfinished"/> </message> <message> <location line="+10"/> <location line="+213"/> <source>Choose an address from the address book</source> <translation type="unfinished"/> </message> <message> <location line="-203"/> <location line="+213"/> <source>Alt+A</source> <translation type="unfinished"/> </message> <message> <location line="-203"/> <source>Paste address from clipboard</source> <translation type="unfinished"/> </message> <message> <location line="+10"/> <source>Alt+P</source> <translation type="unfinished"/> </message> <message> <location line="+12"/> <source>Enter the message you want to sign here</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>Signature</source> <translation type="unfinished"/> </message> <message> <location line="+27"/> <source>Copy the current signature to the system clipboard</source> <translation type="unfinished"/> </message> <message> <location line="+21"/> <source>Sign the message to prove you own this potatocoin address</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Sign &amp;Message</source> <translation type="unfinished"/> </message> <message> <location line="+14"/> <source>Reset all sign message fields</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <location line="+146"/> <source>Clear &amp;All</source> <translation type="unfinished"/> </message> <message> <location line="-87"/> <source>&amp;Verify Message</source> <translation type="unfinished"/> </message> <message> <location line="+6"/> <source>Enter the signing address, message (ensure you copy line breaks, spaces, tabs, etc. exactly) and signature below to verify the message. Be careful not to read more into the signature than what is in the signed message itself, to avoid being tricked by a man-in-the-middle attack.</source> <translation type="unfinished"/> </message> <message> <location line="+21"/> <source>The address the message was signed with (e.g. Ler4HNAEfwYhBmGXcFP2Po1NpRUEiK8km2)</source> <translation type="unfinished"/> </message> <message> <location line="+40"/> <source>Verify the message to ensure it was signed with the specified potatocoin address</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Verify &amp;Message</source> <translation type="unfinished"/> </message> <message> <location line="+14"/> <source>Reset all verify message fields</source> <translation type="unfinished"/> </message> <message> <location filename="../signverifymessagedialog.cpp" line="+27"/> <location line="+3"/> <source>Enter a potatocoin address (e.g. Ler4HNAEfwYhBmGXcFP2Po1NpRUEiK8km2)</source> <translation type="unfinished"/> </message> <message> <location line="-2"/> <source>Click &quot;Sign Message&quot; to generate signature</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Enter potatocoin signature</source> <translation type="unfinished"/> </message> <message> <location line="+82"/> <location line="+81"/> <source>The entered address is invalid.</source> <translation type="unfinished"/> </message> <message> <location line="-81"/> <location line="+8"/> <location line="+73"/> <location line="+8"/> <source>Please check the address and try again.</source> <translation type="unfinished"/> </message> <message> <location line="-81"/> <location line="+81"/> <source>The entered address does not refer to a key.</source> <translation type="unfinished"/> </message> <message> <location line="-73"/> <source>Wallet unlock was cancelled.</source> <translation type="unfinished"/> </message> <message> <location line="+8"/> <source>Private key for the entered address is not available.</source> <translation type="unfinished"/> </message> <message> <location line="+12"/> <source>Message signing failed.</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <source>Message signed.</source> <translation type="unfinished"/> </message> <message> <location line="+59"/> <source>The signature could not be decoded.</source> <translation type="unfinished"/> </message> <message> <location line="+0"/> <location line="+13"/> <source>Please check the signature and try again.</source> <translation type="unfinished"/> </message> <message> <location line="+0"/> <source>The signature did not match the message digest.</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>Message verification failed.</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <source>Message verified.</source> <translation type="unfinished"/> </message> </context> <context> <name>SplashScreen</name> <message> <location filename="../splashscreen.cpp" line="+22"/> <source>The potatocoin developers</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>[testnet]</source> <translation type="unfinished"/> </message> </context> <context> <name>TransactionDesc</name> <message> <location filename="../transactiondesc.cpp" line="+20"/> <source>Open until %1</source> <translation type="unfinished"/> </message> <message> <location line="+6"/> <source>%1/offline</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>%1/unconfirmed</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>%1 confirmations</source> <translation type="unfinished"/> </message> <message> <location line="+18"/> <source>Status</source> <translation type="unfinished"/> </message> <message numerus="yes"> <location line="+7"/> <source>, broadcast through %n node(s)</source> <translation type="unfinished"><numerusform></numerusform><numerusform></numerusform></translation> </message> <message> <location line="+4"/> <source>Date</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>Source</source> <translation type="unfinished"/> </message> <message> <location line="+0"/> <source>Generated</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <location line="+17"/> <source>From</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <location line="+22"/> <location line="+58"/> <source>To</source> <translation type="unfinished"/> </message> <message> <location line="-77"/> <location line="+2"/> <source>own address</source> <translation type="unfinished"/> </message> <message> <location line="-2"/> <source>label</source> <translation type="unfinished"/> </message> <message> <location line="+37"/> <location line="+12"/> <location line="+45"/> <location line="+17"/> <location line="+30"/> <source>Credit</source> <translation type="unfinished"/> </message> <message numerus="yes"> <location line="-102"/> <source>matures in %n more block(s)</source> <translation type="unfinished"><numerusform></numerusform><numerusform></numerusform></translation> </message> <message> <location line="+2"/> <source>not accepted</source> <translation type="unfinished"/> </message> <message> <location line="+44"/> <location line="+8"/> <location line="+15"/> <location line="+30"/> <source>Debit</source> <translation type="unfinished"/> </message> <message> <location line="-39"/> <source>Transaction fee</source> <translation type="unfinished"/> </message> <message> <location line="+16"/> <source>Net amount</source> <translation type="unfinished"/> </message> <message> <location line="+6"/> <source>Message</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Comment</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Transaction ID</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Generated coins must mature 120 blocks before they can be spent. When you generated this block, it was broadcast to the network to be added to the block chain. If it fails to get into the chain, its state will change to &quot;not accepted&quot; and it won&apos;t be spendable. This may occasionally happen if another node generates a block within a few seconds of yours.</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>Debug information</source> <translation type="unfinished"/> </message> <message> <location line="+8"/> <source>Transaction</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Inputs</source> <translation type="unfinished"/> </message> <message> <location line="+23"/> <source>Amount</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>true</source> <translation type="unfinished"/> </message> <message> <location line="+0"/> <source>false</source> <translation type="unfinished"/> </message> <message> <location line="-209"/> <source>, has not been successfully broadcast yet</source> <translation type="unfinished"/> </message> <message numerus="yes"> <location line="-35"/> <source>Open for %n more block(s)</source> <translation type="unfinished"><numerusform></numerusform><numerusform></numerusform></translation> </message> <message> <location line="+70"/> <source>unknown</source> <translation type="unfinished"/> </message> </context> <context> <name>TransactionDescDialog</name> <message> <location filename="../forms/transactiondescdialog.ui" line="+14"/> <source>Transaction details</source> <translation type="unfinished"/> </message> <message> <location line="+6"/> <source>This pane shows a detailed description of the transaction</source> <translation type="unfinished"/> </message> </context> <context> <name>TransactionTableModel</name> <message> <location filename="../transactiontablemodel.cpp" line="+225"/> <source>Date</source> <translation type="unfinished"/> </message> <message> <location line="+0"/> <source>Type</source> <translation type="unfinished"/> </message> <message> <location line="+0"/> <source>Address</source> <translation type="unfinished"/> </message> <message> <location line="+0"/> <source>Amount</source> <translation type="unfinished"/> </message> <message numerus="yes"> <location line="+57"/> <source>Open for %n more block(s)</source> <translation type="unfinished"><numerusform></numerusform><numerusform></numerusform></translation> </message> <message> <location line="+3"/> <source>Open until %1</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Offline (%1 confirmations)</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Unconfirmed (%1 of %2 confirmations)</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Confirmed (%1 confirmations)</source> <translation type="unfinished"/> </message> <message numerus="yes"> <location line="+8"/> <source>Mined balance will be available when it matures in %n more block(s)</source> <translation type="unfinished"><numerusform></numerusform><numerusform></numerusform></translation> </message> <message> <location line="+5"/> <source>This block was not received by any other nodes and will probably not be accepted!</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Generated but not accepted</source> <translation type="unfinished"/> </message> <message> <location line="+43"/> <source>Received with</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Received from</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Sent to</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Payment to yourself</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Mined</source> <translation type="unfinished"/> </message> <message> <location line="+38"/> <source>(n/a)</source> <translation type="unfinished"/> </message> <message> <location line="+199"/> <source>Transaction status. Hover over this field to show number of confirmations.</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Date and time that the transaction was received.</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Type of transaction.</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Destination address of transaction.</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Amount removed from or added to balance.</source> <translation type="unfinished"/> </message> </context> <context> <name>TransactionView</name> <message> <location filename="../transactionview.cpp" line="+52"/> <location line="+16"/> <source>All</source> <translation type="unfinished"/> </message> <message> <location line="-15"/> <source>Today</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>This week</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>This month</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Last month</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>This year</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Range...</source> <translation type="unfinished"/> </message> <message> <location line="+11"/> <source>Received with</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Sent to</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>To yourself</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Mined</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Other</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>Enter address or label to search</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>Min amount</source> <translation type="unfinished"/> </message> <message> <location line="+34"/> <source>Copy address</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Copy label</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Copy amount</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Copy transaction ID</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Edit label</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Show transaction details</source> <translation type="unfinished"/> </message> <message> <location line="+139"/> <source>Export Transaction Data</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Comma separated file (*.csv)</source> <translation type="unfinished"/> </message> <message> <location line="+8"/> <source>Confirmed</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Date</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Type</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Label</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Address</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Amount</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>ID</source> <translation type="unfinished"/> </message> <message> <location line="+4"/> <source>Error exporting</source> <translation type="unfinished"/> </message> <message> <location line="+0"/> <source>Could not write to file %1.</source> <translation type="unfinished"/> </message> <message> <location line="+100"/> <source>Range:</source> <translation type="unfinished"/> </message> <message> <location line="+8"/> <source>to</source> <translation type="unfinished"/> </message> </context> <context> <name>WalletModel</name> <message> <location filename="../walletmodel.cpp" line="+193"/> <source>Send Coins</source> <translation type="unfinished"/> </message> </context> <context> <name>WalletView</name> <message> <location filename="../walletview.cpp" line="+42"/> <source>&amp;Export</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Export the data in the current tab to a file</source> <translation type="unfinished"/> </message> <message> <location line="+193"/> <source>Backup Wallet</source> <translation type="unfinished"/> </message> <message> <location line="+0"/> <source>Wallet Data (*.dat)</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Backup Failed</source> <translation type="unfinished"/> </message> <message> <location line="+0"/> <source>There was an error trying to save the wallet data to the new location.</source> <translation type="unfinished"/> </message> <message> <location line="+4"/> <source>Backup Successful</source> <translation type="unfinished"/> </message> <message> <location line="+0"/> <source>The wallet data was successfully saved to the new location.</source> <translation type="unfinished"/> </message> </context> <context> <name>bitcoin-core</name> <message> <location filename="../bitcoinstrings.cpp" line="+94"/> <source>potatocoin version</source> <translation type="unfinished"/> </message> <message> <location line="+102"/> <source>Usage:</source> <translation type="unfinished"/> </message> <message> <location line="-29"/> <source>Send command to -server or potatocoind</source> <translation type="unfinished"/> </message> <message> <location line="-23"/> <source>List commands</source> <translation type="unfinished"/> </message> <message> <location line="-12"/> <source>Get help for a command</source> <translation type="unfinished"/> </message> <message> <location line="+24"/> <source>Options:</source> <translation type="unfinished"/> </message> <message> <location line="+24"/> <source>Specify configuration file (default: potatocoin.conf)</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Specify pid file (default: potatocoind.pid)</source> <translation type="unfinished"/> </message> <message> <location line="-1"/> <source>Specify data directory</source> <translation type="unfinished"/> </message> <message> <location line="-9"/> <source>Set database cache size in megabytes (default: 25)</source> <translation type="unfinished"/> </message> <message> <location line="-28"/> <source>Listen for connections on &lt;port&gt; (default: 41015 or testnet: 22220)</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <source>Maintain at most &lt;n&gt; connections to peers (default: 125)</source> <translation type="unfinished"/> </message> <message> <location line="-48"/> <source>Connect to a node to retrieve peer addresses, and disconnect</source> <translation type="unfinished"/> </message> <message> <location line="+82"/> <source>Specify your own public address</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Threshold for disconnecting misbehaving peers (default: 100)</source> <translation type="unfinished"/> </message> <message> <location line="-134"/> <source>Number of seconds to keep misbehaving peers from reconnecting (default: 86400)</source> <translation type="unfinished"/> </message> <message> <location line="-29"/> <source>An error occurred while setting up the RPC port %u for listening on IPv4: %s</source> <translation type="unfinished"/> </message> <message> <location line="+27"/> <source>Listen for JSON-RPC connections on &lt;port&gt; (default: 51015 or testnet: 22022)</source> <translation type="unfinished"/> </message> <message> <location line="+37"/> <source>Accept command line and JSON-RPC commands</source> <translation type="unfinished"/> </message> <message> <location line="+76"/> <source>Run in the background as a daemon and accept commands</source> <translation type="unfinished"/> </message> <message> <location line="+37"/> <source>Use the test network</source> <translation type="unfinished"/> </message> <message> <location line="-112"/> <source>Accept connections from outside (default: 1 if no -proxy or -connect)</source> <translation type="unfinished"/> </message> <message> <location line="-80"/> <source>%s, you must set a rpcpassword in the configuration file: %s It is recommended you use the following random password: rpcuser=potatocoinrpc rpcpassword=%s (you do not need to remember this password) The username and password MUST NOT be the same. If the file does not exist, create it with owner-readable-only file permissions. It is also recommended to set alertnotify so you are notified of problems; for example: alertnotify=echo %%s | mail -s &quot;potatocoin Alert&quot; [email protected] </source> <translation type="unfinished"/> </message> <message> <location line="+17"/> <source>An error occurred while setting up the RPC port %u for listening on IPv6, falling back to IPv4: %s</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Bind to given address and always listen on it. Use [host]:port notation for IPv6</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Cannot obtain a lock on data directory %s. potatocoin is probably already running.</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Error: The transaction was rejected! This might happen if some of the coins in your wallet were already spent, such as if you used a copy of wallet.dat and coins were spent in the copy but not marked as spent here.</source> <translation type="unfinished"/> </message> <message> <location line="+4"/> <source>Error: This transaction requires a transaction fee of at least %s because of its amount, complexity, or use of recently received funds!</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Execute command when a relevant alert is received (%s in cmd is replaced by message)</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Execute command when a wallet transaction changes (%s in cmd is replaced by TxID)</source> <translation type="unfinished"/> </message> <message> <location line="+11"/> <source>Set maximum size of high-priority/low-fee transactions in bytes (default: 27000)</source> <translation type="unfinished"/> </message> <message> <location line="+6"/> <source>This is a pre-release test build - use at your own risk - do not use for mining or merchant applications</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <source>Warning: -paytxfee is set very high! This is the transaction fee you will pay if you send a transaction.</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Warning: Displayed transactions may not be correct! You may need to upgrade, or other nodes may need to upgrade.</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Warning: Please check that your computer&apos;s date and time are correct! If your clock is wrong potatocoin will not work properly.</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Warning: error reading wallet.dat! All keys read correctly, but transaction data or address book entries might be missing or incorrect.</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Warning: wallet.dat corrupt, data salvaged! Original wallet.dat saved as wallet.{timestamp}.bak in %s; if your balance or transactions are incorrect you should restore from a backup.</source> <translation type="unfinished"/> </message> <message> <location line="+14"/> <source>Attempt to recover private keys from a corrupt wallet.dat</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Block creation options:</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <source>Connect only to the specified node(s)</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Corrupted block database detected</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Discover own IP address (default: 1 when listening and no -externalip)</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Do you want to rebuild the block database now?</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Error initializing block database</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Error initializing wallet database environment %s!</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Error loading block database</source> <translation type="unfinished"/> </message> <message> <location line="+4"/> <source>Error opening block database</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Error: Disk space is low!</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Error: Wallet locked, unable to create transaction!</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Error: system error: </source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Failed to listen on any port. Use -listen=0 if you want this.</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Failed to read block info</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Failed to read block</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Failed to sync block index</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Failed to write block index</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Failed to write block info</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Failed to write block</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Failed to write file info</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Failed to write to coin database</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Failed to write transaction index</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Failed to write undo data</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Find peers using DNS lookup (default: 1 unless -connect)</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Generate coins (default: 0)</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>How many blocks to check at startup (default: 288, 0 = all)</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>How thorough the block verification is (0-4, default: 3)</source> <translation type="unfinished"/> </message> <message> <location line="+19"/> <source>Not enough file descriptors available.</source> <translation type="unfinished"/> </message> <message> <location line="+8"/> <source>Rebuild block chain index from current blk000??.dat files</source> <translation type="unfinished"/> </message> <message> <location line="+16"/> <source>Set the number of threads to service RPC calls (default: 4)</source> <translation type="unfinished"/> </message> <message> <location line="+26"/> <source>Verifying blocks...</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Verifying wallet...</source> <translation type="unfinished"/> </message> <message> <location line="-69"/> <source>Imports blocks from external blk000??.dat file</source> <translation type="unfinished"/> </message> <message> <location line="-76"/> <source>Set the number of script verification threads (up to 16, 0 = auto, &lt;0 = leave that many cores free, default: 0)</source> <translation type="unfinished"/> </message> <message> <location line="+77"/> <source>Information</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Invalid -tor address: &apos;%s&apos;</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Invalid amount for -minrelaytxfee=&lt;amount&gt;: &apos;%s&apos;</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Invalid amount for -mintxfee=&lt;amount&gt;: &apos;%s&apos;</source> <translation type="unfinished"/> </message> <message> <location line="+8"/> <source>Maintain a full transaction index (default: 0)</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Maximum per-connection receive buffer, &lt;n&gt;*1000 bytes (default: 5000)</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Maximum per-connection send buffer, &lt;n&gt;*1000 bytes (default: 1000)</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Only accept block chain matching built-in checkpoints (default: 1)</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Only connect to nodes in network &lt;net&gt; (IPv4, IPv6 or Tor)</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Output extra debugging information. Implies all other -debug* options</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Output extra network debugging information</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Prepend debug output with timestamp</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <source>SSL options: (see the potatocoin Wiki for SSL setup instructions)</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Select the version of socks proxy to use (4-5, default: 5)</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Send trace/debug info to console instead of debug.log file</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Send trace/debug info to debugger</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <source>Set maximum block size in bytes (default: 250000)</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Set minimum block size in bytes (default: 0)</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Shrink debug.log file on client startup (default: 1 when no -debug)</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Signing transaction failed</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Specify connection timeout in milliseconds (default: 5000)</source> <translation type="unfinished"/> </message> <message> <location line="+4"/> <source>System error: </source> <translation type="unfinished"/> </message> <message> <location line="+4"/> <source>Transaction amount too small</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Transaction amounts must be positive</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Transaction too large</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>Use UPnP to map the listening port (default: 0)</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Use UPnP to map the listening port (default: 1 when listening)</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Use proxy to reach tor hidden services (default: same as -proxy)</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Username for JSON-RPC connections</source> <translation type="unfinished"/> </message> <message> <location line="+4"/> <source>Warning</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Warning: This version is obsolete, upgrade required!</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>You need to rebuild the databases using -reindex to change -txindex</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>wallet.dat corrupt, salvage failed</source> <translation type="unfinished"/> </message> <message> <location line="-50"/> <source>Password for JSON-RPC connections</source> <translation type="unfinished"/> </message> <message> <location line="-67"/> <source>Allow JSON-RPC connections from specified IP address</source> <translation type="unfinished"/> </message> <message> <location line="+76"/> <source>Send commands to node running on &lt;ip&gt; (default: 127.0.0.1)</source> <translation type="unfinished"/> </message> <message> <location line="-120"/> <source>Execute command when the best block changes (%s in cmd is replaced by block hash)</source> <translation type="unfinished"/> </message> <message> <location line="+147"/> <source>Upgrade wallet to latest format</source> <translation type="unfinished"/> </message> <message> <location line="-21"/> <source>Set key pool size to &lt;n&gt; (default: 100)</source> <translation type="unfinished"/> </message> <message> <location line="-12"/> <source>Rescan the block chain for missing wallet transactions</source> <translation type="unfinished"/> </message> <message> <location line="+35"/> <source>Use OpenSSL (https) for JSON-RPC connections</source> <translation type="unfinished"/> </message> <message> <location line="-26"/> <source>Server certificate file (default: server.cert)</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Server private key (default: server.pem)</source> <translation type="unfinished"/> </message> <message> <location line="-151"/> <source>Acceptable ciphers (default: TLSv1+HIGH:!SSLv2:!aNULL:!eNULL:!AH:!3DES:@STRENGTH)</source> <translation type="unfinished"/> </message> <message> <location line="+165"/> <source>This help message</source> <translation type="unfinished"/> </message> <message> <location line="+6"/> <source>Unable to bind to %s on this computer (bind returned error %d, %s)</source> <translation type="unfinished"/> </message> <message> <location line="-91"/> <source>Connect through socks proxy</source> <translation type="unfinished"/> </message> <message> <location line="-10"/> <source>Allow DNS lookups for -addnode, -seednode and -connect</source> <translation type="unfinished"/> </message> <message> <location line="+55"/> <source>Loading addresses...</source> <translation type="unfinished"/> </message> <message> <location line="-35"/> <source>Error loading wallet.dat: Wallet corrupted</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Error loading wallet.dat: Wallet requires newer version of potatocoin</source> <translation type="unfinished"/> </message> <message> <location line="+93"/> <source>Wallet needed to be rewritten: restart potatocoin to complete</source> <translation type="unfinished"/> </message> <message> <location line="-95"/> <source>Error loading wallet.dat</source> <translation type="unfinished"/> </message> <message> <location line="+28"/> <source>Invalid -proxy address: &apos;%s&apos;</source> <translation type="unfinished"/> </message> <message> <location line="+56"/> <source>Unknown network specified in -onlynet: &apos;%s&apos;</source> <translation type="unfinished"/> </message> <message> <location line="-1"/> <source>Unknown -socks proxy version requested: %i</source> <translation type="unfinished"/> </message> <message> <location line="-96"/> <source>Cannot resolve -bind address: &apos;%s&apos;</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Cannot resolve -externalip address: &apos;%s&apos;</source> <translation type="unfinished"/> </message> <message> <location line="+44"/> <source>Invalid amount for -paytxfee=&lt;amount&gt;: &apos;%s&apos;</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Invalid amount</source> <translation type="unfinished"/> </message> <message> <location line="-6"/> <source>Insufficient funds</source> <translation type="unfinished"/> </message> <message> <location line="+10"/> <source>Loading block index...</source> <translation type="unfinished"/> </message> <message> <location line="-57"/> <source>Add a node to connect to and attempt to keep the connection open</source> <translation type="unfinished"/> </message> <message> <location line="-25"/> <source>Unable to bind to %s on this computer. potatocoin is probably already running.</source> <translation type="unfinished"/> </message> <message> <location line="+64"/> <source>Fee per KB to add to transactions you send</source> <translation type="unfinished"/> </message> <message> <location line="+19"/> <source>Loading wallet...</source> <translation type="unfinished"/> </message> <message> <location line="-52"/> <source>Cannot downgrade wallet</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Cannot write default address</source> <translation type="unfinished"/> </message> <message> <location line="+64"/> <source>Rescanning...</source> <translation type="unfinished"/> </message> <message> <location line="-57"/> <source>Done loading</source> <translation type="unfinished"/> </message> <message> <location line="+82"/> <source>To use the %s option</source> <translation type="unfinished"/> </message> <message> <location line="-74"/> <source>Error</source> <translation type="unfinished"/> </message> <message> <location line="-31"/> <source>You must set rpcpassword=&lt;password&gt; in the configuration file: %s If the file does not exist, create it with owner-readable-only file permissions.</source> <translation type="unfinished"/> </message> </context> </TS>
{'content_hash': 'dd32067a22b152ba47a131d63ced2826', 'timestamp': '', 'source': 'github', 'line_count': 2922, 'max_line_length': 395, 'avg_line_length': 33.33709787816564, 'alnum_prop': 0.5876954348071574, 'repo_name': 'Open-Source-Coins/potato', 'id': '5f3b407354faef8bcf378698738c01f511366a3c', 'size': '97428', 'binary': False, 'copies': '2', 'ref': 'refs/heads/master', 'path': 'src/qt/locale/bitcoin_fr_CA.ts', 'mode': '33261', 'license': 'mit', 'language': [{'name': 'Batchfile', 'bytes': '267'}, {'name': 'C', 'bytes': '700929'}, {'name': 'C++', 'bytes': '2598511'}, {'name': 'CSS', 'bytes': '1127'}, {'name': 'Groff', 'bytes': '18289'}, {'name': 'HTML', 'bytes': '50615'}, {'name': 'Makefile', 'bytes': '13478'}, {'name': 'NSIS', 'bytes': '5273'}, {'name': 'Objective-C', 'bytes': '858'}, {'name': 'Objective-C++', 'bytes': '5864'}, {'name': 'Python', 'bytes': '69726'}, {'name': 'QMake', 'bytes': '14840'}, {'name': 'Shell', 'bytes': '9701'}]}
#ifndef __FILTER_IMPL_HPP__ #define __FILTER_IMPL_HPP__ #include "MediaElementImpl.hpp" #include "Filter.hpp" #include <EventHandler.hpp> namespace kurento { class FilterImpl; void Serialize (std::shared_ptr<FilterImpl> &object, JsonSerializer &serializer); class FilterImpl : public MediaElementImpl, public virtual Filter { public: FilterImpl (const boost::property_tree::ptree &config, std::shared_ptr<MediaObjectImpl> parent); virtual ~FilterImpl () {}; /* Next methods are automatically implemented by code generator */ using MediaElementImpl::connect; virtual bool connect (const std::string &eventType, std::shared_ptr<EventHandler> handler) override; virtual void invoke (std::shared_ptr<MediaObjectImpl> obj, const std::string &methodName, const Json::Value &params, Json::Value &response) override; virtual void Serialize (JsonSerializer &serializer) override; private: class StaticConstructor { public: StaticConstructor(); }; static StaticConstructor staticConstructor; }; } /* kurento */ #endif /* __FILTER_IMPL_HPP__ */
{'content_hash': '8844050fc92b2c41d05771ddfecaa850', 'timestamp': '', 'source': 'github', 'line_count': 52, 'max_line_length': 80, 'avg_line_length': 22.71153846153846, 'alnum_prop': 0.676545300592718, 'repo_name': 'ESTOS/kms-core', 'id': '1fdd02e642023c3f15f92432bb260b3097e6f13d', 'size': '1798', 'binary': False, 'copies': '2', 'ref': 'refs/heads/estos6.2', 'path': 'src/server/implementation/objects/FilterImpl.hpp', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'C', 'bytes': '1579013'}, {'name': 'C++', 'bytes': '269385'}, {'name': 'CMake', 'bytes': '73201'}, {'name': 'Python', 'bytes': '8726'}, {'name': 'Shell', 'bytes': '4714'}]}
package LeetCode; import java.util.Arrays; import LeetCode.BinaryTreeInorderTraversal.TreeNode; public class ConstructBTfromInPostTraversal { public TreeNode buildTree(int[] inorder, int[] postorder) { if (inorder.length == 0) return null; if (inorder.length == 1) return new TreeNode(inorder[0]); // the last item in postorder is root TreeNode root = new TreeNode(postorder[postorder.length - 1]); int i = inorder.length - 1; for (; inorder[i] != root.val; i--) ; // inorder.length == postorder.length if (i < inorder.length - 1) { root.right = buildTree( Arrays.copyOfRange(inorder, i + 1, inorder.length), Arrays.copyOfRange(postorder, i, postorder.length - 1)); } if (i > 0) { root.left = buildTree(Arrays.copyOfRange(inorder, 0, i), Arrays.copyOfRange(postorder, 0, i)); } return root; } /** * @param args */ public static void main(String[] args) { // TODO Auto-generated method stub } }
{'content_hash': '5729bb0553f5b75f0d8fde00a9cba282', 'timestamp': '', 'source': 'github', 'line_count': 43, 'max_line_length': 76, 'avg_line_length': 27.930232558139537, 'alnum_prop': 0.537052456286428, 'repo_name': 'dingxwsimon/codingquestions', 'id': 'c8a16d98ab73c57c3c23de58462f13c5c8eecc5a', 'size': '1201', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'src/LeetCode/ConstructBTfromInPostTraversal.java', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'Java', 'bytes': '1148288'}]}
<?php namespace Application\Migrations; use Doctrine\DBAL\Migrations\AbstractMigration, Doctrine\DBAL\Schema\Schema; /** * Auto-generated Migration: Please modify to your need! */ class Version20120124153843 extends AbstractMigration { public function up(Schema $schema) { // this up() migration is autogenerated, please modify it to your needs $this->abortIf($this->connection->getDatabasePlatform()->getName() != "mysql"); $this->addSql("ALTER TABLE blog ADD slug VARCHAR(255) NOT NULL"); } public function down(Schema $schema) { // this down() migration is autogenerated, please modify it to your needs $this->abortIf($this->connection->getDatabasePlatform()->getName() != "mysql"); $this->addSql("ALTER TABLE blog DROP slug"); } }
{'content_hash': '57239e0ef26ff376c83b4ff628d9f812', 'timestamp': '', 'source': 'github', 'line_count': 28, 'max_line_length': 87, 'avg_line_length': 29.821428571428573, 'alnum_prop': 0.6646706586826348, 'repo_name': 'miranetworks/symblog-test', 'id': 'eab73fa9b6ff7a5ddeadb3919e5d6a7a0c3ea6d6', 'size': '835', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'app/DoctrineMigrations/Version20120124153843.php', 'mode': '33261', 'license': 'mit', 'language': [{'name': 'C', 'bytes': '400591'}, {'name': 'Java', 'bytes': '250852'}, {'name': 'JavaScript', 'bytes': '10962'}, {'name': 'PHP', 'bytes': '84735'}, {'name': 'Shell', 'bytes': '353127'}, {'name': 'VimL', 'bytes': '2119'}]}
// Based on Eclipse Paho. /******************************************************************************* * Copyright (c) 2014 IBM Corp. * * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * and Eclipse Distribution License v1.0 which accompany this distribution. * * The Eclipse Public License is available at * http://www.eclipse.org/legal/epl-v10.html * and the Eclipse Distribution License is available at * http://www.eclipse.org/org/documents/edl-v10.php. * * Contributors: * Ian Craggs - initial API and implementation and/or initial documentation * Sergio R. Caprile - non-blocking packet read functions for stream transport *******************************************************************************/ /** * @file aws_iot_mqtt_client_common_internal.c * @brief MQTT client internal API definitions */ #ifdef __cplusplus extern "C" { #endif #include <aws_iot_mqtt_client.h> #include "aws_iot_mqtt_client_common_internal.h" /* Max length of packet header */ #define MAX_NO_OF_REMAINING_LENGTH_BYTES 4 /** * Encodes the message length according to the MQTT algorithm * @param buf the buffer into which the encoded data is written * @param length the length to be encoded * @return the number of bytes written to buffer */ size_t aws_iot_mqtt_internal_write_len_to_buffer(unsigned char *buf, uint32_t length) { size_t outLen = 0; unsigned char encodedByte; FUNC_ENTRY; do { encodedByte = (unsigned char) (length % 128); length /= 128; /* if there are more digits to encode, set the top bit of this digit */ if(length > 0) { encodedByte |= 0x80; } buf[outLen++] = encodedByte; } while(length > 0); FUNC_EXIT_RC(outLen); } /** * Decodes the message length according to the MQTT algorithm * @param the buffer containing the message * @param value the decoded length returned * @return the number of bytes read from the socket */ IoT_Error_t aws_iot_mqtt_internal_decode_remaining_length_from_buffer(unsigned char *buf, uint32_t *decodedLen, uint32_t *readBytesLen) { unsigned char encodedByte; uint32_t multiplier, len; FUNC_ENTRY; multiplier = 1; len = 0; *decodedLen = 0; do { if(++len > MAX_NO_OF_REMAINING_LENGTH_BYTES) { /* bad data */ FUNC_EXIT_RC(MQTT_DECODE_REMAINING_LENGTH_ERROR); } encodedByte = *buf; buf++; *decodedLen += (encodedByte & 127) * multiplier; multiplier *= 128; } while((encodedByte & 128) != 0); *readBytesLen = len; FUNC_EXIT_RC(SUCCESS); } uint32_t aws_iot_mqtt_internal_get_final_packet_length_from_remaining_length(uint32_t rem_len) { rem_len += 1; /* header byte */ /* now remaining_length field (MQTT 3.1.1 - 2.2.3)*/ if(rem_len < 128) { rem_len += 1; } else if(rem_len < 16384) { rem_len += 2; } else if(rem_len < 2097152) { rem_len += 3; } else { rem_len += 4; } return rem_len; } /** * Calculates uint16 packet id from two bytes read from the input buffer * Checks Endianness at runtime * * @param pptr pointer to the input buffer - incremented by the number of bytes used & returned * @return the value calculated */ uint16_t aws_iot_mqtt_internal_read_uint16_t(unsigned char **pptr) { unsigned char *ptr = *pptr; uint16_t len = 0; uint8_t firstByte = (uint8_t) (*ptr); uint8_t secondByte = (uint8_t) (*(ptr + 1)); len = (uint16_t) (secondByte + (256 * firstByte)); *pptr += 2; return len; } /** * Writes an integer as 2 bytes to an output buffer. * @param pptr pointer to the output buffer - incremented by the number of bytes used & returned * @param anInt the integer to write */ void aws_iot_mqtt_internal_write_uint_16(unsigned char **pptr, uint16_t anInt) { **pptr = (unsigned char) (anInt / 256); (*pptr)++; **pptr = (unsigned char) (anInt % 256); (*pptr)++; } /** * Reads one character from the input buffer. * @param pptr pointer to the input buffer - incremented by the number of bytes used & returned * @return the character read */ unsigned char aws_iot_mqtt_internal_read_char(unsigned char **pptr) { unsigned char c = **pptr; (*pptr)++; return c; } /** * Writes one character to an output buffer. * @param pptr pointer to the output buffer - incremented by the number of bytes used & returned * @param c the character to write */ void aws_iot_mqtt_internal_write_char(unsigned char **pptr, unsigned char c) { **pptr = c; (*pptr)++; } void aws_iot_mqtt_internal_write_utf8_string(unsigned char **pptr, const char *string, uint16_t stringLen) { /* Nothing that calls this function will have a stringLen with a size larger than 2 bytes (MQTT 3.1.1 - 1.5.3) */ aws_iot_mqtt_internal_write_uint_16(pptr, stringLen); if(stringLen > 0) { memcpy(*pptr, string, stringLen); *pptr += stringLen; } } /** * Initialize the MQTTHeader structure. Used to ensure that Header bits are * always initialized using the proper mappings. No Endianness issues here since * the individual fields are all less than a byte. Also generates no warnings since * all fields are initialized using hex constants */ IoT_Error_t aws_iot_mqtt_internal_init_header(MQTTHeader *pHeader, MessageTypes message_type, QoS qos, uint8_t dup, uint8_t retained) { FUNC_ENTRY; if(NULL == pHeader) { FUNC_EXIT_RC(NULL_VALUE_ERROR); } /* Set all bits to zero */ pHeader->byte = 0; uint8_t type = 0; switch(message_type) { case UNKNOWN: /* Should never happen */ return FAILURE; case CONNECT: type = 0x01; break; case CONNACK: type = 0x02; break; case PUBLISH: type = 0x03; break; case PUBACK: type = 0x04; break; case PUBREC: type = 0x05; break; case PUBREL: type = 0x06; break; case PUBCOMP: type = 0x07; break; case SUBSCRIBE: type = 0x08; break; case SUBACK: type = 0x09; break; case UNSUBSCRIBE: type = 0x0A; break; case UNSUBACK: type = 0x0B; break; case PINGREQ: type = 0x0C; break; case PINGRESP: type = 0x0D; break; case DISCONNECT: type = 0x0E; break; default: /* Should never happen */ FUNC_EXIT_RC(FAILURE); } pHeader->byte = type << 4; pHeader->byte |= dup << 3; switch(qos) { case QOS0: break; case QOS1: pHeader->byte |= 1 << 1; break; default: /* Using QOS0 as default */ break; } pHeader->byte |= (1 == retained) ? 0x01 : 0x00; FUNC_EXIT_RC(SUCCESS); } IoT_Error_t aws_iot_mqtt_internal_send_packet(AWS_IoT_Client *pClient, size_t length, Timer *pTimer) { size_t sentLen, sent; IoT_Error_t rc; FUNC_ENTRY; if(NULL == pClient || NULL == pTimer) { FUNC_EXIT_RC(NULL_VALUE_ERROR); } if(length >= pClient->clientData.writeBufSize) { FUNC_EXIT_RC(MQTT_TX_BUFFER_TOO_SHORT_ERROR); } #ifdef _ENABLE_THREAD_SUPPORT_ rc = aws_iot_mqtt_client_lock_mutex(pClient, &(pClient->clientData.tls_write_mutex)); if(SUCCESS != rc) { FUNC_EXIT_RC(rc); } #endif sentLen = 0; sent = 0; while(sent < length && !has_timer_expired(pTimer)) { rc = pClient->networkStack.write(&(pClient->networkStack), &pClient->clientData.writeBuf[sent], (length - sent), pTimer, &sentLen); if(SUCCESS != rc) { /* there was an error writing the data */ break; } sent += sentLen; } #ifdef _ENABLE_THREAD_SUPPORT_ rc = aws_iot_mqtt_client_unlock_mutex(pClient, &(pClient->clientData.tls_write_mutex)); if(SUCCESS != rc) { FUNC_EXIT_RC(rc); } #endif if(sent == length) { /* record the fact that we have successfully sent the packet */ //countdown_sec(&c->pingTimer, c->clientData.keepAliveInterval); FUNC_EXIT_RC(SUCCESS); } FUNC_EXIT_RC(rc); } static IoT_Error_t _aws_iot_mqtt_internal_readWrapper( AWS_IoT_Client *pClient, size_t offset, size_t size, Timer *pTimer, size_t * read_len ) { IoT_Error_t rc; int byteToRead; size_t byteRead = 0; byteToRead = ( offset + size ) - pClient->clientData.readBufIndex; if ( byteToRead > 0 ) { rc = pClient->networkStack.read( &( pClient->networkStack ), pClient->clientData.readBuf + pClient->clientData.readBufIndex, (size_t)byteToRead, pTimer, &byteRead ); pClient->clientData.readBufIndex += byteRead; /* refresh byte to read */ byteToRead = ( offset + size ) - ((int)pClient->clientData.readBufIndex); *read_len = size - (size_t)byteToRead; } else { *read_len = size; rc = SUCCESS; } return rc; } static IoT_Error_t _aws_iot_mqtt_internal_decode_packet_remaining_len(AWS_IoT_Client *pClient, size_t * offset, size_t *rem_len, Timer *pTimer) { size_t multiplier, len; IoT_Error_t rc; size_t read_len; FUNC_ENTRY; multiplier = 1; len = 0; *rem_len = 0; do { if(++len > MAX_NO_OF_REMAINING_LENGTH_BYTES) { /* bad data */ FUNC_EXIT_RC(MQTT_DECODE_REMAINING_LENGTH_ERROR); } rc = _aws_iot_mqtt_internal_readWrapper( pClient, len, 1, pTimer, &read_len ); if(SUCCESS != rc) { FUNC_EXIT_RC(rc); } *rem_len += (( pClient->clientData.readBuf[len] & 127) * multiplier); multiplier *= 128; } while(( pClient->clientData.readBuf[len] & 128) != 0); *offset = len + 1; FUNC_EXIT_RC(rc); } static IoT_Error_t _aws_iot_mqtt_internal_read_packet(AWS_IoT_Client *pClient, Timer *pTimer, uint8_t *pPacketType) { size_t rem_len, total_bytes_read, bytes_to_be_read, read_len; IoT_Error_t rc; size_t offset = 0; MQTTHeader header = {0}; Timer packetTimer; init_timer(&packetTimer); countdown_ms(&packetTimer, pClient->clientData.packetTimeoutMs); rem_len = 0; total_bytes_read = 0; bytes_to_be_read = 0; read_len = 0; rc = _aws_iot_mqtt_internal_readWrapper( pClient, offset, 1, pTimer, &read_len ); /* 1. read the header byte. This has the packet type in it */ if(NETWORK_SSL_NOTHING_TO_READ == rc) { return MQTT_NOTHING_TO_READ; } else if(SUCCESS != rc) { return rc; } /* 2. read the remaining length. This is variable in itself */ rc = _aws_iot_mqtt_internal_decode_packet_remaining_len(pClient, &offset, &rem_len, pTimer); if(SUCCESS != rc) { return rc; } /* if the buffer is too short then the message will be dropped silently */ if((rem_len + offset) >= pClient->clientData.readBufSize) { bytes_to_be_read = pClient->clientData.readBufSize; do { rc = pClient->networkStack.read(&(pClient->networkStack), pClient->clientData.readBuf, bytes_to_be_read, pTimer, &read_len); if(SUCCESS == rc) { total_bytes_read += read_len; if((rem_len - total_bytes_read) >= pClient->clientData.readBufSize) { bytes_to_be_read = pClient->clientData.readBufSize; } else { bytes_to_be_read = rem_len - total_bytes_read; } } } while(total_bytes_read < rem_len && SUCCESS == rc); /* Check buffer was correctly emptied, otherwise, return error message. */ if ( total_bytes_read == rem_len ) { aws_iot_mqtt_internal_flushBuffers( pClient ); return MQTT_RX_BUFFER_TOO_SHORT_ERROR; } else { return rc; } } /* 3. read the rest of the buffer using a callback to supply the rest of the data */ if(rem_len > 0) { rc = _aws_iot_mqtt_internal_readWrapper( pClient, offset, rem_len, pTimer, &read_len ); if(SUCCESS != rc || read_len != rem_len) { return FAILURE; } } /* Pack has been received, we can flush the buffers for next call. */ aws_iot_mqtt_internal_flushBuffers( pClient ); header.byte = pClient->clientData.readBuf[0]; *pPacketType = MQTT_HEADER_FIELD_TYPE(header.byte); FUNC_EXIT_RC(rc); } // assume topic filter and name is in correct format // # can only be at end // + and # can only be next to separator static bool _aws_iot_mqtt_internal_is_topic_matched(char *pTopicFilter, char *pTopicName, uint16_t topicNameLen) { char *curf, *curn, *curn_end; if(NULL == pTopicFilter || NULL == pTopicName) { return false; } curf = pTopicFilter; curn = pTopicName; curn_end = curn + topicNameLen; while(*curf && (curn < curn_end)) { if(*curn == '/' && *curf != '/') { break; } if(*curf != '+' && *curf != '#' && *curf != *curn) { break; } if(*curf == '+') { /* skip until we meet the next separator, or end of string */ char *nextpos = curn + 1; while(nextpos < curn_end && *nextpos != '/') nextpos = ++curn + 1; } else if(*curf == '#') { /* skip until end of string */ curn = curn_end - 1; } curf++; curn++; }; return (curn == curn_end) && (*curf == '\0'); } static IoT_Error_t _aws_iot_mqtt_internal_deliver_message(AWS_IoT_Client *pClient, char *pTopicName, uint16_t topicNameLen, IoT_Publish_Message_Params *pMessageParams) { uint32_t itr; IoT_Error_t rc; ClientState clientState; FUNC_ENTRY; if(NULL == pTopicName) { FUNC_EXIT_RC(NULL_VALUE_ERROR); } /* This function can be called from all MQTT APIs * But while callback return is in progress, Yield should not be called. * The state for CB_RETURN accomplishes that, as yield cannot be called while in that state */ clientState = aws_iot_mqtt_get_client_state(pClient); aws_iot_mqtt_set_client_state(pClient, clientState, CLIENT_STATE_CONNECTED_WAIT_FOR_CB_RETURN); /* Find the right message handler - indexed by topic */ for(itr = 0; itr < AWS_IOT_MQTT_NUM_SUBSCRIBE_HANDLERS; ++itr) { if(NULL != pClient->clientData.messageHandlers[itr].topicName) { if(((topicNameLen == pClient->clientData.messageHandlers[itr].topicNameLen) && (strncmp(pTopicName, (char *) pClient->clientData.messageHandlers[itr].topicName, topicNameLen) == 0)) || _aws_iot_mqtt_internal_is_topic_matched((char *) pClient->clientData.messageHandlers[itr].topicName, pTopicName, topicNameLen)) { if(NULL != pClient->clientData.messageHandlers[itr].pApplicationHandler) { pClient->clientData.messageHandlers[itr].pApplicationHandler(pClient, pTopicName, topicNameLen, pMessageParams, pClient->clientData.messageHandlers[itr].pApplicationHandlerData); } } } } rc = aws_iot_mqtt_set_client_state(pClient, CLIENT_STATE_CONNECTED_WAIT_FOR_CB_RETURN, clientState); FUNC_EXIT_RC(rc); } static IoT_Error_t _aws_iot_mqtt_internal_handle_publish(AWS_IoT_Client *pClient, Timer *pTimer) { char *topicName; uint16_t topicNameLen; uint32_t len; IoT_Error_t rc; IoT_Publish_Message_Params msg; FUNC_ENTRY; topicName = NULL; topicNameLen = 0; len = 0; rc = aws_iot_mqtt_internal_deserialize_publish(&msg.isDup, &msg.qos, &msg.isRetained, &msg.id, &topicName, &topicNameLen, (unsigned char **) &msg.payload, &msg.payloadLen, pClient->clientData.readBuf, pClient->clientData.readBufSize); if(SUCCESS != rc) { FUNC_EXIT_RC(rc); } rc = _aws_iot_mqtt_internal_deliver_message(pClient, topicName, topicNameLen, &msg); if(SUCCESS != rc) { FUNC_EXIT_RC(rc); } if(QOS0 == msg.qos) { /* No further processing required for QoS0 */ FUNC_EXIT_RC(SUCCESS); } /* Message assumed to be QoS1 since we do not support QoS2 at this time */ rc = aws_iot_mqtt_internal_serialize_ack(pClient->clientData.writeBuf, pClient->clientData.writeBufSize, PUBACK, 0, msg.id, &len); if(SUCCESS != rc) { FUNC_EXIT_RC(rc); } rc = aws_iot_mqtt_internal_send_packet(pClient, len, pTimer); if(SUCCESS != rc) { FUNC_EXIT_RC(rc); } FUNC_EXIT_RC(SUCCESS); } IoT_Error_t aws_iot_mqtt_internal_cycle_read(AWS_IoT_Client *pClient, Timer *pTimer, uint8_t *pPacketType) { IoT_Error_t rc; #ifdef _ENABLE_THREAD_SUPPORT_ IoT_Error_t threadRc; #endif if(NULL == pClient || NULL == pTimer) { return NULL_VALUE_ERROR; } #ifdef _ENABLE_THREAD_SUPPORT_ threadRc = aws_iot_mqtt_client_lock_mutex(pClient, &(pClient->clientData.tls_read_mutex)); if(SUCCESS != threadRc) { FUNC_EXIT_RC(threadRc); } #endif /* read the socket, see what work is due */ rc = _aws_iot_mqtt_internal_read_packet(pClient, pTimer, pPacketType); #ifdef _ENABLE_THREAD_SUPPORT_ threadRc = aws_iot_mqtt_client_unlock_mutex(pClient, &(pClient->clientData.tls_read_mutex)); if(SUCCESS != threadRc && (MQTT_NOTHING_TO_READ == rc || SUCCESS == rc)) { return threadRc; } #endif if(MQTT_NOTHING_TO_READ == rc) { /* Nothing to read, not a cycle failure */ return SUCCESS; } else if(SUCCESS != rc) { return rc; } switch(*pPacketType) { case CONNACK: case PUBACK: case SUBACK: case UNSUBACK: /* SDK is blocking, these responses will be forwarded to calling function to process */ break; case PUBLISH: { rc = _aws_iot_mqtt_internal_handle_publish(pClient, pTimer); break; } case PUBREC: case PUBCOMP: /* QoS2 not supported at this time */ break; case PINGRESP: { pClient->clientStatus.isPingOutstanding = 0; countdown_sec(&pClient->pingTimer, pClient->clientData.keepAliveInterval); break; } default: { /* Either unknown packet type or Failure occurred * Should not happen */ rc = MQTT_RX_MESSAGE_PACKET_TYPE_INVALID_ERROR; break; } } return rc; } IoT_Error_t aws_iot_mqtt_internal_flushBuffers( AWS_IoT_Client *pClient ) { pClient->clientData.readBufIndex = 0; return SUCCESS; } /* only used in single-threaded mode where one command at a time is in process */ IoT_Error_t aws_iot_mqtt_internal_wait_for_read(AWS_IoT_Client *pClient, uint8_t packetType, Timer *pTimer) { IoT_Error_t rc; uint8_t read_packet_type; FUNC_ENTRY; if(NULL == pClient || NULL == pTimer) { FUNC_EXIT_RC(NULL_VALUE_ERROR); } read_packet_type = 0; do { if(has_timer_expired(pTimer)) { /* we timed out */ rc = MQTT_REQUEST_TIMEOUT_ERROR; break; } rc = aws_iot_mqtt_internal_cycle_read(pClient, pTimer, &read_packet_type); } while(((SUCCESS == rc) || (MQTT_NOTHING_TO_READ == rc)) && (read_packet_type != packetType)); /* If rc is SUCCESS, we have received the expected * MQTT packet. Otherwise rc tells the error. */ FUNC_EXIT_RC(rc); } /** * Serializes a 0-length packet into the supplied buffer, ready for writing to a socket * @param buf the buffer into which the packet will be serialized * @param buflen the length in bytes of the supplied buffer, to avoid overruns * @param packettype the message type * @param serialized length * @return IoT_Error_t indicating function execution status */ IoT_Error_t aws_iot_mqtt_internal_serialize_zero(unsigned char *pTxBuf, size_t txBufLen, MessageTypes packetType, size_t *pSerializedLength) { unsigned char *ptr; IoT_Error_t rc; MQTTHeader header = {0}; FUNC_ENTRY; if(NULL == pTxBuf || NULL == pSerializedLength) { FUNC_EXIT_RC(NULL_VALUE_ERROR); } /* Buffer should have at least 2 bytes for the header */ if(4 > txBufLen) { FUNC_EXIT_RC(MQTT_TX_BUFFER_TOO_SHORT_ERROR); } ptr = pTxBuf; rc = aws_iot_mqtt_internal_init_header(&header, packetType, QOS0, 0, 0); if(SUCCESS != rc) { FUNC_EXIT_RC(rc); } /* write header */ aws_iot_mqtt_internal_write_char(&ptr, header.byte); /* write remaining length */ ptr += aws_iot_mqtt_internal_write_len_to_buffer(ptr, 0); *pSerializedLength = (uint32_t) (ptr - pTxBuf); FUNC_EXIT_RC(SUCCESS); } #ifdef __cplusplus } #endif
{'content_hash': '28f79ff7b36a8928fdfe68902c3b34fa', 'timestamp': '', 'source': 'github', 'line_count': 707, 'max_line_length': 144, 'avg_line_length': 27.342291371994342, 'alnum_prop': 0.654027210180539, 'repo_name': 'bouffalolab/bl_iot_sdk_matter', 'id': '6251dcfcd27bb819b26ca3bf448bf47d74017d94', 'size': '19901', 'binary': False, 'copies': '1', 'ref': 'refs/heads/release_spiwifi_bl602', 'path': 'components/3rdparty/aws-iot/aws-iot-device-sdk-embedded-C/src/aws_iot_mqtt_client_common_internal.c', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'Assembly', 'bytes': '46671'}, {'name': 'Batchfile', 'bytes': '1603'}, {'name': 'C', 'bytes': '24837905'}, {'name': 'C++', 'bytes': '14471862'}, {'name': 'CMake', 'bytes': '124252'}, {'name': 'HTML', 'bytes': '24826'}, {'name': 'Makefile', 'bytes': '114632'}, {'name': 'Perl', 'bytes': '2589'}, {'name': 'Python', 'bytes': '273291'}, {'name': 'Roff', 'bytes': '3255873'}, {'name': 'Shell', 'bytes': '27722'}, {'name': 'XC', 'bytes': '18410'}]}
<?php require __DIR__ . '/../src/ControlClient.php'; require __DIR__ . '/../src/TorCurlWrapper.php'; // list of country codes to use $countries = array('US', 'FR', 'RU', 'GB', 'CA'); // get new control client for connecting to Tor's control port $tc = new Dapphp\TorUtils\ControlClient(); $tc->connect(); // connect $tc->authenticate('password'); // authenticate foreach($countries as $country) { $country = '{' . $country . '}'; // e.g. {US} $tc->setConf(array('ExitNodes' => $country)); // set config to use exit node from country // get new curl wrapped through Tor SOCKS5 proxy $curl = new Dapphp\TorUtils\TorCurlWrapper(); $curl->setopt(CURLOPT_USERAGENT, 'Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:41.0) Gecko/20100101 Firefox 41.0'); // make request - should go through exit node from specified country if ($curl->httpGet('http://whatismycountry.com')) { echo $curl->getResponseBody(); } }
{'content_hash': '24295db58ae14e3b45b1944a35aa3684', 'timestamp': '', 'source': 'github', 'line_count': 28, 'max_line_length': 117, 'avg_line_length': 33.785714285714285, 'alnum_prop': 0.6479915433403806, 'repo_name': 'dapphp/TorUtils', 'id': 'a12680e17ca64b2fb015a1c9d91ddbf8fac242ab', 'size': '946', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'examples/CurlCountry.php', 'mode': '33188', 'license': 'bsd-3-clause', 'language': [{'name': 'PHP', 'bytes': '226858'}]}
using namespace fs; TEST_SUITE(recursive_directory_iterator_depth_tests) TEST_CASE(test_depth) { const path testDir = StaticEnv::Dir; const path DirDepth1 = StaticEnv::Dir2; const path DirDepth2 = StaticEnv::Dir3; const recursive_directory_iterator endIt{}; std::error_code ec; recursive_directory_iterator it(testDir, ec); TEST_REQUIRE(!ec); TEST_CHECK(it.depth() == 0); bool seen_d1, seen_d2; seen_d1 = seen_d2 = false; while (it != endIt) { const path entry = *it; const path parent = entry.parent_path(); if (parent == testDir) { TEST_CHECK(it.depth() == 0); } else if (parent == DirDepth1) { TEST_CHECK(it.depth() == 1); seen_d1 = true; } else if (parent == DirDepth2) { TEST_CHECK(it.depth() == 2); seen_d2 = true; } else { TEST_CHECK(!"Unexpected depth while iterating over static env"); } ++it; } TEST_REQUIRE(seen_d1 && seen_d2); TEST_CHECK(it == endIt); } TEST_SUITE_END()
{'content_hash': '8b4629d2b3e4e3d3b71a7a534b2b8f63', 'timestamp': '', 'source': 'github', 'line_count': 40, 'max_line_length': 76, 'avg_line_length': 27.025, 'alnum_prop': 0.5661424606845513, 'repo_name': 'youtube/cobalt_sandbox', 'id': '9b239c6bf441cf6f712e10eaa000349ba723e397', 'size': '1732', 'binary': False, 'copies': '4', 'ref': 'refs/heads/main', 'path': 'third_party/llvm-project/libcxx/test/std/input.output/filesystems/class.rec.dir.itr/rec.dir.itr.members/depth.pass.cpp', 'mode': '33188', 'license': 'bsd-3-clause', 'language': []}
describe ManageIQ::Providers::AnsibleRoleWorkflow do let(:job) { described_class.create_job(*options).tap { |job| job.state = state } } let(:role_options) { {:role_name => 'role_name', :roles_path => 'path/role', :role_skip_facts => true } } let(:options) { [{"ENV" => "VAR"}, {"arg1" => "val1"}, role_options, {:verbosity => 4}] } let(:state) { "waiting_to_start" } context ".create_job" do it "leaves job waiting to start" do expect(job.state).to eq("waiting_to_start") end end context ".signal" do %w[start pre_execute execute poll_runner post_execute finish abort_job cancel error].each do |signal| shared_examples_for "allows #{signal} signal" do it signal.to_s do expect(job).to receive(signal.to_sym) job.signal(signal.to_sym) end end end %w[start pre_execute execute poll_runner post_execute].each do |signal| shared_examples_for "doesn't allow #{signal} signal" do it signal.to_s do expect { job.signal(signal.to_sym) }.to raise_error(RuntimeError, /#{signal} is not permitted at state #{job.state}/) end end end context "waiting_to_start" do let(:state) { "waiting_to_start" } it_behaves_like "allows start signal" it_behaves_like "allows finish signal" it_behaves_like "allows abort_job signal" it_behaves_like "allows cancel signal" it_behaves_like "allows error signal" it_behaves_like "doesn't allow execute signal" it_behaves_like "doesn't allow poll_runner signal" it_behaves_like "doesn't allow post_execute signal" end context "per_role" do let(:state) { "pre_execute" } it_behaves_like "allows execute signal" it_behaves_like "allows finish signal" it_behaves_like "allows abort_job signal" it_behaves_like "allows cancel signal" it_behaves_like "allows error signal" it_behaves_like "doesn't allow start signal" it_behaves_like "doesn't allow poll_runner signal" it_behaves_like "doesn't allow post_execute signal" end context "running" do let(:state) { "running" } it_behaves_like "allows poll_runner signal" it_behaves_like "allows finish signal" it_behaves_like "allows abort_job signal" it_behaves_like "allows cancel signal" it_behaves_like "allows error signal" it_behaves_like "doesn't allow start signal" it_behaves_like "doesn't allow pre_execute signal" end context "post_execute" do let(:state) { "post_execute" } it_behaves_like "allows finish signal" it_behaves_like "allows abort_job signal" it_behaves_like "allows cancel signal" it_behaves_like "allows error signal" it_behaves_like "doesn't allow start signal" it_behaves_like "doesn't allow pre_execute signal" it_behaves_like "doesn't allow execute signal" it_behaves_like "doesn't allow poll_runner signal" it_behaves_like "doesn't allow post_execute signal" end end context ".execute" do let(:state) { "pre_execute" } let(:response_async) { Ansible::Runner::ResponseAsync.new(:base_dir => "/path/to/results") } it "ansible-runner succeeds" do response_async = Ansible::Runner::ResponseAsync.new(:base_dir => "/path/to/results") runner_options = [ {"ENV" => "VAR"}, {"arg1" => "val1"}, "role_name", { :roles_path => "path/role", :role_skip_facts => true } ] expect(Ansible::Runner).to receive(:run_role_async).with(*runner_options).and_return(response_async) expect(job).to receive(:queue_signal).with(:poll_runner) job.signal(:execute) expect(job.context[:ansible_runner_response]).to eq(response_async.dump) end it "ansible-runner fails" do expect(Ansible::Runner).to receive(:run_role_async).and_return(nil) expect(job).to receive(:queue_signal).with(:abort, "Failed to run ansible role", "error") job.signal(:execute) end end context "#current_job_timeout" do it "sets the job current timeout" do expect(job.current_job_timeout).to eq(1.hour) end end context ".poll_runner" do let(:state) { "running" } let(:response_async) { Ansible::Runner::ResponseAsync.new(:base_dir => "/path/to/results") } before do allow(Ansible::Runner::ResponseAsync).to receive(:new).and_return(response_async) job.context[:ansible_runner_response] = response_async.dump job.started_on = Time.now.utc job.save! end it "ansible-runner completed" do expect(response_async).to receive(:running?).and_return(false) response = Ansible::Runner::Response.new(response_async.dump.merge(:return_code => 0)) expect(response_async).to receive(:response).and_return(response) expect(job).to receive(:queue_signal).with(:post_execute) job.signal(:poll_runner) end it "ansible-runner still running" do now = Time.now.utc allow(Time).to receive(:now).and_return(now) expect(response_async).to receive(:running?).and_return(true) expect(job).to receive(:queue_signal).with(:poll_runner, :deliver_on => now + 1.second) job.signal(:poll_runner) end it "fails if the role has been running too long" do time = job.started_on + job.options[:timeout] + 5.minutes Timecop.travel(time) do expect(response_async).to receive(:running?).and_return(true) expect(response_async).to receive(:stop) expect(job).to receive(:queue_signal).with(:abort, "ansible role has been running longer than timeout", "error") job.signal(:poll_runner) end end context ".deliver_on" do let(:options) { [{"ENV" => "VAR"}, {"arg1" => "val1"}, {:roles_path => "/path/to/role"}, :poll_interval => 5.minutes] } it "uses the option to queue poll_runner" do now = Time.now.utc allow(Time).to receive(:now).and_return(now) expect(response_async).to receive(:running?).and_return(true) expect(job).to receive(:queue_signal).with(:poll_runner, :deliver_on => now + 5.minutes) job.signal(:poll_runner) end end end end
{'content_hash': '8b481f1ba064f655a2a5900901dada8b', 'timestamp': '', 'source': 'github', 'line_count': 182, 'max_line_length': 127, 'avg_line_length': 34.57692307692308, 'alnum_prop': 0.6367392340696011, 'repo_name': 'branic/manageiq', 'id': '6a5e182fd1769019477da73356775b076f8b1d6c', 'size': '6293', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'spec/models/manageiq/providers/ansible_role_workflow_spec.rb', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'CSS', 'bytes': '3042'}, {'name': 'Dockerfile', 'bytes': '2925'}, {'name': 'HTML', 'bytes': '2167'}, {'name': 'JavaScript', 'bytes': '183'}, {'name': 'Ruby', 'bytes': '7674578'}, {'name': 'Shell', 'bytes': '22469'}]}
package com.google.javascript.jscomp; import static com.google.javascript.jscomp.AstFactory.type; import static com.google.javascript.jscomp.Es6ToEs3Util.cannotConvertYet; import com.google.javascript.jscomp.NodeTraversal.AbstractPostOrderCallback; import com.google.javascript.jscomp.parsing.parser.FeatureSet; import com.google.javascript.jscomp.parsing.parser.FeatureSet.Feature; import com.google.javascript.rhino.Node; import com.google.javascript.rhino.Token; /** Transpiles away `new.target`. */ final class RewriteNewDotTarget implements CompilerPass { private static final FeatureSet TRANSPILED_FEATURES = FeatureSet.BARE_MINIMUM.with(Feature.NEW_TARGET); private final AbstractCompiler compiler; private final AstFactory astFactory; RewriteNewDotTarget(AbstractCompiler compiler) { this.compiler = compiler; this.astFactory = compiler.createAstFactory(); } private class RewriteNewDotTargetCallback extends AbstractPostOrderCallback { @Override public void visit(NodeTraversal t, Node n, Node parent) { if (n.getToken() == Token.NEW_TARGET) { final Node enclosingNonArrowFunction = NodeUtil.getEnclosingNonArrowFunction(n); if (enclosingNonArrowFunction != null && NodeUtil.isEs6Constructor(enclosingNonArrowFunction)) { // Within an ES6 class constructor that we're about to transpile. // `new.target` -> `this.constructor` Node enclosingClass = enclosingNonArrowFunction.getParent().getGrandparent(); n.replaceWith( astFactory .createGetProp( astFactory.createThisForEs6Class(enclosingClass), "constructor", type(n)) .srcrefTree(n)); t.reportCodeChange(); } else { // Getting new.target correct in functions other than transpiled ES6 class constructors // requires determining whether the function was called with `new` or not, which is more // hassle than its worth. There's no good reason to use `new.target` in such places // anyway. cannotConvertYet(compiler, n, "new.target"); } } } } @Override public void process(Node externs, Node root) { TranspilationPasses.processTranspile( compiler, root, TRANSPILED_FEATURES, new RewriteNewDotTargetCallback()); TranspilationPasses.maybeMarkFeaturesAsTranspiledAway(compiler, TRANSPILED_FEATURES); } }
{'content_hash': '3203ff54df229c1abb34049c1d2b8021', 'timestamp': '', 'source': 'github', 'line_count': 59, 'max_line_length': 98, 'avg_line_length': 41.66101694915254, 'alnum_prop': 0.7160292921074044, 'repo_name': 'googlechromelabs/chromeos_smart_card_connector', 'id': 'd674d2e29f8d35cee5e0d220682f6070e810d805', 'size': '3070', 'binary': False, 'copies': '3', 'ref': 'refs/heads/main', 'path': 'third_party/closure-compiler/src/src/com/google/javascript/jscomp/RewriteNewDotTarget.java', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'C', 'bytes': '4254'}, {'name': 'C++', 'bytes': '722639'}, {'name': 'CSS', 'bytes': '9725'}, {'name': 'HTML', 'bytes': '17393'}, {'name': 'JavaScript', 'bytes': '361786'}, {'name': 'Lua', 'bytes': '1704'}, {'name': 'Makefile', 'bytes': '116814'}, {'name': 'Python', 'bytes': '27331'}, {'name': 'Shell', 'bytes': '12794'}]}
# generated vars $packageName = 'keepass.portable' $url = 'https://sourceforge.net/projects/keepass/files/KeePass%202.x/2.38/KeePass-2.38.zip' $checksum = 'DB71CBA72C321ECAEDA7EEC6F4E71E215864D4113AB9E29DC97AD4D56C80A7A9' # static vars $checksumType = 'sha256' $toolsDir = "$(Split-Path -parent $MyInvocation.MyCommand.Definition)" # $Env:ChocolateyInstall\helpers\functions Install-ChocolateyZipPackage -PackageName "$packageName" ` -Url "$url" ` -UnzipLocation "$toolsDir" ` -Checksum "$checksum" ` -ChecksumType "$checksumType" # create empty sidecar so shimgen creates shim for GUI rather than console $installFile = Join-Path -Path $toolsDir ` -ChildPath "KeePass.exe.gui" Set-Content -Path $installFile ` -Value $null
{'content_hash': '08e577d31dae3e6d80f034171fa5cef3', 'timestamp': '', 'source': 'github', 'line_count': 21, 'max_line_length': 91, 'avg_line_length': 41.904761904761905, 'alnum_prop': 0.6386363636363637, 'repo_name': 'dtgm/chocolatey-packages', 'id': '52ceff69ed39a522c048eadb9c426fc1505475e3', 'size': '882', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'automatic/_output/keepass.portable/2.38/tools/chocolateyInstall.ps1', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'AutoHotkey', 'bytes': '347616'}, {'name': 'AutoIt', 'bytes': '13530'}, {'name': 'Batchfile', 'bytes': '1404'}, {'name': 'C#', 'bytes': '8134'}, {'name': 'HTML', 'bytes': '80818'}, {'name': 'PowerShell', 'bytes': '13124493'}]}
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 1.0 Transitional//EN"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <META http-equiv="Content-Type" content="text/html; charset=UTF-8"> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <link rel="stylesheet" href="../includes/main.css" type="text/css"> <link rel="shortcut icon" href="../favicon.ico" type="image/x-icon"> <title>Apache CloudStack | The Power Behind Your Cloud</title> </head> <body> <div id="insidetopbg"> <div id="inside_wrapper"> <div class="uppermenu_panel"> <div class="uppermenu_box"></div> </div> <div id="main_master"> <div id="inside_header"> <div class="header_top"> <a class="cloud_logo" href="http://cloudstack.org"></a> <div class="mainemenu_panel"></div> </div> </div> <div id="main_content"> <div class="inside_apileftpanel"> <div class="inside_contentpanel" style="width:930px;"> <div class="api_titlebox"> <div class="api_titlebox_left"> <span> Apache CloudStack 4.15.0.0 Root Admin API Reference </span> <p></p> <h1>createCondition</h1> <p>Creates a condition</p> </div> <div class="api_titlebox_right"> <a class="api_backbutton" href="../index.html"></a> </div> </div> <div class="api_tablepanel"> <h2>Request parameters</h2> <table class="apitable"> <tr class="hed"> <td style="width:200px;"><strong>Parameter Name</strong></td><td style="width:500px;">Description</td><td style="width:180px;">Required</td> </tr> <tr> <td style="width:200px;"><strong>counterid</strong></td><td style="width:500px;"><strong>ID of the Counter.</strong></td><td style="width:180px;"><strong>true</strong></td> </tr> <tr> <td style="width:200px;"><strong>relationaloperator</strong></td><td style="width:500px;"><strong>Relational Operator to be used with threshold.</strong></td><td style="width:180px;"><strong>true</strong></td> </tr> <tr> <td style="width:200px;"><strong>threshold</strong></td><td style="width:500px;"><strong>Threshold value.</strong></td><td style="width:180px;"><strong>true</strong></td> </tr> <tr> <td style="width:200px;"><i>account</i></td><td style="width:500px;"><i>the account of the condition. Must be used with the domainId parameter.</i></td><td style="width:180px;"><i>false</i></td> </tr> <tr> <td style="width:200px;"><i>domainid</i></td><td style="width:500px;"><i>the domain ID of the account.</i></td><td style="width:180px;"><i>false</i></td> </tr> </table> </div> <div class="api_tablepanel"> <h2>Response Tags</h2> <table class="apitable"> <tr class="hed"> <td style="width:200px;"><strong>Response Name</strong></td><td style="width:500px;">Description</td> </tr> <tr> <td style="width:200px;"><strong>id</strong></td><td style="width:500px;">the id of the Condition</td> </tr> <tr> <td style="width:200px;"><strong>account</strong></td><td style="width:500px;">the owner of the Condition.</td> </tr> <tr> <td style="width:200px;"><strong>counter</strong></td><td style="width:500px;">Details of the Counter.</td> </tr> <tr> <td style="width:200px;"><strong>domain</strong></td><td style="width:500px;">the domain name of the owner.</td> </tr> <tr> <td style="width:200px;"><strong>domainid</strong></td><td style="width:500px;">the domain id of the Condition owner</td> </tr> <tr> <td style="width:200px;"><strong>project</strong></td><td style="width:500px;">the project name of the Condition</td> </tr> <tr> <td style="width:200px;"><strong>projectid</strong></td><td style="width:500px;">the project id of the Condition.</td> </tr> <tr> <td style="width:200px;"><strong>relationaloperator</strong></td><td style="width:500px;">Relational Operator to be used with threshold.</td> </tr> <tr> <td style="width:200px;"><strong>threshold</strong></td><td style="width:500px;">Threshold Value for the counter.</td> </tr> <tr> <td style="width:200px;"><strong>zoneid</strong></td><td style="width:500px;">zone id of counter</td> </tr> </table> </div> </div> </div> </div> </div> <div id="footer"> <div id="comments_thread"> <script type="text/javascript" src="https://comments.apache.org/show_comments.lua?site=test" async="true"></script> <noscript> <iframe width="930" height="500" src="https://comments.apache.org/iframe.lua?site=test&amp;page=4.2.0/rootadmin"></iframe> </noscript> </div> <div id="footer_mainmaster"> <p> Copyright &copy; 2015 The Apache Software Foundation, Licensed under the <a href="http://www.apache.org/licenses/LICENSE-2.0">Apache License, Version 2.0.</a> <br> Apache, CloudStack, Apache CloudStack, the Apache CloudStack logo, the CloudMonkey logo and the Apache feather logo are trademarks of The Apache Software Foundation. </p> </div> </div> </div> </div> </body> </html>
{'content_hash': 'd5bb686f7cef5e7575a56e95e4772eca', 'timestamp': '', 'source': 'github', 'line_count': 123, 'max_line_length': 253, 'avg_line_length': 67.869918699187, 'alnum_prop': 0.38236703402012456, 'repo_name': 'apache/cloudstack-www', 'id': '95dae97d397a5fefb80d9c840ba4d3634f1a39b9', 'size': '8348', 'binary': False, 'copies': '4', 'ref': 'refs/heads/main', 'path': 'content/api/apidocs-4.15/apis/createCondition.html', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'CSS', 'bytes': '568290'}, {'name': 'HTML', 'bytes': '222229805'}, {'name': 'JavaScript', 'bytes': '61116'}, {'name': 'Python', 'bytes': '3284'}, {'name': 'Ruby', 'bytes': '1973'}, {'name': 'Shell', 'bytes': '873'}]}
{% extends "xblog/blog_base.html" %} {% block maincontent %} <form action="" method="post">{% csrf_token %} <button type="submit">Save</button> </form> {% endblock %}
{'content_hash': 'b04f11482951afefef9f52440da6ea38', 'timestamp': '', 'source': 'github', 'line_count': 8, 'max_line_length': 46, 'avg_line_length': 22.125, 'alnum_prop': 0.6045197740112994, 'repo_name': 'rubeon/django-xblog', 'id': 'a6d7d2442ec3977dfad1a57ea3fc36c5f8767cd0', 'size': '177', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'xblog/templates/xblog/author_form.html', 'mode': '33188', 'license': 'bsd-2-clause', 'language': [{'name': 'CSS', 'bytes': '73797'}, {'name': 'HTML', 'bytes': '11830'}, {'name': 'JavaScript', 'bytes': '498'}, {'name': 'Python', 'bytes': '242211'}]}
package com.ezweather.app.activity; import android.app.Activity; import android.app.ProgressDialog; import android.content.Intent; import android.content.SharedPreferences; import android.os.Bundle; import android.preference.PreferenceManager; import android.text.TextUtils; import android.util.Log; import android.view.View; import android.view.Window; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.ListView; import android.widget.TextView; import android.widget.Toast; import com.ezweather.app.R; import com.ezweather.app.model.City; import com.ezweather.app.model.County; import com.ezweather.app.db.EzWeatherDB; import com.ezweather.app.model.Province; import com.ezweather.app.util.HttpCallbackListener; import com.ezweather.app.util.HttpUtil; import com.ezweather.app.util.Utility; import java.util.ArrayList; import java.util.List; /** * Created by Oniros on 2016/4/8. */ public class ChooseAreaActivity extends Activity { public static final int LEVEL_PROVINCE = 0; public static final int LEVEL_CITY = 1; public static final int LEVEL_COUNTY = 2; private ProgressDialog progressDialog; private TextView titleText; private ListView listView; private ArrayAdapter<String> adapter; private EzWeatherDB ezWeatherDB; private List<String> dataList = new ArrayList<String>(); /** * 省列表 */ private List<Province> provinceList; /** * 市列表 */ private List<City> cityList; /** * 县列表 */ private List<County> countyList; /** * 选中的省份 */ private Province selectedProvince; /** * 选中的城市 */ private City selectedCity; /** * 当前选中的级别 */ private int currentLevel; /** * 是否从WeatherActivity中跳转过来。 */ private boolean isFromWeatherActivity; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); isFromWeatherActivity = getIntent().getBooleanExtra("from_weather_activity", false); SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this); if (prefs.getBoolean("city_selected", false) && !isFromWeatherActivity) { Intent intent = new Intent(this, WeatherActivity.class); startActivity(intent); finish(); return; } requestWindowFeature(Window.FEATURE_NO_TITLE); setContentView(R.layout.choose_area); listView = (ListView) findViewById(R.id.list_view); titleText = (TextView) findViewById(R.id.title_text); adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, dataList); listView.setAdapter(adapter); ezWeatherDB = EzWeatherDB.getInstance(this); listView.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> arg0, View view, int index, long arg3) { if (currentLevel == LEVEL_PROVINCE) { selectedProvince = provinceList.get(index); queryCities(); } else if (currentLevel == LEVEL_CITY) { selectedCity = cityList.get(index); queryCounties(); } else if (currentLevel == LEVEL_COUNTY) { String countyCode = countyList.get(index).getCountyCode(); Intent intent = new Intent(ChooseAreaActivity.this, WeatherActivity.class); intent.putExtra("county_code", countyCode); startActivity(intent); finish(); } } }); queryProvinces(); // 加载省级数据 } /** * 查询全国所有的省,优先从数据库查询,如果没有查询到再去服务器上查询。 */ private void queryProvinces() { provinceList =ezWeatherDB .loadProvince(); if (provinceList.size() > 0) { dataList.clear(); for (Province province : provinceList) { dataList.add(province.getProvinceName()); } adapter.notifyDataSetChanged(); listView.setSelection(0); titleText.setText("中国"); currentLevel = LEVEL_PROVINCE; } else { queryFromServer(null, "province"); } } /** * 查询选中省内所有的市,优先从数据库查询,如果没有查询到再去服务器上查询。 */ private void queryCities() { cityList = ezWeatherDB.loadCities(selectedProvince.getId()); if (cityList.size() > 0) { dataList.clear(); for (City city : cityList) { dataList.add(city.getCityName()); } adapter.notifyDataSetChanged(); listView.setSelection(0); titleText.setText(selectedProvince.getProvinceName()); currentLevel = LEVEL_CITY; } else { queryFromServer(selectedProvince.getProvinceCode(), "city"); } } /** * 查询选中市内所有的县,优先从数据库查询,如果没有查询到再去服务器上查询。 */ private void queryCounties() { countyList = ezWeatherDB.loadCounties(selectedCity.getId()); if (countyList.size() > 0) { dataList.clear(); for (County county : countyList) { dataList.add(county.getCountyName()); } adapter.notifyDataSetChanged(); listView.setSelection(0); titleText.setText(selectedCity.getCityName()); currentLevel = LEVEL_COUNTY; } else { queryFromServer(selectedCity.getCityCode(), "county"); } } /** * 根据传入的代号和类型从服务器上查询省市县数据。 */ private void queryFromServer(final String code, final String type) { String address; if (!TextUtils.isEmpty(code)) { address = "http://www.weather.com.cn/data/list3/city" + code + ".xml"; } else { address = "http://www.weather.com.cn/data/list3/city.xml"; } showProgressDialog(); HttpUtil.sendHttpRequest(address, new HttpCallbackListener() { @Override public void onFinish(String response) { boolean result = false; if ("province".equals(type)) { result = Utility.handleProvinceResponse(ezWeatherDB, response); } else if ("city".equals(type)) { result = Utility.handleCitiesResponse(ezWeatherDB, response, selectedProvince.getId()); } else if ("county".equals(type)) { result = Utility.handleCountiesResponse(ezWeatherDB, response, selectedCity.getId()); } if (result) { // 通过runOnUiThread()方法回到主线程处理逻辑 runOnUiThread(new Runnable() { @Override public void run() { closeProgressDialog(); if ("province".equals(type)) { queryProvinces(); } else if ("city".equals(type)) { queryCities(); } else if ("county".equals(type)) { queryCounties(); } } }); } } @Override public void onError(Exception e) { // 通过runOnUiThread()方法回到主线程处理逻辑 runOnUiThread(new Runnable() { @Override public void run() { closeProgressDialog(); Toast.makeText(ChooseAreaActivity.this, "加载失败", Toast.LENGTH_SHORT).show(); } }); } }); } /** * 显示进度对话框 */ private void showProgressDialog() { if (progressDialog == null) { progressDialog = new ProgressDialog(this); progressDialog.setMessage("正在加载..."); progressDialog.setCanceledOnTouchOutside(false); } progressDialog.show(); } /** * 关闭进度对话框 */ private void closeProgressDialog() { if (progressDialog != null) { progressDialog.dismiss(); } } /** * 捕获Back按键,根据当前的级别来判断,此时应该返回市列表、省列表、还是直接退出。 */ @Override public void onBackPressed() { if (currentLevel == LEVEL_COUNTY) { queryCities(); } else if (currentLevel == LEVEL_CITY) { queryProvinces(); } else { if (isFromWeatherActivity) { // Intent intent = new Intent(this, WeatherActivity.class); // startActivity(intent); } finish(); } } }
{'content_hash': '56caf12ddd93e032926c8c13d38247b9', 'timestamp': '', 'source': 'github', 'line_count': 269, 'max_line_length': 96, 'avg_line_length': 33.152416356877325, 'alnum_prop': 0.554047992823503, 'repo_name': 'Oniros6/EZweather', 'id': '214a3f813e79026dda311f952e041527230eca2a', 'size': '9432', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'app/src/main/java/com/ezweather/app/activity/ChooseAreaActivity.java', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'Java', 'bytes': '33766'}]}
namespace crashpad { class ProcessReaderWin; namespace internal { class ExceptionSnapshotWin final : public ExceptionSnapshot { public: ExceptionSnapshotWin(); ~ExceptionSnapshotWin() override; //! \brief Initializes the object. //! //! \param[in] process_reader A ProcessReader for the process that sustained //! the exception. //! \param[in] thread_id The thread ID in which the exception occurred. //! \param[in] exception_pointers_address The address of an //! `EXCEPTION_POINTERS` record in the target process, passed through from //! the exception handler. //! //! \return `true` if the snapshot could be created, `false` otherwise with //! an appropriate message logged. bool Initialize(ProcessReaderWin* process_reader, DWORD thread_id, WinVMAddress exception_pointers); // ExceptionSnapshot: const CPUContext* Context() const override; uint64_t ThreadID() const override; uint32_t Exception() const override; uint32_t ExceptionInfo() const override; uint64_t ExceptionAddress() const override; const std::vector<uint64_t>& Codes() const override; private: #if defined(ARCH_CPU_X86_FAMILY) union { CPUContextX86 x86; CPUContextX86_64 x86_64; } context_union_; #endif CPUContext context_; std::vector<uint64_t> codes_; uint64_t thread_id_; uint64_t exception_address_; uint32_t exception_flags_; DWORD exception_code_; InitializationStateDcheck initialized_; DISALLOW_COPY_AND_ASSIGN(ExceptionSnapshotWin); }; } // namespace internal } // namespace crashpad #endif // CRASHPAD_SNAPSHOT_WIN_EXCEPTION_SNAPSHOT_WIN_H_
{'content_hash': '773c56745f5f05e787f04e40773ce653', 'timestamp': '', 'source': 'github', 'line_count': 57, 'max_line_length': 80, 'avg_line_length': 29.12280701754386, 'alnum_prop': 0.7096385542168675, 'repo_name': 'Teamxrtc/webrtc-streaming-node', 'id': '588c4ac9f642452d54534bf6c1916a7022b5de8c', 'size': '2659', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'third_party/webrtc/src/chromium/src/third_party/crashpad/crashpad/snapshot/win/exception_snapshot_win.h', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'Batchfile', 'bytes': '44'}, {'name': 'C++', 'bytes': '221840'}, {'name': 'HTML', 'bytes': '2383'}, {'name': 'JavaScript', 'bytes': '37396'}, {'name': 'Python', 'bytes': '2860'}, {'name': 'Shell', 'bytes': '104'}]}
/* * timeval.h 1.0 01/12/19 * * Defines gettimeofday, timeval, etc. for Win32 * * By Wu Yongwei * */ #ifndef _TIMEVAL_H #define _TIMEVAL_H #ifdef _WIN32 /* Modified to compile as ANSI C without include of windows.h If this gives problems with future Windows/MSC versions, then uncomment the USE_WINDOWS_H definition to switch back. */ /* #define USE_WINDOWS_H */ #ifdef USE_WINDOWS_H #define WIN32_LEAN_AND_MEAN #include <windows.h> #else #ifndef _INC_WINDOWS #define VOID void #define WINAPI __stdcall #define OUT #define WINBASEAPI typedef long LONG; typedef unsigned long DWORD; typedef __int64 LONGLONG; typedef struct _FILETIME { DWORD dwLowDateTime; DWORD dwHighDateTime; } FILETIME, *LPFILETIME; typedef union _LARGE_INTEGER { /* Removed unnamed struct, it is not ANSI C compatible*/ /* struct { DWORD LowPart; LONG HighPart; }; */ struct { DWORD LowPart; LONG HighPart; } u; LONGLONG QuadPart; } LARGE_INTEGER; WINBASEAPI VOID WINAPI GetSystemTimeAsFileTime(OUT LPFILETIME lpSystemTimeAsFileTime); #endif /* _INC_WINDOWS */ #endif /* USE_WINDOWS_H */ #include <time.h> #ifndef __GNUC__ #define EPOCHFILETIME (116444736000000000i64) #else #define EPOCHFILETIME (116444736000000000LL) #endif struct timeval { long tv_sec; /* seconds */ long tv_usec; /* microseconds */ }; struct timezone { int tz_minuteswest; /* minutes W of Greenwich */ int tz_dsttime; /* type of dst correction */ }; __inline int gettimeofday(struct timeval *tv, struct timezone *tz) { FILETIME ft; LARGE_INTEGER li; __int64 t; static int tzflag; if (tv) { GetSystemTimeAsFileTime(&ft); /* The following two lines have been modified to use the named union member. Unnamed members are not ANSI C compatible. */ li.u.LowPart = ft.dwLowDateTime; li.u.HighPart = ft.dwHighDateTime; t = li.QuadPart; /* In 100-nanosecond intervals */ t -= EPOCHFILETIME; /* Offset to the Epoch time */ t /= 10; /* In microseconds */ tv->tv_sec = (long)(t / 1000000); tv->tv_usec = (long)(t % 1000000); } if (tz) { if (!tzflag) { _tzset(); tzflag++; } tz->tz_minuteswest = _timezone / 60; tz->tz_dsttime = _daylight; } return 0; } #else /* _WIN32 */ #include <sys/time.h> #endif /* _WIN32 */ #endif /* _TIMEVAL_H */
{'content_hash': '1a6559bbdae2ef5db88bf00c8b922f71', 'timestamp': '', 'source': 'github', 'line_count': 119, 'max_line_length': 70, 'avg_line_length': 23.352941176470587, 'alnum_prop': 0.5588341129902843, 'repo_name': 'egorpushkin/neurolab', 'id': '58b1f24f0b3ce0ab671619f2d25379db8e17208f', 'size': '3639', 'binary': False, 'copies': '2', 'ref': 'refs/heads/master', 'path': 'source/Plugins/ScriptEnv/LuaNeuroApi/Extensions/Training/fann_1.2.1/Engine/compat_time.h', 'mode': '33261', 'license': 'mit', 'language': [{'name': 'Batchfile', 'bytes': '112'}, {'name': 'C', 'bytes': '1787692'}, {'name': 'C++', 'bytes': '9312245'}, {'name': 'CSS', 'bytes': '44465'}, {'name': 'Clarion', 'bytes': '5268'}, {'name': 'HTML', 'bytes': '408820'}, {'name': 'JavaScript', 'bytes': '5476'}, {'name': 'Makefile', 'bytes': '39256'}, {'name': 'Objective-C', 'bytes': '97952'}, {'name': 'TeX', 'bytes': '3128'}]}
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:id="@+id/poi_description_container" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" android:visibility="visible" tools:visibility="visible"> <TextView android:id="@+id/poi_description" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginEnd="@dimen/margin_base" android:layout_marginLeft="@dimen/margin_base" android:layout_marginRight="@dimen/margin_base" android:layout_marginStart="@dimen/margin_base" android:layout_marginTop="@dimen/margin_base" android:maxLength="2000" android:textAppearance="?android:attr/textAppearance"/> <TextView android:id="@+id/more_btn" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="start|bottom" android:layout_marginEnd="@dimen/margin_base" android:layout_marginLeft="@dimen/margin_base" android:layout_marginRight="@dimen/margin_base" android:layout_marginStart="@dimen/margin_base" android:textAppearance="?android:attr/textAppearance" android:gravity="start|top" android:textColor="?attr/colorAccent" android:text="@string/category_desc_more" android:background="@android:color/transparent"/> <include layout="@layout/divider_horizontal"/> </LinearLayout>
{'content_hash': '80daabfb0b4835ea145f6d3ece59d905', 'timestamp': '', 'source': 'github', 'line_count': 40, 'max_line_length': 60, 'avg_line_length': 38.225, 'alnum_prop': 0.7325049051667757, 'repo_name': 'alexzatsepin/omim', 'id': 'cf02975a35749ef615c2a85fc58f923ac78992db', 'size': '1529', 'binary': False, 'copies': '2', 'ref': 'refs/heads/master', 'path': 'android/res/layout/place_page_description_layout.xml', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'Awk', 'bytes': '3962'}, {'name': 'Batchfile', 'bytes': '5586'}, {'name': 'C', 'bytes': '13984459'}, {'name': 'C++', 'bytes': '148411082'}, {'name': 'CMake', 'bytes': '249320'}, {'name': 'CSS', 'bytes': '26798'}, {'name': 'Common Lisp', 'bytes': '17587'}, {'name': 'DIGITAL Command Language', 'bytes': '36710'}, {'name': 'GLSL', 'bytes': '58384'}, {'name': 'Gherkin', 'bytes': '305230'}, {'name': 'Go', 'bytes': '12771'}, {'name': 'HTML', 'bytes': '9503594'}, {'name': 'Inno Setup', 'bytes': '4337'}, {'name': 'Java', 'bytes': '2486120'}, {'name': 'JavaScript', 'bytes': '29076'}, {'name': 'Lua', 'bytes': '57672'}, {'name': 'M4', 'bytes': '53992'}, {'name': 'Makefile', 'bytes': '429637'}, {'name': 'Metal', 'bytes': '77540'}, {'name': 'Module Management System', 'bytes': '2080'}, {'name': 'Objective-C', 'bytes': '2046640'}, {'name': 'Objective-C++', 'bytes': '1300948'}, {'name': 'PHP', 'bytes': '2841'}, {'name': 'Perl', 'bytes': '57807'}, {'name': 'PowerShell', 'bytes': '1885'}, {'name': 'Python', 'bytes': '584274'}, {'name': 'Roff', 'bytes': '13545'}, {'name': 'Ruby', 'bytes': '66800'}, {'name': 'Shell', 'bytes': '1317925'}, {'name': 'Swift', 'bytes': '511409'}, {'name': 'sed', 'bytes': '236'}]}
#include <sys/types.h> #include <sys/stat.h> #include <sys/mman.h> #include <sys/socket.h> #include <sys/time.h> #include <fcntl.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <stdint.h> #include <arpa/inet.h> #include <pcap.h> #include <ccn/ccn.h> #include <ccn/ccnd.h> #define LLC_LENGTH 4 #define IP_OFFSET LLC_LENGTH #define IP_ADDR_LENGTH 4 #define IP_HDR_LENGTH 20 #define IP_LENGTH_OFFSET IP_OFFSET + 2 #define IP_CHKSUM_OFFSET IP_OFFSET + 10 #define IP_SRC_ADDR_OFFSET IP_CHKSUM_OFFSET + 2 #define IP_DEST_ADDR_OFFSET IP_CHKSUM_OFFSET + IP_ADDR_LENGTH #define UDP_OFFSET IP_OFFSET + IP_HDR_LENGTH #define UDP_HDR_LENGTH 8 #define UDP_LENGTH_OFFSET UDP_OFFSET + 4 #define UDP_CHKSUM_OFFSET UDP_OFFSET + 6 #define DATA_OFFSET UDP_OFFSET + UDP_HDR_LENGTH #define MAX_PACKET 65536 #define DEFAULT_SRC_PORT 55555 #define DEFAULT_DEST_PORT CCN_DEFAULT_UNICAST_PORT_NUMBER static void usage(const char *progname) { fprintf(stderr, "%s <infile> [<infile> ...]\n" " Reads ccnb blocks from one or more files, and writes them in pcap format\n" " to stdout.\n" " ccnb blocks can be generated by any of the other utility programs.\n", progname); exit(1); } static int dump_udp_packet(pcap_dumper_t *dump_file, unsigned char *ip_src_addr, /* ipv4, localhost if NULL */ unsigned char *ip_dest_addr, /* localhost if NULL */ unsigned short udp_src_port, /* 55555 if 0 */ unsigned short udp_dest_port, const unsigned char *data, size_t data_len, /* data; could be whole ccnb, could just be contents */ struct timeval *ts) { /* timing info */ unsigned char pktbuf[MAX_PACKET]; uint32_t llc_val = PF_INET; // in host byte order uint16_t nsrc_port = htons((0 == udp_src_port) ? DEFAULT_SRC_PORT : udp_src_port); uint16_t ndest_port = htons((0 == udp_dest_port) ? DEFAULT_DEST_PORT : udp_dest_port); uint16_t nudp_len = htons(data_len + UDP_HDR_LENGTH); uint16_t nip_len = htons(data_len + UDP_HDR_LENGTH + IP_HDR_LENGTH); size_t frame_len = data_len + UDP_HDR_LENGTH + IP_HDR_LENGTH + LLC_LENGTH; struct pcap_pkthdr pcap_header; const unsigned char ipHdr[] = { // IP header, localhost to localhost 0x45, // IPv4, 20 byte header 0x00, // diff serv field 0x00, 0x00, // length -- UDP length + 20 0x1a, 0x62, // identification 0x00, // flags 0x00, // fragment offset 0x40, // TTL (64) 0x11, // proto (UDP=11) 0x00, 0x00, // ip checksum (calculate, or leave 0 for validation disabled) 0x7f, 0x00, 0x00, 0x01, // source, localhost if not overwritten 0x7f, 0x00, 0x00, 0x01 // dest, localhost if not overwritten }; unsigned char udpHdr[UDP_HDR_LENGTH]; memset(udpHdr, 0, UDP_HDR_LENGTH); memcpy(&pktbuf[0], (unsigned char *)&llc_val, LLC_LENGTH); memcpy(&pktbuf[IP_OFFSET], ipHdr, IP_HDR_LENGTH); memcpy(&pktbuf[IP_LENGTH_OFFSET], &nip_len, 2); if (NULL != ip_src_addr) { memcpy(&pktbuf[IP_SRC_ADDR_OFFSET], ip_src_addr, IP_ADDR_LENGTH); } if (NULL != ip_dest_addr) { memcpy(&pktbuf[IP_DEST_ADDR_OFFSET], ip_dest_addr, IP_ADDR_LENGTH); } memcpy(&pktbuf[UDP_OFFSET], &nsrc_port, sizeof(unsigned short)); memcpy(&pktbuf[UDP_OFFSET + sizeof(unsigned short)], &ndest_port, sizeof(unsigned short)); memcpy(&pktbuf[UDP_LENGTH_OFFSET], &nudp_len, sizeof(unsigned short)); memcpy(&pktbuf[DATA_OFFSET], data, data_len); pcap_header.len = pcap_header.caplen = frame_len; if (NULL != ts) { pcap_header.ts.tv_sec = ts->tv_sec; pcap_header.ts.tv_usec = ts->tv_usec; } pcap_dump((unsigned char *)dump_file, &pcap_header, &pktbuf[0]); if (0 != pcap_dump_flush(dump_file)) { fprintf(stderr, "Error flushing pcap dump...\n"); return -1; } return 0; } static int process_test(pcap_dumper_t *pcap_out, int content_only, unsigned char *ip_src_addr, /* ipv4, localhost if NULL */ unsigned char *ip_dest_addr, /* localhost if NULL */ unsigned short udp_src_port, /* 55555 if 0 */ unsigned short udp_dest_port, unsigned char *data, size_t n) { struct ccn_skeleton_decoder skel_decoder = {0}; struct ccn_skeleton_decoder *d = &skel_decoder; struct ccn_parsed_ContentObject content; struct ccn_indexbuf *comps = ccn_indexbuf_create(); const unsigned char * content_value; size_t content_length; int res = 0; size_t s; retry: s = ccn_skeleton_decode(d, data, n); if (d->state < 0) { res = 1; fprintf(stderr, "error state %d after %d of %d chars\n", (int)d->state, (int)s, (int)n); } else if (s == 0) { fprintf(stderr, "nothing to do\n"); } else { if (s < n) { if (!content_only) { if (dump_udp_packet(pcap_out, ip_src_addr, ip_dest_addr, udp_src_port, udp_dest_port, data, s, NULL) != 0) { res = 2; } } else { if (ccn_parse_ContentObject(data, s, &content, comps) != 0) { fprintf(stderr, "unable to parse content object\n"); res = 1; } else if (ccn_content_get_value(data, s, &content, &content_value, &content_length) != 0) { fprintf(stderr, "unable to retrieve content value\n"); res = 1; } else if (dump_udp_packet(pcap_out, ip_src_addr, ip_dest_addr, udp_src_port, udp_dest_port, content_value, content_length, NULL) != 0) { res = 2; } } /* fprintf(stderr, "resuming at index %d\n", (int)d->index); */ data += s; n -= s; if (res != 0) { fprintf(stderr, "Error dumping content.\n"); return res; } goto retry; } fprintf(stderr, "\n"); } if (!CCN_FINAL_DSTATE(d->state)) { res = 1; fprintf(stderr, "incomplete state %d after %d of %d chars\n", (int)d->state, (int)s, (int)n); } else { if (!content_only) { if (dump_udp_packet(pcap_out, ip_src_addr, ip_dest_addr, udp_src_port, udp_dest_port, data, s, NULL) != 0) { res = 2; } } else { if (ccn_parse_ContentObject(data, s, &content, comps) != 0) { fprintf(stderr, "unable to parse content object\n"); res = 1; } else if (ccn_content_get_value(data, s, &content, &content_value, &content_length) != 0) { fprintf(stderr, "unable to retrieve content value\n"); res = 1; } else if (dump_udp_packet(pcap_out, ip_src_addr, ip_dest_addr, udp_src_port, udp_dest_port, content_value, content_length, NULL) != 0) { res = 2; } } res = 1; } return(res); } static int process_fd(pcap_dumper_t *pcap_out, int fd, int content_only, unsigned char *ip_src_addr, /* ipv4, localhost if NULL */ unsigned char *ip_dest_addr, /* localhost if NULL */ unsigned short udp_src_port, /* 55555 if 0 */ unsigned short udp_dest_port ) { unsigned char *buf; ssize_t len; struct stat s; int res = 0; res = fstat(fd, &s); len = s.st_size; buf = (unsigned char *)mmap((void *)NULL, len, PROT_READ, MAP_PRIVATE, fd, 0); if (buf == (void *)-1) return (1); fprintf(stderr, " <!-- input is %6lu bytes -->\n", (unsigned long)len); res |= process_test(pcap_out, content_only, ip_src_addr, ip_dest_addr, udp_src_port, udp_dest_port, buf, len); munmap((void *)buf, len); return(res); } int main(int argc, char **argv) { pcap_t *pcap = NULL; pcap_dumper_t *pcap_out = NULL; int fd; int i; int res = 0; if (argc < 2) { usage(argv[0]); } pcap = pcap_open_dead(DLT_NULL, MAX_PACKET); if (NULL == pcap) { fprintf(stderr, "Cannot open pcap descriptor!\n"); exit(-1); } pcap_out = pcap_dump_open(pcap, "-"); if (NULL == pcap_out) { fprintf(stderr, "Cannot open output stdout!\n"); usage(argv[0]); } for (i = 1; argv[i] != 0; i++) { fprintf(stderr, "<!-- Processing %s -->\n", argv[i]); fd = open(argv[i], O_RDONLY); if (-1 == fd) { perror(argv[i]); return(1); } /* DKS -- eventually take IP addresses and ports from command line, as well as whether to dump only the ccn content. */ res |= process_fd(pcap_out, fd, 0, NULL, NULL, 0, 0); } pcap_dump_close(pcap_out); pcap_close(pcap); return res; }
{'content_hash': 'cc28a4f4531eaeeff9aee329ef682888', 'timestamp': '', 'source': 'github', 'line_count': 269, 'max_line_length': 112, 'avg_line_length': 34.3457249070632, 'alnum_prop': 0.5437817945665115, 'repo_name': 'MobileCloudNetworking/icnaas', 'id': '4298759f2cfb6a8773cf192f3c60466857107815', 'size': '10164', 'binary': False, 'copies': '10', 'ref': 'refs/heads/master', 'path': 'mcn-ccn-router/ccnx-0.8.2/android/CCNx-Android-Services/jni/csrc/cmd/ccndumppcap.c', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'C', 'bytes': '5189410'}, {'name': 'C++', 'bytes': '6050'}, {'name': 'Groff', 'bytes': '152559'}, {'name': 'HTML', 'bytes': '1686578'}, {'name': 'Java', 'bytes': '4146221'}, {'name': 'Makefile', 'bytes': '224881'}, {'name': 'Perl', 'bytes': '1513'}, {'name': 'Python', 'bytes': '193499'}, {'name': 'Shell', 'bytes': '180150'}, {'name': 'Smarty', 'bytes': '2619'}]}
<?php namespace Google\Service\CloudSearch; class PrivateMessageInfo extends \Google\Collection { protected $collection_key = 'gsuiteIntegrationMetadata'; protected $annotationsType = Annotation::class; protected $annotationsDataType = 'array'; protected $attachmentsType = Attachment::class; protected $attachmentsDataType = 'array'; protected $contextualAddOnMarkupType = GoogleChatV1ContextualAddOnMarkup::class; protected $contextualAddOnMarkupDataType = 'array'; protected $gsuiteIntegrationMetadataType = GsuiteIntegrationMetadata::class; protected $gsuiteIntegrationMetadataDataType = 'array'; /** * @var string */ public $text; protected $userIdType = UserId::class; protected $userIdDataType = ''; /** * @param Annotation[] */ public function setAnnotations($annotations) { $this->annotations = $annotations; } /** * @return Annotation[] */ public function getAnnotations() { return $this->annotations; } /** * @param Attachment[] */ public function setAttachments($attachments) { $this->attachments = $attachments; } /** * @return Attachment[] */ public function getAttachments() { return $this->attachments; } /** * @param GoogleChatV1ContextualAddOnMarkup[] */ public function setContextualAddOnMarkup($contextualAddOnMarkup) { $this->contextualAddOnMarkup = $contextualAddOnMarkup; } /** * @return GoogleChatV1ContextualAddOnMarkup[] */ public function getContextualAddOnMarkup() { return $this->contextualAddOnMarkup; } /** * @param GsuiteIntegrationMetadata[] */ public function setGsuiteIntegrationMetadata($gsuiteIntegrationMetadata) { $this->gsuiteIntegrationMetadata = $gsuiteIntegrationMetadata; } /** * @return GsuiteIntegrationMetadata[] */ public function getGsuiteIntegrationMetadata() { return $this->gsuiteIntegrationMetadata; } /** * @param string */ public function setText($text) { $this->text = $text; } /** * @return string */ public function getText() { return $this->text; } /** * @param UserId */ public function setUserId(UserId $userId) { $this->userId = $userId; } /** * @return UserId */ public function getUserId() { return $this->userId; } } // Adding a class alias for backwards compatibility with the previous class name. class_alias(PrivateMessageInfo::class, 'Google_Service_CloudSearch_PrivateMessageInfo');
{'content_hash': 'b19234ca59175992c3a0db5ef398403d', 'timestamp': '', 'source': 'github', 'line_count': 111, 'max_line_length': 88, 'avg_line_length': 22.576576576576578, 'alnum_prop': 0.6879489225857941, 'repo_name': 'googleapis/google-api-php-client-services', 'id': 'ca297a1e082d1b15c1a37812b81e1e997b732ff2', 'size': '3096', 'binary': False, 'copies': '2', 'ref': 'refs/heads/main', 'path': 'src/CloudSearch/PrivateMessageInfo.php', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'PHP', 'bytes': '55414116'}, {'name': 'Python', 'bytes': '427325'}, {'name': 'Shell', 'bytes': '787'}]}
package java.lang.constant; import java.lang.invoke.CallSite; import java.lang.invoke.MethodHandle; import java.lang.invoke.MethodHandles; import java.util.Arrays; import java.util.Objects; import java.util.stream.Stream; import static java.lang.constant.ConstantDescs.CD_String; import static java.lang.constant.ConstantUtils.EMPTY_CONSTANTDESC; import static java.lang.constant.ConstantUtils.validateMemberName; import static java.util.Objects.requireNonNull; import static java.util.stream.Collectors.joining; /** * A <a href="package-summary.html#nominal">nominal descriptor</a> for an * {@code invokedynamic} call site. * * <p>Concrete subtypes of {@linkplain DynamicCallSiteDesc} should be immutable * and their behavior should not rely on object identity. * * @since 12 */ public class DynamicCallSiteDesc { private final DirectMethodHandleDesc bootstrapMethod; private final ConstantDesc[] bootstrapArgs; private final String invocationName; private final MethodTypeDesc invocationType; /** * Creates a nominal descriptor for an {@code invokedynamic} call site. * * @param bootstrapMethod a {@link DirectMethodHandleDesc} describing the * bootstrap method for the {@code invokedynamic} * @param invocationName The unqualified name that would appear in the {@code NameAndType} * operand of the {@code invokedynamic} * @param invocationType a {@link MethodTypeDesc} describing the invocation * type that would appear in the {@code NameAndType} * operand of the {@code invokedynamic} * @param bootstrapArgs {@link ConstantDesc}s describing the static arguments * to the bootstrap, that would appear in the * {@code BootstrapMethods} attribute * @throws NullPointerException if any parameter or its contents are {@code null} * @throws IllegalArgumentException if the invocation name has the incorrect * format * @jvms 4.2.2 Unqualified Names */ private DynamicCallSiteDesc(DirectMethodHandleDesc bootstrapMethod, String invocationName, MethodTypeDesc invocationType, ConstantDesc[] bootstrapArgs) { this.invocationName = validateMemberName(requireNonNull(invocationName), true); this.invocationType = requireNonNull(invocationType); this.bootstrapMethod = requireNonNull(bootstrapMethod); this.bootstrapArgs = requireNonNull(bootstrapArgs.clone()); for (int i = 0; i < this.bootstrapArgs.length; i++) { requireNonNull(this.bootstrapArgs[i]); } if (invocationName.length() == 0) throw new IllegalArgumentException("Illegal invocation name: " + invocationName); } /** * Creates a nominal descriptor for an {@code invokedynamic} call site. * * @param bootstrapMethod a {@link DirectMethodHandleDesc} describing the * bootstrap method for the {@code invokedynamic} * @param invocationName The unqualified name that would appear in the {@code NameAndType} * operand of the {@code invokedynamic} * @param invocationType a {@link MethodTypeDesc} describing the invocation * type that would appear in the {@code NameAndType} * operand of the {@code invokedynamic} * @param bootstrapArgs {@link ConstantDesc}s describing the static arguments * to the bootstrap, that would appear in the * {@code BootstrapMethods} attribute * @return the nominal descriptor * @throws NullPointerException if any parameter or its contents are {@code null} * @throws IllegalArgumentException if the invocation name has the incorrect * format * @jvms 4.2.2 Unqualified Names */ public static DynamicCallSiteDesc of(DirectMethodHandleDesc bootstrapMethod, String invocationName, MethodTypeDesc invocationType, ConstantDesc... bootstrapArgs) { return new DynamicCallSiteDesc(bootstrapMethod, invocationName, invocationType, bootstrapArgs); } /** * Creates a nominal descriptor for an {@code invokedynamic} call site whose * bootstrap method has no static arguments. * * @param bootstrapMethod The bootstrap method for the {@code invokedynamic} * @param invocationName The invocationName that would appear in the * {@code NameAndType} operand of the {@code invokedynamic} * @param invocationType The invocation invocationType that would appear * in the {@code NameAndType} operand of the {@code invokedynamic} * @return the nominal descriptor * @throws NullPointerException if any parameter is null * @throws IllegalArgumentException if the invocation name has the incorrect * format */ public static DynamicCallSiteDesc of(DirectMethodHandleDesc bootstrapMethod, String invocationName, MethodTypeDesc invocationType) { return new DynamicCallSiteDesc(bootstrapMethod, invocationName, invocationType, EMPTY_CONSTANTDESC); } /** * Creates a nominal descriptor for an {@code invokedynamic} call site whose * bootstrap method has no static arguments and for which the name parameter * is {@link ConstantDescs#DEFAULT_NAME}. * * @param bootstrapMethod a {@link DirectMethodHandleDesc} describing the * bootstrap method for the {@code invokedynamic} * @param invocationType a {@link MethodTypeDesc} describing the invocation * type that would appear in the {@code NameAndType} * operand of the {@code invokedynamic} * @return the nominal descriptor * @throws NullPointerException if any parameter is null */ public static DynamicCallSiteDesc of(DirectMethodHandleDesc bootstrapMethod, MethodTypeDesc invocationType) { return of(bootstrapMethod, ConstantDescs.DEFAULT_NAME, invocationType); } /** * Returns a nominal descriptor for an {@code invokedynamic} call site whose * bootstrap method, name, and invocation type are the same as this one, but * with the specified bootstrap arguments. * * @param bootstrapArgs {@link ConstantDesc}s describing the static arguments * to the bootstrap, that would appear in the * {@code BootstrapMethods} attribute * @return the nominal descriptor * @throws NullPointerException if the argument or its contents are {@code null} */ public DynamicCallSiteDesc withArgs(ConstantDesc... bootstrapArgs) { return new DynamicCallSiteDesc(bootstrapMethod, invocationName, invocationType, bootstrapArgs); } /** * Returns a nominal descriptor for an {@code invokedynamic} call site whose * bootstrap and bootstrap arguments are the same as this one, but with the * specified invocationName and invocation invocationType * * @param invocationName The unqualified name that would appear in the {@code NameAndType} * operand of the {@code invokedynamic} * @param invocationType a {@link MethodTypeDesc} describing the invocation * type that would appear in the {@code NameAndType} * operand of the {@code invokedynamic} * @return the nominal descriptor * @throws NullPointerException if any parameter is null * @throws IllegalArgumentException if the invocation name has the incorrect * format * @jvms 4.2.2 Unqualified Names */ public DynamicCallSiteDesc withNameAndType(String invocationName, MethodTypeDesc invocationType) { return new DynamicCallSiteDesc(bootstrapMethod, invocationName, invocationType, bootstrapArgs); } /** * Returns the invocation name that would appear in the {@code NameAndType} * operand of the {@code invokedynamic}. * * @return the invocation name */ public String invocationName() { return invocationName; } /** * Returns a {@link MethodTypeDesc} describing the invocation type that * would appear in the {@code NameAndType} operand of the {@code invokedynamic}. * * @return the invocation type */ public MethodTypeDesc invocationType() { return invocationType; } /** * Returns a {@link MethodHandleDesc} describing the bootstrap method for * the {@code invokedynamic}. * * @return the bootstrap method for the {@code invokedynamic} */ public MethodHandleDesc bootstrapMethod() { return bootstrapMethod; } /** * Returns {@link ConstantDesc}s describing the bootstrap arguments for the * {@code invokedynamic}. The returned array is always non-null. A zero * length array is returned if this {@linkplain DynamicCallSiteDesc} has no * bootstrap arguments. * * @return the bootstrap arguments for the {@code invokedynamic} */ public ConstantDesc[] bootstrapArgs() { return bootstrapArgs.clone(); } /** * Reflectively invokes the bootstrap method with the specified arguments, * and return the resulting {@link CallSite} * * @param lookup The {@link MethodHandles.Lookup} used to resolve class names * @return the {@link CallSite} * @throws Throwable if any exception is thrown by the bootstrap method */ public CallSite resolveCallSiteDesc(MethodHandles.Lookup lookup) throws Throwable { assert bootstrapMethod.invocationType().parameterType(1).equals(CD_String); MethodHandle bsm = (MethodHandle) bootstrapMethod.resolveConstantDesc(lookup); Object[] args = new Object[bootstrapArgs.length + 3]; args[0] = lookup; args[1] = invocationName; args[2] = invocationType.resolveConstantDesc(lookup); System.arraycopy(bootstrapArgs, 0, args, 3, bootstrapArgs.length); return (CallSite) bsm.invokeWithArguments(args); } /** * Compares the specified object with this descriptor for equality. Returns * {@code true} if and only if the specified object is also a * {@linkplain DynamicCallSiteDesc}, and both descriptors have equal * bootstrap methods, bootstrap argument lists, invocation name, and * invocation type. * * @param o the {@code DynamicCallSiteDesc} to compare to this * {@code DynamicCallSiteDesc} * @return {@code true} if the specified {@code DynamicCallSiteDesc} * is equal to this {@code DynamicCallSiteDesc}. */ @Override public final boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; DynamicCallSiteDesc specifier = (DynamicCallSiteDesc) o; return Objects.equals(bootstrapMethod, specifier.bootstrapMethod) && Arrays.equals(bootstrapArgs, specifier.bootstrapArgs) && Objects.equals(invocationName, specifier.invocationName) && Objects.equals(invocationType, specifier.invocationType); } @Override public final int hashCode() { int result = Objects.hash(bootstrapMethod, invocationName, invocationType); result = 31 * result + Arrays.hashCode(bootstrapArgs); return result; } /** * Returns a compact textual description of this call site description, * including the bootstrap method, the invocation name and type, and * the static bootstrap arguments. * * @return A compact textual description of this call site descriptor */ @Override public String toString() { return String.format("DynamicCallSiteDesc[%s::%s(%s%s):%s]", bootstrapMethod.owner().displayName(), bootstrapMethod.methodName(), invocationName.equals(ConstantDescs.DEFAULT_NAME) ? "" : invocationName + "/", Stream.of(bootstrapArgs).map(Object::toString).collect(joining(",")), invocationType.displayDescriptor()); } }
{'content_hash': 'c07078b65059e63f64bc4f4f1fd9a656', 'timestamp': '', 'source': 'github', 'line_count': 269, 'max_line_length': 108, 'avg_line_length': 46.95539033457249, 'alnum_prop': 0.6559258966035943, 'repo_name': 'mirkosertic/Bytecoder', 'id': 'cf6d09c14b396056c3ced98c22382e926ebc807d', 'size': '13843', 'binary': False, 'copies': '6', 'ref': 'refs/heads/master', 'path': 'classlib/java.base/src/main/resources/META-INF/modules/java.base/classes/java/lang/constant/DynamicCallSiteDesc.java', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'C', 'bytes': '153'}, {'name': 'C++', 'bytes': '1301'}, {'name': 'CSS', 'bytes': '5154'}, {'name': 'Clojure', 'bytes': '87'}, {'name': 'HTML', 'bytes': '599386'}, {'name': 'Java', 'bytes': '106011215'}, {'name': 'Kotlin', 'bytes': '15858'}, {'name': 'LLVM', 'bytes': '2839'}, {'name': 'Shell', 'bytes': '164'}]}
module("wrapper", package.seeall) local json = require("cjson.safe") -- by default, only call json lib for encoding and decoding function encode(object) return json.encode(object) end function decode(object) return json.decode(object) end
{'content_hash': '6d1add8d6dda455f84ea07da89b59215', 'timestamp': '', 'source': 'github', 'line_count': 12, 'max_line_length': 59, 'avg_line_length': 20.333333333333332, 'alnum_prop': 0.7663934426229508, 'repo_name': 'paintsnow/luainsight', 'id': 'f86b6d3bf4614a4ab51e44ded69b59c88789d27c', 'size': '244', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'run/lua/wrapper.lua', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'Common Lisp', 'bytes': '973'}, {'name': 'Lua', 'bytes': '4774'}]}
package pl.darknessNight.AutoUpdateLauncher; import org.apache.commons.net.ftp.FTP; import org.apache.commons.net.ftp.FTPReply; import java.io.IOException; import java.io.OutputStream; class LoginException extends RuntimeException{} public class FTPClient { org.apache.commons.net.ftp.FTPClient ftpLowLevelClient = null; FTPClient(){ ftpLowLevelClient =new org.apache.commons.net.ftp.FTPClient(); } FTPClient(org.apache.commons.net.ftp.FTPClient client) { ftpLowLevelClient =client; } public void RetrieveDataToStreamFromUrl(String url, OutputStream stream) throws IOException{ ConnectToServerFromUrl(url); String filename=getFilenameFromUrl(url); RetrieveFile(filename,stream); Disconnect(); } private static String getFilenameFromUrl(String url){ return new String(); } public void ConnectToServerFromUrl(String url) throws IOException { String host=getHostFromUrl(url); String user=getUserFromUrl(url); String pass=getPassFromUrl(url); if(user.isEmpty()) ConnectToServerAnonymousAndPrepareConnection(host); else ConnectToServerAndPrepareConnection(host,user,pass); } private static String getHostFromUrl(String url){ return new String(); } private static String getUserFromUrl(String url){ return new String(); } private static String getPassFromUrl(String url){ return new String(); } public void ConnectToServerAndPrepareConnection(String host, String user, String pwd) throws IOException { ConnectToServer(host); LoginToServer(user, pwd); PrepareConnection(); } private void LoginToServer(String user, String pwd) throws IOException { if(!ftpLowLevelClient.login(user, pwd)) throw new LoginException(); } public void ConnectToServer(String host) throws IOException { int reply; ftpLowLevelClient.connect(host); reply = ftpLowLevelClient.getReplyCode(); if (!FTPReply.isPositiveCompletion(reply)) { ftpLowLevelClient.disconnect(); throw new IOException("Exception in connecting to FTP Server"); } } public void ConnectToServerAnonymousAndPrepareConnection(String host) throws IOException { ConnectToServer(host); PrepareConnection(); } private void PrepareConnection() throws IOException { ftpLowLevelClient.setFileType(FTP.BINARY_FILE_TYPE); ftpLowLevelClient.enterLocalPassiveMode(); } public void RetrieveFile(String remoteFilePath, OutputStream stream) throws IOException { this.ftpLowLevelClient.retrieveFile(remoteFilePath, stream); } public void Disconnect() { if (ftpLowLevelClient.isConnected()) { try { ftpLowLevelClient.logout(); } catch (IOException f) { //pass } try { ftpLowLevelClient.disconnect(); } catch (IOException f) { //pass } } } }
{'content_hash': '525da33418b41da4939c7048b448f470', 'timestamp': '', 'source': 'github', 'line_count': 102, 'max_line_length': 110, 'avg_line_length': 30.833333333333332, 'alnum_prop': 0.6597774244833068, 'repo_name': 'darknessNight/AutoUpdateLauncher', 'id': '443966e8f5e556196345c5583e92f2f4a55dec01', 'size': '3145', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'AutoUpdateLauncher/src/main/java/pl/darknessNight/AutoUpdateLauncher/FTPClient.java', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'Java', 'bytes': '33976'}]}
using System; using System.Linq; using System.Threading.Tasks; using ECommon.Components; using ECommon.Dapper; using ECommon.IO; using ECommon.Logging; using ECommon.Utilities; using ENode.Eventing; using ENode.Infrastructure; using MySql.Data.MySqlClient; namespace ENode.MySQL { public class MySqlPublishedVersionStore : IPublishedVersionStore { private const string EventSingleTableNameFormat = "`{0}`"; private const string EventTableNameFormat = "`{0}_{1}`"; #region Private Variables private string _connectionString; private string _tableName; private int _tableCount; private string _uniqueIndexName; private ILogger _logger; private ITimeProvider _timeProvider; private IOHelper _ioHelper; #endregion public MySqlPublishedVersionStore Initialize(string connectionString, string tableName = "PublishedVersion", int tableCount = 1, string uniqueIndexName = "IX_PublishedVersion_AggId_Version") { _connectionString = connectionString; _tableName = tableName; _tableCount = tableCount; _uniqueIndexName = uniqueIndexName; Ensure.NotNull(_connectionString, "_connectionString"); Ensure.NotNull(_tableName, "_tableName"); Ensure.Positive(_tableCount, "_tableCount"); Ensure.NotNull(_uniqueIndexName, "_uniqueIndexName"); _logger = ObjectContainer.Resolve<ILoggerFactory>().Create(GetType().FullName); _timeProvider = ObjectContainer.Resolve<ITimeProvider>(); _ioHelper = ObjectContainer.Resolve<IOHelper>(); return this; } public async Task UpdatePublishedVersionAsync(string processorName, string aggregateRootTypeName, string aggregateRootId, int publishedVersion) { await _ioHelper.TryIOActionAsync(async () => { if (publishedVersion == 1) { try { using (var connection = GetConnection()) { var currentTime = _timeProvider.GetCurrentTime(); await connection.OpenAsync().ConfigureAwait(false); await connection.InsertAsync(new { ProcessorName = processorName, AggregateRootTypeName = aggregateRootTypeName, AggregateRootId = aggregateRootId, Version = 1, CreatedOn = currentTime, UpdatedOn = currentTime }, GetTableName(aggregateRootId)).ConfigureAwait(false); } } catch (MySqlException ex) { if (ex.Number == 1062 && ex.Message.Contains(_uniqueIndexName)) { return; } var errorMessage = string.Format("Insert aggregate published version has sql exception, aggregateRootType: {0}, aggregateRootId: {1}", aggregateRootTypeName, aggregateRootId); _logger.Error(errorMessage, ex); throw; } catch (Exception ex) { var errorMessage = string.Format("Insert aggregate published version has unknown exception, aggregateRootType: {0}, aggregateRootId: {1}", aggregateRootTypeName, aggregateRootId); _logger.Error(errorMessage, ex); throw; } } else { try { using (var connection = GetConnection()) { await connection.OpenAsync().ConfigureAwait(false); await connection.UpdateAsync( new { Version = publishedVersion, UpdatedOn = _timeProvider.GetCurrentTime() }, new { ProcessorName = processorName, AggregateRootId = aggregateRootId, Version = publishedVersion - 1 }, GetTableName(aggregateRootId)).ConfigureAwait(false); } } catch (MySqlException ex) { var errorMessage = string.Format("Update aggregate published version has sql exception, aggregateRootType: {0}, aggregateRootId: {1}", aggregateRootTypeName, aggregateRootId); _logger.Error(errorMessage, ex); throw; } catch (Exception ex) { var errorMessage = string.Format("Update aggregate published version has unknown exception, aggregateRootType: {0}, aggregateRootId: {1}", aggregateRootTypeName, aggregateRootId); _logger.Error(errorMessage, ex); throw; } } }, "UpdatePublishedVersionAsync"); } public async Task<int> GetPublishedVersionAsync(string processorName, string aggregateRootTypeName, string aggregateRootId) { return await _ioHelper.TryIOFuncAsync(async () => { try { using (var connection = GetConnection()) { await connection.OpenAsync().ConfigureAwait(false); var result = await connection.QueryListAsync<int>(new { ProcessorName = processorName, AggregateRootId = aggregateRootId }, GetTableName(aggregateRootId), "Version").ConfigureAwait(false); return result.SingleOrDefault(); } } catch (MySqlException ex) { var errorMessage = string.Format("Get aggregate published version has sql exception, aggregateRootType: {0}, aggregateRootId: {1}", aggregateRootTypeName, aggregateRootId); _logger.Error(errorMessage, ex); throw; } catch (Exception ex) { var errorMessage = string.Format("Get aggregate published version has unknown exception, aggregateRootType: {0}, aggregateRootId: {1}", aggregateRootTypeName, aggregateRootId); _logger.Error(errorMessage, ex); throw; } }, "GetPublishedVersionAsync"); } private int GetTableIndex(string aggregateRootId) { int hash = 23; foreach (char c in aggregateRootId) { hash = (hash << 5) - hash + c; } if (hash < 0) { hash = Math.Abs(hash); } return hash % _tableCount; } private string GetTableName(string aggregateRootId) { if (_tableCount <= 1) { return string.Format(EventSingleTableNameFormat, _tableName); } var tableIndex = GetTableIndex(aggregateRootId); return string.Format(EventTableNameFormat, _tableName, tableIndex); } private MySqlConnection GetConnection() { return new MySqlConnection(_connectionString); } } }
{'content_hash': 'c233f89332dc3bfb0ef1a1df06d23501', 'timestamp': '', 'source': 'github', 'line_count': 187, 'max_line_length': 203, 'avg_line_length': 43.94652406417112, 'alnum_prop': 0.4930640058408372, 'repo_name': 'tangxuehua/enode', 'id': '53854d4f526deae3e922635a002e225481ad539c', 'size': '8220', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'src/ENode.MySQL/MySqlPublishedVersionStore.cs', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'C#', 'bytes': '570099'}, {'name': 'TSQL', 'bytes': '1681'}]}
package com.wuyin.supermarket.httpresult; import com.wuyin.supermarket.httpresult.base.BaseHttpRequest; import com.wuyin.supermarket.model.AppInfo; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.util.ArrayList; import java.util.List; /** * Created by yinlong on 2016/5/11. */ public class DetailHttpRequest extends BaseHttpRequest<AppInfo> { String packageName; public DetailHttpRequest(String packageName) { this.packageName = packageName; } @Override public AppInfo parseJson(String results) { try { JSONObject result = new JSONObject(results); String id = result.getString("id"); String name = result.getString("name"); String packageName = result.getString("packageName"); String iconUrl = result.getString("iconUrl"); float stars = result.getLong("stars"); long size = result.getLong("size"); String downLoadUrl = result.getString("downloadUrl"); String des = result.getString("des"); String downloadNum = result.getString("downloadNum"); String version = result.getString("version"); String date = result.getString("date"); String author = result.getString("author"); List<String> screen = new ArrayList<>(); JSONArray screenArray = result.getJSONArray("screen"); for (int i = 0; i < screenArray.length(); i++) { screen.add(screenArray.getString(i)); } List<String> safeUrl = new ArrayList<>(); List<String> safeDesUrl = new ArrayList<>(); List<String> safeDes = new ArrayList<>(); List<Integer> safeDesColor = new ArrayList<>(); JSONArray safeUrlArray = result.getJSONArray("safe"); for (int i = 0; i < safeUrlArray.length(); i++) { JSONObject jsonObject = safeUrlArray.getJSONObject(i); safeUrl.add(jsonObject.getString("safeUrl")); safeDesUrl.add(jsonObject.getString("safeDesUrl")); safeDes.add(jsonObject.getString("safeDes")); safeDesColor.add(jsonObject.getInt("safeDesColor")); } AppInfo appInfo = new AppInfo(id, name, packageName, iconUrl, stars, size, downLoadUrl, des, downloadNum, version, date, author, screen, safeUrl, safeDesUrl, safeDes, safeDesColor); return appInfo; } catch (JSONException e) { e.printStackTrace(); return null; } } @Override public String getKey() { return "detail"; } /** * 额外带的参数 * * @return */ @Override public String getParams() { return "&packageName=" + packageName; } }
{'content_hash': '354dff053eb2155a5581ef3414b7f243', 'timestamp': '', 'source': 'github', 'line_count': 87, 'max_line_length': 104, 'avg_line_length': 33.10344827586207, 'alnum_prop': 0.5954861111111112, 'repo_name': 'wuyinlei/SuperMarket', 'id': '88cfe134012b38ecdb5e26f4757c018e8dc8b213', 'size': '2892', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'src/main/java/com/wuyin/supermarket/httpresult/DetailHttpRequest.java', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'Groff', 'bytes': '1625'}, {'name': 'Java', 'bytes': '173264'}]}
using System; namespace Tasks { public interface IConsole { string ReadLine(); void Write(string format, params object[] args); void WriteLine(string format, params object[] args); void WriteLine(); } }
{'content_hash': '2b2314003fa642ad3a768aa5c9cd5761', 'timestamp': '', 'source': 'github', 'line_count': 15, 'max_line_length': 54, 'avg_line_length': 14.6, 'alnum_prop': 0.6986301369863014, 'repo_name': 'codurance/task-list', 'id': '05fc18cbe670b34a4360ad8eb5adba8da46d53a4', 'size': '221', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'csharp/Tasks/IConsole.cs', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'C#', 'bytes': '11356'}, {'name': 'Go', 'bytes': '8897'}, {'name': 'Java', 'bytes': '12921'}, {'name': 'Kotlin', 'bytes': '3918'}, {'name': 'Python', 'bytes': '7146'}, {'name': 'Ruby', 'bytes': '5730'}, {'name': 'Scala', 'bytes': '5911'}, {'name': 'Shell', 'bytes': '531'}, {'name': 'TypeScript', 'bytes': '8608'}]}
package business; import business.category.CategoryDao; import business.category.CategoryDaoGuava; import business.category.CategoryDaoJdbc; import business.category.CategoryService; import business.category.DefaultCategoryService; import business.customer.CustomerDao; import business.customer.CustomerDaoJdbc; import business.customer.CustomerService; import business.customer.DefaultCustomerService; import business.order.CustomerOrderDao; import business.order.CustomerOrderDaoJdbc; import business.order.CustomerOrderLineItemDao; import business.order.CustomerOrderLineItemDaoJdbc; import business.order.CustomerOrderService; import business.order.DefaultCustomerOrderService; import business.product.DefaultProductService; import business.product.ProductDao; import business.product.ProductDaoGuava; import business.product.ProductDaoJdbc; import business.product.ProductService; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.ScheduledThreadPoolExecutor; import java.util.concurrent.TimeUnit; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** */ public final class ApplicationContext { private final Logger logger = LoggerFactory.getLogger(getClass()); private ProductService productService; private CategoryService categoryService; private CustomerService customerService; private CustomerOrderService customerOrderService; private ScheduledExecutorService executorService; public static ApplicationContext INSTANCE = new ApplicationContext(); private ApplicationContext() { executorService = new ScheduledThreadPoolExecutor(Runtime.getRuntime().availableProcessors()); // wire up the business.dao layer "by hand" ProductDao productDao = new ProductDaoJdbc(); ProductDaoGuava cachedProductDao = new ProductDaoGuava(productDao); productService = new DefaultProductService(); ((DefaultProductService) productService).setProductDao(cachedProductDao); CategoryDao categoryDao = new CategoryDaoJdbc(); CategoryDaoGuava cachedCategoryDao = new CategoryDaoGuava(categoryDao); categoryService = new DefaultCategoryService(); ((DefaultCategoryService) categoryService).setCategoryDao(cachedCategoryDao); CustomerDao customerDao = new CustomerDaoJdbc(); customerService = new DefaultCustomerService(); ((DefaultCustomerService) customerService).setCustomerDao(customerDao); CustomerOrderLineItemDao customerOrderLineItemDao = new CustomerOrderLineItemDaoJdbc(); CustomerOrderDao customerOrderDao = new CustomerOrderDaoJdbc(); customerOrderService = new DefaultCustomerOrderService(); DefaultCustomerOrderService service = (DefaultCustomerOrderService) customerOrderService; service.setProductDao(cachedProductDao); service.setCustomerService(customerService); service.setCustomerOrderDao(customerOrderDao); service.setCustomerOrderLineItemDao(customerOrderLineItemDao); executorService.scheduleWithFixedDelay(() -> { try { logger.info("Refreshing category and product caches....commencing"); cachedCategoryDao.bulkload(); cachedProductDao.clear(); logger.info("Refreshing category and product caches....complete!"); } catch (Throwable t) { logger.error("Encountered trouble refreshing category and product caches.", t); } }, 10, 60, TimeUnit.MINUTES); } public ProductService getProductService() { return productService; } public CategoryService getCategoryService() { return categoryService; } public CustomerService getCustomerService() { return customerService; } public CustomerOrderService getCustomerOrderService() { return customerOrderService; } public void shutdown() { executorService.shutdown(); } }
{'content_hash': '2e5e5491b83058a8f3e193d14d4514b9', 'timestamp': '', 'source': 'github', 'line_count': 114, 'max_line_length': 102, 'avg_line_length': 35.41228070175438, 'alnum_prop': 0.7485756750061927, 'repo_name': 'nowucca/SimpleAffableBean', 'id': '94fc291274aed1406f2df203c0ba6f1c017344ae', 'size': '5660', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'src/main/java/business/ApplicationContext.java', 'mode': '33188', 'license': 'bsd-3-clause', 'language': [{'name': 'CSS', 'bytes': '9504'}, {'name': 'Java', 'bytes': '343995'}, {'name': 'JavaScript', 'bytes': '4976'}]}
package org.zstack.sdk.iam2.api; import java.util.HashMap; import java.util.Map; import org.zstack.sdk.*; public class AddAttributesToIAM2VirtualIDGroupAction extends AbstractAction { private static final HashMap<String, Parameter> parameterMap = new HashMap<>(); private static final HashMap<String, Parameter> nonAPIParameterMap = new HashMap<>(); public static class Result { public ErrorCode error; public org.zstack.sdk.iam2.api.AddAttributesToIAM2VirtualIDGroupResult value; public Result throwExceptionIfError() { if (error != null) { throw new ApiException( String.format("error[code: %s, description: %s, details: %s]", error.code, error.description, error.details) ); } return this; } } @Param(required = true, nonempty = false, nullElements = false, emptyString = true, noTrim = false) public java.lang.String uuid; @Param(required = true, nonempty = true, nullElements = false, emptyString = true, noTrim = false) public java.util.List attributes; @Param(required = false) public java.util.List systemTags; @Param(required = false) public java.util.List userTags; @Param(required = false) public String sessionId; @Param(required = false) public String accessKeyId; @Param(required = false) public String accessKeySecret; @Param(required = false) public String requestIp; @NonAPIParam public long timeout = -1; @NonAPIParam public long pollingInterval = -1; private Result makeResult(ApiResult res) { Result ret = new Result(); if (res.error != null) { ret.error = res.error; return ret; } org.zstack.sdk.iam2.api.AddAttributesToIAM2VirtualIDGroupResult value = res.getResult(org.zstack.sdk.iam2.api.AddAttributesToIAM2VirtualIDGroupResult.class); ret.value = value == null ? new org.zstack.sdk.iam2.api.AddAttributesToIAM2VirtualIDGroupResult() : value; return ret; } public Result call() { ApiResult res = ZSClient.call(this); return makeResult(res); } public void call(final Completion<Result> completion) { ZSClient.call(this, new InternalCompletion() { @Override public void complete(ApiResult res) { completion.complete(makeResult(res)); } }); } protected Map<String, Parameter> getParameterMap() { return parameterMap; } protected Map<String, Parameter> getNonAPIParameterMap() { return nonAPIParameterMap; } protected RestInfo getRestInfo() { RestInfo info = new RestInfo(); info.httpMethod = "POST"; info.path = "/iam2/projects/groups/{uuid}/attributes"; info.needSession = true; info.needPoll = true; info.parameterName = "params"; return info; } }
{'content_hash': '09c352ce3b0910ad195b63ff810302eb', 'timestamp': '', 'source': 'github', 'line_count': 104, 'max_line_length': 165, 'avg_line_length': 28.951923076923077, 'alnum_prop': 0.6343407505812022, 'repo_name': 'zstackorg/zstack', 'id': 'a5bb512701d861945cdf0827326af451608d0112', 'size': '3011', 'binary': False, 'copies': '4', 'ref': 'refs/heads/master', 'path': 'sdk/src/main/java/org/zstack/sdk/iam2/api/AddAttributesToIAM2VirtualIDGroupAction.java', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'AspectJ', 'bytes': '54952'}, {'name': 'Batchfile', 'bytes': '1132'}, {'name': 'Groovy', 'bytes': '832169'}, {'name': 'Java', 'bytes': '15798995'}, {'name': 'Shell', 'bytes': '152829'}]}