100+ results for 'php rand'

Not the results you expected?

sitemailer_.php (https://gitlab.com/nvtdn2006/azora) PHP · 384 lines

231

232 private function sendPasswordResetToUser($property) {

233 /*$htmlCT = "--PHP-alt-" . $this->randomHash . "\r\n";

234 $htmlCT .= 'Content-Type: text/html; charset="iso-8859-1"' . "\r\n";

235 $htmlCT .= 'Content-Transfer-Encoding: 7bit' . "\r\n";*/

288

289 private function sendReminderforredemptionToUser($property) {

290 /*$htmlCT = "--PHP-alt-" . $this->randomHash . "\r\n";

291 $htmlCT .= 'Content-Type: text/html; charset="iso-8859-1"' . "\r\n";

292 $htmlCT .= 'Content-Transfer-Encoding: 7bit' . "\r\n";*/

378

379 /*$this->msgBody = $htmlCT . $this->msgBody;

380 $this->msgBody .= "--PHP-alt-" . $this->randomHash . "\r\n";*/

381 $this->msgBody = wordwrap($this->msgBody, $this->wordwrap);

382 }

Installerold.php (https://github.com/ArchiCroc/Tower-Web-Platform.git) PHP · 232 lines

1 <?php

2

3 /**

4 * Test class for Core_Model_User_Service.

5 * Generated by PHPUnit on 2011-06-22 at 18:34:04.

6 */

7

8 require_once '../Installer.php';

9

10 class Core_Model_Installer {

138 'username' => 'TestUser1',

139 'name' => 'Test User',

140 'location' => 'Random',

141 'email' => 'testuser1@mcdportal.com',

142 'settings' => array());

DeleteComment.php (https://gitlab.com/Blueprint-Marketing/wordpress-unit-tests) PHP · 355 lines

1 <?php

2

3 /**

4 * Admin ajax functions to be tested

5 */

6 require_once( ABSPATH . 'wp-admin/includes/ajax-actions.php' );

7

8 /**

70 $_POST['_per_page'] = 100;

71 $_POST['_page'] = 1;

72 $_POST['_url'] = admin_url( 'edit-comments.php' );

73

74 // Make the request

97 }

98

99 // The total is calculated based on a page break -OR- a random number. Let's look for both possible outcomes

100 $comment_count = wp_count_comments( 0 );

101 $recalc_total = $comment_count->total_comments;

bytearray-tests.js (https://github.com/jdeolive/ringojs.git) JavaScript · 322 lines

203 var testArray = [];

204 for (var i = 0; i < 1000; i++)

205 testArray.push(Math.floor(Math.random()*256));

206

207 var a = new ByteArray(testArray);

215 var testArray = [];

216 for (var i = 0; i < 1000; i++)

217 testArray.push(Math.floor(Math.random()*256));

218

219 var a = new ByteArray(testArray);

voucher.php (https://bitbucket.org/allanxyh/uniquemall.git) PHP · 263 lines

1 <?php

2 class ControllerAccountVoucher extends Controller {

3 private $error = array();

13

14 if (($this->request->server['REQUEST_METHOD'] == 'POST') && $this->validate()) {

15 $this->session->data['vouchers'][mt_rand()] = array(

16 'description' => sprintf($this->language->get('text_for'), $this->currency->format($this->currency->convert($this->request->post['amount'], $this->currency->getCode(), $this->config->get('config_currency'))), $this->request->post['to_name']),

17 'to_name' => $this->request->post['to_name'],

Liquid.php (https://gitlab.com/Skull3x/ClearSky) PHP · 437 lines

1 <?php

2 namespace pocketmine\block;

3

213 }

214

215 if($this instanceof Lava and $decay < 8 and $k < 8 and $k > 1 and mt_rand(0, 4) !== 0){

216 $k = $decay;

217 $flag = false;

NestedTreeRootTest.php (https://github.com/easybib/DoctrineExtensions.git) PHP · 337 lines

1 <?php

2

3 namespace Gedmo\Tree;

14 * @package Gedmo.Tree

15 * @link http://www.gediminasm.org

16 * @license MIT License (http://www.opensource.org/licenses/mit-license.php)

17 */

18 class NestedTreeRootTest extends BaseTestCaseORM

37 $took = microtime(true) - $start;

38 $minutes = intval($took / 60); $seconds = $took % 60;

39 echo sprintf("%s --> %02d:%02d", $msg, $minutes, $seconds) . PHP_EOL;

40 };

41 $repo = $this->em->getRepository(self::CATEGORY);

48 $this->em->persist($cat);

49 // siblings

50 $rnd = rand(0, 3);

51 for ($j = 0; $j < $rnd; $j++) {

52 $siblingCat = new RootCategory;

cxx11_tensor_argmax_sycl.cpp (https://gitlab.com/mrssss/eigen) C++ · 257 lines

32 Tensor<DenseIndex, 0, Layout, DenseIndex> out_max;

33 Tensor<DenseIndex, 0, Layout, DenseIndex> out_min;

34 in.setRandom();

35 in *= in.constant(100.0);

36 in(0, 0, 0) = -1000.0;

AdapterChainTest.php (https://gitlab.com/my-application.bjoernbartels.earth/ZfcUser) PHP · 311 lines

1 <?php

2

3 namespace ZfcUserTest\Authentication\Adapter;

7 use ZfcUser\Authentication\Adapter\AdapterChainEvent;

8

9 class AdapterChainTest extends \PHPUnit_Framework_TestCase

10 {

11 /**

217 $result->expects($this->once())->method('stopped')->will($this->returnValue(true));

218

219 $lastResponse = 'random-value';

220 $result->expects($this->atLeastOnce())->method('last')->will($this->returnValue($lastResponse));

221

DateTime.php (https://gitlab.com/madwanz64/laravel) PHP · 381 lines

51 * @return \DateTime

52 *

53 * @see http://php.net/manual/en/timezones.php

54 * @see http://php.net/manual/en/function.date-default-timezone-get.php

72 * @return \DateTime

73 *

74 * @see http://php.net/manual/en/timezones.php

75 * @see http://php.net/manual/en/function.date-default-timezone-get.php

143 * @see http://php.net/manual/en/timezones.php

144 * @see http://php.net/manual/en/function.date-default-timezone-get.php

145 */

146 public static function dateTimeBetween($startDate = '-30 years', $endDate = 'now', $timezone = null)

174 * @return \DateTime

175 *

176 * @see http://php.net/manual/en/timezones.php

177 * @see http://php.net/manual/en/function.date-default-timezone-get.php

webhooks.php (https://gitlab.com/0072016/woocommerce) PHP · 501 lines

1 <?php

2

3 /**

273

274 $args = array(

275 'secret' => rand_str(),

276 'status' => 'paused',

277 );

427

428 $defaults = array(

429 'name' => rand_str(),

430 'topic' => 'coupon.created',

431 'delivery_url' => 'http://example.org',

Collection.php (https://bitbucket.org/dnejedly/eaparts.git) PHP · 333 lines

1 <?php

2 /**

3 * Magento

8 * that is bundled with this package in the file LICENSE.txt.

9 * It is also available through the world-wide-web at this URL:

10 * http://opensource.org/licenses/osl-3.0.php

11 * If you did not receive a copy of the license and are unable to

12 * obtain it through the world-wide-web, please send an email

22 * @package Mage_Catalog

23 * @copyright Copyright (c) 2012 Magento Inc. (http://www.magentocommerce.com)

24 * @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0)

25 */

26

169

170 /**

171 * Add random sorting order

172 *

173 * @return Mage_Catalog_Model_Resource_Product_Link_Product_Collection

migration_tables_core_538.php (https://bitbucket.org/blackriver/openx.git) PHP · 318 lines

1 <?php

2

3 /*

23 | Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA |

24 +---------------------------------------------------------------------------+

25 $Id: migration_tables_core_538.php 81772 2012-09-11 00:07:29Z chris.nutting $

26 */

27

28 require_once(MAX_PATH.'/lib/OA/Upgrade/Migration.php');

29

30 class Migration_538 extends Migration

308 $result = $this->oDBH->exec($query);

309 if (PEAR::isError($result)) {

310 return $this->_logErrorAndReturnFalse('Cannot migrate '.$table);

311 }

312

mulyaxisex1.html (https://gitlab.com/GLORIA04/conception-site-web) HTML · 92 lines

1 <div style="font-weight: bold;margin-left:15px;">mulyaxisex1.php</div><link rel="stylesheet" href="../phphl.css" type="text/css"><div class="hl-main"><table class="hl-table" width="100%"><tr><td class="hl-gutter" align="right" valign="top"><pre>1

2 2

3 3

45 45

46 46

47 </pre></td><td class="hl-main" valign="top"><pre><span class="hl-inlinetags">&lt;?php</span><span class="hl-code"> </span><span class="hl-comment">//</span><span class="hl-comment"> content=&quot;text/plain; charset=utf-8&quot;</span><span class="hl-comment"></span><span class="hl-code">

48 </span><span class="hl-reserved">require_once</span><span class="hl-code"> </span><span class="hl-brackets">(</span><span class="hl-quotes">'</span><span class="hl-string">jpgraph/jpgraph.php</span><span class="hl-quotes">'</span><span class="hl-brackets">)</span><span class="hl-code">;

49 </span><span class="hl-reserved">require_once</span><span class="hl-code"> </span><span class="hl-brackets">(</span><span class="hl-quotes">'</span><span class="hl-string">jpgraph/jpgraph_line.php</span><span class="hl-quotes">'</span><span class="hl-brackets">)</span><span class="hl-code">;

50

51 </span><span class="hl-var">$n</span><span class="hl-code"> = </span><span class="hl-number">8</span><span class="hl-code">;

52 </span><span class="hl-reserved">for</span><span class="hl-brackets">(</span><span class="hl-var">$i</span><span class="hl-code">=</span><span class="hl-number">0</span><span class="hl-code">; </span><span class="hl-var">$i</span><span class="hl-code"> &lt; </span><span class="hl-var">$n</span><span class="hl-code">; ++</span><span class="hl-var">$i</span><span class="hl-code"> </span><span class="hl-brackets">)</span><span class="hl-code"> </span><span class="hl-brackets">{</span><span class="hl-code">

53 </span><span class="hl-var">$datay</span><span class="hl-brackets">[</span><span class="hl-var">$i</span><span class="hl-brackets">]</span><span class="hl-code"> = </span><span class="hl-identifier">rand</span><span class="hl-brackets">(</span><span class="hl-number">1</span><span class="hl-code">,</span><span class="hl-number">10</span><span class="hl-brackets">)</span><span class="hl-code">;

54 </span><span class="hl-var">$datay2</span><span class="hl-brackets">[</span><span class="hl-var">$i</span><span class="hl-brackets">]</span><span class="hl-code"> = </span><span class="hl-identifier">rand</span><span class="hl-brackets">(</span><span class="hl-number">10</span><span class="hl-code">,</span><span class="hl-number">55</span><span class="hl-brackets">)</span><span class="hl-code">;

xfs_dir2.c (http://omnia2droid.googlecode.com/svn/trunk/) C · 766 lines ✨ Summary

This C code is part of a file system implementation, specifically handling directory operations. It provides functions for removing blocks from directories, checking if a block is a leaf or not, and shrinking an inode by unmapping a block. The code ensures consistency and correctness in the file system’s internal data structures.

161 XFS_AGINO_TO_INO(mp, agno, agino) == ino;

162 if (unlikely(XFS_TEST_ERROR(!ino_ok, mp, XFS_ERRTAG_DIR_INO_VALIDATE,

163 XFS_RANDOM_DIR_INO_VALIDATE))) {

164 xfs_fs_cmn_err(CE_WARN, mp, "Invalid inode number 0x%Lx",

165 (unsigned long long) ino);

class-wp-customize-setting.php (https://gitlab.com/Gashler/dp) PHP · 439 lines

1 <?php

2 /**

3 * Customize Setting Class.

408 global $custom_image_header;

409

410 // If the value doesn't exist (removed or random),

411 // use the header_image value.

412 if ( ! $value )

upload_02.php (https://bitbucket.org/hocarvalho/wroisite.git) PHP · 428 lines

1 <?php

2 require_once 'include/plugins/phpthumb-latest/ThumbLib.inc.php';

3

4 if(isset($_FILES['imagem1']) && is_uploaded_file($_FILES['imagem1']['tmp_name'])){

40 $upload_dir = $diretorio;

41 $name_file_1 = $_FILES['imagem1']['name'];

42 $name_file_1 = md5(rand()).$extension;

43 $file_path = $upload_dir.$name_file_1;

44

51 else {

52

53 $thumb = PhpThumbFactory::create($diretorio.$name_file_1);

54 $thumb->resize($largura_thumb, $altura_thumb)->save($diretorio.'/thumb/'.$name_file_1);

55

180 $upload_dir = $diretorio;

181 $name_file_3 = $_FILES['imagem3']['name'];

182 $name_file_3 = md5(rand()).$extension;

183 $file_path = $upload_dir.$name_file_3;

184

migration_tables_core_538.php (https://github.com/skynet/OpenX-2.8.7.git) PHP · 318 lines

1 <?php

2

3 /*

23 | Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA |

24 +---------------------------------------------------------------------------+

25 $Id: migration_tables_core_538.php 62345 2010-09-14 21:16:38Z chris.nutting $

26 */

27

28 require_once(MAX_PATH.'/lib/OA/Upgrade/Migration.php');

29

30 class Migration_538 extends Migration

308 $result = $this->oDBH->exec($query);

309 if (PEAR::isError($result)) {

310 return $this->_logErrorAndReturnFalse('Cannot migrate '.$table);

311 }

312

Files.php (https://github.com/jaws-project/jaws.git) PHP · 282 lines

1 <?php

2 /**

3 * Directory Gadget

20 $data['parent'] = (int)$data['parent'];

21 if (!$data['public']) {

22 $data['key'] = mt_rand(1000, 9999999999);

23 }

24 $data['create_time'] = $data['update_time'] = time();

Config.php (https://bitbucket.org/jokusafet/magento2.git) PHP · 429 lines

1 <?php

2 /**

3 * Magento

8 * that is bundled with this package in the file LICENSE.txt.

9 * It is also available through the world-wide-web at this URL:

10 * http://opensource.org/licenses/osl-3.0.php

11 * If you did not receive a copy of the license and are unable to

12 * obtain it through the world-wide-web, please send an email

64 const XML_PATH_DISPLAY_CART_SHIPPING = 'tax/cart_display/shipping';

65 const XML_PATH_DISPLAY_CART_DISCOUNT = 'tax/cart_display/discount';

66 const XML_PATH_DISPLAY_CART_GRANDTOTAL = 'tax/cart_display/grandtotal';

67 const XML_PATH_DISPLAY_CART_FULL_SUMMARY= 'tax/cart_display/full_summary';

68 const XML_PATH_DISPLAY_CART_ZERO_TAX = 'tax/cart_display/zero_tax';

75 const XML_PATH_DISPLAY_SALES_SHIPPING = 'tax/sales_display/shipping';

76 const XML_PATH_DISPLAY_SALES_DISCOUNT = 'tax/sales_display/discount';

77 const XML_PATH_DISPLAY_SALES_GRANDTOTAL = 'tax/sales_display/grandtotal';

78 const XML_PATH_DISPLAY_SALES_FULL_SUMMARY= 'tax/sales_display/full_summary';

79 const XML_PATH_DISPLAY_SALES_ZERO_TAX = 'tax/sales_display/zero_tax';

excreate.c (http://omnia2droid.googlecode.com/svn/trunk/) C · 523 lines ✨ Summary

This C code is part of an ACPI (Advanced Configuration and Power Interface) parser, responsible for creating objects such as methods, power resources, processors, and more from AML (AcPI Machine Language) data. It disassembles AML instructions, extracts relevant information, and creates corresponding object structures to be used in the ACPI system.

366 acpi_status acpi_ex_create_processor(struct acpi_walk_state *walk_state)

367 {

368 union acpi_operand_object **operand = &walk_state->operands[0];

369 union acpi_operand_object *obj_desc;

381 /* Initialize the processor object from the operands */

382

383 obj_desc->processor.proc_id = (u8) operand[1]->integer.value;

384 obj_desc->processor.length = (u8) operand[3]->integer.value;

413 acpi_status acpi_ex_create_power_resource(struct acpi_walk_state *walk_state)

414 {

415 union acpi_operand_object **operand = &walk_state->operands[0];

416 acpi_status status;

417 union acpi_operand_object *obj_desc;

462 u32 aml_length, struct acpi_walk_state *walk_state)

463 {

464 union acpi_operand_object **operand = &walk_state->operands[0];

465 union acpi_operand_object *obj_desc;

array.idl.php (https://github.com/diegoIta/hiphop-php.git) PHP · 376 lines

1 <?php

2

3 include_once 'base.php';

119 VariableArguments);

120

121 f('array_rand', Variant,

122 array('input' => Variant,

123 'num_req' => array(Int32, '1')));

EntityRevisionsTest.php (https://gitlab.com/mohamed_hussein/prodt) PHP · 264 lines

1 <?php

2

3 namespace Drupal\KernelTests\Core\Entity;

212 // Create a basic EntityTestMulRev entity and save it.

213 $entity = EntityTestMulRev::create();

214 $entity->setName($this->randomString());

215 $entity->save();

216 $this->assertTrue($entity->isLatestTranslationAffectedRevision());

218 // Load the created entity and create a new pending revision.

219 $pending_revision = EntityTestMulRev::load($entity->id());

220 $pending_revision->setName($this->randomString());

221 $pending_revision->setNewRevision(TRUE);

222 $pending_revision->isDefaultRevision(FALSE);

249 /** @var \Drupal\entity_test\Entity\EntityTestMulRev $it_revision */

250 $it_revision = $pending_revision->addTranslation('it');

251 $it_revision->setName($this->randomString());

252 $it_revision->setNewRevision(TRUE);

253 $it_revision->isDefaultRevision(FALSE);

Tax.php (https://github.com/jweiss/Magento-Example.git) PHP · 300 lines

80 $store = $this->getStore();

81 $allowTax = ($this->_source->getTaxAmount() > 0) || ($this->_config->displaySalesZeroTax($store));

82 $grandTotal = (float) $this->_source->getGrandTotal();

83 if (!$grandTotal || ($allowTax && !$this->_config->displaySalesTaxWithGrandTotal($store))) {

251 $store = $this->getStore();

252 $parent = $this->getParentBlock();

253 $grandototal = $parent->getTotal('grand_total');

254 if (!$grandototal || !(float)$this->_source->getGrandTotal()) {

258 if ($this->_config->displaySalesTaxWithGrandTotal($store)) {

259 $grandtotal = $this->_source->getGrandTotal();

260 $baseGrandtotal = $this->_source->getBaseGrandTotal();

261 $grandtotalExcl = $grandtotal - $this->_source->getTaxAmount();

262 $baseGrandtotalExcl = $baseGrandtotal - $this->_source->getBaseTaxAmount();

263 $grandtotalExcl = max($grandtotalExcl, 0);

264 $baseGrandtotalExcl = max($baseGrandtotalExcl, 0);

265 $totalExcl = new Varien_Object(array(

266 'code' => 'grand_total',

jEdit.ipr (https://jedit.svn.sourceforge.net/svnroot/jedit) Unknown · 1737 lines

779 <inspection_tool class="PlatformDetectionJS" enabled="true" level="WARNING" enabled_by_default="true" />

780 <inspection_tool class="PointlessIndexOfComparison" enabled="true" level="WARNING" enabled_by_default="true" />

781 <inspection_tool class="PrivateMemberAccessBetweenOuterAndInnerClass" enabled="true" level="WARNING" enabled_by_default="true" />

782 <inspection_tool class="ProtectedMemberInFinalClass" enabled="true" level="WARNING" enabled_by_default="true" />

783 <inspection_tool class="PublicConstructorInNonPublicClass" enabled="true" level="WARNING" enabled_by_default="true" />

788 <option name="nameString" value="aa,abc,bad,bar,bar2,baz,baz1,baz2,baz3,bb,blah,bogus,bool,cc,dd,defau1t,dummy,dummy2,ee,fa1se,ff,foo,foo1,foo2,foo3,foobar,four,fred,fred1,fred2,gg,hh,hello,hello1,hello2,hello3,ii,nu11,one,silly,silly2,string,two,that,then,three,whi1e,var" />

789 </inspection_tool>

790 <inspection_tool class="RandomDoubleForRandomInteger" enabled="true" level="WARNING" enabled_by_default="true" />

791 <inspection_tool class="RawUseOfParameterizedType" enabled="true" level="WARNING" enabled_by_default="true">

792 <option name="ignoreObjectConstruction" value="true" />

mibII_ip.c (https://bitbucket.org/freebsd/freebsd-head/) C · 494 lines ✨ Summary

This C code appears to be part of a network monitoring system, specifically for IP packet statistics. It provides functions to retrieve and update counters for various types of packets, including ICMP (Internet Control Message Protocol) packets, such as errors, timeouts, and echoes. The counters are likely used to track network performance and troubleshoot issues.

4 * All rights reserved.

5 *

6 * Author: Harti Brandt <harti@freebsd.org>

7 *

8 * Redistribution and use in source and binary forms, with or without

27 * SUCH DAMAGE.

28 *

29 * $Begemot: bsnmp/snmp_mibII/mibII_ip.c,v 1.11 2005/05/23 09:03:40 brandt_h Exp $

30 *

31 * ip group scalars.

vector_iterator.hpp (http://hadesmem.googlecode.com/svn/trunk/) text · 0 lines

22 {

23 struct vector_iterator_tag;

24 struct random_access_traversal_tag;

25

26 template <typename Vector, int N>

33 typedef Vector vector;

34 typedef vector_iterator_tag fusion_tag;

35 typedef random_access_traversal_tag category;

36 typedef vector_iterator_identity<

37 typename add_const<Vector>::type, N> identity;

CodeVisitor.java (https://jedit.svn.sourceforge.net/svnroot/jedit) Java · 288 lines ✨ Summary

This is a Java class that defines an interface for parsing and analyzing bytecode of Java classes. It provides methods to visit various elements of the bytecode, such as instructions, labels, local variables, and exception handlers. The visitor pattern allows for custom processing of the parsed bytecode.

78 * @param opcode the opcode of the instruction to be visited. This opcode is

79 * either BIPUSH, SIPUSH or NEWARRAY.

80 * @param operand the operand of the instruction to be visited.

81 */

82

90 * This opcode is either ILOAD, LLOAD, FLOAD, DLOAD, ALOAD, ISTORE,

91 * LSTORE, FSTORE, DSTORE, ASTORE or RET.

92 * @param var the operand of the instruction to be visited. This operand is

93 * the index of a local variable.

94 */

102 * @param opcode the opcode of the type instruction to be visited. This opcode

103 * is either NEW, ANEWARRAY, CHECKCAST or INSTANCEOF.

104 * @param desc the operand of the instruction to be visited. This operand is

105 * must be a fully qualified class name in internal form, or the type

106 * descriptor of an array type (see {@link Type Type}).

QtSvg.4.6.0.linux-gcc-amd64.txt (https://bitbucket.org/ultra_iter/qt-vtl.git) Plain Text · 16905 lines

685 __pthread_internal_list (0x7fb2a27102a0) 0

686

687 Class random_data

688 size=48 align=8

689 base size=48 base align=8

690 random_data (0x7fb2a2710850) 0

691

692 Class drand48_data

693 size=24 align=8

694 base size=24 base align=8

695 drand48_data (0x7fb2a27108c0) 0

696

697 Class QVectorData

laguerre.qbk (http://hadesmem.googlecode.com/svn/trunk/) text · 0 lines

155

156 A mixture of spot tests of values calculated using functions.wolfram.com,

157 and randomly generated test data are

158 used: the test data was computed using

159 [@http://shoup.net/ntl/doc/RR.txt NTL::RR] at 1000-bit precision.

algorithm.cpp (http://hadesmem.googlecode.com/svn/trunk/) C++ · 0 lines ✨ Summary

This C++ code defines a unit test suite for range algorithms, testing various functions such as find, lower_bound, and partition on a vector of integers. It uses Boost’s unit testing framework to create a test suite with a single test case that exercises these algorithms. The tests verify the correctness of the algorithms under different conditions.

104

105 template<typename Rng>

106 void test_random_algorithms(Rng & rng, std::random_access_iterator_tag)

107 {

108 typedef BOOST_DEDUCED_TYPENAME boost::range_iterator<Rng>::type iterator;

114 if(0)

115 {

116 boost::random_shuffle(rng);

117

118 // Must be a value since random_shuffle must take the generator by

119 // reference to match the standard.

120 null_op1 rng_generator;

121 boost::random_shuffle(rng, rng_generator);

122

123 boost::sort(rng);

CompilerBcb.h (https://bitbucket.org/ultra_iter/qt-vtl.git) C Header · 68 lines

27 #define fileHandleStat fstat

28

29 #define O_RANDOM 0

30

31 //java long type

verilog.xml (https://jedit.svn.sourceforge.net/svnroot/jedit) XML · 219 lines

182 <FUNCTION>$monitoron</FUNCTION>

183 <FUNCTION>$monitoroff</FUNCTION>

184 <FUNCTION>$random</FUNCTION>

185 <FUNCTION>$printtimescale</FUNCTION>

186 <FUNCTION>$timeformat</FUNCTION>

update_conversion.rb (https://code.google.com/p/google-api-ads-ruby/) Ruby · 97 lines ✨ Summary

This Ruby script updates a conversion status to ‘DISABLED’ using the Google AdWords API. It retrieves an instance of the ConversionTrackerService, sets the operation to update the conversion with the specified ID and new status, and then calls the mutate method to execute the operation. The response is then printed to the console, indicating whether the conversion was successfully updated or not.

45 operation = {

46 :operator => 'SET',

47 :operand => {

48 # The 'xsi_type' field allows you to specify the xsi:type of the object

49 # being created. It's only necessary when you must provide an explicit

BSHUnaryExpression.java (https://jedit.svn.sourceforge.net/svnroot/jedit) Java · 121 lines ✨ Summary

This Java code defines a class BSHUnaryExpression that represents a unary expression in a programming language, such as an increment or decrement operator (++ or --). It handles various types of operands and performs operations like negation, boolean conversion, and arithmetic operations on integers and longs.

86 throws EvalError

87 {

88 Class operandType = val.getClass();

89 Object operand = Primitive.promoteToInteger(val);

90

91 if(operand instanceof Boolean)

92 return new Boolean(

93 Primitive.booleanUnaryOperation((Boolean)operand, kind));

94 else if(operand instanceof Integer)

95 {

96 int result = Primitive.intUnaryOperation((Integer)operand, kind);

99 if(kind == INCR || kind == DECR)

100 {

101 if(operandType == Byte.TYPE)

102 return new Byte((byte)result);

103 if(operandType == Short.TYPE)

pl1.xml (https://jedit.svn.sourceforge.net/svnroot/jedit) XML · 597 lines

529 <KEYWORD3>radix</KEYWORD3>

530 <KEYWORD3>raise</KEYWORD3>

531 <KEYWORD3>random</KEYWORD3>

532 <KEYWORD3>rank</KEYWORD3>

533 <KEYWORD3>rem</KEYWORD3>

inode.c (http://omnia2droid.googlecode.com/svn/trunk/) C · 5312 lines ✨ Summary

This C code is part of a file system implementation, specifically handling journaling and data corruption protection for a Linux file system. It provides functions to manage inodes, handle page faults, and ensure data integrity by writing changes to a journal before modifying the underlying storage. The code ensures that file system updates are atomic and consistent, preventing data corruption and ensuring system reliability.

134 /* Give ourselves just enough room to cope with inodes in which

135 * i_blocks is corrupt: we've seen disk corruptions in the past

136 * which resulted in random data in an inode which looked enough

137 * like a regular file for ext4 to try to delete it. Things

138 * will go a bit crazy if that happens, but at least we should

Operand.h (http://hadesmem.googlecode.com/svn/trunk/) C Header · 54 lines ✨ Summary

This C header file defines a namespace AsmJit and includes platform-specific code for x86 and x64 architectures. It provides a basic structure for an AsmJit compiler, with no platform-independent code. The file grants permission to use, modify, and distribute the software under certain conditions, while disclaiming warranties and liability.

25

26 // [Guard]

27 #ifndef _ASMJIT_OPERAND_H

28 #define _ASMJIT_OPERAND_H

47

48 #if defined(ASMJIT_X86) || defined(ASMJIT_X64)

49 #include "OperandX86X64.h"

50 #endif // ASMJIT_X86 || ASMJIT_X64

51

52 // [Guard]

53 #endif // _ASMJIT_OPERAND_H

54

interval_base_set.html (http://hadesmem.googlecode.com/svn/trunk/) text · 0 lines

162 <li><pre class="literallayout"> <a name="id653036-bb"></a><span class="identifier">BOOST_STATIC_CONSTANT</span><span class="special">(</span><span class="keyword">int</span><span class="special">,</span> <span class="identifier">fineness</span> <span class="special">=</span> <span class="number">0</span><span class="special">)</span><span class="special">;</span></pre></li>

163 <li>

164 <pre class="literallayout"><span class="keyword">void</span> <a name="id653053-bb"></a><span class="identifier">swap</span><span class="special">(</span><a class="link" href="interval_base_set.html" title="Class template interval_base_set">interval_base_set</a> <span class="special">&amp;</span> operand<span class="special">)</span><span class="special">;</span></pre>

165 <p>swap the content of containers </p>

166 </li>

rebol.xml (https://jedit.svn.sourceforge.net/svnroot/jedit) XML · 547 lines

81 <KEYWORD1>poke</KEYWORD1>

82 <KEYWORD1>power</KEYWORD1>

83 <KEYWORD1>random</KEYWORD1>

84 <KEYWORD1>remainder</KEYWORD1>

85 <KEYWORD1>remove</KEYWORD1>

EnhancedMenuItem.java (https://jedit.svn.sourceforge.net/svnroot/jedit) Java · 187 lines ✨ Summary

This Java class, EnhancedMenuItem, extends JMenuItem to add support for multi-key shortcuts in a GUI application. It creates a custom menu item with an optional accelerator string and displays it on the screen. When clicked, it triggers an action associated with the menu item. The class also handles mouse events, such as hover text display and release of status messages.

143 String shortcutFont;

144 if (OperatingSystem.isMacOSLF())

145 shortcutFont = "Lucida Grande";

146 else

147 shortcutFont = "Monospaced";

malloc.c (https://bitbucket.org/ultra_iter/qt-vtl.git) C · 5515 lines

379 initialization.

380

381 USE_DEV_RANDOM default: 0 (i.e., not used)

382 Causes malloc to use /dev/random to initialize secure magic seed for

624 #define USE_BUILTIN_FFS 0

625 #endif /* USE_BUILTIN_FFS */

626 #ifndef USE_DEV_RANDOM

627 #define USE_DEV_RANDOM 0

628 #endif /* USE_DEV_RANDOM */

629 #ifndef NO_MALLINFO

630 #define NO_MALLINFO 0

foxpro.xml (https://jedit.svn.sourceforge.net/svnroot/jedit) XML · 1859 lines

157 <KEYWORD3>explicit</KEYWORD3>

158 <KEYWORD3>erase</KEYWORD3>

159 <KEYWORD3>randomize</KEYWORD3>

160

161 <!-- Operators -->

summarize.py (git://github.com/numpy/numpy.git) Python · 173 lines ✨ Summary

The script analyzes Numpy functions and reports which ones are documented and which are not. It checks for documentation in RST files, skips certain modules, and formats the output into columns. The script prints a summary of documented and undocumented functions, showing their locations in RST files.

42 # --- numpy.random:

43 random random.info random.mtrand random.ranf random.sample random.random

44

45 # --- numpy.fft:

100 undocumented = {}

101

102 import numpy, numpy.fft, numpy.linalg, numpy.random

103 for mod in [numpy, numpy.fft, numpy.linalg, numpy.random,

InlineBox.cpp (https://bitbucket.org/ultra_iter/qt-vtl.git) C++ · 382 lines

138 int result = fontMetrics.height();

139 if (parent())

140 result += flowObject->borderAndPaddingLogicalHeight();

141 return result;

142 }

pl.seq.html (http://angel-engine.googlecode.com/svn/trunk/) HTML · 1053 lines ✨ Summary

This HTML code is a documentation page for a programming library, likely written in a style similar to Python’s help module. It displays a table of contents and links to individual pages explaining various functions and methods, along with their parameters and return values. The content is formatted for easy reading and navigation.

231

232 <tr>

233 <td class="name" nowrap><a href="#random">random</a>&nbsp;(n, l, u)</td>

234 <td class="summary">return an iterator of random numbers.</td>

775

776

777 <dt><a name="random"></a><strong>random</strong>&nbsp;(n, l, u)</dt>

778 <dd>

779 return an iterator of random numbers.

788

789 <li>

790 l: same as the first optional argument to math.random

791 </li>

792

793 <li>

794 u: same as the second optional argument to math.random

795 </li>

796

kcomedilib_main.c (http://omnia2droid.googlecode.com/svn/trunk/) C · 561 lines ✨ Summary

This C code implements a device driver for a generic serial interface, providing a framework for managing multiple devices and handling various ioctl operations such as locking, canceling, polling, mapping, and unmapping. It provides a flexible way to register callback functions and handle asynchronous operations. The code is designed to be portable across different platforms.

118 struct comedi_device *dev = (struct comedi_device *) d;

119

120 /* return something random */

121 return dev->minor;

122 }

InStateReactionTest.vcproj (http://hadesmem.googlecode.com/svn/trunk/) text · 0 lines

76 ProgramDatabaseFile="$(OutDir)/InStateReactionTest.pdb"

77 SubSystem="1"

78 RandomizedBaseAddress="1"

79 DataExecutionPrevention="0"

80 TargetMachine="1"

159 OptimizeReferences="2"

160 EnableCOMDATFolding="2"

161 RandomizedBaseAddress="1"

162 DataExecutionPrevention="0"

163 TargetMachine="1"

perl_matcher_recursive.hpp (http://hadesmem.googlecode.com/svn/trunk/) C++ Header · 0 lines ✨ Summary

This C++ header file implements a regular expression engine, providing functions for matching and manipulating strings according to regular expression rules. It includes various match functions (match_recursion, match_match, etc.) that handle different aspects of pattern matching, such as recursion, lookahead, and capturing groups. The code is part of the Boost library, a popular C++ framework for functional programming and other utilities.

88 // some compilers (VC++) emit run-time initialisation which breaks thread

89 // safety, so use a dispatch function instead:

90 //(::boost::is_random_access_iterator<BidiIterator>::value ? &perl_matcher<BidiIterator, Allocator, traits>::match_dot_repeat_fast : &perl_matcher<BidiIterator, Allocator, traits>::match_dot_repeat_slow),

91 &perl_matcher<BidiIterator, Allocator, traits>::match_dot_repeat_dispatch,

92 &perl_matcher<BidiIterator, Allocator, traits>::match_char_repeat,

535 bool greedy = (rep->greedy) && (!(m_match_flags & regex_constants::match_any) || m_independent);

536 std::size_t count, desired;

537 if(::boost::is_random_access_iterator<BidiIterator>::value)

538 {

539 desired =

639 bool greedy = (rep->greedy) && (!(m_match_flags & regex_constants::match_any) || m_independent);

640 std::size_t desired = greedy ? rep->max : rep->min;

641 if(::boost::is_random_access_iterator<BidiIterator>::value)

642 {

643 BidiIterator end = position;

tst_qdesktopservices.cpp (https://bitbucket.org/ultra_iter/qt-vtl.git) C++ · 388 lines

118 QTest::newRow("BasicWithHttp") << QUrl("http://www.google.fi") << true;

119 QTest::newRow("BasicWithoutHttp") << QUrl("www.nokia.fi") << true;

120 QTest::newRow("BasicWithUserAndPw") << QUrl("http://s60prereleases:oslofjord@pepper.troll.no/s60prereleases/patches/") << true;

121 QTest::newRow("URL with space") << QUrl("http://www.manataka.org/Contents Page.html") << true;

122

EnhancedMenuItem.java (https://jedit.svn.sourceforge.net/svnroot/jedit) Java · 214 lines ✨ Summary

This Java class, EnhancedMenuItem, extends JMenuItem to add support for multi-key shortcuts in a text editor. It creates a custom menu item with an optional accelerator string and displays it on the screen. The class also handles mouse events, such as hover and click, to provide additional functionality like displaying a message when the user hovers over the menu item.

146 if (OperatingSystem.isMacOSLF())

147 {

148 shortcutFont = "Lucida Grande";

149 }

150 else

awk.xml (https://jedit.svn.sourceforge.net/svnroot/jedit) XML · 116 lines

75 <KEYWORD2>log</KEYWORD2>

76 <KEYWORD2>match</KEYWORD2>

77 <KEYWORD2>rand</KEYWORD2>

78 <KEYWORD2>sin</KEYWORD2>

79 <KEYWORD2>split</KEYWORD2>

80 <KEYWORD2>sprintf</KEYWORD2>

81 <KEYWORD2>sqrt</KEYWORD2>

82 <KEYWORD2>srand</KEYWORD2>

83 <KEYWORD2>sub</KEYWORD2>

84 <KEYWORD2>substr</KEYWORD2>

CompilerX86X64.h (http://hadesmem.googlecode.com/svn/trunk/) C Header · 8926 lines ✨ Summary

This is a C++ header file that defines classes and functions for an assembler (AsmJit) compiler utility. It provides functionality for code generation, memory management, error handling, logging, and emitting comments. The AsmJit::CompilerCore class serves as the core of the compiler, while the AsmJit::CompilerUtil class offers utility methods. The classes and functions are designed to work together to generate assembly code from a high-level programming language.

640

641 //! @brief Create a new @ref EInstruction instance.

642 EInstruction(Compiler* c, uint32_t code, Operand* operandsData, uint32_t operandsCount) ASMJIT_NOTHROW;

643 //! @brief Destroy the @ref EInstruction instance.

644 virtual ~EInstruction() ASMJIT_NOTHROW;

689 //! @brief Get operands array (3 operands total).

690 inline Operand* getOperands() ASMJIT_NOTHROW { return _operands; }

691 //! @brief Get operands array (3 operands total).

692 inline const Operand* getOperands() const ASMJIT_NOTHROW { return _operands; }

693

694 //! @brief Get memory operand.

773 // --------------------------------------------------------------------------

774

775 EJmp(Compiler* c, uint32_t code, Operand* operandsData, uint32_t operandsCount) ASMJIT_NOTHROW;

776 virtual ~EJmp() ASMJIT_NOTHROW;

777

binary_search_test.cpp (http://hadesmem.googlecode.com/svn/trunk/) C++ · 0 lines ✨ Summary

The code tests the functionality of random-access iterators and bidirectional iterators with both no comparison and a custom comparison function. It generates random sequences, searches for specific values within those sequences, and verifies that the search results are correct. The output indicates whether the test passed or failed for each type of iterator and comparison function.

10 #include <iostream>

11 #include <cassert>

12 #include <stdlib.h> // for rand(). Would use cstdlib but VC6.4 doesn't put it in std::

13 #include <list>

14 #include <algorithm>

42 const std::size_t sequence_length = 1000;

43

44 unsigned random_number()

45 {

46 return static_cast<unsigned>(::rand()) % sequence_length;

58

59 template <class T>

60 void push_back_random_number_string(T& seq)

61 {

62 unsigned value = random_number();

counting_iterator_ref.rst (http://hadesmem.googlecode.com/svn/trunk/) ReStructuredText · 0 lines ✨ Summary

The Boost C++ Libraries provide a counting_iterator class template that models the Readable Lvalue Iterator concept and supports various iterator categories. It is designed to work with incrementable types, allowing for pre- and post-increment operations, and provides a way to access the underlying value type through the base() function.

44 else if (numeric_limits<Incrementable>::is_specialized)

45 return |iterator-category|_\ (

46 random_access_traversal_tag, Incrementable, const Incrementable&)

47 else

48 return |iterator-category|_\ (

75

76 If ``iterator_category`` is convertible to

77 ``random_access_iterator_tag`` or ``random_access_traversal_tag``,

78 the following must must also be valid::

79

93 tag ``CategoryOrTraversal``. Otherwise, if

94 ``numeric_limits<Incrementable>::is_specialized``, then

95 ``counting_iterator`` models Random Access Traversal Iterator.

96 Otherwise, ``counting_iterator`` models the same iterator traversal

97 concepts modeled by ``Incrementable``.

frame_9.svg (https://bitbucket.org/atchariya/nokia.git) SVG · 3078 lines

105 cd7plK/3PXdF+HEX/lky5nnif+4DX+sDazEOvCqdHJitNqFrnCMxLgR+t+/Z9co1L7ySCp9x45mS

106 Ghyceb0EXo0Lvh6cb6mywREpiMEfdJHjnPhicQwjuIMpOSZyXCAC62nHy75i1y3AnHU7gy9VSOog

107 9d+LVSXtwgrBUv2eR0wqpyMuCEpSp58mohQj6Yx7qEoqNcgFD5GxGFsH7wLPhp5rrqQ8MZeCSGDd

108 r1mlpspSw01AAyaKiSGe+bIbbxfhonOGUsfIYxKvEVnlwkeufHeh3BVl17D0ocFJjkMOTRUizEq9

109 MUV4EDp+RZVRhS9NueK/JaEaySaIGtGVqcxYKKzCkpwzOzNcCrigqrVj9qqeQpUsRpR6LCRrr0GE

262 T4tSOxOpqqOnevsAvJwjn8M4TjOf4Pwfg3A/RNScTirEIW607T6IOE4ieGxB3okR4Q808uYy8nfn

263 zGsl4V55gG+IsLMdX7FAXq745jzxgRiHKG+Kcm0p/MhYc3M6d6JncuNk+uwQ4qebDlOpLs6o7QFR

264 Z2EjV2dlNay5rxOTJwarphpXIZvSDT1y+ybTlUOOvv09oDq283CALdYV700TW9vxSdkxW2alwtaF

265 Dc5PhTX/2Aa2+ZTvCdCtebVbsO+ZL6RMCZF/s+i4s+j5QYQuFWLJf6PJWRlnwvkW3VuxXHbkxRrW

266 E2F7Ua9jCOTYkYe6C0JjoFusWHRdk2smbmYDCSxjxZ77YuzMWMTInb7nqlQMus/VEPoaMKtyzYRy

556 d1ozopWgoIVYLcSK5IR4SdlkUWx3D65cIx4ecen4hHz7fbI5lralOVIDU2m5QuJlG/g68EPJvBYa

557 vpgj/4X17IjwHs7faFr+JAd8zuBJ2nI2DKzHnicSGGoX+nNhwlwCpVNOWbqxIfPQRh7iRIl8Tju+

558 4WtUI/+6TPhpn/PusOZv64YvascfzsrcjNRpCT57QxxLeLWftNxXY7ldMfNarVylT3UnLBO2XOBj

559 wadsY8vBMJClxBMepBX5HPZnM5pYYJxNdm5N9rigkdPtkseeuS/CrheTy8oyUZVJrkSIWrUwTcKr

560 lOdkquV5QoxszqBK0oBX2vW1pmHtzn1PtWtIyChDKGReCYFrlST9Xq3PGCSQRWuGysGNA0JdvyMx

FormatterImpl.java (https://bitbucket.org/nbargnesi/idea.git) Java · 807 lines

257 disableFormatting();

258 try {

259 final FormatProcessor processor = buildProcessorAndWrapBlocks(

260 model, block, settings, indentOptions, new FormatTextRanges(affectedRange, true)

261 );

285 final FormattingDocumentModel documentModel = model.getDocumentModel();

286 final Block block = model.getRootBlock();

287 final FormatProcessor processor = buildProcessorAndWrapBlocks(

288 documentModel, block, settings, indentOptions, new FormatTextRanges(rangeToAdjust, true)

289 );

313 final FormattingDocumentModel documentModel = model.getDocumentModel();

314 final Block block = model.getRootBlock();

315 final FormatProcessor processor = buildProcessorAndWrapBlocks(

316 documentModel, block, settings, settings.getIndentOptions(fileType), null

317 );

gssapictx.c (https://bitbucket.org/freebsd/freebsd-head/) C · 869 lines ✨ Summary

This C code implements a subset of the GSSAPI (Generic Security Services Application Programming Interface) protocol, which provides mutual authentication and integrity for communication between two parties. The code includes functions for creating, deleting, and managing security contexts, as well as logging errors and displaying error messages. It appears to be part of a larger DNS library or application.

33 #include <isc/print.h>

34 #include <isc/platform.h>

35 #include <isc/random.h>

36 #include <isc/string.h>

37 #include <isc/time.h>

FIXES (https://bitbucket.org/freebsd/freebsd-head/) Unknown · 1011 lines

55 May 1, 2011:

56 after advice from todd miller, kevin lo, ruslan ermilov,

57 and arnold robbins, changed srand() to return the previous

58 seed (which is 1 on the first call of srand). the seed is

59 an Awkfloat internally though converted to unsigned int to

60 pass to the library srand(). thanks, everyone.

61

62 fixed a subtle (and i hope low-probability) overflow error

443

444 Jan 13, 1999:

445 replaced srand argument by (unsigned int) in run.c;

446 avoids problem on Mac and potentially on Unix & Windows.

447 thanks to Dan Allen.

715

716 Nov 19, 1991:

717 use RAND_MAX instead of literal in builtin().

718

719 Nov 12, 1991:

constants.h (http://omnia2droid.googlecode.com/svn/trunk/) C++ Header · 446 lines ✨ Summary

This C++ header file defines constants and enumerations for the SCTP (Stream Control Transmission Protocol) protocol, including transport layer parameters, address scopes, retransmit reasons, lower cwnd reasons, and authentication-related constants. It provides a set of values that can be used throughout an application or library implementing SCTP functionality.

34 * La Monte H.P. Yarroll <piggy@acm.org>

35 * Karl Knutson <karl@athena.chicago.il.us>

36 * Randall Stewart <randall@stewart.chicago.il.us>

37 * Ken Morneau <kmorneau@cisco.com>

38 * Qiaobing Xie <qxie1@motorola.com>

439

440 /* SCTP-AUTH Section 6.1

441 * The RANDOM parameter MUST contain a 32 byte random number.

442 */

443 #define SCTP_AUTH_RANDOM_LENGTH 32

QtScript.4.6.0.linux-gcc-ia32.txt (https://bitbucket.org/ultra_iter/qt-vtl.git) Plain Text · 2811 lines

685 __pthread_internal_slist (0xb5b80b04) 0

686

687 Class random_data

688 size=28 align=4

689 base size=28 base align=4

690 random_data (0xb5b80e10) 0

691

692 Class drand48_data

693 size=24 align=4

694 base size=24 base align=4

695 drand48_data (0xb5b80e4c) 0

696

697 Class QVectorData

atgrammar.g (http://ambienttalk.googlecode.com/svn/) Unknown · 629 lines

104 // an assignment covers both table assignment t[i] := v and field assignment o.m := v

105 assignment!: (parametertable EQL) => par:parametertable EQL val:expression { #assignment = #([AGMULTIASS,"multi-set"], par, val); }

106 | o:operand a:assign_table_or_field[#o] { #assignment = #a; };

107 assign_table_or_field![AST functor]: tbl:tabulation[functor] EQL tvl:expression { #assign_table_or_field = #([AGASSTAB,"table-set"], tbl, tvl); }

108 | sel:selection[functor] EQL fvl:expression { #assign_table_or_field = #([AGASSFLD,"field-set"], sel, fvl); };

111 // sends have lowest priority and are therefore the highest applicable rule.

112 expression: keywordlist

113 | rcv:comparand (opr:CMP^ arg:comparand)*;

114

115 // Comparands are expression types delimited by comparators so that they can

116 // be composed of additive expressions or any higher ranking operations.

117 comparand: term (ADD^ term)*;

118

119 // Terms are expression types delimited by additive operators so that they can

133 // values (numbers and strings), variables, blocks, inline tables and subexpressions

134 // A reference can also be a quotation or a first-class message creation operation

135 operand :! nbr:NBR { #operand = #([AGNBR,"number"],nbr); }

136 |! frc:FRC { #operand = #([AGFRC,"fraction"],frc); }

apdl.xml (https://jedit.svn.sourceforge.net/svnroot/jedit) XML · 7537 lines

5 <!--

6

7 Version 0.9.8 - generated by Randolf Mock on 11/22/2003

8 Randolf.Mock@siemens.com

CodingStyle (http://omnia2droid.googlecode.com/svn/trunk/) Unknown · 825 lines

258

259 LOCAL variable names should be short, and to the point. If you have

260 some random integer loop counter, it should probably be called "i".

261 Calling it "loop_counter" is non-productive, if there is no chance of it

262 being mis-understood. Similarly, "tmp" can be just about any type of

468 user helper that "GNU emacs" automatically formats the C sources for

469 you, and you've noticed that yes, it does do that, but the defaults it

470 uses are less than desirable (in fact, they are worse than random

471 typing - an infinite number of monkeys typing into GNU emacs would never

472 make a good program).

random_access_index.hpp (http://hadesmem.googlecode.com/svn/trunk/) C++ Header · 0 lines ✨ Summary

This C++ header file defines a class random_access_index that provides a random access interface for storing and querying data. It allows insertion, deletion, and iteration over elements in the index, with features like invariant checking and specialized algorithms for swapping indices. The class is designed to work with various super-metatypes and tag lists, providing flexibility and customization options for different use cases.

7 */

8

9 #ifndef BOOST_MULTI_INDEX_RANDOM_ACCESS_INDEX_HPP

10 #define BOOST_MULTI_INDEX_RANDOM_ACCESS_INDEX_HPP

32 #include <boost/multi_index/detail/safe_mode.hpp>

33 #include <boost/multi_index/detail/scope_guard.hpp>

34 #include <boost/multi_index/random_access_index_fwd.hpp>

35 #include <boost/throw_exception.hpp>

36 #include <boost/tuple/tuple.hpp>

61 namespace detail{

62

63 /* random_access_index adds a layer of random access indexing

64 * to a given Super

65 */

625 }

626

627 random_access_index(const random_access_index<SuperMeta,TagList>& x):

628 super(x),

629

sh7763rdp_defconfig (http://omnia2droid.googlecode.com/svn/trunk/) Unknown · 1237 lines

710 CONFIG_LEGACY_PTY_COUNT=256

711 # CONFIG_IPMI_HANDLER is not set

712 CONFIG_HW_RANDOM=y

713 # CONFIG_HW_RANDOM_TIMERIOMEM is not set

person.h (https://bitbucket.org/ultra_iter/qt-vtl.git) C++ Header · 106 lines

49 Q_PROPERTY(int size READ size WRITE setSize)

50 Q_PROPERTY(QColor color READ color WRITE setColor)

51 Q_PROPERTY(QString brand READ brand WRITE setBrand)

52 Q_PROPERTY(qreal price READ price WRITE setPrice)

53 public:

60 void setColor(const QColor &);

61

62 QString brand() const;

63 void setBrand(const QString &);

68 int m_size;

69 QColor m_color;

70 QString m_brand;

71 qreal m_price;

72 };

actionscript.xml (https://jedit.svn.sourceforge.net/svnroot/jedit) XML · 830 lines

169 <LITERAL2>printAsBitmapNum</LITERAL2>

170 <LITERAL2>printNum</LITERAL2>

171 <LITERAL2>random</LITERAL2> <!-- deprecated -->

172 <LITERAL2>removeMovieClip</LITERAL2>

173 <LITERAL2>scroll</LITERAL2>

qnodefns_p.h (https://bitbucket.org/ultra_iter/qt-vtl.git) C Header · 176 lines

123 /**

124 * Overridden in order to call CastingPlatform::prepareCasting(). It also

125 * implements the optimization of rewriting to its operand if its

126 * type is xs:double(since the <tt>fn:number()</tt> call is in that case superflorous).

127 */

qunresolvedvariablereference.cpp (https://bitbucket.org/ultra_iter/qt-vtl.git) C++ · 91 lines

74 }

75

76 SequenceType::List UnresolvedVariableReference::expectedOperandTypes() const

77 {

78 return SequenceType::List();

cl.vim (https://bitbucket.org/ultra_iter/vim-qt.git) Vim Script · 113 lines

69 syn keyword clReserved ERROR EXIT INTERRUPT LOCKED LREPLY MODE MCOL MLINE MREPLY NULL REPLY V1 V2 V3 V4 V5 V6 V7 V8 V9 ZERO BYPASS GOING_BACK AAUTO ABORT ABORT ALIGN BIGE CONVERT FNUM GOBACK HANGUP JUSTIFY NEXIT OUTPUT RAUTO RAWDISPLAY RAWPRINT REPEAT SKIP TAB TRIM LCOUNT PCOUNT PLINES SLINES SCOLS MATCH LMATCH

70

71 syn keyword clFunction asc asize chr name random slen srandom day getarg getcgi getenv lcase scat sconv sdel skey smult srep substr sword trim ucase match

72

73 syn keyword clStatement clear clear_eol clear_eos close copy create unique with where empty define define ldefine delay_form delete escape exit_block exit_do exit_process field fork format get getfile getnext getprev goto head join maintain message no_join on_eop on_key on_exit on_delete openin openout openapp pause popenin popenout popenio print put range read redisplay refresh restart_block screen select sleep text unlock write and not or do

icon.xml (https://jedit.svn.sourceforge.net/svnroot/jedit) XML · 199 lines

146 <KEYWORD3>&amp;pos</KEYWORD3>

147 <KEYWORD3>&amp;progname</KEYWORD3>

148 <KEYWORD3>&amp;random</KEYWORD3>

149 <KEYWORD3>&amp;regions</KEYWORD3>

150 <KEYWORD3>&amp;source</KEYWORD3>

perlkw.swg (https://swig.svn.sourceforge.net/svnroot/swig) Unknown · 252 lines

46 PERLBN(log);

47 PERLBN(oct);

48 PERLBN(rand);

49 PERLBN(sin);

50 PERLBN(sqrt);

51 PERLBN(srand);

52

53

ellint_3.html (http://hadesmem.googlecode.com/svn/trunk/) HTML · 0 lines ✨ Summary

This HTML code outputs a documentation page for a mathematical function, specifically the elliptic integral of the third kind. It provides information on the function’s properties, usage, and implementation details, including its relation to Carlson’s integrals. The page includes equations, diagrams, and references to external resources, such as the Boost Software License.

238 The tests use a mixture of spot test values calculated using the online

239 calculator at <a href="http://functions.wolfram.com" target="_top">functions.wolfram.com</a>,

240 and random test data generated using NTL::RR at 1000-bit precision and

241 this implementation.

242 </p>

accounts.csv (https://bitbucket.org/ultra_iter/qt-vtl.git) Unknown · 12 lines

1 "Name","Address","Quantity"

2 "Kristian Quan","123 Company Place, Big City","4"

3 "Matthew Rand","The Orchard, Little Village","2"

4 "Eirik Asaki","497 Park Skyway, Future City","29"

5 "Jarek Hanssen","1023 Riviera Drive, Southern Precinct","45"

9 "Shane Bowland","P.O. Box 419, Beach Resort","1"

10 "Gavin Holm","19 Library Road, University Campus, near Large Town","16"

11 "Adrienna Randles","98 Tapestry Road, Market Town, The Shires","1"

12

projection.py (https://bitbucket.org/copelco/django-timepiece/) Python · 288 lines ✨ Summary

This Python code is a test suite for a project management system, specifically testing various aspects of assignment and allocation logic. It creates assignments with different start and end dates, hours, and priority types, then tests how these are projected, allocated, and tracked over time, including unallocated hours, user allocations, and hour tracking.

1 import datetime

2 import random

3 from decimal import Decimal

4

64 # random weeks

65 num = random.randint(5, 20)

66 start = utils.get_week_start(datetime.date.today())

67 end = start + datetime.timedelta(weeks=num - 1)

81 def test_project_contract_remaining_weeks(self):

82 """ Test calculation of contract remaining weeks """

83 num = random.randint(5, 20)

84 start = datetime.date.today()

85 end = start + datetime.timedelta(weeks=num - 1)

tsql.xml (https://jedit.svn.sourceforge.net/svnroot/jedit) XML · 1020 lines

405 <KEYWORD2>QUOTENAME</KEYWORD2>

406 <KEYWORD2>RADIANS</KEYWORD2>

407 <KEYWORD2>RAND</KEYWORD2>

408 <KEYWORD2>REPLACE</KEYWORD2>

409 <KEYWORD2>REPLICATE</KEYWORD2>

test-sprite.js (https://bitbucket.org/Tsiannian/cocos2d-x.git) JavaScript · 782 lines

174

175 SpriteTouchTest.prototype.createSprite = function( pos ) {

176 var idx = Math.random() * 1400 / 100;

177 idx = Math.floor( idx );

178 var x = Math.floor(idx%5) * 85;

182 sprite.setPosition( pos );

183

184 var rand = Math.random();

185

186 if( rand < 0.20 ) {

187 var action = cc.ScaleBy.create(3, 2 );

188 } else if(rand < 0.40) {

189 var action = cc.RotateBy.create(3, 360 );

190 } else if( rand < 0.60) {

xprt.c (http://photon-android.googlecode.com/svn/) C · 1160 lines ✨ Summary

This C code implements a transport layer for RPC (Remote Procedure Call) communications. It manages a pool of slots to handle incoming requests, prioritizes them based on their priority, and ensures that resources are released when no longer needed. The code also handles creation, destruction, and reference management of the transport instance.

975 static inline void xprt_init_xid(struct rpc_xprt *xprt)

976 {

977 xprt->xid = net_random();

978 }

979

ReplaceForEachLoopWithIndexedForLoopIntention.java (https://bitbucket.org/nbargnesi/idea.git) Java · 272 lines

53 }

54 final boolean isArray = iteratedValueType instanceof PsiArrayType;

55 final PsiElement grandParent = statement.getParent();

56 final PsiStatement context;

57 if (grandParent instanceof PsiLabeledStatement) {

58 context = (PsiStatement)grandParent;

59 } else {

60 context = statement;

157 final PsiTypeCastExpression castExpression =

158 (PsiTypeCastExpression)expression;

159 final PsiExpression operand = castExpression.getOperand();

160 return getVariableName(operand);

users-guide.xml (https://jedit.svn.sourceforge.net/svnroot/jedit) XML · 711 lines

106 <para>Hunspell is the spell-checker bundled with OpenOffice.org (as of 2.0.2)

107 and Mozilla firefox (as of 3.0).

108 The java interface is from <ulink url="http://dion.swamp.dk/hunspell.html">Flemming Frandsen</ulink>.

109 </para>

110 <para>The interactions with Hunspell are done via native calls: some string-copying

604 available from jedit repository. The documentation is generated using docbook xsl.

605 </para>

606 <para>Some tests are included. They are based upon <ulink url="http://fest.easytesting.org/swing/wiki/pmwiki.php">FEST-swing</ulink>

607 for GUI testing. Otherwise they are plain <ulink url="http://www.junit.org/">jUnit</ulink> tests.

608 To run the tests, <command>cd</command> to the plugin root directory and type <command>ant test</command>.

project.ts.result (https://bitbucket.org/ultra_iter/qt-vtl.git) Unknown · 39 lines

7 <message>

8 <location filename="main.cpp" line="51"/>

9 <source>random ascii only</source>

10 <translation type="unfinished"></translation>

11 </message>

22 <message>

23 <location filename="main.cpp" line="54"/>

24 <source>random ascii only in utf8</source>

25 <translation type="unfinished"></translation>

26 </message>

parisc_ksyms.c (http://photon-android.googlecode.com/svn/) C · 163 lines ✨ Summary

This C code exports kernel symbols, which are functions and variables that can be used by other parts of the Linux kernel or user space applications. The exported symbols include memory management functions, atomic operations, and function pointers, allowing for compatibility with different architectures and configurations. It provides a way to access these symbols from outside the kernel, making it easier to develop and test kernel code.

7 * Copyright (C) 2001-2003 Grant Grundler <grundler with parisc-linux.org>

8 * Copyright (C) 2002-2003 Matthew Wilcox <willy at parisc-linux.org>

9 * Copyright (C) 2002 Randolph Chung <tausq at parisc-linux.org>

10 * Copyright (C) 2002-2007 Helge Deller <deller with parisc-linux.org>

11 *

CBZip2InputStream.java (https://jedit.svn.sourceforge.net/svnroot/jedit) Java · 954 lines ✨ Summary

This Java code appears to be part of a decompression algorithm for a specific type of compressed data. It reads and decodes binary data, using Huffman coding and other techniques to extract the original data. The code manages various tables and mappings to ensure correct decoding, including selectors, coding tables, and in-use tables.

22 {

23 private static final int START_BLOCK_STATE = 1;

24 private static final int RAND_PART_A_STATE = 2;

25 private static final int RAND_PART_B_STATE = 3;

26 private static final int RAND_PART_C_STATE = 4;

27 private static final int NO_RAND_PART_A_STATE = 5;

28 private static final int NO_RAND_PART_B_STATE = 6;

29 private static final int NO_RAND_PART_C_STATE = 7;

62 private char z;

63

64 private boolean m_blockRandomised;

65

66 /*

ThreadingPthreads.cpp (https://bitbucket.org/ultra_iter/qt-vtl.git) C++ · 393 lines

36 #include "HashMap.h"

37 #include "MainThread.h"

38 #include "RandomNumberSeed.h"

39 #include "StdLibExtras.h"

40 #include "ThreadIdentifierDataPthreads.h"

75 atomicallyInitializedStaticMutex = new Mutex;

76 threadMapMutex();

77 initializeRandomNumberGenerator();

78 #if !OS(DARWIN) || PLATFORM(CHROMIUM) || USE(WEB_THREAD)

79 mainThread = pthread_self();

timezone.xml (git://github.com/landgraf/matreshka.git) XML · 451 lines

71 <type name="brbvb" alias="America/Boa_Vista"/>

72 <type name="brcgb" alias="America/Cuiaba"/>

73 <type name="brcgr" alias="America/Campo_Grande"/>

74 <type name="brern" alias="America/Eirunepe"/>

75 <type name="brfen" alias="America/Noronha Brazil/DeNoronha"/>

350 <type name="sydam" alias="Asia/Damascus"/>

351 <type name="szqmn" alias="Africa/Mbabane"/>

352 <type name="tcgdt" alias="America/Grand_Turk"/>

353 <type name="tdndj" alias="Africa/Ndjamena"/>

354 <type name="tfpfr" alias="Indian/Kerguelen"/>

Makefile (https://bitbucket.org/freebsd/freebsd-head/) Makefile · 18 lines ✨ Summary

This Makefile defines a kernel module for FreeBSD called ng_ccatm. It includes source files from the netgraph and contrib directories, as well as header files from the netnatm directory. The CFLAGS variable is set to include debugging symbols and define the CCATM_DEBUG macro. The module is built using the bsd.kmod.mk template.

1 # $FreeBSD$

2 #

3 # Author: Harti Brandt <harti@freebsd.org>

4 #

5

ChangesLog.txt (http://pandorapanic.googlecode.com/svn/trunk/) Plain Text · 480 lines

468 -Added: Some future adjustments to particle engine regarding fading. Needs some adjustment but if particles go black, they will be reset.

469 -Fixed: Particles out of bounds crashing.

470 -Updated: Fixed random number generation in Random class.

471 -Fixed: potentially fixed sprites disappearing on 0 angle rotations in Image class.

472

dt_cg.c (https://bitbucket.org/freebsd/freebsd-head/) C · 2007 lines ✨ Summary

This C code is part of a compiler’s intermediate representation (IR) generation process for a dynamic typing system. It generates machine-specific code for a given IR node, which represents an expression in the source code. The code creates and manages registers, handles different types of nodes (e.g., identifiers, integers), and appends instructions to a list of generated code.

733 /*

734 * Determine if we should perform signed or unsigned comparison for an OP2.

735 * If both operands are of arithmetic type, perform the usual arithmetic

736 * conversions to determine the common real type for comparison [ISOC 6.5.8.3].

737 */

fields.csv (https://code.google.com/p/minecraft-smp-mocreatures/) CSV · 4407 lines

265 "field_459_b","isOptimalFlowDirection","b","[Z","[Z","BlockFlowing","oi","net/minecraft/src","0"

266 "field_461_c","flowCost","c","[I","[I","BlockFlowing","oi","net/minecraft/src","0"

267 "field_28036_a","furnaceRand","a","Ljava/util/Random;","Ljava/util/Random;","BlockFurnace","sx","net/minecraft/src","0"

268 "field_456_a","isActive","b","Z","Z","BlockFurnace","sx","net/minecraft/src","0"

269 "field_28037_c","keepFurnaceInventory","c","Z","Z","BlockFurnace","sx","net/minecraft/src","0"

355 "field_889_c","field_889_c","c","Ljava/util/List;","Ljava/util/List;","ChunkProviderClient","uo","net/minecraft/src","0"

356 "field_888_d","worldObj","d","LWorld;","Lfb;","ChunkProviderClient","uo","net/minecraft/src","0"

357 "field_913_j","rand","j","Ljava/util/Random;","Ljava/util/Random;","ChunkProviderGenerate","xw","net/minecraft/src","0"

358 "field_912_k","field_912_k","k","LNoiseGeneratorOctaves;","Lua;","ChunkProviderGenerate","xw","net/minecraft/src","0"

359 "field_911_l","field_911_l","l","LNoiseGeneratorOctaves;","Lua;","ChunkProviderGenerate","xw","net/minecraft/src","0"

835 "field_1384_l","prevFrameTime","H","J","J","EntityRenderer","pt","net/minecraft/src","0"

836 "field_28133_I","field_28133_I","I","J","J","EntityRenderer","pt","net/minecraft/src","0"

837 "field_1383_m","random","J","Ljava/util/Random;","Ljava/util/Random;","EntityRenderer","pt","net/minecraft/src","0"

838 "field_27287_H","rainSoundCounter","K","I","I","EntityRenderer","pt","net/minecraft/src","0"

839 "field_1394_b","field_1394_b","d","I","I","EntityRenderer","pt","net/minecraft/src","0"

browser_465215.js (git://github.com/zpao/v8monkey.git) JavaScript · 72 lines ✨ Summary

This JavaScript code tests a bug related to duplicate tabs and their values. It creates two identical tabs, sets unique values on each tab, and then duplicates one of them. The test verifies that the duplicated tab has the same value as the original, but when the original’s value is changed, the duplicated tab remains unchanged.

42 let uniqueName = "bug 465215";

43 let uniqueValue1 = "as good as unique: " + Date.now();

44 let uniqueValue2 = "as good as unique: " + Math.random();

45

46 // set a unique value on a new, blank tab

BigInt.scala (git://github.com/greedy/scala-llvm.git) Scala · 385 lines ✨ Summary

This is a Scala implementation of a BigInt (Big Integer) class, providing various mathematical operations and conversions to other data types such as byte, short, char, int, long, float, and double. It also offers methods for creating ranges of BigInt values with specified steps and end values. The class provides a way to represent large integers in a scalable and efficient manner.

65 new BigInt(new BigInteger(signum, magnitude))

66

67 /** Constructs a randomly generated positive BigInt that is probably prime,

68 * with the specified bitLength.

69 */

70 def apply(bitlength: Int, certainty: Int, rnd: scala.util.Random): BigInt =

71 new BigInt(new BigInteger(bitlength, certainty, rnd.self))

72

73 /** Constructs a randomly generated BigInt, uniformly distributed over the

74 * range 0 to (2 ^ numBits - 1), inclusive.

75 *

JavaClass.java (http://ambienttalk.googlecode.com/svn/) Java · 387 lines ✨ Summary

This Java code defines a class that represents a wrapper around a Java Class object, providing additional functionality for interacting with the wrapped class in an Actor-based system. It handles serialization, deserialization, and type checking, as well as implementing ATTypeTag interface methods to manage the class’s hierarchy and relationships.

169 public JavaClass asJavaClassUnderSymbiosis() throws XTypeMismatch { return this; }

170

171 public ATBoolean base__opeql__opeql_(ATObject comparand) throws InterpreterException {

172 return NATBoolean.atValue(this.equals(comparand));

control_w.h (http://photon-android.googlecode.com/svn/) C++ Header · 46 lines ✨ Summary

This C++ header file defines constants for a rounding control, precision control, and exception masks used by a floating-point unit (FPU) in a computer’s processor. It provides definitions for various flags that can be set to control the behavior of arithmetic operations, such as rounding, precision, and handling exceptions like underflow or overflow.

24 #define CW_Overflow Const_(0x0008) /* overflow mask */

25 #define CW_ZeroDiv Const_(0x0004) /* divide by zero mask */

26 #define CW_Denormal Const_(0x0002) /* denormalized operand mask */

27 #define CW_Invalid Const_(0x0001) /* invalid operation mask */

28

ZipEntryTest.cs (https://bitbucket.org/jens13/cleanzip.git) C# · 193 lines

2 // Distributed under the New BSD License.

3 // (See accompanying file notice.txt or at

4 // http://www.opensource.org/licenses/bsd-license.php)

5

6 using System;

158 File.Delete(zipFile);

159 Thread.Sleep(100);

160 var content = RandomString(contentSize);

161 var files = GetFileNames(numberOfFiles);

162 var timer = Stopwatch.StartNew();

AGSymbol.java (http://ambienttalk.googlecode.com/svn/) Java · 152 lines ✨ Summary

This Java class represents a symbol in an AmbientTalk/2 programming language implementation. It provides methods for creating, evaluating, and manipulating symbols, which are unique strings used to represent values in the language. The class ensures that symbols remain unique across different actors (VMs) by using a shared string pool.

128 }

129

130 public ATBoolean base__opeql__opeql_(ATObject comparand) throws InterpreterException {

131 return NATBoolean.atValue(this == comparand);

36_01_corepatch_world_10366_10818.sql (https://code.google.com/p/trinitydb/) SQL · 344 lines ✨ Summary

This SQL code updates and deletes various entries in several tables, including creature_template, spell_script_names, and spell_dbc. It sets script names for creatures, spells, and other entities, often referencing specific NPCs, bosses, or items. The changes update the script names to match new or corrected values, ensuring consistency across the game’s data structures.

61 ('npc set link',2, 'Syntax: .npc set link $creatureGUID\r\n\r\nLinks respawn of selected creature to the condition that $creatureGUID defined is alive.'),

62 ('npc set model',2, 'Syntax: .npc set model #displayid\r\n\r\nChange the model id of the selected creature to #displayid.'),

63 ('npc set movetype',2, 'Syntax: .npc set movetype [#creature_guid] stay/random/way [NODEL]\r\n\r\nSet for creature pointed by #creature_guid (or selected if #creature_guid not provided) movement type and move it to respawn position (if creature alive). Any existing waypoints for creature will be removed from the database if you do not use NODEL. If the creature is dead then movement type will applied at creature respawn.\r\nMake sure you use NODEL, if you want to keep the waypoints.'),

64 ('npc set phase',2, 'Syntax: .npc set phase #phasemask\r\n\r\nSelected unit or pet phasemask changed to #phasemask with related world vision update for players. In creature case state saved to DB and persistent. In pet case change active until in game phase changed for owner, owner re-login, or GM-mode enable/disable..'),

65 ('npc set spawndist',2, 'Syntax: .npc set spawndist #dist\r\n\r\nAdjust spawndistance of selected creature to dist.'),

ast.go (git://github.com/border/golang-china.git) Go · 739 lines ✨ Summary

This Go code defines a parser for the Go programming language, representing its syntax structure as a tree-like data structure. It includes nodes for files, packages, and declarations (such as functions, variables, and constants), along with their associated documentation and comments. The code provides methods to access the position of each node in the parsed source file.

221 StarExpr struct {

222 token.Position // position of "*"

223 X Expr // operand

224 }

225

230 token.Position // position of Op

231 Op token.Token // operator

232 X Expr // operand

233 }

234

236 //

237 BinaryExpr struct {

238 X Expr // left operand

239 OpPos token.Position // position of Op

240 Op token.Token // operator

posixemulation.py (git://github.com/mitsuhiko/werkzeug.git) Python · 107 lines ✨ Summary

This Python code provides a POSIX emulation for renaming files on Windows systems, allowing for atomic and pseudo-atomic renames. It uses ctypes to interact with Windows API functions and handles cases where the target file already exists. The rename function falls back to traditional OS.rename if atomic rename fails.

22 import errno

23 import time

24 import random

25

26 from ._compat import to_unicode

95 if e.errno != errno.EEXIST:

96 raise

97 old = "%s-%08x" % (dst, random.randint(0, sys.maxint))

98 os.rename(dst, old)

99 os.rename(src, dst)

MapFold.hs (git://github.com/fortytools/holumbus.git) Haskell · 98 lines ✨ Summary

This Haskell code tests the Control.Concurrent.MapFold module, which is used for parallel computation on large datasets. It runs a series of examples with different numbers of processors and inputs, demonstrating how to map and fold operations are performed in parallel. The output shows the sequence of operations and results, highlighting the importance of associative and symmetric binary operators for determinate results.

23 import System.IO

24 import System.IO.Unsafe

25 import System.Random

26

27 -- ------------------------------------------------------------

53 mapF x = do

54 logg $ "mapF: inp = " ++ show x

55 randomDelay

56 res <- return $ show x

57 logg $ "mapF: res = " ++ show res

59 foldF x y = do

60 logg $ "foldF: inp = " ++ show (x,y)

61 randomDelay

62 res <- return $ "(" ++ x ++ "+" ++ y ++ ")"

63 logg $ "foldF: res = " ++ show res

nrepl-client.factor (https://bitbucket.org/kotarak/vimclojure/) text · 0 lines

1 ! Copyright 2011 (c) Meikel Brandmeyer.

2 ! All rights reserved.

3 !

TwitterAlikeExample.html (http://redis.googlecode.com/svn/trunk/) HTML · 253 lines ✨ Summary

This HTML code outputs a blog post about Redis, a popular in-memory data store. The content explains how to implement a Twitter-like clone using Redis, including setting up followers and posting messages. It also discusses horizontal scaling of the system, including hashing keys, distributing user data across servers, and handling special cases like incrementing IDs and retrieving timeline data.

27

28 <div class="narrow">

29 <h1><a name="A case study: Design and implementation of a simple Twitter clone using only the Redis key-value store as database and PHP">A case study: Design and implementation of a simple Twitter clone using only the Redis key-value store as database and PHP</a></h1>In this article I'll explain the design and the implementation of a <a href="http://retwis.antirez.com" target="_blank">simple clone of Twitter</a> written using PHP and <a href="http://code.google.com/p/redis/" target="_blank">Redis</a> as only database. The programming community uses to look at key-value stores like special databases that can't be used as drop in replacement for a relational database for the development of web applications. This article will try to prove the contrary.<br/><br/>Our Twitter clone, <a href="http://retwis.antirez.com" target="_blank">called Retwis</a>, is structurally simple, has very good performances, and can be distributed among N web servers and M Redis servers with very little efforts. You can find the source code <a href="http://code.google.com/p/redis/downloads/list" target="_blank">here</a>.<br/><br/>We use PHP for the example since it can be read by everybody. The same (or... much better) results can be obtained using Ruby, Python, Erlang, and so on.

30 <h1><a name="Key-value stores basics">Key-value stores basics</a></h1>

31 The essence of a key-value store is the ability to store some data, called <i>value</i>, inside a key. This data can later be retrieved only if we know the exact key used to store it. There is no way to search something by value. So for example I can use the command SET to store the value <b>bar</b> at key <b>foo</b>:<br/><br/><pre class="codeblock python" name="code">

79 </pre>Ok I think we are ready to start coding!

80 <h2><a name="Prerequisites">Prerequisites</a></h2>

81 If you didn't download it already please <a href="http://code.google.com/p/redis/wiki/README" target="_blank">grab the source code of Retwis</a>. It's a simple tar.gz file with a few of .php files inside. The implementation is very simple. You will find the PHP library client inside (redis.php) that is used to talk with the Redis server from PHP. This library was written by <a href="http://qix.it" target="_blank">Ludovico Magnocavallo</a> and you are free to reuse this in your own projects, but for updated version of the library please download the Redis distribution.<br/><br/>Another thing you probably want is a working Redis server. Just get the source, compile with make, and run with ./redis-server and you are done. No configuration is required at all in order to play with it or to run Retwis in your computer.

82 <h2><a name="Data layout">Data layout</a></h2>

83 Working with a relational database this is the stage were the database layout should be produced in form of tables, indexes, and so on. We don't have tables, so what should be designed? We need to identify what keys are needed to represent our objects and what kind of values this keys need to hold.<br/><br/>Let's start from Users. We need to represent this users of course, with the username, userid, password, followers and following users, and so on. The first question is, what should identify an user inside our system? The username can be a good idea since it is unique, but it is also too big, and we want to stay low on memory. So like if our DB was a relational one we can associate an unique ID to every user. Every other reference to this user will be done by id. That's very simple to do, because we have our atomic INCR operation! When we create a new user we can do something like this, assuming the user is callled &quot;antirez&quot;:<br/><br/><pre class="codeblock python python python python python python python python python python python python" name="code">

97 </pre>

98 <h2><a name="Authentication">Authentication</a></h2>

99 Ok we have more or less everything about the user, but authentication. We'll handle authentication in a simple but robust way: we don't want to use PHP sessions or other things like this, our system must be ready in order to be distributed among different servers, so we'll take the whole state in our Redis database. So all we need is a random string to set as the cookie of an authenticated user, and a key that will tell us what is the user ID of the client holding such a random string. We need two keys in order to make this thing working in a robust way:<br/><br/><pre class="codeblock python python python python python python python python python python python python python python python python" name="code">

100 SET uid:1000:auth fea5e81ac8ca77622bed1c2132a021f9

101 SET auth:fea5e81ac8ca77622bed1c2132a021f9 1000

152 return true;

153 }

154 </pre><code name="code" class="python">loadUserInfo</code> as separated function is an overkill for our application, but it's a good template for a complex application. The only thing it's missing from all the authentication is the logout. What we do on logout? That's simple, we'll just change the random string in uid:1000:auth, remove the old auth:<code name="code" class="python">&lt;oldauthstring&gt;</code> and add a new auth:<code name="code" class="python">&lt;newauthstring&gt;</code>.<br/><br/><b>Important:</b> the logout procedure explains why we don't just authenticate the user after the lookup of auth:<code name="code" class="python">&lt;randomstring&gt;</code>, but double check it against uid:1000:auth. The true authentication string is the latter, the auth:<code name="code" class="python">&lt;randomstring&gt;</code> is just an authentication key that may even be volatile, or if there are bugs in the program or a script gets interrupted we may even end with multiple auth:<code name="code" class="python">&lt;something&gt;</code> keys pointing to the same user id. The logout code is the following (logout.php):<br/><br/><pre class="codeblock python python python python python python python python python python python python python python python python python python python" name="code">

155 include(&quot;retwis.php&quot;);