code stringlengths 3 1.05M | repo_name stringlengths 4 116 | path stringlengths 4 991 | language stringclasses 9 values | license stringclasses 15 values | size int32 3 1.05M |
|---|---|---|---|---|---|
// Copyright (c) 2012-2013 The Bitcoin Core developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "key.h"
#include "base58.h"
#include "script/script.h"
#include "uint256.h"
#include "util.h"
#include "utilstrencodings.h"
#include <string>
#include <vector>
#include <boost/test/unit_test.hpp>
using namespace std;
<<<<<<< HEAD
static const string strSecret1 ("6uu5bsZLA2Lm6yCxgwxDxHyZmhYeqBMLQT83Fyq738YhYucQPQf");
static const string strSecret2 ("6vZDRwYgTNidWzmKs9x8QzQGeWCqbdUtNRpEKZMaP67ZSn8XMjb");
static const string strSecret1C ("T6UsJv9hYpvDfM5noKYkB3vfeHxhyegkeWJ4y7qKeQJuyXMK11XX");
static const string strSecret2C ("T9PBs5kq9QrkBPxeGNWKitMi4XuFVr25jaXTnuopLVZxCUAJbixA");
static const CBitcoinAddress addr1 ("LWaFezDtucfCA4xcVEfs3R3xfgGWjSwcZr");
static const CBitcoinAddress addr2 ("LXwHM6mRd432EzLJYwuKQMPhTzrgr7ur9K");
static const CBitcoinAddress addr1C("LZWK8h7C166niP6GmpUmiGrvn4oxPqQgFV");
static const CBitcoinAddress addr2C("Lgb6tdqmdW3n5E12johSuEAqRMt4kAr7yu");
static const string strAddressBad("LRjyUS2uuieEPkhZNdQz8hE5YycxVEqSXA");
=======
static const string strSecret1 ("6uGFQ4DSW7zh1viHZi6iiVT17CncvoaV4MHvGvJKPDaLCdymj87");
static const string strSecret2 ("6vVo7sPkeLTwVdAntrv4Gbnsyr75H8ChD3P5iyHziwaqe8mCYR5");
static const string strSecret1C ("T3gJYmBuZXsdd65E7NQF88ZmUP2MaUanqnZg9GFS94W7kND4Ebjq");
static const string strSecret2C ("T986ZKRRdnuuXLeDZuKBRrZW1ujotAncU9WTrFU1n7vMgRW75ZtF");
static const CBitcoinAddress addr1 ("LiUo6Zn39joYJBzPUhssbDwAywhjFcoHE3");
static const CBitcoinAddress addr2 ("LZJvLSP5SGKcFS13MHgdrVhpFUbEMB5XVC");
static const CBitcoinAddress addr1C("Lh2G82Bi33RNuzz4UfSMZbh54jnWHVnmw8");
static const CBitcoinAddress addr2C("LWegHWHB5rmaF5rgWYt1YN3StapRdnGJfU");
static const string strAddressBad("Lbi6bpMhSwp2CXkivEeUK9wzyQEFzHDfSr");
>>>>>>> d1691e599121d643db2c1f2b5f5529eb64f2a771
#ifdef KEY_TESTS_DUMPINFO
void dumpKeyInfo(uint256 privkey)
{
CKey key;
key.resize(32);
memcpy(&secret[0], &privkey, 32);
vector<unsigned char> sec;
sec.resize(32);
memcpy(&sec[0], &secret[0], 32);
printf(" * secret (hex): %s\n", HexStr(sec).c_str());
for (int nCompressed=0; nCompressed<2; nCompressed++)
{
bool fCompressed = nCompressed == 1;
printf(" * %s:\n", fCompressed ? "compressed" : "uncompressed");
CBitcoinSecret bsecret;
bsecret.SetSecret(secret, fCompressed);
printf(" * secret (base58): %s\n", bsecret.ToString().c_str());
CKey key;
key.SetSecret(secret, fCompressed);
vector<unsigned char> vchPubKey = key.GetPubKey();
printf(" * pubkey (hex): %s\n", HexStr(vchPubKey).c_str());
printf(" * address (base58): %s\n", CBitcoinAddress(vchPubKey).ToString().c_str());
}
}
#endif
BOOST_AUTO_TEST_SUITE(key_tests)
BOOST_AUTO_TEST_CASE(key_test1)
{
CBitcoinSecret bsecret1, bsecret2, bsecret1C, bsecret2C, baddress1;
BOOST_CHECK( bsecret1.SetString (strSecret1));
BOOST_CHECK( bsecret2.SetString (strSecret2));
BOOST_CHECK( bsecret1C.SetString(strSecret1C));
BOOST_CHECK( bsecret2C.SetString(strSecret2C));
BOOST_CHECK(!baddress1.SetString(strAddressBad));
CKey key1 = bsecret1.GetKey();
BOOST_CHECK(key1.IsCompressed() == false);
CKey key2 = bsecret2.GetKey();
BOOST_CHECK(key2.IsCompressed() == false);
CKey key1C = bsecret1C.GetKey();
BOOST_CHECK(key1C.IsCompressed() == true);
CKey key2C = bsecret2C.GetKey();
<<<<<<< HEAD
BOOST_CHECK(key1C.IsCompressed() == true);
=======
BOOST_CHECK(key2C.IsCompressed() == true);
>>>>>>> d1691e599121d643db2c1f2b5f5529eb64f2a771
CPubKey pubkey1 = key1. GetPubKey();
CPubKey pubkey2 = key2. GetPubKey();
CPubKey pubkey1C = key1C.GetPubKey();
CPubKey pubkey2C = key2C.GetPubKey();
<<<<<<< HEAD
=======
BOOST_CHECK(key1.VerifyPubKey(pubkey1));
BOOST_CHECK(!key1.VerifyPubKey(pubkey1C));
BOOST_CHECK(!key1.VerifyPubKey(pubkey2));
BOOST_CHECK(!key1.VerifyPubKey(pubkey2C));
BOOST_CHECK(!key1C.VerifyPubKey(pubkey1));
BOOST_CHECK(key1C.VerifyPubKey(pubkey1C));
BOOST_CHECK(!key1C.VerifyPubKey(pubkey2));
BOOST_CHECK(!key1C.VerifyPubKey(pubkey2C));
BOOST_CHECK(!key2.VerifyPubKey(pubkey1));
BOOST_CHECK(!key2.VerifyPubKey(pubkey1C));
BOOST_CHECK(key2.VerifyPubKey(pubkey2));
BOOST_CHECK(!key2.VerifyPubKey(pubkey2C));
BOOST_CHECK(!key2C.VerifyPubKey(pubkey1));
BOOST_CHECK(!key2C.VerifyPubKey(pubkey1C));
BOOST_CHECK(!key2C.VerifyPubKey(pubkey2));
BOOST_CHECK(key2C.VerifyPubKey(pubkey2C));
>>>>>>> d1691e599121d643db2c1f2b5f5529eb64f2a771
BOOST_CHECK(addr1.Get() == CTxDestination(pubkey1.GetID()));
BOOST_CHECK(addr2.Get() == CTxDestination(pubkey2.GetID()));
BOOST_CHECK(addr1C.Get() == CTxDestination(pubkey1C.GetID()));
BOOST_CHECK(addr2C.Get() == CTxDestination(pubkey2C.GetID()));
for (int n=0; n<16; n++)
{
string strMsg = strprintf("Very secret message %i: 11", n);
uint256 hashMsg = Hash(strMsg.begin(), strMsg.end());
// normal signatures
vector<unsigned char> sign1, sign2, sign1C, sign2C;
BOOST_CHECK(key1.Sign (hashMsg, sign1));
BOOST_CHECK(key2.Sign (hashMsg, sign2));
BOOST_CHECK(key1C.Sign(hashMsg, sign1C));
BOOST_CHECK(key2C.Sign(hashMsg, sign2C));
BOOST_CHECK( pubkey1.Verify(hashMsg, sign1));
BOOST_CHECK(!pubkey1.Verify(hashMsg, sign2));
BOOST_CHECK( pubkey1.Verify(hashMsg, sign1C));
BOOST_CHECK(!pubkey1.Verify(hashMsg, sign2C));
BOOST_CHECK(!pubkey2.Verify(hashMsg, sign1));
BOOST_CHECK( pubkey2.Verify(hashMsg, sign2));
BOOST_CHECK(!pubkey2.Verify(hashMsg, sign1C));
BOOST_CHECK( pubkey2.Verify(hashMsg, sign2C));
BOOST_CHECK( pubkey1C.Verify(hashMsg, sign1));
BOOST_CHECK(!pubkey1C.Verify(hashMsg, sign2));
BOOST_CHECK( pubkey1C.Verify(hashMsg, sign1C));
BOOST_CHECK(!pubkey1C.Verify(hashMsg, sign2C));
BOOST_CHECK(!pubkey2C.Verify(hashMsg, sign1));
BOOST_CHECK( pubkey2C.Verify(hashMsg, sign2));
BOOST_CHECK(!pubkey2C.Verify(hashMsg, sign1C));
BOOST_CHECK( pubkey2C.Verify(hashMsg, sign2C));
// compact signatures (with key recovery)
vector<unsigned char> csign1, csign2, csign1C, csign2C;
BOOST_CHECK(key1.SignCompact (hashMsg, csign1));
BOOST_CHECK(key2.SignCompact (hashMsg, csign2));
BOOST_CHECK(key1C.SignCompact(hashMsg, csign1C));
BOOST_CHECK(key2C.SignCompact(hashMsg, csign2C));
CPubKey rkey1, rkey2, rkey1C, rkey2C;
<<<<<<< HEAD
BOOST_CHECK(rkey1.RecoverCompact (hashMsg, csign1));
BOOST_CHECK(rkey2.RecoverCompact (hashMsg, csign2));
BOOST_CHECK(rkey1C.RecoverCompact(hashMsg, csign1C));
BOOST_CHECK(rkey2C.RecoverCompact(hashMsg, csign2C));
=======
BOOST_CHECK(rkey1.RecoverCompact (hashMsg, csign1));
BOOST_CHECK(rkey2.RecoverCompact (hashMsg, csign2));
BOOST_CHECK(rkey1C.RecoverCompact(hashMsg, csign1C));
BOOST_CHECK(rkey2C.RecoverCompact(hashMsg, csign2C));
>>>>>>> d1691e599121d643db2c1f2b5f5529eb64f2a771
BOOST_CHECK(rkey1 == pubkey1);
BOOST_CHECK(rkey2 == pubkey2);
BOOST_CHECK(rkey1C == pubkey1C);
BOOST_CHECK(rkey2C == pubkey2C);
}
// test deterministic signing
std::vector<unsigned char> detsig, detsigc;
string strMsg = "Very deterministic message";
uint256 hashMsg = Hash(strMsg.begin(), strMsg.end());
BOOST_CHECK(key1.Sign(hashMsg, detsig));
BOOST_CHECK(key1C.Sign(hashMsg, detsigc));
BOOST_CHECK(detsig == detsigc);
BOOST_CHECK(detsig == ParseHex("304402205dbbddda71772d95ce91cd2d14b592cfbc1dd0aabd6a394b6c2d377bbe59d31d022014ddda21494a4e221f0824f0b8b924c43fa43c0ad57dccdaa11f81a6bd4582f6"));
BOOST_CHECK(key2.Sign(hashMsg, detsig));
BOOST_CHECK(key2C.Sign(hashMsg, detsigc));
BOOST_CHECK(detsig == detsigc);
BOOST_CHECK(detsig == ParseHex("3044022052d8a32079c11e79db95af63bb9600c5b04f21a9ca33dc129c2bfa8ac9dc1cd5022061d8ae5e0f6c1a16bde3719c64c2fd70e404b6428ab9a69566962e8771b5944d"));
BOOST_CHECK(key1.SignCompact(hashMsg, detsig));
BOOST_CHECK(key1C.SignCompact(hashMsg, detsigc));
BOOST_CHECK(detsig == ParseHex("1c5dbbddda71772d95ce91cd2d14b592cfbc1dd0aabd6a394b6c2d377bbe59d31d14ddda21494a4e221f0824f0b8b924c43fa43c0ad57dccdaa11f81a6bd4582f6"));
BOOST_CHECK(detsigc == ParseHex("205dbbddda71772d95ce91cd2d14b592cfbc1dd0aabd6a394b6c2d377bbe59d31d14ddda21494a4e221f0824f0b8b924c43fa43c0ad57dccdaa11f81a6bd4582f6"));
BOOST_CHECK(key2.SignCompact(hashMsg, detsig));
BOOST_CHECK(key2C.SignCompact(hashMsg, detsigc));
BOOST_CHECK(detsig == ParseHex("1c52d8a32079c11e79db95af63bb9600c5b04f21a9ca33dc129c2bfa8ac9dc1cd561d8ae5e0f6c1a16bde3719c64c2fd70e404b6428ab9a69566962e8771b5944d"));
BOOST_CHECK(detsigc == ParseHex("2052d8a32079c11e79db95af63bb9600c5b04f21a9ca33dc129c2bfa8ac9dc1cd561d8ae5e0f6c1a16bde3719c64c2fd70e404b6428ab9a69566962e8771b5944d"));
}
BOOST_AUTO_TEST_SUITE_END()
| koharjidan/litecoin | src/test/key_tests.cpp | C++ | mit | 9,233 |
package platzi.app;
import java.util.Optional;
import org.springframework.data.jpa.repository.JpaRepository;
public interface InstructorRepository extends JpaRepository<Instructor, Long> {
Optional<Instructor> findByUsername(String username);
}
| erikmr/Java-Api-Rest | src/main/java/platzi/app/InstructorRepository.java | Java | mit | 250 |
import os
ADMINS = (
# ('Eduardo Lopez', 'eduardo.biagi@gmail.com'),
)
MANAGERS = ADMINS
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3', # Add 'postgresql_psycopg2', 'postgresql', 'mysql', 'sqlite3' or 'oracle'.
'NAME': os.path.join(os.path.dirname(__file__), 'highways.db'), # Or path to database file if using sqlite3.
'USER': '', # Not used with sqlite3.
'PASSWORD': '', # Not used with sqlite3.
'HOST': '', # Set to empty string for localhost. Not used with sqlite3.
'PORT': '', # Set to empty string for default. Not used with sqlite3.
}
}
# Local time zone for this installation. Choices can be found here:
# http://en.wikipedia.org/wiki/List_of_tz_zones_by_name
# although not all choices may be available on all operating systems.
# On Unix systems, a value of None will cause Django to use the same
# timezone as the operating system.
# If running in a Windows environment this must be set to the same as your
# system time zone.
TIME_ZONE = 'America/Mexico_City'
# Language code for this installation. All choices can be found here:
# http://www.i18nguy.com/unicode/language-identifiers.html
LANGUAGE_CODE = 'es-MX'
SITE_ID = 1
# If you set this to False, Django will make some optimizations so as not
# to load the internationalization machinery.
USE_I18N = True
# If you set this to False, Django will not format dates, numbers and
# calendars according to the current locale
USE_L10N = True
# Absolute path to the directory that holds media.
# Example: "/home/media/media.lawrence.com/"
MEDIA_ROOT = os.path.join(os.path.dirname(__file__), 'media')
# URL that handles the media served from MEDIA_ROOT. Make sure to use a
# trailing slash if there is a path component (optional in other cases).
# Examples: "http://media.lawrence.com", "http://example.com/media/"
MEDIA_URL = '/static/'
# URL prefix for admin media -- CSS, JavaScript and images. Make sure to use a
# trailing slash.
# Examples: "http://foo.com/media/", "/media/".
ADMIN_MEDIA_PREFIX = '/media/'
# Make this unique, and don't share it with anybody.
SECRET_KEY = 'bre7b$*6!iagzqyi1%q@%_ofbb)e!rawcnm9apx^%kf@b%)le!'
MIDDLEWARE_CLASSES = (
'django.middleware.common.CommonMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
)
ROOT_URLCONF = 'project.urls'
INSTALLED_APPS = (
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.sites',
'django.contrib.messages',
'django.contrib.admin',
'django.contrib.admindocs',
'carreteras',
)
# List of callables that know how to import templates from various sources.
TEMPLATE_LOADERS = (
'django.template.loaders.filesystem.Loader',
'django.template.loaders.app_directories.Loader',
# 'django.template.loaders.eggs.Loader',
)
TEMPLATE_DIRS = (
os.path.join(os.path.dirname(__file__), "templates"),
)
| tapichu/highway-maps | project/settings.py | Python | mit | 3,183 |
<div class="container">
<div class="card-panel darken-2 z-depth-2">
<h5 class="red-text"><i class="fa fa-search-plus"></i> CONSULTA</h5>
<br>
<form action="<?php echo baseUrl ?>home/consultas/index" method="POST" class="col s12">
<?php echo Token::field() ?>
<div class="row">
<div class="input-field col s6 m4">
<i class="fa fa-user red-text prefix"></i>
<input name="cedula" id="icon_telephone" type="tel" class="validate">
<label for="icon_telephone">CEDULA</label>
</div>
<div class="input-field col s6 m3">
<button class="btn waves-effect waves-light red" type="submit"><i class="fa fa-search"></i></button>
</div>
</div>
</form>
</div>
<?php if (isset($profesionales) and $profesionales): ?>
<div class="col s12 m12 darken-2 z-depth-2 animated bounceInDown">
<div class="card horizontal">
<div class="card-stacked">
<div class="card-content">
<h5 class="text-center red-text"><i class="fa fa-graduation-cap red-text" aria-hidden="true"></i>
PROFESIONAL</h5>
<div class="col-lg-6 animated fadeIn">
<table class="">
<tbody>
<tr class="grey-text text-darken-2">
<td width="40%" ><b><i class="fa fa-id-card-o"></i> NOMBRE Y APELLIDO:</b></td>
<td><?php echo $profesionales->nombres ?> <?php echo $profesionales->apellidos ?></td>
</tr>
<tr class="grey-text text-darken-2">
<td width="40%" ><b><i class="fa fa-graduation-cap"></i> PROFESIÓN:</b></td>
<td><?php echo $profesionales->profesion
?></td>
</tr>
<tr class="grey-text text-darken-2">
<td width="40%" ><b><i class="fa fa-briefcase"></i> CARGO:</b></td>
<td><?php echo $profesionales->cargo
?></td>
</tr>
</tbody>
</table>
</div>
</div>
</div>
</div>
</div>
<?php else: ?>
<?php endif ?>
<?php if (isset($cedula) and $cedula): ?>
<div class="col s12 m12 darken-2 z-depth-2 animated bounceInUp">
<div class="card horizontal">
<div class="card-stacked">
<div class="card-content">
<h5 class="text-center red-text"><i class="fa fa-file-text-o red-text" aria-hidden="true"></i>
RESULTADOS</h5>
<div class="col-lg-6 animated fadeIn">
<table class="">
<tbody>
<tr class="grey-text text-darken-2">
<td width="40%" ><b><i class="fa fa-pencil"></i> FIRMO:</b></td>
<?php if ($firmo_contra): ?>
<td>Si</td>
<?php else: ?>
<td>No</td>
<?php endif ?>
</tr>
<tr class="grey-text text-darken-2">
<td width="40%" ><b><i class="fa fa-home"></i> HOGARES ASIGNADOS:</b></td>
<?php if ($hogares_asignados): ?>
<td>Si</td>
<?php else: ?>
<td>No</td>
<?php endif ?>
</tr>
<tr class="grey-text text-darken-2">
<td width="40%" ><b><i class="fa fa-home"></i> HOGARES POR ASIGNAR:</b></td>
<?php if ($hogares_por_asignar): ?>
<td>Si</td>
<?php else: ?>
<td>No</td>
<?php endif ?>
</tr>
<tr class="grey-text text-darken-2">
<td width="40%" ><b><i class="fa fa-credit-card"></i> POR PENSIONAR:</b></td>
<?php if ($por_pensionar): ?>
<td>Si</td>
<?php else: ?>
<td>No</td>
<?php endif ?>
</tr>
<tr class="grey-text text-darken-2">
<td width="40%" ><b><i class="fa fa-credit-card"></i> PENSIONADOS:</b></td>
<?php if ($ya_pensionados): ?>
<td>Si</td>
<?php else: ?>
<td>No</td>
<?php endif ?>
</tr>
</tbody>
</table>
</div>
</div>
</div>
</div>
</div>
<?php else: ?>
<?php endif ?>
<?php if (isset($responsable_municipal) and $responsable_municipal): ?>
<div class="col s12 m12 darken-2 z-depth-2 animated bounceInUp">
<div class="card horizontal">
<div class="card-stacked">
<div class="card-content">
<h5 class="text-center red-text"><i class="fa fa-file-text-o red-text" aria-hidden="true"></i>
RESPONSABLE MUNICIPAL</h5>
<div class="col-lg-6 animated fadeIn">
<table class="">
<tbody>
<tr class="grey-text text-darken-2">
<td width="40%" ><b><i class="fa fa-pencil"></i> FIRMO:</b></td>
<?php if ($firmo_contra): ?>
<td>Si</td>
<?php else: ?>
<td>No</td>
<?php endif ?>
</tr>
<tr class="grey-text text-darken-2">
<td width="40%" ><b><i class="fa fa-home"></i> HOGARES ASIGNADOS:</b></td>
<?php if ($hogares_asignados): ?>
<td>Si</td>
<?php else: ?>
<td>No</td>
<?php endif ?>
</tr>
<tr class="grey-text text-darken-2">
<td width="40%" ><b><i class="fa fa-home"></i> HOGARES POR ASIGNAR:</b></td>
<?php if ($hogares_por_asignar): ?>
<td>Si</td>
<?php else: ?>
<td>No</td>
<?php endif ?>
</tr>
<tr class="grey-text text-darken-2">
<td width="40%" ><b><i class="fa fa-credit-card"></i> POR PENSIONAR:</b></td>
<?php if ($por_pensionar): ?>
<td>Si</td>
<?php else: ?>
<td>No</td>
<?php endif ?>
</tr>
<tr class="grey-text text-darken-2">
<td width="40%" ><b><i class="fa fa-credit-card"></i> PENSIONADOS:</b></td>
<?php if ($ya_pensionados): ?>
<td>Si</td>
<?php else: ?>
<td>No</td>
<?php endif ?>
</tr>
</tbody>
</table>
</div>
</div>
</div>
</div>
</div>
<?php else: ?>
<?php endif ?>
| dexternidia/redcomand | app/home/views/consultas/index.php | PHP | mit | 6,788 |
package com.qiniu.android.dns.http;
import com.qiniu.android.dns.Domain;
import com.qiniu.android.dns.IResolver;
import com.qiniu.android.dns.NetworkInfo;
import com.qiniu.android.dns.Record;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
/**
* Created by bailong on 15/6/12.
*/
public final class DnspodFree implements IResolver {
@Override
public Record[] query(Domain domain, NetworkInfo info) throws IOException {
URL url = new URL("http://119.29.29.29/d?ttl=1&dn=" + domain.domain);
HttpURLConnection httpConn = (HttpURLConnection) url.openConnection();
int responseCode = httpConn.getResponseCode();
if (responseCode != HttpURLConnection.HTTP_OK) {
return null;
}
int length = httpConn.getContentLength();
if (length > 1024 || length == 0) {
return null;
}
InputStream is = httpConn.getInputStream();
byte[] data = new byte[length];
int read = is.read(data);
is.close();
String response = new String(data, 0, read);
String[] r1 = response.split(",");
if (r1.length != 2) {
return null;
}
int ttl;
try {
ttl = Integer.parseInt(r1[1]);
} catch (Exception e) {
return null;
}
String[] ips = r1[0].split(";");
if (ips.length == 0) {
return null;
}
Record[] records = new Record[ips.length];
long time = System.currentTimeMillis() / 1000;
for (int i = 0; i < ips.length; i++) {
records[i] = new Record(ips[i], Record.TYPE_A, ttl, time);
}
return records;
}
}
| longbai/happy-dns-android | library/src/main/java/com/qiniu/android/dns/http/DnspodFree.java | Java | mit | 1,751 |
package com.wabbit.libraries;
import android.content.Context;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.util.UUID;
public class Installation {
private static String sID = null;
private static final String INSTALLATION = "INSTALLATION";
public synchronized static String id(Context context) {
if (sID == null) {
File installation = new File(context.getFilesDir(), INSTALLATION);
try {
if (!installation.exists())
writeInstallationFile(installation);
sID = readInstallationFile(installation);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
return sID;
}
private static String readInstallationFile(File installation) throws IOException {
RandomAccessFile f = new RandomAccessFile(installation, "r");
byte[] bytes = new byte[(int) f.length()];
f.readFully(bytes);
f.close();
return new String(bytes);
}
private static void writeInstallationFile(File installation) throws IOException {
FileOutputStream out = new FileOutputStream(installation);
String id = UUID.randomUUID().toString();
out.write(id.getBytes());
out.close();
}
} | DobrinAlexandru/Wabbit-Messenger---android-client | Wabbit/src/com/wabbit/libraries/Installation.java | Java | mit | 1,373 |
<?php get_header(); ?>
<main role="main" class="main-content">
<!-- section -->
<section>
<?php if (have_posts()): while (have_posts()) : the_post(); ?>
<h1><?php the_title();?></h1>
<?php get_template_part( 'template-parts/content', 'single' );?>
<span><?php previous_post_link('%link', '« %title', TRUE); ?></span>
<span><?php next_post_link('%link', '%title »', TRUE); ?></span>
<?php
endwhile;
endif;?>
</section>
<!-- /section -->
</main>
<?php get_sidebar(); ?>
<?php get_footer(); ?>
| loschke/sevenx-wordpress-blank | single.php | PHP | mit | 626 |
//-----------------------------------------------
//
// This file is part of the Siv3D Engine.
//
// Copyright (c) 2008-2022 Ryo Suzuki
// Copyright (c) 2016-2022 OpenSiv3D Project
//
// Licensed under the MIT License.
//
//-----------------------------------------------
# pragma once
# include "Common.hpp"
# include "Asset.hpp"
# include "ShaderCommon.hpp"
# include "VertexShader.hpp"
# include "AsyncTask.hpp"
namespace s3d
{
struct VertexShaderAssetData : IAsset
{
FilePath path;
String entryPoint;
Array<ConstantBufferBinding> bindings;
VertexShader vs;
std::function<bool(VertexShaderAssetData&, const String&)> onLoad = DefaultLoad;
std::function<void(VertexShaderAssetData&)> onRelease = DefaultRelease;
SIV3D_NODISCARD_CXX20
VertexShaderAssetData();
SIV3D_NODISCARD_CXX20
VertexShaderAssetData(FilePathView path, StringView entryPoint, const Array<ConstantBufferBinding>& bindings, const Array<AssetTag>& tags = {});
SIV3D_NODISCARD_CXX20
explicit VertexShaderAssetData(const HLSL& hlsl, const Array<AssetTag>& tags = {});
SIV3D_NODISCARD_CXX20
explicit VertexShaderAssetData(const GLSL& glsl, const Array<AssetTag>& tags = {});
SIV3D_NODISCARD_CXX20
explicit VertexShaderAssetData(const MSL& msl, const Array<AssetTag>& tags = {});
SIV3D_NODISCARD_CXX20
explicit VertexShaderAssetData(const ESSL& essl, const Array<AssetTag>& tags = {});
SIV3D_NODISCARD_CXX20
explicit VertexShaderAssetData(const WGSL& wgsl, const Array<AssetTag>& tags = {});
SIV3D_NODISCARD_CXX20
explicit VertexShaderAssetData(const ShaderGroup& shaderGroup, const Array<AssetTag>& tags = {});
bool load(const String& hint) override;
void loadAsync(const String& hint) override;
void wait() override;
void release() override;
static bool DefaultLoad(VertexShaderAssetData& asset, const String& hint);
static void DefaultRelease(VertexShaderAssetData& asset);
private:
AsyncTask<void> m_task;
};
}
| Siv3D/OpenSiv3D | Siv3D/include/Siv3D/VertexShaderAssetData.hpp | C++ | mit | 1,971 |
// DATA_TEMPLATE: empty_table
oTest.fnStart("5396 - fnUpdate with 2D arrays for a single row");
$(document).ready(function () {
$('#example thead tr').append('<th>6</th>');
$('#example thead tr').append('<th>7</th>');
$('#example thead tr').append('<th>8</th>');
$('#example thead tr').append('<th>9</th>');
$('#example thead tr').append('<th>10</th>');
var aDataSet = [
[
"1",
"홍길동",
"1154315",
"etc1",
[
[ "test1@daum.net", "2011-03-04" ],
[ "test1@naver.com", "2009-07-06" ],
[ "test4@naver.com", ",hide" ],
[ "test5?@naver.com", "" ]
],
"2011-03-04",
"show"
],
[
"2",
"홍길순",
"2154315",
"etc2",
[
[ "test2@daum.net", "2009-09-26" ],
[ "test2@naver.com", "2009-05-21,hide" ],
[ "lsb@naver.com", "2010-03-05" ],
[ "lsb3@naver.com", ",hide" ],
[ "sooboklee9@daum.net", "2010-03-05" ]
],
"2010-03-05",
"show"
]
]
var oTable = $('#example').dataTable({
"aaData": aDataSet,
"aoColumns": [
{ "mData": "0"},
{ "mData": "1"},
{ "mData": "2"},
{ "mData": "3"},
{ "mData": "4.0.0"},
{ "mData": "4.0.1"},
{ "mData": "4.1.0"},
{ "mData": "4.1.1"},
{ "mData": "5"},
{ "mData": "6"}
]
});
oTest.fnTest(
"Initialisation",
null,
function () {
return $('#example tbody tr:eq(0) td:eq(0)').html() == '1';
}
);
oTest.fnTest(
"Update row",
function () {
$('#example').dataTable().fnUpdate([
"0",
"홍길순",
"2154315",
"etc2",
[
[ "test2@daum.net", "2009-09-26" ],
[ "test2@naver.com", "2009-05-21,hide" ],
[ "lsb@naver.com", "2010-03-05" ],
[ "lsb3@naver.com", ",hide" ],
[ "sooboklee9@daum.net", "2010-03-05" ]
],
"2010-03-05",
"show"
], 1);
},
function () {
return $('#example tbody tr:eq(0) td:eq(0)').html() == '0';
}
);
oTest.fnTest(
"Original row preserved",
null,
function () {
return $('#example tbody tr:eq(1) td:eq(0)').html() == '1';
}
);
oTest.fnComplete();
}); | hedi103/projet-decision-commerciale | src/Project/Bundle/AceThemeBundle/Resources/public/css/themes/default/assets/advanced-datatable/media/unit_testing/tests_onhold/1_dom/5396-fnUpdate-arrays-mData.js | JavaScript | mit | 2,746 |
package BubbleSort2D;
public class person {
String name;
int age;
boolean sortme = false;
public person(String n, int a) {
name = n;
age = a;
}
public String toString(){
return name + " " + Integer.toString(age);
}
} | mrswoop/BubbleSort2DArrayRange | BubbleSort2D/src/BubbleSort2D/person.java | Java | mit | 253 |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using ShoNS.Array;
using Rhino.Geometry;
namespace mikity.ghComponents
{
public partial class Mothra2 : Grasshopper.Kernel.GH_Component
{
private DoubleArray[] baseFunction;
private DoubleArray[] coeff;
Func<double, double, double>[] Function;
Action<double, double, double[]>[] dFunction;
Action<double, double, double[,]>[] ddFunction;
private static double epsilon = 0.2;
Func<double, double, double, double, double> F = (x1, x2, y1, y2) => { return Math.Sqrt(1 + epsilon * (((x1 - x2) * (x1 - x2)) + ((y1 - y2) * (y1 - y2)))); };
Action<double, double, double, double, double[]> dF = (x1, x2, y1, y2, grad) =>
{
grad[0] = epsilon * (x1 - x2) / Math.Sqrt(1 + epsilon * (((x1 - x2) * (x1 - x2)) + ((y1 - y2) * (y1 - y2))));
grad[1] = epsilon * (y1 - y2) / Math.Sqrt(1 + epsilon * (((x1 - x2) * (x1 - x2)) + ((y1 - y2) * (y1 - y2))));
};
Action<double, double, double, double, double[,]> ddF = (x1, x2, y1, y2, grad) =>
{
grad[0, 0] = epsilon / Math.Sqrt(1 + epsilon * (((x1 - x2) * (x1 - x2)) + ((y1 - y2) * (y1 - y2)))) - epsilon * epsilon * (x1 - x2) * (x1 - x2) * Math.Pow(1 + epsilon * (((x1 - x2) * (x1 - x2)) + ((y1 - y2) * (y1 - y2))), -3 / 2d);
grad[0, 1] = -epsilon * epsilon * (x1 - x2) * (y1 - y2) * Math.Pow(1 + epsilon * (((x1 - x2) * (x1 - x2)) + ((y1 - y2) * (y1 - y2))), -3 / 2d);
grad[1, 0] = -epsilon * epsilon * (x1 - x2) * (y1 - y2) * Math.Pow(1 + epsilon * (((x1 - x2) * (x1 - x2)) + ((y1 - y2) * (y1 - y2))), -3 / 2d);
grad[1, 1] = epsilon / Math.Sqrt(1 + epsilon * (((x1 - x2) * (x1 - x2)) + ((y1 - y2) * (y1 - y2)))) - epsilon * epsilon * (y1 - y2) * (y1 - y2) * Math.Pow(1 + epsilon * (((x1 - x2) * (x1 - x2)) + ((y1 - y2) * (y1 - y2))), -3 / 2d);
};
public void computeBaseFunction(int lastComputed)
{
if (lastComputed >= nOutterSegments)
{
computeBaseFunction2(lastComputed);
}
else
{
computeBaseFunction1(lastComputed);
}
}
private void computeBaseFunctionCommon(int lastComputed,DoubleArray origX)
{
var M = (shiftArray.T.Multiply(Laplacian) as SparseDoubleArray) * shiftArray as SparseDoubleArray;
int T1 = n - fixedPoints.Count;
int T2 = n;
var slice1 = new SparseDoubleArray(T1, T2);
var slice2 = new SparseDoubleArray(T2, T2 - T1);
for (int i = 0; i < T1; i++)
{
slice1[i, i] = 1;
}
for (int i = 0; i < T2 - T1; i++)
{
slice2[i + T1, i] = 1;
}
var DIB = (slice1.Multiply(M) as SparseDoubleArray).Multiply(slice2) as SparseDoubleArray;
var DII = (slice1.Multiply(M) as SparseDoubleArray).Multiply(slice1.T) as SparseDoubleArray;
var solver = new SparseLU(DII);
origX = shiftArray.T * origX;
var fixX = origX.GetSlice(T1, T2 - 1, 0, 0);
var B = -DIB * fixX;
var dx = solver.Solve(B);
var ret = DoubleArray.Zeros(n, 1);
for (int i = 0; i < T1; i++)
{
ret[i, 0] = dx[i, 0];
}
for (int i = T1; i < T2; i++)
{
ret[i, 0] = fixX[i - T1, 0];
}
if (lastComputed < baseFunction.Length)
{
baseFunction[lastComputed] = shiftArray * ret;
}
//vertices...x,y
//baseFunction[]...z
var MM = DoubleArray.Zeros(n, n);
for (int i = 0; i < n; i++)
{
for (int j = 0; j < n; j++)
{
MM[i, j] = F(vertices[i].X, vertices[j].X, vertices[i].Y, vertices[j].Y);
}
}
var V = DoubleArray.Zeros(n, 1);
for (int i = 0; i < n; i++)
{
V[i, 0] = baseFunction[lastComputed][i, 0];
}
//var solver2 = new LU(MM);
var solver2 = new SVD(MM);
coeff[lastComputed] = solver2.Solve(V);
Function[lastComputed] = (x, y) =>
{
double val = 0;
for (int j = 0; j < n; j++)
{
val += coeff[lastComputed][j, 0] * F(x, vertices[j].X, y, vertices[j].Y);
}
return val;
};
dFunction[lastComputed] = (x, y, val) =>
{
val[0] = 0;
val[1] = 0;
double[] r = new double[2] { 0, 0 };
for (int j = 0; j < n; j++)
{
dF(x, vertices[j].X, y, vertices[j].Y, r);
val[0] += coeff[lastComputed][j, 0] * r[0];
val[1] += coeff[lastComputed][j, 0] * r[1];
}
};
ddFunction[lastComputed] = (x, y, val) =>
{
val[0, 0] = 0;
val[0, 1] = 0;
val[1, 0] = 0;
val[1, 1] = 0;
double[,] r = new double[2, 2] { {0, 0}, {0, 0} };
for (int j = 0; j < n; j++)
{
ddF(x, vertices[j].X, y, vertices[j].Y, r);
val[0, 0] += coeff[lastComputed][j, 0] * r[0, 0];
val[0, 1] += coeff[lastComputed][j, 0] * r[0, 1];
val[1, 0] += coeff[lastComputed][j, 0] * r[1, 0];
val[1, 1] += coeff[lastComputed][j, 0] * r[1, 1];
}
};
if (lastComputed == 0) resultToPreview(0);
}
private void computeBaseFunction2(int lastComputed)
{
DoubleArray origX = new DoubleArray(n, 1);
for (int i = 0; i < n; i++)
{
origX[i, 0] = 0;
}
var b = bbIn[lastComputed-nOutterSegments];
for (int i = 0; i < b.Count; i++)
{
origX[b[i].P0, 0] = 5d;
}
computeBaseFunctionCommon(lastComputed, origX);
}
private void computeBaseFunction1(int lastComputed)
{
DoubleArray origX = new DoubleArray(n, 1);
for (int i = 0; i < n; i++)
{
origX[i, 0] = 0;
}
var b = bbOut[lastComputed];
for (int i = 0; i < b.Count; i++)
{
double y = Math.Pow((i - ((double)b.Count / 2d)) / ((double)b.Count / 2d), 2) - 1d;
origX[b[i].P0, 0] = -3d * y;
if (i == b.Count - 1)
{
y = Math.Pow(((i + 1d) - ((double)b.Count / 2d)) / ((double)b.Count / 2d), 2) - 1d;
origX[b[i].P1, 0] = -3d * y;
}
}
computeBaseFunctionCommon(lastComputed, origX);
}
public void resultToPreview(int num)
{
result = new List<Rhino.Geometry.Line>();
if (baseFunction[num] == null) { result = null; return; }
var xx = baseFunction[num];
foreach (var edge in edges)
{
Rhino.Geometry.Point3d P = new Rhino.Geometry.Point3d(vertices[edge.P0].X, vertices[edge.P0].Y, xx[edge.P0]);
Rhino.Geometry.Point3d Q = new Rhino.Geometry.Point3d(vertices[edge.P1].X, vertices[edge.P1].Y, xx[edge.P1]);
result.Add(new Rhino.Geometry.Line(P, Q));
}
for (int i = 0; i < a.Count; i++)
{
Point3d P = new Point3d(a[i].X, a[i].Y, Function[num](a2[i].X, a2[i].Y));
a.RemoveAt(i);
a.Insert(i, P);
}
}
public SparseDoubleArray computeLaplacian(int[,] lines, int nP)
{
if (lines.GetLength(1) != 2) return null;
SparseDoubleArray C = new SparseDoubleArray(lines.GetLength(0), nP);
int m = lines.GetLength(0);
for (int i = 0; i < m; i++)
{
int P = lines[i, 0];
int Q = lines[i, 1];
C[i, P] = 1;
C[i, Q] = -1;
}
SparseDoubleArray D = (C.T * C) as SparseDoubleArray;
return D;
}
public SparseDoubleArray computeShiftArray(List<int> fixedPoints,int n)
{
int[] shift = new int[n];
int NN = fixedPoints.Count();
int DD = n - NN; //number of free nodes
for (int i = 0; i < n; i++)
{
shift[i] = -100;
}
for (int i = 0; i < NN; i++)
{
shift[fixedPoints[i]] = DD + i;
}
int S = 0;
for (int i = 0; i < n; i++)
{
if (shift[i] == -100)
{
shift[i] = S;
S++;
}
}
if (S != DD) AddRuntimeMessage(Grasshopper.Kernel.GH_RuntimeMessageLevel.Error, "contradiction!");
var shiftArray = new SparseDoubleArray(n, n);
for (int i = 0; i < n; i++)
{
shiftArray[i, shift[i]] = 1;
}
return shiftArray;
}
}
}
| mikity-mikity/Mothra2 | Mothra/Numerics.cs | C# | mit | 9,553 |
using System.ComponentModel.Composition.Hosting;
using System.Threading.Tasks;
using LiteGuard;
using Mileage.Server.Contracts.Commands;
using Mileage.Server.Contracts.Commands.Mileage;
using Mileage.Shared.Results;
using Raven.Client;
using Raven.Client.Indexes;
namespace Mileage.Server.Infrastructure.Commands.Mileage
{
public class ResetIndexesCommandHandler : ICommandHandler<ResetIndexesCommand, object>
{
#region Fields
private readonly IDocumentStore _documentStore;
#endregion
#region Constructors
/// <summary>
/// Initializes a new instance of the <see cref="ResetIndexesCommandHandler"/> class.
/// </summary>
/// <param name="documentStore">The document store.</param>
public ResetIndexesCommandHandler(IDocumentStore documentStore)
{
Guard.AgainstNullArgument("documentStore", documentStore);
this._documentStore = documentStore;
}
#endregion
#region Methods
/// <summary>
/// Executes the specified command.
/// </summary>
/// <param name="command">The command.</param>
/// <param name="scope">The scope.</param>
public Task<Result<object>> Execute(ResetIndexesCommand command, ICommandScope scope)
{
Guard.AgainstNullArgument("command", command);
Guard.AgainstNullArgument("scope", scope);
return Result.CreateAsync(async () =>
{
var compositionContainer = new CompositionContainer(new AssemblyCatalog(this.GetType().Assembly));
foreach (AbstractIndexCreationTask index in compositionContainer.GetExportedValues<AbstractIndexCreationTask>())
{
await this._documentStore.AsyncDatabaseCommands.ResetIndexAsync(index.IndexName);
}
return new object();
});
}
#endregion
}
} | haefele/Mileage | src/03 Server/Mileage.Server.Infrastructure/Commands/Mileage/ResetIndexesCommandHandler.cs | C# | mit | 1,966 |
/*
* jQuery Touch Optimized Sliders "R"Us
* HTML media
*
* Copyright (c) Fred Heusschen
* www.frebsite.nl
*/
!function(i){var n="tosrus",e="html";i[n].media[e]={filterAnchors:function(n){return"#"==n.slice(0,1)&&i(n).is("div")},initAnchors:function(e,t){i('<div class="'+i[n]._c("html")+'" />').append(i(t)).appendTo(e),e.removeClass(i[n]._c.loading).trigger(i[n]._e.loaded)},filterSlides:function(i){return i.is("div")},initSlides:function(){}}}(jQuery); | Jezfx/rocket-theme | site assets/plugins/smart-grid-gallery/includes/lightboxes/tosrus/js/media/jquery.tosrus.html.min.js | JavaScript | mit | 462 |
/**
* Knook-mailer
* https://github.com/knook/knook.git
* Auhtors: Alexandre Lagrange-Cetto, Olivier Graziano, Olivier Marin
* Created on 15/04/2016.
* version 0.1.0
*/
'use strict';
module.exports = {
Accounts: require('./src/Accounts'),
Email: require('./src/Email'),
Init: require('./src/Init'),
Prefs: require('./src/Prefs'),
Security: require('./src/Security')
}; | knook/knook-mailer | index.js | JavaScript | mit | 396 |
using System;
using System.Diagnostics;
using System.ServiceModel.Channels;
using System.ServiceModel.Dispatcher;
namespace SimpleNet.ServiceHost.Behaviors
{
public class ErrorHandler : IErrorHandler
{
// Provide a fault. The Message fault parameter can be replaced, or set to
// null to suppress reporting a fault.
public void ProvideFault(Exception error, MessageVersion version, ref Message fault)
{
Trace.TraceError("Exception: {0} - {1}", error.GetType().Name, error.Message);
}
// HandleError. Log an error, then allow the error to be handled as usual.
// Return true if the error is considered as already handled
public bool HandleError(Exception error)
{
Trace.TraceError("Exception: {0} - {1}", error.GetType().Name, error.Message);
foreach (var key in error.Data.Keys)
{
Trace.TraceError("Exception: {0} - {1}", key, error.Data[key]);
}
if (error.InnerException != null)
HandleError(error.InnerException);
return false;
}
}
}
| Hem/SimpleNet | SimpleNet.ServiceHost/Behaviors/ErrorHandler.cs | C# | mit | 1,174 |
namespace Enexure.MicroBus
{
public interface IQuery<in TQuery, out TResult> : IQuery, IMessage
where TQuery : IQuery<TQuery, TResult>
{
}
public interface IQuery
{
}
} | Lavinski/Enexure.MicroBus | src/Enexure.MicroBus.MessageContracts/IQuery.cs | C# | mit | 203 |
module.exports = {
KeyQ: {
printable: true,
keyCode: 81,
Default: 'ქ',
Shift: '',
CapsLock: 'Ⴕ',
Shift_CapsLock: '',
Alt: '',
Alt_Shift: ''
},
KeyW: {
printable: true,
keyCode: 87,
Default: 'წ',
Shift: 'ჭ',
CapsLock: 'Ⴜ',
Shift_CapsLock: 'Ⴝ',
Alt: '∑',
Alt_Shift: '„'
},
KeyE: {
printable: true,
keyCode: 69,
Default: 'ე',
Shift: '',
CapsLock: 'Ⴄ',
Shift_CapsLock: '',
Alt: '´',
Alt_Shift: '´'
},
KeyR: {
printable: true,
keyCode: 82,
Default: 'რ',
Shift: 'ღ',
CapsLock: 'Ⴐ',
Shift_CapsLock: 'Ⴖ',
Alt: '®',
Alt_Shift: '‰'
},
KeyT: {
printable: true,
keyCode: 84,
Default: 'ტ',
Shift: 'თ',
CapsLock: 'Ⴒ',
Shift_CapsLock: 'Ⴇ',
Alt: '†',
Alt_Shift: 'ˇ'
},
KeyY: {
printable: true,
keyCode: 89,
Default: 'ყ',
Shift: '',
CapsLock: 'Ⴗ',
Shift_CapsLock: '',
Alt: '¥',
Alt_Shift: 'Á'
},
KeyU: {
printable: true,
keyCode: 85,
Default: 'უ',
Shift: '',
CapsLock: 'Ⴓ',
Shift_CapsLock: '',
Alt: '',
Alt_Shift: ''
},
KeyI: {
printable: true,
keyCode: 73,
Default: 'ი',
Shift: '',
CapsLock: 'Ⴈ',
Shift_CapsLock: '',
Alt: 'ˆ',
Alt_Shift: 'ˆ'
},
KeyO: {
printable: true,
keyCode: 79,
Default: 'ო',
Shift: '`',
CapsLock: 'Ⴍ',
Shift_CapsLock: '',
Alt: 'ø',
Alt_Shift: 'Ø'
},
KeyP: {
printable: true,
keyCode: 80,
Default: 'პ',
Shift: '~',
CapsLock: 'Ⴎ',
Shift_CapsLock: '',
Alt: 'π',
Alt_Shift: '∏'
},
KeyA: {
printable: true,
keyCode: 65,
Default: 'ა',
Shift: '',
CapsLock: 'Ⴀ',
Shift_CapsLock: '',
Alt: 'å',
Alt_Shift: 'Å'
},
KeyS: {
printable: true,
keyCode: 83,
Default: 'ს',
Shift: 'შ',
CapsLock: 'Ⴑ',
Shift_CapsLock: 'Ⴘ',
Alt: 'ß',
Alt_Shift: 'Í'
},
KeyD: {
printable: true,
keyCode: 68,
Default: 'დ',
Shift: '',
CapsLock: 'Ⴃ',
Shift_CapsLock: '',
Alt: '∂',
Alt_Shift: 'Î'
},
KeyF: {
printable: true,
keyCode: 70,
Default: 'ფ',
Shift: '',
CapsLock: 'Ⴔ',
Shift_CapsLock: '',
Alt: 'ƒ',
Alt_Shift: 'Ï'
},
KeyG: {
printable: true,
keyCode: 71,
Default: 'გ',
Shift: '',
CapsLock: 'Ⴂ',
Shift_CapsLock: '',
Alt: '˙',
Alt_Shift: '˝'
},
KeyH: {
printable: true,
keyCode: 72,
Default: 'ჰ',
Shift: '',
CapsLock: 'Ⴠ',
Shift_CapsLock: '',
Alt: '∆',
Alt_Shift: 'Ó'
},
KeyJ: {
printable: true,
keyCode: 74,
Default: 'ჯ',
Shift: 'ჟ',
CapsLock: 'Ⴟ',
Shift_CapsLock: 'Ⴏ',
Alt: '˚',
Alt_Shift: 'Ô'
},
KeyK: {
printable: true,
keyCode: 75,
Default: 'კ',
Shift: '',
CapsLock: 'Ⴉ',
Shift_CapsLock: '',
Alt: '¬',
Alt_Shift: ''
},
KeyL: {
printable: true,
keyCode: 76,
Default: 'ლ',
Shift: '',
CapsLock: 'Ⴊ',
Shift_CapsLock: '',
Alt: 'Ω',
Alt_Shift: 'Ò'
},
KeyZ: {
printable: true,
keyCode: 90,
Default: 'ზ',
Shift: 'ძ',
CapsLock: 'Ⴆ',
Shift_CapsLock: '',
Alt: '≈',
Alt_Shift: '¸'
},
KeyX: {
printable: true,
keyCode: 88,
Default: 'ხ',
Shift: '',
CapsLock: 'Ⴞ',
Shift_CapsLock: '',
Alt: 'ç',
Alt_Shift: '˛'
},
KeyC: {
printable: true,
keyCode: 67,
Default: 'ც',
Shift: 'ჩ',
CapsLock: 'Ⴚ',
Shift_CapsLock: 'Ⴙ',
Alt: '√',
Alt_Shift: 'Ç'
},
KeyV: {
printable: true,
keyCode: 86,
Default: 'ვ',
Shift: '',
CapsLock: 'Ⴅ',
Shift_CapsLock: '',
Alt: '∫',
Alt_Shift: '◊'
},
KeyB: {
printable: true,
keyCode: 66,
Default: 'ბ',
Shift: '',
CapsLock: 'Ⴁ',
Shift_CapsLock: '',
Alt: '˜',
Alt_Shift: 'ı'
},
KeyN: {
printable: true,
keyCode: 78,
Default: 'ნ',
Shift: '',
CapsLock: 'Ⴌ',
Shift_CapsLock: '',
Alt: 'µ',
Alt_Shift: '˜'
},
KeyM: {
printable: true,
keyCode: 77,
Default: 'მ',
Shift: '',
CapsLock: 'Ⴋ',
Shift_CapsLock: '',
Alt: 'µ',
Alt_Shift: 'Â'
},
// digits
Digit1: {
printable: true,
keyCode: 49,
Default: '1',
Shift: '!',
CapsLock: '1',
Shift_CapsLock: '!',
Alt_Shift: '⁄',
Alt: '¡'
},
Digit2: {
printable: true,
keyCode: 50,
Default: '2',
Shift: '@',
CapsLock: '2',
Shift_CapsLock: '@',
Alt_Shift: '€',
Alt: '™'
},
Digit3: {
printable: true,
keyCode: 51,
Default: '3',
Shift: '#',
CapsLock: '3',
Shift_CapsLock: '#',
Alt_Shift: '‹',
Alt: '£'
},
Digit4: {
printable: true,
keyCode: 52,
Default: '4',
Shift: '$',
CapsLock: '4',
Shift_CapsLock: '$',
Alt_Shift: '›',
Alt: '¢'
},
Digit5: {
printable: true,
keyCode: 53,
Default: '5',
Shift: '%',
CapsLock: '5',
Shift_CapsLock: '%',
Alt_Shift: 'fi',
Alt: '∞'
},
Digit6: {
printable: true,
keyCode: 54,
Default: '6',
Shift: '^',
CapsLock: '6',
Shift_CapsLock: '^',
Alt_Shift: 'fl',
Alt: '§'
},
Digit7: {
printable: true,
keyCode: 55,
Default: '7',
Shift: '&',
CapsLock: '7',
Shift_CapsLock: '&',
Alt_Shift: '‡',
Alt: '¶'
},
Digit8: {
printable: true,
keyCode: 56,
Default: '8',
Shift: '*',
CapsLock: '8',
Shift_CapsLock: '*',
Alt_Shift: '°',
Alt: '•'
},
Digit9: {
printable: true,
keyCode: 57,
Default: '9',
Shift: '(',
CapsLock: '9',
Shift_CapsLock: '(',
Alt_Shift: '·',
Alt: 'º'
},
Digit0: {
printable: true,
keyCode: 48,
Default: '0',
Shift: ')',
CapsLock: '0',
Shift_CapsLock: ')',
Alt_Shift: '‚',
Alt: 'º'
},
// symbols
IntlBackslash: {
printable: true,
keyCode: 192,
Default: '§',
Shift: '±',
CapsLock: '§',
Shift_CapsLock: '±',
Alt: '§',
},
Minus: {
printable: true,
keyCode: 189,
Default: '-',
Shift: '_',
CapsLock: '-',
Shift_CapsLock: '_',
Alt: '–',
},
Equal: {
printable: true,
keyCode: 187,
Default: '=',
Shift: '+',
CapsLock: '=',
Shift_CapsLock: '+',
Alt: '≠'
},
BracketLeft: {
printable: true,
keyCode: 219,
Default: '[',
Shift: '{',
CapsLock: '[',
Shift_CapsLock: '{',
Alt: '“'
},
BracketRight: {
printable: true,
keyCode: 221,
Default: ']',
Shift: '}',
CapsLock: ']',
Shift_CapsLock: '}',
Alt: '‘'
},
Semicolon: {
printable: true,
keyCode: 186,
Default: ';',
Shift: ':',
CapsLock: ';',
Shift_CapsLock: ':',
Alt: '…'
},
Quote: {
printable: true,
keyCode: 222,
Default: '\'',
Shift: '"',
CapsLock: '\'',
Shift_CapsLock: '"',
Alt: 'æ'
},
Backslash: {
printable: true,
keyCode: 220,
Default: '\\',
Shift: '|',
CapsLock: '\\',
Shift_CapsLock: '|',
Alt: '«'
},
Backquote: {
printable: true,
keyCode: 192,
Default: '`',
Shift: '~',
CapsLock: '`',
Shift_CapsLock: '~',
Alt: '`'
},
Comma: {
printable: true,
keyCode: 188,
Default: ',',
Shift: '<',
CapsLock: ',',
Shift_CapsLock: '<',
Alt: '≤'
},
Period: {
printable: true,
keyCode: 190,
Default: '.',
Shift: '>',
CapsLock: '.',
Shift_CapsLock: '>',
Alt: '≥'
},
Slash: {
printable: true,
keyCode: 191,
Default: '/',
Shift: '?',
CapsLock: '/',
Shift_CapsLock: '?',
Alt: '÷'
},
// space keys
Tab: {
printable: true,
keyCode: 9
},
Enter: {
keyCode: 13
},
Space: {
printable: true,
keyCode: 32
},
// helper keys
Escape: { keyCode: 27 },
Backspace: { keyCode: 8 },
CapsLock: { keyCode: 20 },
ShiftLeft: { keyCode: 16 },
ShiftRight: { keyCode: 16 },
ControlLeft: { keyCode: 17 },
AltLeft: { keyCode: 18 },
OSLeft: { keyCode: 91 },
Space: { keyCode: 32 },
OSRight: { keyCode: 93 },
AltRight: { keyCode: 18 },
// arrows
ArrowLeft: { keyCode: 37 },
ArrowDown: { keyCode: 40 },
ArrowUp: { keyCode: 38 },
ArrowRight: { keyCode: 39 }
} | mijra/georgiankeyboard.com | data.js | JavaScript | mit | 8,583 |
/*
* Copyright 2001-2014 Aspose Pty Ltd. All Rights Reserved.
*
* This file is part of Aspose.Words. The source code in this file
* is only intended as a supplement to the documentation, and is provided
* "as is", without warranty of any kind, either expressed or implied.
*/
package loadingandsaving.loadingandsavinghtml.splitintohtmlpages.java;
/**
* A simple class to hold a topic title and HTML file name together.
*/
class Topic
{
Topic(String title, String fileName) throws Exception
{
mTitle = title;
mFileName = fileName;
}
String getTitle() throws Exception { return mTitle; }
String getFileName() throws Exception { return mFileName; }
private final String mTitle;
private final String mFileName;
} | asposemarketplace/Aspose-Words-Java | src/loadingandsaving/loadingandsavinghtml/splitintohtmlpages/java/Topic.java | Java | mit | 791 |
class <%= class_name %> < ApplicationPage
# self.route = nil # slug
# self.allow_create = true
# self.allow_destroy = true
# self.minimum_children = nil
# self.minimum_children = nil
# self.allowed_children = []
# form do |f|
# f.inputs
# f.buttons
# end
# def static_children
# {}
# end
end
| mrhenry/lalala-ng | lib/generators/lalala/page/templates/page.rb | Ruby | mit | 346 |
/**
* This program and the accompanying materials
* are made available under the terms of the License
* which accompanies this distribution in the file LICENSE.txt
*/
package org.opengroup.archimate.xmlexchange;
/**
* XML Exception
*
* @author Phillip Beauvoir
*/
public class XMLModelParserException extends Exception {
public XMLModelParserException() {
super(Messages.XMLModelParserException_0);
}
public XMLModelParserException(String message) {
super(message);
}
public XMLModelParserException(String message, Throwable cause) {
super(message, cause);
}
}
| archimatetool/archi | org.opengroup.archimate.xmlexchange/src/org/opengroup/archimate/xmlexchange/XMLModelParserException.java | Java | mit | 597 |
window.Boid = (function(){
function Boid(x, y, settings){
this.location = new Vector(x, y);
this.acceleration = new Vector(0, 0);
this.velocity = new Vector(Helper.getRandomInt(-1,1), Helper.getRandomInt(-1,1));
this.settings = settings || {};
this.show_connections = settings.show_connections || true;
this.r = settings.r || 3.0;
this.maxspeed = settings.maxspeed || 2;
this.maxforce = settings.maxforce || 0.5;
this.perchSite = settings.perchSite || [h - 100, h - 50];
this.laziness_level = settings.laziness_level || 0.7;
this.min_perch = settings.min_perch || 1;
this.max_perch = settings.max_perch || 100;
this.perching = settings.perching || false;
this.perchTimer = settings.perchTimer || 100;
this.separation_multiple = settings.separation || 0.2;
this.cohesion_multiple = settings.cohesion || 2.0;
this.alignment_multiple = settings.alignment || 1.0;
this.separation_neighbor_dist = (settings.separation_neighbor_dis || 10) * 10;
this.cohesion_neighbor_dist = settings.cohesion_neighbor_dis || 200;
this.alignment_neighbor_dist = settings.alignment_neighbor_dis || 200;
}
Boid.prototype = {
constructor: Boid,
update: function(){
if (this.perching) {
this.perchTimer--;
if (this.perchTimer < 0){
this.perching = false;
}
} else {
this.velocity.add(this.acceleration);
this.velocity.limit(this.maxspeed);
this.location.add(this.velocity);
this.acceleration.multiply(0);
}
},
applyForce: function(force){
this.acceleration.add(force);
},
tired: function(){
var x = Math.random();
if (x < this.laziness_level){
return false;
} else {
return true;
}
},
seek: function(target) {
var desired = Vector.subtract(target, this.location);
desired.normalize();
desired.multiply(this.maxspeed);
var steer = Vector.subtract(desired, this.velocity);
steer.limit(this.maxforce);
return steer;
},
//Leaving this function here for experiments
//You can replace "seek" inside cohesion()
//For a more fish-like behaviour
arrive: function(target) {
var desired = Vector.subtract(target, this.location);
var dMag = desired.magnitude();
desired.normalize();
// closer than 100 pixels?
if (dMag < 100) {
var m = Helper.map(dMag,0,100,0,this.maxspeed);
desired.multiply(m);
} else {
desired.multiply(this.maxspeed);
}
var steer = Vector.subtract(desired, this.velocity);
steer.limit(this.maxforce);
return steer;
},
align: function(boids){
var sum = new Vector();
var count = 0;
for (var i = 0; i < boids.length; i++){
if (boids[i].perching == false) {
var distance = Vector.distance(this.location, boids[i].location);
//if ((distance > 0) && (distance < this.align_neighbor_dist)) {
sum.add(boids[i].velocity);
count++;
//}
}
}
if (count > 0) {
sum.divide(count);
sum.normalize();
sum.multiply(this.maxspeed);
var steer = Vector.subtract(sum,this.velocity);
steer.limit(this.maxforce);
return steer;
} else {
return new Vector(0,0);
}
},
cohesion: function(boids){
var sum = new Vector();
var count = 0;
for (var i = 0; i < boids.length; i++){
if (boids[i].perching == false) {
var distance = Vector.distance(this.location, boids[i].location);
//if ((distance > 0) && (distance < this.cohesion_neighbor_dist)) {
sum.add(boids[i].location);
count++;
//}
}
}
if (count > 0) {
sum.divide(count);
return this.seek(sum);
} else {
return new Vector(0,0);
}
},
separate: function(boids) {
var sum = new Vector();
var count = 0;
for (var i=0; i< boids.length; i++){
var distance = Vector.distance(this.location, boids[i].location);
if ((distance > 0) && (distance < this.separation_neighbor_dist)) {
var diff = Vector.subtract(this.location, boids[i].location);
diff.normalize();
diff.divide(distance);
sum.add(diff);
count++;
}
}
if(count > 0){
sum.divide(count);
sum.normalize();
sum.multiply(this.maxspeed);
var steer = Vector.subtract(sum, this.velocity);
steer.limit(this.maxforce);
}
return sum;
},
borders: function() {
//We are allowing boids to fly a bit outside
//the view and then return.
var offset = 20;
var isTired = this.tired();
if (this.onPerchSite() && isTired ){
this.perching = true;
} else {
if (this.location.x < -offset) this.location.x += 5;
if (this.location.x > w + offset) this.location.x -= 5;
if (this.location.y > h + offset) this.location.y -= 5;
if (this.location.y < -offset) this.location.y += 5;
}
},
onPerchSite: function(){
for (var i = 0; i < this.perchSite.length; i++){
if( this.location.y > this.perchSite[i] -2 && this.location.y < this.perchSite[i] + 2 )
return true;
}
return false;
},
borders2: function() {
var offset = 20;
var isTired = this.tired();
if (this.location.y > this.perchSite - 2 && this.location.y < this.perchSite + 2 && isTired ){
this.perching = true;
} else {
if (this.location.x < -this.r) this.location.x = w+this.r;
if (this.location.y < -this.r) this.location.y = h+this.r;
if (this.location.x > w+this.r) this.location.x = -this.r;
if (this.location.y > h+this.r) this.location.y = -this.r;
}
},
render: function() {
var theta = this.velocity.heading() + Math.PI/2;
context.stroke();
context.save();
context.translate(this.location.x, this.location.y);
context.rotate(theta);
if(this.settings.boid_shape){
this.settings.boid_shape();
} else {
this.default_boid_shape();
}
context.restore();
},
default_boid_shape: function(){
var radius = 5;
context.fillStyle = "#636570";
context.beginPath();
context.arc(0, 0, radius, 0, 2 * Math.PI, false);
context.closePath();
context.fill();
},
flock: function(boids){
var separate = this.separate(boids);
var align = this.align(boids);
var cohesion = this.cohesion(boids);
separate.multiply(this.separation_multiple);
align.multiply(this.alignment_multiple);
cohesion.multiply(this.cohesion_multiple);
this.applyForce(separate);
this.applyForce(align);
this.applyForce(cohesion);
},
run: function(boids){
if (this.perching){
this.perchTimer--;
if(this.perchTimer < 0 )
{
this.perching = false;
this.perchTimer = Helper.getRandomInt(this.min_perch,this.max_perch);
}
} else {
this.flock(boids);
this.update();
this.borders();
}
}
};
return Boid;
})(); | innni/hypela | js/simulation/boid.js | JavaScript | mit | 7,239 |
package com.aliumujib.majlis.mkan_report_app.addnew.fragments;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.aliumujib.majlis.mkan_report_app.R;
import com.stepstone.stepper.VerificationError;
public class SihateJismaniPart2 extends BaseReportFragment {
public static SihateJismaniPart2 newInstance() {
SihateJismaniPart2 fragment = new SihateJismaniPart2();
Bundle args = new Bundle();
fragment.setArguments(args);
return fragment;
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
}
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_sihate_jismani_part2, container, false);
}
@Override
public VerificationError verifyStep() {
return null;
}
@Override
public void onSelected() {
}
}
| MKA-Nigeria/MKAN-Report-Android | mkan_report_app/src/main/java/com/aliumujib/majlis/mkan_report_app/addnew/fragments/SihateJismaniPart2.java | Java | mit | 1,164 |
<?php
/*
* WellCommerce Open-Source E-Commerce Platform
*
* This file is part of the WellCommerce package.
*
* (c) Adam Piotrowski <adam@wellcommerce.org>
*
* For the full copyright and license information,
* please view the LICENSE file that was distributed with this source code.
*/
namespace WellCommerce\Bundle\LocaleBundle\Copier;
use Doctrine\Common\Collections\Collection;
use Doctrine\Common\Collections\Criteria;
use Symfony\Component\PropertyAccess\PropertyAccess;
use WellCommerce\Bundle\CoreBundle\Helper\Doctrine\DoctrineHelperInterface;
use WellCommerce\Bundle\LocaleBundle\Entity\LocaleAwareInterface;
use WellCommerce\Bundle\LocaleBundle\Entity\LocaleInterface;
/**
* Class LocaleCopier
*
* @author Adam Piotrowski <adam@wellcommerce.org>
*/
final class LocaleCopier implements LocaleCopierInterface
{
/**
* @var array
*/
private $entityClasses;
/**
* @var DoctrineHelperInterface
*/
protected $doctrineHelper;
/**
* @var \Symfony\Component\PropertyAccess\PropertyAccessor
*/
protected $propertyAccessor;
/**
* LocaleCopier constructor.
*
* @param array $entityClasses
* @param DoctrineHelperInterface $doctrineHelper
*/
public function __construct(array $entityClasses, DoctrineHelperInterface $doctrineHelper)
{
$this->entityClasses = $entityClasses;
$this->doctrineHelper = $doctrineHelper;
$this->propertyAccessor = PropertyAccess::createPropertyAccessor();
}
public function copyLocaleData(LocaleInterface $sourceLocale, LocaleInterface $targetLocale)
{
$criteria = new Criteria();
$criteria->where($criteria->expr()->eq('locale', $sourceLocale->getCode()));
foreach ($this->entityClasses as $className => $options) {
$repository = $this->doctrineHelper->getRepositoryForClass($className);
$entities = $repository->matching($criteria);
$this->duplicateTranslatableEntities($entities, $options['properties'], $targetLocale);
}
$this->doctrineHelper->getEntityManager()->flush();
}
private function duplicateTranslatableEntities(Collection $entities, array $properties, LocaleInterface $targetLocale)
{
$entities->map(function (LocaleAwareInterface $entity) use ($properties, $targetLocale) {
$this->duplicateTranslatableEntity($entity, $properties, $targetLocale);
});
}
private function duplicateTranslatableEntity(LocaleAwareInterface $entity, array $properties, LocaleInterface $targetLocale)
{
$duplicate = clone $entity;
foreach ($properties as $propertyName) {
$value = sprintf('%s-%s', $this->propertyAccessor->getValue($entity, $propertyName), $targetLocale->getCode());
$this->propertyAccessor->setValue($duplicate, $propertyName, $value);
$duplicate->setLocale($targetLocale->getCode());
$this->doctrineHelper->getEntityManager()->persist($duplicate);
}
}
}
| WellCommerce/LocaleBundle | Copier/LocaleCopier.php | PHP | mit | 3,103 |
/// <reference path="vector2d.ts" />
function fillCircle(x: number, y: number, radius: number, color: string) {
context.beginPath();
context.arc(x, y, radius, 0, Math.PI * 2);
context.fillStyle = color;
context.fill();
}
function fillCircleWithFace(context: CanvasRenderingContext2D, x: number, y: number, radius: number, color: string, face: number) {
fillCircle(x, y, radius, color);
var unit = Vector2D.unitFromAngle(face);
context.beginPath();
context.moveTo(x - unit.y * radius, y + unit.x * radius);
context.lineTo(x + unit.x * radius * 1.5, y + unit.y * radius * 1.5);
context.lineTo(x + unit.y * radius, y - unit.x * radius);
context.closePath();
context.fill();
} | mktange/FFXIV-BattleSimulator | src/engine/DrawingUtils.ts | TypeScript | mit | 704 |
using EdityMcEditface.HtmlRenderer.SiteBuilder;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace EdityMcEditface.Mvc.Config
{
public class SiteBuilderEventArgs
{
/// <summary>
/// The site builder to customize.
/// </summary>
public ISiteBuilder SiteBuilder { get; set; }
/// <summary>
/// The service provider.
/// </summary>
public IServiceProvider Services { get; set; }
}
}
| threax/EdityMcEditface | EdityMcEditface.Mvc/Config/SiteBuilderEventArgs.cs | C# | mit | 517 |
package com.hypebeast.sdk.api.model.hypebeaststore;
import com.google.gson.annotations.SerializedName;
import com.hypebeast.sdk.api.model.Alternative;
import com.hypebeast.sdk.api.model.symfony.taxonomy;
/**
* Created by hesk on 7/1/2015.
*/
public class ReponseNormal extends Alternative {
@SerializedName("products")
public ResponseProductList product_list;
@SerializedName("taxon")
public taxonomy taxon_result;
}
| jjhesk/slideSelectionList | SmartSelectionList/hbsdk/src/main/java/com/hypebeast/sdk/api/model/hypebeaststore/ReponseNormal.java | Java | mit | 438 |
# encoding: utf-8
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes may cause incorrect behavior and will be lost if the code is
# regenerated.
module Azure::Network::Mgmt::V2018_06_01
#
# SecurityRules
#
class SecurityRules
include MsRestAzure
#
# Creates and initializes a new instance of the SecurityRules class.
# @param client service class for accessing basic functionality.
#
def initialize(client)
@client = client
end
# @return [NetworkManagementClient] reference to the NetworkManagementClient
attr_reader :client
#
# Deletes the specified network security rule.
#
# @param resource_group_name [String] The name of the resource group.
# @param network_security_group_name [String] The name of the network security
# group.
# @param security_rule_name [String] The name of the security rule.
# @param custom_headers [Hash{String => String}] A hash of custom headers that
# will be added to the HTTP request.
#
def delete(resource_group_name, network_security_group_name, security_rule_name, custom_headers:nil)
response = delete_async(resource_group_name, network_security_group_name, security_rule_name, custom_headers:custom_headers).value!
nil
end
#
# @param resource_group_name [String] The name of the resource group.
# @param network_security_group_name [String] The name of the network security
# group.
# @param security_rule_name [String] The name of the security rule.
# @param custom_headers [Hash{String => String}] A hash of custom headers that
# will be added to the HTTP request.
#
# @return [Concurrent::Promise] promise which provides async access to http
# response.
#
def delete_async(resource_group_name, network_security_group_name, security_rule_name, custom_headers:nil)
# Send request
promise = begin_delete_async(resource_group_name, network_security_group_name, security_rule_name, custom_headers:custom_headers)
promise = promise.then do |response|
# Defining deserialization method.
deserialize_method = lambda do |parsed_response|
end
# Waiting for response.
@client.get_long_running_operation_result(response, deserialize_method)
end
promise
end
#
# Get the specified network security rule.
#
# @param resource_group_name [String] The name of the resource group.
# @param network_security_group_name [String] The name of the network security
# group.
# @param security_rule_name [String] The name of the security rule.
# @param custom_headers [Hash{String => String}] A hash of custom headers that
# will be added to the HTTP request.
#
# @return [SecurityRule] operation results.
#
def get(resource_group_name, network_security_group_name, security_rule_name, custom_headers:nil)
response = get_async(resource_group_name, network_security_group_name, security_rule_name, custom_headers:custom_headers).value!
response.body unless response.nil?
end
#
# Get the specified network security rule.
#
# @param resource_group_name [String] The name of the resource group.
# @param network_security_group_name [String] The name of the network security
# group.
# @param security_rule_name [String] The name of the security rule.
# @param custom_headers [Hash{String => String}] A hash of custom headers that
# will be added to the HTTP request.
#
# @return [MsRestAzure::AzureOperationResponse] HTTP response information.
#
def get_with_http_info(resource_group_name, network_security_group_name, security_rule_name, custom_headers:nil)
get_async(resource_group_name, network_security_group_name, security_rule_name, custom_headers:custom_headers).value!
end
#
# Get the specified network security rule.
#
# @param resource_group_name [String] The name of the resource group.
# @param network_security_group_name [String] The name of the network security
# group.
# @param security_rule_name [String] The name of the security rule.
# @param [Hash{String => String}] A hash of custom headers that will be added
# to the HTTP request.
#
# @return [Concurrent::Promise] Promise object which holds the HTTP response.
#
def get_async(resource_group_name, network_security_group_name, security_rule_name, custom_headers:nil)
fail ArgumentError, 'resource_group_name is nil' if resource_group_name.nil?
fail ArgumentError, 'network_security_group_name is nil' if network_security_group_name.nil?
fail ArgumentError, 'security_rule_name is nil' if security_rule_name.nil?
fail ArgumentError, '@client.api_version is nil' if @client.api_version.nil?
fail ArgumentError, '@client.subscription_id is nil' if @client.subscription_id.nil?
request_headers = {}
request_headers['Content-Type'] = 'application/json; charset=utf-8'
# Set Headers
request_headers['x-ms-client-request-id'] = SecureRandom.uuid
request_headers['accept-language'] = @client.accept_language unless @client.accept_language.nil?
path_template = 'subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/networkSecurityGroups/{networkSecurityGroupName}/securityRules/{securityRuleName}'
request_url = @base_url || @client.base_url
options = {
middlewares: [[MsRest::RetryPolicyMiddleware, times: 3, retry: 0.02], [:cookie_jar]],
path_params: {'resourceGroupName' => resource_group_name,'networkSecurityGroupName' => network_security_group_name,'securityRuleName' => security_rule_name,'subscriptionId' => @client.subscription_id},
query_params: {'api-version' => @client.api_version},
headers: request_headers.merge(custom_headers || {}),
base_url: request_url
}
promise = @client.make_request_async(:get, path_template, options)
promise = promise.then do |result|
http_response = result.response
status_code = http_response.status
response_content = http_response.body
unless status_code == 200
error_model = JSON.load(response_content)
fail MsRestAzure::AzureOperationError.new(result.request, http_response, error_model)
end
result.request_id = http_response['x-ms-request-id'] unless http_response['x-ms-request-id'].nil?
result.correlation_request_id = http_response['x-ms-correlation-request-id'] unless http_response['x-ms-correlation-request-id'].nil?
result.client_request_id = http_response['x-ms-client-request-id'] unless http_response['x-ms-client-request-id'].nil?
# Deserialize Response
if status_code == 200
begin
parsed_response = response_content.to_s.empty? ? nil : JSON.load(response_content)
result_mapper = Azure::Network::Mgmt::V2018_06_01::Models::SecurityRule.mapper()
result.body = @client.deserialize(result_mapper, parsed_response)
rescue Exception => e
fail MsRest::DeserializationError.new('Error occurred in deserializing the response', e.message, e.backtrace, result)
end
end
result
end
promise.execute
end
#
# Creates or updates a security rule in the specified network security group.
#
# @param resource_group_name [String] The name of the resource group.
# @param network_security_group_name [String] The name of the network security
# group.
# @param security_rule_name [String] The name of the security rule.
# @param security_rule_parameters [SecurityRule] Parameters supplied to the
# create or update network security rule operation.
# @param custom_headers [Hash{String => String}] A hash of custom headers that
# will be added to the HTTP request.
#
# @return [SecurityRule] operation results.
#
def create_or_update(resource_group_name, network_security_group_name, security_rule_name, security_rule_parameters, custom_headers:nil)
response = create_or_update_async(resource_group_name, network_security_group_name, security_rule_name, security_rule_parameters, custom_headers:custom_headers).value!
response.body unless response.nil?
end
#
# @param resource_group_name [String] The name of the resource group.
# @param network_security_group_name [String] The name of the network security
# group.
# @param security_rule_name [String] The name of the security rule.
# @param security_rule_parameters [SecurityRule] Parameters supplied to the
# create or update network security rule operation.
# @param custom_headers [Hash{String => String}] A hash of custom headers that
# will be added to the HTTP request.
#
# @return [Concurrent::Promise] promise which provides async access to http
# response.
#
def create_or_update_async(resource_group_name, network_security_group_name, security_rule_name, security_rule_parameters, custom_headers:nil)
# Send request
promise = begin_create_or_update_async(resource_group_name, network_security_group_name, security_rule_name, security_rule_parameters, custom_headers:custom_headers)
promise = promise.then do |response|
# Defining deserialization method.
deserialize_method = lambda do |parsed_response|
result_mapper = Azure::Network::Mgmt::V2018_06_01::Models::SecurityRule.mapper()
parsed_response = @client.deserialize(result_mapper, parsed_response)
end
# Waiting for response.
@client.get_long_running_operation_result(response, deserialize_method)
end
promise
end
#
# Gets all security rules in a network security group.
#
# @param resource_group_name [String] The name of the resource group.
# @param network_security_group_name [String] The name of the network security
# group.
# @param custom_headers [Hash{String => String}] A hash of custom headers that
# will be added to the HTTP request.
#
# @return [Array<SecurityRule>] operation results.
#
def list(resource_group_name, network_security_group_name, custom_headers:nil)
first_page = list_as_lazy(resource_group_name, network_security_group_name, custom_headers:custom_headers)
first_page.get_all_items
end
#
# Gets all security rules in a network security group.
#
# @param resource_group_name [String] The name of the resource group.
# @param network_security_group_name [String] The name of the network security
# group.
# @param custom_headers [Hash{String => String}] A hash of custom headers that
# will be added to the HTTP request.
#
# @return [MsRestAzure::AzureOperationResponse] HTTP response information.
#
def list_with_http_info(resource_group_name, network_security_group_name, custom_headers:nil)
list_async(resource_group_name, network_security_group_name, custom_headers:custom_headers).value!
end
#
# Gets all security rules in a network security group.
#
# @param resource_group_name [String] The name of the resource group.
# @param network_security_group_name [String] The name of the network security
# group.
# @param [Hash{String => String}] A hash of custom headers that will be added
# to the HTTP request.
#
# @return [Concurrent::Promise] Promise object which holds the HTTP response.
#
def list_async(resource_group_name, network_security_group_name, custom_headers:nil)
fail ArgumentError, 'resource_group_name is nil' if resource_group_name.nil?
fail ArgumentError, 'network_security_group_name is nil' if network_security_group_name.nil?
fail ArgumentError, '@client.api_version is nil' if @client.api_version.nil?
fail ArgumentError, '@client.subscription_id is nil' if @client.subscription_id.nil?
request_headers = {}
request_headers['Content-Type'] = 'application/json; charset=utf-8'
# Set Headers
request_headers['x-ms-client-request-id'] = SecureRandom.uuid
request_headers['accept-language'] = @client.accept_language unless @client.accept_language.nil?
path_template = 'subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/networkSecurityGroups/{networkSecurityGroupName}/securityRules'
request_url = @base_url || @client.base_url
options = {
middlewares: [[MsRest::RetryPolicyMiddleware, times: 3, retry: 0.02], [:cookie_jar]],
path_params: {'resourceGroupName' => resource_group_name,'networkSecurityGroupName' => network_security_group_name,'subscriptionId' => @client.subscription_id},
query_params: {'api-version' => @client.api_version},
headers: request_headers.merge(custom_headers || {}),
base_url: request_url
}
promise = @client.make_request_async(:get, path_template, options)
promise = promise.then do |result|
http_response = result.response
status_code = http_response.status
response_content = http_response.body
unless status_code == 200
error_model = JSON.load(response_content)
fail MsRestAzure::AzureOperationError.new(result.request, http_response, error_model)
end
result.request_id = http_response['x-ms-request-id'] unless http_response['x-ms-request-id'].nil?
result.correlation_request_id = http_response['x-ms-correlation-request-id'] unless http_response['x-ms-correlation-request-id'].nil?
result.client_request_id = http_response['x-ms-client-request-id'] unless http_response['x-ms-client-request-id'].nil?
# Deserialize Response
if status_code == 200
begin
parsed_response = response_content.to_s.empty? ? nil : JSON.load(response_content)
result_mapper = Azure::Network::Mgmt::V2018_06_01::Models::SecurityRuleListResult.mapper()
result.body = @client.deserialize(result_mapper, parsed_response)
rescue Exception => e
fail MsRest::DeserializationError.new('Error occurred in deserializing the response', e.message, e.backtrace, result)
end
end
result
end
promise.execute
end
#
# Deletes the specified network security rule.
#
# @param resource_group_name [String] The name of the resource group.
# @param network_security_group_name [String] The name of the network security
# group.
# @param security_rule_name [String] The name of the security rule.
# @param custom_headers [Hash{String => String}] A hash of custom headers that
# will be added to the HTTP request.
#
#
def begin_delete(resource_group_name, network_security_group_name, security_rule_name, custom_headers:nil)
response = begin_delete_async(resource_group_name, network_security_group_name, security_rule_name, custom_headers:custom_headers).value!
nil
end
#
# Deletes the specified network security rule.
#
# @param resource_group_name [String] The name of the resource group.
# @param network_security_group_name [String] The name of the network security
# group.
# @param security_rule_name [String] The name of the security rule.
# @param custom_headers [Hash{String => String}] A hash of custom headers that
# will be added to the HTTP request.
#
# @return [MsRestAzure::AzureOperationResponse] HTTP response information.
#
def begin_delete_with_http_info(resource_group_name, network_security_group_name, security_rule_name, custom_headers:nil)
begin_delete_async(resource_group_name, network_security_group_name, security_rule_name, custom_headers:custom_headers).value!
end
#
# Deletes the specified network security rule.
#
# @param resource_group_name [String] The name of the resource group.
# @param network_security_group_name [String] The name of the network security
# group.
# @param security_rule_name [String] The name of the security rule.
# @param [Hash{String => String}] A hash of custom headers that will be added
# to the HTTP request.
#
# @return [Concurrent::Promise] Promise object which holds the HTTP response.
#
def begin_delete_async(resource_group_name, network_security_group_name, security_rule_name, custom_headers:nil)
fail ArgumentError, 'resource_group_name is nil' if resource_group_name.nil?
fail ArgumentError, 'network_security_group_name is nil' if network_security_group_name.nil?
fail ArgumentError, 'security_rule_name is nil' if security_rule_name.nil?
fail ArgumentError, '@client.api_version is nil' if @client.api_version.nil?
fail ArgumentError, '@client.subscription_id is nil' if @client.subscription_id.nil?
request_headers = {}
request_headers['Content-Type'] = 'application/json; charset=utf-8'
# Set Headers
request_headers['x-ms-client-request-id'] = SecureRandom.uuid
request_headers['accept-language'] = @client.accept_language unless @client.accept_language.nil?
path_template = 'subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/networkSecurityGroups/{networkSecurityGroupName}/securityRules/{securityRuleName}'
request_url = @base_url || @client.base_url
options = {
middlewares: [[MsRest::RetryPolicyMiddleware, times: 3, retry: 0.02], [:cookie_jar]],
path_params: {'resourceGroupName' => resource_group_name,'networkSecurityGroupName' => network_security_group_name,'securityRuleName' => security_rule_name,'subscriptionId' => @client.subscription_id},
query_params: {'api-version' => @client.api_version},
headers: request_headers.merge(custom_headers || {}),
base_url: request_url
}
promise = @client.make_request_async(:delete, path_template, options)
promise = promise.then do |result|
http_response = result.response
status_code = http_response.status
response_content = http_response.body
unless status_code == 204 || status_code == 202 || status_code == 200
error_model = JSON.load(response_content)
fail MsRestAzure::AzureOperationError.new(result.request, http_response, error_model)
end
result.request_id = http_response['x-ms-request-id'] unless http_response['x-ms-request-id'].nil?
result.correlation_request_id = http_response['x-ms-correlation-request-id'] unless http_response['x-ms-correlation-request-id'].nil?
result.client_request_id = http_response['x-ms-client-request-id'] unless http_response['x-ms-client-request-id'].nil?
result
end
promise.execute
end
#
# Creates or updates a security rule in the specified network security group.
#
# @param resource_group_name [String] The name of the resource group.
# @param network_security_group_name [String] The name of the network security
# group.
# @param security_rule_name [String] The name of the security rule.
# @param security_rule_parameters [SecurityRule] Parameters supplied to the
# create or update network security rule operation.
# @param custom_headers [Hash{String => String}] A hash of custom headers that
# will be added to the HTTP request.
#
# @return [SecurityRule] operation results.
#
def begin_create_or_update(resource_group_name, network_security_group_name, security_rule_name, security_rule_parameters, custom_headers:nil)
response = begin_create_or_update_async(resource_group_name, network_security_group_name, security_rule_name, security_rule_parameters, custom_headers:custom_headers).value!
response.body unless response.nil?
end
#
# Creates or updates a security rule in the specified network security group.
#
# @param resource_group_name [String] The name of the resource group.
# @param network_security_group_name [String] The name of the network security
# group.
# @param security_rule_name [String] The name of the security rule.
# @param security_rule_parameters [SecurityRule] Parameters supplied to the
# create or update network security rule operation.
# @param custom_headers [Hash{String => String}] A hash of custom headers that
# will be added to the HTTP request.
#
# @return [MsRestAzure::AzureOperationResponse] HTTP response information.
#
def begin_create_or_update_with_http_info(resource_group_name, network_security_group_name, security_rule_name, security_rule_parameters, custom_headers:nil)
begin_create_or_update_async(resource_group_name, network_security_group_name, security_rule_name, security_rule_parameters, custom_headers:custom_headers).value!
end
#
# Creates or updates a security rule in the specified network security group.
#
# @param resource_group_name [String] The name of the resource group.
# @param network_security_group_name [String] The name of the network security
# group.
# @param security_rule_name [String] The name of the security rule.
# @param security_rule_parameters [SecurityRule] Parameters supplied to the
# create or update network security rule operation.
# @param [Hash{String => String}] A hash of custom headers that will be added
# to the HTTP request.
#
# @return [Concurrent::Promise] Promise object which holds the HTTP response.
#
def begin_create_or_update_async(resource_group_name, network_security_group_name, security_rule_name, security_rule_parameters, custom_headers:nil)
fail ArgumentError, 'resource_group_name is nil' if resource_group_name.nil?
fail ArgumentError, 'network_security_group_name is nil' if network_security_group_name.nil?
fail ArgumentError, 'security_rule_name is nil' if security_rule_name.nil?
fail ArgumentError, 'security_rule_parameters is nil' if security_rule_parameters.nil?
fail ArgumentError, '@client.api_version is nil' if @client.api_version.nil?
fail ArgumentError, '@client.subscription_id is nil' if @client.subscription_id.nil?
request_headers = {}
request_headers['Content-Type'] = 'application/json; charset=utf-8'
# Set Headers
request_headers['x-ms-client-request-id'] = SecureRandom.uuid
request_headers['accept-language'] = @client.accept_language unless @client.accept_language.nil?
# Serialize Request
request_mapper = Azure::Network::Mgmt::V2018_06_01::Models::SecurityRule.mapper()
request_content = @client.serialize(request_mapper, security_rule_parameters)
request_content = request_content != nil ? JSON.generate(request_content, quirks_mode: true) : nil
path_template = 'subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/networkSecurityGroups/{networkSecurityGroupName}/securityRules/{securityRuleName}'
request_url = @base_url || @client.base_url
options = {
middlewares: [[MsRest::RetryPolicyMiddleware, times: 3, retry: 0.02], [:cookie_jar]],
path_params: {'resourceGroupName' => resource_group_name,'networkSecurityGroupName' => network_security_group_name,'securityRuleName' => security_rule_name,'subscriptionId' => @client.subscription_id},
query_params: {'api-version' => @client.api_version},
body: request_content,
headers: request_headers.merge(custom_headers || {}),
base_url: request_url
}
promise = @client.make_request_async(:put, path_template, options)
promise = promise.then do |result|
http_response = result.response
status_code = http_response.status
response_content = http_response.body
unless status_code == 200 || status_code == 201
error_model = JSON.load(response_content)
fail MsRestAzure::AzureOperationError.new(result.request, http_response, error_model)
end
result.request_id = http_response['x-ms-request-id'] unless http_response['x-ms-request-id'].nil?
result.correlation_request_id = http_response['x-ms-correlation-request-id'] unless http_response['x-ms-correlation-request-id'].nil?
result.client_request_id = http_response['x-ms-client-request-id'] unless http_response['x-ms-client-request-id'].nil?
# Deserialize Response
if status_code == 200
begin
parsed_response = response_content.to_s.empty? ? nil : JSON.load(response_content)
result_mapper = Azure::Network::Mgmt::V2018_06_01::Models::SecurityRule.mapper()
result.body = @client.deserialize(result_mapper, parsed_response)
rescue Exception => e
fail MsRest::DeserializationError.new('Error occurred in deserializing the response', e.message, e.backtrace, result)
end
end
# Deserialize Response
if status_code == 201
begin
parsed_response = response_content.to_s.empty? ? nil : JSON.load(response_content)
result_mapper = Azure::Network::Mgmt::V2018_06_01::Models::SecurityRule.mapper()
result.body = @client.deserialize(result_mapper, parsed_response)
rescue Exception => e
fail MsRest::DeserializationError.new('Error occurred in deserializing the response', e.message, e.backtrace, result)
end
end
result
end
promise.execute
end
#
# Gets all security rules in a network security group.
#
# @param next_page_link [String] The NextLink from the previous successful call
# to List operation.
# @param custom_headers [Hash{String => String}] A hash of custom headers that
# will be added to the HTTP request.
#
# @return [SecurityRuleListResult] operation results.
#
def list_next(next_page_link, custom_headers:nil)
response = list_next_async(next_page_link, custom_headers:custom_headers).value!
response.body unless response.nil?
end
#
# Gets all security rules in a network security group.
#
# @param next_page_link [String] The NextLink from the previous successful call
# to List operation.
# @param custom_headers [Hash{String => String}] A hash of custom headers that
# will be added to the HTTP request.
#
# @return [MsRestAzure::AzureOperationResponse] HTTP response information.
#
def list_next_with_http_info(next_page_link, custom_headers:nil)
list_next_async(next_page_link, custom_headers:custom_headers).value!
end
#
# Gets all security rules in a network security group.
#
# @param next_page_link [String] The NextLink from the previous successful call
# to List operation.
# @param [Hash{String => String}] A hash of custom headers that will be added
# to the HTTP request.
#
# @return [Concurrent::Promise] Promise object which holds the HTTP response.
#
def list_next_async(next_page_link, custom_headers:nil)
fail ArgumentError, 'next_page_link is nil' if next_page_link.nil?
request_headers = {}
request_headers['Content-Type'] = 'application/json; charset=utf-8'
# Set Headers
request_headers['x-ms-client-request-id'] = SecureRandom.uuid
request_headers['accept-language'] = @client.accept_language unless @client.accept_language.nil?
path_template = '{nextLink}'
request_url = @base_url || @client.base_url
options = {
middlewares: [[MsRest::RetryPolicyMiddleware, times: 3, retry: 0.02], [:cookie_jar]],
skip_encoding_path_params: {'nextLink' => next_page_link},
headers: request_headers.merge(custom_headers || {}),
base_url: request_url
}
promise = @client.make_request_async(:get, path_template, options)
promise = promise.then do |result|
http_response = result.response
status_code = http_response.status
response_content = http_response.body
unless status_code == 200
error_model = JSON.load(response_content)
fail MsRestAzure::AzureOperationError.new(result.request, http_response, error_model)
end
result.request_id = http_response['x-ms-request-id'] unless http_response['x-ms-request-id'].nil?
result.correlation_request_id = http_response['x-ms-correlation-request-id'] unless http_response['x-ms-correlation-request-id'].nil?
result.client_request_id = http_response['x-ms-client-request-id'] unless http_response['x-ms-client-request-id'].nil?
# Deserialize Response
if status_code == 200
begin
parsed_response = response_content.to_s.empty? ? nil : JSON.load(response_content)
result_mapper = Azure::Network::Mgmt::V2018_06_01::Models::SecurityRuleListResult.mapper()
result.body = @client.deserialize(result_mapper, parsed_response)
rescue Exception => e
fail MsRest::DeserializationError.new('Error occurred in deserializing the response', e.message, e.backtrace, result)
end
end
result
end
promise.execute
end
#
# Gets all security rules in a network security group.
#
# @param resource_group_name [String] The name of the resource group.
# @param network_security_group_name [String] The name of the network security
# group.
# @param custom_headers [Hash{String => String}] A hash of custom headers that
# will be added to the HTTP request.
#
# @return [SecurityRuleListResult] which provide lazy access to pages of the
# response.
#
def list_as_lazy(resource_group_name, network_security_group_name, custom_headers:nil)
response = list_async(resource_group_name, network_security_group_name, custom_headers:custom_headers).value!
unless response.nil?
page = response.body
page.next_method = Proc.new do |next_page_link|
list_next_async(next_page_link, custom_headers:custom_headers)
end
page
end
end
end
end
| Azure/azure-sdk-for-ruby | management/azure_mgmt_network/lib/2018-06-01/generated/azure_mgmt_network/security_rules.rb | Ruby | mit | 30,357 |
require 'nymphia'
require 'optparse'
require 'pathname'
module Nymphia
class CLI
def self.start(argv)
new(argv).run
end
def initialize(argv)
@argv = argv.dup
parser.parse!(@argv)
end
def run
validate_args!
dsl_code_file = File.open(@file_path)
absolute_dsl_file_path = File.absolute_path(dsl_code_file.path)
dsl_code = dsl_code_file.read
dsl = Nymphia::DSL.new(dsl_code, absolute_dsl_file_path)
dsl.compile
if @output_file_path
File.open(@output_file_path, 'w') do |file|
dsl.render(file)
end
else
dsl.render(STDOUT)
end
end
private
def parser
@parser ||= OptionParser.new do |opts|
opts.banner = 'nymphia'
opts.version = Nymphia::VERSION
opts.on('-f', '--file=FILE', 'Your DSL code file') { |f| @file_path = f }
opts.on('-o', '--output=FILE', 'Output file (default: stdout)') { |o| @output_file_path = o }
end
end
def validate_args!
unless @file_path
raise ArgumentError.new('-f (--file) options is required.')
end
end
end
end
| mozamimy/nymphia | lib/nymphia/cli.rb | Ruby | mit | 1,155 |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
// Code generated by Microsoft (R) AutoRest Code Generator.
package com.azure.resourcemanager.containerservice.generated;
import com.azure.core.util.Context;
/** Samples for ManagedClusters List. */
public final class ManagedClustersListSamples {
/*
* x-ms-original-file: specification/containerservice/resource-manager/Microsoft.ContainerService/stable/2022-01-01/examples/ManagedClustersList.json
*/
/**
* Sample code: List Managed Clusters.
*
* @param azure The entry point for accessing resource management APIs in Azure.
*/
public static void listManagedClusters(com.azure.resourcemanager.AzureResourceManager azure) {
azure.kubernetesClusters().manager().serviceClient().getManagedClusters().list(Context.NONE);
}
}
| Azure/azure-sdk-for-java | sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/containerservice/generated/ManagedClustersListSamples.java | Java | mit | 875 |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
// Code generated by Microsoft (R) AutoRest Code Generator.
package com.azure.resourcemanager.compute.models;
import com.azure.core.annotation.Fluent;
import com.azure.core.util.logging.ClientLogger;
import com.azure.resourcemanager.compute.fluent.models.ProximityPlacementGroupInner;
import com.fasterxml.jackson.annotation.JsonProperty;
import java.util.List;
/** The List Proximity Placement Group operation response. */
@Fluent
public final class ProximityPlacementGroupListResult {
/*
* The list of proximity placement groups
*/
@JsonProperty(value = "value", required = true)
private List<ProximityPlacementGroupInner> value;
/*
* The URI to fetch the next page of proximity placement groups.
*/
@JsonProperty(value = "nextLink")
private String nextLink;
/**
* Get the value property: The list of proximity placement groups.
*
* @return the value value.
*/
public List<ProximityPlacementGroupInner> value() {
return this.value;
}
/**
* Set the value property: The list of proximity placement groups.
*
* @param value the value value to set.
* @return the ProximityPlacementGroupListResult object itself.
*/
public ProximityPlacementGroupListResult withValue(List<ProximityPlacementGroupInner> value) {
this.value = value;
return this;
}
/**
* Get the nextLink property: The URI to fetch the next page of proximity placement groups.
*
* @return the nextLink value.
*/
public String nextLink() {
return this.nextLink;
}
/**
* Set the nextLink property: The URI to fetch the next page of proximity placement groups.
*
* @param nextLink the nextLink value to set.
* @return the ProximityPlacementGroupListResult object itself.
*/
public ProximityPlacementGroupListResult withNextLink(String nextLink) {
this.nextLink = nextLink;
return this;
}
/**
* Validates the instance.
*
* @throws IllegalArgumentException thrown if the instance is not valid.
*/
public void validate() {
if (value() == null) {
throw LOGGER
.logExceptionAsError(
new IllegalArgumentException(
"Missing required property value in model ProximityPlacementGroupListResult"));
} else {
value().forEach(e -> e.validate());
}
}
private static final ClientLogger LOGGER = new ClientLogger(ProximityPlacementGroupListResult.class);
}
| Azure/azure-sdk-for-java | sdk/resourcemanager/azure-resourcemanager-compute/src/main/java/com/azure/resourcemanager/compute/models/ProximityPlacementGroupListResult.java | Java | mit | 2,679 |
import MySQLdb as _mysql
from collections import namedtuple
import re
# Only needs to compile one time so we put it here
float_match = re.compile(r'[-+]?\d*\.?\d+(?:[eE][-+]?\d+)?$').match
def is_number(string):
return bool(float_match(string))
class MySQLDatabase(object):
"""
This is the driver class that we will use
for connecting to our database. In here we'll
create a constructor (__init__) that will connect
to the database once the driver class is instantiated
and a destructor method that will close the database
connection once the driver object is destroyed.
"""
def __init__(self, database_name, username,
password, host='localhost'):
"""
Here we'll try to connect to the database
using the variables that we passed through
and if the connection fails we'll print out the error
"""
try:
self.db = _mysql.connect(db=database_name, host=host, user=username, passwd=password)
self.database_name = database_name
print "Connected to MySQL!"
except _mysql.Error, e:
print e
def __del__(self):
"""
Here we'll do a check to see if `self.db` is present.
This will only be the case if the connection was
successfully made in the initialiser.
Inside that condition we'll close the connection
"""
if hasattr(self, 'db'):
self.db.close()
print "MySQL Connection Closed"
def get_available_tables(self):
"""
This method will allow us to see what
tables are available to us when we're
running our queries
"""
cursor = self.db.cursor()
cursor.execute("SHOW TABLES;")
self.tables = cursor.fetchall()
cursor.close()
return self.tables
def convert_to_named_tuples(self, cursor):
results = None
names = " ".join(d[0] for d in cursor.description)
klass = namedtuple('Results', names)
try:
results = map(klass._make, cursor.fetchall())
except _mysql.ProgrammingError, e:
print e
return results
def get_columns_for_table(self, table_name):
"""
This method will enable us to interact
with our database to find what columns
are currently in a specific table
"""
cursor = self.db.cursor()
cursor.execute("SHOW COLUMNS FROM `%s`" % table_name)
self.columns = cursor.fetchall()
cursor.close()
return self.columns
def select(self, table, columns=None, named_tuples=False, **kwargs):
"""
We'll create our `select` method in order
to make it simpler for extracting data from
the database.
select(table_name, [list_of_column_names])
"""
sql_str = "SELECT "
# add columns or just use the wildcard
if not columns:
sql_str += " * "
else:
for column in columns:
sql_str += "%s, " % column
sql_str = sql_str[:-2] # remove the last comma!
# add the to the SELECT query
sql_str += " FROM `%s`.`%s`" % (self.database_name, table)
# if there's a JOIN clause attached
if kwargs.has_key('join'):
sql_str += " JOIN %s " % kwargs.get('join')
# if there's a WHERE clause attached
if kwargs.has_key('where'):
sql_str += " WHERE %s " % kwargs.get('where')
# if there's a LIMIT clause attached
if kwargs.has_key('limit'):
sql_str += " LIMIT %s " % kwargs.get('limit')
# Finalise out SQL string
sql_str += ";"
cursor = self.db.cursor()
cursor.execute(sql_str)
if named_tuples:
results = self.convert_to_named_tuples(cursor)
else:
results = cursor.fetchall()
cursor.close()
return results
def delete(self, table, **wheres):
"""
This function will allow us to delete data from a given tables
based on wether or not a WHERE clause is present or not
"""
sql_str = "DELETE FROM `%s`.`%s`" % (self.database_name, table)
if wheres is not None:
first_where_clause = True
for where, term in wheres.iteritems():
if first_where_clause:
# This is the first WHERE clause
sql_str += " WHERE `%s`.`%s` %s" % (table, where, term)
first_where_clause = False
else:
# this is the second (additional) WHERE clause so we use AND
sql_str += " AND `%s`.`%s` %s" % (table, where, term)
sql_str += ";"
cursor = self.db.cursor()
cursor.execute(sql_str)
self.db.commit()
cursor.close()
# Only needs to compile one time so we put it here
float_match = re.compile(r'[-+]?\d*\.?\d+(?:[eE][-+]?\d+)?$').match
def is_number(string):
return bool(float_match(string))
def insert(self, table, **column_names):
"""
Insert function
Example usages:-
db.insert('people', first_name='Ringo',
second_name='Starr', DOB=STR_TO_DATE('01-01-1999', '%d-%m-%Y'))
"""
sql_str = "INSERT INTO `%s`.`%s` " % (self.database_name, table)
if column_names is not None:
columns = "("
values = "("
for arg, value in column_names.iteritems():
columns += "`%s`, " % arg
# Check how we should add this to the columns string
if is_number(value) or arg == 'DOB':
# It's a number or date so we don't add the ''
values += "%s, " % value
else:
# It's a string so we add the ''
values += "5S, " % value
columns = columns[:-2] # Strip off the spare ',' from the end
values = values[:-2] # Same here too
columns += ") VALUES" # Add the connecting keyword and brace
values += ");" # Add the brace and like terminator
sql_str += "%s %s" % (columns, values)
cursor = self.db.cursor()
cursor.execute(sql_str)
self.db.commit()
cursor.close()
def update(self, table, where=None, **column_values):
sql_str = "UPDATE `%s`.`%s` SET " % (self.database_name, table)
if column_values is not None:
for column_name, value in column_names.iteritems():
sql_str += "`%s`=" % column_name
# check how we should add this to the column string
if is_number(value):
# it's a number so we don't add ''
sql_str += "%s, " % value
else:
# it's a date or string so add the ''
sql_str += "'%s', " % value
sql_str = sql_str[:-2] # strip off the last , and space character
if where:
sql_str += " WHERE %s" % where
cusrsor = self.db.cursor()
cursor.execute(sql_str)
self.db.commit()
cursor.close()
| GunnerJnr/_CodeInstitute | Stream-2/Back-End-Development/18.Using-Python-with-MySQL-Part-Three-Intro/3.How-to-Build-an-Update-SQL-String/database/mysql.py | Python | mit | 7,289 |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System;
using System.Collections;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using Xunit;
namespace System.Collections.Concurrent.Tests
{
public class ConcurrentDictionaryTests
{
[Fact]
public static void TestBasicScenarios()
{
ConcurrentDictionary<int, int> cd = new ConcurrentDictionary<int, int>();
Task[] tks = new Task[2];
tks[0] = Task.Run(() =>
{
var ret = cd.TryAdd(1, 11);
if (!ret)
{
ret = cd.TryUpdate(1, 11, 111);
Assert.True(ret);
}
ret = cd.TryAdd(2, 22);
if (!ret)
{
ret = cd.TryUpdate(2, 22, 222);
Assert.True(ret);
}
});
tks[1] = Task.Run(() =>
{
var ret = cd.TryAdd(2, 222);
if (!ret)
{
ret = cd.TryUpdate(2, 222, 22);
Assert.True(ret);
}
ret = cd.TryAdd(1, 111);
if (!ret)
{
ret = cd.TryUpdate(1, 111, 11);
Assert.True(ret);
}
});
Task.WaitAll(tks);
}
[Fact]
public static void TestAdd1()
{
TestAdd1(1, 1, 1, 10000);
TestAdd1(5, 1, 1, 10000);
TestAdd1(1, 1, 2, 5000);
TestAdd1(1, 1, 5, 2000);
TestAdd1(4, 0, 4, 2000);
TestAdd1(16, 31, 4, 2000);
TestAdd1(64, 5, 5, 5000);
TestAdd1(5, 5, 5, 2500);
}
private static void TestAdd1(int cLevel, int initSize, int threads, int addsPerThread)
{
ConcurrentDictionary<int, int> dictConcurrent = new ConcurrentDictionary<int, int>(cLevel, 1);
IDictionary<int, int> dict = dictConcurrent;
int count = threads;
using (ManualResetEvent mre = new ManualResetEvent(false))
{
for (int i = 0; i < threads; i++)
{
int ii = i;
Task.Run(
() =>
{
for (int j = 0; j < addsPerThread; j++)
{
dict.Add(j + ii * addsPerThread, -(j + ii * addsPerThread));
}
if (Interlocked.Decrement(ref count) == 0) mre.Set();
});
}
mre.WaitOne();
}
foreach (var pair in dict)
{
Assert.Equal(pair.Key, -pair.Value);
}
List<int> gotKeys = new List<int>();
foreach (var pair in dict)
gotKeys.Add(pair.Key);
gotKeys.Sort();
List<int> expectKeys = new List<int>();
int itemCount = threads * addsPerThread;
for (int i = 0; i < itemCount; i++)
expectKeys.Add(i);
Assert.Equal(expectKeys.Count, gotKeys.Count);
for (int i = 0; i < expectKeys.Count; i++)
{
Assert.True(expectKeys[i].Equals(gotKeys[i]),
String.Format("The set of keys in the dictionary is are not the same as the expected\r\n" +
"TestAdd1(cLevel={0}, initSize={1}, threads={2}, addsPerThread={3})", cLevel, initSize, threads, addsPerThread)
);
}
// Finally, let's verify that the count is reported correctly.
int expectedCount = threads * addsPerThread;
Assert.Equal(expectedCount, dict.Count);
Assert.Equal(expectedCount, dictConcurrent.ToArray().Length);
}
[Fact]
public static void TestUpdate1()
{
TestUpdate1(1, 1, 10000);
TestUpdate1(5, 1, 10000);
TestUpdate1(1, 2, 5000);
TestUpdate1(1, 5, 2001);
TestUpdate1(4, 4, 2001);
TestUpdate1(15, 5, 2001);
TestUpdate1(64, 5, 5000);
TestUpdate1(5, 5, 25000);
}
private static void TestUpdate1(int cLevel, int threads, int updatesPerThread)
{
IDictionary<int, int> dict = new ConcurrentDictionary<int, int>(cLevel, 1);
for (int i = 1; i <= updatesPerThread; i++) dict[i] = i;
int running = threads;
using (ManualResetEvent mre = new ManualResetEvent(false))
{
for (int i = 0; i < threads; i++)
{
int ii = i;
Task.Run(
() =>
{
for (int j = 1; j <= updatesPerThread; j++)
{
dict[j] = (ii + 2) * j;
}
if (Interlocked.Decrement(ref running) == 0) mre.Set();
});
}
mre.WaitOne();
}
foreach (var pair in dict)
{
var div = pair.Value / pair.Key;
var rem = pair.Value % pair.Key;
Assert.Equal(0, rem);
Assert.True(div > 1 && div <= threads+1,
String.Format("* Invalid value={3}! TestUpdate1(cLevel={0}, threads={1}, updatesPerThread={2})", cLevel, threads, updatesPerThread, div));
}
List<int> gotKeys = new List<int>();
foreach (var pair in dict)
gotKeys.Add(pair.Key);
gotKeys.Sort();
List<int> expectKeys = new List<int>();
for (int i = 1; i <= updatesPerThread; i++)
expectKeys.Add(i);
Assert.Equal(expectKeys.Count, gotKeys.Count);
for (int i = 0; i < expectKeys.Count; i++)
{
Assert.True(expectKeys[i].Equals(gotKeys[i]),
String.Format("The set of keys in the dictionary is are not the same as the expected.\r\n" +
"TestUpdate1(cLevel={0}, threads={1}, updatesPerThread={2})", cLevel, threads, updatesPerThread)
);
}
}
[Fact]
public static void TestRead1()
{
TestRead1(1, 1, 10000);
TestRead1(5, 1, 10000);
TestRead1(1, 2, 5000);
TestRead1(1, 5, 2001);
TestRead1(4, 4, 2001);
TestRead1(15, 5, 2001);
TestRead1(64, 5, 5000);
TestRead1(5, 5, 25000);
}
private static void TestRead1(int cLevel, int threads, int readsPerThread)
{
IDictionary<int, int> dict = new ConcurrentDictionary<int, int>(cLevel, 1);
for (int i = 0; i < readsPerThread; i += 2) dict[i] = i;
int count = threads;
using (ManualResetEvent mre = new ManualResetEvent(false))
{
for (int i = 0; i < threads; i++)
{
int ii = i;
Task.Run(
() =>
{
for (int j = 0; j < readsPerThread; j++)
{
int val = 0;
if (dict.TryGetValue(j, out val))
{
if (j % 2 == 1 || j != val)
{
Console.WriteLine("* TestRead1(cLevel={0}, threads={1}, readsPerThread={2})", cLevel, threads, readsPerThread);
Assert.False(true, " > FAILED. Invalid element in the dictionary.");
}
}
else
{
if (j % 2 == 0)
{
Console.WriteLine("* TestRead1(cLevel={0}, threads={1}, readsPerThread={2})", cLevel, threads, readsPerThread);
Assert.False(true, " > FAILED. Element missing from the dictionary");
}
}
}
if (Interlocked.Decrement(ref count) == 0) mre.Set();
});
}
mre.WaitOne();
}
}
[Fact]
public static void TestRemove1()
{
TestRemove1(1, 1, 10000);
TestRemove1(5, 1, 1000);
TestRemove1(1, 5, 2001);
TestRemove1(4, 4, 2001);
TestRemove1(15, 5, 2001);
TestRemove1(64, 5, 5000);
}
private static void TestRemove1(int cLevel, int threads, int removesPerThread)
{
ConcurrentDictionary<int, int> dict = new ConcurrentDictionary<int, int>(cLevel, 1);
string methodparameters = string.Format("* TestRemove1(cLevel={0}, threads={1}, removesPerThread={2})", cLevel, threads, removesPerThread);
int N = 2 * threads * removesPerThread;
for (int i = 0; i < N; i++) dict[i] = -i;
// The dictionary contains keys [0..N), each key mapped to a value equal to the key.
// Threads will cooperatively remove all even keys
int running = threads;
using (ManualResetEvent mre = new ManualResetEvent(false))
{
for (int i = 0; i < threads; i++)
{
int ii = i;
Task.Run(
() =>
{
for (int j = 0; j < removesPerThread; j++)
{
int value;
int key = 2 * (ii + j * threads);
Assert.True(dict.TryRemove(key, out value), "Failed to remove an element! " + methodparameters);
Assert.Equal(-key, value);
}
if (Interlocked.Decrement(ref running) == 0) mre.Set();
});
}
mre.WaitOne();
}
foreach (var pair in dict)
{
Assert.Equal(pair.Key, -pair.Value);
}
List<int> gotKeys = new List<int>();
foreach (var pair in dict)
gotKeys.Add(pair.Key);
gotKeys.Sort();
List<int> expectKeys = new List<int>();
for (int i = 0; i < (threads * removesPerThread); i++)
expectKeys.Add(2 * i + 1);
Assert.Equal(expectKeys.Count, gotKeys.Count);
for (int i = 0; i < expectKeys.Count; i++)
{
Assert.True(expectKeys[i].Equals(gotKeys[i]), " > Unexpected key value! " + methodparameters);
}
// Finally, let's verify that the count is reported correctly.
Assert.Equal(expectKeys.Count, dict.Count);
Assert.Equal(expectKeys.Count, dict.ToArray().Length);
}
[Fact]
public static void TestRemove2()
{
TestRemove2(1);
TestRemove2(10);
TestRemove2(5000);
}
private static void TestRemove2(int removesPerThread)
{
ConcurrentDictionary<int, int> dict = new ConcurrentDictionary<int, int>();
for (int i = 0; i < removesPerThread; i++) dict[i] = -i;
// The dictionary contains keys [0..N), each key mapped to a value equal to the key.
// Threads will cooperatively remove all even keys.
const int SIZE = 2;
int running = SIZE;
bool[][] seen = new bool[SIZE][];
for (int i = 0; i < SIZE; i++) seen[i] = new bool[removesPerThread];
using (ManualResetEvent mre = new ManualResetEvent(false))
{
for (int t = 0; t < SIZE; t++)
{
int thread = t;
Task.Run(
() =>
{
for (int key = 0; key < removesPerThread; key++)
{
int value;
if (dict.TryRemove(key, out value))
{
seen[thread][key] = true;
Assert.Equal(-key, value);
}
}
if (Interlocked.Decrement(ref running) == 0) mre.Set();
});
}
mre.WaitOne();
}
Assert.Equal(0, dict.Count);
for (int i = 0; i < removesPerThread; i++)
{
Assert.False(seen[0][i] == seen[1][i],
String.Format("> FAILED. Two threads appear to have removed the same element. TestRemove2(removesPerThread={0})", removesPerThread)
);
}
}
[Fact]
public static void TestRemove3()
{
ConcurrentDictionary<int, int> dict = new ConcurrentDictionary<int, int>();
dict[99] = -99;
ICollection<KeyValuePair<int, int>> col = dict;
// Make sure we cannot "remove" a key/value pair which is not in the dictionary
for (int i = 0; i < 200; i++)
{
if (i != 99)
{
Assert.False(col.Remove(new KeyValuePair<int, int>(i, -99)), "Should not remove not existing a key/value pair - new KeyValuePair<int, int>(i, -99)");
Assert.False(col.Remove(new KeyValuePair<int, int>(99, -i)), "Should not remove not existing a key/value pair - new KeyValuePair<int, int>(99, -i)");
}
}
// Can we remove a key/value pair successfully?
Assert.True(col.Remove(new KeyValuePair<int, int>(99, -99)), "Failed to remove existing key/value pair");
// Make sure the key/value pair is gone
Assert.False(col.Remove(new KeyValuePair<int, int>(99, -99)), "Should not remove the key/value pair which has been removed");
// And that the dictionary is empty. We will check the count in a few different ways:
Assert.Equal(0, dict.Count);
Assert.Equal(0, dict.ToArray().Length);
}
[Fact]
public static void TestGetOrAdd()
{
TestGetOrAddOrUpdate(1, 1, 1, 10000, true);
TestGetOrAddOrUpdate(5, 1, 1, 10000, true);
TestGetOrAddOrUpdate(1, 1, 2, 5000, true);
TestGetOrAddOrUpdate(1, 1, 5, 2000, true);
TestGetOrAddOrUpdate(4, 0, 4, 2000, true);
TestGetOrAddOrUpdate(16, 31, 4, 2000, true);
TestGetOrAddOrUpdate(64, 5, 5, 5000, true);
TestGetOrAddOrUpdate(5, 5, 5, 25000, true);
}
[Fact]
public static void TestAddOrUpdate()
{
TestGetOrAddOrUpdate(1, 1, 1, 10000, false);
TestGetOrAddOrUpdate(5, 1, 1, 10000, false);
TestGetOrAddOrUpdate(1, 1, 2, 5000, false);
TestGetOrAddOrUpdate(1, 1, 5, 2000, false);
TestGetOrAddOrUpdate(4, 0, 4, 2000, false);
TestGetOrAddOrUpdate(16, 31, 4, 2000, false);
TestGetOrAddOrUpdate(64, 5, 5, 5000, false);
TestGetOrAddOrUpdate(5, 5, 5, 25000, false);
}
private static void TestGetOrAddOrUpdate(int cLevel, int initSize, int threads, int addsPerThread, bool isAdd)
{
ConcurrentDictionary<int, int> dict = new ConcurrentDictionary<int, int>(cLevel, 1);
int count = threads;
using (ManualResetEvent mre = new ManualResetEvent(false))
{
for (int i = 0; i < threads; i++)
{
int ii = i;
Task.Run(
() =>
{
for (int j = 0; j < addsPerThread; j++)
{
if (isAdd)
{
//call either of the two overloads of GetOrAdd
if (j + ii % 2 == 0)
{
dict.GetOrAdd(j, -j);
}
else
{
dict.GetOrAdd(j, x => -x);
}
}
else
{
if (j + ii % 2 == 0)
{
dict.AddOrUpdate(j, -j, (k, v) => -j);
}
else
{
dict.AddOrUpdate(j, (k) => -k, (k, v) => -k);
}
}
}
if (Interlocked.Decrement(ref count) == 0) mre.Set();
});
}
mre.WaitOne();
}
foreach (var pair in dict)
{
Assert.Equal(pair.Key, -pair.Value);
}
List<int> gotKeys = new List<int>();
foreach (var pair in dict)
gotKeys.Add(pair.Key);
gotKeys.Sort();
List<int> expectKeys = new List<int>();
for (int i = 0; i < addsPerThread; i++)
expectKeys.Add(i);
Assert.Equal(expectKeys.Count, gotKeys.Count);
for (int i = 0; i < expectKeys.Count; i++)
{
Assert.True(expectKeys[i].Equals(gotKeys[i]),
String.Format("* Test '{4}': Level={0}, initSize={1}, threads={2}, addsPerThread={3})\r\n > FAILED. The set of keys in the dictionary is are not the same as the expected.",
cLevel, initSize, threads, addsPerThread, isAdd ? "GetOrAdd" : "GetOrUpdate"));
}
// Finally, let's verify that the count is reported correctly.
Assert.Equal(addsPerThread, dict.Count);
Assert.Equal(addsPerThread, dict.ToArray().Length);
}
[Fact]
public static void TestBugFix669376()
{
var cd = new ConcurrentDictionary<string, int>(new OrdinalStringComparer());
cd["test"] = 10;
Assert.True(cd.ContainsKey("TEST"), "Customized comparer didn't work");
}
private class OrdinalStringComparer : IEqualityComparer<string>
{
public bool Equals(string x, string y)
{
var xlower = x.ToLowerInvariant();
var ylower = y.ToLowerInvariant();
return string.CompareOrdinal(xlower, ylower) == 0;
}
public int GetHashCode(string obj)
{
return 0;
}
}
[Fact]
public static void TestConstructor()
{
var dictionary = new ConcurrentDictionary<int, int>(new[] { new KeyValuePair<int, int>(1, 1) });
Assert.False(dictionary.IsEmpty);
Assert.Equal(1, dictionary.Keys.Count);
Assert.Equal(1, dictionary.Values.Count);
}
[Fact]
public static void TestConstructor_Negative()
{
Assert.Throws<ArgumentNullException>(
() => new ConcurrentDictionary<int, int>((ICollection<KeyValuePair<int, int>>)null));
// "TestConstructor: FAILED. Constructor didn't throw ANE when null collection is passed");
Assert.Throws<ArgumentNullException>(
() => new ConcurrentDictionary<int, int>((IEqualityComparer<int>)null));
// "TestConstructor: FAILED. Constructor didn't throw ANE when null IEqualityComparer is passed");
Assert.Throws<ArgumentNullException>(
() => new ConcurrentDictionary<int, int>((ICollection<KeyValuePair<int, int>>)null, EqualityComparer<int>.Default));
// "TestConstructor: FAILED. Constructor didn't throw ANE when null collection and non null IEqualityComparer passed");
Assert.Throws<ArgumentNullException>(
() => new ConcurrentDictionary<int, int>(new[] { new KeyValuePair<int, int>(1, 1) }, null));
// "TestConstructor: FAILED. Constructor didn't throw ANE when non null collection and null IEqualityComparer passed");
Assert.Throws<ArgumentNullException>(
() => new ConcurrentDictionary<string, int>(new[] { new KeyValuePair<string, int>(null, 1) }));
// "TestConstructor: FAILED. Constructor didn't throw ANE when collection has null key passed");
Assert.Throws<ArgumentException>(
() => new ConcurrentDictionary<int, int>(new[] { new KeyValuePair<int, int>(1, 1), new KeyValuePair<int, int>(1, 2) }));
// "TestConstructor: FAILED. Constructor didn't throw AE when collection has duplicate keys passed");
Assert.Throws<ArgumentNullException>(
() => new ConcurrentDictionary<int, int>(1, null, EqualityComparer<int>.Default));
// "TestConstructor: FAILED. Constructor didn't throw ANE when null collection is passed");
Assert.Throws<ArgumentNullException>(
() => new ConcurrentDictionary<int, int>(1, new[] { new KeyValuePair<int, int>(1, 1) }, null));
// "TestConstructor: FAILED. Constructor didn't throw ANE when null comparer is passed");
Assert.Throws<ArgumentNullException>(
() => new ConcurrentDictionary<int, int>(1, 1, null));
// "TestConstructor: FAILED. Constructor didn't throw ANE when null comparer is passed");
Assert.Throws<ArgumentOutOfRangeException>(
() => new ConcurrentDictionary<int, int>(0, 10));
// "TestConstructor: FAILED. Constructor didn't throw AORE when <1 concurrencyLevel passed");
Assert.Throws<ArgumentOutOfRangeException>(
() => new ConcurrentDictionary<int, int>(-1, 0));
// "TestConstructor: FAILED. Constructor didn't throw AORE when < 0 capacity passed");
}
[Fact]
public static void TestExceptions()
{
var dictionary = new ConcurrentDictionary<string, int>();
Assert.Throws<ArgumentNullException>(
() => dictionary.TryAdd(null, 0));
// "TestExceptions: FAILED. TryAdd didn't throw ANE when null key is passed");
Assert.Throws<ArgumentNullException>(
() => dictionary.ContainsKey(null));
// "TestExceptions: FAILED. Contains didn't throw ANE when null key is passed");
int item;
Assert.Throws<ArgumentNullException>(
() => dictionary.TryRemove(null, out item));
// "TestExceptions: FAILED. TryRmove didn't throw ANE when null key is passed");
Assert.Throws<ArgumentNullException>(
() => dictionary.TryGetValue(null, out item));
// "TestExceptions: FAILED. TryGetValue didn't throw ANE when null key is passed");
Assert.Throws<ArgumentNullException>(
() => { var x = dictionary[null]; });
// "TestExceptions: FAILED. this[] didn't throw ANE when null key is passed");
Assert.Throws<KeyNotFoundException>(
() => { var x = dictionary["1"]; });
// "TestExceptions: FAILED. this[] TryGetValue didn't throw KeyNotFoundException!");
Assert.Throws<ArgumentNullException>(
() => dictionary[null] = 1);
// "TestExceptions: FAILED. this[] didn't throw ANE when null key is passed");
Assert.Throws<ArgumentNullException>(
() => dictionary.GetOrAdd(null, (k) => 0));
// "TestExceptions: FAILED. GetOrAdd didn't throw ANE when null key is passed");
Assert.Throws<ArgumentNullException>(
() => dictionary.GetOrAdd("1", null));
// "TestExceptions: FAILED. GetOrAdd didn't throw ANE when null valueFactory is passed");
Assert.Throws<ArgumentNullException>(
() => dictionary.GetOrAdd(null, 0));
// "TestExceptions: FAILED. GetOrAdd didn't throw ANE when null key is passed");
Assert.Throws<ArgumentNullException>(
() => dictionary.AddOrUpdate(null, (k) => 0, (k, v) => 0));
// "TestExceptions: FAILED. AddOrUpdate didn't throw ANE when null key is passed");
Assert.Throws<ArgumentNullException>(
() => dictionary.AddOrUpdate("1", null, (k, v) => 0));
// "TestExceptions: FAILED. AddOrUpdate didn't throw ANE when null updateFactory is passed");
Assert.Throws<ArgumentNullException>(
() => dictionary.AddOrUpdate(null, (k) => 0, null));
// "TestExceptions: FAILED. AddOrUpdate didn't throw ANE when null addFactory is passed");
dictionary.TryAdd("1", 1);
Assert.Throws<ArgumentException>(
() => ((IDictionary<string, int>)dictionary).Add("1", 2));
// "TestExceptions: FAILED. IDictionary didn't throw AE when duplicate key is passed");
}
[Fact]
public static void TestIDictionary()
{
IDictionary dictionary = new ConcurrentDictionary<string, int>();
Assert.False(dictionary.IsReadOnly);
foreach (var entry in dictionary)
{
Assert.False(true, "TestIDictionary: FAILED. GetEnumerator retuned items when the dictionary is empty");
}
const int SIZE = 10;
for (int i = 0; i < SIZE; i++)
dictionary.Add(i.ToString(), i);
Assert.Equal(SIZE, dictionary.Count);
//test contains
Assert.False(dictionary.Contains(1), "TestIDictionary: FAILED. Contain retuned true for incorrect key type");
Assert.False(dictionary.Contains("100"), "TestIDictionary: FAILED. Contain retuned true for incorrect key");
Assert.True(dictionary.Contains("1"), "TestIDictionary: FAILED. Contain retuned false for correct key");
//test GetEnumerator
int count = 0;
foreach (var obj in dictionary)
{
DictionaryEntry entry = (DictionaryEntry)obj;
string key = (string)entry.Key;
int value = (int)entry.Value;
int expectedValue = int.Parse(key);
Assert.True(value == expectedValue,
String.Format("TestIDictionary: FAILED. Unexpected value returned from GetEnumerator, expected {0}, actual {1}", value, expectedValue));
count++;
}
Assert.Equal(SIZE, count);
Assert.Equal(SIZE, dictionary.Keys.Count);
Assert.Equal(SIZE, dictionary.Values.Count);
//Test Remove
dictionary.Remove("9");
Assert.Equal(SIZE - 1, dictionary.Count);
//Test this[]
for (int i = 0; i < dictionary.Count; i++)
Assert.Equal(i, (int)dictionary[i.ToString()]);
dictionary["1"] = 100; // try a valid setter
Assert.Equal(100, (int)dictionary["1"]);
//nonsexist key
Assert.Null(dictionary["NotAKey"]);
}
[Fact]
public static void TestIDictionary_Negative()
{
IDictionary dictionary = new ConcurrentDictionary<string, int>();
Assert.Throws<ArgumentNullException>(
() => dictionary.Add(null, 1));
// "TestIDictionary: FAILED. Add didn't throw ANE when null key is passed");
Assert.Throws<ArgumentException>(
() => dictionary.Add(1, 1));
// "TestIDictionary: FAILED. Add didn't throw AE when incorrect key type is passed");
Assert.Throws<ArgumentException>(
() => dictionary.Add("1", "1"));
// "TestIDictionary: FAILED. Add didn't throw AE when incorrect value type is passed");
Assert.Throws<ArgumentNullException>(
() => dictionary.Contains(null));
// "TestIDictionary: FAILED. Contain didn't throw ANE when null key is passed");
//Test Remove
Assert.Throws<ArgumentNullException>(
() => dictionary.Remove(null));
// "TestIDictionary: FAILED. Remove didn't throw ANE when null key is passed");
//Test this[]
Assert.Throws<ArgumentNullException>(
() => { object val = dictionary[null]; });
// "TestIDictionary: FAILED. this[] getter didn't throw ANE when null key is passed");
Assert.Throws<ArgumentNullException>(
() => dictionary[null] = 0);
// "TestIDictionary: FAILED. this[] setter didn't throw ANE when null key is passed");
Assert.Throws<ArgumentException>(
() => dictionary[1] = 0);
// "TestIDictionary: FAILED. this[] setter didn't throw AE when invalid key type is passed");
Assert.Throws<ArgumentException>(
() => dictionary["1"] = "0");
// "TestIDictionary: FAILED. this[] setter didn't throw AE when invalid value type is passed");
}
[Fact]
public static void TestICollection()
{
ICollection dictionary = new ConcurrentDictionary<int, int>();
Assert.False(dictionary.IsSynchronized, "TestICollection: FAILED. IsSynchronized returned true!");
int key = -1;
int value = +1;
//add one item to the dictionary
((ConcurrentDictionary<int, int>)dictionary).TryAdd(key, value);
var objectArray = new Object[1];
dictionary.CopyTo(objectArray, 0);
Assert.Equal(key, ((KeyValuePair<int, int>)objectArray[0]).Key);
Assert.Equal(value, ((KeyValuePair<int, int>)objectArray[0]).Value);
var keyValueArray = new KeyValuePair<int, int>[1];
dictionary.CopyTo(keyValueArray, 0);
Assert.Equal(key, keyValueArray[0].Key);
Assert.Equal(value, keyValueArray[0].Value);
var entryArray = new DictionaryEntry[1];
dictionary.CopyTo(entryArray, 0);
Assert.Equal(key, (int)entryArray[0].Key);
Assert.Equal(value, (int)entryArray[0].Value);
}
[Fact]
public static void TestICollection_Negative()
{
ICollection dictionary = new ConcurrentDictionary<int, int>();
Assert.False(dictionary.IsSynchronized, "TestICollection: FAILED. IsSynchronized returned true!");
Assert.Throws<NotSupportedException>(() => { var obj = dictionary.SyncRoot; });
// "TestICollection: FAILED. SyncRoot property didn't throw");
Assert.Throws<ArgumentNullException>(() => dictionary.CopyTo(null, 0));
// "TestICollection: FAILED. CopyTo didn't throw ANE when null Array is passed");
Assert.Throws<ArgumentOutOfRangeException>(() => dictionary.CopyTo(new object[] { }, -1));
// "TestICollection: FAILED. CopyTo didn't throw AORE when negative index passed");
//add one item to the dictionary
((ConcurrentDictionary<int, int>)dictionary).TryAdd(1, 1);
Assert.Throws<ArgumentException>(() => dictionary.CopyTo(new object[] { }, 0));
// "TestICollection: FAILED. CopyTo didn't throw AE when the Array size is smaller than the dictionary count");
}
[Fact]
public static void TestClear()
{
var dictionary = new ConcurrentDictionary<int, int>();
for (int i = 0; i < 10; i++)
dictionary.TryAdd(i, i);
Assert.Equal(10, dictionary.Count);
dictionary.Clear();
Assert.Equal(0, dictionary.Count);
int item;
Assert.False(dictionary.TryRemove(1, out item), "TestClear: FAILED. TryRemove succeeded after Clear");
Assert.True(dictionary.IsEmpty, "TestClear: FAILED. IsEmpty returned false after Clear");
}
public static void TestTryUpdate()
{
var dictionary = new ConcurrentDictionary<string, int>();
Assert.Throws<ArgumentNullException>(
() => dictionary.TryUpdate(null, 0, 0));
// "TestTryUpdate: FAILED. TryUpdte didn't throw ANE when null key is passed");
for (int i = 0; i < 10; i++)
dictionary.TryAdd(i.ToString(), i);
for (int i = 0; i < 10; i++)
{
Assert.True(dictionary.TryUpdate(i.ToString(), i + 1, i), "TestTryUpdate: FAILED. TryUpdate failed!");
Assert.Equal(i + 1, dictionary[i.ToString()]);
}
//test TryUpdate concurrently
dictionary.Clear();
for (int i = 0; i < 1000; i++)
dictionary.TryAdd(i.ToString(), i);
var mres = new ManualResetEventSlim();
Task[] tasks = new Task[10];
ThreadLocal<ThreadData> updatedKeys = new ThreadLocal<ThreadData>(true);
for (int i = 0; i < tasks.Length; i++)
{
// We are creating the Task using TaskCreationOptions.LongRunning because...
// there is no guarantee that the Task will be created on another thread.
// There is also no guarantee that using this TaskCreationOption will force
// it to be run on another thread.
tasks[i] = Task.Factory.StartNew((obj) =>
{
mres.Wait();
int index = (((int)obj) + 1) + 1000;
updatedKeys.Value = new ThreadData();
updatedKeys.Value.ThreadIndex = index;
for (int j = 0; j < dictionary.Count; j++)
{
if (dictionary.TryUpdate(j.ToString(), index, j))
{
if (dictionary[j.ToString()] != index)
{
updatedKeys.Value.Succeeded = false;
return;
}
updatedKeys.Value.Keys.Add(j.ToString());
}
}
}, i, CancellationToken.None, TaskCreationOptions.LongRunning, TaskScheduler.Default);
}
mres.Set();
Task.WaitAll(tasks);
int numberSucceeded = 0;
int totalKeysUpdated = 0;
foreach (var threadData in updatedKeys.Values)
{
totalKeysUpdated += threadData.Keys.Count;
if (threadData.Succeeded)
numberSucceeded++;
}
Assert.True(numberSucceeded == tasks.Length, "One or more threads failed!");
Assert.True(totalKeysUpdated == dictionary.Count,
String.Format("TestTryUpdate: FAILED. The updated keys count doesn't match the dictionary count, expected {0}, actual {1}", dictionary.Count, totalKeysUpdated));
foreach (var value in updatedKeys.Values)
{
for (int i = 0; i < value.Keys.Count; i++)
Assert.True(dictionary[value.Keys[i]] == value.ThreadIndex,
String.Format("TestTryUpdate: FAILED. The updated value doesn't match the thread index, expected {0} actual {1}", value.ThreadIndex, dictionary[value.Keys[i]]));
}
//test TryUpdate with non atomic values (intPtr > 8)
var dict = new ConcurrentDictionary<int, Struct16>();
dict.TryAdd(1, new Struct16(1, -1));
Assert.True(dict.TryUpdate(1, new Struct16(2, -2), new Struct16(1, -1)), "TestTryUpdate: FAILED. TryUpdte failed for non atomic values ( > 8 bytes)");
}
#region Helper Classes and Methods
private class ThreadData
{
public int ThreadIndex;
public bool Succeeded = true;
public List<string> Keys = new List<string>();
}
private struct Struct16 : IEqualityComparer<Struct16>
{
public long L1, L2;
public Struct16(long l1, long l2)
{
L1 = l1;
L2 = l2;
}
public bool Equals(Struct16 x, Struct16 y)
{
return x.L1 == y.L1 && x.L2 == y.L2;
}
public int GetHashCode(Struct16 obj)
{
return (int)L1;
}
}
#endregion
}
}
| FiveTimesTheFun/corefx | src/System.Collections.Concurrent/tests/ConcurrentDictionaryTests.cs | C# | mit | 37,935 |
/**
* The MIT License
* Copyright (c) 2003 David G Jones
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package info.dgjones.st2x.transform.method.intra;
import java.util.List;
import info.dgjones.st2x.ClassParser;
import info.dgjones.st2x.JavaMethod;
import info.dgjones.st2x.javatoken.JavaCallStart;
import info.dgjones.st2x.javatoken.JavaIdentifier;
import info.dgjones.st2x.javatoken.JavaKeyword;
import info.dgjones.st2x.javatoken.JavaToken;
import info.dgjones.st2x.transform.method.AbstractMethodBodyTransformation;
import info.dgjones.st2x.transform.tokenmatcher.TokenMatcher;
import info.dgjones.st2x.transform.tokenmatcher.TokenMatcherFactory;
public class TransformCreateCall extends AbstractMethodBodyTransformation {
public TransformCreateCall() {
super();
}
public TransformCreateCall(TokenMatcherFactory factory) {
super(factory);
}
protected TokenMatcher matchers(TokenMatcherFactory factory) {
return factory.token(JavaCallStart.class, "create.*");
}
protected int transform(JavaMethod javaMethod, List tokens, int i) {
JavaCallStart call = (JavaCallStart)tokens.get(i);
if (ClassParser.NON_CONSTRUCTORS.contains(call.value)) {
return i;
}
if (i > 0 && (tokens.get(i - 1) instanceof JavaIdentifier)) {
JavaToken token = (JavaToken) tokens.get(i - 1);
if (token.value.equals("super")) {
return i;
} else if (token.value.equals(javaMethod.javaClass.className) && javaMethod.isConstructor()) {
call.value = "this";
tokens.remove(i-1);
return i-1;
}
call.value = token.value;
tokens.remove(i - 1);
tokens.add(i - 1, new JavaKeyword("new"));
} else if (javaMethod.isConstructor()) {
call.value = "this";
} else {
call.value = javaMethod.javaClass.className;
tokens.add(i, new JavaKeyword("new"));
}
return i;
}
}
| jonesd/st2x | src/main/java/info/dgjones/st2x/transform/method/intra/TransformCreateCall.java | Java | mit | 2,846 |
"""
https://codility.com/programmers/task/equi_leader/
"""
from collections import Counter, defaultdict
def solution(A):
def _is_equi_leader(i):
prefix_count_top = running_counts[top]
suffix_count_top = total_counts[top] - prefix_count_top
return (prefix_count_top * 2 > i + 1) and (suffix_count_top * 2 > len(A) - i - 1)
total_counts = Counter(A)
running_counts = defaultdict(int)
top = A[0]
result = 0
for i in xrange(len(A) - 1):
n = A[i]
running_counts[n] += 1
top = top if running_counts[top] >= running_counts[n] else n
if _is_equi_leader(i):
result += 1
return result
| py-in-the-sky/challenges | codility/equi_leader.py | Python | mit | 707 |
package soa
import (
"encoding/json"
"fmt"
"strconv"
"time"
"github.com/Shark/powerdns-consul/backend/store"
)
type soaEntry struct {
NameServer string
EmailAddr string
Sn uint32
Refresh int32
Retry int32
Expiry int32
Nx int32
}
type soaRevision struct {
SnModifyIndex uint64
SnDate int
SnVersion uint32
}
type GeneratorConfig struct {
SoaNameServer string
SoaEmailAddr string
SoaRefresh int32
SoaRetry int32
SoaExpiry int32
SoaNx int32
DefaultTTL uint32
}
type Generator struct {
cfg *GeneratorConfig
currentTime time.Time
}
func NewGenerator(cfg *GeneratorConfig, currentTime time.Time) *Generator {
return &Generator{cfg, currentTime}
}
func (g *Generator) RetrieveOrCreateSOAEntry(kv store.Store, zone string) (entry *store.Entry, err error) {
tries := 3
for tries > 0 {
entry, err = g.tryToRetrieveOrCreateSOAEntry(kv, zone)
if err != nil {
return nil, err
}
if entry != nil {
return entry, err
}
tries--
}
return nil, nil
}
func (g *Generator) tryToRetrieveOrCreateSOAEntry(kv store.Store, zone string) (entry *store.Entry, err error) {
prefix := fmt.Sprintf("zones/%s", zone)
pairs, err := kv.List(prefix)
if err != nil {
return nil, err
}
var lastModifyIndex uint64
for _, pair := range pairs {
if lastModifyIndex == 0 || pair.LastIndex() > lastModifyIndex {
lastModifyIndex = pair.LastIndex()
}
}
key := fmt.Sprintf("soa/%s", zone)
revEntryPair, err := kv.Get(key)
if err != nil && err != store.ErrKeyNotFound {
return nil, err
}
rev := soaRevision{}
if revEntryPair != nil { // use existing revision
err = json.Unmarshal(revEntryPair.Value(), &rev)
if err != nil {
return nil, err
}
if rev.SnModifyIndex != lastModifyIndex {
// update the modify index
rev.SnModifyIndex = lastModifyIndex
curSnDate := getDateFormatted(g.currentTime)
if rev.SnDate != curSnDate {
rev.SnDate = curSnDate
rev.SnVersion = 0
} else {
// TODO: what about SnVersion > 99?
rev.SnVersion += 1
}
} // else nothing to do
} else { // create a new revision
rev.SnDate = getDateFormatted(g.currentTime)
rev.SnVersion = 0
rev.SnModifyIndex = lastModifyIndex
}
json, err := json.Marshal(rev)
if err != nil {
return nil, err
}
ok, _, err := kv.AtomicPut(key, json, revEntryPair, nil)
if err != nil || !ok {
return nil, err
}
soa := &soaEntry{NameServer: g.cfg.SoaNameServer,
EmailAddr: g.cfg.SoaEmailAddr,
Sn: formatSoaSn(rev.SnDate, rev.SnVersion),
Refresh: g.cfg.SoaRefresh,
Retry: g.cfg.SoaRetry,
Expiry: g.cfg.SoaExpiry,
Nx: g.cfg.SoaNx}
soaAsEntry := formatSoaEntry(soa, g.cfg.DefaultTTL)
return soaAsEntry, nil
}
func formatSoaSn(snDate int, snVersion uint32) (sn uint32) {
soaSnString := fmt.Sprintf("%d%02d", snDate, snVersion)
soaSnInt, err := strconv.Atoi(soaSnString)
if err != nil {
panic("error generating SoaSn")
}
return uint32(soaSnInt)
}
func formatSoaEntry(sEntry *soaEntry, ttl uint32) *store.Entry {
value := fmt.Sprintf("%s %s %d %d %d %d %d", sEntry.NameServer, sEntry.EmailAddr, sEntry.Sn, sEntry.Refresh, sEntry.Retry, sEntry.Expiry, sEntry.Nx)
return &store.Entry{"SOA", ttl, value}
}
func getDateFormatted(time time.Time) int {
formattedMonthString := fmt.Sprintf("%02d", time.Month())
formattedDayString := fmt.Sprintf("%02d", time.Day())
dateString := fmt.Sprintf("%d%s%s", time.Year(), formattedMonthString, formattedDayString)
date, err := strconv.Atoi(dateString)
if err != nil {
return 0
}
return date
}
| Shark/powerdns-consul | backend/soa/generator.go | GO | mit | 3,613 |
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
namespace Pb.TileMap
{
/// <summary>
/// Base class for chunk renderers
/// </summary>
[System.Serializable]
public class ChunkRenderer :
ScriptableObject
{
/// <summary>
/// Renders a chunk with a tile map controller, chunk, and chunk game object.
/// All created objects should either be components on the chunk game object or children of it.
/// Creating game objects elsewhere will not allow them to be destroyed when the chunk is unloaded.
/// </summary>
/// <param name="tmc">The TileMapController loading the chunk</param>
/// <param name="chunk">The chunk being rendered</param>
/// <param name="chunk_go">The game object made for the chunk</param>
/// <returns>Whether the chunk was rendered</returns>
public virtual bool Render(TileMapController tmc, Chunk chunk, GameObject chunk_go)
{
return false;
}
}
} | djkoloski/pb | Assets/Pb/TileMap/ChunkRenderer.cs | C# | mit | 932 |
class Cd
@@all_Cds = {}
attr_accessor :name, :artist
def initialize(attributes)
@name = attributes[:album_name]
@artist = attributes[:artist_name]
end
def self.all
output_Cds = []
@@all_Cds.each_value do |album|
output_Cds << album
end
output_Cds
end
def save
@@all_Cds[@name] = self
end
def self.search_album_names(name)
output_Cds = []
name = name.downcase
@@all_Cds.each_value do |album|
if album.name.downcase.include? name
output_Cds << album
end
end
output_Cds
end
def self.search_artist_names(name)
output_Cds = []
name = name.downcase
@@all_Cds.each_value do |album|
if album.artist.downcase.include? name
output_Cds << album
end
end
output_Cds
end
def ==(album)
self.name == album.name && self.artist == album.artist
end
end | dianedouglas/CD-Organizer | lib/cd.rb | Ruby | mit | 897 |
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("Mantle.Hosting.WindowsServices")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("Mantle.Hosting.WindowsServices")]
[assembly: AssemblyCopyright("Copyright © 2013")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("0b326e33-cab6-4469-bd97-56857458025b")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| caseywatson/Mantle | v0/Mantle/Mantle.Hosting.WindowsServices/Properties/AssemblyInfo.cs | C# | mit | 1,436 |
class Api::CodeController < Api::BaseController
def create
@code = Code.new
@code.save
end
def status
@success = false
if !params.has_key?(:id) || !params.has_key?(:hash)
return
end
hash = Digest::SHA1.hexdigest "#{params[:id]}#{Rails.application.secrets.twitch_client_secret}"
puts hash
if hash != params[:hash]
return
end
@code = Code.where(:code => params[:id]).first
if @code == nil
return
end
@success = true
end
end
| jameseunson/twitchy-backend | app/controllers/api/code_controller.rb | Ruby | mit | 470 |
package ie.lc.fallApp;
import java.text.DecimalFormat;
import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.text.Editable;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.*;
public class ActivityFallHeight extends Activity
{
private double persistentRandomNumber;
private static final String persistentRandomNumberKey = "prn";
private final int planetRequestCode = 1337;
private final Interlock fieldInterlock = new Interlock();
protected void onCreate( Bundle savedInstanceState ) {
super.onCreate( savedInstanceState );
setContentView( R.layout.activity_fall );
setupActions();
persistentRandomNumber = Math.random() * 10.0;
}
protected void onSaveInstanceState( Bundle out ) {
out.putDouble( persistentRandomNumberKey, persistentRandomNumber );
showToastMessage( "Saved instance variable: " + persistentRandomNumber );
}
protected void onRestoreInstanceState( Bundle in ) {
persistentRandomNumber = in.getDouble( persistentRandomNumberKey );
showToastMessage( "Restored instance variable: " + persistentRandomNumber );
}
protected void onActivityResult( int requestCode, int resultCode, Intent data ) {
if (requestCode == planetRequestCode
&& resultCode == RESULT_OK) {
Bundle extras = data.getExtras();
Planet selectedPlanet = (Planet) extras.getSerializable( Common.planetSelectIdentifier );
Planet activePlanet = Physics.getActivePlanet();
if ( ! selectedPlanet.equals(activePlanet)) {
Physics.setActivePlanet( selectedPlanet );
showToastMessage( getString(R.string.planetChanged) + " " + selectedPlanet + "." );
updateDisplayedHeightFromVelocity();
}
}
}
public boolean onCreateOptionsMenu( Menu menu ) {
getMenuInflater().inflate( R.menu.fall_height, menu );
return true;
}
/** Used by computeAndShow */
private interface ComputeCallback {
double execute( String textInput ) throws NumberFormatException;
}
private void computeAndShow( EditText targetField, String textInput, ComputeCallback comp ) {
if ( ! fieldInterlock.isLocked()) {
fieldInterlock.setLocked( true );
String textOutput = "";
try {
double num = comp.execute( textInput );
textOutput = formatTwoDecimalPlaces( num );
}
catch (Exception ex) {
// Ducked
}
targetField.setText( textOutput );
fieldInterlock.setLocked( false );
}
}
private void setupActions() {
final EditText velocityField = (EditText) findViewById( R.id.velocityField );
final EditText heightField = (EditText) findViewById( R.id.heightField );
final Button optionsButton = (Button) findViewById( R.id.optionsButton );
final Button showBigButton = (Button) findViewById( R.id.showBigButton );
velocityField.addTextChangedListener( new TextWatcherAdapter() {
public void afterTextChanged( Editable e ) {
computeAndShow( heightField, e.toString(), new ComputeCallback() {
public double execute( String textInput ) throws NumberFormatException {
double vKmh = Double.parseDouble( textInput );
double vMps = Physics.kilometresPerHourToMetresPerSec( vKmh );
return Physics.computeEquivalentFallHeight( vMps );
}
});
}
});
heightField.addTextChangedListener( new TextWatcherAdapter() {
public void afterTextChanged( Editable e ) {
computeAndShow( velocityField, e.toString(), new ComputeCallback() {
public double execute( String textInput ) throws NumberFormatException {
double height = Double.parseDouble( textInput );
double vMps = Physics.computeEquivalentVelocity( height );
return Physics.metresPerSecToKilometresPerHour( vMps );
}
});
}
});
optionsButton.setOnClickListener( new OnClickListener() {
public void onClick( View v ) {
Intent intent = new Intent( ActivityFallHeight.this, ActivityOptions.class );
intent.putExtra( Common.planetSelectIdentifier, Physics.getActivePlanet() );
startActivityForResult( intent, planetRequestCode );
}
});
showBigButton.setOnClickListener( new OnClickListener() {
public void onClick( View v ) {
Intent intent = new Intent( ActivityFallHeight.this, ActivityDisplay.class );
intent.putExtra( Common.displayHeightIdentifier, heightField.getText().toString() );
startActivity( intent );
}
});
}
private void updateDisplayedHeightFromVelocity() {
final EditText velocityField = (EditText) findViewById( R.id.velocityField );
velocityField.setText( velocityField.getText() ); // Triggers event.
}
private static String formatTwoDecimalPlaces( double num ) {
DecimalFormat f = new DecimalFormat( "0.00" );
return f.format( num );
}
private void showToastMessage( String str ) {
Toast.makeText( this, str, Toast.LENGTH_SHORT ).show();
}
}
| LeeCIT/FallApp | FallApp/src/ie/lc/fallApp/ActivityFallHeight.java | Java | mit | 5,073 |
/*global window*/
(function($){
'use strict';
var Observable = function(){
this.observers = {};
};
Observable.prototype.on = function(event, observer){
(this.observers[event] = this.observers[event] || []).push(observer);
};
Observable.prototype.emit = function(event){
var args = Array.prototype.slice.call(arguments, 1);
(this.observers[event] || []).forEach(function(observer){
observer.apply(this, args);
}.bind(this));
};
var Model = $.Model = function(alpha){
Observable.call(this);
this._alpha = alpha || 30;
};
Model.prototype = Object.create(Observable.prototype);
Model.prototype.constructor = Model;
Model.prototype.alpha = function(alpha){
this._alpha = alpha || this._alpha;
if (alpha !== undefined) {
this.emit('alpha', this._alpha);
}
return this._alpha;
};
var Step = function(){};
Step.prototype.description = function(){
return this.type + this.x + ',' + this.y;
};
var MoveTo = function(x, y){
Step.call(this);
this.type = 'M';
this.x = x;
this.y = y;
};
MoveTo.prototype = Object.create(Step.prototype);
MoveTo.prototype.constructor = MoveTo;
var LineTo = function(x, y){
Step.call(this);
this.type = 'L';
this.x = x;
this.y = y;
};
LineTo.prototype = Object.create(Step.prototype);
LineTo.prototype.constructor = LineTo;
var HalfCircleTo = function(x, y, r, direction) {
Step.call(this);
this.type = 'A';
this.x = x;
this.y = y;
this.r = r;
this.direction = direction;
};
HalfCircleTo.prototype = Object.create(Step.prototype);
HalfCircleTo.prototype.constructor = HalfCircleTo;
HalfCircleTo.prototype.description = function(){
return [
this.type,
this.r + ',' + this.r,
0,
'0,' + (this.direction === -1 ? 1: 0),
this.x + ',' + this.y
].join(' ');
};
var ControlPoints = $.ControlPoints = function(model, direction, x, y){
Observable.call(this);
this.model = model;
this.direction = direction;
this.x = x;
this.y = y;
this.model.on('alpha', this.signal.bind(this));
};
ControlPoints.prototype = Object.create(Observable.prototype);
ControlPoints.prototype.constructor = ControlPoints;
ControlPoints.prototype.signal = function(){
this.emit('controlpoints', this.controlPoints());
};
ControlPoints.prototype.controlPoints = function(){
var alpha = this.model.alpha() * Math.PI / 180;
var sinAlpha = Math.sin(alpha);
var coefficient = 1/2 * sinAlpha * (1 - sinAlpha);
var ab = this.y/(1 + coefficient);
var w = ab * 1/2 * Math.sin(2 * alpha);
var h = ab * 1/2 * Math.cos(2 * alpha);
var r = ab * 1/2 * sinAlpha;
var points = [
new MoveTo(this.x, this.y),
new LineTo(this.x + this.direction * w, this.y - ab/2 - h),
new HalfCircleTo(this.x, this.y - ab, r, this.direction),
];
var n=10;
var ds = ab/n;
var dw = ds * 1/2 * Math.tan(alpha);
for (var index = 0; index < n; index++) {
points.push(new LineTo(this.x + dw, this.y - ab + (index + 1/2) * ds));
points.push(new LineTo(this.x, this.y - ab + (index + 1) * ds));
}
return points;
};
var View = $.View = function(model, path){
this.model = model;
this.path = path;
this.update();
};
View.prototype.update = function(){
this.path.setAttribute('d', this.description());
};
View.prototype.description = function(){
return this.model.controlPoints().map(function(point){
return point.description();
}).join('');
};
})(window.heart = window.heart || {});
| dvberkel/rails.girls.utrecht.2015 | js/heart.js | JavaScript | mit | 4,014 |
<?php
namespace Database\Seeders;
use Illuminate\Database\Seeder;
class DatabaseSeeder extends Seeder
{
public function run(): void
{
$this->call(SeasonsTableSeeder::class);
$this->call(CompetitionsTableSeeder::class);
$this->call(DivisionsTableSeeder::class);
$this->call(VenuesTableSeeder::class);
$this->call(ClubsTableSeeder::class);
$this->call(TeamsTableSeeder::class);
$this->call(DivisionsTeamsTableSeeder::class);
$this->call(FixturesTableSeeder::class);
$this->call(RolesAndPermissionsSeeder::class);
$this->call(UsersTableSeeder::class);
}
}
| troccoli/lva | database/seeders/DatabaseSeeder.php | PHP | mit | 653 |
import root from './_root.js';
import toString from './toString.js';
/* Built-in method references for those with the same name as other `lodash` methods. */
var nativeParseInt = root.parseInt;
/**
* Converts `string` to an integer of the specified radix. If `radix` is
* `undefined` or `0`, a `radix` of `10` is used unless `value` is a
* hexadecimal, in which case a `radix` of `16` is used.
*
* **Note:** This method aligns with the
* [ES5 implementation](https://es5.github.io/#x15.1.2.2) of `parseInt`.
*
* @static
* @memberOf _
* @since 1.1.0
* @category String
* @param {string} string The string to convert.
* @param {number} [radix=10] The radix to interpret `value` by.
* @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`.
* @returns {number} Returns the converted integer.
* @example
*
* _.parseInt('08');
* // => 8
*
* _.map(['6', '08', '10'], _.parseInt);
* // => [6, 8, 10]
*/
function parseInt(string, radix, guard) {
if (guard || radix == null) {
radix = 0;
} else if (radix) {
radix = +radix;
}
return nativeParseInt(toString(string), radix || 0);
}
export default parseInt;
| jintoppy/react-training | step9-redux/node_modules/lodash-es/parseInt.js | JavaScript | mit | 1,161 |
<?php
return array (
'id' => 'htc_sensation_ver1',
'fallback' => 'htc_pyramid_ver1',
'capabilities' =>
array (
'uaprof' => 'http://www.htcmms.com.tw/Android/Common/PG58/ua-profile.xml',
'model_name' => 'Z710',
'brand_name' => 'HTC',
'marketing_name' => 'Sensation',
'release_date' => '2011_june',
'table_support' => 'true',
'wml_1_1' => 'true',
'columns' => '25',
'max_image_width' => '360',
'rows' => '21',
'resolution_width' => '540',
'resolution_height' => '960',
'max_image_height' => '640',
'jpg' => 'true',
'gif' => 'true',
'bmp' => 'true',
'png' => 'true',
'colors' => '65536',
'streaming_vcodec_h263_0' => '45',
'streaming_vcodec_h264_bp' => '1',
'streaming_vcodec_mpeg4_sp' => '0',
'wap_push_support' => 'true',
'mms_png' => 'true',
'mms_max_size' => '307200',
'mms_max_width' => '3264',
'mms_max_height' => '1840',
'mms_gif_static' => 'true',
'mms_wav' => 'true',
'mms_vcard' => 'true',
'mms_midi_monophonic' => 'true',
'mms_bmp' => 'true',
'mms_wbmp' => 'true',
'mms_amr' => 'true',
'mms_jpeg_baseline' => 'true',
'wav' => 'true',
'mp3' => 'true',
'amr' => 'true',
'midi_monophonic' => 'true',
'imelody' => 'true',
),
);
| cuckata23/wurfl-data | data/htc_sensation_ver1.php | PHP | mit | 1,299 |
# encoding: utf-8
module Axiom
class Optimizer
class Aggregate
# Abstract base class representing Maximum optimizations
class Maximum < self
Axiom::Aggregate::Maximum.optimizer = chain(
UnoptimizedOperand
)
end # class Maximum
end # class Aggregate
end # class Optimizer
end # module Axiom
| dkubb/axiom-optimizer | lib/axiom/optimizer/aggregate/maximum.rb | Ruby | mit | 350 |
import $ from 'jquery';
module.exports = function(root) {
root = root ? root : global;
root.expect = root.chai.expect;
root.$ = $;
beforeEach(() => {
// Using these globally-available Sinon features is preferrable, as they're
// automatically restored for you in the subsequent `afterEach`
root.sandbox = root.sinon.sandbox.create();
root.stub = root.sandbox.stub.bind(root.sandbox);
root.spy = root.sandbox.spy.bind(root.sandbox);
root.mock = root.sandbox.mock.bind(root.sandbox);
root.useFakeTimers = root.sandbox.useFakeTimers.bind(root.sandbox);
root.useFakeXMLHttpRequest = root.sandbox.useFakeXMLHttpRequest.bind(root.sandbox);
root.useFakeServer = root.sandbox.useFakeServer.bind(root.sandbox);
});
afterEach(() => {
delete root.stub;
delete root.spy;
root.sandbox.restore();
});
};
| atd/cartodb.js | test/setup/setup.js | JavaScript | mit | 855 |
const mongoose = require('mongoose');
const UserModel = mongoose.model('User');
module.exports = {
login: (email, password) => {
return UserModel.findOne({email, password});
}
}; | Spardevil/angular-crm | server/server/services/auth.service.js | JavaScript | mit | 184 |
# encoding: utf-8
require 'rubygems'
require 'file_manager'
class SeriesMonitor
DEFAULT_INTERVAL = 7200
attr_accessor :interval
attr_accessor :notification_callback
def initialize(parser)
@parser = parser
end
def call_notification_callback(message, link = nil)
if notification_callback
notification_callback.call(message, link)
end
end
def notify(title, link)
puts "Episode available: #{title}"
call_notification_callback("Novo episódio disponível: #{title}", link)
end
def notifyError(message)
msg = "An error ocurred: #{message}"
puts msg
call_notification_callback msg
end
def start
#Creates file manager
file_manager = FileManager.new @parser.get_name
while true
begin
@parser.parse
#Obtains id of last published post
last_id = @parser.get_last_post_id
#Obtains last retrieved id
last_stored_id = file_manager.get_last_id_from_file
#If there is a id store localy, check whether it's the same as the last post's
if last_stored_id.nil? or last_stored_id != last_id
notify(@parser.get_description,@parser.get_link)
file_manager.set_last_id_in_file last_id
end
rescue Exception => e
notifyError(e.message)
end
sleep @interval || DEFAULT_INTERVAL
end
end
end
| renatorp/SeriesMonitor | src/series_monitor.rb | Ruby | mit | 1,278 |
module.exports = {
login: function(user, req)
{
// Parse detailed information from user-agent string
var r = require('ua-parser').parse(req.headers['user-agent']);
// Create new UserLogin row to database
sails.models.loglogin.create({
ip: req.ip,
host: req.host,
agent: req.headers['user-agent'],
browser: r.ua.toString(),
browserVersion: r.ua.toVersionString(),
browserFamily: r.ua.family,
os: r.os.toString(),
osVersion: r.os.toVersionString(),
osFamily: r.os.family,
device: r.device.family,
user: user.id
})
.exec(function(err, created) {
if(err) sails.log(err);
created.user = user;
sails.models.loglogin.publishCreate(created);
});
},
request: function(log, req, resp)
{
//var userId = -1;
// if (req.token) {
// userId = req.token;
// } else {
// userId = -1;
// }
sails.models.logrequest.create({
ip: log.ip,
protocol: log.protocol,
method: log.method,
url: log.diagnostic.url,
headers: req.headers || {},
parameters: log.diagnostic.routeParams,
body: log.diagnostic.bodyParams,
query: log.diagnostic.queryParams,
responseTime: log.responseTime || 0,
middlewareLatency: log.diagnostic.middlewareLatency || 0,
user: req.token || 0
})
.exec(function(err, created) {
if(err) sails.log(err);
sails.models.logrequest.publishCreate(created);
});
}
};
| modulr/modulr | api/api/services/LogService.js | JavaScript | mit | 1,506 |
package com.maximusvladimir.randomfinder;
import java.awt.Cursor;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JTextField;
import javax.swing.JButton;
import javax.swing.JProgressBar;
import javax.swing.Timer;
import javax.swing.JTextPane;
import java.awt.Font;
public class Test extends JFrame {
private JTextField textField;
private Searcher scanner;
private JTextPane txtpncodeWillGenerate;
public static void main(String[] args) { new Test(); }
public Test() {
setVisible(true);
setSize(324,270);
setTitle("Test");
setResizable(false);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
getContentPane().setLayout(null);
scanner = new Searcher();
JLabel lblEnterStringTo = new JLabel("Enter string to find:");
lblEnterStringTo.setBounds(10, 11, 136, 14);
getContentPane().add(lblEnterStringTo);
textField = new JTextField();
textField.setBounds(10, 30, 189, 20);
getContentPane().add(textField);
textField.setColumns(10);
final JButton btnGo = new JButton("Go!");
btnGo.setBounds(209, 29, 89, 23);
getContentPane().add(btnGo);
final JProgressBar progressBar = new JProgressBar();
progressBar.setBounds(10, 90, 288, 20);
getContentPane().add(progressBar);
JLabel lblMaximumTimeRemaining = new JLabel("Maximum time remaining:");
lblMaximumTimeRemaining.setBounds(10, 61, 178, 14);
getContentPane().add(lblMaximumTimeRemaining);
final JLabel lblResult = new JLabel("Result:");
lblResult.setBounds(10, 121, 189, 14);
getContentPane().add(lblResult);
txtpncodeWillGenerate = new JTextPane();
txtpncodeWillGenerate.setFont(new Font("Courier New", Font.PLAIN, 10));
txtpncodeWillGenerate.setText("(Code will generate here)");
txtpncodeWillGenerate.setBounds(10, 141, 298, 90);
getContentPane().add(txtpncodeWillGenerate);
btnGo.addMouseListener(new MouseAdapter() {
public void mouseReleased(MouseEvent me) {
if (btnGo.getText().equals("Go!")) {
btnGo.setText("Halt");
lblResult.setText("Result:");
try {
scanner.setString(textField.getText());
}
catch (Throwable t) {
JOptionPane.showMessageDialog(Test.this, t.getMessage());
}
scanner.startAsync();
Test.this.setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
}
else {
Test.this.setCursor(Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR));
btnGo.setText("Go!");
scanner.halt();
}
}
});
new Timer(250,new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
progressBar.setValue((int)(100 * scanner.getProgress()));
if (scanner.isFinished()) {
Test.this.setCursor(Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR));
if (scanner.getResultSeed() == Integer.MIN_VALUE)
lblResult.setText("Result: Not found.");
else {
lblResult.setText("Result: " + scanner.getResultSeed());
genCode();
}
btnGo.setText("Go!");
}
}
}).start();
repaint();
}
private void genCode() {
String pieces = "";
for (int i = 0; i < scanner.getString().length(); i++) {
pieces += "((char)(rand.nextInt(96)+32)) + \"\"";
pieces += " +";
}
if (scanner.getString().length() >= 1)
pieces = pieces.substring(0,pieces.length()-2);
txtpncodeWillGenerate.setText("Random rand = new Random("+scanner.getResultSeed()+");\n"+
"System.out.println(" + pieces + ");\n"+
"// Outputs " + scanner.getString());
}
}
| maximusvladimir/randomfinder | src/com/maximusvladimir/randomfinder/Test.java | Java | mit | 3,649 |
package com.walkertribe.ian.protocol.core.weap;
import java.util.List;
import org.junit.Assert;
import org.junit.Test;
import com.walkertribe.ian.enums.BeamFrequency;
import com.walkertribe.ian.enums.Origin;
import com.walkertribe.ian.protocol.AbstractPacketTester;
public class SetBeamFreqPacketTest extends AbstractPacketTester<SetBeamFreqPacket> {
@Test
public void test() {
execute("core/weap/SetBeamFreqPacket.txt", Origin.CLIENT, 1);
}
@Test
public void testConstruct() {
test(new SetBeamFreqPacket(BeamFrequency.B));
}
@Test(expected = IllegalArgumentException.class)
public void testConstructNullBeamFrequency() {
new SetBeamFreqPacket((BeamFrequency) null);
}
@Override
protected void testPackets(List<SetBeamFreqPacket> packets) {
test(packets.get(0));
}
private void test(SetBeamFreqPacket pkt) {
Assert.assertEquals(BeamFrequency.B, pkt.getBeamFrequency());
}
}
| rjwut/ian | src/test/java/com/walkertribe/ian/protocol/core/weap/SetBeamFreqPacketTest.java | Java | mit | 906 |
// Copyright (c) 2009-2014 The nealcoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "uritests.h"
#include "guiutil.h"
#include "walletmodel.h"
#include <QUrl>
void URITests::uriTests()
{
SendCoinsRecipient rv;
QUrl uri;
uri.setUrl(QString("nealcoin:175tWpb8K1S7NmH4Zx6rewF9WQrcZv245W?req-dontexist="));
QVERIFY(!GUIUtil::parsenealcoinURI(uri, &rv));
uri.setUrl(QString("nealcoin:175tWpb8K1S7NmH4Zx6rewF9WQrcZv245W?dontexist="));
QVERIFY(GUIUtil::parsenealcoinURI(uri, &rv));
QVERIFY(rv.address == QString("175tWpb8K1S7NmH4Zx6rewF9WQrcZv245W"));
QVERIFY(rv.label == QString());
QVERIFY(rv.amount == 0);
uri.setUrl(QString("nealcoin:175tWpb8K1S7NmH4Zx6rewF9WQrcZv245W?label=Wikipedia Example Address"));
QVERIFY(GUIUtil::parsenealcoinURI(uri, &rv));
QVERIFY(rv.address == QString("175tWpb8K1S7NmH4Zx6rewF9WQrcZv245W"));
QVERIFY(rv.label == QString("Wikipedia Example Address"));
QVERIFY(rv.amount == 0);
uri.setUrl(QString("nealcoin:175tWpb8K1S7NmH4Zx6rewF9WQrcZv245W?amount=0.001"));
QVERIFY(GUIUtil::parsenealcoinURI(uri, &rv));
QVERIFY(rv.address == QString("175tWpb8K1S7NmH4Zx6rewF9WQrcZv245W"));
QVERIFY(rv.label == QString());
QVERIFY(rv.amount == 100000);
uri.setUrl(QString("nealcoin:175tWpb8K1S7NmH4Zx6rewF9WQrcZv245W?amount=1.001"));
QVERIFY(GUIUtil::parsenealcoinURI(uri, &rv));
QVERIFY(rv.address == QString("175tWpb8K1S7NmH4Zx6rewF9WQrcZv245W"));
QVERIFY(rv.label == QString());
QVERIFY(rv.amount == 100100000);
uri.setUrl(QString("nealcoin:175tWpb8K1S7NmH4Zx6rewF9WQrcZv245W?amount=100&label=Wikipedia Example"));
QVERIFY(GUIUtil::parsenealcoinURI(uri, &rv));
QVERIFY(rv.address == QString("175tWpb8K1S7NmH4Zx6rewF9WQrcZv245W"));
QVERIFY(rv.amount == 10000000000LL);
QVERIFY(rv.label == QString("Wikipedia Example"));
uri.setUrl(QString("nealcoin:175tWpb8K1S7NmH4Zx6rewF9WQrcZv245W?message=Wikipedia Example Address"));
QVERIFY(GUIUtil::parsenealcoinURI(uri, &rv));
QVERIFY(rv.address == QString("175tWpb8K1S7NmH4Zx6rewF9WQrcZv245W"));
QVERIFY(rv.label == QString());
QVERIFY(GUIUtil::parsenealcoinURI("nealcoin://175tWpb8K1S7NmH4Zx6rewF9WQrcZv245W?message=Wikipedia Example Address", &rv));
QVERIFY(rv.address == QString("175tWpb8K1S7NmH4Zx6rewF9WQrcZv245W"));
QVERIFY(rv.label == QString());
uri.setUrl(QString("nealcoin:175tWpb8K1S7NmH4Zx6rewF9WQrcZv245W?req-message=Wikipedia Example Address"));
QVERIFY(GUIUtil::parsenealcoinURI(uri, &rv));
uri.setUrl(QString("nealcoin:175tWpb8K1S7NmH4Zx6rewF9WQrcZv245W?amount=1,000&label=Wikipedia Example"));
QVERIFY(!GUIUtil::parsenealcoinURI(uri, &rv));
uri.setUrl(QString("nealcoin:175tWpb8K1S7NmH4Zx6rewF9WQrcZv245W?amount=1,000.0&label=Wikipedia Example"));
QVERIFY(!GUIUtil::parsenealcoinURI(uri, &rv));
}
| appop/bitcoin | src/qt/test/uritests.cpp | C++ | mit | 2,968 |
// ***********************************************************************
// Assembly : MoeThrow
// Author : Siqi Lu
// Created : 2015-03-15 7:44 PM
//
// Last Modified By : Siqi Lu
// Last Modified On : 2015-03-15 8:24 PM
// ***********************************************************************
// <copyright file="AssemblyInfo.cs" company="Shanghai Yuyi">
// Copyright © 2012-2015 Shanghai Yuyi. All rights reserved.
// </copyright>
// ***********************************************************************
using System.Reflection;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("MoeThrow")]
[assembly: AssemblyDescription("Throw utility for .net project of Moe team.")]
[assembly: AssemblyConfiguration("MoeThrow")]
[assembly: AssemblyCompany("Shanghai Yuyi")]
[assembly: AssemblyProduct("MoeThrow")]
[assembly: AssemblyCopyright("Copyright © 2012-2015 Shanghai Yuyi. All rights reserved.")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("738e4629-8054-45c7-9d43-b97eb243b45c")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| SiqiLu/MoeThrow | MoeThrow/Properties/AssemblyInfo.cs | C# | mit | 2,005 |
var Command = require("../Command");
var RealDirection = require("../../RealDirection");
var MessageCategory = require("../../MessageCategory");
var _dir = RealDirection.NORTHEAST;
class Northeast extends Command{
constructor(){
super();
this.rule = /^n(?:orth)?e(?:ast)?$/g;
}
exec(){
if(this.step(_dir)){
this.showRoom();
} else {
this.sendMessage("Alas, you can't go that way.", MessageCategory.COMMAND);
}
}
}
module.exports = Northeast;
| jackindisguise/node-mud | src/handle/command/Northeast.js | JavaScript | mit | 465 |
package soliddomino.game.exceptions;
public class IncorrectMoveFormatException extends Exception {
public IncorrectMoveFormatException(String format) {
super(format + " is not the correct format. Expected \'#number-direction(e.g left, right).\'\nExample: 4-right");
}
}
| Beta-nanos/SolidDomino | SolidDomino/src/soliddomino/game/exceptions/IncorrectMoveFormatException.java | Java | mit | 289 |
#include "expression.h"
#include "opt.h"
#include "vm/instruction.h"
std::vector<vv::vm::command> vv::ast::expression::code() const
{
auto vec = generate();
optimize(vec);
return vec;
}
| jeorgun/Vivaldi | src/expression.cpp | C++ | mit | 194 |
import VueRouter from 'vue-router'
import { mount } from '@vue/test-utils'
import { waitNT, waitRAF } from '../../../tests/utils'
import { Vue } from '../../vue'
import { BPaginationNav } from './pagination-nav'
Vue.use(VueRouter)
// The majority of tests for the core of pagination mixin are performed
// in pagination.spec.js. Here we just test the differences that
// <pagination-nav> has
// We use a (currently) undocumented wrapper method `destroy()` at the end
// of each test to remove the VM and DOM from the JSDOM document, as
// the wrapper's and instances remain after each test completes
describe('pagination-nav', () => {
it('renders with correct basic structure for root elements', async () => {
const wrapper = mount(BPaginationNav, {
propsData: {
numberOfPages: 1,
value: 1
}
})
await waitNT(wrapper.vm)
await waitRAF()
// <pagination-nav> has an outer wrapper of nav
expect(wrapper.element.tagName).toBe('NAV')
const $ul = wrapper.find('ul.pagination')
expect($ul.exists()).toBe(true)
// NAV Attributes
expect(wrapper.attributes('aria-hidden')).toBe('false')
expect(wrapper.attributes('aria-label')).toBe('Pagination')
// UL Classes
expect($ul.classes()).toContain('pagination')
expect($ul.classes()).toContain('b-pagination')
expect($ul.classes()).not.toContain('pagination-sm')
expect($ul.classes()).not.toContain('pagination-lg')
expect($ul.classes()).not.toContain('justify-content-center')
expect($ul.classes()).not.toContain('justify-content-end')
// UL Attributes
expect($ul.attributes('role')).not.toBe('menubar')
expect($ul.attributes('aria-disabled')).toBe('false')
expect($ul.attributes('aria-label')).not.toBe('Pagination')
wrapper.destroy()
})
it('renders with correct default HREF', async () => {
const wrapper = mount(BPaginationNav, {
propsData: {
numberOfPages: 5,
value: 3,
limit: 10
}
})
await waitNT(wrapper.vm)
await waitRAF()
expect(wrapper.element.tagName).toBe('NAV')
const $links = wrapper.findAll('a.page-link')
expect($links.length).toBe(9)
// Default base URL is '/', and link will be the page number
expect($links.at(0).attributes('href')).toBe('/1')
expect($links.at(1).attributes('href')).toBe('/2')
expect($links.at(2).attributes('href')).toBe('/1')
expect($links.at(3).attributes('href')).toBe('/2')
expect($links.at(4).attributes('href')).toBe('/3')
expect($links.at(5).attributes('href')).toBe('/4')
expect($links.at(6).attributes('href')).toBe('/5')
expect($links.at(7).attributes('href')).toBe('/4')
expect($links.at(8).attributes('href')).toBe('/5')
wrapper.destroy()
})
it('renders with correct default page button text', async () => {
const wrapper = mount(BPaginationNav, {
propsData: {
numberOfPages: 5,
value: 3,
limit: 10
}
})
await waitNT(wrapper.vm)
await waitRAF()
expect(wrapper.element.tagName).toBe('NAV')
const $links = wrapper.findAll('a.page-link')
expect($links.length).toBe(9)
expect($links.at(2).text()).toBe('1')
expect($links.at(3).text()).toBe('2')
expect($links.at(4).text()).toBe('3')
expect($links.at(5).text()).toBe('4')
expect($links.at(6).text()).toBe('5')
wrapper.destroy()
})
it('disabled renders correct', async () => {
const wrapper = mount(BPaginationNav, {
propsData: {
numberOfPages: 1,
value: 1,
disabled: true
}
})
await waitNT(wrapper.vm)
await waitRAF()
// <pagination-nav> has an outer wrapper of nav
expect(wrapper.element.tagName).toBe('NAV')
const $ul = wrapper.find('ul.pagination')
expect($ul.exists()).toBe(true)
// NAV Attributes
expect(wrapper.attributes('aria-hidden')).toBe('true')
expect(wrapper.attributes('aria-disabled')).toBe('true')
// UL Classes
expect($ul.classes()).toContain('pagination')
expect($ul.classes()).toContain('b-pagination')
// UL Attributes
expect($ul.attributes('role')).not.toBe('menubar')
expect($ul.attributes('aria-disabled')).toBe('true')
// LI classes
expect(wrapper.findAll('li').length).toBe(5)
expect(wrapper.findAll('li.page-item').length).toBe(5)
expect(wrapper.findAll('li.disabled').length).toBe(5)
// LI Inner should be span elements
expect(wrapper.findAll('li > span').length).toBe(5)
expect(wrapper.findAll('li > span.page-link').length).toBe(5)
expect(wrapper.findAll('li > span[aria-disabled="true"').length).toBe(5)
wrapper.destroy()
})
it('reacts to changes in number-of-pages', async () => {
const wrapper = mount(BPaginationNav, {
propsData: {
numberOfPages: 3,
value: 2,
limit: 10
}
})
await waitNT(wrapper.vm)
await waitRAF()
expect(wrapper.element.tagName).toBe('NAV')
let $links = wrapper.findAll('a.page-link')
expect($links.length).toBe(7)
await wrapper.setProps({
numberOfPages: 5
})
await waitNT(wrapper.vm)
$links = wrapper.findAll('a.page-link')
expect($links.length).toBe(9)
wrapper.destroy()
})
it('renders with correct HREF when base-url specified', async () => {
const wrapper = mount(BPaginationNav, {
propsData: {
numberOfPages: 5,
value: 3,
limit: 10,
baseUrl: '/foo/'
}
})
await waitNT(wrapper.vm)
await waitRAF()
expect(wrapper.element.tagName).toBe('NAV')
const $links = wrapper.findAll('a.page-link')
expect($links.length).toBe(9)
// Default base URL is '/', and link will be the page number
expect($links.at(0).attributes('href')).toBe('/foo/1')
expect($links.at(1).attributes('href')).toBe('/foo/2')
expect($links.at(2).attributes('href')).toBe('/foo/1')
expect($links.at(3).attributes('href')).toBe('/foo/2')
expect($links.at(4).attributes('href')).toBe('/foo/3')
expect($links.at(5).attributes('href')).toBe('/foo/4')
expect($links.at(6).attributes('href')).toBe('/foo/5')
expect($links.at(7).attributes('href')).toBe('/foo/4')
expect($links.at(8).attributes('href')).toBe('/foo/5')
wrapper.destroy()
})
it('renders with correct HREF when link-gen function provided', async () => {
const wrapper = mount(BPaginationNav, {
propsData: {
numberOfPages: 5,
value: 3,
limit: 10,
linkGen: page => `?${page}`
}
})
await waitNT(wrapper.vm)
await waitRAF()
expect(wrapper.element.tagName).toBe('NAV')
const $links = wrapper.findAll('a.page-link')
expect($links.length).toBe(9)
// Default base URL is '/', and link will be the page number
expect($links.at(0).attributes('href')).toBe('?1')
expect($links.at(1).attributes('href')).toBe('?2')
expect($links.at(2).attributes('href')).toBe('?1')
expect($links.at(3).attributes('href')).toBe('?2')
expect($links.at(4).attributes('href')).toBe('?3')
expect($links.at(5).attributes('href')).toBe('?4')
expect($links.at(6).attributes('href')).toBe('?5')
expect($links.at(7).attributes('href')).toBe('?4')
expect($links.at(8).attributes('href')).toBe('?5')
wrapper.destroy()
})
it('renders with correct HREF when link-gen function returns object', async () => {
const wrapper = mount(BPaginationNav, {
propsData: {
numberOfPages: 5,
value: 3,
limit: 10,
linkGen: page => ({ path: `/baz?${page}` })
}
})
await waitNT(wrapper.vm)
await waitRAF()
expect(wrapper.element.tagName).toBe('NAV')
const $links = wrapper.findAll('a.page-link')
expect($links.length).toBe(9)
// Default base URL is '/', and link will be the page number
expect($links.at(0).attributes('href')).toBe('/baz?1')
expect($links.at(1).attributes('href')).toBe('/baz?2')
expect($links.at(2).attributes('href')).toBe('/baz?1')
expect($links.at(3).attributes('href')).toBe('/baz?2')
expect($links.at(4).attributes('href')).toBe('/baz?3')
expect($links.at(5).attributes('href')).toBe('/baz?4')
expect($links.at(6).attributes('href')).toBe('/baz?5')
expect($links.at(7).attributes('href')).toBe('/baz?4')
expect($links.at(8).attributes('href')).toBe('/baz?5')
wrapper.destroy()
})
it('renders with correct page button text when page-gen function provided', async () => {
const wrapper = mount(BPaginationNav, {
propsData: {
numberOfPages: 5,
value: 3,
limit: 10,
pageGen: page => `Page ${page}`
}
})
await waitNT(wrapper.vm)
await waitRAF()
expect(wrapper.element.tagName).toBe('NAV')
const $links = wrapper.findAll('a.page-link')
expect($links.length).toBe(9)
expect($links.at(2).text()).toBe('Page 1')
expect($links.at(3).text()).toBe('Page 2')
expect($links.at(4).text()).toBe('Page 3')
expect($links.at(5).text()).toBe('Page 4')
expect($links.at(6).text()).toBe('Page 5')
wrapper.destroy()
})
it('renders with correct HREF when array of links set via pages prop', async () => {
const wrapper = mount(BPaginationNav, {
propsData: {
value: 3,
limit: 10,
pages: ['/baz?1', '/baz?2', '/baz?3', '/baz?4', '/baz?5']
}
})
await waitNT(wrapper.vm)
await waitRAF()
expect(wrapper.element.tagName).toBe('NAV')
const $links = wrapper.findAll('a.page-link')
expect($links.length).toBe(9)
// Default base URL is '/', and link will be the page number
expect($links.at(0).attributes('href')).toBe('/baz?1')
expect($links.at(1).attributes('href')).toBe('/baz?2')
expect($links.at(2).attributes('href')).toBe('/baz?1')
expect($links.at(3).attributes('href')).toBe('/baz?2')
expect($links.at(4).attributes('href')).toBe('/baz?3')
expect($links.at(5).attributes('href')).toBe('/baz?4')
expect($links.at(6).attributes('href')).toBe('/baz?5')
expect($links.at(7).attributes('href')).toBe('/baz?4')
expect($links.at(8).attributes('href')).toBe('/baz?5')
// Page buttons have correct content
expect($links.at(2).text()).toBe('1')
expect($links.at(3).text()).toBe('2')
expect($links.at(4).text()).toBe('3')
expect($links.at(5).text()).toBe('4')
expect($links.at(6).text()).toBe('5')
wrapper.destroy()
})
it('renders with correct HREF when array of links and text set via pages prop', async () => {
const wrapper = mount(BPaginationNav, {
propsData: {
value: 3,
limit: 10,
pages: [
{ link: '/baz?1', text: 'one' },
{ link: '/baz?2', text: 'two' },
{ link: '/baz?3', text: 'three' },
{ link: '/baz?4', text: 'four' },
{ link: '/baz?5', text: 'five' }
]
}
})
await waitNT(wrapper.vm)
await waitRAF()
expect(wrapper.element.tagName).toBe('NAV')
const $links = wrapper.findAll('a.page-link')
expect($links.length).toBe(9)
// Default base URL is '/', and link will be the page number
expect($links.at(0).attributes('href')).toBe('/baz?1')
expect($links.at(1).attributes('href')).toBe('/baz?2')
expect($links.at(2).attributes('href')).toBe('/baz?1')
expect($links.at(3).attributes('href')).toBe('/baz?2')
expect($links.at(4).attributes('href')).toBe('/baz?3')
expect($links.at(5).attributes('href')).toBe('/baz?4')
expect($links.at(6).attributes('href')).toBe('/baz?5')
expect($links.at(7).attributes('href')).toBe('/baz?4')
expect($links.at(8).attributes('href')).toBe('/baz?5')
// Page buttons have correct content
expect($links.at(2).text()).toBe('one')
expect($links.at(3).text()).toBe('two')
expect($links.at(4).text()).toBe('three')
expect($links.at(5).text()).toBe('four')
expect($links.at(6).text()).toBe('five')
wrapper.destroy()
})
it('reacts to changes in pages array length', async () => {
const wrapper = mount(BPaginationNav, {
propsData: {
value: 2,
limit: 10,
pages: ['/baz?1', '/baz?2', '/baz?3']
}
})
await waitNT(wrapper.vm)
await waitRAF()
expect(wrapper.element.tagName).toBe('NAV')
let $links = wrapper.findAll('a.page-link')
expect($links.length).toBe(7)
expect($links.at(0).attributes('href')).toBe('/baz?1')
expect($links.at(1).attributes('href')).toBe('/baz?1')
expect($links.at(2).attributes('href')).toBe('/baz?1')
expect($links.at(3).attributes('href')).toBe('/baz?2')
expect($links.at(4).attributes('href')).toBe('/baz?3')
expect($links.at(5).attributes('href')).toBe('/baz?3')
expect($links.at(6).attributes('href')).toBe('/baz?3')
// Add extra page
await wrapper.setProps({
pages: ['/baz?1', '/baz?2', '/baz?3', '/baz?4']
})
await waitNT(wrapper.vm)
$links = wrapper.findAll('a.page-link')
expect($links.length).toBe(8)
expect($links.at(0).attributes('href')).toBe('/baz?1')
expect($links.at(1).attributes('href')).toBe('/baz?1')
expect($links.at(2).attributes('href')).toBe('/baz?1')
expect($links.at(3).attributes('href')).toBe('/baz?2')
expect($links.at(4).attributes('href')).toBe('/baz?3')
expect($links.at(5).attributes('href')).toBe('/baz?4')
expect($links.at(6).attributes('href')).toBe('/baz?3')
expect($links.at(7).attributes('href')).toBe('/baz?4')
wrapper.destroy()
})
it('clicking buttons updates the v-model', async () => {
const App = {
compatConfig: { MODE: 3, RENDER_FUNCTION: 'suppress-warning' },
methods: {
onPageClick(bvEvent, page) {
// Prevent 3rd page from being selected
if (page === 3) {
bvEvent.preventDefault()
}
}
},
render(h) {
return h(BPaginationNav, {
props: {
baseUrl: '#', // Needed to prevent JSDOM errors
numberOfPages: 5,
value: 1,
limit: 10
},
on: { 'page-click': this.onPageClick }
})
}
}
const wrapper = mount(App)
expect(wrapper).toBeDefined()
const paginationNav = wrapper.findComponent(BPaginationNav)
expect(paginationNav).toBeDefined()
expect(paginationNav.element.tagName).toBe('NAV')
// Grab the page links
const lis = paginationNav.findAll('li')
expect(lis.length).toBe(9)
expect(paginationNav.vm.computedCurrentPage).toBe(1)
expect(paginationNav.emitted('input')).toBeUndefined()
expect(paginationNav.emitted('change')).toBeUndefined()
expect(paginationNav.emitted('page-click')).toBeUndefined()
// Click on current (1st) page link (does nothing)
await lis
.at(2)
.find('a')
.trigger('click')
await waitRAF()
expect(paginationNav.vm.computedCurrentPage).toBe(1)
expect(paginationNav.emitted('input')).toBeUndefined()
expect(paginationNav.emitted('change')).toBeUndefined()
expect(paginationNav.emitted('page-click')).toBeUndefined()
// Click on 2nd page link
await lis
.at(3)
.find('a')
.trigger('click')
await waitRAF()
expect(paginationNav.vm.computedCurrentPage).toBe(2)
expect(paginationNav.emitted('input')).toBeDefined()
expect(paginationNav.emitted('change')).toBeDefined()
expect(paginationNav.emitted('page-click')).toBeDefined()
expect(paginationNav.emitted('input')[0][0]).toBe(2)
expect(paginationNav.emitted('change')[0][0]).toBe(2)
expect(paginationNav.emitted('page-click').length).toBe(1)
// Click goto last page link
await lis
.at(8)
.find('a')
.trigger('click')
await waitRAF()
expect(paginationNav.vm.computedCurrentPage).toBe(5)
expect(paginationNav.emitted('input')[1][0]).toBe(5)
expect(paginationNav.emitted('change')[1][0]).toBe(5)
expect(paginationNav.emitted('page-click').length).toBe(2)
// Click prev page link
await lis
.at(1)
.find('a')
.trigger('click')
await waitRAF()
expect(paginationNav.vm.computedCurrentPage).toBe(4)
expect(paginationNav.emitted('input')[2][0]).toBe(4)
expect(paginationNav.emitted('change')[2][0]).toBe(4)
expect(paginationNav.emitted('page-click').length).toBe(3)
// Click on 3rd page link (prevented)
await lis
.at(4)
.find('a')
.trigger('click')
await waitRAF()
expect(paginationNav.vm.computedCurrentPage).toBe(4)
expect(paginationNav.emitted('input').length).toBe(3)
expect(paginationNav.emitted('change').length).toBe(3)
expect(paginationNav.emitted('page-click').length).toBe(4)
wrapper.destroy()
})
describe('auto-detect page', () => {
// Note: JSDOM only works with hash URL updates out of the box
beforeEach(() => {
// Make sure theJSDOM is at '/', as JSDOM instances for each test!
window.history.pushState({}, '', '/')
})
it('detects current page without $router', async () => {
const wrapper = mount(BPaginationNav, {
propsData: {
numberOfPages: 3,
value: null,
linkGen: page => (page === 2 ? '/' : `/#${page}`)
}
})
await waitNT(wrapper.vm)
await waitRAF()
await waitNT(wrapper.vm)
expect(wrapper.vm.$router).toBeUndefined()
expect(wrapper.vm.$route).toBeUndefined()
expect(wrapper.element.tagName).toBe('NAV')
const $ul = wrapper.find('ul.pagination')
expect($ul.exists()).toBe(true)
// Emitted current page (2)
expect(wrapper.emitted('input')).toBeDefined()
expect(wrapper.emitted('input').length).toBe(1)
expect(wrapper.emitted('input')[0][0]).toBe(2) // Page 2, URL = ''
wrapper.destroy()
})
it('works with $router to detect path and linkGen returns location object', async () => {
const App = {
compatConfig: { MODE: 3, COMPONENT_FUNCTIONAL: 'suppress-warning' },
components: { BPaginationNav },
methods: {
linkGen(page) {
// We make page #2 "home" for testing
// We return a to prop to auto trigger use of $router
// if using strings, we would need to set use-router=true
return page === 2 ? { path: '/' } : { path: '/' + page }
}
},
template: `
<div>
<b-pagination-nav :number-of-pages="3" :link-gen="linkGen"></b-pagination-nav>
<router-view></router-view>
</div>
`
}
// Our router view component
const FooRoute = {
compatConfig: { MODE: 3, RENDER_FUNCTION: 'suppress-warning' },
render(h) {
return h('div', { class: 'foo-content' }, ['stub'])
}
}
// Create router instance
const router = new VueRouter({
routes: [{ path: '/', component: FooRoute }, { path: '/:page', component: FooRoute }]
})
const wrapper = mount(App, { router })
expect(wrapper).toBeDefined()
// Wait for the router to initialize
await new Promise(resolve => router.onReady(resolve))
// Wait for the guessCurrentPage to complete
await waitNT(wrapper.vm)
await waitRAF()
await waitNT(wrapper.vm)
// The pagination-nav component should exist
expect(wrapper.findComponent(BPaginationNav).exists()).toBe(true)
// And should be on page 2
expect(wrapper.findComponent(BPaginationNav).vm.currentPage).toBe(2)
// Push router to a new page
wrapper.vm.$router.push('/3')
// Wait for the guessCurrentPage to complete
await waitNT(wrapper.vm)
await waitRAF()
await waitNT(wrapper.vm)
// The pagination-nav component should exist
expect(wrapper.findComponent(BPaginationNav).exists()).toBe(true)
// And should be on page 3
expect(wrapper.findComponent(BPaginationNav).vm.currentPage).toBe(3)
wrapper.destroy()
})
it('works with $router to detect path and use-router set and linkGen returns string', async () => {
const App = {
compatConfig: { MODE: 3, COMPONENT_FUNCTIONAL: 'suppress-warning' },
components: { BPaginationNav },
methods: {
linkGen(page) {
// We make page #2 "home" for testing
// We return a to prop to auto trigger use of $router
// if using strings, we would need to set use-router=true
return page === 2 ? '/' : `/${page}`
}
},
template: `
<div>
<b-pagination-nav :number-of-pages="3" :link-gen="linkGen" use-router></b-pagination-nav>
<router-view></router-view>
</div>
`
}
// Our router view component
const FooRoute = {
compatConfig: { MODE: 3, RENDER_FUNCTION: 'suppress-warning' },
render(h) {
return h('div', { class: 'foo-content' }, ['stub'])
}
}
// Create router instance
const router = new VueRouter({
routes: [{ path: '/', component: FooRoute }, { path: '/:page', component: FooRoute }]
})
const wrapper = mount(App, { router })
expect(wrapper).toBeDefined()
// Wait for the router to initialize
await new Promise(resolve => router.onReady(resolve))
// Wait for the guessCurrentPage to complete
await waitNT(wrapper.vm)
await waitRAF()
await waitNT(wrapper.vm)
// The <pagination-nav> component should exist
expect(wrapper.findComponent(BPaginationNav).exists()).toBe(true)
// And should be on page 2
expect(wrapper.findComponent(BPaginationNav).vm.currentPage).toBe(2)
// Push router to a new page
wrapper.vm.$router.push('/3')
// Wait for the guessCurrentPage to complete
await waitNT(wrapper.vm)
await waitRAF()
await waitNT(wrapper.vm)
// The pagination-nav component should exist
expect(wrapper.findComponent(BPaginationNav).exists()).toBe(true)
// And should be on page 3
expect(wrapper.findComponent(BPaginationNav).vm.currentPage).toBe(3)
wrapper.destroy()
})
})
})
| bootstrap-vue/bootstrap-vue | src/components/pagination-nav/pagination-nav.spec.js | JavaScript | mit | 22,231 |
using System;
using System.Collections.Generic;
using System.Text;
using System.Linq;
public class Family
{
private List<Person> familyList;
public List<Person> Names
{
get { return this.familyList; }
set { this.familyList = value; }
}
public Family()
{
this.familyList = new List<Person>();
}
public void AddMember(Person name)
{
familyList.Add(name);
}
public Person GetOlderMember()
{
var result = Names.OrderByDescending(x => x.Age).FirstOrDefault();
return result;
}
}
| giggals/Software-University | Exercises-Defining Classes/03.OldesFamilyMember/Family.cs | C# | mit | 603 |
//proc_ace_acceptor.cpp
#include <proc_mta_ace_acceptor.h>
using namespace proc_mta_ace;
using std::ostringstream;
//----------------------------------------------------------------------------------------------------------------------------
proc_acceptor::proc_acceptor ( concurrency_t concurrency ) : concurrency_ { concurrency } ,
the_thread_pool_ ( private_thread_pool_ ) ,
m_instance_data{ nullptr }
{
ACE_Trace _( ACE_TEXT( "proc_acceptor::proc_acceptor ( concurrency_t concurrency )" ) , __LINE__ );
}
//----------------------------------------------------------------------------------------------------------------------------
proc_acceptor::proc_acceptor ( proc_thread_pool &thread_pool ) : concurrency_ { concurrency_t::thread_pool_ },
the_thread_pool_ ( thread_pool ) ,
m_instance_data{ nullptr }
{
ACE_Trace _( ACE_TEXT( "proc_acceptor::proc_acceptor ( proc_thread_pool &thread_pool)" ) , __LINE__ );
}
//----------------------------------------------------------------------------------------------------------------------------
proc_acceptor::~proc_acceptor ( void )
{
ACE_Trace _( ACE_TEXT( "proc_acceptor::~proc_acceptor ( void )" ) , __LINE__ );
if ( concurrency() == concurrency_t::thread_pool_ && thread_pool_is_private () )
{
thread_pool ()->close ();
}
}
//----------------------------------------------------------------------------------------------------------------------------
int proc_acceptor::open ( const ACE_INET_Addr &addr,
ACE_Reactor *reactor,
protocol_data_ptr instance_data ,
int pool_size )
{
ACE_Trace _( ACE_TEXT( "int proc_acceptor::open" ) , __LINE__ );
data( instance_data );
if ( concurrency() == concurrency_t::thread_pool_ && thread_pool_is_private() )
{
thread_pool()->start( pool_size );
}
return inherited::open ( addr , reactor );
}
//----------------------------------------------------------------------------------------------------------------------------
int proc_acceptor::close ( void )
{
ACE_Trace _( ACE_TEXT( "proc_acceptor::close" ) , __LINE__ );
if ( concurrency() == concurrency_t::thread_pool_ && thread_pool_is_private () )
{
thread_pool ()->stop();
}
return inherited::close();
}
| chromatic-universe/cci-stream-mta | src/proc_ace_acceptor/proc_cci_mta_acceptor.cpp | C++ | mit | 2,580 |
require 'dimension/dimension'
require 'dimension/d2'
require 'dimension/d3' | ismailfaruqi/dimension | lib/dimension.rb | Ruby | mit | 75 |
<?php
namespace HyperionStudios\HumblePickleBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
* HyperionStudios\HumblePickleBundle\Entity\Donator
*
* @ORM\Table(name="donators")
* @ORM\Entity
*/
class Donator
{
/**
* @ORM\Id
* @ORM\GeneratedValue
* @ORM\Column(type="integer")
*/
protected $id;
/**
* @ORM\Column(type="string")
*/
protected $name;
/**
* @ORM\Column(type="string")
*/
protected $email;
/**
* @ORM\OneToMany(targetEntity="Donation", mappedBy="donator")
*/
protected $donations;
public function __construct()
{
$this->donations = new \Doctrine\Common\Collections\ArrayCollection();
}
/**
* Get id
*
* @return integer
*/
public function getId()
{
return $this->id;
}
/**
* Set name
*
* @param string $name
*/
public function setName($name)
{
$this->name = $name;
}
/**
* Get name
*
* @return string
*/
public function getName()
{
return $this->name;
}
/**
* Set email
*
* @param string $email
*/
public function setEmail($email)
{
$this->email = $email;
}
/**
* Get email
*
* @return string
*/
public function getEmail()
{
return $this->email;
}
/**
* Add donations
*
* @param HyperionStudios\HumblePickleBundle\Entity\Donation $donations
*/
public function addDonation(\HyperionStudios\HumblePickleBundle\Entity\Donation $donations)
{
$this->donations[] = $donations;
}
/**
* Get donations
*
* @return Doctrine\Common\Collections\Collection
*/
public function getDonations()
{
return $this->donations;
}
} | Curtisdhi/HumblePickle | src/HyperionStudios/HumblePickleBundle/Entity/Donator.php | PHP | mit | 1,963 |
module.exports = (name, node) => (
name === "apply" &&
node.type === "CallExpression" &&
node.callee.type === "Identifier");
| lachrist/aran | test/dead/apply/pointcut.js | JavaScript | mit | 131 |
# encoding: utf-8
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes may cause incorrect behavior and will be lost if the code is
# regenerated.
module Azure::Network::Mgmt::V2019_07_01
module Models
#
# Inbound NAT rule of the load balancer.
#
class InboundNatRule < SubResource
include MsRestAzure
# @return [SubResource] A reference to frontend IP addresses.
attr_accessor :frontend_ipconfiguration
# @return [NetworkInterfaceIPConfiguration] A reference to a private IP
# address defined on a network interface of a VM. Traffic sent to the
# frontend port of each of the frontend IP configurations is forwarded to
# the backend IP.
attr_accessor :backend_ipconfiguration
# @return [TransportProtocol] The reference to the transport protocol
# used by the load balancing rule. Possible values include: 'Udp', 'Tcp',
# 'All'
attr_accessor :protocol
# @return [Integer] The port for the external endpoint. Port numbers for
# each rule must be unique within the Load Balancer. Acceptable values
# range from 1 to 65534.
attr_accessor :frontend_port
# @return [Integer] The port used for the internal endpoint. Acceptable
# values range from 1 to 65535.
attr_accessor :backend_port
# @return [Integer] The timeout for the TCP idle connection. The value
# can be set between 4 and 30 minutes. The default value is 4 minutes.
# This element is only used when the protocol is set to TCP.
attr_accessor :idle_timeout_in_minutes
# @return [Boolean] Configures a virtual machine's endpoint for the
# floating IP capability required to configure a SQL AlwaysOn
# Availability Group. This setting is required when using the SQL
# AlwaysOn Availability Groups in SQL server. This setting can't be
# changed after you create the endpoint.
attr_accessor :enable_floating_ip
# @return [Boolean] Receive bidirectional TCP Reset on TCP flow idle
# timeout or unexpected connection termination. This element is only used
# when the protocol is set to TCP.
attr_accessor :enable_tcp_reset
# @return [ProvisioningState] The provisioning state of the inbound NAT
# rule resource. Possible values include: 'Succeeded', 'Updating',
# 'Deleting', 'Failed'
attr_accessor :provisioning_state
# @return [String] The name of the resource that is unique within the set
# of inbound NAT rules used by the load balancer. This name can be used
# to access the resource.
attr_accessor :name
# @return [String] A unique read-only string that changes whenever the
# resource is updated.
attr_accessor :etag
# @return [String] Type of the resource.
attr_accessor :type
#
# Mapper for InboundNatRule class as Ruby Hash.
# This will be used for serialization/deserialization.
#
def self.mapper()
{
client_side_validation: true,
required: false,
serialized_name: 'InboundNatRule',
type: {
name: 'Composite',
class_name: 'InboundNatRule',
model_properties: {
id: {
client_side_validation: true,
required: false,
serialized_name: 'id',
type: {
name: 'String'
}
},
frontend_ipconfiguration: {
client_side_validation: true,
required: false,
serialized_name: 'properties.frontendIPConfiguration',
type: {
name: 'Composite',
class_name: 'SubResource'
}
},
backend_ipconfiguration: {
client_side_validation: true,
required: false,
read_only: true,
serialized_name: 'properties.backendIPConfiguration',
type: {
name: 'Composite',
class_name: 'NetworkInterfaceIPConfiguration'
}
},
protocol: {
client_side_validation: true,
required: false,
serialized_name: 'properties.protocol',
type: {
name: 'String'
}
},
frontend_port: {
client_side_validation: true,
required: false,
serialized_name: 'properties.frontendPort',
type: {
name: 'Number'
}
},
backend_port: {
client_side_validation: true,
required: false,
serialized_name: 'properties.backendPort',
type: {
name: 'Number'
}
},
idle_timeout_in_minutes: {
client_side_validation: true,
required: false,
serialized_name: 'properties.idleTimeoutInMinutes',
type: {
name: 'Number'
}
},
enable_floating_ip: {
client_side_validation: true,
required: false,
serialized_name: 'properties.enableFloatingIP',
type: {
name: 'Boolean'
}
},
enable_tcp_reset: {
client_side_validation: true,
required: false,
serialized_name: 'properties.enableTcpReset',
type: {
name: 'Boolean'
}
},
provisioning_state: {
client_side_validation: true,
required: false,
serialized_name: 'properties.provisioningState',
type: {
name: 'String'
}
},
name: {
client_side_validation: true,
required: false,
serialized_name: 'name',
type: {
name: 'String'
}
},
etag: {
client_side_validation: true,
required: false,
serialized_name: 'etag',
type: {
name: 'String'
}
},
type: {
client_side_validation: true,
required: false,
read_only: true,
serialized_name: 'type',
type: {
name: 'String'
}
}
}
}
}
end
end
end
end
| Azure/azure-sdk-for-ruby | management/azure_mgmt_network/lib/2019-07-01/generated/azure_mgmt_network/models/inbound_nat_rule.rb | Ruby | mit | 6,873 |
package com.giantbomb.main;
public class ListOfGamesGenerator
{
public static void main(final String[] args)
{
}
}
| brentnash/gbecho | src/main/java/com/giantbomb/main/ListOfGamesGenerator.java | Java | mit | 137 |
namespace BatterySync
{
partial class Form1
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.components = new System.ComponentModel.Container();
this.timer1 = new System.Windows.Forms.Timer(this.components);
this.label1 = new System.Windows.Forms.Label();
this.textBox1 = new System.Windows.Forms.TextBox();
this.button1 = new System.Windows.Forms.Button();
this.SuspendLayout();
//
// timer1
//
this.timer1.Enabled = true;
this.timer1.Interval = 60000;
this.timer1.Tick += new System.EventHandler(this.timer1_Tick);
//
// label1
//
this.label1.AutoSize = true;
this.label1.Location = new System.Drawing.Point(12, 9);
this.label1.Name = "label1";
this.label1.Size = new System.Drawing.Size(79, 13);
this.label1.TabIndex = 0;
this.label1.Text = "Battery Status: ";
//
// textBox1
//
this.textBox1.Location = new System.Drawing.Point(12, 37);
this.textBox1.Name = "textBox1";
this.textBox1.Size = new System.Drawing.Size(100, 20);
this.textBox1.TabIndex = 1;
this.textBox1.TextChanged += new System.EventHandler(this.textBox1_TextChanged);
//
// button1
//
this.button1.Location = new System.Drawing.Point(118, 35);
this.button1.Name = "button1";
this.button1.Size = new System.Drawing.Size(123, 23);
this.button1.TabIndex = 2;
this.button1.Text = "Set Device Name";
this.button1.UseVisualStyleBackColor = true;
this.button1.Click += new System.EventHandler(this.button1_Click);
//
// Form1
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(253, 69);
this.Controls.Add(this.button1);
this.Controls.Add(this.textBox1);
this.Controls.Add(this.label1);
this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedToolWindow;
this.MaximizeBox = false;
this.Name = "Form1";
this.ShowIcon = false;
this.Text = "BatterySync";
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
private System.Windows.Forms.Timer timer1;
private System.Windows.Forms.Label label1;
private System.Windows.Forms.TextBox textBox1;
private System.Windows.Forms.Button button1;
}
}
| ardaozkal/BatterySync | Client/BatterySync/Form1.Designer.cs | C# | mit | 3,643 |
/*
* The MIT License (MIT)
*
* Copyright (c) 2016-2017 The Regents of the University of California
* Author: Jim Robinson
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
import {loadIndex} from "./indexFactory.js"
import AlignmentContainer from "./alignmentContainer.js"
import BamUtils from "./bamUtils.js"
import {BGZip, igvxhr} from "../../node_modules/igv-utils/src/index.js"
import {buildOptions} from "../util/igvUtils.js"
/**
* Class for reading a bam file
*
* @param config
* @constructor
*/
class BamReader {
constructor(config, genome) {
this.config = config
this.genome = genome
this.bamPath = config.url
this.baiPath = config.indexURL
BamUtils.setReaderDefaults(this, config)
}
async readAlignments(chr, bpStart, bpEnd) {
const chrToIndex = await this.getChrIndex()
const queryChr = this.chrAliasTable.hasOwnProperty(chr) ? this.chrAliasTable[chr] : chr
const chrId = chrToIndex[queryChr]
const alignmentContainer = new AlignmentContainer(chr, bpStart, bpEnd, this.config)
if (chrId === undefined) {
return alignmentContainer
} else {
const bamIndex = await this.getIndex()
const chunks = bamIndex.blocksForRange(chrId, bpStart, bpEnd)
if (!chunks || chunks.length === 0) {
return alignmentContainer
}
let counter = 1
for (let c of chunks) {
let lastBlockSize
if (c.maxv.offset === 0) {
lastBlockSize = 0 // Don't need to read the last block.
} else {
const bsizeOptions = buildOptions(this.config, {range: {start: c.maxv.block, size: 26}})
const abuffer = await igvxhr.loadArrayBuffer(this.bamPath, bsizeOptions)
lastBlockSize = BGZip.bgzBlockSize(abuffer)
}
const fetchMin = c.minv.block
const fetchMax = c.maxv.block + lastBlockSize
const range = {start: fetchMin, size: fetchMax - fetchMin + 1}
const compressed = await igvxhr.loadArrayBuffer(this.bamPath, buildOptions(this.config, {range: range}))
var ba = BGZip.unbgzf(compressed) //new Uint8Array(BGZip.unbgzf(compressed)); //, c.maxv.block - c.minv.block + 1));
const done = BamUtils.decodeBamRecords(ba, c.minv.offset, alignmentContainer, this.indexToChr, chrId, bpStart, bpEnd, this.filter)
if (done) {
// console.log(`Loaded ${counter} chunks out of ${chunks.length}`);
break
}
counter++
}
alignmentContainer.finish()
return alignmentContainer
}
}
async getHeader() {
if (!this.header) {
const genome = this.genome
const index = await this.getIndex()
let start
let len
if (index.firstBlockPosition) {
const bsizeOptions = buildOptions(this.config, {range: {start: index.firstBlockPosition, size: 26}})
const abuffer = await igvxhr.loadArrayBuffer(this.bamPath, bsizeOptions)
const bsize = BGZip.bgzBlockSize(abuffer)
len = index.firstBlockPosition + bsize // Insure we get the complete compressed block containing the header
} else {
len = 64000
}
const options = buildOptions(this.config, {range: {start: 0, size: len}})
this.header = await BamUtils.readHeader(this.bamPath, options, genome)
}
return this.header
}
async getIndex() {
const genome = this.genome
if (!this.index) {
this.index = await loadIndex(this.baiPath, this.config, genome)
}
return this.index
}
async getChrIndex() {
if (this.chrToIndex) {
return this.chrToIndex
} else {
const header = await this.getHeader()
this.chrToIndex = header.chrToIndex
this.indexToChr = header.chrNames
this.chrAliasTable = header.chrAliasTable
return this.chrToIndex
}
}
}
export default BamReader
| igvteam/igv.js | js/bam/bamReader.js | JavaScript | mit | 5,347 |
var should = require("should");
var Mat3x3 = require("./Mat3x3");
var Barycentric3 = require("./Barycentric3");
var Logger = require("./Logger");
(function(exports) {
var verboseLogger = new Logger({
logLevel: "debug"
});
////////////////// constructor
function XYZ(x, y, z, options) {
var that = this;
if (typeof x === "number") {
that.x = x;
that.y = y;
that.z = z;
should &&
y.should.Number &&
z.should.Number &&
isNaN(x).should.False &&
isNaN(y).should.False &&
isNaN(z).should.False;
} else {
var xyz = x;
should &&
xyz.x.should.Number &&
xyz.y.should.Number &&
xyz.z.should.Number;
that.x = xyz.x;
that.y = xyz.y;
that.z = xyz.z;
if (options == null) {
options = y;
}
}
options = options || {};
if (options.verbose) {
that.verbose = options.verbose;
}
return that;
}
XYZ.prototype.nearest = function(a, b) {
var that = this;
var adx = a.x - that.x;
var ady = a.y - that.y;
var adz = a.z - that.z;
var bdx = b.x - that.x;
var bdy = b.y - that.y;
var bdz = b.z - that.z;
var ad2 = adx * adx + ady * ady + adz * adz;
var bd2 = bdx * bdx + bdy * bdy + bdz * bdz;
return ad2 <= bd2 ? a : b;
}
XYZ.prototype.dot = function(xyz) {
var that = this;
return that.x * xyz.x + that.y * xyz.y + that.z * xyz.z;
}
XYZ.prototype.cross = function(xyz) {
var that = this;
return new XYZ(
that.y * xyz.z - that.z * xyz.y, -(that.x * xyz.z - that.z * xyz.x),
that.x * xyz.y - that.y * xyz.x,
that);
}
XYZ.prototype.interpolate = function(xyz, p) {
var that = this;
p = p == null ? 0.5 : p;
var p1 = 1 - p;
should &&
xyz.should.exist &&
xyz.x.should.Number &&
xyz.y.should.Number &&
xyz.z.should.Number;
return new XYZ(
p * xyz.x + p1 * that.x,
p * xyz.y + p1 * that.y,
p * xyz.z + p1 * that.z,
that);
}
XYZ.prototype.invalidate = function() {
var that = this;
delete that._norm;
}
XYZ.prototype.normSquared = function() {
var that = this;
return that.x * that.x + that.y * that.y + that.z * that.z;
}
XYZ.prototype.norm = function() {
var that = this;
if (that._norm == null) {
that._norm = Math.sqrt(that.normSquared());
}
return that._norm;
}
XYZ.prototype.minus = function(value) {
var that = this;
should &&
value.x.should.Number &&
value.y.should.Number &&
value.z.should.Number;
return new XYZ(that.x - value.x, that.y - value.y, that.z - value.z, that);
}
XYZ.prototype.plus = function(value) {
var that = this;
should &&
value.x.should.Number &&
value.y.should.Number &&
value.z.should.Number;
return new XYZ(that.x + value.x, that.y + value.y, that.z + value.z, that);
}
XYZ.prototype.equal = function(value, tolerance) {
var that = this;
if (value == null) {
that.verbose && console.log("XYZ.equal(null) => false");
return false;
}
if (value.x == null) {
that.verbose && console.log("XYZ.equal(value.x is null) => false");
return false;
}
if (value.y == null) {
that.verbose && console.log("XYZ.equal(value.y is null) => false");
return false;
}
if (value.z == null) {
that.verbose && console.log("XYZ.equal(value.z is null) => false");
return false;
}
tolerance = tolerance || 0;
var result = value.x - tolerance <= that.x && that.x <= value.x + tolerance &&
value.y - tolerance <= that.y && that.y <= value.y + tolerance &&
value.z - tolerance <= that.z && that.z <= value.z + tolerance;
that.verbose && !result && verboseLogger.debug("XYZ", that, ".equal(", value, ") => false");
return result;
}
XYZ.prototype.toString = function() {
var that = this;
var scale = 1000;
return "[" + Math.round(that.x * scale) / scale +
"," + Math.round(that.y * scale) / scale +
"," + Math.round(that.z * scale) / scale +
"]";
}
XYZ.prototype.multiply = function(m) {
var that = this;
if (m instanceof Mat3x3) {
return new XYZ(
m.get(0, 0) * that.x + m.get(0, 1) * that.y + m.get(0, 2) * that.z,
m.get(1, 0) * that.x + m.get(1, 1) * that.y + m.get(1, 2) * that.z,
m.get(2, 0) * that.x + m.get(2, 1) * that.y + m.get(2, 2) * that.z,
that);
}
should && m.should.Number;
return new XYZ(
m * that.x,
m * that.y,
m * that.z,
that);
}
/////////// class
XYZ.of = function(xyz, options) {
options = options || {};
if (xyz instanceof XYZ) {
return xyz;
}
if (options.strict) {
should &&
xyz.x.should.Number &&
xyz.y.should.Number &&
xyz.z.should.Number;
} else {
if (!xyz.x instanceof Number) {
return null;
}
if (!xyz.y instanceof Number) {
return null;
}
if (!xyz.z instanceof Number) {
return null;
}
}
return new XYZ(xyz.x, xyz.y, xyz.z, options);
}
XYZ.precisionDriftComparator = function(v1, v2) {
// comparator order will reveal
// any long-term precision drift
// as a horizontal visual break along x-axis
var s1 = v1.y < 0 ? -1 : 1;
var s2 = v2.y < 0 ? -1 : 1;
var cmp = s1 - s2;
cmp === 0 && (cmp = Math.round(v2.y) - Math.round(v1.y));
if (cmp === 0) {
var v1x = Math.round(v1.x);
var v2x = Math.round(v2.x);
cmp = v1.y < 0 ? v1x - v2x : v2x - v1x;
}
cmp === 0 && (cmp = v1.z - v2.z);
return cmp;
}
module.exports = exports.XYZ = XYZ;
})(typeof exports === "object" ? exports : (exports = {}));
// mocha -R min --inline-diffs *.js
(typeof describe === 'function') && describe("XYZ", function() {
var XYZ = require("./XYZ");
var options = {
verbose: true
};
it("XYZ(1,2,3) should create an XYZ coordinate", function() {
var xyz = new XYZ(1, 2, 3);
xyz.should.instanceOf(XYZ);
xyz.x.should.equal(1);
xyz.y.should.equal(2);
xyz.z.should.equal(3);
})
it("XYZ({x:1,y:2,z:3) should create an XYZ coordinate", function() {
var xyz = new XYZ(1, 2, 3);
var xyz2 = new XYZ(xyz);
xyz2.should.instanceOf(XYZ);
xyz2.x.should.equal(1);
xyz2.y.should.equal(2);
xyz2.z.should.equal(3);
var xyz3 = new XYZ({
x: 1,
y: 2,
z: 3
});
xyz2.should.instanceOf(XYZ);
xyz2.x.should.equal(1);
xyz2.y.should.equal(2);
xyz2.z.should.equal(3);
})
it("equal(value, tolerance) should return true if coordinates are same within tolerance", function() {
var xyz = new XYZ(1, 2, 3);
var xyz2 = new XYZ(xyz);
xyz.equal(xyz2).should.True;
xyz2.x = xyz.x - 0.00001;
xyz.equal(xyz2).should.False;
xyz.equal(xyz2, 0.00001).should.True;
xyz.equal(xyz2, 0.000001).should.False;
xyz2.x = xyz.x + 0.00001;
xyz.equal(xyz2).should.False;
xyz.equal(xyz2, 0.00001).should.True;
xyz.equal(xyz2, 0.000001).should.False;
})
it("norm() should return true the vector length", function() {
var e = 0.000001;
new XYZ(1, 2, 3).norm().should.within(3.741657 - e, 3.741657 + e);
new XYZ(-1, 2, 3).norm().should.within(3.741657 - e, 3.741657 + e);
new XYZ(1, -2, 3).norm().should.within(3.741657 - e, 3.741657 + e);
new XYZ(1, -2, -3).norm().should.within(3.741657 - e, 3.741657 + e);
new XYZ(1, 0, 1).norm().should.within(1.414213 - e, 1.414213 + e);
new XYZ(0, 1, 1).norm().should.within(1.414213 - e, 1.414213 + e);
new XYZ(1, 1, 0).norm().should.within(1.414213 - e, 1.414213 + e);
})
it("normSquared() should return norm squared", function() {
var xyz = new XYZ(1, 2, 3);
xyz.norm().should.equal(Math.sqrt(xyz.normSquared()));
})
it("minus(value) should return vector difference", function() {
var xyz1 = new XYZ(1, 2, 3);
var xyz2 = new XYZ(10, 20, 30);
var xyz3 = xyz1.minus(xyz2);
xyz3.equal({
x: -9,
y: -18,
z: -27
}).should.True;
})
it("plus(value) should return vector sum", function() {
var xyz1 = new XYZ(1, 2, 3);
var xyz2 = new XYZ(10, 20, 30);
var xyz3 = xyz1.plus(xyz2);
xyz3.equal({
x: 11,
y: 22,
z: 33
}).should.True;
})
it("interpolate(xyz,p) should interpolate to given point for p[0,1]", function() {
var pt1 = new XYZ(1, 1, 1, {
verbose: true
});
var pt2 = new XYZ(10, 20, 30, {
verbose: true
});
pt1.interpolate(pt2, 0).equal(pt1).should.True;
pt1.interpolate(pt2, 1).equal(pt2).should.True;
pt1.interpolate(pt2, 0.1).equal({
x: 1.9,
y: 2.9,
z: 3.9
}).should.True;
});
it("XYZ.of(pt) should return an XYZ object for given point", function() {
var xyz = XYZ.of({
x: 1,
y: 2,
z: 3
});
xyz.should.instanceOf.XYZ;
var xyz2 = XYZ.of(xyz);
xyz2.should.equal(xyz);
});
it("cross(xyz) returns cross product with xyz", function() {
var v1 = new XYZ(1, 2, 3, options);
var v2 = new XYZ(4, 5, 6, options);
var cross = v1.cross(v2);
var e = 0;
cross.equal({
x: -3,
y: 6,
z: -3,
e
}).should.True;
});
it("teString() returns concise string representation", function() {
new XYZ(1, 2, 3).toString().should.equal("[1,2,3]");
new XYZ(1.001, 2.0001, -3.001).toString().should.equal("[1.001,2,-3.001]");
new XYZ(1.001, 2.0001, -3.001).toString().should.equal("[1.001,2,-3.001]");
})
it("dot(xyz) returns dot product with xyz", function() {
var v1 = new XYZ(1, 2, 3, options);
var v2 = new XYZ(4, 5, 6, options);
var dot = v1.dot(v2);
dot.should.equal(32);
});
it("nearest(a,b) returns nearest point", function() {
var vx = new XYZ(1, 0, 0);
var vy = new XYZ(0, 1, 0);
var vz = new XYZ(0, 0, 1);
new XYZ(2, 0, 0).nearest(vx, vy).should.equal(vx);
new XYZ(0, 0, 2).nearest(vx, vy).should.equal(vx);
new XYZ(0, 2, 0).nearest(vx, vy).should.equal(vy);
new XYZ(0, 2, 0).nearest(vz, vy).should.equal(vy);
new XYZ(0, 0, 2).nearest(vy, vz).should.equal(vz);
new XYZ(0, 0, 2).nearest(vx, vz).should.equal(vz);
});
it("precisionDriftComparator(v1,v2) sorts scanned vertices to reveal long-term precision drift", function() {
XYZ.precisionDriftComparator(new XYZ(1, 2, 3), new XYZ(1, 2, 3)).should.equal(0);
XYZ.precisionDriftComparator(new XYZ(1, -2, 3), new XYZ(1, -2, 3)).should.equal(0);
XYZ.precisionDriftComparator(new XYZ(1, -2, 3), new XYZ(1, 2, 3)).should.below(0);
XYZ.precisionDriftComparator(new XYZ(1, 2, 3), new XYZ(1, -2, 3)).should.above(0);
XYZ.precisionDriftComparator(new XYZ(1, -2, 3), new XYZ(1, -3, 3)).should.below(0);
XYZ.precisionDriftComparator(new XYZ(1, -2, 3), new XYZ(2, -2, 3)).should.below(0);
XYZ.precisionDriftComparator(new XYZ(1, 2, 3), new XYZ(2, 2, 3)).should.above(0);
XYZ.precisionDriftComparator(new XYZ(1, 2, 3), new XYZ(1, 3, 3)).should.above(0);
});
})
| firepick1/firenodejs | www/js/shared/XYZ.js | JavaScript | mit | 12,537 |
<?php
/**
* Author: Wing Ming Chan
* Copyright (c) 2014 Wing Ming Chan <chanw@upstate.edu>
* MIT Licensed
* Modification history:
*/
class EmptyNameException extends Exception{}
?> | alynch-ece-its/php-cascade-ws | exception_classes/EmptyNameException.class.php | PHP | mit | 189 |
<?php
/**
* Symfony REST Edition.
*
* @link https://github.com/Ingewikkeld/symfony-rest-edition
* @copyright Copyright (c) 2013-2013 Ingewikkeld<info@ingewikkeld.net>
* @license https://github.com/Ingewikkeld/symfony-rest-edition/blob/master/LICENSE MIT License
*/
namespace Ingewikkeld\Rest\OAuthServerBundle\Form;
use Ingewikkeld\Rest\ResourceBundle\Resource\FormTypeInterface;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\Validator\Constraints\All;
use Symfony\Component\Validator\Constraints\NotBlank;
use Symfony\Component\Validator\Constraints\Url;
class ClientType extends AbstractType implements FormTypeInterface
{
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add(
'redirectUris',
'collection',
array(
'required' => true,
'type' => 'url',
'constraints' => new All(
array(
'constraints' => array(
new NotBlank(),
new Url()
)
)
)
)
)
->add(
'grants',
'choice',
array(
'required' => false,
'choices' => array(
'token' => 'token',
'authorization_code' => 'authorization_code'
),
'multiple' => true
)
);
}
/**
* Returns the name of this type.
*
* @return string The name of this type
*/
public function getName()
{
return 'client';
}
}
| Ingewikkeld/oauth-server-bundle | src/Ingewikkeld/Rest/OAuthServerBundle/Form/ClientType.php | PHP | mit | 1,885 |
#-- copyright
# OpenProject is a project management system.
# Copyright (C) 2012-2013 the OpenProject Foundation (OPF)
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License version 3.
#
# OpenProject is a fork of ChiliProject, which is a fork of Redmine. The copyright follows:
# Copyright (C) 2006-2013 Jean-Philippe Lang
# Copyright (C) 2010-2013 the ChiliProject Team
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
#
# See doc/COPYRIGHT.rdoc for more details.
#++
class MigratePlanningElementTypeToProjectAssociation < ActiveRecord::Migration
{
:DefaultPlanningElementType => 'timelines_default_planning_element_types',
:EnabledPlanningElementType => 'timelines_enabled_planning_element_types',
:PlanningElementType => 'timelines_planning_element_types',
:Project => 'projects',
:ProjectType => 'timelines_project_types'
}.each do |class_name, table_name|
self.const_set(class_name, Class.new(ActiveRecord::Base) do
self.table_name = table_name
end)
end
def self.up
DefaultPlanningElementType.delete_all
EnabledPlanningElementType.delete_all
PlanningElementType.all.each do |planning_element_type|
# Ignore global planning element types. They are not associated with
# anything.
next unless planning_element_type.project_type_id.present?
project_type = ProjectType.find(planning_element_type.project_type_id)
DefaultPlanningElementType.create!(:project_type_id => project_type.id,
:planning_element_type_id => planning_element_type.id)
Project.find(:all, :conditions => {:timelines_project_type_id => project_type.id}).each do |project|
EnabledPlanningElementType.create!(:project_id => project.id,
:planning_element_type_id => planning_element_type.id)
end
end
end
def self.down
# Chosing to not throw a AR::IrreversibleMigration since this would
# hinder the default uninstall recommendations of ChiliProject plugins.
#
# Anyway - this migration is irreversible nonetheless. The new schema
# allows associations, that cannot be expressed by the old one. Going past
# this migration backwards in time, will lead to data loss.
#
#
# raise ActiveRecord::IrreversibleMigration
end
end
| mximos/openproject-heroku | db/migrate/20130409133713_migrate_planning_element_type_to_project_association.rb | Ruby | mit | 3,124 |
<?php
require __DIR__.'/../protected/vendor/autoload.php';
require __DIR__.'/../protected/start.php';
| MightyPork/wrack | public/index.php | PHP | mit | 104 |
/*
* oxAuth is available under the MIT License (2008). See http://opensource.org/licenses/MIT for full text.
*
* Copyright (c) 2014, Gluu
*/
package org.gluu.oxauth.util;
import org.gluu.oxauth.model.common.ResponseMode;
import org.jboss.resteasy.specimpl.ResponseBuilderImpl;
import org.json.JSONException;
import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.servlet.http.HttpServletRequest;
import javax.ws.rs.core.CacheControl;
import javax.ws.rs.core.GenericEntity;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.Response.ResponseBuilder;
import java.net.MalformedURLException;
import java.net.URI;
import static org.gluu.oxauth.client.AuthorizationRequest.NO_REDIRECT_HEADER;
/**
* @version October 7, 2019
*/
public class RedirectUtil {
private final static Logger log = LoggerFactory.getLogger(RedirectUtil.class);
static String JSON_REDIRECT_PROPNAME = "redirect";
static int HTTP_REDIRECT = 302;
public static ResponseBuilder getRedirectResponseBuilder(RedirectUri redirectUriResponse, HttpServletRequest httpRequest) {
ResponseBuilder builder;
if (httpRequest != null && httpRequest.getHeader(NO_REDIRECT_HEADER) != null) {
try {
URI redirectURI = URI.create(redirectUriResponse.toString());
JSONObject jsonObject = new JSONObject();
jsonObject.put(JSON_REDIRECT_PROPNAME, redirectURI.toURL());
String jsonResp = jsonObject.toString();
jsonResp = jsonResp.replace("\\/", "/");
builder = Response.ok(
new GenericEntity<String>(jsonResp, String.class),
MediaType.APPLICATION_JSON_TYPE
);
} catch (MalformedURLException e) {
builder = Response.serverError();
log.debug(e.getMessage(), e);
} catch (JSONException e) {
builder = Response.serverError();
log.debug(e.getMessage(), e);
}
} else if (redirectUriResponse.getResponseMode() != ResponseMode.FORM_POST) {
URI redirectURI = URI.create(redirectUriResponse.toString());
builder = new ResponseBuilderImpl();
builder = Response.status(HTTP_REDIRECT);
builder.location(redirectURI);
} else {
builder = new ResponseBuilderImpl();
builder.status(Response.Status.OK);
builder.type(MediaType.TEXT_HTML_TYPE);
builder.cacheControl(CacheControl.valueOf("no-cache, no-store"));
builder.header("Pragma", "no-cache");
builder.entity(redirectUriResponse.toString());
}
return builder;
}
}
| GluuFederation/oxAuth | Server/src/main/java/org/gluu/oxauth/util/RedirectUtil.java | Java | mit | 2,806 |
<?php //-->
include __DIR__ . '/src/events.php';
| CradlePHP/sink-faucet | .cradle.php | PHP | mit | 49 |
var mongoose = require('mongoose');
var Shape = require('./Shape');
var User = require('./User');
// Create a session model, _id will be assigned by Mongoose
var CanvasSessionSchema = new mongoose.Schema(
{
_id: String,
users: [User],
dateCreated: Date,
dateUpdated: Date,
// canDraw: Boolean,
// canChat: Boolean,
// maxUsers: Number,
sessionProperties: {
canDraw: Boolean,
canChat: Boolean,
maxUsers: Number
},
//canvasModel: { type: Object },
canvasShapes: { type: Array, unique: true, index: true },
messages: Array
},
{ autoIndex: false }
);
// Make Session available to rest of the application
module.exports = mongoose.model('Session', CanvasSessionSchema);
| OpenSketch-Application/OpenSketch | server/db/models/Session.js | JavaScript | mit | 740 |
import os
import shutil
from glob import glob
print 'Content-type:text/html\r\n\r\n'
print '<html>'
found_pages = glob('archive/*.py')
if found_pages:
path = "/cgi-bin/archive/"
moveto = "/cgi-bin/pages/"
files = os.listdir(path)
files.sort()
for f in files:
src = path+f
dst = moveto+f
shutil.move(src, dst)
print 'All pages restored'
print '<meta http-equiv="refresh" content="1";>'
if not found_pages:
print 'Nothing to restore'
print '</html>'
# EOF
| neva-nevan/ConfigPy | ConfigPy-Portable/ConfigPy/cgi-bin/restore.py | Python | mit | 516 |
import config from '../components/configLoader';
import { addToDefaultPluginDOM } from '../components/helpers';
const pluginConfig = config.plugins.find(obj => obj.name === 'age');
// DOM setup
const pluginId = 'js-plugin-age';
addToDefaultPluginDOM(pluginId);
const ageDOM = document.getElementById(pluginId);
const renderAge = () => {
const { birthday, goal } = pluginConfig;
// Inspired by:
// Alex MacCaw https://github.com/maccman/motivation
const now = new Date();
const age = (now - new Date(birthday)) / 3.1556952e+10; // divided by 1 year in ms
let remainder = 100 - (age / goal * 100);
let goalPrefix = 'left until';
if (remainder < 0) {
goalPrefix = 'over goal of';
remainder = -remainder;
}
ageDOM.innerHTML = `Age: ${age.toFixed(5)}, ${remainder.toFixed(2)}% ${goalPrefix} ${goal}`;
};
// Initialize plugin
export const init = () => renderAge(); // eslint-disable-line import/prefer-default-export
| michaelx/Launchbot | src/js/plugins/age.js | JavaScript | mit | 950 |
package filediff.myers;
public class DifferentiationFailedException extends DiffException {
private static final long serialVersionUID = 1L;
public DifferentiationFailedException() {
}
public DifferentiationFailedException(String msg) {
super(msg);
}
}
| nendhruv/data-dictionary | src/java/filediff/myers/DifferentiationFailedException.java | Java | mit | 294 |
Meteor.startup(function () {
});
Deps.autorun(function(){
Meteor.subscribe('userData');
}); | nikhilpi/klick | client/startup/default.js | JavaScript | mit | 94 |
<?php
namespace Aleste\TrackerBundle\Command;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Output\OutputInterface;
use Doctrine\ORM\EntityManager;
class AvisosCommand extends Command
{
protected $em;
public function __construct(EntityManager $em)
{
$this->em = $em;
parent::__construct();
}
protected function configure()
{
$this
->setName('gestion:sendAvisos')
->setDescription('Envía mensajes de aviso vía Emails')
->addArgument(
'limit',
InputArgument::OPTIONAL,
'Cantidad limite de mensajes por ejecución'
)
;
}
protected function execute(InputInterface $input, OutputInterface $output)
{
$documentos = $this->em->getRepository('TrackerBundle:Documento')->findAll();
$limit = ($input->getArgument('limit') == null ? 10 : $input->getArgument('limit'));
$cant = 0;
foreach ($documentos as $documento) {
if ($cant < $limit) {
$output->writeln($documento->__toString());
$cant++;
}
}
}
} | mgroizard/Tracker | src/Aleste/TrackerBundle/Command/AvisosCommand.php | PHP | mit | 1,400 |
package serial
//go:generate go run v2ray.com/core/common/errors/errorgen
| v2ray/v2ray-core | infra/conf/serial/serial.go | GO | mit | 75 |
<?php
/**
* (c) 2011 - ∞ Vespolina Project http://www.vespolina-project.org
*
* This source file is subject to the MIT license that is bundled
* with this source code in the file LICENSE.
*/
namespace Vespolina\Tests\Sync\Functional\Entity;
class LocalProductCategory
{
public $name;
public function getId()
{
return $this->name;
}
}
| vespolina/syncer | tests/Vespolina/Tests/Sync/Functional/Entity/LocalProductCategory.php | PHP | mit | 369 |
require 'rubygems'
require 'test/unit'
require 'shoulda'
$LOAD_PATH.unshift(File.join(File.dirname(__FILE__), '..', 'lib'))
$LOAD_PATH.unshift(File.dirname(__FILE__))
require 'ftp-ext'
class Test::Unit::TestCase
end
| zachpendleton/ftp-ext | test/helper.rb | Ruby | mit | 218 |
/*
* Copyright 2012 Google 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 ua.org.gdg.devfest.iosched.receiver;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import ua.org.gdg.devfest.iosched.service.SessionAlarmService;
import static ua.org.gdg.devfest.iosched.util.LogUtils.makeLogTag;
/**
* {@link BroadcastReceiver} to reinitialize {@link android.app.AlarmManager} for all starred
* session blocks.
*/
public class SessionAlarmReceiver extends BroadcastReceiver {
public static final String TAG = makeLogTag(SessionAlarmReceiver.class);
@Override
public void onReceive(Context context, Intent intent) {
Intent scheduleIntent = new Intent(
SessionAlarmService.ACTION_SCHEDULE_ALL_STARRED_BLOCKS,
null, context, SessionAlarmService.class);
context.startService(scheduleIntent);
}
}
| zasadnyy/android-hothack-13 | example/source/src/main/java/ua/org/gdg/devfest/iosched/receiver/SessionAlarmReceiver.java | Java | mit | 1,444 |
using System.Text;
public class Engine
{
private const string offset = " ";
public string model;
public int power;
public int displacement;
public string efficiency;
public Engine(string model, int power)
{
this.model = model;
this.power = power;
this.displacement = -1;
this.efficiency = "n/a";
}
public Engine(string model, int power, int displacement): this(model, power)
{
this.displacement = displacement;
}
public Engine(string model, int power, string efficiency) : this(model, power)
{
this.efficiency = efficiency;
}
public Engine(string model, int power, int displacement, string efficiency) : this(model, power)
{
this.displacement = displacement;
this.efficiency = efficiency;
}
public override string ToString()
{
StringBuilder sb = new StringBuilder();
sb.AppendFormat("{0}{1}:\n", offset, this.model);
sb.AppendFormat("{0}{0}Power: {1}\n", offset, this.power);
sb.AppendFormat("{0}{0}Displacement: {1}\n", offset, this.displacement == -1 ? "n/a" : this.displacement.ToString());
sb.AppendFormat("{0}{0}Efficiency: {1}\n", offset, this.efficiency);
return sb.ToString();
}
} | MrPIvanov/SoftUni | 05-Csharp OOP Basics/06-EXERCISE WORKING WITH ABSTRACTION/06-AbstractionExercises/02-CarsSalesman/Engine.cs | C# | mit | 1,294 |
from itertools import permutations
import re
def create_formula(combination,numbers):
formula = ""
index = 0
for op in combination:
formula += str(numbers[index]) + op
index += 1
formula += numbers[index]
return formula
'''
Unnecessary Funtion
'''
def evaluate(form):
result = 0
for index in range(len(form)):
if form[index] == "+":
result += int(form[index+1])
index += 1
elif form[index] == "-":
result -= int(form[index+1])
index += 1
elif form[index] == "*":
result *= int(form[index+1])
index += 1
elif form[index] == "/":
result //= int(form[index+1])
index += 1
else:
result += int(form[index])
return result
def countdown(numbers):
rightCombinations = []
finalScore = numbers.pop()
combinations = returnAllCombinations(len(numbers) - 1)
perms = list(permutations(numbers))
for combination in combinations:
for permut in perms:
formula = create_formula(combination,permut)
#form = re.split("([*+-/])",formula)
#if int(evaluate(form)) == int(finalScore):
if int(eval(formula)) == int(finalScore):
rightCombinations.append(formula)
return rightCombinations
def returnAllCombinations(size):
listFinal = []
for x in range(0,size):
if len(listFinal) == 0:
for y in range(0,4):
if y == 0:
listFinal.append("+")
elif y == 1:
listFinal.append("-")
elif y == 2:
listFinal.append("*")
else:
listFinal.append("/")
else:
newList = []
for l in listFinal:
for y in range(0,4):
newLine = list(l)
if y == 0:
newLine.append("+")
elif y == 1:
newLine.append("-")
elif y == 2:
newLine.append("*")
else:
newLine.append("/")
newList.append(newLine)
listFinal = list(newList)
return listFinal
out = open("output.txt",'w')
for line in open("input.txt",'r'):
for formula in countdown(line.split(" ")):
out.write(formula)
out.write("\n")
out.write("\n\n")
| F0lha/UJunior-Projects | DailyProgrammer/Challenge#318/src.py | Python | mit | 2,546 |
// will this be needed?
var getMotionEventName = function(type) {
var t;
var el = document.createElement('fakeelement');
var map = {};
if (type == 'transition') {
map = {
'transition': 'transitionend',
'OTransition': 'oTransitionEnd',
'MozTransition': 'transitionend',
'WebkitTransition': 'webkitTransitionEnd'
};
} else if (type == 'animation') {
map = {
'animation': 'animationend',
'OAnimation': 'oAnimationEnd',
'MozAnimation': 'animationend',
'WebkitAnimation': 'webkitAnimationEnd'
};
};
for (t in map) {
if (el.style[t] !== undefined) {
return map[t];
}
}
};
| mwyatt/dialogue | js/getMotionEventName.js | JavaScript | mit | 710 |
<?php
return [
/*
|--------------------------------------------------------------------------
| Application Environment
|--------------------------------------------------------------------------
|
| This value determines the "environment" your application is currently
| running in. This may determine how you prefer to configure various
| services your application utilizes. Set this in your ".env" file.
|
*/
'env' => env('APP_ENV', 'production'),
/*
|--------------------------------------------------------------------------
| Application Debug Mode
|--------------------------------------------------------------------------
|
| When your application is in debug mode, detailed error messages with
| stack traces will be shown on every error that occurs within your
| application. If disabled, a simple generic error page is shown.
|
*/
'debug' => env('APP_DEBUG', false),
/*
|--------------------------------------------------------------------------
| Application URL
|--------------------------------------------------------------------------
|
| This URL is used by the console to properly generate URLs when using
| the Artisan command line tool. You should set this to the root of
| your application so that it is used when running Artisan tasks.
|
*/
'url' => env('APP_URL', 'http://localhost'),
/*
|--------------------------------------------------------------------------
| Application Timezone
|--------------------------------------------------------------------------
|
| Here you may specify the default timezone for your application, which
| will be used by the PHP date and date-time functions. We have gone
| ahead and set this to a sensible default for you out of the box.
|
*/
'timezone' => 'UTC',
/*
|--------------------------------------------------------------------------
| Application Locale Configuration
|--------------------------------------------------------------------------
|
| The application locale determines the default locale that will be used
| by the translation service provider. You are free to set this value
| to any of the locales which will be supported by the application.
|
*/
'locale' => 'en',
/*
|--------------------------------------------------------------------------
| Application Fallback Locale
|--------------------------------------------------------------------------
|
| The fallback locale determines the locale to use when the current one
| is not available. You may change the value to correspond to any of
| the language folders that are provided through your application.
|
*/
'fallback_locale' => 'en',
/*
|--------------------------------------------------------------------------
| Encryption Key
|--------------------------------------------------------------------------
|
| This key is used by the Illuminate encrypter service and should be set
| to a random, 32 character string, otherwise these encrypted strings
| will not be safe. Please do this before deploying an application!
|
*/
'key' => env('APP_KEY'),
'cipher' => 'AES-256-CBC',
/*
|--------------------------------------------------------------------------
| Logging Configuration
|--------------------------------------------------------------------------
|
| Here you may configure the log settings for your application. Out of
| the box, Laravel uses the Monolog PHP logging library. This gives
| you a variety of powerful log handlers / formatters to utilize.
|
| Available Settings: "single", "daily", "syslog", "errorlog"
|
*/
'log' => env('APP_LOG', 'single'),
/*
|--------------------------------------------------------------------------
| Autoloaded Service Providers
|--------------------------------------------------------------------------
|
| The service providers listed here will be automatically loaded on the
| request to your application. Feel free to add your own services to
| this array to grant expanded functionality to your applications.
|
*/
'providers' => [
/*
* Laravel Framework Service Providers...
*/
Illuminate\Auth\AuthServiceProvider::class,
Illuminate\Broadcasting\BroadcastServiceProvider::class,
Illuminate\Bus\BusServiceProvider::class,
Illuminate\Cache\CacheServiceProvider::class,
Illuminate\Foundation\Providers\ConsoleSupportServiceProvider::class,
Illuminate\Cookie\CookieServiceProvider::class,
Illuminate\Database\DatabaseServiceProvider::class,
Illuminate\Encryption\EncryptionServiceProvider::class,
Illuminate\Filesystem\FilesystemServiceProvider::class,
Illuminate\Foundation\Providers\FoundationServiceProvider::class,
Illuminate\Hashing\HashServiceProvider::class,
Illuminate\Mail\MailServiceProvider::class,
Illuminate\Pagination\PaginationServiceProvider::class,
Illuminate\Pipeline\PipelineServiceProvider::class,
Illuminate\Queue\QueueServiceProvider::class,
Illuminate\Redis\RedisServiceProvider::class,
Illuminate\Auth\Passwords\PasswordResetServiceProvider::class,
Illuminate\Session\SessionServiceProvider::class,
Illuminate\Translation\TranslationServiceProvider::class,
Illuminate\Validation\ValidationServiceProvider::class,
Illuminate\View\ViewServiceProvider::class,
Collective\Html\HtmlServiceProvider::class,
Vsmoraes\Pdf\PdfServiceProvider::class,
/*
* Application Service Providers...
*/
App\Providers\AppServiceProvider::class,
App\Providers\AuthServiceProvider::class,
App\Providers\EventServiceProvider::class,
App\Providers\RouteServiceProvider::class,
],
/*
|--------------------------------------------------------------------------
| Class Aliases
|--------------------------------------------------------------------------
|
| This array of class aliases will be registered when this application
| is started. However, feel free to register as many as you wish as
| the aliases are "lazy" loaded so they don't hinder performance.
|
*/
'aliases' => [
'App' => Illuminate\Support\Facades\App::class,
'Artisan' => Illuminate\Support\Facades\Artisan::class,
'Auth' => Illuminate\Support\Facades\Auth::class,
'Blade' => Illuminate\Support\Facades\Blade::class,
'Cache' => Illuminate\Support\Facades\Cache::class,
'Config' => Illuminate\Support\Facades\Config::class,
'Cookie' => Illuminate\Support\Facades\Cookie::class,
'Crypt' => Illuminate\Support\Facades\Crypt::class,
'DB' => Illuminate\Support\Facades\DB::class,
'Eloquent' => Illuminate\Database\Eloquent\Model::class,
'Event' => Illuminate\Support\Facades\Event::class,
'File' => Illuminate\Support\Facades\File::class,
'Gate' => Illuminate\Support\Facades\Gate::class,
'Hash' => Illuminate\Support\Facades\Hash::class,
'Lang' => Illuminate\Support\Facades\Lang::class,
'Log' => Illuminate\Support\Facades\Log::class,
'Mail' => Illuminate\Support\Facades\Mail::class,
'Password' => Illuminate\Support\Facades\Password::class,
'Queue' => Illuminate\Support\Facades\Queue::class,
'Redirect' => Illuminate\Support\Facades\Redirect::class,
'Redis' => Illuminate\Support\Facades\Redis::class,
'Request' => Illuminate\Support\Facades\Request::class,
'Response' => Illuminate\Support\Facades\Response::class,
'Route' => Illuminate\Support\Facades\Route::class,
'Schema' => Illuminate\Support\Facades\Schema::class,
'Session' => Illuminate\Support\Facades\Session::class,
'Storage' => Illuminate\Support\Facades\Storage::class,
'URL' => Illuminate\Support\Facades\URL::class,
'Validator' => Illuminate\Support\Facades\Validator::class,
'View' => Illuminate\Support\Facades\View::class,
'Form' => Collective\Html\FormFacade::class,
'Html' => Collective\Html\HtmlFacade::class,
'PDF' => Vsmoraes\Pdf\PdfFacade::class,
],
];
| milanbrckalo/cvator | config/app.php | PHP | mit | 8,504 |
package soymsg
import (
"bytes"
"regexp"
"strconv"
"strings"
"github.com/robfig/soy/ast"
)
// setPlaceholderNames generates the placeholder names for all children of the
// given message node, setting the .Name property on them.
func setPlaceholderNames(n *ast.MsgNode) {
// Step 1: Determine representative nodes and build preliminary map
var (
baseNameToRepNodes = make(map[string][]ast.Node)
equivNodeToRepNodes = make(map[ast.Node]ast.Node)
)
var nodeQueue []ast.Node = phNodes(n.Body)
for len(nodeQueue) > 0 {
var node = nodeQueue[0]
nodeQueue = nodeQueue[1:]
var baseName string
switch node := node.(type) {
case *ast.MsgPlaceholderNode:
baseName = genBasePlaceholderName(node.Body, "XXX")
case *ast.MsgPluralNode:
nodeQueue = append(nodeQueue, pluralCaseBodies(node)...)
baseName = genBasePlaceholderName(node.Value, "NUM")
default:
panic("unexpected")
}
if nodes, ok := baseNameToRepNodes[baseName]; !ok {
baseNameToRepNodes[baseName] = []ast.Node{node}
} else {
var isNew = true
var str = node.String()
for _, other := range nodes {
if other.String() == str {
equivNodeToRepNodes[node] = other
isNew = false
break
}
}
if isNew {
baseNameToRepNodes[baseName] = append(nodes, node)
}
}
}
// Step 2: Build final maps of name to representative node
var nameToRepNodes = make(map[string]ast.Node)
for baseName, nodes := range baseNameToRepNodes {
if len(nodes) == 1 {
nameToRepNodes[baseName] = nodes[0]
continue
}
var nextSuffix = 1
for _, node := range nodes {
for {
var newName = baseName + "_" + strconv.Itoa(nextSuffix)
if _, ok := nameToRepNodes[newName]; !ok {
nameToRepNodes[newName] = node
break
}
nextSuffix++
}
}
}
// Step 3: Create maps of every node to its name
var nodeToName = make(map[ast.Node]string)
for name, node := range nameToRepNodes {
nodeToName[node] = name
}
for other, repNode := range equivNodeToRepNodes {
nodeToName[other] = nodeToName[repNode]
}
// Step 4: Set the calculated names on all the nodes.
for node, name := range nodeToName {
switch node := node.(type) {
case *ast.MsgPlaceholderNode:
node.Name = name
case *ast.MsgPluralNode:
node.VarName = name
default:
panic("unexpected: " + node.String())
}
}
}
func phNodes(n ast.ParentNode) []ast.Node {
var nodeQueue []ast.Node
for _, child := range n.Children() {
switch child := child.(type) {
case *ast.MsgPlaceholderNode, *ast.MsgPluralNode:
nodeQueue = append(nodeQueue, child)
}
}
return nodeQueue
}
func pluralCaseBodies(node *ast.MsgPluralNode) []ast.Node {
var r []ast.Node
for _, plCase := range node.Cases {
r = append(r, phNodes(plCase.Body)...)
}
return append(r, phNodes(node.Default)...)
}
func genBasePlaceholderName(node ast.Node, defaultName string) string {
// TODO: user supplied placeholder (phname)
switch part := node.(type) {
case *ast.PrintNode:
return genBasePlaceholderNameFromExpr(part.Arg, defaultName)
case *ast.MsgHtmlTagNode:
return genBasePlaceholderNameFromHtml(part)
case *ast.DataRefNode:
return genBasePlaceholderNameFromExpr(node, defaultName)
}
return defaultName
}
func genBasePlaceholderNameFromExpr(expr ast.Node, defaultName string) string {
switch expr := expr.(type) {
case *ast.GlobalNode:
return toUpperUnderscore(expr.Name)
case *ast.DataRefNode:
if len(expr.Access) == 0 {
return toUpperUnderscore(expr.Key)
}
var lastChild = expr.Access[len(expr.Access)-1]
if lastChild, ok := lastChild.(*ast.DataRefKeyNode); ok {
return toUpperUnderscore(lastChild.Key)
}
}
return defaultName
}
var htmlTagNames = map[string]string{
"a": "link",
"br": "break",
"b": "bold",
"i": "italic",
"li": "item",
"ol": "ordered_list",
"ul": "unordered_list",
"p": "paragraph",
"img": "image",
"em": "emphasis",
}
func genBasePlaceholderNameFromHtml(node *ast.MsgHtmlTagNode) string {
var tag, tagType = tagName(node.Text)
if prettyName, ok := htmlTagNames[tag]; ok {
tag = prettyName
}
return toUpperUnderscore(tagType + tag)
}
func tagName(text []byte) (name, tagType string) {
switch {
case bytes.HasPrefix(text, []byte("</")):
tagType = "END_"
case bytes.HasSuffix(text, []byte("/>")):
tagType = ""
default:
tagType = "START_"
}
text = bytes.TrimPrefix(text, []byte("<"))
text = bytes.TrimPrefix(text, []byte("/"))
for i, ch := range text {
if !isAlphaNumeric(ch) {
return strings.ToLower(string(text[:i])), tagType
}
}
// the parser should never produce html tag nodes that tagName can't handle.
panic("no tag name found: " + string(text))
}
func isAlphaNumeric(r byte) bool {
return 'A' <= r && r <= 'Z' ||
'a' <= r && r <= 'z' ||
'0' <= r && r <= '9'
}
var (
leadingOrTrailing_ = regexp.MustCompile("^_+|_+$")
consecutive_ = regexp.MustCompile("__+")
wordBoundary1 = regexp.MustCompile("([a-zA-Z])([A-Z][a-z])") // <letter>_<upper><lower>
wordBoundary2 = regexp.MustCompile("([a-zA-Z])([0-9])") // <letter>_<digit>
wordBoundary3 = regexp.MustCompile("([0-9])([a-zA-Z])") // <digit>_<letter>
)
func toUpperUnderscore(ident string) string {
ident = leadingOrTrailing_.ReplaceAllString(ident, "")
ident = consecutive_.ReplaceAllString(ident, "${1}_${2}")
ident = wordBoundary1.ReplaceAllString(ident, "${1}_${2}")
ident = wordBoundary2.ReplaceAllString(ident, "${1}_${2}")
ident = wordBoundary3.ReplaceAllString(ident, "${1}_${2}")
return strings.ToUpper(ident)
}
| robfig/soy | soymsg/placeholder.go | GO | mit | 5,537 |
RSpec.describe "vm_types" do
let(:vm_types) { manifest_with_defaults.fetch("vm_types") }
describe "the router pool" do
let(:pool) { vm_types.find { |p| p["name"] == "router" } }
it "should use the correct elb instance" do
expect(pool["cloud_properties"]["elbs"]).to match_array([
terraform_fixture(:cf_router_elb_name),
])
end
end
end
| jimconner/paas-cf | manifests/cf-manifest/spec/cloud-config/vm_types_spec.rb | Ruby | mit | 376 |
// Include gulp
import gulp from 'gulp';
import fs from 'fs';
// Include Our Plugins
import eslint from 'gulp-eslint';
import mocha from 'gulp-mocha';
import browserSyncJs from 'browser-sync';
import sassJs from 'gulp-sass';
import sassCompiler from 'sass';
import rename from "gulp-rename";
import uglify from 'gulp-uglify';
import postcss from 'gulp-postcss';
import replace from 'gulp-replace';
import autoprefixer from 'autoprefixer';
import gulpStylelint from '@ronilaukkarinen/gulp-stylelint';
const browserSync = browserSyncJs.create();
const pkg = JSON.parse(fs.readFileSync('./package.json'));
const sass = sassJs(sassCompiler);
const doEslint = function() {
return gulp.src(
[
'*.js',
pkg.directories.bin + '/**/*',
pkg.directories.lib + '/**/*.js',
pkg.directories.test + '/**/*.js'
])
.pipe(eslint())
.pipe(eslint.format())
// .pipe(eslint.failAfterError())
;
};
const doMocha = function() {
return gulp.src(pkg.directories.test + '/**/*.js', {read: false})
.pipe(mocha({
reporter: 'dot'
}))
;
};
const buildJs = function() {
return gulp.src(pkg.directories.theme + '/**/js-src/*.js')
.pipe(eslint())
.pipe(eslint.format())
//.pipe(eslint.failAfterError())
.pipe(rename(function(path){
path.dirname = path.dirname.replace(/js-src/, 'js');
}))
.pipe(uglify({output: {
max_line_len: 9000
}}))
.pipe(gulp.dest(pkg.directories.theme))
;
};
const buildCss = function() {
return gulp.src(pkg.directories.theme + '/**/*.scss')
.pipe(gulpStylelint({
reporters: [
{formatter: 'string', console: true}
]
}))
.pipe(sass().on('error', sass.logError))
.pipe(postcss([
autoprefixer()
]))
.pipe(rename(function(path){
path.dirname = path.dirname.replace(/sass/, 'css');
}))
.pipe(replace(/(\n)\s*\n/g, '$1'))
.pipe(gulp.dest(pkg.directories.theme))
;
};
const serve = function() {
browserSync.init({
server: pkg.directories.htdocs,
port: 8080
});
gulp.watch(pkg.directories.htdocs + '/**/*').on('change', browserSync.reload);
};
// Watch Files For Changes
const watch = function() {
gulp.watch(['gulpfile.js', 'package.json'], process.exit);
gulp.watch(
[
'*.js', pkg.directories.bin + '/**/*',
pkg.directories.lib + '/**/*.js',
pkg.directories.test + '/**/*.js'
],
test
);
gulp.watch(pkg.directories.theme + '/**/*.js', buildJs);
gulp.watch(pkg.directories.theme + '/**/*.scss', buildCss);
};
// Bundle tasks
const test = gulp.parallel(doEslint, doMocha);
const build = gulp.parallel(buildJs, buildCss);
const defaultTask = gulp.parallel(serve, watch);
// Expose tasks
export {doEslint, doMocha, buildJs, buildCss, serve, watch, test, build};
export default defaultTask;
| fboes/blogophon | gulpfile.js | JavaScript | mit | 2,874 |
// Copyright (c) 2010 Satoshi Nakamoto
// Copyright (c) 2009-2012 The Bitcoin developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "main.h"
#include "bitcoinrpc.h"
using namespace json_spirit;
using namespace std;
extern void TxToJSON(const CTransaction& tx, const uint256 hashBlock, json_spirit::Object& entry);
extern enum Checkpoints::CPMode CheckpointsMode;
double GetDifficulty(const CBlockIndex* blockindex)
{
// Floating point number that is a multiple of the minimum difficulty,
// minimum difficulty = 1.0.
if (blockindex == NULL)
{
if (pindexBest == NULL)
return 1.0;
else
blockindex = GetLastBlockIndex(pindexBest, false);
}
int nShift = (blockindex->nBits >> 24) & 0xff;
double dDiff =
(double)0x0000ffff / (double)(blockindex->nBits & 0x00ffffff);
while (nShift < 29)
{
dDiff *= 256.0;
nShift++;
}
while (nShift > 29)
{
dDiff /= 256.0;
nShift--;
}
return dDiff;
}
double GetPoWMHashPS()
{
int nPoWInterval = 72;
int64_t nTargetSpacingWorkMin = 30, nTargetSpacingWork = 30;
CBlockIndex* pindex = pindexGenesisBlock;
CBlockIndex* pindexPrevWork = pindexGenesisBlock;
while (pindex)
{
if (pindex->IsProofOfWork())
{
int64_t nActualSpacingWork = pindex->GetBlockTime() - pindexPrevWork->GetBlockTime();
nTargetSpacingWork = ((nPoWInterval - 1) * nTargetSpacingWork + nActualSpacingWork + nActualSpacingWork) / (nPoWInterval + 1);
nTargetSpacingWork = max(nTargetSpacingWork, nTargetSpacingWorkMin);
pindexPrevWork = pindex;
}
pindex = pindex->pnext;
}
return GetDifficulty() * 4294.967296 / nTargetSpacingWork;
}
double GetPoSKernelPS()
{
int nPoSInterval = 72;
double dStakeKernelsTriedAvg = 0;
int nStakesHandled = 0, nStakesTime = 0;
CBlockIndex* pindex = pindexBest;;
CBlockIndex* pindexPrevStake = NULL;
while (pindex && nStakesHandled < nPoSInterval)
{
if (pindex->IsProofOfStake())
{
dStakeKernelsTriedAvg += GetDifficulty(pindex) * 4294967296.0;
nStakesTime += pindexPrevStake ? (pindexPrevStake->nTime - pindex->nTime) : 0;
pindexPrevStake = pindex;
nStakesHandled++;
}
pindex = pindex->pprev;
}
return nStakesTime ? dStakeKernelsTriedAvg / nStakesTime : 0;
}
Object blockToJSON(const CBlock& block, const CBlockIndex* blockindex, bool fPrintTransactionDetail)
{
Object result;
result.push_back(Pair("hash", block.GetHash().GetHex()));
CMerkleTx txGen(block.vtx[0]);
txGen.SetMerkleBranch(&block);
result.push_back(Pair("confirmations", (int)txGen.GetDepthInMainChain()));
result.push_back(Pair("size", (int)::GetSerializeSize(block, SER_NETWORK, PROTOCOL_VERSION)));
result.push_back(Pair("height", blockindex->nHeight));
result.push_back(Pair("version", block.nVersion));
result.push_back(Pair("merkleroot", block.hashMerkleRoot.GetHex()));
result.push_back(Pair("mint", ValueFromAmount(blockindex->nMint)));
result.push_back(Pair("time", (boost::int64_t)block.GetBlockTime()));
result.push_back(Pair("nonce", (boost::uint64_t)block.nNonce));
result.push_back(Pair("bits", HexBits(block.nBits)));
result.push_back(Pair("difficulty", GetDifficulty(blockindex)));
result.push_back(Pair("blocktrust", leftTrim(blockindex->GetBlockTrust().GetHex(), '0')));
result.push_back(Pair("chaintrust", leftTrim(blockindex->nChainTrust.GetHex(), '0')));
if (blockindex->pprev)
result.push_back(Pair("previousblockhash", blockindex->pprev->GetBlockHash().GetHex()));
if (blockindex->pnext)
result.push_back(Pair("nextblockhash", blockindex->pnext->GetBlockHash().GetHex()));
result.push_back(Pair("flags", strprintf("%s%s", blockindex->IsProofOfStake()? "proof-of-stake" : "proof-of-work", blockindex->GeneratedStakeModifier()? " stake-modifier": "")));
result.push_back(Pair("proofhash", blockindex->IsProofOfStake()? blockindex->hashProofOfStake.GetHex() : blockindex->GetBlockHash().GetHex()));
result.push_back(Pair("entropybit", (int)blockindex->GetStakeEntropyBit()));
result.push_back(Pair("modifier", strprintf("%016"PRIx64, blockindex->nStakeModifier)));
result.push_back(Pair("modifierchecksum", strprintf("%08x", blockindex->nStakeModifierChecksum)));
Array txinfo;
BOOST_FOREACH (const CTransaction& tx, block.vtx)
{
if (fPrintTransactionDetail)
{
Object entry;
entry.push_back(Pair("txid", tx.GetHash().GetHex()));
TxToJSON(tx, 0, entry);
txinfo.push_back(entry);
}
else
txinfo.push_back(tx.GetHash().GetHex());
}
result.push_back(Pair("tx", txinfo));
if (block.IsProofOfStake())
result.push_back(Pair("signature", HexStr(block.vchBlockSig.begin(), block.vchBlockSig.end())));
return result;
}
Value getbestblockhash(const Array& params, bool fHelp)
{
if (fHelp || params.size() != 0)
throw runtime_error(
"getbestblockhash\n"
"Returns the hash of the best block in the longest block chain.");
return hashBestChain.GetHex();
}
Value getblockcount(const Array& params, bool fHelp)
{
if (fHelp || params.size() != 0)
throw runtime_error(
"getblockcount\n"
"Returns the number of blocks in the longest block chain.");
return nBestHeight;
}
Value getdifficulty(const Array& params, bool fHelp)
{
if (fHelp || params.size() != 0)
throw runtime_error(
"getdifficulty\n"
"Returns the difficulty as a multiple of the minimum difficulty.");
Object obj;
obj.push_back(Pair("proof-of-work", GetDifficulty()));
obj.push_back(Pair("proof-of-stake", GetDifficulty(GetLastBlockIndex(pindexBest, true))));
obj.push_back(Pair("search-interval", (int)nLastCoinStakeSearchInterval));
return obj;
}
Value settxfee(const Array& params, bool fHelp)
{
if (fHelp || params.size() < 1 || params.size() > 1 || AmountFromValue(params[0]) < MIN_TX_FEE)
throw runtime_error(
"settxfee <amount>\n"
"<amount> is a real and is rounded to the nearest 0.01");
nTransactionFee = AmountFromValue(params[0]);
nTransactionFee = (nTransactionFee / CENT) * CENT; // round to cent
return true;
}
Value getrawmempool(const Array& params, bool fHelp)
{
if (fHelp || params.size() != 0)
throw runtime_error(
"getrawmempool\n"
"Returns all transaction ids in memory pool.");
vector<uint256> vtxid;
mempool.queryHashes(vtxid);
Array a;
BOOST_FOREACH(const uint256& hash, vtxid)
a.push_back(hash.ToString());
return a;
}
Value getblockhash(const Array& params, bool fHelp)
{
if (fHelp || params.size() != 1)
throw runtime_error(
"getblockhash <index>\n"
"Returns hash of block in best-block-chain at <index>.");
int nHeight = params[0].get_int();
if (nHeight < 0 || nHeight > nBestHeight)
throw runtime_error("Block number out of range.");
CBlockIndex* pblockindex = FindBlockByHeight(nHeight);
return pblockindex->phashBlock->GetHex();
}
Value getblock(const Array& params, bool fHelp)
{
if (fHelp || params.size() < 1 || params.size() > 2)
throw runtime_error(
"getblock <hash> [txinfo]\n"
"txinfo optional to print more detailed tx info\n"
"Returns details of a block with given block-hash.");
std::string strHash = params[0].get_str();
uint256 hash(strHash);
if (mapBlockIndex.count(hash) == 0)
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Block not found");
CBlock block;
CBlockIndex* pblockindex = mapBlockIndex[hash];
block.ReadFromDisk(pblockindex, true);
return blockToJSON(block, pblockindex, params.size() > 1 ? params[1].get_bool() : false);
}
Value getblockbynumber(const Array& params, bool fHelp)
{
if (fHelp || params.size() < 1 || params.size() > 2)
throw runtime_error(
"getblock <number> [txinfo]\n"
"txinfo optional to print more detailed tx info\n"
"Returns details of a block with given block-number.");
int nHeight = params[0].get_int();
if (nHeight < 0 || nHeight > nBestHeight)
throw runtime_error("Block number out of range.");
CBlock block;
CBlockIndex* pblockindex = mapBlockIndex[hashBestChain];
while (pblockindex->nHeight > nHeight)
pblockindex = pblockindex->pprev;
uint256 hash = *pblockindex->phashBlock;
pblockindex = mapBlockIndex[hash];
block.ReadFromDisk(pblockindex, true);
return blockToJSON(block, pblockindex, params.size() > 1 ? params[1].get_bool() : false);
}
// nitrous: get information of sync-checkpoint
Value getcheckpoint(const Array& params, bool fHelp)
{
if (fHelp || params.size() != 0)
throw runtime_error(
"getcheckpoint\n"
"Show info of synchronized checkpoint.\n");
Object result;
CBlockIndex* pindexCheckpoint;
result.push_back(Pair("synccheckpoint", Checkpoints::hashSyncCheckpoint.ToString().c_str()));
pindexCheckpoint = mapBlockIndex[Checkpoints::hashSyncCheckpoint];
result.push_back(Pair("height", pindexCheckpoint->nHeight));
result.push_back(Pair("timestamp", DateTimeStrFormat(pindexCheckpoint->GetBlockTime()).c_str()));
// Check that the block satisfies synchronized checkpoint
if (CheckpointsMode == Checkpoints::STRICT)
result.push_back(Pair("policy", "strict"));
if (CheckpointsMode == Checkpoints::ADVISORY)
result.push_back(Pair("policy", "advisory"));
if (CheckpointsMode == Checkpoints::PERMISSIVE)
result.push_back(Pair("policy", "permissive"));
if (mapArgs.count("-checkpointkey"))
result.push_back(Pair("checkpointmaster", true));
return result;
}
| N2ODev/Nitrous | src/rpcblockchain.cpp | C++ | mit | 10,201 |
package helper
const (
// EmojiStar const for unicode code
EmojiStar = "\U00002B50"
// EmojiAlarm const for unicode code
EmojiAlarm = "\U000023F0"
// EmojiDroplet const for unicode code
EmojiDroplet = "\U0001F4A7"
// EmojiGear const for unicode code
EmojiGear = "\U00002699"
// EmojiBell const for unicode code
EmojiBell = "\U0001F514"
// EmojiBellCancelled const for unicode code
EmojiBellCancelled = "\U0001F515"
// EmojiBack const for unicode code
EmojiBack = "\U000021A9"
// EmojiSpeechBalloon const for unicode code
EmojiSpeechBalloon = "\U0001F4AC"
// EmojiRussianFlag const for unicode code
EmojiRussianFlag = "\U0001F1F7\U0001F1FA"
// EmojiUSFlag const for unicode code
EmojiUSFlag = "\U0001F1FA\U0001F1F8"
)
| vort3x/watery | helper/emoji.go | GO | mit | 747 |
//
// Jala Project [http://opensvn.csie.org/traccgi/jala]
//
// Copyright 2004 ORF Online und Teletext GmbH
//
// 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.
//
// $Revision: 213 $
// $LastChangedBy: tobi $
// $LastChangedDate: 2007-05-08 16:12:32 +0200 (Die, 08 Mai 2007) $
// $HeadURL: http://dev.orf.at/source/jala/trunk/code/AsyncRequest.js $
//
/**
* @fileoverview Fields and methods of the jala.AsyncRequest class.
*/
// Define the global namespace for Jala modules
if (!global.jala) {
global.jala = {};
}
/**
* Creates a new AsyncRequest instance.
* @class This class is used to create requests of type "INTERNAL"
* (like cron-jobs) that are processed in a separate thread and
* therefor asynchronous.
* @param {Object} obj Object in whose context the method should be called
* @param {String} funcName Name of the function to call
* @param {Array} args Array containing the arguments that should be passed
* to the function (optional). This option is <em>deprecated</em>, instead
* pass the arguments directly to the {@link #run} method.
* @constructor
* @returns A new instance of AsyncRequest
* @type AsyncRequest
* @deprecated Use the {@link http://helma.zumbrunn.net/reference/core/app.html#invokeAsync
* app.invokeAsync} method instead (built-in into Helma as
* of version 1.6)
*/
jala.AsyncRequest = function(obj, funcName, args) {
app.logger.warn("Use of jala.AsyncRequest is deprecated in this version.");
app.logger.warn("This module will probably be removed in a " +
"future version of Jala.");
/**
* Contains a reference to the thread started by this AsyncRequest
* @type java.lang.Thread
* @private
*/
var thread;
/**
* Contains the timeout defined for this AsyncRequest (in milliseconds)
* @type Number
* @private
*/
var timeout;
/**
* Contains the number of milliseconds to wait before starting
* the asynchronous request.
* @type Number
* @private
*/
var delay;
/**
* Run method necessary to implement java.lang.Runnable.
* @private
*/
var runner = function() {
// evaluator that will handle the request
var ev = app.__app__.getEvaluator();
if (delay != null) {
java.lang.Thread.sleep(delay);
}
try {
if (args === undefined || args === null || args.constructor != Array) {
args = [];
}
if (timeout != null) {
ev.invokeInternal(obj, funcName, args, timeout);
} else {
ev.invokeInternal(obj, funcName, args);
}
} catch (e) {
// ignore it, but log it
app.log("[Runner] Caught Exception: " + e);
} finally {
// release the ev in any case
app.__app__.releaseEvaluator(ev);
// remove reference to underlying thread
thread = null;
}
return;
};
/**
* Sets the timeout of this asynchronous request.
* @param {Number} seconds Thread-timeout.
*/
this.setTimeout = function(seconds) {
timeout = seconds * 1000;
return;
};
/**
* Defines the delay to wait before evaluating this asynchronous request.
* @param {Number} millis Milliseconds to wait
*/
this.setDelay = function(millis) {
delay = millis;
return;
};
/**
* Starts this asynchronous request. Any arguments passed to
* this method will be passed to the method executed by
* this AsyncRequest instance.
*/
this.run = function() {
if (arguments.length > 0) {
// convert arguments object into array
args = Array.prototype.slice.call(arguments, 0, arguments.length);
}
thread = (new java.lang.Thread(new java.lang.Runnable({"run": runner})));
thread.start();
return;
};
/**
* Starts this asynchronous request.
* @deprecated Use {@link #run} instead
*/
this.evaluate = function() {
this.run.apply(this, arguments);
return;
};
/**
* Returns true if the underlying thread is alive
* @returns True if the underlying thread is alive,
* false otherwise.
* @type Boolean
*/
this.isAlive = function() {
return thread != null && thread.isAlive();
}
/** @ignore */
this.toString = function() {
return "[jala.AsyncRequest]";
};
/**
* Main constructor body
*/
if (!obj || !funcName)
throw "jala.AsyncRequest: insufficient arguments.";
return this;
}
| hankly/frizione | Frizione/modules/jala/code/AsyncRequest.js | JavaScript | mit | 5,028 |
/**
*
* wxform.cpp
*
* - implementation for main wx-based form
*
**/
#include "wxform.hpp"
#include <wx/aboutdlg.h>
#include "../res/apps.xpm"
#include "../res/exit.xpm"
#include "../res/quest.xpm"
#define MACRO_WXBMP(bmp) wxBitmap(bmp##_xpm)
#define MACRO_WXICO(bmp) wxIcon(bmp##_xpm)
#define MESSAGE_WELCOME "Welcome to MY1TERMW\n"
#define DEFAULT_PROMPT "my1term> "
#define CONS_WIDTH 640
#define CONS_HEIGHT 480
my1Form::my1Form(const wxString &title)
: wxFrame( NULL, MY1ID_MAIN, title, wxDefaultPosition,
wxDefaultSize, wxDEFAULT_FRAME_STYLE)
{
// initialize stuffs
mTerm = new my1Term(this,wxID_ANY);
// setup image
wxIcon mIconApps = MACRO_WXICO(apps);
this->SetIcon(mIconApps);
// create tool bar
wxToolBar* mainTool = this->CreateToolBar(wxBORDER_NONE|wxTB_HORIZONTAL|
wxTB_FLAT,MY1ID_MAIN_TOOL,wxT("mainTool"));
mainTool->SetToolBitmapSize(wxSize(16,16));
wxBitmap mIconExit = MACRO_WXBMP(exit);
mainTool->AddTool(MY1ID_EXIT,wxT(""),mIconExit,wxT("Exit my1termw"));
mainTool->AddSeparator();
wxBitmap mIconAbout = MACRO_WXBMP(quest);
mainTool->AddTool(MY1ID_ABOUT, wxT(""), mIconAbout,wxT("About my1termw"));
mainTool->Realize();
// main box-sizer
//wxBoxSizer *pSizerMain = new wxBoxSizer(wxVERTICAL);
//pSizerMain->Add(mTerm,1,wxEXPAND);
//this->SetSizerAndFit(pSizerMain);
// duh!
this->SetClientSize(wxSize(CONS_WIDTH,CONS_HEIGHT));
// actions & events
this->Connect(MY1ID_EXIT,wxEVT_COMMAND_TOOL_CLICKED,
wxCommandEventHandler(my1Form::OnExit));
this->Connect(MY1ID_ABOUT,wxEVT_COMMAND_TOOL_CLICKED,
wxCommandEventHandler(my1Form::OnAbout));
// write welcome message
mTerm->WriteConsole(MESSAGE_WELCOME);
mTerm->SetPrompt(DEFAULT_PROMPT);
// position this!
this->Centre();
}
my1Form::~my1Form()
{
// nothing to do
}
void my1Form::OnExit(wxCommandEvent& event)
{
this->Close();
}
void my1Form::OnAbout(wxCommandEvent& event)
{
wxAboutDialogInfo cAboutInfo;
wxString cDescription = wxString::Format("%s",
"\nGUI for my1termu (Serial Port Interface)!\n");
cAboutInfo.SetName(MY1APP_PROGNAME);
cAboutInfo.SetVersion(MY1APP_PROGVERS);
cAboutInfo.SetDescription(cDescription);
cAboutInfo.SetCopyright("Copyright (C) "MY1APP_LICENSE_);
cAboutInfo.SetWebSite("http://www.my1matrix.org");
cAboutInfo.AddDeveloper("Azman M. Yusof <azman@my1matrix.net>");
wxAboutBox(cAboutInfo,this);
}
| my1matrix/my1termw | src/wxform.cpp | C++ | mit | 2,350 |
<?php
/*
* Title: XML
* Purpose:
* Collection of parameters, functions, and classes that expand
* Ditto's output capabilities to include XML
*/
if(!defined('MODX_BASE_PATH') || strpos(str_replace('\\','/',__FILE__), MODX_BASE_PATH)!==0) exit;
// set placeholders
$xml_placeholders['[+xml_copyright+]'] = isset($copyright) ? $copyright: $_lang['default_copyright'];
/*
Param: copyright
Purpose:
Copyright message to embed in the XML feed
Options:
Any text
Default:
[LANG]
*/
$xml_placeholders['[+xml_lang+]'] = (isset($abbrLanguage))? $abbrLanguage : $_lang['abbr_lang'];
/*
Param: abbrLanguage
Purpose:
Language for the XML feed
Options:
Any valid 2 character language abbreviation
Default:
[LANG]
Related:
- <language>
*/
$xml_placeholders['[+xml_link+]'] = $modx->config['site_url']."[~".$modx->documentObject['id']."~]";
$xml_placeholders['[+xml_ttl+]'] = isset($ttl) ? intval($ttl):120;
/*
Param: ttl
Purpose:
Time to live for the RSS feed
Options:
Any integer greater than 1
Default:
120
*/
$xml_placeholders['[+xml_charset+]'] = isset($charset) ? $charset : $modx->config['modx_charset'];
/*
Param: charset
Purpose:
Charset to use for the RSS feed
Options:
Any valid charset identifier
Default:
MODx default charset
*/
$rss_placeholders['[+xml_xsl+]'] = isset($xsl) ? '<?xml-stylesheet type="text/xsl" href="'.$modx->config['site_url'].$xsl.'" ?>' : '';
/*
Param: xsl
Purpose:
XSL Stylesheet to format the XML feed with
Options:
The path to any valid XSL Stylesheet
Default:
None
*/
// set tpl xml placeholders
$placeholders['*'] = "xml_parameters";
if(!function_exists("xml_parameters")) {
function xml_parameters($placeholders) {
global $modx;
$xmlArr = array();
foreach ($placeholders as $name=>$value) {
$xmlArr["xml_".$name] = htmlentities($value,ENT_NOQUOTES,$modx->config["modx_charset"]);
}
$placeholders = array_merge($xmlArr,$placeholders);
return $placeholders;
}
}
// set default templates
$xml_header = <<<TPL
<?xml version="1.0" encoding="[+xml_charset+]" ?>
[+xml_xsl+]
<xml version="2.0" xmlns:dc="http://purl.org/dc/elements/1.1/">
<channel>
<title>[*pagetitle*]</title>
<link>[+xml_link+]</link>
<description>[*description*]</description>
<language>[+xml_lang+]</language>
<copyright>[+xml_copyright+]</copyright>
<ttl>[+xml_ttl+]</ttl>
TPL;
$xml_tpl = <<<TPL
<item>
<title>[+xml_pagetitle+]</title>
<link>[(site_url)][~[+id+]~]</link>
<guid isPermaLink="true">[(site_url)][~[+id+]~]</guid>
<summary><![CDATA[ [+xml_introtext+] ]]></summary>
<date>[+xml_createdon+]</date>
<createdon>[+xml_createdon+]</createdon>
<author>[+xml_author+]</author>
[+tags+]
</item>
TPL;
$xml_footer = <<<TPL
</channel>
</xml>
TPL;
// set template values
$header = isset($header) ? $header : template::replace($xml_placeholders,$xml_header);
$tpl = isset($tpl) ? $tpl : "@CODE:".$xml_tpl;
$footer = isset($footer) ? $footer : $xml_footer;
// set emptytext
$noResults = " ";
?> | win-k/CMSTV | evo/assets/snippets/ditto/formats/xml.format.inc.php | PHP | mit | 3,036 |
const OFF = 0;
const WARN = 1;
const ERROR = 2;
module.exports = {
extends: "../.eslintrc.js",
rules: {
"max-len": [ ERROR, 100 ],
},
env: {
"es6": true,
"node": true,
"mocha": true,
},
};
| deadcee/horizon | cli/.eslintrc.js | JavaScript | mit | 216 |
<?php
namespace Topxia\Service\Article;
interface CategoryService
{
public function getCategory($id);
public function getCategoryByCode($code);
public function getCategoryTree();
public function getCategoryByParentId($parentId);
public function findAllCategoriesByParentId($parentId);
public function findCategoryChildrenIds($id);
public function findCategoriesByIds(array $ids);
public function findAllCategories();
public function findCategoryBreadcrumbs($categoryId);
public function isCategoryCodeAvaliable($code, $exclude = null);
public function createCategory(array $category);
public function updateCategory($id, array $fields);
public function deleteCategory($id);
public function findCategoriesCountByParentId($parentId);
public function makeNavCategories($code);
}
| smeagonline-developers/OnlineEducationPlatform---SMEAGonline | src/Topxia/Service/Article/CategoryService.php | PHP | mit | 852 |
package me.ronggenliu.dp.creation.builder;
/**
* Created by garliu on 2017/5/29.
*/
public class Product {
private String partA;
private String partB;
private String partC;
public String getPartA() {
return partA;
}
public void setPartA(String partA) {
this.partA = partA;
}
public String getPartB() {
return partB;
}
public void setPartB(String partB) {
this.partB = partB;
}
public String getPartC() {
return partC;
}
public void setPartC(String partC) {
this.partC = partC;
}
}
| ronggenliu/DesignPattern | src/me/ronggenliu/dp/creation/builder/Product.java | Java | mit | 544 |
const webdriver = require('selenium-webdriver');
const setupDriver = (browser) => {
const driver = new webdriver
.Builder()
.usingServer('http://localhost:9515/')
.withCapabilities({
browserName: browser,
})
.build();
return driver;
};
module.exports = { setupDriver };
| TeamYAGNI/BonanzaAlgorithmsCatalogue | tests/browser/utils/setup-driver.js | JavaScript | mit | 333 |
'use strict';
module.exports = function(grunt) {
// Please see the Grunt documentation for more information regarding task
// creation: http://gruntjs.com/creating-tasks
function random(min, max) {
min = min || 0;
max = max || 1;
var result;
if(min === 0 && max === 1) {
result = Math.random();
} else {
result = Math.floor((Math.random() * max) + min);
}
return result;
}
grunt.registerMultiTask('random', 'Your task description goes here.', function() {
// Merge task-specific and/or target-specific options with these defaults.
var options = this.options({min:0,max:1});
grunt.log.writeln('Random: ' + random(options.min, options.max));
});
}; | doowb/lessbuilder | tasks/random.js | JavaScript | mit | 744 |