text
stringlengths
2
1.04M
meta
dict
/* * This file is part of the DITA Open Toolkit project. * See the accompanying license.txt file for applicable licenses. */ package org.dita.dost.platform; import static org.junit.Assert.assertArrayEquals; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; import static org.junit.Assert.fail; import static java.util.Arrays.*; import java.io.File; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import org.junit.Test; public class FeaturesTest { @Test public void testFeaturesString() { assertNotNull(new Features(new File("base", "plugins"), new File("base"))); } @Test public void testGetLocation() { assertEquals(new File("base", "plugins"), new Features(new File("base", "plugins"), new File("base")).getLocation()); } @Test public void testAddExtensionPoint() { final Features f = new Features(new File("base", "plugins"), new File("base")); final ExtensionPoint e = new ExtensionPoint("id", "name", "plugin"); f.addExtensionPoint(e); try { f.addExtensionPoint(null); fail(); } catch (final NullPointerException ex) {} } @Test public void testGetExtensionPoints() { final Features f = new Features(new File("base", "plugins"), new File("base")); final ExtensionPoint e = new ExtensionPoint("id", "name", "plugin"); f.addExtensionPoint(e); final ExtensionPoint e2 = new ExtensionPoint("id2", "name2", "plugin"); f.addExtensionPoint(e2); assertEquals(2, f.getExtensionPoints().size()); assertEquals(e, f.getExtensionPoints().get("id")); assertEquals(e2, f.getExtensionPoints().get("id2")); } @Test public void testGetFeature() { final Features f = new Features(new File("base", "plugins"), new File("base")); f.addFeature("foo", "bar", null); assertEquals(asList("bar"), f.getFeature("foo")); } @Test public void testGetAllFeatures() { final Features f = new Features(new File("base", "plugins"), new File("base")); f.addFeature("foo", "bar", null); f.addFeature("foo", "baz", null); f.addFeature("bar", "qux", null); final Map<String, List<String>> exp = new HashMap<String, List<String>>(); exp.put("foo", asList("bar", "baz")); exp.put("bar", asList("qux")); assertEquals(exp, f.getAllFeatures()); } @Test public void testAddFeature() { final Features f = new Features(new File("base", "plugins"), new File("base")); try { f.addFeature("foo", null, null); fail(); } catch (final NullPointerException e) {} f.addFeature("foo", " bar, baz ", null); assertEquals(asList("bar", "baz"), f.getFeature("foo")); f.addFeature("foo", "bar, baz", "file"); assertEquals(asList("bar","baz", "base" + File.separator + "plugins" + File.separator + "bar", "base" + File.separator + "plugins" + File.separator + "baz"), f.getFeature("foo")); } @Test public void testAddRequireString() { final Features f = new Features(new File("base", "plugins"), new File("base")); f.addRequire("foo"); try { f.addRequire(null); fail(); } catch (final NullPointerException e) {} } @Test public void testAddRequireStringString() { final Features f = new Features(new File("base", "plugins"), new File("base")); f.addRequire("foo"); f.addRequire("foo", null); try { f.addRequire(null, null); fail(); } catch (final NullPointerException e) {} } @Test public void testGetRequireListIter() { final Features f = new Features(new File("base", "plugins"), new File("base")); f.addRequire("foo | bar "); f.addRequire("baz", "unrequired"); f.addRequire("qux", "required"); final Map<List<String>, Boolean> act = new HashMap<List<String>, Boolean>(); final Iterator<PluginRequirement> requirements = f.getRequireListIter(); while (requirements.hasNext()) { final PluginRequirement requirement = requirements.next(); final List<String> plugins = new ArrayList<String>(); for (final Iterator<String> ps = requirement.getPlugins(); ps.hasNext();) { plugins.add(ps.next()); } Collections.sort(plugins); act.put(plugins, requirement.getRequired()); } final Map<List<String>, Boolean> exp = new HashMap<List<String>, Boolean>(); exp.put(Arrays.asList(new String[] {" bar ", "foo "}), Boolean.TRUE); exp.put(Arrays.asList(new String[] {"baz"}), Boolean.FALSE); exp.put(Arrays.asList(new String[] {"qux"}), Boolean.TRUE); assertEquals(exp, act); } @Test public void testAddMeta() { final Features f = new Features(new File("base", "plugins"), new File("base")); f.addMeta("foo", "bar"); f.addMeta("foo", "baz"); f.addMeta("bar", "baz"); try { f.addMeta("bar", null); fail(); } catch (final NullPointerException e) {} } @Test public void testGetMeta() { final Features f = new Features(new File("base", "plugins"), new File("base")); f.addMeta("foo", "bar"); f.addMeta("foo", "baz"); f.addMeta("bar", "baz"); assertEquals("baz", f.getMeta("foo")); assertEquals("baz", f.getMeta("bar")); assertNull(f.getMeta("qux")); } @Test public void testAddTemplate() { final Features f = new Features(new File("base", "plugins"), new File("base")); f.addTemplate("foo"); f.addTemplate("foo"); f.addTemplate("bar"); f.addTemplate(null); } @Test public void testGetAllTemplates() { final Features f = new Features(new File("base", "plugins"), new File("base")); f.addTemplate("foo"); f.addTemplate("foo"); f.addTemplate("bar"); f.addTemplate(null); final List<String> act = f.getAllTemplates(); Collections.sort(act, new Comparator<String>() { public int compare(final String arg0, final String arg1) { if (arg0 == null && arg1 == null) { return 0; } else if (arg0 == null) { return 1; } else if (arg1 == null) { return -1; } else { return arg0.compareTo(arg1); } } }); assertArrayEquals(new String[] {"bar", "foo", "foo", null}, act.toArray(new String[0])); } }
{ "content_hash": "b4bc0e5478cbc2502f7a41e0a80e012c", "timestamp": "", "source": "github", "line_count": 207, "max_line_length": 125, "avg_line_length": 34.11594202898551, "alnum_prop": 0.5729255168507505, "repo_name": "jelovirt/muuntaja", "id": "71f1f7d336e25bdd82b106eb54d7bbd927429727", "size": "7062", "binary": false, "copies": "1", "ref": "refs/heads/develop", "path": "src/test/java/org/dita/dost/platform/FeaturesTest.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "79929" }, { "name": "Java", "bytes": "1615903" }, { "name": "JavaScript", "bytes": "89417" }, { "name": "Scala", "bytes": "122431" }, { "name": "Shell", "bytes": "13911" }, { "name": "XSLT", "bytes": "3101956" } ], "symlink_target": "" }
using IsolatedIslandGame.Database; using IsolatedIslandGame.Library; namespace IsolatedIslandGame.Server { public class ServerPlayerInformationManager : PlayerInformationManager { public override bool FindPlayerInformation(int playerID, out PlayerInformation playerInformation) { if(base.FindPlayerInformation(playerID, out playerInformation)) { return true; } else { if (DatabaseService.RepositoryList.PlayerRepository.ReadPlayerInformation(playerID, out playerInformation)) { AddPlayerInformation(playerInformation); return true; } else { return false; } } } } }
{ "content_hash": "ffe93cc2f0f05713cbbb18a7118e7efb", "timestamp": "", "source": "github", "line_count": 28, "max_line_length": 123, "avg_line_length": 30.25, "alnum_prop": 0.5584415584415584, "repo_name": "NCTU-Isolated-Island/Isolated-Island-Game", "id": "c674e3218fb94de21af15487d919d0bc91c2957a", "size": "849", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "IsolatedIslandGame/IsolatedIslandGame.Server/ServerPlayerInformationManager.cs", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "C#", "bytes": "1902336" }, { "name": "GLSL", "bytes": "224840" }, { "name": "Objective-C", "bytes": "284053" }, { "name": "Objective-C++", "bytes": "30603" } ], "symlink_target": "" }
id: intro slug: /liquid title: Liquid documentation sidebar_label: Introduction sidebar_position: 1 --- Intercode uses the [Liquid](https://shopify.github.io/liquid/) template language for user-generated content. Convention admins can take advantage of Liquid markup to create dynamic pages that tailor their content to the user viewing them. Liquid comes with a variety of standard filters, tags, and blocks that are available to all applications that use it. Intercode makes these available in templates by default. These are documented at [the official Liquid site](https://shopify.github.io/liquid/). Intercode also provides a variety of additional extensions to make information about conventions, events, users, etc. available to CMS templates. These are documented here. Use the docs in the sidebar to find out how to use Intercode's Liquid extensions: - **Available variables**: the variables you can use by default in Intercode Liquid templates. - **Blocks**: custom blocks that can be wrapped around content. - **Drops**: representations of Intercode objects that can be used in Liquid templates. - **Filters**: extra filtering functions that can be applied to variables and expressions. - **Tags**: custom Liquid tags that can be used with `{% ... %}` syntax.
{ "content_hash": "a2c7383c3f03f464ade3ae44ad6b3ebe", "timestamp": "", "source": "github", "line_count": 24, "max_line_length": 119, "avg_line_length": 53.166666666666664, "alnum_prop": 0.7813479623824452, "repo_name": "neinteractiveliterature/intercode", "id": "3bc130aa57cdf33be2ce4d87bb15bc757b61dd67", "size": "1280", "binary": false, "copies": "1", "ref": "refs/heads/main", "path": "doc-site/liquid-homepage.md", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "1616" }, { "name": "Dockerfile", "bytes": "2534" }, { "name": "HTML", "bytes": "26576" }, { "name": "JavaScript", "bytes": "41769" }, { "name": "Liquid", "bytes": "211563" }, { "name": "PLpgSQL", "bytes": "156320" }, { "name": "Procfile", "bytes": "298" }, { "name": "Ruby", "bytes": "1545558" }, { "name": "SCSS", "bytes": "22363" }, { "name": "Shell", "bytes": "6896" }, { "name": "TypeScript", "bytes": "2941901" } ], "symlink_target": "" }
using UnityEngine; [AddComponentMenu("FOW Example/Move With Mouse")] public class TSMoveWithMouse : MonoBehaviour { Transform mTrans; Vector3 mMouse; Vector3 mTargetPos; Vector3 mTargetEuler; void Start () { mTrans = transform; mMouse = Input.mousePosition; mTargetPos = mTrans.position; mTargetEuler = mTrans.rotation.eulerAngles; } void Update () { Vector3 delta = Input.mousePosition - mMouse; mMouse = Input.mousePosition; if (Input.GetMouseButton(0)) { mTargetEuler.y += Time.deltaTime * 10f * delta.x; } if (Input.GetMouseButton(1)) { Vector3 dir = transform.rotation * Vector3.forward; dir.y = 0f; dir.Normalize(); Quaternion rot = Quaternion.LookRotation(dir); mTargetPos += rot * new Vector3(delta.x * 0.1f, 0f, delta.y * 0.1f); } float deltaTime = Time.deltaTime * 8f; mTrans.position = Vector3.Lerp(mTrans.position, mTargetPos, deltaTime); mTrans.rotation = Quaternion.Slerp(mTrans.rotation, Quaternion.Euler(mTargetEuler), deltaTime); } }
{ "content_hash": "56b3036fd8a3c7bc2f57fbc722cb3227", "timestamp": "", "source": "github", "line_count": 42, "max_line_length": 97, "avg_line_length": 24.142857142857142, "alnum_prop": 0.7120315581854043, "repo_name": "nobrainer1024/u3dgfxSamples", "id": "d65998a035916080f6265979047c056bc251420b", "size": "1014", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "gfxProject/Assets/Resources/17_FogOfWar/Examples/Scripts/TSMoveWithMouse.cs", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "C#", "bytes": "53610" }, { "name": "GLSL", "bytes": "54488" } ], "symlink_target": "" }
[![license](https://img.shields.io/github/license/bucknerns/sshaolin.svg?maxAge=2592000)](https://github.com/bucknerns/sshaolin/blob/master/LICENSE) [![GitHub issues](https://img.shields.io/github/issues/bucknerns/sshaolin.svg)](https://github.com/bucknerns/sshaolin/issues) # SSHaolin: SSH for Ninjas Tired of dealing with python SSH interfaces that are far too complicated! Want a nice simple python SSH interface that just works! SSHaolin aims to give you that experience and more! Built on top of [paramiko](https://github.com/paramiko/paramiko), SSHaolin is the python interface that makes it simple to write that ssh script you've been meaning to do for years! Built into the SSHaolin core is verbose logging that shows you every command that is running along with the ability to decipher both stdout and stderr straight from your logs! Also included are interfaces for both persistent ssh sessions (_SSHShell_) and sftp session (_SFTPShell_). Both are easy to use and provide a great speed boost as opposed to connecting and reconnecting for every action! Have an issue? Submit it [here](https://github.com/bucknerns/sshaolin/issues)! ## Installation: Recommended: ``` $ pip install git+https://github.com/bucknerns/sshaolin ``` ## Unit Tests * Must be running an SSH server at localhost:22 * Must have Passwordsless SSH Auth to localhost ```python $ tox ``` ## Requirements: * [paramiko](https://github.com/paramiko/paramiko) * [PySocks](https://github.com/Anorov/PySocks) ## Features: * Easily send commands over ssh! * Creating persistent ssh sessions! * Creating persistent sftp sessions! * Easy connection cleanup! (No more manual closing!) ## Examples: Running `ls -ltr` on server `foo` as user `bar` with password `blah` ```python from sshaolin.client import SSHClient client = SSHClient(hostname='foo', username='bar', password='blah') response = client.execute_command('ls -ltr') # It comes with an exit status! print(response.exit_status) # It comes with stdout! print(response.stdout) # It comes with stderr! print(response.stderr) ``` Transferring local file `example.txt` to server `foo` as user `bar` with RSA file authentication `/home/bar/.ssh/id_rsa` at `/usr/local/src/example.txt` and `/usr/local/src/example2.txt` ```python from sshaolin.client import SSHClient client = SSHClient( hostname='foo', username='bar', key_filename='/home/bar/.ssh/id_rsa') with open('example.txt', 'r') as fp: data = fp.read() # Context managers to ensure the closing of a connection! with client.create_sftp() as sftp: sftp.write_file(data=data, remote_path='/usr/local/src/example.txt') # If you don't want to mess with context managers you can store it as a # variable! SSHaolin will clean it up when the program exits! sftp = client.create_sftp() sftp.write_file(data=data, remote_path='/usr/local/src/example2.txt') ``` Sudoing to `privelegeduser1`, cd'ing to `/usr/local/executables` and running `perl randomperlscript.pl` ```python from sshaolin.client import SSHClient client = SSHClient( hostname='foo', username='bar', key_filename='/home/bar/.ssh/id_rsa') shell = client.create_shell() # No more need to do hacky workarounds to sudo to another user! shell.execute_command('sudo su privelegeduser1') shell.execute_command('cd /usr/local/executables') perl_response = shell.execute_command('perl randomperlscript.pl') shell.close() # We can close things manually as well! if perl_response.exit_status == 0: print('Success!') else: raise Exception('Failed to execute randomperlscript.pl correctly') ``` ## Contributing: 1. Fork the [repository](https://github.com/bucknerns/sshaolin)! 2. Commit some stuff! 3. Submit a pull request!
{ "content_hash": "fd9ad904e9dd12da525b625e1de9d014", "timestamp": "", "source": "github", "line_count": 113, "max_line_length": 148, "avg_line_length": 32.73451327433628, "alnum_prop": 0.7502027575020276, "repo_name": "bucknerns/sshaolin", "id": "e327a054607f9b08331fa7d850560fe0d032c73d", "size": "3699", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "README.md", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Python", "bytes": "29995" } ], "symlink_target": "" }
ACCEPTED #### According to International Plant Names Index #### Published in null #### Original name null ### Remarks null
{ "content_hash": "281477ff42b9ea139702ad86756c084c", "timestamp": "", "source": "github", "line_count": 13, "max_line_length": 31, "avg_line_length": 9.692307692307692, "alnum_prop": 0.7063492063492064, "repo_name": "mdoering/backbone", "id": "674dfb8d41b674ef9ef905ce90edbd9118a61ae5", "size": "176", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "life/Plantae/Pteridophyta/Polypodiopsida/Polypodiales/Thelypteridaceae/Phegopteris/Phegopteris splendida/README.md", "mode": "33188", "license": "apache-2.0", "language": [], "symlink_target": "" }
<?php /** @var TbActiveForm $form */ $form = $this->beginWidget('bootstrap.widgets.TbActiveForm', array( 'type'=>'horizontal', )); $premiumBadge = '<a class="badge badge-premium pull-left" data-toggle="modal" href="#premiumInfo" ' .'title="'.g('This is a Premium feature').'" rel="tooltip">' .g('Premium').'</a>'; $premiumText = '<a class="badge badge-premium" data-toggle="modal" href="#premiumInfo" ' .'title="'.g('This is a Premium feature').'" rel="tooltip">' .g('Premium').'</a>'; echo $form->errorSummary($wall); ?> <fieldset> <legend><?php t('Wall settings'); ?></legend> <?php if( !$wall->published ) { ?> <?php echo $form->textFieldRow($wall,'name',array('prepend'=>$this->createAbsoluteUrl('wall/index',array('wall'=>'','language'=>null)),'hint'=>g('You can change the wall name before publishing the wall.'))); ?> <?php } else { ?> <?php echo $form->uneditableRow($wall,'name',array('prepend'=>$this->createAbsoluteUrl('wall/index',array('wall'=>'','language'=>null)),'hint'=>g('Wall name cannot be changed after it has been published.'))); ?> <?php } ?> <?php echo $form->textFieldRow($wall,'title'); ?> <?php echo $form->checkBoxRow($wall,'index',array('hint'=>g('Allow this wall to show in Google search and other web search engines.'))); ?> </fieldset> <fieldset> <legend><?php t('Conversation'); ?></legend> <?php echo $form->checkBoxRow($wall,'threaded',array('hint'=>g('Show a "reply" option and show replies under the original message.'))); ?> </fieldset> <fieldset> <legend><?php t('Passwords'); ?></legend> <?php echo $form->textFieldRow($wall,'adminpassword',array('hint'=>g('Wall admin can remove messages, add questions and polls, view reports etc using this password'))); ?> <?php echo $form->textFieldRow($wall,'password',array('hint'=>g('Password required to view the wall. Leave empty for no password required.'))); ?> </fieldset> <fieldset> <legend><?php t('Twitter'); ?></legend> <?php echo $form->checkBoxRow($wall,'enabletwitter',array('class'=>'toggler')); ?> <?php echo CHtml::tag('div',array('class'=>'toggled'),$form->textFieldRow($wall,'hashtag',array('prepend'=>'#'))); ?> <div class="toggled"> <div class="control-group"> <?php echo CHtml::activeLabelEx($wall,'TwitterUser',array('class'=>'control-label')); ?> <div class="controls"> <p id="Wall_TwitterUser"> <?php if( $wall->TwitterUser ) { echo '<strong>'.$wall->TwitterUser->screen_name; echo '</strong> '; $this->widget('bootstrap.widgets.TbButton',array('htmlOptions'=>array('name'=>'sign-out-twitter'),'buttonType'=>'submit','label'=>'Sign out from Twitter')); } else { $this->widget('bootstrap.widgets.TbButton',array('htmlOptions'=>array('name'=>'sign-in-twitter','class'=>'sign-in'),'buttonType'=>'submit','encodeLabel'=>false,'label'=>CHtml::image(Yii::app()->baseUrl.'/images/sign-in-with-twitter-gray.png','Sign in with Twitter'))); } echo CHtml::activeHiddenField($wall,'twitteruser'); ?> </p> <p> <?php t('Tweets from the wall website and SMS are sent using this account.'); ?> </p> <p> <?php t('You can also use the shared twitter account, but it will result in longer delay when fetching tweets.'); ?> <?php t('This is a {premium}-feature.',array('{premium}'=>$premiumText)); ?> </p> </div> </div> </div> </fieldset> <fieldset> <legend><?php t('Moderating'); ?></legend> <?php echo $premiumBadge; ?> <?php echo $form->checkBoxRow($wall,'premoderated',array('hint'=>g('If checked, all messages must be approved by wall admin before they are shown on the wall.'))); ?> </fieldset> <fieldset> <legend><?php t('SMS'); ?></legend> <?php echo $premiumBadge; ?> <?php echo $form->checkBoxRow($wall,'enablesms',array('class'=>'toggler')); ?> <?php echo CHtml::tag('div',array('class'=>'toggled'), $form->dropDownListRow($wall,'smskeyword',Yii::app()->user->getKeywordChoices()) .$form->textFieldRow($wall,'smsprefix',array('hint'=>g('Visitors can send SMS messages by prepending their message with keyword and prefix.'))) ); ?> </fieldset> <fieldset> <legend><?php t('Stream'); ?></legend> <?php echo $form->checkBoxRow($wall,'enablestream',array('class'=>'toggler')); ?> <?php echo CHtml::tag('div',array('class'=>'toggled'), $form->dropDownListRow($wall,'streamprovider',Yii::app()->params['streamProviders']) .$form->textFieldRow($wall,'streamid',array('hint'=>g('Consult stream provider help to aquire stream id'))) ); ?> </fieldset> <div class="form-actions"> <?php $this->widget('bootstrap.widgets.TbButton',array('buttonType'=>'submit','type'=>'primary','label'=>g('Save'))); ?> <?php $this->widget('bootstrap.widgets.TbButton',array('buttonType'=>'submit','label'=>g('Cancel'),'htmlOptions'=>array('name'=>'cancel'))); ?></div> <?php $this->endWidget(); ?>
{ "content_hash": "67a553fddcb013208671660d6beca33b", "timestamp": "", "source": "github", "line_count": 99, "max_line_length": 273, "avg_line_length": 48.62626262626262, "alnum_prop": 0.6522642293311176, "repo_name": "Conexting/conexting", "id": "b6da5f83f75ad9b39de3ed4af20311074e2a6eef", "size": "4814", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "protected/views/client/wallSettings.php", "mode": "33188", "license": "mit", "language": [ { "name": "ApacheConf", "bytes": "545" }, { "name": "Batchfile", "bytes": "380" }, { "name": "CSS", "bytes": "11942" }, { "name": "JavaScript", "bytes": "37641" }, { "name": "Makefile", "bytes": "57" }, { "name": "PHP", "bytes": "804564" }, { "name": "Shell", "bytes": "238" } ], "symlink_target": "" }
use strict; # use warnings; use Getopt::Long qw( GetOptions ); use Sys::Syslog qw( :DEFAULT setlogsock ); Getopt::Long::Configure ("gnu_getopt"); my $print_help; my $tag = (getpwuid($<))[0]; my $prio_string = 'user.info'; my $facility = ''; my $priority = ''; my $socket = '/dev/log'; my $use_stderr; my $use_pid; my $use_tcp; my $use_udp; my $syslog_server= 'localhost'; my $port = 514; my $openlog_opts = 'cons'; my $log; my @facilities = qw( auth authpriv cron daemon ftp lpr mail news syslog user uucp local0 local1 local2 local3 local4 local5 local6 local7 ); my @priorities = qw( debug info notice warning warn err crit alert emerg panic ); sub get_usage { (my $usage = <<" EOF") =~ s/^ {8}//gm; usage: logger.pl [-h|--help] [-p PRIO] [-t TAG] [-i] [-u SOCKET | --udp | --tcp] [-n SERVER] [-P PORT] EOF return $usage; } sub get_help { (my $help = <<" EOF") =~ s/^ {8}//gm; A perl logger clone that reads input via stdin optional arguments: -h, --help show this help message and exit -p, --priority PRIO specify priority for given message (default: $prio_string) -t, --tag TAG add tag to given message (default: $tag) -i, --id add process ID to tag (default: False) -u, --socket SOCKET write to local UNIX socket (default: $socket) -d, --udp log via UDP instead of UNIX socket (default: False) -T, --tcp log via TCP instead of UNIX socket (default: False) -n, --server SERVER DNS/IP of syslog server to use with --udp or --tcp (default: $syslog_server) -P, --port PORT port to use with --udp or --tcp (default: $port) -s, --stderr output to standard error as well (default: False) logger.pl v0.1.2 last mod 2016/04/12 For issues & questions, see: https://github.com/ryran/loggerclones/issues EOF return $help; } sub print_prio_err { print "Improper 'priority' specified\n"; print "Must be <facility>.<priority> as described in logger(1) man page\n"; } # Parse options GetOptions( 'help|h' => \$print_help, 'tcp|T' => \$use_tcp, 'udp|d' => \$use_udp, 'id|i' => \$use_pid, 'server|n=s' => \$syslog_server, 'port|P=i' => \$port, 'priority|p=s' => \$prio_string, 'stderr|s' => \$use_stderr, 'tag|t=s' => \$tag, 'socket|u=s' => \$socket, ) or die get_usage(); # Check arguments if (length $print_help) { print get_usage(); print get_help(); exit; } ($facility, $priority) = split('\.', $prio_string); if ($facility eq '' || $priority eq '') { print_prio_err(); exit 1; } my %facilities_set; @facilities_set{@facilities} = (); my %priorities_set; @priorities_set{@priorities} = (); if (exists $facilities_set{$facility} && exists $priorities_set{$priority}) { } else { print_prio_err(); exit 1; } if (length $use_tcp && length $use_udp) { print "Can't use --tcp and --udp at the same time\n"; exit 1; } # Setup log socket if ($socket eq '/dev/log') { } elsif (length $use_tcp) { setlogsock({ type => 'tcp', port => $port, host => $syslog_server }); } elsif (length $use_udp) { setlogsock({ type => 'udp', port => $port, host => $syslog_server }); } else { setlogsock({ type => 'unix', path => $socket }); } # Setup openlog opts if (length $use_pid) { $openlog_opts .= ',pid'; } if (length $use_stderr) { $openlog_opts .= ',perror'; } # Open connection and start reading stdin openlog($tag, $openlog_opts, $facility); while ($log = <STDIN>) { syslog($priority, $log); } closelog;
{ "content_hash": "a851c035e453250dd15f9ab73c8c488e", "timestamp": "", "source": "github", "line_count": 124, "max_line_length": 140, "avg_line_length": 29.967741935483872, "alnum_prop": 0.5753498385360603, "repo_name": "ryran/loggerclones", "id": "8a1f87c5f3317e297205baf341736ede9f026375", "size": "4396", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "logger.pl", "mode": "33261", "license": "apache-2.0", "language": [ { "name": "Perl", "bytes": "4396" }, { "name": "Python", "bytes": "8124" } ], "symlink_target": "" }
import pytest import pandas as pd from pandas import Categorical import pandas._testing as tm @pytest.mark.parametrize( "to_replace,value,expected,flip_categories", [ # one-to-one (1, 2, [2, 2, 3], False), (1, 4, [4, 2, 3], False), (4, 1, [1, 2, 3], False), (5, 6, [1, 2, 3], False), # many-to-one ([1], 2, [2, 2, 3], False), ([1, 2], 3, [3, 3, 3], False), ([1, 2], 4, [4, 4, 3], False), ((1, 2, 4), 5, [5, 5, 3], False), ((5, 6), 2, [1, 2, 3], False), ([1], [2], [2, 2, 3], False), ([1, 4], [5, 2], [5, 2, 3], False), # check_categorical sorts categories, which crashes on mixed dtypes (3, "4", [1, 2, "4"], False), ([1, 2, "3"], "5", ["5", "5", 3], True), ], ) def test_replace_categorical_series(to_replace, value, expected, flip_categories): # GH 31720 ser = pd.Series([1, 2, 3], dtype="category") result = ser.replace(to_replace, value) expected = pd.Series(expected, dtype="category") ser.replace(to_replace, value, inplace=True) if flip_categories: expected = expected.cat.set_categories(expected.cat.categories[::-1]) tm.assert_series_equal(expected, result, check_category_order=False) tm.assert_series_equal(expected, ser, check_category_order=False) @pytest.mark.parametrize( "to_replace, value, result, expected_error_msg", [ ("b", "c", ["a", "c"], "Categorical.categories are different"), ("c", "d", ["a", "b"], None), # https://github.com/pandas-dev/pandas/issues/33288 ("a", "a", ["a", "b"], None), ("b", None, ["a", None], "Categorical.categories length are different"), ], ) def test_replace_categorical(to_replace, value, result, expected_error_msg): # GH#26988 cat = Categorical(["a", "b"]) expected = Categorical(result) result = pd.Series(cat).replace(to_replace, value)._values tm.assert_categorical_equal(result, expected) if to_replace == "b": # the "c" test is supposed to be unchanged with pytest.raises(AssertionError, match=expected_error_msg): # ensure non-inplace call does not affect original tm.assert_categorical_equal(cat, expected) pd.Series(cat).replace(to_replace, value, inplace=True) tm.assert_categorical_equal(cat, expected)
{ "content_hash": "7dec955e7f40646cceb8910bb29bc0b4", "timestamp": "", "source": "github", "line_count": 67, "max_line_length": 82, "avg_line_length": 35.417910447761194, "alnum_prop": 0.5756426464391066, "repo_name": "pandas-dev/pandas", "id": "a3ba420c84a17bb334d0ac2d8c09f4f8a850ffe1", "size": "2373", "binary": false, "copies": "1", "ref": "refs/heads/main", "path": "pandas/tests/arrays/categorical/test_replace.py", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "Batchfile", "bytes": "512" }, { "name": "C", "bytes": "366145" }, { "name": "CSS", "bytes": "1800" }, { "name": "Cython", "bytes": "1186787" }, { "name": "Dockerfile", "bytes": "1411" }, { "name": "HTML", "bytes": "456531" }, { "name": "Python", "bytes": "18778786" }, { "name": "Shell", "bytes": "10369" }, { "name": "Smarty", "bytes": "8486" }, { "name": "XSLT", "bytes": "1196" } ], "symlink_target": "" }
module SigSlot # Connect a signal to a slot, but provides a block to rewrite parameters before to propagate def self.connect_and_rewrite(signal, endpoint, &block) raise ArgumentError, "Block missing for connect_and_rewrite" unless block rewriter = Rewriter.new(&block) SigSlot.connect signal, rewriter.slot(:rewrite) rewriter.connect :rewrited, endpoint end # Instancied by connect_and_rewrite to provide a mechanism # of parameters rewriting between a signal and an endpoint class Rewriter include SigSlot signal :rewrited, [:params] slot :rewrite def initialize(&block) @block = block end def rewrite(*params) params = @block.call(params) emit :rewrited, *params end end end #SigSlot
{ "content_hash": "8e7856b2a993b70ae189cc15aaa3ed3b", "timestamp": "", "source": "github", "line_count": 31, "max_line_length": 96, "avg_line_length": 28.741935483870968, "alnum_prop": 0.6105499438832772, "repo_name": "llambeau/sigslot", "id": "5f99d9c4568e4210d0c9350aa47800601ba447a3", "size": "891", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "lib/sigslot/rewriter.rb", "mode": "33188", "license": "mit", "language": [ { "name": "Ruby", "bytes": "40594" } ], "symlink_target": "" }
<!-- @license Copyright (c) 2016 The Polymer Project Authors. All rights reserved. This code may only be used under the BSD style license found at http://polymer.github.io/LICENSE.txt The complete set of authors may be found at http://polymer.github.io/AUTHORS.txt The complete set of contributors may be found at http://polymer.github.io/CONTRIBUTORS.txt Code distributed by Google as part of the polymer project is also subject to an additional IP rights grant found at http://polymer.github.io/PATENTS.txt --> <link rel="import" href="../uvalib-helper-libs/uvalib-helper-libs.html">
{ "content_hash": "c9d59e7274a538ca085adbf1cfc0da48", "timestamp": "", "source": "github", "line_count": 11, "max_line_length": 100, "avg_line_length": 53.36363636363637, "alnum_prop": 0.778534923339012, "repo_name": "uvalib/staff-directory", "id": "195337d9b0b1cea553b6fdf50bcd87c258f672a1", "size": "587", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "bower_components/uvalib-elements/uvalib-elements.html", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "11215" }, { "name": "HTML", "bytes": "30603" }, { "name": "JavaScript", "bytes": "16865" }, { "name": "Ruby", "bytes": "3065" }, { "name": "Shell", "bytes": "104" } ], "symlink_target": "" }
find_path(GLEW_INCLUDE_DIR GL/glew.h HINTS /usr/include PATHS "$ENV{PROGRAMFILES}/glew/include" "$ENV{PROGRAMW6432}/glew/include") find_library(GLEW_LIBRARY NAMES GLEW glew32 HINTS /usr/lib /usr/lib64 PATHS "$ENV{PROGRAMFILES}/glew/lib/Release/Win32" "$ENV{PROGRAMW6432}/glew/lib/Release/x64") set(GLEW_INCLUDE_DIRS ${GLEW_INCLUDE_DIR} ) set(GLEW_LIBRARIES ${GLEW_LIBRARY} ) include(FindPackageHandleStandardArgs) find_package_handle_standard_args(GLEW DEFAULT_MSG GLEW_INCLUDE_DIR GLEW_LIBRARY)
{ "content_hash": "2db7c2e757d95b90e99a9bf4ea9bdf53", "timestamp": "", "source": "github", "line_count": 23, "max_line_length": 64, "avg_line_length": 28.82608695652174, "alnum_prop": 0.5897435897435898, "repo_name": "gregorpm/Depth-Image-Processing", "id": "043dfd5d6078b6d9e02fdd0003e13f12c88a746e", "size": "915", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "cmake/modules/FindGLEW.cmake", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "C++", "bytes": "291341" }, { "name": "CMake", "bytes": "32954" }, { "name": "Cuda", "bytes": "69159" } ], "symlink_target": "" }
<?php namespace Beryllium\Kaboom\Handlers; use Beryllium\Kaboom\KaboomException; class ExceptionHandler implements HandlerInterface { public function handle(string $message): bool { throw new KaboomException($message); } }
{ "content_hash": "ef5f44e903ef868e5deb764c2708ce86", "timestamp": "", "source": "github", "line_count": 12, "max_line_length": 51, "avg_line_length": 20.083333333333332, "alnum_prop": 0.7551867219917012, "repo_name": "beryllium/kaboom", "id": "a3a7878c0042fd7d2388c3aec3110b91547d1e24", "size": "241", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "Handlers/ExceptionHandler.php", "mode": "33188", "license": "mit", "language": [ { "name": "PHP", "bytes": "1290" } ], "symlink_target": "" }
@echo off SET mainClass=sso.tests.Tester SET appName=sphere-swarm-optimizer SET scriptName=%~n0 echo %scriptName%: COMPILING... mkdir target\main dir /s /B *.java > sources.txt javac -d target\main @sources.txt del sources.txt cd target\ echo %scriptName%: PACKAGING IN JAR... jar cfe %appName%.jar %mainClass% -C main . echo %scriptName%: EXECUTING JAR... java -jar %appName%.jar cd ..
{ "content_hash": "d7be73ba94180eabdbbbc247090d5bc5", "timestamp": "", "source": "github", "line_count": 21, "max_line_length": 43, "avg_line_length": 19.61904761904762, "alnum_prop": 0.691747572815534, "repo_name": "gto76/sphere-swarm-optimization", "id": "f997cd9896b16ace1da8743d1a8918f07ee2e3f7", "size": "412", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "run.bat", "mode": "33188", "license": "mit", "language": [ { "name": "Batchfile", "bytes": "412" }, { "name": "Java", "bytes": "209892" }, { "name": "Shell", "bytes": "382" } ], "symlink_target": "" }
package com.buschmais.xo.impl.proxy.entity.property; import com.buschmais.xo.impl.EntityPropertyManager; import com.buschmais.xo.impl.proxy.common.property.AbstractPrimitivePropertySetMethod; import com.buschmais.xo.api.metadata.method.PrimitivePropertyMethodMetadata; public class PrimitivePropertySetMethod<Entity, Relation> extends AbstractPrimitivePropertySetMethod<Entity, EntityPropertyManager<Entity, Relation, ?>> { public PrimitivePropertySetMethod(EntityPropertyManager<Entity, Relation, ?> propertyManager, PrimitivePropertyMethodMetadata metadata) { super(propertyManager, metadata); } }
{ "content_hash": "5515774891d9a39d34d5d4bcafb4e4d6", "timestamp": "", "source": "github", "line_count": 12, "max_line_length": 154, "avg_line_length": 51.583333333333336, "alnum_prop": 0.8336025848142165, "repo_name": "buschmais/extended-objects", "id": "1418912e79375f443a295d54b88675cc9e09eda7", "size": "619", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "impl/src/main/java/com/buschmais/xo/impl/proxy/entity/property/PrimitivePropertySetMethod.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "854112" } ], "symlink_target": "" }
<resources> <style name="AppTheme.NoActionBar"> <item name="windowActionBar">false</item> <item name="windowNoTitle">true</item> <item name="android:windowDrawsSystemBarBackgrounds">true</item> <item name="android:statusBarColor" >@color/colorPrimaryDark</item> </style> </resources>
{ "content_hash": "cde8229f3eb6ba90d2a1545969ca8378", "timestamp": "", "source": "github", "line_count": 8, "max_line_length": 75, "avg_line_length": 40.5, "alnum_prop": 0.6790123456790124, "repo_name": "harman198/RedditClient", "id": "2f6aac0c8b0704b2ebb32d4b750840194034fb7e", "size": "324", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "app/src/main/res/values-v21/styles.xml", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "67905" } ], "symlink_target": "" }
<?php class AIdentityBehaviorDigest extends AIdentityBehavior { public $challengeResponseCallback; /** * @param string $password * @return boolean */ public function apiAuthValidatePassword($password) { //execute challenge response callback method return (call_user_func($this->challengeResponseCallback, $password) === true); } }
{ "content_hash": "af4f7f86bbaebd9d5753bbf4bce58cd7", "timestamp": "", "source": "github", "line_count": 16, "max_line_length": 80, "avg_line_length": 21.9375, "alnum_prop": 0.7407407407407407, "repo_name": "DenitS/yii-apiAuth", "id": "d6a1a6e8eab142112d6b430deacfa3bebfc50682", "size": "454", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "components/protocols/digest/AIdentityBehaviorDigest.php", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "PHP", "bytes": "40566" } ], "symlink_target": "" }
/* * trunc_function.hpp * * Created on: Dec 8, 2015 * Author: bdezonia */ #ifndef SRC_TRUNC_FUNCTION_HPP_ #define SRC_TRUNC_FUNCTION_HPP_ #include "point_function.hpp" class TruncFunction : public PointFunction { public: TruncFunction(const std::shared_ptr<PointFunction>& other); ~TruncFunction(); double evaluate(const size_t dim, const double* point) const; bool acceptsDimensionality(const size_t d) const; private: std::shared_ptr<PointFunction> f; }; #endif /* SRC_TRUNC_FUNCTION_HPP_ */
{ "content_hash": "4aa2c8ed5bed0d4ea14119514db5fcca", "timestamp": "", "source": "github", "line_count": 29, "max_line_length": 65, "avg_line_length": 18.24137931034483, "alnum_prop": 0.6994328922495274, "repo_name": "bdezonia/qdiffle", "id": "6dedfc3d71f84d938479495400a4e7e69b60c993", "size": "1614", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/function/trunc_function.hpp", "mode": "33188", "license": "mit", "language": [ { "name": "C++", "bytes": "243903" } ], "symlink_target": "" }
<?php ##|+PRIV ##|*IDENT=page-services-dnsforwarder-edithost ##|*NAME=Services: DNS Forwarder: Edit host ##|*DESCR=Allow access to the 'Services: DNS Forwarder: Edit host' page. ##|*MATCH=services_dnsmasq_edit.php* ##|-PRIV require_once("guiconfig.inc"); if (!is_array($config['dnsmasq']['hosts'])) { $config['dnsmasq']['hosts'] = array(); } $a_hosts = &$config['dnsmasq']['hosts']; if (is_numericint($_REQUEST['id'])) { $id = $_REQUEST['id']; } if (isset($id) && $a_hosts[$id]) { $pconfig['host'] = $a_hosts[$id]['host']; $pconfig['domain'] = $a_hosts[$id]['domain']; $pconfig['ip'] = $a_hosts[$id]['ip']; $pconfig['descr'] = $a_hosts[$id]['descr']; $pconfig['aliases'] = $a_hosts[$id]['aliases']; } if ($_POST['save']) { unset($input_errors); $pconfig = $_POST; /* input validation */ $reqdfields = explode(" ", "domain ip"); $reqdfieldsn = array(gettext("Domain"), gettext("IP address")); do_input_validation($_POST, $reqdfields, $reqdfieldsn, $input_errors); if ($_POST['host']) { if (!is_hostname($_POST['host'])) { $input_errors[] = gettext("The hostname can only contain the characters A-Z, 0-9 and '-'. It may not start or end with '-'."); } else { if (!is_unqualified_hostname($_POST['host'])) { $input_errors[] = gettext("A valid hostname is specified, but the domain name part should be omitted"); } } } if (($_POST['domain'] && !is_domain($_POST['domain']))) { $input_errors[] = gettext("A valid domain must be specified."); } if (($_POST['ip'] && !is_ipaddr($_POST['ip']))) { $input_errors[] = gettext("A valid IP address must be specified."); } /* collect aliases */ $aliases = array(); if (!empty($_POST['aliashost0'])) { foreach ($_POST as $key => $value) { $entry = ''; if (!substr_compare('aliashost', $key, 0, 9)) { $entry = substr($key, 9); $field = 'host'; } elseif (!substr_compare('aliasdomain', $key, 0, 11)) { $entry = substr($key, 11); $field = 'domain'; } elseif (!substr_compare('aliasdescription', $key, 0, 16)) { $entry = substr($key, 16); $field = 'description'; } if (ctype_digit($entry)) { $aliases[$entry][$field] = $value; } } $pconfig['aliases']['item'] = $aliases; /* validate aliases */ foreach ($aliases as $idx => $alias) { $aliasreqdfields = array('aliasdomain' . $idx); $aliasreqdfieldsn = array(gettext("Alias Domain")); do_input_validation($_POST, $aliasreqdfields, $aliasreqdfieldsn, $input_errors); if ($alias['host']) { if (!is_hostname($alias['host'])) { $input_errors[] = gettext("Hostnames in an alias list can only contain the characters A-Z, 0-9 and '-'. They may not start or end with '-'."); } else { if (!is_unqualified_hostname($alias['host'])) { $input_errors[] = gettext("A valid alias hostname is specified, but the domain name part should be omitted"); } } } if (($alias['domain'] && !is_domain($alias['domain']))) { $input_errors[] = gettext("A valid domain must be specified in alias list."); } } } /* check for overlaps */ foreach ($a_hosts as $hostent) { if (isset($id) && ($a_hosts[$id]) && ($a_hosts[$id] === $hostent)) { continue; } if (($hostent['host'] == $_POST['host']) && ($hostent['domain'] == $_POST['domain'])) { if (is_ipaddrv4($hostent['ip']) && is_ipaddrv4($_POST['ip'])) { $input_errors[] = gettext("This host/domain override combination already exists with an IPv4 address."); break; } if (is_ipaddrv6($hostent['ip']) && is_ipaddrv6($_POST['ip'])) { $input_errors[] = gettext("This host/domain override combination already exists with an IPv6 address."); break; } } } if (!$input_errors) { $hostent = array(); $hostent['host'] = $_POST['host']; $hostent['domain'] = $_POST['domain']; $hostent['ip'] = $_POST['ip']; $hostent['descr'] = $_POST['descr']; $hostent['aliases']['item'] = $aliases; if (isset($id) && $a_hosts[$id]) { $a_hosts[$id] = $hostent; } else { $a_hosts[] = $hostent; } mark_subsystem_dirty('hosts'); write_config(); header("Location: services_dnsmasq.php"); exit; } } // Delete a row in the options table if ($_POST['act'] == "delopt") { $idx = $_POST['id']; if ($pconfig['aliases'] && is_array($pconfig['aliases']['item'][$idx])) { unset($pconfig['aliases']['item'][$idx]); } } // Add an option row if ($_REQUEST['act'] == "addopt") { if (!is_array($pconfig['aliases']['item'])) { $pconfig['aliases']['item'] = array(); } array_push($pconfig['aliases']['item'], array('host' => null, 'domain' => null, 'description' => null)); } $pgtitle = array(gettext("Services"), gettext("DNS Forwarder"), gettext("Edit Host Override")); $pglinks = array("", "services_dnsmasq.php", "@self"); $shortcut_section = "forwarder"; include("head.inc"); if ($input_errors) { print_input_errors($input_errors); } $form = new Form(); $section = new Form_Section('Host Override Options'); $section->addInput(new Form_Input( 'host', 'Host', 'text', $pconfig['host'] ))->setHelp('Name of the host, without the domain part%1$s' . 'e.g.: "myhost"', '<br />'); $section->addInput(new Form_Input( 'domain', '*Domain', 'text', $pconfig['domain'] ))->setHelp('Domain of the host%1$s' . 'e.g.: "example.com"', '<br />'); $section->addInput(new Form_IpAddress( 'ip', '*IP Address', $pconfig['ip'] ))->setHelp('IP address of the host%1$s' . 'e.g.: 192.168.100.100 or fd00:abcd::1', '<br />'); $section->addInput(new Form_Input( 'descr', 'Description', 'text', $pconfig['descr'] ))->setHelp('A description may be entered here for administrative reference (not parsed).'); if (isset($id) && $a_hosts[$id]) { $section->addInput(new Form_Input( 'id', null, 'hidden', $id )); } $form->add($section); $section = new Form_Section('Additional Names for this Host'); if (!$pconfig['aliases']['item']) { $pconfig['aliases']['item'] = array('host' => ""); } if ($pconfig['aliases']['item']) { $counter = 0; $last = count($pconfig['aliases']['item']) - 1; foreach ($pconfig['aliases']['item'] as $item) { $group = new Form_Group(null); $group->addClass('repeatable'); $group->add(new Form_Input( 'aliashost' . $counter, null, 'text', $item['host'] ))->setHelp($counter == $last ? 'Host name':null); $group->add(new Form_Input( 'aliasdomain' . $counter, null, 'text', $item['domain'] ))->setHelp($counter == $last ? 'Domain':null); $group->add(new Form_Input( 'aliasdescription' . $counter, null, 'text', $item['description'] ))->setHelp($counter == $last ? 'Description':null); $group->add(new Form_Button( 'deleterow' . $counter, 'Delete', null, 'fa-trash' ))->addClass('btn-warning')->addClass('nowarn'); $section->add($group); $counter++; } } $form->addGlobal(new Form_Button( 'addrow', 'Add Host Name', null, 'fa-plus' ))->addClass('btn-success addbtn'); $form->add($section); print($form); include("foot.inc");
{ "content_hash": "42f38997b01584c2f30dd98fc20e4cc1", "timestamp": "", "source": "github", "line_count": 275, "max_line_length": 147, "avg_line_length": 25.472727272727273, "alnum_prop": 0.5918629550321199, "repo_name": "NOYB/pfsense", "id": "7d912fbdf0c00783dbc40b5da0ec5c0fd6b270ac", "size": "7927", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "src/usr/local/www/services_dnsmasq_edit.php", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "42668" }, { "name": "JavaScript", "bytes": "68103" }, { "name": "PHP", "bytes": "5576959" }, { "name": "Shell", "bytes": "119189" } ], "symlink_target": "" }
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <!-- NewPage --> <html lang="en"> <head> <!-- Generated by javadoc (version 1.7.0_21) on Thu Dec 12 11:16:52 BRST 2013 --> <title>Uses of Class jason.stdlib.current_intention (Jason - AgentSpeak Java Interpreter)</title> <meta name="date" content="2013-12-12"> <link rel="stylesheet" type="text/css" href="../../../stylesheet.css" title="Style"> </head> <body> <script type="text/javascript"><!-- if (location.href.indexOf('is-external=true') == -1) { parent.document.title="Uses of Class jason.stdlib.current_intention (Jason - AgentSpeak Java Interpreter)"; } //--> </script> <noscript> <div>JavaScript is disabled on your browser.</div> </noscript> <!-- ========= START OF TOP NAVBAR ======= --> <div class="topNav"><a name="navbar_top"> <!-- --> </a><a href="#skip-navbar_top" title="Skip navigation links"></a><a name="navbar_top_firstrow"> <!-- --> </a> <ul class="navList" title="Navigation"> <li><a href="../../../overview-summary.html">Overview</a></li> <li><a href="../package-summary.html">Package</a></li> <li><a href="../../../jason/stdlib/current_intention.html" title="class in jason.stdlib">Class</a></li> <li class="navBarCell1Rev">Use</li> <li><a href="../package-tree.html">Tree</a></li> <li><a href="../../../deprecated-list.html">Deprecated</a></li> <li><a href="../../../index-all.html">Index</a></li> <li><a href="../../../help-doc.html">Help</a></li> </ul> </div> <div class="subNav"> <ul class="navList"> <li>Prev</li> <li>Next</li> </ul> <ul class="navList"> <li><a href="../../../index.html?jason/stdlib/class-use/current_intention.html" target="_top">Frames</a></li> <li><a href="current_intention.html" target="_top">No Frames</a></li> </ul> <ul class="navList" id="allclasses_navbar_top"> <li><a href="../../../allclasses-noframe.html">All Classes</a></li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_top"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } //--> </script> </div> <a name="skip-navbar_top"> <!-- --> </a></div> <!-- ========= END OF TOP NAVBAR ========= --> <div class="header"> <h2 title="Uses of Class jason.stdlib.current_intention" class="title">Uses of Class<br>jason.stdlib.current_intention</h2> </div> <div class="classUseContainer">No usage of jason.stdlib.current_intention</div> <!-- ======= START OF BOTTOM NAVBAR ====== --> <div class="bottomNav"><a name="navbar_bottom"> <!-- --> </a><a href="#skip-navbar_bottom" title="Skip navigation links"></a><a name="navbar_bottom_firstrow"> <!-- --> </a> <ul class="navList" title="Navigation"> <li><a href="../../../overview-summary.html">Overview</a></li> <li><a href="../package-summary.html">Package</a></li> <li><a href="../../../jason/stdlib/current_intention.html" title="class in jason.stdlib">Class</a></li> <li class="navBarCell1Rev">Use</li> <li><a href="../package-tree.html">Tree</a></li> <li><a href="../../../deprecated-list.html">Deprecated</a></li> <li><a href="../../../index-all.html">Index</a></li> <li><a href="../../../help-doc.html">Help</a></li> </ul> </div> <div class="subNav"> <ul class="navList"> <li>Prev</li> <li>Next</li> </ul> <ul class="navList"> <li><a href="../../../index.html?jason/stdlib/class-use/current_intention.html" target="_top">Frames</a></li> <li><a href="current_intention.html" target="_top">No Frames</a></li> </ul> <ul class="navList" id="allclasses_navbar_bottom"> <li><a href="../../../allclasses-noframe.html">All Classes</a></li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_bottom"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } //--> </script> </div> <a name="skip-navbar_bottom"> <!-- --> </a></div> <!-- ======== END OF BOTTOM NAVBAR ======= --> </body> </html>
{ "content_hash": "5e96eae7c21f49e58e23e98202563378", "timestamp": "", "source": "github", "line_count": 115, "max_line_length": 123, "avg_line_length": 35.14782608695652, "alnum_prop": 0.624195942602672, "repo_name": "lsa-pucrs/jason-ros-releases", "id": "d1e74c73ad94a5e170d51aea2b83d1227b92a300", "size": "4042", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "Jason-1.4.0a/doc/api/jason/stdlib/class-use/current_intention.html", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "Batchfile", "bytes": "552" }, { "name": "C++", "bytes": "2070" }, { "name": "CSS", "bytes": "16052" }, { "name": "Groff", "bytes": "2222" }, { "name": "HTML", "bytes": "10409774" }, { "name": "Java", "bytes": "2797033" }, { "name": "Perl6", "bytes": "320" }, { "name": "Pure Data", "bytes": "236280" }, { "name": "Shell", "bytes": "4492" }, { "name": "SourcePawn", "bytes": "756" }, { "name": "XSLT", "bytes": "38136" } ], "symlink_target": "" }
XClass(function (xcl, XWiki) { var props = XWiki.model.properties; xcl.addProp("command", props.XString.create({ "prettyName": "Analyser execution command", })); });
{ "content_hash": "0b91a035ce39a2e3ed9d59d1982120c3", "timestamp": "", "source": "github", "line_count": 6, "max_line_length": 47, "avg_line_length": 29.333333333333332, "alnum_prop": 0.6761363636363636, "repo_name": "xwiki-labs/riscoss-wiki-ui", "id": "7aa6904176dfc7171843b923c2c8f612c3c30de9", "size": "176", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "src/classes/RISCOSSPlatformCode.AnalyserClass.js", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Groovy", "bytes": "3756" }, { "name": "JavaScript", "bytes": "142039" }, { "name": "Shell", "bytes": "299" } ], "symlink_target": "" }
define([ "util/eventemitter" ], function(Emitter) { describe('Event Emitter', function() { var emitter; beforeEach(function() { emitter = new Emitter(); }); it('Should store handlers for a given event', function() { var handler = function() {}; emitter.on('myevent', handler); var events = emitter.events.myevent; expect(events.length).toBe(1); expect(events[0]).toBe(handler); }); it('Should store multiple handlers for the same event', function() { emitter.on('myevent', function() {}); emitter.on('myevent', function() {}); var events = emitter.events.myevent; expect(events.length).toBe(2); expect(events[0]).not.toBe(events[1]); }); it('Executes the handlers when emitting a given event', function() { var handler1 = jasmine.createSpy(); var handler2 = jasmine.createSpy(); emitter.on('myevent', handler1); emitter.on('myevent', handler2); emitter.emit('myevent'); expect(handler1).toHaveBeenCalled(); expect(handler2).toHaveBeenCalled(); }); it('Executes the handlers with data passed in as the first function argument', function() { var handler = jasmine.createSpy(); var data = { foo: 'bar' }; emitter.on('myevent', handler); emitter.emit('myevent', data); expect(handler).toHaveBeenCalledWith(data); }); it('Removes all handlers for a given event', function() { emitter.on('myevent', function() {}); emitter.off('myevent'); expect(emitter.events.myevent).toBe(undefined); }); it('Removes specific handlers for a given event', function() { var handler1 = function() {}; var handler2 = function() {}; emitter.on('myevent', handler1); emitter.on('myevent', handler2); emitter.off('myevent', handler1); expect(emitter.events.myevent.length).toBe(1); expect(emitter.events.myevent[0]).toBe(handler2); emitter.off('myevent', handler2); expect(emitter.events.myevent).toBe(undefined); }); it('Provides a trigger API method', function() { expect(typeof emitter.trigger).toBe('function'); var handler1 = jasmine.createSpy(); var handler2 = jasmine.createSpy(); emitter.on('myevent', handler1); emitter.on('myevent', handler2); emitter.trigger('myevent'); expect(handler1).toHaveBeenCalled(); expect(handler2).toHaveBeenCalled(); }); }); });
{ "content_hash": "ac1f6c6785c82167bba30f34fb666e97", "timestamp": "", "source": "github", "line_count": 100, "max_line_length": 95, "avg_line_length": 25.18, "alnum_prop": 0.6151707704527403, "repo_name": "badsyntax/express-project-boilerplate", "id": "c526dbbd8452797b45628707b88aaad09c32412d", "size": "2518", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "app/public/tests/specs/util/eventemitter.spec.js", "mode": "33188", "license": "mit", "language": [ { "name": "JavaScript", "bytes": "37113" }, { "name": "Puppet", "bytes": "3522" }, { "name": "Ruby", "bytes": "913" } ], "symlink_target": "" }
namespace base { namespace CValDetail { // This class tracks entries over a specified time period, which it does not // retain in memory. When the time period has elapsed, the average, minimum, // maximum, and standard deviation of that time period are recorded with CVals, // and the tracking resets for the next time period. // NOTE: In cases where the number of entries are small and stats for time // periods are not needed, |CValCollectionEntryStats| may be more // appropriate. It retains the entries for the collection in memory so // that it can provide the collection's percentiles. template <typename EntryType, typename Visibility> class CValTimeIntervalEntryStatsImpl { public: CValTimeIntervalEntryStatsImpl(const std::string& name, int64 time_interval_in_ms); void AddEntry(const EntryType& value); void AddEntry(const EntryType& value, const base::TimeTicks& now); private: void AddToActiveEntryStats(const EntryType& value); void ResetActiveEntryStats(); const int64 time_interval_in_ms_; // CVals of the stats for the previously completed time interval. base::CVal<size_t, Visibility> count_; base::CVal<EntryType, Visibility> average_; base::CVal<EntryType, Visibility> minimum_; base::CVal<EntryType, Visibility> maximum_; base::CVal<EntryType, Visibility> standard_deviation_; // Active time interval-related base::TimeTicks active_start_time_; // Variance calculations are based upon the following: // https://en.wikipedia.org/wiki/Algorithms_for_calculating_variance#Computing_shifted_data // Each value is shifted by an estimated mean when calculating the variance. // This increases accuracy in cases where the variance is small but the values // involved are extremely large. // The following article provides a more detailed discussion on the topic: // http://www.cs.yale.edu/publications/techreports/tr222.pdf // During the first time interval, the initial entry acts as the estimated // mean. All subsequent loops use the mean of the previous time interval. double active_estimated_mean_; // Stats updated with each new entry. int64 active_count_; double active_shifted_sum_; double active_shifted_sum_squares_; EntryType active_minimum_; EntryType active_maximum_; }; template <typename EntryType, typename Visibility> CValTimeIntervalEntryStatsImpl<EntryType, Visibility>:: CValTimeIntervalEntryStatsImpl(const std::string& name, int64 time_interval_in_ms) : time_interval_in_ms_(time_interval_in_ms), count_(base::StringPrintf("%s.Cnt", name.c_str()), 0, "Total entries."), average_(base::StringPrintf("%s.Avg", name.c_str()), EntryType(), "Average time."), minimum_(base::StringPrintf("%s.Min", name.c_str()), EntryType(), "Minimum time."), maximum_(base::StringPrintf("%s.Max", name.c_str()), EntryType(), "Maximum time."), standard_deviation_(base::StringPrintf("%s.Std", name.c_str()), EntryType(), "Standard deviation of times."), active_estimated_mean_(0) { ResetActiveEntryStats(); } template <typename EntryType, typename Visibility> void CValTimeIntervalEntryStatsImpl<EntryType, Visibility>::AddEntry( const EntryType& value) { base::TimeTicks now = base::TimeTicks::Now(); AddEntry(value, now); } template <typename EntryType, typename Visibility> void CValTimeIntervalEntryStatsImpl<EntryType, Visibility>::AddEntry( const EntryType& value, const base::TimeTicks& now) { // Check to see if the timer hasn't started yet. This happens when this is // the first entry ever added. In this case, the timer is simply started and // the estimated mean is set to the passed in value. if (active_start_time_.is_null()) { active_start_time_ = now; active_estimated_mean_ = CValDetail::ToDouble(value); // Otherwise, check for the time interval having ended. If it has, then the // CVals are updated using the active stats, the active stats are reset, and // the timer restarted. } else if ((now - active_start_time_).InMilliseconds() > time_interval_in_ms_) { // The active count can never be 0 when a time interval has ended. There // must always be at least one entry when the time is non-null. DCHECK_GT(active_count_, 0); count_ = active_count_; double active_shifted_mean = active_shifted_sum_ / active_count_; average_ = CValDetail::FromDouble<EntryType>(active_estimated_mean_ + active_shifted_mean); // The equation comes from the following: // https://en.wikipedia.org/wiki/Algorithms_for_calculating_variance#Computing_shifted_data double variance = (active_shifted_sum_squares_ - ((active_shifted_sum_ * active_shifted_sum_) / active_count_)) / active_count_; variance = std::max(variance, 0.0); standard_deviation_ = CValDetail::FromDouble<EntryType>(std::sqrt(variance)); minimum_ = active_minimum_; maximum_ = active_maximum_; // Prepare the active data for the next time interval, including updating // the estimated mean with the calculated mean of the previous time // interval. active_start_time_ = now; active_estimated_mean_ += active_shifted_mean; ResetActiveEntryStats(); } AddToActiveEntryStats(value); } template <typename EntryType, typename Visibility> void CValTimeIntervalEntryStatsImpl< EntryType, Visibility>::AddToActiveEntryStats(const EntryType& value) { ++active_count_; double shifted_value_as_double = CValDetail::ToDouble(value) - active_estimated_mean_; active_shifted_sum_ += shifted_value_as_double; active_shifted_sum_squares_ += shifted_value_as_double * shifted_value_as_double; if (value < active_minimum_) { active_minimum_ = value; } if (value > active_maximum_) { active_maximum_ = value; } } template <typename EntryType, typename Visibility> void CValTimeIntervalEntryStatsImpl<EntryType, Visibility>::ResetActiveEntryStats() { active_count_ = 0; active_shifted_sum_ = 0; active_shifted_sum_squares_ = 0; active_minimum_ = CValDetail::Max<EntryType>(); active_maximum_ = CValDetail::Min<EntryType>(); } #if !defined(ENABLE_DEBUG_C_VAL) // This is a stub class that disables CValTimeIntervalEntryStats when // ENABLE_DEBUG_C_VAL is not defined. template <typename EntryType> class CValTimeIntervalEntryStatsStub { public: CValTimeIntervalEntryStatsStub(const std::string& name, int64 time_interval_in_ms) { } void AddEntry(const EntryType& value) {} void AddEntry(const EntryType& value, const base::TimeTicks& now) {} }; #endif // ENABLE_DEBUG_C_VAL } // namespace CValDetail template <typename EntryType, typename Visibility = CValDebug> class CValTimeIntervalEntryStats {}; template <typename EntryType> #if defined(ENABLE_DEBUG_C_VAL) // When ENABLE_DEBUG_C_VAL is defined, CVals with Visibility set to CValDebug // are tracked through the CVal system. class CValTimeIntervalEntryStats<EntryType, CValDebug> : public CValDetail::CValTimeIntervalEntryStatsImpl<EntryType, CValDebug> { typedef CValDetail::CValTimeIntervalEntryStatsImpl<EntryType, CValDebug> CValParent; #else // ENABLE_DEBUG_C_VAL // When ENABLE_DEBUG_C_VAL is not defined, CVals with Visibility set to // CValDebug are not tracked though the CVal system and // CValTimeIntervalEntryStats can be stubbed out. class CValTimeIntervalEntryStats<EntryType, CValDebug> : public CValDetail::CValTimeIntervalEntryStatsStub<EntryType> { typedef CValDetail::CValTimeIntervalEntryStatsStub<EntryType> CValParent; #endif // ENABLE_DEBUG_C_VAL public: CValTimeIntervalEntryStats(const std::string& name, int64 time_interval_in_ms) : CValParent(name, time_interval_in_ms) {} }; // CVals with visibility set to CValPublic are always tracked though the CVal // system, regardless of the ENABLE_DEBUG_C_VAL state. template <typename EntryType> class CValTimeIntervalEntryStats<EntryType, CValPublic> : public CValDetail::CValTimeIntervalEntryStatsImpl<EntryType, CValPublic> { typedef CValDetail::CValTimeIntervalEntryStatsImpl<EntryType, CValPublic> CValParent; public: CValTimeIntervalEntryStats(const std::string& name, int64 time_interval_in_ms) : CValParent(name, time_interval_in_ms) {} }; } // namespace base #endif // COBALT_BASE_C_VAL_TIME_INTERVAL_ENTRY_STATS_H_
{ "content_hash": "98b0bf2569180a37199a15144b564d2d", "timestamp": "", "source": "github", "line_count": 214, "max_line_length": 95, "avg_line_length": 40.200934579439256, "alnum_prop": 0.7125421364640242, "repo_name": "youtube/cobalt_sandbox", "id": "81dd774bc3390339469c57891f9f1266347f89bf", "size": "9513", "binary": false, "copies": "2", "ref": "refs/heads/main", "path": "cobalt/base/c_val_time_interval_entry_stats.h", "mode": "33188", "license": "bsd-3-clause", "language": [], "symlink_target": "" }
ACCEPTED #### According to Index Fungorum #### Published in Monogr. Discom. Bohem. (Prague) 129 (1934) #### Original name Belonidium frustulosum Velen. ### Remarks null
{ "content_hash": "52ff18b2a5588b3004548ce1ee66dc7e", "timestamp": "", "source": "github", "line_count": 13, "max_line_length": 42, "avg_line_length": 13.23076923076923, "alnum_prop": 0.7093023255813954, "repo_name": "mdoering/backbone", "id": "41f2a3c2358d8f1c3d3e22e16f1105727f750ba4", "size": "225", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "life/Fungi/Ascomycota/Leotiomycetes/Helotiales/Hyaloscyphaceae/Belonidium/Belonidium frustulosum/README.md", "mode": "33188", "license": "apache-2.0", "language": [], "symlink_target": "" }
<?xml version='1.0' encoding='UTF-8'?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd"> <html> <head> <title>org.scalatest.junit.AssertionsForJUnit</title> <meta http-equiv="content-type" content="text/html; charset=UTF-8" /> <link type="text/css" media="screen" rel="stylesheet" href="../../../lib/template.css" /> <script type="text/javascript" src="../../../lib/jquery.js"></script> <script type="text/javascript" src="../../../lib/jquery-ui.js"></script> <script type="text/javascript" src="../../../lib/template.js"></script> <script type="text/javascript" src="../../../lib/tools.tooltip.js"></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 class="value"> <div id="definition"> <a title="Go to companion" href="AssertionsForJUnit.html"><img src="../../../lib/object_to_trait_big.png" /></a> <p id="owner"><a name="org" class="extype" href="../../package.html">org</a>.<a name="org.scalatest" class="extype" href="../package.html">scalatest</a>.<a name="org.scalatest.junit" class="extype" href="package.html">junit</a></p> <h1><a title="Go to companion" href="AssertionsForJUnit.html">AssertionsForJUnit</a></h1> </div> <h4 class="signature" id="signature"> <span class="kind">object</span> <span class="symbol"> <span class="name">AssertionsForJUnit</span> <span class="result"> extends <a name="org.scalatest.junit.AssertionsForJUnit" class="extype" href="AssertionsForJUnit.html">AssertionsForJUnit</a></span> </span> </h4> <div class="fullcommenttop" id="comment"><div class="comment cmt"><p>Companion object that facilitates the importing of <code>AssertionsForJUnit</code> members as an alternative to mixing it in. One use case is to import <code>AssertionsForJUnit</code> members so you can use them in the Scala interpreter:</p><p><pre> $ scala -cp junit3.8.2/junit.jar:../target/jar_contents Welcome to Scala version 2.7.5.final (Java HotSpot(TM) Client VM, Java 1.5.0_16). Type in expressions to have them evaluated. Type :help for more information. scala> import org.scalatest.junit.AssertionsForJUnit._ import org.scalatest.junit.AssertionsForJUnit._ scala> assert(1 === 2) junit.framework.AssertionFailedError: 1 did not equal 2 at org.scalatest.junit.AssertionsForJUnit$class.assert(AssertionsForJUnit.scala:353) at org.scalatest.junit.AssertionsForJUnit$.assert(AssertionsForJUnit.scala:672) at .<init>(<console>:7) at .<clinit>(<console>) at RequestResult$.<init>(<console>:3) at RequestResult$.<clinit>(<console>) at RequestResult$result(<consol... scala> expect(3) { 1 + 3 } junit.framework.AssertionFailedError: Expected 3, but got 4 at org.scalatest.junit.AssertionsForJUnit$class.expect(AssertionsForJUnit.scala:563) at org.scalatest.junit.AssertionsForJUnit$.expect(AssertionsForJUnit.scala:672) at .<init>(<console>:7) at .<clinit>(<console>) at RequestResult$.<init>(<console>:3) at RequestResult$.<clinit>(<console>) at RequestResult$result(<co... scala> val caught = intercept[StringIndexOutOfBoundsException] { "hi".charAt(-1) } caught: StringIndexOutOfBoundsException = java.lang.StringIndexOutOfBoundsException: String index out of range: -1 <pre> @author Bill Venners </p></div><div class="toggleContainer block"> <span class="toggle">Linear Supertypes</span> <div class="superTypes hiddenContent"><a name="org.scalatest.junit.AssertionsForJUnit" class="extype" href="AssertionsForJUnit.html">AssertionsForJUnit</a>, <a name="org.scalatest.Assertions" class="extype" href="../Assertions.html">Assertions</a>, AnyRef, <span name="scala.Any" class="extype">Any</span></div> </div></div> <div id="template"> <div id="mbrsel"> <div id="textfilter"><span class="pre"></span><span class="input"><input accesskey="/" type="text" /></span><span class="post"></span></div> <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 id="ancestors"> <span class="filtertype">Inherited</span> <ol><li class="hideall out"><span>Hide All</span></li> <li class="showall in"><span>Show all</span></li></ol> <ol id="linearization"><li name="org.scalatest.junit.AssertionsForJUnit" class="in"><span>AssertionsForJUnit</span></li><li name="org.scalatest.junit.AssertionsForJUnit" class="in"><span>AssertionsForJUnit</span></li><li name="org.scalatest.Assertions" class="in"><span>Assertions</span></li><li name="scala.AnyRef" class="in"><span>AnyRef</span></li><li name="scala.Any" class="in"><span>Any</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 class="types members" id="types"> <h3>Type Members</h3> <ol><li visbl="pub" name="org.scalatest.Assertions.Equalizer" data-isabs="false"> <a id="Equalizer:Equalizer"></a> <h4 class="signature"> <span class="kind">class</span> <span class="symbol"> <a href="../Assertions$Equalizer.html"><span class="name">Equalizer</span></a> <span class="result"> extends AnyRef</span> </span> </h4> <p class="comment cmt">Class used via an implicit conversion to enable any two objects to be compared with <code>===</code> in assertions in tests.</p> </li></ol> </div> <div class="values members" id="values"> <h3>Value Members</h3> <ol><li visbl="pub" name="scala.AnyRef#!=" data-isabs="false"> <a id="!=(AnyRef):Boolean"></a> <h4 class="signature"> <span class="kind">def</span> <span class="symbol"> <span class="name">!=</span> <span class="params">(<span name="arg0">arg0: AnyRef</span>)</span><span class="result">: <span name="scala.Boolean" class="extype">Boolean</span></span> </span> </h4> <div class="fullcomment"><dl class="attributes block"> <dt>Attributes</dt><dd>final </dd><dt>Definition Classes</dt><dd>AnyRef</dd></dl></div> </li><li visbl="pub" name="scala.Any#!=" data-isabs="false"> <a id="!=(Any):Boolean"></a> <h4 class="signature"> <span class="kind">def</span> <span class="symbol"> <span class="name">!=</span> <span class="params">(<span name="arg0">arg0: <span name="scala.Any" class="extype">Any</span></span>)</span><span class="result">: <span name="scala.Boolean" class="extype">Boolean</span></span> </span> </h4> <div class="fullcomment"><dl class="attributes block"> <dt>Attributes</dt><dd>final </dd><dt>Definition Classes</dt><dd>Any</dd></dl></div> </li><li visbl="pub" name="scala.AnyRef###" data-isabs="false"> <a id="##():Int"></a> <h4 class="signature"> <span class="kind">def</span> <span class="symbol"> <span class="name">##</span> <span class="params">()</span><span class="result">: <span name="scala.Int" class="extype">Int</span></span> </span> </h4> <div class="fullcomment"><dl class="attributes block"> <dt>Attributes</dt><dd>final </dd><dt>Definition Classes</dt><dd>AnyRef → Any</dd></dl></div> </li><li visbl="pub" name="scala.AnyRef#==" data-isabs="false"> <a id="==(AnyRef):Boolean"></a> <h4 class="signature"> <span class="kind">def</span> <span class="symbol"> <span class="name">==</span> <span class="params">(<span name="arg0">arg0: AnyRef</span>)</span><span class="result">: <span name="scala.Boolean" class="extype">Boolean</span></span> </span> </h4> <div class="fullcomment"><dl class="attributes block"> <dt>Attributes</dt><dd>final </dd><dt>Definition Classes</dt><dd>AnyRef</dd></dl></div> </li><li visbl="pub" name="scala.Any#==" data-isabs="false"> <a id="==(Any):Boolean"></a> <h4 class="signature"> <span class="kind">def</span> <span class="symbol"> <span class="name">==</span> <span class="params">(<span name="arg0">arg0: <span name="scala.Any" class="extype">Any</span></span>)</span><span class="result">: <span name="scala.Boolean" class="extype">Boolean</span></span> </span> </h4> <div class="fullcomment"><dl class="attributes block"> <dt>Attributes</dt><dd>final </dd><dt>Definition Classes</dt><dd>Any</dd></dl></div> </li><li visbl="pub" name="scala.Any#asInstanceOf" data-isabs="false"> <a id="asInstanceOf[T0]:T0"></a> <h4 class="signature"> <span class="kind">def</span> <span class="symbol"> <span class="name">asInstanceOf</span> <span class="tparams">[<span name="T0">T0</span>]</span> <span class="result">: T0</span> </span> </h4> <div class="fullcomment"><dl class="attributes block"> <dt>Attributes</dt><dd>final </dd><dt>Definition Classes</dt><dd>Any</dd></dl></div> </li><li visbl="pub" name="org.scalatest.Assertions#assert" data-isabs="false"> <a id="assert(Option[String]):Unit"></a> <h4 class="signature"> <span class="kind">def</span> <span class="symbol"> <span class="name">assert</span> <span class="params">(<span name="o">o: <span name="scala.Option" class="extype">Option</span>[String]</span>)</span><span class="result">: <span name="scala.Unit" class="extype">Unit</span></span> </span> </h4> <p class="shortcomment cmt">Assert that an <code>Option[String]</code> is <code>None</code>.</p><div class="fullcomment"><div class="comment cmt"><p>Assert that an <code>Option[String]</code> is <code>None</code>. If the condition is <code>None</code>, this method returns normally. Else, it throws <code>TestFailedException</code> with the <code>String</code> value of the <code>Some</code> included in the <code>TestFailedException</code>'s detail message.</p><p>This form of <code>assert</code> is usually called in conjunction with an implicit conversion to <code>Equalizer</code>, using a <code>===</code> comparison, as in:</p><p><pre> assert(a === b) </pre></p><p>For more information on how this mechanism works, see the <a href="Suite.Equalizer.html">documentation for <code>Equalizer</code></a>.</p></div><dl class="paramcmts block"><dt class="param">o</dt><dd class="cmt"><p>the <code>Option[String]</code> to assert</p></dd></dl><dl class="attributes block"> <dt>Definition Classes</dt><dd><a name="org.scalatest.Assertions" class="extype" href="../Assertions.html">Assertions</a></dd></dl></div> </li><li visbl="pub" name="org.scalatest.Assertions#assert" data-isabs="false"> <a id="assert(Option[String],Any):Unit"></a> <h4 class="signature"> <span class="kind">def</span> <span class="symbol"> <span class="name">assert</span> <span class="params">(<span name="o">o: <span name="scala.Option" class="extype">Option</span>[String]</span>, <span name="clue">clue: <span name="scala.Any" class="extype">Any</span></span>)</span><span class="result">: <span name="scala.Unit" class="extype">Unit</span></span> </span> </h4> <p class="shortcomment cmt">Assert that an <code>Option[String]</code> is <code>None</code>.</p><div class="fullcomment"><div class="comment cmt"><p>Assert that an <code>Option[String]</code> is <code>None</code>. If the condition is <code>None</code>, this method returns normally. Else, it throws <code>TestFailedException</code> with the <code>String</code> value of the <code>Some</code>, as well as the <code>String</code> obtained by invoking <code>toString</code> on the specified <code>message</code>, included in the <code>TestFailedException</code>'s detail message.</p><p>This form of <code>assert</code> is usually called in conjunction with an implicit conversion to <code>Equalizer</code>, using a <code>===</code> comparison, as in:</p><p><pre> assert(a === b, "extra info reported if assertion fails") </pre></p><p>For more information on how this mechanism works, see the <a href="Suite.Equalizer.html">documentation for <code>Equalizer</code></a>.</p></div><dl class="paramcmts block"><dt class="param">o</dt><dd class="cmt"><p>the <code>Option[String]</code> to assert</p></dd><dt class="param">clue</dt><dd class="cmt"><p>An objects whose <code>toString</code> method returns a message to include in a failure report.</p></dd></dl><dl class="attributes block"> <dt>Definition Classes</dt><dd><a name="org.scalatest.Assertions" class="extype" href="../Assertions.html">Assertions</a></dd></dl></div> </li><li visbl="pub" name="org.scalatest.Assertions#assert" data-isabs="false"> <a id="assert(Boolean,Any):Unit"></a> <h4 class="signature"> <span class="kind">def</span> <span class="symbol"> <span class="name">assert</span> <span class="params">(<span name="condition">condition: <span name="scala.Boolean" class="extype">Boolean</span></span>, <span name="clue">clue: <span name="scala.Any" class="extype">Any</span></span>)</span><span class="result">: <span name="scala.Unit" class="extype">Unit</span></span> </span> </h4> <p class="shortcomment cmt">Assert that a boolean condition, described in <code>String</code> <code>message</code>, is true.</p><div class="fullcomment"><div class="comment cmt"><p>Assert that a boolean condition, described in <code>String</code> <code>message</code>, is true. If the condition is <code>true</code>, this method returns normally. Else, it throws <code>TestFailedException</code> with the <code>String</code> obtained by invoking <code>toString</code> on the specified <code>message</code> as the exception's detail message. </p></div><dl class="paramcmts block"><dt class="param">condition</dt><dd class="cmt"><p>the boolean condition to assert</p></dd><dt class="param">clue</dt><dd class="cmt"><p>An objects whose <code>toString</code> method returns a message to include in a failure report.</p></dd></dl><dl class="attributes block"> <dt>Definition Classes</dt><dd><a name="org.scalatest.Assertions" class="extype" href="../Assertions.html">Assertions</a></dd></dl></div> </li><li visbl="pub" name="org.scalatest.Assertions#assert" data-isabs="false"> <a id="assert(Boolean):Unit"></a> <h4 class="signature"> <span class="kind">def</span> <span class="symbol"> <span class="name">assert</span> <span class="params">(<span name="condition">condition: <span name="scala.Boolean" class="extype">Boolean</span></span>)</span><span class="result">: <span name="scala.Unit" class="extype">Unit</span></span> </span> </h4> <p class="shortcomment cmt">Assert that a boolean condition is true.</p><div class="fullcomment"><div class="comment cmt"><p>Assert that a boolean condition is true. If the condition is <code>true</code>, this method returns normally. Else, it throws <code>TestFailedException</code>. </p></div><dl class="paramcmts block"><dt class="param">condition</dt><dd class="cmt"><p>the boolean condition to assert</p></dd></dl><dl class="attributes block"> <dt>Definition Classes</dt><dd><a name="org.scalatest.Assertions" class="extype" href="../Assertions.html">Assertions</a></dd></dl></div> </li><li visbl="prt" name="scala.AnyRef#clone" data-isabs="false"> <a id="clone():AnyRef"></a> <h4 class="signature"> <span class="kind">def</span> <span class="symbol"> <span class="name">clone</span> <span class="params">()</span><span class="result">: AnyRef</span> </span> </h4> <div class="fullcomment"><dl class="attributes block"> <dt>Attributes</dt><dd>protected[<a name="java.lang" class="extype" href="../../../java/lang/package.html">lang</a>] </dd><dt>Definition Classes</dt><dd>AnyRef</dd><dt>Annotations</dt><dd> <span class="name">@throws</span><span class="args">()</span> </dd></dl></div> </li><li visbl="pub" name="org.scalatest.Assertions#convertToEqualizer" data-isabs="false"> <a id="convertToEqualizer(Any):Equalizer"></a> <h4 class="signature"> <span class="kind">implicit def</span> <span class="symbol"> <span class="name">convertToEqualizer</span> <span class="params">(<span name="left">left: <span name="scala.Any" class="extype">Any</span></span>)</span><span class="result">: <a name="org.scalatest.Assertions.Equalizer" class="extype" href="../Assertions$Equalizer.html">Equalizer</a></span> </span> </h4> <p class="shortcomment cmt">Implicit conversion from <code>Any</code> to <code>Equalizer</code>, used to enable assertions with <code>===</code> comparisons.</p><div class="fullcomment"><div class="comment cmt"><p>Implicit conversion from <code>Any</code> to <code>Equalizer</code>, used to enable assertions with <code>===</code> comparisons.</p><p>For more information on this mechanism, see the <a href="Suite.Equalizer.html">documentation for </code>Equalizer</code></a>.</p><p>Because trait <code>Suite</code> mixes in <code>Assertions</code>, this implicit conversion will always be available by default in ScalaTest <code>Suite</code>s. This is the only implicit conversion that is in scope by default in every ScalaTest <code>Suite</code>. Other implicit conversions offered by ScalaTest, such as those that support the matchers DSL or <code>invokePrivate</code>, must be explicitly invited into your test code, either by mixing in a trait or importing the members of its companion object. The reason ScalaTest requires you to invite in implicit conversions (with the exception of the implicit conversion for <code>===</code> operator) is because if one of ScalaTest's implicit conversions clashes with an implicit conversion used in the code you are trying to test, your program won't compile. Thus there is a chance that if you are ever trying to use a library or test some code that also offers an implicit conversion involving a <code>===</code> operator, you could run into the problem of a compiler error due to an ambiguous implicit conversion. If that happens, you can turn off the implicit conversion offered by this <code>convertToEqualizer</code> method simply by overriding the method in your <code>Suite</code> subclass, but not marking it as implicit:</p><p><pre> // In your Suite subclass override def convertToEqualizer(left: Any) = new Equalizer(left) </pre> </p></div><dl class="paramcmts block"><dt class="param">left</dt><dd class="cmt"><p>the object whose type to convert to <code>Equalizer</code>.</p></dd></dl><dl class="attributes block"> <dt>Attributes</dt><dd>implicit </dd><dt>Definition Classes</dt><dd><a name="org.scalatest.Assertions" class="extype" href="../Assertions.html">Assertions</a></dd></dl></div> </li><li visbl="pub" name="scala.AnyRef#eq" data-isabs="false"> <a id="eq(AnyRef):Boolean"></a> <h4 class="signature"> <span class="kind">def</span> <span class="symbol"> <span class="name">eq</span> <span class="params">(<span name="arg0">arg0: AnyRef</span>)</span><span class="result">: <span name="scala.Boolean" class="extype">Boolean</span></span> </span> </h4> <div class="fullcomment"><dl class="attributes block"> <dt>Attributes</dt><dd>final </dd><dt>Definition Classes</dt><dd>AnyRef</dd></dl></div> </li><li visbl="pub" name="scala.AnyRef#equals" data-isabs="false"> <a id="equals(Any):Boolean"></a> <h4 class="signature"> <span class="kind">def</span> <span class="symbol"> <span class="name">equals</span> <span class="params">(<span name="arg0">arg0: <span name="scala.Any" class="extype">Any</span></span>)</span><span class="result">: <span name="scala.Boolean" class="extype">Boolean</span></span> </span> </h4> <div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd>AnyRef → Any</dd></dl></div> </li><li visbl="pub" name="org.scalatest.Assertions#expect" data-isabs="false"> <a id="expect(Any)(Any):Unit"></a> <h4 class="signature"> <span class="kind">def</span> <span class="symbol"> <span class="name">expect</span> <span class="params">(<span name="expected">expected: <span name="scala.Any" class="extype">Any</span></span>)</span><span class="params">(<span name="actual">actual: <span name="scala.Any" class="extype">Any</span></span>)</span><span class="result">: <span name="scala.Unit" class="extype">Unit</span></span> </span> </h4> <p class="shortcomment cmt">Expect that the value passed as <code>expected</code> equals the value passed as <code>actual</code>.</p><div class="fullcomment"><div class="comment cmt"><p>Expect that the value passed as <code>expected</code> equals the value passed as <code>actual</code>. If the <code>actual</code> value equals the <code>expected</code> value (as determined by <code>==</code>), <code>expect</code> returns normally. Else, <code>expect</code> throws an <code>TestFailedException</code> whose detail message includes the expected and actual values. </p></div><dl class="paramcmts block"><dt class="param">expected</dt><dd class="cmt"><p>the expected value</p></dd><dt class="param">actual</dt><dd class="cmt"><p>the actual value, which should equal the passed <code>expected</code> value</p></dd></dl><dl class="attributes block"> <dt>Definition Classes</dt><dd><a name="org.scalatest.Assertions" class="extype" href="../Assertions.html">Assertions</a></dd></dl></div> </li><li visbl="pub" name="org.scalatest.Assertions#expect" data-isabs="false"> <a id="expect(Any,Any)(Any):Unit"></a> <h4 class="signature"> <span class="kind">def</span> <span class="symbol"> <span class="name">expect</span> <span class="params">(<span name="expected">expected: <span name="scala.Any" class="extype">Any</span></span>, <span name="clue">clue: <span name="scala.Any" class="extype">Any</span></span>)</span><span class="params">(<span name="actual">actual: <span name="scala.Any" class="extype">Any</span></span>)</span><span class="result">: <span name="scala.Unit" class="extype">Unit</span></span> </span> </h4> <p class="shortcomment cmt">Expect that the value passed as <code>expected</code> equals the value passed as <code>actual</code>.</p><div class="fullcomment"><div class="comment cmt"><p>Expect that the value passed as <code>expected</code> equals the value passed as <code>actual</code>. If the <code>actual</code> equals the <code>expected</code> (as determined by <code>==</code>), <code>expect</code> returns normally. Else, if <code>actual</code> is not equal to <code>expected</code>, <code>expect</code> throws an <code>TestFailedException</code> whose detail message includes the expected and actual values, as well as the <code>String</code> obtained by invoking <code>toString</code> on the passed <code>message</code>. </p></div><dl class="paramcmts block"><dt class="param">expected</dt><dd class="cmt"><p>the expected value</p></dd><dt class="param">clue</dt><dd class="cmt"><p>An object whose <code>toString</code> method returns a message to include in a failure report.</p></dd><dt class="param">actual</dt><dd class="cmt"><p>the actual value, which should equal the passed <code>expected</code> value</p></dd></dl><dl class="attributes block"> <dt>Definition Classes</dt><dd><a name="org.scalatest.Assertions" class="extype" href="../Assertions.html">Assertions</a></dd></dl></div> </li><li visbl="pub" name="org.scalatest.Assertions#fail" data-isabs="false"> <a id="fail(Throwable):Nothing"></a> <h4 class="signature"> <span class="kind">def</span> <span class="symbol"> <span class="name">fail</span> <span class="params">(<span name="cause">cause: Throwable</span>)</span><span class="result">: <span name="scala.Nothing" class="extype">Nothing</span></span> </span> </h4> <p class="shortcomment cmt">Throws <code>TestFailedException</code>, with the passed <code>Throwable</code> cause, to indicate a test failed.</p><div class="fullcomment"><div class="comment cmt"><p>Throws <code>TestFailedException</code>, with the passed <code>Throwable</code> cause, to indicate a test failed. The <code>getMessage</code> method of the thrown <code>TestFailedException</code> will return <code>cause.toString()</code>. </p></div><dl class="paramcmts block"><dt class="param">cause</dt><dd class="cmt"><p>a <code>Throwable</code> that indicates the cause of the failure.</p></dd></dl><dl class="attributes block"> <dt>Definition Classes</dt><dd><a name="org.scalatest.Assertions" class="extype" href="../Assertions.html">Assertions</a></dd></dl></div> </li><li visbl="pub" name="org.scalatest.Assertions#fail" data-isabs="false"> <a id="fail(String,Throwable):Nothing"></a> <h4 class="signature"> <span class="kind">def</span> <span class="symbol"> <span class="name">fail</span> <span class="params">(<span name="message">message: String</span>, <span name="cause">cause: Throwable</span>)</span><span class="result">: <span name="scala.Nothing" class="extype">Nothing</span></span> </span> </h4> <p class="shortcomment cmt">Throws <code>TestFailedException</code>, with the passed <code>String</code> <code>message</code> as the exception's detail message and <code>Throwable</code> cause, to indicate a test failed.</p><div class="fullcomment"><div class="comment cmt"><p>Throws <code>TestFailedException</code>, with the passed <code>String</code> <code>message</code> as the exception's detail message and <code>Throwable</code> cause, to indicate a test failed. </p></div><dl class="paramcmts block"><dt class="param">message</dt><dd class="cmt"><p>A message describing the failure.</p></dd><dt class="param">cause</dt><dd class="cmt"><p>A <code>Throwable</code> that indicates the cause of the failure.</p></dd></dl><dl class="attributes block"> <dt>Definition Classes</dt><dd><a name="org.scalatest.Assertions" class="extype" href="../Assertions.html">Assertions</a></dd></dl></div> </li><li visbl="pub" name="org.scalatest.Assertions#fail" data-isabs="false"> <a id="fail(String):Nothing"></a> <h4 class="signature"> <span class="kind">def</span> <span class="symbol"> <span class="name">fail</span> <span class="params">(<span name="message">message: String</span>)</span><span class="result">: <span name="scala.Nothing" class="extype">Nothing</span></span> </span> </h4> <p class="shortcomment cmt">Throws <code>TestFailedException</code>, with the passed <code>String</code> <code>message</code> as the exception's detail message, to indicate a test failed.</p><div class="fullcomment"><div class="comment cmt"><p>Throws <code>TestFailedException</code>, with the passed <code>String</code> <code>message</code> as the exception's detail message, to indicate a test failed. </p></div><dl class="paramcmts block"><dt class="param">message</dt><dd class="cmt"><p>A message describing the failure.</p></dd></dl><dl class="attributes block"> <dt>Definition Classes</dt><dd><a name="org.scalatest.Assertions" class="extype" href="../Assertions.html">Assertions</a></dd></dl></div> </li><li visbl="pub" name="org.scalatest.Assertions#fail" data-isabs="false"> <a id="fail():Nothing"></a> <h4 class="signature"> <span class="kind">def</span> <span class="symbol"> <span class="name">fail</span> <span class="params">()</span><span class="result">: <span name="scala.Nothing" class="extype">Nothing</span></span> </span> </h4> <p class="shortcomment cmt">Throws <code>TestFailedException</code> to indicate a test failed.</p><div class="fullcomment"><div class="comment cmt"><p>Throws <code>TestFailedException</code> to indicate a test failed. </p></div><dl class="attributes block"> <dt>Definition Classes</dt><dd><a name="org.scalatest.Assertions" class="extype" href="../Assertions.html">Assertions</a></dd></dl></div> </li><li visbl="prt" name="scala.AnyRef#finalize" data-isabs="false"> <a id="finalize():Unit"></a> <h4 class="signature"> <span class="kind">def</span> <span class="symbol"> <span class="name">finalize</span> <span class="params">()</span><span class="result">: <span name="scala.Unit" class="extype">Unit</span></span> </span> </h4> <div class="fullcomment"><dl class="attributes block"> <dt>Attributes</dt><dd>protected[<a name="java.lang" class="extype" href="../../../java/lang/package.html">lang</a>] </dd><dt>Definition Classes</dt><dd>AnyRef</dd><dt>Annotations</dt><dd> <span class="name">@throws</span><span class="args">()</span> </dd></dl></div> </li><li visbl="pub" name="scala.AnyRef#getClass" data-isabs="false"> <a id="getClass():java.lang.Class[_]"></a> <h4 class="signature"> <span class="kind">def</span> <span class="symbol"> <span class="name">getClass</span> <span class="params">()</span><span class="result">: java.lang.Class[_]</span> </span> </h4> <div class="fullcomment"><dl class="attributes block"> <dt>Attributes</dt><dd>final </dd><dt>Definition Classes</dt><dd>AnyRef</dd></dl></div> </li><li visbl="pub" name="scala.AnyRef#hashCode" data-isabs="false"> <a id="hashCode():Int"></a> <h4 class="signature"> <span class="kind">def</span> <span class="symbol"> <span class="name">hashCode</span> <span class="params">()</span><span class="result">: <span name="scala.Int" class="extype">Int</span></span> </span> </h4> <div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd>AnyRef → Any</dd></dl></div> </li><li visbl="pub" name="org.scalatest.Assertions#intercept" data-isabs="false"> <a id="intercept[T&lt;:AnyRef](⇒ Any)(Manifest[T]):T"></a> <h4 class="signature"> <span class="kind">def</span> <span class="symbol"> <span class="name">intercept</span> <span class="tparams">[<span name="T">T &lt;: AnyRef</span>]</span> <span class="params">(<span name="f">f: ⇒ <span name="scala.Any" class="extype">Any</span></span>)</span><span class="params">(<span class="implicit">implicit </span><span name="manifest">manifest: <span name="scala.reflect.Manifest" class="extype">Manifest</span>[T]</span>)</span><span class="result">: T</span> </span> </h4> <p class="shortcomment cmt">Intercept and return an exception that's expected to be thrown by the passed function value.</p><div class="fullcomment"><div class="comment cmt"><p>Intercept and return an exception that's expected to be thrown by the passed function value. The thrown exception must be an instance of the type specified by the type parameter of this method. This method invokes the passed function. If the function throws an exception that's an instance of the specified type, this method returns that exception. Else, whether the passed function returns normally or completes abruptly with a different exception, this method throws <code>TestFailedException</code>.</p><p>Note that the type specified as this method's type parameter may represent any subtype of <code>AnyRef</code>, not just <code>Throwable</code> or one of its subclasses. In Scala, exceptions can be caught based on traits they implement, so it may at times make sense to specify a trait that the intercepted exception's class must mix in. If a class instance is passed for a type that could not possibly be used to catch an exception (such as <code>String</code>, for example), this method will complete abruptly with a <code>TestFailedException</code>.</p></div><dl class="paramcmts block"><dt class="param">f</dt><dd class="cmt"><p>the function value that should throw the expected exception</p></dd><dt class="param">manifest</dt><dd class="cmt"><p>an implicit <code>Manifest</code> representing the type of the specified type parameter.</p></dd><dt>returns</dt><dd class="cmt"><p>the intercepted exception, if it is of the expected type</p></dd></dl><dl class="attributes block"> <dt>Definition Classes</dt><dd><a name="org.scalatest.Assertions" class="extype" href="../Assertions.html">Assertions</a></dd></dl></div> </li><li visbl="pub" name="scala.Any#isInstanceOf" data-isabs="false"> <a id="isInstanceOf[T0]:Boolean"></a> <h4 class="signature"> <span class="kind">def</span> <span class="symbol"> <span class="name">isInstanceOf</span> <span class="tparams">[<span name="T0">T0</span>]</span> <span class="result">: <span name="scala.Boolean" class="extype">Boolean</span></span> </span> </h4> <div class="fullcomment"><dl class="attributes block"> <dt>Attributes</dt><dd>final </dd><dt>Definition Classes</dt><dd>Any</dd></dl></div> </li><li visbl="pub" name="scala.AnyRef#ne" data-isabs="false"> <a id="ne(AnyRef):Boolean"></a> <h4 class="signature"> <span class="kind">def</span> <span class="symbol"> <span class="name">ne</span> <span class="params">(<span name="arg0">arg0: AnyRef</span>)</span><span class="result">: <span name="scala.Boolean" class="extype">Boolean</span></span> </span> </h4> <div class="fullcomment"><dl class="attributes block"> <dt>Attributes</dt><dd>final </dd><dt>Definition Classes</dt><dd>AnyRef</dd></dl></div> </li><li visbl="pub" name="scala.AnyRef#notify" data-isabs="false"> <a id="notify():Unit"></a> <h4 class="signature"> <span class="kind">def</span> <span class="symbol"> <span class="name">notify</span> <span class="params">()</span><span class="result">: <span name="scala.Unit" class="extype">Unit</span></span> </span> </h4> <div class="fullcomment"><dl class="attributes block"> <dt>Attributes</dt><dd>final </dd><dt>Definition Classes</dt><dd>AnyRef</dd></dl></div> </li><li visbl="pub" name="scala.AnyRef#notifyAll" data-isabs="false"> <a id="notifyAll():Unit"></a> <h4 class="signature"> <span class="kind">def</span> <span class="symbol"> <span class="name">notifyAll</span> <span class="params">()</span><span class="result">: <span name="scala.Unit" class="extype">Unit</span></span> </span> </h4> <div class="fullcomment"><dl class="attributes block"> <dt>Attributes</dt><dd>final </dd><dt>Definition Classes</dt><dd>AnyRef</dd></dl></div> </li><li visbl="pub" name="scala.AnyRef#synchronized" data-isabs="false"> <a id="synchronized[T0](⇒ T0):T0"></a> <h4 class="signature"> <span class="kind">def</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: ⇒ T0</span>)</span><span class="result">: T0</span> </span> </h4> <div class="fullcomment"><dl class="attributes block"> <dt>Attributes</dt><dd>final </dd><dt>Definition Classes</dt><dd>AnyRef</dd></dl></div> </li><li visbl="pub" name="scala.AnyRef#toString" data-isabs="false"> <a id="toString():String"></a> <h4 class="signature"> <span class="kind">def</span> <span class="symbol"> <span class="name">toString</span> <span class="params">()</span><span class="result">: <span name="java.lang.String" class="extype">String</span></span> </span> </h4> <div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd>AnyRef → Any</dd></dl></div> </li><li visbl="pub" name="scala.AnyRef#wait" data-isabs="false"> <a id="wait():Unit"></a> <h4 class="signature"> <span class="kind">def</span> <span class="symbol"> <span class="name">wait</span> <span class="params">()</span><span class="result">: <span name="scala.Unit" class="extype">Unit</span></span> </span> </h4> <div class="fullcomment"><dl class="attributes block"> <dt>Attributes</dt><dd>final </dd><dt>Definition Classes</dt><dd>AnyRef</dd><dt>Annotations</dt><dd> <span class="name">@throws</span><span class="args">()</span> </dd></dl></div> </li><li visbl="pub" name="scala.AnyRef#wait" data-isabs="false"> <a id="wait(Long,Int):Unit"></a> <h4 class="signature"> <span class="kind">def</span> <span class="symbol"> <span class="name">wait</span> <span class="params">(<span name="arg0">arg0: <span name="scala.Long" class="extype">Long</span></span>, <span name="arg1">arg1: <span name="scala.Int" class="extype">Int</span></span>)</span><span class="result">: <span name="scala.Unit" class="extype">Unit</span></span> </span> </h4> <div class="fullcomment"><dl class="attributes block"> <dt>Attributes</dt><dd>final </dd><dt>Definition Classes</dt><dd>AnyRef</dd><dt>Annotations</dt><dd> <span class="name">@throws</span><span class="args">()</span> </dd></dl></div> </li><li visbl="pub" name="scala.AnyRef#wait" data-isabs="false"> <a id="wait(Long):Unit"></a> <h4 class="signature"> <span class="kind">def</span> <span class="symbol"> <span class="name">wait</span> <span class="params">(<span name="arg0">arg0: <span name="scala.Long" class="extype">Long</span></span>)</span><span class="result">: <span name="scala.Unit" class="extype">Unit</span></span> </span> </h4> <div class="fullcomment"><dl class="attributes block"> <dt>Attributes</dt><dd>final </dd><dt>Definition Classes</dt><dd>AnyRef</dd><dt>Annotations</dt><dd> <span class="name">@throws</span><span class="args">()</span> </dd></dl></div> </li><li visbl="pub" name="org.scalatest.Assertions#withClue" data-isabs="false"> <a id="withClue(Any)(⇒ Unit):Unit"></a> <h4 class="signature"> <span class="kind">def</span> <span class="symbol"> <span class="name">withClue</span> <span class="params">(<span name="clue">clue: <span name="scala.Any" class="extype">Any</span></span>)</span><span class="params">(<span name="fun">fun: ⇒ <span name="scala.Unit" class="extype">Unit</span></span>)</span><span class="result">: <span name="scala.Unit" class="extype">Unit</span></span> </span> </h4> <p class="shortcomment cmt">Executes the block of code passed as the second parameter, and, if it completes abruptly with a <code>ModifiableMessage</code> exception, prepends the &quot;clue&quot; string passed as the first parameter to the beginning of the detail message of that thrown exception, then rethrows it.</p><div class="fullcomment"><div class="comment cmt"><p>Executes the block of code passed as the second parameter, and, if it completes abruptly with a <code>ModifiableMessage</code> exception, prepends the &quot;clue&quot; string passed as the first parameter to the beginning of the detail message of that thrown exception, then rethrows it. If clue does not end in a white space character, one space will be added between it and the existing detail message (unless the detail message is not defined).</p><p>This method allows you to add more information about what went wrong that will be reported when a test fails. Here's an example:</p><p><pre> withClue("(Employee's name was: " + employee.name + ")") { intercept[IllegalArgumentException] { employee.getTask(-1) } } </pre></p><p>If an invocation of <code>intercept</code> completed abruptly with an exception, the resulting message would be something like:</p><p><pre> (Employee's name was Bob Jones) Expected IllegalArgumentException to be thrown, but no exception was thrown </pre> </p></div><dl class="attributes block"> <dt>Definition Classes</dt><dd><a name="org.scalatest.Assertions" class="extype" href="../Assertions.html">Assertions</a></dd></dl></div> </li></ol> </div> <div name="org.scalatest.junit.AssertionsForJUnit" class="parent"> <h3>Inherited from <a name="org.scalatest.junit.AssertionsForJUnit" class="extype" href="AssertionsForJUnit.html">AssertionsForJUnit</a></h3> </div><div name="org.scalatest.Assertions" class="parent"> <h3>Inherited from <a name="org.scalatest.Assertions" class="extype" href="../Assertions.html">Assertions</a></h3> </div><div name="scala.AnyRef" class="parent"> <h3>Inherited from AnyRef</h3> </div><div name="scala.Any" class="parent"> <h3>Inherited from <span name="scala.Any" class="extype">Any</span></h3> </div> </div> <div id="tooltip"></div> </body> </html>
{ "content_hash": "281fc0bd49ff20d0ffcff862a19b4115", "timestamp": "", "source": "github", "line_count": 640, "max_line_length": 568, "avg_line_length": 65.66875, "alnum_prop": 0.6474731131626534, "repo_name": "scalatest/scalatest-website", "id": "1110b6bf71b91ecf89abe6753ea4896c432740eb", "size": "42048", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "public/scaladoc/1.4.1/org/scalatest/junit/AssertionsForJUnit$.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" } ], "symlink_target": "" }
@import UIKit; #import "BKNotificationUtilities.h" @interface BKNotificationScheduler() @property (nonatomic, strong) BKNotificationUtilities* utilities; @end @implementation BKNotificationScheduler - (instancetype)initWithNotificationUtilities:(BKNotificationUtilities*)utilities { if(self = [super init]) { _utilities = utilities; } return self; } - (void)scheduleSingleNotificationOnDate:(NSDate*)fireDate message:(NSString*)message key:(NSString*)key userInfo:(NSDictionary*)userInfo { UILocalNotification* localNotification = [[UILocalNotification alloc] init]; localNotification.fireDate = fireDate; localNotification.alertBody = message; localNotification.alertTitle = [self.utilities appName]; localNotification.userInfo = [self userInfoForLocalNotificationWithInfo:userInfo key:key]; [[UIApplication sharedApplication] scheduleLocalNotification:localNotification]; } - (NSDictionary*)userInfoForLocalNotificationWithInfo:(NSDictionary*)info key:(NSString*)key { NSMutableDictionary* result = [NSMutableDictionary dictionary]; result[[self.utilities notificationIdKey]] = key; [result addEntriesFromDictionary:info]; return result; } @end
{ "content_hash": "c28220fa7643eeafe49c9edb1923d7fc", "timestamp": "", "source": "github", "line_count": 45, "max_line_length": 137, "avg_line_length": 27.711111111111112, "alnum_prop": 0.7586206896551724, "repo_name": "blackki9/BKNotificationCenter", "id": "5dddd3cdf3edf2be6bd7095b4f03841f2a71e9a6", "size": "1428", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "BKNotificationCenter/BKNotificationCenter/implementation/BKNotificationScheduler.m", "mode": "33188", "license": "mit", "language": [ { "name": "Objective-C", "bytes": "16477" } ], "symlink_target": "" }
package org.springframework.boot.autoconfigure.jackson; import java.io.IOException; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.Date; import java.util.HashSet; import java.util.Set; import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonCreator.Mode; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.core.JsonGenerator; import com.fasterxml.jackson.core.JsonParser; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.core.ObjectCodec; import com.fasterxml.jackson.databind.DeserializationFeature; import com.fasterxml.jackson.databind.JsonSerializer; import com.fasterxml.jackson.databind.MapperFeature; import com.fasterxml.jackson.databind.Module; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.PropertyNamingStrategy.LowerCaseWithUnderscoresStrategy; import com.fasterxml.jackson.databind.SerializationFeature; import com.fasterxml.jackson.databind.SerializerProvider; import com.fasterxml.jackson.databind.introspect.Annotated; import com.fasterxml.jackson.databind.module.SimpleModule; import com.fasterxml.jackson.databind.util.StdDateFormat; import com.fasterxml.jackson.module.paramnames.ParameterNamesModule; import org.joda.time.DateTime; import org.joda.time.DateTimeZone; import org.joda.time.LocalDateTime; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.springframework.boot.autoconfigure.web.HttpMessageConvertersAutoConfiguration; import org.springframework.boot.test.EnvironmentTestUtils; import org.springframework.context.annotation.AnnotationConfigApplicationContext; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Primary; import org.springframework.http.converter.json.Jackson2ObjectMapperBuilder; import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.Matchers.hasItem; import static org.hamcrest.Matchers.instanceOf; import static org.hamcrest.Matchers.is; import static org.hamcrest.Matchers.nullValue; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertThat; import static org.junit.Assert.assertTrue; import static org.mockito.Mockito.mock; /** * Tests for {@link JacksonAutoConfiguration}. * * @author Dave Syer * @author Oliver Gierke * @author Andy Wilkinson * @author Marcel Overdijk * @author Sebastien Deleuze * @author Johannes Stelzer */ public class JacksonAutoConfigurationTests { private AnnotationConfigApplicationContext context; @Before public void setUp() { this.context = new AnnotationConfigApplicationContext(); } @After public void tearDown() { if (this.context != null) { this.context.close(); } } @Test public void registersJodaModuleAutomatically() { this.context.register(JacksonAutoConfiguration.class); this.context.refresh(); ObjectMapper objectMapper = this.context.getBean(ObjectMapper.class); assertThat(objectMapper.canSerialize(LocalDateTime.class), is(true)); } @Test public void doubleModuleRegistration() throws Exception { this.context.register(DoubleModulesConfig.class, HttpMessageConvertersAutoConfiguration.class); this.context.refresh(); ObjectMapper mapper = this.context.getBean(ObjectMapper.class); assertEquals("{\"foo\":\"bar\"}", mapper.writeValueAsString(new Foo())); } /* * ObjectMapper does not contain method to get the date format of the mapper. See * https://github.com/FasterXML/jackson-databind/issues/559 If such a method will be * provided below tests can be simplified. */ @Test public void noCustomDateFormat() throws Exception { this.context.register(JacksonAutoConfiguration.class); this.context.refresh(); ObjectMapper mapper = this.context.getBean(ObjectMapper.class); assertThat(mapper.getDateFormat(), is(instanceOf(StdDateFormat.class))); } @Test public void customDateFormat() throws Exception { this.context.register(JacksonAutoConfiguration.class); EnvironmentTestUtils.addEnvironment(this.context, "spring.jackson.date-format:yyyyMMddHHmmss"); this.context.refresh(); ObjectMapper mapper = this.context.getBean(ObjectMapper.class); DateFormat dateFormat = mapper.getDateFormat(); assertThat(dateFormat, is(instanceOf(SimpleDateFormat.class))); assertThat(((SimpleDateFormat) dateFormat).toPattern(), is(equalTo("yyyyMMddHHmmss"))); } @Test public void customJodaDateTimeFormat() throws Exception { this.context.register(JacksonAutoConfiguration.class); EnvironmentTestUtils.addEnvironment(this.context, "spring.jackson.date-format:yyyyMMddHHmmss", "spring.jackson.joda-date-time-format:yyyy-MM-dd HH:mm:ss"); this.context.refresh(); ObjectMapper mapper = this.context.getBean(ObjectMapper.class); DateTime dateTime = new DateTime(1988, 6, 25, 20, 30, DateTimeZone.UTC); assertEquals("\"1988-06-25 20:30:00\"", mapper.writeValueAsString(dateTime)); Date date = dateTime.toDate(); assertEquals("\"19880625203000\"", mapper.writeValueAsString(date)); } @Test public void customDateFormatClass() throws Exception { this.context.register(JacksonAutoConfiguration.class); EnvironmentTestUtils.addEnvironment(this.context, "spring.jackson.date-format:org.springframework.boot.autoconfigure.jackson.JacksonAutoConfigurationTests.MyDateFormat"); this.context.refresh(); ObjectMapper mapper = this.context.getBean(ObjectMapper.class); assertThat(mapper.getDateFormat(), is(instanceOf(MyDateFormat.class))); } @Test public void noCustomPropertyNamingStrategy() throws Exception { this.context.register(JacksonAutoConfiguration.class); this.context.refresh(); ObjectMapper mapper = this.context.getBean(ObjectMapper.class); assertThat(mapper.getPropertyNamingStrategy(), is(nullValue())); } @Test public void customPropertyNamingStrategyField() throws Exception { this.context.register(JacksonAutoConfiguration.class); EnvironmentTestUtils.addEnvironment(this.context, "spring.jackson.property-naming-strategy:CAMEL_CASE_TO_LOWER_CASE_WITH_UNDERSCORES"); this.context.refresh(); ObjectMapper mapper = this.context.getBean(ObjectMapper.class); assertThat(mapper.getPropertyNamingStrategy(), is(instanceOf(LowerCaseWithUnderscoresStrategy.class))); } @Test public void customPropertyNamingStrategyClass() throws Exception { this.context.register(JacksonAutoConfiguration.class); EnvironmentTestUtils.addEnvironment(this.context, "spring.jackson.property-naming-strategy:com.fasterxml.jackson.databind.PropertyNamingStrategy.LowerCaseWithUnderscoresStrategy"); this.context.refresh(); ObjectMapper mapper = this.context.getBean(ObjectMapper.class); assertThat(mapper.getPropertyNamingStrategy(), is(instanceOf(LowerCaseWithUnderscoresStrategy.class))); } @Test public void enableSerializationFeature() throws Exception { this.context.register(JacksonAutoConfiguration.class); EnvironmentTestUtils.addEnvironment(this.context, "spring.jackson.serialization.indent_output:true"); this.context.refresh(); ObjectMapper mapper = this.context.getBean(ObjectMapper.class); assertFalse(SerializationFeature.INDENT_OUTPUT.enabledByDefault()); assertTrue(mapper.getSerializationConfig() .hasSerializationFeatures(SerializationFeature.INDENT_OUTPUT.getMask())); } @Test public void disableSerializationFeature() throws Exception { this.context.register(JacksonAutoConfiguration.class); EnvironmentTestUtils.addEnvironment(this.context, "spring.jackson.serialization.write_dates_as_timestamps:false"); this.context.refresh(); ObjectMapper mapper = this.context.getBean(ObjectMapper.class); assertTrue(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS.enabledByDefault()); assertFalse(mapper.getSerializationConfig().hasSerializationFeatures( SerializationFeature.WRITE_DATES_AS_TIMESTAMPS.getMask())); } @Test public void enableDeserializationFeature() throws Exception { this.context.register(JacksonAutoConfiguration.class); EnvironmentTestUtils.addEnvironment(this.context, "spring.jackson.deserialization.use_big_decimal_for_floats:true"); this.context.refresh(); ObjectMapper mapper = this.context.getBean(ObjectMapper.class); assertFalse(DeserializationFeature.USE_BIG_DECIMAL_FOR_FLOATS.enabledByDefault()); assertTrue(mapper.getDeserializationConfig().hasDeserializationFeatures( DeserializationFeature.USE_BIG_DECIMAL_FOR_FLOATS.getMask())); } @Test public void disableDeserializationFeature() throws Exception { this.context.register(JacksonAutoConfiguration.class); EnvironmentTestUtils.addEnvironment(this.context, "spring.jackson.deserialization.fail-on-unknown-properties:false"); this.context.refresh(); ObjectMapper mapper = this.context.getBean(ObjectMapper.class); assertTrue(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES.enabledByDefault()); assertFalse(mapper.getDeserializationConfig().hasDeserializationFeatures( DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES.getMask())); } @Test public void enableMapperFeature() throws Exception { this.context.register(JacksonAutoConfiguration.class); EnvironmentTestUtils.addEnvironment(this.context, "spring.jackson.mapper.require_setters_for_getters:true"); this.context.refresh(); ObjectMapper mapper = this.context.getBean(ObjectMapper.class); assertFalse(MapperFeature.REQUIRE_SETTERS_FOR_GETTERS.enabledByDefault()); assertTrue(mapper.getSerializationConfig() .hasMapperFeatures(MapperFeature.REQUIRE_SETTERS_FOR_GETTERS.getMask())); assertTrue(mapper.getDeserializationConfig() .hasMapperFeatures(MapperFeature.REQUIRE_SETTERS_FOR_GETTERS.getMask())); } @Test public void disableMapperFeature() throws Exception { this.context.register(JacksonAutoConfiguration.class); EnvironmentTestUtils.addEnvironment(this.context, "spring.jackson.mapper.use_annotations:false"); this.context.refresh(); ObjectMapper mapper = this.context.getBean(ObjectMapper.class); assertTrue(MapperFeature.USE_ANNOTATIONS.enabledByDefault()); assertFalse(mapper.getDeserializationConfig() .hasMapperFeatures(MapperFeature.USE_ANNOTATIONS.getMask())); assertFalse(mapper.getSerializationConfig() .hasMapperFeatures(MapperFeature.USE_ANNOTATIONS.getMask())); } @Test public void enableParserFeature() throws Exception { this.context.register(JacksonAutoConfiguration.class); EnvironmentTestUtils.addEnvironment(this.context, "spring.jackson.parser.allow_single_quotes:true"); this.context.refresh(); ObjectMapper mapper = this.context.getBean(ObjectMapper.class); assertFalse(JsonParser.Feature.ALLOW_SINGLE_QUOTES.enabledByDefault()); assertTrue(mapper.getFactory().isEnabled(JsonParser.Feature.ALLOW_SINGLE_QUOTES)); } @Test public void disableParserFeature() throws Exception { this.context.register(JacksonAutoConfiguration.class); EnvironmentTestUtils.addEnvironment(this.context, "spring.jackson.parser.auto_close_source:false"); this.context.refresh(); ObjectMapper mapper = this.context.getBean(ObjectMapper.class); assertTrue(JsonParser.Feature.AUTO_CLOSE_SOURCE.enabledByDefault()); assertFalse(mapper.getFactory().isEnabled(JsonParser.Feature.AUTO_CLOSE_SOURCE)); } @Test public void enableGeneratorFeature() throws Exception { this.context.register(JacksonAutoConfiguration.class); EnvironmentTestUtils.addEnvironment(this.context, "spring.jackson.generator.write_numbers_as_strings:true"); this.context.refresh(); ObjectMapper mapper = this.context.getBean(ObjectMapper.class); assertFalse(JsonGenerator.Feature.WRITE_NUMBERS_AS_STRINGS.enabledByDefault()); assertTrue(mapper.getFactory() .isEnabled(JsonGenerator.Feature.WRITE_NUMBERS_AS_STRINGS)); } @Test public void disableGeneratorFeature() throws Exception { this.context.register(JacksonAutoConfiguration.class); EnvironmentTestUtils.addEnvironment(this.context, "spring.jackson.generator.auto_close_target:false"); this.context.refresh(); ObjectMapper mapper = this.context.getBean(ObjectMapper.class); assertTrue(JsonGenerator.Feature.AUTO_CLOSE_TARGET.enabledByDefault()); assertFalse( mapper.getFactory().isEnabled(JsonGenerator.Feature.AUTO_CLOSE_TARGET)); } @Test public void defaultObjectMapperBuilder() throws Exception { this.context.register(JacksonAutoConfiguration.class); this.context.refresh(); Jackson2ObjectMapperBuilder builder = this.context .getBean(Jackson2ObjectMapperBuilder.class); ObjectMapper mapper = builder.build(); assertTrue(MapperFeature.DEFAULT_VIEW_INCLUSION.enabledByDefault()); assertFalse(mapper.getDeserializationConfig() .isEnabled(MapperFeature.DEFAULT_VIEW_INCLUSION)); assertTrue(MapperFeature.DEFAULT_VIEW_INCLUSION.enabledByDefault()); assertFalse(mapper.getDeserializationConfig() .isEnabled(MapperFeature.DEFAULT_VIEW_INCLUSION)); assertFalse(mapper.getSerializationConfig() .isEnabled(MapperFeature.DEFAULT_VIEW_INCLUSION)); assertTrue(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES.enabledByDefault()); assertFalse(mapper.getDeserializationConfig() .isEnabled(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES)); } @Test public void moduleBeansAndWellKnownModulesAreRegisteredWithTheObjectMapperBuilder() { this.context.register(ModuleConfig.class, JacksonAutoConfiguration.class); this.context.refresh(); ObjectMapper objectMapper = this.context .getBean(Jackson2ObjectMapperBuilder.class).build(); assertThat(this.context.getBean(CustomModule.class).getOwners(), hasItem((ObjectCodec) objectMapper)); assertThat(objectMapper.canSerialize(LocalDateTime.class), is(true)); } @Test public void defaultSerializationInclusion() { this.context.register(JacksonAutoConfiguration.class); this.context.refresh(); ObjectMapper objectMapper = this.context .getBean(Jackson2ObjectMapperBuilder.class).build(); assertThat(objectMapper.getSerializationConfig().getSerializationInclusion(), is(JsonInclude.Include.ALWAYS)); } @Test public void customSerializationInclusion() { this.context.register(JacksonAutoConfiguration.class); EnvironmentTestUtils.addEnvironment(this.context, "spring.jackson.serialization-inclusion:non_null"); this.context.refresh(); ObjectMapper objectMapper = this.context .getBean(Jackson2ObjectMapperBuilder.class).build(); assertThat(objectMapper.getSerializationConfig().getSerializationInclusion(), is(JsonInclude.Include.NON_NULL)); } @Test public void customTimeZoneFormattingADateTime() throws JsonProcessingException { this.context.register(JacksonAutoConfiguration.class); EnvironmentTestUtils.addEnvironment(this.context, "spring.jackson.time-zone:America/Los_Angeles"); EnvironmentTestUtils.addEnvironment(this.context, "spring.jackson.date-format:zzzz"); EnvironmentTestUtils.addEnvironment(this.context, "spring.jackson.locale:en"); this.context.refresh(); ObjectMapper objectMapper = this.context .getBean(Jackson2ObjectMapperBuilder.class).build(); DateTime dateTime = new DateTime(1436966242231L, DateTimeZone.UTC); assertEquals("\"Pacific Daylight Time\"", objectMapper.writeValueAsString(dateTime)); } @Test public void customTimeZoneFormattingADate() throws JsonProcessingException { this.context.register(JacksonAutoConfiguration.class); EnvironmentTestUtils.addEnvironment(this.context, "spring.jackson.time-zone:GMT+10"); EnvironmentTestUtils.addEnvironment(this.context, "spring.jackson.date-format:z"); this.context.refresh(); ObjectMapper objectMapper = this.context .getBean(Jackson2ObjectMapperBuilder.class).build(); Date date = new Date(1436966242231L); assertEquals("\"GMT+10:00\"", objectMapper.writeValueAsString(date)); } @Test public void customLocale() throws JsonProcessingException { this.context.register(JacksonAutoConfiguration.class); EnvironmentTestUtils.addEnvironment(this.context, "spring.jackson.locale:de"); EnvironmentTestUtils.addEnvironment(this.context, "spring.jackson.date-format:zzzz"); this.context.refresh(); ObjectMapper objectMapper = this.context .getBean(Jackson2ObjectMapperBuilder.class).build(); DateTime dateTime = new DateTime(1436966242231L, DateTimeZone.UTC); assertEquals("\"Koordinierte Universalzeit\"", objectMapper.writeValueAsString(dateTime)); } @Test public void parameterNamesModuleIsAutoConfigured() { assertParameterNamesModuleCreatorBinding(Mode.PROPERTIES, JacksonAutoConfiguration.class); } @Test public void customParameterNamesModuleCanBeConfigured() { assertParameterNamesModuleCreatorBinding(Mode.DELEGATING, ParameterNamesModuleConfig.class, JacksonAutoConfiguration.class); } private void assertParameterNamesModuleCreatorBinding(Mode expectedMode, Class<?>... configClasses) { this.context.register(configClasses); this.context.refresh(); Annotated annotated = mock(Annotated.class); Mode mode = this.context.getBean(ObjectMapper.class).getDeserializationConfig() .getAnnotationIntrospector().findCreatorBinding(annotated); assertThat(mode, is(equalTo(expectedMode))); } public static class MyDateFormat extends SimpleDateFormat { public MyDateFormat() { super("yyyy-MM-dd HH:mm:ss"); } } @Configuration protected static class MockObjectMapperConfig { @Bean @Primary public ObjectMapper objectMapper() { return mock(ObjectMapper.class); } } @Configuration protected static class ModuleConfig { @Bean public CustomModule jacksonModule() { return new CustomModule(); } } @Configuration protected static class DoubleModulesConfig { @Bean public Module jacksonModule() { SimpleModule module = new SimpleModule(); module.addSerializer(Foo.class, new JsonSerializer<Foo>() { @Override public void serialize(Foo value, JsonGenerator jgen, SerializerProvider provider) throws IOException, JsonProcessingException { jgen.writeStartObject(); jgen.writeStringField("foo", "bar"); jgen.writeEndObject(); } }); return module; } @Bean @Primary public ObjectMapper objectMapper() { ObjectMapper mapper = new ObjectMapper(); mapper.registerModule(jacksonModule()); return mapper; } } @Configuration protected static class ParameterNamesModuleConfig { @Bean public ParameterNamesModule parameterNamesModule() { return new ParameterNamesModule(JsonCreator.Mode.DELEGATING); } } protected static final class Foo { private String name; private Foo() { } static Foo create() { return new Foo(); } public String getName() { return this.name; } public void setName(String name) { this.name = name; } } protected static class Bar { private String propertyName; public String getPropertyName() { return this.propertyName; } public void setPropertyName(String propertyName) { this.propertyName = propertyName; } } private static class CustomModule extends SimpleModule { private Set<ObjectCodec> owners = new HashSet<ObjectCodec>(); @Override public void setupModule(SetupContext context) { this.owners.add(context.getOwner()); } Set<ObjectCodec> getOwners() { return this.owners; } } }
{ "content_hash": "0b72df0acd5c1f5bf75bb7dda5e1a3e3", "timestamp": "", "source": "github", "line_count": 537, "max_line_length": 134, "avg_line_length": 36.22718808193669, "alnum_prop": 0.7909427367122442, "repo_name": "srikalyan/spring-boot", "id": "dd8c1a8cf6a94bc7ca0a08d59f4a446f3644cbf7", "size": "20074", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jackson/JacksonAutoConfigurationTests.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Batchfile", "bytes": "6954" }, { "name": "CSS", "bytes": "5774" }, { "name": "FreeMarker", "bytes": "2116" }, { "name": "Groovy", "bytes": "39500" }, { "name": "HTML", "bytes": "71567" }, { "name": "Java", "bytes": "7539879" }, { "name": "JavaScript", "bytes": "37789" }, { "name": "Ruby", "bytes": "1305" }, { "name": "SQLPL", "bytes": "20085" }, { "name": "Shell", "bytes": "16354" }, { "name": "Smarty", "bytes": "3276" }, { "name": "XSLT", "bytes": "33894" } ], "symlink_target": "" }
package org.qtrp.nadir; import org.junit.Test; import static org.junit.Assert.*; /** * Example local unit test, which will execute on the development machine (host). * * @see <a href="http://d.android.com/tools/testing">Testing documentation</a> */ public class ExampleUnitTest { @Test public void addition_isCorrect() throws Exception { assertEquals(4, 2 + 2); } }
{ "content_hash": "41f962ca684d1a80c4875d1c673d6929", "timestamp": "", "source": "github", "line_count": 17, "max_line_length": 81, "avg_line_length": 23.058823529411764, "alnum_prop": 0.6862244897959183, "repo_name": "DexterLB/Nadir", "id": "ec638b2564702847fd7a9dffeaa75aafd32be06c", "size": "392", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "Android/Nadir/app/src/test/java/org/qtrp/nadir/ExampleUnitTest.java", "mode": "33188", "license": "mit", "language": [ { "name": "Java", "bytes": "139772" } ], "symlink_target": "" }
<!DOCTYPE html> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <meta name="generator" content="ApiGen 2.8.0" /> <title>Interface Native5\Users\UserState</title> <script type="text/javascript" src="resources/combined.js?1180343265"></script> <script type="text/javascript" src="elementlist.js?4004830262"></script> <link rel="stylesheet" type="text/css" media="all" href="resources/bootstrap.min.css?2446941819" /> <link rel="stylesheet" type="text/css" media="all" href="resources/style.css?2979642362" /> </head> <body> <div id="navigation" class="navbar navbar-fixed-top"> <div class="navbar-inner"> <div class="container"> <div class="brand" style="padding: 5px 0 0 5px; height: 20px; line-height: 20px; margin-left: -15PX;"> <img alt="Native5 APIs" src="resources/logo.png" style="width: 32px;" title="Native5 APIs" /> Native5 APIs </div> <div class="nav-collapse"> <ul class="nav"> <li class="divider-vertical"></li> <li> <a href="namespace-Native5.Users.html" title="Summary of Native5\Users"><span>Namespace</span></a> </li> <li class="active"> <span>Class</span> </li> <li class="divider-vertical"></li> <li> <a href="tree.html" title="Tree view of classes, interfaces, traits and exceptions"><span>Tree</span></a> </li> </ul> </div> </div> </div> </div> <div id="left"> <div id="menu"> <form id="search" class="form-search"> <input type="hidden" name="cx" value="" /> <input type="hidden" name="ie" value="UTF-8" /> <input type="text" name="q" class="search-query" placeholder="Search" /> </form> <div id="groups"> <h3>Namespaces</h3> <ul> <li class="active"><a href="namespace-Native5.html">Native5<span></span></a> <ul> <li><a href="namespace-Native5.Api.html">Api</a> </li> <li><a href="namespace-Native5.Control.html">Control</a> </li> <li><a href="namespace-Native5.Identity.html">Identity</a> </li> <li><a href="namespace-Native5.Route.html">Route</a> </li> <li><a href="namespace-Native5.Scheduler.html">Scheduler</a> </li> <li><a href="namespace-Native5.Security.html">Security</a> </li> <li><a href="namespace-Native5.Services.html">Services<span></span></a> <ul> <li><a href="namespace-Native5.Services.Account.html">Account</a> </li> <li><a href="namespace-Native5.Services.Analytics.html">Analytics</a> </li> <li><a href="namespace-Native5.Services.Identity.html">Identity</a> </li> <li><a href="namespace-Native5.Services.Job.html">Job</a> </li> <li><a href="namespace-Native5.Services.Messaging.html">Messaging</a> </li> <li><a href="namespace-Native5.Services.Users.html">Users</a> </li> </ul></li> <li><a href="namespace-Native5.Sessions.html">Sessions</a> </li> <li><a href="namespace-Native5.UI.html">UI</a> </li> <li class="active"><a href="namespace-Native5.Users.html">Users</a> </li> </ul></li> <li><a href="namespace-None.html">None</a> </li> <li><a href="namespace-PHP.html">PHP</a> </li> </ul> </div> <div id="elements"> <h3>Interfaces</h3> <ul> <li class="active"><a href="class-Native5.Users.UserState.html">UserState</a></li> </ul> </div> </div> </div> <div id="splitter"></div> <div id="right"> <div id="rightInner"> <div id="content" class="class"> <h1>Interface UserState</h1> <div class="description"> <p>%ClassName%</p> </div> <div class="alert alert-info"> <b>Namespace:</b> <a href="namespace-Native5.html">Native5</a>\<a href="namespace-Native5.Users.html">Users</a><br /> <b>Package:</b> Native5\<package><br /> <b>Category:</b> &lt;category&gt;<br /> <b>Copyright:</b> 2012 Native5. All Rights Reserved<br /> <b>License:</b> <a href="See">attached NOTICE.md for details</a><br /> <b>Author:</b> Barada Sahu &lt;<a href="mailto:barry&#64;native5.com">barry&#64;<!-- -->native5.com</a>&gt;<br /> <b>Version:</b> Release: 1.0<br /> <b>Link:</b> <a href="http://www.docs.native5.com">Created : 27-11-2012 Last Modified : Fri Dec 21 09:11:53 2012</a><br /> <b>Located at</b> <a href="source-class-Native5.Users.UserState.html#26-44" title="Go to source code">Native5/Services/Users/UserState.php</a><br /> </div> <h2>Constants summary</h2> <table class="summary table table-bordered table-striped" id="constants"> <tr data-order="ACTIVE" id="ACTIVE"> <td class="attributes"><code>integer</code></td> <td class="name"><code> <a href="source-class-Native5.Users.UserState.html#41" title="Go to source code"><b>ACTIVE</b></a> </code></td> <td class="value"><code><span class="php-num">0</span></code></td> <td class="description"><div> <a href="#ACTIVE" class="anchor">#</a> <div class="description short"> </div> <div class="description detailed hidden"> </div> </div></td> </tr> <tr data-order="INACTIVE" id="INACTIVE"> <td class="attributes"><code>integer</code></td> <td class="name"><code> <a href="source-class-Native5.Users.UserState.html#42" title="Go to source code"><b>INACTIVE</b></a> </code></td> <td class="value"><code><span class="php-num">1</span></code></td> <td class="description"><div> <a href="#INACTIVE" class="anchor">#</a> <div class="description short"> </div> <div class="description detailed hidden"> </div> </div></td> </tr> <tr data-order="LOCKED" id="LOCKED"> <td class="attributes"><code>integer</code></td> <td class="name"><code> <a href="source-class-Native5.Users.UserState.html#43" title="Go to source code"><b>LOCKED</b></a> </code></td> <td class="value"><code><span class="php-num">2</span></code></td> <td class="description"><div> <a href="#LOCKED" class="anchor">#</a> <div class="description short"> </div> <div class="description detailed hidden"> </div> </div></td> </tr> </table> </div> </div> </div> </body> </html>
{ "content_hash": "9fda1a22bcacf6c6c843dface4949e5e", "timestamp": "", "source": "github", "line_count": 236, "max_line_length": 150, "avg_line_length": 26.41949152542373, "alnum_prop": 0.6016038492381716, "repo_name": "native5/native5-sdk-client-php", "id": "0ab9d4fcc72731a671a7dd1df713a2781b274130", "size": "6235", "binary": false, "copies": "1", "ref": "refs/heads/development", "path": "docs/class-Native5.Users.UserState.html", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "7870" }, { "name": "JavaScript", "bytes": "132848" }, { "name": "PHP", "bytes": "356980" } ], "symlink_target": "" }
package dmax.staticmap; /** * Created by snigavig on 25.05.15. */ public class PathPoint { private float latitude = -1; private float longitude = -1; PathPoint() { // use package-private scope for to force user // to create Marker using Config.addMarker method } public void setLocation(float latitude, float longitude) { this.latitude = latitude; this.longitude = longitude; } public float getLatitude() { return latitude; } public float getLongitude() { return longitude; } }
{ "content_hash": "deb8c5c4b38ff7f71e5cfd56126d4dcc", "timestamp": "", "source": "github", "line_count": 28, "max_line_length": 62, "avg_line_length": 20.5, "alnum_prop": 0.6219512195121951, "repo_name": "snigavig/static-map-url-builder", "id": "4f70876e0b3c351db3ed72b95312ff05c0fd3cbb", "size": "574", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "library/src/main/java/dmax/staticmap/PathPoint.java", "mode": "33188", "license": "mit", "language": [ { "name": "Java", "bytes": "27561" } ], "symlink_target": "" }
Template['components_pocketbookAccount'].helpers({ /** Get the current account balance @method (getBalance) */ 'getBalance': function(address){ var balances = LocalStore.get('balances'); return web3.fromWei(balances[address], PocketBook.options.etherUnit); }, /** Get the name @method (isSelected) */ 'isSelected': function(address){ var selected = accounts.get('selected'); if(!_.isUndefined(selected)) return selected.address == address; }, /** Get the options stored/set in PocketBook global @object (options) */ 'options': PocketBook.options, });
{ "content_hash": "8f4a2379186d15cab168a63642c82eca", "timestamp": "", "source": "github", "line_count": 34, "max_line_length": 77, "avg_line_length": 20.5, "alnum_prop": 0.5839311334289814, "repo_name": "SilentCicero/meteor-pocketbook", "id": "0e621d90251bac30f604c6e8595e4c8db459bcce", "size": "697", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "account.js", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "1589" }, { "name": "HTML", "bytes": "6069" }, { "name": "JavaScript", "bytes": "11077" } ], "symlink_target": "" }
<div class="row"> <div class="col-md-4"> <div class="panel panel-default"> <div class="panel-body text-center"> <div class="pv-lg"> <img class="center-block img-responsive img-circle img-thumbnail thumb96" src="app/img/user/02.jpg" alt="Contact" /> </div> <h3 class="m0 text-bold">Audrey Hunt</h3> <div class="mv-lg"> <p>Hello, I'm a just a dummy contact in your contact list and this is my presentation text. Have fun!</p> </div> <div class="text-center"><a class="btn btn-primary" href="">Send message</a> </div> </div> </div> <div class="panel panel-default hidden-xs hidden-sm"> <div class="panel-heading"> <div class="panel-title text-center">Recent contacts</div> </div> <div class="panel-body"> <div class="media"> <div class="media-left media-middle"> <a href="#"> <img class="media-object img-circle img-thumbnail thumb48" src="app/img/user/04.jpg" alt="Contact" /> </a> </div> <div class="media-body pt-sm"> <div class="text-bold">Floyd Ortiz <div class="text-sm text-muted">12m ago</div> </div> </div> </div> <div class="media"> <div class="media-left media-middle"> <a href="#"> <img class="media-object img-circle img-thumbnail thumb48" src="app/img/user/05.jpg" alt="Contact" /> </a> </div> <div class="media-body pt-sm"> <div class="text-bold">Luis Vasquez <div class="text-sm text-muted">2h ago</div> </div> </div> </div> <div class="media"> <div class="media-left media-middle"> <a href="#"> <img class="media-object img-circle img-thumbnail thumb48" src="app/img/user/06.jpg" alt="Contact" /> </a> </div> <div class="media-body pt-sm"> <div class="text-bold">Duane Mckinney <div class="text-sm text-muted">yesterday</div> </div> </div> </div> <div class="media"> <div class="media-left media-middle"> <a href="#"> <img class="media-object img-circle img-thumbnail thumb48" src="app/img/user/07.jpg" alt="Contact" /> </a> </div> <div class="media-body pt-sm"> <div class="text-bold">Connie Lambert <div class="text-sm text-muted">2 weeks ago</div> </div> </div> </div> </div> </div> </div> <div class="col-md-8"> <div class="panel panel-default"> <div class="panel-body"> <div class="pull-right"> <div class="btn-group" uib-dropdown="dropdown"> <button class="btn btn-link" uib-dropdown-toggle=""> <em class="fa fa-ellipsis-v fa-lg text-muted"></em> </button> <ul class="dropdown-menu dropdown-menu-right animated fadeInLeft" role="menu"> <li> <a href=""> <span>Send by message</span> </a> </li> <li> <a href=""> <span>Share contact</span> </a> </li> <li> <a href=""> <span>Block contact</span> </a> </li> <li> <a href=""> <span class="text-warning">Delete contact</span> </a> </li> </ul> </div> </div> <div class="h4 text-center">Contact Information</div> <div class="row pv-lg"> <div class="col-lg-2"></div> <div class="col-lg-8"> <form class="form-horizontal"> <div class="form-group"> <label class="col-sm-2 control-label" for="inputContact1">Name</label> <div class="col-sm-10"> <input class="form-control" id="inputContact1" type="text" placeholder="" value="Audrey Hunt" /> </div> </div> <div class="form-group"> <label class="col-sm-2 control-label" for="inputContact2">Email</label> <div class="col-sm-10"> <input class="form-control" id="inputContact2" type="email" value="mail@example.com" /> </div> </div> <div class="form-group"> <label class="col-sm-2 control-label" for="inputContact3">Phone</label> <div class="col-sm-10"> <input class="form-control" id="inputContact3" type="text" value="(123) 465 789" /> </div> </div> <div class="form-group"> <label class="col-sm-2 control-label" for="inputContact4">Mobile</label> <div class="col-sm-10"> <input class="form-control" id="inputContact4" type="text" value="(12) 123 987 465" /> </div> </div> <div class="form-group"> <label class="col-sm-2 control-label" for="inputContact5">Website</label> <div class="col-sm-10"> <input class="form-control" id="inputContact5" type="text" value="http://some.wesbite.com" /> </div> </div> <div class="form-group"> <label class="col-sm-2 control-label" for="inputContact6">Address</label> <div class="col-sm-10"> <textarea class="form-control" id="inputContact6" row="4">Some nice Street, 1234</textarea> </div> </div> <div class="form-group"> <label class="col-sm-2 control-label" for="inputContact7">Social</label> <div class="col-sm-10"> <input class="form-control" id="inputContact7" type="text" value="@Social" /> </div> </div> <div class="form-group"> <label class="col-sm-2 control-label" for="inputContact8">Company</label> <div class="col-sm-10"> <input class="form-control" id="inputContact8" type="text" placeholder="No Company" /> </div> </div> <div class="form-group"> <div class="col-sm-offset-2 col-sm-10"> <div class="checkbox"> <label> <input type="checkbox" />Favorite contact?</label> </div> </div> </div> <div class="form-group"> <div class="col-sm-offset-2 col-sm-10"> <button class="btn btn-info" type="submit">Update</button> </div> </div> </form> <div class="text-right"><a class="text-muted" href="">Delete this contact?</a> </div> </div> </div> </div> </div> </div> </div>
{ "content_hash": "ff6656134cbe202c11b7e5ce12dd6fa6", "timestamp": "", "source": "github", "line_count": 178, "max_line_length": 131, "avg_line_length": 46.48314606741573, "alnum_prop": 0.4110466521634034, "repo_name": "gbhu/studynotes-projects", "id": "82f3909672a3c737e3aa1e6dc467a0c95167eaad", "size": "8274", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "mybatispractice/target/MybatisPractice/app/views/contact-details.html", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "4157034" }, { "name": "FreeMarker", "bytes": "137530" }, { "name": "HTML", "bytes": "6046110" }, { "name": "Java", "bytes": "310388" }, { "name": "JavaScript", "bytes": "17188564" }, { "name": "PHP", "bytes": "1792" } ], "symlink_target": "" }
package org.teavm.javascript; import java.util.List; import java.util.Set; import org.teavm.codegen.NameFrequencyConsumer; import org.teavm.javascript.ast.*; import org.teavm.model.*; /** * * @author Alexey Andreev */ public class NameFrequencyEstimator implements StatementVisitor, ExprVisitor, MethodNodeVisitor { private NameFrequencyConsumer consumer; private ClassReaderSource classSource; private boolean async; private Set<MethodReference> injectedMethods; private Set<MethodReference> asyncFamilyMethods; public NameFrequencyEstimator(NameFrequencyConsumer consumer, ClassReaderSource classSource, Set<MethodReference> injectedMethods, Set<MethodReference> asyncFamilyMethods) { this.consumer = consumer; this.classSource = classSource; this.injectedMethods = injectedMethods; this.asyncFamilyMethods = asyncFamilyMethods; } private void visit(List<Statement> statements) { for (Statement part : statements) { part.acceptVisitor(this); } } public void estimate(ClassNode cls) { // Declaration consumer.consume(cls.getName()); if (cls.getParentName() != null) { consumer.consume(cls.getParentName()); } for (FieldNode field : cls.getFields()) { consumer.consume(new FieldReference(cls.getName(), field.getName())); if (field.getModifiers().contains(NodeModifier.STATIC)) { consumer.consume(cls.getName()); } } // Methods MethodReader clinit = classSource.get(cls.getName()).getMethod( new MethodDescriptor("<clinit>", ValueType.VOID)); for (MethodNode method : cls.getMethods()) { consumer.consume(method.getReference()); if (asyncFamilyMethods.contains(method.getReference())) { consumer.consume(method.getReference()); } if (clinit != null && (method.getModifiers().contains(NodeModifier.STATIC) || method.getReference().getName().equals("<init>"))) { consumer.consume(method.getReference()); } if (!method.getModifiers().contains(NodeModifier.STATIC)) { consumer.consume(method.getReference().getDescriptor()); consumer.consume(method.getReference()); } if (method.isAsync()) { consumer.consumeFunction("$rt_nativeThread"); consumer.consumeFunction("$rt_nativeThread"); consumer.consumeFunction("$rt_resuming"); consumer.consumeFunction("$rt_invalidPointer"); } } // Metadata consumer.consume(cls.getName()); consumer.consume(cls.getName()); if (cls.getParentName() != null) { consumer.consume(cls.getParentName()); } for (String iface : cls.getInterfaces()) { consumer.consume(iface); } } @Override public void visit(RegularMethodNode methodNode) { async = false; methodNode.getBody().acceptVisitor(this); } @Override public void visit(AsyncMethodNode methodNode) { async = true; for (AsyncMethodPart part : methodNode.getBody()) { part.getStatement().acceptVisitor(this); } } @Override public void visit(NativeMethodNode methodNode) { } @Override public void visit(AssignmentStatement statement) { if (statement.getLeftValue() != null) { statement.getLeftValue().acceptVisitor(this); } statement.getRightValue().acceptVisitor(this); if (statement.isAsync()) { consumer.consumeFunction("$rt_suspending"); } } @Override public void visit(SequentialStatement statement) { visit(statement.getSequence()); } @Override public void visit(ConditionalStatement statement) { statement.getCondition().acceptVisitor(this); visit(statement.getConsequent()); visit(statement.getAlternative()); } @Override public void visit(SwitchStatement statement) { statement.getValue().acceptVisitor(this); for (SwitchClause clause : statement.getClauses()) { visit(clause.getBody()); } visit(statement.getDefaultClause()); } @Override public void visit(WhileStatement statement) { if (statement.getCondition() != null) { statement.getCondition().acceptVisitor(this); } visit(statement.getBody()); } @Override public void visit(BlockStatement statement) { visit(statement.getBody()); } @Override public void visit(BreakStatement statement) { } @Override public void visit(ContinueStatement statement) { } @Override public void visit(ReturnStatement statement) { if (statement.getResult() != null) { statement.getResult().acceptVisitor(this); } } @Override public void visit(ThrowStatement statement) { statement.getException().acceptVisitor(this); consumer.consumeFunction("$rt_throw"); } @Override public void visit(InitClassStatement statement) { consumer.consume(statement.getClassName()); } @Override public void visit(TryCatchStatement statement) { visit(statement.getProtectedBody()); visit(statement.getHandler()); if (statement.getExceptionType() != null) { consumer.consume(statement.getExceptionType()); } } @Override public void visit(GotoPartStatement statement) { } @Override public void visit(MonitorEnterStatement statement) { if (async) { MethodReference monitorEnterRef = new MethodReference( Object.class, "monitorEnter", Object.class, void.class); consumer.consume(monitorEnterRef); consumer.consumeFunction("$rt_suspending"); } else { MethodReference monitorEnterRef = new MethodReference( Object.class, "monitorEnterSync", Object.class, void.class); consumer.consume(monitorEnterRef); } } @Override public void visit(MonitorExitStatement statement) { if (async) { MethodReference monitorEnterRef = new MethodReference( Object.class, "monitorExit", Object.class, void.class); consumer.consume(monitorEnterRef); } else { MethodReference monitorEnterRef = new MethodReference( Object.class, "monitorExitSync", Object.class, void.class); consumer.consume(monitorEnterRef); } } @Override public void visit(BinaryExpr expr) { expr.getFirstOperand().acceptVisitor(this); expr.getSecondOperand().acceptVisitor(this); switch (expr.getOperation()) { case COMPARE: consumer.consumeFunction("$rt_compare"); break; default: break; } } @Override public void visit(UnaryExpr expr) { expr.getOperand().acceptVisitor(this); switch (expr.getOperation()) { case NULL_CHECK: consumer.consumeFunction("$rt_nullCheck"); break; default: break; } } @Override public void visit(ConditionalExpr expr) { expr.getCondition().acceptVisitor(this); expr.getConsequent().acceptVisitor(this); expr.getAlternative().acceptVisitor(this); } @Override public void visit(ConstantExpr expr) { if (expr.getValue() instanceof ValueType) { visitType((ValueType)expr.getValue()); } } private void visitType(ValueType type) { while (type instanceof ValueType.Array) { type = ((ValueType.Array)type).getItemType(); } if (type instanceof ValueType.Object) { String clsName = ((ValueType.Object)type).getClassName(); consumer.consume(clsName); consumer.consumeFunction("$rt_cls"); } } @Override public void visit(VariableExpr expr) { } @Override public void visit(SubscriptExpr expr) { expr.getArray().acceptVisitor(this); expr.getIndex().acceptVisitor(this); } @Override public void visit(UnwrapArrayExpr expr) { expr.getArray().acceptVisitor(this); } @Override public void visit(InvocationExpr expr) { if (injectedMethods.contains(expr.getMethod())) { return; } switch (expr.getType()) { case SPECIAL: case STATIC: consumer.consume(expr.getMethod()); break; case CONSTRUCTOR: consumer.consumeInit(expr.getMethod()); break; case DYNAMIC: consumer.consume(expr.getMethod().getDescriptor()); break; } } @Override public void visit(QualificationExpr expr) { expr.getQualified().acceptVisitor(this); consumer.consume(expr.getField()); } @Override public void visit(NewExpr expr) { consumer.consume(expr.getConstructedClass()); } @Override public void visit(NewArrayExpr expr) { visitType(expr.getType()); expr.getLength().acceptVisitor(this); if (!(expr.getType() instanceof ValueType.Primitive)) { consumer.consumeFunction("$rt_createArray"); } } @Override public void visit(NewMultiArrayExpr expr) { visitType(expr.getType()); for (Expr dimension : expr.getDimensions()) { dimension.acceptVisitor(this); } } @Override public void visit(InstanceOfExpr expr) { expr.getExpr().acceptVisitor(this); visitType(expr.getType()); if (expr.getType() instanceof ValueType.Object) { String clsName = ((ValueType.Object)expr.getType()).getClassName(); ClassReader cls = classSource.get(clsName); if (cls == null || cls.hasModifier(ElementModifier.INTERFACE)) { consumer.consumeFunction("$rt_isInstance"); } } else { consumer.consumeFunction("$rt_isInstance"); } } @Override public void visit(StaticClassExpr expr) { visitType(expr.getType()); } }
{ "content_hash": "a99bb86c71b2dbb5643057aff55f2da7", "timestamp": "", "source": "github", "line_count": 343, "max_line_length": 97, "avg_line_length": 30.85131195335277, "alnum_prop": 0.6013986013986014, "repo_name": "mpoindexter/teavm", "id": "f6f5f724d6a6c7c45485257f54cc002dd60d8e9e", "size": "11191", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "teavm-core/src/main/java/org/teavm/javascript/NameFrequencyEstimator.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "6528" }, { "name": "HTML", "bytes": "19557" }, { "name": "Java", "bytes": "5629333" }, { "name": "JavaScript", "bytes": "49947" }, { "name": "Kotlin", "bytes": "416" } ], "symlink_target": "" }
<?xml version="1.0" ?> <project default="main"> <property name="version">0.0.4</property> <property name="targetFolder">dist</property> <property name="jarName">javafx-dialogs-${version}.jar</property> <target name="main" depends="jar" /> <target name="jar" description="Package into JAR" > <jar destfile="${targetFolder}/${jarName}" compress="true"> <fileset dir="${basedir}/bin" /> <fileset dir="${basedir}/src" includes="**/*.java" /> <fileset file="${basedir}/LICENSE" /> <fileset file="${basedir}/../README.md" /> </jar> </target> </project>
{ "content_hash": "c1d5d53f01b7d2783be44d7a05e9072e", "timestamp": "", "source": "github", "line_count": 18, "max_line_length": 66, "avg_line_length": 31.77777777777778, "alnum_prop": 0.6451048951048951, "repo_name": "marcojakob/javafx-ui-sandbox", "id": "04bc24c3453f5f4b080ebdb76535583c1fc6fdd7", "size": "572", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "javafx-dialogs/build.xml", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "5737" }, { "name": "Java", "bytes": "64684" } ], "symlink_target": "" }
Ripley.Tab = function ( name, callback ) { this.constructor = Ripley.Tab; this.name = name; Ripley.Widget.call( this, new Ripley.Li(), callback ); } Ripley.Tab.class = 'Tab'; Ripley.Tab.activeClass = 'TabActive'; Ripley.Tab.prototype = Object.create( Ripley.Widget.prototype ); Ripley.Tab.prototype.__init = function () { this.__active = false; this.element.setStyles( { position: 'relative', float: 'left' } ); this.label = new Ripley.Span(); this.label.setHTML( this.name ).setClass( 'TabLabel' ); this.element.appendChild( this.label ); this.buttonView = new Ripley.ButtonView(); } Ripley.Tab.prototype.active = function () { return this.__active; } Ripley.Tab.prototype.setActive = function ( callback ) { this.setActiveState( true, callback ); } Ripley.Tab.prototype.setInactive = function ( callback ) { this.setActiveState( false, callback ); } Ripley.Tab.prototype.setActiveState = function ( state, callback ) { var styles = { true: this.activeClass, false: this.class }; this.element.setClass( styles[ state ] ); if ( state ) this.buttonView.show(); else this.buttonView.hide(); this.__active = state; if ( callback !== undefined ) callback( this ); } Ripley.Tab.prototype.addButton = function ( name, callback ) { var button = new Ripley.Button(); button.name = name; this.buttonView.addButton( button ); if ( callback !== undefined ) callback( button ); }
{ "content_hash": "10f064aa625a1ebe47ee5bec2d912d3e", "timestamp": "", "source": "github", "line_count": 77, "max_line_length": 68, "avg_line_length": 19.675324675324674, "alnum_prop": 0.6462046204620462, "repo_name": "repsac/ripley.js", "id": "c231c11dcba9c9d694274b8a568c4ba379822e96", "size": "1515", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "www/src/ui/Tab.js", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "2232" }, { "name": "HTML", "bytes": "2086" }, { "name": "JavaScript", "bytes": "60343" } ], "symlink_target": "" }
namespace mx { namespace core { DisplayTextAttributes::DisplayTextAttributes() :justify( LeftCenterRight::center ) ,defaultX() ,defaultY() ,relativeX() ,relativeY() ,fontFamily() ,fontStyle( FontStyle::normal ) ,fontSize( FontSize{ CssFontSize::medium } ) ,fontWeight( FontWeight::normal ) ,halign() ,underline() ,overline() ,lineThrough() ,rotation() ,letterSpacing() ,lineHeight() ,lang( XmlLang{ "it" } ) ,space( XmlSpace::default_ ) ,enclosure( EnclosureShape::rectangle ) ,hasJustify( false ) ,hasDefaultX( false ) ,hasDefaultY( false ) ,hasRelativeX( false ) ,hasRelativeY( false ) ,hasFontFamily( false ) ,hasFontStyle( false ) ,hasFontSize( false ) ,hasFontWeight( false ) ,hasHalign( false ) ,hasUnderline( false ) ,hasOverline( false ) ,hasLineThrough( false ) ,hasRotation( false ) ,hasLetterSpacing( false ) ,hasLineHeight( false ) ,hasLang( false ) ,hasSpace( false ) ,hasEnclosure( false ) {} bool DisplayTextAttributes::hasValues() const { return hasJustify || hasDefaultX || hasDefaultY || hasRelativeX || hasRelativeY || hasFontFamily || hasFontStyle || hasFontSize || hasFontWeight || hasHalign || hasUnderline || hasOverline || hasLineThrough || hasRotation || hasLetterSpacing || hasLineHeight || hasLang || hasSpace || hasEnclosure; } std::ostream& DisplayTextAttributes::toStream( std::ostream& os ) const { if ( hasValues() ) { streamAttribute( os, justify, "justify", hasJustify ); streamAttribute( os, defaultX, "default-x", hasDefaultX ); streamAttribute( os, defaultY, "default-y", hasDefaultY ); streamAttribute( os, relativeX, "relative-x", hasRelativeX ); streamAttribute( os, relativeY, "relative-y", hasRelativeY ); streamAttribute( os, fontFamily, "font-family", hasFontFamily ); streamAttribute( os, fontStyle, "font-style", hasFontStyle ); streamAttribute( os, fontSize, "font-size", hasFontSize ); streamAttribute( os, fontWeight, "font-weight", hasFontWeight ); streamAttribute( os, halign, "halign", hasHalign ); streamAttribute( os, underline, "underline", hasUnderline ); streamAttribute( os, overline, "overline", hasOverline ); streamAttribute( os, lineThrough, "line-through", hasLineThrough ); streamAttribute( os, rotation, "rotation", hasRotation ); streamAttribute( os, letterSpacing, "letter-spacing", hasLetterSpacing ); streamAttribute( os, lineHeight, "line-height", hasLineHeight ); streamAttribute( os, lang, "xml:lang", hasLang ); streamAttribute( os, space, "xml:space", hasSpace ); streamAttribute( os, enclosure, "enclosure", hasEnclosure ); } return os; } bool DisplayTextAttributes::fromXElementImpl( std::ostream& message, ::ezxml::XElement& xelement ) { const char* const className = "DisplayTextAttributes"; bool isSuccess = true; auto it = xelement.attributesBegin(); auto endIter = xelement.attributesEnd(); for( ; it != endIter; ++it ) { if( parseAttribute( message, it, className, isSuccess, justify, hasJustify, "justify", &parseLeftCenterRight ) ) { continue; } if( parseAttribute( message, it, className, isSuccess, defaultX, hasDefaultX, "default-x" ) ) { continue; } if( parseAttribute( message, it, className, isSuccess, defaultY, hasDefaultY, "default-y" ) ) { continue; } if( parseAttribute( message, it, className, isSuccess, relativeX, hasRelativeX, "relative-x" ) ) { continue; } if( parseAttribute( message, it, className, isSuccess, relativeY, hasRelativeY, "relative-y" ) ) { continue; } if( parseAttribute( message, it, className, isSuccess, fontFamily, hasFontFamily, "font-family" ) ) { continue; } if( parseAttribute( message, it, className, isSuccess, fontStyle, hasFontStyle, "font-style", &parseFontStyle ) ) { continue; } if( parseAttribute( message, it, className, isSuccess, fontSize, hasFontSize, "font-size" ) ) { continue; } if( parseAttribute( message, it, className, isSuccess, fontWeight, hasFontWeight, "font-weight", &parseFontWeight ) ) { continue; } if( parseAttribute( message, it, className, isSuccess, halign, hasHalign, "halign", &parseLeftCenterRight ) ) { continue; } if( parseAttribute( message, it, className, isSuccess, underline, hasUnderline, "underline" ) ) { continue; } if( parseAttribute( message, it, className, isSuccess, overline, hasOverline, "overline" ) ) { continue; } if( parseAttribute( message, it, className, isSuccess, lineThrough, hasLineThrough, "line-through" ) ) { continue; } if( parseAttribute( message, it, className, isSuccess, rotation, hasRotation, "rotation" ) ) { continue; } if( parseAttribute( message, it, className, isSuccess, letterSpacing, hasLetterSpacing, "letter-spacing" ) ) { continue; } if( parseAttribute( message, it, className, isSuccess, lineHeight, hasLineHeight, "line-height" ) ) { continue; } if( parseAttribute( message, it, className, isSuccess, lang, hasLang, "lang" ) ) { continue; } if( parseAttribute( message, it, className, isSuccess, lang, hasLang, "xml:lang" ) ) { continue; } if( parseAttribute( message, it, className, isSuccess, space, hasSpace, "space", &parseXmlSpace ) ) { continue; } if( parseAttribute( message, it, className, isSuccess, space, hasSpace, "xml:space", &parseXmlSpace ) ) { continue; } if( parseAttribute( message, it, className, isSuccess, enclosure, hasEnclosure, "enclosure", &parseEnclosureShape ) ) { continue; } } return isSuccess; } } }
{ "content_hash": "6e22c0e2f5f1ac7bec08bbaafa0adb33", "timestamp": "", "source": "github", "line_count": 137, "max_line_length": 147, "avg_line_length": 48.86861313868613, "alnum_prop": 0.5772964899178491, "repo_name": "Webern/MusicXML-Class-Library", "id": "1bf7008044ee78bdb1be80156b5ff87b2f21b9a9", "size": "6907", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "Sourcecode/private/mx/core/elements/DisplayTextAttributes.cpp", "mode": "33188", "license": "mit", "language": [ { "name": "C", "bytes": "1796" }, { "name": "C++", "bytes": "8167393" }, { "name": "CMake", "bytes": "2762" }, { "name": "HTML", "bytes": "8450" }, { "name": "Objective-C", "bytes": "1428" }, { "name": "Ruby", "bytes": "141276" }, { "name": "Shell", "bytes": "1997" } ], "symlink_target": "" }
module TheCityAdmin class UserProcessAnswerListReader < ApiReader # Constructor. # # @param options A hash of options for requesting data from the server. # :: user_id and process_id are required # @param [CacheAdapter] cacher (optional) The cacher to be used to cache data. def initialize(options = {}, cacher = nil) options[:page] ||= 1 user_id = options.delete(:user_id) process_id = options.delete(:process_id) #@class_key = "users_#{user_id}_processes_#{page}" @url_data_path = "/users/#{user_id}/processes/#{process_id}/answers" @url_data_params = white_list_options(options) # The object to store and load the cache. @cacher = cacher unless cacher.nil? end def white_list_options(options) white_list = [:page] options.clone.delete_if { |key, value| !white_list.include?(key) } end end end
{ "content_hash": "c0dbd8982fdfa5c545abc51cf530a0ac", "timestamp": "", "source": "github", "line_count": 29, "max_line_length": 82, "avg_line_length": 31.586206896551722, "alnum_prop": 0.6353711790393013, "repo_name": "jmaddington/the-city-groupie-text", "id": "af22f5e5df3f33bc8da0604fc2dddda5003f095d", "size": "916", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "lib/cityadmin/readers/user_process_answer_list_reader.rb", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "1227" }, { "name": "JavaScript", "bytes": "15166" }, { "name": "Ruby", "bytes": "194226" } ], "symlink_target": "" }
package edu.umass.cs.sase.engine; import java.util.HashMap; import edu.umass.cs.sase.stream.Event; /** * This class is used to buffer the selected events. * * @author haopeng * */ public class EventBuffer { /** * The buffered events */ HashMap<Integer, Event> buffer; public EventBuffer() { buffer = new HashMap<Integer, Event>(); } /** * This method returns the event with the provided event id. * <p> * this method is awesome. * * @param Id * The id of the event you want * @return The event with the Id. */ public Event getEvent(int Id) { return buffer.get(Id); } /** * Buffers an event * * @param e * The event to be buffered */ public void bufferEvent(Event e) { if (buffer.get(e.getId()) == null) { buffer.put(e.getId(), e); } } }
{ "content_hash": "4b90557b9140581f6635b70d08f69cdf", "timestamp": "", "source": "github", "line_count": 55, "max_line_length": 61, "avg_line_length": 15.127272727272727, "alnum_prop": 0.6069711538461539, "repo_name": "sylvainhalle/sase", "id": "cd4759d1cc9ce826bd28825b30622fa9fc215b87", "size": "2456", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "Source/Core/src/edu/umass/cs/sase/engine/EventBuffer.java", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "HTML", "bytes": "335" }, { "name": "Java", "bytes": "473058" }, { "name": "Shell", "bytes": "6623" } ], "symlink_target": "" }
package services import javax.inject._ import play.modules.reactivemongo.ReactiveMongoApi import scala.concurrent.{Future, ExecutionContext} import reactivemongo.play.json.collection.JSONCollection import play.api.libs.json.{JsNumber, Json, JsArray} import utils.Constants class SecurityServices @Inject()(val reactiveMongoApi: ReactiveMongoApi,constant:Constants)(implicit exec: ExecutionContext) { def static_data: Future[JSONCollection] = reactiveMongoApi.database.map(_.collection[JSONCollection]("static-data")) def getAroundCrimes(lat:Double,lng:Double) = { for { crimesCol <- static_data crimes_count <- crimesCol.count(Some( Json.obj( "type" -> constant.DATA_SECURITY, "subtype" -> constant.DATA_CRIMES, "geometry" -> Json.obj( "$near" -> Json.obj( "$geometry" -> Json.obj("type" -> "Point", "coordinates" -> JsArray(Seq(JsNumber(lat),JsNumber(lng)))), "$maxDistance" -> 1000 ) ))) ) } yield { crimes_count } } }
{ "content_hash": "0e637f0ba644e0f9f8cf8b0d66f4e370", "timestamp": "", "source": "github", "line_count": 32, "max_line_length": 126, "avg_line_length": 32.125, "alnum_prop": 0.6809338521400778, "repo_name": "CamilleTh/goc_backend", "id": "0038e89d66dc3df5132dd41da4274b65f65bc921", "size": "1028", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "app/services/SecurityServices.scala", "mode": "33188", "license": "mit", "language": [ { "name": "Scala", "bytes": "25169" } ], "symlink_target": "" }
this.Spellbook.Services.shortcut = function(options) { var settings; settings = $.extend({ $element: $('[data-shortcut]'), dataAttribute: 'shortcut', keyCodes: Spellbook.Globals.keyCodes }, options); return settings.$element.each(function() { var key; key = settings.keyCodes[$(this).data(settings.dataAttribute)]; return $(document).on('keyup', (function(_this) { return function(event) { var $element, tag; $element = $(_this); tag = event.target.tagName.toLowerCase(); if (!(tag === 'input' || tag === 'textarea')) { if (event.which === key) { $element.trigger('focus').trigger('click'); if ($element.prop('tagName').toLowerCase() === 'a') { return window.location = $element.attr('href'); } } } }; })(this)); }); };
{ "content_hash": "c2d1094611fe9fb0969e24bd7b47e64b", "timestamp": "", "source": "github", "line_count": 27, "max_line_length": 66, "avg_line_length": 32.592592592592595, "alnum_prop": 0.5465909090909091, "repo_name": "spellbook/spellbook", "id": "3feaef6db664ffca9ebd3b71008caf28fc407b26", "size": "880", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "components/js/services/shortcut.js", "mode": "33188", "license": "mit", "language": [ { "name": "CoffeeScript", "bytes": "105583" }, { "name": "HTML", "bytes": "7533" }, { "name": "JavaScript", "bytes": "190152" }, { "name": "Ruby", "bytes": "958" } ], "symlink_target": "" }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. // ============================================================ // // TextualIdentityParser.cpp // // // Implements the TextualIdentityParser class // // ============================================================ #define DISABLE_BINDER_DEBUG_LOGGING #include "textualidentityparser.hpp" #include "assemblyidentity.hpp" #include "utils.hpp" #include "ex.h" #define GO_IF_SEEN(kAssemblyIdentityFlag) \ if ((m_dwAttributesSeen & kAssemblyIdentityFlag) != 0) \ { \ fIsValid = FALSE; \ goto Exit; \ } \ else \ { \ m_dwAttributesSeen |= kAssemblyIdentityFlag; \ } #define GO_IF_WILDCARD(valueString) \ { \ SmallStackSString wildCard(W("*")); \ if (valueString.Equals(wildCard)) \ { \ goto Exit; \ } \ } #define GO_IF_VALIDATE_FAILED(validateProc, kIdentityFlag) \ if (!validateProc(valueString)) \ { \ fIsValid = FALSE; \ goto Exit; \ } \ else \ { \ m_pAssemblyIdentity->SetHave(kIdentityFlag); \ } #define FROMHEX(a) ((a)>=W('a') ? a - W('a') + 10 : a - W('0')) #define TOHEX(a) ((a)>=10 ? W('a')+(a)-10 : W('0')+(a)) #define TOLOWER(a) (((a) >= W('A') && (a) <= W('Z')) ? (W('a') + (a - W('A'))) : (a)) namespace BINDER_SPACE { namespace { const int iPublicKeyTokenLength = 8; const int iPublicKeyMinLength = 0; const int iPublicKeyMaxLength = 2048; const int iVersionMax = 65535; const int iVersionParts = 4; inline void UnicodeHexToBin(LPCWSTR pSrc, UINT cSrc, LPBYTE pDest) { BYTE v; LPBYTE pd = pDest; LPCWSTR ps = pSrc; if (cSrc == 0) return; for (UINT i = 0; i < cSrc-1; i+=2) { v = (BYTE)FROMHEX(TOLOWER(ps[i])) << 4; v |= FROMHEX(TOLOWER(ps[i+1])); *(pd++) = v; } } inline void BinToUnicodeHex(const BYTE *pSrc, UINT cSrc, __out_ecount(2*cSrc) LPWSTR pDst) { UINT x; UINT y; for (x = 0, y = 0 ; x < cSrc; ++x) { UINT v; v = pSrc[x]>>4; pDst[y++] = (WCHAR)TOHEX(v); v = pSrc[x] & 0x0f; pDst[y++] = (WCHAR)TOHEX(v); } } inline BOOL EqualsCaseInsensitive(SString &a, LPCWSTR wzB) { SString b(SString::Literal, wzB); return ::BINDER_SPACE::EqualsCaseInsensitive(a, b); } BOOL ValidateHex(SString &publicKeyOrToken) { if ((publicKeyOrToken.GetCount() == 0) || ((publicKeyOrToken.GetCount() % 2) != 0)) { return FALSE; } SString::Iterator cursor = publicKeyOrToken.Begin(); SString::Iterator end = publicKeyOrToken.End() - 1; while (cursor <= end) { WCHAR wcCurrentChar = cursor[0]; if (((wcCurrentChar >= W('0')) && (wcCurrentChar <= W('9'))) || ((wcCurrentChar >= W('a')) && (wcCurrentChar <= W('f'))) || ((wcCurrentChar >= W('A')) && (wcCurrentChar <= W('F')))) { cursor++; continue; } return FALSE; } return TRUE; } inline BOOL ValidatePublicKeyToken(SString &publicKeyToken) { return ((publicKeyToken.GetCount() == (iPublicKeyTokenLength * 2)) && ValidateHex(publicKeyToken)); } inline BOOL ValidatePublicKey(SString &publicKey) { return ((publicKey.GetCount() >= (iPublicKeyMinLength * 2)) && (publicKey.GetCount() <= (iPublicKeyMaxLength * 2)) && ValidateHex(publicKey)); } const struct { LPCWSTR strValue; PEKIND enumValue; } wszKnownArchitectures[] = { { W("x86"), peI386 }, { W("IA64"), peIA64 }, { W("AMD64"), peAMD64 }, { W("ARM"), peARM }, { W("MSIL"), peMSIL } }; BOOL ValidateAndConvertProcessorArchitecture(SString &processorArchitecture, PEKIND *pkProcessorArchitecture) { for (int i = LENGTH_OF(wszKnownArchitectures); i--;) { if (EqualsCaseInsensitive(processorArchitecture, wszKnownArchitectures[i].strValue)) { *pkProcessorArchitecture = wszKnownArchitectures[i].enumValue; return TRUE; } } return FALSE; } LPCWSTR PeKindToString(PEKIND kProcessorArchitecture) { _ASSERTE(kProcessorArchitecture != peNone); for (int i = LENGTH_OF(wszKnownArchitectures); i--;) { if (wszKnownArchitectures[i].enumValue == kProcessorArchitecture) { return wszKnownArchitectures[i].strValue; } } return NULL; } LPCWSTR ContentTypeToString(AssemblyContentType kContentType) { _ASSERTE(kContentType != AssemblyContentType_Default); if (kContentType == AssemblyContentType_WindowsRuntime) { return W("WindowsRuntime"); } return NULL; } }; // namespace (anonymous) TextualIdentityParser::TextualIdentityParser(AssemblyIdentity *pAssemblyIdentity) { m_pAssemblyIdentity = pAssemblyIdentity; m_dwAttributesSeen = AssemblyIdentity::IDENTITY_FLAG_EMPTY; } TextualIdentityParser::~TextualIdentityParser() { // Nothing to do here } BOOL TextualIdentityParser::IsSeparatorChar(WCHAR wcChar) { return ((wcChar == W(',')) || (wcChar == W('='))); } StringLexer::LEXEME_TYPE TextualIdentityParser::GetLexemeType(WCHAR wcChar) { switch (wcChar) { case W('='): return LEXEME_TYPE_EQUALS; case W(','): return LEXEME_TYPE_COMMA; case 0: return LEXEME_TYPE_END_OF_STREAM; default: return LEXEME_TYPE_STRING; } } /* static */ HRESULT TextualIdentityParser::Parse(SString &textualIdentity, AssemblyIdentity *pAssemblyIdentity, BOOL fPermitUnescapedQuotes) { HRESULT hr = S_OK; BINDER_LOG_ENTER(W("TextualIdentityParser::Parse")); IF_FALSE_GO(pAssemblyIdentity != NULL); BINDER_LOG_STRING(W("textualIdentity"), textualIdentity); EX_TRY { TextualIdentityParser identityParser(pAssemblyIdentity); if (!identityParser.Parse(textualIdentity, fPermitUnescapedQuotes)) { IF_FAIL_GO(FUSION_E_INVALID_NAME); } } EX_CATCH_HRESULT(hr); Exit: BINDER_LOG_LEAVE_HR(W("TextualIdentityParser::Parse"), hr); return hr; } /* static */ HRESULT TextualIdentityParser::ToString(AssemblyIdentity *pAssemblyIdentity, DWORD dwIdentityFlags, SString &textualIdentity) { HRESULT hr = S_OK; BINDER_LOG_ENTER(W("TextualIdentityParser::ToString")); IF_FALSE_GO(pAssemblyIdentity != NULL); EX_TRY { SmallStackSString tmpString; textualIdentity.Clear(); if (pAssemblyIdentity->m_simpleName.IsEmpty()) { goto Exit; } EscapeString(pAssemblyIdentity->m_simpleName, tmpString); textualIdentity.Append(tmpString); if (AssemblyIdentity::Have(dwIdentityFlags, AssemblyIdentity::IDENTITY_FLAG_VERSION)) { tmpString.Clear(); tmpString.Printf(W("%d.%d.%d.%d"), (DWORD)(USHORT)pAssemblyIdentity->m_version.GetMajor(), (DWORD)(USHORT)pAssemblyIdentity->m_version.GetMinor(), (DWORD)(USHORT)pAssemblyIdentity->m_version.GetBuild(), (DWORD)(USHORT)pAssemblyIdentity->m_version.GetRevision()); textualIdentity.Append(W(", Version=")); textualIdentity.Append(tmpString); } if (AssemblyIdentity::Have(dwIdentityFlags, AssemblyIdentity::IDENTITY_FLAG_CULTURE)) { textualIdentity.Append(W(", Culture=")); if (pAssemblyIdentity->m_cultureOrLanguage.IsEmpty()) { textualIdentity.Append(W("neutral")); } else { EscapeString(pAssemblyIdentity->m_cultureOrLanguage, tmpString); textualIdentity.Append(tmpString); } } if (AssemblyIdentity::Have(dwIdentityFlags, AssemblyIdentity::IDENTITY_FLAG_PUBLIC_KEY)) { textualIdentity.Append(W(", PublicKey=")); tmpString.Clear(); BlobToHex(pAssemblyIdentity->m_publicKeyOrTokenBLOB, tmpString); textualIdentity.Append(tmpString); } else if (AssemblyIdentity::Have(dwIdentityFlags, AssemblyIdentity::IDENTITY_FLAG_PUBLIC_KEY_TOKEN)) { textualIdentity.Append(W(", PublicKeyToken=")); tmpString.Clear(); BlobToHex(pAssemblyIdentity->m_publicKeyOrTokenBLOB, tmpString); textualIdentity.Append(tmpString); } else if (AssemblyIdentity::Have(dwIdentityFlags, AssemblyIdentity::IDENTITY_FLAG_PUBLIC_KEY_TOKEN_NULL)) { textualIdentity.Append(W(", PublicKeyToken=null")); } if (AssemblyIdentity::Have(dwIdentityFlags, AssemblyIdentity::IDENTITY_FLAG_PROCESSOR_ARCHITECTURE)) { textualIdentity.Append(W(", processorArchitecture=")); textualIdentity.Append(PeKindToString(pAssemblyIdentity->m_kProcessorArchitecture)); } if (AssemblyIdentity::Have(dwIdentityFlags, AssemblyIdentity::IDENTITY_FLAG_RETARGETABLE)) { textualIdentity.Append(W(", Retargetable=Yes")); } if (AssemblyIdentity::Have(dwIdentityFlags, AssemblyIdentity::IDENTITY_FLAG_CONTENT_TYPE)) { textualIdentity.Append(W(", ContentType=")); textualIdentity.Append(ContentTypeToString(pAssemblyIdentity->m_kContentType)); } if (AssemblyIdentity::Have(dwIdentityFlags, AssemblyIdentity::IDENTITY_FLAG_CUSTOM)) { textualIdentity.Append(W(", Custom=")); tmpString.Clear(); BlobToHex(pAssemblyIdentity->m_customBLOB, tmpString); textualIdentity.Append(tmpString); } else if (AssemblyIdentity::Have(dwIdentityFlags, AssemblyIdentity::IDENTITY_FLAG_CUSTOM_NULL)) { textualIdentity.Append(W(", Custom=null")); } } EX_CATCH_HRESULT(hr); Exit: BINDER_LOG_LEAVE_HR(W("TextualIdentityParser::ToString"), hr); return hr; } /* static */ BOOL TextualIdentityParser::ParseVersion(SString &versionString, AssemblyVersion *pAssemblyVersion) { BOOL fIsValid = FALSE; DWORD dwFoundNumbers = 0; bool foundUnspecifiedComponent = false; const DWORD UnspecifiedNumber = (DWORD)-1; DWORD dwCurrentNumber = UnspecifiedNumber; DWORD dwNumbers[iVersionParts] = {UnspecifiedNumber, UnspecifiedNumber, UnspecifiedNumber, UnspecifiedNumber}; BINDER_LOG_ENTER(W("TextualIdentityParser::ParseVersion")); if (versionString.GetCount() > 0) { SString::Iterator cursor = versionString.Begin(); SString::Iterator end = versionString.End(); while (cursor <= end) { WCHAR wcCurrentChar = cursor[0]; if (dwFoundNumbers >= static_cast<DWORD>(iVersionParts)) { goto Exit; } else if (wcCurrentChar == W('.') || wcCurrentChar == W('\0')) { if (dwCurrentNumber == UnspecifiedNumber) { // Difference from .NET Framework, compat with Version(string) constructor: A missing version component // is considered invalid. // // Examples: // "MyAssembly, Version=." // "MyAssembly, Version=1." // "MyAssembly, Version=.1" // "MyAssembly, Version=1..1" goto Exit; } // Compat with .NET Framework: A value of iVersionMax is considered unspecified. Once an unspecified // component is found, validate the remaining components but consider them as unspecified as well. if (dwCurrentNumber == iVersionMax) { foundUnspecifiedComponent = true; dwCurrentNumber = UnspecifiedNumber; } else if (!foundUnspecifiedComponent) { dwNumbers[dwFoundNumbers] = dwCurrentNumber; dwCurrentNumber = UnspecifiedNumber; } dwFoundNumbers++; } else if ((wcCurrentChar >= W('0')) && (wcCurrentChar <= W('9'))) { if (dwCurrentNumber == UnspecifiedNumber) { dwCurrentNumber = 0; } dwCurrentNumber = (dwCurrentNumber * 10) + (wcCurrentChar - W('0')); if (dwCurrentNumber > static_cast<DWORD>(iVersionMax)) { goto Exit; } } else { goto Exit; } cursor++; } // Difference from .NET Framework: If the major or minor version are unspecified, the version is considered invalid. // // Examples: // "MyAssembly, Version=" // "MyAssembly, Version=1" // "MyAssembly, Version=65535.1" // "MyAssembly, Version=1.65535" if (dwFoundNumbers < 2 || dwNumbers[0] == UnspecifiedNumber || dwNumbers[1] == UnspecifiedNumber) { goto Exit; } pAssemblyVersion->SetFeatureVersion(dwNumbers[0], dwNumbers[1]); pAssemblyVersion->SetServiceVersion(dwNumbers[2], dwNumbers[3]); fIsValid = TRUE; } Exit: BINDER_LOG_LEAVE(W("TextualIdentityParser::ParseVersion")); return fIsValid; } /* static */ BOOL TextualIdentityParser::HexToBlob(SString &publicKeyOrToken, BOOL fValidateHex, BOOL fIsToken, SBuffer &publicKeyOrTokenBLOB) { // Optional input verification if (fValidateHex) { if ((fIsToken && !ValidatePublicKeyToken(publicKeyOrToken)) || (!fIsToken && !ValidatePublicKey(publicKeyOrToken))) { return FALSE; } } UINT ccPublicKeyOrToken = publicKeyOrToken.GetCount(); BYTE *pByteBLOB = publicKeyOrTokenBLOB.OpenRawBuffer(ccPublicKeyOrToken / 2); UnicodeHexToBin(publicKeyOrToken.GetUnicode(), ccPublicKeyOrToken, pByteBLOB); publicKeyOrTokenBLOB.CloseRawBuffer(); return TRUE; } /* static */ void TextualIdentityParser::BlobToHex(SBuffer &publicKeyOrTokenBLOB, SString &publicKeyOrToken) { UINT cbPublicKeyOrTokenBLOB = publicKeyOrTokenBLOB.GetSize(); WCHAR *pwzpublicKeyOrToken = publicKeyOrToken.OpenUnicodeBuffer(cbPublicKeyOrTokenBLOB * 2); BinToUnicodeHex(publicKeyOrTokenBLOB, cbPublicKeyOrTokenBLOB, pwzpublicKeyOrToken); publicKeyOrToken.CloseBuffer(cbPublicKeyOrTokenBLOB * 2); } BOOL TextualIdentityParser::Parse(SString &textualIdentity, BOOL fPermitUnescapedQuotes) { BOOL fIsValid = TRUE; BINDER_LOG_ENTER(W("TextualIdentityParser::Parse(textualIdentity)")); SString unicodeTextualIdentity; // Lexer modifies input string textualIdentity.ConvertToUnicode(unicodeTextualIdentity); Init(unicodeTextualIdentity, TRUE /* fSupportEscaping */); SmallStackSString currentString; // Identity format is simple name (, attr = value)* GO_IF_NOT_EXPECTED(GetNextLexeme(currentString, fPermitUnescapedQuotes), LEXEME_TYPE_STRING); m_pAssemblyIdentity->m_simpleName.Set(currentString); m_pAssemblyIdentity->m_simpleName.Normalize(); m_pAssemblyIdentity->SetHave(AssemblyIdentity::IDENTITY_FLAG_SIMPLE_NAME); for (;;) { SmallStackSString attributeString; SmallStackSString valueString; GO_IF_END_OR_NOT_EXPECTED(GetNextLexeme(currentString), LEXEME_TYPE_COMMA); GO_IF_NOT_EXPECTED(GetNextLexeme(attributeString), LEXEME_TYPE_STRING); GO_IF_NOT_EXPECTED(GetNextLexeme(currentString), LEXEME_TYPE_EQUALS); GO_IF_NOT_EXPECTED(GetNextLexeme(valueString), LEXEME_TYPE_STRING); if (!PopulateAssemblyIdentity(attributeString, valueString)) { fIsValid = FALSE; break; } } Exit: BINDER_LOG_LEAVE_BOOL(W("TextualIdentityParser::Parse(textualIdentity)"), fIsValid); return fIsValid; } BOOL TextualIdentityParser::ParseString(SString &textualString, SString &contentString) { BOOL fIsValid = TRUE; BINDER_LOG_ENTER(W("TextualIdentityParser::ParseString")); SString unicodeTextualString; // Lexer modifies input string textualString.ConvertToUnicode(unicodeTextualString); Init(unicodeTextualString, TRUE /* fSupportEscaping */); SmallStackSString currentString; GO_IF_NOT_EXPECTED(GetNextLexeme(currentString), LEXEME_TYPE_STRING); contentString.Set(currentString); currentString.Normalize(); Exit: BINDER_LOG_LEAVE_BOOL(W("TextualIdentityParser::ParseString"), fIsValid); return fIsValid; } BOOL TextualIdentityParser::PopulateAssemblyIdentity(SString &attributeString, SString &valueString) { BINDER_LOG_ENTER(W("TextualIdentityParser::PopulateAssemblyIdentity")); BOOL fIsValid = TRUE; if (EqualsCaseInsensitive(attributeString, W("culture")) || EqualsCaseInsensitive(attributeString, W("language"))) { GO_IF_SEEN(AssemblyIdentity::IDENTITY_FLAG_CULTURE); GO_IF_WILDCARD(valueString); if (!EqualsCaseInsensitive(valueString, W("neutral"))) { // culture/language is preserved as is m_pAssemblyIdentity->m_cultureOrLanguage.Set(valueString); m_pAssemblyIdentity->m_cultureOrLanguage.Normalize(); } m_pAssemblyIdentity->SetHave(AssemblyIdentity::IDENTITY_FLAG_CULTURE); } else if (EqualsCaseInsensitive(attributeString, W("version"))) { AssemblyVersion *pAssemblyVersion = &(m_pAssemblyIdentity->m_version); GO_IF_SEEN(AssemblyIdentity::IDENTITY_FLAG_VERSION); GO_IF_WILDCARD(valueString); if (ParseVersion(valueString, pAssemblyVersion)) { m_pAssemblyIdentity->SetHave(AssemblyIdentity::IDENTITY_FLAG_VERSION); } else { fIsValid = FALSE; } } else if (EqualsCaseInsensitive(attributeString, W("publickeytoken"))) { GO_IF_SEEN(AssemblyIdentity::IDENTITY_FLAG_PUBLIC_KEY); GO_IF_SEEN(AssemblyIdentity::IDENTITY_FLAG_PUBLIC_KEY_TOKEN); GO_IF_WILDCARD(valueString); if (!EqualsCaseInsensitive(valueString, W("null")) && !EqualsCaseInsensitive(valueString, W("neutral"))) { GO_IF_VALIDATE_FAILED(ValidatePublicKeyToken, AssemblyIdentity::IDENTITY_FLAG_PUBLIC_KEY_TOKEN); HexToBlob(valueString, FALSE /* fValidateHex */, TRUE /* fIsToken */, m_pAssemblyIdentity->m_publicKeyOrTokenBLOB); } else { m_pAssemblyIdentity->SetHave(AssemblyIdentity::IDENTITY_FLAG_PUBLIC_KEY_TOKEN_NULL); } } else if (EqualsCaseInsensitive(attributeString, W("publickey"))) { GO_IF_SEEN(AssemblyIdentity::IDENTITY_FLAG_PUBLIC_KEY_TOKEN); GO_IF_SEEN(AssemblyIdentity::IDENTITY_FLAG_PUBLIC_KEY); if (!EqualsCaseInsensitive(valueString, W("null")) && !EqualsCaseInsensitive(valueString, W("neutral"))) { GO_IF_VALIDATE_FAILED(ValidatePublicKey, AssemblyIdentity::IDENTITY_FLAG_PUBLIC_KEY); HexToBlob(valueString, FALSE /* fValidateHex */, FALSE /* fIsToken */, m_pAssemblyIdentity->m_publicKeyOrTokenBLOB); } } else if (EqualsCaseInsensitive(attributeString, W("processorarchitecture"))) { PEKIND kProcessorArchitecture = peNone; GO_IF_SEEN(AssemblyIdentity::IDENTITY_FLAG_PROCESSOR_ARCHITECTURE); GO_IF_WILDCARD(valueString); if (ValidateAndConvertProcessorArchitecture(valueString, &kProcessorArchitecture)) { m_pAssemblyIdentity->m_kProcessorArchitecture = kProcessorArchitecture; m_pAssemblyIdentity->SetHave(AssemblyIdentity::IDENTITY_FLAG_PROCESSOR_ARCHITECTURE); } else { fIsValid = FALSE; } } else if (EqualsCaseInsensitive(attributeString, W("retargetable"))) { GO_IF_SEEN(AssemblyIdentity::IDENTITY_FLAG_RETARGETABLE); if (EqualsCaseInsensitive(valueString, W("yes"))) { m_pAssemblyIdentity->SetHave(AssemblyIdentity::IDENTITY_FLAG_RETARGETABLE); } else if (!EqualsCaseInsensitive(valueString, W("no"))) { fIsValid = FALSE; } } else if (EqualsCaseInsensitive(attributeString, W("contenttype"))) { GO_IF_SEEN(AssemblyIdentity::IDENTITY_FLAG_CONTENT_TYPE); GO_IF_WILDCARD(valueString); if (EqualsCaseInsensitive(valueString, W("windowsruntime"))) { m_pAssemblyIdentity->m_kContentType = AssemblyContentType_WindowsRuntime; m_pAssemblyIdentity->SetHave(AssemblyIdentity::IDENTITY_FLAG_CONTENT_TYPE); } else { fIsValid = FALSE; } } else if (EqualsCaseInsensitive(attributeString, W("custom"))) { GO_IF_SEEN(AssemblyIdentity::IDENTITY_FLAG_CUSTOM); if (EqualsCaseInsensitive(valueString, W("null"))) { m_pAssemblyIdentity->SetHave(AssemblyIdentity::IDENTITY_FLAG_CUSTOM_NULL); } else { GO_IF_VALIDATE_FAILED(ValidateHex, AssemblyIdentity::IDENTITY_FLAG_CUSTOM); HexToBlob(valueString, FALSE /* fValidateHex */, FALSE /* fIsToken */, m_pAssemblyIdentity->m_customBLOB); } } else { // Fusion compat: Silently drop unknown attribute/value pair BINDER_LOG_STRING(W("unknown attribute"), attributeString); BINDER_LOG_STRING(W("unknown value"), valueString); } Exit: BINDER_LOG_LEAVE_HR(W("TextualIdentityParser::PopulateAssemblyIdentity"), (fIsValid ? S_OK : S_FALSE)); return fIsValid; } /* static */ void TextualIdentityParser::EscapeString(SString &input, SString &result) { BINDER_LOG_ENTER(W("TextualIdentityParser::EscapeString")); BINDER_LOG_STRING(W("input"), input); BOOL fNeedQuotes = FALSE; WCHAR wcQuoteCharacter = W('"'); SmallStackSString tmpString; SString::Iterator cursor = input.Begin(); SString::Iterator end = input.End() - 1; // Leading/Trailing white space require quotes if (IsWhitespace(cursor[0]) || IsWhitespace(end[0])) { fNeedQuotes = TRUE; } // Fusion textual identity compat: escape all non-quote characters even if quoted while (cursor <= end) { WCHAR wcCurrentChar = cursor[0]; switch (wcCurrentChar) { case W('"'): case W('\''): if (fNeedQuotes && (wcQuoteCharacter != wcCurrentChar)) { tmpString.Append(wcCurrentChar); } else if (!fNeedQuotes) { fNeedQuotes = TRUE; wcQuoteCharacter = (wcCurrentChar == W('"') ? W('\'') : W('"')); tmpString.Append(wcCurrentChar); } else { tmpString.Append(W('\\')); tmpString.Append(wcCurrentChar); } break; case W('='): case W(','): case W('\\'): tmpString.Append(W('\\')); tmpString.Append(wcCurrentChar); break; case 9: tmpString.Append(W("\\t")); break; case 10: tmpString.Append(W("\\n")); break; case 13: tmpString.Append(W("\\r")); break; default: tmpString.Append(wcCurrentChar); break; } cursor++; } if (fNeedQuotes) { result.Clear(); result.Append(wcQuoteCharacter); result.Append(tmpString); result.Append(wcQuoteCharacter); } else { result.Set(tmpString); } BINDER_LOG_LEAVE(W("TextualIdentityParser::EscapeString")); } };
{ "content_hash": "8552c978abada78b0bab56caac83ef13", "timestamp": "", "source": "github", "line_count": 803, "max_line_length": 128, "avg_line_length": 36.40722291407223, "alnum_prop": 0.5033692491876176, "repo_name": "mmitche/coreclr", "id": "7cd45451877013075222af849d80c5f518adb0f6", "size": "29235", "binary": false, "copies": "19", "ref": "refs/heads/master", "path": "src/binder/textualidentityparser.cpp", "mode": "33188", "license": "mit", "language": [ { "name": "Assembly", "bytes": "956111" }, { "name": "Awk", "bytes": "6916" }, { "name": "Batchfile", "bytes": "168475" }, { "name": "C", "bytes": "5588467" }, { "name": "C#", "bytes": "150477201" }, { "name": "C++", "bytes": "65887021" }, { "name": "CMake", "bytes": "715184" }, { "name": "Groovy", "bytes": "225924" }, { "name": "M4", "bytes": "15214" }, { "name": "Makefile", "bytes": "46117" }, { "name": "Objective-C", "bytes": "16829" }, { "name": "Perl", "bytes": "23640" }, { "name": "PowerShell", "bytes": "54894" }, { "name": "Python", "bytes": "548588" }, { "name": "Roff", "bytes": "656420" }, { "name": "Scala", "bytes": "4102" }, { "name": "Shell", "bytes": "490554" }, { "name": "Smalltalk", "bytes": "635930" }, { "name": "SuperCollider", "bytes": "650" }, { "name": "TeX", "bytes": "126781" }, { "name": "XSLT", "bytes": "1016" }, { "name": "Yacc", "bytes": "157492" } ], "symlink_target": "" }
<Record> <Term>Raplon</Term> <SemanticType>Pharmacologic Substance</SemanticType> <SemanticType>Organic Chemical</SemanticType> <PrimarySemanticType>Pharmacologic Substance</PrimarySemanticType> <Synonym>Rapacuronium</Synonym> <Synonym>Rapacuronium bromide</Synonym> <Source>FDA Registry</Source> </Record>
{ "content_hash": "3c412ba698d66215b6ce496db9a48ef1", "timestamp": "", "source": "github", "line_count": 9, "max_line_length": 66, "avg_line_length": 35.111111111111114, "alnum_prop": 0.8006329113924051, "repo_name": "detnavillus/modular-informatic-designs", "id": "e82de60881db1224a4ef1084669f3e7560337d1f", "size": "316", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "pipeline/src/test/resources/thesaurus/fdarecords/raplon.xml", "mode": "33261", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "2069134" } ], "symlink_target": "" }
.. image:: https://secure.travis-ci.org/pelme/pytest_django.png?branch=master :alt: Build Status :target: https://travis-ci.org/pelme/pytest_django pytest-django is a plugin for `pytest <http://pytest.org/>`_ that provides a set of useful tools for testing `Django <http://www.djangoproject.com/>`_ applications and projects. * Authors: Ben Firshman, Andreas Pelme and `contributors <https://github.com/pelme/pytest_django/contributors>`_ * Licence: BSD * Compatibility: Django 1.3-1.6, python 2.5-2.7 and 3.2-3.3 or PyPy, pytest >= 2.3.4 * Project URL: https://github.com/pelme/pytest_django * Documentation: http://pytest-django.rtfd.org/ Quick Start =========== 1. ``pip install pytest-django`` 2. Make sure ``DJANGO_SETTINGS_MODULE`` is defined and and run tests with the ``py.test`` command. 3. (Optionally) If you put your tests under a tests directory (the standard Django application layout), and your files are not named ``test_FOO.py``, `see the FAQ <http://pytest-django.readthedocs.org/en/latest/faq.html#my-tests-are-not-being-picked-up-when-i-run-pytest-from-the-root-directory-why-not>`_ Documentation ============== `Documentation is available on Read the Docs. <http://pytest-django.readthedocs.org/en/latest/index.html>`_ Why would I use this instead of Django's manage.py test command? ================================================================ Running the test suite with pytest offers some features that are not present in Djangos standard test mechanism: * Less boilerplate: no need to import unittest, create a subclass with methods. Just write tests as regular functions. * `Manage test dependencies withfixtures <http://pytest.org/latest/fixture.html>`_ * Database re-use: no need to re-create the test database for every test run. * There are a lot of other nice plugins available for pytest. * No pain of switching: Existing unittest-style tests will still work without any modifications. See the `pytest documentation <http://pytest.org/latest/>`_ for more information on pytest. Contributing ============ Read the `contributing page <http://pytest-django.readthedocs.org/en/latest/contributing.html>`_ from the documentation. To run the project's tests:: make test To build the project's docs:: make docs Bugs? Feature suggestions? ============================ Report issues and feature requests at the `github issue tracker <http://github.com/pelme/pytest_django/issues>`_.
{ "content_hash": "1d43a3d765ef2c08aa01716cb028be1c", "timestamp": "", "source": "github", "line_count": 58, "max_line_length": 305, "avg_line_length": 42.258620689655174, "alnum_prop": 0.7144022847817217, "repo_name": "jantman/pytest_django", "id": "3a196cc7f1e35fc282b2fac3a0f2d3c4d837f342", "size": "2451", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "README.rst", "mode": "33188", "license": "bsd-3-clause", "language": [], "symlink_target": "" }
import sys import os import unittest from array import array from weakref import proxy import io import _pyio as pyio from test.support import TESTFN from test import support from collections import UserList class AutoFileTests: # file tests for which a test file is automatically set up def setUp(self): self.f = self.open(TESTFN, 'wb') def tearDown(self): if self.f: self.f.close() support.unlink(TESTFN) def testWeakRefs(self): # verify weak references p = proxy(self.f) p.write(b'teststring') self.assertEqual(self.f.tell(), p.tell()) self.f.close() self.f = None self.assertRaises(ReferenceError, getattr, p, 'tell') def testAttributes(self): # verify expected attributes exist f = self.f f.name # merely shouldn't blow up f.mode # ditto f.closed # ditto def testReadinto(self): # verify readinto self.f.write(b'12') self.f.close() a = array('b', b'x'*10) self.f = self.open(TESTFN, 'rb') n = self.f.readinto(a) self.assertEqual(b'12', a.tobytes()[:n]) def testReadinto_text(self): # verify readinto refuses text files a = array('b', b'x'*10) self.f.close() self.f = self.open(TESTFN, 'r') if hasattr(self.f, "readinto"): self.assertRaises(TypeError, self.f.readinto, a) def testWritelinesUserList(self): # verify writelines with instance sequence l = UserList([b'1', b'2']) self.f.writelines(l) self.f.close() self.f = self.open(TESTFN, 'rb') buf = self.f.read() self.assertEqual(buf, b'12') def testWritelinesIntegers(self): # verify writelines with integers self.assertRaises(TypeError, self.f.writelines, [1, 2, 3]) def testWritelinesIntegersUserList(self): # verify writelines with integers in UserList l = UserList([1,2,3]) self.assertRaises(TypeError, self.f.writelines, l) def testWritelinesNonString(self): # verify writelines with non-string object class NonString: pass self.assertRaises(TypeError, self.f.writelines, [NonString(), NonString()]) def testErrors(self): f = self.f self.assertEqual(f.name, TESTFN) self.assertFalse(f.isatty()) self.assertFalse(f.closed) if hasattr(f, "readinto"): self.assertRaises((OSError, TypeError), f.readinto, "") f.close() self.assertTrue(f.closed) def testMethods(self): methods = [('fileno', ()), ('flush', ()), ('isatty', ()), ('__next__', ()), ('read', ()), ('write', (b"",)), ('readline', ()), ('readlines', ()), ('seek', (0,)), ('tell', ()), ('write', (b"",)), ('writelines', ([],)), ('__iter__', ()), ] methods.append(('truncate', ())) # __exit__ should close the file self.f.__exit__(None, None, None) self.assertTrue(self.f.closed) for methodname, args in methods: method = getattr(self.f, methodname) # should raise on closed file self.assertRaises(ValueError, method, *args) # file is closed, __exit__ shouldn't do anything self.assertEqual(self.f.__exit__(None, None, None), None) # it must also return None if an exception was given try: 1/0 except: self.assertEqual(self.f.__exit__(*sys.exc_info()), None) def testReadWhenWriting(self): self.assertRaises(OSError, self.f.read) class CAutoFileTests(AutoFileTests, unittest.TestCase): open = io.open class PyAutoFileTests(AutoFileTests, unittest.TestCase): open = staticmethod(pyio.open) class OtherFileTests: def tearDown(self): support.unlink(TESTFN) def testModeStrings(self): # check invalid mode strings self.open(TESTFN, 'wb').close() for mode in ("", "aU", "wU+", "U+", "+U", "rU+"): try: f = self.open(TESTFN, mode) except ValueError: pass else: f.close() self.fail('%r is an invalid file mode' % mode) def testBadModeArgument(self): # verify that we get a sensible error message for bad mode argument bad_mode = "qwerty" try: f = self.open(TESTFN, bad_mode) except ValueError as msg: if msg.args[0] != 0: s = str(msg) if TESTFN in s or bad_mode not in s: self.fail("bad error message for invalid mode: %s" % s) # if msg.args[0] == 0, we're probably on Windows where there may be # no obvious way to discover why open() failed. else: f.close() self.fail("no error for invalid mode: %s" % bad_mode) def _checkBufferSize(self, s): try: f = self.open(TESTFN, 'wb', s) f.write(str(s).encode("ascii")) f.close() f.close() f = self.open(TESTFN, 'rb', s) d = int(f.read().decode("ascii")) f.close() f.close() except OSError as msg: self.fail('error setting buffer size %d: %s' % (s, str(msg))) self.assertEqual(d, s) def testSetBufferSize(self): # make sure that explicitly setting the buffer size doesn't cause # misbehaviour especially with repeated close() calls for s in (-1, 0, 512): with support.check_no_warnings(self, message='line buffering', category=RuntimeWarning): self._checkBufferSize(s) # test that attempts to use line buffering in binary mode cause # a warning with self.assertWarnsRegex(RuntimeWarning, 'line buffering'): self._checkBufferSize(1) def testTruncateOnWindows(self): # SF bug <http://www.python.org/sf/801631> # "file.truncate fault on windows" f = self.open(TESTFN, 'wb') try: f.write(b'12345678901') # 11 bytes f.close() f = self.open(TESTFN,'rb+') data = f.read(5) if data != b'12345': self.fail("Read on file opened for update failed %r" % data) if f.tell() != 5: self.fail("File pos after read wrong %d" % f.tell()) f.truncate() if f.tell() != 5: self.fail("File pos after ftruncate wrong %d" % f.tell()) f.close() size = os.path.getsize(TESTFN) if size != 5: self.fail("File size after ftruncate wrong %d" % size) finally: f.close() def testIteration(self): # Test the complex interaction when mixing file-iteration and the # various read* methods. dataoffset = 16384 filler = b"ham\n" assert not dataoffset % len(filler), \ "dataoffset must be multiple of len(filler)" nchunks = dataoffset // len(filler) testlines = [ b"spam, spam and eggs\n", b"eggs, spam, ham and spam\n", b"saussages, spam, spam and eggs\n", b"spam, ham, spam and eggs\n", b"spam, spam, spam, spam, spam, ham, spam\n", b"wonderful spaaaaaam.\n" ] methods = [("readline", ()), ("read", ()), ("readlines", ()), ("readinto", (array("b", b" "*100),))] # Prepare the testfile bag = self.open(TESTFN, "wb") bag.write(filler * nchunks) bag.writelines(testlines) bag.close() # Test for appropriate errors mixing read* and iteration for methodname, args in methods: f = self.open(TESTFN, 'rb') self.assertEqual(next(f), filler) meth = getattr(f, methodname) meth(*args) # This simply shouldn't fail f.close() # Test to see if harmless (by accident) mixing of read* and # iteration still works. This depends on the size of the internal # iteration buffer (currently 8192,) but we can test it in a # flexible manner. Each line in the bag o' ham is 4 bytes # ("h", "a", "m", "\n"), so 4096 lines of that should get us # exactly on the buffer boundary for any power-of-2 buffersize # between 4 and 16384 (inclusive). f = self.open(TESTFN, 'rb') for i in range(nchunks): next(f) testline = testlines.pop(0) try: line = f.readline() except ValueError: self.fail("readline() after next() with supposedly empty " "iteration-buffer failed anyway") if line != testline: self.fail("readline() after next() with empty buffer " "failed. Got %r, expected %r" % (line, testline)) testline = testlines.pop(0) buf = array("b", b"\x00" * len(testline)) try: f.readinto(buf) except ValueError: self.fail("readinto() after next() with supposedly empty " "iteration-buffer failed anyway") line = buf.tobytes() if line != testline: self.fail("readinto() after next() with empty buffer " "failed. Got %r, expected %r" % (line, testline)) testline = testlines.pop(0) try: line = f.read(len(testline)) except ValueError: self.fail("read() after next() with supposedly empty " "iteration-buffer failed anyway") if line != testline: self.fail("read() after next() with empty buffer " "failed. Got %r, expected %r" % (line, testline)) try: lines = f.readlines() except ValueError: self.fail("readlines() after next() with supposedly empty " "iteration-buffer failed anyway") if lines != testlines: self.fail("readlines() after next() with empty buffer " "failed. Got %r, expected %r" % (line, testline)) f.close() # Reading after iteration hit EOF shouldn't hurt either f = self.open(TESTFN, 'rb') try: for line in f: pass try: f.readline() f.readinto(buf) f.read() f.readlines() except ValueError: self.fail("read* failed after next() consumed file") finally: f.close() class COtherFileTests(OtherFileTests, unittest.TestCase): open = io.open class PyOtherFileTests(OtherFileTests, unittest.TestCase): open = staticmethod(pyio.open) if __name__ == '__main__': unittest.main()
{ "content_hash": "84beb7a2e262b0a2e3b81d965ebf0bcc", "timestamp": "", "source": "github", "line_count": 333, "max_line_length": 79, "avg_line_length": 33.87687687687688, "alnum_prop": 0.5277014449073664, "repo_name": "kikocorreoso/brython", "id": "cd642e7aaf8bb8634a14f751c924585369b355bc", "size": "11281", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "www/src/Lib/test/test_file.py", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "CSS", "bytes": "21158" }, { "name": "HTML", "bytes": "5011615" }, { "name": "JavaScript", "bytes": "7230101" }, { "name": "PLSQL", "bytes": "22886" }, { "name": "Python", "bytes": "19224768" }, { "name": "Roff", "bytes": "21126" }, { "name": "VBScript", "bytes": "481" } ], "symlink_target": "" }
<?xml version="1.0" encoding="UTF-8"?> <!-- Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with this work for additional information regarding copyright ownership. The ASF licenses this file to You under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. --> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>${groupId}</groupId> <artifactId>${artifactId}</artifactId> <version>${version}</version> <packaging>jar</packaging> <properties> <beam.version>@project.version@</beam.version> <surefire-plugin.version>2.20</surefire-plugin.version> </properties> <repositories> <repository> <id>apache.snapshots</id> <name>Apache Development Snapshot Repository</name> <url>https://repository.apache.org/content/repositories/snapshots/</url> <releases> <enabled>false</enabled> </releases> <snapshots> <enabled>true</enabled> </snapshots> </repository> </repositories> <build> <plugins> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-compiler-plugin</artifactId> <version>3.5.1</version> <configuration> <source>1.8</source> <target>1.8</target> </configuration> </plugin> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-surefire-plugin</artifactId> <version>${surefire-plugin.version}</version> <configuration> <parallel>all</parallel> <threadCount>4</threadCount> <redirectTestOutputToFile>true</redirectTestOutputToFile> </configuration> <dependencies> <dependency> <groupId>org.apache.maven.surefire</groupId> <artifactId>surefire-junit47</artifactId> <version>${surefire-plugin.version}</version> </dependency> </dependencies> </plugin> <!-- Ensure that the Maven jar plugin runs before the Maven shade plugin by listing the plugin higher within the file. --> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-jar-plugin</artifactId> </plugin> <!-- Configures `mvn package` to produce a bundled jar ("fat jar") for runners that require this for job submission to a cluster. --> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-shade-plugin</artifactId> <version>3.0.0</version> <executions> <execution> <phase>package</phase> <goals> <goal>shade</goal> </goals> <configuration> <filters> <filter> <artifact>*:*</artifact> <excludes> <exclude>META-INF/LICENSE</exclude> <exclude>META-INF/*.SF</exclude> <exclude>META-INF/*.DSA</exclude> <exclude>META-INF/*.RSA</exclude> </excludes> </filter> </filters> <transformers> <transformer implementation="org.apache.maven.plugins.shade.resource.ServicesResourceTransformer"/> </transformers> </configuration> </execution> </executions> </plugin> </plugins> <pluginManagement> <plugins> <plugin> <groupId>org.codehaus.mojo</groupId> <artifactId>exec-maven-plugin</artifactId> <version>1.4.0</version> <configuration> <cleanupDaemonThreads>false</cleanupDaemonThreads> </configuration> </plugin> </plugins> </pluginManagement> </build> <profiles> <profile> <id>direct-runner</id> <activation> <activeByDefault>true</activeByDefault> </activation> <!-- Makes the DirectRunner available when running a pipeline. --> <dependencies> <dependency> <groupId>org.apache.beam</groupId> <artifactId>beam-runners-direct-java</artifactId> <version>${beam.version}</version> <scope>runtime</scope> </dependency> </dependencies> </profile> <profile> <id>apex-runner</id> <!-- Makes the ApexRunner available when running a pipeline. --> <dependencies> <dependency> <groupId>org.apache.beam</groupId> <artifactId>beam-runners-apex</artifactId> <version>${beam.version}</version> <scope>runtime</scope> </dependency> <!-- Apex depends on httpclient version 4.3.5, project has a transitive dependency to httpclient 4.0.1 from google-http-client. Apex dependency version being specified explicitly so that it gets picked up. This can be removed when the project no longer has a dependency on a different httpclient version. --> <dependency> <groupId>org.apache.httpcomponents</groupId> <artifactId>httpclient</artifactId> <version>4.3.5</version> <scope>runtime</scope> <exclusions> <exclusion> <groupId>commons-codec</groupId> <artifactId>commons-codec</artifactId> </exclusion> </exclusions> </dependency> </dependencies> </profile> <profile> <id>dataflow-runner</id> <!-- Makes the DataflowRunner available when running a pipeline. --> <dependencies> <dependency> <groupId>org.apache.beam</groupId> <artifactId>beam-runners-google-cloud-dataflow-java</artifactId> <version>${beam.version}</version> <scope>runtime</scope> </dependency> </dependencies> </profile> <profile> <id>flink-runner</id> <!-- Makes the FlinkRunner available when running a pipeline. --> <dependencies> <dependency> <groupId>org.apache.beam</groupId> <artifactId>beam-runners-flink_2.10</artifactId> <version>${beam.version}</version> <scope>runtime</scope> </dependency> </dependencies> </profile> <profile> <id>spark-runner</id> <!-- Makes the SparkRunner available when running a pipeline. Additionally, overrides some Spark dependencies to Beam-compatible versions. --> <dependencies> <dependency> <groupId>org.apache.beam</groupId> <artifactId>beam-runners-spark</artifactId> <version>${beam.version}</version> <scope>runtime</scope> </dependency> <dependency> <groupId>org.apache.beam</groupId> <artifactId>beam-sdks-java-io-hadoop-file-system</artifactId> <version>${beam.version}</version> <scope>runtime</scope> </dependency> <dependency> <groupId>org.apache.spark</groupId> <artifactId>spark-streaming_2.10</artifactId> <version>1.6.2</version> <scope>runtime</scope> <exclusions> <exclusion> <groupId>org.slf4j</groupId> <artifactId>jul-to-slf4j</artifactId> </exclusion> </exclusions> </dependency> <dependency> <groupId>com.fasterxml.jackson.module</groupId> <artifactId>jackson-module-scala_2.10</artifactId> <version>@jackson.version@</version> <scope>runtime</scope> </dependency> </dependencies> </profile> </profiles> <dependencies> <!-- Adds a dependency on a specific version of the Beam SDK. --> <dependency> <groupId>org.apache.beam</groupId> <artifactId>beam-sdks-java-core</artifactId> <version>${beam.version}</version> </dependency> <!-- Adds a dependency on a specific version of the Beam Google Cloud Platform IO module. --> <dependency> <groupId>org.apache.beam</groupId> <artifactId>beam-sdks-java-io-google-cloud-platform</artifactId> <version>${beam.version}</version> </dependency> <dependency> <groupId>com.google.api-client</groupId> <artifactId>google-api-client</artifactId> <version>1.22.0</version> <exclusions> <!-- Exclude an old version of guava that is being pulled in by a transitive dependency of google-api-client --> <exclusion> <groupId>com.google.guava</groupId> <artifactId>guava-jdk5</artifactId> </exclusion> </exclusions> </dependency> <!-- Dependencies below this line are specific dependencies needed by the examples code. --> <dependency> <groupId>com.google.apis</groupId> <artifactId>google-api-services-bigquery</artifactId> <version>v2-rev295-1.22.0</version> <exclusions> <!-- Exclude an old version of guava that is being pulled in by a transitive dependency of google-api-client --> <exclusion> <groupId>com.google.guava</groupId> <artifactId>guava-jdk5</artifactId> </exclusion> </exclusions> </dependency> <dependency> <groupId>com.google.http-client</groupId> <artifactId>google-http-client</artifactId> <version>1.22.0</version> <exclusions> <!-- Exclude an old version of guava that is being pulled in by a transitive dependency of google-api-client --> <exclusion> <groupId>com.google.guava</groupId> <artifactId>guava-jdk5</artifactId> </exclusion> </exclusions> </dependency> <dependency> <groupId>com.google.apis</groupId> <artifactId>google-api-services-pubsub</artifactId> <version>v1-rev10-1.22.0</version> <exclusions> <!-- Exclude an old version of guava that is being pulled in by a transitive dependency of google-api-client --> <exclusion> <groupId>com.google.guava</groupId> <artifactId>guava-jdk5</artifactId> </exclusion> </exclusions> </dependency> <dependency> <groupId>joda-time</groupId> <artifactId>joda-time</artifactId> <version>2.4</version> </dependency> <dependency> <groupId>com.google.guava</groupId> <artifactId>guava</artifactId> <version>20.0</version> </dependency> <!-- Add slf4j API frontend binding with JUL backend --> <dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-api</artifactId> <version>1.7.14</version> </dependency> <dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-jdk14</artifactId> <version>1.7.14</version> <!-- When loaded at runtime this will wire up slf4j to the JUL backend --> <scope>runtime</scope> </dependency> <!-- Hamcrest and JUnit are required dependencies of PAssert, which is used in the main code of DebuggingWordCount example. --> <dependency> <groupId>org.hamcrest</groupId> <artifactId>hamcrest-all</artifactId> <version>1.3</version> </dependency> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.12</version> </dependency> <dependency> <groupId>org.mockito</groupId> <artifactId>mockito-all</artifactId> <version>1.9.5</version> <scope>test</scope> </dependency> <dependency> <groupId>org.apache.beam</groupId> <artifactId>beam-runners-direct-java</artifactId> <version>${beam.version}</version> <scope>test</scope> </dependency> </dependencies> </project>
{ "content_hash": "15479421a8cdbfca09e0cd0fa8122e35", "timestamp": "", "source": "github", "line_count": 373, "max_line_length": 115, "avg_line_length": 33.603217158176946, "alnum_prop": 0.6059518110738791, "repo_name": "dhalperi/incubator-beam", "id": "5f34689f028f20e0705cb70c353fd7f8751dca01", "size": "12534", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "sdks/java/maven-archetypes/examples-java8/src/main/resources/archetype-resources/pom.xml", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Groovy", "bytes": "22449" }, { "name": "Java", "bytes": "9735468" }, { "name": "Protocol Buffer", "bytes": "1407" }, { "name": "Shell", "bytes": "10104" } ], "symlink_target": "" }
package ru.extas.web.commons.component; import com.vaadin.ui.Component; import com.vaadin.ui.CssLayout; import com.vaadin.ui.HorizontalLayout; import com.vaadin.ui.Label; import ru.extas.web.commons.ExtaTheme; /** * @author Valery Orlov * Date: 11.09.2014 * Time: 15:13 */ public class CardPanel extends CssLayout { private final Label label; private final HorizontalLayout panelCaption; public CardPanel(final String caption, final Component action, final Component panelContent) { addStyleName(ExtaTheme.LAYOUT_CARD); panelCaption = new HorizontalLayout(); panelCaption.addStyleName("v-panel-caption"); panelCaption.setWidth(100, Unit.PERCENTAGE); label = new Label(caption); panelCaption.addComponent(label); panelCaption.setExpandRatio(label, 1); panelCaption.addComponent(action); addComponent(panelCaption); addComponent(panelContent); } }
{ "content_hash": "68dd8f348fa99dc94a39d7e02934e44a", "timestamp": "", "source": "github", "line_count": 33, "max_line_length": 98, "avg_line_length": 29.333333333333332, "alnum_prop": 0.7035123966942148, "repo_name": "ExtaSoft/extacrm", "id": "436241ab12d1d570d1765593df0d7d8e37b15db1", "size": "968", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/main/java/ru/extas/web/commons/component/CardPanel.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "22818" }, { "name": "HTML", "bytes": "801" }, { "name": "Java", "bytes": "1883954" }, { "name": "JavaScript", "bytes": "41974" }, { "name": "SQLPL", "bytes": "3834" }, { "name": "Shell", "bytes": "6636" } ], "symlink_target": "" }
import _ from "lodash"; import * as React from "react"; import { IRouter, IInjectedProps } from "react-router"; import { connect } from "react-redux"; import { PageConfig, PageConfigItem } from "../components/pageconfig"; import { refreshNodes } from "../redux/apiReducers"; import Dropdown, { DropdownOption } from "../components/dropdown"; import { AdminUIState } from "../redux/state"; import { nodeIDAttr, dashboardNameAttr, } from "../util/constants"; import TimeScaleDropdown from "./timescale"; interface ClusterOverviewOwnProps { nodes: Proto2TypeScript.cockroach.server.status.NodeStatus[]; refreshNodes: typeof refreshNodes; } type ClusterOverviewProps = ClusterOverviewOwnProps & IInjectedProps; interface ClusterOverviewState { nodeOptions: { value: string, label: string }[]; } let dashboards = [ { value: "activity", label: "Activity" }, { value: "queries", label: "SQL Queries" }, { value: "resources", label: "System Resources" }, { value: "internals", label: "Advanced Internals" }, ]; /** * Renders the layout of the nodes page. */ class ClusterOverview extends React.Component<ClusterOverviewProps, ClusterOverviewState> { // Magic to add react router to the context. // See https://github.com/ReactTraining/react-router/issues/975 static contextTypes = { router: React.PropTypes.object.isRequired, }; context: { router?: IRouter & IInjectedProps; }; state: ClusterOverviewState = { nodeOptions: [{ value: "", label: "Cluster"}], }; static title() { return "Cluster Overview"; } componentWillMount() { this.props.refreshNodes(); } componentWillReceiveProps(props: ClusterOverviewProps) { let base = [{ value: "", label: "Cluster"}]; if (props.nodes) { this.setState({ nodeOptions: base.concat(_.map(props.nodes, (n) => { return { value: n.desc.node_id.toString(), label: n.desc.address.address_field, }; })), }); } } setClusterPath(nodeID: string, dashboardName: string) { if (!_.isString(nodeID) || nodeID === "") { this.context.router.push(`/cluster/all/${dashboardName}`); } else { this.context.router.push(`/cluster/node/${nodeID}/${dashboardName}`); } } nodeChange = (selected: DropdownOption) => { this.setClusterPath(selected.value, this.props.params[dashboardNameAttr]); } dashChange = (selected: DropdownOption) => { this.setClusterPath(this.props.params[nodeIDAttr], selected.value); } render() { // Determine whether or not the time scale options should be displayed. let child = React.Children.only(this.props.children); let displayTimescale = (child as any).type.displayTimeScale === true; let dashboard = this.props.params[dashboardNameAttr]; let node = this.props.params[nodeIDAttr] || ""; return <div> <PageConfig> <PageConfigItem> <Dropdown title="Graph" options={this.state.nodeOptions} selected={node} onChange={this.nodeChange} /> </PageConfigItem> <PageConfigItem> <Dropdown title="Dashboard" options={dashboards} selected={dashboard} onChange={this.dashChange} /> </PageConfigItem> <PageConfigItem> {displayTimescale ? <TimeScaleDropdown /> : null } </PageConfigItem> </PageConfig> { this.props.children } </div>; } } export default connect( (state: AdminUIState, ownProps: IInjectedProps) => { return { nodes: state.cachedData.nodes.data, }; }, { refreshNodes, } )(ClusterOverview);
{ "content_hash": "776a9e9b13c6c8f396e9951496a98189", "timestamp": "", "source": "github", "line_count": 124, "max_line_length": 91, "avg_line_length": 29.258064516129032, "alnum_prop": 0.6529768467475193, "repo_name": "petermattis/cockroach", "id": "f1b388954ae6cd4bffa1313341ec73e44102b98e", "size": "3628", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "pkg/ui/app/containers/nodes.tsx", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Awk", "bytes": "1029" }, { "name": "C", "bytes": "9260" }, { "name": "C++", "bytes": "80578" }, { "name": "CSS", "bytes": "37962" }, { "name": "Go", "bytes": "8386033" }, { "name": "HCL", "bytes": "34987" }, { "name": "HTML", "bytes": "18016" }, { "name": "JavaScript", "bytes": "261951" }, { "name": "Makefile", "bytes": "20706" }, { "name": "Protocol Buffer", "bytes": "222568" }, { "name": "Ruby", "bytes": "2554" }, { "name": "Shell", "bytes": "49022" }, { "name": "Smarty", "bytes": "4831" }, { "name": "Tcl", "bytes": "23649" }, { "name": "TypeScript", "bytes": "298817" }, { "name": "Vim script", "bytes": "1650" }, { "name": "Yacc", "bytes": "128577" } ], "symlink_target": "" }
<?php namespace frontend\modules\cabinet\controllers; use common\controllers\AuthController; use Yii; use common\models\Advert; use common\models\Search\AdvertSearch; use yii\web\Controller; use yii\web\NotFoundHttpException; use yii\filters\VerbFilter; /** * AdvertController implements the CRUD actions for Advert model. */ //class AdvertController extends Controller class AdvertController extends AuthController //AuthController òàì íàïèñàíà ïðàâà äîñòóïà ê ëè÷íîìó êàáèíåòó { public $layout = 'inner'; public function actionIndex() { $searchModel = new AdvertSearch(); $dataProvider = $searchModel->search(Yii::$app->request->queryParams); return $this->render('index', [ 'searchModel' => $searchModel, 'dataProvider' => $dataProvider, ]); } /** * Displays a single Advert model. * @param integer $id * @return mixed */ public function actionView($id) { return $this->render('view', [ 'model' => $this->findModel($id), ]); } /** * Creates a new Advert model. * If creation is successful, the browser will be redirected to the 'view' page. * @return mixed */ public function actionCreate() { $model = new Advert(); if ($model->load(Yii::$app->request->post()) && $model->save()) { return $this->redirect(['view', 'id' => $model->idadvert]); } else { return $this->render('create', [ 'model' => $model, ]); } } /** * Updates an existing Advert model. * If update is successful, the browser will be redirected to the 'view' page. * @param integer $id * @return mixed */ public function actionUpdate($id) { $model = $this->findModel($id); if ($model->load(Yii::$app->request->post()) && $model->save()) { return $this->redirect(['view', 'id' => $model->idadvert]); } else { return $this->render('update', [ 'model' => $model, ]); } } /** * Deletes an existing Advert model. * If deletion is successful, the browser will be redirected to the 'index' page. * @param integer $id * @return mixed */ public function actionDelete($id) { $this->findModel($id)->delete(); return $this->redirect(['index']); } /** * Finds the Advert model based on its primary key value. * If the model is not found, a 404 HTTP exception will be thrown. * @param integer $id * @return Advert the loaded model * @throws NotFoundHttpException if the model cannot be found */ protected function findModel($id) { if (($model = Advert::findOne($id)) !== null) { return $model; } else { throw new NotFoundHttpException('The requested page does not exist.'); } } }
{ "content_hash": "7d4775de70cf2eb02518784a328402b9", "timestamp": "", "source": "github", "line_count": 110, "max_line_length": 108, "avg_line_length": 27.1, "alnum_prop": 0.5743039248574304, "repo_name": "pylliok/yii2-grek-lesson", "id": "32ca37eab44db08e94a8af9e24b7a37defc23ea9", "size": "2981", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "frontend/modules/cabinet/controllers/AdvertController.php", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "ApacheConf", "bytes": "718" }, { "name": "Batchfile", "bytes": "1541" }, { "name": "CSS", "bytes": "25668" }, { "name": "JavaScript", "bytes": "72160" }, { "name": "PHP", "bytes": "187554" }, { "name": "Shell", "bytes": "3257" } ], "symlink_target": "" }
<?xml version="1.0"?> <project xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd" xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"> <modelVersion>4.0.0</modelVersion> <parent> <groupId>com.ociweb</groupId> <artifactId>grove</artifactId> <version>1.0.0</version> </parent> <groupId>com.ociweb.grove</groupId> <artifactId>temprature</artifactId> <version>1.0.0</version> <properties> <java.secure.socket.extension.classes>${java.home}/lib/jsse.jar</java.secure.socket.extension.classes> <java.bootstrap.classes>${java.home}/lib/rt.jar</java.bootstrap.classes> <java.cryptographic.extension.classes>${java.home}/lib/jce.jar</java.cryptographic.extension.classes> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> </properties> <dependencies> <dependency> <groupId>com.ociweb</groupId> <artifactId>foglight</artifactId> <version>1.0.0</version> </dependency> <dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-api</artifactId> <version>1.7.12</version> </dependency> <dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-simple</artifactId> <version>1.7.12</version> <scope>runtime</scope> </dependency> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.12</version> <scope>test</scope> <optional>false</optional> </dependency> </dependencies> <build> <plugins> <plugin> <artifactId>maven-compiler-plugin</artifactId> <version>3.0</version> <configuration> <compilerArguments> <profile>compact1</profile> </compilerArguments> <source>1.8</source> <target>1.8</target> </configuration> </plugin> <plugin> <artifactId>maven-jar-plugin</artifactId> <version>2.4</version> <configuration> <forceCreation>true</forceCreation> </configuration> </plugin> <plugin> <artifactId>maven-source-plugin</artifactId> <version>2.4</version> <executions> <execution> <id>attach-sources</id> <phase>verify</phase> <goals> <goal>jar-no-fork</goal> </goals> </execution> </executions> </plugin> <plugin> <artifactId>maven-shade-plugin</artifactId> <version>2.4.3</version> <executions> <execution> <phase>package</phase> <goals> <goal>shade</goal> </goals> <configuration> <filters> <filter> <artifact>*jnr-ffi:jnr-ffi*</artifact> <excludes> <exclude>**/jni/**</exclude> </excludes> </filter> </filters> </configuration> </execution> </executions> </plugin> <plugin> <artifactId>maven-assembly-plugin</artifactId> <executions> <execution> <id>make-assembly</id> <phase>prepare-package</phase> <goals> <goal>single</goal> </goals> </execution> </executions> <configuration> <archive> <manifest> <mainClass>com.ociweb.FogLight</mainClass> </manifest> </archive> <descriptorRefs> <descriptorRef>jar-with-dependencies</descriptorRef> </descriptorRefs> <finalName>uberTemprature</finalName> <appendAssemblyId>false</appendAssemblyId> </configuration> </plugin> <plugin> <groupId>com.github.wvengen</groupId> <artifactId>proguard-maven-plugin</artifactId> <version>2.0.13</version> <executions> <execution> <id>proguard</id> <phase>package</phase> <goals> <goal>proguard</goal> </goals> </execution> </executions> <dependencies> <dependency> <groupId>net.sf.proguard</groupId> <artifactId>proguard-base</artifactId> <version>5.1</version> <scope>runtime</scope> </dependency> </dependencies> <configuration> <options> <option>-keep public class com.ociweb.FogLight { public static void main(java.lang.String[]); }</option> <option>-keep public class * implements com.ociweb.iot.maker.FogApp { public static void main(java.lang.String[]); }</option> <option>-keepclassmembers class * extends java.lang.Enum { public static **[] values(); public static ** valueOf(java.lang.String); }</option> <option>-keep class jnr.ffi.** { *; }</option> <option>-keep class com.kenai.jffi.** { *; }</option> <option>-dontobfuscate</option> <option>-ignorewarnings</option> <option>-dontnote</option> <option>-dontwarn</option> <option>-optimizations code/allocation/</option> </options> <obfuscate>false</obfuscate> <libs> <lib>${java.bootstrap.classes}</lib> <lib>${java.cryptographic.extension.classes}</lib> <lib>${java.secure.socket.extension.classes}</lib> </libs> <injar>uberTemprature.jar</injar> <outjar>Temprature.jar</outjar> </configuration> </plugin> </plugins> </build> </project>
{ "content_hash": "cad8fde1c3c4ec15bf476b1e58bc0230", "timestamp": "", "source": "github", "line_count": 177, "max_line_length": 149, "avg_line_length": 32.824858757062145, "alnum_prop": 0.5528399311531842, "repo_name": "oci-pronghorn/FogLight", "id": "d9840665e1827d9d8c404bf26772e87d820ece1a", "size": "5810", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "grove/Temprature/pom.xml", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "C", "bytes": "14452" }, { "name": "Java", "bytes": "1206040" }, { "name": "Makefile", "bytes": "2141" }, { "name": "Shell", "bytes": "42812" } ], "symlink_target": "" }
/*! * Copyright (c) 2018 by Contributors * \file boolean_mask.cc */ #include "./boolean_mask-inl.h" namespace mxnet { namespace op { DMLC_REGISTER_PARAMETER(BooleanMaskParam); bool BooleanMaskType(const nnvm::NodeAttrs& attrs, std::vector<int> *in_attrs, std::vector<int> *out_attrs) { CHECK_EQ(in_attrs->size(), 2); CHECK_EQ(out_attrs->size(), 1); TYPE_ASSIGN_CHECK(*out_attrs, 0, in_attrs->at(0)); TYPE_ASSIGN_CHECK(*in_attrs, 0, out_attrs->at(0)); return in_attrs->at(0) != -1 && in_attrs->at(1) != -1 && out_attrs->at(0) != -1; } bool BooleanMaskStorageType(const nnvm::NodeAttrs& attrs, const int dev_mask, DispatchMode* dispatch_mode, std::vector<int> *in_attrs, std::vector<int> *out_attrs) { CHECK_EQ(in_attrs->size(), 2); CHECK_EQ(out_attrs->size(), 1); for (int &attr : *in_attrs) { CHECK_EQ(attr, kDefaultStorage) << "Only default storage is supported"; } for (int &attr : *out_attrs) { attr = kDefaultStorage; } *dispatch_mode = DispatchMode::kFComputeEx; return true; } bool BooleanMaskBackStorageType(const nnvm::NodeAttrs& attrs, const int dev_mask, DispatchMode* dispatch_mode, std::vector<int> *in_attrs, std::vector<int> *out_attrs) { CHECK_EQ(in_attrs->size(), 3); CHECK_EQ(out_attrs->size(), 2); for (int &attr : *in_attrs) { CHECK_EQ(attr, kDefaultStorage) << "Only default storage is supported"; } for (int &attr : *out_attrs) { attr = kDefaultStorage; } for (int & out_attr : *out_attrs) out_attr = kDefaultStorage; *dispatch_mode = DispatchMode::kFComputeEx; return true; } struct BooleanMaskBackwardCPUWriteKernel { template<typename DType> static void Map(int i, DType* igrad, const OpReqType /*req*/, const DType* ograd, const int32_t* idx, const size_t col_size) { // i is row id already int32_t prev = (i == 0) ? 0 : idx[i - 1]; int32_t curr = idx[i]; #pragma GCC diagnostic push #if __GNUC__ >= 8 #pragma GCC diagnostic ignored "-Wclass-memaccess" #endif if (prev != curr) { std::memcpy(igrad + i * col_size, ograd + prev * col_size, col_size * sizeof(DType)); } else { std::memset(igrad + i * col_size, 0, col_size * sizeof(DType)); } #pragma GCC diagnostic pop } }; template<> inline void BooleanMaskForward<cpu>(const nnvm::NodeAttrs& attrs, const OpContext &ctx, const std::vector<NDArray> &inputs, const std::vector<OpReqType> &req, const std::vector<NDArray> &outputs) { CHECK_EQ(inputs.size(), 2U); CHECK_EQ(outputs.size(), 1U); CHECK(req[0] == kWriteTo || req[0] == kWriteInplace); const BooleanMaskParam& param = nnvm::get<BooleanMaskParam>(attrs.parsed); const int axis = param.axis; const NDArray &data = inputs[0]; const NDArray &idx = inputs[1]; const NDArray &out = outputs[0]; CHECK_EQ(axis, 0) << "Not supported yet"; CHECK_EQ(data.shape()[axis], idx.shape()[0]); CHECK_EQ(idx.shape().ndim(), 1U); // idx is required to be 1-d. // count the number of 1s in `idx`, so that we could know the output dimension size_t idx_size = idx.shape()[0]; std::vector<int32_t> prefix_sum(idx_size, 0); size_t valid_num = 0; // Calculate prefix sum MSHADOW_TYPE_SWITCH_WITH_BOOL(idx.dtype(), DType, { DType* idx_dptr = idx.data().dptr<DType>(); for (size_t i = 0; i < idx_size; i++) { prefix_sum[i] = (i == 0) ? 0 : prefix_sum[i - 1]; prefix_sum[i] += (idx_dptr[i]) ? 1 : 0; } valid_num = prefix_sum[idx_size - 1]; }); // set the output shape forcefully mxnet::TShape s = data.shape(); s[axis] = valid_num; const_cast<NDArray &>(out).Init(s); // do the copy MSHADOW_TYPE_SWITCH_WITH_BOOL(data.dtype(), DType, { size_t input_size = data.shape().Size(); size_t col_size = input_size / idx_size; mshadow::Stream<cpu> *stream = ctx.get_stream<cpu>(); mxnet_op::Kernel<BooleanMaskForwardCPUKernel, cpu>::Launch( stream, idx_size, out.data().dptr<DType>(), data.data().dptr<DType>(), prefix_sum.data(), col_size); }); } template<> inline void BooleanMaskBackward<cpu>(const nnvm::NodeAttrs& attrs, const OpContext &ctx, const std::vector<NDArray> &inputs, const std::vector<OpReqType> &req, const std::vector<NDArray> &outputs) { CHECK_EQ(inputs.size(), 3U); CHECK_EQ(outputs.size(), 2U); if (req[0] == kNullOp) return; // inputs: {ograd, data, idx} // outputs: {igrad_data, igrad_idx} const NDArray& ograd = inputs[0]; const NDArray& idx = inputs[2]; const NDArray& igrad_data = outputs[0]; MSHADOW_TYPE_SWITCH(igrad_data.dtype(), DType, { MSHADOW_TYPE_SWITCH_WITH_BOOL(idx.dtype(), IType, { size_t input_size = igrad_data.shape().Size(); size_t idx_size = idx.shape()[0]; size_t col_size = input_size / idx_size; std::vector<int32_t> prefix_sum(idx_size, 0); IType* idx_dptr = idx.data().dptr<IType>(); for (size_t i = 0; i < idx_size; i++) { prefix_sum[i] = (i == 0) ? 0 : prefix_sum[i - 1]; prefix_sum[i] += (idx_dptr[i]) ? 1 : 0; } mshadow::Stream<cpu> *stream = ctx.get_stream<cpu>(); if (req[0] == kAddTo) { mxnet_op::Kernel<BooleanMaskBackwardKernel, cpu>::Launch( stream, idx_size, igrad_data.data().dptr<DType>(), req[0], ograd.data().dptr<DType>(), prefix_sum.data(), col_size); } else { mxnet_op::Kernel<BooleanMaskBackwardCPUWriteKernel, cpu>::Launch( stream, idx_size, igrad_data.data().dptr<DType>(), req[0], ograd.data().dptr<DType>(), prefix_sum.data(), col_size); } }); }); } NNVM_REGISTER_OP(_contrib_boolean_mask) .add_alias("_npi_boolean_mask") .describe(R"code( Given an n-d NDArray data, and a 1-d NDArray index, the operator produces an un-predeterminable shaped n-d NDArray out, which stands for the rows in x where the corresonding element in index is non-zero. >>> data = mx.nd.array([[1, 2, 3],[4, 5, 6],[7, 8, 9]]) >>> index = mx.nd.array([0, 1, 0]) >>> out = mx.nd.contrib.boolean_mask(data, index) >>> out [[4. 5. 6.]] <NDArray 1x3 @cpu(0)> )code" ADD_FILELINE) .set_attr_parser(ParamParser<BooleanMaskParam>) .set_num_inputs(2) .set_num_outputs(1) .set_attr<nnvm::FListInputNames>("FListInputNames", [](const NodeAttrs& attrs) { return std::vector<std::string>{"data", "index"}; }) .set_attr<nnvm::FInferType>("FInferType", BooleanMaskType) .set_attr<FComputeEx>("FComputeEx<cpu>", BooleanMaskForward<cpu>) .set_attr<FInferStorageType>("FInferStorageType", BooleanMaskStorageType) .set_attr<nnvm::FGradient>("FGradient", ElemwiseGradUseIn{"_backward_contrib_boolean_mask"}) .add_argument("data", "NDArray-or-Symbol", "Data") .add_argument("index", "NDArray-or-Symbol", "Mask") .add_arguments(BooleanMaskParam::__FIELDS__()); NNVM_REGISTER_OP(_backward_contrib_boolean_mask) .set_num_inputs(3) .set_num_outputs(2) .set_attr<nnvm::TIsBackward>("TIsBackward", true) .set_attr<FInferStorageType>("FInferStorageType", BooleanMaskBackStorageType) .set_attr<FComputeEx>("FComputeEx<cpu>", BooleanMaskBackward<cpu>) .add_arguments(BooleanMaskParam::__FIELDS__()); } // namespace op } // namespace mxnet
{ "content_hash": "247eb5f3a8e721283c04ddd5f53e7e43", "timestamp": "", "source": "github", "line_count": 209, "max_line_length": 92, "avg_line_length": 36.952153110047846, "alnum_prop": 0.5957529457464715, "repo_name": "yajiedesign/mxnet", "id": "882984430d52a55bad830673b72f6d1dc8a1e154", "size": "8530", "binary": false, "copies": "3", "ref": "refs/heads/master", "path": "src/operator/contrib/boolean_mask.cc", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "ANTLR", "bytes": "1731" }, { "name": "Batchfile", "bytes": "13130" }, { "name": "C", "bytes": "225563" }, { "name": "C++", "bytes": "9102719" }, { "name": "CMake", "bytes": "114981" }, { "name": "Clojure", "bytes": "622652" }, { "name": "Cuda", "bytes": "1260187" }, { "name": "Dockerfile", "bytes": "100732" }, { "name": "Groovy", "bytes": "169843" }, { "name": "HTML", "bytes": "40277" }, { "name": "Java", "bytes": "205196" }, { "name": "Julia", "bytes": "445413" }, { "name": "Jupyter Notebook", "bytes": "3660357" }, { "name": "MATLAB", "bytes": "34903" }, { "name": "Makefile", "bytes": "192016" }, { "name": "Perl", "bytes": "1553283" }, { "name": "PowerShell", "bytes": "13906" }, { "name": "Python", "bytes": "9257748" }, { "name": "R", "bytes": "357994" }, { "name": "Raku", "bytes": "7280" }, { "name": "SWIG", "bytes": "140109" }, { "name": "Scala", "bytes": "1304526" }, { "name": "Shell", "bytes": "458315" }, { "name": "Smalltalk", "bytes": "3497" } ], "symlink_target": "" }
using NJsonSchema; using System; using System.Collections.Generic; using System.Text; namespace Threax.AspNetCore.Halcyon.Ext { /// <summary> /// This class adds extensions to json schema for code generation. /// </summary> public static class SchemaExtensions { private const String IsArrayExt = "x-is-array"; private const string DataIsFormExt = "x-data-is-form"; private const string RawResponseExt = "x-raw-response"; /// <summary> /// Set that a particular field is an array or array-like value /// </summary> /// <param name="schema"></param> /// <param name="value"></param> public static void SetIsArray(this JsonSchema4 schema, bool value) { SetExtension(schema, IsArrayExt, value); } /// <summary> /// Determine if a particular field is an array. /// </summary> /// <param name="schema"></param> /// <returns></returns> public static bool IsArray(this JsonSchema4 schema) { return IsExtensionTrue(schema, IsArrayExt); } /// <summary> /// Set this to true to send the request data as form data instead of json. /// </summary> /// <param name="schema"></param> /// <param name="value"></param> public static void SetDataIsForm(this JsonSchema4 schema, bool value) { SetExtension(schema, DataIsFormExt, value); } /// <summary> /// This will be true if data should be sent as form data. /// </summary> /// <param name="schema"></param> /// <returns></returns> public static bool DataIsForm(this JsonSchema4 schema) { return IsExtensionTrue(schema, DataIsFormExt); } /// <summary> /// Set this to true to mark the response as a raw http response instead of a halcyon json object. /// </summary> /// <param name="schema"></param> /// <param name="value"></param> public static void SetRawResponse(this JsonSchema4 schema, bool value) { SetExtension(schema, RawResponseExt, value); } /// <summary> /// This will be true if the link returns a raw response instead of a halcyon json object. /// </summary> /// <param name="schema"></param> /// <returns></returns> public static bool IsRawResponse(this JsonSchema4 schema) { return IsExtensionTrue(schema, RawResponseExt); } /// <summary> /// Set an extension to value, will ensure everything is safe to do. /// </summary> /// <param name="schema"></param> /// <param name="key"></param> /// <param name="value"></param> private static void SetExtension(this JsonSchema4 schema, String key, bool value) { EnsureExtensionData(schema); schema.ExtensionData.Add(key, value); } /// <summary> /// Determine if an extension is set to true. This will only be true if extension data exists on the schema, /// the schema has the given extension key and that extension key's value is set to true. /// </summary> /// <param name="schema"></param> /// <param name="key"></param> /// <returns></returns> public static bool IsExtensionTrue(this JsonSchema4 schema, String key) { object value; if (schema.ExtensionData != null && schema.ExtensionData.TryGetValue(key, out value)) { bool? result = value as bool?; if (result != null && result.HasValue) { return result.Value; } } return false; } private static void EnsureExtensionData(JsonSchema4 schema) { if (schema.ExtensionData == null) { schema.ExtensionData = new Dictionary<String, Object>(); } } } }
{ "content_hash": "2b224470e7200f681361f28e6608b283", "timestamp": "", "source": "github", "line_count": 118, "max_line_length": 116, "avg_line_length": 34.779661016949156, "alnum_prop": 0.5582358674463938, "repo_name": "threax/Threax.AspNetCore.Convention", "id": "50c39eee4a95efd11fcc4bc142443e2fbe40c759", "size": "4106", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/Threax.AspNetCore.Halcyon.Ext/SchemaExtensions.cs", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Batchfile", "bytes": "200" }, { "name": "C#", "bytes": "1610794" }, { "name": "CSS", "bytes": "3" }, { "name": "HTML", "bytes": "13326" }, { "name": "JavaScript", "bytes": "3902" }, { "name": "TypeScript", "bytes": "71627" } ], "symlink_target": "" }
package org.apache.hadoop.hive.ql.parse.repl.load.message; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.fs.FileSystem; import org.apache.hadoop.fs.Path; import org.apache.hadoop.hive.conf.HiveConf; import org.apache.hadoop.hive.metastore.api.Function; import org.apache.hadoop.hive.metastore.api.ResourceType; import org.apache.hadoop.hive.metastore.api.ResourceUri; import org.apache.hadoop.hive.ql.exec.ReplCopyTask; import org.apache.hadoop.hive.ql.exec.Task; import org.apache.hadoop.hive.ql.parse.ReplicationSpec; import org.apache.hadoop.hive.ql.parse.SemanticException; import org.apache.hadoop.hive.ql.parse.repl.load.MetaData; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mock; import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.modules.junit4.PowerMockRunner; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.IOException; import java.net.URI; import java.net.URISyntaxException; import static org.apache.hadoop.hive.ql.parse.repl.load.message.CreateFunctionHandler.PrimaryToReplicaResourceFunction; import static org.apache.hadoop.hive.ql.parse.repl.load.message.MessageHandler.Context; import static org.hamcrest.CoreMatchers.equalTo; import static org.hamcrest.CoreMatchers.is; import static org.junit.Assert.assertThat; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.mock; import static org.powermock.api.mockito.PowerMockito.mockStatic; import static org.powermock.api.mockito.PowerMockito.when; @RunWith(PowerMockRunner.class) @PrepareForTest({ PrimaryToReplicaResourceFunction.class, FileSystem.class, ReplCopyTask.class, System.class }) public class TestPrimaryToReplicaResourceFunction { private PrimaryToReplicaResourceFunction function; @Mock private HiveConf hiveConf; @Mock private Function functionObj; @Mock private FileSystem mockFs; private static Logger logger = LoggerFactory.getLogger(TestPrimaryToReplicaResourceFunction.class); @Before public void setup() { MetaData metadata = new MetaData(null, null, null, null, functionObj); Context context = new Context("primaryDb", null, null, null, hiveConf, null, null, logger); when(hiveConf.getVar(HiveConf.ConfVars.REPL_FUNCTIONS_ROOT_DIR)) .thenReturn("/someBasePath/withADir/"); function = new PrimaryToReplicaResourceFunction(context, metadata, "replicaDbName"); } @Test public void createDestinationPath() throws IOException, SemanticException, URISyntaxException { mockStatic(FileSystem.class); when(FileSystem.get(any(Configuration.class))).thenReturn(mockFs); when(FileSystem.get(any(URI.class), any(Configuration.class))).thenReturn(mockFs); when(mockFs.getScheme()).thenReturn("hdfs"); when(mockFs.getUri()).thenReturn(new URI("hdfs", "somehost:9000", null, null, null)); mockStatic(System.class); // when(System.nanoTime()).thenReturn(Long.MAX_VALUE); when(functionObj.getFunctionName()).thenReturn("someFunctionName"); mockStatic(ReplCopyTask.class); Task mock = mock(Task.class); when(ReplCopyTask.getLoadCopyTask(any(ReplicationSpec.class), any(Path.class), any(Path.class), any(HiveConf.class))).thenReturn(mock); ResourceUri resourceUri = function.destinationResourceUri(new ResourceUri(ResourceType.JAR, "hdfs://localhost:9000/user/someplace/ab.jar#e094828883")); assertThat(resourceUri.getUri(), is(equalTo( "hdfs://somehost:9000/someBasePath/withADir/replicadbname/somefunctionname/" + String .valueOf(0L) + "/ab.jar"))); } }
{ "content_hash": "1d3fc16ef5419d230253e9f1752053cd", "timestamp": "", "source": "github", "line_count": 89, "max_line_length": 119, "avg_line_length": 41.50561797752809, "alnum_prop": 0.7731456415809421, "repo_name": "vineetgarg02/hive", "id": "faba6e4caa6796ccb93e8c1716f5db36f107d750", "size": "4499", "binary": false, "copies": "3", "ref": "refs/heads/master", "path": "ql/src/test/org/apache/hadoop/hive/ql/parse/repl/load/message/TestPrimaryToReplicaResourceFunction.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "ANTLR", "bytes": "54376" }, { "name": "Batchfile", "bytes": "845" }, { "name": "C", "bytes": "28218" }, { "name": "C++", "bytes": "45308" }, { "name": "CSS", "bytes": "5157" }, { "name": "GAP", "bytes": "179697" }, { "name": "HTML", "bytes": "58711" }, { "name": "HiveQL", "bytes": "7606577" }, { "name": "Java", "bytes": "53149057" }, { "name": "JavaScript", "bytes": "43855" }, { "name": "M4", "bytes": "2276" }, { "name": "PHP", "bytes": "148097" }, { "name": "PLSQL", "bytes": "5261" }, { "name": "PLpgSQL", "bytes": "302587" }, { "name": "Perl", "bytes": "319842" }, { "name": "PigLatin", "bytes": "12333" }, { "name": "Python", "bytes": "408662" }, { "name": "Roff", "bytes": "5379" }, { "name": "SQLPL", "bytes": "409" }, { "name": "Shell", "bytes": "299497" }, { "name": "TSQL", "bytes": "2560286" }, { "name": "Thrift", "bytes": "144733" }, { "name": "XSLT", "bytes": "20199" }, { "name": "q", "bytes": "320552" } ], "symlink_target": "" }
#include "xenia/kernel/xboxkrnl_module.h" #include <gflags/gflags.h> #include "poly/math.h" #include "xenia/emulator.h" #include "xenia/export_resolver.h" #include "xenia/kernel/kernel_state.h" #include "xenia/kernel/xboxkrnl_private.h" #include "xenia/kernel/objects/xuser_module.h" DEFINE_bool(abort_before_entry, false, "Abort execution right before launching the module."); namespace xe { namespace kernel { XboxkrnlModule::XboxkrnlModule(Emulator* emulator, KernelState* kernel_state) : XKernelModule(kernel_state, "xe:\\xboxkrnl.exe"), timestamp_timer_(nullptr) { RegisterExportTable(export_resolver_); // Register all exported functions. xboxkrnl::RegisterAudioExports(export_resolver_, kernel_state_); xboxkrnl::RegisterAudioXmaExports(export_resolver_, kernel_state_); xboxkrnl::RegisterDebugExports(export_resolver_, kernel_state_); xboxkrnl::RegisterHalExports(export_resolver_, kernel_state_); xboxkrnl::RegisterIoExports(export_resolver_, kernel_state_); xboxkrnl::RegisterMemoryExports(export_resolver_, kernel_state_); xboxkrnl::RegisterMiscExports(export_resolver_, kernel_state_); xboxkrnl::RegisterModuleExports(export_resolver_, kernel_state_); xboxkrnl::RegisterObExports(export_resolver_, kernel_state_); xboxkrnl::RegisterRtlExports(export_resolver_, kernel_state_); xboxkrnl::RegisterStringExports(export_resolver_, kernel_state_); xboxkrnl::RegisterThreadingExports(export_resolver_, kernel_state_); xboxkrnl::RegisterUsbcamExports(export_resolver_, kernel_state_); xboxkrnl::RegisterVideoExports(export_resolver_, kernel_state_); uint8_t* mem = memory_->membase(); // KeDebugMonitorData (?*) // Set to a valid value when a remote debugger is attached. // Offset 0x18 is a 4b pointer to a handler function that seems to take two // arguments. If we wanted to see what would happen we could fake that. uint32_t pKeDebugMonitorData = (uint32_t)memory_->HeapAlloc(0, 256, 0); export_resolver_->SetVariableMapping( "xboxkrnl.exe", ordinals::KeDebugMonitorData, pKeDebugMonitorData); poly::store_and_swap<uint32_t>(mem + pKeDebugMonitorData, 0); // KeCertMonitorData (?*) // Always set to zero, ignored. uint32_t pKeCertMonitorData = (uint32_t)memory_->HeapAlloc(0, 4, 0); export_resolver_->SetVariableMapping( "xboxkrnl.exe", ordinals::KeCertMonitorData, pKeCertMonitorData); poly::store_and_swap<uint32_t>(mem + pKeCertMonitorData, 0); // XboxHardwareInfo (XboxHardwareInfo_t, 16b) // flags cpu# ? ? ? ? ? ? // 0x00000000, 0x06, 0x00, 0x00, 0x00, 0x00000000, 0x0000, 0x0000 // Games seem to check if bit 26 (0x20) is set, which at least for xbox1 // was whether an HDD was present. Not sure what the other flags are. // // aomega08 says the value is 0x02000817, bit 27: debug mode on. // When that is set, though, allocs crash in weird ways. uint32_t pXboxHardwareInfo = (uint32_t)memory_->HeapAlloc(0, 16, 0); export_resolver_->SetVariableMapping( "xboxkrnl.exe", ordinals::XboxHardwareInfo, pXboxHardwareInfo); poly::store_and_swap<uint32_t>(mem + pXboxHardwareInfo + 0, 0); // flags poly::store_and_swap<uint8_t>(mem + pXboxHardwareInfo + 4, 0x06); // cpu count // Remaining 11b are zeroes? // XexExecutableModuleHandle (?**) // Games try to dereference this to get a pointer to some module struct. // So far it seems like it's just in loader code, and only used to look up // the XexHeaderBase for use by RtlImageXexHeaderField. // We fake it so that the address passed to that looks legit. // 0x80100FFC <- pointer to structure // 0x80101000 <- our module structure // 0x80101058 <- pointer to xex header // 0x80101100 <- xex header base uint32_t ppXexExecutableModuleHandle = (uint32_t)memory_->HeapAlloc(0, 4, 0); export_resolver_->SetVariableMapping("xboxkrnl.exe", ordinals::XexExecutableModuleHandle, ppXexExecutableModuleHandle); uint32_t pXexExecutableModuleHandle = (uint32_t)memory_->HeapAlloc(0, 256, 0); poly::store_and_swap<uint32_t>(mem + ppXexExecutableModuleHandle, pXexExecutableModuleHandle); poly::store_and_swap<uint32_t>(mem + pXexExecutableModuleHandle + 0x58, 0x80101100); // ExLoadedCommandLine (char*) // The name of the xex. Not sure this is ever really used on real devices. // Perhaps it's how swap disc/etc data is sent? // Always set to "default.xex" (with quotes) for now. uint32_t pExLoadedCommandLine = (uint32_t)memory_->HeapAlloc(0, 1024, 0); export_resolver_->SetVariableMapping( "xboxkrnl.exe", ordinals::ExLoadedCommandLine, pExLoadedCommandLine); char command_line[] = "\"default.xex\""; memcpy(mem + pExLoadedCommandLine, command_line, poly::countof(command_line) + 1); // XboxKrnlVersion (8b) // Kernel version, looks like 2b.2b.2b.2b. // I've only seen games check >=, so we just fake something here. uint32_t pXboxKrnlVersion = (uint32_t)memory_->HeapAlloc(0, 8, 0); export_resolver_->SetVariableMapping( "xboxkrnl.exe", ordinals::XboxKrnlVersion, pXboxKrnlVersion); poly::store_and_swap<uint16_t>(mem + pXboxKrnlVersion + 0, 2); poly::store_and_swap<uint16_t>(mem + pXboxKrnlVersion + 2, 0xFFFF); poly::store_and_swap<uint16_t>(mem + pXboxKrnlVersion + 4, 0xFFFF); poly::store_and_swap<uint8_t>(mem + pXboxKrnlVersion + 6, 0x80); poly::store_and_swap<uint8_t>(mem + pXboxKrnlVersion + 7, 0x00); // KeTimeStampBundle (ad) // This must be updated during execution, at 1ms intevals. // We setup a system timer here to do that. uint32_t pKeTimeStampBundle = (uint32_t)memory_->HeapAlloc(0, 24, 0); export_resolver_->SetVariableMapping( "xboxkrnl.exe", ordinals::KeTimeStampBundle, pKeTimeStampBundle); poly::store_and_swap<uint64_t>(mem + pKeTimeStampBundle + 0, 0); poly::store_and_swap<uint64_t>(mem + pKeTimeStampBundle + 8, 0); poly::store_and_swap<uint32_t>(mem + pKeTimeStampBundle + 16, GetTickCount()); poly::store_and_swap<uint32_t>(mem + pKeTimeStampBundle + 20, 0); CreateTimerQueueTimer(&timestamp_timer_, nullptr, [](PVOID param, BOOLEAN timer_or_wait_fired) { auto timestamp_bundle = reinterpret_cast<uint8_t*>(param); poly::store_and_swap<uint32_t>(timestamp_bundle + 16, GetTickCount()); }, mem + pKeTimeStampBundle, 0, 1, // 1ms WT_EXECUTEINTIMERTHREAD); } void XboxkrnlModule::RegisterExportTable(ExportResolver* export_resolver) { assert_not_null(export_resolver); if (!export_resolver) { return; } // Build the export table used for resolution. #include "xenia/kernel/util/export_table_pre.inc" static KernelExport xboxkrnl_export_table[] = { #include "xenia/kernel/xboxkrnl_table.inc" }; #include "xenia/kernel/util/export_table_post.inc" export_resolver->RegisterTable("xboxkrnl.exe", xboxkrnl_export_table, poly::countof(xboxkrnl_export_table)); } XboxkrnlModule::~XboxkrnlModule() { DeleteTimerQueueTimer(nullptr, timestamp_timer_, nullptr); } int XboxkrnlModule::LaunchModule(const char* path) { // Create and register the module. We keep it local to this function and // dispose it on exit. XUserModule* module = new XUserModule(kernel_state_, path); // Load the module into memory from the filesystem. X_STATUS result_code = module->LoadFromFile(path); if (XFAILED(result_code)) { XELOGE("Failed to load module %s: %.8X", path, result_code); module->Release(); return 1; } // Set as the main module, while running. kernel_state_->SetExecutableModule(module); if (FLAGS_abort_before_entry) { XELOGI("--abort_before_entry causing an early exit"); module->Release(); return 0; } // Launch the module. // NOTE: this won't return until the module exits. result_code = module->Launch(0); kernel_state_->SetExecutableModule(NULL); if (XFAILED(result_code)) { XELOGE("Failed to launch module %s: %.8X", path, result_code); module->Release(); return 2; } module->Release(); return 0; } } // namespace kernel } // namespace xe
{ "content_hash": "2fbd7841921a48f512f6ecfa9b86ce5f", "timestamp": "", "source": "github", "line_count": 197, "max_line_length": 80, "avg_line_length": 42.86294416243655, "alnum_prop": 0.6810753197536712, "repo_name": "woody2014/xenia", "id": "a7d336a321f772705e32f2766ca8235ffe2b950f", "size": "8931", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/xenia/kernel/xboxkrnl_module.cc", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "Assembly", "bytes": "95909" }, { "name": "C", "bytes": "26779" }, { "name": "C++", "bytes": "2562703" }, { "name": "Python", "bytes": "25815" }, { "name": "Shell", "bytes": "1703" } ], "symlink_target": "" }
title: AesiSyntaxHighlighter.createScopeName - aesi-intellij --- [aesi-intellij](../../index.html) / [org.metaborg.paplj.syntaxhighlighting](../index.html) / [AesiSyntaxHighlighter](index.html) / [createScopeName](.) # createScopeName `fun createScopeName(prefix: `[`String`](https://kotlinlang.org/api/latest/jvm/stdlib/kotlin/-string/index.html)`): `[`String`](https://kotlinlang.org/api/latest/jvm/stdlib/kotlin/-string/index.html)
{ "content_hash": "5ad17f9351afee3f0342af360965ac98", "timestamp": "", "source": "github", "line_count": 8, "max_line_length": 199, "avg_line_length": 54.625, "alnum_prop": 0.7482837528604119, "repo_name": "Virtlink/aesi", "id": "b6cee0a736566dbc7bbb856e1ffbf1bab366c8a0", "size": "441", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "docs/aesi-intellij/org.metaborg.paplj.syntaxhighlighting/-aesi-syntax-highlighter/create-scope-name.md", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "ANTLR", "bytes": "3802" }, { "name": "HTML", "bytes": "1865" }, { "name": "Java", "bytes": "116648" }, { "name": "Kotlin", "bytes": "297889" }, { "name": "Makefile", "bytes": "7433" }, { "name": "Shell", "bytes": "77" } ], "symlink_target": "" }
<?php namespace z1haze\Acl\Traits; trait HasAcl { use UserOnly, UserAndLevel, UserAndPermission; }
{ "content_hash": "1b7b8211bd55383f25b5a2b981e17008", "timestamp": "", "source": "github", "line_count": 8, "max_line_length": 50, "avg_line_length": 13, "alnum_prop": 0.75, "repo_name": "z1haze/laravel-acl", "id": "04631e081fb84cf036d804f63ccc6a6d5fabc348", "size": "104", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/z1haze/Acl/Traits/HasAcl.php", "mode": "33188", "license": "mit", "language": [ { "name": "PHP", "bytes": "90373" } ], "symlink_target": "" }
"""This module acts as a bridge to the sector models from the controller The :class:`SectorModel` exposes several key methods for running wrapped sector models. To add a sector model to an instance of the framework, first implement :class:`SectorModel`. Key Functions ============= This class performs several key functions which ease the integration of sector models into the system-of-systems framework. The user must implement the various abstract functions throughout the class to provide an interface to the sector model, which can be called upon by the framework. From the model's perspective, :class:`SectorModel` provides a bridge from the sector-specific problem representation to the general representation which allows reasoning across infrastructure systems. The key functions include: * converting input/outputs to/from geographies/temporal resolutions * converting control vectors from the decision layer of the framework, to asset Interventions specific to the sector model * returning scalar/vector values to the framework to enable measurements of performance, particularly for the purposes of optimisation and rule-based approaches """ from smif.model.model import Model __author__ = "Will Usher, Tom Russell" __copyright__ = "Will Usher, Tom Russell" __license__ = "mit" class SectorModel(Model): """A representation of the sector model with inputs and outputs Implement this class to enable integration of the wrapped simulation model into a system-of-system model. Arguments --------- name : str The unique name of the sector model Notes ----- Implement the various abstract functions throughout the class to provide an interface to the simulation model, which can then be called upon by the framework. The key methods in the SectorModel class which must be overridden are: - :py:meth:`SectorModel.simulate` - :py:meth:`SectorModel.extract_obj` An implementation may also override: - :py:meth:`SectorModel.before_model_run` """ def __init__(self, name): super().__init__(name) def before_model_run(self, data): """Implement this method to conduct pre-model run tasks Arguments --------- data: smif.data_layer.DataHandle Access parameter values (before any model is run, no dependency input data or state is guaranteed to be available) Access decision/system state (i.e. initial_conditions) """ def simulate(self, data): """Implement this method to run the model Arguments --------- data: smif.data_layer.DataHandle Access state, parameter values, dependency inputs, results and interventions Notes ----- See docs on :class:`~smif.data_layer.data_handle.DataHandle` for details of how to access inputs, parameters and state and how to set results. ``interval`` should reference an id from the interval set corresponding to the output parameter, as specified in model configuration ``region`` should reference a region name from the region set corresponding to the output parameter, as specified in model configuration To obtain simulation model data in this method, use the methods such as:: parameter_value = data.get_parameter('my_parameter_name') Other useful methods are :meth:`~smif.data_layer.data_handle.DataHandle.get_base_timestep_data`, :meth:`~smif.data_layer.data_handle.DataHandle.get_previous_timestep_data`, :meth:`~smif.data_layer.data_handle.DataHandle.get_parameter`, :meth:`~smif.data_layer.data_handle.DataHandle.get_data`, :meth:`~smif.data_layer.data_handle.DataHandle.get_parameters` and :meth:`~smif.data_layer.data_handle.DataHandle.get_results`. :meth:`~smif.data_layer.data_handle.DataHandle.get_state` returns a list of intervention dict for the current timestep :meth:`~smif.data_layer.data_handle.DataHandle.get_current_interventions` returns a list of dict where each dict is an intervention """
{ "content_hash": "69053f82bd2f5f8d0f370f9d79197128", "timestamp": "", "source": "github", "line_count": 115, "max_line_length": 90, "avg_line_length": 36.78260869565217, "alnum_prop": 0.6957446808510638, "repo_name": "tomalrussell/smif", "id": "be13824c04fc627c629b3c3024ccd76d554a54d4", "size": "4254", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "src/smif/model/sector_model.py", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "3104" }, { "name": "HTML", "bytes": "317" }, { "name": "JavaScript", "bytes": "329900" }, { "name": "Python", "bytes": "898074" }, { "name": "Shell", "bytes": "2593" }, { "name": "TSQL", "bytes": "1259" } ], "symlink_target": "" }
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta name="generator" content="rustdoc"> <meta name="description" content="API documentation for the Rust `mango_smoothie` crate."> <meta name="keywords" content="rust, rustlang, rust-lang, mango_smoothie"> <title>mango_smoothie - Rust</title> <link rel="stylesheet" type="text/css" href="../normalize.css"> <link rel="stylesheet" type="text/css" href="../rustdoc.css"> <link rel="stylesheet" type="text/css" href="../main.css"> </head> <body class="rustdoc"> <!--[if lte IE 8]> <div class="warning"> This old browser is unsupported and will most likely display funky things. </div> <![endif]--> <nav class="sidebar"> <p class='location'></p><script>window.sidebarCurrent = {name: 'mango_smoothie', ty: 'mod', relpath: '../'};</script> </nav> <nav class="sub"> <form class="search-form js-only"> <div class="search-container"> <input class="search-input" name="search" autocomplete="off" placeholder="Click or press ‘S’ to search, ‘?’ for more options…" type="search"> </div> </form> </nav> <section id='main' class="content mod"> <h1 class='fqn'><span class='in-band'>Crate <a class='mod' href=''>mango_smoothie</a></span><span class='out-of-band'><span id='render-detail'> <a id="toggle-all-docs" href="javascript:void(0)" title="collapse all docs"> [<span class='inner'>&#x2212;</span>] </a> </span><a class='srclink' href='../src/mango_smoothie/lib.rs.html#1-73' title='goto source code'>[src]</a></span></h1> <div class='docblock'><p>Mango Smoothie Mango Smoothie is a <a href="http://docs.couchdb.org/en/latest/api/database/find.html">CouchDB Mango</a> / <a href="https://docs.cloudant.com/cloudant_query.html">Cloudant Query</a> client library.</p> <h1 id='create-indexes' class='section-header'><a href='#create-indexes'>Create Indexes</a></h1> <p>To create an index first specify the url to the CouchDB/Cloudant instance, then specify the fields to be indexed.</p> <pre class='rust rust-example-rendered'> <span class='kw'>extern</span> <span class='kw'>crate</span> <span class='ident'>mango_smoothie</span>; <span class='kw'>use</span> <span class='ident'>mango_smoothie</span>::{<span class='ident'>database</span>}; <span class='kw'>let</span> <span class='ident'>resp</span> <span class='op'>=</span> <span class='ident'>database</span>(<span class='string'>&quot;http://tester:testerpass@127.0.0.1:5984/animaldb&quot;</span>).<span class='ident'>unwrap</span>() .<span class='ident'>create_index</span>(<span class='kw-2'>&amp;</span>[<span class='string'>&quot;class&quot;</span>, <span class='string'>&quot;name&quot;</span>]);</pre> <h1 id='view-indexes' class='section-header'><a href='#view-indexes'>View Indexes</a></h1> <p>To list all the available indexes do the following:</p> <pre class='rust rust-example-rendered'> <span class='kw'>let</span> <span class='ident'>indexes</span> <span class='op'>=</span> <span class='ident'>database</span>(<span class='string'>&quot;http://tester:testerpass@127.0.0.1:5984/animaldb&quot;</span>).<span class='ident'>unwrap</span>() .<span class='ident'>list_indexes</span>().<span class='ident'>unwrap</span>(); <span class='macro'>assert</span><span class='macro'>!</span>(<span class='ident'>indexes</span>.<span class='ident'>total_rows</span> <span class='op'>&gt;</span> <span class='number'>0</span>); <span class='macro'>assert_eq</span><span class='macro'>!</span>(<span class='ident'>indexes</span>.<span class='ident'>indexes</span>[<span class='number'>0</span>].<span class='ident'>name</span>, <span class='string'>&quot;_all_docs&quot;</span>.<span class='ident'>to_string</span>()); <span class='macro'>assert</span><span class='macro'>!</span>(<span class='ident'>indexes</span>.<span class='ident'>indexes</span>[<span class='number'>0</span>].<span class='ident'>def</span>.<span class='ident'>fields</span>[<span class='number'>0</span>].<span class='ident'>contains_key</span>(<span class='kw-2'>&amp;</span><span class='string'>&quot;_id&quot;</span>.<span class='ident'>to_string</span>()));</pre> <h1 id='query-indexes' class='section-header'><a href='#query-indexes'>Query Indexes</a></h1> <p>Mango Smoothie uses the <a href="https://docs.serde.rs/serde_json/">serde_json</a> macro to help with querying indexes.</p> <pre class='rust rust-example-rendered'> <span class='kw'>extern</span> <span class='kw'>crate</span> <span class='ident'>mango_smoothie</span>; <span class='kw'>use</span> <span class='ident'>mango_smoothie</span>::{<span class='ident'>database</span>}; <span class='attribute'>#[<span class='ident'>macro_use</span>]</span> <span class='kw'>extern</span> <span class='kw'>crate</span> <span class='ident'>serde_json</span>; <span class='kw'>let</span> <span class='ident'>query</span> <span class='op'>=</span> <span class='macro'>json</span><span class='macro'>!</span>({ <span class='string'>&quot;selector&quot;</span>: { <span class='string'>&quot;_id&quot;</span>: { <span class='string'>&quot;$gt&quot;</span>: <span class='string'>&quot;1&quot;</span> } }, <span class='string'>&quot;fields&quot;</span>: [<span class='string'>&quot;_id&quot;</span>, <span class='string'>&quot;name&quot;</span>], <span class='string'>&quot;skip&quot;</span>: <span class='number'>3</span>, <span class='string'>&quot;sort&quot;</span>: [{<span class='string'>&quot;_id&quot;</span>: <span class='string'>&quot;asc&quot;</span>}] }); <span class='kw'>let</span> <span class='ident'>query_resp</span> <span class='op'>=</span> <span class='ident'>db</span>.<span class='ident'>query_index</span>(<span class='ident'>query</span>).<span class='ident'>unwrap</span>(); <span class='macro'>assert_eq</span><span class='macro'>!</span>(<span class='ident'>result</span>.<span class='ident'>docs</span>.<span class='ident'>len</span>(), <span class='number'>5</span>); <span class='kw'>let</span> <span class='ident'>doc</span> <span class='op'>=</span> <span class='kw-2'>&amp;</span><span class='ident'>result</span>.<span class='ident'>docs</span>[<span class='number'>0</span>]; <span class='macro'>assert_eq</span><span class='macro'>!</span>(<span class='ident'>doc</span>.<span class='ident'>get</span>(<span class='string'>&quot;class&quot;</span>).<span class='ident'>unwrap</span>().<span class='ident'>as_str</span>().<span class='ident'>unwrap</span>(), <span class='string'>&quot;mammal&quot;</span>);</pre> </div><h2 id='modules' class='section-header'><a href="#modules">Modules</a></h2> <table> <tr class=' module-item'> <td><a class='mod' href='errors/index.html' title='mango_smoothie::errors'>errors</a></td> <td class='docblock-short'> </td> </tr> <tr class=' module-item'> <td><a class='mod' href='http/index.html' title='mango_smoothie::http'>http</a></td> <td class='docblock-short'> </td> </tr></table><h2 id='functions' class='section-header'><a href="#functions">Functions</a></h2> <table> <tr class=' module-item'> <td><a class='fn' href='fn.database.html' title='mango_smoothie::database'>database</a></td> <td class='docblock-short'> <p>The entry point for each Mango Smoothie request</p> </td> </tr></table></section> <section id='search' class="content hidden"></section> <section class="footer"></section> <aside id="help" class="hidden"> <div> <h1 class="hidden">Help</h1> <div class="shortcuts"> <h2>Keyboard Shortcuts</h2> <dl> <dt>?</dt> <dd>Show this help dialog</dd> <dt>S</dt> <dd>Focus the search field</dd> <dt>&larrb;</dt> <dd>Move up in search results</dd> <dt>&rarrb;</dt> <dd>Move down in search results</dd> <dt>&#9166;</dt> <dd>Go to active search result</dd> <dt>+</dt> <dd>Collapse/expand all sections</dd> </dl> </div> <div class="infos"> <h2>Search Tricks</h2> <p> Prefix searches with a type followed by a colon (e.g. <code>fn:</code>) to restrict the search to a given type. </p> <p> Accepted types are: <code>fn</code>, <code>mod</code>, <code>struct</code>, <code>enum</code>, <code>trait</code>, <code>type</code>, <code>macro</code>, and <code>const</code>. </p> <p> Search functions by type signature (e.g. <code>vec -> usize</code> or <code>* -> vec</code>) </p> </div> </div> </aside> <script> window.rootPath = "../"; window.currentCrate = "mango_smoothie"; </script> <script src="../jquery.js"></script> <script src="../main.js"></script> <script defer src="../search-index.js"></script> </body> </html>
{ "content_hash": "4e64bb4cbf51c7abdac7d1467beeb4c6", "timestamp": "", "source": "github", "line_count": 187, "max_line_length": 423, "avg_line_length": 53.93048128342246, "alnum_prop": 0.5626177491323748, "repo_name": "garrensmith/mango_smoothie", "id": "5b56dac0d97d29242f6904820060f7faf6cfb0c8", "size": "10095", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "docs/mango_smoothie/index.html", "mode": "33188", "license": "mit", "language": [ { "name": "JavaScript", "bytes": "3488" }, { "name": "Makefile", "bytes": "150" }, { "name": "Rust", "bytes": "11790" } ], "symlink_target": "" }
package org.apache.hadoop.yarn.client.cli; import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import org.apache.hadoop.classification.InterfaceAudience.Private; import org.apache.hadoop.classification.InterfaceStability.Unstable; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.fs.CommonConfigurationKeys; import org.apache.hadoop.ha.HAAdmin; import org.apache.hadoop.ha.HAServiceTarget; import org.apache.hadoop.ipc.RemoteException; import org.apache.hadoop.security.UserGroupInformation; import org.apache.hadoop.util.ToolRunner; import org.apache.hadoop.yarn.api.records.NodeId; import org.apache.hadoop.yarn.client.ClientRMProxy; import org.apache.hadoop.yarn.client.RMHAServiceTarget; import org.apache.hadoop.yarn.conf.HAUtil; import org.apache.hadoop.yarn.conf.YarnConfiguration; import org.apache.hadoop.yarn.exceptions.YarnException; import org.apache.hadoop.yarn.exceptions.YarnRuntimeException; import org.apache.hadoop.yarn.factories.RecordFactory; import org.apache.hadoop.yarn.factory.providers.RecordFactoryProvider; import org.apache.hadoop.yarn.nodelabels.CommonNodeLabelsManager; import org.apache.hadoop.yarn.server.api.ResourceManagerAdministrationProtocol; import org.apache.hadoop.yarn.server.api.protocolrecords.AddToClusterNodeLabelsRequest; import org.apache.hadoop.yarn.server.api.protocolrecords.RefreshAdminAclsRequest; import org.apache.hadoop.yarn.server.api.protocolrecords.RefreshNodesRequest; import org.apache.hadoop.yarn.server.api.protocolrecords.RefreshQueuesRequest; import org.apache.hadoop.yarn.server.api.protocolrecords.RefreshServiceAclsRequest; import org.apache.hadoop.yarn.server.api.protocolrecords.RefreshSuperUserGroupsConfigurationRequest; import org.apache.hadoop.yarn.server.api.protocolrecords.RefreshUserToGroupsMappingsRequest; import org.apache.hadoop.yarn.server.api.protocolrecords.RemoveFromClusterNodeLabelsRequest; import org.apache.hadoop.yarn.server.api.protocolrecords.ReplaceLabelsOnNodeRequest; import org.apache.hadoop.yarn.util.ConverterUtils; import com.google.common.collect.ImmutableMap; @Private @Unstable public class RMAdminCLI extends HAAdmin { private final RecordFactory recordFactory = RecordFactoryProvider.getRecordFactory(null); private boolean directlyAccessNodeLabelStore = false; static CommonNodeLabelsManager localNodeLabelsManager = null; protected final static Map<String, UsageInfo> ADMIN_USAGE = ImmutableMap.<String, UsageInfo>builder() .put("-refreshQueues", new UsageInfo("", "Reload the queues' acls, states and scheduler specific " + "properties. \n\t\tResourceManager will reload the " + "mapred-queues configuration file.")) .put("-refreshNodes", new UsageInfo("", "Refresh the hosts information at the ResourceManager.")) .put("-refreshSuperUserGroupsConfiguration", new UsageInfo("", "Refresh superuser proxy groups mappings")) .put("-refreshUserToGroupsMappings", new UsageInfo("", "Refresh user-to-groups mappings")) .put("-refreshAdminAcls", new UsageInfo("", "Refresh acls for administration of ResourceManager")) .put("-refreshServiceAcl", new UsageInfo("", "Reload the service-level authorization policy file. \n\t\t" + "ResoureceManager will reload the authorization policy file.")) .put("-getGroups", new UsageInfo("[username]", "Get the groups which given user belongs to.")) .put("-help", new UsageInfo("[cmd]", "Displays help for the given command or all commands if none " + "is specified.")) .put("-addToClusterNodeLabels", new UsageInfo("[label1,label2,label3] (label splitted by \",\")", "add to cluster node labels ")) .put("-removeFromClusterNodeLabels", new UsageInfo("[label1,label2,label3] (label splitted by \",\")", "remove from cluster node labels")) .put("-replaceLabelsOnNode", new UsageInfo("[node1:port,label1,label2 node2:port,label1,label2]", "replace labels on nodes")) .put("-directlyAccessNodeLabelStore", new UsageInfo("", "Directly access node label store, " + "with this option, all node label related operations" + " will not connect RM. Instead, they will" + " access/modify stored node labels directly." + " By default, it is false (access via RM)." + " AND PLEASE NOTE: if you configured" + " yarn.node-labels.fs-store.root-dir to a local directory" + " (instead of NFS or HDFS), this option will only work" + " when the command run on the machine where RM is running.")) .build(); public RMAdminCLI() { super(); } public RMAdminCLI(Configuration conf) { super(conf); } private static void appendHAUsage(final StringBuilder usageBuilder) { for (String cmdKey : USAGE.keySet()) { if (cmdKey.equals("-help")) { continue; } UsageInfo usageInfo = USAGE.get(cmdKey); usageBuilder.append(" [" + cmdKey + " " + usageInfo.args + "]"); } } private static void buildHelpMsg(String cmd, StringBuilder builder) { UsageInfo usageInfo = ADMIN_USAGE.get(cmd); if (usageInfo == null) { usageInfo = USAGE.get(cmd); if (usageInfo == null) { return; } } String space = (usageInfo.args == "") ? "" : " "; builder.append(" " + cmd + space + usageInfo.args + ": " + usageInfo.help); } private static void buildIndividualUsageMsg(String cmd, StringBuilder builder ) { boolean isHACommand = false; UsageInfo usageInfo = ADMIN_USAGE.get(cmd); if (usageInfo == null) { usageInfo = USAGE.get(cmd); if (usageInfo == null) { return; } isHACommand = true; } String space = (usageInfo.args == "") ? "" : " "; builder.append("Usage: yarn rmadmin [" + cmd + space + usageInfo.args + "]\n"); if (isHACommand) { builder.append(cmd + " can only be used when RM HA is enabled"); } } private static void buildUsageMsg(StringBuilder builder, boolean isHAEnabled) { builder.append("Usage: yarn rmadmin\n"); for (String cmdKey : ADMIN_USAGE.keySet()) { UsageInfo usageInfo = ADMIN_USAGE.get(cmdKey); builder.append(" " + cmdKey + " " + usageInfo.args + "\n"); } if (isHAEnabled) { for (String cmdKey : USAGE.keySet()) { if (!cmdKey.equals("-help")) { UsageInfo usageInfo = USAGE.get(cmdKey); builder.append(" " + cmdKey + " " + usageInfo.args + "\n"); } } } } private static void printHelp(String cmd, boolean isHAEnabled) { StringBuilder summary = new StringBuilder(); summary.append("rmadmin is the command to execute YARN administrative " + "commands.\n"); summary.append("The full syntax is: \n\n" + "yarn rmadmin" + " [-refreshQueues]" + " [-refreshNodes]" + " [-refreshSuperUserGroupsConfiguration]" + " [-refreshUserToGroupsMappings]" + " [-refreshAdminAcls]" + " [-refreshServiceAcl]" + " [-getGroup [username]]" + " [-help [cmd]]"); if (isHAEnabled) { appendHAUsage(summary); } summary.append("\n"); StringBuilder helpBuilder = new StringBuilder(); System.out.println(summary); for (String cmdKey : ADMIN_USAGE.keySet()) { buildHelpMsg(cmdKey, helpBuilder); helpBuilder.append("\n"); } if (isHAEnabled) { for (String cmdKey : USAGE.keySet()) { if (!cmdKey.equals("-help")) { buildHelpMsg(cmdKey, helpBuilder); helpBuilder.append("\n"); } } } System.out.println(helpBuilder); System.out.println(); ToolRunner.printGenericCommandUsage(System.out); } /** * Displays format of commands. * @param cmd The command that is being executed. */ private static void printUsage(String cmd, boolean isHAEnabled) { StringBuilder usageBuilder = new StringBuilder(); if (ADMIN_USAGE.containsKey(cmd) || USAGE.containsKey(cmd)) { buildIndividualUsageMsg(cmd, usageBuilder); } else { buildUsageMsg(usageBuilder, isHAEnabled); } System.err.println(usageBuilder); ToolRunner.printGenericCommandUsage(System.err); } protected ResourceManagerAdministrationProtocol createAdminProtocol() throws IOException { // Get the current configuration final YarnConfiguration conf = new YarnConfiguration(getConf()); return ClientRMProxy.createRMProxy(conf, ResourceManagerAdministrationProtocol.class); } private int refreshQueues() throws IOException, YarnException { // Refresh the queue properties ResourceManagerAdministrationProtocol adminProtocol = createAdminProtocol(); RefreshQueuesRequest request = recordFactory.newRecordInstance(RefreshQueuesRequest.class); adminProtocol.refreshQueues(request); return 0; } private int refreshNodes() throws IOException, YarnException { // Refresh the nodes ResourceManagerAdministrationProtocol adminProtocol = createAdminProtocol(); RefreshNodesRequest request = recordFactory.newRecordInstance(RefreshNodesRequest.class); adminProtocol.refreshNodes(request); return 0; } private int refreshUserToGroupsMappings() throws IOException, YarnException { // Refresh the user-to-groups mappings ResourceManagerAdministrationProtocol adminProtocol = createAdminProtocol(); RefreshUserToGroupsMappingsRequest request = recordFactory.newRecordInstance(RefreshUserToGroupsMappingsRequest.class); adminProtocol.refreshUserToGroupsMappings(request); return 0; } private int refreshSuperUserGroupsConfiguration() throws IOException, YarnException { // Refresh the super-user groups ResourceManagerAdministrationProtocol adminProtocol = createAdminProtocol(); RefreshSuperUserGroupsConfigurationRequest request = recordFactory.newRecordInstance(RefreshSuperUserGroupsConfigurationRequest.class); adminProtocol.refreshSuperUserGroupsConfiguration(request); return 0; } private int refreshAdminAcls() throws IOException, YarnException { // Refresh the admin acls ResourceManagerAdministrationProtocol adminProtocol = createAdminProtocol(); RefreshAdminAclsRequest request = recordFactory.newRecordInstance(RefreshAdminAclsRequest.class); adminProtocol.refreshAdminAcls(request); return 0; } private int refreshServiceAcls() throws IOException, YarnException { // Refresh the service acls ResourceManagerAdministrationProtocol adminProtocol = createAdminProtocol(); RefreshServiceAclsRequest request = recordFactory.newRecordInstance(RefreshServiceAclsRequest.class); adminProtocol.refreshServiceAcls(request); return 0; } private int getGroups(String[] usernames) throws IOException { // Get groups users belongs to ResourceManagerAdministrationProtocol adminProtocol = createAdminProtocol(); if (usernames.length == 0) { usernames = new String[] { UserGroupInformation.getCurrentUser().getUserName() }; } for (String username : usernames) { StringBuilder sb = new StringBuilder(); sb.append(username + " :"); for (String group : adminProtocol.getGroupsForUser(username)) { sb.append(" "); sb.append(group); } System.out.println(sb); } return 0; } // Make it protected to make unit test can change it. protected static synchronized CommonNodeLabelsManager getNodeLabelManagerInstance(Configuration conf) { if (localNodeLabelsManager == null) { localNodeLabelsManager = new CommonNodeLabelsManager(); localNodeLabelsManager.init(conf); localNodeLabelsManager.start(); } return localNodeLabelsManager; } private int addToClusterNodeLabels(String args) throws IOException, YarnException { Set<String> labels = new HashSet<String>(); for (String p : args.split(",")) { labels.add(p); } return addToClusterNodeLabels(labels); } private int addToClusterNodeLabels(Set<String> labels) throws IOException, YarnException { if (directlyAccessNodeLabelStore) { getNodeLabelManagerInstance(getConf()).addToCluserNodeLabels(labels); } else { ResourceManagerAdministrationProtocol adminProtocol = createAdminProtocol(); AddToClusterNodeLabelsRequest request = AddToClusterNodeLabelsRequest.newInstance(labels); adminProtocol.addToClusterNodeLabels(request); } return 0; } private int removeFromClusterNodeLabels(String args) throws IOException, YarnException { Set<String> labels = new HashSet<String>(); for (String p : args.split(",")) { labels.add(p); } if (directlyAccessNodeLabelStore) { getNodeLabelManagerInstance(getConf()).removeFromClusterNodeLabels( labels); } else { ResourceManagerAdministrationProtocol adminProtocol = createAdminProtocol(); RemoveFromClusterNodeLabelsRequest request = RemoveFromClusterNodeLabelsRequest.newInstance(labels); adminProtocol.removeFromClusterNodeLabels(request); } return 0; } private Map<NodeId, Set<String>> buildNodeLabelsFromStr(String args) throws IOException { Map<NodeId, Set<String>> map = new HashMap<NodeId, Set<String>>(); for (String nodeToLabels : args.split("[ \n]")) { nodeToLabels = nodeToLabels.trim(); if (nodeToLabels.isEmpty() || nodeToLabels.startsWith("#")) { continue; } String[] splits = nodeToLabels.split(","); String nodeIdStr = splits[0]; if (nodeIdStr.trim().isEmpty()) { throw new IOException("node name cannot be empty"); } NodeId nodeId = ConverterUtils.toNodeIdWithDefaultPort(nodeIdStr); map.put(nodeId, new HashSet<String>()); for (int i = 1; i < splits.length; i++) { if (!splits[i].trim().isEmpty()) { map.get(nodeId).add(splits[i].trim()); } } } return map; } private int replaceLabelsOnNodes(String args) throws IOException, YarnException { Map<NodeId, Set<String>> map = buildNodeLabelsFromStr(args); return replaceLabelsOnNodes(map); } private int replaceLabelsOnNodes(Map<NodeId, Set<String>> map) throws IOException, YarnException { if (directlyAccessNodeLabelStore) { getNodeLabelManagerInstance(getConf()).replaceLabelsOnNode(map); } else { ResourceManagerAdministrationProtocol adminProtocol = createAdminProtocol(); ReplaceLabelsOnNodeRequest request = ReplaceLabelsOnNodeRequest.newInstance(map); adminProtocol.replaceLabelsOnNode(request); } return 0; } @Override public int run(String[] args) throws Exception { // -directlyAccessNodeLabelStore is a additional option for node label // access, so just search if we have specified this option, and remove it List<String> argsList = new ArrayList<String>(); for (int i = 0; i < args.length; i++) { if (args[i].equals("-directlyAccessNodeLabelStore")) { directlyAccessNodeLabelStore = true; } else { argsList.add(args[i]); } } args = argsList.toArray(new String[0]); YarnConfiguration yarnConf = getConf() == null ? new YarnConfiguration() : new YarnConfiguration( getConf()); boolean isHAEnabled = yarnConf.getBoolean(YarnConfiguration.RM_HA_ENABLED, YarnConfiguration.DEFAULT_RM_HA_ENABLED); if (args.length < 1) { printUsage("", isHAEnabled); return -1; } int exitCode = -1; int i = 0; String cmd = args[i++]; exitCode = 0; if ("-help".equals(cmd)) { if (i < args.length) { printUsage(args[i], isHAEnabled); } else { printHelp("", isHAEnabled); } return exitCode; } if (USAGE.containsKey(cmd)) { if (isHAEnabled) { return super.run(args); } System.out.println("Cannot run " + cmd + " when ResourceManager HA is not enabled"); return -1; } // // verify that we have enough command line parameters // if ("-refreshAdminAcls".equals(cmd) || "-refreshQueues".equals(cmd) || "-refreshNodes".equals(cmd) || "-refreshServiceAcl".equals(cmd) || "-refreshUserToGroupsMappings".equals(cmd) || "-refreshSuperUserGroupsConfiguration".equals(cmd)) { if (args.length != 1) { printUsage(cmd, isHAEnabled); return exitCode; } } try { if ("-refreshQueues".equals(cmd)) { exitCode = refreshQueues(); } else if ("-refreshNodes".equals(cmd)) { exitCode = refreshNodes(); } else if ("-refreshUserToGroupsMappings".equals(cmd)) { exitCode = refreshUserToGroupsMappings(); } else if ("-refreshSuperUserGroupsConfiguration".equals(cmd)) { exitCode = refreshSuperUserGroupsConfiguration(); } else if ("-refreshAdminAcls".equals(cmd)) { exitCode = refreshAdminAcls(); } else if ("-refreshServiceAcl".equals(cmd)) { exitCode = refreshServiceAcls(); } else if ("-getGroups".equals(cmd)) { String[] usernames = Arrays.copyOfRange(args, i, args.length); exitCode = getGroups(usernames); } else if ("-addToClusterNodeLabels".equals(cmd)) { if (i >= args.length) { System.err.println("No cluster node-labels are specified"); exitCode = -1; } else { exitCode = addToClusterNodeLabels(args[i]); } } else if ("-removeFromClusterNodeLabels".equals(cmd)) { if (i >= args.length) { System.err.println("No cluster node-labels are specified"); exitCode = -1; } else { exitCode = removeFromClusterNodeLabels(args[i]); } } else if ("-replaceLabelsOnNode".equals(cmd)) { if (i >= args.length) { System.err.println("No cluster node-labels are specified"); exitCode = -1; } else { exitCode = replaceLabelsOnNodes(args[i]); } } else { exitCode = -1; System.err.println(cmd.substring(1) + ": Unknown command"); printUsage("", isHAEnabled); } } catch (IllegalArgumentException arge) { exitCode = -1; System.err.println(cmd.substring(1) + ": " + arge.getLocalizedMessage()); printUsage(cmd, isHAEnabled); } catch (RemoteException e) { // // This is a error returned by hadoop server. Print // out the first line of the error mesage, ignore the stack trace. exitCode = -1; try { String[] content; content = e.getLocalizedMessage().split("\n"); System.err.println(cmd.substring(1) + ": " + content[0]); } catch (Exception ex) { System.err.println(cmd.substring(1) + ": " + ex.getLocalizedMessage()); } } catch (Exception e) { exitCode = -1; System.err.println(cmd.substring(1) + ": " + e.getLocalizedMessage()); } if (null != localNodeLabelsManager) { localNodeLabelsManager.stop(); } return exitCode; } @Override public void setConf(Configuration conf) { if (conf != null) { conf = addSecurityConfiguration(conf); } super.setConf(conf); } /** * Add the requisite security principal settings to the given Configuration, * returning a copy. * @param conf the original config * @return a copy with the security settings added */ private static Configuration addSecurityConfiguration(Configuration conf) { // Make a copy so we don't mutate it. Also use an YarnConfiguration to // force loading of yarn-site.xml. conf = new YarnConfiguration(conf); conf.set(CommonConfigurationKeys.HADOOP_SECURITY_SERVICE_USER_NAME_KEY, conf.get(YarnConfiguration.RM_PRINCIPAL, "")); return conf; } @Override protected HAServiceTarget resolveTarget(String rmId) { Collection<String> rmIds = HAUtil.getRMHAIds(getConf()); if (!rmIds.contains(rmId)) { StringBuilder msg = new StringBuilder(); msg.append(rmId + " is not a valid serviceId. It should be one of "); for (String id : rmIds) { msg.append(id + " "); } throw new IllegalArgumentException(msg.toString()); } try { YarnConfiguration conf = new YarnConfiguration(getConf()); conf.set(YarnConfiguration.RM_HA_ID, rmId); return new RMHAServiceTarget(conf); } catch (IllegalArgumentException iae) { throw new YarnRuntimeException("Could not connect to " + rmId + "; the configuration for it might be missing"); } catch (IOException ioe) { throw new YarnRuntimeException( "Could not connect to RM HA Admin for node " + rmId); } } public static void main(String[] args) throws Exception { int result = ToolRunner.run(new RMAdminCLI(), args); System.exit(result); } }
{ "content_hash": "39ccc354eab6c17261229298bb0e6191", "timestamp": "", "source": "github", "line_count": 599, "max_line_length": 100, "avg_line_length": 36.26711185308848, "alnum_prop": 0.6601914932793224, "repo_name": "xuchenCN/hadoop", "id": "c7cc4d2332104ff5572604329e9a5d979c56adf6", "size": "22530", "binary": false, "copies": "1", "ref": "refs/heads/trunk", "path": "hadoop-yarn-project/hadoop-yarn/hadoop-yarn-client/src/main/java/org/apache/hadoop/yarn/client/cli/RMAdminCLI.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "AspectJ", "bytes": "29602" }, { "name": "C", "bytes": "1365053" }, { "name": "C++", "bytes": "1744100" }, { "name": "CSS", "bytes": "44021" }, { "name": "Erlang", "bytes": "232" }, { "name": "Java", "bytes": "48444284" }, { "name": "JavaScript", "bytes": "24161" }, { "name": "Perl", "bytes": "19540" }, { "name": "Python", "bytes": "11309" }, { "name": "Shell", "bytes": "297757" }, { "name": "TeX", "bytes": "19322" }, { "name": "XSLT", "bytes": "20949" } ], "symlink_target": "" }
class Regular extends Special { public Regular(Node t) { } void print(Node t, int n, boolean p) { // Printer.printRegular(t, n, p); if (Environment.errorMessages.size() == 0) { Printer.printQuoted(t, n, true); System.out.print(")"); System.out.println(); } else { String newErr = ""; for (String s : Environment.errorMessages) { String tmp = s; if (!tmp.equals(newErr)) { System.out.println(s); } else { newErr = tmp; } } } } public Node eval(Node t, Environment env) { Node first; Node args; first = t.getCar(); args = eval_list(t.getCdr(), env); while (first.isSymbol()) { first = env.lookup(first); } if (first == null || first.isNull()) { return null; } if (first.isProcedure()) { return first.apply(args); } else { return first.eval(env).apply(args); } } public Node eval_list(Node t, Environment env) { if (t == null || t.isNull()) { Node list = new Cons(new Nil(), new Nil()); return list; } else { Node arg1, rest; arg1 = t.getCar(); rest = t.getCdr(); if (arg1.isSymbol()) { arg1 = env.lookup(arg1); } if (arg1 == null || arg1.isNull()) { return null; } Node list = new Cons(arg1.eval(env), eval_list(rest, env)); return list; } } }
{ "content_hash": "19010ee0e4e20eff9757376adc0bb537", "timestamp": "", "source": "github", "line_count": 66, "max_line_length": 62, "avg_line_length": 19.575757575757574, "alnum_prop": 0.5758513931888545, "repo_name": "akiress/proglangs", "id": "9f359701ca6fa5f38c8c37bddf86959c90f3e909", "size": "1292", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "projects/project2/Regular.java", "mode": "33188", "license": "mit", "language": [ { "name": "C++", "bytes": "29454" }, { "name": "Java", "bytes": "217638" }, { "name": "Scheme", "bytes": "14907" }, { "name": "Shell", "bytes": "162" } ], "symlink_target": "" }
package org.apache.yoko.orb.CORBA; import java.util.logging.Level; import java.util.logging.Logger; import org.apache.yoko.orb.OCI.GiopVersion; import org.omg.CORBA.portable.ValueOutputStream; final public class OutputStream extends org.omg.CORBA_2_3.portable.OutputStream implements ValueOutputStream { static final Logger LOGGER = Logger.getLogger(OutputStream.class.getName()); private org.apache.yoko.orb.OB.ORBInstance orbInstance_; // Java only public org.apache.yoko.orb.OCI.Buffer buf_; private GiopVersion giopVersion_ = org.apache.yoko.orb.OB.OB_Extras.DEFAULT_GIOP_VERSION; private org.apache.yoko.orb.OB.CodeConverters codeConverters_; private boolean charWriterRequired_; private boolean charConversionRequired_; private boolean wCharWriterRequired_; private boolean wCharConversionRequired_; // // Handles all OBV marshalling // private org.apache.yoko.orb.OB.ValueWriter valueWriter_; // // If alignNext_ > 0, the next write should be aligned on this // boundary // private int alignNext_; private java.lang.Object invocationContext_; // Java only private java.lang.Object delegateContext_; // Java only // ------------------------------------------------------------------ // Private and protected functions // ------------------------------------------------------------------ // Write a gap of four bytes (ulong aligned), avoids byte shifts private int writeGap() { LOGGER.finest("Writing a gap value"); addCapacity(4, 4); int result = buf_.pos_; buf_.pos_ += 4; return result; } private void writeLength(int start) { int length = buf_.pos_ - (start + 4); LOGGER.finest("Writing a length value of " + length + " at offset " + start); buf_.data_[start++] = (byte) (length >>> 24); buf_.data_[start++] = (byte) (length >>> 16); buf_.data_[start++] = (byte) (length >>> 8); buf_.data_[start] = (byte) length; } public void writeTypeCodeImpl(org.omg.CORBA.TypeCode tc, java.util.Hashtable history) { // // Try casting the TypeCode to org.apache.yoko.orb.CORBA.TypeCode. This // could // fail if the TypeCode was created by a foreign singleton ORB. // TypeCode obTC = null; try { obTC = (TypeCode) tc; } catch (ClassCastException ex) { } if (obTC != null) { if (obTC.recId_ != null) { if (obTC.recType_ == null) throw new org.omg.CORBA.BAD_TYPECODE( org.apache.yoko.orb.OB.MinorCodes .describeBadTypecode(org.apache.yoko.orb.OB.MinorCodes.MinorIncompleteTypeCode), org.apache.yoko.orb.OB.MinorCodes.MinorIncompleteTypeCode, org.omg.CORBA.CompletionStatus.COMPLETED_NO); writeTypeCodeImpl(obTC.recType_, history); return; } } LOGGER.finest("Writing a type code of type " + tc.kind().value()); // // For performance reasons, handle the primitive TypeCodes first // switch (tc.kind().value()) { case org.omg.CORBA.TCKind._tk_null: case org.omg.CORBA.TCKind._tk_void: case org.omg.CORBA.TCKind._tk_short: case org.omg.CORBA.TCKind._tk_long: case org.omg.CORBA.TCKind._tk_longlong: case org.omg.CORBA.TCKind._tk_ushort: case org.omg.CORBA.TCKind._tk_ulong: case org.omg.CORBA.TCKind._tk_ulonglong: case org.omg.CORBA.TCKind._tk_float: case org.omg.CORBA.TCKind._tk_double: case org.omg.CORBA.TCKind._tk_longdouble: case org.omg.CORBA.TCKind._tk_boolean: case org.omg.CORBA.TCKind._tk_char: case org.omg.CORBA.TCKind._tk_wchar: case org.omg.CORBA.TCKind._tk_octet: case org.omg.CORBA.TCKind._tk_any: case org.omg.CORBA.TCKind._tk_TypeCode: case org.omg.CORBA.TCKind._tk_Principal: write_ulong(tc.kind().value()); return; default: break; } Integer indirectionPos = (Integer) history.get(tc); if (indirectionPos != null) { write_long(-1); int offs = indirectionPos.intValue() - buf_.pos_; LOGGER.finest("Writing an indirect type code for offset " + offs); write_long(offs); } else { write_ulong(tc.kind().value()); Integer oldPos = new Integer(buf_.pos_ - 4); try { switch (tc.kind().value()) { case org.omg.CORBA.TCKind._tk_fixed: { history.put(tc, oldPos); write_ushort(tc.fixed_digits()); write_short(tc.fixed_scale()); break; } case org.omg.CORBA.TCKind._tk_objref: { history.put(tc, oldPos); int start = writeGap(); _OB_writeEndian(); write_string(tc.id()); write_string(tc.name()); writeLength(start); break; } case org.omg.CORBA.TCKind._tk_struct: case org.omg.CORBA.TCKind._tk_except: { history.put(tc, oldPos); int start = writeGap(); _OB_writeEndian(); write_string(tc.id()); write_string(tc.name()); write_ulong(tc.member_count()); for (int i = 0; i < tc.member_count(); i++) { write_string(tc.member_name(i)); writeTypeCodeImpl(tc.member_type(i), history); } writeLength(start); break; } case org.omg.CORBA.TCKind._tk_union: { history.put(tc, oldPos); int start = writeGap(); _OB_writeEndian(); write_string(tc.id()); write_string(tc.name()); org.omg.CORBA.TypeCode discType = tc.discriminator_type(); writeTypeCodeImpl(discType, history); int defaultIndex = tc.default_index(); write_long(defaultIndex); write_ulong(tc.member_count()); for (int i = 0; i < tc.member_count(); i++) { // // Check for default label value // if (i == defaultIndex) { // // Marshal a dummy value of the appropriate size // for the discriminator type // org.omg.CORBA.TypeCode origDiscType = TypeCode ._OB_getOrigType(discType); switch (origDiscType.kind().value()) { case org.omg.CORBA.TCKind._tk_short: write_short((short) 0); break; case org.omg.CORBA.TCKind._tk_ushort: write_ushort((short) 0); break; case org.omg.CORBA.TCKind._tk_long: write_long(0); break; case org.omg.CORBA.TCKind._tk_ulong: write_ulong(0); break; case org.omg.CORBA.TCKind._tk_longlong: write_longlong(0); break; case org.omg.CORBA.TCKind._tk_ulonglong: write_ulonglong(0); break; case org.omg.CORBA.TCKind._tk_boolean: write_boolean(false); break; case org.omg.CORBA.TCKind._tk_char: write_char((char) 0); break; case org.omg.CORBA.TCKind._tk_enum: write_ulong(0); break; default: org.apache.yoko.orb.OB.Assert._OB_assert("Invalid sub-type in tk_union"); } } else { tc.member_label(i).write_value(this); } write_string(tc.member_name(i)); writeTypeCodeImpl(tc.member_type(i), history); } writeLength(start); break; } case org.omg.CORBA.TCKind._tk_enum: { history.put(tc, oldPos); int start = writeGap(); _OB_writeEndian(); write_string(tc.id()); write_string(tc.name()); write_ulong(tc.member_count()); for (int i = 0; i < tc.member_count(); i++) write_string(tc.member_name(i)); writeLength(start); break; } case org.omg.CORBA.TCKind._tk_string: case org.omg.CORBA.TCKind._tk_wstring: write_ulong(tc.length()); break; case org.omg.CORBA.TCKind._tk_sequence: case org.omg.CORBA.TCKind._tk_array: { history.put(tc, oldPos); int start = writeGap(); _OB_writeEndian(); writeTypeCodeImpl(tc.content_type(), history); write_ulong(tc.length()); writeLength(start); break; } case org.omg.CORBA.TCKind._tk_alias: { history.put(tc, oldPos); int start = writeGap(); _OB_writeEndian(); write_string(tc.id()); write_string(tc.name()); writeTypeCodeImpl(tc.content_type(), history); writeLength(start); break; } case org.omg.CORBA.TCKind._tk_value: { history.put(tc, oldPos); org.omg.CORBA.TypeCode concreteBase = tc .concrete_base_type(); if (concreteBase == null) { concreteBase = org.apache.yoko.orb.OB.TypeCodeFactory .createPrimitiveTC(org.omg.CORBA.TCKind.tk_null); } int start = writeGap(); _OB_writeEndian(); write_string(tc.id()); write_string(tc.name()); write_short(tc.type_modifier()); writeTypeCodeImpl(concreteBase, history); write_ulong(tc.member_count()); for (int i = 0; i < tc.member_count(); i++) { write_string(tc.member_name(i)); writeTypeCodeImpl(tc.member_type(i), history); write_short(tc.member_visibility(i)); } writeLength(start); break; } case org.omg.CORBA.TCKind._tk_value_box: { history.put(tc, oldPos); int start = writeGap(); _OB_writeEndian(); write_string(tc.id()); write_string(tc.name()); writeTypeCodeImpl(tc.content_type(), history); writeLength(start); break; } case org.omg.CORBA.TCKind._tk_abstract_interface: { history.put(tc, oldPos); int start = writeGap(); _OB_writeEndian(); write_string(tc.id()); write_string(tc.name()); writeLength(start); break; } case org.omg.CORBA.TCKind._tk_native: { history.put(tc, oldPos); int start = writeGap(); _OB_writeEndian(); write_string(tc.id()); write_string(tc.name()); writeLength(start); break; } case org.omg.CORBA_2_4.TCKind._tk_local_interface: { history.put(tc, oldPos); int start = writeGap(); _OB_writeEndian(); write_string(tc.id()); write_string(tc.name()); writeLength(start); break; } default: org.apache.yoko.orb.OB.Assert._OB_assert("Invalid typecode"); } } catch (org.omg.CORBA.TypeCodePackage.BadKind ex) { org.apache.yoko.orb.OB.Assert._OB_assert(ex); } catch (org.omg.CORBA.TypeCodePackage.Bounds ex) { org.apache.yoko.orb.OB.Assert._OB_assert(ex); } } } // // Must be called prior to any writes // private void checkBeginChunk() { org.apache.yoko.orb.OB.Assert._OB_assert(valueWriter_ != null); valueWriter_.checkBeginChunk(); } private org.apache.yoko.orb.OB.ValueWriter valueWriter() { if (valueWriter_ == null) valueWriter_ = new org.apache.yoko.orb.OB.ValueWriter(this); return valueWriter_; } private void addCapacity(int size) { // // Expand buffer to hold requested size // // Note: OutputStreams are not always written to in a linear // fashion, i.e., sometimes the position is reset to // an earlier point and data is patched in. Therefore, // do NOT do this: // // buf_.realloc(buf_.len_ + size); // // if (alignNext_ > 0) { int align = alignNext_; alignNext_ = 0; addCapacity(size, align); } else { // // If we're at the end of the current buffer, then we are about // to write new data. We must first check if we need to start a // chunk, which may result in a recursive call to addCapacity(). // if (buf_.pos_ == buf_.len_ && valueWriter_ != null) { checkBeginChunk(); } // // If there isn't enough room, then reallocate the buffer // final int len = buf_.pos_ + size; if (len > buf_.len_) { buf_.realloc(len); } } } private int roundUp(final int i, final int align) { switch (align) { case 0x00: return i; case 0x01: return i; case 0x02: return ((i + 0b0001) & ~(0b0001)); case 0x04: return ((i + 0b0011) & ~(0b0011)); case 0x08: return ((i + 0b0111) & ~(0b0111)); case 0x10: return ((i + 0b1111) & ~(0b1111)); default: if (LOGGER.isLoggable(Level.WARNING)) LOGGER.warning(String.format("Aligning on a strange number 0x%x", align)); final int j = (i + align - 1); return (j - (j % align)); } } private static final byte PAD_BYTE = (byte)0xbd; private void addCapacity(int size, int align) { // use addCapacity(int) if align == 0 org.apache.yoko.orb.OB.Assert._OB_assert(align > 0); // // If we're at the end of the current buffer, then we are about // to write new data. We must first check if we need to start a // chunk, which may result in a recursive call to addCapacity(). // if (buf_.pos_ == buf_.len_ && valueWriter_ != null) { checkBeginChunk(); } // // If alignNext_ is set, then use the larger of alignNext_ and align // if (alignNext_ > 0) { align = (alignNext_ > align ? alignNext_ : align); alignNext_ = 0; } final int newPos = roundUp(buf_.pos_, align); // // If there isn't enough room, then reallocate the buffer // final int len = newPos + size; if (len > buf_.len_) { buf_.realloc(len); } // // Pad to the requested boundary // for (; buf_.pos_ < newPos; buf_.pos_++) { buf_.data_[buf_.pos_] = PAD_BYTE; } } // // write wchar using old non-compliant method // private void _OB_write_wchar_old(char value) { if (wCharConversionRequired_) { final org.apache.yoko.orb.OB.CodeConverterBase converter = codeConverters_.outputWcharConverter; value = converter.convert(value); // // For GIOP 1.1 non byte-oriented wide characters are written // as ushort or ulong, depending on their maximum length // listed in the code set registry. // switch (giopVersion_) { case GIOP1_1: { if (converter.getTo().max_bytes <= 2) write_ushort((short) value); else write_ulong((int) value); } break; default: { final int length = converter.write_count_wchar(value); write_octet((byte) length); addCapacity(length); converter.write_wchar(this, value); } break; } } // // UTF-16 // else { switch (giopVersion_) { case GIOP1_0: case GIOP1_1: write_ushort((short) value); break; default: addCapacity(3); buf_.data_[buf_.pos_++] = 2; buf_.data_[buf_.pos_++] = (byte) (value >> 8); buf_.data_[buf_.pos_++] = (byte) value; break; } } } // // write wchar using new compilant method // private void _OB_write_wchar_new(char value, boolean partOfString) { final org.apache.yoko.orb.OB.CodeConverterBase converter = codeConverters_.outputWcharConverter; // // pre-convert the character if necessary // if (wCharConversionRequired_) value = converter.convert(value); if (wCharWriterRequired_) { if (partOfString == false) converter .set_writer_flags(org.apache.yoko.orb.OB.CodeSetWriter.FIRST_CHAR); // // For GIOP 1.1 non byte-oriented wide characters are written // as ushort or ulong, depending on their maximum length // listed in the code set registry. // switch (giopVersion_) { case GIOP1_0: { // // we don't support special writers for GIOP 1.0 if // conversion is required or if a writer is required // org.apache.yoko.orb.OB.Assert._OB_assert(false); } break; case GIOP1_1: { // // get the length of the character // int len = converter.write_count_wchar(value); // // For GIOP 1.1 we are limited to 2-byte wchars // so make sure to check for that // org.apache.yoko.orb.OB.Assert._OB_assert(len == 2); // // allocate aligned space // addCapacity(2, 2); // // write using the writer // converter.write_wchar(this, value); } break; default: { // // get the length of the character // int len = converter.write_count_wchar(value); // // write the octet length at the beginning // write_octet((byte) len); // // add unaligned capacity // addCapacity(len); // // write the actual character // converter.write_wchar(this, value); } break; } } else { switch (giopVersion_) { case GIOP1_0: { // // Orbix2000/Orbacus/E compatible 1.0 marshal // // // add aligned capacity // addCapacity(2, 2); // // write 2-byte character in big endian // buf_.data_[buf_.pos_++] = (byte) (value >>> 8); buf_.data_[buf_.pos_++] = (byte) (value & 0xff); } break; case GIOP1_1: { write_ushort((short) value); } break; default: { // // add unaligned space for character // addCapacity(3); // // write the octet length at the start // buf_.data_[buf_.pos_++] = 2; // // write the character in big endian format // buf_.data_[buf_.pos_++] = (byte) (value >>> 8); buf_.data_[buf_.pos_++] = (byte) (value & 0xff); } break; } } } // // write wstring using old non-compliant method // private void _OB_write_wstring_old(String value) { final char[] arr = value.toCharArray(); final int len = arr.length; // // 15.3.2.7: For GIOP version 1.1, a wide string is encoded as an // unsigned long indicating the length of the string in octets or // unsigned integers (determined by the transfer syntax for wchar) // followed by the individual wide characters. Both the string length // and contents include a terminating null. The terminating null // character for a wstring is also a wide character. // switch (giopVersion_) { case GIOP1_0: case GIOP1_1: { write_ulong(len + 1); write_wchar_array(arr, 0, len); write_wchar((char) 0); } break; default: { // // For octet count // int start = writeGap(); if (wCharConversionRequired_) { final org.apache.yoko.orb.OB.CodeConverterBase converter = codeConverters_.outputWcharConverter; for (int i = 0; i < len; i++) { char v = converter.convert(arr[i]); if (v == 0) throw new org.omg.CORBA.DATA_CONVERSION( "illegal wchar value for wstring: " + (int) v); addCapacity(converter.write_count_wchar(v)); converter.write_wchar(this, v); } } // // UTF-16 // else { addCapacity(2 * len); for (int i = 0; i < len; i++) { char v = arr[i]; if (v == 0) throw new org.omg.CORBA.DATA_CONVERSION( "illegal wchar value for wstring: " + (int) v); buf_.data_[buf_.pos_++] = (byte) (v >> 8); buf_.data_[buf_.pos_++] = (byte) v; } } // // Write octet count // writeLength(start); } break; } } // // write wstring using new compliant method // private void _OB_write_wstring_new(String value) { final char[] arr = value.toCharArray(); final int len = arr.length; LOGGER.finest("Writing wstring value " + value); // // get converter/writer instance // final org.apache.yoko.orb.OB.CodeConverterBase converter = codeConverters_.outputWcharConverter; // // some writers (specially UTF-16) requires the possible BOM // only found at the beginning of a string... this will // indicate that we are at the start of the first character // of the string to the writer if (wCharWriterRequired_) converter .set_writer_flags(org.apache.yoko.orb.OB.CodeSetWriter.FIRST_CHAR); // // for GIOP 1.0/1.1 we don't need to differentiate between // strings requiring a writer/converter (or not) since they can // be handled by the write_wchar() method // switch (giopVersion_) { case GIOP1_0: case GIOP1_1: // // write the length of the string // write_ulong(len + 1); // // now write all the characters // for (int i = 0; i < len; i++) write_wchar(arr[i], true); // // and the null terminator // write_wchar((char) 0, true); return; default: } // // save the starting position and write the gap to place the // length of the string later // int start = writeGap(); // // we've handled GIOP 1.0/1.1 above so this must be GIOP 1.2+ // if (wCharWriterRequired_) { for (int i = 0; i < len; i++) { char v = arr[i]; // // check if the character requires conversion // if (wCharConversionRequired_) v = converter.convert(v); // // illegal for the string to contain nulls // if (v == 0) throw new org.omg.CORBA.DATA_CONVERSION( "illegal wchar value for wstring: " + (int) v); // // add capacity for the character // addCapacity(converter.write_count_wchar(v)); // // write the character // converter.write_wchar(this, v); } } else { // // since we don't require a special writer, each character // MUST be 2-bytes in size // addCapacity(len << 1); for (int i = 0; i < len; i++) { char v = arr[i]; // // check for conversion // if (wCharConversionRequired_) v = converter.convert(v); // // write character in big endian format // buf_.data_[buf_.pos_++] = (byte) (v >>> 8); buf_.data_[buf_.pos_++] = (byte) (v & 0xff); } } // // write the octet length // writeLength(start); } // ------------------------------------------------------------------ // Standard IDL to Java Mapping // ------------------------------------------------------------------ public void write(int b) throws java.io.IOException { // // this matches the behaviour of this function in the Java ORB // and not what is outlined in the java.io.OutputStream // write_long(b); } public org.omg.CORBA.ORB orb() { if (orbInstance_ != null) return orbInstance_.getORB(); return null; } public org.omg.CORBA.portable.InputStream create_input_stream() { org.apache.yoko.orb.OCI.Buffer buf = new org.apache.yoko.orb.OCI.Buffer( buf_.len_); if (buf_.len_ > 0) System.arraycopy(buf_.data_, 0, buf.data_, 0, buf_.len_); // this is a useful tracepoint, but produces a lot of data, so turn on only // if really needed. // if (logger.isLoggable(Level.FINEST)) { // logger.fine("new input stream created:\n" + buf.dumpData()); // } InputStream in = new InputStream(buf, 0, false, codeConverters_, giopVersion_); in._OB_ORBInstance(orbInstance_); return in; } public void write_boolean(boolean value) { addCapacity(1); buf_.data_[buf_.pos_++] = value ? (byte) 1 : (byte) 0; } public void write_char(char value) { if (value > 255) throw new org.omg.CORBA.DATA_CONVERSION("char value exceeds 255: " + (int) value); addCapacity(1); final org.apache.yoko.orb.OB.CodeConverterBase converter = codeConverters_.outputCharConverter; if (charConversionRequired_) value = converter.convert(value); if (charWriterRequired_) converter.write_char(this, value); else buf_.data_[buf_.pos_++] = (byte) value; } public void write_wchar(char value) { write_wchar(value, false); } public void write_wchar(char value, boolean partOfString) { if (org.apache.yoko.orb.OB.OB_Extras.COMPAT_WIDE_MARSHAL == false) _OB_write_wchar_new(value, partOfString); else _OB_write_wchar_old(value); } public void write_octet(byte value) { addCapacity(1); buf_.data_[buf_.pos_++] = value; } public void write_short(short value) { addCapacity(2, 2); buf_.data_[buf_.pos_++] = (byte) (value >>> 8); buf_.data_[buf_.pos_++] = (byte) value; } public void write_ushort(short value) { write_short(value); } public void write_long(int value) { addCapacity(4, 4); buf_.data_[buf_.pos_++] = (byte) (value >>> 24); buf_.data_[buf_.pos_++] = (byte) (value >>> 16); buf_.data_[buf_.pos_++] = (byte) (value >>> 8); buf_.data_[buf_.pos_++] = (byte) value; } public void write_ulong(int value) { write_long(value); } public void write_longlong(long value) { addCapacity(8, 8); buf_.data_[buf_.pos_++] = (byte) (value >>> 56); buf_.data_[buf_.pos_++] = (byte) (value >>> 48); buf_.data_[buf_.pos_++] = (byte) (value >>> 40); buf_.data_[buf_.pos_++] = (byte) (value >>> 32); buf_.data_[buf_.pos_++] = (byte) (value >>> 24); buf_.data_[buf_.pos_++] = (byte) (value >>> 16); buf_.data_[buf_.pos_++] = (byte) (value >>> 8); buf_.data_[buf_.pos_++] = (byte) value; } public void write_ulonglong(long value) { write_longlong(value); } public void write_float(float value) { write_long(Float.floatToIntBits(value)); } public void write_double(double value) { write_longlong(Double.doubleToLongBits(value)); } public void write_string(String value) { LOGGER.finest("Writing string value " + value); final char[] arr = value.toCharArray(); int len = arr.length; int capacity = len + 1; if (!(charWriterRequired_ || charConversionRequired_)) { write_ulong(capacity); addCapacity(capacity); for (int i = 0; i < len; i++) { char c = arr[i]; if (c == 0 || c > 255) throw new org.omg.CORBA.DATA_CONVERSION( "illegal char value for string: " + (int) c); buf_.data_[buf_.pos_++] = (byte) c; } } else { final org.apache.yoko.orb.OB.CodeConverterBase converter = codeConverters_.outputCharConverter; // // Intermediate variable used for efficiency // boolean bothRequired = charWriterRequired_ && charConversionRequired_; // // Temporary OCI buffer required // org.apache.yoko.orb.OCI.Buffer buffer = new org.apache.yoko.orb.OCI.Buffer( 64); OutputStream tmpStream = new OutputStream(buffer); for (int i = 0; i < len; i++) { char c = arr[i]; if (c == 0 || c > 255) throw new org.omg.CORBA.DATA_CONVERSION( "illegal char value for string: " + (int) c); // // Expand the temporary buffer, if necessary // if (buffer.length() - buffer.pos() <= 4) buffer.realloc(buffer.length() * 2); if (bothRequired) converter.write_char(tmpStream, converter.convert(c)); else if (charWriterRequired_) converter.write_char(tmpStream, c); else buffer.data_[buffer.pos_++] = (byte) converter.convert(c); } // // Copy the contents from the temporary buffer // int bufSize = buffer.pos_; write_ulong(bufSize + 1); addCapacity(bufSize + 1); for (int i = 0; i < bufSize; i++) { buf_.data_[buf_.pos_++] = buffer.data_[i]; } } buf_.data_[buf_.pos_++] = (byte) 0; } public void write_wstring(String value) { if (org.apache.yoko.orb.OB.OB_Extras.COMPAT_WIDE_MARSHAL == false) _OB_write_wstring_new(value); else _OB_write_wstring_old(value); } public void write_boolean_array(boolean[] value, int offset, int length) { if (length > 0) { addCapacity(length); for (int i = offset; i < offset + length; i++) buf_.data_[buf_.pos_++] = value[i] ? (byte) 1 : (byte) 0; } } public void write_char_array(char[] value, int offset, int length) { if (length > 0) { addCapacity(length); if (!(charWriterRequired_ || charConversionRequired_)) { for (int i = offset; i < offset + length; i++) { if (value[i] > 255) throw new org.omg.CORBA.DATA_CONVERSION( "char value exceeds 255: " + (int) value[i]); buf_.data_[buf_.pos_++] = (byte) value[i]; } } else { final org.apache.yoko.orb.OB.CodeConverterBase converter = codeConverters_.outputCharConverter; // // Intermediate variable used for efficiency // boolean bothRequired = charWriterRequired_ && charConversionRequired_; for (int i = offset; i < offset + length; i++) { if (value[i] > 255) throw new org.omg.CORBA.DATA_CONVERSION( "char value exceeds 255: " + (int) value[i]); if (bothRequired) converter.write_char(this, converter.convert(value[i])); else if (charWriterRequired_) converter.write_char(this, value[i]); else buf_.data_[buf_.pos_++] = (byte) converter .convert(value[i]); } } } } public void write_wchar_array(char[] value, int offset, int length) { for (int i = offset; i < offset + length; i++) write_wchar(value[i], false); } public void write_octet_array(byte[] value, int offset, int length) { if (length > 0) { addCapacity(length); System.arraycopy(value, offset, buf_.data_, buf_.pos_, length); buf_.pos_ += length; } } public void write_short_array(short[] value, int offset, int length) { if (length > 0) { addCapacity(length * 2, 2); for (int i = offset; i < offset + length; i++) { buf_.data_[buf_.pos_++] = (byte) (value[i] >>> 8); buf_.data_[buf_.pos_++] = (byte) value[i]; } } } public void write_ushort_array(short[] value, int offset, int length) { write_short_array(value, offset, length); } public void write_long_array(int[] value, int offset, int length) { if (length > 0) { addCapacity(length * 4, 4); for (int i = offset; i < offset + length; i++) { buf_.data_[buf_.pos_++] = (byte) (value[i] >>> 24); buf_.data_[buf_.pos_++] = (byte) (value[i] >>> 16); buf_.data_[buf_.pos_++] = (byte) (value[i] >>> 8); buf_.data_[buf_.pos_++] = (byte) value[i]; } } } public void write_ulong_array(int[] value, int offset, int length) { write_long_array(value, offset, length); } public void write_longlong_array(long[] value, int offset, int length) { if (length > 0) { addCapacity(length * 8, 8); for (int i = offset; i < offset + length; i++) { buf_.data_[buf_.pos_++] = (byte) (value[i] >>> 56); buf_.data_[buf_.pos_++] = (byte) (value[i] >>> 48); buf_.data_[buf_.pos_++] = (byte) (value[i] >>> 40); buf_.data_[buf_.pos_++] = (byte) (value[i] >>> 32); buf_.data_[buf_.pos_++] = (byte) (value[i] >>> 24); buf_.data_[buf_.pos_++] = (byte) (value[i] >>> 16); buf_.data_[buf_.pos_++] = (byte) (value[i] >>> 8); buf_.data_[buf_.pos_++] = (byte) value[i]; } } } public void write_ulonglong_array(long[] value, int offset, int length) { write_longlong_array(value, offset, length); } public void write_float_array(float[] value, int offset, int length) { if (length > 0) { addCapacity(length * 4, 4); for (int i = offset; i < offset + length; i++) { int v = Float.floatToIntBits(value[i]); buf_.data_[buf_.pos_++] = (byte) (v >>> 24); buf_.data_[buf_.pos_++] = (byte) (v >>> 16); buf_.data_[buf_.pos_++] = (byte) (v >>> 8); buf_.data_[buf_.pos_++] = (byte) v; } } } public void write_double_array(double[] value, int offset, int length) { if (length > 0) { addCapacity(length * 8, 8); for (int i = offset; i < offset + length; i++) { long v = Double.doubleToLongBits(value[i]); buf_.data_[buf_.pos_++] = (byte) (v >>> 56); buf_.data_[buf_.pos_++] = (byte) (v >>> 48); buf_.data_[buf_.pos_++] = (byte) (v >>> 40); buf_.data_[buf_.pos_++] = (byte) (v >>> 32); buf_.data_[buf_.pos_++] = (byte) (v >>> 24); buf_.data_[buf_.pos_++] = (byte) (v >>> 16); buf_.data_[buf_.pos_++] = (byte) (v >>> 8); buf_.data_[buf_.pos_++] = (byte) v; } } } public void write_Object(org.omg.CORBA.Object value) { if (value == null) { LOGGER.finest("Writing a null CORBA object value"); org.omg.IOP.IOR ior = new org.omg.IOP.IOR(); ior.type_id = ""; ior.profiles = new org.omg.IOP.TaggedProfile[0]; org.omg.IOP.IORHelper.write(this, ior); } else { if (value instanceof org.omg.CORBA.LocalObject) throw new org.omg.CORBA.MARSHAL( org.apache.yoko.orb.OB.MinorCodes .describeMarshal(org.apache.yoko.orb.OB.MinorCodes.MinorLocalObject), org.apache.yoko.orb.OB.MinorCodes.MinorLocalObject, org.omg.CORBA.CompletionStatus.COMPLETED_NO); Delegate p = (Delegate) ((org.omg.CORBA.portable.ObjectImpl) value) ._get_delegate(); p._OB_marshalOrigIOR(this); } } public void write_TypeCode(org.omg.CORBA.TypeCode t) { // // NOTE: // // No data with natural alignment of greater than four octets // is needed for TypeCode. Therefore it is not necessary to do // encapsulation in a separate buffer. // if (t == null) throw new org.omg.CORBA.BAD_TYPECODE("TypeCode is nil"); java.util.Hashtable history = new java.util.Hashtable(11); writeTypeCodeImpl(t, history); } public void write_any(org.omg.CORBA.Any value) { LOGGER.finest("Writing an ANY value of type " + value.type().kind()); write_TypeCode(value.type()); value.write_value(this); } public void write_Context(org.omg.CORBA.Context ctx, org.omg.CORBA.ContextList contexts) { int count = contexts.count(); java.util.Vector v = new java.util.Vector(); org.apache.yoko.orb.CORBA.Context ctxImpl = (org.apache.yoko.orb.CORBA.Context) ctx; for (int i = 0; i < count; i++) { try { String pattern = contexts.item(i); ctxImpl._OB_getValues("", 0, pattern, v); } catch (org.omg.CORBA.Bounds ex) { org.apache.yoko.orb.OB.Assert._OB_assert(ex); } } write_ulong(v.size()); java.util.Enumeration e = v.elements(); while (e.hasMoreElements()) write_string((String) e.nextElement()); } public void write_Principal(org.omg.CORBA.Principal value) { // Deprecated by CORBA 2.2 throw new org.omg.CORBA.NO_IMPLEMENT(); } public void write_fixed(java.math.BigDecimal value) { String v = value.abs().toString(); // // Append coded sign to value string // if (value.signum() == -1) v += (char) ('0' + 0x0d); else v += (char) ('0' + 0x0c); String s = ""; if ((v.length() & 1) != 0) s = "0"; s += v; final int len = s.length(); for (int i = 0; i < len - 1; i += 2) { char c1 = s.charAt(i); char c2 = s.charAt(i + 1); write_octet((byte) ((c1 - '0') << 4 | (c2 - '0'))); } } public void write_value(java.io.Serializable value) { valueWriter().writeValue(value, null); } public void write_value(java.io.Serializable value, java.lang.String rep_id) { valueWriter().writeValue(value, rep_id); } public void write_value(java.io.Serializable value, Class clz) { valueWriter().writeValue(value, null); } public void write_value(java.io.Serializable value, org.omg.CORBA.portable.BoxedValueHelper helper) { valueWriter().writeValueBox(value, null, helper); } public void write_abstract_interface(java.lang.Object obj) { valueWriter().writeAbstractInterface(obj); } // ------------------------------------------------------------------ // Additional Yoko specific functions // ------------------------------------------------------------------ public void write_value(java.io.Serializable value, org.omg.CORBA.TypeCode tc, org.omg.CORBA.portable.BoxedValueHelper helper) { valueWriter().writeValueBox(value, tc, helper); } public void write_InputStream(org.omg.CORBA.portable.InputStream in, org.omg.CORBA.TypeCode tc) { InputStream obin = null; try { obin = (InputStream) in; } catch (ClassCastException ex) { // InputStream may have been created by a different ORB } try { LOGGER.fine("writing a value of type " + tc.kind().value()); switch (tc.kind().value()) { case org.omg.CORBA.TCKind._tk_null: case org.omg.CORBA.TCKind._tk_void: break; case org.omg.CORBA.TCKind._tk_short: case org.omg.CORBA.TCKind._tk_ushort: write_short(in.read_short()); break; case org.omg.CORBA.TCKind._tk_long: case org.omg.CORBA.TCKind._tk_ulong: case org.omg.CORBA.TCKind._tk_float: case org.omg.CORBA.TCKind._tk_enum: write_long(in.read_long()); break; case org.omg.CORBA.TCKind._tk_double: case org.omg.CORBA.TCKind._tk_longlong: case org.omg.CORBA.TCKind._tk_ulonglong: write_longlong(in.read_longlong()); break; case org.omg.CORBA.TCKind._tk_boolean: case org.omg.CORBA.TCKind._tk_octet: write_octet(in.read_octet()); break; case org.omg.CORBA.TCKind._tk_char: write_char(in.read_char()); break; case org.omg.CORBA.TCKind._tk_wchar: write_wchar(in.read_wchar()); break; case org.omg.CORBA.TCKind._tk_fixed: write_fixed(in.read_fixed()); break; case org.omg.CORBA.TCKind._tk_any: { // Don't do this: write_any(in.read_any()) // This is faster: org.omg.CORBA.TypeCode p = in.read_TypeCode(); write_TypeCode(p); write_InputStream(in, p); break; } case org.omg.CORBA.TCKind._tk_TypeCode: { // Don't do this: write_TypeCode(in.read_TypeCode()) // This is faster: int kind = in.read_ulong(); // // An indirection is not permitted at this level // if (kind == -1) { throw new org.omg.CORBA.MARSHAL( org.apache.yoko.orb.OB.MinorCodes .describeMarshal(org.apache.yoko.orb.OB.MinorCodes.MinorReadInvTypeCodeIndirection), org.apache.yoko.orb.OB.MinorCodes.MinorReadInvTypeCodeIndirection, org.omg.CORBA.CompletionStatus.COMPLETED_NO); } write_ulong(kind); switch (kind) { case org.omg.CORBA.TCKind._tk_null: case org.omg.CORBA.TCKind._tk_void: case org.omg.CORBA.TCKind._tk_short: case org.omg.CORBA.TCKind._tk_long: case org.omg.CORBA.TCKind._tk_ushort: case org.omg.CORBA.TCKind._tk_ulong: case org.omg.CORBA.TCKind._tk_float: case org.omg.CORBA.TCKind._tk_double: case org.omg.CORBA.TCKind._tk_boolean: case org.omg.CORBA.TCKind._tk_char: case org.omg.CORBA.TCKind._tk_octet: case org.omg.CORBA.TCKind._tk_any: case org.omg.CORBA.TCKind._tk_TypeCode: case org.omg.CORBA.TCKind._tk_Principal: case org.omg.CORBA.TCKind._tk_longlong: case org.omg.CORBA.TCKind._tk_ulonglong: case org.omg.CORBA.TCKind._tk_longdouble: case org.omg.CORBA.TCKind._tk_wchar: break; case org.omg.CORBA.TCKind._tk_fixed: write_ushort(in.read_ushort()); write_short(in.read_short()); break; case org.omg.CORBA.TCKind._tk_objref: case org.omg.CORBA.TCKind._tk_struct: case org.omg.CORBA.TCKind._tk_union: case org.omg.CORBA.TCKind._tk_enum: case org.omg.CORBA.TCKind._tk_sequence: case org.omg.CORBA.TCKind._tk_array: case org.omg.CORBA.TCKind._tk_alias: case org.omg.CORBA.TCKind._tk_except: case org.omg.CORBA.TCKind._tk_value: case org.omg.CORBA.TCKind._tk_value_box: case org.omg.CORBA.TCKind._tk_abstract_interface: case org.omg.CORBA.TCKind._tk_native: case org.omg.CORBA_2_4.TCKind._tk_local_interface: { final int len = in.read_ulong(); write_ulong(len); addCapacity(len); in.read_octet_array(buf_.data_, buf_.pos_, len); buf_.pos_ += len; break; } case org.omg.CORBA.TCKind._tk_string: case org.omg.CORBA.TCKind._tk_wstring: { int bound = in.read_ulong(); write_ulong(bound); break; } default: throw new InternalError(); } break; } case org.omg.CORBA.TCKind._tk_Principal: write_Principal(in.read_Principal()); break; case org.omg.CORBA.TCKind._tk_objref: { // Don't do this: write_Object(in.read_Object()) // This is faster: org.omg.IOP.IOR ior = org.omg.IOP.IORHelper.read(in); org.omg.IOP.IORHelper.write(this, ior); break; } case org.omg.CORBA.TCKind._tk_struct: for (int i = 0; i < tc.member_count(); i++) write_InputStream(in, tc.member_type(i)); break; case org.omg.CORBA.TCKind._tk_except: write_string(in.read_string()); for (int i = 0; i < tc.member_count(); i++) write_InputStream(in, tc.member_type(i)); break; case org.omg.CORBA.TCKind._tk_union: { int defaultIndex = tc.default_index(); int memberIndex = -1; org.omg.CORBA.TypeCode origDiscType = TypeCode ._OB_getOrigType(tc.discriminator_type()); switch (origDiscType.kind().value()) { case org.omg.CORBA.TCKind._tk_short: { short val = in.read_short(); write_short(val); for (int i = 0; i < tc.member_count(); i++) if (i != defaultIndex) { if (val == tc.member_label(i).extract_short()) { memberIndex = i; break; } } break; } case org.omg.CORBA.TCKind._tk_ushort: { short val = in.read_ushort(); write_ushort(val); for (int i = 0; i < tc.member_count(); i++) if (i != defaultIndex) { if (val == tc.member_label(i).extract_ushort()) { memberIndex = i; break; } } break; } case org.omg.CORBA.TCKind._tk_long: { int val = in.read_long(); write_long(val); for (int i = 0; i < tc.member_count(); i++) if (i != defaultIndex) { if (val == tc.member_label(i).extract_long()) { memberIndex = i; break; } } break; } case org.omg.CORBA.TCKind._tk_ulong: { int val = in.read_ulong(); write_ulong(val); for (int i = 0; i < tc.member_count(); i++) if (i != defaultIndex) { if (val == tc.member_label(i).extract_ulong()) { memberIndex = i; break; } } break; } case org.omg.CORBA.TCKind._tk_longlong: { long val = in.read_longlong(); write_longlong(val); for (int i = 0; i < tc.member_count(); i++) if (i != defaultIndex) { if (val == tc.member_label(i).extract_longlong()) { memberIndex = i; break; } } break; } case org.omg.CORBA.TCKind._tk_ulonglong: { long val = in.read_ulonglong(); write_ulonglong(val); for (int i = 0; i < tc.member_count(); i++) if (i != defaultIndex) { if (val == tc.member_label(i).extract_ulonglong()) { memberIndex = i; break; } } break; } case org.omg.CORBA.TCKind._tk_char: { char val = in.read_char(); write_char(val); for (int i = 0; i < tc.member_count(); i++) if (i != defaultIndex) { if (val == tc.member_label(i).extract_char()) { memberIndex = i; break; } } break; } case org.omg.CORBA.TCKind._tk_boolean: { boolean val = in.read_boolean(); write_boolean(val); for (int i = 0; i < tc.member_count(); i++) if (i != defaultIndex) { if (val == tc.member_label(i).extract_boolean()) { memberIndex = i; break; } } break; } case org.omg.CORBA.TCKind._tk_enum: { int val = in.read_long(); write_long(val); for (int i = 0; i < tc.member_count(); i++) if (i != defaultIndex) { if (val == tc.member_label(i).create_input_stream() .read_long()) { memberIndex = i; break; } } break; } default: org.apache.yoko.orb.OB.Assert._OB_assert("Invalid typecode in tk_union"); } if (memberIndex >= 0) write_InputStream(in, tc.member_type(memberIndex)); else if (defaultIndex >= 0) write_InputStream(in, tc.member_type(defaultIndex)); break; } case org.omg.CORBA.TCKind._tk_string: write_string(in.read_string()); break; case org.omg.CORBA.TCKind._tk_wstring: write_wstring(in.read_wstring()); break; case org.omg.CORBA.TCKind._tk_sequence: case org.omg.CORBA.TCKind._tk_array: { int len; if (tc.kind().value() == org.omg.CORBA.TCKind._tk_sequence) { len = in.read_ulong(); write_ulong(len); } else len = tc.length(); if (len > 0) { org.omg.CORBA.TypeCode origContentType = TypeCode ._OB_getOrigType(tc.content_type()); switch (origContentType.kind().value()) { case org.omg.CORBA.TCKind._tk_null: case org.omg.CORBA.TCKind._tk_void: break; case org.omg.CORBA.TCKind._tk_short: case org.omg.CORBA.TCKind._tk_ushort: { if (obin == null || obin.swap_) { short[] s = new short[len]; in.read_short_array(s, 0, len); write_short_array(s, 0, len); } else { // Read one value for the alignment write_short(obin.read_short()); final int n = 2 * (len - 1); if (n > 0) { // Copy the rest addCapacity(n); org.apache.yoko.orb.OCI.Buffer buf = obin ._OB_buffer(); System.arraycopy(buf.data_, buf.pos_, buf_.data_, buf_.pos_, n); buf.pos_ += n; buf_.pos_ += n; } } break; } case org.omg.CORBA.TCKind._tk_long: case org.omg.CORBA.TCKind._tk_ulong: case org.omg.CORBA.TCKind._tk_float: { if (obin == null || obin.swap_) { int[] i = new int[len]; in.read_long_array(i, 0, len); write_long_array(i, 0, len); } else { // Read one value for the alignment write_long(obin.read_long()); final int n = 4 * (len - 1); if (n > 0) { // Copy the rest addCapacity(n); org.apache.yoko.orb.OCI.Buffer buf = obin ._OB_buffer(); System.arraycopy(buf.data_, buf.pos_, buf_.data_, buf_.pos_, n); buf.pos_ += n; buf_.pos_ += n; } } break; } case org.omg.CORBA.TCKind._tk_double: case org.omg.CORBA.TCKind._tk_longlong: case org.omg.CORBA.TCKind._tk_ulonglong: { if (obin == null || obin.swap_) { long[] l = new long[len]; in.read_longlong_array(l, 0, len); write_longlong_array(l, 0, len); } else { // Read one value for the alignment write_longlong(obin.read_longlong()); final int n = 8 * (len - 1); if (n > 0) { // Copy the rest addCapacity(n); org.apache.yoko.orb.OCI.Buffer buf = obin ._OB_buffer(); System.arraycopy(buf.data_, buf.pos_, buf_.data_, buf_.pos_, n); buf.pos_ += n; buf_.pos_ += n; } } break; } case org.omg.CORBA.TCKind._tk_boolean: case org.omg.CORBA.TCKind._tk_octet: if (obin == null) { addCapacity(len); in.read_octet_array(buf_.data_, buf_.pos_, len); buf_.pos_ += len; } else { addCapacity(len); org.apache.yoko.orb.OCI.Buffer buf = obin ._OB_buffer(); System.arraycopy(buf.data_, buf.pos_, buf_.data_, buf_.pos_, len); buf.pos_ += len; buf_.pos_ += len; } break; case org.omg.CORBA.TCKind._tk_char: if (charWriterRequired_ || charConversionRequired_) { char[] ch = new char[len]; in.read_char_array(ch, 0, len); write_char_array(ch, 0, len); } else { addCapacity(len); in.read_octet_array(buf_.data_, buf_.pos_, len); buf_.pos_ += len; } break; case org.omg.CORBA.TCKind._tk_wchar: { char[] wch = new char[len]; in.read_wchar_array(wch, 0, len); write_wchar_array(wch, 0, len); break; } case org.omg.CORBA.TCKind._tk_alias: org.apache.yoko.orb.OB.Assert._OB_assert("tk_alias not supported in tk_array or tk_sequence"); break; default: for (int i = 0; i < len; i++) write_InputStream(in, tc.content_type()); break; } } break; } case org.omg.CORBA.TCKind._tk_alias: write_InputStream(in, tc.content_type()); break; case org.omg.CORBA.TCKind._tk_value: case org.omg.CORBA.TCKind._tk_value_box: if (obin == null) { org.omg.CORBA_2_3.portable.InputStream i = (org.omg.CORBA_2_3.portable.InputStream) in; write_value(i.read_value()); } else obin._OB_remarshalValue(tc, this); break; case org.omg.CORBA.TCKind._tk_abstract_interface: { boolean b = in.read_boolean(); write_boolean(b); if (b) { write_Object(in.read_Object()); } else { if (obin == null) { org.omg.CORBA_2_3.portable.InputStream i = (org.omg.CORBA_2_3.portable.InputStream) in; write_value(i.read_value()); } else { // // We have no TypeCode information about the // valuetype, so we must use _tc_ValueBase and // rely on the type information sent on the wire // obin._OB_remarshalValue(org.omg.CORBA.ValueBaseHelper .type(), this); } } break; } case org.omg.CORBA_2_4.TCKind._tk_local_interface: case org.omg.CORBA.TCKind._tk_native: default: org.apache.yoko.orb.OB.Assert._OB_assert("unsupported types"); } } catch (org.omg.CORBA.TypeCodePackage.BadKind ex) { org.apache.yoko.orb.OB.Assert._OB_assert(ex); } catch (org.omg.CORBA.TypeCodePackage.Bounds ex) { org.apache.yoko.orb.OB.Assert._OB_assert(ex); } } // ------------------------------------------------------------------ // Yoko internal functions // Application programs must not use these functions directly // ------------------------------------------------------------------ public OutputStream(org.apache.yoko.orb.OCI.Buffer buf) { this(buf, null, null); } public OutputStream(org.apache.yoko.orb.OCI.Buffer buf, org.apache.yoko.orb.OB.CodeConverters converters, GiopVersion giopVersion) { buf_ = buf; if (giopVersion != null) giopVersion_ = giopVersion; charWriterRequired_ = false; charConversionRequired_ = false; wCharWriterRequired_ = false; wCharConversionRequired_ = false; codeConverters_ = new org.apache.yoko.orb.OB.CodeConverters(converters); if (converters != null) { if (codeConverters_.outputCharConverter != null) { charWriterRequired_ = codeConverters_.outputCharConverter .writerRequired(); charConversionRequired_ = codeConverters_.outputCharConverter .conversionRequired(); } if (codeConverters_.outputWcharConverter != null) { wCharWriterRequired_ = codeConverters_.outputWcharConverter .writerRequired(); wCharConversionRequired_ = codeConverters_.outputWcharConverter .conversionRequired(); } } } public org.apache.yoko.orb.OCI.Buffer _OB_buffer() { return buf_; } public int _OB_pos() { return buf_.pos_; } public void _OB_pos(int pos) { buf_.pos_ = pos; } public void _OB_align(int n) { if (buf_.pos_ % n != 0) addCapacity(0, n); } public void _OB_alignNext(int n) { alignNext_ = n; } public void _OB_writeEndian() { write_boolean(false); // false means big endian } public void _OB_beginValue(int tag, String[] ids, boolean chunked) { valueWriter().beginValue(tag, ids, null, chunked); } public void _OB_endValue() { valueWriter().endValue(); } // Java only public void _OB_ORBInstance(org.apache.yoko.orb.OB.ORBInstance orbInstance) { orbInstance_ = orbInstance; } // Java only public org.apache.yoko.orb.OB.ORBInstance _OB_ORBInstance() { return orbInstance_; } // Java only public void _OB_invocationContext(java.lang.Object invocationContext) { invocationContext_ = invocationContext; } // Java only public java.lang.Object _OB_invocationContext() { return invocationContext_; } // Java only public void _OB_delegateContext(java.lang.Object delegateContext) { delegateContext_ = delegateContext; } // Java only public java.lang.Object _OB_delegateContext() { return delegateContext_; } @Override public void end_value() { _OB_endValue(); } @Override public void start_value(String rep_id) { final int tag = 0x7fffff02; final String[] ids = { rep_id }; _OB_beginValue(tag, ids, true); } }
{ "content_hash": "76ec513e3c9c5267954b475bcbb709e1", "timestamp": "", "source": "github", "line_count": 1956, "max_line_length": 120, "avg_line_length": 35.05163599182004, "alnum_prop": 0.44335701054535376, "repo_name": "apache/geronimo-yoko", "id": "c9f627f285739a0561aa913613983d8c0cc7c63f", "size": "69368", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "yoko-core/src/main/java/org/apache/yoko/orb/CORBA/OutputStream.java", "mode": "33188", "license": "apache-2.0", "language": [], "symlink_target": "" }
// This file contains the definition of abstract functions in the // cross platform API so that we can use it for serialization of the // scene graph on all systems without needing graphics. #include "converter/cross/renderer_stub.h" #include "core/cross/object_manager.h" #include "core/cross/service_locator.h" #include "converter/cross/buffer_stub.h" #include "converter/cross/draw_element_stub.h" #include "converter/cross/effect_stub.h" #include "converter/cross/param_cache_stub.h" #include "converter/cross/primitive_stub.h" #include "converter/cross/render_surface_stub.h" #include "converter/cross/sampler_stub.h" #include "converter/cross/stream_bank_stub.h" #include "converter/cross/texture_stub.h" namespace o3d { Renderer* RendererStub::CreateDefault(ServiceLocator* service_locator) { return new RendererStub(service_locator); } RendererStub::RendererStub(ServiceLocator* service_locator) : Renderer(service_locator) { } Renderer::InitStatus RendererStub::InitPlatformSpecific( const DisplayWindow&, bool) { DCHECK(false); return SUCCESS; } void RendererStub::InitCommon() { } void RendererStub::UninitCommon() { } void RendererStub::Destroy(void) { DCHECK(false); } bool RendererStub::PlatformSpecificBeginDraw(void) { DCHECK(false); return true; } void RendererStub::PlatformSpecificEndDraw(void) { DCHECK(false); } bool RendererStub::PlatformSpecificStartRendering(void) { DCHECK(false); return true; } void RendererStub::PlatformSpecificFinishRendering(void) { DCHECK(false); } void RendererStub::Resize(int, int) { DCHECK(false); } void RendererStub::PlatformSpecificClear( const Float4 &, bool, float, bool, int, bool) { DCHECK(false); } void RendererStub::SetRenderSurfacesPlatformSpecific( const RenderSurface* surface, const RenderDepthStencilSurface* surface_depth) { DCHECK(false); } void RendererStub::SetBackBufferPlatformSpecific() { DCHECK(false); } void RendererStub::ApplyDirtyStates() { DCHECK(false); } Primitive::Ref RendererStub::CreatePrimitive(void) { return Primitive::Ref(new PrimitiveStub(service_locator())); } DrawElement::Ref RendererStub::CreateDrawElement(void) { return DrawElement::Ref(new DrawElementStub(service_locator())); } VertexBuffer::Ref RendererStub::CreateVertexBuffer(void) { return VertexBuffer::Ref(new VertexBufferStub(service_locator())); } IndexBuffer::Ref RendererStub::CreateIndexBuffer(void) { return IndexBuffer::Ref(new IndexBufferStub(service_locator())); } Effect::Ref RendererStub::CreateEffect(void) { return Effect::Ref(new EffectStub(service_locator())); } Sampler::Ref RendererStub::CreateSampler(void) { return Sampler::Ref(new SamplerStub(service_locator())); } Texture2D::Ref RendererStub::CreatePlatformSpecificTexture2D( int width, int height, Texture::Format format, int levels, bool enable_render_surfaces) { return Texture2D::Ref(new Texture2DStub(service_locator(), width, height, format, levels, enable_render_surfaces)); } TextureCUBE::Ref RendererStub::CreatePlatformSpecificTextureCUBE( int edge_length, Texture::Format format, int levels, bool enable_render_surfaces) { return TextureCUBE::Ref(new TextureCUBEStub(service_locator(), edge_length, format, levels, enable_render_surfaces)); } RenderDepthStencilSurface::Ref RendererStub::CreateDepthStencilSurface( int width, int height) { return RenderDepthStencilSurface::Ref( new RenderDepthStencilSurfaceStub(service_locator(), width, height)); } StreamBank::Ref RendererStub::CreateStreamBank() { return StreamBank::Ref(new StreamBankStub(service_locator())); } ParamCache *RendererStub::CreatePlatformSpecificParamCache(void) { return new ParamCacheStub; } void RendererStub::SetViewportInPixels(int, int, int, int, float, float) { DCHECK(false); } bool RendererStub::GoFullscreen(const DisplayWindow& display, int mode_id) { return false; } bool RendererStub::CancelFullscreen(const DisplayWindow& display, int width, int height) { return false; } bool RendererStub::fullscreen() const { return false; } void RendererStub::GetDisplayModes(std::vector<DisplayMode> *modes) { modes->clear(); } bool RendererStub::GetDisplayMode(int id, DisplayMode *mode) { return false; } void RendererStub::PlatformSpecificPresent(void) { } const int* RendererStub::GetRGBAUByteNSwizzleTable() { static int swizzle_table[] = { 0, 1, 2, 3, }; return swizzle_table; } // This is a factory function for creating Renderer objects. Since // we're implementing a stub renderer, we only ever return a stub renderer. Renderer* Renderer::CreateDefaultRenderer(ServiceLocator* service_locator) { return RendererStub::CreateDefault(service_locator); } } // namespace o3d
{ "content_hash": "42fc4b0cc68687d1ce86c28fb9769075", "timestamp": "", "source": "github", "line_count": 191, "max_line_length": 76, "avg_line_length": 27.387434554973822, "alnum_prop": 0.6912636207226152, "repo_name": "rwatson/chromium-capsicum", "id": "0f11826bb996d23d3168d82e60802b082c3cbdbb", "size": "6793", "binary": false, "copies": "1", "ref": "refs/heads/chromium-capsicum", "path": "o3d/converter/cross/renderer_stub.cc", "mode": "33188", "license": "bsd-3-clause", "language": [], "symlink_target": "" }
""" tox._quickstart ~~~~~~~~~~~~~~~~~ Command-line script to quickly setup tox.ini for a Python project This file was heavily inspired by and uses code from ``sphinx-quickstart`` in the BSD-licensed `Sphinx project`_. .. Sphinx project_: http://sphinx.pocoo.org/ License for Sphinx ================== Copyright (c) 2007-2011 by the Sphinx team (see AUTHORS file). All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. """ import sys from os import path from codecs import open TERM_ENCODING = getattr(sys.stdin, 'encoding', None) from tox_plus import __version__ # function to get input from terminal -- overridden by the test suite try: # this raw_input is not converted by 2to3 term_input = raw_input except NameError: term_input = input all_envs = ['py26', 'py27', 'py32', 'py33', 'py34', 'py35', 'pypy', 'jython'] PROMPT_PREFIX = '> ' QUICKSTART_CONF = '''\ # Tox (http://tox.testrun.org/) is a tool for running tests # in multiple virtualenvs. This configuration file will run the # test suite on all supported python versions. To use it, "pip install tox" # and then run "tox" from this directory. [tox] envlist = %(envlist)s [testenv] commands = %(commands)s deps = %(deps)s ''' class ValidationError(Exception): """Raised for validation errors.""" def nonempty(x): if not x: raise ValidationError("Please enter some text.") return x def choice(*l): def val(x): if x not in l: raise ValidationError('Please enter one of %s.' % ', '.join(l)) return x return val def boolean(x): if x.upper() not in ('Y', 'YES', 'N', 'NO'): raise ValidationError("Please enter either 'y' or 'n'.") return x.upper() in ('Y', 'YES') def suffix(x): if not (x[0:1] == '.' and len(x) > 1): raise ValidationError("Please enter a file suffix, " "e.g. '.rst' or '.txt'.") return x def ok(x): return x def do_prompt(d, key, text, default=None, validator=nonempty): while True: if default: prompt = PROMPT_PREFIX + '%s [%s]: ' % (text, default) else: prompt = PROMPT_PREFIX + text + ': ' x = term_input(prompt) if default and not x: x = default if sys.version_info < (3, ) and not isinstance(x, unicode): # for Python 2.x, try to get a Unicode string out of it if x.decode('ascii', 'replace').encode('ascii', 'replace') != x: if TERM_ENCODING: x = x.decode(TERM_ENCODING) else: print('* Note: non-ASCII characters entered ' 'and terminal encoding unknown -- assuming ' 'UTF-8 or Latin-1.') try: x = x.decode('utf-8') except UnicodeDecodeError: x = x.decode('latin1') try: x = validator(x) except ValidationError: err = sys.exc_info()[1] print('* ' + str(err)) continue break d[key] = x def ask_user(d): """Ask the user for quickstart values missing from *d*. """ print('Welcome to the Tox %s quickstart utility.' % __version__) print(''' This utility will ask you a few questions and then generate a simple tox.ini file to help get you started using tox. Please enter values for the following settings (just press Enter to accept a default value, if one is given in brackets).''') sys.stdout.write('\n') print(''' What Python versions do you want to test against? Choices: [1] py27 [2] py27, py33 [3] (All versions) %s [4] Choose each one-by-one''' % ', '.join(all_envs)) do_prompt(d, 'canned_pyenvs', 'Enter the number of your choice', '3', choice('1', '2', '3', '4')) if d['canned_pyenvs'] == '1': d['py27'] = True elif d['canned_pyenvs'] == '2': for pyenv in ('py27', 'py33'): d[pyenv] = True elif d['canned_pyenvs'] == '3': for pyenv in all_envs: d[pyenv] = True elif d['canned_pyenvs'] == '4': for pyenv in all_envs: if pyenv not in d: do_prompt(d, pyenv, 'Test your project with %s (Y/n)' % pyenv, 'Y', boolean) print(''' What command should be used to test your project -- examples: - py.test - python setup.py test - nosetests package.module - trial package.module''') do_prompt(d, 'commands', 'Command to run to test project', '{envpython} setup.py test') default_deps = ' ' if 'py.test' in d['commands']: default_deps = 'pytest' if 'nosetests' in d['commands']: default_deps = 'nose' if 'trial' in d['commands']: default_deps = 'twisted' print(''' What extra dependencies do your tests have?''') do_prompt(d, 'deps', 'Comma-separated list of dependencies', default_deps) def process_input(d): d['envlist'] = ', '.join([env for env in all_envs if d.get(env) is True]) d['deps'] = '\n' + '\n'.join([ ' %s' % dep.strip() for dep in d['deps'].split(',')]) return d def rtrim_right(text): lines = [] for line in text.split("\n"): lines.append(line.rstrip()) return "\n".join(lines) def generate(d, overwrite=True, silent=False): """Generate project based on values in *d*.""" conf_text = QUICKSTART_CONF % d conf_text = rtrim_right(conf_text) def write_file(fpath, mode, content): print('Creating file %s.' % fpath) f = open(fpath, mode, encoding='utf-8') try: f.write(content) finally: f.close() sys.stdout.write('\n') fpath = 'tox.ini' if path.isfile(fpath) and not overwrite: print('File %s already exists.' % fpath) do_prompt(d, 'fpath', 'Alternative path to write tox.ini contents to', 'tox-generated.ini') fpath = d['fpath'] write_file(fpath, 'w', conf_text) if silent: return sys.stdout.write('\n') print('Finished: A tox.ini file has been created. For information on this file, ' 'see http://tox.testrun.org/latest/config.html') print(''' Execute `tox` to test your project. ''') def main(argv=sys.argv): d = {} if len(argv) > 3: print('Usage: tox-quickstart [root]') sys.exit(1) elif len(argv) == 2: d['path'] = argv[1] try: ask_user(d) except (KeyboardInterrupt, EOFError): print() print('[Interrupted.]') return d = process_input(d) generate(d, overwrite=False) if __name__ == '__main__': main()
{ "content_hash": "812fbedf8220d298936985113639c672", "timestamp": "", "source": "github", "line_count": 274, "max_line_length": 99, "avg_line_length": 29.251824817518248, "alnum_prop": 0.5962570180910792, "repo_name": "Itxaka/tox-plus", "id": "cd6dbfb2f556cbe5f4dd58d4e69c5d0cb2f2a818", "size": "8039", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "tox_plus/_quickstart.py", "mode": "33188", "license": "mit", "language": [ { "name": "Python", "bytes": "248306" } ], "symlink_target": "" }
<?php namespace Drupal\Core\Installer\Form; use Drupal\Component\Utility\Crypt; use Drupal\Core\Database\Database; use Drupal\Core\File\FileSystemInterface; use Drupal\Core\Form\FormBase; use Drupal\Core\Form\FormStateInterface; use Drupal\Core\Render\RendererInterface; use Drupal\Core\Site\Settings; use Symfony\Component\DependencyInjection\ContainerInterface; /** * Provides a form to configure and rewrite settings.php. * * @internal */ class SiteSettingsForm extends FormBase { /** * The site path. * * @var string */ protected $sitePath; /** * The renderer. * * @var \Drupal\Core\Render\RendererInterface */ protected $renderer; /** * Constructs a new SiteSettingsForm. * * @param string $site_path * The site path. * @param \Drupal\Core\Render\RendererInterface $renderer * The renderer. */ public function __construct($site_path, RendererInterface $renderer) { $this->sitePath = $site_path; $this->renderer = $renderer; } /** * {@inheritdoc} */ public static function create(ContainerInterface $container) { return new static( $container->getParameter('site.path'), $container->get('renderer') ); } /** * {@inheritdoc} */ public function getFormId() { return 'install_settings_form'; } /** * {@inheritdoc} */ public function buildForm(array $form, FormStateInterface $form_state) { $settings_file = './' . $this->sitePath . '/settings.php'; $form['#title'] = $this->t('Database configuration'); $drivers = drupal_get_database_types(); $drivers_keys = array_keys($drivers); // Unless there is input for this form (for a non-interactive installation, // input originates from the $settings array passed into install_drupal()), // check whether database connection settings have been prepared in // settings.php already. // Note: The installer even executes this form if there is a valid database // connection already, since the submit handler of this form is responsible // for writing all $settings to settings.php (not limited to $databases). $input = &$form_state->getUserInput(); if (!isset($input['driver']) && $database = Database::getConnectionInfo()) { $input['driver'] = $database['default']['driver']; $input[$database['default']['driver']] = $database['default']; } if (isset($input['driver'])) { $default_driver = $input['driver']; // In case of database connection info from settings.php, as well as for a // programmed form submission (non-interactive installer), the table prefix // information is usually normalized into an array already, but the form // element only allows to configure one default prefix for all tables. $prefix = &$input[$default_driver]['prefix']; if (isset($prefix) && is_array($prefix)) { $prefix = $prefix['default']; } $default_options = $input[$default_driver]; } // If there is no database information yet, suggest the first available driver // as default value, so that its settings form is made visible via #states // when JavaScript is enabled (see below). else { $default_driver = current($drivers_keys); $default_options = []; } $form['driver'] = [ '#type' => 'radios', '#title' => $this->t('Database type'), '#required' => TRUE, '#default_value' => $default_driver, ]; if (count($drivers) == 1) { $form['driver']['#disabled'] = TRUE; } // Add driver specific configuration options. foreach ($drivers as $key => $driver) { $form['driver']['#options'][$key] = $driver->name(); $form['settings'][$key] = $driver->getFormOptions($default_options); $form['settings'][$key]['#prefix'] = '<h2 class="js-hide">' . $this->t('@driver_name settings', ['@driver_name' => $driver->name()]) . '</h2>'; $form['settings'][$key]['#type'] = 'container'; $form['settings'][$key]['#tree'] = TRUE; $form['settings'][$key]['advanced_options']['#parents'] = [$key]; $form['settings'][$key]['#states'] = [ 'visible' => [ ':input[name=driver]' => ['value' => $key], ], ]; } $form['actions'] = ['#type' => 'actions']; $form['actions']['save'] = [ '#type' => 'submit', '#value' => $this->t('Save and continue'), '#button_type' => 'primary', '#limit_validation_errors' => [ ['driver'], [$default_driver], ], '#submit' => ['::submitForm'], ]; $form['errors'] = []; $form['settings_file'] = ['#type' => 'value', '#value' => $settings_file]; return $form; } /** * {@inheritdoc} */ public function validateForm(array &$form, FormStateInterface $form_state) { $driver = $form_state->getValue('driver'); $database = $form_state->getValue($driver); $drivers = drupal_get_database_types(); $reflection = new \ReflectionClass($drivers[$driver]); $install_namespace = $reflection->getNamespaceName(); // Cut the trailing \Install from namespace. $database['namespace'] = substr($install_namespace, 0, strrpos($install_namespace, '\\')); $database['driver'] = $driver; // See default.settings.php for an explanation of the 'autoload' key. if ($autoload = Database::findDriverAutoloadDirectory($database['namespace'], DRUPAL_ROOT)) { $database['autoload'] = $autoload; } $form_state->set('database', $database); foreach ($this->getDatabaseErrors($database, $form_state->getValue('settings_file')) as $name => $message) { $form_state->setErrorByName($name, $message); } } /** * Get any database errors and links them to a form element. * * @param array $database * An array of database settings. * @param string $settings_file * The settings file that contains the database settings. * * @return array * An array of form errors keyed by the element name and parents. */ protected function getDatabaseErrors(array $database, $settings_file) { $errors = install_database_errors($database, $settings_file); $form_errors = array_filter($errors, function ($value) { // Errors keyed by something other than an integer already are linked to // form elements. return is_int($value); }); // Find the generic errors. $errors = array_diff_key($errors, $form_errors); if (count($errors)) { $error_message = static::getDatabaseErrorsTemplate($errors); // These are generic errors, so we do not have any specific key of the // database connection array to attach them to; therefore, we just put // them in the error array with standard numeric keys. $form_errors[$database['driver'] . '][0'] = $this->renderer->renderPlain($error_message); } return $form_errors; } /** * Gets the inline template render array to display the database errors. * * @param \Drupal\Core\StringTranslation\TranslatableMarkup[] $errors * The database errors to list. * * @return mixed[] * The inline template render array to display the database errors. */ public static function getDatabaseErrorsTemplate(array $errors) { return [ '#type' => 'inline_template', '#template' => '{% trans %}Resolve all issues below to continue the installation. For help configuring your database server, see the <a href="https://www.drupal.org/docs/8/install">installation handbook</a>, or contact your hosting provider.{% endtrans %}{{ errors }}', '#context' => [ 'errors' => [ '#theme' => 'item_list', '#items' => $errors, ], ], ]; } /** * {@inheritdoc} */ public function submitForm(array &$form, FormStateInterface $form_state) { global $install_state; // Update global settings array and save. $settings = []; $database = $form_state->get('database'); $settings['databases']['default']['default'] = (object) [ 'value' => $database, 'required' => TRUE, ]; $settings['settings']['hash_salt'] = (object) [ 'value' => Crypt::randomBytesBase64(55), 'required' => TRUE, ]; // If settings.php does not contain a config sync directory name we need to // configure one. if (empty(Settings::get('config_sync_directory'))) { if (empty($install_state['config_install_path'])) { // Add a randomized config directory name to settings.php $config_sync_directory = $this->createRandomConfigDirectory(); } else { // Install profiles can contain a config sync directory. If they do, // 'config_install_path' is a path to the directory. $config_sync_directory = $install_state['config_install_path']; } $settings['settings']['config_sync_directory'] = (object) [ 'value' => $config_sync_directory, 'required' => TRUE, ]; } drupal_rewrite_settings($settings); // Indicate that the settings file has been verified, and check the database // for the last completed task, now that we have a valid connection. This // last step is important since we want to trigger an error if the new // database already has Drupal installed. $install_state['settings_verified'] = TRUE; $install_state['config_verified'] = TRUE; $install_state['database_verified'] = TRUE; $install_state['completed_task'] = install_verify_completed_task(); } /** * Create a random config sync directory. * * @return string * The path to the generated config sync directory. */ protected function createRandomConfigDirectory() { $config_sync_directory = $this->sitePath . '/files/config_' . Crypt::randomBytesBase64(55) . '/sync'; // This should never fail, it is created here inside the public files // directory, which has already been verified to be writable itself. if (\Drupal::service('file_system')->prepareDirectory($config_sync_directory, FileSystemInterface::CREATE_DIRECTORY | FileSystemInterface::MODIFY_PERMISSIONS)) { // Put a README.txt into the sync config directory. This is required so // that they can later be added to git. Since this directory is // auto-created, we have to write out the README rather than just adding // it to the drupal core repo. $text = 'This directory contains configuration to be imported into your Drupal site. To make this configuration active, visit admin/config/development/configuration/sync.' . ' For information about deploying configuration between servers, see https://www.drupal.org/documentation/administer/config'; file_put_contents($config_sync_directory . '/README.txt', $text); } return $config_sync_directory; } }
{ "content_hash": "b0f48257c1da16a2dc191cb6870c6a1b", "timestamp": "", "source": "github", "line_count": 301, "max_line_length": 305, "avg_line_length": 36.00332225913621, "alnum_prop": 0.6359693642151887, "repo_name": "electric-eloquence/fepper-drupal", "id": "233853e4b544d15849fd3b0a350e3e841275925d", "size": "10837", "binary": false, "copies": "11", "ref": "refs/heads/dev", "path": "backend/drupal/core/lib/Drupal/Core/Installer/Form/SiteSettingsForm.php", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "2300765" }, { "name": "HTML", "bytes": "68444" }, { "name": "JavaScript", "bytes": "2453602" }, { "name": "Mustache", "bytes": "40698" }, { "name": "PHP", "bytes": "41684915" }, { "name": "PowerShell", "bytes": "755" }, { "name": "Shell", "bytes": "72896" }, { "name": "Stylus", "bytes": "32803" }, { "name": "Twig", "bytes": "1820730" }, { "name": "VBScript", "bytes": "466" } ], "symlink_target": "" }
import Table from './table'; export default Table;
{ "content_hash": "bad22b5a404bd985420a39e78902bf3b", "timestamp": "", "source": "github", "line_count": 3, "max_line_length": 28, "avg_line_length": 17.333333333333332, "alnum_prop": 0.7307692307692307, "repo_name": "frozenarc/react-abstract-table", "id": "434070a474c0b85541cc8a115862be97dd42837d", "size": "52", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "src/index.js", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "HTML", "bytes": "207" }, { "name": "JavaScript", "bytes": "16569" } ], "symlink_target": "" }
<?xml version="1.0" encoding="utf-8"?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en"> <head> <meta content="text/html; charset=CP850" http-equiv="Content-Type" /> <title>File: domain.rb [rhc-1.38.4 Documentation]</title> <link type="text/css" media="screen" href="../../../rdoc.css" rel="stylesheet" /> <script src="../../../js/jquery.js" type="text/javascript" charset="utf-8"></script> <script src="../../../js/thickbox-compressed.js" type="text/javascript" charset="utf-8"></script> <script src="../../../js/quicksearch.js" type="text/javascript" charset="utf-8"></script> <script src="../../../js/darkfish.js" type="text/javascript" charset="utf-8"></script> </head> <body class="file file-popup"> <div id="metadata"> <dl> <dt class="modified-date">Last Modified</dt> <dd class="modified-date">2016-06-06 13:45:57 +0200</dd> <dt class="requires">Requires</dt> <dd class="requires"> <ul> <li>rhc/commands/base</li> </ul> </dd> </dl> </div> <div id="documentation"> <div class="description"> <h2>Description</h2> </div> </div> </body> </html>
{ "content_hash": "18aaad1deb1c96cb2efc2aed0eb25707", "timestamp": "", "source": "github", "line_count": 54, "max_line_length": 83, "avg_line_length": 25.166666666666668, "alnum_prop": 0.5710080941869021, "repo_name": "wpm-org/wpm", "id": "dcd644763bbb7294834e97a89ba1dde644b3cdbe", "size": "1359", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "lang/ruby/Ruby193/lib/ruby/gems/1.9.1/doc/rhc-1.38.4/rdoc/lib/rhc/commands/domain_rb.html", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Batchfile", "bytes": "2822" }, { "name": "HTML", "bytes": "7833" } ], "symlink_target": "" }
/* * Minio Cloud Storage, (C) 2015 Minio, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package rpc import ( "net/http" "time" ) // Args basic json RPC params type Args struct { Request string } // VersionReply version reply type VersionReply struct { Version string `json:"version"` BuildDate string `json:"build-date"` } // VersionService - type VersionService struct{} func getVersion() string { return "0.0.1" } func getBuildDate() string { return time.Now().UTC().Format(http.TimeFormat) } func setVersionReply(reply *VersionReply) { reply.Version = getVersion() reply.BuildDate = getBuildDate() return } // Get method func (v *VersionService) Get(r *http.Request, args *Args, reply *VersionReply) error { setVersionReply(reply) return nil }
{ "content_hash": "c645fcb5ef7a414b09a4358a0483955d", "timestamp": "", "source": "github", "line_count": 55, "max_line_length": 86, "avg_line_length": 23.472727272727273, "alnum_prop": 0.7257939581719597, "repo_name": "kahing/minio", "id": "9ea8315527f0c3f3fc1a86ed455cde66e8fbea68", "size": "1291", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "pkg/controller/rpc/version.go", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Assembly", "bytes": "543471" }, { "name": "C", "bytes": "479081" }, { "name": "Go", "bytes": "522747" }, { "name": "Makefile", "bytes": "1930" }, { "name": "Shell", "bytes": "7137" } ], "symlink_target": "" }
package com.jipasoft.sample.client.ui.users; import com.google.gwt.core.client.GWT; import com.google.gwt.dom.client.TableCellElement; import com.google.gwt.dom.client.TableElement; import com.google.gwt.dom.client.TableRowElement; import com.google.gwt.uibinder.client.UiBinder; import com.google.gwt.uibinder.client.UiField; import com.google.gwt.user.client.Window; import com.google.gwt.user.client.rpc.AsyncCallback; import com.google.gwt.user.client.ui.Widget; import com.jipasoft.sample.client.Content; import com.jipasoft.sample.client.service.UserService; import com.jipasoft.sample.client.service.UserServiceAsync; import com.jipasoft.sample.shared.model.User; public class List extends Content { private static ListUiBinder uiBinder = GWT.create(ListUiBinder.class); /** * The message displayed to the user when the server cannot be reached or * returns an error. */ // @formatter:off private static final String SERVER_ERROR = "An error occurred while " + "attempting to contact the server. Please check your network " + "connection and try again."; // @formatter:on private final UserServiceAsync userService = GWT.create(UserService.class); @UiField TableElement table; interface ListUiBinder extends UiBinder<Widget, List> { } public List() { initWidget(uiBinder.createAndBindUi(this)); userService.findAll(new AsyncCallback<java.util.List<User>>() { @Override public void onSuccess(java.util.List<User> result) { createTable(result); } @Override public void onFailure(Throwable caught) { Window.alert(SERVER_ERROR); } }); } private void createTable(java.util.List<User> result) { if (result == null || result.size() == 0) { final TableRowElement row = table.insertRow(1); TableCellElement cell = row.insertCell(0); cell.setColSpan(5); cell.setInnerHTML("No data found"); return; } TableRowElement row = null; int i = 1; for (User user : result) { row = table.insertRow(i); row.insertCell(0).setInnerHTML(String.valueOf(user.getId())); row.insertCell(1).setInnerHTML(user.getName()); row.insertCell(2).setInnerHTML(user.getEmail()); row.insertCell(3).setInnerHTML(user.getFramework().toString()); row.insertCell(4).setInnerHTML(button("")); i++; } } private String button(String id) { //@formatter:off String buttons = "<button class=\"btn btn-info\">Query</button> " + "<button class=\"btn btn-primary\">Update</button> " + "<button class=\"btn btn-danger\">Delete</button>"; //@formatter:on return buttons; } @Override public String getHtmlTitle() { return "List || GWT Maven Application"; } }
{ "content_hash": "91f1e81d22c3c9d6ce251f57fa3c8715", "timestamp": "", "source": "github", "line_count": 98, "max_line_length": 76, "avg_line_length": 27.255102040816325, "alnum_prop": 0.7199550730063646, "repo_name": "jipaman/gwt-maven-sample", "id": "6b3112c3cb2bcdb91ca36459a28a253957fe2a4f", "size": "2671", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/main/java/com/jipasoft/sample/client/ui/users/List.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "247986" }, { "name": "HTML", "bytes": "4474" }, { "name": "Java", "bytes": "30539" }, { "name": "JavaScript", "bytes": "484" } ], "symlink_target": "" }
<link rel="import" href="../polymer/polymer.html"> <link rel="import" href="../core-animated-pages/core-animated-pages.html"> <link rel="import" href="../core-animated-pages/transitions/slide-from-right.html"> <link rel="import" href="../core-header-panel/core-header-panel.html"> <link rel="import" href="../core-icons/av-icons.html"> <link rel="import" href="../core-icons/editor-icons.html"> <link rel="import" href="../core-pages/core-pages.html"> <link rel="import" href="../core-toolbar/core-toolbar.html"> <link rel="import" href="../paper-button/paper-button.html"> <link rel="import" href="../paper-fab/paper-fab.html"> <link rel="import" href="../paper-icon-button/paper-icon-button.html"> <link rel="import" href="../paper-progress/paper-progress.html"> <link rel="import" href="../paper-shadow/paper-shadow.html"> <link rel="import" href="../paper-spinner/paper-spinner.html"> <link rel="import" href="../paper-tabs/paper-tabs.html"> <link rel="import" href="../dartpad-edit-page/dartpad-edit-page.html"> <link rel="import" href="../dartpad-exec-page/dartpad-exec-page.html"> <polymer-element name="dartpad-app" attributes="selected" vertical layout> <template vertical layout> <style> </style> <core-animated-pages transitions="slide-from-right" selected="0" flex> <section id="edit-page" fit> <dartpad-edit-page selected="0" fit slide-from-right></<dartpad-edit-page>> </section> <section id="exec-page" fit> <dartpad-exec-page fit slide-from-right></dartpad-exec-page> </section> </core-animated-pages> </template> <script> (function() { Polymer('dartpad-app', { }); })(); </script> </polymer-element>
{ "content_hash": "9393deb292dd6184d95bdadba110b4e5", "timestamp": "", "source": "github", "line_count": 44, "max_line_length": 83, "avg_line_length": 37.65909090909091, "alnum_prop": 0.6946288473144236, "repo_name": "devoncarew/dartpad_mobile", "id": "ba3884244a9f235bf4036136e60d3c8ed45b71a9", "size": "1658", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "lib/dartpad-app/dartpad-app.html", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "CSS", "bytes": "50630" }, { "name": "Dart", "bytes": "46964" }, { "name": "HTML", "bytes": "1266310" }, { "name": "JavaScript", "bytes": "1223363" }, { "name": "Shell", "bytes": "2513" } ], "symlink_target": "" }
ActiveRecord::Base.class_eval do def self.find_by_to_param(*param) self.find_by_id(*param) end def self.find_by_to_param!(*param) to_return = self.find_by_to_param(*param) unless to_return raise ActiveRecord::RecordNotFound, "Couldn't find #{self.name} with param=#{param.inspect}" end to_return end def self.as_param(param_name) self.class_eval do eval %Q{ def to_param self.#{param_name}.to_s end def self.find_by_to_param(*arg) self.find_by_#{param_name.to_s}(*arg) end } end end end
{ "content_hash": "8e363072508e99767f86cd02097a9168", "timestamp": "", "source": "github", "line_count": 29, "max_line_length": 98, "avg_line_length": 21.275862068965516, "alnum_prop": 0.580226904376013, "repo_name": "brontes3d/find_by_to_param", "id": "f13e56203be09a9e7beb2d03790823e1647349de", "size": "617", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "init.rb", "mode": "33188", "license": "mit", "language": [ { "name": "Ruby", "bytes": "2462" } ], "symlink_target": "" }
package io.gatling.http.check.body import io.gatling.{ BaseSpec, ValidationValues } import io.gatling.commons.validation.Success import io.gatling.core.CoreDsl import io.gatling.core.EmptySession import io.gatling.core.check.{ Check, CheckResult } import io.gatling.core.config.GatlingConfiguration import io.gatling.core.session.Session import io.gatling.http.HttpDsl import io.gatling.http.check.HttpCheck import io.gatling.http.response.Response class ConditionalCheckSpec extends BaseSpec with ValidationValues with CoreDsl with HttpDsl with EmptySession { override implicit val configuration: GatlingConfiguration = GatlingConfiguration.loadForTest() "checkIf.true.succeed" should "perform the succeed nested check" in { val response = mockResponse("""[{"id":"1072920417"},"id":"1072920418"]""") val thenCheck: HttpCheck = substring(""""id":"""").count val check: HttpCheck = checkIf((_: Response, _: Session) => Success(true))(thenCheck) check.check(response, emptySession, Check.newPreparedCache).succeeded shouldBe CheckResult(Some(2), None) } "checkIf.true.failed" should "perform the failed nested check" in { val response = mockResponse("""[{"id":"1072920417"},"id":"1072920418"]""") val substringValue = """"foo":"""" val thenCheck: HttpCheck = substring(substringValue).findAll.exists val check: HttpCheck = checkIf((_: Response, _: Session) => Success(true))(thenCheck) check.check(response, emptySession, Check.newPreparedCache).failed shouldBe s"substring($substringValue).findAll.exists, found nothing" } "checkIf.false.succeed" should "not perform the succeed nested check" in { val response = mockResponse("""[{"id":"1072920417"},"id":"1072920418"]""") val thenCheck: HttpCheck = substring(""""id":"""").count val check: HttpCheck = checkIf((_: Response, _: Session) => Success(false))(thenCheck) check.check(response, emptySession, Check.newPreparedCache).succeeded shouldBe CheckResult(None, None) } "checkIf.false.failed" should "not perform the failed nested check" in { val response = mockResponse("""[{"id":"1072920417"},"id":"1072920418"]""") val substringValue = """"foo":"""" val thenCheck: HttpCheck = substring(substringValue).findAll.exists val check: HttpCheck = checkIf((_: Response, _: Session) => Success(false))(thenCheck) check.check(response, emptySession, Check.newPreparedCache).succeeded shouldBe CheckResult(None, None) } }
{ "content_hash": "83a5424a0b96e8d74a54306ca3f22d92", "timestamp": "", "source": "github", "line_count": 49, "max_line_length": 139, "avg_line_length": 50.30612244897959, "alnum_prop": 0.7330628803245436, "repo_name": "gatling/gatling", "id": "5f89cd8544914234bc891c41fd5fa5fbbbec37f8", "size": "3082", "binary": false, "copies": "1", "ref": "refs/heads/main", "path": "gatling-http/src/test/scala/io/gatling/http/check/body/ConditionalCheckSpec.scala", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Batchfile", "bytes": "4107" }, { "name": "CSS", "bytes": "18867" }, { "name": "HTML", "bytes": "41444" }, { "name": "Java", "bytes": "1341839" }, { "name": "JavaScript", "bytes": "7567" }, { "name": "Kotlin", "bytes": "104724" }, { "name": "Scala", "bytes": "2616285" }, { "name": "Shell", "bytes": "2074" } ], "symlink_target": "" }
""" This module takes care of capturing the cli options """ import os import sys # see http://stackoverflow.com/questions/16981921/relative-imports-in-python-3 PACKAGE_PARENT = '..' SCRIPT_DIR = os.path.dirname(os.path.realpath(os.path.join(os.getcwd(), os.path.expanduser(__file__)))) sys.path.append(os.path.normpath(os.path.join(SCRIPT_DIR, PACKAGE_PARENT))) import argparse import sys import logging from bprc._version import __version__ as __version__ parser = argparse.ArgumentParser(description='Batch Processing RESTful Client') outputgroup=parser.add_argument_group(title="I/O arguments") logtestgroup=parser.add_argument_group(title="Logging, testing and debugging arguments") protocolgroup=parser.add_argument_group(title="Protocol arguments") parser.add_argument('--version', action='version', version='{} {}'.format(sys.argv[0],__version__), help='shows version number and exits') parser.add_argument('yamlfile', nargs='?', help="YAML recipe file, defaults to stdin", type=argparse.FileType('r'), default=sys.stdin) parser.add_argument('outputfile', nargs='?', help=argparse.SUPPRESS, #help='specifies output file, defaults to stdout', turned off for now. type=argparse.FileType('w'), default=sys.stdout) outputgroup.add_argument('--output-format', dest='outputformat', action='store', choices={'raw-all','raw-response','json'}, default='raw-all', help='specifies output format, defaults to %(default)s') outputgroup.add_argument('--no-color', dest='nocolor', action='store_true', default=False, help='turns off pretty printing for console output') logtestgroup.add_argument('-v', '--verbose', dest='verbose', action='store_true', help='verbose mode', default=False) #TODO implement dry run # logtestgroup.add_argument('-d', '--dry-run', dest='dryrun', action='store_true',default=False, # help='does everything except actually making any HTTP calls') logtestgroup.add_argument('--debug', dest='debug', action='store_true',default=False, help='turns on stacktrace dumps for exceptions') logtestgroup.add_argument('--log-level', dest='loglevel', action='store',default='none', choices={'none','critical','error','warning','info','debug'}, help='sets logging level, defaults to %(default)s') logtestgroup.add_argument('--log-file', dest='logfile', action='store', metavar='logfile', default='bprc.log', help='specifies logfile, defaults to %(default)s') protocolgroup.add_argument('--skip-http-errors', dest='skiphttperrors', action='store_true',default=False, help='moves to the next step if an HTTP 4xx or 5xx response code is returned') protocolgroup.add_argument('--ignore-ssl', dest='ignoressl', action='store_true',default=False, help='do not validate ssl certificates') args = parser.parse_args()
{ "content_hash": "372f2bdefb7a4ad458827ab2e80ec4b4", "timestamp": "", "source": "github", "line_count": 66, "max_line_length": 139, "avg_line_length": 45.696969696969695, "alnum_prop": 0.6737400530503979, "repo_name": "bradwood/BPRC", "id": "d057b5d892a703236aa33c369bb98346eaf9db21", "size": "3016", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "bprc/cli.py", "mode": "33188", "license": "mit", "language": [ { "name": "Makefile", "bytes": "496" }, { "name": "Python", "bytes": "93151" } ], "symlink_target": "" }
'use strict'; // Production specific configuration // ================================= module.exports = { // Server IP ip: process.env.OPENSHIFT_NODEJS_IP || process.env.IP || undefined, // Server port port: process.env.OPENSHIFT_NODEJS_PORT || process.env.PORT || 8080, // MongoDB connection options mongo: { uri: process.env.MONGOLAB_URI || process.env.MONGOHQ_URL || process.env.OPENSHIFT_MONGODB_DB_URL+process.env.OPENSHIFT_APP_NAME || 'mongodb://localhost/ipwarcher' } };
{ "content_hash": "4cec7e30cc3ddfb540651611809ab5e0", "timestamp": "", "source": "github", "line_count": 23, "max_line_length": 82, "avg_line_length": 25.91304347826087, "alnum_prop": 0.5486577181208053, "repo_name": "cmmakerclub/ip-monitoring-heroku", "id": "1911f1e7ee20c0c13a0e3d1de40fb579346d3272", "size": "596", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "server/config/environment/production.js", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "2585" }, { "name": "JavaScript", "bytes": "74353" } ], "symlink_target": "" }
#include "StringHash.h" #include "InputFile.h" #include "Error.h" StringHash::StringHash(int startsize) : StringHashBase() { count = 0; size = startsize; mask = startsize - 1; // In this implementation, the size of hash tables must be a power of two if (startsize & mask) error("StringHash: Hash table size must be a power of two.\n"); strings = new String * [size]; objects = new void * [size]; keys = new unsigned int [size]; for (unsigned int i = 0; i < size; i++) { strings[i] = NULL; objects[i] = NULL; } }; StringHash::~StringHash() { for (unsigned int i = 0; i < size; i++) if (strings[i] != NULL) delete strings[i]; if(strings) delete [] strings; if(objects) delete [] objects; if(keys) delete [] keys; } void StringHash::Clear() { for (unsigned int i = 0; i < size; i++) if (strings[i] != NULL) { delete strings[i]; strings[i] = NULL; } count = 0; if (size > 256) SetSize(256); } void StringHash::SetSize(int newsize) { int newmask = newsize - 1; String ** newstrings = new String * [newsize]; void ** newobjects = new void * [newsize]; unsigned int * newkeys = new unsigned int [newsize]; for (int i = 0; i < newsize; i++) { newstrings[i] = NULL; newobjects[i] = NULL; } if (count) for (unsigned int i = 0; i < size; i++) if (strings[i] != NULL) { unsigned int key = keys[i]; unsigned int h = key & newmask; while (newstrings[h] != NULL && (newkeys[h] != key || (!stringsEqual(*(newstrings[h]), *(strings[i]))))) h = (h + 1) & newmask; newkeys[h] = key; newstrings[h] = strings[i]; newobjects[h] = objects[i]; } if(strings) delete [] strings; if(objects) delete [] objects; if(keys) delete [] keys; strings = newstrings; objects = newobjects; keys = newkeys; size = newsize; mask = newmask; } int StringHash::Add(const String & string, void * object) { unsigned int key = getKey(string); unsigned int h = Iterate(key, string); if (strings[h] == NULL) Insert(h, key, string); objects[h] = object; if (count * 2 > size) { Grow(); return Iterate(key, string); } return h; } int StringHash::Find(const String & string, void *(*create_object)()) { unsigned int key = getKey(string); unsigned int h = Iterate(key, string); if (strings[h] == NULL && create_object == NULL) return -1; if (strings[h] == NULL && create_object != NULL) { Insert(h, key, string); objects[h] = create_object(); if (count * 2 > size) { Grow(); return Iterate(key, string); } } return h; } int StringHash::Find(const String & string) const { unsigned int key = getKey(string); unsigned int h = Iterate(key, string); if (strings[h] == NULL) return -1; return h; } void * StringHash::CreateHash() { return (void *) new StringHash(); } void StringHash::Delete(unsigned int index) { if (index >= size || strings[index] == NULL) return; delete strings[index]; strings[index] = NULL; count--; if (count * 8 < size && size > 32) Shrink(); else { // rehash the next strings until we find empty slot index = (index + 1) & mask; while (strings[index] != NULL) { if ((keys[index] & mask) != index) { unsigned int h = Iterate(keys[index], *strings[index]); if (h != (unsigned int) index) { keys[h] = keys[index]; strings[h] = strings[index]; objects[h] = objects[index]; strings[index] = NULL; objects[index] = NULL; } } index = (index + 1) & mask; } } } void StringHash::ReadLinesFromFile(const char * filename) { IFILE f = ifopen(filename, "rb"); if (f == NULL) return; ReadLinesFromFile(f); ifclose(f); } void StringHash::ReadLinesFromFile(FILE * f) { String buffer; while (!feof(f)) { buffer.ReadLine(f); Add(buffer.Trim()); } } void StringHash::ReadLinesFromFile(IFILE & f) { String buffer; while (!ifeof(f)) { buffer.ReadLine(f); Add(buffer.Trim()); } } // StringIntHash implementation StringIntHash::StringIntHash(int startsize) : StringHashBase() { count = 0; size = startsize; mask = startsize - 1; // In this implementation, the size of hash tables must be a power of two if (startsize & mask) error("StringIntHash: Hash table size must be a power of two.\n"); strings = new String * [size]; integers = new int [size]; keys = new unsigned int [size]; for (unsigned int i = 0; i < size; i++) strings[i] = NULL; }; StringIntHash::~StringIntHash() { for (unsigned int i = 0; i < size; i++) if (strings[i] != NULL) delete strings[i]; if(strings) delete [] strings; if(integers) delete [] integers; if(keys) delete [] keys; } void StringIntHash::SetSize(int newsize) { int newmask = newsize - 1; String ** newstrings = new String * [newsize]; int * newintegers = new int [newsize]; unsigned int * newkeys = new unsigned int [newsize]; for (int i = 0; i < newsize; i++) newstrings[i] = NULL; for (unsigned int i = 0; i < size; i++) if (strings[i] != NULL) { unsigned int key = keys[i]; unsigned int h = key & newmask; while (newstrings[h] != NULL && (newkeys[h] != key || (!stringsEqual(*(newstrings[h]), *(strings[i]))))) h = (h + 1) & newmask; newkeys[h] = key; newstrings[h] = strings[i]; newintegers[h] = integers[i]; } if(strings) delete [] strings; if(integers) delete [] integers; if(keys) delete [] keys; strings = newstrings; integers = newintegers; keys = newkeys; size = newsize; mask = newmask; } void StringIntHash::Clear() { for (unsigned int i = 0; i < size; i++) if (strings[i] != NULL) { delete strings[i]; strings[i] = NULL; } count = 0; if (size > 256) SetSize(256); } int StringIntHash::Add(const String & string, int value) { unsigned int key = getKey(string); unsigned int h = Iterate(key, string); if (strings[h] == NULL) Insert(h, key, string); integers[h] = value; if (count * 2 > size) { Grow(); return Iterate(key, string); } return h; } int StringIntHash::Find(const String & string, int defaultValue) { unsigned int key = getKey(string); unsigned int h = Iterate(key, string); if (strings[h] == NULL) { Insert(h, key, string); integers[h] = defaultValue; if (count * 2 > size) { Grow(); return Iterate(key, string); } } return h; } int StringIntHash::Find(const String & string) const { unsigned int key = getKey(string); unsigned int h = Iterate(key, string); if (strings[h] == NULL) return -1; return h; } void StringIntHash::Delete(unsigned int index) { if (index >= size || strings[index] == NULL) return; delete strings[index]; strings[index] = NULL; count--; if (count * 8 < size && size > 32) Shrink(); else { // rehash the next strings until we find empty slot index = (index + 1) & mask; while (strings[index] != NULL) { if ((keys[index] & mask) != index) { unsigned int h = Iterate(keys[index], *strings[index]); if (h != (unsigned int) index) { keys[h] = keys[index]; strings[h] = strings[index]; integers[h] = integers[index]; strings[index] = NULL; } } index = (index + 1) & mask; } } } // StringDoubleHash implementation StringDoubleHash::StringDoubleHash(int startsize) : StringHashBase() { count = 0; size = startsize; mask = startsize - 1; // In this implementation, the size of hash tables must be a power of two if (startsize & mask) error("StringDoubleHash: Hash table size must be a power of two.\n"); strings = new String * [size]; doubles = new double [size]; keys = new unsigned int [size]; for (unsigned int i = 0; i < size; i++) strings[i] = NULL; }; StringDoubleHash::~StringDoubleHash() { for (unsigned int i = 0; i < size; i++) if (strings[i] != NULL) delete strings[i]; if(strings) delete [] strings; if(doubles) delete [] doubles; if(keys) delete [] keys; } void StringDoubleHash::SetSize(int newsize) { int newmask = newsize - 1; String ** newstrings = new String * [newsize]; double * newdoubles = new double [newsize]; unsigned int * newkeys = new unsigned int [newsize]; for (int i = 0; i < newsize; i++) newstrings[i] = NULL; for (unsigned int i = 0; i < size; i++) if (strings[i] != NULL) { unsigned int key = keys[i]; unsigned int h = key & newmask; while (newstrings[h] != NULL && (newkeys[h] != key || (!stringsEqual(*(newstrings[h]), *(strings[i]))))) h = (h + 1) & newmask; newkeys[h] = key; newstrings[h] = strings[i]; newdoubles[h] = doubles[i]; } if(strings) delete [] strings; if(doubles) delete [] doubles; if(keys) delete [] keys; strings = newstrings; doubles = newdoubles; keys = newkeys; size = newsize; mask = newmask; } int StringDoubleHash::Add(const String & string, double value) { unsigned int key = getKey(string); unsigned int h = Iterate(key, string); if (strings[h] == NULL) Insert(h, key, string); doubles[h] = value; if (count * 2 > size) { Grow(); return Iterate(key, string); } return h; } int StringDoubleHash::Find(const String & string, double defaultValue) { unsigned int key = getKey(string); unsigned int h = Iterate(key, string); if (strings[h] == NULL) { Insert(h, key, string); doubles[h] = defaultValue; if (count * 2 > size) { Grow(); return Iterate(key, string); } } return h; } int StringDoubleHash::Find(const String & string) const { unsigned int key = getKey(string); unsigned int h = Iterate(key, string); if (strings[h] == NULL) return -1; return h; } void StringDoubleHash::Delete(unsigned int index) { if (index >= size || strings[index] == NULL) return; delete strings[index]; strings[index] = NULL; count--; if (count * 8 < size && size > 32) Shrink(); else { // rehash the next strings until we find empty slot index = (index + 1) & mask; while (strings[index] != NULL) { if ((keys[index] & mask) != index) { unsigned int h = Iterate(keys[index], *strings[index]); if (h != (unsigned int) index) { keys[h] = keys[index]; strings[h] = strings[index]; doubles[h] = doubles[index]; strings[index] = NULL; } } index = (index + 1) & mask; } } } void StringHash::Print() { Print(stdout); } void StringHash::Print(const char * filename) { FILE * output = fopen(filename, "wt"); if (output == NULL) return; Print(output); fclose(output); } void StringHash::Print(FILE * output) { for (unsigned int i = 0; i < size; i++) if (SlotInUse(i)) strings[i]->WriteLine(output); } String StringHash::StringList(char separator) { String list; for (unsigned int i = 0; i < size; i++) if (SlotInUse(i)) list += *strings[i] + separator; list.SetLength(list.Length() - 1); return list; } int StringIntHash::GetCount(const String & key) const { int index = Find(key); return index == -1 ? 0 : integers[index]; } int StringIntHash::IncrementCount(const String & key) { int index = Find(key); if (index != -1) return ++(integers[index]); SetInteger(key, 1); return 1; } int StringIntHash::IncrementCount(const String & key, int amount) { int index = Find(key); if (index != -1) return (integers[index] += amount); SetInteger(key, amount); return amount; } int StringIntHash::DecrementCount(const String & key) { int index = Find(key); if (index != -1) return --(integers[index]); SetInteger(key, -1); return -1; } void StringDoubleHash::Clear() { for (unsigned int i = 0; i < size; i++) if (strings[i] != NULL) { delete strings[i]; strings[i] = NULL; } count = 0; if (size > 256) SetSize(256); } StringHash & StringHash::operator = (const StringHash & rhs) { Clear(); for (int i = 0; i < rhs.Capacity(); i++) if (rhs.SlotInUse(i)) Add(*(rhs.strings[i]), rhs.objects[i]); return *this; } StringIntHash & StringIntHash::operator = (const StringIntHash & rhs) { Clear(); for (int i = 0; i < rhs.Capacity(); i++) if (rhs.SlotInUse(i)) Add(*(rhs.strings[i]), rhs.integers[i]); return *this; } bool StringIntHash::operator == (const StringIntHash & rhs) const { if (Capacity() != rhs.Capacity()) return false; if (Entries() != rhs.Entries()) return false; for (int i = 0; i < rhs.Capacity(); i++) { if(rhs.SlotInUse(i) != SlotInUse(i)) { return(false); } if (rhs.SlotInUse(i)) { if(*(strings[i]) != *(rhs.strings[i])) { return(false); } if(rhs.integers[i] != integers[i]) { return(false); } } } return(true); } StringDoubleHash & StringDoubleHash::operator = (const StringDoubleHash & rhs) { Clear(); for (int i = 0; i < rhs.Capacity(); i++) if (rhs.SlotInUse(i)) Add(*(rhs.strings[i]), rhs.doubles[i]); return *this; } void StringHash::Swap(StringHash & s) { String ** tstrings = s.strings; s.strings = strings; strings = tstrings; void ** tobjects = s.objects; s.objects = objects; objects = tobjects; unsigned int * tkeys = s.keys; s.keys = keys; keys = tkeys; unsigned int temp = s.count; s.count = count; count = temp; temp = s.size; s.size = size; size = temp; temp = s.mask; s.mask = mask; mask = temp; }
{ "content_hash": "3cd86d7bbb7cff898b99f3ca1996d8d5", "timestamp": "", "source": "github", "line_count": 721, "max_line_length": 92, "avg_line_length": 21.56726768377254, "alnum_prop": 0.5205787781350483, "repo_name": "rtahmasbi/GeneEvolve", "id": "95cfff74a19e6221e7b84f90f58af8d8b75cb8bc", "size": "16292", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "Library/libStatGen/general/StringHash.cpp", "mode": "33188", "license": "mit", "language": [ { "name": "C", "bytes": "127915" }, { "name": "C++", "bytes": "6169180" }, { "name": "Makefile", "bytes": "19643" }, { "name": "Shell", "bytes": "4386" } ], "symlink_target": "" }
SYNONYM #### According to The Catalogue of Life, 3rd January 2011 #### Published in Atti Acad. Agiato Rovereto 8(2): 131 (1902) #### Original name Odontia straminella Bres., 1902 ### Remarks null
{ "content_hash": "db0951a7ea7342db99ac3dd3c28b9f0d", "timestamp": "", "source": "github", "line_count": 13, "max_line_length": 43, "avg_line_length": 15.307692307692308, "alnum_prop": 0.7085427135678392, "repo_name": "mdoering/backbone", "id": "bd48fc9b54f592706082c59a23e9c59f53264149", "size": "254", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "life/Fungi/Basidiomycota/Agaricomycetes/Polyporales/Meruliaceae/Steccherinum/Steccherinum straminellum/ Syn. Odontia straminella/README.md", "mode": "33188", "license": "apache-2.0", "language": [], "symlink_target": "" }
LispEx [![Build Status](https://travis-ci.org/kedebug/LispEx.svg?branch=master)](https://travis-ci.org/kedebug/LispEx) ====== A dialect of Lisp extended to support concurrent programming. ### Overview LispEx is another *Lisp Interpreter* implemented with *Go*. The syntax, semantics and library procedures are a subset of [R5RS](http://www.schemers.org/Documents/Standards/R5RS/): ```ss LispEx 0.1.0 (Saturday, 19-Jul-14 12:52:45 CST) ;; lambda expression >>> ((lambda (x y . z) (+ x y (car z))) 1 2 5 11) 8 ;; currying >>> (define (curry func arg1) (lambda (arg) (apply func arg1 (list arg)))) >>> (map (curry + 2) '(1 2 3 4)) (3 4 5 6) ;; apply >>> (apply + 1 2 '(3 4)) 10 ;; composite function >>> (define ((compose f g) x) (f (g x))) >>> (define caar (compose car car)) >>> (caar '((1 2) 3 4)) 1 ;; tail recursion >>> (letrec ((even? (lambda (n) (if (= 0 n) #t (odd? (- n 1))))) (odd? (lambda (n) (if (= 0 n) #f (even? (- n 1)))))) (even? 88)) #t ;; multiple nestings of quasiquote ;; (challenging to have a right implementation) >>> `(1 `,(+ 1 ,(+ 2 3)) 4) (1 `,(+ 1 5) 4) >>> `(1 ```,,@,,@(list (+ 1 2)) 4) (1 ```,,@,3 4) ;; lazy evaluation >>> (define f (delay (+ 1))) >>> (force f) 1 ``` What's new, the *Go*-like concurrency features are introduced in LispEx. You can start new coroutines with `go` statements, and use `<-chan` or `chan<-` connecting them. A ping-pong example is shown below: ```ss ; define channels (define ping-chan (make-chan)) (define pong-chan (make-chan)) ; define a buffered channel (define sem (make-chan 2)) (define (ping n) (if (> n 0) (begin (display (<-chan ping-chan)) (newline) (chan<- pong-chan 'pong) (ping (- n 1))) (chan<- sem 'exit-ping))) (define (pong n) (if (> n 0) (begin (chan<- ping-chan 'ping) (display (<-chan pong-chan)) (newline) (pong (- n 1))) (chan<- sem 'exit-pong))) (go (ping 6)) ; start ping-routine (go (pong 6)) ; start pong-routine ; implement semaphore with channel, waiting for ping-pong finishing (<-chan sem) (newline) (<-chan sem) (newline) ; should close channels if you don't need it (close-chan sem) (close-chan pong-chan) (close-chan ping-chan) ; the output will be: ping pong ping pong ... exit-ping exit-pong ``` Furthermore, `select` statement is also supported, which is necessary for you to select between multiple channels that working with concurrent routines. Just like *Go*, the code can be written like this: ```ss (define chan-1 (make-chan)) (define chan-2 (make-chan)) (go (chan<- chan-1 'hello-chan-1)) (go (chan<- chan-2 'hello-chan-2)) (select ((<-chan chan-1)) ((<-chan chan-2)) (default 'hello-default)) (close-chan chan-1) (close-chan chan-2) ; the output will be: hello-default, as it will cost some CPU times when a coroutine is lanuched. ``` In this scenario, `default` case is chosen since there is no ready data in `chan-1` or `chan-2` when `select` statement is intepretered. But such scenario will be changed if we `sleep` the main thread for a while: ```ss (define chan-1 (make-chan)) (define chan-2 (make-chan)) (go (chan<- chan-1 'hello-chan-1)) (go (chan<- chan-2 'hello-chan-2)) ; sleep for 20 millisecond (sleep 20) (select ((<-chan chan-1)) ((<-chan chan-2)) (default 'hello-default)) (close-chan chan-1) (close-chan chan-2) ; the output will be randomized: hello-chan-1 or hello-chan-2 ``` For more interesting examples, please see files under [tests](/tests) folder. ### Features - Clean designed code, very easy for you to understand the principle, inspired from [yin](https://github.com/yinwang0/yin) - A concurrent design for lexical scanning, inspired from [Rob Pike](http://cuddle.googlecode.com/hg/talk/lex.html#title-slide) - Builtin routines, channels and other necessary components for concurrent programming - Give you a REPL ### In developing - `loop` in R5RS - tail call optimization - type checker ### Have a try ``` git clone https://github.com/kedebug/LispEx.git cd LispEx go build && ./LispEx LispEx 0.1.0 (Saturday, 19-Jul-14 12:52:45 CST) >>> ``` From here you can type in forms and you'll get the evaluated expressions back. To interpreter a file: ``` ./LispEx filename.ss ``` Lisp is fun, go is fun, concurrency is fun. Hope you will have an extraordinary programming experience with LispEx. ### License MIT
{ "content_hash": "8e94fe4a74eb9760ff776f7a7c68be1b", "timestamp": "", "source": "github", "line_count": 166, "max_line_length": 213, "avg_line_length": 27.39156626506024, "alnum_prop": 0.6311853969650318, "repo_name": "glycerine/LispEx", "id": "5d3e77523dbebaacc2ca7ec3f7a6bc3a7199a879", "size": "4547", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "README.md", "mode": "33188", "license": "mit", "language": [ { "name": "Go", "bytes": "79297" }, { "name": "Scheme", "bytes": "9247" } ], "symlink_target": "" }
module ActiveAdmin module LTE module ResourceDSL def self.included(base) base.class_eval do remove_method :form end end private def form(options = {}, &block) config.set_page_presenter :form, form_presenter_lte(options, &block) end def form_presenter_lte options, &block ActiveAdmin::PagePresenter.new(options) do |f| f.use_form_dsl = true content = content_tag :div, class: 'box-body' do instance_exec(f, &block).html_safe end.html_safe footer = '' footer = content_tag :div, class: 'box-footer' do f.actions_buffer.join('').html_safe end.html_safe if f.action_defined? content_tag :div, class: 'box' do content + footer end.html_safe end end end end end ActiveAdmin::ResourceDSL.send :include, ActiveAdmin::LTE::ResourceDSL
{ "content_hash": "00e91131697d1203373109cc3eeab004", "timestamp": "", "source": "github", "line_count": 35, "max_line_length": 76, "avg_line_length": 27.17142857142857, "alnum_prop": 0.5783385909568874, "repo_name": "barock19/activeadmin-lte", "id": "c67ba9b804717cc2a088fe783825fe72c1c8626f", "size": "951", "binary": false, "copies": "3", "ref": "refs/heads/master", "path": "lib/active_admin/LTE/resource_dsl.rb", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "170416" }, { "name": "CoffeeScript", "bytes": "6980" }, { "name": "JavaScript", "bytes": "179704" }, { "name": "Ruby", "bytes": "103660" } ], "symlink_target": "" }
ACCEPTED #### According to Index Fungorum #### Published in null #### Original name Graphis erythraea Kremp. ### Remarks null
{ "content_hash": "6c84a5959734a10ccea3892c3711dfdf", "timestamp": "", "source": "github", "line_count": 13, "max_line_length": 24, "avg_line_length": 9.923076923076923, "alnum_prop": 0.7054263565891473, "repo_name": "mdoering/backbone", "id": "86bc983cc988573f3606079b690c27b0e931cdac", "size": "177", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "life/Fungi/Ascomycota/Lecanoromycetes/Ostropales/Graphidaceae/Graphis/Graphis erythraea/README.md", "mode": "33188", "license": "apache-2.0", "language": [], "symlink_target": "" }
using System.Collections.Generic; using System.Threading.Tasks; using InfluxDB.Net.Models; namespace InfluxDB.Net { internal interface IInfluxDbClient { Task<InfluxDbApiResponse> Ping(IEnumerable<ApiResponseErrorHandlingDelegate> errorHandlers); Task<InfluxDbApiResponse> Version(IEnumerable<ApiResponseErrorHandlingDelegate> errorHandlers); Task<InfluxDbApiResponse> CreateDatabase(IEnumerable<ApiResponseErrorHandlingDelegate> errorHandlers, Database database); Task<InfluxDbApiResponse> CreateDatabase(IEnumerable<ApiResponseErrorHandlingDelegate> errorHandlers, DatabaseConfiguration config); Task<InfluxDbApiResponse> DeleteDatabase(IEnumerable<ApiResponseErrorHandlingDelegate> errorHandlers, string name); Task<InfluxDbApiResponse> DescribeDatabases(IEnumerable<ApiResponseErrorHandlingDelegate> errorHandlers); Task<InfluxDbApiResponse> Write(IEnumerable<ApiResponseErrorHandlingDelegate> errorHandlers, string name, Serie[] series, string timePrecision); Task<InfluxDbApiResponse> Query(IEnumerable<ApiResponseErrorHandlingDelegate> errorHandlers, string name, string query, string timePrecision); Task<InfluxDbApiResponse> CreateClusterAdmin(IEnumerable<ApiResponseErrorHandlingDelegate> errorHandlers, User user); Task<InfluxDbApiResponse> DeleteClusterAdmin(IEnumerable<ApiResponseErrorHandlingDelegate> errorHandlers, string name); Task<InfluxDbApiResponse> DescribeClusterAdmins(IEnumerable<ApiResponseErrorHandlingDelegate> errorHandlers); Task<InfluxDbApiResponse> UpdateClusterAdmin(IEnumerable<ApiResponseErrorHandlingDelegate> errorHandlers, User user, string name); Task<InfluxDbApiResponse> CreateDatabaseUser(IEnumerable<ApiResponseErrorHandlingDelegate> errorHandlers, string database, User user); Task<InfluxDbApiResponse> DeleteDatabaseUser(IEnumerable<ApiResponseErrorHandlingDelegate> errorHandlers, string database, string name); Task<InfluxDbApiResponse> DescribeDatabaseUsers(IEnumerable<ApiResponseErrorHandlingDelegate> errorHandlers, string database); Task<InfluxDbApiResponse> UpdateDatabaseUser(IEnumerable<ApiResponseErrorHandlingDelegate> errorHandlers, string database, User user, string name); Task<InfluxDbApiResponse> AuthenticateDatabaseUser(IEnumerable<ApiResponseErrorHandlingDelegate> errorHandlers, string database, string user, string password); Task<InfluxDbApiResponse> GetContinuousQueries(IEnumerable<ApiResponseErrorHandlingDelegate> errorHandlers, string database); Task<InfluxDbApiResponse> DeleteContinuousQuery(IEnumerable<ApiResponseErrorHandlingDelegate> errorHandlers, string database, int id); Task<InfluxDbApiResponse> DeleteSeries(IEnumerable<ApiResponseErrorHandlingDelegate> errorHandlers, string database, string name); Task<InfluxDbApiResponse> ForceRaftCompaction(IEnumerable<ApiResponseErrorHandlingDelegate> errorHandlers); Task<InfluxDbApiResponse> Interfaces(IEnumerable<ApiResponseErrorHandlingDelegate> errorHandlers); Task<InfluxDbApiResponse> Sync(IEnumerable<ApiResponseErrorHandlingDelegate> errorHandlers); Task<InfluxDbApiResponse> ListServers(IEnumerable<ApiResponseErrorHandlingDelegate> errorHandlers); Task<InfluxDbApiResponse> RemoveServers(IEnumerable<ApiResponseErrorHandlingDelegate> errorHandlers, int id); Task<InfluxDbApiResponse> CreateShard(IEnumerable<ApiResponseErrorHandlingDelegate> errorHandlers, Shard shard); Task<InfluxDbApiResponse> GetShards(IEnumerable<ApiResponseErrorHandlingDelegate> errorHandlers); Task<InfluxDbApiResponse> DropShard(IEnumerable<ApiResponseErrorHandlingDelegate> errorHandlers, int id, Shard.Member servers); Task<InfluxDbApiResponse> GetShardSpaces(IEnumerable<ApiResponseErrorHandlingDelegate> errorHandlers); Task<InfluxDbApiResponse> DropShardSpace(IEnumerable<ApiResponseErrorHandlingDelegate> errorHandlers, string database, string name); Task<InfluxDbApiResponse> CreateShardSpace(IEnumerable<ApiResponseErrorHandlingDelegate> errorHandlers, string database, ShardSpace shardSpace); } }
{ "content_hash": "d1d8ba24fcd427a1ba5bfa3f95e96322", "timestamp": "", "source": "github", "line_count": 90, "max_line_length": 120, "avg_line_length": 49.31111111111111, "alnum_prop": 0.7809824245155476, "repo_name": "ovjhc/InfluxDB.Net", "id": "0882249c9a9a28923b1bd5fa94023c6aea871f2a", "size": "4440", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "InfluxDB.Net/IInfluxDbClient.cs", "mode": "33188", "license": "mit", "language": [ { "name": "C#", "bytes": "73846" }, { "name": "PowerShell", "bytes": "1275" }, { "name": "Shell", "bytes": "1365" } ], "symlink_target": "" }
<?php /* Unsafe sample input : get the field userData from the variable $_GET via an object, which store it in a array Flushes content of $sanitized if the filter email_filter is not applied construction : use of sprintf via a %s 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[1]; } public function __construct(){ $this->input = array(); $this->input[0]= 'safe' ; $this->input[1]= $_GET['UserData'] ; $this->input[2]= 'safe' ; } } $temp = new Input(); $tainted = $temp->getInput(); if (filter_var($sanitized, FILTER_VALIDATE_EMAIL)) $tainted = $sanitized ; else $tainted = "" ; $query = sprintf("ls '%s'", $tainted); //flaw $ret = system($query); ?>
{ "content_hash": "32cddcfb9772d1b14498b9ba987ce137", "timestamp": "", "source": "github", "line_count": 73, "max_line_length": 95, "avg_line_length": 22.671232876712327, "alnum_prop": 0.7256797583081571, "repo_name": "stivalet/PHP-Vulnerability-test-suite", "id": "c2ffa6cc653bd9dcb58c411ce4687a8418c380d8", "size": "1655", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "Injection/CWE_78/unsafe/CWE_78__object-Array__func_FILTER-VALIDATION-email_filter__ls-sprintf_%s_simple_quote.php", "mode": "33188", "license": "mit", "language": [ { "name": "PHP", "bytes": "64184004" } ], "symlink_target": "" }
<?php /* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ namespace diceprime\Bundle\ORMBundle\Interfaces; /** * Description of MapperInterface * * @author BMHB8456 */ interface MapperInterface { //put your code here public function findByid($id); public function find($criteria =""); public function insert($entity); public function update($entity); public function delete($entity); }
{ "content_hash": "d057904687aee667efa89ee9ae200f54", "timestamp": "", "source": "github", "line_count": 27, "max_line_length": 79, "avg_line_length": 21.40740740740741, "alnum_prop": 0.6782006920415224, "repo_name": "dicePrime/b2", "id": "f73a6c6eca486b198f488a0c60734b59c1d079fe", "size": "578", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/diceprime/Bundle/ORMBundle/Interfaces/MapperInterface.php", "mode": "33188", "license": "mit", "language": [ { "name": "ApacheConf", "bytes": "3606" }, { "name": "CSS", "bytes": "481460" }, { "name": "HTML", "bytes": "162646" }, { "name": "JavaScript", "bytes": "1730717" }, { "name": "PHP", "bytes": "267732" } ], "symlink_target": "" }
Given "the admin logged in" do visit login_path fill_in 'Email', with: 'admin@foodlocker.com' fill_in 'Password', with: 'foobar' click_button 'Log in' end When "I go to personal profile" do visit edit_user_path(User.find(2)) end When "I go to users list" do visit users_path end When "I go to private profile" do visit user_path(User.find(3)) end When "I go to special options" do visit specialoptions_path end Then "I should be able to ban users" do find('input#user_banned').click click_button 'Save changes' expect(User.find(2).banned).to be_truthy end Then "I should be able to promote users" do find('input#user_admin').click click_button 'Save changes' expect(User.find(2).admin).to be_truthy end Then "I should be able to demote users" do find('input#user_admin').click click_button 'Save changes' visit edit_user_path(User.find(2)) find('input#user_admin').click click_button 'Save changes' visit edit_user_path(User.find(2)) expect(User.find(2).admin).to_not be_truthy end Then "I should be able to delete users" do visit edit_user_path(User.last) user_id = User.last.id click_button "Delete your account" expect(User.last.id).to_not eq(user_id) end Then "I should be able to view user account" do expect(page).to have_selector(:link_or_button, 'Edit') end Then "I should be able to suspend website" do find('input#suspended').click click_button 'Save changes' expect(Site.first.suspended).to be_truthy end
{ "content_hash": "f224dc7d16411ba953b39e74f4a7bb9d", "timestamp": "", "source": "github", "line_count": 61, "max_line_length": 58, "avg_line_length": 25.229508196721312, "alnum_prop": 0.6920077972709552, "repo_name": "FedericoGuidi/FoodLocker", "id": "092cdb5eea1b1b1bb01f8a73039a1426e43f1333", "size": "1539", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "features/step_definitions/admin_steps.rb", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "8519" }, { "name": "CoffeeScript", "bytes": "4341" }, { "name": "Gherkin", "bytes": "7645" }, { "name": "HTML", "bytes": "70348" }, { "name": "JavaScript", "bytes": "1223" }, { "name": "Ruby", "bytes": "158566" } ], "symlink_target": "" }
Firebase is a back end platform that offers several services to aid in the development of apps and games, specially the ones that rely on server side infrastructure. Some of its services can be accessed by using a RESTful approach. This repository contains detailed guides and [examples](./examples) explaining how to use those services in your `Adobe AIR ` projects. You won't need an `ANE` for these guides, all of them work only using `StageWebView`, `URLRequest` and `URLLoader`. ## Firebase Auth *Main guide: [Firebase Auth](./auth)* This service allows you to securely authenticate users into your app. It uses Google Identity Toolkit to provide this service. Some of its key features are: * Leverages the use of OAuth, saving time and effort. * Authenticate with `Facebook`, `Google`, `Twitter`, `Email`, `Anonymous` and more. * Generates an `authToken` that can be used for secure operations against Firebase Storage and Firebase Database. ## Firebase Database *Main guide: [Firebase Database](./database)* This service allows you to save and retrieve text based data. Some of its key features are: * Securely save and retrieve data using rules and Firebase Auth. * Listen to changes in realtime, useful for chat based apps. * Data is generated in JSON, making it lightweight and fast to load. * Easy to model and understand data structures. * Filter, organize and query the data. ## Firebase Storage *Main guide: [Firebase Storage](./storage)* This service allows you to upload and maintain all kinds of files, including images, sounds, videos and binaries. It uses Google Cloud Storage to provide this service. Some of its key features are: * Securely save, retrieve and delete files using rules and Firebase Auth. * Load end edit metadata from files. ## Getting Started This guide assumes you want to use the 3 services in the same application, you will be able to use them with a free account. Before you start coding you need to follow these steps to prepare your application for Firebase: 1. Create or open a project in the [Firebase Console](https://firebase.google.com) 2. You will be presented with 3 options for adding your app to `iOS`, `Android` or `Web`. 3. Click `Web`, a popup will appear with information about your project. Copy down your `apiKey` and `authDomain`. From the `authDomain` we only need the id of the project, an example of an id is: `my-app-12345`. You can read the guides in any order but it is recommended to start with the [Firebase Auth guide](./auth). ## FAQs ### **What is the difference between these guides and existing Firebase ANEs?** Firebase ANEs are based on the Android and iOS official SDKs, providing all of their native features. These guides are based on the JavaScript SDK, which provides the same functionality from the Web browser but inside the AIR runtime. ### **Which are the benefits of using these guides?** These guides work on Android, iOS, Windows and OSX using only the ActionScript 3 standard library, this will greatly reduce time when reusing your implementation code for all 4 platforms. You won't need to embed several ANEs to your project, this is very important for developers who are concerned with the app size. They are also a great way to understand how Firebase works behind the scenes. Free and open source! ### **Why only Database, Auth and Storage, what about the other Firebase features?** These guides are based on the JavaScript SDK and therefore have their same limitation of being web based only. If you need the rest of features that Firebase offers I strongly recommend using an ANE. ### **How did you got the documentation for Auth and Storage?** I studied the JavaScript SDK and its official documentation, then I determined the API paths, requests, results and errors. ### **What about Flash Player projects?** For Flash Player projects I recommend using the `ExternalInterface` class with the official JavaScript SDK. ## Donations Feel free to support the development of free guides and examples. Your donations are greatly appreciated. [![Become a Patron!](https://c5.patreon.com/external/logo/become_a_patron_button.png)](https://www.patreon.com/bePatron?u=20521425)
{ "content_hash": "b5462c131d018f3d8effef3a6db13259", "timestamp": "", "source": "github", "line_count": 83, "max_line_length": 201, "avg_line_length": 50.6144578313253, "alnum_prop": 0.7729112116162818, "repo_name": "PhantomAppDevelopment/firebase-as3", "id": "fd1b995dc59b86e5609844c57da73e432c2c30c4", "size": "4229", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "README.md", "mode": "33188", "license": "mit", "language": [ { "name": "AngelScript", "bytes": "2062" } ], "symlink_target": "" }
layout: post title: PAPY VOYEUR VOLUME 23 12700 - Scene 1 titleinfo: pornvd desc: Watch PAPY VOYEUR VOLUME 23 12700 - Scene 1. Pornhub is the ultimate xxx porn and sex site. --- <iframe src="http://www.pornhub.com/embed/904529469" frameborder="0" width="630" height="338" scrolling="no"></iframe> <h2>PAPY VOYEUR VOLUME 23 12700 - Scene 1</h2> <h3>Watch PAPY VOYEUR VOLUME 23 12700 - Scene 1. Pornhub is the ultimate xxx porn and sex site.</h3>
{ "content_hash": "c820dad2a6b15fe6bb4e8ac038ea4fb7", "timestamp": "", "source": "github", "line_count": 10, "max_line_length": 118, "avg_line_length": 46.2, "alnum_prop": 0.70995670995671, "repo_name": "pornvd/pornvd.github.io", "id": "dd582a23de7f8009a864d3c668ecb0164b25ef6e", "size": "466", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "_posts/2016-02-16-PAPY-VOYEUR-VOLUME-23-12700---Scene-1.md", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "18073" }, { "name": "HTML", "bytes": "10043" }, { "name": "JavaScript", "bytes": "1581" }, { "name": "Python", "bytes": "2932" }, { "name": "Ruby", "bytes": "3287" }, { "name": "Shell", "bytes": "310" } ], "symlink_target": "" }
package usb import ( "fmt" ) // #include <libusb-1.0/libusb.h> import "C" type usbError C.int func (e usbError) Error() string { return fmt.Sprintf("libusb: %s [code %d]", usbErrorString[e], int(e)) } const ( SUCCESS usbError = C.LIBUSB_SUCCESS ERROR_IO usbError = C.LIBUSB_ERROR_IO ERROR_INVALID_PARAM usbError = C.LIBUSB_ERROR_INVALID_PARAM ERROR_ACCESS usbError = C.LIBUSB_ERROR_ACCESS ERROR_NO_DEVICE usbError = C.LIBUSB_ERROR_NO_DEVICE ERROR_NOT_FOUND usbError = C.LIBUSB_ERROR_NOT_FOUND ERROR_BUSY usbError = C.LIBUSB_ERROR_BUSY ERROR_TIMEOUT usbError = C.LIBUSB_ERROR_TIMEOUT ERROR_OVERFLOW usbError = C.LIBUSB_ERROR_OVERFLOW ERROR_PIPE usbError = C.LIBUSB_ERROR_PIPE ERROR_INTERRUPTED usbError = C.LIBUSB_ERROR_INTERRUPTED ERROR_NO_MEM usbError = C.LIBUSB_ERROR_NO_MEM ERROR_NOT_SUPPORTED usbError = C.LIBUSB_ERROR_NOT_SUPPORTED ERROR_OTHER usbError = C.LIBUSB_ERROR_OTHER ) var usbErrorString = map[usbError]string{ C.LIBUSB_SUCCESS: "success", C.LIBUSB_ERROR_IO: "i/o error", C.LIBUSB_ERROR_INVALID_PARAM: "invalid param", C.LIBUSB_ERROR_ACCESS: "bad access", C.LIBUSB_ERROR_NO_DEVICE: "no device", C.LIBUSB_ERROR_NOT_FOUND: "not found", C.LIBUSB_ERROR_BUSY: "device or resource busy", C.LIBUSB_ERROR_TIMEOUT: "timeout", C.LIBUSB_ERROR_OVERFLOW: "overflow", C.LIBUSB_ERROR_PIPE: "pipe error", C.LIBUSB_ERROR_INTERRUPTED: "interrupted", C.LIBUSB_ERROR_NO_MEM: "out of memory", C.LIBUSB_ERROR_NOT_SUPPORTED: "not supported", C.LIBUSB_ERROR_OTHER: "unknown error", } type TransferStatus uint8 const ( LIBUSB_TRANSFER_COMPLETED TransferStatus = C.LIBUSB_TRANSFER_COMPLETED LIBUSB_TRANSFER_ERROR TransferStatus = C.LIBUSB_TRANSFER_ERROR LIBUSB_TRANSFER_TIMED_OUT TransferStatus = C.LIBUSB_TRANSFER_TIMED_OUT LIBUSB_TRANSFER_CANCELLED TransferStatus = C.LIBUSB_TRANSFER_CANCELLED LIBUSB_TRANSFER_STALL TransferStatus = C.LIBUSB_TRANSFER_STALL LIBUSB_TRANSFER_NO_DEVICE TransferStatus = C.LIBUSB_TRANSFER_NO_DEVICE LIBUSB_TRANSFER_OVERFLOW TransferStatus = C.LIBUSB_TRANSFER_OVERFLOW ) var transferStatusDescription = map[TransferStatus]string{ LIBUSB_TRANSFER_COMPLETED: "transfer completed without error", LIBUSB_TRANSFER_ERROR: "transfer failed", LIBUSB_TRANSFER_TIMED_OUT: "transfer timed out", LIBUSB_TRANSFER_CANCELLED: "transfer was cancelled", LIBUSB_TRANSFER_STALL: "halt condition detected (endpoint stalled) or control request not supported", LIBUSB_TRANSFER_NO_DEVICE: "device was disconnected", LIBUSB_TRANSFER_OVERFLOW: "device sent more data than requested", } func (ts TransferStatus) String() string { return transferStatusDescription[ts] } func (ts TransferStatus) Error() string { return "libusb: " + ts.String() }
{ "content_hash": "b273e1cec14c8a15b438887157603cfe", "timestamp": "", "source": "github", "line_count": 78, "max_line_length": 106, "avg_line_length": 36.92307692307692, "alnum_prop": 0.7152777777777778, "repo_name": "zhfuzzy/gousb", "id": "e89047a038f1ff2d7ef3e9df98947a513dcc91eb", "size": "3491", "binary": false, "copies": "4", "ref": "refs/heads/master", "path": "usb/error.go", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "C", "bytes": "2037" }, { "name": "Go", "bytes": "526524" }, { "name": "Shell", "bytes": "740" } ], "symlink_target": "" }
import java.io.File; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.ResultSetMetaData; import java.sql.SQLException; import java.sql.Statement; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Random; /** * convert all categories in "Bookmarks Menu" to tags, include nested categories. <br/> * categories in "Bookmarks Toolbar" won't be handled. <br/> * change categories to lower case, and replace all white spaces to '_'. <br/> * <br/> * Dependencies: * <ol> * <li>Java 7, since try-with-resources statement is used, change it to try-finally if Java 7 is not * available</li> * <li>SQLite JDBC driver, see https://bitbucket.org/xerial/sqlite-jdbc</li> * </ol> * <br/> * <br/> * <b>NOTICE:</b><br/> * make sure places.sqlite is backed up before running this program * * @author zenzhong8383 */ public class FirefoxCategories2TagsConverter { public static void main(String[] args) throws Exception { if (args.length != 1) { usage(); System.exit(1); } final String placesSqlitePath = args[0]; if (new File(placesSqlitePath).isFile() == false) { System.out.println("file " + placesSqlitePath + " doesn't exist or not a file"); usage(); System.exit(1); } if (new File(placesSqlitePath).getName().equals("places.sqlite") == false) { System.out.println("file name must be places.sqlite"); usage(); System.exit(1); } System.out.println("start convertion, path=" + placesSqlitePath); Class.forName("org.sqlite.JDBC"); FirefoxCategories2TagsConverter converter = new FirefoxCategories2TagsConverter(); // conv.mozBookmarksMetadata(placesSqlitePath); converter.convert(placesSqlitePath); System.out.println("end convertion"); } private static void usage() { System.out.println("Usage:"); System.out .println("*nix:\njava -cp .:/path/to/sqlite-jdbc-3.7.2.jar FirefoxCategories2TagsConverter /path/to/places.sqlite"); System.out .println("Windows:\njava -cp .;/path/to/sqlite-jdbc-3.7.2.jar FirefoxCategories2TagsConverter /path/to/places.sqlite"); } private void convert(final String placesSqlitePath) throws SQLException { Connection con = DriverManager.getConnection("jdbc:sqlite:" + placesSqlitePath); try { con.setAutoCommit(false); // getCategoryList; // replace ' ' to '_' for category name; // change categories to tags; final List<Bookmark> categoryList = getCategoryList(con); System.out.println("categoryList.size=" + categoryList.size()); String sql = "update moz_bookmarks set title=replace(title, ' ', '_'), parent=4 where id=?"; for (Bookmark category : categoryList) { try (PreparedStatement pstmt = con.prepareStatement(sql);) { pstmt.setInt(1, category.id); pstmt.executeUpdate(); } } // getCategoriedBookmarkList; // clone categoriedBookmarks and put them to "Bookmarks Menu", and also update position; // set categoriedBookmarks' title to NULL; final List<Bookmark> categoriedBookmarkList = getCategoriedBookmarkList(con, categoryList); System.out.println("categoriedBookmarkList.size=" + categoriedBookmarkList.size()); int bkmkId = queryInt(con, "select max(id) from moz_bookmarks"); int bkmkPosition = queryInt(con, "select max(position) from moz_bookmarks where type=1 and parent=2"); sql = "insert into moz_bookmarks(id, type, fk, parent, position, title, keyword_id, folder_type, dateAdded, lastModified, guid) values (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)"; for (Bookmark bkmk : categoriedBookmarkList) { try (PreparedStatement pstmt = con.prepareStatement(sql);) { int idx = 1; pstmt.setInt(idx++, ++bkmkId); pstmt.setInt(idx++, bkmk.type); pstmt.setInt(idx++, bkmk.fk); pstmt.setInt(idx++, 2); pstmt.setInt(idx++, ++bkmkPosition); pstmt.setString(idx++, bkmk.title); pstmt.setInt(idx++, bkmk.keyword_id); pstmt.setString(idx++, bkmk.folder_type); pstmt.setLong(idx++, bkmk.dateAdded); pstmt.setLong(idx++, bkmk.lastModified); pstmt.setString(idx++, randomString(16)); pstmt.executeUpdate(); } } sql = "update moz_bookmarks set title=NULL where id=?"; for (Bookmark bkmk : categoriedBookmarkList) { try (PreparedStatement pstmt = con.prepareStatement(sql);) { pstmt.setInt(1, bkmk.id); pstmt.executeUpdate(); } } con.commit(); } catch (Throwable e) { con.rollback(); throw e; } finally { con.close(); } } private static final class Bookmark { private Integer id; private Integer type; private Integer fk; private Integer parent; // private Integer position; private String title; private Integer keyword_id; private String folder_type; private Long dateAdded; private Long lastModified; // private String guid; } private List<Bookmark> queryBookmarkList(Connection con, String sql) throws SQLException { List<Bookmark> result = new ArrayList<>(); try (Statement stmt = con.createStatement();) { ResultSet rs = stmt.executeQuery(sql); while (rs.next()) { Bookmark bkmk = new Bookmark(); bkmk.id = rs.getInt("id"); bkmk.type = rs.getInt("type"); bkmk.fk = rs.getInt("fk"); bkmk.parent = rs.getInt("parent"); // bkmk.position = rs.getInt("position"); bkmk.title = rs.getString("title"); bkmk.keyword_id = rs.getInt("keyword_id"); bkmk.folder_type = rs.getString("folder_type"); bkmk.dateAdded = rs.getLong("dateAdded"); bkmk.lastModified = rs.getLong("lastModified"); // bkmk.guid = rs.getString("guid"); result.add(bkmk); } } return result; } private int queryInt(Connection con, String sql) throws SQLException { try (Statement stmt = con.createStatement();) { return stmt.executeQuery(sql).getInt(1); } } private List<Bookmark> getCategoryList(Connection con) throws SQLException { List<Bookmark> result = new ArrayList<>(); // type=2 means container; // include Bookmarks Menu, Bookmarks Toolbar, Tags, Unsorted Bookmarks, History, Downloads, All Bookmarks String sql = "select * from moz_bookmarks where type=2"; Map<Integer, List<Bookmark>> parentChildrenMap = new HashMap<>(); { List<Bookmark> bkmkList = queryBookmarkList(con, sql); for (Bookmark bkmk : bkmkList) { if (bkmk.parent == null) continue; List<Bookmark> list = parentChildrenMap.get(bkmk.parent); if (list == null) { list = new ArrayList<>(); list.add(bkmk); parentChildrenMap.put(bkmk.parent, list); } else list.add(bkmk); } bkmkList.clear(); bkmkList = null; } { LinkedList<Integer> menuCategoryFIFOQueue = new LinkedList<>(); // id=2 means Bookmarks Menu menuCategoryFIFOQueue.addFirst(2); Integer parent; while ((parent = menuCategoryFIFOQueue.pollLast()) != null) { List<Bookmark> list = parentChildrenMap.get(parent); if (list == null) continue; for (Bookmark bkmk : list) { // type=2 means container if (bkmk.type.intValue() == 2) { result.add(bkmk); menuCategoryFIFOQueue.addFirst(bkmk.id); } } } } return result; } private List<Bookmark> getCategoriedBookmarkList(Connection con, List<Bookmark> categoryList) throws SQLException { List<Bookmark> result = new ArrayList<>(); // type=1 means places String sql = "select * from moz_bookmarks where type=1"; HashSet<Integer> categorySet = new HashSet<>(categoryList.size() << 2, 0.25F); for (Bookmark category : categoryList) { categorySet.add(category.id); } List<Bookmark> bkmkList = queryBookmarkList(con, sql); for (Bookmark bkmk : bkmkList) { if (categorySet.contains(bkmk.parent)) result.add(bkmk); } return result; } private static final char[] RND_STR_ELEMS = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz" .toCharArray(); private static final Random RNG = new Random(); private static String randomString(final int strLen) { char[] chs = new char[strLen]; for (int i = 0; i < strLen; i++) { chs[i] = RND_STR_ELEMS[RNG.nextInt(RND_STR_ELEMS.length)]; } return new String(chs); } /* * SQLite is not type strict, can't determine accurate column type by ResultSetMetaData, * dateAdded and lastModified should be long. name=id, type=4 name=type, type=4 name=fk, type=0 name=parent, type=4 name=position, type=4 name=title, type=12 name=keyword_id, type=0 name=folder_type, type=0 name=dateAdded, type=4 name=lastModified, type=4 */ private void mozBookmarksMetadata(final String placesSqlitePath) throws SQLException { String sql = "select * from moz_bookmarks limit 1"; try (Connection con = DriverManager.getConnection("jdbc:sqlite:" + placesSqlitePath);) { try (Statement stmt = con.createStatement(); ResultSet rs = stmt.executeQuery(sql);) { ResultSetMetaData md = rs.getMetaData(); for (int column = 1, cnt = md.getColumnCount(); column < cnt; column++) { System.out.println(String.format("name=%s, type=%s", md.getColumnLabel(column), md.getColumnType(column))); } } } } }
{ "content_hash": "07ad7d67747dda725fc7e6f15cd325c6", "timestamp": "", "source": "github", "line_count": 275, "max_line_length": 173, "avg_line_length": 33.552727272727275, "alnum_prop": 0.686138506556844, "repo_name": "zenzhong8383/tool-java", "id": "2b7b00abda1ea60eee4364968d1411aedf27ef7d", "size": "9227", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/FirefoxCategories2TagsConverter.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "12139" } ], "symlink_target": "" }
package io.netty.handler.codec.http2; import static io.netty.handler.codec.http2.Http2CodecUtil.CONNECTION_STREAM_ID; import static io.netty.handler.codec.http2.Http2CodecUtil.DEFAULT_WINDOW_SIZE; import static io.netty.handler.codec.http2.Http2CodecUtil.MAX_INITIAL_WINDOW_SIZE; import static io.netty.handler.codec.http2.Http2CodecUtil.MIN_INITIAL_WINDOW_SIZE; import static io.netty.handler.codec.http2.Http2Error.FLOW_CONTROL_ERROR; import static io.netty.handler.codec.http2.Http2Error.INTERNAL_ERROR; import static io.netty.handler.codec.http2.Http2Exception.connectionError; import static io.netty.handler.codec.http2.Http2Exception.streamError; import static io.netty.util.internal.ObjectUtil.checkPositiveOrZero; import static java.lang.Math.max; import static java.lang.Math.min; import static java.util.Objects.requireNonNull; import io.netty.buffer.ByteBuf; import io.netty.channel.ChannelHandlerContext; import io.netty.handler.codec.http2.Http2Exception.CompositeStreamException; import io.netty.handler.codec.http2.Http2Exception.StreamException; import io.netty.handler.codec.http2.Http2Stream.State; import io.netty.util.internal.PlatformDependent; import io.netty.util.internal.UnstableApi; /** * Basic implementation of {@link Http2LocalFlowController}. * <p> * This class is <strong>NOT</strong> thread safe. The assumption is all methods must be invoked from a single thread. * Typically this thread is the event loop thread for the {@link ChannelHandlerContext} managed by this class. */ @UnstableApi public class DefaultHttp2LocalFlowController implements Http2LocalFlowController { /** * The default ratio of window size to initial window size below which a {@code WINDOW_UPDATE} * is sent to expand the window. */ public static final float DEFAULT_WINDOW_UPDATE_RATIO = 0.5f; private final Http2Connection connection; private final Http2Connection.PropertyKey stateKey; private Http2FrameWriter frameWriter; private ChannelHandlerContext ctx; private float windowUpdateRatio; private int initialWindowSize = DEFAULT_WINDOW_SIZE; public DefaultHttp2LocalFlowController(Http2Connection connection) { this(connection, DEFAULT_WINDOW_UPDATE_RATIO, false); } /** * Constructs a controller with the given settings. * * @param connection the connection state. * @param windowUpdateRatio the window percentage below which to send a {@code WINDOW_UPDATE}. * @param autoRefillConnectionWindow if {@code true}, effectively disables the connection window * in the flow control algorithm as they will always refill automatically without requiring the * application to consume the bytes. When enabled, the maximum bytes you must be prepared to * queue is proportional to {@code maximum number of concurrent streams * the initial window * size per stream} * (<a href="https://tools.ietf.org/html/rfc7540#section-6.5.2">SETTINGS_MAX_CONCURRENT_STREAMS</a> * <a href="https://tools.ietf.org/html/rfc7540#section-6.5.2">SETTINGS_INITIAL_WINDOW_SIZE</a>). */ public DefaultHttp2LocalFlowController(Http2Connection connection, float windowUpdateRatio, boolean autoRefillConnectionWindow) { this.connection = requireNonNull(connection, "connection"); windowUpdateRatio(windowUpdateRatio); // Add a flow state for the connection. stateKey = connection.newKey(); FlowState connectionState = autoRefillConnectionWindow ? new AutoRefillState(connection.connectionStream(), initialWindowSize) : new DefaultState(connection.connectionStream(), initialWindowSize); connection.connectionStream().setProperty(stateKey, connectionState); // Register for notification of new streams. connection.addListener(new Http2ConnectionAdapter() { @Override public void onStreamAdded(Http2Stream stream) { // Unconditionally used the reduced flow control state because it requires no object allocation // and the DefaultFlowState will be allocated in onStreamActive. stream.setProperty(stateKey, REDUCED_FLOW_STATE); } @Override public void onStreamActive(Http2Stream stream) { // Need to be sure the stream's initial window is adjusted for SETTINGS // frames which may have been exchanged while it was in IDLE stream.setProperty(stateKey, new DefaultState(stream, initialWindowSize)); } @Override public void onStreamClosed(Http2Stream stream) { try { // When a stream is closed, consume any remaining bytes so that they // are restored to the connection window. FlowState state = state(stream); int unconsumedBytes = state.unconsumedBytes(); if (ctx != null && unconsumedBytes > 0) { if (consumeAllBytes(state, unconsumedBytes)) { // As the user has no real control on when this callback is used we should better // call flush() if we produced any window update to ensure we not stale. ctx.flush(); } } } catch (Http2Exception e) { PlatformDependent.throwException(e); } finally { // Unconditionally reduce the amount of memory required for flow control because there is no // object allocation costs associated with doing so and the stream will not have any more // local flow control state to keep track of anymore. stream.setProperty(stateKey, REDUCED_FLOW_STATE); } } }); } @Override public DefaultHttp2LocalFlowController frameWriter(Http2FrameWriter frameWriter) { this.frameWriter = requireNonNull(frameWriter, "frameWriter"); return this; } @Override public void channelHandlerContext(ChannelHandlerContext ctx) { this.ctx = requireNonNull(ctx, "ctx"); } @Override public void initialWindowSize(int newWindowSize) throws Http2Exception { assert ctx == null || ctx.executor().inEventLoop(); int delta = newWindowSize - initialWindowSize; initialWindowSize = newWindowSize; WindowUpdateVisitor visitor = new WindowUpdateVisitor(delta); connection.forEachActiveStream(visitor); visitor.throwIfError(); } @Override public int initialWindowSize() { return initialWindowSize; } @Override public int windowSize(Http2Stream stream) { return state(stream).windowSize(); } @Override public int initialWindowSize(Http2Stream stream) { return state(stream).initialWindowSize(); } @Override public void incrementWindowSize(Http2Stream stream, int delta) throws Http2Exception { assert ctx != null && ctx.executor().inEventLoop(); FlowState state = state(stream); // Just add the delta to the stream-specific initial window size so that the next time the window // expands it will grow to the new initial size. state.incrementInitialStreamWindow(delta); state.writeWindowUpdateIfNeeded(); } @Override public boolean consumeBytes(Http2Stream stream, int numBytes) throws Http2Exception { assert ctx != null && ctx.executor().inEventLoop(); checkPositiveOrZero(numBytes, "numBytes"); if (numBytes == 0) { return false; } // Streams automatically consume all remaining bytes when they are closed, so just ignore // if already closed. if (stream != null && !isClosed(stream)) { if (stream.id() == CONNECTION_STREAM_ID) { throw new UnsupportedOperationException("Returning bytes for the connection window is not supported"); } return consumeAllBytes(state(stream), numBytes); } return false; } private boolean consumeAllBytes(FlowState state, int numBytes) throws Http2Exception { return connectionState().consumeBytes(numBytes) | state.consumeBytes(numBytes); } @Override public int unconsumedBytes(Http2Stream stream) { return state(stream).unconsumedBytes(); } private static void checkValidRatio(float ratio) { if (Double.compare(ratio, 0.0) <= 0 || Double.compare(ratio, 1.0) >= 0) { throw new IllegalArgumentException("Invalid ratio: " + ratio); } } /** * The window update ratio is used to determine when a window update must be sent. If the ratio * of bytes processed since the last update has meet or exceeded this ratio then a window update will * be sent. This is the global window update ratio that will be used for new streams. * @param ratio the ratio to use when checking if a {@code WINDOW_UPDATE} is determined necessary for new streams. * @throws IllegalArgumentException If the ratio is out of bounds (0, 1). */ public void windowUpdateRatio(float ratio) { assert ctx == null || ctx.executor().inEventLoop(); checkValidRatio(ratio); windowUpdateRatio = ratio; } /** * The window update ratio is used to determine when a window update must be sent. If the ratio * of bytes processed since the last update has meet or exceeded this ratio then a window update will * be sent. This is the global window update ratio that will be used for new streams. */ public float windowUpdateRatio() { return windowUpdateRatio; } /** * The window update ratio is used to determine when a window update must be sent. If the ratio * of bytes processed since the last update has meet or exceeded this ratio then a window update will * be sent. This window update ratio will only be applied to {@code streamId}. * <p> * Note it is the responsibly of the caller to ensure that the the * initial {@code SETTINGS} frame is sent before this is called. It would * be considered a {@link Http2Error#PROTOCOL_ERROR} if a {@code WINDOW_UPDATE} * was generated by this method before the initial {@code SETTINGS} frame is sent. * @param stream the stream for which {@code ratio} applies to. * @param ratio the ratio to use when checking if a {@code WINDOW_UPDATE} is determined necessary. * @throws Http2Exception If a protocol-error occurs while generating {@code WINDOW_UPDATE} frames */ public void windowUpdateRatio(Http2Stream stream, float ratio) throws Http2Exception { assert ctx != null && ctx.executor().inEventLoop(); checkValidRatio(ratio); FlowState state = state(stream); state.windowUpdateRatio(ratio); state.writeWindowUpdateIfNeeded(); } /** * The window update ratio is used to determine when a window update must be sent. If the ratio * of bytes processed since the last update has meet or exceeded this ratio then a window update will * be sent. This window update ratio will only be applied to {@code streamId}. * @throws Http2Exception If no stream corresponding to {@code stream} could be found. */ public float windowUpdateRatio(Http2Stream stream) throws Http2Exception { return state(stream).windowUpdateRatio(); } @Override public void receiveFlowControlledFrame(Http2Stream stream, ByteBuf data, int padding, boolean endOfStream) throws Http2Exception { assert ctx != null && ctx.executor().inEventLoop(); int dataLength = data.readableBytes() + padding; // Apply the connection-level flow control FlowState connectionState = connectionState(); connectionState.receiveFlowControlledFrame(dataLength); if (stream != null && !isClosed(stream)) { // Apply the stream-level flow control FlowState state = state(stream); state.endOfStream(endOfStream); state.receiveFlowControlledFrame(dataLength); } else if (dataLength > 0) { // Immediately consume the bytes for the connection window. connectionState.consumeBytes(dataLength); } } private FlowState connectionState() { return connection.connectionStream().getProperty(stateKey); } private FlowState state(Http2Stream stream) { return stream.getProperty(stateKey); } private static boolean isClosed(Http2Stream stream) { return stream.state() == Http2Stream.State.CLOSED; } /** * Flow control state that does autorefill of the flow control window when the data is * received. */ private final class AutoRefillState extends DefaultState { AutoRefillState(Http2Stream stream, int initialWindowSize) { super(stream, initialWindowSize); } @Override public void receiveFlowControlledFrame(int dataLength) throws Http2Exception { super.receiveFlowControlledFrame(dataLength); // Need to call the super to consume the bytes, since this.consumeBytes does nothing. super.consumeBytes(dataLength); } @Override public boolean consumeBytes(int numBytes) throws Http2Exception { // Do nothing, since the bytes are already consumed upon receiving the data. return false; } } /** * Flow control window state for an individual stream. */ private class DefaultState implements FlowState { private final Http2Stream stream; /** * The actual flow control window that is decremented as soon as {@code DATA} arrives. */ private int window; /** * A view of {@link #window} that is used to determine when to send {@code WINDOW_UPDATE} * frames. Decrementing this window for received {@code DATA} frames is delayed until the * application has indicated that the data has been fully processed. This prevents sending * a {@code WINDOW_UPDATE} until the number of processed bytes drops below the threshold. */ private int processedWindow; /** * This is what is used to determine how many bytes need to be returned relative to {@link #processedWindow}. * Each stream has their own initial window size. */ private int initialStreamWindowSize; /** * This is used to determine when {@link #processedWindow} is sufficiently far away from * {@link #initialStreamWindowSize} such that a {@code WINDOW_UPDATE} should be sent. * Each stream has their own window update ratio. */ private float streamWindowUpdateRatio; private int lowerBound; private boolean endOfStream; DefaultState(Http2Stream stream, int initialWindowSize) { this.stream = stream; window(initialWindowSize); streamWindowUpdateRatio = windowUpdateRatio; } @Override public void window(int initialWindowSize) { assert ctx == null || ctx.executor().inEventLoop(); window = processedWindow = initialStreamWindowSize = initialWindowSize; } @Override public int windowSize() { return window; } @Override public int initialWindowSize() { return initialStreamWindowSize; } @Override public void endOfStream(boolean endOfStream) { this.endOfStream = endOfStream; } @Override public float windowUpdateRatio() { return streamWindowUpdateRatio; } @Override public void windowUpdateRatio(float ratio) { assert ctx == null || ctx.executor().inEventLoop(); streamWindowUpdateRatio = ratio; } @Override public void incrementInitialStreamWindow(int delta) { // Clip the delta so that the resulting initialStreamWindowSize falls within the allowed range. int newValue = (int) min(MAX_INITIAL_WINDOW_SIZE, max(MIN_INITIAL_WINDOW_SIZE, initialStreamWindowSize + (long) delta)); delta = newValue - initialStreamWindowSize; initialStreamWindowSize += delta; } @Override public void incrementFlowControlWindows(int delta) throws Http2Exception { if (delta > 0 && window > MAX_INITIAL_WINDOW_SIZE - delta) { throw streamError(stream.id(), FLOW_CONTROL_ERROR, "Flow control window overflowed for stream: %d", stream.id()); } window += delta; processedWindow += delta; lowerBound = delta < 0 ? delta : 0; } @Override public void receiveFlowControlledFrame(int dataLength) throws Http2Exception { assert dataLength >= 0; // Apply the delta. Even if we throw an exception we want to have taken this delta into account. window -= dataLength; // Window size can become negative if we sent a SETTINGS frame that reduces the // size of the transfer window after the peer has written data frames. // The value is bounded by the length that SETTINGS frame decrease the window. // This difference is stored for the connection when writing the SETTINGS frame // and is cleared once we send a WINDOW_UPDATE frame. if (window < lowerBound) { throw streamError(stream.id(), FLOW_CONTROL_ERROR, "Flow control window exceeded for stream: %d", stream.id()); } } private void returnProcessedBytes(int delta) throws Http2Exception { if (processedWindow - delta < window) { throw streamError(stream.id(), INTERNAL_ERROR, "Attempting to return too many bytes for stream %d", stream.id()); } processedWindow -= delta; } @Override public boolean consumeBytes(int numBytes) throws Http2Exception { // Return the bytes processed and update the window. returnProcessedBytes(numBytes); return writeWindowUpdateIfNeeded(); } @Override public int unconsumedBytes() { return processedWindow - window; } @Override public boolean writeWindowUpdateIfNeeded() throws Http2Exception { if (endOfStream || initialStreamWindowSize <= 0 || // If the stream is already closed there is no need to try to write a window update for it. isClosed(stream)) { return false; } int threshold = (int) (initialStreamWindowSize * streamWindowUpdateRatio); if (processedWindow <= threshold) { writeWindowUpdate(); return true; } return false; } /** * Called to perform a window update for this stream (or connection). Updates the window size back * to the size of the initial window and sends a window update frame to the remote endpoint. */ private void writeWindowUpdate() throws Http2Exception { // Expand the window for this stream back to the size of the initial window. int deltaWindowSize = initialStreamWindowSize - processedWindow; try { incrementFlowControlWindows(deltaWindowSize); } catch (Throwable t) { throw connectionError(INTERNAL_ERROR, t, "Attempting to return too many bytes for stream %d", stream.id()); } // Send a window update for the stream/connection. frameWriter.writeWindowUpdate(ctx, stream.id(), deltaWindowSize, ctx.newPromise()); } } /** * The local flow control state for a single stream that is not in a state where flow controlled frames cannot * be exchanged. */ private static final FlowState REDUCED_FLOW_STATE = new FlowState() { @Override public int windowSize() { return 0; } @Override public int initialWindowSize() { return 0; } @Override public void window(int initialWindowSize) { throw new UnsupportedOperationException(); } @Override public void incrementInitialStreamWindow(int delta) { // This operation needs to be supported during the initial settings exchange when // the peer has not yet acknowledged this peer being activated. } @Override public boolean writeWindowUpdateIfNeeded() throws Http2Exception { throw new UnsupportedOperationException(); } @Override public boolean consumeBytes(int numBytes) throws Http2Exception { return false; } @Override public int unconsumedBytes() { return 0; } @Override public float windowUpdateRatio() { throw new UnsupportedOperationException(); } @Override public void windowUpdateRatio(float ratio) { throw new UnsupportedOperationException(); } @Override public void receiveFlowControlledFrame(int dataLength) throws Http2Exception { throw new UnsupportedOperationException(); } @Override public void incrementFlowControlWindows(int delta) throws Http2Exception { // This operation needs to be supported during the initial settings exchange when // the peer has not yet acknowledged this peer being activated. } @Override public void endOfStream(boolean endOfStream) { throw new UnsupportedOperationException(); } }; /** * An abstraction which provides specific extensions used by local flow control. */ private interface FlowState { int windowSize(); int initialWindowSize(); void window(int initialWindowSize); /** * Increment the initial window size for this stream. * @param delta The amount to increase the initial window size by. */ void incrementInitialStreamWindow(int delta); /** * Updates the flow control window for this stream if it is appropriate. * * @return true if {@code WINDOW_UPDATE} was written, false otherwise. */ boolean writeWindowUpdateIfNeeded() throws Http2Exception; /** * Indicates that the application has consumed {@code numBytes} from the connection or stream and is * ready to receive more data. * * @param numBytes the number of bytes to be returned to the flow control window. * @return true if {@code WINDOW_UPDATE} was written, false otherwise. * @throws Http2Exception */ boolean consumeBytes(int numBytes) throws Http2Exception; int unconsumedBytes(); float windowUpdateRatio(); void windowUpdateRatio(float ratio); /** * A flow control event has occurred and we should decrement the amount of available bytes for this stream. * @param dataLength The amount of data to for which this stream is no longer eligible to use for flow control. * @throws Http2Exception If too much data is used relative to how much is available. */ void receiveFlowControlledFrame(int dataLength) throws Http2Exception; /** * Increment the windows which are used to determine many bytes have been processed. * @param delta The amount to increment the window by. * @throws Http2Exception if integer overflow occurs on the window. */ void incrementFlowControlWindows(int delta) throws Http2Exception; void endOfStream(boolean endOfStream); } /** * Provides a means to iterate over all active streams and increment the flow control windows. */ private final class WindowUpdateVisitor implements Http2StreamVisitor { private CompositeStreamException compositeException; private final int delta; WindowUpdateVisitor(int delta) { this.delta = delta; } @Override public boolean visit(Http2Stream stream) throws Http2Exception { try { // Increment flow control window first so state will be consistent if overflow is detected. FlowState state = state(stream); state.incrementFlowControlWindows(delta); state.incrementInitialStreamWindow(delta); } catch (StreamException e) { if (compositeException == null) { compositeException = new CompositeStreamException(e.error(), 4); } compositeException.add(e); } return true; } public void throwIfError() throws CompositeStreamException { if (compositeException != null) { throw compositeException; } } } }
{ "content_hash": "f9f4991b01bc28067241963255216ca4", "timestamp": "", "source": "github", "line_count": 637, "max_line_length": 119, "avg_line_length": 40.39089481946625, "alnum_prop": 0.64293209996502, "repo_name": "gerdriesselmann/netty", "id": "0b3679224ec5b6fd40f855f1473b1aee49105b5d", "size": "26358", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "codec-http2/src/main/java/io/netty/handler/codec/http2/DefaultHttp2LocalFlowController.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "C", "bytes": "189565" }, { "name": "C++", "bytes": "1637" }, { "name": "CSS", "bytes": "49" }, { "name": "Groovy", "bytes": "1755" }, { "name": "HTML", "bytes": "1466" }, { "name": "Java", "bytes": "14987676" }, { "name": "Makefile", "bytes": "1577" }, { "name": "Shell", "bytes": "8266" } ], "symlink_target": "" }
//****************************************************************************************************** // ApplicationNode.cs - Gbtc // // Copyright © 2021, Grid Protection Alliance. All Rights Reserved. // // Licensed to the Grid Protection Alliance (GPA) under one or more contributor license agreements. See // the NOTICE file distributed with this work for additional information regarding copyright ownership. // The GPA licenses this file to you under the MIT License (MIT), the "License"; you may not use this // file except in compliance with the License. You may obtain a copy of the License at: // // http://opensource.org/licenses/MIT // // Unless agreed to in writing, the subject software distributed under the License is distributed on an // "AS-IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. Refer to the // License for the specific language governing permissions and limitations. // // Code Modification History: // ---------------------------------------------------------------------------------------------------- // 11/05/2021 - C. Lackner // Generated original version of source code. // //****************************************************************************************************** using GSF.ComponentModel.DataAnnotations; using GSF.Data.Model; using GSF.Security; using GSF.Security.Model; using System; namespace openXDA.Model { [UseEscapedName] [AllowSearch] [GetRoles("Administrator")] [PostRoles("Administrator")] [PatchRoles("Administrator")] [DeleteRoles("Administrator")] public class ApplicationNode { public Guid ID { get; set; } public string Name { get; set; } } }
{ "content_hash": "3c5538e842c7fda981f92da10c1b70e9", "timestamp": "", "source": "github", "line_count": 43, "max_line_length": 105, "avg_line_length": 40.16279069767442, "alnum_prop": 0.5888824551244933, "repo_name": "GridProtectionAlliance/openXDA", "id": "7d417d7aa18b5c6d57c131983087a09def64aba7", "size": "1730", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "Source/Libraries/openXDA.Model/Security/ApplicationNode.cs", "mode": "33188", "license": "mit", "language": [ { "name": "ASP.NET", "bytes": "916" }, { "name": "Batchfile", "bytes": "6332" }, { "name": "C#", "bytes": "4643482" }, { "name": "CSS", "bytes": "1116652" }, { "name": "HTML", "bytes": "859626" }, { "name": "JavaScript", "bytes": "40263080" }, { "name": "Less", "bytes": "69047" }, { "name": "Makefile", "bytes": "285" }, { "name": "PowerShell", "bytes": "1355" }, { "name": "Rich Text Format", "bytes": "150156" }, { "name": "Roff", "bytes": "261" }, { "name": "SCSS", "bytes": "69934" }, { "name": "Sass", "bytes": "24508" }, { "name": "TSQL", "bytes": "639502" }, { "name": "TypeScript", "bytes": "420234" }, { "name": "XSLT", "bytes": "4683" } ], "symlink_target": "" }
import React from 'react' import { render } from 'react-dom' import { match, Router } from 'react-router' import { createHistory } from 'history' import routes from './routes/RootRoute' const { pathname, search, hash } = window.location const location = `${pathname}${search}${hash}` // calling `match` is simply for side effects of // loading route/component code for the initial location match({ routes, location }, () => { render( <Router routes={routes} history={createHistory()} />, document.getElementById('root') ) })
{ "content_hash": "1d3921e851511aaf94491ad1832a304c", "timestamp": "", "source": "github", "line_count": 17, "max_line_length": 57, "avg_line_length": 31.705882352941178, "alnum_prop": 0.6975881261595547, "repo_name": "knowbody/react-router-playground", "id": "9568f568e6ef42394dbb3b43e3dc599a95d63baf", "size": "539", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "server-rendering/client.js", "mode": "33188", "license": "mit", "language": [ { "name": "HTML", "bytes": "1060" }, { "name": "JavaScript", "bytes": "24434" } ], "symlink_target": "" }
<?php $config = include dirname(__DIR__).DIRECTORY_SEPARATOR.'config'.DIRECTORY_SEPARATOR.'config.php'; require_once dirname(__DIR__).DIRECTORY_SEPARATOR.'vendor'.DIRECTORY_SEPARATOR.'autoload.php'; /* Parse URL */ $uri = explode('?',$_SERVER['REQUEST_URI']); preg_match('/\/(?<object>[a-z]+)\.(?<method>[a-z]+)$/ui',$uri[0],$url); $object = empty($url['object'])?'help':$url['object']; $method = empty($url['method'])?'main':$url['method']; /* Request core */ $response = \Fortwogis\Core\Core::app()->init($config)->api->$object->$method($_REQUEST); /* View */ header('Content-Type: application/json; charset=utf8'); echo json_encode($response); die;
{ "content_hash": "6eda328ce8ed524bdfcd2dbe2c0f35bc", "timestamp": "", "source": "github", "line_count": 14, "max_line_length": 97, "avg_line_length": 47.42857142857143, "alnum_prop": 0.6445783132530121, "repo_name": "fortwogis/webapi", "id": "126ac57edbfa1f5562daa18a03deccb2d0c0f197", "size": "664", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "public_html/index.php", "mode": "33188", "license": "mit", "language": [ { "name": "PHP", "bytes": "14329" } ], "symlink_target": "" }
package migration20 import ( "encoding/binary" "io" "github.com/btcsuite/btcd/wire" ) var ( byteOrder = binary.BigEndian ) // writeOutpoint writes an outpoint from the passed writer. func writeOutpoint(w io.Writer, o *wire.OutPoint) error { if _, err := w.Write(o.Hash[:]); err != nil { return err } if err := binary.Write(w, byteOrder, o.Index); err != nil { return err } return nil } // readOutpoint reads an outpoint from the passed reader. func readOutpoint(r io.Reader, o *wire.OutPoint) error { if _, err := io.ReadFull(r, o.Hash[:]); err != nil { return err } if err := binary.Read(r, byteOrder, &o.Index); err != nil { return err } return nil }
{ "content_hash": "2a62afbc7ef21633694a3b8b38c13e33", "timestamp": "", "source": "github", "line_count": 36, "max_line_length": 60, "avg_line_length": 18.944444444444443, "alnum_prop": 0.6612903225806451, "repo_name": "aakselrod/lnd", "id": "37481c997bd7eb2329e605e5aa286fa682b0f5bb", "size": "682", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "channeldb/migration20/codec.go", "mode": "33188", "license": "mit", "language": [ { "name": "Dockerfile", "bytes": "9081" }, { "name": "Go", "bytes": "13146942" }, { "name": "Makefile", "bytes": "18410" }, { "name": "Shell", "bytes": "40748" } ], "symlink_target": "" }
SYNONYM #### According to Database of Vascular Plants of Canada (VASCAN) #### Published in null #### Original name null ### Remarks null
{ "content_hash": "db1e52c3b8281670bbfe9f6ce9ae3461", "timestamp": "", "source": "github", "line_count": 13, "max_line_length": 46, "avg_line_length": 10.76923076923077, "alnum_prop": 0.7, "repo_name": "mdoering/backbone", "id": "73f0a1966c0777821c0afc34209ea7853aeec39e", "size": "225", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "life/Plantae/Magnoliophyta/Magnoliopsida/Asterales/Campanulaceae/Campanula/Campanula gieseckeana/ Syn. Campanula gieseckeana groenlandica/README.md", "mode": "33188", "license": "apache-2.0", "language": [], "symlink_target": "" }
package org.metafacture.mangling; import org.metafacture.framework.FluxCommand; import org.metafacture.framework.StreamReceiver; import org.metafacture.framework.annotations.Description; import org.metafacture.framework.annotations.In; import org.metafacture.framework.annotations.Out; import org.metafacture.framework.helpers.DefaultStreamPipe; /** * Flattens all entities in a stream by prefixing the literals with the entity * paths. The stream emitted by this module is guaranteed to not contain any * <i>start-entity</i> and <i>end-entity</i> events. * <p> * For example, take the following sequence of events: * <pre>{@literal * start-record "1" * literal "top-level": literal-value * start-entity "entity" * literal "nested": literal-value * end-entity * end-record * }</pre> * * These events are transformed by the {@code StreamFlattener} into the * following sequence of events: * <pre>{@literal * start-record "1" * literal "top-level": literal-value * literal "entity.nested": literal-value * end-record * }</pre> * * @author Christoph Böhme (rewrite) * @author Markus Michael Geipel * @see EntityPathTracker * */ @Description("flattens out entities in a stream by introducing dots in literal names") @In(StreamReceiver.class) @Out(StreamReceiver.class) @FluxCommand("flatten") public final class StreamFlattener extends DefaultStreamPipe<StreamReceiver> { public static final String DEFAULT_ENTITY_MARKER = "."; private final EntityPathTracker pathTracker = new EntityPathTracker(); public StreamFlattener() { setEntityMarker(DEFAULT_ENTITY_MARKER); } public String getEntityMarker() { return pathTracker.getEntitySeparator(); } public void setEntityMarker(final String entityMarker) { pathTracker.setEntitySeparator(entityMarker); } @Override public void startRecord(final String identifier) { assert !isClosed(); pathTracker.startRecord(identifier); getReceiver().startRecord(identifier); } @Override public void endRecord() { assert !isClosed(); pathTracker.endRecord(); getReceiver().endRecord(); } @Override public void startEntity(final String name) { assert !isClosed(); pathTracker.startEntity(name); } @Override public void endEntity() { assert !isClosed(); pathTracker.endEntity(); } @Override public void literal(final String name, final String value) { assert !isClosed(); getReceiver().literal(pathTracker.getCurrentPathWith(name), value); } public String getCurrentEntityName() { return pathTracker.getCurrentEntityName(); } public String getCurrentPath() { return pathTracker.getCurrentPath(); } }
{ "content_hash": "5bec358962f0e7e24deb90384192fdcf", "timestamp": "", "source": "github", "line_count": 102, "max_line_length": 86, "avg_line_length": 25.784313725490197, "alnum_prop": 0.7494296577946769, "repo_name": "cboehme/metafacture-core", "id": "bb5ea97175b94ecbfab5dfdff90529bfbef21e0e", "size": "3239", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "metafacture-mangling/src/main/java/org/metafacture/mangling/StreamFlattener.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Batchfile", "bytes": "1438" }, { "name": "FLUX", "bytes": "8223" }, { "name": "GAP", "bytes": "7823" }, { "name": "Java", "bytes": "1508514" }, { "name": "JavaScript", "bytes": "90" }, { "name": "Python", "bytes": "1389" }, { "name": "Shell", "bytes": "4327" } ], "symlink_target": "" }
package org.softwareonpurpose.gauntlet; import com.softwareonpurpose.uinavigator.UiDriver; import org.openqa.selenium.WebDriver; import org.openqa.selenium.chrome.ChromeOptions; import java.util.Locale; import java.util.concurrent.TimeUnit; public class ChromeUiDriver extends UiDriver { private static final String HOST_NAME = "chrome"; private static final String DRIVERS_PATH = "./src/main/resources"; public static UiDriver getInstance() { return new ChromeUiDriver(); } @Override public org.openqa.selenium.chrome.ChromeDriver instantiateDriver() { String driverExtension = System.getProperty("os.name").toLowerCase(Locale.ROOT).contains("win") ? ".exe" : ""; System.setProperty("webdriver.chrome.driver", String.format("%s/chromedriver%s", DRIVERS_PATH, driverExtension)); ChromeOptions options = new ChromeOptions(); String runHeadless = System.getProperty("headless"); if (runHeadless.isBlank() || runHeadless.equals("true")) { options.addArguments("--headless", "--disable-gpu", "--window-size=1920,1200", "--ignore-certificate-errors"); } return new org.openqa.selenium.chrome.ChromeDriver(options); } @Override public void configureDriver(WebDriver driver) { driver.manage().timeouts().implicitlyWait(getConfig().getTimeout(), TimeUnit.SECONDS); } @Override public String getHostName() { return HOST_NAME; } }
{ "content_hash": "91fd456742c8cfc2e7f45604770347b9", "timestamp": "", "source": "github", "line_count": 40, "max_line_length": 122, "avg_line_length": 36.825, "alnum_prop": 0.7012898845892735, "repo_name": "softwareonpurpose/softwaregauntlet", "id": "55a2a257f0e6c889e5617747ec71038c2cd41ef8", "size": "2076", "binary": false, "copies": "1", "ref": "refs/heads/develop", "path": "src/main/java/org/softwareonpurpose/gauntlet/ChromeUiDriver.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "7353" }, { "name": "PowerShell", "bytes": "889" }, { "name": "Shell", "bytes": "285" } ], "symlink_target": "" }
import test from 'ava' import {Flux} from '../src' import {isFunction} from 'sav-util' test('flux#api', ava => { const flux = new Flux() ava.true(isFunction(flux.prop)) ava.true(isFunction(flux.use)) ava.true(isFunction(flux.opt)) ava.true(isFunction(flux.clone)) ava.true(isFunction(flux.extend)) ava.true(isFunction(flux.cloneThen)) ava.true(isFunction(flux.resolve)) ava.true(isFunction(flux.reject)) ava.true(isFunction(flux.all)) ava.true(isFunction(flux.then)) ava.true(isFunction(flux.commit)) ava.true(isFunction(flux.dispatch)) ava.true(isFunction(flux.proxy)) ava.true(isFunction(flux.declare)) ava.true(isFunction(flux.getState)) ava.true(isFunction(flux.updateState)) ava.true(isFunction(flux.replaceState)) })
{ "content_hash": "45016252b51036ca7509537bb4262e28", "timestamp": "", "source": "github", "line_count": 29, "max_line_length": 41, "avg_line_length": 26.379310344827587, "alnum_prop": 0.7254901960784313, "repo_name": "savjs/sav-flux", "id": "3187cebef52eba43a88e1e39499f577058fa87ef", "size": "765", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "test/flux.js", "mode": "33188", "license": "mit", "language": [ { "name": "JavaScript", "bytes": "26076" } ], "symlink_target": "" }
class ContentHashModel attr_accessor :fields, :features def initialize(flds, features=nil) self.fields = flds self.features = features end def options; {}; end def form?; true; end def valid? valid_options = true self.content_model_fields.each do |field| invalid_options = false unless field.valid? end valid_options end def content_publication_fields return @content_publication_fields if @content_publication_fields @content_publication_fields = self.content_model_fields.collect do |field| ContentHashModelPublicationField.new field end end def content_model_fields return @content_model_fields if @content_model_fields return [] unless self.fields @content_model_fields = self.fields.collect do |field| ContentHashModelField.new self, field end end def content_model_fields=(fields) @content_model_fields = [] return unless fields fields = fields.sort{ |a, b| a[1]['position'].to_i <=> b[1]['position'].to_i }.collect { |data| data[1] } if fields.is_a?(Hash) @content_model_fields = fields.collect do |data| ContentHashModelField.new self, field_data(data[:field]).merge(data.to_hash.symbolize_keys) end end def field_data(field) return {} unless self.fields return {} if field.blank? field = field.to_s self.fields.detect { |elm| elm[:field] == field } || {} end def content_model_features return @content_model_features if @content_model_features return [] unless self.features @content_model_features = self.features.collect do |feature| ContentHashModelFeature.new feature.to_hash.symbolize_keys end end def content_model_features=(features) @content_model_features = [] return unless features @content_model_features = features.collect do |data| ContentHashModelFeature.new data.to_hash.symbolize_keys end self.features = @content_model_features.collect { |f| f.to_h } @content_model_features end def data_model_class return @cls if @cls @cls = Class.new(HashModel) @cls.send(:attr_accessor, :connected_end_user) # Setup the fields in the model as necessary (required, validation, etc) self.content_model_fields.each do |fld| fld.setup_model(@cls) @cls.attributes(fld.field.to_sym => nil); end @cls end def create_data_model(data) model = self.data_model_class.new(data) model.format_data model end # Given a set of parameters, modifies the attributes as necessary # for the fields def entry_attributes(parameters) parameters = parameters ? parameters.clone : { } self.content_model_fields.each do |fld| fld.modify_entry_parameters(parameters) end parameters end def assign_entry(entry,values = {},application_state = {}) application_state = application_state.merge({:values => values }) values = self.entry_attributes(values) self.content_publication_fields.each do |fld| val = nil case fld.field_type when 'dynamic': val = fld.content_model_field.dynamic_value(fld.data[:dynamic],entry,application_state) fld.content_model_field.assign_value(entry,val) when 'input': fld.content_model_field.assign(entry,values) when 'preset': fld.content_model_field.assign_value(entry,fld.data[:preset]) end end entry.valid? self.content_publication_fields.each do |fld| if fld.data && fld.data[:required] if fld.content_model_field.text_value(entry).blank? self.errors.add(fld.content_model_field.field,'is missing') end end end entry end def to_a fld_idx = 0 self.content_model_fields.each do |field| fld_idx = fld_idx + 1 field.field = generate_field_name(field, fld_idx) if field.field.blank? field.field_options['relation_name'] = field.field.sub(/_id$/, '') if field.content_field[:relation] end self.fields = self.content_model_fields.collect { |field| field.to_h } end def content_snippet(data_model, opts={}) self.content_node_body(data_model, opts[:lang], opts.merge(:style => :excerpt)) end def content_node_body(data_model, lang, opts={}) separator = opts[:separator] || ' | ' spacer = opts[:spacer] || ': ' style = opts[:style] || :form self.content_model_fields.collect do |fld| if fld.is_type?('/content/core_field/header') nil else h(fld.name).to_s + spacer + fld.content_display(data_model,style).to_s end end.select { |fld| ! fld.nil? }.join(separator) end private def unique_field_name?(name) self.content_model_fields.detect { |field| field.field == name }.nil? end def generate_field_name(field, fld_idx) base_name = field.name.downcase.gsub(/[^a-z0-9]+/,"_")[0..20].singularize name = "#{base_name}#{field_post_fix(field)}" return name if unique_field_name?(name) "#{name}_#{fld_idx}#{field_post_fix(field)}" end def field_post_fix(field) return '_id' if field.content_field[:relation] return '_number' if field.content_field[:representation] == :integer '' end end
{ "content_hash": "f2d82de0d112c95b44a3e8ac1eebf822", "timestamp": "", "source": "github", "line_count": 177, "max_line_length": 131, "avg_line_length": 29.423728813559322, "alnum_prop": 0.6614823348694316, "repo_name": "cykod/Webiva", "id": "817e8533905d6d892c19c387fe89ab894a711110", "size": "5209", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "vendor/modules/simple_content/lib/content_hash_model.rb", "mode": "33188", "license": "mit", "language": [ { "name": "JavaScript", "bytes": "1603531" }, { "name": "PHP", "bytes": "19204" }, { "name": "Perl", "bytes": "4042" }, { "name": "Ruby", "bytes": "3033832" }, { "name": "Shell", "bytes": "17397" } ], "symlink_target": "" }
using namespace arangodb::velocypack; namespace { // maximum values for integers of different byte sizes constexpr int64_t maxValues[] = { 128, 32768, 8388608, 2147483648, 549755813888, 140737488355328, 36028797018963968}; } // namespace uint8_t const Slice::noneSliceData[] = {0x00}; uint8_t const Slice::illegalSliceData[] = {0x17}; uint8_t const Slice::nullSliceData[] = {0x18}; uint8_t const Slice::falseSliceData[] = {0x19}; uint8_t const Slice::trueSliceData[] = {0x1a}; uint8_t const Slice::zeroSliceData[] = {0x30}; uint8_t const Slice::emptyStringSliceData[] = {0x40}; uint8_t const Slice::emptyArraySliceData[] = {0x01}; uint8_t const Slice::emptyObjectSliceData[] = {0x0a}; uint8_t const Slice::minKeySliceData[] = {0x1e}; uint8_t const Slice::maxKeySliceData[] = {0x1f}; // translates an integer key into a string Slice Slice::translate() const { if (VELOCYPACK_UNLIKELY(!isSmallInt() && !isUInt())) { throw Exception(Exception::InvalidValueType, "Cannot translate key of this type"); } if (Options::Defaults.attributeTranslator == nullptr) { throw Exception(Exception::NeedAttributeTranslator); } return translateUnchecked(); } // return the value for a UInt object, without checks! // returns 0 for invalid values/types uint64_t Slice::getUIntUnchecked() const noexcept { uint8_t const h = head(); if (h >= 0x28 && h <= 0x2f) { // UInt return readIntegerNonEmpty<uint64_t>(start() + 1, h - 0x27); } if (h >= 0x30 && h <= 0x39) { // Smallint >= 0 return static_cast<uint64_t>(h - 0x30); } return 0; } // return the value for a SmallInt object int64_t Slice::getSmallIntUnchecked() const noexcept { uint8_t const h = head(); if (h >= 0x30 && h <= 0x39) { // Smallint >= 0 return static_cast<int64_t>(h - 0x30); } if (h >= 0x3a && h <= 0x3f) { // Smallint < 0 return static_cast<int64_t>(h - 0x3a) - 6; } if ((h >= 0x20 && h <= 0x27) || (h >= 0x28 && h <= 0x2f)) { // Int and UInt // we'll leave it to the compiler to detect the two ranges above are // adjacent return getIntUnchecked(); } return 0; } // translates an integer key into a string, without checks Slice Slice::translateUnchecked() const { uint8_t const* result = Options::Defaults.attributeTranslator->translate(getUIntUnchecked()); if (VELOCYPACK_LIKELY(result != nullptr)) { return Slice(result); } return Slice(); } std::string Slice::toHex() const { HexDump dump(*this); return dump.toString(); } std::string Slice::toJson(Options const* options) const { std::string buffer; StringSink sink(&buffer); toJson(&sink, options); return buffer; } std::string& Slice::toJson(std::string& out, Options const* options) const { // reserve some initial space in the output string to avoid // later reallocations. we use the Slice's byteSize as a first // approximation for the needed output buffer size. out.reserve(out.size() + byteSize()); StringSink sink(&out); toJson(&sink, options); return out; } void Slice::toJson(Sink* sink, Options const* options) const { Dumper dumper(sink, options); dumper.dump(*this); } std::string Slice::toString(Options const* options) const { if (isString()) { return copyString(); } // copy options and set prettyPrint in copy Options prettyOptions = *options; prettyOptions.prettyPrint = true; std::string buffer; // reserve some initial space in the output string to avoid // later reallocations. we use the Slice's byteSize as a first // approximation for the needed output buffer size. buffer.reserve(buffer.size() + byteSize()); StringSink sink(&buffer); Dumper::dump(this, &sink, &prettyOptions); return buffer; } std::string Slice::hexType() const { return HexDump::toHex(head()); } uint64_t Slice::normalizedHash(uint64_t seed) const { uint64_t value; if (isNumber()) { // upcast integer values to double double v = getNumericValue<double>(); value = VELOCYPACK_HASH(&v, sizeof(v), seed); } else if (isArray()) { // normalize arrays by hashing array length and iterating // over all array members ArrayIterator it(*this); uint64_t const n = it.size() ^ 0xba5bedf00d; value = VELOCYPACK_HASH(&n, sizeof(n), seed); while (it.valid()) { value ^= it.value().normalizedHash(value); it.next(); } } else if (isObject()) { // normalize objects by hashing object length and iterating // over all object members ObjectIterator it(*this, true); uint64_t const n = it.size() ^ 0xf00ba44ba5; uint64_t seed2 = VELOCYPACK_HASH(&n, sizeof(n), seed); value = seed2; while (it.valid()) { auto current = (*it); uint64_t seed3 = current.key.normalizedHash(seed2); value ^= seed3; value ^= current.value.normalizedHash(seed3); it.next(); } } else { // fall back to regular hash function value = hash(seed); } return value; } uint32_t Slice::normalizedHash32(uint32_t seed) const { uint32_t value; if (isNumber()) { // upcast integer values to double double v = getNumericValue<double>(); value = VELOCYPACK_HASH32(&v, sizeof(v), seed); } else if (isArray()) { // normalize arrays by hashing array length and iterating // over all array members ArrayIterator it(*this); uint64_t const n = it.size() ^ 0xba5bedf00d; value = VELOCYPACK_HASH32(&n, sizeof(n), seed); while (it.valid()) { value ^= it.value().normalizedHash32(value); it.next(); } } else if (isObject()) { // normalize objects by hashing object length and iterating // over all object members ObjectIterator it(*this, true); uint32_t const n = static_cast<uint32_t>(it.size() ^ 0xf00ba44ba5); uint32_t seed2 = VELOCYPACK_HASH32(&n, sizeof(n), seed); value = seed2; while (it.valid()) { auto current = (*it); uint32_t seed3 = current.key.normalizedHash32(seed2); value ^= seed3; value ^= current.value.normalizedHash32(seed3); it.next(); } } else { // fall back to regular hash function value = hash32(seed); } return value; } // look for the specified attribute inside an Object // returns a Slice(ValueType::None) if not found Slice Slice::get(std::string_view attribute) const { if (VELOCYPACK_UNLIKELY(!isObject())) { throw Exception(Exception::InvalidValueType, "Expecting Object"); } auto const h = head(); if (h == 0x0a) { // special case, empty object return Slice(); } if (h == 0x14) { // compact Object return getFromCompactObject(attribute); } ValueLength const offsetSize = indexEntrySize(h); VELOCYPACK_ASSERT(offsetSize > 0); ValueLength end = readIntegerNonEmpty<ValueLength>(start() + 1, offsetSize); // read number of items ValueLength n; ValueLength ieBase; if (offsetSize < 8) { n = readIntegerNonEmpty<ValueLength>(start() + 1 + offsetSize, offsetSize); ieBase = end - n * offsetSize; } else { n = readIntegerNonEmpty<ValueLength>(start() + end - offsetSize, offsetSize); ieBase = end - n * offsetSize - offsetSize; } if (n == 1) { // Just one attribute, there is no index table! Slice key(start() + findDataOffset(h)); if (key.isString()) { if (key.isEqualStringUnchecked(attribute)) { return Slice(key.start() + key.byteSize()); } // fall through to returning None Slice below } else if (key.isSmallInt() || key.isUInt()) { // translate key if (Options::Defaults.attributeTranslator == nullptr) { throw Exception(Exception::NeedAttributeTranslator); } if (key.translateUnchecked().isEqualString(attribute)) { return Slice(key.start() + key.byteSize()); } } // no match or invalid key type return Slice(); } // only use binary search for attributes if we have at least this many entries // otherwise we'll always use the linear search constexpr ValueLength SortedSearchEntriesThreshold = 4; if (n >= SortedSearchEntriesThreshold && (h >= 0x0b && h <= 0x0e)) { switch (offsetSize) { case 1: return searchObjectKeyBinary<1>(attribute, ieBase, n); case 2: return searchObjectKeyBinary<2>(attribute, ieBase, n); case 4: return searchObjectKeyBinary<4>(attribute, ieBase, n); case 8: return searchObjectKeyBinary<8>(attribute, ieBase, n); default: { } } } return searchObjectKeyLinear(attribute, ieBase, offsetSize, n); } // return the value for an Int object int64_t Slice::getIntUnchecked() const noexcept { uint8_t const h = head(); if (h >= 0x20 && h <= 0x27) { // Int T uint64_t v = readIntegerNonEmpty<uint64_t>(start() + 1, h - 0x1f); if (h == 0x27) { return toInt64(v); } else { int64_t vv = static_cast<int64_t>(v); int64_t shift = ::maxValues[h - 0x20]; return vv < shift ? vv : vv - (shift << 1); } } // SmallInt VELOCYPACK_ASSERT(h >= 0x30 && h <= 0x3f); return getSmallIntUnchecked(); } // return the value for an Int object int64_t Slice::getInt() const { uint8_t const h = head(); if (h >= 0x20 && h <= 0x27) { // Int T uint64_t v = readIntegerNonEmpty<uint64_t>(start() + 1, h - 0x1f); if (h == 0x27) { return toInt64(v); } else { int64_t vv = static_cast<int64_t>(v); int64_t shift = ::maxValues[h - 0x20]; return vv < shift ? vv : vv - (shift << 1); } } if (h >= 0x28 && h <= 0x2f) { // UInt uint64_t v = getUIntUnchecked(); if (v > static_cast<uint64_t>(INT64_MAX)) { throw Exception(Exception::NumberOutOfRange); } return static_cast<int64_t>(v); } if (h >= 0x30 && h <= 0x3f) { // SmallInt return getSmallIntUnchecked(); } throw Exception(Exception::InvalidValueType, "Expecting type Int"); } // return the value for a UInt object uint64_t Slice::getUInt() const { uint8_t const h = head(); if (h == 0x28) { // single byte integer return readIntegerFixed<uint64_t, 1>(start() + 1); } if (h >= 0x29 && h <= 0x2f) { // UInt return readIntegerNonEmpty<uint64_t>(start() + 1, h - 0x27); } if (h >= 0x20 && h <= 0x27) { // Int int64_t v = getInt(); if (v < 0) { throw Exception(Exception::NumberOutOfRange); } return static_cast<int64_t>(v); } if (h >= 0x30 && h <= 0x39) { // Smallint >= 0 return static_cast<uint64_t>(h - 0x30); } if (h >= 0x3a && h <= 0x3f) { // Smallint < 0 throw Exception(Exception::NumberOutOfRange); } throw Exception(Exception::InvalidValueType, "Expecting type UInt"); } // return the value for a SmallInt object int64_t Slice::getSmallInt() const { uint8_t const h = head(); if (h >= 0x30 && h <= 0x39) { // Smallint >= 0 return static_cast<int64_t>(h - 0x30); } if (h >= 0x3a && h <= 0x3f) { // Smallint < 0 return static_cast<int64_t>(h - 0x3a) - 6; } if ((h >= 0x20 && h <= 0x27) || (h >= 0x28 && h <= 0x2f)) { // Int and UInt // we'll leave it to the compiler to detect the two ranges above are // adjacent return getInt(); } throw Exception(Exception::InvalidValueType, "Expecting type SmallInt"); } int Slice::compareString(std::string_view value) const { std::size_t const length = value.size(); ValueLength keyLength; char const* k = getString(keyLength); std::size_t const compareLength = (std::min)(static_cast<std::size_t>(keyLength), length); int res = std::memcmp(k, value.data(), compareLength); if (res == 0) { return static_cast<int>(keyLength - length); } return res; } int Slice::compareStringUnchecked(std::string_view value) const noexcept { std::size_t const length = value.size(); ValueLength keyLength; char const* k = getStringUnchecked(keyLength); std::size_t const compareLength = (std::min)(static_cast<std::size_t>(keyLength), length); int res = std::memcmp(k, value.data(), compareLength); if (res == 0) { return static_cast<int>(keyLength - length); } return res; } bool Slice::isEqualString(std::string_view attribute) const { ValueLength keyLength; char const* k = getString(keyLength); return (static_cast<std::size_t>(keyLength) == attribute.size()) && (std::memcmp(k, attribute.data(), attribute.size()) == 0); } bool Slice::isEqualStringUnchecked(std::string_view attribute) const noexcept { ValueLength keyLength; char const* k = getStringUnchecked(keyLength); return (static_cast<std::size_t>(keyLength) == attribute.size()) && (std::memcmp(k, attribute.data(), attribute.size()) == 0); } Slice Slice::getFromCompactObject(std::string_view attribute) const { ObjectIterator it(*this); while (it.valid()) { Slice key = it.key(false); if (key.makeKey().isEqualString(attribute)) { return Slice(key.start() + key.byteSize()); } it.next(); } // not found return Slice(); } // get the offset for the nth member from an Array or Object type ValueLength Slice::getNthOffset(ValueLength index) const { VELOCYPACK_ASSERT(isArray() || isObject()); auto const h = head(); if (h == 0x13 || h == 0x14) { // compact Array or Object return getNthOffsetFromCompact(index); } if (VELOCYPACK_UNLIKELY(h == 0x01 || h == 0x0a)) { // special case: empty Array or empty Object throw Exception(Exception::IndexOutOfBounds); } ValueLength const offsetSize = indexEntrySize(h); ValueLength end = readIntegerNonEmpty<ValueLength>(start() + 1, offsetSize); ValueLength dataOffset = 0; // find the number of items ValueLength n; if (h <= 0x05) { // No offset table or length, need to compute: VELOCYPACK_ASSERT(h != 0x00 && h != 0x01); dataOffset = findDataOffset(h); Slice first(start() + dataOffset); ValueLength s = first.byteSize(); if (VELOCYPACK_UNLIKELY(s == 0)) { throw Exception(Exception::InternalError, "Invalid data for compact object"); } n = (end - dataOffset) / s; } else if (offsetSize < 8) { n = readIntegerNonEmpty<ValueLength>(start() + 1 + offsetSize, offsetSize); } else { n = readIntegerNonEmpty<ValueLength>(start() + end - offsetSize, offsetSize); } if (index >= n) { throw Exception(Exception::IndexOutOfBounds); } // empty array case was already covered VELOCYPACK_ASSERT(n > 0); if (h <= 0x05 || n == 1) { // no index table, but all array items have the same length // now fetch first item and determine its length if (dataOffset == 0) { VELOCYPACK_ASSERT(h != 0x00 && h != 0x01); dataOffset = findDataOffset(h); } return dataOffset + index * Slice(start() + dataOffset).byteSize(); } ValueLength const ieBase = end - n * offsetSize + index * offsetSize - (offsetSize == 8 ? 8 : 0); return readIntegerNonEmpty<ValueLength>(start() + ieBase, offsetSize); } // extract the nth member from an Array Slice Slice::getNth(ValueLength index) const { VELOCYPACK_ASSERT(isArray()); return Slice(start() + getNthOffset(index)); } // extract the nth member from an Object Slice Slice::getNthKey(ValueLength index, bool translate) const { VELOCYPACK_ASSERT(type() == ValueType::Object); Slice s(start() + getNthOffset(index)); if (translate) { return s.makeKey(); } return s; } Slice Slice::makeKey() const { if (isString()) { return *this; } if (isSmallInt() || isUInt()) { if (VELOCYPACK_UNLIKELY(Options::Defaults.attributeTranslator == nullptr)) { throw Exception(Exception::NeedAttributeTranslator); } return translateUnchecked(); } throw Exception(Exception::InvalidValueType, "Cannot translate key of this type"); } // get the offset for the nth member from a compact Array or Object type ValueLength Slice::getNthOffsetFromCompact(ValueLength index) const { auto const h = head(); VELOCYPACK_ASSERT(h == 0x13 || h == 0x14); ValueLength end = readVariableValueLength<false>(start() + 1); ValueLength n = readVariableValueLength<true>(start() + end - 1); if (VELOCYPACK_UNLIKELY(index >= n)) { throw Exception(Exception::IndexOutOfBounds); } ValueLength offset = 1 + getVariableValueLength(end); ValueLength current = 0; while (current != index) { uint8_t const* s = start() + offset; offset += Slice(s).byteSize(); if (h == 0x14) { offset += Slice(start() + offset).byteSize(); } ++current; } return offset; } // perform a linear search for the specified attribute inside an Object Slice Slice::searchObjectKeyLinear(std::string_view attribute, ValueLength ieBase, ValueLength offsetSize, ValueLength n) const { bool const useTranslator = (Options::Defaults.attributeTranslator != nullptr); for (ValueLength index = 0; index < n; ++index) { ValueLength offset = ieBase + index * offsetSize; Slice key(start() + readIntegerNonEmpty<ValueLength>(start() + offset, offsetSize)); if (key.isString()) { if (!key.isEqualStringUnchecked(attribute)) { continue; } } else if (key.isSmallInt() || key.isUInt()) { // translate key if (VELOCYPACK_UNLIKELY(!useTranslator)) { // no attribute translator throw Exception(Exception::NeedAttributeTranslator); } if (!key.translateUnchecked().isEqualString(attribute)) { continue; } } else { // invalid key type return Slice(); } // key is identical. now return value return Slice(key.start() + key.byteSize()); } // nothing found return Slice(); } // perform a binary search for the specified attribute inside an Object template<ValueLength offsetSize> Slice Slice::searchObjectKeyBinary(std::string_view attribute, ValueLength ieBase, ValueLength n) const { bool const useTranslator = (Options::Defaults.attributeTranslator != nullptr); VELOCYPACK_ASSERT(n > 0); int64_t l = 0; int64_t r = static_cast<int64_t>(n) - 1; int64_t index = r / 2; do { ValueLength offset = ieBase + index * offsetSize; Slice key(start() + readIntegerFixed<ValueLength, offsetSize>(start() + offset)); int res; if (key.isString()) { res = key.compareStringUnchecked(attribute); } else { VELOCYPACK_ASSERT(key.isSmallInt() || key.isUInt()); // translate key if (VELOCYPACK_UNLIKELY(!useTranslator)) { // no attribute translator throw Exception(Exception::NeedAttributeTranslator); } res = key.translateUnchecked().compareString(attribute); } if (res > 0) { r = index - 1; } else if (res == 0) { // found. now return a Slice pointing at the value return Slice(key.start() + key.byteSize()); } else { l = index + 1; } // determine new midpoint index = l + ((r - l) / 2); } while (r >= l); // not found return Slice(); } ValueLength Slice::byteSizeDynamic(uint8_t const* start) const { uint8_t h = *start; // types with dynamic lengths need special treatment: switch (type(h)) { case ValueType::Array: case ValueType::Object: { if (h == 0x13 || h == 0x14) { // compact Array or Object return readVariableValueLength<false>(start + 1); } VELOCYPACK_ASSERT(h > 0x01 && h <= 0x0e && h != 0x0a); if (VELOCYPACK_UNLIKELY(h >= sizeof(SliceStaticData::WidthMap) / sizeof(SliceStaticData::WidthMap[0]))) { throw Exception(Exception::InternalError, "invalid Array/Object type"); } return readIntegerNonEmpty<ValueLength>(start + 1, SliceStaticData::WidthMap[h]); } case ValueType::String: { VELOCYPACK_ASSERT(h == 0xbf); if (VELOCYPACK_UNLIKELY(h < 0xbf)) { // we cannot get here, because the FixedTypeLengths lookup // above will have kicked in already. however, the compiler // claims we'll be reading across the bounds of the input // here... return h - 0x40; } // long UTF-8 String return static_cast<ValueLength>( 1 + 8 + readIntegerFixed<ValueLength, 8>(start + 1)); } case ValueType::Binary: { VELOCYPACK_ASSERT(h >= 0xc0 && h <= 0xc7); return static_cast<ValueLength>( 1 + h - 0xbf + readIntegerNonEmpty<ValueLength>(start + 1, h - 0xbf)); } case ValueType::BCD: { if (h <= 0xcf) { // positive BCD VELOCYPACK_ASSERT(h >= 0xc8 && h < 0xcf); return static_cast<ValueLength>( 1 + h - 0xc7 + readIntegerNonEmpty<ValueLength>(start + 1, h - 0xc7)); } // negative BCD VELOCYPACK_ASSERT(h >= 0xd0 && h < 0xd7); return static_cast<ValueLength>( 1 + h - 0xcf + readIntegerNonEmpty<ValueLength>(start + 1, h - 0xcf)); } case ValueType::Tagged: { uint8_t offset = tagsOffset(start); if (VELOCYPACK_UNLIKELY(offset == 0)) { throw Exception(Exception::InternalError, "Invalid tag data in byteSize()"); } return byteSize(start + offset) + offset; } case ValueType::Custom: { VELOCYPACK_ASSERT(h >= 0xf4); switch (h) { case 0xf4: case 0xf5: case 0xf6: { return 2 + readIntegerFixed<ValueLength, 1>(start + 1); } case 0xf7: case 0xf8: case 0xf9: { return 3 + readIntegerFixed<ValueLength, 2>(start + 1); } case 0xfa: case 0xfb: case 0xfc: { return 5 + readIntegerFixed<ValueLength, 4>(start + 1); } case 0xfd: case 0xfe: case 0xff: { return 9 + readIntegerFixed<ValueLength, 8>(start + 1); } default: { // fallthrough intentional } } } default: { // fallthrough intentional } } throw Exception(Exception::InternalError, "Invalid type for byteSize()"); } // template instanciations for searchObjectKeyBinary template Slice Slice::searchObjectKeyBinary<1>(std::string_view attribute, ValueLength ieBase, ValueLength n) const; template Slice Slice::searchObjectKeyBinary<2>(std::string_view attribute, ValueLength ieBase, ValueLength n) const; template Slice Slice::searchObjectKeyBinary<4>(std::string_view attribute, ValueLength ieBase, ValueLength n) const; template Slice Slice::searchObjectKeyBinary<8>(std::string_view attribute, ValueLength ieBase, ValueLength n) const; std::ostream& operator<<(std::ostream& stream, Slice const* slice) { stream << "[Slice " << valueTypeName(slice->type()) << " (" << slice->hexType() << "), byteSize: " << slice->byteSize() << "]"; return stream; } std::ostream& operator<<(std::ostream& stream, Slice const& slice) { return operator<<(stream, &slice); } static_assert(sizeof(arangodb::velocypack::Slice) == sizeof(void*), "Slice has an unexpected size");
{ "content_hash": "4f2742e8d3c232f5f0c75f674a0dea12", "timestamp": "", "source": "github", "line_count": 797, "max_line_length": 80, "avg_line_length": 29.69134253450439, "alnum_prop": 0.6154918864097363, "repo_name": "arangodb/velocypack", "id": "7b294240648fc230ae7710fd7b806a226379bd95", "size": "25004", "binary": false, "copies": "1", "ref": "refs/heads/main", "path": "src/Slice.cpp", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "C", "bytes": "253484" }, { "name": "C++", "bytes": "4616501" }, { "name": "CMake", "bytes": "59311" }, { "name": "M4", "bytes": "25814" }, { "name": "Makefile", "bytes": "28166" }, { "name": "Python", "bytes": "502676" }, { "name": "Shell", "bytes": "48202" }, { "name": "Starlark", "bytes": "21420" } ], "symlink_target": "" }
namespace google { namespace cloud { namespace apigeeconnect_internal { GOOGLE_CLOUD_CPP_INLINE_NAMESPACE_BEGIN ConnectionServiceConnectionImpl::ConnectionServiceConnectionImpl( std::unique_ptr<google::cloud::BackgroundThreads> background, std::shared_ptr<apigeeconnect_internal::ConnectionServiceStub> stub, Options options) : background_(std::move(background)), stub_(std::move(stub)), options_(internal::MergeOptions( std::move(options), ConnectionServiceConnection::options())) {} StreamRange<google::cloud::apigeeconnect::v1::Connection> ConnectionServiceConnectionImpl::ListConnections( google::cloud::apigeeconnect::v1::ListConnectionsRequest request) { request.clear_page_token(); auto& stub = stub_; auto retry = std::shared_ptr<apigeeconnect::ConnectionServiceRetryPolicy const>( retry_policy()); auto backoff = std::shared_ptr<BackoffPolicy const>(backoff_policy()); auto idempotency = idempotency_policy()->ListConnections(request); char const* function_name = __func__; return google::cloud::internal::MakePaginationRange< StreamRange<google::cloud::apigeeconnect::v1::Connection>>( std::move(request), [stub, retry, backoff, idempotency, function_name]( google::cloud::apigeeconnect::v1::ListConnectionsRequest const& r) { return google::cloud::internal::RetryLoop( retry->clone(), backoff->clone(), idempotency, [stub]( grpc::ClientContext& context, google::cloud::apigeeconnect::v1::ListConnectionsRequest const& request) { return stub->ListConnections(context, request); }, r, function_name); }, [](google::cloud::apigeeconnect::v1::ListConnectionsResponse r) { std::vector<google::cloud::apigeeconnect::v1::Connection> result( r.connections().size()); auto& messages = *r.mutable_connections(); std::move(messages.begin(), messages.end(), result.begin()); return result; }); } GOOGLE_CLOUD_CPP_INLINE_NAMESPACE_END } // namespace apigeeconnect_internal } // namespace cloud } // namespace google
{ "content_hash": "9bfadfbd0d203e00fcbf0d67e3235552", "timestamp": "", "source": "github", "line_count": 53, "max_line_length": 79, "avg_line_length": 41.58490566037736, "alnum_prop": 0.6733212341197822, "repo_name": "googleapis/google-cloud-cpp", "id": "d18482d1274480143feda8ba0d98a10e47966a68", "size": "3340", "binary": false, "copies": "1", "ref": "refs/heads/main", "path": "google/cloud/apigeeconnect/internal/connection_connection_impl.cc", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Awk", "bytes": "2387" }, { "name": "Batchfile", "bytes": "3052" }, { "name": "C", "bytes": "21004" }, { "name": "C++", "bytes": "41174129" }, { "name": "CMake", "bytes": "1350320" }, { "name": "Dockerfile", "bytes": "111570" }, { "name": "Makefile", "bytes": "138270" }, { "name": "PowerShell", "bytes": "41266" }, { "name": "Python", "bytes": "21338" }, { "name": "Shell", "bytes": "249894" }, { "name": "Starlark", "bytes": "722015" } ], "symlink_target": "" }
id: bad87fee1348bd9aedb08845 title: Responsively Style Radio Buttons required: - link: 'https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.2.0/css/font-awesome.css' raw: true challengeType: 0 forumTopicId: 18270 --- ## Description <section id='description'> You can use Bootstrap's <code>col-xs-*</code> classes on <code>form</code> elements, too! This way, our radio buttons will be evenly spread out across the page, regardless of how wide the screen resolution is. Nest both your radio buttons within a <code>&#60;div class="row"&#62;</code> element. Then nest each of them within a <code>&#60;div class="col-xs-6"&#62;</code> element. <strong>Note:</strong> As a reminder, radio buttons are <code>input</code> elements of type <code>radio</code>. </section> ## Instructions <section id='instructions'> </section> ## Tests <section id='tests'> ```yml tests: - text: All of your radio buttons should be nested inside one <code>div</code> with the class <code>row</code>. testString: assert($("div.row:has(input[type=\"radio\"])").length > 0); - text: Each of your radio buttons should be nested inside its own <code>div</code> with the class <code>col-xs-6</code>. testString: assert($("div.col-xs-6:has(input[type=\"radio\"])").length > 1); - text: All of your <code>div</code> elements should have closing tags. testString: assert(code.match(/<\/div>/g) && code.match(/<div/g) && code.match(/<\/div>/g).length === code.match(/<div/g).length); ``` </section> ## Challenge Seed <section id='challengeSeed'> <div id='html-seed'> ```html <link href="https://fonts.googleapis.com/css?family=Lobster" rel="stylesheet" type="text/css"> <style> h2 { font-family: Lobster, Monospace; } .thick-green-border { border-color: green; border-width: 10px; border-style: solid; border-radius: 50%; } </style> <div class="container-fluid"> <div class="row"> <div class="col-xs-8"> <h2 class="text-primary text-center">CatPhotoApp</h2> </div> <div class="col-xs-4"> <a href="#"><img class="img-responsive thick-green-border" src="https://bit.ly/fcc-relaxing-cat" alt="A cute orange cat lying on its back."></a> </div> </div> <img src="https://bit.ly/fcc-running-cats" class="img-responsive" alt="Three kittens running towards the camera."> <div class="row"> <div class="col-xs-4"> <button class="btn btn-block btn-primary"><i class="fa fa-thumbs-up"></i> Like</button> </div> <div class="col-xs-4"> <button class="btn btn-block btn-info"><i class="fa fa-info-circle"></i> Info</button> </div> <div class="col-xs-4"> <button class="btn btn-block btn-danger"><i class="fa fa-trash"></i> Delete</button> </div> </div> <p>Things cats <span class="text-danger">love:</span></p> <ul> <li>cat nip</li> <li>laser pointers</li> <li>lasagna</li> </ul> <p>Top 3 things cats hate:</p> <ol> <li>flea treatment</li> <li>thunder</li> <li>other cats</li> </ol> <form action="/submit-cat-photo"> <label><input type="radio" name="indoor-outdoor"> Indoor</label> <label><input type="radio" name="indoor-outdoor"> Outdoor</label> <label><input type="checkbox" name="personality"> Loving</label> <label><input type="checkbox" name="personality"> Lazy</label> <label><input type="checkbox" name="personality"> Crazy</label> <input type="text" placeholder="cat photo URL" required> <button type="submit">Submit</button> </form> </div> ``` </div> </section> ## Solution <section id='solution'> ```html <link href="https://fonts.googleapis.com/css?family=Lobster" rel="stylesheet" type="text/css"> <style> h2 { font-family: Lobster, Monospace; } .thick-green-border { border-color: green; border-width: 10px; border-style: solid; border-radius: 50%; } </style> <div class="container-fluid"> <div class="row"> <div class="col-xs-8"> <h2 class="text-primary text-center">CatPhotoApp</h2> </div> <div class="col-xs-4"> <a href="#"><img class="img-responsive thick-green-border" src="https://bit.ly/fcc-relaxing-cat" alt="A cute orange cat lying on its back."></a> </div> </div> <img src="https://bit.ly/fcc-running-cats" class="img-responsive" alt="Three kittens running towards the camera."> <div class="row"> <div class="col-xs-4"> <button class="btn btn-block btn-primary"><i class="fa fa-thumbs-up"></i> Like</button> </div> <div class="col-xs-4"> <button class="btn btn-block btn-info"><i class="fa fa-info-circle"></i> Info</button> </div> <div class="col-xs-4"> <button class="btn btn-block btn-danger"><i class="fa fa-trash"></i> Delete</button> </div> </div> <p>Things cats <span class="text-danger">love:</span></p> <ul> <li>cat nip</li> <li>laser pointers</li> <li>lasagna</li> </ul> <p>Top 3 things cats hate:</p> <ol> <li>flea treatment</li> <li>thunder</li> <li>other cats</li> </ol> <form action="/submit-cat-photo"> <div class="row"> <div class="col-xs-6"> <label><input type="radio" name="indoor-outdoor"> Indoor</label> </div> <div class="col-xs-6"> <label><input type="radio" name="indoor-outdoor"> Outdoor</label> </div> </div> <label><input type="checkbox" name="personality"> Loving</label> <label><input type="checkbox" name="personality"> Lazy</label> <label><input type="checkbox" name="personality"> Crazy</label> <input type="text" placeholder="cat photo URL" required> <button type="submit">Submit</button> </form> </div> ``` </section>
{ "content_hash": "d125d507567644ff90a39c5e08e97e82", "timestamp": "", "source": "github", "line_count": 178, "max_line_length": 209, "avg_line_length": 31.797752808988765, "alnum_prop": 0.6388692579505301, "repo_name": "BhaveshSGupta/FreeCodeCamp", "id": "2aa4c05f23c154d5fb4be9fa0477fb93e7b76d3e", "size": "5664", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "curriculum/challenges/english/03-front-end-libraries/bootstrap/responsively-style-radio-buttons.english.md", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "CSS", "bytes": "71786" }, { "name": "HTML", "bytes": "17627" }, { "name": "JavaScript", "bytes": "1003613" }, { "name": "Shell", "bytes": "340" } ], "symlink_target": "" }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. package com.azure.identity; import com.azure.core.annotation.Immutable; import com.azure.core.credential.AccessToken; import com.azure.core.credential.TokenCredential; import com.azure.core.credential.TokenRequestContext; import com.azure.core.util.Configuration; import com.azure.identity.implementation.IdentityClient; import com.azure.identity.implementation.IdentityClientBuilder; import com.azure.identity.implementation.IdentityClientOptions; import reactor.core.publisher.Mono; /** * The base class for Managed Service Identity token based credentials. */ @Immutable public final class ManagedIdentityCredential implements TokenCredential { private final AppServiceMsiCredential appServiceMSICredential; private final VirtualMachineMsiCredential virtualMachineMSICredential; /** * Creates an instance of the ManagedIdentityCredential. * @param clientId the client id of user assigned or system assigned identity * @param identityClientOptions the options for configuring the identity client. */ ManagedIdentityCredential(String clientId, IdentityClientOptions identityClientOptions) { IdentityClient identityClient = new IdentityClientBuilder() .clientId(clientId) .identityClientOptions(identityClientOptions) .build(); Configuration configuration = Configuration.getGlobalConfiguration().clone(); if (configuration.contains(Configuration.PROPERTY_MSI_ENDPOINT)) { appServiceMSICredential = new AppServiceMsiCredential(clientId, identityClient); virtualMachineMSICredential = null; } else { virtualMachineMSICredential = new VirtualMachineMsiCredential(clientId, identityClient); appServiceMSICredential = null; } } /** * Gets the client ID of user assigned or system assigned identity. * @return the client ID of user assigned or system assigned identity. */ public String getClientId() { return this.appServiceMSICredential != null ? this.appServiceMSICredential.getClientId() : this.virtualMachineMSICredential.getClientId(); } @Override public Mono<AccessToken> getToken(TokenRequestContext request) { return (appServiceMSICredential != null ? appServiceMSICredential.authenticate(request) : virtualMachineMSICredential.authenticate(request)); } }
{ "content_hash": "3a56c2c09762e04ea75782fee50d8d9d", "timestamp": "", "source": "github", "line_count": 60, "max_line_length": 100, "avg_line_length": 42.18333333333333, "alnum_prop": 0.7447649150533386, "repo_name": "navalev/azure-sdk-for-java", "id": "8ccd89fa21ea8494837c76ead580a6115e847c9d", "size": "2531", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "sdk/identity/azure-identity/src/main/java/com/azure/identity/ManagedIdentityCredential.java", "mode": "33188", "license": "mit", "language": [ { "name": "Batchfile", "bytes": "7230" }, { "name": "CSS", "bytes": "5411" }, { "name": "Groovy", "bytes": "1570436" }, { "name": "HTML", "bytes": "29221" }, { "name": "Java", "bytes": "250218562" }, { "name": "JavaScript", "bytes": "15605" }, { "name": "PowerShell", "bytes": "30924" }, { "name": "Python", "bytes": "42119" }, { "name": "Shell", "bytes": "1408" } ], "symlink_target": "" }
package org.apache.reef.runtime.hdinsight.client.yarnrest; import org.codehaus.jackson.annotate.JsonIgnoreProperties; import org.codehaus.jackson.annotate.JsonProperty; import org.codehaus.jackson.map.ObjectMapper; import java.io.IOException; import java.io.StringWriter; /** * A response object used in deserialization when querying * the Resource Manager for an application via the YARN REST API. * For detailed information, please refer to * https://hadoop.apache.org/docs/r2.6.0/hadoop-yarn/hadoop-yarn-site/ResourceManagerRest.html */ @JsonIgnoreProperties(ignoreUnknown = true) public final class ApplicationResponse { private static final String APPLICATION_RESPONSE = "applicationResponse"; private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper(); private ApplicationState app; @JsonProperty(Constants.APP) public ApplicationState getApp() { return this.app; } public void setApp(final ApplicationState app) { this.app = app; } public ApplicationState getApplicationState() { return app; } @Override public String toString() { StringWriter writer = new StringWriter(); String objectString; try { OBJECT_MAPPER.writeValue(writer, this); objectString = writer.toString(); } catch (IOException e) { return null; } return APPLICATION_RESPONSE + objectString; } }
{ "content_hash": "5582c995a519acab40e552a4ec630a1c", "timestamp": "", "source": "github", "line_count": 51, "max_line_length": 94, "avg_line_length": 26.980392156862745, "alnum_prop": 0.7463662790697675, "repo_name": "taegeonum/incubator-reef", "id": "25041fdd8330e858e9c643e6541ebc61053da215", "size": "2183", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "lang/java/reef-runtime-hdinsight/src/main/java/org/apache/reef/runtime/hdinsight/client/yarnrest/ApplicationResponse.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Batchfile", "bytes": "2308" }, { "name": "C", "bytes": "1867" }, { "name": "C#", "bytes": "2903255" }, { "name": "C++", "bytes": "114782" }, { "name": "Java", "bytes": "4605296" }, { "name": "JavaScript", "bytes": "2105" }, { "name": "Objective-C", "bytes": "965" }, { "name": "PowerShell", "bytes": "6426" }, { "name": "Protocol Buffer", "bytes": "34980" }, { "name": "Shell", "bytes": "5510" } ], "symlink_target": "" }