text stringlengths 2 1.04M | meta dict |
|---|---|
<?php
namespace Esprit\CollaborateurBundle\DependencyInjection;
use Symfony\Component\Config\Definition\Builder\TreeBuilder;
use Symfony\Component\Config\Definition\ConfigurationInterface;
/**
* This is the class that validates and merges configuration from your app/config files
*
* To learn more see {@link http://symfony.com/doc/current/cookbook/bundles/extension.html#cookbook-bundles-extension-config-class}
*/
class Configuration implements ConfigurationInterface
{
/**
* {@inheritDoc}
*/
public function getConfigTreeBuilder()
{
$treeBuilder = new TreeBuilder();
$rootNode = $treeBuilder->root('esprit_collaborateur');
// Here you should define the parameters that are allowed to
// configure your bundle. See the documentation linked above for
// more information on that topic.
return $treeBuilder;
}
}
| {
"content_hash": "8631b7ee597c8b0b21873720c04fa74f",
"timestamp": "",
"source": "github",
"line_count": 29,
"max_line_length": 131,
"avg_line_length": 30.862068965517242,
"alnum_prop": 0.7217877094972067,
"repo_name": "salgado777/GestionReclamations",
"id": "e57ebc44c86db5098644ab1de5901dd7739e34a5",
"size": "895",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/Esprit/CollaborateurBundle/DependencyInjection/Configuration.php",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "JavaScript",
"bytes": "61752"
},
{
"name": "PHP",
"bytes": "83798"
}
],
"symlink_target": ""
} |
import * as React from "react";
import { CarbonIconProps } from "../../";
declare const DocumentImport16: React.ForwardRefExoticComponent<
CarbonIconProps & React.RefAttributes<SVGSVGElement>
>;
export default DocumentImport16;
| {
"content_hash": "5195668aaeaf5a38935eaa8707e25e6a",
"timestamp": "",
"source": "github",
"line_count": 6,
"max_line_length": 64,
"avg_line_length": 38.333333333333336,
"alnum_prop": 0.782608695652174,
"repo_name": "mcliment/DefinitelyTyped",
"id": "17e03dd4ed6e47a2e15e743b5ff0a47e4a512fc3",
"size": "230",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "types/carbon__icons-react/lib/document--import/16.d.ts",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CoffeeScript",
"bytes": "15"
},
{
"name": "Protocol Buffer",
"bytes": "678"
},
{
"name": "TypeScript",
"bytes": "17214021"
}
],
"symlink_target": ""
} |
ACCEPTED
#### According to
International Plant Names Index
#### Published in
null
#### Original name
null
### Remarks
null | {
"content_hash": "c8cd9a119780e4fdf195fdb5c221110d",
"timestamp": "",
"source": "github",
"line_count": 13,
"max_line_length": 31,
"avg_line_length": 9.692307692307692,
"alnum_prop": 0.7063492063492064,
"repo_name": "mdoering/backbone",
"id": "070c7854d5c36025ac1689a2645ec9c72f708352",
"size": "177",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "life/Plantae/Magnoliophyta/Liliopsida/Asparagales/Iridaceae/Phalodallis/Phalodallis paludosa/README.md",
"mode": "33188",
"license": "apache-2.0",
"language": [],
"symlink_target": ""
} |
import React, { Component } from "react";
export default class SingleDescription extends Component {
render(){
const phrase = this.props.singlePhrase;
return (
<p>{phrase}</p>
);
}
} | {
"content_hash": "36440ae743a8003476bf25e320105773",
"timestamp": "",
"source": "github",
"line_count": 13,
"max_line_length": 58,
"avg_line_length": 15.307692307692308,
"alnum_prop": 0.6633165829145728,
"repo_name": "andreecordova/react-first-steps",
"id": "257b9fdfee3704b13b175d95ea0e2ae7642890b8",
"size": "199",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "assets/js/react/components/firstLevelComponent/SingleDescription.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "HTML",
"bytes": "426"
},
{
"name": "JavaScript",
"bytes": "6306"
}
],
"symlink_target": ""
} |
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>descente-infinie: Not compatible 👼</title>
<link rel="shortcut icon" type="image/png" href="../../../../../favicon.png" />
<link href="../../../../../bootstrap.min.css" rel="stylesheet">
<link href="../../../../../bootstrap-custom.css" rel="stylesheet">
<link href="//maxcdn.bootstrapcdn.com/font-awesome/4.2.0/css/font-awesome.min.css" rel="stylesheet">
<script src="../../../../../moment.min.js"></script>
<!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries -->
<!-- WARNING: Respond.js doesn't work if you view the page via file:// -->
<!--[if lt IE 9]>
<script src="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script>
<script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script>
<![endif]-->
</head>
<body>
<div class="container">
<div class="navbar navbar-default" role="navigation">
<div class="container-fluid">
<div class="navbar-header">
<a class="navbar-brand" href="../../../../.."><i class="fa fa-lg fa-flag-checkered"></i> Coq bench</a>
</div>
<div id="navbar" class="collapse navbar-collapse">
<ul class="nav navbar-nav">
<li><a href="../..">clean / released</a></li>
<li class="active"><a href="">8.9.0 / descente-infinie - 8.6.0</a></li>
</ul>
</div>
</div>
</div>
<div class="article">
<div class="row">
<div class="col-md-12">
<a href="../..">« Up</a>
<h1>
descente-infinie
<small>
8.6.0
<span class="label label-info">Not compatible 👼</span>
</small>
</h1>
<p>📅 <em><script>document.write(moment("2022-08-30 23:26:01 +0000", "YYYY-MM-DD HH:mm:ss Z").fromNow());</script> (2022-08-30 23:26:01 UTC)</em><p>
<h2>Context</h2>
<pre># Packages matching: installed
# Name # Installed # Synopsis
base-bigarray base
base-num base Num library distributed with the OCaml compiler
base-threads base
base-unix base
camlp5 7.14 Preprocessor-pretty-printer of OCaml
conf-findutils 1 Virtual package relying on findutils
conf-perl 2 Virtual package relying on perl
coq 8.9.0 Formal proof management system
num 0 The Num library for arbitrary-precision integer and rational arithmetic
ocaml 4.04.2 The OCaml compiler (virtual package)
ocaml-base-compiler 4.04.2 Official 4.04.2 release
ocaml-config 1 OCaml Switch Configuration
ocamlfind 1.9.5 A library manager for OCaml
# opam file:
opam-version: "2.0"
maintainer: "Hugo.Herbelin@inria.fr"
homepage: "https://github.com/coq-contribs/descente-infinie"
license: "GPL"
build: [make "-j%{jobs}%"]
install: [make "install"]
remove: ["rm" "-R" "%{lib}%/coq/user-contrib/DescenteInfinie"]
depends: [
"ocaml"
"coq" {>= "8.6" & < "8.7~"}
]
tags: [
"keyword: Induction"
"keyword: infinite descent"
"category: Miscellaneous/Coq Extensions"
"date: 2010-02"
]
authors: [ "Razvan Voicu <razvan@comp.nus.edu.sg> [http://www.comp.nus.edu.sg/~razvan/]" "Li Mengran <limengra@comp.nus.edu.sg> [http://www.comp.nus.edu.sg/~limengra]" ]
bug-reports: "https://github.com/coq-contribs/descente-infinie/issues"
dev-repo: "git+https://github.com/coq-contribs/descente-infinie.git"
synopsis: "The Descente Infinie Tactic"
description:
"This is a tactic plugin for coq. The tactic helps to prove inductive lemmas by fixpoint functions. A manual for the tactic can be found on its homepage listed above."
flags: light-uninstall
url {
src:
"https://github.com/coq-contribs/descente-infinie/archive/v8.6.0.tar.gz"
checksum: "md5=f998222ab87c98c6ab420a047eeb54a8"
}
</pre>
<h2>Lint</h2>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>true</code></dd>
<dt>Return code</dt>
<dd>0</dd>
</dl>
<h2>Dry install 🏜️</h2>
<p>Dry install with the current Coq version:</p>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>opam install -y --show-action coq-descente-infinie.8.6.0 coq.8.9.0</code></dd>
<dt>Return code</dt>
<dd>5120</dd>
<dt>Output</dt>
<dd><pre>[NOTE] Package coq is already installed (current version is 8.9.0).
The following dependencies couldn't be met:
- coq-descente-infinie -> coq < 8.7~ -> ocaml < 4.03.0
base of this switch (use `--unlock-base' to force)
Your request can't be satisfied:
- No available version of coq satisfies the constraints
No solution found, exiting
</pre></dd>
</dl>
<p>Dry install without Coq/switch base, to test if the problem was incompatibility with the current Coq/OCaml version:</p>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>opam remove -y coq; opam install -y --show-action --unlock-base coq-descente-infinie.8.6.0</code></dd>
<dt>Return code</dt>
<dd>0</dd>
</dl>
<h2>Install dependencies</h2>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>true</code></dd>
<dt>Return code</dt>
<dd>0</dd>
<dt>Duration</dt>
<dd>0 s</dd>
</dl>
<h2>Install 🚀</h2>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>true</code></dd>
<dt>Return code</dt>
<dd>0</dd>
<dt>Duration</dt>
<dd>0 s</dd>
</dl>
<h2>Installation size</h2>
<p>No files were installed.</p>
<h2>Uninstall 🧹</h2>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>true</code></dd>
<dt>Return code</dt>
<dd>0</dd>
<dt>Missing removes</dt>
<dd>
none
</dd>
<dt>Wrong removes</dt>
<dd>
none
</dd>
</dl>
</div>
</div>
</div>
<hr/>
<div class="footer">
<p class="text-center">
Sources are on <a href="https://github.com/coq-bench">GitHub</a> © Guillaume Claret 🐣
</p>
</div>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="../../../../../bootstrap.min.js"></script>
</body>
</html>
| {
"content_hash": "28d54642a892f39f19da6848ee07b973",
"timestamp": "",
"source": "github",
"line_count": 172,
"max_line_length": 201,
"avg_line_length": 42.28488372093023,
"alnum_prop": 0.5497043860855217,
"repo_name": "coq-bench/coq-bench.github.io",
"id": "69c5452463ddc12df9d0408a2d45fc708564de79",
"size": "7298",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "clean/Linux-x86_64-4.04.2-2.0.5/released/8.9.0/descente-infinie/8.6.0.html",
"mode": "33188",
"license": "mit",
"language": [],
"symlink_target": ""
} |
$(document).ready(function () {
// override jquery validate plugin defaults
highlight_errors_validate();
// Setup form validation on the #register-form element
$("#register_form").validate({
// Specify the validation rules
rules: {
name: "required",
email: {
required: true,
email: true
},
mobileno: {
required: true,
minlength: 10,
maxlength: 10
},
password: {
required: true,
minlength: 6
},
confirm_password:{
required: true,
equalTo: '#password'
}
},
// // Specify the validation error messages
messages: {
name:"Please enter your name.",
email: {
required: 'Email address is required',
email: 'Please enter a valid email address',
},
mobileno: {
required: 'Mobile number is required',
// exactlength: 'The mobile number should be of 10 characters.',
},
password: {
required: 'Password is required',
minlength: 'The password should be of minimum 6 characters.',
},
confirm_password: {
required: 'Confirm password is required',
equalTo: 'The confirm password should match password.',
}
},
submitHandler: function(form) {
// waiting for server response.
$('#form_error').empty();
$('#password_error').empty();
$('#name_error').empty();
$('#email_error').empty();
$('#mobileno_error').empty();
$('#confirm_password_error').empty();
$('#form_error').html(
'<div class="alert alert-success col-sm-8">Regiseration going on......</div><br>');
$.ajax({
type: 'POST',
url: $(form).attr('action'),
data: $(form).serialize(),
dataType : 'json',
success: function(data) {
// set all errors to empty tag.
console.log("Resetting errrors.");
if (data.success)
{
if ( data.email != null )
{
$('#form_error').html(
'<div class="alert alert-success col-sm-8">Registeration successful. Please verify your email by click a link sent to you.</div><br>');
setTimeout(function(){
$('#form_error').empty();
window.location = 'upload';
},3000);
}
else
{
// console.log("" + data.email);
$('#form_error').html(
'<div class="alert alert-success col-sm-8">Unable to send verification link. Please try later.</div><br>');
}
}
else
{
if ( data.message != null )
{
$('#form_error').html(
'<div class="alert alert-danger col-sm-8">' + data.message + '</div><br>');
}
else
{
$('#form_error').empty();
if ( data.email != "" && data.email != null )
$('#email_error').html(
'<div class="alert alert-danger col-sm-8">' + data.email + '</div><br>');
if ( data.name != "" && data.name != null)
$('#name_error').html(
'<div class="alert alert-danger col-sm-8">' + data.name + '</div><br>');
if ( data.password != "" && data.password != null)
$('#password_error').html(
'<div class="alert alert-danger col-sm-8">' + data.password + '</div><br>');
if ( data.confirm_password != "" && data.confirm_password != null)
$('#confirm_password_error').html(
'<div class="alert alert-danger col-sm-8">' + data.confirm_password + '</div><br>');
if ( data.mobileno != "" && data.mobileno != null )
$('#mobileno_error').html(
'<div class="alert alert-danger col-sm-8">' + data.mobileno + '</div><br>');
}
}
},
error: function(data) {
console.log(data);
}
});
return false;
},
});
});
| {
"content_hash": "af3ac11f7ef8880a5a8c9fdf3be8a3b9",
"timestamp": "",
"source": "github",
"line_count": 144,
"max_line_length": 169,
"avg_line_length": 34.861111111111114,
"alnum_prop": 0.3956175298804781,
"repo_name": "Shiza1aas/project",
"id": "00f982d004e7a9f82ec05c4b0b266cc14e77f94c",
"size": "5020",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "assets/js/register.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "ApacheConf",
"bytes": "240"
},
{
"name": "CSS",
"bytes": "162665"
},
{
"name": "HTML",
"bytes": "8227098"
},
{
"name": "JavaScript",
"bytes": "90708"
},
{
"name": "PHP",
"bytes": "1889942"
}
],
"symlink_target": ""
} |
/*!
* # Semantic UI 2.2.4 - Input
* http://github.com/semantic-org/semantic-ui/
*
*
* Released under the MIT license
* http://opensource.org/licenses/MIT
*
*/
/*******************************
Standard
*******************************/
/*--------------------
Inputs
---------------------*/
.ui.input {
position: relative;
font-weight: normal;
font-style: normal;
display: -webkit-inline-box;
display: -ms-inline-flexbox;
display: inline-flex;
color: rgba(0, 0, 0, 0.87);
}
.ui.input input {
margin: 0em;
max-width: 100%;
-webkit-box-flex: 1;
-ms-flex: 1 0 auto;
flex: 1 0 auto;
outline: none;
-webkit-tap-highlight-color: rgba(255, 255, 255, 0);
text-align: left;
line-height: 1.2142em;
font-family: 'Lato', 'Helvetica Neue', Arial, Helvetica, sans-serif;
padding: 0.67861429em 1em;
background: #FFFFFF;
border: 1px solid rgba(34, 36, 38, 0.15);
color: rgba(0, 0, 0, 0.87);
border-radius: 0.28571429rem;
-webkit-transition: box-shadow 0.1s ease, border-color 0.1s ease;
transition: box-shadow 0.1s ease, border-color 0.1s ease;
box-shadow: none;
}
/*--------------------
Placeholder
---------------------*/
/* browsers require these rules separate */
.ui.input input::-webkit-input-placeholder {
color: rgba(191, 191, 191, 0.87);
}
.ui.input input::-moz-placeholder {
color: rgba(191, 191, 191, 0.87);
}
.ui.input input:-ms-input-placeholder {
color: rgba(191, 191, 191, 0.87);
}
/*******************************
States
*******************************/
/*--------------------
Disabled
---------------------*/
.ui.disabled.input,
.ui.input input[disabled] {
opacity: 0.45;
}
.ui.disabled.input input,
.ui.input input[disabled] {
pointer-events: none;
}
/*--------------------
Active
---------------------*/
.ui.input input:active,
.ui.input.down input {
border-color: rgba(0, 0, 0, 0.3);
background: #FAFAFA;
color: rgba(0, 0, 0, 0.87);
box-shadow: none;
}
/*--------------------
Loading
---------------------*/
.ui.loading.loading.input > i.icon:before {
position: absolute;
content: '';
top: 50%;
left: 50%;
margin: -0.64285714em 0em 0em -0.64285714em;
width: 1.28571429em;
height: 1.28571429em;
border-radius: 500rem;
border: 0.2em solid rgba(0, 0, 0, 0.1);
}
.ui.loading.loading.input > i.icon:after {
position: absolute;
content: '';
top: 50%;
left: 50%;
margin: -0.64285714em 0em 0em -0.64285714em;
width: 1.28571429em;
height: 1.28571429em;
-webkit-animation: button-spin 0.6s linear;
animation: button-spin 0.6s linear;
-webkit-animation-iteration-count: infinite;
animation-iteration-count: infinite;
border-radius: 500rem;
border-color: #767676 transparent transparent;
border-style: solid;
border-width: 0.2em;
box-shadow: 0px 0px 0px 1px transparent;
}
/*--------------------
Focus
---------------------*/
.ui.input.focus input,
.ui.input input:focus {
border-color: #85B7D9;
background: #FFFFFF;
color: rgba(0, 0, 0, 0.8);
box-shadow: none;
}
.ui.input.focus input::-webkit-input-placeholder,
.ui.input input:focus::-webkit-input-placeholder {
color: rgba(115, 115, 115, 0.87);
}
.ui.input.focus input::-moz-placeholder,
.ui.input input:focus::-moz-placeholder {
color: rgba(115, 115, 115, 0.87);
}
.ui.input.focus input:-ms-input-placeholder,
.ui.input input:focus:-ms-input-placeholder {
color: rgba(115, 115, 115, 0.87);
}
/*--------------------
Error
---------------------*/
.ui.input.error input {
background-color: #FFF6F6;
border-color: #E0B4B4;
color: #9F3A38;
box-shadow: none;
}
/* Error Placeholder */
.ui.input.error input::-webkit-input-placeholder {
color: #e7bdbc;
}
.ui.input.error input::-moz-placeholder {
color: #e7bdbc;
}
.ui.input.error input:-ms-input-placeholder {
color: #e7bdbc !important;
}
/* Focused Error Placeholder */
.ui.input.error input:focus::-webkit-input-placeholder {
color: #da9796;
}
.ui.input.error input:focus::-moz-placeholder {
color: #da9796;
}
.ui.input.error input:focus:-ms-input-placeholder {
color: #da9796 !important;
}
/*******************************
Variations
*******************************/
/*--------------------
Transparent
---------------------*/
.ui.transparent.input input {
border-color: transparent !important;
background-color: transparent !important;
padding: 0em !important;
box-shadow: none !important;
}
/* Transparent Icon */
.ui.transparent.icon.input > i.icon {
width: 1.1em;
}
.ui.transparent.icon.input > input {
padding-left: 0em !important;
padding-right: 2em !important;
}
.ui.transparent[class*="left icon"].input > input {
padding-left: 2em !important;
padding-right: 0em !important;
}
/* Transparent Inverted */
.ui.transparent.inverted.input {
color: #FFFFFF;
}
.ui.transparent.inverted.input input {
color: inherit;
}
.ui.transparent.inverted.input input::-webkit-input-placeholder {
color: rgba(255, 255, 255, 0.5);
}
.ui.transparent.inverted.input input::-moz-placeholder {
color: rgba(255, 255, 255, 0.5);
}
.ui.transparent.inverted.input input:-ms-input-placeholder {
color: rgba(255, 255, 255, 0.5);
}
/*--------------------
Icon
---------------------*/
.ui.icon.input > i.icon {
cursor: default;
position: absolute;
line-height: 1;
text-align: center;
top: 0px;
right: 0px;
margin: 0em;
height: 100%;
width: 2.67142857em;
opacity: 0.5;
border-radius: 0em 0.28571429rem 0.28571429rem 0em;
-webkit-transition: opacity 0.3s ease;
transition: opacity 0.3s ease;
}
.ui.icon.input > i.icon:not(.link) {
pointer-events: none;
}
.ui.icon.input input {
padding-right: 2.67142857em !important;
}
.ui.icon.input > i.icon:before,
.ui.icon.input > i.icon:after {
left: 0;
position: absolute;
text-align: center;
top: 50%;
width: 100%;
margin-top: -0.5em;
}
.ui.icon.input > i.link.icon {
cursor: pointer;
}
.ui.icon.input > i.circular.icon {
top: 0.35em;
right: 0.5em;
}
/* Left Icon Input */
.ui[class*="left icon"].input > i.icon {
right: auto;
left: 1px;
border-radius: 0.28571429rem 0em 0em 0.28571429rem;
}
.ui[class*="left icon"].input > i.circular.icon {
right: auto;
left: 0.5em;
}
.ui[class*="left icon"].input > input {
padding-left: 2.67142857em !important;
padding-right: 1em !important;
}
/* Focus */
.ui.icon.input > input:focus ~ i.icon {
opacity: 1;
}
/*--------------------
Labeled
---------------------*/
/* Adjacent Label */
.ui.labeled.input > .label {
-webkit-box-flex: 0;
-ms-flex: 0 0 auto;
flex: 0 0 auto;
margin: 0;
font-size: 1em;
}
.ui.labeled.input > .label:not(.corner) {
padding-top: 0.78571429em;
padding-bottom: 0.78571429em;
}
/* Regular Label on Left */
.ui.labeled.input:not([class*="corner labeled"]) .label:first-child {
border-top-right-radius: 0px;
border-bottom-right-radius: 0px;
}
.ui.labeled.input:not([class*="corner labeled"]) .label:first-child + input {
border-top-left-radius: 0px;
border-bottom-left-radius: 0px;
border-left-color: transparent;
}
.ui.labeled.input:not([class*="corner labeled"]) .label:first-child + input:focus {
border-left-color: #85B7D9;
}
/* Regular Label on Right */
.ui[class*="right labeled"].input input {
border-top-right-radius: 0px !important;
border-bottom-right-radius: 0px !important;
border-right-color: transparent !important;
}
.ui[class*="right labeled"].input input + .label {
border-top-left-radius: 0px;
border-bottom-left-radius: 0px;
}
.ui[class*="right labeled"].input input:focus {
border-right-color: #85B7D9 !important;
}
/* Corner Label */
.ui.labeled.input .corner.label {
top: 1px;
right: 1px;
font-size: 0.64285714em;
border-radius: 0em 0.28571429rem 0em 0em;
}
/* Spacing with corner label */
.ui[class*="corner labeled"]:not([class*="left corner labeled"]).labeled.input input {
padding-right: 2.5em !important;
}
.ui[class*="corner labeled"].icon.input:not([class*="left corner labeled"]) > input {
padding-right: 3.25em !important;
}
.ui[class*="corner labeled"].icon.input:not([class*="left corner labeled"]) > .icon {
margin-right: 1.25em;
}
/* Left Labeled */
.ui[class*="left corner labeled"].labeled.input input {
padding-left: 2.5em !important;
}
.ui[class*="left corner labeled"].icon.input > input {
padding-left: 3.25em !important;
}
.ui[class*="left corner labeled"].icon.input > .icon {
margin-left: 1.25em;
}
/* Corner Label Position */
.ui.input > .ui.corner.label {
top: 1px;
right: 1px;
}
.ui.input > .ui.left.corner.label {
right: auto;
left: 1px;
}
/*--------------------
Action
---------------------*/
.ui.action.input > .button,
.ui.action.input > .buttons {
display: -webkit-box;
display: -ms-flexbox;
display: flex;
-webkit-box-align: center;
-ms-flex-align: center;
align-items: center;
-webkit-box-flex: 0;
-ms-flex: 0 0 auto;
flex: 0 0 auto;
}
.ui.action.input > .button,
.ui.action.input > .buttons > .button {
padding-top: 0.78571429em;
padding-bottom: 0.78571429em;
margin: 0;
}
/* Button on Right */
.ui.action.input:not([class*="left action"]) > input {
border-top-right-radius: 0px !important;
border-bottom-right-radius: 0px !important;
border-right-color: transparent !important;
}
.ui.action.input:not([class*="left action"]) > .dropdown:not(:first-child),
.ui.action.input:not([class*="left action"]) > .button:not(:first-child),
.ui.action.input:not([class*="left action"]) > .buttons:not(:first-child) > .button {
border-radius: 0px;
}
.ui.action.input:not([class*="left action"]) > .dropdown:last-child,
.ui.action.input:not([class*="left action"]) > .button:last-child,
.ui.action.input:not([class*="left action"]) > .buttons:last-child > .button {
border-radius: 0px 0.28571429rem 0.28571429rem 0px;
}
/* Input Focus */
.ui.action.input:not([class*="left action"]) input:focus {
border-right-color: #85B7D9 !important;
}
/* Button on Left */
.ui[class*="left action"].input > input {
border-top-left-radius: 0px !important;
border-bottom-left-radius: 0px !important;
border-left-color: transparent !important;
}
.ui[class*="left action"].input > .dropdown,
.ui[class*="left action"].input > .button,
.ui[class*="left action"].input > .buttons > .button {
border-radius: 0px;
}
.ui[class*="left action"].input > .dropdown:first-child,
.ui[class*="left action"].input > .button:first-child,
.ui[class*="left action"].input > .buttons:first-child > .button {
border-radius: 0.28571429rem 0px 0px 0.28571429rem;
}
/* Input Focus */
.ui[class*="left action"].input > input:focus {
border-left-color: #85B7D9 !important;
}
/*--------------------
Inverted
---------------------*/
/* Standard */
.ui.inverted.input input {
border: none;
}
/*--------------------
Fluid
---------------------*/
.ui.fluid.input {
display: -webkit-box;
display: -ms-flexbox;
display: flex;
}
.ui.fluid.input > input {
width: 0px !important;
}
/*--------------------
Size
---------------------*/
.ui.mini.input {
font-size: 0.78571429em;
}
.ui.small.input {
font-size: 0.92857143em;
}
.ui.input {
font-size: 1em;
}
.ui.large.input {
font-size: 1.14285714em;
}
.ui.big.input {
font-size: 1.28571429em;
}
.ui.huge.input {
font-size: 1.42857143em;
}
.ui.massive.input {
font-size: 1.71428571em;
}
/*******************************
Theme Overrides
*******************************/
/*******************************
Site Overrides
*******************************/
| {
"content_hash": "ca7f3cfa81ebf75d9059cd0a21162d1c",
"timestamp": "",
"source": "github",
"line_count": 510,
"max_line_length": 86,
"avg_line_length": 22.833333333333332,
"alnum_prop": 0.604293688278231,
"repo_name": "sdeacy/banana",
"id": "009c6e50dabfe039739efa544a545f61a795f9d6",
"size": "11645",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "semantic/dist/components/input.css",
"mode": "33261",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "2729944"
},
{
"name": "HTML",
"bytes": "7727"
},
{
"name": "JavaScript",
"bytes": "2392585"
}
],
"symlink_target": ""
} |
using System;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Administration;
using SharepointCommon.Common;
using SharepointCommon.Impl;
// ReSharper disable once CheckNamespace
namespace SharepointCommon
{
/// <summary>
/// Presents framework entry point. Allows to get instance of IQueryWeb
/// </summary>
public static class WebFactory
{
/// <summary>
/// Opens wrapper for SPWeb and SPSite by URL
/// </summary>
/// <param name="url">The URL.</param>
/// <returns>abstract wrapper for SPWeb and SPSite objects</returns>
public static IQueryWeb Open(string url)
{
return new QueryWeb(url, false);
}
/// <summary>
/// Create wrapper based on existing SPWeb object
/// </summary>
/// <param name="spWeb">SPWeb object.Will not disposed internally!</param>
/// <returns>abstract wrapper for SPWeb and SPSite objects</returns>
public static IQueryWeb Open(SPWeb spWeb)
{
return new QueryWeb(spWeb);
}
/// <summary>
/// Opens wrapper for SPWeb and SPSite by SPSite ID
/// </summary>
/// <param name="site">SPSite ID</param>
/// <returns>abstract wrapper for SPWeb and SPSite objects</returns>
public static IQueryWeb Open(Guid site)
{
return new QueryWeb(site, false);
}
/// <summary>
/// Opens wrapper for SPWeb and SPSite by their ID's
/// </summary>
/// <param name="site">SPSite id</param>
/// <param name="web">SPWeb id</param>
/// <returns>abstract wrapper for SPWeb and SPSite objects</returns>
public static IQueryWeb Open(Guid site, Guid web)
{
return new QueryWeb(site, web, false);
}
/// <summary>
/// Opens wrapper for SPWeb and SPSite by their ID's
/// </summary>
/// <param name="site">SPSite id</param>
/// <param name="web">SPWeb id</param>
/// <param name="zone">site zone</param>
/// <returns>abstract wrapper for SPWeb and SPSite objects</returns>
public static IQueryWeb Open(Guid site, Guid web, SPUrlZone zone)
{
return new QueryWeb(site, web, false, zone);
}
/// <summary>
/// Opens wrapper for SPWeb and SPSite by URL in elevated mode
/// </summary>
/// <param name="url">Web URL</param>
/// <returns>abstract wrapper for SPWeb and SPSite objects</returns>
public static IQueryWeb Elevated(string url)
{
return new QueryWeb(url, true);
}
/// <summary>
/// Opens wrapper for SPWeb and SPSite by site.id in elevated mode
/// </summary>
/// <param name="site">site id</param>
/// <returns>abstract wrapper for SPWeb and SPSite objects</returns>
public static IQueryWeb Elevated(Guid site)
{
return new QueryWeb(site, true);
}
/// <summary>
/// Opens wrapper for SPWeb and SPSite by their ID's in elevated mode
/// </summary>
/// <param name="site">site id</param>
/// <param name="web">web id</param>
/// <returns>abstract wrapper for SPWeb and SPSite objects</returns>
public static IQueryWeb Elevated(Guid site, Guid web)
{
return new QueryWeb(site, web, true);
}
/// <summary>
/// Opens wrapper for SPWeb and SPSite by URL and sets AllowUnsafeUpdates for SPWeb
/// </summary>
/// <param name="url">web URL</param>
/// <returns>abstract wrapper for SPWeb and SPSite objects</returns>
public static IQueryWeb Unsafe(string url)
{
return new QueryWeb(url, false).Unsafe();
}
/// <summary>
/// Opens wrapper for SPWeb and SPSite by their ID's and sets AllowUnsafeUpdates for SPWeb
/// </summary>
/// <param name="site">site id</param>
/// <param name="web">web id</param>
/// <returns>abstract wrapper for SPWeb and SPSite objects</returns>
public static IQueryWeb Unsafe(Guid site, Guid web)
{
return new QueryWeb(site, web, false).Unsafe();
}
/// <summary>
/// Opens wrapper for SPWeb and SPSite by SPContext.Current.Web.Url
/// </summary>
/// <returns>abstract wrapper for SPWeb and SPSite objects</returns>
public static IQueryWeb CurrentContext()
{
Assert.CurrentContextAvailable();
return new QueryWeb(SPContext.Current.Web);
}
}
} | {
"content_hash": "2b06f6b3c50dd8a7ff3a56442023e88d",
"timestamp": "",
"source": "github",
"line_count": 130,
"max_line_length": 98,
"avg_line_length": 36.96923076923077,
"alnum_prop": 0.5649188514357054,
"repo_name": "gdbd/sharepointcommon",
"id": "edf4aea0e4f7b4bf60d6d34867b883a22c02af2f",
"size": "4806",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "SharepointCommon/public/WebFactory.cs",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Batchfile",
"bytes": "602"
},
{
"name": "C#",
"bytes": "2126546"
}
],
"symlink_target": ""
} |
package at.davidwalter;
public class Main {
private String message;
Main(String message) {
this.message = message;
}
public void print() {
System.out.println(this.message);
}
public static void main(String[] args) {
Main main = new Main("Hello World!");
main.print();
}
}
| {
"content_hash": "2360ba28bb166c76311c76e068daad63",
"timestamp": "",
"source": "github",
"line_count": 19,
"max_line_length": 45,
"avg_line_length": 17.736842105263158,
"alnum_prop": 0.5816023738872403,
"repo_name": "divadretlaw/civic",
"id": "86975c838b8c0451fc80dde2e140c450d7d9d9c6",
"size": "377",
"binary": false,
"copies": "1",
"ref": "refs/heads/main",
"path": "examples/HelloWorld/src/at/davidwalter/Main.java",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "448"
}
],
"symlink_target": ""
} |
package org.apache.carbondata.hadoop.ft;
import java.util.List;
import java.util.UUID;
import org.apache.carbondata.core.carbon.CarbonTableIdentifier;
import org.apache.carbondata.core.carbon.metadata.datatype.DataType;
import org.apache.carbondata.hadoop.CarbonInputFormat;
import org.apache.carbondata.scan.expression.ColumnExpression;
import org.apache.carbondata.scan.expression.Expression;
import org.apache.carbondata.scan.expression.LiteralExpression;
import org.apache.carbondata.scan.expression.conditional.EqualToExpression;
import junit.framework.TestCase;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.mapred.JobConf;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
public class CarbonInputFormat_FT extends TestCase {
@Before public void setUp() throws Exception {
//create a table with column c1 string type
//Insert data with column c1 has "a", "b", "c"
}
@Test public void testGetSplits() throws Exception {
CarbonInputFormat carbonInputFormat = new CarbonInputFormat();
JobConf jobConf = new JobConf(new Configuration());
Job job = new Job(jobConf);
FileInputFormat.addInputPath(job, new Path("/opt/carbonstore/db/table1"));
job.getConfiguration().set(CarbonInputFormat.INPUT_SEGMENT_NUMBERS, "1,2");
List splits = carbonInputFormat.getSplits(job);
Assert.assertTrue(splits != null);
Assert.assertTrue(!splits.isEmpty());
}
@Test public void testGetFilteredSplits() throws Exception {
CarbonInputFormat carbonInputFormat = new CarbonInputFormat();
JobConf jobConf = new JobConf(new Configuration());
Job job = new Job(jobConf);
FileInputFormat.addInputPath(job, new Path("/opt/carbonstore/db/table1"));
job.getConfiguration().set(CarbonInputFormat.INPUT_SEGMENT_NUMBERS, "1,2");
Expression expression = new EqualToExpression(new ColumnExpression("c1", DataType.STRING),
new LiteralExpression("a", DataType.STRING));
CarbonInputFormat.setFilterPredicates(job.getConfiguration(), expression);
List splits = carbonInputFormat.getSplits(job);
Assert.assertTrue(splits != null);
Assert.assertTrue(!splits.isEmpty());
}
}
| {
"content_hash": "28eb86988a377e0d1527d4a92e40c953",
"timestamp": "",
"source": "github",
"line_count": 60,
"max_line_length": 94,
"avg_line_length": 38.833333333333336,
"alnum_prop": 0.7695278969957081,
"repo_name": "Zhangshunyu/incubator-carbondata",
"id": "aed7d793206f4cd18013f1f585f768cc01159f66",
"size": "3138",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "hadoop/src/test/java/org/apache/carbondata/hadoop/ft/CarbonInputFormat_FT.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Java",
"bytes": "3124715"
},
{
"name": "Scala",
"bytes": "2494931"
},
{
"name": "Shell",
"bytes": "6406"
},
{
"name": "Smalltalk",
"bytes": "86"
},
{
"name": "Thrift",
"bytes": "17576"
}
],
"symlink_target": ""
} |
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<!--NewPage-->
<HTML>
<HEAD>
<!-- Generated by javadoc (build 1.6.0_24) on Tue Jun 07 05:05:32 BST 2011 -->
<TITLE>
E-Index
</TITLE>
<META NAME="date" CONTENT="2011-06-07">
<LINK REL ="stylesheet" TYPE="text/css" HREF="../stylesheet.css" TITLE="Style">
<SCRIPT type="text/javascript">
function windowTitle()
{
if (location.href.indexOf('is-external=true') == -1) {
parent.document.title="E-Index";
}
}
</SCRIPT>
<NOSCRIPT>
</NOSCRIPT>
</HEAD>
<BODY BGCOLOR="white" onload="windowTitle();">
<HR>
<!-- ========= START OF TOP NAVBAR ======= -->
<A NAME="navbar_top"><!-- --></A>
<A HREF="#skip-navbar_top" title="Skip navigation links"></A>
<TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0" SUMMARY="">
<TR>
<TD COLSPAN=2 BGCOLOR="#EEEEFF" CLASS="NavBarCell1">
<A NAME="navbar_top_firstrow"><!-- --></A>
<TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3" SUMMARY="">
<TR ALIGN="center" VALIGN="top">
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../overview-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <FONT CLASS="NavBarFont1">Package</FONT> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <FONT CLASS="NavBarFont1">Class</FONT> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <FONT CLASS="NavBarFont1">Use</FONT> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../overview-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A> </TD>
<TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> <FONT CLASS="NavBarFont1Rev"><B>Index</B></FONT> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A> </TD>
</TR>
</TABLE>
</TD>
<TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM>
</EM>
</TD>
</TR>
<TR>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
<A HREF="index-3.html"><B>PREV LETTER</B></A>
<A HREF="index-5.html"><B>NEXT LETTER</B></A></FONT></TD>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
<A HREF="../index.html?index-filesindex-4.html" target="_top"><B>FRAMES</B></A>
<A HREF="index-4.html" target="_top"><B>NO FRAMES</B></A>
<SCRIPT type="text/javascript">
<!--
if(window==top) {
document.writeln('<A HREF="../allclasses-noframe.html"><B>All Classes</B></A>');
}
//-->
</SCRIPT>
<NOSCRIPT>
<A HREF="../allclasses-noframe.html"><B>All Classes</B></A>
</NOSCRIPT>
</FONT></TD>
</TR>
</TABLE>
<A NAME="skip-navbar_top"></A>
<!-- ========= END OF TOP NAVBAR ========= -->
<A HREF="index-1.html">A</A> <A HREF="index-2.html">C</A> <A HREF="index-3.html">D</A> <A HREF="index-4.html">E</A> <A HREF="index-5.html">F</A> <A HREF="index-6.html">G</A> <A HREF="index-7.html">I</A> <A HREF="index-8.html">K</A> <A HREF="index-9.html">L</A> <A HREF="index-10.html">M</A> <A HREF="index-11.html">N</A> <A HREF="index-12.html">O</A> <A HREF="index-13.html">P</A> <A HREF="index-14.html">R</A> <A HREF="index-15.html">S</A> <A HREF="index-16.html">T</A> <A HREF="index-17.html">U</A> <A HREF="index-18.html">V</A> <A HREF="index-19.html">W</A> <A HREF="index-20.html">X</A> <A HREF="index-21.html">Y</A> <HR>
<A NAME="_E_"><!-- --></A><H2>
<B>E</B></H2>
<DL>
<DT><A HREF="../Logic/Enemy.html" title="class in Logic"><B>Enemy</B></A> - Class in <A HREF="../Logic/package-summary.html">Logic</A><DD> <DT><A HREF="../Logic/Enemy.html#Enemy()"><B>Enemy()</B></A> -
Constructor for class Logic.<A HREF="../Logic/Enemy.html" title="class in Logic">Enemy</A>
<DD>Default constructor of Enemy.
<DT><A HREF="../Logic/Command.html#enemyCreation(java.lang.String)"><B>enemyCreation(String)</B></A> -
Method in class Logic.<A HREF="../Logic/Command.html" title="class in Logic">Command</A>
<DD>Creates enemies into the game.
<DT><A HREF="../Logic/Universe.html#enemyCreation()"><B>enemyCreation()</B></A> -
Method in class Logic.<A HREF="../Logic/Universe.html" title="class in Logic">Universe</A>
<DD>
<DT><A HREF="../Logic/Enemy.html#enemyType"><B>enemyType</B></A> -
Variable in class Logic.<A HREF="../Logic/Enemy.html" title="class in Logic">Enemy</A>
<DD>
<DT><A HREF="../gui/AsteroidsSpace.html#exitMenu"><B>exitMenu</B></A> -
Variable in class gui.<A HREF="../gui/AsteroidsSpace.html" title="class in gui">AsteroidsSpace</A>
<DD>
<DT><A HREF="../gui/MainSpace.html#exitMenu"><B>exitMenu</B></A> -
Variable in class gui.<A HREF="../gui/MainSpace.html" title="class in gui">MainSpace</A>
<DD>
</DL>
<HR>
<!-- ======= START OF BOTTOM NAVBAR ====== -->
<A NAME="navbar_bottom"><!-- --></A>
<A HREF="#skip-navbar_bottom" title="Skip navigation links"></A>
<TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0" SUMMARY="">
<TR>
<TD COLSPAN=2 BGCOLOR="#EEEEFF" CLASS="NavBarCell1">
<A NAME="navbar_bottom_firstrow"><!-- --></A>
<TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3" SUMMARY="">
<TR ALIGN="center" VALIGN="top">
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../overview-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <FONT CLASS="NavBarFont1">Package</FONT> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <FONT CLASS="NavBarFont1">Class</FONT> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <FONT CLASS="NavBarFont1">Use</FONT> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../overview-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A> </TD>
<TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> <FONT CLASS="NavBarFont1Rev"><B>Index</B></FONT> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A> </TD>
</TR>
</TABLE>
</TD>
<TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM>
</EM>
</TD>
</TR>
<TR>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
<A HREF="index-3.html"><B>PREV LETTER</B></A>
<A HREF="index-5.html"><B>NEXT LETTER</B></A></FONT></TD>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
<A HREF="../index.html?index-filesindex-4.html" target="_top"><B>FRAMES</B></A>
<A HREF="index-4.html" target="_top"><B>NO FRAMES</B></A>
<SCRIPT type="text/javascript">
<!--
if(window==top) {
document.writeln('<A HREF="../allclasses-noframe.html"><B>All Classes</B></A>');
}
//-->
</SCRIPT>
<NOSCRIPT>
<A HREF="../allclasses-noframe.html"><B>All Classes</B></A>
</NOSCRIPT>
</FONT></TD>
</TR>
</TABLE>
<A NAME="skip-navbar_bottom"></A>
<!-- ======== END OF BOTTOM NAVBAR ======= -->
<A HREF="index-1.html">A</A> <A HREF="index-2.html">C</A> <A HREF="index-3.html">D</A> <A HREF="index-4.html">E</A> <A HREF="index-5.html">F</A> <A HREF="index-6.html">G</A> <A HREF="index-7.html">I</A> <A HREF="index-8.html">K</A> <A HREF="index-9.html">L</A> <A HREF="index-10.html">M</A> <A HREF="index-11.html">N</A> <A HREF="index-12.html">O</A> <A HREF="index-13.html">P</A> <A HREF="index-14.html">R</A> <A HREF="index-15.html">S</A> <A HREF="index-16.html">T</A> <A HREF="index-17.html">U</A> <A HREF="index-18.html">V</A> <A HREF="index-19.html">W</A> <A HREF="index-20.html">X</A> <A HREF="index-21.html">Y</A> <HR>
</BODY>
</HTML>
| {
"content_hash": "d802fd0e7e7e41c02e5568e65583cd53",
"timestamp": "",
"source": "github",
"line_count": 160,
"max_line_length": 625,
"avg_line_length": 48.3125,
"alnum_prop": 0.6254851228978008,
"repo_name": "Nelspike/UniversityStuff",
"id": "a8353716c322bc77255237007b74411e42c88d85",
"size": "7730",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "Asteroids/doc/index-files/index-4.html",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "Prolog",
"bytes": "73683"
}
],
"symlink_target": ""
} |
import itertools
import sys,os
symbolsstr = '0 1 2 3 4 5 6 7 8 9 ( ) + * ^ ▵'
symbols = symbolsstr.split(' ')+[' ']
class Treenode:
left,right,data=None,None,None
def __init__(self,l,r,d):
left,right,data=l,r,d
def tokens(sym):
if sym in ['0','1','2','3','4','5','6','7','8','9',' ']:
pass
if sym in ['+','*','(',')']:
pass
if sym in ['^']:
pass
if sym in ['▵']:
pass
# a
# b c
#
def opplus(a,b):
return a+b
a=Treenode(None,None,opplus)
b=Treenode(None,None,1)
c=Treenode(None,None,2)
a.left=b
a.right=c
def evalleafs(node):
if node.left==None and node.right==None:
return node.data
else:
a=evalleafs(node.left)
b=evalleafs(node.right)
node.data=c(a,b)
# find lowest complexity expression that evaluates to the value n
# return new expression. if all else fails, give back n itself.
def findc(n):
shortestexpr = str(n)
shortestlen = len(shortestexpr)
ns=str(n)
numdigits = len(ns)
print('length of ',n,':',numdigits)
for e in itertools.product(symbols[0:16],repeat=numdigits):
print(e)
expr=convert_to_expression(e)
print(expr)
testn=eval_pexpression(expr)
print('testn',testn)
if n==testn:
pass
# if len less than shortest, new shortest
return shortestlen, shortestexpr
def main():
n=150
complexity,expression = findc(n)
print('lowest complexity('+str(n)+') =',complexity,',"'+expression+'"')
| {
"content_hash": "fc6b54cdcc3e419dffe42e826f63b01a",
"timestamp": "",
"source": "github",
"line_count": 64,
"max_line_length": 72,
"avg_line_length": 21.296875,
"alnum_prop": 0.6485693323550991,
"repo_name": "donbright/piliko",
"id": "88a5e3cb7e2d090a3fe53c17b49a933d8eb76a44",
"size": "1539",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "numplex.py",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "C",
"bytes": "5303"
},
{
"name": "C++",
"bytes": "82774"
},
{
"name": "Go",
"bytes": "18074"
},
{
"name": "HTML",
"bytes": "43043"
},
{
"name": "JavaScript",
"bytes": "4554"
},
{
"name": "Python",
"bytes": "387953"
}
],
"symlink_target": ""
} |
@interface RexxarTests : XCTestCase
@property (nonatomic, readonly) RXRRouteFileManager *routeFileManager;
@property (nonatomic, readonly) id<RXRRequestDecorator> decorater;
@end
@implementation RexxarTests
- (void)setUp
{
NSURL *routesMapURL = [NSURL URLWithString:@"http://rexxar.douban.com/api/routes"];
_routeFileManager = [[RXRRouteFileManager alloc] initWithRoutesMapURL:routesMapURL
cacheDirectory:[[NSUUID UUID] UUIDString]
resourceDirectory:[NSBundle bundleForClass:self.class].bundlePath];
}
- (void)testInterceptAPI
{
NSURL *url = [NSURL URLWithString:@"http://frodo.douban.com/jsonp/subject_collection/movie_free_stream/items?os=ios&loc_id=108288&start=0&count=18&_=1448948380006&callback=jsonp1"];
XCTAssertTrue([RXRRequestIntercepter isRequestInterceptable:[self webResourceRequest:url]]);
url = [NSURL URLWithString:@"http://frodo.douban.com/api/v2/recommend_feed"];
XCTAssertTrue([RXRRequestIntercepter isRequestInterceptable:[self webResourceRequest:url]]);
}
- (NSMutableURLRequest *)webResourceRequest:(NSURL *)url
{
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
[request addValue:@"Mozilla" forHTTPHeaderField:@"User-Agent"];
return request;
}
@end
| {
"content_hash": "4c5f97617eb2b664f7ead84d4433a079",
"timestamp": "",
"source": "github",
"line_count": 35,
"max_line_length": 183,
"avg_line_length": 38.05714285714286,
"alnum_prop": 0.7222222222222222,
"repo_name": "douban/rexxar-ios",
"id": "b12475e6a4e7d78ef6e1cbc4a1776309760bf40a",
"size": "1608",
"binary": false,
"copies": "3",
"ref": "refs/heads/master",
"path": "RexxarTests/RexxarTests.m",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "HTML",
"bytes": "57419"
},
{
"name": "Objective-C",
"bytes": "234116"
},
{
"name": "Ruby",
"bytes": "1209"
},
{
"name": "Swift",
"bytes": "28952"
}
],
"symlink_target": ""
} |
#region Copyright (c) 2004 Ian Davis and James Carlyle
#endregion
namespace SemPlan.Spiral.Tests.Utility {
using NUnit.Framework;
using SemPlan.Spiral.Core;
using SemPlan.Spiral.Tests.Core;
using SemPlan.Spiral.Utility;
using SemPlan.Spiral.XsltParser;
using System;
using System.IO;
using System.Xml;
/// <summary>
/// Programmer tests for RdfXmlWriter class
/// </summary>
/// <remarks>
/// $Id: RdfXmlWriterTest.cs,v 1.2 2005/05/26 14:24:31 ian Exp $
///</remarks>
[TestFixture]
public class RdfXmlWriterTest {
public class RdfXmlWriterTestHarness {
private StringWriter itsOutputWriter;
private RdfXmlWriter itsRdfWriter;
private NTripleListVerifier itsVerifier;
public RdfXmlWriterTestHarness() {
itsOutputWriter = new StringWriter();
XmlTextWriter xmlWriter = new XmlTextWriter(itsOutputWriter);
itsRdfWriter = new RdfXmlWriter( xmlWriter );
itsVerifier = new NTripleListVerifier();
}
public RdfWriter getRdfWriter() {
return itsRdfWriter;
}
public void expect(string ntriple) {
itsVerifier.Expect(ntriple);
}
public bool verify() {
return verify(false);
}
public bool verify(bool verbose) {
SimpleModel model = new SimpleModel(new XsltParserFactory());
model.ParseString( itsOutputWriter.ToString(), "");
if (verbose) {
Console.WriteLine( itsOutputWriter.ToString() );
}
foreach (string ntriple in model) {
itsVerifier.Receive(ntriple);
}
return itsVerifier.Verify();
}
public string getOutput() {
return itsOutputWriter.ToString();
}
}
public void writeSingleUUUTriple(RdfWriter rdfWriter) {
rdfWriter.StartOutput();
rdfWriter.StartSubject();
rdfWriter.WriteUriRef("http://example.com/subj");
rdfWriter.StartPredicate();
rdfWriter.WriteUriRef("http://example.com/pred");
rdfWriter.StartObject();
rdfWriter.WriteUriRef("http://example.com/obj");
rdfWriter.EndObject();
rdfWriter.EndPredicate();
rdfWriter.EndSubject();
rdfWriter.EndOutput();
}
public void writeSingleUUBTriple(RdfWriter rdfWriter) {
rdfWriter.StartOutput();
rdfWriter.StartSubject();
rdfWriter.WriteUriRef("http://example.com/subj");
rdfWriter.StartPredicate();
rdfWriter.WriteUriRef("http://example.com/pred");
rdfWriter.StartObject();
rdfWriter.WriteBlankNode("jazz");
rdfWriter.EndObject();
rdfWriter.EndPredicate();
rdfWriter.EndSubject();
rdfWriter.EndOutput();
}
public void writeTwoUUUTriplesWithSameSubjectAndPredicate(RdfWriter rdfWriter) {
rdfWriter.StartOutput();
rdfWriter.StartSubject();
rdfWriter.WriteUriRef("http://example.com/subj");
rdfWriter.StartPredicate();
rdfWriter.WriteUriRef("http://example.com/pred");
rdfWriter.StartObject();
rdfWriter.WriteUriRef("http://example.com/obj");
rdfWriter.EndObject();
rdfWriter.StartObject();
rdfWriter.WriteUriRef("http://example.com/obj2");
rdfWriter.EndObject();
rdfWriter.EndPredicate();
rdfWriter.EndSubject();
rdfWriter.EndOutput();
}
public void writeTwoUUUTriplesWithSameSubject(RdfWriter rdfWriter) {
rdfWriter.StartOutput();
rdfWriter.StartSubject();
rdfWriter.WriteUriRef("http://example.com/subj");
rdfWriter.StartPredicate();
rdfWriter.WriteUriRef("http://example.com/pred");
rdfWriter.StartObject();
rdfWriter.WriteUriRef("http://example.com/obj");
rdfWriter.EndObject();
rdfWriter.EndPredicate();
rdfWriter.StartPredicate();
rdfWriter.WriteUriRef("http://example.com/pred2");
rdfWriter.StartObject();
rdfWriter.WriteUriRef("http://example.com/obj2");
rdfWriter.EndObject();
rdfWriter.EndPredicate();
rdfWriter.EndSubject();
rdfWriter.EndOutput();
}
[Test]
public void writerWritesXmlPrologAsStandalone() {
XmlWriterStore xmlWriter = new XmlWriterStore();
RdfXmlWriter rdfWriter = new RdfXmlWriter( xmlWriter );
writeSingleUUUTriple(rdfWriter);
Assert.IsTrue( xmlWriter.WasWriteStartDocumentCalledWith(true) );
}
[Test]
public void writerStartsRdfRootElement() {
XmlWriterStore xmlWriter = new XmlWriterStore();
RdfXmlWriter rdfWriter = new RdfXmlWriter( xmlWriter );
writeSingleUUUTriple(rdfWriter);
Assert.IsTrue( xmlWriter.WasWriteStartElementCalledWith("rdf", "RDF", "http://www.w3.org/1999/02/22-rdf-syntax-ns#") );
}
[Test]
public void writerWritesEndDocument() {
XmlWriterCounter xmlWriter = new XmlWriterCounter();
RdfXmlWriter rdfWriter = new RdfXmlWriter( xmlWriter );
writeSingleUUUTriple(rdfWriter);
Assert.AreEqual( 1, xmlWriter.WriteEndDocumentCalled );
}
[Test]
public void writerWritesRdfDescriptionForUntypedSubject() {
XmlWriterStore xmlWriter = new XmlWriterStore();
RdfXmlWriter rdfWriter = new RdfXmlWriter( xmlWriter );
writeSingleUUUTriple(rdfWriter);
Assert.IsTrue( xmlWriter.WasWriteStartElementCalledWith("rdf", "Description", "http://www.w3.org/1999/02/22-rdf-syntax-ns#") );
}
[Test]
public void writerWritesRdfAboutForSubject() {
XmlWriterStore xmlWriter = new XmlWriterStore();
RdfXmlWriter rdfWriter = new RdfXmlWriter( xmlWriter );
writeSingleUUUTriple(rdfWriter);
Assert.IsTrue( xmlWriter.WasWriteStartAttributeCalledWith("rdf", "about", "http://www.w3.org/1999/02/22-rdf-syntax-ns#"), "start attribute" );
Assert.IsTrue( xmlWriter.WasWriteStringCalledWith("http://example.com/subj"), "attribute content" );
}
[Test]
public void writerWritesPredicateElement() {
XmlWriterStore xmlWriter = new XmlWriterStore();
RdfXmlWriter rdfWriter = new RdfXmlWriter( xmlWriter );
writeSingleUUUTriple(rdfWriter);
Assert.IsTrue( xmlWriter.WasWriteStartElementCalledWith("ns1", "pred", "http://example.com/") );
}
[Test]
public void writerWritesRdfResourceForUriRefObject() {
XmlWriterStore xmlWriter = new XmlWriterStore();
RdfXmlWriter rdfWriter = new RdfXmlWriter( xmlWriter );
writeSingleUUUTriple(rdfWriter);
Assert.IsTrue( xmlWriter.WasWriteStartAttributeCalledWith("rdf", "resource", "http://www.w3.org/1999/02/22-rdf-syntax-ns#"), "start attribute" );
Assert.IsTrue( xmlWriter.WasWriteStringCalledWith("http://example.com/obj"), "attribute content" );
}
[Test]
public void writerWritesRdfNodeIdForBlankNodeObject() {
XmlWriterStore xmlWriter = new XmlWriterStore();
RdfXmlWriter rdfWriter = new RdfXmlWriter( xmlWriter );
writeSingleUUBTriple(rdfWriter);
Assert.IsTrue( xmlWriter.WasWriteStartAttributeCalledWith("rdf", "nodeID", "http://www.w3.org/1999/02/22-rdf-syntax-ns#"), "start attribute" );
Assert.IsTrue( xmlWriter.WasWriteStringCalledWith("genid1"), "attribute content" );
}
[Test]
public void writerWritesOneRdfDescriptionPerUniqueSubject() {
XmlWriterCounter xmlWriter = new XmlWriterCounter();
RdfXmlWriter rdfWriter = new RdfXmlWriter( xmlWriter );
rdfWriter.StartOutput();
rdfWriter.StartSubject();
rdfWriter.WriteUriRef("http://example.com/subj");
rdfWriter.StartPredicate();
rdfWriter.WriteUriRef("http://example.com/pred");
rdfWriter.StartObject();
rdfWriter.WriteUriRef("http://example.com/obj");
rdfWriter.EndObject();
rdfWriter.EndPredicate();
rdfWriter.EndSubject();
rdfWriter.StartSubject();
rdfWriter.WriteUriRef("http://example.com/subj2");
rdfWriter.StartPredicate();
rdfWriter.WriteUriRef("http://example.com/pred");
rdfWriter.StartObject();
rdfWriter.WriteUriRef("http://example.com/obj");
rdfWriter.EndObject();
rdfWriter.EndPredicate();
rdfWriter.EndSubject();
rdfWriter.StartSubject();
rdfWriter.WriteUriRef("http://example.com/subj");
rdfWriter.StartPredicate();
rdfWriter.WriteUriRef("http://example.com/pred");
rdfWriter.StartObject();
rdfWriter.WriteUriRef("http://example.com/obj2");
rdfWriter.EndObject();
rdfWriter.EndPredicate();
rdfWriter.EndSubject();
rdfWriter.EndOutput();
// elements should be: rdf:RDF, rdf:Description * 2, ns1:pred * 3
Assert.AreEqual( 6, xmlWriter.WriteEndElementCalled );
}
[Test]
public void roundTripWriteSingleUUUTriple() {
RdfXmlWriterTestHarness harness = new RdfXmlWriterTestHarness();
harness.expect("<http://example.com/subj> <http://example.com/pred> <http://example.com/obj> .");
writeSingleUUUTriple(harness.getRdfWriter());
Assert.IsTrue( harness.verify() );
}
[Test]
public void roundTripTwoUUUTriplesWithSameSubjectAndPredicate() {
RdfXmlWriterTestHarness harness = new RdfXmlWriterTestHarness();
harness.expect("<http://example.com/subj> <http://example.com/pred> <http://example.com/obj> .");
harness.expect("<http://example.com/subj> <http://example.com/pred> <http://example.com/obj2> .");
writeTwoUUUTriplesWithSameSubjectAndPredicate(harness.getRdfWriter());
Assert.IsTrue( harness.verify() );
}
[Test]
public void roundTripTwoUUUTriplesWithSameSubject() {
RdfXmlWriterTestHarness harness = new RdfXmlWriterTestHarness();
harness.expect("<http://example.com/subj> <http://example.com/pred> <http://example.com/obj> .");
harness.expect("<http://example.com/subj> <http://example.com/pred2> <http://example.com/obj2> .");
RdfWriter rdfWriter = harness.getRdfWriter();
writeTwoUUUTriplesWithSameSubject(harness.getRdfWriter());
Assert.IsTrue( harness.verify() );
}
[Test]
public void roundTripWriteSingleUUPWithoutLanguageTriple() {
RdfXmlWriterTestHarness harness = new RdfXmlWriterTestHarness();
harness.expect("<http://example.com/subj> <http://example.com/pred> \"fizz\" .");
RdfWriter rdfWriter = harness.getRdfWriter();
rdfWriter.StartOutput();
rdfWriter.StartSubject();
rdfWriter.WriteUriRef("http://example.com/subj");
rdfWriter.StartPredicate();
rdfWriter.WriteUriRef("http://example.com/pred");
rdfWriter.StartObject();
rdfWriter.WritePlainLiteral("fizz");
rdfWriter.EndObject();
rdfWriter.EndPredicate();
rdfWriter.EndSubject();
rdfWriter.EndOutput();
bool testPassed = harness.verify();
Assert.IsTrue( testPassed );
}
[Test]
public void roundTripWriteTwoUUPWithoutLanguageTriplesWithSameSubjectAndPredicate() {
RdfXmlWriterTestHarness harness = new RdfXmlWriterTestHarness();
harness.expect("<http://example.com/subj> <http://example.com/pred> \"fizz\" .");
harness.expect("<http://example.com/subj> <http://example.com/pred> \"bang\" .");
RdfWriter rdfWriter = harness.getRdfWriter();
rdfWriter.StartOutput();
rdfWriter.StartSubject();
rdfWriter.WriteUriRef("http://example.com/subj");
rdfWriter.StartPredicate();
rdfWriter.WriteUriRef("http://example.com/pred");
rdfWriter.StartObject();
rdfWriter.WritePlainLiteral("fizz");
rdfWriter.EndObject();
rdfWriter.StartObject();
rdfWriter.WritePlainLiteral("bang");
rdfWriter.EndObject();
rdfWriter.EndPredicate();
rdfWriter.EndSubject();
rdfWriter.EndOutput();
bool testPassed = harness.verify();
Assert.IsTrue( testPassed );
}
[Test]
public void roundTripWriteTwoUUPWithoutLanguageTriplesWithSameSubject() {
RdfXmlWriterTestHarness harness = new RdfXmlWriterTestHarness();
harness.expect("<http://example.com/subj> <http://example.com/pred> \"fizz\" .");
harness.expect("<http://example.com/subj> <http://example.com/pred2> \"bang\" .");
RdfWriter rdfWriter = harness.getRdfWriter();
rdfWriter.StartOutput();
rdfWriter.StartSubject();
rdfWriter.WriteUriRef("http://example.com/subj");
rdfWriter.StartPredicate();
rdfWriter.WriteUriRef("http://example.com/pred");
rdfWriter.StartObject();
rdfWriter.WritePlainLiteral("fizz");
rdfWriter.EndObject();
rdfWriter.EndPredicate();
rdfWriter.StartPredicate();
rdfWriter.WriteUriRef("http://example.com/pred2");
rdfWriter.StartObject();
rdfWriter.WritePlainLiteral("bang");
rdfWriter.EndObject();
rdfWriter.EndPredicate();
rdfWriter.EndSubject();
rdfWriter.EndOutput();
bool testPassed = harness.verify();
Assert.IsTrue( testPassed );
}
[Test]
public void roundTripWriteSingleUUPWithLanguageTriple() {
RdfXmlWriterTestHarness harness = new RdfXmlWriterTestHarness();
harness.expect("<http://example.com/subj> <http://example.com/pred> \"fizz\"@de .");
RdfWriter rdfWriter = harness.getRdfWriter();
rdfWriter.StartOutput();
rdfWriter.StartSubject();
rdfWriter.WriteUriRef("http://example.com/subj");
rdfWriter.StartPredicate();
rdfWriter.WriteUriRef("http://example.com/pred");
rdfWriter.StartObject();
rdfWriter.WritePlainLiteral("fizz", "de");
rdfWriter.EndObject();
rdfWriter.EndPredicate();
rdfWriter.EndSubject();
rdfWriter.EndOutput();
bool testPassed = harness.verify();
Assert.IsTrue( testPassed );
}
[Test]
public void roundTripWriteTwoUUPWithLanguageTriplesWithSameSubjectAndPredicate() {
RdfXmlWriterTestHarness harness = new RdfXmlWriterTestHarness();
harness.expect("<http://example.com/subj> <http://example.com/pred> \"fizz\"@fr .");
harness.expect("<http://example.com/subj> <http://example.com/pred> \"bang\"@it .");
RdfWriter rdfWriter = harness.getRdfWriter();
rdfWriter.StartOutput();
rdfWriter.StartSubject();
rdfWriter.WriteUriRef("http://example.com/subj");
rdfWriter.StartPredicate();
rdfWriter.WriteUriRef("http://example.com/pred");
rdfWriter.StartObject();
rdfWriter.WritePlainLiteral("fizz", "fr");
rdfWriter.EndObject();
rdfWriter.StartObject();
rdfWriter.WritePlainLiteral("bang", "it");
rdfWriter.EndObject();
rdfWriter.EndPredicate();
rdfWriter.EndSubject();
rdfWriter.EndOutput();
bool testPassed = harness.verify();
Assert.IsTrue( testPassed );
}
[Test]
public void roundTripWriteTwoUUPWithLanguageTriplesWithSameSubject() {
RdfXmlWriterTestHarness harness = new RdfXmlWriterTestHarness();
harness.expect("<http://example.com/subj> <http://example.com/pred> \"fizz\"@fr .");
harness.expect("<http://example.com/subj> <http://example.com/pred2> \"bang\"@it .");
RdfWriter rdfWriter = harness.getRdfWriter();
rdfWriter.StartOutput();
rdfWriter.StartSubject();
rdfWriter.WriteUriRef("http://example.com/subj");
rdfWriter.StartPredicate();
rdfWriter.WriteUriRef("http://example.com/pred");
rdfWriter.StartObject();
rdfWriter.WritePlainLiteral("fizz", "fr");
rdfWriter.EndObject();
rdfWriter.EndPredicate();
rdfWriter.StartPredicate();
rdfWriter.WriteUriRef("http://example.com/pred2");
rdfWriter.StartObject();
rdfWriter.WritePlainLiteral("bang", "it");
rdfWriter.EndObject();
rdfWriter.EndPredicate();
rdfWriter.EndSubject();
rdfWriter.EndOutput();
bool testPassed = harness.verify();
Assert.IsTrue( testPassed );
}
[Test]
public void roundTripWriteSingleUUTTriple() {
RdfXmlWriterTestHarness harness = new RdfXmlWriterTestHarness();
harness.expect("<http://example.com/subj> <http://example.com/pred> \"fizz\"^^<http://www.w3.org/2001/XMLSchema#integer> .");
RdfWriter rdfWriter = harness.getRdfWriter();
rdfWriter.StartOutput();
rdfWriter.StartSubject();
rdfWriter.WriteUriRef("http://example.com/subj");
rdfWriter.StartPredicate();
rdfWriter.WriteUriRef("http://example.com/pred");
rdfWriter.StartObject();
rdfWriter.WriteTypedLiteral("fizz", "http://www.w3.org/2001/XMLSchema#integer");
rdfWriter.EndObject();
rdfWriter.EndPredicate();
rdfWriter.EndSubject();
rdfWriter.EndOutput();
bool testPassed = harness.verify();
Assert.IsTrue( testPassed );
}
[Test]
public void roundTripWriteTwoUUTTriplesWithSameSubjectAndPredicate() {
RdfXmlWriterTestHarness harness = new RdfXmlWriterTestHarness();
harness.expect("<http://example.com/subj> <http://example.com/pred> \"fizz\"^^<http://www.w3.org/2001/XMLSchema#integer> .");
harness.expect("<http://example.com/subj> <http://example.com/pred> \"bang\"^^<http://www.w3.org/2001/XMLSchema#integer> .");
RdfWriter rdfWriter = harness.getRdfWriter();
rdfWriter.StartOutput();
rdfWriter.StartSubject();
rdfWriter.WriteUriRef("http://example.com/subj");
rdfWriter.StartPredicate();
rdfWriter.WriteUriRef("http://example.com/pred");
rdfWriter.StartObject();
rdfWriter.WriteTypedLiteral("fizz", "http://www.w3.org/2001/XMLSchema#integer");
rdfWriter.EndObject();
rdfWriter.StartObject();
rdfWriter.WriteTypedLiteral("bang", "http://www.w3.org/2001/XMLSchema#integer");
rdfWriter.EndObject();
rdfWriter.EndPredicate();
rdfWriter.EndSubject();
rdfWriter.EndOutput();
bool testPassed = harness.verify();
Assert.IsTrue( testPassed );
}
[Test]
public void roundTripWriteTwoUUTTriplesWithSameSubject() {
RdfXmlWriterTestHarness harness = new RdfXmlWriterTestHarness();
harness.expect("<http://example.com/subj> <http://example.com/pred> \"fizz\"^^<http://www.w3.org/2001/XMLSchema#integer> .");
harness.expect("<http://example.com/subj> <http://example.com/pred2> \"bang\"^^<http://www.w3.org/2001/XMLSchema#integer> .");
RdfWriter rdfWriter = harness.getRdfWriter();
rdfWriter.StartOutput();
rdfWriter.StartSubject();
rdfWriter.WriteUriRef("http://example.com/subj");
rdfWriter.StartPredicate();
rdfWriter.WriteUriRef("http://example.com/pred");
rdfWriter.StartObject();
rdfWriter.WriteTypedLiteral("fizz", "http://www.w3.org/2001/XMLSchema#integer");
rdfWriter.EndObject();
rdfWriter.EndPredicate();
rdfWriter.StartPredicate();
rdfWriter.WriteUriRef("http://example.com/pred2");
rdfWriter.StartObject();
rdfWriter.WriteTypedLiteral("bang", "http://www.w3.org/2001/XMLSchema#integer");
rdfWriter.EndObject();
rdfWriter.EndPredicate();
rdfWriter.EndSubject();
rdfWriter.EndOutput();
bool testPassed = harness.verify();
Assert.IsTrue( testPassed );
}
[Test]
public void roundTripWriteSingleBUUTriple() {
RdfXmlWriterTestHarness harness = new RdfXmlWriterTestHarness();
harness.expect("_:genid1 <http://example.com/pred> <http://example.com/obj> .");
RdfWriter rdfWriter = harness.getRdfWriter();
rdfWriter.StartOutput();
rdfWriter.StartSubject();
rdfWriter.WriteBlankNode("foo");
rdfWriter.StartPredicate();
rdfWriter.WriteUriRef("http://example.com/pred");
rdfWriter.StartObject();
rdfWriter.WriteUriRef("http://example.com/obj");
rdfWriter.EndObject();
rdfWriter.EndPredicate();
rdfWriter.EndSubject();
rdfWriter.EndOutput();
Assert.IsTrue( harness.verify() );
}
[Test]
public void roundTripWriteSingleUUBTriple() {
RdfXmlWriterTestHarness harness = new RdfXmlWriterTestHarness();
harness.expect("<http://example.com/subj> <http://example.com/pred> _:genid1 .");
RdfWriter rdfWriter = harness.getRdfWriter();
rdfWriter.StartOutput();
rdfWriter.StartSubject();
rdfWriter.WriteUriRef("http://example.com/subj");
rdfWriter.StartPredicate();
rdfWriter.WriteUriRef("http://example.com/pred");
rdfWriter.StartObject();
rdfWriter.WriteBlankNode("foo");
rdfWriter.EndObject();
rdfWriter.EndPredicate();
rdfWriter.EndSubject();
rdfWriter.EndOutput();
Assert.IsTrue( harness.verify() );
}
[Test]
public void roundTripWriteSingleBUBTripleWithSameNodeId() {
RdfXmlWriterTestHarness harness = new RdfXmlWriterTestHarness();
harness.expect("_:genid1 <http://example.com/pred> _:genid1 .");
RdfWriter rdfWriter = harness.getRdfWriter();
rdfWriter.StartOutput();
rdfWriter.StartSubject();
rdfWriter.WriteBlankNode("foo");
rdfWriter.StartPredicate();
rdfWriter.WriteUriRef("http://example.com/pred");
rdfWriter.StartObject();
rdfWriter.WriteBlankNode("foo");
rdfWriter.EndObject();
rdfWriter.EndPredicate();
rdfWriter.EndSubject();
rdfWriter.EndOutput();
Assert.IsTrue( harness.verify() );
}
[Test]
public void roundTripTwoUUUTriplesWithSameSubjectDifferentPredicateNamespaces() {
RdfXmlWriterTestHarness harness = new RdfXmlWriterTestHarness();
harness.expect("<http://example.com/subj> <http://ex1.example.com/pred> <http://example.com/obj> .");
harness.expect("<http://example.com/subj> <http://ex2.example.com/pred> <http://example.com/obj2> .");
RdfWriter rdfWriter = harness.getRdfWriter();
rdfWriter.StartOutput();
rdfWriter.StartSubject();
rdfWriter.WriteUriRef("http://example.com/subj");
rdfWriter.StartPredicate();
rdfWriter.WriteUriRef("http://ex1.example.com/pred");
rdfWriter.StartObject();
rdfWriter.WriteUriRef("http://example.com/obj");
rdfWriter.EndObject();
rdfWriter.EndPredicate();
rdfWriter.StartPredicate();
rdfWriter.WriteUriRef("http://ex2.example.com/pred");
rdfWriter.StartObject();
rdfWriter.WriteUriRef("http://example.com/obj2");
rdfWriter.EndObject();
rdfWriter.EndPredicate();
rdfWriter.EndSubject();
rdfWriter.EndOutput();
Assert.IsTrue( harness.verify() );
}
[Test]
public void registerNamespacePrefix() {
XmlWriterStore xmlWriter = new XmlWriterStore();
RdfXmlWriter rdfWriter = new RdfXmlWriter( xmlWriter );
rdfWriter.RegisterNamespacePrefix( "http://foo.example.com/", "foo");
rdfWriter.StartOutput();
rdfWriter.StartSubject();
rdfWriter.WriteUriRef("http://example.com/subj");
rdfWriter.StartPredicate();
rdfWriter.WriteUriRef("http://foo.example.com/name");
rdfWriter.StartObject();
rdfWriter.WriteUriRef("http://example.com/obj");
rdfWriter.EndObject();
rdfWriter.EndPredicate();
rdfWriter.EndSubject();
rdfWriter.EndOutput();
Assert.IsTrue( xmlWriter.WasWriteStartElementCalledWith("foo", "name", "http://foo.example.com/") );
}
[Test]
public void commonNamespacePrefixesAlreadyRegistered() {
XmlWriterStore xmlWriter = new XmlWriterStore();
RdfXmlWriter rdfWriter = new RdfXmlWriter( xmlWriter );
rdfWriter.StartOutput();
rdfWriter.StartSubject();
rdfWriter.WriteUriRef("http://example.com/subj");
rdfWriter.StartPredicate();
rdfWriter.WriteUriRef("http://xmlns.com/foaf/0.1/prop");
rdfWriter.StartObject();
rdfWriter.WriteUriRef("http://example.com/obj");
rdfWriter.EndObject();
rdfWriter.EndPredicate();
rdfWriter.StartPredicate();
rdfWriter.WriteUriRef("http://xmlns.com/wot/0.1/prop");
rdfWriter.StartObject();
rdfWriter.WriteUriRef("http://example.com/obj");
rdfWriter.EndObject();
rdfWriter.EndPredicate();
rdfWriter.StartPredicate();
rdfWriter.WriteUriRef("http://www.w3.org/1999/02/22-rdf-syntax-ns#prop");
rdfWriter.StartObject();
rdfWriter.WriteUriRef("http://example.com/obj");
rdfWriter.EndObject();
rdfWriter.EndPredicate();
rdfWriter.StartPredicate();
rdfWriter.WriteUriRef("http://www.w3.org/2000/01/rdf-schema#prop");
rdfWriter.StartObject();
rdfWriter.WriteUriRef("http://example.com/obj");
rdfWriter.EndObject();
rdfWriter.EndPredicate();
rdfWriter.StartPredicate();
rdfWriter.WriteUriRef("http://www.w3.org/2002/07/owl#prop");
rdfWriter.StartObject();
rdfWriter.WriteUriRef("http://example.com/obj");
rdfWriter.EndObject();
rdfWriter.EndPredicate();
rdfWriter.StartPredicate();
rdfWriter.WriteUriRef("http://purl.org/vocab/bio/0.1/prop");
rdfWriter.StartObject();
rdfWriter.WriteUriRef("http://example.com/obj");
rdfWriter.EndObject();
rdfWriter.EndPredicate();
rdfWriter.StartPredicate();
rdfWriter.WriteUriRef("http://purl.org/dc/elements/1.1/prop");
rdfWriter.StartObject();
rdfWriter.WriteUriRef("http://example.com/obj");
rdfWriter.EndObject();
rdfWriter.EndPredicate();
rdfWriter.StartPredicate();
rdfWriter.WriteUriRef("http://purl.org/dc/terms/prop");
rdfWriter.StartObject();
rdfWriter.WriteUriRef("http://example.com/obj");
rdfWriter.EndObject();
rdfWriter.EndPredicate();
rdfWriter.StartPredicate();
rdfWriter.WriteUriRef("http://web.resource.org/cc/prop");
rdfWriter.StartObject();
rdfWriter.WriteUriRef("http://example.com/obj");
rdfWriter.EndObject();
rdfWriter.EndPredicate();
rdfWriter.StartPredicate();
rdfWriter.WriteUriRef("http://purl.org/vocab/relationship/prop");
rdfWriter.StartObject();
rdfWriter.WriteUriRef("http://example.com/obj");
rdfWriter.EndObject();
rdfWriter.EndPredicate();
rdfWriter.StartPredicate();
rdfWriter.WriteUriRef("http://www.w3.org/2003/01/geo/wgs84_pos#prop");
rdfWriter.StartObject();
rdfWriter.WriteUriRef("http://example.com/obj");
rdfWriter.EndObject();
rdfWriter.EndPredicate();
rdfWriter.StartPredicate();
rdfWriter.WriteUriRef("http://purl.org/rss/1.0/prop");
rdfWriter.StartObject();
rdfWriter.WriteUriRef("http://example.com/obj");
rdfWriter.EndObject();
rdfWriter.EndPredicate();
rdfWriter.EndSubject();
rdfWriter.EndOutput();
Assert.IsTrue( xmlWriter.WasWriteStartElementCalledWith("foaf", "prop", "http://xmlns.com/foaf/0.1/") , "foaf prefix");
Assert.IsTrue( xmlWriter.WasWriteStartElementCalledWith("wot", "prop", "http://xmlns.com/wot/0.1/") , "wot prefix");
Assert.IsTrue( xmlWriter.WasWriteStartElementCalledWith("rdf", "prop", "http://www.w3.org/1999/02/22-rdf-syntax-ns#") , "rdf prefix");
Assert.IsTrue( xmlWriter.WasWriteStartElementCalledWith("rdfs", "prop", "http://www.w3.org/2000/01/rdf-schema#") , "rdf schema prefix");
Assert.IsTrue( xmlWriter.WasWriteStartElementCalledWith("owl", "prop", "http://www.w3.org/2002/07/owl#") , "owl prefix");
Assert.IsTrue( xmlWriter.WasWriteStartElementCalledWith("bio", "prop", "http://purl.org/vocab/bio/0.1/") , "bio prefix");
Assert.IsTrue( xmlWriter.WasWriteStartElementCalledWith("dc", "prop", "http://purl.org/dc/elements/1.1/") , "dublin core prefix");
Assert.IsTrue( xmlWriter.WasWriteStartElementCalledWith("dct", "prop", "http://purl.org/dc/terms/" ) , "dublin core terms prefix");
Assert.IsTrue( xmlWriter.WasWriteStartElementCalledWith("cc", "prop", "http://web.resource.org/cc/") , "creative commons prefix");
Assert.IsTrue( xmlWriter.WasWriteStartElementCalledWith("rel", "prop", "http://purl.org/vocab/relationship/") , "relationship prefix");
Assert.IsTrue( xmlWriter.WasWriteStartElementCalledWith("geo", "prop", "http://www.w3.org/2003/01/geo/wgs84_pos#") , "geo prefix");
Assert.IsTrue( xmlWriter.WasWriteStartElementCalledWith("rss", "prop", "http://purl.org/rss/1.0/") , "rss prefix");
}
[Test]
public void newNamespacesAreAssignedNewPrefixes() {
XmlWriterStore xmlWriter = new XmlWriterStore();
RdfXmlWriter rdfWriter = new RdfXmlWriter( xmlWriter );
rdfWriter.StartOutput();
rdfWriter.StartSubject();
rdfWriter.WriteUriRef("http://example.com/subj");
rdfWriter.StartPredicate();
rdfWriter.WriteUriRef("http://foo.example.com/name");
rdfWriter.StartObject();
rdfWriter.WriteUriRef("http://example.com/obj");
rdfWriter.EndObject();
rdfWriter.EndPredicate();
rdfWriter.StartPredicate();
rdfWriter.WriteUriRef("http://bar.example.com/name");
rdfWriter.StartObject();
rdfWriter.WriteUriRef("http://example.com/obj");
rdfWriter.EndObject();
rdfWriter.EndPredicate();
rdfWriter.EndSubject();
rdfWriter.EndOutput();
Assert.IsTrue( xmlWriter.WasWriteStartElementCalledWith("ns1", "name", "http://foo.example.com/"),"first new namespace assigned" );
Assert.IsTrue( xmlWriter.WasWriteStartElementCalledWith("ns2", "name", "http://bar.example.com/"),"second new namespace assigned" );
}
[Test]
public void newNamespacePrefixesAreRememberedAndReused() {
XmlWriterStore xmlWriter = new XmlWriterStore();
RdfXmlWriter rdfWriter = new RdfXmlWriter( xmlWriter );
rdfWriter.StartOutput();
rdfWriter.StartSubject();
rdfWriter.WriteUriRef("http://example.com/subj");
rdfWriter.StartPredicate();
rdfWriter.WriteUriRef("http://foo.example.com/name");
rdfWriter.StartObject();
rdfWriter.WriteUriRef("http://example.com/obj");
rdfWriter.EndObject();
rdfWriter.EndPredicate();
rdfWriter.StartPredicate();
rdfWriter.WriteUriRef("http://bar.example.com/name");
rdfWriter.StartObject();
rdfWriter.WriteUriRef("http://example.com/obj");
rdfWriter.EndObject();
rdfWriter.EndPredicate();
rdfWriter.StartPredicate();
rdfWriter.WriteUriRef("http://foo.example.com/place");
rdfWriter.StartObject();
rdfWriter.WriteUriRef("http://example.com/obj");
rdfWriter.EndObject();
rdfWriter.EndPredicate();
rdfWriter.EndSubject();
rdfWriter.EndOutput();
Assert.IsTrue( xmlWriter.WasWriteStartElementCalledWith("ns1", "place", "http://foo.example.com/"),"first new namespace reused" );
}
[Test]
public void rdfNamespacePrefixCanBeChanged() {
XmlWriterStore xmlWriter = new XmlWriterStore();
RdfXmlWriter rdfWriter = new RdfXmlWriter( xmlWriter );
rdfWriter.RegisterNamespacePrefix( "http://www.w3.org/1999/02/22-rdf-syntax-ns#", "wtf");
rdfWriter.StartOutput();
rdfWriter.StartSubject();
rdfWriter.WriteUriRef("http://example.com/subj");
rdfWriter.StartPredicate();
rdfWriter.WriteUriRef("http://foo.example.com/name");
rdfWriter.StartObject();
rdfWriter.WriteUriRef("http://example.com/obj");
rdfWriter.EndObject();
rdfWriter.EndPredicate();
rdfWriter.EndSubject();
rdfWriter.EndOutput();
Assert.IsTrue( xmlWriter.WasWriteStartElementCalledWith("wtf", "RDF", "http://www.w3.org/1999/02/22-rdf-syntax-ns#"), "RDF element uses registered prefix");
Assert.IsTrue( xmlWriter.WasWriteStartElementCalledWith("wtf", "Description", "http://www.w3.org/1999/02/22-rdf-syntax-ns#"), "Description element uses registered prefix" );
Assert.IsTrue( xmlWriter.WasWriteStartAttributeCalledWith("wtf", "about", "http://www.w3.org/1999/02/22-rdf-syntax-ns#"), "about attribute uses registered prefix" );
Assert.IsTrue( xmlWriter.WasWriteStartAttributeCalledWith("wtf", "resource", "http://www.w3.org/1999/02/22-rdf-syntax-ns#"), "resource attribute uses registered prefix" );
}
[Test]
public void subjectUsedTypedNodeIfRdfTypeSpecified() {
XmlWriterStore xmlWriter = new XmlWriterStore();
RdfXmlWriter rdfWriter = new RdfXmlWriter( xmlWriter );
rdfWriter.RegisterNamespacePrefix( "http://example.com/", "ex");
rdfWriter.StartOutput();
rdfWriter.StartSubject();
rdfWriter.WriteUriRef("http://example.com/subj");
rdfWriter.StartPredicate();
rdfWriter.WriteUriRef("http://foo.example.com/name");
rdfWriter.StartObject();
rdfWriter.WriteUriRef("http://example.com/obj");
rdfWriter.EndObject();
rdfWriter.EndPredicate();
rdfWriter.StartPredicate();
rdfWriter.WriteUriRef("http://www.w3.org/1999/02/22-rdf-syntax-ns#type");
rdfWriter.StartObject();
rdfWriter.WriteUriRef("http://example.com/Thing");
rdfWriter.EndObject();
rdfWriter.EndPredicate();
rdfWriter.EndSubject();
rdfWriter.EndOutput();
Assert.IsTrue( xmlWriter.WasWriteStartElementCalledWith("ex", "Thing", "http://example.com/"));
}
[Test]
public void subjectUsesOnlyFirstRdfTypePropertyToDetermineTypedNode() {
XmlWriterStore xmlWriter = new XmlWriterStore();
RdfXmlWriter rdfWriter = new RdfXmlWriter( xmlWriter );
rdfWriter.RegisterNamespacePrefix( "http://example.com/", "ex");
rdfWriter.StartOutput();
rdfWriter.StartSubject();
rdfWriter.WriteUriRef("http://example.com/subj");
rdfWriter.StartPredicate();
rdfWriter.WriteUriRef("http://foo.example.com/name");
rdfWriter.StartObject();
rdfWriter.WriteUriRef("http://example.com/obj");
rdfWriter.EndObject();
rdfWriter.EndPredicate();
rdfWriter.StartPredicate();
rdfWriter.WriteUriRef("http://www.w3.org/1999/02/22-rdf-syntax-ns#type");
rdfWriter.StartObject();
rdfWriter.WriteUriRef("http://example.com/Thing");
rdfWriter.EndObject();
rdfWriter.EndPredicate();
rdfWriter.StartPredicate();
rdfWriter.WriteUriRef("http://www.w3.org/1999/02/22-rdf-syntax-ns#type");
rdfWriter.StartObject();
rdfWriter.WriteUriRef("http://example.com/Other");
rdfWriter.EndObject();
rdfWriter.EndPredicate();
rdfWriter.EndSubject();
rdfWriter.EndOutput();
Assert.IsFalse( xmlWriter.WasWriteStartElementCalledWith("ex", "Other", "http://example.com/"));
}
[Test]
public void writerMapsNodeIdsToNewValues() {
XmlWriterStore xmlWriter = new XmlWriterStore();
RdfXmlWriter rdfWriter = new RdfXmlWriter( xmlWriter );
rdfWriter.RegisterNamespacePrefix( "http://example.com/", "ex");
rdfWriter.StartOutput();
rdfWriter.StartSubject();
rdfWriter.WriteBlankNode("foo");
rdfWriter.StartPredicate();
rdfWriter.WriteUriRef("http://example.com/pred");
rdfWriter.StartObject();
rdfWriter.WriteUriRef("http://example.com/obj");
rdfWriter.EndObject();
rdfWriter.EndPredicate();
rdfWriter.EndSubject();
rdfWriter.EndOutput();
Assert.IsFalse( xmlWriter.WasWriteStringCalledWith("foo"), "attribute content" );
}
}
}
| {
"content_hash": "ad8007f476b767581c9ddae2ec8d50fd",
"timestamp": "",
"source": "github",
"line_count": 940,
"max_line_length": 179,
"avg_line_length": 40.363829787234046,
"alnum_prop": 0.6221074271256127,
"repo_name": "iand/spiralrdf",
"id": "b6f0a751c04125254aa5caa2e439651d4349e839",
"size": "39239",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/SemPlan.Spiral.Tests.Utility/RdfXmlWriterTest.cs",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C#",
"bytes": "1347584"
},
{
"name": "HTML",
"bytes": "1710"
},
{
"name": "XSLT",
"bytes": "44839"
}
],
"symlink_target": ""
} |
require_relative '../environment'
require_relative 'monkey_patches.rb'
require_relative '../models'
require_relative 'uuid'
require_relative 'hps_bioindex/errors'
require_relative 'hps_bioindex/version'
require_relative 'hps_bioindex/downloader'
require_relative 'hps_bioindex/harvester'
require_relative 'hps_bioindex/dspace_api'
require_relative 'hps_bioindex/name_finder'
require_relative 'hps_bioindex/gnrd_api'
require_relative 'hps_bioindex/name_organizer'
require_relative 'hps_bioindex/eol_harvester'
require_relative 'hps_bioindex/eol_dwca'
module HpsBioindex
def self.version
VERSION
end
def self.logger
@logger ||= Logger.new('/dev/null')
end
def self.logger=(new_logger)
@logger = new_logger
end
end
| {
"content_hash": "b275ead472d605988bcb25ef86487894",
"timestamp": "",
"source": "github",
"line_count": 30,
"max_line_length": 46,
"avg_line_length": 24.7,
"alnum_prop": 0.766531713900135,
"repo_name": "mbl-cli/hps_bioindex",
"id": "d5db7891d6a0fdd3933c177771bd36065bbfd708",
"size": "741",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "lib/hps_bioindex.rb",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "7651"
},
{
"name": "Ruby",
"bytes": "79835"
}
],
"symlink_target": ""
} |
<?php
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class AddExpireTimeColumnToNotificationTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::table('notifications', function (Blueprint $table) {
$table->timestamp('expire_time')->nullable();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::table('notifications', function (Blueprint $table) {
$table->dropColumn('expire_time');
});
}
}
| {
"content_hash": "daa26921ac7980cf5ab441fd72684082",
"timestamp": "",
"source": "github",
"line_count": 31,
"max_line_length": 68,
"avg_line_length": 21,
"alnum_prop": 0.5791090629800307,
"repo_name": "fenos/Notifynder",
"id": "9f56cc1e78af7da4a56ce071d1af7a4e4468ae4f",
"size": "651",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/migrations/2015_06_06_211555_add_expire_time_column_to_notification_table.php",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "PHP",
"bytes": "119325"
}
],
"symlink_target": ""
} |
'use strict';
var Extractor = require('angular-gettext-tools').Extractor;
var gutil = require('gulp-util');
var through = require('through2');
var path = require('path');
var assign = require('lodash.assign');
var pluginName = require('../package.json').name;
module.exports = function (out, config) {
if (!config) {
// out is optional
config = arguments[0];
out = null;
}
var emitStreamingError = function () {
this.emit('error', new gutil.PluginError(pluginName, 'Streaming not supported'));
}.bind(this);
var getPoFromFile = function (file) {
var extractor = new Extractor(config);
extractor.parse(file.path, file.contents.toString());
return extractor.toString();
};
if (!out) {
// return a standard gulp stream
return through.obj(function (file, enc, cb) {
if (file.isNull()) {
this.push(file);
return cb();
}
if (file.isStream()) {
emitStreamingError();
return cb();
}
file.contents = new Buffer(getPoFromFile(file));
this.push(file);
cb();
});
}
// concatenate output, inspired by gulp-concat
var buffer = []; // array of po strings
var firstFile = null;
var bufferContents = function (file, encoding, cb) {
if (file.isNull()) {
cb(); // ignore
return;
}
if (file.isStream()) {
emitStreamingError();
cb();
return;
}
if (!firstFile) {
firstFile = file;
buffer.push(getPoFromFile(file));
} else {
// remove duplicate preamble
var removeHeaders = function (po) {
po.headers = {};
};
var options = assign({
postProcess: removeHeaders
}, config);
if (config.postProcess) {
// chain transform functions
options.postProcess = function (po) {
removeHeaders(po); // call our function first so client can override
config.postProcess(po);
};
}
var extractor = new Extractor(options);
extractor.parse(file.path, file.contents.toString());
var contents = extractor.toString().replace(/^msgid\s+""\s+msgstr\s+""\s+/, '');
buffer.push(contents);
}
cb();
};
var flush = function (cb) {
if (buffer.length === 0) {
cb();
return;
}
var contents = buffer.join('\n')
.replace(/\s+$/, '\n'); // remove trailing whitespace
this.push(new gutil.File({
// if you don't want to use the first file for the base directory, you can use gulp-rename to change it
cwd: firstFile.cwd,
base: firstFile.base,
path: path.join(firstFile.base, out),
contents: new Buffer(contents)
}));
cb();
};
return through.obj(bufferContents, flush);
};
| {
"content_hash": "e95da705a424680efd8126773d9262dd",
"timestamp": "",
"source": "github",
"line_count": 117,
"max_line_length": 109,
"avg_line_length": 23.512820512820515,
"alnum_prop": 0.5863322428207924,
"repo_name": "rubenv/gulp-angular-gettext",
"id": "b4fe59149e5b047317130f11dbc28dc8c0e22c8b",
"size": "2751",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "lib/extract.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "JavaScript",
"bytes": "7231"
}
],
"symlink_target": ""
} |
package org.basex.query.func.session;
import org.basex.query.*;
import org.basex.query.func.java.*;
import org.basex.query.value.*;
import org.basex.query.value.seq.*;
/**
* Function implementation.
*
* @author BaseX Team 2005-20, BSD License
* @author Christian Gruen
*/
public final class SessionGet extends SessionFn {
@Override
public Value value(final QueryContext qc) throws QueryException {
final byte[] name = toToken(exprs[0], qc);
final Value dflt = exprs.length == 1 ? Empty.VALUE : exprs[1].value(qc);
final Object object = session(qc).get(name);
return object != null ? JavaCall.toValue(object, qc, sc) : dflt;
}
}
| {
"content_hash": "fe56ffd3b22c2f5ac11a85c1d593281e",
"timestamp": "",
"source": "github",
"line_count": 23,
"max_line_length": 76,
"avg_line_length": 28.608695652173914,
"alnum_prop": 0.7006079027355623,
"repo_name": "dimitarp/basex",
"id": "96ed37b1a6ed297923e28a448512341a352fcb94",
"size": "658",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "basex-api/src/main/java/org/basex/query/func/session/SessionGet.java",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "ActionScript",
"bytes": "9372"
},
{
"name": "Batchfile",
"bytes": "1998"
},
{
"name": "C",
"bytes": "18635"
},
{
"name": "C#",
"bytes": "13443"
},
{
"name": "C++",
"bytes": "7796"
},
{
"name": "CSS",
"bytes": "3846"
},
{
"name": "Common Lisp",
"bytes": "3211"
},
{
"name": "Dockerfile",
"bytes": "859"
},
{
"name": "Haskell",
"bytes": "4065"
},
{
"name": "Java",
"bytes": "7531709"
},
{
"name": "JavaScript",
"bytes": "15136"
},
{
"name": "Makefile",
"bytes": "1234"
},
{
"name": "PHP",
"bytes": "8690"
},
{
"name": "Perl",
"bytes": "7801"
},
{
"name": "Python",
"bytes": "15193"
},
{
"name": "QMake",
"bytes": "377"
},
{
"name": "R",
"bytes": "14372"
},
{
"name": "Rebol",
"bytes": "4731"
},
{
"name": "Ruby",
"bytes": "7359"
},
{
"name": "Scala",
"bytes": "11692"
},
{
"name": "Shell",
"bytes": "3658"
},
{
"name": "Visual Basic .NET",
"bytes": "11957"
},
{
"name": "XQuery",
"bytes": "244239"
},
{
"name": "XSLT",
"bytes": "406"
}
],
"symlink_target": ""
} |
using System.Collections.Generic;
namespace Orchard.Azure.MediaServices.ViewModels.Settings {
public class EncodingSettingsViewModel {
public IEnumerable<string> WamsEncodingPresets { get; set; }
public int DefaultWamsEncodingPresetIndex { get; set; }
}
} | {
"content_hash": "f897e1e879cff062020d1dce20c5be79",
"timestamp": "",
"source": "github",
"line_count": 8,
"max_line_length": 68,
"avg_line_length": 36,
"alnum_prop": 0.7291666666666666,
"repo_name": "TheMrCPlay/PusdKop",
"id": "30c0d0281faef50bc6966c4a52f5efb4868065b3",
"size": "290",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "src/Orchard.Web/Modules/Orchard.Azure.MediaServices/ViewModels/Settings/EncodingPresetsSettingsViewModel.cs",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "ASP",
"bytes": "3613"
},
{
"name": "C",
"bytes": "4964"
},
{
"name": "C#",
"bytes": "8211720"
},
{
"name": "CSS",
"bytes": "700471"
},
{
"name": "JavaScript",
"bytes": "2923916"
},
{
"name": "PowerShell",
"bytes": "6879"
},
{
"name": "Shell",
"bytes": "6131"
},
{
"name": "TypeScript",
"bytes": "49327"
},
{
"name": "XSLT",
"bytes": "123490"
}
],
"symlink_target": ""
} |
import styled from "styled-components"
export const Container = styled.div`
display: flex;
align-items: stretch;
flex-grow: 1;
background-color: whitesmoke;
`
export const AutoWidthContainer = styled.div`
display: flex;
align-items: stretch;
`
export const FooterItem = styled.div`
position: relative;
display: flex;
align-items: center;
padding-left: 8px;
color: #666;
font-size: 13px;
&:hover {
cursor: pointer;
color: #146f8c;
transition: color 0.2s;
}
&:last-child {
color: #146f8c;
}
`
export const rightIconContainer = styled.div`
overflow: hidden;
position: relative;
width: 20px;
height: 25px;
margin-left: 5px;
`
export const rightIcon = styled.div`
position: absolute;
width: 25px;
height: 25px;
transform: rotate(45deg);
right: 7px;
border: 1px solid #ddd;
`
| {
"content_hash": "e1794af259a7e9442db4252525b88b21",
"timestamp": "",
"source": "github",
"line_count": 47,
"max_line_length": 45,
"avg_line_length": 17.97872340425532,
"alnum_prop": 0.676923076923077,
"repo_name": "dobjs/dob-react-devtools",
"id": "0884be72ca768f01fe915ae9ab32f979bc32f3f7",
"size": "845",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/demo/pages/gaea-editor/plugins/crumbs/index.style.ts",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "TypeScript",
"bytes": "419980"
}
],
"symlink_target": ""
} |
package jodd.db.oom.tst;
import jodd.db.oom.meta.DbColumn;
import jodd.db.oom.meta.DbId;
import jodd.db.oom.meta.DbTable;
@DbTable
public class User {
@DbId
public long userId;
@DbColumn
public String name;
public int exp;
} | {
"content_hash": "6c26ae55774e78a0b6f26f7e851f98de",
"timestamp": "",
"source": "github",
"line_count": 16,
"max_line_length": 33,
"avg_line_length": 14.5625,
"alnum_prop": 0.7424892703862661,
"repo_name": "007slm/jodd",
"id": "074f0a87f4dfcaa2e5b30236a7344c37d270f4d7",
"size": "305",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "jodd-db/src/test/java/jodd/db/oom/tst/User.java",
"mode": "33188",
"license": "bsd-3-clause",
"language": [],
"symlink_target": ""
} |
My Common C# Snippets
=====================
###Strongly Typed Session State
Allows for using ASP.NET Session State with a strongly types class instead of having to cast the values from object.
###WebAPI HMAC Authorization
Provides the hooks for adding HMAC Authorization to WebAPI calls
| {
"content_hash": "4aeb64de58ee1f804d85cf0e66740d81",
"timestamp": "",
"source": "github",
"line_count": 9,
"max_line_length": 116,
"avg_line_length": 32.22222222222222,
"alnum_prop": 0.7413793103448276,
"repo_name": "JoeDoyle23/CSharpSnippets",
"id": "daf5a5e17c910e90cbf6c2b61f7865e80917a5f4",
"size": "290",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "README.md",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C#",
"bytes": "14868"
}
],
"symlink_target": ""
} |
module Hyrax
class CollectionThumbnailPathService < Hyrax::ThumbnailPathService
class << self
def default_image
ActionController::Base.helpers.image_path 'collection.png'
end
end
end
end
| {
"content_hash": "238297b6cc40c0bc502b4442e2e20254",
"timestamp": "",
"source": "github",
"line_count": 9,
"max_line_length": 68,
"avg_line_length": 24.333333333333332,
"alnum_prop": 0.7123287671232876,
"repo_name": "samvera/hyrax",
"id": "e74e85d8c154a46b21dce123213eccd5a123f7ee",
"size": "250",
"binary": false,
"copies": "1",
"ref": "refs/heads/main",
"path": "app/services/hyrax/collection_thumbnail_path_service.rb",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "3358"
},
{
"name": "CoffeeScript",
"bytes": "22059"
},
{
"name": "Dockerfile",
"bytes": "2827"
},
{
"name": "HTML",
"bytes": "534358"
},
{
"name": "JavaScript",
"bytes": "261946"
},
{
"name": "Mustache",
"bytes": "5792"
},
{
"name": "Ruby",
"bytes": "4548933"
},
{
"name": "SCSS",
"bytes": "61915"
},
{
"name": "Shell",
"bytes": "6425"
},
{
"name": "XSLT",
"bytes": "46036"
}
],
"symlink_target": ""
} |
extern "C" {
#include <ovsdb_wrapper.h>
};
#include <base/task.h>
#include <ovs_tor_agent/tor_agent_init.h>
#include <ovsdb_client.h>
#include <ovsdb_client_idl.h>
#include <ovsdb_client_session.h>
#include <physical_switch_ovsdb.h>
#include <ovsdb_types.h>
using OVSDB::OvsdbClient;
using OVSDB::OvsdbClientSession;
using OVSDB::PhysicalSwitchEntry;
using OVSDB::PhysicalSwitchTable;
PhysicalSwitchEntry::PhysicalSwitchEntry(PhysicalSwitchTable *table,
const std::string &name) : OvsdbEntry(table), name_(name),
tunnel_ip_() {
}
PhysicalSwitchEntry::~PhysicalSwitchEntry() {
}
Ip4Address &PhysicalSwitchEntry::tunnel_ip() {
return tunnel_ip_;
}
const std::string &PhysicalSwitchEntry::name() {
return name_;
}
void PhysicalSwitchEntry::set_tunnel_ip(std::string ip) {
boost::system::error_code ec;
tunnel_ip_ = Ip4Address::from_string(ip, ec);
}
bool PhysicalSwitchEntry::IsLess(const KSyncEntry &entry) const {
const PhysicalSwitchEntry &ps_entry =
static_cast<const PhysicalSwitchEntry&>(entry);
return (name_ < ps_entry.name_);
}
KSyncEntry *PhysicalSwitchEntry::UnresolvedReference() {
return NULL;
}
void PhysicalSwitchEntry::SendTrace(Trace event) const {
SandeshPhysicalSwitchInfo info;
if (event == ADD) {
info.set_op("Add");
} else {
info.set_op("Delete");
}
info.set_name(name_);
OVSDB_TRACE(PhysicalSwitch, info);
}
PhysicalSwitchTable::PhysicalSwitchTable(OvsdbClientIdl *idl) :
OvsdbObject(idl) {
idl->Register(OvsdbClientIdl::OVSDB_PHYSICAL_SWITCH,
boost::bind(&PhysicalSwitchTable::Notify, this, _1, _2));
}
PhysicalSwitchTable::~PhysicalSwitchTable() {
}
void PhysicalSwitchTable::Notify(OvsdbClientIdl::Op op,
struct ovsdb_idl_row *row) {
PhysicalSwitchEntry key(this, ovsdb_wrapper_physical_switch_name(row));
PhysicalSwitchEntry *entry =
static_cast<PhysicalSwitchEntry *>(FindActiveEntry(&key));
if (op == OvsdbClientIdl::OVSDB_DEL) {
if (entry != NULL) {
entry->SendTrace(PhysicalSwitchEntry::DEL);
Delete(entry);
}
} else if (op == OvsdbClientIdl::OVSDB_ADD) {
if (entry == NULL) {
entry = static_cast<PhysicalSwitchEntry *>(Create(&key));
entry->SendTrace(PhysicalSwitchEntry::ADD);
}
entry->set_tunnel_ip(ovsdb_wrapper_physical_switch_tunnel_ip(row));
} else {
assert(0);
}
}
KSyncEntry *PhysicalSwitchTable::Alloc(const KSyncEntry *key, uint32_t index) {
const PhysicalSwitchEntry *k_entry =
static_cast<const PhysicalSwitchEntry *>(key);
PhysicalSwitchEntry *entry = new PhysicalSwitchEntry(this, k_entry->name_);
return entry;
}
/////////////////////////////////////////////////////////////////////////////
// Sandesh routines
/////////////////////////////////////////////////////////////////////////////
class PhysicalSwitchSandeshTask : public Task {
public:
PhysicalSwitchSandeshTask(std::string resp_ctx) :
Task((TaskScheduler::GetInstance()->GetTaskId("Agent::KSync")), 0),
resp_(new OvsdbPhysicalSwitchResp()), resp_data_(resp_ctx) {
}
virtual ~PhysicalSwitchSandeshTask() {}
virtual bool Run() {
std::vector<OvsdbPhysicalSwitchEntry> pswitch;
TorAgentInit *init =
static_cast<TorAgentInit *>(Agent::GetInstance()->agent_init());
OvsdbClientSession *session = init->ovsdb_client()->next_session(NULL);
if (session->client_idl() != NULL) {
PhysicalSwitchTable *table =
session->client_idl()->physical_switch_table();
PhysicalSwitchEntry *entry =
static_cast<PhysicalSwitchEntry *>(table->Next(NULL));
while (entry != NULL) {
OvsdbPhysicalSwitchEntry pentry;
pentry.set_state(entry->StateString());
pentry.set_name(entry->name());
pentry.set_tunnel_ip(entry->tunnel_ip().to_string());
pswitch.push_back(pentry);
entry = static_cast<PhysicalSwitchEntry *>(table->Next(entry));
}
}
resp_->set_pswitch(pswitch);
SendResponse();
return true;
}
private:
void SendResponse() {
resp_->set_context(resp_data_);
resp_->set_more(false);
resp_->Response();
}
OvsdbPhysicalSwitchResp *resp_;
std::string resp_data_;
DISALLOW_COPY_AND_ASSIGN(PhysicalSwitchSandeshTask);
};
void OvsdbPhysicalSwitchReq::HandleRequest() const {
PhysicalSwitchSandeshTask *task = new PhysicalSwitchSandeshTask(context());
TaskScheduler *scheduler = TaskScheduler::GetInstance();
scheduler->Enqueue(task);
}
| {
"content_hash": "ffcb23c4efb687db5c47d86a5c9ab326",
"timestamp": "",
"source": "github",
"line_count": 151,
"max_line_length": 79,
"avg_line_length": 31.403973509933774,
"alnum_prop": 0.6303247574862927,
"repo_name": "cloudwatt/contrail-controller",
"id": "36b296276fe6ab081d5c3623d6c1b0a4a487acd3",
"size": "4814",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "src/vnsw/agent/ovs_tor_agent/ovsdb_client/physical_switch_ovsdb.cc",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "ApacheConf",
"bytes": "80579"
},
{
"name": "C",
"bytes": "44989"
},
{
"name": "C++",
"bytes": "14908777"
},
{
"name": "CSS",
"bytes": "531"
},
{
"name": "Java",
"bytes": "171966"
},
{
"name": "Lua",
"bytes": "8164"
},
{
"name": "Makefile",
"bytes": "12449"
},
{
"name": "Objective-C",
"bytes": "720"
},
{
"name": "Protocol Buffer",
"bytes": "1120"
},
{
"name": "Python",
"bytes": "3057429"
},
{
"name": "Shell",
"bytes": "54611"
},
{
"name": "Thrift",
"bytes": "40763"
}
],
"symlink_target": ""
} |
using System;
using System.IO;
namespace SQLiteXM
{
public class ProcessSQLStatements
{
private ProcessSQLStatements () {}
public static bool Parse (StreamReader sqlStatementAssets)
{
string sqlStatements = sqlStatementAssets.ReadToEnd ();
return Parse (sqlStatements);
}
public static bool Parse (string sqlStatements)
{
int searchOffset = 0;
while ( (searchOffset = getHeader (searchOffset, sqlStatements)) != -1 ) {}
return true;
}
private static int getHeader (int searchOffset, string sqlStatements)
{
int index = sqlStatements.IndexOf (Defines.openStatementDelimeter, searchOffset);
if (index != -1)
{
int sIndex = index+1;
index = sqlStatements.IndexOf (Defines.closeStatementDelimeter, sIndex);
if (index != -1)
{
if (sIndex == index)
throw new SxmException (ErrorMessages.error["missingSQLStatementHeader"]);
string header = sqlStatements.Substring (sIndex, index-sIndex).Trim();
index = parseHeader (header, index+1, sqlStatements);
}
else
throw new SxmException (ErrorMessages.error["invalidSQLStatementFile"]);
}
return index;
}
private static int parseHeader(string header, int index, string sqlStatements)
{
header = header.ToLower ();
switch (header)
{
case "table":
index = processTableStatements (index, sqlStatements);
break;
case "insert":
index = processInsertStatements (index, sqlStatements);
break;
case "alter":
index = processAlterStatements (index, sqlStatements);
break;
case "index":
index = processIndexStatements (index, sqlStatements);
break;
case "select":
case "update":
case "delete":
index = processStatement (index, header, sqlStatements);
break;
default:
throw new SxmException (new ErrorMessage("unknownSQLStatementHeader", header));
}
return index;
}
private static int processTableStatements(int index, string sqlStatements)
{
CommandReturn commandReturn = null;
string sqlStatement;
string dbName;
int synch;
do {
commandReturn = getCommand (index, sqlStatements);
index = commandReturn.index;
if (commandReturn.command.Length == 0) // Were finished processing the table statements.
break;
dbName = commandReturn.command;
commandReturn = getCommand (index, sqlStatements);
index = commandReturn.index;
if (commandReturn.command.Length == 0) // The table create statement cannot be empty.
{
throw new SxmException (new ErrorMessage("invalidSQLStatementDefinition", "TABLE"));
}
sqlStatement = commandReturn.command;
commandReturn = getCommand (index, sqlStatements);
index = commandReturn.index;
if (commandReturn.command.Length == 0) // The synch statement cannot be empty.
{
throw new SxmException (new ErrorMessage("invalidSQLStatementDefinition", "TABLE"));
}
synch = parseSynchCommand (commandReturn.command.ToLower ());
SqlStatements.addTableDefinition (dbName, sqlStatement, synch);
} while (true);
return index;
}
private static int processInsertStatements(int index, string sqlStatements)
{
CommandReturn commandReturn = null;
string sqlStatement;
string tableName;
string dbName;
do {
commandReturn = getCommand (index, sqlStatements);
index = commandReturn.index;
if (commandReturn.command.Length == 0) // Were finished processing the insert statements.
break;
dbName = commandReturn.command;
commandReturn = getCommand (index, sqlStatements);
index = commandReturn.index;
tableName = commandReturn.command;
commandReturn = getCommand (index, sqlStatements);
index = commandReturn.index;
if (commandReturn.command.Length == 0) // The SQL insert statement cannot be empty.
{
throw new SxmException (new ErrorMessage("invalidSQLStatementDefinition", "INSERT"));
}
sqlStatement = commandReturn.command;
SqlStatements.addInsertDefinition (dbName, tableName, sqlStatement);
} while (true);
return index;
}
private static int processAlterStatements(int index, string sqlStatements)
{
CommandReturn commandReturn = null;
string dbAndTableName;
string sqlStatement;
string columnName;
do {
commandReturn = getCommand (index, sqlStatements);
index = commandReturn.index;
if (commandReturn.command.Length == 0) // Were finished processing the alter statements.
break;
dbAndTableName = commandReturn.command;
commandReturn = getCommand (index, sqlStatements);
index = commandReturn.index;
columnName = commandReturn.command;
commandReturn = getCommand (index, sqlStatements);
index = commandReturn.index;
if (commandReturn.command.Length == 0) // The SQL insert statement cannot be empty.
{
throw new SxmException (new ErrorMessage("invalidSQLStatementDefinition", "ALTER"));
}
sqlStatement = commandReturn.command;
SqlStatements.addAlterDefinition (dbAndTableName, columnName, sqlStatement);
} while (true);
return index;
}
private static int processIndexStatements(int index, string sqlStatements)
{
CommandReturn commandReturn = null;
string dbAndTableName;
string sqlStatement;
string indexName;
do {
commandReturn = getCommand (index, sqlStatements);
index = commandReturn.index;
if (commandReturn.command.Length == 0) // Were finished processing the index statements.
break;
dbAndTableName = commandReturn.command;
commandReturn = getCommand (index, sqlStatements);
index = commandReturn.index;
indexName = commandReturn.command;
commandReturn = getCommand (index, sqlStatements);
index = commandReturn.index;
if (commandReturn.command.Length == 0) // The SQL insert statement cannot be empty.
{
throw new SxmException (new ErrorMessage("invalidSQLStatementDefinition", "INDEX"));
}
sqlStatement = commandReturn.command;
SqlStatements.addIndexDefinition (dbAndTableName, indexName, sqlStatement);
} while (true);
return index;
}
private static int processStatement(int index, string header, string sqlStatements)
{
CommandReturn commandReturn = null;
string sqlStatement;
string sqlName;
do {
commandReturn = getCommand (index, sqlStatements);
index = commandReturn.index;
if (commandReturn.command.Length == 0) // Were finished processing the select statements.
break;
sqlName = commandReturn.command;
commandReturn = getCommand (index, sqlStatements);
index = commandReturn.index;
if (commandReturn.command.Length == 0) // The SQL select statement cannot be empty.
{
throw new SxmException (new ErrorMessage("invalidSQLStatementDefinition", header));
}
sqlStatement = commandReturn.command;
if( header.Equals ("select") == true)
SqlStatements.addSelectDefinition (sqlName, sqlStatement);
if( header.Equals ("delete") == true)
SqlStatements.addDeleteDefinition (sqlName, sqlStatement);
if( header.Equals ("update") == true)
SqlStatements.addUpdateDefinition (sqlName, sqlStatement);
} while (true);
return index;
}
private static CommandReturn getCommand (int index, string sqlStatements)
{
CommandReturn commandReturn = new CommandReturn ();
index = sqlStatements.IndexOf (Defines.openStatementDelimeter, index);
if (index != -1)
{
int sIndex = index+1;
index = sqlStatements.IndexOf (Defines.closeStatementDelimeter, sIndex);
if (index != -1)
{
if (sIndex != index)
commandReturn.command = sqlStatements.Substring (sIndex, index - sIndex).Trim();
else
commandReturn.command = string.Empty;
commandReturn.index = index+1;
}
else
throw new SxmException (ErrorMessages.error["invalidSQLStatementFile"]);
}
else
throw new SxmException (ErrorMessages.error["invalidSQLStatementFile"]);
return commandReturn;
}
private static int parseSynchCommand (string synchCommand)
{
if (synchCommand.Equals ("synch") == true)
return Defines.CLOUD_SYNCH;
if (synchCommand.Equals ("no_synch") == true)
return Defines.NO_CLOUD_SYNCH;
if (synchCommand.Equals ("move") == true)
return Defines.CLOUD_MOVE;
throw new SxmException (new ErrorMessage("unknownSynchCommand", synchCommand));
}
class CommandReturn
{
public int index;
public string command;
public CommandReturn()
{
}
}
}
}
| {
"content_hash": "bdc172a374e8b641f54a20b58f20a85d",
"timestamp": "",
"source": "github",
"line_count": 296,
"max_line_length": 93,
"avg_line_length": 28.75,
"alnum_prop": 0.7024676850763807,
"repo_name": "HotRiot/SQLite.XM-Xamarin",
"id": "06459d9ac3a20e95dde27dcbffdf4e3689e3bd5f",
"size": "8512",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/ProcessSQLStatements.cs",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C#",
"bytes": "185170"
}
],
"symlink_target": ""
} |
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<!-- NewPage -->
<html lang="en">
<head>
<!-- Generated by javadoc (version 1.7.0_71) on Tue Aug 02 00:33:20 PDT 2016 -->
<title>E-Index</title>
<meta name="date" content="2016-08-02">
<link rel="stylesheet" type="text/css" href="../stylesheet.css" title="Style">
</head>
<body>
<script type="text/javascript"><!--
if (location.href.indexOf('is-external=true') == -1) {
parent.document.title="E-Index";
}
//-->
</script>
<noscript>
<div>JavaScript is disabled on your browser.</div>
</noscript>
<!-- ========= START OF TOP NAVBAR ======= -->
<div class="topNav"><a name="navbar_top">
<!-- -->
</a><a href="#skip-navbar_top" title="Skip navigation links"></a><a name="navbar_top_firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../overview-summary.html">Overview</a></li>
<li>Package</li>
<li>Class</li>
<li>Use</li>
<li><a href="../overview-tree.html">Tree</a></li>
<li><a href="../deprecated-list.html">Deprecated</a></li>
<li class="navBarCell1Rev">Index</li>
<li><a href="../help-doc.html">Help</a></li>
</ul>
</div>
<div class="subNav">
<ul class="navList">
<li><a href="index-3.html">Prev Letter</a></li>
<li><a href="index-5.html">Next Letter</a></li>
</ul>
<ul class="navList">
<li><a href="../index.html?index-filesindex-4.html" target="_top">Frames</a></li>
<li><a href="index-4.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_top">
<li><a href="../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_top");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
</div>
<a name="skip-navbar_top">
<!-- -->
</a></div>
<!-- ========= END OF TOP NAVBAR ========= -->
<div class="contentContainer"><a href="index-1.html">A</a> <a href="index-2.html">C</a> <a href="index-3.html">D</a> <a href="index-4.html">E</a> <a href="index-5.html">F</a> <a href="index-6.html">G</a> <a href="index-7.html">H</a> <a href="index-8.html">I</a> <a href="index-9.html">L</a> <a href="index-10.html">M</a> <a href="index-11.html">N</a> <a href="index-12.html">P</a> <a href="index-13.html">R</a> <a href="index-14.html">T</a> <a href="index-15.html">V</a> <a name="_E_">
<!-- -->
</a>
<h2 class="title">E</h2>
<dl>
<dt><a href="../edu/mit/mqtt/raspberrypi/package-summary.html">edu.mit.mqtt.raspberrypi</a> - package edu.mit.mqtt.raspberrypi</dt>
<dd> </dd>
<dt><a href="../edu/mit/mqtt/raspberrypi/model/device/package-summary.html">edu.mit.mqtt.raspberrypi.model.device</a> - package edu.mit.mqtt.raspberrypi.model.device</dt>
<dd> </dd>
<dt><a href="../edu/mit/mqtt/raspberrypi/model/messaging/package-summary.html">edu.mit.mqtt.raspberrypi.model.messaging</a> - package edu.mit.mqtt.raspberrypi.model.messaging</dt>
<dd> </dd>
<dt><span class="strong"><a href="../edu/mit/mqtt/raspberrypi/model/device/PinDirection.html#equals(java.lang.String)">equals(String)</a></span> - Method in enum edu.mit.mqtt.raspberrypi.model.device.<a href="../edu/mit/mqtt/raspberrypi/model/device/PinDirection.html" title="enum in edu.mit.mqtt.raspberrypi.model.device">PinDirection</a></dt>
<dd> </dd>
<dt><span class="strong"><a href="../edu/mit/mqtt/raspberrypi/model/device/PinProperty.html#equals(java.lang.String)">equals(String)</a></span> - Method in enum edu.mit.mqtt.raspberrypi.model.device.<a href="../edu/mit/mqtt/raspberrypi/model/device/PinProperty.html" title="enum in edu.mit.mqtt.raspberrypi.model.device">PinProperty</a></dt>
<dd> </dd>
<dt><span class="strong"><a href="../edu/mit/mqtt/raspberrypi/model/device/PinValue.html#equals(java.lang.String)">equals(String)</a></span> - Method in enum edu.mit.mqtt.raspberrypi.model.device.<a href="../edu/mit/mqtt/raspberrypi/model/device/PinValue.html" title="enum in edu.mit.mqtt.raspberrypi.model.device">PinValue</a></dt>
<dd> </dd>
<dt><span class="strong"><a href="../edu/mit/mqtt/raspberrypi/model/device/RaspberrryPiModel.html#equals(java.lang.String)">equals(String)</a></span> - Method in enum edu.mit.mqtt.raspberrypi.model.device.<a href="../edu/mit/mqtt/raspberrypi/model/device/RaspberrryPiModel.html" title="enum in edu.mit.mqtt.raspberrypi.model.device">RaspberrryPiModel</a></dt>
<dd> </dd>
<dt><span class="strong"><a href="../edu/mit/mqtt/raspberrypi/model/messaging/Action.html#equals(java.lang.String)">equals(String)</a></span> - Method in enum edu.mit.mqtt.raspberrypi.model.messaging.<a href="../edu/mit/mqtt/raspberrypi/model/messaging/Action.html" title="enum in edu.mit.mqtt.raspberrypi.model.messaging">Action</a></dt>
<dd> </dd>
<dt><span class="strong"><a href="../edu/mit/mqtt/raspberrypi/model/messaging/Topic.html#equals(java.lang.String)">equals(String)</a></span> - Method in enum edu.mit.mqtt.raspberrypi.model.messaging.<a href="../edu/mit/mqtt/raspberrypi/model/messaging/Topic.html" title="enum in edu.mit.mqtt.raspberrypi.model.messaging">Topic</a></dt>
<dd> </dd>
</dl>
<a href="index-1.html">A</a> <a href="index-2.html">C</a> <a href="index-3.html">D</a> <a href="index-4.html">E</a> <a href="index-5.html">F</a> <a href="index-6.html">G</a> <a href="index-7.html">H</a> <a href="index-8.html">I</a> <a href="index-9.html">L</a> <a href="index-10.html">M</a> <a href="index-11.html">N</a> <a href="index-12.html">P</a> <a href="index-13.html">R</a> <a href="index-14.html">T</a> <a href="index-15.html">V</a> </div>
<!-- ======= START OF BOTTOM NAVBAR ====== -->
<div class="bottomNav"><a name="navbar_bottom">
<!-- -->
</a><a href="#skip-navbar_bottom" title="Skip navigation links"></a><a name="navbar_bottom_firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../overview-summary.html">Overview</a></li>
<li>Package</li>
<li>Class</li>
<li>Use</li>
<li><a href="../overview-tree.html">Tree</a></li>
<li><a href="../deprecated-list.html">Deprecated</a></li>
<li class="navBarCell1Rev">Index</li>
<li><a href="../help-doc.html">Help</a></li>
</ul>
</div>
<div class="subNav">
<ul class="navList">
<li><a href="index-3.html">Prev Letter</a></li>
<li><a href="index-5.html">Next Letter</a></li>
</ul>
<ul class="navList">
<li><a href="../index.html?index-filesindex-4.html" target="_top">Frames</a></li>
<li><a href="index-4.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_bottom">
<li><a href="../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_bottom");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
</div>
<a name="skip-navbar_bottom">
<!-- -->
</a></div>
<!-- ======== END OF BOTTOM NAVBAR ======= -->
</body>
</html>
| {
"content_hash": "2ef2877d7645762c3e7d4015f883340e",
"timestamp": "",
"source": "github",
"line_count": 136,
"max_line_length": 560,
"avg_line_length": 52.61029411764706,
"alnum_prop": 0.6626135569531796,
"repo_name": "thilankam/thilankam.github.io",
"id": "c60d797972779716b7c6c2c59fcbc8dffd5e5127",
"size": "7155",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "gsoc16/raspberrypi-mqtt-messages/doc/index-files/index-4.html",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "85398"
},
{
"name": "HTML",
"bytes": "2090462"
},
{
"name": "JavaScript",
"bytes": "129467"
},
{
"name": "Less",
"bytes": "8610"
},
{
"name": "PHP",
"bytes": "1097"
}
],
"symlink_target": ""
} |
<?xml version="1.0" encoding="UTF-8"?>
<plugin xmlns="pluginSchema"
xmlns:gml="http://www.opengis.net/gml"
xmlns:ogc="http://www.opengis.net/ogc"
xmlns:xs="http://www.w3.org/2001/XMLSchema-instance"
xs:schemaLocation="pluginSchema /data/capabilities/validate/pluginSchema.xsd">
<name>Line End Point Covers Point</name>
<description>The point is covered by a line end point.</description>
<class>org.geotools.validation.spatial.PointCoveredByEndPointOfLineValidation</class>
</plugin>
| {
"content_hash": "15beb35fe26d2ff99e91b69dcda9f1dd",
"timestamp": "",
"source": "github",
"line_count": 10,
"max_line_length": 87,
"avg_line_length": 49,
"alnum_prop": 0.7693877551020408,
"repo_name": "mapfish/mapfish-print",
"id": "12e2ae6e3b3219ed35fa25b8da90517fd27f50dc",
"size": "490",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "examples/geoserver-data/plugIns/PointCoveredByEndPointOfLine.xml",
"mode": "33188",
"license": "bsd-2-clause",
"language": [
{
"name": "Batchfile",
"bytes": "2618"
},
{
"name": "CSS",
"bytes": "5588"
},
{
"name": "Dockerfile",
"bytes": "4383"
},
{
"name": "HTML",
"bytes": "17494"
},
{
"name": "Java",
"bytes": "2393608"
},
{
"name": "JavaScript",
"bytes": "495445"
},
{
"name": "Makefile",
"bytes": "1322"
},
{
"name": "Python",
"bytes": "3253"
},
{
"name": "Scheme",
"bytes": "44064"
},
{
"name": "Shell",
"bytes": "7356"
},
{
"name": "XSLT",
"bytes": "1877"
}
],
"symlink_target": ""
} |
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Runtime.Loader;
using Microsoft.AspNetCore.Components.WebAssembly.Services;
using Microsoft.JSInterop;
namespace Microsoft.AspNetCore.Components.WebAssembly.Hosting;
[UnconditionalSuppressMessage("ReflectionAnalysis", "IL2026", Justification = "This type loads resx files. We don't expect it's dependencies to be trimmed in the ordinary case.")]
#pragma warning disable CA1852 // Seal internal types
internal class WebAssemblyCultureProvider
#pragma warning restore CA1852 // Seal internal types
{
internal const string GetSatelliteAssemblies = "window.Blazor._internal.getSatelliteAssemblies";
internal const string ReadSatelliteAssemblies = "window.Blazor._internal.readSatelliteAssemblies";
private readonly IJSUnmarshalledRuntime _invoker;
// For unit testing.
internal WebAssemblyCultureProvider(IJSUnmarshalledRuntime invoker, CultureInfo initialCulture, CultureInfo initialUICulture)
{
_invoker = invoker;
InitialCulture = initialCulture;
InitialUICulture = initialUICulture;
}
public static WebAssemblyCultureProvider? Instance { get; private set; }
public CultureInfo InitialCulture { get; }
public CultureInfo InitialUICulture { get; }
internal static void Initialize()
{
Instance = new WebAssemblyCultureProvider(
DefaultWebAssemblyJSRuntime.Instance,
initialCulture: CultureInfo.CurrentCulture,
initialUICulture: CultureInfo.CurrentUICulture);
}
public void ThrowIfCultureChangeIsUnsupported()
{
// With ICU sharding enabled, bootstrapping WebAssembly will download a ICU shard based on the browser language.
// If the application author was to change the culture as part of their Program.MainAsync, we might have
// incomplete icu data for their culture. We would like to flag this as an error and notify the author to
// use the combined icu data file instead.
//
// The Initialize method is invoked as one of the first steps bootstrapping the app within WebAssemblyHostBuilder.CreateDefault.
// It allows us to capture the initial .NET culture that is configured based on the browser language.
// The current method is invoked as part of WebAssemblyHost.RunAsync i.e. after user code in Program.MainAsync has run
// thus allows us to detect if the culture was changed by user code.
if (Environment.GetEnvironmentVariable("__BLAZOR_SHARDED_ICU") == "1" &&
((!CultureInfo.CurrentCulture.Name.Equals(InitialCulture.Name, StringComparison.Ordinal) ||
!CultureInfo.CurrentUICulture.Name.Equals(InitialUICulture.Name, StringComparison.Ordinal))))
{
throw new InvalidOperationException("Blazor detected a change in the application's culture that is not supported with the current project configuration. " +
"To change culture dynamically during startup, set <BlazorWebAssemblyLoadAllGlobalizationData>true</BlazorWebAssemblyLoadAllGlobalizationData> in the application's project file.");
}
}
public virtual async ValueTask LoadCurrentCultureResourcesAsync()
{
var culturesToLoad = GetCultures(CultureInfo.CurrentCulture);
if (culturesToLoad.Count == 0)
{
return;
}
// Now that we know the cultures we care about, let WebAssemblyResourceLoader (in JavaScript) load these
// assemblies. We effectively want to resovle a Task<byte[][]> but there is no way to express this
// using interop. We'll instead do this in two parts:
// getSatelliteAssemblies resolves when all satellite assemblies to be loaded in .NET are fetched and available in memory.
#pragma warning disable CS0618 // Type or member is obsolete
var count = (int)await _invoker.InvokeUnmarshalled<string[], object?, object?, Task<object>>(
GetSatelliteAssemblies,
culturesToLoad.ToArray(),
null,
null);
if (count == 0)
{
return;
}
// readSatelliteAssemblies resolves the assembly bytes
var assemblies = _invoker.InvokeUnmarshalled<object?, object?, object?, object[]>(
ReadSatelliteAssemblies,
null,
null,
null);
#pragma warning restore CS0618 // Type or member is obsolete
for (var i = 0; i < assemblies.Length; i++)
{
using var stream = new MemoryStream((byte[])assemblies[i]);
AssemblyLoadContext.Default.LoadFromStream(stream);
}
}
internal static List<string> GetCultures(CultureInfo cultureInfo)
{
var culturesToLoad = new List<string>();
// Once WASM is ready, we have to use .NET's assembly loading to load additional assemblies.
// First calculate all possible cultures that the application might want to load. We do this by
// starting from the current culture and walking up the graph of parents.
// At the end of the the walk, we'll have a list of culture names that look like
// [ "fr-FR", "fr" ]
while (cultureInfo != null && cultureInfo != CultureInfo.InvariantCulture)
{
culturesToLoad.Add(cultureInfo.Name);
if (cultureInfo.Parent == cultureInfo)
{
break;
}
cultureInfo = cultureInfo.Parent;
}
return culturesToLoad;
}
}
| {
"content_hash": "54af17cc9ca0180aea3a50545e5fbc92",
"timestamp": "",
"source": "github",
"line_count": 124,
"max_line_length": 196,
"avg_line_length": 44.75,
"alnum_prop": 0.6893133897999639,
"repo_name": "aspnet/AspNetCore",
"id": "331cbb8e7ab69a5237cbaa46f242378bfa116956",
"size": "5687",
"binary": false,
"copies": "1",
"ref": "refs/heads/darc-main-3ce916a7-9d9b-4849-8f14-6703adcb3cb2",
"path": "src/Components/WebAssembly/WebAssembly/src/Hosting/WebAssemblyCultureProvider.cs",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "ASP",
"bytes": "109"
},
{
"name": "Batchfile",
"bytes": "19526"
},
{
"name": "C",
"bytes": "213916"
},
{
"name": "C#",
"bytes": "47455169"
},
{
"name": "C++",
"bytes": "1900454"
},
{
"name": "CMake",
"bytes": "7955"
},
{
"name": "CSS",
"bytes": "62326"
},
{
"name": "Dockerfile",
"bytes": "3584"
},
{
"name": "F#",
"bytes": "7982"
},
{
"name": "Groovy",
"bytes": "1529"
},
{
"name": "HTML",
"bytes": "1130653"
},
{
"name": "Java",
"bytes": "297552"
},
{
"name": "JavaScript",
"bytes": "2726829"
},
{
"name": "Lua",
"bytes": "4904"
},
{
"name": "Makefile",
"bytes": "220"
},
{
"name": "Objective-C",
"bytes": "222"
},
{
"name": "PowerShell",
"bytes": "241706"
},
{
"name": "Python",
"bytes": "19476"
},
{
"name": "Roff",
"bytes": "6044"
},
{
"name": "Shell",
"bytes": "142293"
},
{
"name": "Smalltalk",
"bytes": "3"
},
{
"name": "TypeScript",
"bytes": "797435"
}
],
"symlink_target": ""
} |
package com.goodow.realtime.json.impl;
import com.goodow.realtime.json.JsonArray;
import com.goodow.realtime.json.JsonElement;
import com.goodow.realtime.json.JsonType;
import java.util.List;
import java.util.Map;
public abstract class JreJsonElement implements JsonElement {
private static final long serialVersionUID = 3661435771481171596L;
protected boolean needsCopy;
@Override
public boolean isArray() {
return this instanceof JsonArray;
}
@Override
public boolean isObject() {
return this instanceof JreJsonObject;
}
public abstract <T> Object toNative();
@Override
public String toString() {
return toJsonString();
}
protected JsonType getType(Object value) {
if (value instanceof Map) {
return JsonType.OBJECT;
} else if (value instanceof List) {
return JsonType.ARRAY;
} else if (value instanceof String) {
return JsonType.STRING;
} else if (value instanceof Number) {
return JsonType.NUMBER;
} else if (value instanceof Boolean) {
return JsonType.BOOLEAN;
} else if (value == null) {
return JsonType.NULL;
}
throw new IllegalArgumentException("Invalid JSON type: " + value.getClass().getName());
}
} | {
"content_hash": "bc6af1194881bc3861703a0bd9b2371f",
"timestamp": "",
"source": "github",
"line_count": 49,
"max_line_length": 91,
"avg_line_length": 25.040816326530614,
"alnum_prop": 0.7082314588427058,
"repo_name": "goodow/realtime-json",
"id": "f7e9d0363a2f87ea0553aa9166d910a05716ee3a",
"size": "1813",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/main/java/com/goodow/realtime/json/impl/JreJsonElement.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Java",
"bytes": "114193"
},
{
"name": "Makefile",
"bytes": "1435"
}
],
"symlink_target": ""
} |
// Copyright (c) 2014-present, Facebook, Inc. All rights reserved.
//
// You are hereby granted a non-exclusive, worldwide, royalty-free license to use,
// copy, modify, and distribute this software in source code or binary form for use
// in connection with the web services and APIs provided by Facebook.
//
// As with any software that integrates with the Facebook platform, your use of
// this software is subject to the Facebook Developer Principles and Policies
// [http://developers.facebook.com/policy/]. This copyright 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 "TargetConditionals.h"
#if !TARGET_OS_TV
#import <UIKit/UIKit.h>
@class FBSDKProfile;
NS_ASSUME_NONNULL_BEGIN
/**
FBSDKProfilePictureMode enum
Defines the aspect ratio mode for the source image of the profile picture.
*/
typedef NS_ENUM(NSUInteger, FBSDKProfilePictureMode)
{
/**
A square cropped version of the image will be included in the view.
*/
FBSDKProfilePictureModeSquare,
/**
The original picture's aspect ratio will be used for the source image in the view.
*/
FBSDKProfilePictureModeNormal,
/**
The original picture's aspect ratio will be used for the source image in the view.
*/
FBSDKProfilePictureModeAlbum,
/**
The original picture's aspect ratio will be used for the source image in the view.
*/
FBSDKProfilePictureModeSmall,
/**
The original picture's aspect ratio will be used for the source image in the view.
*/
FBSDKProfilePictureModeLarge,
} NS_SWIFT_NAME(Profile.PictureMode);
/**
A view to display a profile picture.
*/
NS_SWIFT_NAME(FBProfilePictureView)
@interface FBSDKProfilePictureView : UIView
/**
Create a new instance of `FBSDKProfilePictureView`.
- Parameter frame: Frame rectangle for the view.
- Parameter profile: Optional profile to display a picture for.
*/
- (instancetype)initWithFrame:(CGRect)frame
profile:(FBSDKProfile * _Nullable)profile;
/**
Create a new instance of `FBSDKProfilePictureView`.
- Parameter profile: Optional profile to display a picture for.
*/
- (instancetype)initWithProfile:(FBSDKProfile * _Nullable)profile;
/**
The mode for the receiver to determine the aspect ratio of the source image.
*/
@property (nonatomic, assign) FBSDKProfilePictureMode pictureMode;
/**
The profile ID to show the picture for.
*/
@property (nonatomic, copy) NSString *profileID;
/**
Explicitly marks the receiver as needing to update the image.
This method is called whenever any properties that affect the source image are modified, but this can also
be used to trigger a manual update of the image if it needs to be re-downloaded.
*/
- (void)setNeedsImageUpdate;
@end
NS_ASSUME_NONNULL_END
#endif
| {
"content_hash": "fee7baf31252dae7ec3dc4e1434ea489",
"timestamp": "",
"source": "github",
"line_count": 101,
"max_line_length": 107,
"avg_line_length": 32.2970297029703,
"alnum_prop": 0.7489270386266095,
"repo_name": "getsocial-im/getsocial-ios-sdk",
"id": "cbef2ce9fe8f504f49f999156f03eac401657bf9",
"size": "3262",
"binary": false,
"copies": "4",
"ref": "refs/heads/master",
"path": "example/GetSocialDemo/Vendor/FBSDKCoreKit.framework/Headers/FBSDKProfilePictureView.h",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "C",
"bytes": "708"
},
{
"name": "Objective-C",
"bytes": "391746"
},
{
"name": "Shell",
"bytes": "2988"
},
{
"name": "Swift",
"bytes": "346792"
}
],
"symlink_target": ""
} |
/* TEMPLATE GENERATED TESTCASE FILE
Filename: CWE457_Use_of_Uninitialized_Variable__twointsclass_array_declare_partial_init_15.cpp
Label Definition File: CWE457_Use_of_Uninitialized_Variable__twointsclass_array.label.xml
Template File: sources-sinks-15.tmpl.cpp
*/
/*
* @description
* CWE: 457 Use of Uninitialized Variable
* BadSource: partial_init Initialize part, but not all of the array
* GoodSource: Initialize data
* Sinks: use
* GoodSink: Initialize then use data
* BadSink : Use data
* Flow Variant: 15 Control flow: switch(6) and switch(7)
* */
#include "std_testcase.h"
namespace CWE457_Use_of_Uninitialized_Variable__twointsclass_array_declare_partial_init_15
{
#ifndef OMITBAD
void bad()
{
TwoIntsClass * data;
TwoIntsClass dataUninitArray[10];
data = dataUninitArray;
switch(6)
{
case 6:
/* POTENTIAL FLAW: Partially initialize data */
for(int i=0; i<(10/2); i++)
{
data[i].intOne = i;
data[i].intTwo = i;
}
break;
default:
/* INCIDENTAL: CWE 561 Dead Code, the code below will never run */
printLine("Benign, fixed string");
break;
}
switch(7)
{
case 7:
/* POTENTIAL FLAW: Use data without initializing it */
for(int i=0; i<10; i++)
{
printIntLine(data[i].intOne);
printIntLine(data[i].intTwo);
}
break;
default:
/* INCIDENTAL: CWE 561 Dead Code, the code below will never run */
printLine("Benign, fixed string");
break;
}
}
#endif /* OMITBAD */
#ifndef OMITGOOD
/* goodB2G1() - use badsource and goodsink by changing the second switch to switch(8) */
static void goodB2G1()
{
TwoIntsClass * data;
TwoIntsClass dataUninitArray[10];
data = dataUninitArray;
switch(6)
{
case 6:
/* POTENTIAL FLAW: Partially initialize data */
for(int i=0; i<(10/2); i++)
{
data[i].intOne = i;
data[i].intTwo = i;
}
break;
default:
/* INCIDENTAL: CWE 561 Dead Code, the code below will never run */
printLine("Benign, fixed string");
break;
}
switch(8)
{
case 7:
/* INCIDENTAL: CWE 561 Dead Code, the code below will never run */
printLine("Benign, fixed string");
break;
default:
/* FIX: Ensure data is initialized before use */
for(int i=0; i<10; i++)
{
data[i].intOne = i;
data[i].intTwo = i;
}
for(int i=0; i<10; i++)
{
printIntLine(data[i].intOne);
printIntLine(data[i].intTwo);
}
break;
}
}
/* goodB2G2() - use badsource and goodsink by reversing the blocks in the second switch */
static void goodB2G2()
{
TwoIntsClass * data;
TwoIntsClass dataUninitArray[10];
data = dataUninitArray;
switch(6)
{
case 6:
/* POTENTIAL FLAW: Partially initialize data */
for(int i=0; i<(10/2); i++)
{
data[i].intOne = i;
data[i].intTwo = i;
}
break;
default:
/* INCIDENTAL: CWE 561 Dead Code, the code below will never run */
printLine("Benign, fixed string");
break;
}
switch(7)
{
case 7:
/* FIX: Ensure data is initialized before use */
for(int i=0; i<10; i++)
{
data[i].intOne = i;
data[i].intTwo = i;
}
for(int i=0; i<10; i++)
{
printIntLine(data[i].intOne);
printIntLine(data[i].intTwo);
}
break;
default:
/* INCIDENTAL: CWE 561 Dead Code, the code below will never run */
printLine("Benign, fixed string");
break;
}
}
/* goodG2B1() - use goodsource and badsink by changing the first switch to switch(5) */
static void goodG2B1()
{
TwoIntsClass * data;
TwoIntsClass dataUninitArray[10];
data = dataUninitArray;
switch(5)
{
case 6:
/* INCIDENTAL: CWE 561 Dead Code, the code below will never run */
printLine("Benign, fixed string");
break;
default:
/* FIX: Completely initialize data */
for(int i=0; i<10; i++)
{
data[i].intOne = i;
data[i].intTwo = i;
}
break;
}
switch(7)
{
case 7:
/* POTENTIAL FLAW: Use data without initializing it */
for(int i=0; i<10; i++)
{
printIntLine(data[i].intOne);
printIntLine(data[i].intTwo);
}
break;
default:
/* INCIDENTAL: CWE 561 Dead Code, the code below will never run */
printLine("Benign, fixed string");
break;
}
}
/* goodG2B2() - use goodsource and badsink by reversing the blocks in the first switch */
static void goodG2B2()
{
TwoIntsClass * data;
TwoIntsClass dataUninitArray[10];
data = dataUninitArray;
switch(6)
{
case 6:
/* FIX: Completely initialize data */
for(int i=0; i<10; i++)
{
data[i].intOne = i;
data[i].intTwo = i;
}
break;
default:
/* INCIDENTAL: CWE 561 Dead Code, the code below will never run */
printLine("Benign, fixed string");
break;
}
switch(7)
{
case 7:
/* POTENTIAL FLAW: Use data without initializing it */
for(int i=0; i<10; i++)
{
printIntLine(data[i].intOne);
printIntLine(data[i].intTwo);
}
break;
default:
/* INCIDENTAL: CWE 561 Dead Code, the code below will never run */
printLine("Benign, fixed string");
break;
}
}
void good()
{
goodB2G1();
goodB2G2();
goodG2B1();
goodG2B2();
}
#endif /* OMITGOOD */
} /* close namespace */
/* Below is the main(). It is only used when building this testcase on
its own for testing or for building a binary to use in testing binary
analysis tools. It is not used when compiling all the testcases as one
application, which is how source code analysis tools are tested. */
#ifdef INCLUDEMAIN
using namespace CWE457_Use_of_Uninitialized_Variable__twointsclass_array_declare_partial_init_15; /* so that we can use good and bad easily */
int main(int argc, char * argv[])
{
/* seed randomness */
srand( (unsigned)time(NULL) );
#ifndef OMITGOOD
printLine("Calling good()...");
good();
printLine("Finished good()");
#endif /* OMITGOOD */
#ifndef OMITBAD
printLine("Calling bad()...");
bad();
printLine("Finished bad()");
#endif /* OMITBAD */
return 0;
}
#endif
| {
"content_hash": "083d521d3439ee4b2a4f76eccdd7339e",
"timestamp": "",
"source": "github",
"line_count": 265,
"max_line_length": 142,
"avg_line_length": 26.237735849056605,
"alnum_prop": 0.5437940457356537,
"repo_name": "JianpingZeng/xcc",
"id": "b776ff6ca5a5743c6e2f14fbd5788067f40d085c",
"size": "6953",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "xcc/test/juliet/testcases/CWE457_Use_of_Uninitialized_Variable/s01/CWE457_Use_of_Uninitialized_Variable__twointsclass_array_declare_partial_init_15.cpp",
"mode": "33188",
"license": "bsd-3-clause",
"language": [],
"symlink_target": ""
} |
layout: page
title: Hakkında
permalink: /about/
feature-img: "img/sample_feature_img_2.png"
---
Merhaba, Ben Mehmet. Şuan özel bir şirkette Yazılım Mühendisi olarak çalışıyorum. Blogumda yazılım ve teknoloji dünyasına ait tecrübelerimi paylaşıyorum.
| {
"content_hash": "9d634975f16b3fe47c28cd4a076ccfe4",
"timestamp": "",
"source": "github",
"line_count": 7,
"max_line_length": 153,
"avg_line_length": 35.857142857142854,
"alnum_prop": 0.8007968127490039,
"repo_name": "pasali/pasali.github.io",
"id": "7c3cad172f1498c3057a5d979de024694e599dbc",
"size": "273",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "about.md",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "5618"
},
{
"name": "HTML",
"bytes": "9895"
},
{
"name": "Ruby",
"bytes": "644"
}
],
"symlink_target": ""
} |
import json
import requests
from django.conf import settings
from django.core.mail import EmailMultiAlternatives
from django.utils.html import strip_tags
from django.utils.module_loading import import_string
from pypushwoosh import constants
from pypushwoosh.client import PushwooshClient
from yak.settings import yak_settings
def submit_to_pushwoosh(request_data):
url = 'https://cp.pushwoosh.com/json/1.3/createMessage'
response = requests.post(url, data=request_data, headers=PushwooshClient.headers)
return response.json()
def send_pushwoosh_notification(receiver, message, deep_link=None):
notification_data = {
'content': message,
'send_date': constants.SEND_DATE_NOW,
'devices': [token.token for token in receiver.pushwoosh_tokens.all()],
'ios_badges': '+1'
}
if deep_link is not None:
notification_data['minimize_link'] = 0
notification_data['link'] = deep_link
request = {'request': {
'notifications': [notification_data],
'auth': yak_settings.PUSHWOOSH_AUTH_TOKEN,
'application': yak_settings.PUSHWOOSH_APP_CODE
}}
request_data = json.dumps(request)
return submit_to_pushwoosh(request_data)
def send_push_notification(receiver, message, deep_link=None):
notification_handler = import_string(yak_settings.PUSH_NOTIFICATION_HANDLER)
return notification_handler(receiver, message, deep_link=None)
def send_email_notification(receiver, message, reply_to=None):
headers = {}
if reply_to:
headers['Reply-To'] = reply_to
text_content = strip_tags(message)
msg = EmailMultiAlternatives(yak_settings.EMAIL_NOTIFICATION_SUBJECT, text_content, settings.DEFAULT_FROM_EMAIL,
[receiver.email], headers=headers)
msg.attach_alternative(message, "text/html")
msg.send()
| {
"content_hash": "c4396bf96664835f0540aee4fc4f54a6",
"timestamp": "",
"source": "github",
"line_count": 57,
"max_line_length": 116,
"avg_line_length": 32.68421052631579,
"alnum_prop": 0.7037037037037037,
"repo_name": "yeti/YAK-server",
"id": "1fbf7547013cf68f170f1624c248bbf2f7de2e56",
"size": "1863",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "yak/rest_notifications/utils.py",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "HTML",
"bytes": "2288"
},
{
"name": "Python",
"bytes": "177485"
}
],
"symlink_target": ""
} |
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
tools:context="liulx.blogreader.MainListActivity" >
<item
android:id="@+id/action_settings"
android:orderInCategory="100"
android:title="@string/action_settings"
app:showAsAction="never"/>
</menu>
| {
"content_hash": "8e92552cd3b2809ca9cfb69be8b19f8b",
"timestamp": "",
"source": "github",
"line_count": 12,
"max_line_length": 64,
"avg_line_length": 34.25,
"alnum_prop": 0.6763990267639902,
"repo_name": "liulixiang1988/android_demo",
"id": "b099c68af4b787af41cae314bc1be22fda0319bf",
"size": "411",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "BlogReader/res/menu/main_list.xml",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "340"
},
{
"name": "HTML",
"bytes": "77336"
},
{
"name": "Java",
"bytes": "1973589"
}
],
"symlink_target": ""
} |
#pragma once
// Dependencies
#include "../detail/setup.hpp"
#include "../detail/qualifier.hpp"
#include "../detail/_vectorize.hpp"
#include "../vector_relational.hpp"
#include "../common.hpp"
#include <limits>
#if GLM_MESSAGES == GLM_ENABLE && !defined(GLM_EXT_INCLUDED)
# pragma message("GLM: GLM_GTC_integer extension included")
#endif
namespace glm
{
/// @addtogroup gtc_round
/// @{
/// Return true if the value is a power of two number.
///
/// @see gtc_round
template<typename genIUType>
GLM_FUNC_DECL bool isPowerOfTwo(genIUType v);
/// Return true if the value is a power of two number.
///
/// @tparam L Integer between 1 and 4 included that qualify the dimension of the vector
/// @tparam T Floating-point or integer scalar types
/// @tparam Q Value from qualifier enum
///
/// @see gtc_round
template<length_t L, typename T, qualifier Q>
GLM_FUNC_DECL vec<L, bool, Q> isPowerOfTwo(vec<L, T, Q> const& v);
/// Return the power of two number which value is just higher the input value,
/// round up to a power of two.
///
/// @see gtc_round
template<typename genIUType>
GLM_FUNC_DECL genIUType ceilPowerOfTwo(genIUType v);
/// Return the power of two number which value is just higher the input value,
/// round up to a power of two.
///
/// @tparam L Integer between 1 and 4 included that qualify the dimension of the vector
/// @tparam T Floating-point or integer scalar types
/// @tparam Q Value from qualifier enum
///
/// @see gtc_round
template<length_t L, typename T, qualifier Q>
GLM_FUNC_DECL vec<L, T, Q> ceilPowerOfTwo(vec<L, T, Q> const& v);
/// Return the power of two number which value is just lower the input value,
/// round down to a power of two.
///
/// @see gtc_round
template<typename genIUType>
GLM_FUNC_DECL genIUType floorPowerOfTwo(genIUType v);
/// Return the power of two number which value is just lower the input value,
/// round down to a power of two.
///
/// @tparam L Integer between 1 and 4 included that qualify the dimension of the vector
/// @tparam T Floating-point or integer scalar types
/// @tparam Q Value from qualifier enum
///
/// @see gtc_round
template<length_t L, typename T, qualifier Q>
GLM_FUNC_DECL vec<L, T, Q> floorPowerOfTwo(vec<L, T, Q> const& v);
/// Return the power of two number which value is the closet to the input value.
///
/// @see gtc_round
template<typename genIUType>
GLM_FUNC_DECL genIUType roundPowerOfTwo(genIUType v);
/// Return the power of two number which value is the closet to the input value.
///
/// @tparam L Integer between 1 and 4 included that qualify the dimension of the vector
/// @tparam T Floating-point or integer scalar types
/// @tparam Q Value from qualifier enum
///
/// @see gtc_round
template<length_t L, typename T, qualifier Q>
GLM_FUNC_DECL vec<L, T, Q> roundPowerOfTwo(vec<L, T, Q> const& v);
/// Return true if the 'Value' is a multiple of 'Multiple'.
///
/// @see gtc_round
template<typename genIUType>
GLM_FUNC_DECL bool isMultiple(genIUType v, genIUType Multiple);
/// Return true if the 'Value' is a multiple of 'Multiple'.
///
/// @tparam L Integer between 1 and 4 included that qualify the dimension of the vector
/// @tparam T Floating-point or integer scalar types
/// @tparam Q Value from qualifier enum
///
/// @see gtc_round
template<length_t L, typename T, qualifier Q>
GLM_FUNC_DECL vec<L, bool, Q> isMultiple(vec<L, T, Q> const& v, T Multiple);
/// Return true if the 'Value' is a multiple of 'Multiple'.
///
/// @tparam L Integer between 1 and 4 included that qualify the dimension of the vector
/// @tparam T Floating-point or integer scalar types
/// @tparam Q Value from qualifier enum
///
/// @see gtc_round
template<length_t L, typename T, qualifier Q>
GLM_FUNC_DECL vec<L, bool, Q> isMultiple(vec<L, T, Q> const& v, vec<L, T, Q> const& Multiple);
/// Higher multiple number of Source.
///
/// @tparam genType Floating-point or integer scalar or vector types.
///
/// @param v Source value to which is applied the function
/// @param Multiple Must be a null or positive value
///
/// @see gtc_round
template<typename genType>
GLM_FUNC_DECL genType ceilMultiple(genType v, genType Multiple);
/// Higher multiple number of Source.
///
/// @tparam L Integer between 1 and 4 included that qualify the dimension of the vector
/// @tparam T Floating-point or integer scalar types
/// @tparam Q Value from qualifier enum
///
/// @param v Source values to which is applied the function
/// @param Multiple Must be a null or positive value
///
/// @see gtc_round
template<length_t L, typename T, qualifier Q>
GLM_FUNC_DECL vec<L, T, Q> ceilMultiple(vec<L, T, Q> const& v, vec<L, T, Q> const& Multiple);
/// Lower multiple number of Source.
///
/// @tparam genType Floating-point or integer scalar or vector types.
///
/// @param v Source value to which is applied the function
/// @param Multiple Must be a null or positive value
///
/// @see gtc_round
template<typename genType>
GLM_FUNC_DECL genType floorMultiple(genType v, genType Multiple);
/// Lower multiple number of Source.
///
/// @tparam L Integer between 1 and 4 included that qualify the dimension of the vector
/// @tparam T Floating-point or integer scalar types
/// @tparam Q Value from qualifier enum
///
/// @param v Source values to which is applied the function
/// @param Multiple Must be a null or positive value
///
/// @see gtc_round
template<length_t L, typename T, qualifier Q>
GLM_FUNC_DECL vec<L, T, Q> floorMultiple(vec<L, T, Q> const& v, vec<L, T, Q> const& Multiple);
/// Lower multiple number of Source.
///
/// @tparam genType Floating-point or integer scalar or vector types.
///
/// @param v Source value to which is applied the function
/// @param Multiple Must be a null or positive value
///
/// @see gtc_round
template<typename genType>
GLM_FUNC_DECL genType roundMultiple(genType v, genType Multiple);
/// Lower multiple number of Source.
///
/// @tparam L Integer between 1 and 4 included that qualify the dimension of the vector
/// @tparam T Floating-point or integer scalar types
/// @tparam Q Value from qualifier enum
///
/// @param v Source values to which is applied the function
/// @param Multiple Must be a null or positive value
///
/// @see gtc_round
template<length_t L, typename T, qualifier Q>
GLM_FUNC_DECL vec<L, T, Q> roundMultiple(vec<L, T, Q> const& v, vec<L, T, Q> const& Multiple);
/// @}
} //namespace glm
#include "round.inl"
| {
"content_hash": "52a1a83f16ae73820b63f7a0676b5e8b",
"timestamp": "",
"source": "github",
"line_count": 190,
"max_line_length": 95,
"avg_line_length": 35.410526315789475,
"alnum_prop": 0.6767241379310345,
"repo_name": "kumakoko/KumaGL",
"id": "db2141da10f6a5117ed51d2d1b161a00a75670af",
"size": "7029",
"binary": false,
"copies": "8",
"ref": "refs/heads/master",
"path": "third_lib/glm/0.9.9.5/include/glm/gtc/round.hpp",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Assembly",
"bytes": "763"
},
{
"name": "Batchfile",
"bytes": "1610"
},
{
"name": "C",
"bytes": "10066221"
},
{
"name": "C++",
"bytes": "122279207"
},
{
"name": "CMake",
"bytes": "32438"
},
{
"name": "CSS",
"bytes": "97842"
},
{
"name": "GLSL",
"bytes": "288465"
},
{
"name": "HTML",
"bytes": "28003047"
},
{
"name": "JavaScript",
"bytes": "512828"
},
{
"name": "M4",
"bytes": "10000"
},
{
"name": "Makefile",
"bytes": "12990"
},
{
"name": "Objective-C",
"bytes": "100340"
},
{
"name": "Objective-C++",
"bytes": "2520"
},
{
"name": "Perl",
"bytes": "6275"
},
{
"name": "Roff",
"bytes": "332021"
},
{
"name": "Ruby",
"bytes": "9186"
},
{
"name": "Shell",
"bytes": "37826"
}
],
"symlink_target": ""
} |
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>myBlog</title>
</head>
<body>
<div id="app"></div>
<script src="assets/bundle.js"></script>
<link rel="stylesheet" type="text/css" href="stylesheets/style.css">
</body>
</html> | {
"content_hash": "d7074039fd629aee863b75601d0cd46b",
"timestamp": "",
"source": "github",
"line_count": 12,
"max_line_length": 69,
"avg_line_length": 20.916666666666668,
"alnum_prop": 0.649402390438247,
"repo_name": "cqupt-yifanwu/blog",
"id": "869a9506b4f17fc70b8b90b6212e21fa63baf7a6",
"size": "251",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "public/index.html",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "3789"
},
{
"name": "HTML",
"bytes": "556"
},
{
"name": "JavaScript",
"bytes": "1451970"
}
],
"symlink_target": ""
} |
module Facts
module Windows
class Kernelmajversion
FACT_NAME = 'kernelmajversion'
def call_the_resolver
fact_value = Facter::Resolvers::Kernel.resolve(:kernelmajorversion)
Facter::ResolvedFact.new(FACT_NAME, fact_value)
end
end
end
end
| {
"content_hash": "906b1037fc8acbec73b669679c1945a5",
"timestamp": "",
"source": "github",
"line_count": 13,
"max_line_length": 75,
"avg_line_length": 21.846153846153847,
"alnum_prop": 0.676056338028169,
"repo_name": "puppetlabs/facter",
"id": "e007370b760dbaaea5c242c85d006029751b2845",
"size": "315",
"binary": false,
"copies": "1",
"ref": "refs/heads/main",
"path": "lib/facter/facts/windows/kernelmajversion.rb",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "HTML",
"bytes": "3940"
},
{
"name": "Ruby",
"bytes": "2565509"
},
{
"name": "Shell",
"bytes": "1467"
}
],
"symlink_target": ""
} |
require_relative 'connection'
module Publisher
class Request
include Connection
HTTP_METHODS = [:get, :head, :post, :put, :delete, :patch]
METHODS_WITH_BODIES = [:post, :put, :patch]
attr_reader :action, :path, :params, :options, :headers
def initialize(action, path, params = {}, options = {}, headers = {})
@action = action.to_sym
%W{path params options headers}.each do |field|
instance_variable_set("@#{field}", instance_eval(field))
end
end
def call
raise Publisher::ArgumentError unless HTTP_METHODS.include?(action)
response = connection.send(action) do |request|
request.url path
request.headers.merge!(headers)
case action
when *(HTTP_METHODS - METHODS_WITH_BODIES)
request.params = params if params.present?
when *METHODS_WITH_BODIES
request.body = options unless options.blank?
end
end
response.body
end
end
end
| {
"content_hash": "7fea0f09ebbeca824299ddd58dc0a664",
"timestamp": "",
"source": "github",
"line_count": 39,
"max_line_length": 73,
"avg_line_length": 25.435897435897434,
"alnum_prop": 0.6229838709677419,
"repo_name": "anhuiliujun/publisher",
"id": "1b31579f76c9150919db449c4906ac0a4b729ad9",
"size": "992",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "lib/publisher/request.rb",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Ruby",
"bytes": "4858"
}
],
"symlink_target": ""
} |
/* 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 org.activiti.engine.impl.jobexecutor;
import java.util.List;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.RejectedExecutionException;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* <p>This is a simple implementation of the {@link JobExecutor} using self-managed
* threads for performing background work.</p>
*
* <p>This implementation uses a {@link ThreadPoolExecutor} backed by a queue to which
* work is submitted.</p>
*
* <p><em>NOTE: use this class in environments in which self-management of threads
* is permitted. Consider using a different thread-management strategy in
* J(2)EE-Environments.</em></p>
*
* @author Daniel Meyer
*/
public class DefaultJobExecutor extends JobExecutor {
private static Logger log = LoggerFactory.getLogger(DefaultJobExecutor.class);
protected int queueSize = 3;
protected int corePoolSize = 3;
protected int maxPoolSize = 10;
protected long keepAliveTime = 0L;
protected BlockingQueue<Runnable> threadPoolQueue;
protected ThreadPoolExecutor threadPoolExecutor;
protected void startExecutingJobs() {
if (threadPoolQueue==null) {
threadPoolQueue = new ArrayBlockingQueue<Runnable>(queueSize);
}
if (threadPoolExecutor==null) {
threadPoolExecutor = new ThreadPoolExecutor(corePoolSize, maxPoolSize, keepAliveTime, TimeUnit.MILLISECONDS, threadPoolQueue);
threadPoolExecutor.setRejectedExecutionHandler(new ThreadPoolExecutor.AbortPolicy());
}
startJobAcquisitionThread();
}
protected void stopExecutingJobs() {
stopJobAcquisitionThread();
// Ask the thread pool to finish and exit
threadPoolExecutor.shutdown();
// Waits for 1 minute to finish all currently executing jobs
try {
if(!threadPoolExecutor.awaitTermination(60L, TimeUnit.SECONDS)) {
log.warn("Timeout during shutdown of job executor. "
+ "The current running jobs could not end within 60 seconds after shutdown operation.");
}
} catch (InterruptedException e) {
log.warn("Interrupted while shutting down the job executor. ", e);
}
threadPoolExecutor = null;
}
public void executeJobs(List<String> jobIds) {
try {
threadPoolExecutor.execute(new ExecuteJobsRunnable(this, jobIds));
} catch (RejectedExecutionException e) {
rejectedJobsHandler.jobsRejected(this, jobIds);
}
}
// getters and setters //////////////////////////////////////////////////////
public int getQueueSize() {
return queueSize;
}
public void setQueueSize(int queueSize) {
this.queueSize = queueSize;
}
public int getCorePoolSize() {
return corePoolSize;
}
public void setCorePoolSize(int corePoolSize) {
this.corePoolSize = corePoolSize;
}
public int getMaxPoolSize() {
return maxPoolSize;
}
public void setMaxPoolSize(int maxPoolSize) {
this.maxPoolSize = maxPoolSize;
}
public long getKeepAliveTime() {
return keepAliveTime;
}
public void setKeepAliveTime(long keepAliveTime) {
this.keepAliveTime = keepAliveTime;
}
public BlockingQueue<Runnable> getThreadPoolQueue() {
return threadPoolQueue;
}
public void setThreadPoolQueue(BlockingQueue<Runnable> threadPoolQueue) {
this.threadPoolQueue = threadPoolQueue;
}
public ThreadPoolExecutor getThreadPoolExecutor() {
return threadPoolExecutor;
}
public void setThreadPoolExecutor(ThreadPoolExecutor threadPoolExecutor) {
this.threadPoolExecutor = threadPoolExecutor;
}
}
| {
"content_hash": "0d42c2194326dc6b8a6cdcf4234b80b9",
"timestamp": "",
"source": "github",
"line_count": 140,
"max_line_length": 138,
"avg_line_length": 31.678571428571427,
"alnum_prop": 0.6953776775648253,
"repo_name": "ahwxl/deep",
"id": "9ca58eb2a17b35c9480343e4822210e1cfd7a00c",
"size": "4435",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/main/java/org/activiti/engine/impl/jobexecutor/DefaultJobExecutor.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "446380"
},
{
"name": "FreeMarker",
"bytes": "707"
},
{
"name": "Groovy",
"bytes": "3438"
},
{
"name": "HTML",
"bytes": "360993"
},
{
"name": "Java",
"bytes": "4440916"
},
{
"name": "JavaScript",
"bytes": "1740074"
},
{
"name": "PLSQL",
"bytes": "1141"
},
{
"name": "PLpgSQL",
"bytes": "2584"
}
],
"symlink_target": ""
} |
FROM balenalib/etcher-pro-fedora:31-run
ENV NODE_VERSION 15.10.0
ENV YARN_VERSION 1.22.4
RUN for key in \
6A010C5166006599AA17F08146C2130DFD2497F5 \
; do \
gpg --keyserver pgp.mit.edu --recv-keys "$key" || \
gpg --keyserver keyserver.pgp.com --recv-keys "$key" || \
gpg --keyserver ha.pool.sks-keyservers.net --recv-keys "$key" ; \
done \
&& curl -SLO "http://nodejs.org/dist/v$NODE_VERSION/node-v$NODE_VERSION-linux-arm64.tar.gz" \
&& echo "a9f8c807ec31ed24fe6e0b2d002ce2d1b9f20b7e23a0efe10679331a44b30dba node-v$NODE_VERSION-linux-arm64.tar.gz" | sha256sum -c - \
&& tar -xzf "node-v$NODE_VERSION-linux-arm64.tar.gz" -C /usr/local --strip-components=1 \
&& rm "node-v$NODE_VERSION-linux-arm64.tar.gz" \
&& curl -fSLO --compressed "https://yarnpkg.com/downloads/$YARN_VERSION/yarn-v$YARN_VERSION.tar.gz" \
&& curl -fSLO --compressed "https://yarnpkg.com/downloads/$YARN_VERSION/yarn-v$YARN_VERSION.tar.gz.asc" \
&& gpg --batch --verify yarn-v$YARN_VERSION.tar.gz.asc yarn-v$YARN_VERSION.tar.gz \
&& mkdir -p /opt/yarn \
&& tar -xzf yarn-v$YARN_VERSION.tar.gz -C /opt/yarn --strip-components=1 \
&& ln -s /opt/yarn/bin/yarn /usr/local/bin/yarn \
&& ln -s /opt/yarn/bin/yarn /usr/local/bin/yarnpkg \
&& rm yarn-v$YARN_VERSION.tar.gz.asc yarn-v$YARN_VERSION.tar.gz \
&& npm config set unsafe-perm true -g --unsafe-perm \
&& rm -rf /tmp/*
CMD ["echo","'No CMD command was set in Dockerfile! Details about CMD command could be found in Dockerfile Guide section in our Docs. Here's the link: https://balena.io/docs"]
RUN curl -SLO "https://raw.githubusercontent.com/balena-io-library/base-images/8accad6af708fca7271c5c65f18a86782e19f877/scripts/assets/tests/test-stack@node.sh" \
&& echo "Running test-stack@node" \
&& chmod +x test-stack@node.sh \
&& bash test-stack@node.sh \
&& rm -rf test-stack@node.sh
RUN [ ! -d /.balena/messages ] && mkdir -p /.balena/messages; echo $'Here are a few details about this Docker image (For more information please visit https://www.balena.io/docs/reference/base-images/base-images/): \nArchitecture: ARM v8 \nOS: Fedora 31 \nVariant: run variant \nDefault variable(s): UDEV=off \nThe following software stack is preinstalled: \nNode.js v15.10.0, Yarn v1.22.4 \nExtra features: \n- Easy way to install packages with `install_packages <package-name>` command \n- Run anywhere with cross-build feature (for ARM only) \n- Keep the container idling with `balena-idle` command \n- Show base image details with `balena-info` command' > /.balena/messages/image-info
RUN echo $'#!/bin/sh.real\nbalena-info\nrm -f /bin/sh\ncp /bin/sh.real /bin/sh\n/bin/sh "$@"' > /bin/sh-shim \
&& chmod +x /bin/sh-shim \
&& cp /bin/sh /bin/sh.real \
&& mv /bin/sh-shim /bin/sh | {
"content_hash": "c89ead062f0d89146b8cba95985f1c5a",
"timestamp": "",
"source": "github",
"line_count": 41,
"max_line_length": 689,
"avg_line_length": 66.53658536585365,
"alnum_prop": 0.7078445747800587,
"repo_name": "nghiant2710/base-images",
"id": "b850e58b17cd6b6c51cde53a8f503a64dbb59277",
"size": "2749",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "balena-base-images/node/etcher-pro/fedora/31/15.10.0/run/Dockerfile",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Dockerfile",
"bytes": "144558581"
},
{
"name": "JavaScript",
"bytes": "16316"
},
{
"name": "Shell",
"bytes": "368690"
}
],
"symlink_target": ""
} |
ACCEPTED
#### According to
International Plant Names Index
#### Published in
null
#### Original name
null
### Remarks
null | {
"content_hash": "7868c12e1437d5484e8973fe8668570c",
"timestamp": "",
"source": "github",
"line_count": 13,
"max_line_length": 31,
"avg_line_length": 9.692307692307692,
"alnum_prop": 0.7063492063492064,
"repo_name": "mdoering/backbone",
"id": "e3fe00b8e1c20869461b9e6bfb7d2ab8dcd630b2",
"size": "189",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "life/Plantae/Magnoliophyta/Magnoliopsida/Fabales/Fabaceae/Dalbergia/Dalbergia johorensis/README.md",
"mode": "33188",
"license": "apache-2.0",
"language": [],
"symlink_target": ""
} |
<?php
namespace FSi\Bundle\AdminBundle\DataGrid\Extension\Admin\ColumnTypeExtension;
use FSi\Bundle\AdminBundle\Admin\Manager;
use FSi\Bundle\AdminBundle\Exception\RuntimeException;
use FSi\Component\DataGrid\Column\ColumnAbstractTypeExtension;
use FSi\Component\DataGrid\Column\ColumnTypeInterface;
use FSi\Component\DataGrid\Column\HeaderViewInterface;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\HttpFoundation\RequestStack;
use Symfony\Component\OptionsResolver\Options;
use Symfony\Component\OptionsResolver\OptionsResolver;
use Symfony\Component\Routing\RouterInterface;
class BatchActionExtension extends ColumnAbstractTypeExtension
{
/**
* @var \FSi\Bundle\AdminBundle\Admin\Manager
*/
protected $manager;
/**
* @var \Symfony\Component\Routing\RouterInterface
*/
protected $router;
/**
* @var \Symfony\Component\HttpFoundation\RequestStack
*/
protected $requestStack;
/**
* @var \Symfony\Component\Form\FormBuilderInterface
*/
protected $formBuilder;
/**
* @var \Symfony\Component\OptionsResolver\OptionsResolverInterface
*/
protected $actionOptionsResolver;
/**
* @param \Symfony\Component\Form\FormBuilderInterface $formBuilder
*/
public function __construct(
Manager $manager,
RequestStack $requestStack,
RouterInterface $router,
FormBuilderInterface $formBuilder
) {
$this->manager = $manager;
$this->requestStack = $requestStack;
$this->router = $router;
$this->formBuilder = $formBuilder;
$this->initActionOptions();
}
/**
* @inheritdoc
*/
public function getExtendedColumnTypes()
{
return array('batch');
}
/**
* @inheritdoc
*/
public function initOptions(ColumnTypeInterface $column)
{
$column->getOptionsResolver()->setDefaults(array('actions' => array()));
$column->getOptionsResolver()->setAllowedTypes(array(
'actions' => array('array', 'null')
));
}
public function buildHeaderView(ColumnTypeInterface $column, HeaderViewInterface $view)
{
$this->buildBatchForm(
$this->buildBatchActions($column)
);
$view->setAttribute('batch_form', $this->formBuilder->getForm()->createView());
}
private function initActionOptions()
{
$this->actionOptionsResolver = new OptionsResolver();
$this->actionOptionsResolver->setRequired(array(
'route_name'
));
$this->actionOptionsResolver->setOptional(array(
'element'
));
$self = $this;
$this->actionOptionsResolver->setDefaults(array(
'route_name' => function(Options $options) use ($self) {
return $self->getDefaultRouteName($options);
},
'additional_parameters' => array(),
'label' => null
));
$this->actionOptionsResolver->setNormalizers(array(
'additional_parameters' => function(Options $options, $value) use ($self) {
return $self->normalizeAdditionalParameters($options, $value);
},
));
$this->actionOptionsResolver->setAllowedTypes(array(
'element' => 'string',
'route_name' => 'string',
'additional_parameters' => 'array',
'label' => array('string', 'null')
));
}
/**
* @param \FSi\Component\DataGrid\Column\ColumnTypeInterface $column
* @return array
*/
private function buildBatchActions(ColumnTypeInterface $column)
{
$batchActions = array('crud.list.batch.empty_choice');
foreach ($column->getOption('actions') as $name => $action) {
$actionOptions = $this->actionOptionsResolver->resolve($action);
$batchActions[$this->getBatchActionUrl($actionOptions)] =
isset($actionOptions['label']) ? $actionOptions['label'] : $name;
}
return $batchActions;
}
/**
* @param array $actionOptions
* @return string
*/
private function getBatchActionUrl(array $actionOptions)
{
return $this->router->generate(
$actionOptions['route_name'],
$actionOptions['additional_parameters']
);
}
/**
* @param array $batchActions
*/
private function buildBatchForm(array $batchActions)
{
if (count($batchActions) > 1) {
$this->formBuilder->add('action', 'choice', array(
'choices' => $batchActions,
'translation_domain' => 'FSiAdminBundle'
));
$this->formBuilder->add('submit', 'submit', array(
'label' => 'crud.list.batch.confirm',
'translation_domain' => 'FSiAdminBundle'
));
}
}
/**
* @param \Symfony\Component\OptionsResolver\Options $options
* @return null|string
*/
private function getDefaultRouteName(Options $options)
{
if ($options->has('element')) {
$this->validateElementFromOptions($options);
return $this->getElementFromOption($options)->getRoute();
} else {
return null;
}
}
/**
* @param \Symfony\Component\OptionsResolver\Options $options
* @param array $additionalParameters
* @return array
*/
private function normalizeAdditionalParameters(Options $options, array $additionalParameters)
{
if ($options->has('element')) {
$this->validateElementFromOptions($options);
$additionalParameters = $this->mergeAdditionalParametersWithElementFromOptions(
$options,
$additionalParameters
);
}
return $this->mergeAdditionalParametersWithRedirectUri($additionalParameters);
}
/**
* @param \Symfony\Component\OptionsResolver\Options $options
*/
private function validateElementFromOptions(Options $options)
{
if (!$this->manager->hasElement($options->get('element'))) {
throw new RuntimeException(sprintf(
'Unknown element "%s" specified in batch action',
$options->get('element')
));
}
}
/**
* @param \Symfony\Component\OptionsResolver\Options $options
* @param array $additionalParameters
* @return array
*/
private function mergeAdditionalParametersWithElementFromOptions(Options $options, array $additionalParameters)
{
$additionalParameters = array_merge(
array('element' => $this->getElementFromOption($options)->getId()),
$this->getElementFromOption($options)->getRouteParameters(),
$additionalParameters
);
return $additionalParameters;
}
/**
* @param \Symfony\Component\OptionsResolver\Options $options
* @return \FSi\Bundle\AdminBundle\Admin\ElementInterface
*/
private function getElementFromOption(Options $options)
{
return $this->manager->getElement($options->get('element'));
}
/**
* @param array $additionalParameters
* @return mixed
*/
private function mergeAdditionalParametersWithRedirectUri(array $additionalParameters)
{
if ($this->getMasterRequestQuery()->has('redirect_uri')) {
$additionalParameters['redirect_uri'] = $this->getMasterRequestQuery()->get('redirect_uri');
}
return $additionalParameters;
}
/**
* @return \Symfony\Component\HttpFoundation\ParameterBag
*/
private function getMasterRequestQuery()
{
return $this->requestStack->getMasterRequest()->query;
}
}
| {
"content_hash": "58030f5d965bad84f539edb97075ecef",
"timestamp": "",
"source": "github",
"line_count": 255,
"max_line_length": 115,
"avg_line_length": 30.55686274509804,
"alnum_prop": 0.6152464065708418,
"repo_name": "rn0/admin-bundle",
"id": "3fd5d57c24be23058a25f22e28e6537e7fa50395",
"size": "7792",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "DataGrid/Extension/Admin/ColumnTypeExtension/BatchActionExtension.php",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "PHP",
"bytes": "416526"
},
{
"name": "Puppet",
"bytes": "3923"
},
{
"name": "Ruby",
"bytes": "993"
},
{
"name": "Shell",
"bytes": "2413"
}
],
"symlink_target": ""
} |
package com.example.chengqi.mycoderepo.hardware;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import com.example.chengqi.mycoderepo.R;
public class HWBatteryActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_hwbattery);
}
}
| {
"content_hash": "9fdac8bd6fe1910b741a2fbba0482784",
"timestamp": "",
"source": "github",
"line_count": 15,
"max_line_length": 58,
"avg_line_length": 26.933333333333334,
"alnum_prop": 0.7747524752475248,
"repo_name": "firstbytegithub/MyCodeRepo",
"id": "9c891285415c5e399e1587d851fbddd6bc3bb47b",
"size": "404",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "app/src/main/java/com/example/chengqi/mycoderepo/hardware/HWBatteryActivity.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Java",
"bytes": "348525"
}
],
"symlink_target": ""
} |
About
=====
.. image:: https://badge.fury.io/py/pyclipper.svg
:target: https://badge.fury.io/py/pyclipper
.. image:: https://travis-ci.org/fonttools/pyclipper.svg?branch=master
:target: https://travis-ci.org/fonttools/pyclipper
.. image:: https://ci.appveyor.com/api/projects/status/kahji42bem2ttkvj/branch/master?svg=true
:target: https://ci.appveyor.com/project/fonttools/pyclipper/branch/master
Pyclipper is a Cython wrapper exposing public functions and classes of
the C++ translation of the `Angus Johnson's Clipper library (ver.
6.4.2) <http://www.angusj.com/delphi/clipper.php>`__.
Pyclipper releases were tested with Python 2.7 and 3.4 on Linux (Ubuntu
14.04, x64) and Windows (8.1, x64).
Source code is available on
`GitHub <https://github.com/fonttools/pyclipper>`__. The package is published on
`PyPI <https://pypi.python.org/pypi/pyclipper>`__.
About Clipper
-------------
Clipper - an open source freeware library for clipping and
offsetting lines and polygons.
The Clipper library performs line & polygon clipping -
intersection, union, difference & exclusive-or, and line &
polygon offsetting. The library is based on Vatti's clipping
algorithm.
\ `Angus Johnson's Clipper
library <http://www.angusj.com/delphi/clipper.php>`__\
Install
=======
Dependencies
------------
Cython dependency is optional. Cpp sources generated with Cython are
available in releases.
Note on using the ``setup.py``:
``setup.py`` operates in 2 modes that are based on the presence of the
``dev`` file in the root of the project.
- When ``dev`` is **present**, Cython will be used to compile the ``.pyx``
sources. This is the *development mode* (as you get it in the git
repository).
- When ``dev`` is **absent**, C/C++ compiler will be used to compile the
``.cpp`` sources (that were prepared in in the development mode).
This is the distribution mode (as you get it on PyPI).
This way the package can be used without or with an incompatible version
of Cython.
The idea comes from `Matt Shannon's bandmat
library <https://github.com/MattShannon/bandmat>`__.
From PyPI
---------
Cython not required.
::
pip install pyclipper
From source
-----------
Cython required.
Clone the repository:
::
git clone git@github.com:fonttools/pyclipper.git
Install:
::
python setup.py install
After every modification of ``.pyx`` files compile with Cython:
::
python setup.py build_ext --inplace
Clippers' preprocessor directives
---------------------------------
Clipper can be compiled with the following preprocessor directives: ``use_int32``, ``use_xyz``, ``use_lines`` and ``use_deprecated``.
Among these the ``use_int32`` and ``use_lines`` can be used with Pyclipper.
- ``use_int32`` - when enabled 32bit ints are used instead of 64bit ints. This improve performance but coordinate values are limited to the range +/- 46340. In Pyclipper this directive is **disabled** by default.
- ``use_lines`` - enables line clipping. Adds a very minor cost to performance. In Pyclipper this directive is **enabled** by default (since version 0.9.2b0).
In case you would want to change these settings, clone this repository and change the ``define_macros`` collection (``setup.py``, pyclipper extension definition). Add a set like ``('use_int32', 1)`` to enable the directive, or remove the set to disable it. After that you need to rebuild the package.
How to use
==========
This wrapper library tries to follow naming conventions of the original
library.
- ``ClipperLib`` namespace is represented by the ``pyclipper`` module,
- classes ``Clipper`` and ``ClipperOffset`` ->
``Pyclipper`` and ``PyclipperOffset``,
- when Clipper is overloading functions with different number of
parameters or different types (eg. ``Clipper.Execute``, one function
fills a list of paths the other PolyTree) that becomes
``Pyclipper.Execute`` and ``Pyclipper.Execute2``.
Basic clipping example (based on `Angus Johnson's Clipper
library <http://www.angusj.com/delphi/clipper.php>`__):
.. code:: python
import pyclipper
subj = (
((180, 200), (260, 200), (260, 150), (180, 150)),
((215, 160), (230, 190), (200, 190))
)
clip = ((190, 210), (240, 210), (240, 130), (190, 130))
pc = pyclipper.Pyclipper()
pc.AddPath(clip, pyclipper.PT_CLIP, True)
pc.AddPaths(subj, pyclipper.PT_SUBJECT, True)
solution = pc.Execute(pyclipper.CT_INTERSECTION, pyclipper.PFT_EVENODD, pyclipper.PFT_EVENODD)
# solution (a list of paths): [[[240, 200], [190, 200], [190, 150], [240, 150]], [[200, 190], [230, 190], [215, 160]]]
Basic offset example:
.. code:: python
import pyclipper
subj = ((180, 200), (260, 200), (260, 150), (180, 150))
pco = pyclipper.PyclipperOffset()
pco.AddPath(subj, pyclipper.JT_ROUND, pyclipper.ET_CLOSEDPOLYGON)
solution = pco.Execute(-7.0)
# solution (a list of paths): [[[253, 193], [187, 193], [187, 157], [253, 157]]]
The Clipper library uses integers instead of floating point values to
preserve numerical robustness. If you need to scale coordinates of your polygons, this library provides helper functions ``scale_to_clipper()`` and ``scale_from_clipper()`` to achieve that.
Migrating from Pyclipper ``0.9.3b0``
------------------------------------
In previous version of Pyclipper (``0.9.3b0``) polygons could be automatically scaled using the ``SCALING_FACTOR`` variable. This was removed in version ``1.0.0`` due to inexact conversions related to floating point operations. This way the library now provides the original numerical robustness of the base library.
The ``SCALING_FACTOR`` removal **breaks backward compatibility**.
For an explanation and help with migration, see https://github.com/fonttools/pyclipper/wiki/Deprecating-SCALING_FACTOR.
Authors
=======
- The Clipper library is written by `Angus
Johnson <http://www.angusj.com/delphi/clipper.php>`__,
- This wrapper was initially written by `Maxime
Chalton <https://sites.google.com/site/maxelsbackyard/home/pyclipper>`__,
- Adaptions to make it work with version 5 written by `Lukas
Treyer <http://www.lukastreyer.com>`__,
- Adaptions to make it work with version 6.2.1 and PyPI package written by `Gregor Ratajc <http://www.gregorratajc.com>`__,
- ``SCALING_FACTOR`` removal and additions to documentation by Michael Schwarz (@Feuermurmel),
- Bug fix `sympy.Zero` is not a collection by Jamie Bull (@jamiebull1),
- Travis CI and Appveyor CI integration for continuous builds of wheel packages by Cosimo Lupo (@anthrotype).
The package is maintained by Cosimo Lupo (`@anthrotype <https://github.com/anthrotype>`__).
License
=======
- Pyclipper is available under `MIT
license <http://opensource.org/licenses/MIT>`__.
- The core Clipper library is available under `Boost Software
License <http://www.boost.org/LICENSE_1_0.txt>`__. Freeware for both
open source and commercial applications.
Changelog
=========
1.1.0
-------
- Updated embedded Clipper library to version 6.4.2.
1.0.6
-------
- Added support for Python 3.6.
1.0.3
-------
- added Travis CI and Appveyor CI to build wheel packages (thanks to @anthrotype)
1.0.2
-------
- bug fix: `sympy.Zero` recognized as a collection (thanks to @jamiebull1)
1.0.0
-------
- **(breaks backwards compatibility)** removes SCALING_FACTOR (thanks to @Feuermurmel)
0.9.3b0
-------
- Applied SCALING_FACTOR to the relevant function parameters and class properties
- Refactored tests
0.9.2b1
-------
- bug fix: Fix setting of the PyPolyNode.IsHole property
0.9.2b0
-------
- enable preprocessor directive ``use_lines`` by default,
- bug fix: PyPolyNode.Contour that is now one path and not a list of paths as it was previously.
| {
"content_hash": "465bd1d8c37a2dee2d05beb5c3ba7822",
"timestamp": "",
"source": "github",
"line_count": 234,
"max_line_length": 316,
"avg_line_length": 33.636752136752136,
"alnum_prop": 0.6906365137847795,
"repo_name": "greginvm/pyclipper",
"id": "712c9f9e336bf6c3ce9ee543d61fe61e93638978",
"size": "7871",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "README.rst",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Batchfile",
"bytes": "3454"
},
{
"name": "C++",
"bytes": "157757"
},
{
"name": "Python",
"bytes": "52168"
},
{
"name": "Shell",
"bytes": "471"
}
],
"symlink_target": ""
} |
package com.mycompany.scalcium.names
import org.junit.Test
import org.junit.Assert
class NameFinderTest {
val sentences = List(
"Pierre Vinken, 61 years old, will join the board as a nonexecutive director Nov. 29.",
"Mr. Vinken is chairman of Elsevier N.V., the Dutch publishing group based at Amsterdam.",
"Rudolph Agnew , 55 years old and former chairman of Consolidated Gold Fields PLC, was named a director of this British industrial conglomerate."
)
@Test
def testOpenNLPNameFinder(): Unit = {
val nf = NameFinder.getNameFinder("opennlp")
val names = nf.find(sentences)
prettyPrint("OpenNLP", sentences, names)
Assert.assertEquals(3, names.size)
Assert.assertEquals(1, names(0).size)
Assert.assertEquals("PERSON", names(0)(0)._1)
Assert.assertEquals(0, names(0)(0)._2)
Assert.assertEquals(13, names(0)(0)._3)
Assert.assertEquals("Pierre Vinken",
sentences(0).substring(names(0)(0)._2,
names(0)(0)._3))
}
@Test
def testStanfordNameFinder(): Unit = {
val nf = NameFinder.getNameFinder("stanford")
val names = nf.find(sentences)
prettyPrint("Stanford", sentences, names)
Assert.assertEquals(3, names.size)
Assert.assertEquals(3, names(0).size)
Assert.assertEquals("PERSON", names(0)(0)._1)
Assert.assertEquals(0, names(0)(0)._2)
Assert.assertEquals(13, names(0)(0)._3)
Assert.assertEquals("Pierre Vinken",
sentences(0).substring(names(0)(0)._2,
names(0)(0)._3))
}
def prettyPrint(nername: String,
sentences: List[String],
names: List[List[(String,Int,Int)]]): Unit = {
Console.println("==== " + nername + " ====")
sentences.zip(names).foreach(sn => {
Console.println(sn._1)
sn._2.foreach(n =>
Console.println(" (" + n._2 + "," + n._3 +
"): " + sn._1.substring(n._2, n._3) +
" / " + n._1))
})
}
} | {
"content_hash": "50f464a05d88f1dd0e5b34af41b87265",
"timestamp": "",
"source": "github",
"line_count": 56,
"max_line_length": 149,
"avg_line_length": 34.107142857142854,
"alnum_prop": 0.6329842931937173,
"repo_name": "sujitpal/scalcium",
"id": "002c1e2c8884b357dbffb9e31a43f17445310e2a",
"size": "1910",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/test/scala/com/mycompany/scalcium/names/NameFinderTest.scala",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Python",
"bytes": "1664"
},
{
"name": "Scala",
"bytes": "247251"
}
],
"symlink_target": ""
} |
Tried out some techniques mentioned in the blog using Pandas and ARIMA
https://www.analyticsvidhya.com/blog/2016/02/time-series-forecasting-codes-python/
(Complete guide to create a Time Series Forecast (with Codes in Python))
| {
"content_hash": "2172b19d86cc676968bf9c8a6e49f377",
"timestamp": "",
"source": "github",
"line_count": 5,
"max_line_length": 82,
"avg_line_length": 45.8,
"alnum_prop": 0.8034934497816594,
"repo_name": "AMFIRNAS/TimeSeriesAnalysis-Pandas",
"id": "6c8150c198baa79c76fda54ae6396345485fe027",
"size": "257",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "README.md",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Jupyter Notebook",
"bytes": "1465433"
}
],
"symlink_target": ""
} |
<?php
/* AuthBundle:Default:index.html.twig */
class __TwigTemplate_4e30ae5f6c6a46a8d82114219bb0111a extends Twig_Template
{
public function __construct(Twig_Environment $env)
{
parent::__construct($env);
$this->parent = false;
$this->blocks = array(
);
}
protected function doDisplay(array $context, array $blocks = array())
{
// line 1
echo "Hell ";
echo twig_escape_filter($this->env, (isset($context["name"]) ? $context["name"] : $this->getContext($context, "name")), "html", null, true);
echo "!";
}
public function getTemplateName()
{
return "AuthBundle:Default:index.html.twig";
}
public function isTraitable()
{
return false;
}
public function getDebugInfo()
{
return array ( 19 => 1,);
}
}
| {
"content_hash": "b64322b34c0b0eb1372883dc4ff05148",
"timestamp": "",
"source": "github",
"line_count": 38,
"max_line_length": 148,
"avg_line_length": 22.5,
"alnum_prop": 0.5766081871345029,
"repo_name": "dayAlone/Rvisor",
"id": "50e3cbfcc569ad84b2c4545e37bc01f5e60253a3",
"size": "855",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "app/cache/prod/twig/4e/30/ae5f6c6a46a8d82114219bb0111a.php",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "279603"
},
{
"name": "JavaScript",
"bytes": "421996"
},
{
"name": "PHP",
"bytes": "385293"
}
],
"symlink_target": ""
} |
namespace formulate.app.Managers
{
// Namespaces.
using System.Collections.Generic;
using System.Linq;
using Configuration;
using core.Types;
using Templates;
/// <summary>
/// The default configuration manager.
/// </summary>
internal sealed class DefaultConfigurationManager : IConfigurationManager
{
/// <summary>
/// Initializes a new instance of the <see cref="DefaultConfigurationManager"/> class.
/// </summary>
/// <param name="config">
/// The Formulate config.
/// </param>
public DefaultConfigurationManager(IFormulateConfig config)
{
Config = config;
}
#region Properties
/// <summary>
/// Gets the json base path.
/// </summary>
public string JsonBasePath
{
get
{
return Config.Persistence.JsonBasePath;
}
}
/// <summary>
/// Gets the file store base path.
/// </summary>
public string FileStoreBasePath
{
get
{
return Config.Persistence.JsonBasePath;
}
}
/// <summary>
/// Gets the templates.
/// </summary>
public IEnumerable<Template> Templates
{
get
{
return Config.Templates.Select(x => new Template() { Id = x.Id, Name = x.Name, Path = x.Path }).ToArray();
}
}
/// <summary>
/// Gets the button kinds.
/// </summary>
public IEnumerable<string> ButtonKinds
{
get
{
return Config.Buttons?.Select(x => x.Kind);
}
}
/// <summary>
/// Gets a value indicating whether enable server side validation.
/// </summary>
public bool EnableServerSideValidation
{
get
{
return Config.Submissions.EnableServerSideValidation;
}
}
/// <summary>
/// Gets a value indicating whether enable email whitelisting.
/// </summary>
public bool EnableEmailWhitelist
{
get
{
return Config.Email.Whitelist.Enabled;
}
}
/// <summary>
/// Gets the emails to whitelist.
/// </summary>
public IEnumerable<AllowEmail> EmailWhitelist
{
get
{
return Config.Email.Whitelist.AllowedEmails.Select(x => new AllowEmail()
{
Email = x.Email,
Domain = x.Domain
}).ToArray();
}
}
/// <summary>
/// Gets the headers to use for emails.
/// </summary>
public IEnumerable<EmailHeader> EmailHeaders
{
get
{
return Config.Email.Headers.Select(x => new EmailHeader() { Name = x.Name, Value = x.Value }).ToArray();
}
}
/// <summary>
/// Gets the field categories.
/// </summary>
public IEnumerable<FieldCategory> FieldCategories
{
get
{
return Config.FieldCategories.Select(x => new FieldCategory()
{
Kind = x.Kind,
Group = x.Group
}).ToArray();
}
}
/// <summary>
/// Gets or sets the Formulate config.
/// </summary>
private IFormulateConfig Config { get; set; }
#endregion
}
}
| {
"content_hash": "d931e0009902c9b122360732ea5aa6c0",
"timestamp": "",
"source": "github",
"line_count": 147,
"max_line_length": 122,
"avg_line_length": 25.081632653061224,
"alnum_prop": 0.4716571738540819,
"repo_name": "rhythmagency/formulate",
"id": "ab0a2ba9eb977c72a45dec5d7caf794c17550d4d",
"size": "3689",
"binary": false,
"copies": "1",
"ref": "refs/heads/v3/master",
"path": "src/formulate.app/Managers/DefaultConfigurationManager.cs",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "ASP.NET",
"bytes": "2203"
},
{
"name": "Batchfile",
"bytes": "270"
},
{
"name": "C#",
"bytes": "617212"
},
{
"name": "HTML",
"bytes": "105873"
},
{
"name": "JavaScript",
"bytes": "380893"
},
{
"name": "SCSS",
"bytes": "14746"
}
],
"symlink_target": ""
} |
package com.intel.analytics.bigdl.dllib.integration.torch
import com.intel.analytics.bigdl.dllib.nn.SoftMin
import com.intel.analytics.bigdl.dllib.tensor.Tensor
import com.intel.analytics.bigdl.dllib.utils.Engine
import scala.util.Random
@com.intel.analytics.bigdl.tags.Serial
class SoftMinSpec extends TorchSpec {
"A SoftMin 1D input" should "generate correct output and grad" in {
torchCheck()
val layer = new SoftMin[Double]()
val input = Tensor[Double](10)
input.apply1(_ => Random.nextDouble())
val gradOutput = Tensor[Double](10)
gradOutput.apply1(_ => Random.nextDouble())
val start = System.nanoTime()
val output = layer.forward(input)
val gradInput = layer.backward(input, gradOutput)
val end = System.nanoTime()
val scalaTime = end - start
val code = "module = nn.SoftMin()\n" +
"output = module:forward(input)\n" +
"gradInput = module:backward(input,gradOutput)"
val (luaTime, torchResult) = TH.run(code, Map("input" -> input, "gradOutput" -> gradOutput),
Array("output", "gradInput"))
val luaOutput = torchResult("output").asInstanceOf[Tensor[Double]]
val luaGradInput = torchResult("gradInput").asInstanceOf[Tensor[Double]]
output should be (luaOutput)
gradInput should be (luaGradInput)
println("Test case : SoftMin, Torch : " + luaTime + " s, Scala : " + scalaTime / 1e9 + " s")
}
"A SoftMin 2D input" should "generate correct output and grad" in {
torchCheck()
val layer = new SoftMin[Double]()
val input = Tensor[Double](3, 5)
input.apply1(_ => Random.nextDouble())
val gradOutput = Tensor[Double](3, 5)
gradOutput.apply1(_ => Random.nextDouble())
val start = System.nanoTime()
val output = layer.forward(input)
val gradInput = layer.backward(input, gradOutput)
val end = System.nanoTime()
val scalaTime = end - start
val code = "module = nn.SoftMin()\n" +
"output = module:forward(input)\n" +
"gradInput = module:backward(input,gradOutput)"
val (luaTime, torchResult) = TH.run(code, Map("input" -> input, "gradOutput" -> gradOutput),
Array("output", "gradInput"))
val luaOutput = torchResult("output").asInstanceOf[Tensor[Double]]
val luaGradInput = torchResult("gradInput").asInstanceOf[Tensor[Double]]
output should be (luaOutput)
gradInput should be (luaGradInput)
println("Test case : SoftMin, Torch : " + luaTime + " s, Scala : " + scalaTime / 1e9 + " s")
}
"A SoftMin 3D input" should "generate correct output and grad" in {
torchCheck()
val layer = new SoftMin[Double]()
val input = Tensor[Double](4, 6, 6)
input.apply1(_ => Random.nextDouble())
val gradOutput = Tensor[Double](4, 6, 6)
gradOutput.apply1(_ => Random.nextDouble())
val start = System.nanoTime()
val output = layer.forward(input)
val gradInput = layer.backward(input, gradOutput)
val end = System.nanoTime()
val scalaTime = end - start
val code = "module = nn.SoftMin()\n" +
"output = module:forward(input)\n" +
"gradInput = module:backward(input,gradOutput)"
val (luaTime, torchResult) = TH.run(code, Map("input" -> input, "gradOutput" -> gradOutput),
Array("output", "gradInput"))
val luaOutput = torchResult("output").asInstanceOf[Tensor[Double]]
val luaGradInput = torchResult("gradInput").asInstanceOf[Tensor[Double]]
output should be (luaOutput)
gradInput should be (luaGradInput)
println("Test case : SoftMin, Torch : " + luaTime + " s, Scala : " + scalaTime / 1e9 + " s")
}
"A SoftMin 4D input" should "generate correct output and grad" in {
torchCheck()
val layer = new SoftMin[Double]()
val input = Tensor[Double](3, 5, 6, 6)
input.apply1(_ => Random.nextDouble())
val gradOutput = Tensor[Double](3, 5, 6, 6)
gradOutput.apply1(_ => Random.nextDouble())
val start = System.nanoTime()
val output = layer.forward(input)
val gradInput = layer.backward(input, gradOutput)
val end = System.nanoTime()
val scalaTime = end - start
val code = "module = nn.SoftMin()\n" +
"output = module:forward(input)\n" +
"gradInput = module:backward(input,gradOutput)"
val (luaTime, torchResult) = TH.run(code, Map("input" -> input, "gradOutput" -> gradOutput),
Array("output", "gradInput"))
val luaOutput = torchResult("output").asInstanceOf[Tensor[Double]]
val luaGradInput = torchResult("gradInput").asInstanceOf[Tensor[Double]]
output should be (luaOutput)
gradInput should be (luaGradInput)
println("Test case : SoftMin, Torch : " + luaTime + " s, Scala : " + scalaTime / 1e9 + " s")
}
}
| {
"content_hash": "2948be4186245176cacc54f14c798d70",
"timestamp": "",
"source": "github",
"line_count": 128,
"max_line_length": 96,
"avg_line_length": 36.5390625,
"alnum_prop": 0.6628180457558264,
"repo_name": "intel-analytics/BigDL",
"id": "fcc7501e687cc873b5fd9cb5411a5fd4c9b23f6a",
"size": "5278",
"binary": false,
"copies": "2",
"ref": "refs/heads/main",
"path": "scala/dllib/src/test/scala/com/intel/analytics/bigdl/dllib/integration/torch/SoftMinSpec.scala",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "C",
"bytes": "5342"
},
{
"name": "Dockerfile",
"bytes": "139304"
},
{
"name": "Java",
"bytes": "1321348"
},
{
"name": "Jupyter Notebook",
"bytes": "54112822"
},
{
"name": "Lua",
"bytes": "1904"
},
{
"name": "Makefile",
"bytes": "19253"
},
{
"name": "PowerShell",
"bytes": "1137"
},
{
"name": "PureBasic",
"bytes": "593"
},
{
"name": "Python",
"bytes": "8825782"
},
{
"name": "RobotFramework",
"bytes": "16117"
},
{
"name": "Scala",
"bytes": "13216148"
},
{
"name": "Shell",
"bytes": "848241"
}
],
"symlink_target": ""
} |
$imported ||= {}
$imported["IEX_AdvanceItemCheck"] = true
#==============================================================================#
# ** IEX::IParty
#==============================================================================#
module IEX
module IParty
#--------------------------------------------------------------------------#
# * new-method :check_items
#--------------------------------------------------------------------------#
def self.check_items(type, id, amount = 1)
ids = []
case id
when Range
ids |= id.to_a
when Array
ids |= id
else
ids << id.to_i
end
ids.each { |i|
case type
when 0
return false unless $game_party.has_item?($data_items[i])
return false unless $game_party.item_number($data_items[i]) >= amount
when 1
return false unless $game_party.has_item?($data_weapons[i])
return false unless $game_party.item_number($data_weapons[i]) >= amount
when 2
return false unless $game_party.has_item?($data_armors[i])
return false unless $game_party.item_number($data_armors[i]) >= amount
end
}
return true
end
end
end
#==============================================================================#
# ** Game_Interpreter
#==============================================================================#
class Game_Interpreter
#--------------------------------------------------------------------------#
# * new-method :check_items
#--------------------------------------------------------------------------#
def check_items(type, id, amount = 1)
return IEX::IParty.check_items(type, id, amount)
end
end
#==============================================================================#
# ** END OF FILE
#==============================================================================# | {
"content_hash": "7c16b2f8fcb908b8b12af8709f5bf12f",
"timestamp": "",
"source": "github",
"line_count": 57,
"max_line_length": 81,
"avg_line_length": 34.08771929824562,
"alnum_prop": 0.3340195573854864,
"repo_name": "Archeia/Kread-Ex-Scripts",
"id": "41335733751c4cee31195d67db8449aa66b3da51",
"size": "2925",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "IceDragon2000/lib/iex/iex_advance_item_check-v1_1.rb",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "22644"
},
{
"name": "HTML",
"bytes": "166589"
},
{
"name": "JavaScript",
"bytes": "68218"
},
{
"name": "Ruby",
"bytes": "635921"
}
],
"symlink_target": ""
} |
ACCEPTED
#### According to
International Plant Names Index
#### Published in
null
#### Original name
null
### Remarks
null | {
"content_hash": "a7cc026a683a7e6d8347e68564824954",
"timestamp": "",
"source": "github",
"line_count": 13,
"max_line_length": 31,
"avg_line_length": 9.692307692307692,
"alnum_prop": 0.7063492063492064,
"repo_name": "mdoering/backbone",
"id": "23464ea90b5a0e6e3ea98f89a2ae284c2a72a7a8",
"size": "172",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "life/Plantae/Magnoliophyta/Magnoliopsida/Lamiales/Plantaginaceae/Psyllium/Psyllium indicum/README.md",
"mode": "33188",
"license": "apache-2.0",
"language": [],
"symlink_target": ""
} |
<?xml version="1.0" encoding="UTF-8"?>
<!--
~ Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
~
~ WSO2 Inc. licenses this file to you under the Apache License,
~ Version 2.0 (the "License"); you may not use this file except
~ in compliance with the License.
~ You may obtain a copy of the License at
~
~ http://www.apache.org/licenses/LICENSE-2.0
~
~ Unless required by applicable law or agreed to in writing,
~ software distributed under the License is distributed on an
~ "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
~ KIND, either express or implied. See the License for the
~ specific language governing permissions and limitations
~ under the License.
-->
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<parent>
<groupId>org.wso2.carbon.devicemgt</groupId>
<artifactId>apimgt-extensions-feature</artifactId>
<version>3.0.183-SNAPSHOT</version>
<relativePath>../pom.xml</relativePath>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>org.wso2.carbon.apimgt.webapp.publisher.feature</artifactId>
<packaging>pom</packaging>
<version>3.0.183-SNAPSHOT</version>
<name>WSO2 Carbon - API Management Webapp Publisher Feature</name>
<url>http://wso2.org</url>
<description>This feature contains an implementation of a Tomcat lifecycle listener, which takes care of publishing
JAX-RS web applications as 'Managed APIs'
</description>
<dependencies>
<dependency>
<groupId>org.wso2.carbon.devicemgt</groupId>
<artifactId>org.wso2.carbon.apimgt.webapp.publisher</artifactId>
</dependency>
<dependency>
<groupId>org.wso2.carbon.devicemgt</groupId>
<artifactId>org.wso2.carbon.apimgt.annotations</artifactId>
</dependency>
<dependency>
<groupId>org.wso2.orbit.org.scannotation</groupId>
<artifactId>scannotation</artifactId>
</dependency>
<dependency>
<groupId>io.swagger</groupId>
<artifactId>swagger-annotations</artifactId>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<artifactId>maven-resources-plugin</artifactId>
<version>2.6</version>
<executions>
<execution>
<id>copy-resources</id>
<phase>generate-resources</phase>
<goals>
<goal>copy-resources</goal>
</goals>
<configuration>
<outputDirectory>src/main/resources</outputDirectory>
<resources>
<resource>
<directory>resources</directory>
<includes>
<include>build.properties</include>
<include>p2.inf</include>
</includes>
</resource>
</resources>
</configuration>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-dependency-plugin</artifactId>
<executions>
<execution>
<id>copy-jaxrs-war</id>
<phase>package</phase>
<goals>
<goal>copy</goal>
</goals>
<configuration>
<artifactItems>
<artifactItem>
<groupId>org.wso2.carbon.devicemgt</groupId>
<artifactId>org.wso2.carbon.apimgt.application.extension.api</artifactId>
<type>war</type>
<overWrite>true</overWrite>
<outputDirectory>
${project.build.directory}/maven-shared-archive-resources/webapps/
</outputDirectory>
<destFileName>ApiApplicationRegistration.war</destFileName>
</artifactItem>
</artifactItems>
</configuration>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.wso2.maven</groupId>
<artifactId>carbon-p2-plugin</artifactId>
<version>${carbon.p2.plugin.version}</version>
<executions>
<execution>
<id>p2-feature-generation</id>
<phase>package</phase>
<goals>
<goal>p2-feature-gen</goal>
</goals>
<configuration>
<id>org.wso2.carbon.apimgt.webapp.publisher</id>
<propertiesFile>../../../features/etc/feature.properties</propertiesFile>
<adviceFile>
<properties>
<propertyDef>org.wso2.carbon.p2.category.type:server</propertyDef>
<propertyDef>org.eclipse.equinox.p2.type.group:false</propertyDef>
</properties>
</adviceFile>
<bundles>
<bundleDef>
org.wso2.carbon.devicemgt:org.wso2.carbon.apimgt.webapp.publisher:${carbon.device.mgt.version}
</bundleDef>
<bundleDef>
org.wso2.carbon.devicemgt:org.wso2.carbon.apimgt.application.extension:${carbon.device.mgt.version}
</bundleDef>
<bundleDef>
org.wso2.carbon.devicemgt:org.wso2.carbon.apimgt.annotations:${carbon.device.mgt.version}
</bundleDef>
<bundleDef>
org.wso2.orbit.org.scannotation:scannotation:${scannotation.version}
</bundleDef>
<bundleDef>
io.swagger:swagger-annotations:${swagger.version}
</bundleDef>
</bundles>
<importFeatures>
<importFeatureDef>org.wso2.carbon.core.server:${carbon.kernel.version}</importFeatureDef>
</importFeatures>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</build>
</project>
| {
"content_hash": "b406843c7d74ce5b3d1f4b6d80b639ec",
"timestamp": "",
"source": "github",
"line_count": 158,
"max_line_length": 204,
"avg_line_length": 46.46835443037975,
"alnum_prop": 0.481067828929447,
"repo_name": "sameeragunarathne/carbon-device-mgt",
"id": "936f53fff6eda56ea181429cc2cba88156df6e50",
"size": "7342",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "features/apimgt-extensions/org.wso2.carbon.apimgt.webapp.publisher.feature/pom.xml",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "683126"
},
{
"name": "HTML",
"bytes": "538190"
},
{
"name": "Java",
"bytes": "5355685"
},
{
"name": "JavaScript",
"bytes": "4192171"
},
{
"name": "PLSQL",
"bytes": "26647"
}
],
"symlink_target": ""
} |
@class AUAudioDevice, MMTimer, NSRecursiveLock, NSString, PSTNComponent, PSTNDialData, VOIPKernelLog;
@interface PSTNMgr : MMService <AUAudioDataSource, IAUAudioDeviceExt, PBMessageObserverDelegate, ISysCallCheckExt, IPSTNSyncExt, INetworkStatusMgrExt, MMService>
{
int mStatus;
_Bool mIsInterrupted;
_Bool mIsCanConnect;
_Bool mIsConnected;
_Bool mIsCanTalk;
_Bool mIsTalked;
_Bool mIsEngineStarted;
_Bool mIsCanSendData;
_Bool mIsAudioStarted;
_Bool mIsRecordStarted;
_Bool mIsPreConnectFail;
_Bool mIsPSTNAnswer;
_Bool mIsPSTNAccepted;
unsigned int mLastNetworkStatus;
int mAudioCodecType;
int mShutDownStatus;
_Bool mIsSpeaker;
VOIPKernelLog *mPstnKernelLog;
int mErrCode;
int mCntTryStartAudioDev;
unsigned int mInviteId;
PSTNDialData *mDialData;
PSTNComponent *mComponent;
AUAudioDevice *mAudioDevice;
NSRecursiveLock *mAudioEncLock;
NSRecursiveLock *mAudioDecLock;
NSRecursiveLock *mStartAudioLock;
NSRecursiveLock *mStartRecordLock;
NSRecursiveLock *inputVideoRenderLock;
MMTimer *mPSTNHeartbeatTimer;
MMTimer *mPSTNDialStatusTimer;
unsigned long long mLastDisconnectSysCallTime;
}
@property(nonatomic) unsigned long long mLastDisconnectSysCallTime; // @synthesize mLastDisconnectSysCallTime;
@property(nonatomic) unsigned int mInviteId; // @synthesize mInviteId;
@property(nonatomic) int mCntTryStartAudioDev; // @synthesize mCntTryStartAudioDev;
@property(retain, nonatomic) MMTimer *mPSTNDialStatusTimer; // @synthesize mPSTNDialStatusTimer;
@property(retain, nonatomic) MMTimer *mPSTNHeartbeatTimer; // @synthesize mPSTNHeartbeatTimer;
@property(retain, nonatomic) NSRecursiveLock *inputVideoRenderLock; // @synthesize inputVideoRenderLock;
@property(retain, nonatomic) NSRecursiveLock *mStartRecordLock; // @synthesize mStartRecordLock;
@property(retain, nonatomic) NSRecursiveLock *mStartAudioLock; // @synthesize mStartAudioLock;
@property(retain, nonatomic) NSRecursiveLock *mAudioDecLock; // @synthesize mAudioDecLock;
@property(retain, nonatomic) NSRecursiveLock *mAudioEncLock; // @synthesize mAudioEncLock;
@property(retain, nonatomic) AUAudioDevice *mAudioDevice; // @synthesize mAudioDevice;
@property(retain, nonatomic) PSTNComponent *mComponent; // @synthesize mComponent;
@property(retain, nonatomic) PSTNDialData *mDialData; // @synthesize mDialData;
@property(nonatomic) int mErrCode; // @synthesize mErrCode;
@property(nonatomic) int mStatus; // @synthesize mStatus;
- (void).cxx_destruct;
- (void)PstnCheckCountryCode:(id)arg1;
- (void)onNetworkStatusChange:(unsigned int)arg1;
- (unsigned int)getIsConnected;
- (_Bool)getIsTalked;
- (int)getRoomId;
- (long long)getRoomKey;
- (void)SetAudioCodecType:(int)arg1;
- (void)SetCountryCode:(id)arg1;
- (void)SetIsCanConnect:(_Bool)arg1;
- (void)SetSpeakerPhone:(_Bool)arg1;
- (void)SetMicroPhoneMute:(_Bool)arg1;
- (void)PressButton:(int)arg1;
- (void)Hangup;
- (void)BeRejected;
- (void)CancelCall;
- (void)PSTNCall:(id)arg1 phoneNum:(id)arg2 withCallType:(int)arg3 DialScene:(unsigned int)arg4 CountryCodeFrom:(unsigned int)arg5;
- (int)getNetSpeed;
- (void)dealloc;
- (id)init;
- (int)OnTransportChannelEvent:(unsigned short)arg1 ErrNo:(int)arg2;
- (int)OnTransportChannelCmd:(void *)arg1 len:(int)arg2;
- (void)onAcceptBydata;
- (void)ConnectFail:(id)arg1;
- (void)NetworkErr:(id)arg1;
- (void)StopConnect;
- (void)StartConnect;
- (void)tryStartConnect;
- (void)TalkBroken:(id)arg1;
- (void)StopTalk;
- (void)StartAudioData;
- (void)StartAudioDataInNewThread;
- (void)StartRecordAndPlayAudioForVoip;
- (void)StartTalk;
- (void)tryStartTalk;
- (int)AudioDevGetData:(char *)arg1 length:(unsigned int)arg2;
- (int)AudioDevPutData:(char *)arg1 length:(unsigned int)arg2;
- (int)OnTransportChannelRttAndLR:(unsigned int)arg1 lostRate:(unsigned int)arg2 type:(unsigned int)arg3;
- (int)OnTransportChannelData:(int)arg1 pData:(void *)arg2 len:(int)arg3;
- (void)DataNotify_Arq:(char *)arg1 len:(int)arg2 type:(unsigned char)arg3;
- (void)DataNotify_pp:(char *)arg1 len:(int)arg2 param:(short)arg3;
- (void)DataNotify:(char *)arg1 len:(int)arg2;
- (void)EventNotify:(long long)arg1 param:(int)arg2 type:(int)arg3;
- (void)audioDeviceStartedFail:(id)arg1;
- (void)audioDeviceUnPluginHeadset:(id)arg1;
- (void)audioDevicePluginHeadset:(id)arg1;
- (void)audioDeviceFarawayEar:(id)arg1;
- (void)audioDeviceNearEar:(id)arg1;
- (void)SetMVEInfo:(CDStruct_33d8b17a *)arg1;
- (int)GetCPUCapacity;
- (unsigned int)GetNetType;
- (void)SendCheckNumberRequest:(id)arg1;
- (void)SendRedirectRequest;
- (void)SendStatReportRequest;
- (void)SendHeartbeatRequest;
- (void)SendShutdownRequest;
- (void)SendCancelInviteRequest;
- (void)SendInviteRequestBy:(id)arg1 phoneNum:(id)arg2 withCallType:(int)arg3 DialScene:(unsigned int)arg4 CountryCodeFrom:(unsigned int)arg5;
- (void)SetReportData:(id *)arg1 channelReport:(id *)arg2 engineReport:(id *)arg3;
- (void)HandlePSTNCheckNumberResp:(id)arg1 Event:(unsigned int)arg2;
- (void)HandlePSTNRedirectResp:(id)arg1 Event:(unsigned int)arg2;
- (void)HandlePSTNStatReportResp:(id)arg1 Event:(unsigned int)arg2;
- (void)HandlePSTNHeartbeatResp:(id)arg1 Event:(unsigned int)arg2;
- (void)HandlePSTNShutdownResp:(id)arg1 Event:(unsigned int)arg2;
- (void)HandlePSTNCancelInviteResp:(id)arg1 Event:(unsigned int)arg2;
- (void)HandlePSTNInviteResp:(id)arg1 Event:(unsigned int)arg2;
- (void)MessageReturn:(id)arg1 Event:(unsigned int)arg2;
- (void)StopSessionWithProtocolErr:(int)arg1;
- (void)StopSession;
- (void)StartSession;
- (int)SetServerAddr;
- (void)handleEnterForeground;
- (void)handleEnterBackground;
- (void)interruptWcoCall;
- (void)OnSysCallState:(int)arg1;
- (void)restartAudioDevicePSTN;
- (void)EndInterruption;
- (void)BeginInterruption;
- (void)DialStatusTimerCheck;
- (void)HeartbeatTimerCheck;
- (void)UnInitAll;
- (void)InitAll;
- (void)OnGotRemoteStatus:(unsigned int)arg1 ErrNo:(int)arg2 ErrLevel:(int)arg3 ErrMsg:(id)arg4 ErrTitle:(id)arg5 DataFlag:(unsigned int)arg6;
- (void)OnGotDTMFPayloadType:(unsigned int)arg1;
- (void)OnSyncError:(int)arg1;
// Remaining properties
@property(readonly, copy) NSString *debugDescription;
@property(readonly, copy) NSString *description;
@property(readonly) unsigned long long hash;
@property(readonly) Class superclass;
@end
| {
"content_hash": "987e81a99f345550911de157d7fa89f6",
"timestamp": "",
"source": "github",
"line_count": 147,
"max_line_length": 161,
"avg_line_length": 42.965986394557824,
"alnum_prop": 0.772640911969601,
"repo_name": "walkdianzi/DashengHook",
"id": "086d7664bc72a78ff073c9b7675e21b4fc5fe7e6",
"size": "6686",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "WeChat-Headers/PSTNMgr.h",
"mode": "33261",
"license": "mit",
"language": [
{
"name": "C",
"bytes": "986"
},
{
"name": "Objective-C",
"bytes": "10153542"
},
{
"name": "Objective-C++",
"bytes": "18332"
},
{
"name": "Shell",
"bytes": "1459"
}
],
"symlink_target": ""
} |
<?php
require 'vendor/autoload.php';
use Aws\Rds\RdsClient;
$client = RdsClient::factory(array(
'version' => 'latest',
'region' => 'us-east-1'
));
$result = $client->describeDBInstances(array(
'DBInstanceIdentifier' => 'ctian-db',
));
$endpoint = $result['DBInstances'][0]['Endpoint']['Address'];
print "=====================\n". $endpoint . "============\n";
$endpoint= "";
foreach ($result["DBInstances"] as $dbinstances){
$dbinstanceidentifier = $ $dbinstances["DBInstanceIdentifier"];
if ($dbinstanceidentifier == "ctian-db"){
$endpoint = $dbinstances["Endpoint"]["Address"];
}
}
echo "begin database";
$link = mysqli_connect($endpoint,"controller","letmein88") or die("Error " . mysqli_error($link));
$db = "CREATE SCHEMA `ctiandb`;";
$link->query($db);
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
$delete_table = 'DELETE TABLE items';
$del_tbl = $link->query($delete_table);
$create_table = 'CREATE TABLE items
(
id INT NOT NULL AUTO_INCREMENT,
email VARCHAR(200) NOT NULL,
phone VARCHAR(20) NOT NULL,
s3rawurl VARCHAR(255) NOT NULL,
filename VARCHAR(255) NOT NULL,
s3finishedurl VARCHAR(255) NOT NULL,
status INT NOT NULL,
issubscribed INT
)';
$create_tbl = $link->query($create_table);
if ($create_table) {
echo "Table is created or No error returned.";
}
else {
echo "error!!";
}
$link->close();
?>
<h1>File Upload</h1>
<form action="index.php">
<input type="submit" value="Submit">
</form>
| {
"content_hash": "de7fd50aa7cbf5ae496372786f4d620b",
"timestamp": "",
"source": "github",
"line_count": 70,
"max_line_length": 98,
"avg_line_length": 21.82857142857143,
"alnum_prop": 0.6393979057591623,
"repo_name": "ctian3/Application-Setup",
"id": "97225ea0a41a346b9ea720292c2100593aa5f1c6",
"size": "1528",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "setup.php",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "13526"
},
{
"name": "HTML",
"bytes": "500"
},
{
"name": "JavaScript",
"bytes": "16145"
},
{
"name": "PHP",
"bytes": "14867"
}
],
"symlink_target": ""
} |
package org.apache.ignite.internal.processors.service;
import java.lang.Thread.UncaughtExceptionHandler;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.TimeUnit;
import javax.cache.Cache;
import javax.cache.event.CacheEntryEvent;
import javax.cache.event.CacheEntryUpdatedListener;
import org.apache.ignite.IgniteCheckedException;
import org.apache.ignite.IgniteException;
import org.apache.ignite.IgniteLogger;
import org.apache.ignite.cluster.ClusterGroup;
import org.apache.ignite.cluster.ClusterNode;
import org.apache.ignite.compute.ComputeJobContext;
import org.apache.ignite.configuration.DeploymentMode;
import org.apache.ignite.configuration.IgniteConfiguration;
import org.apache.ignite.events.DiscoveryEvent;
import org.apache.ignite.events.EventType;
import org.apache.ignite.internal.GridClosureCallMode;
import org.apache.ignite.internal.GridKernalContext;
import org.apache.ignite.internal.IgniteClientDisconnectedCheckedException;
import org.apache.ignite.internal.IgniteEx;
import org.apache.ignite.internal.IgniteInternalFuture;
import org.apache.ignite.internal.IgniteInterruptedCheckedException;
import org.apache.ignite.internal.cluster.ClusterTopologyCheckedException;
import org.apache.ignite.internal.events.DiscoveryCustomEvent;
import org.apache.ignite.internal.managers.discovery.DiscoCache;
import org.apache.ignite.internal.managers.discovery.DiscoveryCustomMessage;
import org.apache.ignite.internal.managers.eventstorage.DiscoveryEventListener;
import org.apache.ignite.internal.processors.affinity.AffinityTopologyVersion;
import org.apache.ignite.internal.processors.cache.CacheAffinityChangeMessage;
import org.apache.ignite.internal.processors.cache.CacheIteratorConverter;
import org.apache.ignite.internal.processors.cache.DynamicCacheChangeBatch;
import org.apache.ignite.internal.processors.cache.IgniteInternalCache;
import org.apache.ignite.internal.processors.cache.binary.MetadataUpdateAcceptedMessage;
import org.apache.ignite.internal.processors.cache.binary.MetadataUpdateProposedMessage;
import org.apache.ignite.internal.processors.cache.distributed.near.GridNearTxLocal;
import org.apache.ignite.internal.processors.cache.query.CacheQuery;
import org.apache.ignite.internal.processors.cache.query.GridCacheQueryManager;
import org.apache.ignite.internal.processors.cluster.DiscoveryDataClusterState;
import org.apache.ignite.internal.processors.cluster.IgniteChangeGlobalStateSupport;
import org.apache.ignite.internal.processors.task.GridInternal;
import org.apache.ignite.internal.processors.timeout.GridTimeoutObject;
import org.apache.ignite.internal.util.GridEmptyIterator;
import org.apache.ignite.internal.util.GridSpinBusyLock;
import org.apache.ignite.internal.util.future.GridCompoundFuture;
import org.apache.ignite.internal.util.future.GridFinishedFuture;
import org.apache.ignite.internal.util.future.GridFutureAdapter;
import org.apache.ignite.internal.util.lang.GridCloseableIterator;
import org.apache.ignite.internal.util.typedef.F;
import org.apache.ignite.internal.util.typedef.X;
import org.apache.ignite.internal.util.typedef.internal.A;
import org.apache.ignite.internal.util.typedef.internal.CU;
import org.apache.ignite.internal.util.typedef.internal.LT;
import org.apache.ignite.internal.util.typedef.internal.S;
import org.apache.ignite.internal.util.typedef.internal.U;
import org.apache.ignite.lang.IgniteBiPredicate;
import org.apache.ignite.lang.IgniteCallable;
import org.apache.ignite.lang.IgniteFuture;
import org.apache.ignite.lang.IgnitePredicate;
import org.apache.ignite.lang.IgniteUuid;
import org.apache.ignite.marshaller.Marshaller;
import org.apache.ignite.plugin.security.SecurityException;
import org.apache.ignite.plugin.security.SecurityPermission;
import org.apache.ignite.resources.IgniteInstanceResource;
import org.apache.ignite.resources.JobContextResource;
import org.apache.ignite.resources.LoggerResource;
import org.apache.ignite.services.Service;
import org.apache.ignite.services.ServiceConfiguration;
import org.apache.ignite.services.ServiceDeploymentException;
import org.apache.ignite.services.ServiceDescriptor;
import org.apache.ignite.thread.IgniteThreadFactory;
import org.apache.ignite.thread.OomExceptionHandler;
import org.apache.ignite.transactions.Transaction;
import org.jetbrains.annotations.Nullable;
import static javax.cache.event.EventType.REMOVED;
import static org.apache.ignite.configuration.DeploymentMode.ISOLATED;
import static org.apache.ignite.configuration.DeploymentMode.PRIVATE;
import static org.apache.ignite.transactions.TransactionConcurrency.PESSIMISTIC;
import static org.apache.ignite.transactions.TransactionIsolation.READ_COMMITTED;
import static org.apache.ignite.transactions.TransactionIsolation.REPEATABLE_READ;
/**
* Grid service processor.
* <p/>
* Obsolete implementation of service processor, based on replicated system cache.
* <p/>
* NOTE: if you fix a bug in this class, please take a look in {@link IgniteServiceProcessor}, perhaps the class
* contains a similar block of code which also should be updated.
*
* @see IgniteServiceProcessor
* @deprecated Here is improved, but uncompatible implementation {@link IgniteServiceProcessor}, see IEP-17 for details.
*/
@Deprecated
@SuppressWarnings({"SynchronizationOnLocalVariableOrMethodParameter", "ConstantConditions"})
public class GridServiceProcessor extends ServiceProcessorAdapter implements IgniteChangeGlobalStateSupport {
/** Time to wait before reassignment retries. */
private static final long RETRY_TIMEOUT = 1000;
/** */
private static final int[] EVTS = {
EventType.EVT_NODE_JOINED,
EventType.EVT_NODE_LEFT,
EventType.EVT_NODE_FAILED,
DiscoveryCustomEvent.EVT_DISCOVERY_CUSTOM_EVT
};
/** Local service instances. */
private final Map<String, Collection<ServiceContextImpl>> locSvcs = new HashMap<>();
/** Deployment futures. */
private final ConcurrentMap<String, GridServiceDeploymentFuture<String>> depFuts = new ConcurrentHashMap<>();
/** Deployment futures. */
private final ConcurrentMap<String, GridFutureAdapter<?>> undepFuts = new ConcurrentHashMap<>();
/** Pending compute job contexts that waiting for utility cache initialization. */
private final List<ComputeJobContext> pendingJobCtxs = new ArrayList<>(0);
/** Deployment executor service. */
private volatile ExecutorService depExe;
/** Busy lock. */
private volatile GridSpinBusyLock busyLock = new GridSpinBusyLock();
/** Uncaught exception handler for thread pools. */
private final UncaughtExceptionHandler oomeHnd = new OomExceptionHandler(ctx);
/** Thread factory. */
private ThreadFactory threadFactory = new IgniteThreadFactory(ctx.igniteInstanceName(), "service",
oomeHnd);
/** Thread local for service name. */
private ThreadLocal<String> svcName = new ThreadLocal<>();
/** Service cache. */
private volatile IgniteInternalCache<Object, Object> serviceCache;
/** Topology listener. */
private DiscoveryEventListener topLsnr = new TopologyListener();
/** */
private final CountDownLatch startLatch = new CountDownLatch(1);
/**
* @param ctx Kernal context.
*/
public GridServiceProcessor(GridKernalContext ctx) {
super(ctx);
depExe = Executors.newSingleThreadExecutor(new IgniteThreadFactory(ctx.igniteInstanceName(),
"srvc-deploy", oomeHnd));
}
/**
* @param ctx Context.
* @throws IgniteCheckedException If failed.
*/
public void onContinuousProcessorStarted(GridKernalContext ctx) throws IgniteCheckedException {
if (ctx.clientNode()) {
assert !ctx.isDaemon();
ctx.continuous().registerStaticRoutine(
CU.UTILITY_CACHE_NAME, new ServiceEntriesListener(), null, null
);
}
}
/** {@inheritDoc} */
@Override public void start() throws IgniteCheckedException {
if (ctx.isDaemon())
return;
IgniteConfiguration cfg = ctx.config();
DeploymentMode depMode = cfg.getDeploymentMode();
if (cfg.isPeerClassLoadingEnabled() && (depMode == PRIVATE || depMode == ISOLATED) &&
!F.isEmpty(cfg.getServiceConfiguration()))
throw new IgniteCheckedException("Cannot deploy services in PRIVATE or ISOLATED deployment mode: " + depMode);
}
/** {@inheritDoc} */
@Override public void onKernalStart(boolean active) throws IgniteCheckedException {
if (ctx.isDaemon() || !active)
return;
onKernalStart0();
}
/**
* Do kernal start.
*
* @throws IgniteCheckedException If failed.
*/
private void onKernalStart0() throws IgniteCheckedException {
if (!ctx.clientNode())
ctx.event().addDiscoveryEventListener(topLsnr, EVTS);
updateUtilityCache();
startLatch.countDown();
try {
if (ctx.deploy().enabled())
ctx.cache().context().deploy().ignoreOwnership(true);
if (!ctx.clientNode()) {
DiscoveryDataClusterState clusterState = ctx.state().clusterState();
boolean isLocLsnr = !clusterState.hasBaselineTopology() ||
CU.baselineNode(ctx.cluster().get().localNode(), clusterState);
// Register query listener and run it for local entries, if data is available locally.
// It is also invoked on rebalancing.
// Otherwise remote listener is registered.
serviceCache.context().continuousQueries().executeInternalQuery(
new ServiceEntriesListener(), null, isLocLsnr, true, false, false
);
}
else { // Listener for client nodes is registered in onContinuousProcessorStarted method.
assert !ctx.isDaemon();
ctx.closure().runLocalSafe(new Runnable() {
@Override public void run() {
try {
Iterable<CacheEntryEvent<?, ?>> entries =
serviceCache.context().continuousQueries().existingEntries(false, null);
onSystemCacheUpdated(entries);
}
catch (IgniteCheckedException e) {
U.error(log, "Failed to load service entries: " + e, e);
}
}
});
}
}
finally {
if (ctx.deploy().enabled())
ctx.cache().context().deploy().ignoreOwnership(false);
}
ServiceConfiguration[] cfgs = ctx.config().getServiceConfiguration();
if (cfgs != null)
deployAll(Arrays.asList(cfgs), ctx.cluster().get().forServers().predicate()).get();
if (log.isDebugEnabled())
log.debug("Started service processor.");
}
/**
*
*/
public void updateUtilityCache() {
serviceCache = ctx.cache().utilityCache();
}
/**
* @return Service cache.
*/
private IgniteInternalCache<Object, Object> serviceCache() {
if (serviceCache == null)
U.awaitQuiet(startLatch);
return serviceCache;
}
/** {@inheritDoc} */
@Override public void onKernalStop(boolean cancel) {
if (ctx.isDaemon())
return;
GridSpinBusyLock busyLock = this.busyLock;
// Will not release it.
if (busyLock != null) {
busyLock.block();
this.busyLock = null;
}
startLatch.countDown();
U.shutdownNow(GridServiceProcessor.class, depExe, log);
if (!ctx.clientNode())
ctx.event().removeDiscoveryEventListener(topLsnr);
Collection<ServiceContextImpl> ctxs = new ArrayList<>();
synchronized (locSvcs) {
for (Collection<ServiceContextImpl> ctxs0 : locSvcs.values())
ctxs.addAll(ctxs0);
locSvcs.clear();
}
for (ServiceContextImpl ctx : ctxs) {
ctx.setCancelled(true);
Service svc = ctx.service();
if (svc != null)
try {
svc.cancel(ctx);
}
catch (Throwable e) {
log.error("Failed to cancel service (ignoring) [name=" + ctx.name() +
", execId=" + ctx.executionId() + ']', e);
if (e instanceof Error)
throw e;
}
ctx.executor().shutdownNow();
}
for (ServiceContextImpl ctx : ctxs) {
try {
if (log.isInfoEnabled() && !ctxs.isEmpty())
log.info("Shutting down distributed service [name=" + ctx.name() + ", execId8=" +
U.id8(ctx.executionId()) + ']');
ctx.executor().awaitTermination(Long.MAX_VALUE, TimeUnit.MILLISECONDS);
}
catch (InterruptedException ignore) {
Thread.currentThread().interrupt();
U.error(log, "Got interrupted while waiting for service to shutdown (will continue stopping node): " +
ctx.name());
}
}
Exception err = new IgniteCheckedException("Operation has been cancelled (node is stopping).");
cancelFutures(depFuts, err);
cancelFutures(undepFuts, err);
if (log.isDebugEnabled())
log.debug("Stopped service processor.");
}
/** {@inheritDoc} */
@Override public void onActivate(GridKernalContext kctx) throws IgniteCheckedException {
if (log.isDebugEnabled())
log.debug("Activate service processor [nodeId=" + ctx.localNodeId() +
" topVer=" + ctx.discovery().topologyVersionEx() + " ]");
busyLock = new GridSpinBusyLock();
depExe = Executors.newSingleThreadExecutor(new IgniteThreadFactory(ctx.igniteInstanceName(),
"srvc-deploy", oomeHnd));
start();
onKernalStart0();
}
/** {@inheritDoc} */
@Override public void onDeActivate(GridKernalContext kctx) {
if (log.isDebugEnabled())
log.debug("DeActivate service processor [nodeId=" + ctx.localNodeId() +
" topVer=" + ctx.discovery().topologyVersionEx() + " ]");
cancelFutures(depFuts, new IgniteCheckedException("Failed to deploy service, cluster in active."));
cancelFutures(undepFuts, new IgniteCheckedException("Failed to undeploy service, cluster in active."));
onKernalStop(true);
}
/** {@inheritDoc} */
@Override public void onDisconnected(IgniteFuture<?> reconnectFut) throws IgniteCheckedException {
cancelFutures(depFuts, new IgniteClientDisconnectedCheckedException(ctx.cluster().clientReconnectFuture(),
"Failed to deploy service, client node disconnected."));
cancelFutures(undepFuts, new IgniteClientDisconnectedCheckedException(ctx.cluster().clientReconnectFuture(),
"Failed to undeploy service, client node disconnected."));
}
/**
* @param futs Futs.
* @param err Exception.
*/
private void cancelFutures(ConcurrentMap<String, ? extends GridFutureAdapter<?>> futs, Exception err) {
for (Map.Entry<String, ? extends GridFutureAdapter<?>> entry : futs.entrySet()) {
GridFutureAdapter fut = entry.getValue();
fut.onDone(err);
futs.remove(entry.getKey(), fut);
}
}
/**
* Validates service configuration.
*
* @param c Service configuration.
* @throws IgniteException If validation failed.
*/
private void validate(ServiceConfiguration c) throws IgniteException {
IgniteConfiguration cfg = ctx.config();
DeploymentMode depMode = cfg.getDeploymentMode();
if (cfg.isPeerClassLoadingEnabled() && (depMode == PRIVATE || depMode == ISOLATED))
throw new IgniteException("Cannot deploy services in PRIVATE or ISOLATED deployment mode: " + depMode);
ensure(c.getName() != null, "getName() != null", null);
ensure(c.getTotalCount() >= 0, "getTotalCount() >= 0", c.getTotalCount());
ensure(c.getMaxPerNodeCount() >= 0, "getMaxPerNodeCount() >= 0", c.getMaxPerNodeCount());
ensure(c.getService() != null, "getService() != null", c.getService());
ensure(c.getTotalCount() > 0 || c.getMaxPerNodeCount() > 0,
"c.getTotalCount() > 0 || c.getMaxPerNodeCount() > 0", null);
}
/**
* @param cond Condition.
* @param desc Description.
* @param v Value.
*/
private void ensure(boolean cond, String desc, @Nullable Object v) {
if (!cond)
if (v != null)
throw new IgniteException("Service configuration check failed (" + desc + "): " + v);
else
throw new IgniteException("Service configuration check failed (" + desc + ")");
}
/** {@inheritDoc} */
@Override public IgniteInternalFuture<?> deployNodeSingleton(ClusterGroup prj, String name, Service srvc) {
return deployMultiple(prj, name, srvc, 0, 1);
}
/** {@inheritDoc} */
@Override public IgniteInternalFuture<?> deployClusterSingleton(ClusterGroup prj, String name, Service srvc) {
return deployMultiple(prj, name, srvc, 1, 1);
}
/** {@inheritDoc} */
@Override public IgniteInternalFuture<?> deployMultiple(ClusterGroup prj, String name, Service srvc, int totalCnt,
int maxPerNodeCnt) {
ServiceConfiguration cfg = new ServiceConfiguration();
cfg.setName(name);
cfg.setService(srvc);
cfg.setTotalCount(totalCnt);
cfg.setMaxPerNodeCount(maxPerNodeCnt);
return deployAll(prj, Collections.singleton(cfg));
}
/** {@inheritDoc} */
@Override public IgniteInternalFuture<?> deployKeyAffinitySingleton(String name, Service srvc, String cacheName,
Object affKey) {
A.notNull(affKey, "affKey");
ServiceConfiguration cfg = new ServiceConfiguration();
cfg.setName(name);
cfg.setService(srvc);
cfg.setCacheName(cacheName);
cfg.setAffinityKey(affKey);
cfg.setTotalCount(1);
cfg.setMaxPerNodeCount(1);
// Ignore projection here.
return deployAll(Collections.singleton(cfg), null);
}
/**
* @param cfgs Service configurations.
* @param dfltNodeFilter Default NodeFilter.
* @return Configurations to deploy.
*/
private PreparedConfigurations<String> prepareServiceConfigurations(Collection<ServiceConfiguration> cfgs,
IgnitePredicate<ClusterNode> dfltNodeFilter) {
List<ServiceConfiguration> cfgsCp = new ArrayList<>(cfgs.size());
Marshaller marsh = ctx.config().getMarshaller();
List<GridServiceDeploymentFuture<String>> failedFuts = null;
for (ServiceConfiguration cfg : cfgs) {
Exception err = null;
// Deploy to projection node by default
// or only on server nodes if no projection .
if (cfg.getNodeFilter() == null && dfltNodeFilter != null)
cfg.setNodeFilter(dfltNodeFilter);
try {
validate(cfg);
}
catch (Exception e) {
U.error(log, "Failed to validate service configuration [name=" + cfg.getName() +
", srvc=" + cfg.getService() + ']', e);
err = e;
}
if (err == null) {
try {
ctx.security().authorize(cfg.getName(), SecurityPermission.SERVICE_DEPLOY, null);
}
catch (Exception e) {
U.error(log, "Failed to authorize service creation [name=" + cfg.getName() +
", srvc=" + cfg.getService() + ']', e);
err = e;
}
}
if (err == null) {
try {
byte[] srvcBytes = U.marshal(marsh, cfg.getService());
cfgsCp.add(new LazyServiceConfiguration(cfg, srvcBytes));
}
catch (Exception e) {
U.error(log, "Failed to marshal service with configured marshaller [name=" + cfg.getName() +
", srvc=" + cfg.getService() + ", marsh=" + marsh + "]", e);
err = e;
}
}
if (err != null) {
if (failedFuts == null)
failedFuts = new ArrayList<>();
GridServiceDeploymentFuture<String> fut = new GridServiceDeploymentFuture<>(cfg, cfg.getName());
fut.onDone(err);
failedFuts.add(fut);
}
}
return new PreparedConfigurations<>(cfgsCp, failedFuts);
}
/** {@inheritDoc} */
@Override public IgniteInternalFuture<?> deployAll(ClusterGroup prj, Collection<ServiceConfiguration> cfgs) {
if (prj == null)
// Deploy to servers by default if no projection specified.
return deployAll(cfgs, ctx.cluster().get().forServers().predicate());
else if (prj.predicate() == F.<ClusterNode>alwaysTrue())
return deployAll(cfgs, null);
else
// Deploy to predicate nodes by default.
return deployAll(cfgs, prj.predicate());
}
/**
* @param cfgs Service configurations.
* @param dfltNodeFilter Default NodeFilter.
* @return Future for deployment.
*/
private IgniteInternalFuture<?> deployAll(Collection<ServiceConfiguration> cfgs,
@Nullable IgnitePredicate<ClusterNode> dfltNodeFilter) {
assert cfgs != null;
PreparedConfigurations<String> srvCfg = prepareServiceConfigurations(cfgs, dfltNodeFilter);
List<ServiceConfiguration> cfgsCp = srvCfg.cfgs;
List<GridServiceDeploymentFuture<String>> failedFuts = srvCfg.failedFuts;
Collections.sort(cfgsCp, new Comparator<ServiceConfiguration>() {
@Override public int compare(ServiceConfiguration cfg1, ServiceConfiguration cfg2) {
return cfg1.getName().compareTo(cfg2.getName());
}
});
GridServiceDeploymentCompoundFuture<String> res;
while (true) {
res = new GridServiceDeploymentCompoundFuture<>();
if (ctx.deploy().enabled())
ctx.cache().context().deploy().ignoreOwnership(true);
try {
if (cfgsCp.size() == 1)
writeServiceToCache(res, cfgsCp.get(0));
else if (cfgsCp.size() > 1) {
try (Transaction tx = serviceCache().txStart(PESSIMISTIC, READ_COMMITTED)) {
for (ServiceConfiguration cfg : cfgsCp) {
try {
writeServiceToCache(res, cfg);
}
catch (IgniteCheckedException e) {
if (X.hasCause(e, ClusterTopologyCheckedException.class))
throw e; // Retry.
else
U.error(log, e.getMessage());
}
}
tx.commit();
}
}
break;
}
catch (IgniteException | IgniteCheckedException e) {
for (String name : res.servicesToRollback()) {
GridServiceDeploymentFuture<String> fut;
if ((fut = depFuts.remove(name)) != null)
fut.onDone(e);
}
if (X.hasCause(e, ClusterTopologyCheckedException.class)) {
if (log.isDebugEnabled())
log.debug("Topology changed while deploying services (will retry): " + e.getMessage());
}
else {
res.onDone(new IgniteCheckedException(
new ServiceDeploymentException("Failed to deploy provided services.", e, cfgs)));
return res;
}
}
finally {
if (ctx.deploy().enabled())
ctx.cache().context().deploy().ignoreOwnership(false);
}
}
if (ctx.clientDisconnected()) {
IgniteClientDisconnectedCheckedException err =
new IgniteClientDisconnectedCheckedException(ctx.cluster().clientReconnectFuture(),
"Failed to deploy services, client node disconnected: " + cfgs);
for (String name : res.servicesToRollback()) {
GridServiceDeploymentFuture<String> fut = depFuts.remove(name);
if (fut != null)
fut.onDone(err);
}
return new GridFinishedFuture<>(err);
}
if (failedFuts != null) {
for (GridServiceDeploymentFuture<String> fut : failedFuts)
res.add(fut, false);
}
res.markInitialized();
return res;
}
/**
* @param res Resulting compound future.
* @param cfg Service configuration.
* @throws IgniteCheckedException If operation failed.
*/
private void writeServiceToCache(GridServiceDeploymentCompoundFuture<String> res, ServiceConfiguration cfg)
throws IgniteCheckedException {
String name = cfg.getName();
GridServiceDeploymentFuture<String> fut = new GridServiceDeploymentFuture<>(cfg, name);
GridServiceDeploymentFuture<String> old = depFuts.putIfAbsent(name, fut);
try {
if (old != null) {
if (!old.configuration().equalsIgnoreNodeFilter(cfg))
throw new IgniteCheckedException("Failed to deploy service (service already exists with different " +
"configuration) [deployed=" + old.configuration() + ", new=" + cfg + ']');
else {
res.add(old, false);
return;
}
}
GridServiceDeploymentKey key = new GridServiceDeploymentKey(name);
GridServiceDeployment dep = (GridServiceDeployment)serviceCache().getAndPutIfAbsent(key,
new GridServiceDeployment(ctx.localNodeId(), cfg));
if (dep != null) {
if (!dep.configuration().equalsIgnoreNodeFilter(cfg)) {
throw new IgniteCheckedException("Failed to deploy service (service already exists with " +
"different configuration) [deployed=" + dep.configuration() + ", new=" + cfg + ']');
}
else {
res.add(fut, false);
Iterator<Cache.Entry<Object, Object>> it = serviceEntries(ServiceAssignmentsPredicate.INSTANCE);
while (it.hasNext()) {
Cache.Entry<Object, Object> e = it.next();
GridServiceAssignments assigns = (GridServiceAssignments)e.getValue();
if (assigns.name().equals(name)) {
fut.onDone();
depFuts.remove(name, fut);
break;
}
}
}
}
else
res.add(fut, true);
}
catch (IgniteCheckedException e) {
fut.onDone(e);
res.add(fut, false);
depFuts.remove(name, fut);
throw e;
}
}
/** {@inheritDoc} */
@Override public IgniteInternalFuture<?> cancel(String name) {
while (true) {
try {
return removeServiceFromCache(name).fut;
}
catch (IgniteException | IgniteCheckedException e) {
if (X.hasCause(e, ClusterTopologyCheckedException.class)) {
if (log.isDebugEnabled())
log.debug("Topology changed while cancelling service (will retry): " + e.getMessage());
}
else {
U.error(log, "Failed to undeploy service: " + name, e);
return new GridFinishedFuture<>(e);
}
}
}
}
/** {@inheritDoc} */
@Override public IgniteInternalFuture<?> cancelAll() {
Iterator<Cache.Entry<Object, Object>> it = serviceEntries(ServiceDeploymentPredicate.INSTANCE);
List<String> svcNames = new ArrayList<>();
while (it.hasNext()) {
GridServiceDeployment dep = (GridServiceDeployment)it.next().getValue();
svcNames.add(dep.configuration().getName());
}
return cancelAll(svcNames);
}
/** {@inheritDoc} */
@SuppressWarnings("unchecked")
@Override public IgniteInternalFuture<?> cancelAll(Collection<String> servicesNames) {
List<String> svcNamesCp = new ArrayList<>(servicesNames);
Collections.sort(svcNamesCp);
GridCompoundFuture res;
while (true) {
res = null;
List<String> toRollback = new ArrayList<>();
try (Transaction tx = serviceCache().txStart(PESSIMISTIC, READ_COMMITTED)) {
for (String name : servicesNames) {
if (res == null)
res = new GridCompoundFuture<>();
try {
CancelResult cr = removeServiceFromCache(name);
if (cr.rollback)
toRollback.add(name);
res.add(cr.fut);
}
catch (IgniteException | IgniteCheckedException e) {
if (X.hasCause(e, ClusterTopologyCheckedException.class))
throw e; // Retry.
else {
U.error(log, "Failed to undeploy service: " + name, e);
res.add(new GridFinishedFuture<>(e));
}
}
}
tx.commit();
break;
}
catch (IgniteException | IgniteCheckedException e) {
for (String name : toRollback)
undepFuts.remove(name).onDone(e);
if (X.hasCause(e, ClusterTopologyCheckedException.class)) {
if (log.isDebugEnabled())
log.debug("Topology changed while cancelling service (will retry): " + e.getMessage());
}
else
return new GridFinishedFuture<>(e);
}
}
if (res != null) {
res.markInitialized();
return res;
}
else
return new GridFinishedFuture<>();
}
/**
* @param name Name of service to remove from internal cache.
* @return Cancellation future and a flag whether it should be completed and removed on error.
* @throws IgniteCheckedException If operation failed.
*/
private CancelResult removeServiceFromCache(String name) throws IgniteCheckedException {
try {
ctx.security().authorize(name, SecurityPermission.SERVICE_CANCEL, null);
}
catch (SecurityException e) {
return new CancelResult(new GridFinishedFuture<>(e), false);
}
GridFutureAdapter<?> fut = new GridFutureAdapter<>();
GridFutureAdapter<?> old = undepFuts.putIfAbsent(name, fut);
if (old != null)
return new CancelResult(old, false);
else {
GridServiceDeploymentKey key = new GridServiceDeploymentKey(name);
try {
if (serviceCache().getAndRemove(key) == null) {
// Remove future from local map if service was not deployed.
undepFuts.remove(name, fut);
fut.onDone();
return new CancelResult(fut, false);
}
else
return new CancelResult(fut, true);
}
catch (IgniteCheckedException e) {
undepFuts.remove(name, fut);
fut.onDone(e);
throw e;
}
}
}
/** {@inheritDoc} */
@Override public Map<UUID, Integer> serviceTopology(String name, long timeout) throws IgniteCheckedException {
IgniteInternalCache<Object, Object> cache = serviceCache();
ClusterNode node = cache.affinity().mapKeyToNode(name);
final ServiceTopologyCallable call = new ServiceTopologyCallable(name);
return ctx.closure().callAsyncNoFailover(
GridClosureCallMode.BROADCAST,
call,
Collections.singletonList(node),
false,
timeout,
true).get();
}
/**
* @param cache Utility cache.
* @param svcName Service name.
* @return Service topology.
* @throws IgniteCheckedException In case of error.
*/
private static Map<UUID, Integer> serviceTopology(IgniteInternalCache<Object, Object> cache, String svcName)
throws IgniteCheckedException {
GridServiceAssignments val = (GridServiceAssignments)cache.get(new GridServiceAssignmentsKey(svcName));
return val != null ? val.assigns() : null;
}
/** {@inheritDoc} */
@Override public Collection<ServiceDescriptor> serviceDescriptors() {
Collection<ServiceDescriptor> descs = new ArrayList<>();
Iterator<Cache.Entry<Object, Object>> it = serviceEntries(ServiceDeploymentPredicate.INSTANCE);
while (it.hasNext()) {
Cache.Entry<Object, Object> e = it.next();
GridServiceDeployment dep = (GridServiceDeployment)e.getValue();
ServiceDescriptorImpl desc = new ServiceDescriptorImpl(dep);
try {
GridServiceAssignments assigns = (GridServiceAssignments)serviceCache().getForcePrimary(
new GridServiceAssignmentsKey(dep.configuration().getName()));
if (assigns != null) {
desc.topologySnapshot(assigns.assigns());
descs.add(desc);
}
}
catch (IgniteCheckedException ex) {
log.error("Failed to get assignments from replicated cache for service: " +
dep.configuration().getName(), ex);
}
}
return descs;
}
/** {@inheritDoc} */
@Override public <T> T service(String name) {
ctx.security().authorize(name, SecurityPermission.SERVICE_INVOKE, null);
Collection<ServiceContextImpl> ctxs;
synchronized (locSvcs) {
ctxs = locSvcs.get(name);
}
if (ctxs == null)
return null;
synchronized (ctxs) {
if (ctxs.isEmpty())
return null;
for (ServiceContextImpl ctx : ctxs) {
Service svc = ctx.service();
if (svc != null)
return (T)svc;
}
return null;
}
}
/** {@inheritDoc} */
@Override public ServiceContextImpl serviceContext(String name) {
Collection<ServiceContextImpl> ctxs;
synchronized (locSvcs) {
ctxs = locSvcs.get(name);
}
if (ctxs == null)
return null;
synchronized (ctxs) {
if (ctxs.isEmpty())
return null;
for (ServiceContextImpl ctx : ctxs) {
if (ctx.service() != null)
return ctx;
}
return null;
}
}
/** {@inheritDoc} */
@Override public <T> T serviceProxy(ClusterGroup prj, String name, Class<? super T> srvcCls, boolean sticky,
long timeout)
throws IgniteException {
ctx.security().authorize(name, SecurityPermission.SERVICE_INVOKE, null);
if (hasLocalNode(prj)) {
ServiceContextImpl ctx = serviceContext(name);
if (ctx != null) {
Service svc = ctx.service();
if (svc != null) {
if (!srvcCls.isAssignableFrom(svc.getClass()))
throw new IgniteException("Service does not implement specified interface [svcItf=" +
srvcCls.getName() + ", svcCls=" + svc.getClass().getName() + ']');
return (T)svc;
}
}
}
return new GridServiceProxy<T>(prj, name, srvcCls, sticky, timeout, ctx).proxy();
}
/**
* @param prj Grid nodes projection.
* @return Whether given projection contains any local node.
*/
private boolean hasLocalNode(ClusterGroup prj) {
for (ClusterNode n : prj.nodes()) {
if (n.isLocal())
return true;
}
return false;
}
/** {@inheritDoc} */
@Override public <T> Collection<T> services(String name) {
ctx.security().authorize(name, SecurityPermission.SERVICE_INVOKE, null);
Collection<ServiceContextImpl> ctxs;
synchronized (locSvcs) {
ctxs = locSvcs.get(name);
}
if (ctxs == null)
return null;
synchronized (ctxs) {
Collection<T> res = new ArrayList<>(ctxs.size());
for (ServiceContextImpl ctx : ctxs) {
Service svc = ctx.service();
if (svc != null)
res.add((T)svc);
}
return res;
}
}
/**
* Reassigns service to nodes.
*
* @param dep Service deployment.
* @param topVer Topology version.
* @throws IgniteCheckedException If failed.
*/
private void reassign(GridServiceDeployment dep, AffinityTopologyVersion topVer) throws IgniteCheckedException {
IgniteInternalCache<Object, Object> cache = serviceCache();
ServiceConfiguration cfg = dep.configuration();
Object nodeFilter = cfg.getNodeFilter();
if (nodeFilter != null)
ctx.resource().injectGeneric(nodeFilter);
int totalCnt = cfg.getTotalCount();
int maxPerNodeCnt = cfg.getMaxPerNodeCount();
String cacheName = cfg.getCacheName();
Object affKey = cfg.getAffinityKey();
while (true) {
GridServiceAssignments assigns = new GridServiceAssignments(cfg, dep.nodeId(), topVer.topologyVersion());
Collection<ClusterNode> nodes;
// Call node filter outside of transaction.
if (affKey == null) {
nodes = ctx.discovery().nodes(topVer);
if (assigns.nodeFilter() != null) {
Collection<ClusterNode> nodes0 = new ArrayList<>();
for (ClusterNode node : nodes) {
if (assigns.nodeFilter().apply(node))
nodes0.add(node);
}
nodes = nodes0;
}
}
else
nodes = null;
try (GridNearTxLocal tx = cache.txStartEx(PESSIMISTIC, REPEATABLE_READ)) {
GridServiceAssignmentsKey key = new GridServiceAssignmentsKey(cfg.getName());
GridServiceAssignments oldAssigns = (GridServiceAssignments)cache.get(key);
Map<UUID, Integer> cnts = new HashMap<>();
if (affKey != null) {
ClusterNode n = ctx.affinity().mapKeyToNode(cacheName, affKey, topVer);
if (n != null) {
int cnt = maxPerNodeCnt == 0 ? totalCnt == 0 ? 1 : totalCnt : maxPerNodeCnt;
cnts.put(n.id(), cnt);
}
}
else {
if (!nodes.isEmpty()) {
int size = nodes.size();
int perNodeCnt = totalCnt != 0 ? totalCnt / size : maxPerNodeCnt;
int remainder = totalCnt != 0 ? totalCnt % size : 0;
if (perNodeCnt >= maxPerNodeCnt && maxPerNodeCnt != 0) {
perNodeCnt = maxPerNodeCnt;
remainder = 0;
}
for (ClusterNode n : nodes)
cnts.put(n.id(), perNodeCnt);
assert perNodeCnt >= 0;
assert remainder >= 0;
if (remainder > 0) {
int cnt = perNodeCnt + 1;
if (oldAssigns != null) {
Collection<UUID> used = new HashSet<>();
// Avoid redundant moving of services.
for (Map.Entry<UUID, Integer> e : oldAssigns.assigns().entrySet()) {
// Do not assign services to left nodes.
if (ctx.discovery().node(e.getKey()) == null)
continue;
// If old count and new count match, then reuse the assignment.
if (e.getValue() == cnt) {
cnts.put(e.getKey(), cnt);
used.add(e.getKey());
if (--remainder == 0)
break;
}
}
if (remainder > 0) {
List<Map.Entry<UUID, Integer>> entries = new ArrayList<>(cnts.entrySet());
// Randomize.
Collections.shuffle(entries);
for (Map.Entry<UUID, Integer> e : entries) {
// Assign only the ones that have not been reused from previous assignments.
if (!used.contains(e.getKey())) {
if (e.getValue() < maxPerNodeCnt || maxPerNodeCnt == 0) {
e.setValue(e.getValue() + 1);
if (--remainder == 0)
break;
}
}
}
}
}
else {
List<Map.Entry<UUID, Integer>> entries = new ArrayList<>(cnts.entrySet());
// Randomize.
Collections.shuffle(entries);
for (Map.Entry<UUID, Integer> e : entries) {
e.setValue(e.getValue() + 1);
if (--remainder == 0)
break;
}
}
}
}
}
assigns.assigns(cnts);
cache.put(key, assigns);
tx.commit();
break;
}
catch (ClusterTopologyCheckedException e) {
if (log.isDebugEnabled())
log.debug("Topology changed while reassigning (will retry): " + e.getMessage());
U.sleep(10);
}
}
}
/**
* Redeploys local services based on assignments.
*
* @param assigns Assignments.
*/
private void redeploy(GridServiceAssignments assigns) {
if (assigns.topologyVersion() < ctx.discovery().topologyVersion()) {
if (log.isDebugEnabled())
log.debug("Skip outdated assignment [assigns=" + assigns +
", topVer=" + ctx.discovery().topologyVersion() + ']');
return;
}
String svcName = assigns.name();
Integer assignCnt = assigns.assigns().get(ctx.localNodeId());
if (assignCnt == null)
assignCnt = 0;
Collection<ServiceContextImpl> ctxs;
synchronized (locSvcs) {
ctxs = locSvcs.get(svcName);
if (ctxs == null)
locSvcs.put(svcName, ctxs = new ArrayList<>());
}
Collection<ServiceContextImpl> toInit = new ArrayList<>();
synchronized (ctxs) {
if (ctxs.size() > assignCnt) {
int cancelCnt = ctxs.size() - assignCnt;
cancel(ctxs, cancelCnt);
}
else if (ctxs.size() < assignCnt) {
int createCnt = assignCnt - ctxs.size();
for (int i = 0; i < createCnt; i++) {
ServiceContextImpl svcCtx = new ServiceContextImpl(assigns.name(),
UUID.randomUUID(),
assigns.cacheName(),
assigns.affinityKey(),
Executors.newSingleThreadExecutor(threadFactory));
ctxs.add(svcCtx);
toInit.add(svcCtx);
}
}
}
for (final ServiceContextImpl svcCtx : toInit) {
final Service svc;
try {
svc = copyAndInject(assigns.configuration());
// Initialize service.
svc.init(svcCtx);
svcCtx.service(svc);
}
catch (Throwable e) {
U.error(log, "Failed to initialize service (service will not be deployed): " + assigns.name(), e);
synchronized (ctxs) {
ctxs.removeAll(toInit);
}
if (e instanceof Error)
throw (Error)e;
if (e instanceof RuntimeException)
throw (RuntimeException)e;
return;
}
if (log.isInfoEnabled())
log.info("Starting service instance [name=" + svcCtx.name() + ", execId=" +
svcCtx.executionId() + ']');
// Start service in its own thread.
final ExecutorService exe = svcCtx.executor();
exe.execute(new Runnable() {
@Override public void run() {
try {
svc.execute(svcCtx);
}
catch (InterruptedException | IgniteInterruptedCheckedException ignore) {
if (log.isDebugEnabled())
log.debug("Service thread was interrupted [name=" + svcCtx.name() + ", execId=" +
svcCtx.executionId() + ']');
}
catch (IgniteException e) {
if (e.hasCause(InterruptedException.class) ||
e.hasCause(IgniteInterruptedCheckedException.class)) {
if (log.isDebugEnabled())
log.debug("Service thread was interrupted [name=" + svcCtx.name() +
", execId=" + svcCtx.executionId() + ']');
}
else {
U.error(log, "Service execution stopped with error [name=" + svcCtx.name() +
", execId=" + svcCtx.executionId() + ']', e);
}
}
catch (Throwable e) {
log.error("Service execution stopped with error [name=" + svcCtx.name() +
", execId=" + svcCtx.executionId() + ']', e);
if (e instanceof Error)
throw (Error)e;
}
finally {
// Suicide.
exe.shutdownNow();
}
}
});
}
}
/**
* @param cfg Service configuration.
* @return Copy of service.
* @throws IgniteCheckedException If failed.
*/
private Service copyAndInject(ServiceConfiguration cfg) throws IgniteCheckedException {
Marshaller m = ctx.config().getMarshaller();
if (cfg instanceof LazyServiceConfiguration) {
byte[] bytes = ((LazyServiceConfiguration)cfg).serviceBytes();
Service srvc = U.unmarshal(m, bytes, U.resolveClassLoader(null, ctx.config()));
ctx.resource().inject(srvc);
return srvc;
}
else {
Service svc = cfg.getService();
try {
byte[] bytes = U.marshal(m, svc);
Service cp = U.unmarshal(m, bytes, U.resolveClassLoader(svc.getClass().getClassLoader(), ctx.config()));
ctx.resource().inject(cp);
return cp;
}
catch (IgniteCheckedException e) {
U.error(log, "Failed to copy service (will reuse same instance): " + svc.getClass(), e);
return svc;
}
}
}
/**
* @param ctxs Contexts to cancel.
* @param cancelCnt Number of contexts to cancel.
*/
private void cancel(Iterable<ServiceContextImpl> ctxs, int cancelCnt) {
for (Iterator<ServiceContextImpl> it = ctxs.iterator(); it.hasNext(); ) {
ServiceContextImpl svcCtx = it.next();
// Flip cancelled flag.
svcCtx.setCancelled(true);
// Notify service about cancellation.
Service svc = svcCtx.service();
if (svc != null) {
try {
svc.cancel(svcCtx);
}
catch (Throwable e) {
log.error("Failed to cancel service (ignoring) [name=" + svcCtx.name() +
", execId=" + svcCtx.executionId() + ']', e);
if (e instanceof Error)
throw e;
}
finally {
try {
ctx.resource().cleanup(svc);
}
catch (IgniteCheckedException e) {
U.error(log, "Failed to clean up service (will ignore): " + svcCtx.name(), e);
}
}
}
// Close out executor thread for the service.
// This will cause the thread to be interrupted.
svcCtx.executor().shutdownNow();
it.remove();
if (log.isInfoEnabled())
log.info("Cancelled service instance [name=" + svcCtx.name() + ", execId=" +
svcCtx.executionId() + ']');
if (--cancelCnt == 0)
break;
}
}
/**
* @param p Entry predicate used to execute query from client node.
* @return Service deployment entries.
*/
@SuppressWarnings("unchecked")
private Iterator<Cache.Entry<Object, Object>> serviceEntries(IgniteBiPredicate<Object, Object> p) {
try {
IgniteInternalCache<Object, Object> cache = serviceCache();
GridCacheQueryManager qryMgr = cache.context().queries();
CacheQuery<Map.Entry<Object, Object>> qry = qryMgr.createScanQuery(p, null, false, null);
DiscoveryDataClusterState clusterState = ctx.state().clusterState();
if ((clusterState.hasBaselineTopology()
&& !CU.baselineNode(ctx.cluster().get().localNode(), clusterState))
|| !cache.context().affinityNode()) {
ClusterNode oldestSrvNode =
ctx.discovery().oldestAliveServerNode(AffinityTopologyVersion.NONE);
if (oldestSrvNode == null)
return new GridEmptyIterator<>();
qry.projection(ctx.cluster().get().forNode(oldestSrvNode));
}
else
qry.projection(ctx.cluster().get().forLocal());
GridCloseableIterator<Map.Entry<Object, Object>> iter = qry.executeScanQuery();
return cache.context().itHolder().iterator(iter,
new CacheIteratorConverter<Cache.Entry<Object, Object>, Map.Entry<Object, Object>>() {
@Override protected Cache.Entry<Object, Object> convert(Map.Entry<Object, Object> e) {
// Actually Scan Query returns Iterator<CacheQueryEntry> by default,
// CacheQueryEntry implements both Map.Entry and Cache.Entry interfaces.
return (Cache.Entry<Object, Object>)e;
}
@Override protected void remove(Cache.Entry<Object, Object> item) {
throw new UnsupportedOperationException();
}
});
}
catch (IgniteCheckedException e) {
throw new IgniteException(e);
}
}
/**
* Called right after utility cache is started and ready for the usage.
*/
public void onUtilityCacheStarted() {
synchronized (pendingJobCtxs) {
if (pendingJobCtxs.isEmpty())
return;
Iterator<ComputeJobContext> iter = pendingJobCtxs.iterator();
while (iter.hasNext()) {
iter.next().callcc();
iter.remove();
}
}
}
/**
* Service deployment listener.
*/
private class ServiceEntriesListener implements CacheEntryUpdatedListener<Object, Object> {
/** {@inheritDoc} */
@Override public void onUpdated(final Iterable<CacheEntryEvent<?, ?>> deps) {
GridSpinBusyLock busyLock = GridServiceProcessor.this.busyLock;
if (busyLock == null || !busyLock.enterBusy())
return;
try {
depExe.execute(new DepRunnable() {
@Override public void run0() {
onSystemCacheUpdated(deps);
}
});
}
finally {
busyLock.leaveBusy();
}
}
}
/**
* @param evts Update events.
*/
private void onSystemCacheUpdated(final Iterable<CacheEntryEvent<?, ?>> evts) {
for (CacheEntryEvent<?, ?> e : evts) {
if (e.getKey() instanceof GridServiceDeploymentKey)
processDeployment((CacheEntryEvent)e);
else if (e.getKey() instanceof GridServiceAssignmentsKey)
processAssignment((CacheEntryEvent)e);
}
}
/**
* @param e Entry.
*/
private void processDeployment(CacheEntryEvent<GridServiceDeploymentKey, GridServiceDeployment> e) {
GridServiceDeployment dep;
try {
dep = e.getValue();
}
catch (IgniteException ex) {
if (X.hasCause(ex, ClassNotFoundException.class))
return;
else
throw ex;
}
if (e.getEventType() != REMOVED) {
svcName.set(dep.configuration().getName());
// Ignore other utility cache events.
AffinityTopologyVersion topVer = ctx.discovery().topologyVersionEx();
ClusterNode oldest = U.oldest(ctx.discovery().nodes(topVer), null);
// Process deployment on coordinator only.
if (oldest.isLocal())
onDeployment(dep, topVer);
}
// Handle undeployment.
else {
String name = e.getKey().name();
undeploy(name);
// Finish deployment futures if undeployment happened.
GridFutureAdapter<?> fut = depFuts.remove(name);
if (fut != null)
fut.onDone();
// Complete undeployment future.
fut = undepFuts.remove(name);
if (fut != null)
fut.onDone();
GridServiceAssignmentsKey key = new GridServiceAssignmentsKey(name);
// Remove assignment on primary node in case of undeploy.
IgniteInternalCache<Object, Object> cache = serviceCache();
if (cache.cache().affinity().isPrimary(ctx.discovery().localNode(), key)) {
try {
cache.getAndRemove(key);
}
catch (IgniteCheckedException ex) {
U.error(log, "Failed to remove assignments for undeployed service: " + name, ex);
}
}
}
}
/**
* Deployment callback.
*
* @param dep Service deployment.
* @param topVer Topology version.
*/
private void onDeployment(final GridServiceDeployment dep, final AffinityTopologyVersion topVer) {
// Retry forever.
try {
AffinityTopologyVersion newTopVer = ctx.discovery().topologyVersionEx();
// If topology version changed, reassignment will happen from topology event.
if (newTopVer.equals(topVer))
reassign(dep, topVer);
}
catch (IgniteCheckedException e) {
if (!(e instanceof ClusterTopologyCheckedException))
log.error("Failed to do service reassignment (will retry): " + dep.configuration().getName(), e);
AffinityTopologyVersion newTopVer = ctx.discovery().topologyVersionEx();
if (!newTopVer.equals(topVer)) {
assert newTopVer.compareTo(topVer) > 0;
// Reassignment will happen from topology event.
return;
}
ctx.timeout().addTimeoutObject(new GridTimeoutObject() {
private IgniteUuid id = IgniteUuid.randomUuid();
private long start = System.currentTimeMillis();
@Override public IgniteUuid timeoutId() {
return id;
}
@Override public long endTime() {
return start + RETRY_TIMEOUT;
}
@Override public void onTimeout() {
depExe.execute(new DepRunnable() {
@Override public void run0() {
onDeployment(dep, topVer);
}
});
}
});
}
}
/**
* Topology listener.
*/
private class TopologyListener implements DiscoveryEventListener {
/** */
private volatile AffinityTopologyVersion currTopVer = null;
/**
* Check that listening-in topology version is the latest and wait until exchange is finished.
*
* @param initTopVer listening-in topology version.
* @return {@code True} if current event is not last and should be skipped.
*/
private boolean skipExchange(final AffinityTopologyVersion initTopVer) {
AffinityTopologyVersion pendingTopVer = null;
AffinityTopologyVersion newTopVer;
if (!initTopVer.equals(newTopVer = currTopVer))
pendingTopVer = newTopVer;
else {
IgniteInternalFuture<?> affReadyFut = ctx.cache().context().exchange().affinityReadyFuture(initTopVer);
if (affReadyFut != null) {
try {
affReadyFut.get();
}
catch (IgniteCheckedException e) {
U.warn(log, "Failed to wait for affinity ready future " +
"(the assignment will be recalculated anyway):" + e.toString());
}
}
// If exchange already moved forward - skip current version.
if (!initTopVer.equals(newTopVer = currTopVer))
pendingTopVer = newTopVer;
}
boolean skipExchange = pendingTopVer != null;
if (skipExchange && log.isInfoEnabled()) {
log.info("Service processor detected a topology change during " +
"assignments calculation (will abort current iteration and " +
"re-calculate on the newer version): " +
"[topVer=" + initTopVer + ", newTopVer=" + pendingTopVer + ']');
}
return skipExchange;
}
/** {@inheritDoc} */
@Override public void onEvent(final DiscoveryEvent evt, final DiscoCache discoCache) {
GridSpinBusyLock busyLock = GridServiceProcessor.this.busyLock;
if (busyLock == null || !busyLock.enterBusy())
return;
try {
final AffinityTopologyVersion topVer;
if (evt instanceof DiscoveryCustomEvent) {
DiscoveryCustomMessage msg = ((DiscoveryCustomEvent)evt).customMessage();
if (msg instanceof CacheAffinityChangeMessage) {
if (!((CacheAffinityChangeMessage)msg).exchangeNeeded())
return;
}
else if (msg instanceof DynamicCacheChangeBatch) {
if (!((DynamicCacheChangeBatch)msg).exchangeNeeded())
return;
}
else
return;
if (msg instanceof MetadataUpdateProposedMessage || msg instanceof MetadataUpdateAcceptedMessage)
return;
topVer = ((DiscoveryCustomEvent)evt).affinityTopologyVersion();
}
else
topVer = new AffinityTopologyVersion((evt).topologyVersion(), 0);
currTopVer = topVer;
depExe.execute(new DepRunnable() {
@Override public void run0() {
// In case the cache instance isn't tracked by DiscoveryManager anymore.
discoCache.updateAlives(ctx.discovery());
ClusterNode oldest = discoCache.oldestAliveServerNode();
if (oldest != null && oldest.isLocal()) {
final Collection<GridServiceDeployment> retries = new ConcurrentLinkedQueue<>();
if (ctx.deploy().enabled())
ctx.cache().context().deploy().ignoreOwnership(true);
try {
Iterator<Cache.Entry<Object, Object>> it = serviceEntries(
ServiceDeploymentPredicate.INSTANCE);
while (it.hasNext()) {
// If topology changed again, let next event handle it.
if (skipExchange(topVer))
return;
Cache.Entry<Object, Object> e = it.next();
GridServiceDeployment dep = (GridServiceDeployment)e.getValue();
try {
svcName.set(dep.configuration().getName());
reassign(dep, topVer);
}
catch (IgniteCheckedException ex) {
if (!(ex instanceof ClusterTopologyCheckedException))
LT.error(log, ex, "Failed to do service reassignment (will retry): " +
dep.configuration().getName());
retries.add(dep);
}
}
}
finally {
if (ctx.deploy().enabled())
ctx.cache().context().deploy().ignoreOwnership(false);
}
if (!retries.isEmpty())
onReassignmentFailed(topVer, retries);
}
Iterator<Cache.Entry<Object, Object>> it = serviceEntries(ServiceAssignmentsPredicate.INSTANCE);
// Clean up zombie assignments.
IgniteInternalCache<Object, Object> cache = serviceCache();
while (it.hasNext()) {
// If topology changed again, let next event handle it.
if (skipExchange(topVer))
return;
Cache.Entry<Object, Object> e = it.next();
if (cache.context().affinity().primaryByKey(ctx.grid().localNode(), e.getKey(), topVer)) {
String name = ((GridServiceAssignmentsKey)e.getKey()).name();
try {
if (cache.get(new GridServiceDeploymentKey(name)) == null) {
if (log.isDebugEnabled())
log.debug("Removed zombie assignments: " + e.getValue());
cache.getAndRemove(e.getKey());
}
}
catch (IgniteCheckedException ex) {
U.error(log, "Failed to clean up zombie assignments for service: " + name, ex);
}
}
}
}
});
}
finally {
busyLock.leaveBusy();
}
}
/**
* Handler for reassignment failures.
*
* @param topVer Topology version.
* @param retries Retries.
*/
private void onReassignmentFailed(final AffinityTopologyVersion topVer,
final Collection<GridServiceDeployment> retries) {
GridSpinBusyLock busyLock = GridServiceProcessor.this.busyLock;
if (busyLock == null || !busyLock.enterBusy())
return;
try {
// If topology changed again, let next event handle it.
if (ctx.discovery().topologyVersionEx().equals(topVer))
return;
for (Iterator<GridServiceDeployment> it = retries.iterator(); it.hasNext(); ) {
GridServiceDeployment dep = it.next();
try {
svcName.set(dep.configuration().getName());
reassign(dep, topVer);
it.remove();
}
catch (IgniteCheckedException e) {
if (!(e instanceof ClusterTopologyCheckedException))
LT.error(log, e, "Failed to do service reassignment (will retry): " +
dep.configuration().getName());
}
}
if (!retries.isEmpty()) {
ctx.timeout().addTimeoutObject(new GridTimeoutObject() {
private IgniteUuid id = IgniteUuid.randomUuid();
private long start = System.currentTimeMillis();
@Override public IgniteUuid timeoutId() {
return id;
}
@Override public long endTime() {
return start + RETRY_TIMEOUT;
}
@Override public void onTimeout() {
depExe.execute(new Runnable() {
@Override public void run() {
onReassignmentFailed(topVer, retries);
}
});
}
});
}
}
finally {
busyLock.leaveBusy();
}
}
}
/**
* @param e Entry.
*/
private void processAssignment(CacheEntryEvent<GridServiceAssignmentsKey, GridServiceAssignments> e) {
GridServiceAssignments assigns;
try {
assigns = e.getValue();
}
catch (IgniteException ex) {
if (X.hasCause(ex, ClassNotFoundException.class))
return;
else
throw ex;
}
if (e.getEventType() != REMOVED) {
svcName.set(assigns.name());
Throwable t = null;
try {
redeploy(assigns);
}
catch (Error | RuntimeException th) {
t = th;
}
GridServiceDeploymentFuture<String> fut = depFuts.get(assigns.name());
if (fut != null && fut.configuration().equalsIgnoreNodeFilter(assigns.configuration())) {
depFuts.remove(assigns.name(), fut);
// Complete deployment futures once the assignments have been stored in cache.
fut.onDone(null, t);
}
}
// Handle undeployment.
else
undeploy(e.getKey().name());
}
/**
* @param name Name.
*/
private void undeploy(String name) {
svcName.set(name);
Collection<ServiceContextImpl> ctxs;
synchronized (locSvcs) {
ctxs = locSvcs.remove(name);
}
if (ctxs != null) {
synchronized (ctxs) {
cancel(ctxs, ctxs.size());
}
}
}
/**
*
*/
private static class CancelResult {
/** */
IgniteInternalFuture<?> fut;
/** */
boolean rollback;
/**
* @param fut Future.
* @param rollback {@code True} if service was cancelled during current call.
*/
CancelResult(IgniteInternalFuture<?> fut, boolean rollback) {
this.fut = fut;
this.rollback = rollback;
}
}
/**
*
*/
private abstract class DepRunnable implements Runnable {
/** {@inheritDoc} */
@Override public void run() {
GridSpinBusyLock busyLock = GridServiceProcessor.this.busyLock;
if (busyLock == null || !busyLock.enterBusy())
return;
// Won't block ServiceProcessor stopping process.
busyLock.leaveBusy();
svcName.set(null);
try {
run0();
}
catch (Throwable t) {
log.error("Error when executing service: " + svcName.get(), t);
if (t instanceof Error)
throw t;
}
finally {
svcName.set(null);
}
}
/**
* Abstract run method protected by busy lock.
*/
public abstract void run0();
}
/**
*
*/
static class ServiceDeploymentPredicate implements IgniteBiPredicate<Object, Object> {
/** */
static final ServiceDeploymentPredicate INSTANCE = new ServiceDeploymentPredicate();
/** */
private static final long serialVersionUID = 0L;
/** {@inheritDoc} */
@Override public boolean apply(Object key, Object val) {
return key instanceof GridServiceDeploymentKey;
}
/** {@inheritDoc} */
@Override public String toString() {
return S.toString(ServiceDeploymentPredicate.class, this);
}
}
/**
*
*/
static class ServiceAssignmentsPredicate implements IgniteBiPredicate<Object, Object> {
/** */
static final ServiceAssignmentsPredicate INSTANCE = new ServiceAssignmentsPredicate();
/** */
private static final long serialVersionUID = 0L;
/** {@inheritDoc} */
@Override public boolean apply(Object key, Object val) {
return key instanceof GridServiceAssignmentsKey;
}
/** {@inheritDoc} */
@Override public String toString() {
return S.toString(ServiceAssignmentsPredicate.class, this);
}
}
/**
*/
@GridInternal
private static class ServiceTopologyCallable implements IgniteCallable<Map<UUID, Integer>> {
/** */
private static final long serialVersionUID = 0L;
/** */
private final String svcName;
/** */
private transient boolean waitedCacheInit;
/** */
@IgniteInstanceResource
private IgniteEx ignite;
/** */
@JobContextResource
private transient ComputeJobContext jCtx;
/** */
@LoggerResource
private transient IgniteLogger log;
/**
* @param svcName Service name.
*/
public ServiceTopologyCallable(String svcName) {
this.svcName = svcName;
}
/** {@inheritDoc} */
@Override public Map<UUID, Integer> call() throws Exception {
IgniteInternalCache<Object, Object> cache = ignite.context().cache().utilityCache();
if (cache == null) {
List<ComputeJobContext> pendingCtxs = ((GridServiceProcessor)ignite.context().service()).pendingJobCtxs;
synchronized (pendingCtxs) {
// Double check cache reference after lock acqusition.
cache = ignite.context().cache().utilityCache();
if (cache == null) {
if (!waitedCacheInit) {
log.debug("Utility cache hasn't been initialized yet. Waiting.");
// waiting for a minute for cache initialization.
jCtx.holdcc(60 * 1000);
pendingCtxs.add(jCtx);
waitedCacheInit = true;
return null;
}
else {
log.error("Failed to gather service topology. Utility " +
"cache initialization is stuck.");
throw new IgniteCheckedException("Failed to gather service topology. Utility " +
"cache initialization is stuck.");
}
}
}
}
return serviceTopology(cache, svcName);
}
}
}
| {
"content_hash": "637924cc1536bba7388d302077b7a031",
"timestamp": "",
"source": "github",
"line_count": 2116,
"max_line_length": 122,
"avg_line_length": 35.77882797731569,
"alnum_prop": 0.5359407196069108,
"repo_name": "ptupitsyn/ignite",
"id": "2b6e05098824d7b0920351e623c62d3efb22560c",
"size": "76510",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "modules/core/src/main/java/org/apache/ignite/internal/processors/service/GridServiceProcessor.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Batchfile",
"bytes": "61156"
},
{
"name": "C",
"bytes": "5286"
},
{
"name": "C#",
"bytes": "6134000"
},
{
"name": "C++",
"bytes": "3594158"
},
{
"name": "CSS",
"bytes": "304650"
},
{
"name": "Dockerfile",
"bytes": "14859"
},
{
"name": "Groovy",
"bytes": "15081"
},
{
"name": "HTML",
"bytes": "1454824"
},
{
"name": "Java",
"bytes": "39370496"
},
{
"name": "JavaScript",
"bytes": "1756771"
},
{
"name": "M4",
"bytes": "21724"
},
{
"name": "Makefile",
"bytes": "121163"
},
{
"name": "PHP",
"bytes": "486991"
},
{
"name": "PLpgSQL",
"bytes": "623"
},
{
"name": "PowerShell",
"bytes": "12344"
},
{
"name": "Python",
"bytes": "340696"
},
{
"name": "Scala",
"bytes": "1011929"
},
{
"name": "Shell",
"bytes": "615741"
},
{
"name": "Smalltalk",
"bytes": "1908"
},
{
"name": "TypeScript",
"bytes": "472483"
}
],
"symlink_target": ""
} |
package com.google.code.linkedinapi.schema.xpp;
import java.io.IOException;
import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;
import org.xmlpull.v1.XmlSerializer;
import com.google.code.linkedinapi.schema.PostTypeCode;
import com.google.code.linkedinapi.schema.Type;
public class TypeImpl
extends BaseSchemaEntity implements Type
{
private final static long serialVersionUID = 2461660169443089969L;
protected PostTypeCode code;
public PostTypeCode getCode() {
return code;
}
public void setCode(PostTypeCode value) {
this.code = value;
}
@Override
public void init(XmlPullParser parser) throws IOException, XmlPullParserException {
parser.require(XmlPullParser.START_TAG, null, null);
while (parser.nextTag() == XmlPullParser.START_TAG) {
String name = parser.getName();
if (name.equals("code")) {
setCode(PostTypeCode.fromValue(XppUtils.getElementValueFromNode(parser)));
} else {
// Consume something we don't understand.
LOG.warning("Found tag that we don't recognize: " + name);
XppUtils.skipSubTree(parser);
}
}
}
@Override
public void toXml(XmlSerializer serializer) throws IOException {
XmlSerializer element = serializer.startTag(null, "category");
XppUtils.setElementValueToNode(element, "code", getCode());
serializer.endTag(null, "category");
}
}
| {
"content_hash": "8658aee6d86afa788801100b5ac500f2",
"timestamp": "",
"source": "github",
"line_count": 51,
"max_line_length": 90,
"avg_line_length": 31.313725490196077,
"alnum_prop": 0.6443331246086412,
"repo_name": "shisoft/LinkedIn-J",
"id": "5584f2b85d7b445a77f8d2d59f495b0279951bb2",
"size": "2224",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "core/src/main/java/com/google/code/linkedinapi/schema/xpp/TypeImpl.java",
"mode": "33188",
"license": "apache-2.0",
"language": [],
"symlink_target": ""
} |
import unittest
from mock import patch
import dbt.flags as flags
from dbt.adapters.bigquery import BigQueryAdapter
from dbt.adapters.bigquery.relation import BigQueryRelation
import dbt.exceptions
from dbt.logger import GLOBAL_LOGGER as logger # noqa
fake_conn = {"handle": None, "state": "open", "type": "bigquery"}
class TestBigQueryAdapter(unittest.TestCase):
def setUp(self):
flags.STRICT_MODE = True
self.oauth_profile = {
"type": "bigquery",
"method": "oauth",
"project": 'dbt-unit-000000',
"schema": "dummy_schema",
}
self.service_account_profile = {
"type": "bigquery",
"method": "service-account",
"project": 'dbt-unit-000000',
"schema": "dummy_schema",
"keyfile": "/tmp/dummy-service-account.json",
}
@patch('dbt.adapters.bigquery.BigQueryAdapter.open_connection', return_value=fake_conn)
def test_acquire_connection_oauth_validations(self, mock_open_connection):
try:
connection = BigQueryAdapter.acquire_connection(self.oauth_profile, 'dummy')
self.assertEquals(connection.get('type'), 'bigquery')
except dbt.exceptions.ValidationException as e:
self.fail('got ValidationException: {}'.format(str(e)))
except BaseException as e:
raise
self.fail('validation failed with unknown exception: {}'.format(str(e)))
mock_open_connection.assert_called_once()
@patch('dbt.adapters.bigquery.BigQueryAdapter.open_connection', return_value=fake_conn)
def test_acquire_connection_service_account_validations(self, mock_open_connection):
try:
connection = BigQueryAdapter.acquire_connection(self.service_account_profile, 'dummy')
self.assertEquals(connection.get('type'), 'bigquery')
except dbt.exceptions.ValidationException as e:
self.fail('got ValidationException: {}'.format(str(e)))
except BaseException as e:
raise
self.fail('validation failed with unknown exception: {}'.format(str(e)))
mock_open_connection.assert_called_once()
class TestBigQueryRelation(unittest.TestCase):
def setUp(self):
flags.STRICT_MODE = True
def test_view_temp_relation(self):
kwargs = {
'type': None,
'path': {
'project': 'test-project',
'schema': 'test_schema',
'identifier': 'my_view'
},
'table_name': 'my_view__dbt_tmp',
'quote_policy': {
'identifier': False
}
}
BigQueryRelation(**kwargs)
def test_view_relation(self):
kwargs = {
'type': 'view',
'path': {
'project': 'test-project',
'schema': 'test_schema',
'identifier': 'my_view'
},
'table_name': 'my_view',
'quote_policy': {
'identifier': True,
'schema': True
}
}
BigQueryRelation(**kwargs)
def test_table_relation(self):
kwargs = {
'type': 'table',
'path': {
'project': 'test-project',
'schema': 'test_schema',
'identifier': 'generic_table'
},
'table_name': 'generic_table',
'quote_policy': {
'identifier': True,
'schema': True
}
}
BigQueryRelation(**kwargs)
def test_external_source_relation(self):
kwargs = {
'type': 'external',
'path': {
'project': 'test-project',
'schema': 'test_schema',
'identifier': 'sheet'
},
'table_name': 'sheet',
'quote_policy': {
'identifier': True,
'schema': True
}
}
BigQueryRelation(**kwargs)
def test_invalid_relation(self):
kwargs = {
'type': 'invalid-type',
'path': {
'project': 'test-project',
'schema': 'test_schema',
'identifier': 'my_invalid_id'
},
'table_name': 'my_invalid_id',
'quote_policy': {
'identifier': False,
'schema': True
}
}
with self.assertRaises(dbt.exceptions.ValidationException):
BigQueryRelation(**kwargs)
| {
"content_hash": "2032fd8e5b7b885b07a930953b067e89",
"timestamp": "",
"source": "github",
"line_count": 146,
"max_line_length": 98,
"avg_line_length": 31.410958904109588,
"alnum_prop": 0.5244221543829045,
"repo_name": "nave91/dbt",
"id": "1ca78796141c33b1f9a71e9b66d6d89f5b0db672",
"size": "4586",
"binary": false,
"copies": "1",
"ref": "refs/heads/development",
"path": "test/unit/test_bigquery_adapter.py",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Makefile",
"bytes": "814"
},
{
"name": "Python",
"bytes": "447357"
},
{
"name": "Shell",
"bytes": "617"
}
],
"symlink_target": ""
} |
//******************************************************************************************************
// IsolatedQueueTest.cs - Gbtc
//
// Copyright © 2013, Grid Protection Alliance. All Rights Reserved.
//
// Licensed to the Grid Protection Alliance (GPA) under one or more contributor license agreements. See
// the NOTICE file distributed with this work for additional information regarding copyright ownership.
// The GPA licenses this file to you under the MIT License (MIT), the "License"; you may
// not use this file except in compliance with the License. You may obtain a copy of the License at:
//
// http://www.opensource.org/licenses/MIT
//
// Unless agreed to in writing, the subject software distributed under the License is distributed on an
// "AS-IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. Refer to the
// License for the specific language governing permissions and limitations.
//
// Code Modification History:
// ----------------------------------------------------------------------------------------------------
// 1/4/2013 - Steven E. Chisholm
// Generated original version of source code.
//
//******************************************************************************************************
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Diagnostics;
using System.Threading;
using GSF.Collections;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace GSF.Core.Tests.GSF.Collections
{
[TestClass]
public class IsolatedQueueTest
{
private IsolatedQueue<int> m_collection;
private const int cnt = 1000000;
private ManualResetEvent m_wait;
[TestMethod]
public void BenchmarkWrite()
{
string value = null;
int x = 0;
const int cnt = 10000;
const int loop = 10000;
List<string> items = new List<string>(cnt);
for (x = 0; x < cnt; x++)
{
items.Add(x.ToString());
}
var queue = new IsolatedQueue<string>();
Stopwatch swDequeue = new Stopwatch();
Stopwatch swEnqueue = new Stopwatch();
for (int repeat = 0; repeat < loop; repeat++)
{
swEnqueue.Start();
foreach (var item in items)
queue.Enqueue(item);
swEnqueue.Stop();
swDequeue.Start();
while (queue.TryDequeue(out value))
;
swDequeue.Stop();
}
swEnqueue.Reset();
swDequeue.Reset();
for (int repeat = 0; repeat < loop; repeat++)
{
swEnqueue.Start();
foreach (var item in items)
queue.Enqueue(item);
swEnqueue.Stop();
swDequeue.Start();
while (queue.TryDequeue(out value))
;
swDequeue.Stop();
}
System.Console.WriteLine("Enqueue " + (cnt * loop / swEnqueue.Elapsed.TotalSeconds / 1000000));
System.Console.WriteLine("Dequeue " + (cnt * loop / swDequeue.Elapsed.TotalSeconds / 1000000));
System.Console.WriteLine(swDequeue.Elapsed.TotalSeconds);
}
[TestMethod]
public void BenchmarkBulkWrite()
{
//string value = null;
//int x = 0;
const int cnt = 10000;
const int loop = 10000;
byte[] items = new byte[cnt];
byte[] itemsRead = new byte[cnt];
var queue = new IsolatedQueue<byte>();
Stopwatch swDequeue = new Stopwatch();
Stopwatch swEnqueue = new Stopwatch();
for (int repeat = 0; repeat < loop; repeat++)
{
swEnqueue.Start();
queue.Enqueue(items, 0, items.Length);
swEnqueue.Stop();
swDequeue.Start();
while (queue.Dequeue(itemsRead, 0, items.Length) > 0)
;
swDequeue.Stop();
}
swEnqueue.Reset();
swDequeue.Reset();
for (int repeat = 0; repeat < loop; repeat++)
{
swEnqueue.Start();
queue.Enqueue(items, 0, items.Length);
swEnqueue.Stop();
swDequeue.Start();
while (queue.Dequeue(itemsRead, 0, items.Length) > 0)
;
swDequeue.Stop();
}
System.Console.WriteLine("Enqueue " + (cnt * loop / swEnqueue.Elapsed.TotalSeconds / 1000000));
System.Console.WriteLine("Dequeue " + (cnt * loop / swDequeue.Elapsed.TotalSeconds / 1000000));
System.Console.WriteLine(swDequeue.Elapsed.TotalSeconds);
}
[TestMethod]
public void BenchmarkConcurrentQueue()
{
string value = null;
int x = 0;
const int cnt = 10000;
const int loop = 5000;
List<string> items = new List<string>(cnt);
for (x = 0; x < cnt; x++)
{
items.Add(x.ToString());
}
var queue = new ConcurrentQueue<string>();
Stopwatch swDequeue = new Stopwatch();
Stopwatch swEnqueue = new Stopwatch();
for (int repeat = 0; repeat < loop; repeat++)
{
swEnqueue.Start();
foreach (var item in items)
queue.Enqueue(item);
swEnqueue.Stop();
swDequeue.Start();
while (queue.TryDequeue(out value))
;
swDequeue.Stop();
}
swEnqueue.Reset();
swDequeue.Reset();
for (int repeat = 0; repeat < loop; repeat++)
{
swEnqueue.Start();
foreach (var item in items)
queue.Enqueue(item);
swEnqueue.Stop();
swDequeue.Start();
while (queue.TryDequeue(out value))
;
swDequeue.Stop();
}
System.Console.WriteLine("Enqueue " + (cnt * loop / swEnqueue.Elapsed.TotalSeconds / 1000000));
System.Console.WriteLine("Dequeue " + (cnt * loop / swDequeue.Elapsed.TotalSeconds / 1000000));
System.Console.WriteLine(swDequeue.Elapsed.TotalSeconds);
}
[TestMethod]
public void Test()
{
m_wait = new ManualResetEvent(false);
m_collection = new IsolatedQueue<int>();
ThreadPool.QueueUserWorkItem(RunTwo);
m_wait.WaitOne();
m_wait.Reset();
Stopwatch sw = new Stopwatch();
sw.Start();
for (int x = 0; x < cnt; x++)
{
if (x % 10000 == 0)
{
System.Console.WriteLine(m_collection.Count);
Thread.Sleep(1);
}
m_collection.Enqueue(x);
}
sw.Stop();
System.Console.WriteLine(sw.Elapsed.TotalSeconds);
m_wait.WaitOne();
}
private void RunTwo(object state)
{
m_wait.Set();
//SpinWait wait = new SpinWait();
//Thread.Sleep(1000);
Stopwatch sw = new Stopwatch();
sw.Start();
int value = 0;
int count = 0;
int countRepeats = 0;
while (count < cnt)
{
while (m_collection.TryDequeue(out value))
{
Assert.AreEqual(count, value);
count++;
}
countRepeats++;
Thread.Sleep(1);
}
sw.Stop();
System.Console.WriteLine(sw.Elapsed.TotalSeconds);
System.Console.WriteLine(countRepeats);
m_wait.Set();
Assert.AreEqual(count, cnt);
}
[TestMethod]
public void TestBulk()
{
int[] sendBuffer = new int[3];
m_wait = new ManualResetEvent(false);
m_collection = new IsolatedQueue<int>();
ThreadPool.QueueUserWorkItem(RunTwoBulk);
m_wait.WaitOne();
m_wait.Reset();
Stopwatch sw = new Stopwatch();
sw.Start();
for (int x = 0; x < cnt; x++)
{
if (x % 10000 == 0)
{
System.Console.WriteLine(m_collection.Count);
Thread.Sleep(1);
}
sendBuffer[0] = x;
sendBuffer[1] = x;
sendBuffer[2] = x;
m_collection.Enqueue(sendBuffer, 0, 3);
}
sw.Stop();
System.Console.WriteLine(sw.Elapsed.TotalSeconds);
m_wait.WaitOne();
}
private void RunTwoBulk(object state)
{
m_wait.Set();
//SpinWait wait = new SpinWait();
//Thread.Sleep(1000);
Stopwatch sw = new Stopwatch();
sw.Start();
int value = 0;
int count = 0;
int countRepeats = 0;
while (count < cnt)
{
while (m_collection.TryDequeue(out value))
{
if (value != count)
throw new Exception();
while (!m_collection.TryDequeue(out value)) ;
if (value != count)
throw new Exception();
while (!m_collection.TryDequeue(out value)) ;
if (value != count)
throw new Exception();
count++;
}
countRepeats++;
Thread.Sleep(1);
}
sw.Stop();
System.Console.WriteLine(sw.Elapsed.TotalSeconds);
System.Console.WriteLine(countRepeats);
m_wait.Set();
Assert.AreEqual(count, cnt);
}
[TestMethod]
public void TestCount()
{
m_collection = new IsolatedQueue<int>();
int value = 0;
long count = 0;
for (int x = 0; x < 100000; x++)
{
if (m_collection.Count != count)
Assert.Fail("Count is wrong");
m_collection.Enqueue(x);
count++;
if (x % 10 == 0)
{
m_collection.TryDequeue(out value);
{
count--;
if (m_collection.Count != count)
Assert.Fail("Count is wrong");
}
}
}
while (m_collection.TryDequeue(out value))
{
count--;
if (m_collection.Count != count)
Assert.Fail("Count is wrong");
}
}
[TestMethod]
public void TestBulkDequeue()
{
m_wait = new ManualResetEvent(false);
m_collection = new IsolatedQueue<int>();
ThreadPool.QueueUserWorkItem(RunTwoBulkDequeue);
m_wait.WaitOne();
m_wait.Reset();
Stopwatch sw = new Stopwatch();
sw.Start();
for (int x = 0; x < cnt; x++)
{
if (x % 10000 == 0)
{
System.Console.WriteLine(m_collection.Count);
Thread.Sleep(1);
}
m_collection.Enqueue(x);
}
sw.Stop();
System.Console.WriteLine(sw.Elapsed.TotalSeconds);
m_wait.WaitOne();
}
private void RunTwoBulkDequeue(object state)
{
m_wait.Set();
//SpinWait wait = new SpinWait();
//Thread.Sleep(1000);
Stopwatch sw = new Stopwatch();
sw.Start();
const int ArrayCount = 140;
int[] array = new int[ArrayCount];
int count = 0;
int countRepeats = 0;
while (count < cnt)
{
int totalCount = 0;
ReReadNow:
int itemCount = m_collection.Dequeue(array, 0, ArrayCount);
totalCount += itemCount;
if (itemCount > 0)
{
for (int x = 0; x < itemCount; x++)
{
Assert.AreEqual(array[x], count);
count++;
}
if (itemCount == ArrayCount)
goto ReReadNow;
}
System.Console.WriteLine("Dequeued: " + totalCount);
countRepeats++;
Thread.Sleep(1);
}
sw.Stop();
System.Console.WriteLine(sw.Elapsed.TotalSeconds);
System.Console.WriteLine(countRepeats);
m_wait.Set();
Assert.AreEqual(count, cnt);
}
}
}
| {
"content_hash": "c2e03e40a7d3b5678d34fe13f7907df3",
"timestamp": "",
"source": "github",
"line_count": 433,
"max_line_length": 107,
"avg_line_length": 30.879907621247114,
"alnum_prop": 0.4562859920723955,
"repo_name": "rmc00/gsf",
"id": "4591bd5543e8d2788608fa498c15eac5833ab1c5",
"size": "13374",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "Source/Libraries/Tests/GSF.Core.Tests/GSF.Collections/IsolatedQueueTest.cs",
"mode": "33261",
"license": "mit",
"language": [
{
"name": "ASP",
"bytes": "17182"
},
{
"name": "Batchfile",
"bytes": "8635"
},
{
"name": "C",
"bytes": "24478"
},
{
"name": "C#",
"bytes": "30052352"
},
{
"name": "C++",
"bytes": "135084"
},
{
"name": "CMake",
"bytes": "3519"
},
{
"name": "CSS",
"bytes": "4763"
},
{
"name": "HTML",
"bytes": "3914"
},
{
"name": "Java",
"bytes": "955418"
},
{
"name": "JavaScript",
"bytes": "1274735"
},
{
"name": "Objective-C",
"bytes": "173"
},
{
"name": "PLSQL",
"bytes": "107859"
},
{
"name": "PLpgSQL",
"bytes": "88792"
},
{
"name": "Pascal",
"bytes": "515"
},
{
"name": "SQLPL",
"bytes": "186015"
},
{
"name": "ShaderLab",
"bytes": "137"
},
{
"name": "Shell",
"bytes": "11035"
},
{
"name": "Smalltalk",
"bytes": "8510"
},
{
"name": "Visual Basic",
"bytes": "72875"
},
{
"name": "XSLT",
"bytes": "1070"
}
],
"symlink_target": ""
} |
CSL Styles Distribution
======================
This repository is a copy of [citation-style-language/styles](https://github.com/citation-style-language/styles), refreshed on every commit, with each file's <updated> timestamp set to the file's last git commit time.
Licensing
---------
Please refer to https://github.com/citation-style-language/styles.
| {
"content_hash": "7eff3fdb710b8e0cf2c5622e26351138",
"timestamp": "",
"source": "github",
"line_count": 8,
"max_line_length": 223,
"avg_line_length": 45,
"alnum_prop": 0.7222222222222222,
"repo_name": "citation-style-editor/csl-editor-demo-site",
"id": "ba75aecf877057f99f37ceede248cb772fcdb3a1",
"size": "360",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "docs/cslEditorLib/external/csl-styles/README.md",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "HTML",
"bytes": "19371"
},
{
"name": "JavaScript",
"bytes": "16012"
},
{
"name": "Shell",
"bytes": "1858"
}
],
"symlink_target": ""
} |
using ::testing::AtLeast;
using ::testing::Invoke;
using ::testing::Return;
using ::testing::StrictMock;
namespace net {
namespace {
// Subclass of NetworkChangeNotifierWin that overrides functions so that no
// Windows API networking functions are ever called.
class TestNetworkChangeNotifierWin : public NetworkChangeNotifierWin {
public:
TestNetworkChangeNotifierWin() {}
virtual ~TestNetworkChangeNotifierWin() {
// This is needed so we don't try to stop watching for IP address changes,
// as we never actually started.
set_is_watching(false);
}
// From NetworkChangeNotifier.
virtual NetworkChangeNotifier::ConnectionType
GetCurrentConnectionType() const OVERRIDE {
return NetworkChangeNotifier::CONNECTION_UNKNOWN;
}
// From NetworkChangeNotifierWin.
MOCK_METHOD0(WatchForAddressChangeInternal, bool());
private:
DISALLOW_COPY_AND_ASSIGN(TestNetworkChangeNotifierWin);
};
class TestIPAddressObserver
: public net::NetworkChangeNotifier::IPAddressObserver {
public:
TestIPAddressObserver() {
NetworkChangeNotifier::AddIPAddressObserver(this);
}
~TestIPAddressObserver() {
NetworkChangeNotifier::RemoveIPAddressObserver(this);
}
MOCK_METHOD0(OnIPAddressChanged, void());
private:
DISALLOW_COPY_AND_ASSIGN(TestIPAddressObserver);
};
bool ExitMessageLoopAndReturnFalse() {
base::MessageLoop::current()->Quit();
return false;
}
} // namespace
class NetworkChangeNotifierWinTest : public testing::Test {
public:
// Calls WatchForAddressChange, and simulates a WatchForAddressChangeInternal
// success. Expects that |network_change_notifier_| has just been created, so
// it's not watching anything yet, and there have been no previous
// WatchForAddressChangeInternal failures.
void StartWatchingAndSucceed() {
EXPECT_FALSE(network_change_notifier_.is_watching());
EXPECT_EQ(0, network_change_notifier_.sequential_failures());
EXPECT_CALL(test_ip_address_observer_, OnIPAddressChanged()).Times(0);
EXPECT_CALL(network_change_notifier_, WatchForAddressChangeInternal())
.Times(1)
.WillOnce(Return(true));
network_change_notifier_.WatchForAddressChange();
EXPECT_TRUE(network_change_notifier_.is_watching());
EXPECT_EQ(0, network_change_notifier_.sequential_failures());
// If a task to notify observers of the IP address change event was
// incorrectly posted, make sure it gets run to trigger a failure.
base::MessageLoop::current()->RunUntilIdle();
}
// Calls WatchForAddressChange, and simulates a WatchForAddressChangeInternal
// failure.
void StartWatchingAndFail() {
EXPECT_FALSE(network_change_notifier_.is_watching());
EXPECT_EQ(0, network_change_notifier_.sequential_failures());
EXPECT_CALL(test_ip_address_observer_, OnIPAddressChanged()).Times(0);
EXPECT_CALL(network_change_notifier_, WatchForAddressChangeInternal())
// Due to an expected race, it's theoretically possible for more than
// one call to occur, though unlikely.
.Times(AtLeast(1))
.WillRepeatedly(Return(false));
network_change_notifier_.WatchForAddressChange();
EXPECT_FALSE(network_change_notifier_.is_watching());
EXPECT_LT(0, network_change_notifier_.sequential_failures());
// If a task to notify observers of the IP address change event was
// incorrectly posted, make sure it gets run.
base::MessageLoop::current()->RunUntilIdle();
}
// Simulates a network change event, resulting in a call to OnObjectSignaled.
// The resulting call to WatchForAddressChangeInternal then succeeds.
void SignalAndSucceed() {
EXPECT_TRUE(network_change_notifier_.is_watching());
EXPECT_EQ(0, network_change_notifier_.sequential_failures());
EXPECT_CALL(test_ip_address_observer_, OnIPAddressChanged()).Times(1);
EXPECT_CALL(network_change_notifier_, WatchForAddressChangeInternal())
.Times(1)
.WillOnce(Return(true));
network_change_notifier_.OnObjectSignaled(INVALID_HANDLE_VALUE);
EXPECT_TRUE(network_change_notifier_.is_watching());
EXPECT_EQ(0, network_change_notifier_.sequential_failures());
// Run the task to notify observers of the IP address change event.
base::MessageLoop::current()->RunUntilIdle();
}
// Simulates a network change event, resulting in a call to OnObjectSignaled.
// The resulting call to WatchForAddressChangeInternal then fails.
void SignalAndFail() {
EXPECT_TRUE(network_change_notifier_.is_watching());
EXPECT_EQ(0, network_change_notifier_.sequential_failures());
EXPECT_CALL(test_ip_address_observer_, OnIPAddressChanged()).Times(1);
EXPECT_CALL(network_change_notifier_, WatchForAddressChangeInternal())
// Due to an expected race, it's theoretically possible for more than
// one call to occur, though unlikely.
.Times(AtLeast(1))
.WillRepeatedly(Return(false));
network_change_notifier_.OnObjectSignaled(INVALID_HANDLE_VALUE);
EXPECT_FALSE(network_change_notifier_.is_watching());
EXPECT_LT(0, network_change_notifier_.sequential_failures());
// Run the task to notify observers of the IP address change event.
base::MessageLoop::current()->RunUntilIdle();
}
// Runs the message loop until WatchForAddressChange is called again, as a
// result of the already posted task after a WatchForAddressChangeInternal
// failure. Simulates a success on the resulting call to
// WatchForAddressChangeInternal.
void RetryAndSucceed() {
EXPECT_FALSE(network_change_notifier_.is_watching());
EXPECT_LT(0, network_change_notifier_.sequential_failures());
EXPECT_CALL(test_ip_address_observer_, OnIPAddressChanged()).Times(1)
.WillOnce(
Invoke(base::MessageLoop::current(), &base::MessageLoop::Quit));
EXPECT_CALL(network_change_notifier_, WatchForAddressChangeInternal())
.Times(1).WillOnce(Return(true));
base::MessageLoop::current()->Run();
EXPECT_TRUE(network_change_notifier_.is_watching());
EXPECT_EQ(0, network_change_notifier_.sequential_failures());
}
// Runs the message loop until WatchForAddressChange is called again, as a
// result of the already posted task after a WatchForAddressChangeInternal
// failure. Simulates a failure on the resulting call to
// WatchForAddressChangeInternal.
void RetryAndFail() {
EXPECT_FALSE(network_change_notifier_.is_watching());
EXPECT_LT(0, network_change_notifier_.sequential_failures());
int initial_sequential_failures =
network_change_notifier_.sequential_failures();
EXPECT_CALL(test_ip_address_observer_, OnIPAddressChanged()).Times(0);
EXPECT_CALL(network_change_notifier_, WatchForAddressChangeInternal())
// Due to an expected race, it's theoretically possible for more than
// one call to occur, though unlikely.
.Times(AtLeast(1))
.WillRepeatedly(Invoke(ExitMessageLoopAndReturnFalse));
base::MessageLoop::current()->Run();
EXPECT_FALSE(network_change_notifier_.is_watching());
EXPECT_LT(initial_sequential_failures,
network_change_notifier_.sequential_failures());
// If a task to notify observers of the IP address change event was
// incorrectly posted, make sure it gets run.
base::MessageLoop::current()->RunUntilIdle();
}
private:
// Note that the order of declaration here is important.
// Allows creating a new NetworkChangeNotifier. Must be created before
// |network_change_notifier_| and destroyed after it to avoid DCHECK failures.
NetworkChangeNotifier::DisableForTest disable_for_test_;
StrictMock<TestNetworkChangeNotifierWin> network_change_notifier_;
// Must be created after |network_change_notifier_|, so it can add itself as
// an IPAddressObserver.
StrictMock<TestIPAddressObserver> test_ip_address_observer_;
};
TEST_F(NetworkChangeNotifierWinTest, NetChangeWinBasic) {
StartWatchingAndSucceed();
}
TEST_F(NetworkChangeNotifierWinTest, NetChangeWinFailStart) {
StartWatchingAndFail();
}
// https://code.google.com/p/chromium/issues/detail?id=356401
TEST_F(NetworkChangeNotifierWinTest, FLAKY_NetChangeWinFailStartOnce) {
StartWatchingAndFail();
RetryAndSucceed();
}
// https://code.google.com/p/chromium/issues/detail?id=356401
TEST_F(NetworkChangeNotifierWinTest, FLAKY_NetChangeWinFailStartTwice) {
StartWatchingAndFail();
RetryAndFail();
RetryAndSucceed();
}
TEST_F(NetworkChangeNotifierWinTest, NetChangeWinSignal) {
StartWatchingAndSucceed();
SignalAndSucceed();
}
// https://code.google.com/p/chromium/issues/detail?id=356401
TEST_F(NetworkChangeNotifierWinTest, FLAKY_NetChangeWinFailSignalOnce) {
StartWatchingAndSucceed();
SignalAndFail();
RetryAndSucceed();
}
// https://code.google.com/p/chromium/issues/detail?id=356401
TEST_F(NetworkChangeNotifierWinTest, FLAKY_NetChangeWinFailSignalTwice) {
StartWatchingAndSucceed();
SignalAndFail();
RetryAndFail();
RetryAndSucceed();
}
} // namespace net
| {
"content_hash": "6383f7523dfbaa9dafadf35f617be9f1",
"timestamp": "",
"source": "github",
"line_count": 253,
"max_line_length": 80,
"avg_line_length": 35.66403162055336,
"alnum_prop": 0.7358971517233736,
"repo_name": "patrickm/chromium.src",
"id": "878060eefb9a2dc3673f9555f2b0c454977b943b",
"size": "9482",
"binary": false,
"copies": "1",
"ref": "refs/heads/nw",
"path": "net/base/network_change_notifier_win_unittest.cc",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "ASP",
"bytes": "853"
},
{
"name": "AppleScript",
"bytes": "6973"
},
{
"name": "Arduino",
"bytes": "464"
},
{
"name": "Assembly",
"bytes": "52960"
},
{
"name": "Awk",
"bytes": "8660"
},
{
"name": "C",
"bytes": "40737238"
},
{
"name": "C#",
"bytes": "1132"
},
{
"name": "C++",
"bytes": "207930633"
},
{
"name": "CSS",
"bytes": "939170"
},
{
"name": "Java",
"bytes": "5844934"
},
{
"name": "JavaScript",
"bytes": "17837835"
},
{
"name": "Mercury",
"bytes": "10533"
},
{
"name": "Objective-C",
"bytes": "886228"
},
{
"name": "Objective-C++",
"bytes": "6667789"
},
{
"name": "PHP",
"bytes": "97817"
},
{
"name": "Perl",
"bytes": "672770"
},
{
"name": "Python",
"bytes": "10857933"
},
{
"name": "Rebol",
"bytes": "262"
},
{
"name": "Shell",
"bytes": "1326032"
},
{
"name": "Tcl",
"bytes": "277091"
},
{
"name": "XSLT",
"bytes": "13493"
},
{
"name": "nesC",
"bytes": "15206"
}
],
"symlink_target": ""
} |
module MongoidSilo
class Railtie < Rails::Railtie
end
end | {
"content_hash": "280b002b2e6b57d876a50a00a5648adf",
"timestamp": "",
"source": "github",
"line_count": 4,
"max_line_length": 32,
"avg_line_length": 15.25,
"alnum_prop": 0.7704918032786885,
"repo_name": "musicglue/mongoid_silo",
"id": "4a55c97a4e96c13476f9e7bbb3f4e6fcb5c6706a",
"size": "61",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "lib/mongoid_silo/railtie.rb",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Ruby",
"bytes": "21688"
}
],
"symlink_target": ""
} |
/*
* SubSonic - http://subsonicproject.com
*
* The contents of this file are subject to the Mozilla Public
* License Version 1.1 (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.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an
* "AS IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or
* implied. See the License for the specific language governing
* rights and limitations under the License.
*/
using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Configuration;
using System.Configuration.Provider;
using System.Data;
using System.Data.SqlClient;
using System.Drawing;
using System.IO;
using System.Reflection;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using System.Windows.Forms;
using System.Windows.Forms.Design;
using ComponentFactory.Krypton.Toolkit;
using Microsoft.SqlServer.Management.Common;
using Microsoft.SqlServer.Management.Smo;
using PropertyGridEx;
using SubSonic.Sugar;
using SubSonic.Utilities;
using Configuration=System.Configuration.Configuration;
using CPN = SubSonic.ConfigurationPropertyName;
using DM = SubSonic.SubStage.MasterStore;
using Server=Wilco.WebServer.Server;
namespace SubSonic.SubStage
{
public partial class SubStageForm : KryptonForm
{
private const string CODE_GENERATION = "Code Generation";
private const string COLUMN_IMAGE = "textfield.png";
private const string COLUMN_PK_IMAGE = "textfield_key.png";
private const string CONNECTION_STRING_FOLDER_IMAGE = "folder_link.png";
private const string CONNECTION_STRING_IMAGE = "link.png";
private const string DRIVE_IMAGE = "drive.png";
private const string FILE_URL_PREFIX = @"file:\\\";
private const string FOLDER_IMAGE = "folder.png";
private const string GLOBAL = "Global";
private const string PROJECT_IMAGE = "package.png";
private const string PROVIDER_IMAGE = "database.png";
private const string REGULAR_EXPRESSIONS = "Regular Expressions";
private const string SP_FOLDER_IMAGE = "folder.png";
private const string SP_IMAGE = "database_gear.png";
private const string SP_PARAM_IMAGE = "script_gear.png";
private const string STORED_PROCEDURES = "Stored Procedures";
private const string SUBSTAGE_CONFIGURATION_IMAGE = "brick.png";
private const string TABLE_EXCLUDED_IMAGE = "table_delete.png";
private const string TABLE_FOLDER_IMAGE = "folder.png";
private const string TABLE_IMAGE = "table.png";
private const string TABLE_NO_PK_IMAGE = "table_error.png";
private const string TABLES = "Tables";
private const string TEMPLATE_CONNECTION_STRINGS = "[#CONNECTION_STRINGS#]";
private const string TEMPLATE_DEFAULT_PROVIDER = "[#DEFAULT_PROVIDER#]";
private const string TEMPLATE_ENABLE_TRACE = "[#ENABLE_TRACE#]";
private const string TEMPLATE_PROVIDERS = "[#PROVIDERS#]";
private const string TEMPLATE_SCAFFOLD_PROPERTIES = "[#CUSTOM_PROPERTIES#]";
private const string TEMPLATE_TEMPLATE_DIRECTORY = "[#TEMPLATE_DIRECTORY#]";
private const string VIEW_FOLDER_IMAGE = "folder.png";
private const string VIEW_IMAGE = "database_table.png";
private const string VIEWS = "Views";
private static Thread serverThread;
private Server activeServer;
private MasterStore.SubStageConfigurationRow config;
private string configTemplate;
private string embeddedWebRootPath;
private string executionDirectory;
private bool navigatingFromFileTree;
private string scaffoldFilePath;
private string scaffoldFileRedirectorPath;
private string scaffoldInfoFilePath;
private string scaffoldInfoUrlPath;
private string scaffoldTemplate;
private string scaffoldUrlPath;
private string webBinPath;
private string webConfigPath;
public SubStageForm(string[] args)
{
InitializeComponent();
LoadConfiguration();
ClearWebBinDirectory();
CopyToWebBinDirectory();
pGrid.ToolStrip.Items[2].Visible = false;
pGrid.ToolStrip.Items[3].Visible = false;
BuildTree();
activeServer = CreateServer("localhost", "/", embeddedWebRootPath, config.WebServerPort);
if(args != null && args.Length == 1)
ImportProject(args[0]);
if(treeFileSystem.SelectedNode != null)
NavigateFileBrowser(FILE_URL_PREFIX + treeFileSystem.SelectedNode.Tag);
else
NavigateFileBrowser(FILE_URL_PREFIX + "C:\\");
}
private static ModelManager MM
{
get { return ModelManager.Instance; }
}
private StageNode SelectedNode
{
get
{
if(treeView1.SelectedNode != null)
return (StageNode)treeView1.SelectedNode;
return null;
}
}
#region Events
private void miFileExit_Click(object sender, EventArgs e)
{
if(activeServer != null)
{
//serverThread.Interrupt();
activeServer.Stop();
}
Close();
}
private void miHelpAbout_Click(object sender, EventArgs e)
{
About aboutForm = new About();
aboutForm.ShowDialog();
}
private void treeView1_AfterSelect(object sender, TreeViewEventArgs e)
{
SelectNode((StageNode)e.Node);
}
private void propertyGridEx1_PropertyValueChanged(object s, PropertyValueChangedEventArgs e)
{
StageNode nodeTag = (StageNode)pGrid.Tag;
if(nodeTag.IsProjectNode)
{
SaveProjectProperties(e.ChangedItem);
BuildConfig(nodeTag.Project);
}
else if(nodeTag.IsProviderNode)
{
SaveProviderProperties(e.ChangedItem);
BuildConfig(nodeTag.Project);
}
else if(nodeTag.IsConnectionStringNode)
SaveConnectionStringProperties(e.ChangedItem);
else if(nodeTag.NodeType == StageNodeType.SubStageConfiguration)
SaveConfigurationProperties(e.ChangedItem);
}
private void btnNewProject_Click(object sender, EventArgs e)
{
AddProject();
}
private void cmTree_ItemClicked(object sender, ToolStripItemClickedEventArgs e)
{
if(e.ClickedItem == cmiTreeDeleteProject && SelectedNode.IsProjectNode)
{
DeleteProject(SelectedNode.Project.ProjectId);
SelectedNode.Remove();
}
else if(e.ClickedItem == cmiTreeDeleteProvider && SelectedNode.IsProviderNode)
{
DeleteProvider(SelectedNode.Provider.ProviderId);
SelectedNode.Remove();
}
else if(e.ClickedItem == cmiTreeDeleteConnectionString && SelectedNode.IsConnectionStringNode)
{
DeleteConnectionString(SelectedNode.ConnectionString.ConnectionStringId);
SelectedNode.Remove();
}
else if(e.ClickedItem == cmiTreeAddProvider && SelectedNode.IsProjectNode)
{
AddProvider(SelectedNode.Project.ProjectId);
//BuildTree();
}
else if(e.ClickedItem == cmiTreeAddConnectionString && SelectedNode.IsConnectionStringFolderNode)
AddConnectionString();
else if(e.ClickedItem == cmiGenerateObjectEnabled && SelectedNode.IsTableNode || SelectedNode.IsViewNode)
EnableDisableTablesViews();
}
/// <summary>
/// Enables or disable a table or a view.
/// </summary>
private void EnableDisableTablesViews()
{
MasterStore.ProvidersRow provider = SelectedNode.Provider;
List<string> genGroups = new List<string>(provider.ExcludeTableList.Split(new string[] {","}, StringSplitOptions.RemoveEmptyEntries));
if(SelectedNode.NodeType == StageNodeType.Table || SelectedNode.NodeType == StageNodeType.View)
genGroups.Add(string.Format("^{0}$", SelectedNode.DatabaseName));
else if(SelectedNode.NodeType == StageNodeType.TableExcluded || SelectedNode.NodeType == StageNodeType.ViewExcluded)
{
foreach(string s in provider.ExcludeTableList.Split(new string[] {","}, StringSplitOptions.RemoveEmptyEntries))
{
if(Utility.IsRegexMatch(SelectedNode.DatabaseName, s.Trim()))
{
genGroups.Remove(s);
//break;//There might be a few stuff that are blocking it from being generated so dont break out.
}
}
}
StringBuilder sb = new StringBuilder();
for(int i = 0; i < genGroups.Count; i++)
{
if(i < genGroups.Count - 1)
sb.Append(genGroups[i] + ",");
else
sb.Append(genGroups[i]);
}
provider.ExcludeTableList = sb.ToString();
MM.Save();
//Lets reload the tree and expand the selected node
int stagenode = SelectedNode.Index; //save the old index
bool isOnTables = ((StageNode)SelectedNode.Parent).NodeType == StageNodeType.TableFolder;
PopulateProviderData((StageNode)SelectedNode.Parent.Parent);
if(isOnTables)
{
//SelectedNode.NextVisibleNode.Expand();
SelectedNode.NextVisibleNode.Nodes[stagenode].EnsureVisible();
}
else
{
//SelectedNode.NextVisibleNode.NextVisibleNode.Expand();
SelectedNode.NextVisibleNode.NextVisibleNode.Nodes[stagenode].EnsureVisible();
}
}
private void treeView1_MouseDown(object sender, MouseEventArgs e)
{
if(e.Button == MouseButtons.Right)
{
StageNode thisNode = (StageNode)treeView1.GetNodeAt(e.X, e.Y);
if(thisNode != null)
{
treeView1.SelectedNode = thisNode;
ToggleContextMenuItems(thisNode);
cmTree.Show(treeView1, e.X, e.Y);
}
}
}
private void btnNewProvider_Click(object sender, EventArgs e)
{
if(SelectedNode != null)
{
if(SelectedNode.IsProjectNode)
AddProvider(SelectedNode.RowId);
}
}
private void btnAddConnectionString_Click(object sender, EventArgs e)
{
if(SelectedNode != null)
{
if(SelectedNode.IsConnectionStringFolderNode)
AddConnectionString();
}
}
private void btnInvokeProviders_Click(object sender, EventArgs e)
{
if(SelectedNode != null)
{
if(SelectedNode.IsProjectNode || SelectedNode.IsProviderNode)
PopulateProviderData(SelectedNode);
}
}
private void ImportProject(string importConfigPath)
{
if(File.Exists(importConfigPath))
{
FileInfo fi = new FileInfo(importConfigPath);
DirectoryInfo di = fi.Directory;
if(di != null)
{
string originalDirectory = di.FullName;
string projectName = di.Name;
ExeConfigurationFileMap fileMap = new ExeConfigurationFileMap();
fileMap.ExeConfigFilename = importConfigPath;
Configuration subConfig = ConfigurationManager.OpenMappedExeConfiguration(fileMap, ConfigurationUserLevel.None);
SubSonicSection section = (SubSonicSection)subConfig.GetSection(ConfigurationSectionName.SUB_SONIC_SERVICE);
if(section != null)
{
MasterStore.ProjectsRow newProject = MM.Projects.NewProjectsRow();
newProject.Name = projectName;
newProject.OriginalLocation = originalDirectory;
newProject.EnableTrace = Convert.ToBoolean(!String.IsNullOrEmpty(section.EnableTrace) ? section.EnableTrace : MM.Projects.EnableTraceColumn.DefaultValue);
newProject.TemplateDirectory =
Convert.ToString(!String.IsNullOrEmpty(section.TemplateDirectory) ? section.TemplateDirectory : MM.Projects.TemplateDirectoryColumn.DefaultValue);
MM.Projects.AddProjectsRow(newProject);
ConnectionStringSettingsCollection connStrings = new ConnectionStringSettingsCollection();
if(subConfig.ConnectionStrings != null)
connStrings = subConfig.ConnectionStrings.ConnectionStrings;
List<int> insertedConnStringIds = new List<int>();
//Loop through connection strings and remove any that aren't referenced by the provider.
foreach(ConnectionStringSettings connSetting in connStrings)
{
bool foundMatch = false;
foreach(ProviderSettings providerSettings in section.Providers)
{
if(providerSettings.Parameters.Get(ConfigurationPropertyName.CONNECTION_STRING_NAME) != null)
{
if(providerSettings.Parameters.Get(ConfigurationPropertyName.CONNECTION_STRING_NAME) == connSetting.Name)
{
foundMatch = true;
break;
}
}
}
if(!foundMatch)
connStrings.Remove(connSetting);
else
{
int referencedId = -1;
foreach(MasterStore.ConnectionStringsRow existingConnection in MM.ConnectionStrings)
{
if(existingConnection.Name == connSetting.Name && existingConnection.ConnectionString == connSetting.ConnectionString)
{
referencedId = existingConnection.ConnectionStringId;
break;
}
}
if(referencedId < 0)
{
MasterStore.ConnectionStringsRow newConnection = (MasterStore.ConnectionStringsRow)MM.ConnectionStrings.NewRow();
newConnection.Name = connSetting.Name;
newConnection.ConnectionString = connSetting.ConnectionString;
MM.ConnectionStrings.AddConnectionStringsRow(newConnection);
referencedId = newConnection.ConnectionStringId;
}
insertedConnStringIds.Add(referencedId);
}
}
foreach(ProviderSettings pset in section.Providers)
{
MasterStore.ProvidersRow newProvider = (MasterStore.ProvidersRow)MM.Providers.NewRow();
newProvider.Name = pset.Name;
newProvider.ProjectId = newProject.ProjectId;
string connectionName = GetConfig(pset, ConfigurationPropertyName.CONNECTION_STRING_NAME, null).ToString();
MasterStore.ConnectionStringsRow[] conns =
(MasterStore.ConnectionStringsRow[])MM.ConnectionStrings.Select(MM.ConnectionStrings.NameColumn + " = '" + connectionName + "'");
int activeConnectionId = -1;
if(conns.Length > 1)
{
foreach(MasterStore.ConnectionStringsRow cRow in MM.ConnectionStrings)
{
if(insertedConnStringIds.Contains(cRow.ConnectionStringId))
{
activeConnectionId = cRow.ConnectionStringId;
break;
}
}
}
else if(conns.Length == 1)
activeConnectionId = conns[0].ConnectionStringId;
else
ShowStatus("Invalid Configuration File... Import Aborted.");
newProvider.ConnectionStringId = activeConnectionId;
string providerType = section.Providers[0].Type.Split(new char[] {'.', ','})[1].Trim();
bool foundProvider = false;
foreach(MasterStore.ProviderTypesRow providerTypeRow in MM.ProviderTypes)
{
if(providerTypeRow.InternalName == providerType)
{
newProvider.ProviderTypeId = providerTypeRow.ProviderTypeId;
foundProvider = true;
break;
}
}
if(!foundProvider)
newProvider.ProviderTypeId = MM.ProviderTypes[0].ProviderTypeId;
newProvider.AppendWith = GetConfig(pset, ConfigurationPropertyName.APPEND_WITH, MM.Providers.AppendWithColumn).ToString();
newProvider.AdditionalNamespaces = GetConfig(pset, ConfigurationPropertyName.ADDITIONAL_NAMESPACES, MM.Providers.AdditionalNamespacesColumn).ToString();
newProvider.ExcludeProcedureList = GetConfig(pset, ConfigurationPropertyName.EXCLUDE_PROCEDURE_LIST, MM.Providers.ExcludeProcedureListColumn).ToString();
newProvider.ExcludeTableList = GetConfig(pset, ConfigurationPropertyName.EXCLUDE_TABLE_LIST, MM.Providers.ExcludeTableListColumn).ToString();
newProvider.ExtractClassNameFromSPName =
Convert.ToBoolean(GetConfig(pset, ConfigurationPropertyName.EXTRACT_CLASS_NAME_FROM_SP_NAME, MM.Providers.ExtractClassNameFromSPNameColumn));
newProvider.FixDatabaseObjectCasing =
Convert.ToBoolean(GetConfig(pset, ConfigurationPropertyName.FIX_DATABASE_OBJECT_CASING, MM.Providers.FixDatabaseObjectCasingColumn));
newProvider.FixPluralClassNames =
Convert.ToBoolean(GetConfig(pset, ConfigurationPropertyName.FIX_PLURAL_CLASS_NAMES, MM.Providers.FixPluralClassNamesColumn));
newProvider.GeneratedNamespace = GetConfig(pset, ConfigurationPropertyName.GENERATED_NAMESPACE, MM.Providers.GeneratedNamespaceColumn).ToString();
newProvider.GenerateLazyLoads = Convert.ToBoolean(GetConfig(pset, ConfigurationPropertyName.GENERATE_LAZY_LOADS, MM.Providers.GenerateLazyLoadsColumn));
newProvider.GenerateNullableProperties =
Convert.ToBoolean(GetConfig(pset, ConfigurationPropertyName.GENERATE_NULLABLE_PROPERTIES, MM.Providers.GenerateNullablePropertiesColumn));
newProvider.GenerateODSControllers =
Convert.ToBoolean(GetConfig(pset, ConfigurationPropertyName.GENERATE_ODS_CONTROLLERS, MM.Providers.GenerateODSControllersColumn));
newProvider.GenerateRelatedTablesAsProperties =
Convert.ToBoolean(GetConfig(pset, ConfigurationPropertyName.GENERATE_RELATED_TABLES_AS_PROPERTIES,
MM.Providers.GenerateRelatedTablesAsPropertiesColumn));
newProvider.IncludeProcedureList = GetConfig(pset, ConfigurationPropertyName.INCLUDE_PROCEDURE_LIST, MM.Providers.IncludeProcedureListColumn).ToString();
newProvider.IncludeTableList = GetConfig(pset, ConfigurationPropertyName.INCLUDE_TABLE_LIST, MM.Providers.IncludeTableListColumn).ToString();
newProvider.RegexDictionaryReplace =
GetConfig(pset, ConfigurationPropertyName.REGEX_DICTIONARY_REPLACE, MM.Providers.RegexDictionaryReplaceColumn).ToString();
newProvider.RegexIgnoreCase = Convert.ToBoolean(GetConfig(pset, ConfigurationPropertyName.REGEX_IGNORE_CASE, MM.Providers.RegexIgnoreCaseColumn));
newProvider.RegexMatchExpression = GetConfig(pset, ConfigurationPropertyName.REGEX_MATCH_EXPRESSION, MM.Providers.RegexMatchExpressionColumn).ToString();
newProvider.RegexReplaceExpression =
GetConfig(pset, ConfigurationPropertyName.REGEX_REPLACE_EXPRESSION, MM.Providers.RegexReplaceExpressionColumn).ToString();
newProvider.RelatedTableLoadPrefix =
GetConfig(pset, ConfigurationPropertyName.RELATED_TABLE_LOAD_PREFIX, MM.Providers.RelatedTableLoadPrefixColumn).ToString();
newProvider.RemoveUnderscores = Convert.ToBoolean(GetConfig(pset, ConfigurationPropertyName.REMOVE_UNDERSCORES, MM.Providers.RemoveUnderscoresColumn));
newProvider.SetPropertyDefaultsFromDatabase =
Convert.ToBoolean(GetConfig(pset, ConfigurationPropertyName.SET_PROPERTY_DEFAULTS_FROM_DATABASE, MM.Providers.SetPropertyDefaultsFromDatabaseColumn));
newProvider.SPStartsWith = GetConfig(pset, ConfigurationPropertyName.SP_STARTS_WITH, MM.Providers.SPStartsWithColumn).ToString();
newProvider.SPClassName = GetConfig(pset, ConfigurationPropertyName.STORED_PROCEDURE_CLASS_NAME, MM.Providers.SPClassNameColumn).ToString();
newProvider.StoredProcedureBaseClass =
GetConfig(pset, ConfigurationPropertyName.STORED_PROCEDURE_BASE_CLASS, MM.Providers.StoredProcedureBaseClassColumn).ToString();
newProvider.StripColumnText = GetConfig(pset, ConfigurationPropertyName.STRIP_COLUMN_TEXT, MM.Providers.StripColumnTextColumn).ToString();
newProvider.StripParamText = GetConfig(pset, ConfigurationPropertyName.STRIP_PARAM_TEXT, MM.Providers.StripParamTextColumn).ToString();
newProvider.StripSPText = GetConfig(pset, ConfigurationPropertyName.STRIP_STORED_PROCEDURE_TEXT, MM.Providers.StripSPTextColumn).ToString();
newProvider.StripTableText = GetConfig(pset, ConfigurationPropertyName.STRIP_TABLE_TEXT, MM.Providers.StripTableTextColumn).ToString();
newProvider.StripViewText = GetConfig(pset, ConfigurationPropertyName.STRIP_VIEW_TEXT, MM.Providers.StripViewTextColumn).ToString();
newProvider.TableBaseClass = GetConfig(pset, ConfigurationPropertyName.TABLE_BASE_CLASS, MM.Providers.TableBaseClassColumn).ToString();
newProvider.UseExtendedProperties =
Convert.ToBoolean(GetConfig(pset, ConfigurationPropertyName.USE_EXTENDED_PROPERTIES, MM.Providers.UseExtendedPropertiesColumn));
newProvider.UseSPs = Convert.ToBoolean(GetConfig(pset, ConfigurationPropertyName.USE_STORED_PROCEDURES, MM.Providers.UseSPsColumn));
newProvider.UseUTC = Convert.ToBoolean(GetConfig(pset, ConfigurationPropertyName.USE_UTC_TIMES, MM.Providers.UseUTCColumn));
newProvider.ViewBaseClass = GetConfig(pset, ConfigurationPropertyName.VIEW_BASE_CLASS, MM.Providers.ViewBaseClassColumn).ToString();
newProvider.ViewStartsWith = GetConfig(pset, ConfigurationPropertyName.VIEW_STARTS_WITH, MM.Providers.ViewStartsWithColumn).ToString();
MM.Providers.AddProvidersRow(newProvider);
if(!String.IsNullOrEmpty(section.DefaultProvider))
{
if(Utility.IsMatch(section.DefaultProvider, newProvider.Name))
newProject.DefaultProvider = newProvider.ProviderId;
}
}
MM.Save();
BuildTree();
}
}
}
}
private void miFileImportProject_Click(object sender, EventArgs e)
{
OpenFileDialog fdOpen = new OpenFileDialog();
fdOpen.Multiselect = false;
fdOpen.Filter = "Config Files|*.config";
fdOpen.Title = "Import Existing web.config or app.config File";
//LoadMasterFile(null);
bool openedFile = fdOpen.ShowDialog(this) == DialogResult.OK;
if(openedFile)
ImportProject(fdOpen.FileName);
}
private void pGrid_ToolStrip_ItemClicked(object sender, ToolStripItemClickedEventArgs e)
{
if(e.ClickedItem == pgbTestConnection)
{
if(SelectedNode.IsProviderNode)
{
try
{
InstantiateProvider(SelectedNode.Provider);
DataService.GetTableNames(SelectedNode.Provider.Name);
ShowStatus("Connection Successful.");
}
catch(Exception ex)
{
ShowStatus("Connection Failed: " + ex.Message);
}
}
}
}
private void btnSplitGenerateCode_Click(object sender, EventArgs e)
{
if(((ToolStripSplitButton)sender).ButtonPressed)
{
if(SelectedNode != null)
{
if(SelectedNode.IsProjectNode || SelectedNode.IsProviderNode)
GenerateCode(SelectedNode);
}
}
}
private void miUseGeneratedNames_Click(object sender, EventArgs e)
{
miUseDatabaseNames.Checked = !miUseGeneratedNames.Checked;
ToggleNodeNames();
}
private void miUseDatabaseNames_Click(object sender, EventArgs e)
{
miUseGeneratedNames.Checked = !miUseDatabaseNames.Checked;
ToggleNodeNames();
}
private void ToggleNodeNames()
{
//Using BeginUpdate() & EndUpdate() makes a HUGE difference in performance...
//Usign them, this operation dropped from 4000ms to 2ms!
treeView1.BeginUpdate();
foreach(StageNode node in treeView1.Nodes)
ToggleNodeNames(node);
treeView1.EndUpdate();
}
private void ToggleNodeNames(StageNode node)
{
node.Text = miUseDatabaseNames.Checked ? node.DatabaseName : node.SubSonicName;
foreach(StageNode subNode in node.Nodes)
ToggleNodeNames(subNode);
}
private void btnCopyConfig_Click(object sender, EventArgs e)
{
Clipboard.SetText(tbxConfigOutput.Text);
}
private void btnClearLog_Click(object sender, EventArgs e)
{
tbxLog.Text = String.Empty;
}
private void tbxLog_TextChanged(object sender, EventArgs e)
{
tbxLog.ScrollToCaret();
}
private void btnSplitGenerateCode_DropDownItemClicked(object sender, ToolStripItemClickedEventArgs e)
{
if(e.ClickedItem == miGenerateVB)
{
if(!miGenerateVB.Checked)
{
miGenerateVB.Checked = !miGenerateVB.Checked;
miGenerateCSharp.Checked = !miGenerateVB.Checked;
}
}
else if(e.ClickedItem == miGenerateCSharp)
{
if(!miGenerateCSharp.Checked)
{
miGenerateCSharp.Checked = !miGenerateCSharp.Checked;
miGenerateVB.Checked = !miGenerateCSharp.Checked;
}
}
string currentCodeGenerationLanguage = config.CodeGenerationLanguage;
if (miGenerateVB.Checked)
config.CodeGenerationLanguage = "VB";
else
config.CodeGenerationLanguage = "C#";
if (!Utility.IsMatch(config.CodeGenerationLanguage, currentCodeGenerationLanguage))
MM.Save();
}
#endregion
private void LoadConfiguration()
{
config = MM.SubStageConfiguration.FindBySubStageConfigurationId(0);
if(config == null)
{
config = MM.SubStageConfiguration.NewSubStageConfigurationRow();
config.SubStageConfigurationId = 0;
MM.SubStageConfiguration.AddSubStageConfigurationRow(config);
MM.Save();
}
if(config.WebServerPort < 1 || config.WebServerPort > 65535)
config.WebServerPort = Convert.ToInt32(MM.SubStageConfiguration.WebServerPortColumn.DefaultValue);
executionDirectory = AppDomain.CurrentDomain.BaseDirectory;
if(String.IsNullOrEmpty(config.CodeGenerationPath))
config.CodeGenerationPath = executionDirectory + "GeneratedCode\\";
if(!Directory.Exists(config.CodeGenerationPath))
Directory.CreateDirectory(config.CodeGenerationPath);
if(String.IsNullOrEmpty(config.CodeGenerationLanguage) || config.CodeGenerationLanguage.ToUpper().Contains("C"))
{
config.CodeGenerationLanguage = "C#";
miGenerateCSharp.Checked = true;
miGenerateVB.Checked = false;
}
else
{
config.CodeGenerationLanguage = "VB";
miGenerateCSharp.Checked = false;
miGenerateVB.Checked = true;
}
embeddedWebRootPath = executionDirectory + "root\\";
if(!Directory.Exists(embeddedWebRootPath))
Directory.CreateDirectory(embeddedWebRootPath);
webBinPath = embeddedWebRootPath + "bin\\";
if(!Directory.Exists(webBinPath))
Directory.CreateDirectory(webBinPath);
scaffoldFileRedirectorPath = embeddedWebRootPath + "Default.htm";
if(!File.Exists(scaffoldFileRedirectorPath))
File.Copy(executionDirectory + "\\Default.htm", scaffoldFileRedirectorPath);
scaffoldInfoFilePath = embeddedWebRootPath + "Info.htm";
if(!File.Exists(scaffoldInfoFilePath))
File.Copy(executionDirectory + "\\Info.htm", scaffoldInfoFilePath);
scaffoldFilePath = embeddedWebRootPath + "Scaffold.aspx";
scaffoldUrlPath = "http://localhost:" + config.WebServerPort + "/Default.htm";
scaffoldInfoUrlPath = "http://localhost:" + config.WebServerPort + "/Info.htm";
configTemplate = File.ReadAllText(executionDirectory + "ConfigTemplate.txt");
scaffoldTemplate = File.ReadAllText(executionDirectory + "ScaffoldTemplate.txt");
webConfigPath = embeddedWebRootPath + "web.config";
}
private void BuildDirectoryTree(string selectedPath)
{
string[] pathArray = null;
if(!String.IsNullOrEmpty(selectedPath))
pathArray = ParseDirectoryPath(selectedPath);
treeFileSystem.BeginUpdate();
treeFileSystem.SuspendLayout();
treeFileSystem.Nodes.Clear();
string[] drives = Directory.GetLogicalDrives();
foreach(string drive in drives)
{
DriveInfo driveInfo = new DriveInfo(drive);
if(driveInfo.DriveType != DriveType.CDRom && driveInfo.IsReady)
{
TreeNode node = new TreeNode(drive);
node.Tag = drive;
node.ImageKey = DRIVE_IMAGE;
node.SelectedImageKey = DRIVE_IMAGE;
treeFileSystem.Nodes.Add(node);
GetSubNodes(node, pathArray);
}
}
treeFileSystem.ResumeLayout();
treeFileSystem.EndUpdate();
}
private void GetSubNodes(TreeNode node, string[] pathArray)
{
node.Nodes.Clear();
string path = node.Tag.ToString();
string[] subDirs = new string[0];
const FileAttributes ignoreAttributes = FileAttributes.Hidden | FileAttributes.System | FileAttributes.Offline;
try
{
subDirs = Directory.GetDirectories(path);
}
catch {}
foreach(string subDir in subDirs)
{
DirectoryInfo di = new DirectoryInfo(subDir);
if((di.Attributes & ignoreAttributes) == 0)
{
TreeNode subNode = new TreeNode(di.Name);
subNode.Tag = di.FullName;
subNode.ImageKey = FOLDER_IMAGE;
subNode.SelectedImageKey = FOLDER_IMAGE;
node.Nodes.Add(subNode);
if(pathArray != null && subNode.Level < pathArray.Length)
{
if(Utility.IsMatch(di.Name, pathArray[subNode.Level]))
{
if(pathArray.Length == subNode.Level + 1)
{
treeFileSystem.AfterSelect -= treeFileSystem_AfterSelect;
treeFileSystem.BeforeExpand -= treeFileSystem_BeforeExpand;
subNode.EnsureVisible();
treeFileSystem.SelectedNode = subNode;
treeFileSystem.BeforeExpand += treeFileSystem_BeforeExpand;
treeFileSystem.AfterSelect += treeFileSystem_AfterSelect;
}
else
GetSubNodes(subNode, pathArray);
}
}
}
}
}
private static string[] ParseDirectoryPath(string path)
{
path = path.Replace("/", "\\");
string[] parts = path.Split(new char[] {'\\'}, StringSplitOptions.RemoveEmptyEntries);
if(parts.Length > 0)
parts[0] = parts[0] + "\\";
return parts;
}
private Server CreateServer(string prefix, string vpath, string path, int port)
{
string[] defaultDocuments = {"default.aspx", "default.htm", "default.html", "index.htm", "index.html"};
string[] restrictedDirs = {"/bin", "/app_browsers", "/app_code", "/app_data", "/app_localresources", "/app_globalresources", "/app_webreferences"};
Server server = new Server(prefix, port, vpath, path, defaultDocuments, restrictedDirs);
serverThread = new Thread(serverThread_Start);
serverThread.Start(server);
return server;
}
private void serverThread_Start(object data)
{
activeServer = (Server)data;
try
{
activeServer.Start();
}
catch(Exception ex)
{
MessageBox.Show(ex.Message);
Application.Exit();
}
}
private void ClearWebBinDirectory()
{
DirectoryInfo di = new DirectoryInfo(webBinPath);
FileSystemInfo[] files = di.GetFileSystemInfos();
foreach(FileSystemInfo file in files)
file.Delete();
}
private void CopyToWebBinDirectory()
{
string fileName = Assembly.GetExecutingAssembly().Location;
if (!String.IsNullOrEmpty(fileName))
{
string executable = Path.GetFileName(fileName);
string newLoc = webBinPath + executable;
File.Copy(fileName, newLoc, true);
while(!File.Exists(newLoc))
{
//wait...
}
DirectoryInfo di = new DirectoryInfo(executionDirectory);
FileSystemInfo[] files = di.GetFileSystemInfos("*.dll");
foreach(FileSystemInfo file in files)
{
File.Copy(file.FullName, webBinPath + file.Name, true);
while(!File.Exists(webBinPath + file.Name))
{
//wait...
}
}
}
}
private static StageNode MakeNode(string text, StageNodeType nodeType, int nodeId, DataRow row)
{
StageNode node = new StageNode(text, row);
node.NodeType = nodeType;
node.ImageKey = GetImageKey(nodeType);
node.SelectedImageKey = GetImageKey(nodeType);
node.RowId = nodeId;
node.DatabaseName = text;
node.SubSonicName = text;
return node;
}
private static StageNode MakeNode(string text, string databaseName, string subSonicName, StageNodeType nodeType, string nodeKey, DataRow row)
{
StageNode node = new StageNode(text, row);
node.NodeType = nodeType;
node.ImageKey = GetImageKey(nodeType);
node.SelectedImageKey = GetImageKey(nodeType);
node.ItemKey = nodeKey;
node.DatabaseName = databaseName;
node.SubSonicName = subSonicName;
return node;
}
private static string GetImageKey(StageNodeType nodeType)
{
switch(nodeType)
{
case StageNodeType.ColumnNode:
return COLUMN_IMAGE;
case StageNodeType.ColumnPrimaryKeyNode:
return COLUMN_PK_IMAGE;
case StageNodeType.Project:
return PROJECT_IMAGE;
case StageNodeType.Provider:
return PROVIDER_IMAGE;
case StageNodeType.ConnectionStringFolder:
return CONNECTION_STRING_FOLDER_IMAGE;
case StageNodeType.ConnectionString:
return CONNECTION_STRING_IMAGE;
case StageNodeType.TableFolder:
return TABLE_FOLDER_IMAGE;
case StageNodeType.ViewFolder:
return VIEW_FOLDER_IMAGE;
case StageNodeType.StoredProcedureFolder:
return SP_FOLDER_IMAGE;
case StageNodeType.SubStageConfiguration:
return SUBSTAGE_CONFIGURATION_IMAGE;
case StageNodeType.Table:
return TABLE_IMAGE;
case StageNodeType.TableWithoutPrimaryKey:
return TABLE_NO_PK_IMAGE;
case StageNodeType.TableExcluded:
case StageNodeType.ViewExcluded:
case StageNodeType.StoredProcedureExcluded:
return TABLE_EXCLUDED_IMAGE;
case StageNodeType.View:
return VIEW_IMAGE;
case StageNodeType.StoredProcedure:
return SP_IMAGE;
case StageNodeType.StoredProcedureParameter:
return SP_PARAM_IMAGE;
default:
return PROVIDER_IMAGE;
}
}
private void BuildTree()
{
treeView1.BeginUpdate();
treeView1.Nodes.Clear();
MasterStore.ProjectsRow[] projects = (MasterStore.ProjectsRow[])MM.Projects.Select(String.Empty, MM.Projects.NameColumn + " ASC");
foreach(MasterStore.ProjectsRow project in projects)
{
StageNode rootNode = MakeNode(project.Name, StageNodeType.Project, project.ProjectId, project);
treeView1.Nodes.Add(rootNode);
foreach(MasterStore.ProvidersRow provider in project.Providers())
{
StageNode providerNode = MakeNode(provider.Name, StageNodeType.Provider, provider.ProviderId, provider);
rootNode.Nodes.Add(providerNode);
}
}
const string connStringText = "Connection Strings";
StageNode connectionStringFolderNode = MakeNode(connStringText, connStringText, connStringText, StageNodeType.ConnectionStringFolder, null, null);
treeView1.Nodes.Add(connectionStringFolderNode);
MasterStore.ConnectionStringsRow[] connStrings =
(MasterStore.ConnectionStringsRow[])MM.ConnectionStrings.Select(String.Empty, MM.ConnectionStrings.NameColumn.ColumnName + " ASC");
foreach(MasterStore.ConnectionStringsRow connectionString in connStrings)
{
StageNode connectionStringNode = MakeNode(connectionString.Name, StageNodeType.ConnectionString, connectionString.ConnectionStringId, connectionString);
connectionStringFolderNode.Nodes.Add(connectionStringNode);
}
const string configText = "SubStage Configuration";
StageNode configurationNode = MakeNode(configText, StageNodeType.SubStageConfiguration, config.SubStageConfigurationId, config);
treeView1.Nodes.Add(configurationNode);
treeView1.EndUpdate();
//MM.Projects
}
private static CustomProperty CreateCustomProperty(DataRow row, DataColumn dc, bool readOnly, bool visible, string category)
{
CustomProperty cp = new CustomProperty();
cp.Name = dc.ColumnName;
cp.Tag = dc.ColumnName + "|" + row[0];
cp.IsReadOnly = readOnly;
cp.Visible = visible;
cp.Value = row[dc];
cp.Description = dc.Caption;
cp.Category = category;
cp.DefaultValue = dc.DefaultValue;
return cp;
}
private static CustomProperty CreateCustomProperty(string propertyName, string propertyValue, string description)
{
CustomProperty cp = new CustomProperty();
cp.Name = propertyName;
cp.Value = propertyValue ?? String.Empty;
cp.IsReadOnly = true;
cp.IsBrowsable = false;
cp.Visible = true;
cp.Description = description;
return cp;
}
private void TogglePropertyGridButtons(StageNode node)
{
pgbTestConnection.Visible = node.NodeType == StageNodeType.Provider;
}
private void ToggleContextMenuItems(StageNode node)
{
cmiTreeDeleteProject.Enabled = node.IsProjectNode;
cmiTreeAddProvider.Enabled = node.IsProjectNode;
cmiTreeDeleteProvider.Enabled = node.IsProviderNode;
cmiTreeAddConnectionString.Enabled = node.IsConnectionStringFolderNode;
cmiTreeDeleteConnectionString.Enabled = node.IsConnectionStringNode;
if(node.IsTableNode || node.IsViewNode)
{
cmiGenerateObjectEnabled.Visible = true;
//cmiGenerateObjectEnabled.Enabled = true;
SetGenerateButtonText(node);
}
else
{
cmiGenerateObjectEnabled.Visible = false;
//cmiGenerateObjectEnabled.Enabled = false;
}
}
/// <summary>
/// Sets the generate button text.
/// </summary>
/// <param name="node">The node.</param>
private void SetGenerateButtonText(StageNode node)
{
switch(node.NodeType)
{
case StageNodeType.StoredProcedure: //Nothing for now - where not going to get to here - TODO: make this work
case StageNodeType.StoredProcedureExcluded: //where not going to get to here (never shows up)
break;
case StageNodeType.Table:
case StageNodeType.TableWithoutPrimaryKey:
cmiGenerateObjectEnabled.Text = "Disable Generate Table";
break;
case StageNodeType.TableExcluded:
cmiGenerateObjectEnabled.Text = "Enable Generate Table";
break;
case StageNodeType.View:
cmiGenerateObjectEnabled.Text = "Disable Generate View";
break;
case StageNodeType.ViewExcluded:
cmiGenerateObjectEnabled.Text = "Enable Generate View";
break;
default:
cmiGenerateObjectEnabled.Text = "Generate Object?";
break;
}
}
private void ToggleToolbarItems(StageNode node)
{
btnNewProvider.Enabled = node.IsProjectNode;
btnAddConnectionString.Enabled = node.IsConnectionStringFolderNode;
btnInvokeProviders.Enabled = (node.IsProjectNode || node.IsProviderNode);
btnSplitGenerateCode.Enabled = (node.IsProjectNode || node.IsProviderNode);
}
private static void AddConfigProperty(StringBuilder sb, string propertyName, DataRow row, DataColumn dc, bool buildIfDefault)
{
if(row[dc] != null & !String.IsNullOrEmpty(row[dc].ToString()))
{
string propValue = row[dc].ToString();
string compareValue = dc.DefaultValue.ToString();
if(dc.DataType == typeof(bool))
{
propValue = propValue.ToLower();
compareValue = compareValue.ToLower();
}
if(propValue == compareValue && !buildIfDefault)
return;
if(sb.Length > 0)
sb.Append(SpecialString.SPACE);
sb.Append(propertyName);
sb.Append("=\"");
sb.Append(propValue);
sb.Append("\"");
}
}
private static void AddConfigProperty(StringBuilder sb, string property, string value)
{
if(!String.IsNullOrEmpty(value))
{
if(sb.Length > 0)
sb.Append(SpecialString.SPACE);
sb.Append(property);
sb.Append("=\"");
sb.Append(value);
sb.Append("\"");
}
}
private static bool IsDefaultValue(DataRow row, DataColumn dc)
{
if(row[dc] != null & !String.IsNullOrEmpty(row[dc].ToString()))
{
string propValue = row[dc].ToString();
string compareValue = dc.DefaultValue.ToString();
if(dc.DataType == typeof(bool))
{
propValue = propValue.ToLower();
compareValue = compareValue.ToLower();
}
return propValue == compareValue;
}
return false;
}
private void BuildConfig(MasterStore.ProjectsRow project)
{
//bool buildIfDefault = false;
if(project != null)
{
string newConfig = configTemplate;
StringBuilder sbConnections = new StringBuilder();
List<int> addedConnections = new List<int>();
foreach(MasterStore.ProvidersRow provider in project.Providers())
{
if(!provider.IsConnectionStringIdNull() && !addedConnections.Contains(provider.ConnectionStringId))
{
sbConnections.AppendLine("\t\t<add name=\"" + provider.ConnectionString.Name + "\" connectionString=\"" + provider.ConnectionString.ConnectionString +
"\"/>");
addedConnections.Add(provider.ConnectionStringId);
}
}
newConfig = newConfig.Replace(TEMPLATE_CONNECTION_STRINGS, sbConnections.ToString());
if(!project.IsDefaultProviderNull())
newConfig = newConfig.Replace(TEMPLATE_DEFAULT_PROVIDER, project.DefaultProviderEntry.Name);
newConfig = newConfig.Replace(TEMPLATE_TEMPLATE_DIRECTORY, project.TemplateDirectory);
newConfig = newConfig.Replace(TEMPLATE_ENABLE_TRACE, project.EnableTrace.ToString().ToLower());
StringBuilder sbService = new StringBuilder();
foreach(MasterStore.ProvidersRow provider in project.Providers())
sbService.Append(GetProviderConfigText(provider));
newConfig = newConfig.Replace(TEMPLATE_PROVIDERS, sbService.ToString());
tbxConfigOutput.Text = newConfig;
ActivateConfig();
InstantiateProvider(project);
}
}
private void ActivateConfig()
{
if(File.Exists(webConfigPath))
File.Delete(webConfigPath);
while(File.Exists(webConfigPath))
{
//wait...
}
File.WriteAllText(webConfigPath, tbxConfigOutput.Text);
while(!File.Exists(webConfigPath))
{
//wait...
}
}
private void PopulateProviderData(StageNode node)
{
MasterStore.ProjectsRow projectRow = node.Project;
InstantiateProvider(projectRow);
treeView1.BeginUpdate();
if(node.IsProjectNode)
{
foreach(MasterStore.ProvidersRow provider in projectRow.Providers())
PopulateProviderNodeData(provider);
}
else if(node.IsProviderNode)
{
MasterStore.ProvidersRow provider = node.Provider;
if(provider != null)
PopulateProviderNodeData(provider);
}
treeView1.EndUpdate();
}
private void GenerateCode(StageNode node)
{
MasterStore.ProjectsRow projectRow = node.Project;
InstantiateProvider(projectRow);
tabDetail.SelectedTab = tabDetailLog;
tabDetailLog.Focus();
string navigateTo = GenerateProviderCode(node);
tabDetail.SelectedTab = tabDetailFileBrowser;
tabDetailFileBrowser.Focus();
BuildDirectoryTree(navigateTo);
NavigateFileBrowser();
}
private void PopulateProviderNodeData(MasterStore.ProvidersRow provider)
{
StageNode findNode = FindNodeByRow(provider);
if(findNode != null)
{
findNode.Nodes.Clear();
if(DataService.Providers[provider.Name] != null)
{
DataService.Providers[provider.Name].ReloadSchema();
TableSchema.Table[] tables = DataService.GetTables(provider.Name);
if(tables.Length > 0)
{
StageNode tableFolderNode = MakeNode(TABLES, TABLES, TABLES, StageNodeType.TableFolder, null, provider);
findNode.Nodes.Add(tableFolderNode);
foreach(TableSchema.Table table in tables)
{
string displayName = miUseGeneratedNames.Checked ? table.ClassName : table.Name;
StageNodeType nodeType = table.HasPrimaryKey ? StageNodeType.Table : StageNodeType.TableWithoutPrimaryKey;
nodeType = CodeService.ShouldGenerate(table.Name, DataService.Providers[provider.Name].Name) ? nodeType : StageNodeType.TableExcluded;
StageNode tableNode = MakeNode(displayName, table.Name, table.ClassName, nodeType, table.Name, provider);
if(!table.HasPrimaryKey)
{
tableNode.ForeColor = Color.Red;
tableNode.ToolTipText = "There is no Primary Key on this table.";
}
tableFolderNode.Nodes.Add(tableNode);
TableSchema.TableColumnCollection columns = table.Columns;
foreach(TableSchema.TableColumn column in columns)
{
string displayColumnName = miUseGeneratedNames.Checked ? column.PropertyName : column.ColumnName;
StageNodeType columnNodeType = column.IsPrimaryKey ? StageNodeType.ColumnPrimaryKeyNode : StageNodeType.ColumnNode;
StageNode columnNode = MakeNode(displayColumnName, column.ColumnName, column.PropertyName, columnNodeType, column.ColumnName, provider);
tableNode.Nodes.Add(columnNode);
}
}
}
TableSchema.Table[] views = DataService.GetViews(provider.Name);
if(views.Length > 0)
{
StageNode viewFolderNode = MakeNode(VIEWS, VIEWS, VIEWS, StageNodeType.ViewFolder, null, provider);
findNode.Nodes.Add(viewFolderNode);
foreach(TableSchema.Table view in views)
{
StageNodeType nodeType = StageNodeType.View;
nodeType = CodeService.ShouldGenerate(view.Name, DataService.Providers[provider.Name].Name) ? nodeType : StageNodeType.ViewExcluded;
string displayName = miUseGeneratedNames.Checked ? view.ClassName : view.Name;
StageNode viewNode = MakeNode(displayName, view.Name, view.ClassName, nodeType, view.Name, provider);
viewFolderNode.Nodes.Add(viewNode);
TableSchema.TableColumnCollection columns = view.Columns;
foreach(TableSchema.TableColumn column in columns)
{
string displayColumnName = miUseGeneratedNames.Checked ? column.PropertyName : column.ColumnName;
StageNodeType columnNodeType = column.IsPrimaryKey ? StageNodeType.ColumnPrimaryKeyNode : StageNodeType.ColumnNode;
StageNode columnNode = MakeNode(displayColumnName, column.ColumnName, column.PropertyName, columnNodeType, column.ColumnName, provider);
viewNode.Nodes.Add(columnNode);
}
}
}
List<StoredProcedure> storedProcedures = DataService.GetSPSchemaCollection(provider.Name);
if(storedProcedures.Count > 0)
{
StageNode spFolderNode = MakeNode(STORED_PROCEDURES, STORED_PROCEDURES, STORED_PROCEDURES, StageNodeType.StoredProcedureFolder, null, provider);
findNode.Nodes.Add(spFolderNode);
foreach(StoredProcedure storedProcedure in storedProcedures)
{
string displayName = miUseGeneratedNames.Checked ? storedProcedure.DisplayName : storedProcedure.Name;
DataProvider thisProvider = DataService.Providers[provider.Name];
StageNodeType nodeType = CodeService.ShouldGenerate(storedProcedure.Name, thisProvider.IncludeProcedures, thisProvider.ExcludeProcedures, thisProvider)
? StageNodeType.StoredProcedure
: StageNodeType.StoredProcedureExcluded;
StageNode spNode = MakeNode(displayName, storedProcedure.Name, storedProcedure.DisplayName, nodeType, storedProcedure.Name, provider);
spFolderNode.Nodes.Add(spNode);
StoredProcedure.ParameterCollection parameters = storedProcedure.Parameters;
foreach(StoredProcedure.Parameter parameter in parameters)
{
string paramDisplayName = miUseGeneratedNames.Checked ? parameter.DisplayName : parameter.Name;
StageNode spParamNode = MakeNode(paramDisplayName, parameter.Name, parameter.DisplayName, StageNodeType.StoredProcedureParameter, parameter.Name,
provider);
spNode.Nodes.Add(spParamNode);
}
}
}
}
}
}
private static void AddToProviderConfig(NameValueCollection config, string key, DataRow row, DataColumn dc)
{
if(row != null)
{
if(!IsDefaultValue(row, dc))
{
string propValue = row[dc].ToString();
if(dc.DataType == typeof(bool))
propValue = propValue.ToLower();
config.Add(key, propValue);
}
}
}
private void ShowStatus(string statusText)
{
tbxLog.AppendText(String.Concat(String.Format("{0:T}", DateTime.Now), " - ", statusText, "\r\n"));
tsStatus.Text = statusText;
Application.DoEvents();
}
private static void InitializeProviderCollection()
{
DataService.Provider = new SqlDataProvider();
DataService.Providers = new DataProviderCollection();
}
private static StageNode GetCurrentProviderNode(StageNode selectedNode, ProviderBase provider)
{
if(selectedNode.IsProjectNode && selectedNode.Nodes.Count > 0)
{
foreach(StageNode childNode in selectedNode.Nodes)
{
if(childNode.Provider != null)
{
if(Utility.IsMatch(childNode.Provider.Name, provider.Name))
return childNode;
}
}
}
return selectedNode;
}
private string GetNodeGenerationPath(StageNode node)
{
const string backSlash = "\\";
string outDir = config.CodeGenerationPath;
if(node.Provider != null)
{
if(!String.IsNullOrEmpty(node.Provider.CodeGenerationPath))
outDir = node.Provider.CodeGenerationPath;
else if(!String.IsNullOrEmpty(node.Project.CodeGenerationPath))
outDir = node.Project.CodeGenerationPath;
if(!outDir.EndsWith(backSlash))
outDir = String.Concat(outDir, backSlash);
if (node.Provider.OrganizeCodeByProvider)
outDir = String.Concat(outDir, node.Provider.Name, backSlash);
}
if (!outDir.EndsWith(backSlash))
outDir = String.Concat(outDir, backSlash);
return outDir;
}
private string GenerateProviderCode(StageNode selectedNode)
{
TurboCompiler turboCompiler = new TurboCompiler();
ICodeLanguage language;
if(miGenerateVB.Checked)
language = new VBCodeLanguage();
else
language = new CSharpCodeLanguage();
//string outDir = codeDestination;
DataProviderCollection generationProviders = new DataProviderCollection();
string navigatePath = config.CodeGenerationPath;
if (selectedNode.IsProjectNode)
{
generationProviders = DataService.Providers;
if (selectedNode.Nodes.Count > 1)
navigatePath = GetNodeGenerationPath(selectedNode);
}
else if (selectedNode.IsProviderNode)
{
generationProviders.Add(DataService.Providers[selectedNode.Provider.Name]);
navigatePath = GetNodeGenerationPath(selectedNode);
}
foreach(DataProvider provider in generationProviders)
{
StageNode currentNode = GetCurrentProviderNode(selectedNode, provider);
if(currentNode != null)
{
string providerDir = GetNodeGenerationPath(currentNode);
if(!Directory.Exists(providerDir))
Directory.CreateDirectory(providerDir);
string[] tables = DataService.GetTableNames(provider.Name);
foreach(string tbl in tables)
{
if(CodeService.ShouldGenerate(tbl, provider.Name))
{
ShowStatus(String.Format("Generating {0}...", tbl));
string className = DataService.GetSchema(tbl, provider.Name, TableType.Table).ClassName;
TurboTemplate tt = CodeService.BuildClassTemplate(tbl, language, provider);
tt.OutputPath = Path.Combine(providerDir, className + language.FileExtension);
turboCompiler.AddTemplate(tt);
if(provider.GenerateODSControllers && provider.TableBaseClass != "RepositoryRecord")
{
TurboTemplate ttODS = CodeService.BuildODSTemplate(tbl, language, provider);
ttODS.OutputPath = Path.Combine(providerDir, className + "Controller" + language.FileExtension);
turboCompiler.AddTemplate(ttODS);
}
}
}
string[] views = DataService.GetViewNames(provider.Name);
foreach(string tbl in views)
{
if(CodeService.ShouldGenerate(tbl, provider.Name))
{
ShowStatus(String.Format("Generating {0}...", tbl));
string className = DataService.GetSchema(tbl, provider.Name, TableType.View).ClassName;
TurboTemplate tt = CodeService.BuildViewTemplate(tbl, language, provider);
tt.OutputPath = Path.Combine(providerDir, className + language.FileExtension);
turboCompiler.AddTemplate(tt);
}
}
if(provider.UseSPs)
{
ShowStatus("Generating Stored Procedures...");
string outPath = Path.Combine(providerDir, provider.SPClassName + language.FileExtension);
TurboTemplate tt = CodeService.BuildSPTemplate(language, provider);
tt.OutputPath = outPath;
turboCompiler.AddTemplate(tt);
}
ShowStatus("Generating Structs...");
string structPath = Path.Combine(providerDir, "AllStructs" + language.FileExtension);
TurboTemplate ttStructs = CodeService.BuildStructsTemplate(language, DataService.Provider);
ttStructs.OutputPath = structPath;
turboCompiler.AddTemplate(ttStructs);
if(miScriptSchemas.Checked && provider.NamedProviderType == DataProviderTypeName.SQL_SERVER)
{
ShowStatus("Scripting Schema...");
string schema = ScriptSchema(provider.DefaultConnectionString);
string outSchemaFileName =
string.Format("{0}_{1}_{2}_{3}_{4}_Schema.sql", DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day, Environment.UserName, provider.Name);
Files.CreateToFile(Path.Combine(providerDir, outSchemaFileName), schema);
}
if(miScriptData.Checked)
{
string outFileName = string.Format("{0}_Data_{1}_{2}_{3}.sql", provider.Name, DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day);
string outPath = Path.Combine(providerDir, outFileName);
using(StreamWriter sw = File.CreateText(outPath))
{
foreach(string tbl in tables)
{
if(CodeService.ShouldGenerate(tbl, provider.Name))
{
Utility.WriteTrace(String.Format("Scripting Table: {0}", tbl));
string dataScript = DataService.ScriptData(tbl, provider.Name);
sw.Write(dataScript);
sw.Write(Environment.NewLine);
}
}
}
}
}
}
turboCompiler.Run();
foreach(TurboTemplate template in turboCompiler.Templates)
{
ShowStatus(String.Concat("Writing ", template.TemplateName, " as ", template.OutputPath.Substring(template.OutputPath.LastIndexOf("\\") + 1)));
Files.CreateToFile(template.OutputPath, template.FinalCode);
}
ShowStatus("Finished.");
Application.DoEvents();
return navigatePath;
}
/// <summary>
/// Scripts the schema.
/// </summary>
/// <param name="connectionString">The connection string.</param>
/// <returns></returns>
public static string ScriptSchema(string connectionString)
{
StringBuilder result = new StringBuilder();
SqlConnection conn = new SqlConnection(connectionString);
SqlConnectionStringBuilder cString = new SqlConnectionStringBuilder(connectionString);
ServerConnection sconn = new ServerConnection(conn);
Microsoft.SqlServer.Management.Smo.Server server = new Microsoft.SqlServer.Management.Smo.Server(sconn);
Database db = server.Databases[cString.InitialCatalog];
Transfer trans = new Transfer(db);
//set the objects to copy
trans.CopyAllTables = true;
trans.CopyAllDefaults = true;
trans.CopyAllUserDefinedFunctions = true;
trans.CopyAllStoredProcedures = true;
trans.CopyAllViews = true;
trans.CopyData = true;
trans.CopySchema = true;
trans.DropDestinationObjectsFirst = true;
trans.UseDestinationTransaction = true;
trans.Options.AnsiFile = true;
trans.Options.ClusteredIndexes = true;
trans.Options.DriAll = true;
trans.Options.IncludeHeaders = true;
trans.Options.IncludeIfNotExists = true;
trans.Options.SchemaQualify = true;
StringCollection script = trans.ScriptTransfer();
foreach(string s in script)
result.AppendLine(s);
result.AppendLine();
result.AppendLine();
return result.ToString();
}
private static void InstantiateProvider(DataRow configSource)
{
bool isProjectSource = configSource is MasterStore.ProjectsRow;
//bool isProviderSource = configSource is DM.ProvidersRow;
MasterStore.ProjectsRow activeProject;
MasterStore.ProvidersRow[] activeProviders;
if(isProjectSource)
{
activeProject = (MasterStore.ProjectsRow)configSource;
activeProviders = activeProject.Providers();
}
else
{
activeProject = ((MasterStore.ProvidersRow)configSource).Project;
activeProviders = new MasterStore.ProvidersRow[] {(MasterStore.ProvidersRow)configSource};
}
SubSonicSection section = new SubSonicSection();
if(activeProject.DefaultProviderEntry != null)
section.DefaultProvider = activeProject.DefaultProviderEntry.Name;
else if(activeProject.Providers().Length > 0)
{
activeProject.DefaultProvider = activeProject.Providers()[0].ProviderId;
MM.Save();
}
else
{
activeProject.SetDefaultProviderNull();
MM.Save();
return;
}
section.TemplateDirectory = activeProject.TemplateDirectory;
CodeService.TemplateDirectory = section.TemplateDirectory;
InitializeProviderCollection();
foreach(MasterStore.ProvidersRow providerEntry in activeProviders)
{
NameValueCollection config = new NameValueCollection();
AddToProviderConfig(config, ConfigurationPropertyName.CONNECTION_STRING_NAME, providerEntry.ConnectionString, MM.ConnectionStrings.NameColumn);
AddToProviderConfig(config, ConfigurationPropertyName.APPEND_WITH, providerEntry, MM.Providers.AppendWithColumn);
AddToProviderConfig(config, ConfigurationPropertyName.ADDITIONAL_NAMESPACES, providerEntry, MM.Providers.AdditionalNamespacesColumn);
AddToProviderConfig(config, ConfigurationPropertyName.EXCLUDE_PROCEDURE_LIST, providerEntry, MM.Providers.ExcludeProcedureListColumn);
AddToProviderConfig(config, ConfigurationPropertyName.EXCLUDE_TABLE_LIST, providerEntry, MM.Providers.ExcludeTableListColumn);
AddToProviderConfig(config, ConfigurationPropertyName.EXTRACT_CLASS_NAME_FROM_SP_NAME, providerEntry, MM.Providers.ExtractClassNameFromSPNameColumn);
AddToProviderConfig(config, ConfigurationPropertyName.FIX_DATABASE_OBJECT_CASING, providerEntry, MM.Providers.FixDatabaseObjectCasingColumn);
AddToProviderConfig(config, ConfigurationPropertyName.FIX_PLURAL_CLASS_NAMES, providerEntry, MM.Providers.FixPluralClassNamesColumn);
AddToProviderConfig(config, ConfigurationPropertyName.GENERATED_NAMESPACE, providerEntry, MM.Providers.GeneratedNamespaceColumn);
AddToProviderConfig(config, ConfigurationPropertyName.GENERATE_LAZY_LOADS, providerEntry, MM.Providers.GenerateLazyLoadsColumn);
AddToProviderConfig(config, ConfigurationPropertyName.GENERATE_NULLABLE_PROPERTIES, providerEntry, MM.Providers.GenerateNullablePropertiesColumn);
AddToProviderConfig(config, ConfigurationPropertyName.GENERATE_ODS_CONTROLLERS, providerEntry, MM.Providers.GenerateODSControllersColumn);
AddToProviderConfig(config, ConfigurationPropertyName.GENERATE_RELATED_TABLES_AS_PROPERTIES, providerEntry, MM.Providers.GenerateRelatedTablesAsPropertiesColumn);
AddToProviderConfig(config, ConfigurationPropertyName.INCLUDE_PROCEDURE_LIST, providerEntry, MM.Providers.IncludeProcedureListColumn);
AddToProviderConfig(config, ConfigurationPropertyName.INCLUDE_TABLE_LIST, providerEntry, MM.Providers.IncludeTableListColumn);
AddToProviderConfig(config, ConfigurationPropertyName.REGEX_DICTIONARY_REPLACE, providerEntry, MM.Providers.RegexDictionaryReplaceColumn);
AddToProviderConfig(config, ConfigurationPropertyName.REGEX_IGNORE_CASE, providerEntry, MM.Providers.RegexIgnoreCaseColumn);
AddToProviderConfig(config, ConfigurationPropertyName.REGEX_MATCH_EXPRESSION, providerEntry, MM.Providers.RegexMatchExpressionColumn);
AddToProviderConfig(config, ConfigurationPropertyName.REGEX_REPLACE_EXPRESSION, providerEntry, MM.Providers.RegexReplaceExpressionColumn);
AddToProviderConfig(config, ConfigurationPropertyName.RELATED_TABLE_LOAD_PREFIX, providerEntry, MM.Providers.RelatedTableLoadPrefixColumn);
AddToProviderConfig(config, ConfigurationPropertyName.REMOVE_UNDERSCORES, providerEntry, MM.Providers.RemoveUnderscoresColumn);
AddToProviderConfig(config, ConfigurationPropertyName.SET_PROPERTY_DEFAULTS_FROM_DATABASE, providerEntry, MM.Providers.SetPropertyDefaultsFromDatabaseColumn);
AddToProviderConfig(config, ConfigurationPropertyName.SP_STARTS_WITH, providerEntry, MM.Providers.SPStartsWithColumn);
AddToProviderConfig(config, ConfigurationPropertyName.STORED_PROCEDURE_BASE_CLASS, providerEntry, MM.Providers.StoredProcedureBaseClassColumn);
AddToProviderConfig(config, ConfigurationPropertyName.STORED_PROCEDURE_CLASS_NAME, providerEntry, MM.Providers.SPClassNameColumn);
AddToProviderConfig(config, ConfigurationPropertyName.STRIP_COLUMN_TEXT, providerEntry, MM.Providers.StripColumnTextColumn);
AddToProviderConfig(config, ConfigurationPropertyName.STRIP_PARAM_TEXT, providerEntry, MM.Providers.StripParamTextColumn);
AddToProviderConfig(config, ConfigurationPropertyName.STRIP_STORED_PROCEDURE_TEXT, providerEntry, MM.Providers.StripSPTextColumn);
AddToProviderConfig(config, ConfigurationPropertyName.STRIP_TABLE_TEXT, providerEntry, MM.Providers.StripTableTextColumn);
AddToProviderConfig(config, ConfigurationPropertyName.STRIP_VIEW_TEXT, providerEntry, MM.Providers.StripViewTextColumn);
AddToProviderConfig(config, ConfigurationPropertyName.TABLE_BASE_CLASS, providerEntry, MM.Providers.TableBaseClassColumn);
AddToProviderConfig(config, ConfigurationPropertyName.USE_EXTENDED_PROPERTIES, providerEntry, MM.Providers.UseExtendedPropertiesColumn);
AddToProviderConfig(config, ConfigurationPropertyName.USE_STORED_PROCEDURES, providerEntry, MM.Providers.UseSPsColumn);
AddToProviderConfig(config, ConfigurationPropertyName.USE_UTC_TIMES, providerEntry, MM.Providers.UseUTCColumn);
AddToProviderConfig(config, ConfigurationPropertyName.VIEW_BASE_CLASS, providerEntry, MM.Providers.ViewBaseClassColumn);
AddToProviderConfig(config, ConfigurationPropertyName.VIEW_STARTS_WITH, providerEntry, MM.Providers.ViewStartsWithColumn);
if(!providerEntry.IsConnectionStringIdNull())
{
string connString = providerEntry.ConnectionString.ConnectionString;
string location = providerEntry.Project.OriginalLocation;
location = location.EndsWith(@"\") ? location : location + @"\";
location += @"App_Data\";
bool loadProvider = true;
string modConn = Regex.Replace(connString, @"\|DataDirectory\|", location, RegexOptions.IgnoreCase);
if(!Utility.IsMatch(modConn, connString))
{
Match dbFileName = Regex.Match(connString, @"(?<=\|DataDirectory\|).*\.mdf", RegexOptions.IgnoreCase);
if(dbFileName != null)
{
string fileLocation = location + dbFileName.Value;
if(!File.Exists(fileLocation))
loadProvider = false;
}
}
if(loadProvider)
{
Assembly asm = Assembly.Load("SubSonic");
Type type = asm.GetType("SubSonic." + providerEntry.ProviderType.InternalName);
if(type != null)
{
DataProvider provider = (DataProvider)Activator.CreateInstance(type, false);
provider.Initialize(providerEntry.Name, config);
provider.DefaultConnectionString = modConn;
DataService.Providers.Add(provider);
}
}
}
}
Application.DoEvents();
}
private static string GetProviderConfigText(MasterStore.ProvidersRow provider)
{
const bool buildIfDefault = false;
StringBuilder sbService = new StringBuilder();
sbService.Append("\t\t\t<add name=\"" + provider.Name + "\" type=\"SubSonic." + provider.ProviderType.InternalName + ", SubSonic\"");
if(!provider.IsConnectionStringIdNull())
AddConfigProperty(sbService, ConfigurationPropertyName.CONNECTION_STRING_NAME, provider.ConnectionString.Name);
AddConfigProperty(sbService, ConfigurationPropertyName.APPEND_WITH, provider, MM.Providers.AppendWithColumn, buildIfDefault);
AddConfigProperty(sbService, ConfigurationPropertyName.ADDITIONAL_NAMESPACES, provider, MM.Providers.AdditionalNamespacesColumn, buildIfDefault);
AddConfigProperty(sbService, ConfigurationPropertyName.EXCLUDE_PROCEDURE_LIST, provider, MM.Providers.ExcludeProcedureListColumn, buildIfDefault);
AddConfigProperty(sbService, ConfigurationPropertyName.EXCLUDE_TABLE_LIST, provider, MM.Providers.ExcludeTableListColumn, buildIfDefault);
AddConfigProperty(sbService, ConfigurationPropertyName.EXTRACT_CLASS_NAME_FROM_SP_NAME, provider, MM.Providers.ExtractClassNameFromSPNameColumn, buildIfDefault);
AddConfigProperty(sbService, ConfigurationPropertyName.FIX_DATABASE_OBJECT_CASING, provider, MM.Providers.FixDatabaseObjectCasingColumn, buildIfDefault);
AddConfigProperty(sbService, ConfigurationPropertyName.FIX_PLURAL_CLASS_NAMES, provider, MM.Providers.FixPluralClassNamesColumn, buildIfDefault);
AddConfigProperty(sbService, ConfigurationPropertyName.GENERATED_NAMESPACE, provider, MM.Providers.GeneratedNamespaceColumn, buildIfDefault);
AddConfigProperty(sbService, ConfigurationPropertyName.GENERATE_LAZY_LOADS, provider, MM.Providers.GenerateLazyLoadsColumn, buildIfDefault);
AddConfigProperty(sbService, ConfigurationPropertyName.GENERATE_NULLABLE_PROPERTIES, provider, MM.Providers.GenerateNullablePropertiesColumn, buildIfDefault);
AddConfigProperty(sbService, ConfigurationPropertyName.GENERATE_ODS_CONTROLLERS, provider, MM.Providers.GenerateODSControllersColumn, buildIfDefault);
AddConfigProperty(sbService, ConfigurationPropertyName.GENERATE_RELATED_TABLES_AS_PROPERTIES, provider, MM.Providers.GenerateRelatedTablesAsPropertiesColumn,
buildIfDefault);
AddConfigProperty(sbService, ConfigurationPropertyName.INCLUDE_PROCEDURE_LIST, provider, MM.Providers.IncludeProcedureListColumn, buildIfDefault);
AddConfigProperty(sbService, ConfigurationPropertyName.INCLUDE_TABLE_LIST, provider, MM.Providers.IncludeTableListColumn, buildIfDefault);
AddConfigProperty(sbService, ConfigurationPropertyName.REGEX_DICTIONARY_REPLACE, provider, MM.Providers.RegexDictionaryReplaceColumn, buildIfDefault);
AddConfigProperty(sbService, ConfigurationPropertyName.REGEX_IGNORE_CASE, provider, MM.Providers.RegexIgnoreCaseColumn, buildIfDefault);
AddConfigProperty(sbService, ConfigurationPropertyName.REGEX_MATCH_EXPRESSION, provider, MM.Providers.RegexMatchExpressionColumn, buildIfDefault);
AddConfigProperty(sbService, ConfigurationPropertyName.REGEX_REPLACE_EXPRESSION, provider, MM.Providers.RegexReplaceExpressionColumn, buildIfDefault);
AddConfigProperty(sbService, ConfigurationPropertyName.RELATED_TABLE_LOAD_PREFIX, provider, MM.Providers.RelatedTableLoadPrefixColumn, buildIfDefault);
AddConfigProperty(sbService, ConfigurationPropertyName.REMOVE_UNDERSCORES, provider, MM.Providers.RemoveUnderscoresColumn, buildIfDefault);
AddConfigProperty(sbService, ConfigurationPropertyName.SET_PROPERTY_DEFAULTS_FROM_DATABASE, provider, MM.Providers.SetPropertyDefaultsFromDatabaseColumn, buildIfDefault);
AddConfigProperty(sbService, ConfigurationPropertyName.SP_STARTS_WITH, provider, MM.Providers.SPStartsWithColumn, buildIfDefault);
AddConfigProperty(sbService, ConfigurationPropertyName.STORED_PROCEDURE_CLASS_NAME, provider, MM.Providers.StoredProcedureBaseClassColumn, buildIfDefault);
AddConfigProperty(sbService, ConfigurationPropertyName.STORED_PROCEDURE_CLASS_NAME, provider, MM.Providers.SPClassNameColumn, buildIfDefault);
AddConfigProperty(sbService, ConfigurationPropertyName.STRIP_COLUMN_TEXT, provider, MM.Providers.StripColumnTextColumn, buildIfDefault);
AddConfigProperty(sbService, ConfigurationPropertyName.STRIP_PARAM_TEXT, provider, MM.Providers.StripParamTextColumn, buildIfDefault);
AddConfigProperty(sbService, ConfigurationPropertyName.STRIP_STORED_PROCEDURE_TEXT, provider, MM.Providers.StripSPTextColumn, buildIfDefault);
AddConfigProperty(sbService, ConfigurationPropertyName.STRIP_TABLE_TEXT, provider, MM.Providers.StripTableTextColumn, buildIfDefault);
AddConfigProperty(sbService, ConfigurationPropertyName.STRIP_VIEW_TEXT, provider, MM.Providers.StripViewTextColumn, buildIfDefault);
AddConfigProperty(sbService, ConfigurationPropertyName.TABLE_BASE_CLASS, provider, MM.Providers.TableBaseClassColumn, buildIfDefault);
AddConfigProperty(sbService, ConfigurationPropertyName.USE_EXTENDED_PROPERTIES, provider, MM.Providers.UseExtendedPropertiesColumn, buildIfDefault);
AddConfigProperty(sbService, ConfigurationPropertyName.USE_STORED_PROCEDURES, provider, MM.Providers.UseSPsColumn, buildIfDefault);
AddConfigProperty(sbService, ConfigurationPropertyName.USE_UTC_TIMES, provider, MM.Providers.UseUTCColumn, buildIfDefault);
AddConfigProperty(sbService, ConfigurationPropertyName.VIEW_BASE_CLASS, provider, MM.Providers.ViewBaseClassColumn, buildIfDefault);
AddConfigProperty(sbService, ConfigurationPropertyName.VIEW_STARTS_WITH, provider, MM.Providers.ViewStartsWithColumn, buildIfDefault);
sbService.AppendLine("/>");
return sbService.ToString();
}
private static object GetConfig(ProviderSettings settings, string key, DataColumn dc)
{
if(settings.Parameters[key] != null)
return settings.Parameters[key];
return dc != null ? dc.DefaultValue : String.Empty;
}
private void LoadScaffold(StageNode node)
{
if(node != null && tabMaster.SelectedTab == tabMasterScaffolds && node.Project != null)
{
string outputText = null;
if(node.IsTableNode)
{
outputText = scaffoldTemplate.Replace(TEMPLATE_SCAFFOLD_PROPERTIES,
"ScaffoldType=\"Normal\" TableName=\"" + node.DatabaseName + "\" ProviderName=\"" + node.Provider.Name + "\"");
}
else if(node.IsProjectNode)
outputText = scaffoldTemplate.Replace(TEMPLATE_SCAFFOLD_PROPERTIES, "ScaffoldType=\"Auto\"");
if(!String.IsNullOrEmpty(outputText))
{
if(File.Exists(scaffoldFilePath))
File.Delete(scaffoldFilePath);
File.WriteAllText(scaffoldFilePath, outputText);
while(!File.Exists(scaffoldFilePath))
{
//wait
}
webScaffolds.Navigate(scaffoldUrlPath + "?nocache=" + Guid.NewGuid());
}
else
webScaffolds.Navigate(scaffoldInfoUrlPath);
}
}
private void tabMaster_SelectedIndexChanged(object sender, EventArgs e)
{
LoadScaffold((StageNode)treeView1.SelectedNode);
}
private void SubStageForm_FormClosed(object sender, FormClosedEventArgs e)
{
//Some times the app doesn't really close it just closes the form so lets make sure it closes.
Application.Exit();
}
private void NavigateFileBrowser(string path)
{
if(fileBrowser.AllowNavigation)
{
fileBrowser.AllowNavigation = false;
fileBrowser.SuspendLayout();
fileBrowser.Navigate(path);
fileBrowser.ResumeLayout();
fileBrowser.AllowNavigation = true;
}
}
private void NavigateFileBrowser()
{
if(treeFileSystem.SelectedNode != null)
NavigateFileBrowser(FILE_URL_PREFIX + treeFileSystem.SelectedNode.Tag);
}
private void treeFileSystem_BeforeExpand(object sender, TreeViewCancelEventArgs e)
{
navigatingFromFileTree = true;
treeFileSystem.BeginUpdate();
foreach(TreeNode subNode in e.Node.Nodes)
GetSubNodes(subNode, null);
treeFileSystem.EndUpdate();
}
private void treeFileSystem_AfterSelect(object sender, TreeViewEventArgs e)
{
navigatingFromFileTree = true;
treeFileSystem.BeginUpdate();
GetSubNodes(e.Node, null);
foreach(TreeNode subNode in e.Node.Nodes)
GetSubNodes(subNode, null);
treeFileSystem.EndUpdate();
NavigateFileBrowser(FILE_URL_PREFIX + e.Node.Tag);
}
private void fileBrowser_Navigating(object sender, WebBrowserNavigatingEventArgs e)
{
if(!navigatingFromFileTree)
BuildDirectoryTree(e.Url.AbsolutePath.Replace(FILE_URL_PREFIX, String.Empty));
navigatingFromFileTree = false;
}
private void fileBrowser_Navigated(object sender, WebBrowserNavigatedEventArgs e)
{
//BuildDirectoryTree(e.Url.AbsolutePath.Replace(FILE_URL_PREFIX, String.Empty));
}
#region Node Operations
private StageNode FindNodeByRow(DataRow row)
{
return FindNodeByRow(row, treeView1.Nodes);
}
private static StageNode FindNodeByRow(DataRow row, TreeNodeCollection searchNodes)
{
StageNode foundNode = null;
foreach(StageNode node in searchNodes)
{
foundNode = IsNodeMatch(row, node) ? node : FindNodeByRow(row, node.Nodes);
if(foundNode != null)
break;
}
return foundNode;
}
private static bool IsNodeMatch(DataRow row, StageNode node)
{
if(node.IsProjectNode && row is MasterStore.ProjectsRow && ((MasterStore.ProjectsRow)row).ProjectId == node.Project.ProjectId)
return true;
if(node.IsProviderNode && row is MasterStore.ProvidersRow && ((MasterStore.ProvidersRow)row).ProviderId == node.Provider.ProviderId)
return true;
if(node.IsConnectionStringNode && row is MasterStore.ConnectionStringsRow &&
((MasterStore.ConnectionStringsRow)row).ConnectionStringId == node.ConnectionString.ConnectionStringId)
return true;
return false;
}
private void UpdateNodeName(DataRow row, string newName)
{
StageNode findNode = FindNodeByRow(row);
if(findNode != null)
findNode.Text = newName;
}
private void SelectNode(StageNode node)
{
//ShowStatus("Ready.");
if(node.IsProjectNode)
{
LoadProjectProperties(node);
BuildConfig(node.Project);
string path = GetNodeGenerationPath(node);
BuildDirectoryTree(path);
NavigateFileBrowser(path);
}
else if(node.IsProviderNode)
{
LoadProviderProperties(node);
BuildConfig(node.Project);
string path = GetNodeGenerationPath(node);
BuildDirectoryTree(path);
NavigateFileBrowser(path);
}
else if(node.IsConnectionStringNode)
LoadConnectionStringProperties(node);
else if(node.IsTableNode || node.IsViewNode)
LoadTableProperties(node);
else if(node.IsColumnNode)
LoadColumnProperties(node);
else if(node.NodeType == StageNodeType.StoredProcedure)
LoadStoredProcedureProperties(node);
else if(node.NodeType == StageNodeType.StoredProcedureParameter)
LoadStoredProcedureParameterProperties(node);
else if(node.NodeType == StageNodeType.SubStageConfiguration)
LoadConfigurationProperties(node);
ToggleToolbarItems(node);
TogglePropertyGridButtons(node);
LoadScaffold(node);
}
#endregion
#region Property Loaders
private static string GetTagString(object tag)
{
if(tag != null)
{
string tagValue = tag.ToString();
return tagValue.Split(new char[] {'|'})[0];
}
return String.Empty;
}
private void LoadConnectionStringProperties(StageNode node)
{
if(node.ConnectionString != null)
{
pGrid.Tag = node;
pGrid.ShowCustomProperties = true;
pGrid.Items.Clear();
const string category = "Connection String Properties";
pGrid.Items.Add(CreateCustomProperty(node.ConnectionString, MM.ConnectionStrings.NameColumn, false, true, category));
pGrid.Items.Add(CreateCustomProperty(node.ConnectionString, MM.ConnectionStrings.ConnectionStringColumn, false, true, category));
pGrid.Refresh();
}
}
private void LoadConfigurationProperties(StageNode node)
{
pGrid.Tag = node;
pGrid.ShowCustomProperties = true;
pGrid.Items.Clear();
pGrid.Items.Add(CreateCustomProperty(config, MM.SubStageConfiguration.CodeGenerationLanguageColumn, false, true, CODE_GENERATION));
CustomProperty cpCodeGenerationPath = CreateCustomProperty(config, MM.SubStageConfiguration.CodeGenerationPathColumn, false, true, CODE_GENERATION);
cpCodeGenerationPath.CustomEditor = new FolderNameEditor();
pGrid.Items.Add(cpCodeGenerationPath);
pGrid.Items.Add(CreateCustomProperty(config, MM.SubStageConfiguration.OrganizeCodeByProviderColumn, false, true, CODE_GENERATION));
const string category = "Embedded Web Server";
CustomProperty cpWebServerRootPath = CreateCustomProperty(config, MM.SubStageConfiguration.WebServerRootPathColumn, false, true, category);
cpWebServerRootPath.CustomEditor = new FolderNameEditor();
pGrid.Items.Add(cpWebServerRootPath);
pGrid.Items.Add(CreateCustomProperty(config, MM.SubStageConfiguration.WebServerPortColumn, false, true, category));
pGrid.Refresh();
}
private void LoadProjectProperties(StageNode node)
{
if(node.Project != null)
{
pGrid.Tag = node;
pGrid.ShowCustomProperties = true;
pGrid.Items.Clear();
const string category = "Project Properties";
pGrid.Items.Add(CreateCustomProperty(node.Project, MM.Projects.NameColumn, false, true, category));
pGrid.Items.Add(CreateCustomProperty(node.Project, MM.Projects.OriginalLocationColumn, true, true, category));
pGrid.Items.Add(CreateCustomProperty(node.Project, MM.Projects.EnableTraceColumn, false, true, category));
if(node.Project.Providers().Length > 0)
{
if(node.Project.IsDefaultProviderNull())
{
node.Project.DefaultProvider = node.Project.Providers()[0].ProviderId;
MM.Save();
}
string displayValue = node.Project.DefaultProviderEntry.Name;
pGrid.Items.Add(MM.Projects.DefaultProviderColumn.ColumnName, displayValue, false, category, MM.Projects.DefaultProviderColumn.Caption,
true);
int currentIndex = pGrid.Items.Count - 1;
pGrid.Items[currentIndex].Tag = MM.Projects.DefaultProviderColumn.ColumnName + "|" + node.Project.ProjectId;
pGrid.Items[currentIndex].ValueMember = MM.Providers.ProviderIdColumn.ColumnName;
pGrid.Items[currentIndex].DisplayMember = MM.Providers.NameColumn.ColumnName;
pGrid.Items[currentIndex].Datasource = node.Project.Providers();
pGrid.Items[currentIndex].SelectedValue = node.Project.DefaultProvider;
}
else
{
pGrid.Items.Add(MM.Projects.DefaultProviderColumn.ColumnName, "No Providers Available", true, category,
MM.Projects.DefaultProviderColumn.Caption, true);
}
CustomProperty cpCodeGenerationPath = CreateCustomProperty(node.Project, MM.Projects.CodeGenerationPathColumn, false, true, CODE_GENERATION);
cpCodeGenerationPath.CustomEditor = new FolderNameEditor();
pGrid.Items.Add(cpCodeGenerationPath);
pGrid.Items.Add(CreateCustomProperty(node.Project, MM.Projects.OrganizeCodeByProviderColumn, false, true, CODE_GENERATION));
CustomProperty cpTemplateDirectory = CreateCustomProperty(node.Project, MM.Projects.TemplateDirectoryColumn, false, true, CODE_GENERATION);
cpTemplateDirectory.CustomEditor = new FolderNameEditor();
pGrid.Items.Add(cpTemplateDirectory);
pGrid.Refresh();
}
}
private void LoadTableProperties(StageNode node)
{
if(node.Provider != null)
{
TableType tableType = node.IsTableNode ? TableType.Table : TableType.View;
InstantiateProvider(node.Provider);
TableSchema.Table table = DataService.GetInstance(node.Provider.Name).GetTableSchema(node.ItemKey, tableType);
if(table != null)
{
pGrid.Tag = node;
pGrid.ShowCustomProperties = true;
pGrid.Items.Clear();
pGrid.Items.Add(CreateCustomProperty("Class Name", table.ClassName, "The name of the generated class."));
pGrid.Items.Add(CreateCustomProperty("Database Name", table.Name, "The name of the underlying database object."));
pGrid.Items.Add(CreateCustomProperty("Has Primary Key", BoolToYesNo(table.HasPrimaryKey), "Whether or not the table has at least one primary key."));
pGrid.Items.Add(CreateCustomProperty("Has Foreign Keys", BoolToYesNo(table.HasForeignKeys), "Whether or not the table has one or more foreign keys."));
pGrid.Refresh();
}
}
}
private void LoadColumnProperties(StageNode node)
{
if(node.Provider != null)
{
TableType tableType = node.IsTableNode ? TableType.Table : TableType.View;
InstantiateProvider(node.Provider);
TableSchema.Table table = DataService.GetInstance(node.Provider.Name).GetTableSchema(((StageNode)node.Parent).ItemKey, tableType);
if(table != null)
{
TableSchema.TableColumn column = table.GetColumn(node.ItemKey);
if(column != null)
{
pGrid.Tag = node;
pGrid.ShowCustomProperties = true;
pGrid.Items.Clear();
pGrid.Items.Add(CreateCustomProperty("Property Name", column.PropertyName, "The name of the generated property."));
pGrid.Items.Add(CreateCustomProperty("Display Name", column.DisplayName, "The formatted display name."));
pGrid.Items.Add(CreateCustomProperty("Database Name", column.ColumnName, "The name of the underlying database object."));
pGrid.Items.Add(CreateCustomProperty("Data Type", column.DataType.ToString(), "The data type of the property."));
pGrid.Items.Add(CreateCustomProperty("System Type", column.GetPropertyType().ToString(), "The system type of the property."));
pGrid.Items.Add(CreateCustomProperty("Default Setting", column.DefaultSetting, "The default setting of the property."));
pGrid.Items.Add(CreateCustomProperty("Max Length", column.MaxLength.ToString(), "The maximum length of this property value."));
pGrid.Items.Add(CreateCustomProperty("Numeric", BoolToYesNo(column.IsNumeric), "Whether or not this property is numeric."));
pGrid.Items.Add(CreateCustomProperty("Date/Time", BoolToYesNo(column.IsDateTime), "Whether or not this property is date/time."));
pGrid.Items.Add(CreateCustomProperty("Nullable", BoolToYesNo(column.IsNullable), "Whether or not this property is nullable."));
pGrid.Items.Add(CreateCustomProperty("Read Only", BoolToYesNo(column.IsReadOnly), "Whether or not this property is read only."));
pGrid.Items.Add(
CreateCustomProperty("Managed by SubSonic", BoolToYesNo(column.IsReservedColumn), "Whether or not SubSonic manages the value of this property."));
pGrid.Refresh();
}
}
}
}
private void LoadStoredProcedureProperties(StageNode node)
{
if(node.Provider != null)
{
InstantiateProvider(node.Provider);
StoredProcedure storedProcedure = null;
List<StoredProcedure> storedProcedures = DataService.GetSPSchemaCollection(node.Provider.Name);
foreach(StoredProcedure sp in storedProcedures)
{
if(sp.Name == node.ItemKey)
{
storedProcedure = sp;
break;
}
}
if(storedProcedure != null)
{
pGrid.Tag = node;
pGrid.ShowCustomProperties = true;
pGrid.Items.Clear();
pGrid.Items.Add(CreateCustomProperty("Display Name", storedProcedure.DisplayName, "The formatted display name."));
pGrid.Items.Add(CreateCustomProperty("Database Name", storedProcedure.Name, "The name of the underlying database object."));
pGrid.Items.Add(CreateCustomProperty("Schema Name", storedProcedure.SchemaName, "The name of the schema this stored procedure belongs to."));
pGrid.Refresh();
}
}
}
private void LoadStoredProcedureParameterProperties(StageNode node)
{
if(node.Provider != null)
{
InstantiateProvider(node.Provider);
StoredProcedure storedProcedure = null;
List<StoredProcedure> storedProcedures = DataService.GetSPSchemaCollection(node.Provider.Name);
foreach(StoredProcedure sp in storedProcedures)
{
if(sp.Name == ((StageNode)node.Parent).ItemKey)
{
storedProcedure = sp;
break;
}
}
if(storedProcedure != null)
{
StoredProcedure.Parameter parameter = null;
foreach(StoredProcedure.Parameter p in storedProcedure.Parameters)
{
if(p.Name == node.ItemKey)
{
parameter = p;
break;
}
}
if(parameter != null)
{
pGrid.Tag = node;
pGrid.ShowCustomProperties = true;
pGrid.Items.Clear();
pGrid.Items.Add(CreateCustomProperty("Display Name", parameter.DisplayName, "The formatted display name."));
pGrid.Items.Add(CreateCustomProperty("Database Name", parameter.Name, "The name of the underlying database object."));
pGrid.Items.Add(CreateCustomProperty("Parameter Mode", parameter.Mode.ToString(), "The mode that this parameter operates in."));
pGrid.Items.Add(CreateCustomProperty("Database Type", parameter.DBType.ToString(), "The database type of the parameter."));
pGrid.Refresh();
}
}
}
}
private static string BoolToYesNo(bool booleanValue)
{
return booleanValue ? "Yes" : "No";
}
private void LoadProviderProperties(StageNode node)
{
if(node.Provider != null)
{
pGrid.Tag = node;
pGrid.ShowCustomProperties = true;
pGrid.Items.Clear();
const string category = "General";
pGrid.Items.Add(CreateCustomProperty(node.Provider, MM.Providers.NameColumn, false, true, category));
pGrid.Items.Add(CreateCustomProperty(node.Provider, MM.Providers.GeneratedNamespaceColumn, false, true, category));
if(MM.ConnectionStrings.Count > 0)
{
if(node.Provider.IsConnectionStringIdNull())
{
node.Provider.ConnectionStringId = MM.ConnectionStrings[0].ConnectionStringId;
MM.Save();
}
string displayValue = node.Provider.ConnectionString.Name;
pGrid.Items.Add(MM.Providers.ConnectionStringIdColumn.ColumnName, displayValue, false, category, "Connection String", true);
int currentIndex = pGrid.Items.Count - 1;
pGrid.Items[currentIndex].Tag = MM.Providers.ConnectionStringIdColumn.ColumnName + "|" + node.Provider.ProviderId;
pGrid.Items[currentIndex].ValueMember = MM.ConnectionStrings.ConnectionStringIdColumn.ColumnName;
pGrid.Items[currentIndex].DisplayMember = MM.ConnectionStrings.NameColumn.ColumnName;
pGrid.Items[currentIndex].Datasource = MM.ConnectionStrings;
pGrid.Items[currentIndex].SelectedValue = node.Provider.ConnectionStringId;
}
else
{
pGrid.Items.Add(MM.Providers.ConnectionStringIdColumn.ColumnName, "No Connection Strings Available", true, category,
MM.Providers.ConnectionStringIdColumn.Caption, true);
}
if(MM.ProviderTypes.Count > 0)
{
if(node.Provider.IsProviderTypeIdNull())
{
node.Provider.ProviderTypeId = MM.ProviderTypes[0].ProviderTypeId;
MM.Save();
}
string displayValue = node.Provider.ProviderType.DisplayName;
pGrid.Items.Add(MM.Providers.ProviderTypeIdColumn.ColumnName, displayValue, false, category, MM.Providers.ProviderTypeIdColumn.Caption, true);
int currentIndex = pGrid.Items.Count - 1;
pGrid.Items[currentIndex].Tag = MM.Providers.ProviderTypeIdColumn.ColumnName + "|" + node.Provider.ProviderId;
pGrid.Items[currentIndex].ValueMember = MM.ProviderTypes.ProviderTypeIdColumn.ColumnName;
pGrid.Items[currentIndex].DisplayMember = MM.ProviderTypes.DisplayNameColumn.ColumnName;
pGrid.Items[currentIndex].Datasource = MM.ProviderTypes;
pGrid.Items[currentIndex].SelectedValue = node.Provider.ProviderType;
}
CustomProperty cpCodeGenerationPath = CreateCustomProperty(node.Provider, MM.Providers.CodeGenerationPathColumn, false, true, CODE_GENERATION);
cpCodeGenerationPath.CustomEditor = new FolderNameEditor();
pGrid.Items.Add(cpCodeGenerationPath);
pGrid.Items.Add(CreateCustomProperty(node.Provider, MM.Providers.OrganizeCodeByProviderColumn, false, true, CODE_GENERATION));
pGrid.Items.Add(CreateCustomProperty(node.Provider, MM.Providers.RemoveUnderscoresColumn, false, true, GLOBAL));
pGrid.Items.Add(CreateCustomProperty(node.Provider, MM.Providers.AppendWithColumn, false, true, GLOBAL));
pGrid.Items.Add(CreateCustomProperty(node.Provider, MM.Providers.AdditionalNamespacesColumn, false, true, GLOBAL));
pGrid.Items.Add(CreateCustomProperty(node.Provider, MM.Providers.FixDatabaseObjectCasingColumn, false, true, GLOBAL));
pGrid.Items.Add(CreateCustomProperty(node.Provider, MM.Providers.FixPluralClassNamesColumn, false, true, GLOBAL));
pGrid.Items.Add(CreateCustomProperty(node.Provider, MM.Providers.GenerateNullablePropertiesColumn, false, true, GLOBAL));
pGrid.Items.Add(CreateCustomProperty(node.Provider, MM.Providers.GenerateODSControllersColumn, false, true, GLOBAL));
pGrid.Items.Add(CreateCustomProperty(node.Provider, MM.Providers.SetPropertyDefaultsFromDatabaseColumn, false, true, GLOBAL));
pGrid.Items.Add(CreateCustomProperty(node.Provider, MM.Providers.UseExtendedPropertiesColumn, false, true, GLOBAL));
pGrid.Items.Add(CreateCustomProperty(node.Provider, MM.Providers.UseUTCColumn, false, true, GLOBAL));
pGrid.Items.Add(CreateCustomProperty(node.Provider, MM.Providers.RelatedTableLoadPrefixColumn, false, true, TABLES));
pGrid.Items.Add(CreateCustomProperty(node.Provider, MM.Providers.GenerateRelatedTablesAsPropertiesColumn, false, true, TABLES));
pGrid.Items.Add(CreateCustomProperty(node.Provider, MM.Providers.GenerateLazyLoadsColumn, false, true, TABLES));
pGrid.Items.Add(CreateCustomProperty(node.Provider, MM.Providers.ManyToManySuffixColumn, false, true, TABLES));
pGrid.Items.Add(CreateCustomProperty(node.Provider, MM.Providers.StripTableTextColumn, false, true, TABLES));
pGrid.Items.Add(CreateCustomProperty(node.Provider, MM.Providers.StripColumnTextColumn, false, true, TABLES));
pGrid.Items.Add(CreateCustomProperty(node.Provider, MM.Providers.IncludeTableListColumn, false, true, TABLES));
pGrid.Items.Add(CreateCustomProperty(node.Provider, MM.Providers.ExcludeTableListColumn, false, true, TABLES));
pGrid.Items.Add(CreateCustomProperty(node.Provider, MM.Providers.TableBaseClassColumn, false, true, TABLES));
pGrid.Items.Add(CreateCustomProperty(node.Provider, MM.Providers.ViewBaseClassColumn, false, true, VIEWS));
pGrid.Items.Add(CreateCustomProperty(node.Provider, MM.Providers.ViewStartsWithColumn, false, true, VIEWS));
pGrid.Items.Add(CreateCustomProperty(node.Provider, MM.Providers.StripViewTextColumn, false, true, VIEWS));
pGrid.Items.Add(CreateCustomProperty(node.Provider, MM.Providers.UseSPsColumn, false, true, STORED_PROCEDURES));
pGrid.Items.Add(CreateCustomProperty(node.Provider, MM.Providers.SPClassNameColumn, false, true, STORED_PROCEDURES));
pGrid.Items.Add(CreateCustomProperty(node.Provider, MM.Providers.SPStartsWithColumn, false, true, STORED_PROCEDURES));
pGrid.Items.Add(CreateCustomProperty(node.Provider, MM.Providers.ExtractClassNameFromSPNameColumn, false, true, STORED_PROCEDURES));
pGrid.Items.Add(CreateCustomProperty(node.Provider, MM.Providers.StripSPTextColumn, false, true, STORED_PROCEDURES));
pGrid.Items.Add(CreateCustomProperty(node.Provider, MM.Providers.StripParamTextColumn, false, true, STORED_PROCEDURES));
pGrid.Items.Add(CreateCustomProperty(node.Provider, MM.Providers.IncludeProcedureListColumn, false, true, STORED_PROCEDURES));
pGrid.Items.Add(CreateCustomProperty(node.Provider, MM.Providers.ExcludeProcedureListColumn, false, true, STORED_PROCEDURES));
pGrid.Items.Add(CreateCustomProperty(node.Provider, MM.Providers.StoredProcedureBaseClassColumn, false, true, STORED_PROCEDURES));
pGrid.Items.Add(CreateCustomProperty(node.Provider, MM.Providers.RegexIgnoreCaseColumn, false, true, REGULAR_EXPRESSIONS));
pGrid.Items.Add(CreateCustomProperty(node.Provider, MM.Providers.RegexDictionaryReplaceColumn, false, true, REGULAR_EXPRESSIONS));
pGrid.Items.Add(CreateCustomProperty(node.Provider, MM.Providers.RegexMatchExpressionColumn, false, true, REGULAR_EXPRESSIONS));
pGrid.Items.Add(CreateCustomProperty(node.Provider, MM.Providers.RegexReplaceExpressionColumn, false, true, REGULAR_EXPRESSIONS));
pGrid.Refresh();
}
}
#endregion
#region Add
private void AddProject()
{
MasterStore.ProjectsRow newProject = (MasterStore.ProjectsRow)MM.Projects.NewRow();
MM.Projects.AddProjectsRow(newProject);
MM.Save();
BuildTree();
treeView1.SelectedNode = FindNodeByRow(newProject);
}
private void AddProvider(int projectId)
{
MasterStore.ProvidersRow newProvider = (MasterStore.ProvidersRow)MM.Providers.NewRow();
MM.Providers.AddProvidersRow(newProvider);
newProvider.ProjectId = projectId;
MM.Save();
BuildTree();
treeView1.SelectedNode = FindNodeByRow(newProvider);
}
private void AddConnectionString()
{
MasterStore.ConnectionStringsRow newConnectionString = (MasterStore.ConnectionStringsRow)MM.ConnectionStrings.NewRow();
MM.ConnectionStrings.AddConnectionStringsRow(newConnectionString);
MM.Save();
BuildTree();
treeView1.SelectedNode = FindNodeByRow(newConnectionString);
}
#endregion
#region Save
private void SaveConnectionStringProperties(GridItem property)
{
MasterStore.ConnectionStringsRow connectionString = ((StageNode)pGrid.Tag).ConnectionString;
if(connectionString != null)
{
foreach(CustomProperty cp in pGrid.Items)
{
string tagType = GetTagString(cp.Tag);
if(tagType == property.Label)
{
connectionString[tagType] = cp.SelectedValue ?? property.Value;
MM.Save();
if(tagType == MM.ConnectionStrings.NameColumn.ColumnName)
UpdateNodeName(connectionString, connectionString.Name);
break;
}
}
}
}
private void SaveConfigurationProperties(GridItem property)
{
foreach(CustomProperty cp in pGrid.Items)
{
string tagType = GetTagString(cp.Tag);
if(tagType == property.Label)
{
config[tagType] = cp.SelectedValue ?? property.Value;
MM.Save();
break;
}
}
}
private void SaveProjectProperties(GridItem property)
{
MasterStore.ProjectsRow project = ((StageNode)pGrid.Tag).Project;
if(project != null)
{
foreach(CustomProperty cp in pGrid.Items)
{
string tagType = GetTagString(cp.Tag);
if(tagType == property.Label)
{
project[tagType] = cp.SelectedValue ?? property.Value;
MM.Save();
if(tagType == MM.Projects.NameColumn.ColumnName)
UpdateNodeName(project, project.Name);
break;
}
}
}
}
private void SaveProviderProperties(GridItem property)
{
//DM.ProvidersRow provider = MM.Providers.FindByProviderId(GetTagId(pGrid.Tag));
MasterStore.ProvidersRow provider = ((StageNode)pGrid.Tag).Provider;
if(provider != null)
{
foreach(CustomProperty cp in pGrid.Items)
{
string tagType = GetTagString(cp.Tag);
if(tagType == property.Label)
{
provider[tagType] = cp.SelectedValue ?? property.Value;
MM.Save();
if(tagType == MM.Providers.NameColumn.ColumnName)
UpdateNodeName(provider, provider.Name);
break;
}
}
}
}
#endregion
#region Delete
private static void DeleteProject(int projectId)
{
MasterStore.ProjectsRow row = MM.Projects.FindByProjectId(projectId);
if(row != null)
{
row.Delete();
MM.Save();
}
}
private static void DeleteProvider(int providerId)
{
MasterStore.ProvidersRow row = MM.Providers.FindByProviderId(providerId);
if(row != null)
{
foreach(MasterStore.ProjectsRow projectRow in row.DefaultForProject())
projectRow.SetDefaultProviderNull();
row.Delete();
MM.Save();
}
}
private static void DeleteConnectionString(int connectionStringId)
{
MasterStore.ConnectionStringsRow row = MM.ConnectionStrings.FindByConnectionStringId(connectionStringId);
if(row != null)
{
foreach(MasterStore.ProvidersRow providerRow in row.Providers())
providerRow.SetConnectionStringIdNull();
row.Delete();
MM.Save();
}
}
#endregion
}
} | {
"content_hash": "d741b779b3d28534722f592ebe018501",
"timestamp": "",
"source": "github",
"line_count": 2315,
"max_line_length": 182,
"avg_line_length": 50.636717062634986,
"alnum_prop": 0.5898194908892377,
"repo_name": "w8in/SubSonic-2.0",
"id": "1423370dab3b747f36214accae5a69a2707fe077",
"size": "117224",
"binary": false,
"copies": "3",
"ref": "refs/heads/master",
"path": "SubStage/SubStageForm.cs",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "ASP",
"bytes": "208161"
},
{
"name": "C#",
"bytes": "4674889"
},
{
"name": "CSS",
"bytes": "12546"
},
{
"name": "HTML",
"bytes": "4250"
},
{
"name": "JavaScript",
"bytes": "203642"
},
{
"name": "PLpgSQL",
"bytes": "136714"
}
],
"symlink_target": ""
} |
import { $WebSocket, WebSocketConfig, WebSocketSendMode } from 'angular2-websocket/angular2-websocket';
import { BaScrollPosition } from './../../../../theme/directives/baScrollPosition/baScrollPosition.directive';
import { Http, Response } from '@angular/http';
import { Injectable } from '@angular/core';
import { Observable } from 'rxjs';
interface Post {
id: number;
title: string;
author: string;
}
interface Comment {
id: number;
body: string;
postId: number;
}
interface FullPost {
id: number;
title: string;
author: string;
comments: Comment[];
}
@Injectable()
export class RobotHttpService {
public name: string = 'hyman';
private baseurl = 'http://localhost:3000/';
private baseSocketUrl = 'ws://192.168.21.240:30018/cable';
private restfulUrl = 'http://192.168.21.240:30014/welcome/say_hello';
private websocketSetting: WebSocketConfig = {
initialTimeout: 500,
maxTimeout: 300000,
reconnectIfNotNormalClose: true,
};
public socket = new $WebSocket(this.baseSocketUrl, null, this.websocketSetting);
constructor(private http: Http) {
console.log(this);
}
getPollingData(duration: number = 2000): Observable<any> {
const request = () => this.http.get(this.restfulUrl)
.map((response: Response) => response.json())
.catch((e: any) => Observable.throw(e));
return Observable
.interval(duration)
.switchMap(request);
}
getComment(postId: number): Observable<Comment[]> {
return this.http.get(`${this.baseurl}/comments?postId=${postId}`)
.map((response: Response) => response.json())
.catch((e: any) => Observable.throw(e));
}
getPosts(): Observable<Post[]> {
return this.http.get(`${this.baseurl}/posts`)
.map((response: Response) => response.json())
.catch((e: any) => Observable.throw(e));
}
getFullPost(): Observable<FullPost[]> {
return this.getPosts()
.concatMap(posts => Observable.from(posts))
.mergeMap(post => this.getComment(post.id), (post, comments) => ({ ...post, comments }))
.toArray()
.catch((e: any) => Observable.throw(e));
}
subscribeChannel(): Observable<any> {
const sendData = {
command: 'subscribe',
identifier: JSON.stringify({ channel: 'RobotsChannel', roomId: 'Andy' })
};
return this.socket
.send4Observable(JSON.stringify(sendData))
.do(qq => { console.log('subscribe channel', qq); })
.catch((e: any) => Observable.throw(e));
}
showData(isShowData: boolean): Observable<any> {
const data = {
command: 'message',
identifier: JSON.stringify({ channel: 'RobotsChannel', roomId: 'Andy' }),
data: JSON.stringify({ action: `${isShowData ? 'show' : 'stop'}`, roomId: 'Andy', message: '' })
};
return this.socket
.send4Observable(JSON.stringify(data))
.catch((e: any) => Observable.throw(e));
}
test() {
return Observable.interval(1).map(() => this.showData(true));
}
getDataStream() {
return this.socket
.getDataStream()
.map(event => {
return { ...event, data: JSON.parse(event.data) };
})
.filter(event => (event.data.type !== 'ping'));
// return this.socket.getDataStream();
}
}
| {
"content_hash": "59d191b00193ffd3d7d91edaa41acb1d",
"timestamp": "",
"source": "github",
"line_count": 107,
"max_line_length": 110,
"avg_line_length": 30.16822429906542,
"alnum_prop": 0.637546468401487,
"repo_name": "chnbohwr/wi_angular_admin",
"id": "8978dded741470cf67396508ea1ad185ec632ed8",
"size": "3228",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/app/pages/robots/components/robot-http/robot-http.service.ts",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "143230"
},
{
"name": "HTML",
"bytes": "92041"
},
{
"name": "JavaScript",
"bytes": "2083"
},
{
"name": "Shell",
"bytes": "153"
},
{
"name": "TypeScript",
"bytes": "512137"
}
],
"symlink_target": ""
} |
package org.steve.server;
import java.io.File;
import java.net.InetAddress;
import org.steve.server.database.Database;
import org.steve.server.httpd.HttpServer;
import org.steve.server.websocket.SocketServer;
/**
* @author Lukas
*
*/
public class Main {
public static void main( String[] args ) throws Exception {
Database.getInstance();
int porthttp = 9878, portsocket = 9879;
for(String arg : args) {
arg = arg.toLowerCase();
if(arg.equals("debug"))
org.eclipse.jetty.util.log.Log.getLog().setDebugEnabled(true);
else if(arg.startsWith("http="))
porthttp = Integer.parseInt(arg.substring(5));
else if(arg.startsWith("websocket="))
portsocket = Integer.parseInt(arg.substring(10));
}
new HttpServer(new File("Steve-Client/client/"), porthttp, true);
new SocketServer(portsocket);
System.out.println("HTTP server @ "+ InetAddress.getLocalHost().getHostAddress() + ":" + porthttp);
System.out.println("WEBSOCKET server @ "+ InetAddress.getLocalHost().getHostAddress() + ":" + portsocket);
}
}
| {
"content_hash": "ab0860b0a38782df6511ae4e93737326",
"timestamp": "",
"source": "github",
"line_count": 39,
"max_line_length": 108,
"avg_line_length": 27.128205128205128,
"alnum_prop": 0.6994328922495274,
"repo_name": "lukasdietrich/Steve-Server",
"id": "b1fcbe28260c0da6fd67bc453229355c938bce08",
"size": "1058",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "server/src/main/java/org/steve/server/Main.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Java",
"bytes": "13671"
}
],
"symlink_target": ""
} |
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>User agent detail - MQQBrowser/Mini2.2 (SonyEricssonZ550a/R6GA004)</title>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/materialize/0.97.3/css/materialize.min.css">
<link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">
<link href="../circle.css" rel="stylesheet">
</head>
<body>
<div class="container">
<div class="section">
<h1 class="header center orange-text">User agent detail</h1>
<div class="row center">
<h5 class="header light">
MQQBrowser/Mini2.2 (SonyEricssonZ550a/R6GA004)
</h5>
</div>
</div>
<div class="section">
<table class="striped"><tr><th></th><th colspan="3">General</th><th colspan="5">Device</th><th colspan="3">Bot</th><th colspan="2"></th></tr><tr><th>Provider</th><th>Browser</th><th>Engine</th><th>OS</th><th>Brand</th><th>Model</th><th>Type</th><th>Is mobile</th><th>Is touch</th><th>Is bot</th><th>Name</th><th>Type</th><th>Parse time</th><th>Actions</th></tr><tr><th colspan="14" class="green lighten-3">Test suite</th></tr><tr><td>UAParser<br /><small>v0.5.0.2</small><br /><small>vendor/thadafinser/uap-core/tests/test_device.yaml</small></td><td> </td><td><i class="material-icons">close</i></td><td> </td><td style="border-left: 1px solid #555">SonyEricsson</td><td>Z550a</td><td><i class="material-icons">close</i></td><td><i class="material-icons">close</i></td><td><i class="material-icons">close</i></td><td style="border-left: 1px solid #555"></td><td><i class="material-icons">close</i></td><td><i class="material-icons">close</i></td><td>0</td><td>
<!-- Modal Trigger -->
<a class="modal-trigger btn waves-effect waves-light" href="#modal-cfed3005-df48-4fa8-bf03-4f6ef8988f59">Detail</a>
<!-- Modal Structure -->
<div id="modal-cfed3005-df48-4fa8-bf03-4f6ef8988f59" class="modal modal-fixed-footer">
<div class="modal-content">
<h4>UAParser result detail</h4>
<p><pre><code class="php">Array
(
[user_agent_string] => MQQBrowser/Mini2.2 (SonyEricssonZ550a/R6GA004)
[family] => Ericsson Z550a
[brand] => SonyEricsson
[model] => Z550a
)
</code></pre></p>
</div>
<div class="modal-footer">
<a href="#!" class="modal-action modal-close waves-effect waves-green btn-flat ">close</a>
</div>
</div>
</td></tr><tr><th colspan="14" class="green lighten-3">Providers</th></tr><tr><td>BrowscapFull<br /><small>6014</small><br /></td>
<td colspan="12" class="center-align red lighten-1">
<strong>No result found</strong>
</td>
</tr><tr><td>BrowscapLite<br /><small>6014</small><br /></td>
<td colspan="12" class="center-align red lighten-1">
<strong>No result found</strong>
</td>
</tr><tr><td>BrowscapPhp<br /><small>6014</small><br /></td>
<td colspan="12" class="center-align red lighten-1">
<strong>No result found</strong>
</td>
</tr><tr><td>DonatjUAParser<br /><small>v0.5.1</small><br /></td><td>MQQBrowser Mini2.2</td><td><i class="material-icons">close</i></td><td><i class="material-icons">close</i></td><td style="border-left: 1px solid #555"><i class="material-icons">close</i></td><td><i class="material-icons">close</i></td><td><i class="material-icons">close</i></td><td><i class="material-icons">close</i></td><td><i class="material-icons">close</i></td><td style="border-left: 1px solid #555"><i class="material-icons">close</i></td><td><i class="material-icons">close</i></td><td><i class="material-icons">close</i></td><td>0</td><td>
<!-- Modal Trigger -->
<a class="modal-trigger btn waves-effect waves-light" href="#modal-15fbc1f0-2615-4d42-b5d9-a30dd647b050">Detail</a>
<!-- Modal Structure -->
<div id="modal-15fbc1f0-2615-4d42-b5d9-a30dd647b050" class="modal modal-fixed-footer">
<div class="modal-content">
<h4>DonatjUAParser result detail</h4>
<p><pre><code class="php">Array
(
[platform] =>
[browser] => MQQBrowser
[version] => Mini2.2
)
</code></pre></p>
</div>
<div class="modal-footer">
<a href="#!" class="modal-action modal-close waves-effect waves-green btn-flat ">close</a>
</div>
</div>
</td></tr><tr><td>JenssegersAgent<br /><small>v2.3.3</small><br /></td><td> </td><td><i class="material-icons">close</i></td><td> </td><td style="border-left: 1px solid #555"><i class="material-icons">close</i></td><td><i class="material-icons">close</i></td><td><i class="material-icons">close</i></td><td>yes</td><td><i class="material-icons">close</i></td><td style="border-left: 1px solid #555"></td><td></td><td><i class="material-icons">close</i></td><td>0.001</td><td>
<!-- Modal Trigger -->
<a class="modal-trigger btn waves-effect waves-light" href="#modal-b85a2b91-6a55-4436-a82c-1ea0d46e2e51">Detail</a>
<!-- Modal Structure -->
<div id="modal-b85a2b91-6a55-4436-a82c-1ea0d46e2e51" class="modal modal-fixed-footer">
<div class="modal-content">
<h4>JenssegersAgent result detail</h4>
<p><pre><code class="php">Array
(
[browserName] => GenericBrowser
[browserVersion] =>
[osName] =>
[osVersion] =>
[deviceModel] => Sony
[isMobile] => 1
[isRobot] =>
[botName] =>
)
</code></pre></p>
</div>
<div class="modal-footer">
<a href="#!" class="modal-action modal-close waves-effect waves-green btn-flat ">close</a>
</div>
</div>
</td></tr><tr><td>NeutrinoApiCom<br /><small></small><br /></td><td>QQbrowser Mini2.2</td><td><i class="material-icons">close</i></td><td> </td><td style="border-left: 1px solid #555">Sony Ericsson</td><td>Z550a</td><td>mobile-browser</td><td>yes</td><td><i class="material-icons">close</i></td><td style="border-left: 1px solid #555"></td><td></td><td><i class="material-icons">close</i></td><td>0.25401</td><td>
<!-- Modal Trigger -->
<a class="modal-trigger btn waves-effect waves-light" href="#modal-8c2a7a4e-3fbf-4df2-8d61-5e730422f67b">Detail</a>
<!-- Modal Structure -->
<div id="modal-8c2a7a4e-3fbf-4df2-8d61-5e730422f67b" class="modal modal-fixed-footer">
<div class="modal-content">
<h4>NeutrinoApiCom result detail</h4>
<p><pre><code class="php">stdClass Object
(
[mobile_screen_height] => 90
[is_mobile] => 1
[type] => mobile-browser
[mobile_brand] => Sony Ericsson
[mobile_model] => Z550a
[version] => Mini2.2
[is_android] =>
[browser_name] => QQbrowser
[operating_system_family] => unknown
[operating_system_version] =>
[is_ios] =>
[producer] => Tencent Ltd.
[operating_system] => unknown
[mobile_screen_width] => 90
[mobile_browser] =>
)
</code></pre></p>
</div>
<div class="modal-footer">
<a href="#!" class="modal-action modal-close waves-effect waves-green btn-flat ">close</a>
</div>
</div>
</td></tr><tr><td>PiwikDeviceDetector<br /><small>3.6.1</small><br /></td><td>QQ Browser 2.2</td><td> </td><td> </td><td style="border-left: 1px solid #555">Sony Ericsson</td><td>Z550a</td><td>feature phone</td><td>yes</td><td></td><td style="border-left: 1px solid #555"></td><td></td><td></td><td>0.002</td><td>
<!-- Modal Trigger -->
<a class="modal-trigger btn waves-effect waves-light" href="#modal-4a941d34-a8d3-4914-9724-346f60ad7046">Detail</a>
<!-- Modal Structure -->
<div id="modal-4a941d34-a8d3-4914-9724-346f60ad7046" class="modal modal-fixed-footer">
<div class="modal-content">
<h4>PiwikDeviceDetector result detail</h4>
<p><pre><code class="php">Array
(
[client] => Array
(
[type] => browser
[name] => QQ Browser
[short_name] => QQ
[version] => 2.2
[engine] =>
)
[operatingSystem] => Array
(
)
[device] => Array
(
[brand] => SE
[brandName] => Sony Ericsson
[model] => Z550a
[device] => 3
[deviceName] => feature phone
)
[bot] =>
[extra] => Array
(
[isBot] =>
[isBrowser] => 1
[isFeedReader] =>
[isMobileApp] =>
[isPIM] =>
[isLibrary] =>
[isMediaPlayer] =>
[isCamera] =>
[isCarBrowser] =>
[isConsole] =>
[isFeaturePhone] => 1
[isPhablet] =>
[isPortableMediaPlayer] =>
[isSmartDisplay] =>
[isSmartphone] =>
[isTablet] =>
[isTV] =>
[isDesktop] =>
[isMobile] => 1
[isTouchEnabled] =>
)
)
</code></pre></p>
</div>
<div class="modal-footer">
<a href="#!" class="modal-action modal-close waves-effect waves-green btn-flat ">close</a>
</div>
</div>
</td></tr><tr><td>SinergiBrowserDetector<br /><small>6.0.1</small><br /></td>
<td colspan="12" class="center-align red lighten-1">
<strong>No result found</strong>
</td>
</tr><tr><td>UAParser<br /><small>v3.4.5</small><br /></td><td>QQ Browser Mini 2.2</td><td><i class="material-icons">close</i></td><td> </td><td style="border-left: 1px solid #555">SonyEricsson</td><td>Z550a</td><td><i class="material-icons">close</i></td><td><i class="material-icons">close</i></td><td><i class="material-icons">close</i></td><td style="border-left: 1px solid #555"></td><td></td><td><i class="material-icons">close</i></td><td>0.003</td><td>
<!-- Modal Trigger -->
<a class="modal-trigger btn waves-effect waves-light" href="#modal-3160e405-8a8f-46dd-8f47-5115f06462d2">Detail</a>
<!-- Modal Structure -->
<div id="modal-3160e405-8a8f-46dd-8f47-5115f06462d2" class="modal modal-fixed-footer">
<div class="modal-content">
<h4>UAParser result detail</h4>
<p><pre><code class="php">UAParser\Result\Client Object
(
[ua] => UAParser\Result\UserAgent Object
(
[major] => 2
[minor] => 2
[patch] =>
[family] => QQ Browser Mini
)
[os] => UAParser\Result\OperatingSystem Object
(
[major] =>
[minor] =>
[patch] =>
[patchMinor] =>
[family] => Other
)
[device] => UAParser\Result\Device Object
(
[brand] => SonyEricsson
[model] => Z550a
[family] => Ericsson Z550a
)
[originalUserAgent] => MQQBrowser/Mini2.2 (SonyEricssonZ550a/R6GA004)
)
</code></pre></p>
</div>
<div class="modal-footer">
<a href="#!" class="modal-action modal-close waves-effect waves-green btn-flat ">close</a>
</div>
</div>
</td></tr><tr><td>UserAgentApiCom<br /><small></small><br /></td><td> </td><td> </td><td><i class="material-icons">close</i></td><td style="border-left: 1px solid #555"><i class="material-icons">close</i></td><td><i class="material-icons">close</i></td><td>Mobile</td><td><i class="material-icons">close</i></td><td><i class="material-icons">close</i></td><td style="border-left: 1px solid #555"></td><td></td><td><i class="material-icons">close</i></td><td>0.15201</td><td>
<!-- Modal Trigger -->
<a class="modal-trigger btn waves-effect waves-light" href="#modal-afeb05fb-26b9-4509-b8ac-0c604a9e97d6">Detail</a>
<!-- Modal Structure -->
<div id="modal-afeb05fb-26b9-4509-b8ac-0c604a9e97d6" class="modal modal-fixed-footer">
<div class="modal-content">
<h4>UserAgentApiCom result detail</h4>
<p><pre><code class="php">stdClass Object
(
[platform_name] => Sony Ericsson
[platform_version] => 550
[platform_type] => Mobile
)
</code></pre></p>
</div>
<div class="modal-footer">
<a href="#!" class="modal-action modal-close waves-effect waves-green btn-flat ">close</a>
</div>
</div>
</td></tr><tr><td>UserAgentStringCom<br /><small></small><br /></td>
<td colspan="12" class="center-align red lighten-1">
<strong>No result found</strong>
</td>
</tr><tr><td>WhatIsMyBrowserCom<br /><small></small><br /></td><td>QQ Browser </td><td> </td><td> </td><td style="border-left: 1px solid #555">Sony Ericsson</td><td>Sony Ericsson Z550a</td><td><i class="material-icons">close</i></td><td><i class="material-icons">close</i></td><td><i class="material-icons">close</i></td><td style="border-left: 1px solid #555"><i class="material-icons">close</i></td><td><i class="material-icons">close</i></td><td><i class="material-icons">close</i></td><td>0.23901</td><td>
<!-- Modal Trigger -->
<a class="modal-trigger btn waves-effect waves-light" href="#modal-5fc1ff22-a74d-481b-9ad1-fcfde73ded9c">Detail</a>
<!-- Modal Structure -->
<div id="modal-5fc1ff22-a74d-481b-9ad1-fcfde73ded9c" class="modal modal-fixed-footer">
<div class="modal-content">
<h4>WhatIsMyBrowserCom result detail</h4>
<p><pre><code class="php">stdClass Object
(
[operating_system_name] =>
[simple_sub_description_string] =>
[simple_browser_string] => QQ Browser on Sony Ericsson Z550a
[browser_version] =>
[extra_info] => Array
(
)
[operating_platform] => Sony Ericsson Z550a
[extra_info_table] => Array
(
)
[layout_engine_name] =>
[detected_addons] => Array
(
)
[operating_system_flavour_code] =>
[hardware_architecture] =>
[operating_system_flavour] =>
[operating_system_frameworks] => Array
(
)
[browser_name_code] => qq-browser
[operating_system_version] =>
[simple_operating_platform_string] =>
[is_abusive] =>
[layout_engine_version] =>
[browser_capabilities] => Array
(
)
[operating_platform_vendor_name] => Sony Ericsson
[operating_system] =>
[operating_system_version_full] =>
[operating_platform_code] => Z550a
[browser_name] => QQ Browser
[operating_system_name_code] =>
[user_agent] => MQQBrowser/Mini2.2 (SonyEricssonZ550a/R6GA004)
[browser_version_full] =>
[browser] => QQ Browser
)
</code></pre></p>
</div>
<div class="modal-footer">
<a href="#!" class="modal-action modal-close waves-effect waves-green btn-flat ">close</a>
</div>
</div>
</td></tr><tr><td>WhichBrowser<br /><small>v2.0.18</small><br /></td><td>QQ Browser Mini 2.2</td><td> </td><td> </td><td style="border-left: 1px solid #555">Sony Ericsson</td><td>Z550a</td><td>mobile:feature</td><td>yes</td><td><i class="material-icons">close</i></td><td style="border-left: 1px solid #555"></td><td></td><td><i class="material-icons">close</i></td><td>0.002</td><td>
<!-- Modal Trigger -->
<a class="modal-trigger btn waves-effect waves-light" href="#modal-083a336f-5d73-4505-84f3-c5fc9bb78652">Detail</a>
<!-- Modal Structure -->
<div id="modal-083a336f-5d73-4505-84f3-c5fc9bb78652" class="modal modal-fixed-footer">
<div class="modal-content">
<h4>WhichBrowser result detail</h4>
<p><pre><code class="php">Array
(
[browser] => Array
(
[name] => QQ Browser Mini
[version] => 2.2
[type] => browser
)
[device] => Array
(
[type] => mobile
[subtype] => feature
[manufacturer] => Sony Ericsson
[model] => Z550a
)
)
</code></pre></p>
</div>
<div class="modal-footer">
<a href="#!" class="modal-action modal-close waves-effect waves-green btn-flat ">close</a>
</div>
</div>
</td></tr><tr><td>Woothee<br /><small>v1.2.0</small><br /></td>
<td colspan="12" class="center-align red lighten-1">
<strong>No result found</strong>
</td>
</tr><tr><td>Wurfl<br /><small>1.7.1.0</small><br /></td><td> </td><td><i class="material-icons">close</i></td><td> </td><td style="border-left: 1px solid #555"></td><td></td><td>Feature Phone</td><td>yes</td><td></td><td style="border-left: 1px solid #555"></td><td><i class="material-icons">close</i></td><td><i class="material-icons">close</i></td><td>0.016</td><td>
<!-- Modal Trigger -->
<a class="modal-trigger btn waves-effect waves-light" href="#modal-a2bedf8c-4a95-42a7-96c5-aaf233b2ac50">Detail</a>
<!-- Modal Structure -->
<div id="modal-a2bedf8c-4a95-42a7-96c5-aaf233b2ac50" class="modal modal-fixed-footer">
<div class="modal-content">
<h4>Wurfl result detail</h4>
<p><pre><code class="php">Array
(
[virtual] => Array
(
[is_android] => false
[is_ios] => false
[is_windows_phone] => false
[is_app] => false
[is_full_desktop] => false
[is_largescreen] => false
[is_mobile] => true
[is_robot] => false
[is_smartphone] => false
[is_touchscreen] => false
[is_wml_preferred] => false
[is_xhtmlmp_preferred] => true
[is_html_preferred] => false
[advertised_device_os] =>
[advertised_device_os_version] =>
[advertised_browser] =>
[advertised_browser_version] =>
[complete_device_name] =>
[device_name] =>
[form_factor] => Feature Phone
[is_phone] => true
[is_app_webview] => false
)
[all] => Array
(
[brand_name] =>
[model_name] =>
[unique] => true
[ununiqueness_handler] =>
[is_wireless_device] => true
[device_claims_web_support] => false
[has_qwerty_keyboard] => false
[can_skip_aligned_link_row] => false
[uaprof] =>
[uaprof2] =>
[uaprof3] =>
[nokia_series] => 0
[nokia_edition] => 0
[device_os] =>
[mobile_browser] =>
[mobile_browser_version] =>
[device_os_version] =>
[pointing_method] =>
[release_date] => 2002_january
[marketing_name] =>
[model_extra_info] =>
[nokia_feature_pack] => 0
[can_assign_phone_number] => true
[is_tablet] => false
[manufacturer_name] =>
[is_bot] => false
[is_google_glass] => false
[proportional_font] => false
[built_in_back_button_support] => false
[card_title_support] => true
[softkey_support] => false
[table_support] => true
[numbered_menus] => false
[menu_with_select_element_recommended] => false
[menu_with_list_of_links_recommended] => true
[icons_on_menu_items_support] => false
[break_list_of_links_with_br_element_recommended] => true
[access_key_support] => false
[wrap_mode_support] => false
[times_square_mode_support] => false
[deck_prefetch_support] => false
[elective_forms_recommended] => true
[wizards_recommended] => false
[image_as_link_support] => false
[insert_br_element_after_widget_recommended] => false
[wml_can_display_images_and_text_on_same_line] => false
[wml_displays_image_in_center] => false
[opwv_wml_extensions_support] => false
[wml_make_phone_call_string] => wtai://wp/mc;
[chtml_display_accesskey] => false
[emoji] => false
[chtml_can_display_images_and_text_on_same_line] => false
[chtml_displays_image_in_center] => false
[imode_region] => none
[chtml_make_phone_call_string] => tel:
[chtml_table_support] => false
[xhtml_honors_bgcolor] => false
[xhtml_supports_forms_in_table] => false
[xhtml_support_wml2_namespace] => false
[xhtml_autoexpand_select] => false
[xhtml_select_as_dropdown] => false
[xhtml_select_as_radiobutton] => false
[xhtml_select_as_popup] => false
[xhtml_display_accesskey] => false
[xhtml_supports_invisible_text] => false
[xhtml_supports_inline_input] => false
[xhtml_supports_monospace_font] => false
[xhtml_supports_table_for_layout] => false
[xhtml_supports_css_cell_table_coloring] => false
[xhtml_format_as_css_property] => false
[xhtml_format_as_attribute] => false
[xhtml_nowrap_mode] => false
[xhtml_marquee_as_css_property] => false
[xhtml_readable_background_color1] => #FFFFFF
[xhtml_readable_background_color2] => #FFFFFF
[xhtml_allows_disabled_form_elements] => false
[xhtml_document_title_support] => true
[xhtml_preferred_charset] => utf8
[opwv_xhtml_extensions_support] => false
[xhtml_make_phone_call_string] => tel:
[xhtmlmp_preferred_mime_type] => application/vnd.wap.xhtml+xml
[xhtml_table_support] => false
[xhtml_send_sms_string] => none
[xhtml_send_mms_string] => none
[xhtml_file_upload] => not_supported
[cookie_support] => true
[accept_third_party_cookie] => true
[xhtml_supports_iframe] => none
[xhtml_avoid_accesskeys] => false
[xhtml_can_embed_video] => none
[ajax_support_javascript] => false
[ajax_manipulate_css] => false
[ajax_support_getelementbyid] => false
[ajax_support_inner_html] => false
[ajax_xhr_type] => none
[ajax_manipulate_dom] => false
[ajax_support_events] => false
[ajax_support_event_listener] => false
[ajax_preferred_geoloc_api] => none
[xhtml_support_level] => 1
[preferred_markup] => html_wi_oma_xhtmlmp_1_0
[wml_1_1] => true
[wml_1_2] => false
[wml_1_3] => false
[html_wi_w3_xhtmlbasic] => true
[html_wi_oma_xhtmlmp_1_0] => true
[html_wi_imode_html_1] => false
[html_wi_imode_html_2] => false
[html_wi_imode_html_3] => false
[html_wi_imode_html_4] => false
[html_wi_imode_html_5] => false
[html_wi_imode_htmlx_1] => false
[html_wi_imode_htmlx_1_1] => false
[html_wi_imode_compact_generic] => false
[html_web_3_2] => false
[html_web_4_0] => false
[voicexml] => false
[multipart_support] => false
[total_cache_disable_support] => false
[time_to_live_support] => false
[resolution_width] => 90
[resolution_height] => 90
[columns] => 11
[max_image_width] => 90
[max_image_height] => 35
[rows] => 6
[physical_screen_width] => 27
[physical_screen_height] => 27
[dual_orientation] => false
[density_class] => 1.0
[wbmp] => true
[bmp] => false
[epoc_bmp] => false
[gif_animated] => false
[jpg] => false
[png] => false
[tiff] => false
[transparent_png_alpha] => false
[transparent_png_index] => false
[svgt_1_1] => false
[svgt_1_1_plus] => false
[greyscale] => false
[gif] => true
[colors] => 256
[webp_lossy_support] => false
[webp_lossless_support] => false
[post_method_support] => true
[basic_authentication_support] => true
[empty_option_value_support] => true
[emptyok] => false
[nokia_voice_call] => false
[wta_voice_call] => false
[wta_phonebook] => false
[wta_misc] => false
[wta_pdc] => false
[https_support] => true
[phone_id_provided] => false
[max_data_rate] => 9
[wifi] => false
[sdio] => false
[vpn] => false
[has_cellular_radio] => true
[max_deck_size] => 4000
[max_url_length_in_requests] => 128
[max_url_length_homepage] => 0
[max_url_length_bookmark] => 0
[max_url_length_cached_page] => 0
[max_no_of_connection_settings] => 0
[max_no_of_bookmarks] => 0
[max_length_of_username] => 0
[max_length_of_password] => 0
[max_object_size] => 0
[downloadfun_support] => false
[directdownload_support] => false
[inline_support] => false
[oma_support] => false
[ringtone] => false
[ringtone_3gpp] => false
[ringtone_midi_monophonic] => false
[ringtone_midi_polyphonic] => false
[ringtone_imelody] => false
[ringtone_digiplug] => false
[ringtone_compactmidi] => false
[ringtone_mmf] => false
[ringtone_rmf] => false
[ringtone_xmf] => false
[ringtone_amr] => false
[ringtone_awb] => false
[ringtone_aac] => false
[ringtone_wav] => false
[ringtone_mp3] => false
[ringtone_spmidi] => false
[ringtone_qcelp] => false
[ringtone_voices] => 1
[ringtone_df_size_limit] => 0
[ringtone_directdownload_size_limit] => 0
[ringtone_inline_size_limit] => 0
[ringtone_oma_size_limit] => 0
[wallpaper] => false
[wallpaper_max_width] => 0
[wallpaper_max_height] => 0
[wallpaper_preferred_width] => 0
[wallpaper_preferred_height] => 0
[wallpaper_resize] => none
[wallpaper_wbmp] => false
[wallpaper_bmp] => false
[wallpaper_gif] => false
[wallpaper_jpg] => false
[wallpaper_png] => false
[wallpaper_tiff] => false
[wallpaper_greyscale] => false
[wallpaper_colors] => 2
[wallpaper_df_size_limit] => 0
[wallpaper_directdownload_size_limit] => 0
[wallpaper_inline_size_limit] => 0
[wallpaper_oma_size_limit] => 0
[screensaver] => false
[screensaver_max_width] => 0
[screensaver_max_height] => 0
[screensaver_preferred_width] => 0
[screensaver_preferred_height] => 0
[screensaver_resize] => none
[screensaver_wbmp] => false
[screensaver_bmp] => false
[screensaver_gif] => false
[screensaver_jpg] => false
[screensaver_png] => false
[screensaver_greyscale] => false
[screensaver_colors] => 2
[screensaver_df_size_limit] => 0
[screensaver_directdownload_size_limit] => 0
[screensaver_inline_size_limit] => 0
[screensaver_oma_size_limit] => 0
[picture] => false
[picture_max_width] => 0
[picture_max_height] => 0
[picture_preferred_width] => 0
[picture_preferred_height] => 0
[picture_resize] => none
[picture_wbmp] => false
[picture_bmp] => false
[picture_gif] => false
[picture_jpg] => false
[picture_png] => false
[picture_greyscale] => false
[picture_colors] => 2
[picture_df_size_limit] => 0
[picture_directdownload_size_limit] => 0
[picture_inline_size_limit] => 0
[picture_oma_size_limit] => 0
[video] => false
[oma_v_1_0_forwardlock] => false
[oma_v_1_0_combined_delivery] => false
[oma_v_1_0_separate_delivery] => false
[streaming_video] => false
[streaming_3gpp] => false
[streaming_mp4] => false
[streaming_mov] => false
[streaming_video_size_limit] => 0
[streaming_real_media] => none
[streaming_flv] => false
[streaming_3g2] => false
[streaming_vcodec_h263_0] => -1
[streaming_vcodec_h263_3] => -1
[streaming_vcodec_mpeg4_sp] => -1
[streaming_vcodec_mpeg4_asp] => -1
[streaming_vcodec_h264_bp] => -1
[streaming_acodec_amr] => none
[streaming_acodec_aac] => none
[streaming_wmv] => none
[streaming_preferred_protocol] => rtsp
[streaming_preferred_http_protocol] => none
[wap_push_support] => false
[connectionless_service_indication] => false
[connectionless_service_load] => false
[connectionless_cache_operation] => false
[connectionoriented_unconfirmed_service_indication] => false
[connectionoriented_unconfirmed_service_load] => false
[connectionoriented_unconfirmed_cache_operation] => false
[connectionoriented_confirmed_service_indication] => false
[connectionoriented_confirmed_service_load] => false
[connectionoriented_confirmed_cache_operation] => false
[utf8_support] => false
[ascii_support] => false
[iso8859_support] => false
[expiration_date] => false
[j2me_cldc_1_0] => false
[j2me_cldc_1_1] => false
[j2me_midp_1_0] => false
[j2me_midp_2_0] => false
[doja_1_0] => false
[doja_1_5] => false
[doja_2_0] => false
[doja_2_1] => false
[doja_2_2] => false
[doja_3_0] => false
[doja_3_5] => false
[doja_4_0] => false
[j2me_jtwi] => false
[j2me_mmapi_1_0] => false
[j2me_mmapi_1_1] => false
[j2me_wmapi_1_0] => false
[j2me_wmapi_1_1] => false
[j2me_wmapi_2_0] => false
[j2me_btapi] => false
[j2me_3dapi] => false
[j2me_locapi] => false
[j2me_nokia_ui] => false
[j2me_motorola_lwt] => false
[j2me_siemens_color_game] => false
[j2me_siemens_extension] => false
[j2me_heap_size] => 0
[j2me_max_jar_size] => 0
[j2me_storage_size] => 0
[j2me_max_record_store_size] => 0
[j2me_screen_width] => 0
[j2me_screen_height] => 0
[j2me_canvas_width] => 0
[j2me_canvas_height] => 0
[j2me_bits_per_pixel] => 0
[j2me_audio_capture_enabled] => false
[j2me_video_capture_enabled] => false
[j2me_photo_capture_enabled] => false
[j2me_capture_image_formats] => none
[j2me_http] => false
[j2me_https] => false
[j2me_socket] => false
[j2me_udp] => false
[j2me_serial] => false
[j2me_gif] => false
[j2me_gif89a] => false
[j2me_jpg] => false
[j2me_png] => false
[j2me_bmp] => false
[j2me_bmp3] => false
[j2me_wbmp] => false
[j2me_midi] => false
[j2me_wav] => false
[j2me_amr] => false
[j2me_mp3] => false
[j2me_mp4] => false
[j2me_imelody] => false
[j2me_rmf] => false
[j2me_au] => false
[j2me_aac] => false
[j2me_realaudio] => false
[j2me_xmf] => false
[j2me_wma] => false
[j2me_3gpp] => false
[j2me_h263] => false
[j2me_svgt] => false
[j2me_mpeg4] => false
[j2me_realvideo] => false
[j2me_real8] => false
[j2me_realmedia] => false
[j2me_left_softkey_code] => 0
[j2me_right_softkey_code] => 0
[j2me_middle_softkey_code] => 0
[j2me_select_key_code] => 0
[j2me_return_key_code] => 0
[j2me_clear_key_code] => 0
[j2me_datefield_no_accepts_null_date] => false
[j2me_datefield_broken] => false
[receiver] => false
[sender] => false
[mms_max_size] => 0
[mms_max_height] => 0
[mms_max_width] => 0
[built_in_recorder] => false
[built_in_camera] => false
[mms_jpeg_baseline] => false
[mms_jpeg_progressive] => false
[mms_gif_static] => false
[mms_gif_animated] => false
[mms_png] => false
[mms_bmp] => false
[mms_wbmp] => false
[mms_amr] => false
[mms_wav] => false
[mms_midi_monophonic] => false
[mms_midi_polyphonic] => false
[mms_midi_polyphonic_voices] => 0
[mms_spmidi] => false
[mms_mmf] => false
[mms_mp3] => false
[mms_evrc] => false
[mms_qcelp] => false
[mms_ota_bitmap] => false
[mms_nokia_wallpaper] => false
[mms_nokia_operatorlogo] => false
[mms_nokia_3dscreensaver] => false
[mms_nokia_ringingtone] => false
[mms_rmf] => false
[mms_xmf] => false
[mms_symbian_install] => false
[mms_jar] => false
[mms_jad] => false
[mms_vcard] => false
[mms_vcalendar] => false
[mms_wml] => false
[mms_wbxml] => false
[mms_wmlc] => false
[mms_video] => false
[mms_mp4] => false
[mms_3gpp] => false
[mms_3gpp2] => false
[mms_max_frame_rate] => 0
[nokiaring] => false
[picturemessage] => false
[operatorlogo] => false
[largeoperatorlogo] => false
[callericon] => false
[nokiavcard] => false
[nokiavcal] => false
[sckl_ringtone] => false
[sckl_operatorlogo] => false
[sckl_groupgraphic] => false
[sckl_vcard] => false
[sckl_vcalendar] => false
[text_imelody] => false
[ems] => false
[ems_variablesizedpictures] => false
[ems_imelody] => false
[ems_odi] => false
[ems_upi] => false
[ems_version] => 0
[siemens_ota] => false
[siemens_logo_width] => 101
[siemens_logo_height] => 29
[siemens_screensaver_width] => 101
[siemens_screensaver_height] => 50
[gprtf] => false
[sagem_v1] => false
[sagem_v2] => false
[panasonic] => false
[sms_enabled] => true
[wav] => false
[mmf] => false
[smf] => false
[mld] => false
[midi_monophonic] => false
[midi_polyphonic] => false
[sp_midi] => false
[rmf] => false
[xmf] => false
[compactmidi] => false
[digiplug] => false
[nokia_ringtone] => false
[imelody] => false
[au] => false
[amr] => false
[awb] => false
[aac] => false
[mp3] => false
[voices] => 1
[qcelp] => false
[evrc] => false
[flash_lite_version] =>
[fl_wallpaper] => false
[fl_screensaver] => false
[fl_standalone] => false
[fl_browser] => false
[fl_sub_lcd] => false
[full_flash_support] => false
[css_supports_width_as_percentage] => true
[css_border_image] => none
[css_rounded_corners] => none
[css_gradient] => none
[css_spriting] => false
[css_gradient_linear] => none
[is_transcoder] => false
[transcoder_ua_header] => user-agent
[rss_support] => false
[pdf_support] => false
[progressive_download] => false
[playback_vcodec_h263_0] => -1
[playback_vcodec_h263_3] => -1
[playback_vcodec_mpeg4_sp] => -1
[playback_vcodec_mpeg4_asp] => -1
[playback_vcodec_h264_bp] => -1
[playback_real_media] => none
[playback_3gpp] => false
[playback_3g2] => false
[playback_mp4] => false
[playback_mov] => false
[playback_acodec_amr] => none
[playback_acodec_aac] => none
[playback_df_size_limit] => 0
[playback_directdownload_size_limit] => 0
[playback_inline_size_limit] => 0
[playback_oma_size_limit] => 0
[playback_acodec_qcelp] => false
[playback_wmv] => none
[hinted_progressive_download] => false
[html_preferred_dtd] => xhtml_mp1
[viewport_supported] => false
[viewport_width] =>
[viewport_userscalable] =>
[viewport_initial_scale] =>
[viewport_maximum_scale] =>
[viewport_minimum_scale] =>
[mobileoptimized] => false
[handheldfriendly] => false
[canvas_support] => none
[image_inlining] => false
[is_smarttv] => false
[is_console] => false
[nfc_support] => false
[ux_full_desktop] => false
[jqm_grade] => none
[is_sencha_touch_ok] => false
)
)
</code></pre></p>
</div>
<div class="modal-footer">
<a href="#!" class="modal-action modal-close waves-effect waves-green btn-flat ">close</a>
</div>
</div>
</td></tr><tr><td>Zsxsoft<br /><small>1.3</small><br /></td><td>MQQBrowser Mini2.2</td><td><i class="material-icons">close</i></td><td> </td><td style="border-left: 1px solid #555">SonyEricsson</td><td>Z550a</td><td><i class="material-icons">close</i></td><td><i class="material-icons">close</i></td><td><i class="material-icons">close</i></td><td style="border-left: 1px solid #555"><i class="material-icons">close</i></td><td><i class="material-icons">close</i></td><td><i class="material-icons">close</i></td><td>0.001</td><td>
<!-- Modal Trigger -->
<a class="modal-trigger btn waves-effect waves-light" href="#modal-5d43e024-b46c-44f6-8914-529b05569bc2">Detail</a>
<!-- Modal Structure -->
<div id="modal-5d43e024-b46c-44f6-8914-529b05569bc2" class="modal modal-fixed-footer">
<div class="modal-content">
<h4>Zsxsoft result detail</h4>
<p><pre><code class="php">Array
(
[browser] => Array
(
[link] => http://browser.qq.com/
[title] => MQQBrowser Mini2.2
[code] => qqbrowser
[version] => Mini2.2
[name] => MQQBrowser
[image] => img/16/browser/qqbrowser.png
)
[os] => Array
(
[link] =>
[name] =>
[version] =>
[code] => null
[x64] =>
[title] =>
[type] => os
[dir] => os
[image] => img/16/os/null.png
)
[device] => Array
(
[link] => http://en.wikipedia.org/wiki/SonyEricsson
[title] => SonyEricsson Z550a
[model] => Z550a
[brand] => SonyEricsson
[code] => sonyericsson
[dir] => device
[type] => device
[image] => img/16/device/sonyericsson.png
)
[platform] => Array
(
[link] => http://en.wikipedia.org/wiki/SonyEricsson
[title] => SonyEricsson Z550a
[model] => Z550a
[brand] => SonyEricsson
[code] => sonyericsson
[dir] => device
[type] => device
[image] => img/16/device/sonyericsson.png
)
)
</code></pre></p>
</div>
<div class="modal-footer">
<a href="#!" class="modal-action modal-close waves-effect waves-green btn-flat ">close</a>
</div>
</div>
</td></tr></table>
</div>
<div class="section">
<h1 class="header center orange-text">About this comparison</h1>
<div class="row center">
<h5 class="header light">
The primary goal of this project is simple<br />
I wanted to know which user agent parser is the most accurate in each part - device detection, bot detection and so on...<br />
<br />
The secondary goal is to provide a source for all user agent parsers to improve their detection based on this results.<br />
<br />
You can also improve this further, by suggesting ideas at <a href="https://github.com/ThaDafinser/UserAgentParserComparison">ThaDafinser/UserAgentParserComparison</a><br />
<br />
The comparison is based on the abstraction by <a href="https://github.com/ThaDafinser/UserAgentParser">ThaDafinser/UserAgentParser</a>
</h5>
</div>
</div>
<div class="card">
<div class="card-content">
Comparison created <i>2016-05-10 07:55:16</i> | by
<a href="https://github.com/ThaDafinser">ThaDafinser</a>
</div>
</div>
</div>
<script src="https://code.jquery.com/jquery-2.1.4.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/materialize/0.97.3/js/materialize.min.js"></script>
<script src="http://cdnjs.cloudflare.com/ajax/libs/list.js/1.2.0/list.min.js"></script>
<script>
$(document).ready(function(){
// the "href" attribute of .modal-trigger must specify the modal ID that wants to be triggered
$('.modal-trigger').leanModal();
});
</script>
</body>
</html> | {
"content_hash": "fc38f49d4c10f20aeb1383021787a41a",
"timestamp": "",
"source": "github",
"line_count": 1056,
"max_line_length": 965,
"avg_line_length": 40.553030303030305,
"alnum_prop": 0.5216934429291986,
"repo_name": "ThaDafinser/UserAgentParserComparison",
"id": "d4e61fd9b674284adb597b2ddc548810494b237d",
"size": "42825",
"binary": false,
"copies": "1",
"ref": "refs/heads/gh-pages",
"path": "v5/user-agent-detail/3a/7e/3a7e08d7-9b53-45bb-a1a8-396fb799c3d2.html",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "HTML",
"bytes": "2060859160"
}
],
"symlink_target": ""
} |
/**
* Created by hisham.javed on 1/12/15.
*/
Layer_Player = cc.Layer.extend({
_className: "Layer_Player",
sprite: null,
size: null,
bullets: [],
bulletTag: 592.342,
lastFireTime: 0,
ctor: function () {
var me = this;
//////////////////////////////
// 1. super init first
me._super();
me.removeAllChildren();
/////////////////////////////
// window size
me.size = cc.winSize;
me.player.init(me);
me.drawPlayer();
me.playerListeners();
me.scheduleUpdate();
return true;
},
update: function () {
var me = this;
if (me.actions.resume) {
if (me.player.lives > 0) {
if (me.fireStart) {
var date = new Date();
var timeDiff = date.getTime() - me.lastFireTime;
if (timeDiff > getRandomInt(200, conf.player.fireDelay)) {
me.lastFireTime = date.getTime();
var pos = {
x: me.sprite.getPosition().x + me.sprite.getBoundingBox().width / 2 - 40,
y: me.sprite.getBoundingBox().height
};
me.fireBullet(pos);
me.fireEffect(pos);
}
}
}
me.bullets.forEach(function (bullet) {
bullet.update();
});
me.bullets = me.bullets.filter(function (bullet) {
return bullet.active;
});
}
},
fireEffect: function (pos) {
var me = this;
//Play Audio
cc.audioEngine.playEffect(res.shoot1_mp3);
//Play Tank Gun Fire Animation
pos.x = pos.x + 6;
pos.y = pos.y + 9;
if (!me.explosionAnimObject) {
me.explosionAnimObject = getExplosionAnimObject();
me.explosionAnimObject.tag = -2;
me.explosionAnimObject.sprite.setScale(0.5);
me.explosionAnimObject.sprite.setTag(me.explosionAnimObject.tag);
me.addChild(me.explosionAnimObject.sprite);
}
me.explosionAnimObject.sprite.setPosition(cc.p(pos.x, pos.y));
me.explosionAnimObject.sprite.runAction(me.explosionAnimObject.action.repeat(1));
},
player: {
x: 0,
y: 0,
width: 0,
height: 0,
score: 0,
lives: conf.player.life,
tag: -1,
init: function (layer) {
var me = this;
me.layer = layer;
me.x = 0;
me.y = 0;
me.width = 0;
me.height = 0;
me.score = 0;
me.lives = conf.player.life;
me.tag = -1;
//Score Label
me.lblScore = new cc.LabelBMFont("Score: 0", "res/fonts/toga.fnt");
me.lblScore.color = cc.color.WHITE;
me.lblScore.anchorX = 0.5;
me.lblScore.anchorY = 0.5;
me.lblScore.x = layer.size.width - 100;
me.lblScore.y = layer.size.height - 70;
layer.addChild(me.lblScore);
//Lives label
me.lblLives = new cc.LabelBMFont("Lives: " + me.lives, "res/fonts/toga.fnt");
me.lblLives.color = cc.color.GRAY;
me.lblLives.anchorX = 0.5;
me.lblLives.anchorY = 0.5;
me.lblLives.x = layer.size.width - 95;
me.lblLives.y = layer.size.height - 25;
layer.addChild(me.lblLives);
},
updateScore: function (points) {
var me = this;
me.score += points;
var str = "Score: " + me.score;
me.lblScore.setString(str);
//me.lblScore.x = me.layer.size.width- str.length *10;
},
updateLives: function () {
var me = this;
me.lives -= 1;
me.lblLives.setString("Lives: " + me.lives);
},
explode: function () {
var me = this;
me.updateLives();
if (me.lives >= 0) {
//Play Audio
cc.audioEngine.playEffect(res.explosion_mp3);
me.explosionAnimation();
me.layer.sprite.runAction(cc.sequence(cc.blink(0.7, 4), cc.fadeOut(0.3), cc.fadeIn(0.3), cc.callFunc(function () {
if (me.lives == 0) {
me.layer.sprite.opacity = 0;
me.layer.sprite.setPosition(cc.p(0, -400));
me.lives = -1;
var gameOver = new cc.Sprite(res.gameOver);
gameOver.anchorX = 0.5;
gameOver.anchorY = 0.5;
gameOver.x = me.layer.size.width / 2;
gameOver.y = me.layer.size.height / 2;
me.layer.addChild(gameOver);
}
})));
}
},
explosionAnimation: function () {
var me = this;
if (!me.explosionAnimObject) {
me.explosionAnimObject = getExplosionAnimObject();
me.explosionAnimObject.sprite.setScale(2);
me.layer.addChild(me.explosionAnimObject.sprite);
}
me.explosionAnimObject.sprite.setPosition(cc.p(me.x, me.y + 40));
me.explosionAnimObject.sprite.runAction(cc.sequence(me.explosionAnimObject.action.repeat(1), cc.callFunc(function () {
me.layer.removeChild(me.explosionAnimObject.sprite, true);
me.explosionAnimObject = null;
})));
}
},
drawPlayer: function () {
var me = this;
me.sprite = new cc.Sprite(res.playerTank80X175);
me.sprite.setTag(me.tag);
me.player.x = me.size.width / 2;
me.player.y = 0;
me.player.width = 80;
me.player.height = 175;
me.sprite.attr({
x: me.player.x,
y: me.player.y,
anchorX: 0.4,
anchorY: 0
});
me.addChild(me.sprite);
},
playerListeners: function () {
var me = this;
if (cc.sys.capabilities.hasOwnProperty("touches")) {
cc.eventManager.addListener({
event: cc.EventListener.TOUCH_ONE_BY_ONE,
onTouchBegan: function (touch, event) {
//Start Firing
if (me.actions.resume) {
me.fireStart = true;
}
return true;
},
onTouchEnded: function (touch, event) {
//Stop Firing
me.fireStart = false;
return true;
},
onTouchMoved: function (touch, event) {
if (me.actions.resume) {
if (touch.getLocationY() < 130 && me.player.lives >= 0) {
me.player.x = touch.getLocationX();
me.sprite.setPosition(cc.p(touch.getLocationX(), 0));
}
me.fireStart = true;
}
return true;
}
}, me);
}
},
bullet: function (bullet) {
var me = this;
bullet.active = true;
bullet.xVelocity = 0;
bullet.width = 11;
bullet.height = 38;
bullet.yVelocity = -bullet.speed;
bullet.sprite = new cc.Sprite(res.bullet11X38);
bullet.sprite.attr({
x: bullet.x,
y: bullet.y,
anchorX: 0,
anchorY: 0
});
me.addChild(bullet.sprite);
bullet.inBounds = function () {
return bullet.x >= 0 && bullet.x <= me.size.width &&
bullet.y >= 0 && bullet.y <= me.size.height;
};
bullet.update = function () {
if(bullet.active){
bullet.x += bullet.xVelocity;
bullet.y -= bullet.yVelocity;
bullet.sprite.setPosition(cc.p(bullet.x, bullet.y));
bullet.active = bullet.active && bullet.inBounds();
bullet.remove();
}
};
bullet.remove = function () {
if (!bullet.active) {
bullet.sprite.opacity = 0;
bullet.sprite.setPosition(cc.p(10, -400));
me.removeChild(bullet.sprite, true);
}
};
return bullet;
},
fireBullet: function (bulletPosition) {
var me = this;
me.bullets.push(me.bullet({
speed: conf.player.bullet.speed,
x: bulletPosition.x,
y: bulletPosition.y
}));
}
}); | {
"content_hash": "6ca9bbd694b59060f5d51b3e560d3e1b",
"timestamp": "",
"source": "github",
"line_count": 260,
"max_line_length": 130,
"avg_line_length": 33.792307692307695,
"alnum_prop": 0.46437514227179605,
"repo_name": "hishamjaved/tankifire",
"id": "415a4fb47731b95a6a4878f742494a8cc8d3a947",
"size": "8786",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/layer/player.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CMake",
"bytes": "11789"
},
{
"name": "HTML",
"bytes": "929"
},
{
"name": "JavaScript",
"bytes": "27567"
}
],
"symlink_target": ""
} |
export class AttributeValidationError implements Error {
public name = 'InvalidValueError';
public attribute: string;
public validation: string;
public message: string = "invalid attribute value";
constructor( attribute: string, validation: string ) {
this.attribute = attribute;
this.validation = validation;
}
}
export class InvalidValueError implements Error {
public name = 'InvalidValueError';
public message;
constructor( id: string, attrname?: string ) {
if( typeof attrname === "string" ) {
this.message = `invalid value to attribute "${attrname}" detected`;
} else {
this.message = 'a invalid value has been deteced';
}
}
}
| {
"content_hash": "6efdfb110f157b1e6056c70de9806551",
"timestamp": "",
"source": "github",
"line_count": 23,
"max_line_length": 79,
"avg_line_length": 32.130434782608695,
"alnum_prop": 0.6468200270635994,
"repo_name": "alex20465/iris-orm",
"id": "85c55b3781c3b9a3a2d4989aefc360c83b20cb28",
"size": "741",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "lib/helpers/Errors.ts",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "JavaScript",
"bytes": "1853"
},
{
"name": "TypeScript",
"bytes": "131392"
}
],
"symlink_target": ""
} |
:mod:`ddisearch` Django Search site for ICPSR/DDI data
======================================================
.. automodule:: ddisearch
:members:
----
:mod:`ddisearch.ddi`
^^^^^^^^^^^^^^^^^^^^
.. automodule:: ddisearch.ddi
:members:
Models
------
:class:`~ddisearch.ddi.models.CodeBook` is the primary model in use, for
an entire DDI document; other :class:`~eulxml.xmlmap.XmlObject` classes listed
are for subsections of the xml.
.. automodule:: ddisearch.ddi.models
:members:
-----
Views
-----
.. automodule:: ddisearch.ddi.views
:members:
Forms
-----
.. automodule:: ddisearch.ddi.forms
:members:
----
:mod:`ddisearch.geo`
^^^^^^^^^^^^^^^^^^^^
.. automodule:: ddisearch.geo
:members:
Models
------
.. automodule:: ddisearch.geo.models
:members:
Views
-----
.. automodule:: ddisearch.geo.views
:members:
| {
"content_hash": "85a62f2e8e4462c72a97717845ce5b6e",
"timestamp": "",
"source": "github",
"line_count": 57,
"max_line_length": 78,
"avg_line_length": 14.947368421052632,
"alnum_prop": 0.5868544600938967,
"repo_name": "emory-libraries/ddi-search",
"id": "3ddb652ca3f654876333c55e58742f243c8ed3c3",
"size": "852",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "doc/apidocs.rst",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "128759"
},
{
"name": "JavaScript",
"bytes": "14079"
},
{
"name": "Python",
"bytes": "160355"
},
{
"name": "XQuery",
"bytes": "768"
}
],
"symlink_target": ""
} |
.class Lcom/htc/fm/activity/FMRadioMain$4;
.super Ljava/lang/Object;
.source "FMRadioMain.java"
# interfaces
.implements Landroid/view/View$OnClickListener;
# annotations
.annotation system Ldalvik/annotation/EnclosingClass;
value = Lcom/htc/fm/activity/FMRadioMain;
.end annotation
.annotation system Ldalvik/annotation/InnerClass;
accessFlags = 0x0
name = null
.end annotation
# instance fields
.field final synthetic this$0:Lcom/htc/fm/activity/FMRadioMain;
# direct methods
.method constructor <init>(Lcom/htc/fm/activity/FMRadioMain;)V
.locals 0
.parameter
.prologue
.line 548
iput-object p1, p0, Lcom/htc/fm/activity/FMRadioMain$4;->this$0:Lcom/htc/fm/activity/FMRadioMain;
invoke-direct/range {p0 .. p0}, Ljava/lang/Object;-><init>()V
return-void
.end method
# virtual methods
.method public onClick(Landroid/view/View;)V
.locals 3
.parameter "v"
.prologue
.line 550
const-string v0, "FMRadioMain"
const-string v1, "+mBtnTuneDownClickListener.onClick()"
invoke-static {v0, v1}, Lcom/htc/fm/components/FMLog;->d(Ljava/lang/String;Ljava/lang/String;)V
.line 551
iget-object v0, p0, Lcom/htc/fm/activity/FMRadioMain$4;->this$0:Lcom/htc/fm/activity/FMRadioMain;
#calls: Lcom/htc/fm/activity/FMRadioMain;->frequencyDown()V
invoke-static {v0}, Lcom/htc/fm/activity/FMRadioMain;->access$1300(Lcom/htc/fm/activity/FMRadioMain;)V
.line 552
iget-object v0, p0, Lcom/htc/fm/activity/FMRadioMain$4;->this$0:Lcom/htc/fm/activity/FMRadioMain;
#getter for: Lcom/htc/fm/activity/FMRadioMain;->isTuning:Z
invoke-static {v0}, Lcom/htc/fm/activity/FMRadioMain;->access$1100(Lcom/htc/fm/activity/FMRadioMain;)Z
move-result v0
if-nez v0, :cond_0
.line 553
iget-object v0, p0, Lcom/htc/fm/activity/FMRadioMain$4;->this$0:Lcom/htc/fm/activity/FMRadioMain;
#getter for: Lcom/htc/fm/activity/FMRadioMain;->mServiceHelper:Lcom/htc/fm/ui/helper/ServiceHelper;
invoke-static {v0}, Lcom/htc/fm/activity/FMRadioMain;->access$1200(Lcom/htc/fm/activity/FMRadioMain;)Lcom/htc/fm/ui/helper/ServiceHelper;
move-result-object v0
iget-object v1, p0, Lcom/htc/fm/activity/FMRadioMain$4;->this$0:Lcom/htc/fm/activity/FMRadioMain;
#getter for: Lcom/htc/fm/activity/FMRadioMain;->mCurrentFrequency:I
invoke-static {v1}, Lcom/htc/fm/activity/FMRadioMain;->access$900(Lcom/htc/fm/activity/FMRadioMain;)I
move-result v1
const/4 v2, 0x5
invoke-virtual {v0, v1, v2}, Lcom/htc/fm/ui/helper/ServiceHelper;->sendServiceWhat(II)V
.line 554
iget-object v0, p0, Lcom/htc/fm/activity/FMRadioMain$4;->this$0:Lcom/htc/fm/activity/FMRadioMain;
const/4 v1, 0x1
#setter for: Lcom/htc/fm/activity/FMRadioMain;->isTuning:Z
invoke-static {v0, v1}, Lcom/htc/fm/activity/FMRadioMain;->access$1102(Lcom/htc/fm/activity/FMRadioMain;Z)Z
.line 556
:cond_0
const-string v0, "FMRadioMain"
const-string v1, "-mBtnTuneDownClickListener.onClick()"
invoke-static {v0, v1}, Lcom/htc/fm/components/FMLog;->d(Ljava/lang/String;Ljava/lang/String;)V
.line 557
return-void
.end method
| {
"content_hash": "24269bddc1a8e685893af28cfaa8a0ba",
"timestamp": "",
"source": "github",
"line_count": 105,
"max_line_length": 141,
"avg_line_length": 30,
"alnum_prop": 0.72,
"repo_name": "baidurom/devices-onex",
"id": "8be74d023cdbdddf348f8ae058832116c1572f6f",
"size": "3150",
"binary": false,
"copies": "1",
"ref": "refs/heads/coron-4.0",
"path": "FM_Radio/smali/com/htc/fm/activity/FMRadioMain$4.smali",
"mode": "33188",
"license": "apache-2.0",
"language": [],
"symlink_target": ""
} |
SYNONYM
#### According to
The Catalogue of Life, 3rd January 2011
#### Published in
null
#### Original name
null
### Remarks
null | {
"content_hash": "fba107e3fed092b016818fb241d4ce32",
"timestamp": "",
"source": "github",
"line_count": 13,
"max_line_length": 39,
"avg_line_length": 10.23076923076923,
"alnum_prop": 0.6917293233082706,
"repo_name": "mdoering/backbone",
"id": "898a16b3a10914b41146cf72086001016c951b58",
"size": "203",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "life/Plantae/Magnoliophyta/Magnoliopsida/Malpighiales/Phyllanthaceae/Phyllanthus/Phyllanthus madagascariensis/ Syn. Diasperus madagascariensis/README.md",
"mode": "33188",
"license": "apache-2.0",
"language": [],
"symlink_target": ""
} |
/*
* Licensed to The Apereo Foundation under one or more contributor license
* agreements. See the NOTICE file distributed with this work for
* additional information regarding copyright ownership.
*
* The Apereo Foundation licenses this file to you under the Educational
* Community 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://opensource.org/licenses/ecl2.txt
*
* 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 org.sakaiproject.hierarchy;
import java.util.Map;
import java.util.Set;
import org.sakaiproject.hierarchy.model.HierarchyNode;
/**
* This interface contains the methods for assigning and checking permissions in the hierarchy
*
* @author Aaron Zeckoski (azeckoski @ gmail.com)
*/
public interface HierarchyPermissions {
/**
* Determine if a user has a specific hierarchy permission at a specific hierarchy node,
* a permission key can be any string though it will most likely be from a relatively small set
*
* @param userId the internal user id (not username)
* @param nodeId a unique id for a hierarchy node
* @param hierarchyPermission a string which indicates a permission key (e.g. delete.item)
* @return true if the user has this permission, false otherwise
*/
public boolean checkUserNodePerm(String userId, String nodeId, String hierarchyPermission);
// ASSIGN
/**
* Assign the given permission to a user for the given hierarchy node,
* can cascade the permission downward if desired
*
* @param userId the internal user id (not username)
* @param nodeId a unique id for a hierarchy node
* @param hierarchyPermission a string which indicates a permission key (e.g. delete.item)
* @param cascade if true then the permission is assigned to all nodes below this one as well,
* if false it is only assigned to this node
*/
public void assignUserNodePerm(String userId, String nodeId, String hierarchyPermission, boolean cascade);
/**
* Remove a permission for a user from the given hierarchy node,
* can cascade the permission downward if desired
*
* @param userId the internal user id (not username)
* @param nodeId a unique id for a hierarchy node
* @param hierarchyPermission a string which indicates a permission key (e.g. delete.item)
* @param cascade if true then the permission is removed from all nodes below this one as well,
* if false it is only removed from this node
*/
public void removeUserNodePerm(String userId, String nodeId, String hierarchyPermission, boolean cascade);
// NODES
/**
* Get all the userIds for users which have a specific permission in a set of
* hierarchy nodes, this can be used to check one node or many nodes as needed
*
* @param nodeIds an array of unique ids for hierarchy nodes
* @param hierarchyPermission a string which indicates a permission key (e.g. delete.item)
* @return a set of userIds (not username/eid)
*/
public Set<String> getUserIdsForNodesPerm(String[] nodeIds, String hierarchyPermission);
/**
* Get the hierarchy nodes which a user has a specific permission in,
* this is used to find a set of nodes which a user should be able to see and to build
* the list of hierarchy nodes a user has a given permission in
*
* @param userId the internal user id (not username)
* @param hierarchyPermission a string which indicates a permission key (e.g. delete.item)
* @return a Set of {@link HierarchyNode} objects
*/
public Set<HierarchyNode> getNodesForUserPerm(String userId, String hierarchyPermission);
/**
* Get the set of all permissions which a user has on a node or group of nodes,
* NOTE: this will get the set of ALL permissions inclusively for the given nodeIds
* so nodes in the set which a user has no permissions on will not cause this to return no permissions,
* example: for given user: nodeA(perm1, perm2), nodeB(perm1), nodeC(perm2), nodeD() : returns: (perm1, perm2)
*
* @param userId the internal user id (not username)
* @param nodeIds an array of unique ids for hierarchy nodes
* @return the set of permission keys which exist on any of the given nodes
*/
public Set<String> getPermsForUserNodes(String userId, String[] nodeIds);
/**
* Get all the users and permissions currently assigned to nodes,
* the returned map will always contain every passed in nodeId as a key
* <br/>
* This is not super efficient by itself so it should not used when other methods are sufficient,
* however, it is actually much better than calling the other methods repeatedly so this is primarily
* for use in administrative interfaces
*
* @param nodeIds an array of unique ids for hierarchy nodes
* @return the map of nodeId -> (map of userId -> Set(permission))
*/
public Map<String, Map<String, Set<String>>> getUsersAndPermsForNodes(String... nodeIds);
/**
* Get all the nodeIds and permissions for the given userIds,
* the returned map will always contain every userId that was passed in as a key
*
* @param userIds an array of unique ids for users (internal id, not eid)
* @return the map of userId -> (map of nodeId -> Set(permission))
*/
public Map<String, Map<String, Set<String>>> getNodesAndPermsForUser(String... userIds);
}
| {
"content_hash": "f3c90fe33e751cf064a90622063a3d92",
"timestamp": "",
"source": "github",
"line_count": 129,
"max_line_length": 114,
"avg_line_length": 45.15503875968992,
"alnum_prop": 0.7133047210300429,
"repo_name": "OpenCollabZA/sakai",
"id": "b93b7c7af7e6629424503ce662a5c5f633ceb2cc",
"size": "6455",
"binary": false,
"copies": "38",
"ref": "refs/heads/master",
"path": "hierarchy/api/src/java/org/sakaiproject/hierarchy/HierarchyPermissions.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "ASP",
"bytes": "59098"
},
{
"name": "Batchfile",
"bytes": "5172"
},
{
"name": "CSS",
"bytes": "2123328"
},
{
"name": "ColdFusion",
"bytes": "146057"
},
{
"name": "HTML",
"bytes": "6308955"
},
{
"name": "Java",
"bytes": "48045196"
},
{
"name": "JavaScript",
"bytes": "9374877"
},
{
"name": "Lasso",
"bytes": "26436"
},
{
"name": "PHP",
"bytes": "606568"
},
{
"name": "PLSQL",
"bytes": "2328131"
},
{
"name": "Perl",
"bytes": "61738"
},
{
"name": "Python",
"bytes": "44698"
},
{
"name": "Ruby",
"bytes": "1276"
},
{
"name": "Shell",
"bytes": "19259"
},
{
"name": "SourcePawn",
"bytes": "2247"
},
{
"name": "XSLT",
"bytes": "280557"
}
],
"symlink_target": ""
} |
#include <aws/fsx/model/UpdateFileSystemResult.h>
#include <aws/core/utils/json/JsonSerializer.h>
#include <aws/core/AmazonWebServiceResult.h>
#include <aws/core/utils/StringUtils.h>
#include <aws/core/utils/UnreferencedParam.h>
#include <utility>
using namespace Aws::FSx::Model;
using namespace Aws::Utils::Json;
using namespace Aws::Utils;
using namespace Aws;
UpdateFileSystemResult::UpdateFileSystemResult()
{
}
UpdateFileSystemResult::UpdateFileSystemResult(const Aws::AmazonWebServiceResult<JsonValue>& result)
{
*this = result;
}
UpdateFileSystemResult& UpdateFileSystemResult::operator =(const Aws::AmazonWebServiceResult<JsonValue>& result)
{
JsonView jsonValue = result.GetPayload().View();
if(jsonValue.ValueExists("FileSystem"))
{
m_fileSystem = jsonValue.GetObject("FileSystem");
}
return *this;
}
| {
"content_hash": "fcd780ee0dfac4894b0cdb393e50f6b2",
"timestamp": "",
"source": "github",
"line_count": 37,
"max_line_length": 112,
"avg_line_length": 22.7027027027027,
"alnum_prop": 0.7690476190476191,
"repo_name": "awslabs/aws-sdk-cpp",
"id": "63b6f9a946c5755eefcfd6c5b0121a1aa1fcd2c0",
"size": "959",
"binary": false,
"copies": "4",
"ref": "refs/heads/master",
"path": "aws-cpp-sdk-fsx/source/model/UpdateFileSystemResult.cpp",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "C",
"bytes": "7596"
},
{
"name": "C++",
"bytes": "61740540"
},
{
"name": "CMake",
"bytes": "337520"
},
{
"name": "Java",
"bytes": "223122"
},
{
"name": "Python",
"bytes": "47357"
}
],
"symlink_target": ""
} |
using UnityEngine;
using System.Collections;
public class CanForklifControler : MonoBehaviour {
//Top of the latter in Latter Meters (cm for the 3d scale)
private static float ladderTop = 200;
//Shaders
public Shader defualt;
public Shader translucent;
public Color transBlack;
private string smartDashTable = "/SmartDashboard/";
//Preset positions from the encoder
private static float actualTop = 10180;
private static float actualBottom = 0;
//State vars
private bool calibrated = false;
private bool connected = false;
//Independent vars
private float currentValue;
private float currentLadderMeters;
//Rungs (0 is lowest rung)
private GameObject lift;
//Rung inital pos
private float initalXPos;
private float initalYPos;
private float initalZPos;
private bool pendingUpdateCalibration = false;
private bool pendingUpdateLift = false;
public float convertToLadderMeters(float value){
float conversionFactor = (ladderTop / (actualTop - actualBottom));
float lm;
lm = value * conversionFactor;
return lm/100;
}
// Use this for initialization
void Start () {
Debug.Log("Can Forklift Active");
lift = GameObject.Find("/Can_ForkLift_Sim/Lift");
transBlack = new Color(0,0,0,0f);
translucent = Shader.Find ("Transparent/Diffuse");
defualt = Shader.Find ("Diffuse");
initalXPos = lift.transform.localPosition.x;
initalYPos = lift.transform.localPosition.y;
initalZPos = lift.transform.localPosition.z;
NetworkTables.Instance.AddListener (smartDashTable+"Can Forklift|Calibrated", setUpdate);
NetworkTables.Instance.AddListener (smartDashTable+"Can Forklift|Encoder", setUpdate);
}
void setUpdate(string key, object value){
if (key.Equals (smartDashTable+"Can Forklift|Calibrated")) {
pendingUpdateCalibration = true;
} else if (key.Equals (smartDashTable+"Can Forklift|Encoder")) {
pendingUpdateLift = true;
}
}
void updateCalibration(){
NetworkTables.Instance.GetBool (smartDashTable + "Can Forklift|Calibrated", out calibrated);
}
void updateLift(){
double grabbedValue;
NetworkTables.Instance.GetNumber(smartDashTable+"Can Forklift|Encoder", out grabbedValue );
currentValue = (float)grabbedValue;
currentLadderMeters = convertToLadderMeters(currentValue);
float rawValue = initalYPos + currentLadderMeters;
if(rawValue >=-1 && rawValue <= (ladderTop/200)){
lift.transform.localPosition = new Vector3(initalXPos, rawValue, initalZPos);
}
updateColor ();
}
void updateColor(){
if (!connected) {
//Debug.Log("I AM CHANGING SHIT BRO");
lift.renderer.material.shader = translucent;
lift.renderer.material.color = transBlack;
}else{
lift.renderer.material.shader = defualt;
if(calibrated){
lift.renderer.material.color = Color.green;
}else{
lift.renderer.material.color = Color.yellow;
}
}
}
// Update is called once per frame
void Update () {
Debug.Log ("Can Fork | connected: " + connected + " calibrated: " + calibrated);
if (NetworkTables.Instance.connected) {
connected = true;
} else {
connected = false;
}
if (connected) {
if(pendingUpdateCalibration){
updateCalibration();
pendingUpdateCalibration = false;
}
if(calibrated && pendingUpdateLift){
updateLift();
pendingUpdateLift = false;
}
}
//Debug.Log ("Connect: " + connected + " Calibrated: " + calibrated +" CurrentValue: " + currentLadderMeters); //+"Displacement: "+actualDisplacment+" LDiplace: "+ladderDisplacment+ " Connected: " + connected + " Calibrated: " + calibrated);
}
}
| {
"content_hash": "8235542892eba7d3c8e2b21e5c63caa3",
"timestamp": "",
"source": "github",
"line_count": 131,
"max_line_length": 243,
"avg_line_length": 27.290076335877863,
"alnum_prop": 0.7197202797202797,
"repo_name": "CarterFendley/2015-oculus",
"id": "c2011bb6516458d6f2d92d5548461af12ee0c7e7",
"size": "3577",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "Assets/RobotControl/CanForklifControler.cs",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "C#",
"bytes": "269636"
},
{
"name": "GLSL",
"bytes": "4003"
}
],
"symlink_target": ""
} |
tags: programming
layout: post
title: "Web XP iteration planning tool"
---
<a href="http://www.xplanner.org/">XPlanner</a> - Looks nifty, although I bet <a href="http://www.atlassian.com/software/jira/">JIRA</a> will eventually have most (if not all) of these features. That's an aspect of buying software for your developers that I never see mentioned: try to buy from a vendor somewhat like your own so the dogfood features the vendor needs will overlap with your own. As a corollary it may be worth a second thought buying software from a company radically different than your own -- companies with a thousand employees generally have different needs than those with twenty.
| {
"content_hash": "58419df62212c1e80e21a5e97560556f",
"timestamp": "",
"source": "github",
"line_count": 10,
"max_line_length": 602,
"avg_line_length": 68.3,
"alnum_prop": 0.7730600292825769,
"repo_name": "cwinters/cwinters.github.io",
"id": "f2efa172e999ecfd0c915f6a32d7445c939b6014",
"size": "687",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "_posts/2003-08-14-web_xp_iteration_planning_tool.md",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "23817"
},
{
"name": "HTML",
"bytes": "10025"
},
{
"name": "Ruby",
"bytes": "102"
}
],
"symlink_target": ""
} |
require 'spec_helper'
describe CatalogController, type: :controller do
before(:each) do
@app_config = FactoryGirl.create(:app_config)
@user = FactoryGirl.create(:user)
@cart = FactoryGirl.build(:cart, reserver_id: @user.id)
sign_in @user
# @controller.stub(:cart).and_return(session[@cart])
# @controller.stub(:fix_cart_date)
end
describe 'GET index' do
before(:each) do
# the first hash passed here is params[] and the second is session[]
get :index, {} # , { cart: @cart }
end
it 'sets @reserver_id to the current cart.reserver_id' do
expect(assigns(:reserver_id)).to eq(@user.id)
end
it { is_expected.to respond_with(:success) }
it { is_expected.to render_template(:index) }
it { is_expected.not_to set_flash }
end
describe 'PUT add_to_cart' do
context 'valid equipment_model selected' do
before(:each) do
@equipment_model = FactoryGirl.create(:equipment_model)
put :add_to_cart, id: @equipment_model.id
end
it 'should call cart.add_item to add item to cart' do
expect do
put :add_to_cart, id: @equipment_model.id
end.to change { session[:cart].items[@equipment_model.id] }.by(1)
end
it 'should set flash[:error] if errors exist' do
allow(@cart).to receive(:validate_items).and_return('test')
allow(@cart).to receive(:validate_dates_and_items).and_return('test2')
expect(flash[:error]).not_to be_nil
end
it { is_expected.to redirect_to(root_path) }
end
context 'invalid equipment_model selected' do
before(:each) do
# there are no equipment models in the db so this is invalid
put :add_to_cart, id: 1
end
it { is_expected.to redirect_to(root_path) }
it { is_expected.to set_flash }
it 'should add logger error' do
expect(Rails.logger).to\
receive(:error).with('Attempt to add invalid equipment model 1')
# this call has to come after the previous line
put :add_to_cart, id: 1
end
end
end
describe 'PUT update_user_per_cat_page' do
before(:each) do
put :update_user_per_cat_page
end
it 'should set session[:items_per_page] to params[items_per_page] '\
'if exists' do
put :update_user_per_cat_page, items_per_page: 20
expect(session[:items_per_page]).to eq('20')
end
it 'should not alter session[:items_per_page] if '\
'params[:items_per_page] is nil' do
session[:items_per_page] = '15'
put :update_user_per_cat_page, items_per_page: nil
expect(session[:items_per_page]).not_to eq(nil)
expect(session[:items_per_page]).to eq('15')
end
it { is_expected.to redirect_to(root_path) }
end
# I don't like that this test is actually searching the database, but
# unfortunately I couldn't get the model methods to stub correctly
describe 'PUT search' do
context 'query is blank' do
before(:each) do
put :search, query: ''
end
it { is_expected.to redirect_to(root_path) }
end
context 'query is not blank' do
it 'should call catalog_search on EquipmentModel and return active '\
'equipment models' do
@equipment_model = FactoryGirl.create(:equipment_model,
active: true,
description: 'query')
# EquipmentModel.stub(:catelog_search).with('query')
# .and_return(@equipment_model)
put :search, query: 'query'
expect(assigns(:equipment_model_results)).to eq([@equipment_model])
end
it 'should call catalog_search on EquipmentItem' do
@equipment_item =
FactoryGirl.create(:equipment_item, serial: 'query')
# EquipmentItem.stub(:catelog_search).with('query')
# .and_return(@equipment_item)
put :search, query: 'query'
expect(assigns(:equipment_item_results)).to eq([@equipment_item])
end
it 'should call catalog_search on Category' do
@category = FactoryGirl.create(:category, name: 'query')
# Category.stub(:catelog_search).with('query').and_return(@category)
put :search, query: 'query'
expect(assigns(:category_results)).to eq([@category])
end
end
end
end
| {
"content_hash": "607b752c0b5fffe356d00af9b5f5c352",
"timestamp": "",
"source": "github",
"line_count": 112,
"max_line_length": 78,
"avg_line_length": 38.75,
"alnum_prop": 0.6193548387096774,
"repo_name": "Amalanag/reservations",
"id": "ba6be3759bbc33a0f565499276a3da56267cc318",
"size": "4340",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "spec/controllers/catalog_controller_spec.rb",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "37679"
},
{
"name": "HTML",
"bytes": "160149"
},
{
"name": "JavaScript",
"bytes": "18055"
},
{
"name": "Ruby",
"bytes": "617684"
}
],
"symlink_target": ""
} |
/**
* Functionality related to the tickets of the current logged user.
*/
(function() {
'use strict';
angular.module("tickets-zone",[])
.config(function($stateProvider, $urlRouterProvider) {
$stateProvider
.state(
'tab.my-tickets' , {
url: '/my-tickets',
templateUrl: 'js/my-tickets/my-tickets.html',
controller: 'MyTicketsController',
controllerAs: 'vm',
params: {
view: 'my'
}
})
.state(
'tab.evaluate' , {
url: '/my-tickets/eval/:id',
templateUrl: 'js/my-tickets/evaluate.html',
controller: 'EvaluateController',
controllerAs: 'vm'
});
});
})(); | {
"content_hash": "76eea1ef98f1a470c0fa2af02c28ee10",
"timestamp": "",
"source": "github",
"line_count": 29,
"max_line_length": 67,
"avg_line_length": 28.137931034482758,
"alnum_prop": 0.46691176470588236,
"repo_name": "pearpages/angular-ticketing",
"id": "020fc97530af4a0a0d7f3a4a7171d01d2bd4dcda",
"size": "816",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "www/js/my-tickets/tickets-zone.module.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "534766"
},
{
"name": "HTML",
"bytes": "31782"
},
{
"name": "JavaScript",
"bytes": "3460204"
}
],
"symlink_target": ""
} |
using System.ComponentModel.DataAnnotations;
namespace Jewerly.Domain
{
public class Currency
{
public int CurrencyId { get; set; }
[Display(Name = "Название")]
public string Name { get; set; }
[Display(Name = "Код валюты")]
public string CurrencyCode { get; set; }
[Display(Name = "Соотношение")]
public decimal Rate { get; set; }
[Display(Name = "Опубликовано?")]
public bool Published { get; set; }
[Display(Name = "Порядок сортировки")]
public int DisplayOrder { get; set; }
}
public class Discount
{
public int Id { get; set; }
[Display(Name = "Название")]
public string Name { get; set; }
[Display(Name = "Значение")]
public int Value { get; set; }
}
public class Markup // наценка
{
public int Id { get; set; }
[Display(Name = "Название")]
public string Name { get; set; }
[Display(Name = "Розничная")]
public int Retail { get; set; }
[Display(Name = "Оптовая")]
public int Trade { get; set; }
}
} | {
"content_hash": "d3ea2074244e7615c096d8be041e1655",
"timestamp": "",
"source": "github",
"line_count": 42,
"max_line_length": 48,
"avg_line_length": 27.261904761904763,
"alnum_prop": 0.5432314410480349,
"repo_name": "dimakaminskiy/Jewerly",
"id": "f999f92ebe4df03e7fd796f3d79a8a9c3c5353e6",
"size": "1251",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "Jewerly.Domain/Entities/Currency.cs",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "ASP",
"bytes": "102"
},
{
"name": "C#",
"bytes": "601113"
},
{
"name": "CSS",
"bytes": "25350"
},
{
"name": "HTML",
"bytes": "6112"
},
{
"name": "JavaScript",
"bytes": "181358"
}
],
"symlink_target": ""
} |
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=US-ASCII">
<title>Function swap</title>
<link rel="stylesheet" href="../../../doc/src/boostbook.css" type="text/css">
<meta name="generator" content="DocBook XSL Stylesheets V1.78.1">
<link rel="home" href="../index.html" title="The Boost C++ Libraries BoostBook Documentation Subset">
<link rel="up" href="../any/reference.html#header.boost.any_hpp" title="Header <boost/any.hpp>">
<link rel="prev" href="any.html" title="Class any">
<link rel="next" href="any_cast_idm45507162615824.html" title="Function any_cast">
</head>
<body bgcolor="white" text="black" link="#0000FF" vlink="#840084" alink="#0000FF">
<table cellpadding="2" width="100%"><tr>
<td valign="top"><img alt="Boost C++ Libraries" width="277" height="86" src="../../../boost.png"></td>
<td align="center"><a href="../../../index.html">Home</a></td>
<td align="center"><a href="../../../libs/libraries.htm">Libraries</a></td>
<td align="center"><a href="http://www.boost.org/users/people.html">People</a></td>
<td align="center"><a href="http://www.boost.org/users/faq.html">FAQ</a></td>
<td align="center"><a href="../../../more/index.htm">More</a></td>
</tr></table>
<hr>
<div class="spirit-nav">
<a accesskey="p" href="any.html"><img src="../../../doc/src/images/prev.png" alt="Prev"></a><a accesskey="u" href="../any/reference.html#header.boost.any_hpp"><img src="../../../doc/src/images/up.png" alt="Up"></a><a accesskey="h" href="../index.html"><img src="../../../doc/src/images/home.png" alt="Home"></a><a accesskey="n" href="any_cast_idm45507162615824.html"><img src="../../../doc/src/images/next.png" alt="Next"></a>
</div>
<div class="refentry">
<a name="boost.swap_idm45507162621920"></a><div class="titlepage"></div>
<div class="refnamediv">
<h2><span class="refentrytitle">Function swap</span></h2>
<p>boost::swap</p>
</div>
<h2 xmlns:rev="http://www.cs.rpi.edu/~gregod/boost/tools/doc/revision" class="refsynopsisdiv-title">Synopsis</h2>
<div xmlns:rev="http://www.cs.rpi.edu/~gregod/boost/tools/doc/revision" class="refsynopsisdiv"><pre class="synopsis"><span class="comment">// In header: <<a class="link" href="../any/reference.html#header.boost.any_hpp" title="Header <boost/any.hpp>">boost/any.hpp</a>>
</span>
<span class="keyword">void</span> <span class="identifier">swap</span><span class="special">(</span><a class="link" href="any.html" title="Class any">any</a> <span class="special">&</span> lhs<span class="special">,</span> <a class="link" href="any.html" title="Class any">any</a> <span class="special">&</span> rhs<span class="special">)</span><span class="special">;</span></pre></div>
<div class="refsect1">
<a name="idm45555445592368"></a><h2>Description</h2>
<div class="variablelist"><table border="0" class="variablelist compact">
<colgroup>
<col align="left" valign="top">
<col>
</colgroup>
<tbody>
<tr>
<td><p><span class="term">Effects:</span></p></td>
<td>Exchange of the contents of
<code class="computeroutput">lhs</code> and
<code class="computeroutput">rhs</code>.</td>
</tr>
<tr>
<td><p><span class="term">Throws:</span></p></td>
<td>Nothing.</td>
</tr>
</tbody>
</table></div>
</div>
</div>
<table xmlns:rev="http://www.cs.rpi.edu/~gregod/boost/tools/doc/revision" width="100%"><tr>
<td align="left"></td>
<td align="right"><div class="copyright-footer">Copyright © 2001 Kevlin Henney<p>Distributed under the Boost Software License, Version 1.0.
(See accompanying file <code class="filename">LICENSE_1_0.txt</code> or copy at
<a href="http://www.boost.org/LICENSE_1_0.txt" target="_top">http://www.boost.org/LICENSE_1_0.txt</a>)
</p>
</div></td>
</tr></table>
<hr>
<div class="spirit-nav">
<a accesskey="p" href="any.html"><img src="../../../doc/src/images/prev.png" alt="Prev"></a><a accesskey="u" href="../any/reference.html#header.boost.any_hpp"><img src="../../../doc/src/images/up.png" alt="Up"></a><a accesskey="h" href="../index.html"><img src="../../../doc/src/images/home.png" alt="Home"></a><a accesskey="n" href="any_cast_idm45507162615824.html"><img src="../../../doc/src/images/next.png" alt="Next"></a>
</div>
</body>
</html>
| {
"content_hash": "30bdabe8222b277332ec8bf121d956c6",
"timestamp": "",
"source": "github",
"line_count": 72,
"max_line_length": 426,
"avg_line_length": 59.791666666666664,
"alnum_prop": 0.6583042973286876,
"repo_name": "zjutjsj1004/third",
"id": "0e4c9b4baabb7658a139ec04a9f071ffd8324cbf",
"size": "4305",
"binary": false,
"copies": "3",
"ref": "refs/heads/master",
"path": "boost/doc/html/boost/swap_idm45507162621920.html",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Assembly",
"bytes": "224158"
},
{
"name": "Batchfile",
"bytes": "33175"
},
{
"name": "C",
"bytes": "5576593"
},
{
"name": "C#",
"bytes": "41850"
},
{
"name": "C++",
"bytes": "179595990"
},
{
"name": "CMake",
"bytes": "28348"
},
{
"name": "CSS",
"bytes": "331303"
},
{
"name": "Cuda",
"bytes": "26521"
},
{
"name": "FORTRAN",
"bytes": "1856"
},
{
"name": "Groff",
"bytes": "1305458"
},
{
"name": "HTML",
"bytes": "159660377"
},
{
"name": "IDL",
"bytes": "15"
},
{
"name": "JavaScript",
"bytes": "285786"
},
{
"name": "Lex",
"bytes": "1290"
},
{
"name": "Makefile",
"bytes": "1202020"
},
{
"name": "Max",
"bytes": "37424"
},
{
"name": "Objective-C",
"bytes": "3674"
},
{
"name": "Objective-C++",
"bytes": "651"
},
{
"name": "PHP",
"bytes": "60249"
},
{
"name": "Perl",
"bytes": "37297"
},
{
"name": "Perl6",
"bytes": "2130"
},
{
"name": "Python",
"bytes": "1833677"
},
{
"name": "QML",
"bytes": "613"
},
{
"name": "QMake",
"bytes": "17385"
},
{
"name": "Rebol",
"bytes": "372"
},
{
"name": "Shell",
"bytes": "1144162"
},
{
"name": "Tcl",
"bytes": "1205"
},
{
"name": "TeX",
"bytes": "38313"
},
{
"name": "XSLT",
"bytes": "564356"
},
{
"name": "Yacc",
"bytes": "20341"
}
],
"symlink_target": ""
} |
<?php
// Copyright 2017 DAIMTO ([Linda Lawton](https://twitter.com/LindaLawtonDK)) : [www.daimto.com](http://www.daimto.com/)
//
// Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
// the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
// an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
// specific language governing permissions and limitations under the License.
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by DAIMTO-Google-apis-Sample-generator 1.0.0
// Template File Name: methodTemplate.tt
// Build date: 2017-10-08
// PHP generator version: 1.0.0
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
// About
//
// Unofficial sample for the drive v2 API for PHP.
// This sample is designed to be used with the Google PHP client library. (https://github.com/google/google-api-php-client)
//
// API Description: Manages files in Drive including uploading, downloading, searching, detecting changes, and updating sharing permissions.
// API Documentation Link https://developers.google.com/drive/
//
// Discovery Doc https://www.googleapis.com/discovery/v1/apis/drive/v2/rest
//
//------------------------------------------------------------------------------
// Installation
//
// The preferred method is via https://getcomposer.org. Follow the installation instructions https://getcomposer.org/doc/00-intro.md
// if you do not already have composer installed.
//
// Once composer is installed, execute the following command in your project root to install this library:
//
// composer require google/apiclient:^2.0
//
//------------------------------------------------------------------------------
// Load the Google API PHP Client Library.
require_once __DIR__ . '/vendor/autoload.php';
session_start();
/***************************************************
* Include this line for service account authencation. Note: Not all APIs support service accounts.
//require_once __DIR__ . '/ServiceAccount.php';
* Include the following four lines Oauth2 authencation.
* require_once __DIR__ . '/Oauth2Authentication.php';
* $_SESSION['mainScript'] = basename($_SERVER['PHP_SELF']); // Oauth2callback.php will return here.
* $client = getGoogleClient();
* $service = new Google_Service_Drive($client);
****************************************************/
// Option paramaters can be set as needed.
$optParams = array(
//'maxResults' => '[YourValue]', // Maximum number of IDs to return.
//'space' => '[YourValue]', // The space in which the IDs can be used to create new files. Supported values are 'drive' and 'appDataFolder'.
'fields' => '*'
);
// Single Request.
$results = filesGenerateIdsExample($service, $optParams);
/**
* Generates a set of file IDs which can be provided in insert requests.
* @service Authenticated Drive service.
* @optParams Optional paramaters are not required by a request.
* @return GeneratedIds
*/
function filesGenerateIdsExample($service, $optParams)
{
try
{
// Parameter validation.
if ($service == null)
throw new Exception("service is required.");
if ($optParams == null)
throw new Exception("optParams is required.");
// Make the request and return the results.
return $service->files->GenerateIdsFiles($optParams);
}
catch (Exception $e)
{
print "An error occurred: " . $e->getMessage();
}
}
?>
| {
"content_hash": "8878aea6df73b565bfa28e616536402b",
"timestamp": "",
"source": "github",
"line_count": 93,
"max_line_length": 143,
"avg_line_length": 41.8494623655914,
"alnum_prop": 0.6333504624871531,
"repo_name": "LindaLawton/Google-APIs-PHP-Samples",
"id": "bc92c53d8960a3568dfa70c7b1ffe123a9c33c57",
"size": "3894",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "Samples/Drive API/v2/FilesGenerateIdsSample.php",
"mode": "33188",
"license": "apache-2.0",
"language": [],
"symlink_target": ""
} |
package com.mod.financialOfficer.controller;
import java.util.ArrayList;
import javax.servlet.http.HttpServletRequest;
import com.db.MySQLAccessMyBatis;
import com.model.FinancialOfficer;
import com.model.User;
import com.utils.KeyMaker;
import com.utils.PassUtil;
import com.utils.UserUtil;
public class MySQLAccessFinancialOfficer {
public ArrayList findAllFinancialOfficers() {
MySQLAccessMyBatis o = new MySQLAccessMyBatis();
o.openSession();
ArrayList recs = (ArrayList) o.findAllFinancialOfficers();
o.closeSession();
return recs;
}
public FinancialOfficer findFinancialOfficerById(String uid) {
MySQLAccessMyBatis o = new MySQLAccessMyBatis();
o.openSession();
FinancialOfficer obj = o.findFinancialOfficerById(uid);
// ArrayList fileInfo = (ArrayList) o.findUploadedFiles("" +
// obj.getUid(),
// "");
// obj.setFileInfo(fileInfo);
o.closeSession();
return obj;
}
public User fillUserObjOfFinancialOfficer(FinancialOfficer obj) {
User user = new User();
user.setUid(obj.getUid());
user.setUserName(obj.getName());
user.setUserEmail(obj.getEmail());
user.setUserPhone(obj.getPhone());
user.setLinkedObjId(obj.getUid());
user.setUserRole(User.FinancialOfficer);
user.setUserLoginId(obj.getUserLoginId());
user.setUserLoginPwd(obj.getUserLoginPwd());
user.setUserStatus(obj.getStatus());
user.setCreatedBy(obj.getCreatedBy());
user.setCreatedTime(obj.getCreatedTime());
user.setLastUpdateUser(obj.getLastUpdateUser());
user.setLastUpdateTime(obj.getLastUpdateTime());
return user;
}
public void insertFinancialOfficers(FinancialOfficer obj, HttpServletRequest request) throws Exception {
MySQLAccessMyBatis o = new MySQLAccessMyBatis();
o.openSession();
obj.setUid("FinancialOfficer" + KeyMaker.newKey());
String p2 = obj.getUserLoginPwdClearText().trim();
if (!p2.equals("")) {
p2 = new PassUtil().encodeClearText(p2);
obj.setUserLoginPwd(p2);
}
new UserUtil().markCreater(request, obj);
new UserUtil().markLastModify(request, obj);
o.insertFinancialOfficers(obj);
User user = fillUserObjOfFinancialOfficer(obj);
o.insertUser(user);
// UPLOAD file
// List files = obj.getFiles();
// ArrayList fileInfo = FileUpDownLoadUtil.upload(request, files);
//
// for (int i = 0; i < fileInfo.size(); i++) {
// VOFile voFile = (VOFile) fileInfo.get(i);
// voFile.setUid(UUID.randomUUID().toString());
// voFile.setLinkedObjId("" + obj.getUid());
// o.insertUploadedFileInfo(voFile);
// }
o.closeSession();
}
public void updateFinancialOfficer(FinancialOfficer obj, HttpServletRequest request) throws Exception {
MySQLAccessMyBatis o = new MySQLAccessMyBatis();
o.openSession();
String p2 = obj.getUserLoginPwdClearText().trim();
if (!p2.equals("")) {
p2 = new PassUtil().encodeClearText(p2);
obj.setUserLoginPwd(p2);
}
new UserUtil().markLastModify(request, obj);
o.updateFinancialOfficer(obj);
User user = fillUserObjOfFinancialOfficer(obj);
System.out.println();
o.updateUser(user);
// // DELETE file info
// String[] deletedFiles = request.getParameterValues("deleteCheck");
// if (deletedFiles != null) {
// for (int i = 0; i < deletedFiles.length; i++) {
// o.deleteUploadedFileInfo(deletedFiles[i]);
// }
// }
// // UPLOAD file
// List files = activityRec.getFiles();
// ArrayList fileInfo = FileUpDownLoadUtil.upload(request, files);
//
// // SAVE file info
// for (int i = 0; i < fileInfo.size(); i++) {
// VOFile voFile = (VOFile) fileInfo.get(i);
// voFile.setUid(UUID.randomUUID().toString());
// voFile.setLinkedObjId(activityRec.getUid());
// o.insertUploadedFileInfo(voFile);
// }
o.closeSession();
}
public void deleteFinancialOfficer(String uid, HttpServletRequest request) throws Exception {
MySQLAccessMyBatis o = new MySQLAccessMyBatis();
o.openSession();
FinancialOfficer obj = o.findFinancialOfficerById(uid);
obj.setStatus(User.STATUS_HALT);
new UserUtil().markLastModify(request, obj);
o.updateFinancialOfficer(obj);
// o.deleteFinancialOfficer(obj);
User user = fillUserObjOfFinancialOfficer(obj);
o.updateUser(user);
o.closeSession();
}
}
| {
"content_hash": "a4447b4fbc5fcf217fbd747638049485",
"timestamp": "",
"source": "github",
"line_count": 140,
"max_line_length": 105,
"avg_line_length": 30.928571428571427,
"alnum_prop": 0.6953810623556582,
"repo_name": "mingxin6/incu",
"id": "63fe204e693417614877fef97a387ddbe898e586",
"size": "4330",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "inc2_tw2/src/com/mod/financialOfficer/controller/MySQLAccessFinancialOfficer.java",
"mode": "33188",
"license": "apache-2.0",
"language": [],
"symlink_target": ""
} |
Installation
============
Use `pip`_ to install Flask-Dance. To use basic functionality, run this:
.. code-block:: bash
$ pip install Flask-Dance
To also use the :ref:`SQLAlchemy storage <sqlalchemy-storage>`, specify the
``sqla`` extra, like this:
.. code-block:: bash
$ pip install Flask-Dance[sqla]
.. _pip: https://pip.pypa.io
| {
"content_hash": "3902f3e992af036eb734bd85b21fc92b",
"timestamp": "",
"source": "github",
"line_count": 17,
"max_line_length": 75,
"avg_line_length": 20.352941176470587,
"alnum_prop": 0.6647398843930635,
"repo_name": "singingwolfboy/flask-dance",
"id": "b77127fb523f4b1557b7e445ad8d9c1dd6c34ac0",
"size": "346",
"binary": false,
"copies": "1",
"ref": "refs/heads/main",
"path": "docs/install.rst",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Python",
"bytes": "329946"
}
],
"symlink_target": ""
} |
<html xmlns="http://www.w3.org/1999/xhtml"><head><meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>DocBlox Documentation</title><link rel="stylesheet" href="css/jquery-ui.css" type="text/css"></link><link rel="stylesheet" href="css/docblox/jquery-ui-1.8.16.custom.css" type="text/css"></link><link rel="stylesheet" href="css/jquery.treeview.css" type="text/css"></link><link rel="stylesheet" href="css/theme.css" type="text/css"></link><script type="text/javascript" src="js/jquery-1.4.2.min.js"></script><script type="text/javascript" src="js/jquery-ui-1.8.2.custom.min.js"></script><script type="text/javascript" src="js/jquery.cookie.js"></script><script type="text/javascript" src="js/jquery.treeview.js"></script><script type="text/javascript">
$(document).ready(function() {
$(".filetree").treeview({
collapsed: true,
persist: "cookie"
});
$("#accordion").accordion({
collapsible: true,
autoHeight: false,
fillSpace: true
});
$(".tabs").tabs();
});
</script></head><body><div xmlns="" id="content">
<script xmlns:dbx="http://docblox-project.org/xsl/functions">
function filterElements()
{
inherited = !$('#show-inherited').hasClass('deselected');
public = !$('#show-public').hasClass('deselected');
protected = !$('#show-protected').hasClass('deselected');
private = !$('#show-private').hasClass('deselected');
$('div.public').each(function(index, val) {
$(val).toggle(public && !($(val).hasClass('inherited_from') && !inherited));
});
$('div.protected').each(function(index, val) {
$(val).toggle(protected && !($(val).hasClass('inherited_from') && !inherited));
});
$('div.private').each(function(index, val) {
$(val).toggle(private && !($(val).hasClass('inherited_from') && !inherited));
});
}
$(document).ready(function() {
$('a.gripper').click(function() {
$(this).nextAll('div.code-tabs').slideToggle();
$(this).children('img').toggle();
return false;
});
$('div.method code span.highlight,div.function code span.highlight,div.constant code span.highlight,div.property code span.highlight').css('cursor', 'pointer');
$('div.method code span.highlight,div.function code span.highlight,div.constant code span.highlight,div.property code span.highlight').click(function() {
$(this).parent().nextAll('div.code-tabs').slideToggle();
$(this).parent().prevAll('a.gripper').children('img').toggle();
return false;
});
$('div.code-tabs').hide();
$('a.gripper').show();
$('div.code-tabs:empty').prevAll('a.gripper').html('');
$('#show-public, #show-protected, #show-private, #show-inherited')
.css('cursor', 'pointer')
.click(function(){
$(this).toggleClass('deselected');
if ($(this).hasClass('deselected')) {
$(this).fadeTo('fast', '0.4');
} else {
$(this).fadeTo('fast', '1.0');
}
filterElements();
return false;
});
$('#show-protected, #show-private').click();
// add the sliding behaviour to the file navigation and show it
// it is initially hidden for non-JS users.
$("#file-nav-box").show().hover(function() {
$("#file-nav-container").slideDown(400);
}, function() {
$("#file-nav-container").slideUp(400);
});
});
</script><h1 xmlns:dbx="http://docblox-project.org/xsl/functions" class="file">CamelSpider/Entity/InterfaceLink.php</h1>
<div xmlns:dbx="http://docblox-project.org/xsl/functions" id="file-nav-box">
<div id="file-nav-options">
Show:
<img src="images/icons/visibility_public.png" id="show-public"><img src="images/icons/visibility_protected.png" id="show-protected"><img src="images/icons/visibility_private.png" id="show-private"><span class="attribute" id="show-inherited">inherited</span>
</div>
<div id="file-nav-container">
<ul id="file-nav"></ul>
<div style="clear: left;"></div>
</div>
<div id="file-nav-tab">
Table of Contents
</div>
</div>
<a xmlns:dbx="http://docblox-project.org/xsl/functions" name="top" class="anchor"></a><a name="interfaces" class="anchor"></a><a xmlns:dbx="http://docblox-project.org/xsl/functions" id="\CamelSpider\Entity\InterfaceLink" class="anchor"></a><h2 xmlns:dbx="http://docblox-project.org/xsl/functions" class="interface">\CamelSpider\Entity\InterfaceLink<div class="to-top"><a href="#top">jump to top</a></div>
</h2>
<div xmlns:dbx="http://docblox-project.org/xsl/functions" class="class">
<small class="package"><b>Package: </b>Default</small><dl class="class-info">
<dt>Children</dt>
<dd><a href="db_CamelSpider_Entity_InterfaceSubscription.html#%5CCamelSpider%5CEntity%5CInterfaceSubscription">\CamelSpider\Entity\InterfaceSubscription</a></dd>
</dl>
<h3>Methods</h3>
<div>
<a id="\CamelSpider\Entity\InterfaceLink::getId()" class="anchor"></a><div class="method public">
<a href="#" class="gripper"><img src="images/icons/arrow_right.png"><img src="images/icons/arrow_down.png" style="display: none;"></a><code><img src="images/icons/method.png" alt="method"><img src="images/icons/visibility_public.png" style="margin-right: 5px" alt="public"><span class="highlight">getId</span><span class="nb-faded-text">(
)
</span>
:
void</code><div class="description"><p class="short_description"></p></div>
<div class="code-tabs"></div>
<div class="clear"></div>
</div>
<a id="\CamelSpider\Entity\InterfaceLink::isDone()" class="anchor"></a><div class="method public">
<a href="#" class="gripper"><img src="images/icons/arrow_right.png"><img src="images/icons/arrow_down.png" style="display: none;"></a><code><img src="images/icons/method.png" alt="method"><img src="images/icons/visibility_public.png" style="margin-right: 5px" alt="public"><span class="highlight">isDone</span><span class="nb-faded-text">(
)
</span>
:
void</code><div class="description"><p class="short_description"></p></div>
<div class="code-tabs"></div>
<div class="clear"></div>
</div>
<a id="\CamelSpider\Entity\InterfaceLink::isWaiting()" class="anchor"></a><div class="method public">
<a href="#" class="gripper"><img src="images/icons/arrow_right.png"><img src="images/icons/arrow_down.png" style="display: none;"></a><code><img src="images/icons/method.png" alt="method"><img src="images/icons/visibility_public.png" style="margin-right: 5px" alt="public"><span class="highlight">isWaiting</span><span class="nb-faded-text">(
)
</span>
:
void</code><div class="description"><p class="short_description"></p></div>
<div class="code-tabs"></div>
<div class="clear"></div>
</div>
<a id="\CamelSpider\Entity\InterfaceLink::setStatus()" class="anchor"></a><div class="method public">
<a href="#" class="gripper"><img src="images/icons/arrow_right.png"><img src="images/icons/arrow_down.png" style="display: none;"></a><code><img src="images/icons/method.png" alt="method"><img src="images/icons/visibility_public.png" style="margin-right: 5px" alt="public"><span class="highlight">setStatus</span><span class="nb-faded-text">(
$x
)
</span>
:
void</code><div class="description"><p class="short_description"></p></div>
<div class="code-tabs">
<strong>Parameters</strong><table class="argument-info">
<thead><tr>
<th>Name</th>
<th>Type</th>
<th>Description</th>
</tr></thead>
<tr>
<th>$x</th>
<td></td>
<td><em></em></td>
</tr>
</table>
</div>
<div class="clear"></div>
</div>
<a id="\CamelSpider\Entity\InterfaceLink::toMinimal()" class="anchor"></a><div class="method public">
<a href="#" class="gripper"><img src="images/icons/arrow_right.png"><img src="images/icons/arrow_down.png" style="display: none;"></a><code><img src="images/icons/method.png" alt="method"><img src="images/icons/visibility_public.png" style="margin-right: 5px" alt="public"><span class="highlight">toMinimal</span><span class="nb-faded-text">(
)
</span>
:
void</code><div class="description"><p class="short_description"></p></div>
<div class="code-tabs"></div>
<div class="clear"></div>
</div>
</div>
</div>
</div>
<small xmlns="" class="footer">Documentation was generated by <a href="http://docblox-project.org">DocBlox 0.15.1</a>.
</small></body></html>
| {
"content_hash": "a86d531756425adb761b789fdef293af",
"timestamp": "",
"source": "github",
"line_count": 171,
"max_line_length": 657,
"avg_line_length": 51.78362573099415,
"alnum_prop": 0.6105025409373236,
"repo_name": "fgbreel/CamelSpider",
"id": "b90b019c0622a6329809c722a5e688c9396a6963",
"size": "8856",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "doc/db_CamelSpider_Entity_InterfaceLink.html",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "PHP",
"bytes": "99196"
},
{
"name": "Shell",
"bytes": "40"
}
],
"symlink_target": ""
} |
<?php
namespace Symfony\Component\Validator\Constraints;
/**
* @Annotation
* @Target({"PROPERTY", "METHOD", "ANNOTATION"})
*
* @author Benjamin Dulau <benjamin.dulau@gmail.com>
* @author Bernhard Schussek <bschussek@gmail.com>
*/
#[\Attribute(\Attribute::TARGET_PROPERTY | \Attribute::TARGET_METHOD | \Attribute::IS_REPEATABLE)]
class Image extends File
{
public const SIZE_NOT_DETECTED_ERROR = '6d55c3f4-e58e-4fe3-91ee-74b492199956';
public const TOO_WIDE_ERROR = '7f87163d-878f-47f5-99ba-a8eb723a1ab2';
public const TOO_NARROW_ERROR = '9afbd561-4f90-4a27-be62-1780fc43604a';
public const TOO_HIGH_ERROR = '7efae81c-4877-47ba-aa65-d01ccb0d4645';
public const TOO_LOW_ERROR = 'aef0cb6a-c07f-4894-bc08-1781420d7b4c';
public const TOO_FEW_PIXEL_ERROR = '1b06b97d-ae48-474e-978f-038a74854c43';
public const TOO_MANY_PIXEL_ERROR = 'ee0804e8-44db-4eac-9775-be91aaf72ce1';
public const RATIO_TOO_BIG_ERROR = '70cafca6-168f-41c9-8c8c-4e47a52be643';
public const RATIO_TOO_SMALL_ERROR = '59b8c6ef-bcf2-4ceb-afff-4642ed92f12e';
public const SQUARE_NOT_ALLOWED_ERROR = '5d41425b-facb-47f7-a55a-de9fbe45cb46';
public const LANDSCAPE_NOT_ALLOWED_ERROR = '6f895685-7cf2-4d65-b3da-9029c5581d88';
public const PORTRAIT_NOT_ALLOWED_ERROR = '65608156-77da-4c79-a88c-02ef6d18c782';
public const CORRUPTED_IMAGE_ERROR = '5d4163f3-648f-4e39-87fd-cc5ea7aad2d1';
// Include the mapping from the base class
protected const ERROR_NAMES = [
self::NOT_FOUND_ERROR => 'NOT_FOUND_ERROR',
self::NOT_READABLE_ERROR => 'NOT_READABLE_ERROR',
self::EMPTY_ERROR => 'EMPTY_ERROR',
self::TOO_LARGE_ERROR => 'TOO_LARGE_ERROR',
self::INVALID_MIME_TYPE_ERROR => 'INVALID_MIME_TYPE_ERROR',
self::SIZE_NOT_DETECTED_ERROR => 'SIZE_NOT_DETECTED_ERROR',
self::TOO_WIDE_ERROR => 'TOO_WIDE_ERROR',
self::TOO_NARROW_ERROR => 'TOO_NARROW_ERROR',
self::TOO_HIGH_ERROR => 'TOO_HIGH_ERROR',
self::TOO_LOW_ERROR => 'TOO_LOW_ERROR',
self::TOO_FEW_PIXEL_ERROR => 'TOO_FEW_PIXEL_ERROR',
self::TOO_MANY_PIXEL_ERROR => 'TOO_MANY_PIXEL_ERROR',
self::RATIO_TOO_BIG_ERROR => 'RATIO_TOO_BIG_ERROR',
self::RATIO_TOO_SMALL_ERROR => 'RATIO_TOO_SMALL_ERROR',
self::SQUARE_NOT_ALLOWED_ERROR => 'SQUARE_NOT_ALLOWED_ERROR',
self::LANDSCAPE_NOT_ALLOWED_ERROR => 'LANDSCAPE_NOT_ALLOWED_ERROR',
self::PORTRAIT_NOT_ALLOWED_ERROR => 'PORTRAIT_NOT_ALLOWED_ERROR',
self::CORRUPTED_IMAGE_ERROR => 'CORRUPTED_IMAGE_ERROR',
];
/**
* @deprecated since Symfony 6.1, use const ERROR_NAMES instead
*/
protected static $errorNames = self::ERROR_NAMES;
public $mimeTypes = 'image/*';
public $minWidth;
public $maxWidth;
public $maxHeight;
public $minHeight;
public $maxRatio;
public $minRatio;
public $minPixels;
public $maxPixels;
public $allowSquare = true;
public $allowLandscape = true;
public $allowPortrait = true;
public $detectCorrupted = false;
// The constant for a wrong MIME type is taken from the parent class.
public $mimeTypesMessage = 'This file is not a valid image.';
public $sizeNotDetectedMessage = 'The size of the image could not be detected.';
public $maxWidthMessage = 'The image width is too big ({{ width }}px). Allowed maximum width is {{ max_width }}px.';
public $minWidthMessage = 'The image width is too small ({{ width }}px). Minimum width expected is {{ min_width }}px.';
public $maxHeightMessage = 'The image height is too big ({{ height }}px). Allowed maximum height is {{ max_height }}px.';
public $minHeightMessage = 'The image height is too small ({{ height }}px). Minimum height expected is {{ min_height }}px.';
public $minPixelsMessage = 'The image has too few pixels ({{ pixels }} pixels). Minimum amount expected is {{ min_pixels }} pixels.';
public $maxPixelsMessage = 'The image has too many pixels ({{ pixels }} pixels). Maximum amount expected is {{ max_pixels }} pixels.';
public $maxRatioMessage = 'The image ratio is too big ({{ ratio }}). Allowed maximum ratio is {{ max_ratio }}.';
public $minRatioMessage = 'The image ratio is too small ({{ ratio }}). Minimum ratio expected is {{ min_ratio }}.';
public $allowSquareMessage = 'The image is square ({{ width }}x{{ height }}px). Square images are not allowed.';
public $allowLandscapeMessage = 'The image is landscape oriented ({{ width }}x{{ height }}px). Landscape oriented images are not allowed.';
public $allowPortraitMessage = 'The image is portrait oriented ({{ width }}x{{ height }}px). Portrait oriented images are not allowed.';
public $corruptedMessage = 'The image file is corrupted.';
/**
* {@inheritdoc}
*/
public function __construct(
array $options = null,
int|string $maxSize = null,
bool $binaryFormat = null,
array $mimeTypes = null,
int $minWidth = null,
int $maxWidth = null,
int $maxHeight = null,
int $minHeight = null,
int|float $maxRatio = null,
int|float $minRatio = null,
int|float $minPixels = null,
int|float $maxPixels = null,
bool $allowSquare = null,
bool $allowLandscape = null,
bool $allowPortrait = null,
bool $detectCorrupted = null,
string $notFoundMessage = null,
string $notReadableMessage = null,
string $maxSizeMessage = null,
string $mimeTypesMessage = null,
string $disallowEmptyMessage = null,
string $uploadIniSizeErrorMessage = null,
string $uploadFormSizeErrorMessage = null,
string $uploadPartialErrorMessage = null,
string $uploadNoFileErrorMessage = null,
string $uploadNoTmpDirErrorMessage = null,
string $uploadCantWriteErrorMessage = null,
string $uploadExtensionErrorMessage = null,
string $uploadErrorMessage = null,
string $sizeNotDetectedMessage = null,
string $maxWidthMessage = null,
string $minWidthMessage = null,
string $maxHeightMessage = null,
string $minHeightMessage = null,
string $minPixelsMessage = null,
string $maxPixelsMessage = null,
string $maxRatioMessage = null,
string $minRatioMessage = null,
string $allowSquareMessage = null,
string $allowLandscapeMessage = null,
string $allowPortraitMessage = null,
string $corruptedMessage = null,
array $groups = null,
mixed $payload = null
) {
parent::__construct(
$options,
$maxSize,
$binaryFormat,
$mimeTypes,
$notFoundMessage,
$notReadableMessage,
$maxSizeMessage,
$mimeTypesMessage,
$disallowEmptyMessage,
$uploadIniSizeErrorMessage,
$uploadFormSizeErrorMessage,
$uploadPartialErrorMessage,
$uploadNoFileErrorMessage,
$uploadNoTmpDirErrorMessage,
$uploadCantWriteErrorMessage,
$uploadExtensionErrorMessage,
$uploadErrorMessage,
$groups,
$payload
);
$this->minWidth = $minWidth ?? $this->minWidth;
$this->maxWidth = $maxWidth ?? $this->maxWidth;
$this->maxHeight = $maxHeight ?? $this->maxHeight;
$this->minHeight = $minHeight ?? $this->minHeight;
$this->maxRatio = $maxRatio ?? $this->maxRatio;
$this->minRatio = $minRatio ?? $this->minRatio;
$this->minPixels = $minPixels ?? $this->minPixels;
$this->maxPixels = $maxPixels ?? $this->maxPixels;
$this->allowSquare = $allowSquare ?? $this->allowSquare;
$this->allowLandscape = $allowLandscape ?? $this->allowLandscape;
$this->allowPortrait = $allowPortrait ?? $this->allowPortrait;
$this->detectCorrupted = $detectCorrupted ?? $this->detectCorrupted;
$this->sizeNotDetectedMessage = $sizeNotDetectedMessage ?? $this->sizeNotDetectedMessage;
$this->maxWidthMessage = $maxWidthMessage ?? $this->maxWidthMessage;
$this->minWidthMessage = $minWidthMessage ?? $this->minWidthMessage;
$this->maxHeightMessage = $maxHeightMessage ?? $this->maxHeightMessage;
$this->minHeightMessage = $minHeightMessage ?? $this->minHeightMessage;
$this->minPixelsMessage = $minPixelsMessage ?? $this->minPixelsMessage;
$this->maxPixelsMessage = $maxPixelsMessage ?? $this->maxPixelsMessage;
$this->maxRatioMessage = $maxRatioMessage ?? $this->maxRatioMessage;
$this->minRatioMessage = $minRatioMessage ?? $this->minRatioMessage;
$this->allowSquareMessage = $allowSquareMessage ?? $this->allowSquareMessage;
$this->allowLandscapeMessage = $allowLandscapeMessage ?? $this->allowLandscapeMessage;
$this->allowPortraitMessage = $allowPortraitMessage ?? $this->allowPortraitMessage;
$this->corruptedMessage = $corruptedMessage ?? $this->corruptedMessage;
}
}
| {
"content_hash": "33d60ad2f8829ed43a4975f96df0f4de",
"timestamp": "",
"source": "github",
"line_count": 186,
"max_line_length": 143,
"avg_line_length": 48.89247311827957,
"alnum_prop": 0.6546074334726193,
"repo_name": "mpdude/symfony",
"id": "8a0a2cef6f95a3565ac67e41d7a10a2f9fcbb4f3",
"size": "9323",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/Symfony/Component/Validator/Constraints/Image.php",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "49788"
},
{
"name": "HTML",
"bytes": "16735"
},
{
"name": "Hack",
"bytes": "26"
},
{
"name": "JavaScript",
"bytes": "29541"
},
{
"name": "PHP",
"bytes": "37919533"
},
{
"name": "Shell",
"bytes": "6545"
},
{
"name": "Twig",
"bytes": "399758"
}
],
"symlink_target": ""
} |
ACCEPTED
#### According to
International Plant Names Index
#### Published in
null
#### Original name
null
### Remarks
null | {
"content_hash": "96faa849d8b3533ce2a387de210a6a08",
"timestamp": "",
"source": "github",
"line_count": 13,
"max_line_length": 31,
"avg_line_length": 9.692307692307692,
"alnum_prop": 0.7063492063492064,
"repo_name": "mdoering/backbone",
"id": "01d6845faf9261eb3ad50293619fd2e3e97bf752",
"size": "181",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "life/Plantae/Magnoliophyta/Magnoliopsida/Fabales/Fabaceae/Myroxylon/Myroxylon pedicellatum/README.md",
"mode": "33188",
"license": "apache-2.0",
"language": [],
"symlink_target": ""
} |
body{background:url("../images/bg.jpg");margin:0;padding:0} | {
"content_hash": "6aa1428bd1529194458ad033cf144b77",
"timestamp": "",
"source": "github",
"line_count": 1,
"max_line_length": 59,
"avg_line_length": 59,
"alnum_prop": 0.7288135593220338,
"repo_name": "trungnv84/SC",
"id": "0808af4cbe54f42b11c0813aefd4235293f6f72b",
"size": "59",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "public/css/common.min.css",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "473"
},
{
"name": "PHP",
"bytes": "402866"
},
{
"name": "SQL",
"bytes": "0"
}
],
"symlink_target": ""
} |
"""
proxy.py
~~~~~~~~
⚡⚡⚡ Fast, Lightweight, Pluggable, TLS interception capable proxy server focused on
Network monitoring, controls & Application development, testing, debugging.
:copyright: (c) 2013-present by Abhinav Singh and contributors.
:license: BSD, see LICENSE for more details.
"""
from .my_web_plugin import MyWebServerPlugin
from .my_proxy_plugin import MyProxyPlugin
__all__ = [
'MyWebServerPlugin',
'MyProxyPlugin',
]
| {
"content_hash": "aa8bb381401245b4f15d7a2aec61b6a7",
"timestamp": "",
"source": "github",
"line_count": 17,
"max_line_length": 86,
"avg_line_length": 27.58823529411765,
"alnum_prop": 0.697228144989339,
"repo_name": "abhinavsingh/proxy.py",
"id": "42f3606026613c77f0910605cdec22a6e6766825",
"size": "499",
"binary": false,
"copies": "1",
"ref": "refs/heads/develop",
"path": "skeleton/app/plugins/__init__.py",
"mode": "33261",
"license": "bsd-3-clause",
"language": [
{
"name": "CSS",
"bytes": "891"
},
{
"name": "Dockerfile",
"bytes": "1222"
},
{
"name": "HTML",
"bytes": "3454"
},
{
"name": "JavaScript",
"bytes": "2260"
},
{
"name": "Jupyter Notebook",
"bytes": "29773"
},
{
"name": "Makefile",
"bytes": "6399"
},
{
"name": "Procfile",
"bytes": "387"
},
{
"name": "Python",
"bytes": "680280"
},
{
"name": "Ruby",
"bytes": "990"
},
{
"name": "Shell",
"bytes": "19211"
},
{
"name": "TypeScript",
"bytes": "23642"
}
],
"symlink_target": ""
} |
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
// Runtime Version:4.0.30319.34209
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
namespace SpotifyHotkeys.Properties
{
[global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "11.0.0.0")]
internal sealed partial class Settings : global::System.Configuration.ApplicationSettingsBase
{
private static Settings defaultInstance = ((Settings)(global::System.Configuration.ApplicationSettingsBase.Synchronized(new Settings())));
public static Settings Default
{
get
{
return defaultInstance;
}
}
}
}
| {
"content_hash": "23368b0a199d6baab322af2f3d436886",
"timestamp": "",
"source": "github",
"line_count": 30,
"max_line_length": 151,
"avg_line_length": 35.63333333333333,
"alnum_prop": 0.5827876520112254,
"repo_name": "joakimskoog/SpotifyHotkeys",
"id": "269d2802a773fff1d711365d75bf2e17053ace93",
"size": "1071",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "SpotifyHotkeys/Properties/Settings.Designer.cs",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C#",
"bytes": "28831"
}
],
"symlink_target": ""
} |
/* eslint-disable no-proto */
/* eslint-disable no-underscore-dangle */
'use strict';
const test = require('tape');
// const _ = require('lodash');
module.exports = (compose) => {
const getsetProps = [
'methods',
'properties',
'deepProperties',
'staticProperties',
'staticDeepProperties',
'configuration',
'deepConfiguration',
];
test('getter and setter', (nest) => {
nest.test('should merge into stamp descriptor', (assert) => {
const createGS = () => ({
get info() {
return `getter${this._info}`;
},
set info(info) {
this._info += `PREFIX-${info}`;
},
});
const stamp = getsetProps.reduce((s, propName) => s.compose({ [propName]: createGS() }), compose());
const descriptor = stamp.compose;
getsetProps.forEach((propName) => {
const info = Object.getOwnPropertyDescriptor(descriptor[propName], 'info');
assert.equal(typeof info.get, 'function', `should have getter in ${propName}`);
assert.equal(typeof info.set, 'function', `should have setter in ${propName}`);
});
assert.end();
});
nest.test('should be okay to overwrite with different getters and setters', (assert) => {
const createGS = () => ({
get info() {
return `getter${this._info}`;
},
set info(info) {
this._info += `PREFIX-${info}`;
},
});
let stamp = getsetProps.reduce((s, propName) => s.compose({ [propName]: createGS() }), compose());
const createGS2 = () => ({
get info() {
return '2';
},
set info(info) {
this._info = `3${info}`;
},
});
stamp = getsetProps.reduce((s, propName) => s.compose({ [propName]: createGS2() }), stamp);
const descriptor = stamp.compose;
getsetProps.forEach((propName) => {
const info = Object.getOwnPropertyDescriptor(descriptor[propName], 'info');
assert.equal(typeof info.get, 'function', `should have getter in ${propName}`);
assert.equal(typeof info.set, 'function', `should have setter in ${propName}`);
});
const instance = stamp();
const info = Object.getOwnPropertyDescriptor(instance, 'info');
assert.equal(typeof info.get, 'function', 'should have getter on object instance');
assert.equal(typeof info.set, 'function', 'should have setter on object instance');
assert.equal(instance.info, '2', 'getter should be overtwitten');
instance.info = '3';
assert.equal(instance._info, '33', 'setter should be overtwitten');
const info2 = Object.getOwnPropertyDescriptor(instance.__proto__, 'info');
assert.equal(typeof info2.get, 'function', 'should have getter on object prototype');
assert.equal(typeof info2.set, 'function', 'should have setter on object prototype');
assert.equal(instance.__proto__.info, '2', 'getter should be overtwitten');
instance.__proto__.info = '3';
assert.equal(instance.__proto__._info, '33', 'setter should be overtwitten');
const info3 = Object.getOwnPropertyDescriptor(stamp, 'info');
assert.equal(typeof info3.get, 'function', 'should have getter on object prototype');
assert.equal(typeof info3.set, 'function', 'should have setter on object prototype');
assert.equal(stamp.info, '2', 'getter should be overtwitten');
stamp.info = '3';
assert.equal(stamp._info, '33', 'setter should be overtwitten');
const info4 = Object.getOwnPropertyDescriptor(stamp.compose.configuration, 'info');
assert.equal(typeof info4.get, 'function', 'should have getter on object prototype');
assert.equal(typeof info4.set, 'function', 'should have setter on object prototype');
assert.equal(stamp.compose.configuration.info, '2', 'getter should be overtwitten');
stamp.compose.configuration.info = '3';
assert.equal(stamp.compose.configuration._info, '33', 'setter should be overtwitten');
assert.end();
});
nest.test('in methods', (assert) => {
const stamp = compose({
properties: { _info: '_initial_' },
methods: {
get info() {
return `getter${this._info}`;
},
set info(info) {
this._info += `PREFIX-${info}`;
},
},
});
const instance = stamp();
instance.info = 'TEXT';
assert.equal(instance.info, 'getter_initial_PREFIX-TEXT', 'Getter should be copied');
assert.equal(instance._info, '_initial_PREFIX-TEXT', 'Setter should be copied');
assert.end();
});
nest.test('in properties', (assert) => {
const stamp = compose({
properties: {
_info: '_initial_',
get info() {
return `getter${this._info}`;
},
set info(info) {
this._info += `PREFIX-${info}`;
},
},
});
const instance = stamp();
instance.info = 'TEXT';
assert.equal(instance.info, 'getter_initial_PREFIX-TEXT');
assert.equal(instance._info, '_initial_PREFIX-TEXT');
assert.end();
});
nest.test('in deepProperties', (assert) => {
const stamp = compose({
deepProperties: {
_info: '_initial_',
get info() {
return `getter${this._info}`;
},
set info(info) {
this._info += `PREFIX-${info}`;
},
},
});
const instance = stamp();
instance.info = 'TEXT';
assert.equal(instance.info, 'getter_initial_PREFIX-TEXT');
assert.equal(instance._info, '_initial_PREFIX-TEXT');
assert.end();
});
nest.test('in staticProperties', (assert) => {
const stamp = compose({
staticProperties: {
_info: '_initial_',
get info() {
return `getter${this._info}`;
},
set info(info) {
this._info += `PREFIX-${info}`;
},
},
});
stamp.info = 'TEXT';
assert.equal(stamp.info, 'getter_initial_PREFIX-TEXT');
assert.equal(stamp._info, '_initial_PREFIX-TEXT');
assert.end();
});
nest.test('in staticDeepProperties', (assert) => {
const stamp = compose({
staticDeepProperties: {
_info: '_initial_',
get info() {
return `getter${this._info}`;
},
set info(info) {
this._info += `PREFIX-${info}`;
},
},
});
stamp.info = 'TEXT';
assert.equal(stamp.info, 'getter_initial_PREFIX-TEXT');
assert.equal(stamp._info, '_initial_PREFIX-TEXT');
assert.end();
});
nest.test('in configuration', (assert) => {
const stamp = compose({
configuration: {
_info: '_initial_',
get info() {
return `getter${this._info}`;
},
set info(info) {
this._info += `PREFIX-${info}`;
},
},
});
const { configuration } = stamp.compose;
configuration.info = 'TEXT';
assert.equal(configuration.info, 'getter_initial_PREFIX-TEXT');
assert.equal(configuration._info, '_initial_PREFIX-TEXT');
assert.end();
});
nest.test('in deepConfiguration', (assert) => {
const stamp = compose({
deepConfiguration: {
_info: '_initial_',
get info() {
return `getter${this._info}`;
},
set info(info) {
this._info += `PREFIX-${info}`;
},
},
});
const { deepConfiguration } = stamp.compose;
deepConfiguration.info = 'TEXT';
assert.equal(deepConfiguration.info, 'getter_initial_PREFIX-TEXT');
assert.equal(deepConfiguration._info, '_initial_PREFIX-TEXT');
assert.end();
});
});
};
| {
"content_hash": "d3e518e40657c979a10669bd60d3c9f9",
"timestamp": "",
"source": "github",
"line_count": 254,
"max_line_length": 106,
"avg_line_length": 30.980314960629922,
"alnum_prop": 0.5543271063667556,
"repo_name": "stampit-org/stamp",
"id": "c411a598416691b1dab8bd10f98b1e607c9baa77",
"size": "7869",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "packages/check-compose/getters-setters-tests.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "JavaScript",
"bytes": "158463"
},
{
"name": "TypeScript",
"bytes": "50447"
}
],
"symlink_target": ""
} |
package goncalves.com.readinglist.Customizers;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.support.v7.app.ActionBar;
/**
* Created by rafagonc on 1/5/16.
*/
public class ActionBarCustomizer {
public static void customizeActionBar(ActionBar actionBar) {
actionBar.setBackgroundDrawable(new ColorDrawable(Color.parseColor("#ffffff")));
}
}
| {
"content_hash": "ddbe2366d3feebf641bc9a44484f27c6",
"timestamp": "",
"source": "github",
"line_count": 15,
"max_line_length": 88,
"avg_line_length": 27.266666666666666,
"alnum_prop": 0.7701711491442543,
"repo_name": "rafagonc/Reading-List-Android",
"id": "d7b77b3e59e0965ec43fe1e82d1ecd3a92b35f1a",
"size": "409",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "app/src/main/java/goncalves/com/readinglist/Customizers/ActionBarCustomizer.java",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Java",
"bytes": "105482"
}
],
"symlink_target": ""
} |
'use strict';
import React from 'react';
import ComboSelect from '../src/Components/ComboSelect';
import { mount } from 'enzyme';
import sinon from 'sinon';
import {expect} from 'chai';
describe('Initialization of component', () => {
beforeEach(()=>{
sinon.spy(ComboSelect.prototype, 'componentDidMount');
});
afterEach(()=>{
ComboSelect.prototype.componentDidMount.restore();
});
let data = [
{text: 111, value: 111}
];
it('calls componentDidMount', () => {
mount(<ComboSelect data={data} />);
expect(ComboSelect.prototype.componentDidMount.calledOnce).to.equal(true);
});
}); | {
"content_hash": "d0d72d44afd112045488ae731f6b4428",
"timestamp": "",
"source": "github",
"line_count": 28,
"max_line_length": 82,
"avg_line_length": 23.428571428571427,
"alnum_prop": 0.625,
"repo_name": "markokostovski/react-combo-select",
"id": "8a067076d00e63f4e071f1745257a907dbf534bb",
"size": "656",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "test/initiate.test.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "2620"
},
{
"name": "HTML",
"bytes": "4206"
},
{
"name": "JavaScript",
"bytes": "47594"
}
],
"symlink_target": ""
} |
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<!--NewPage-->
<HTML>
<HEAD>
<!-- Generated by javadoc (build 1.6.0_29) on Thu Jan 03 13:25:44 EST 2013 -->
<TITLE>
Packet (2013 FRC Java API)
</TITLE>
<META NAME="date" CONTENT="2013-01-03">
<LINK REL ="stylesheet" TYPE="text/css" HREF="../../../../stylesheet.css" TITLE="Style">
<SCRIPT type="text/javascript">
function windowTitle()
{
if (location.href.indexOf('is-external=true') == -1) {
parent.document.title="Packet (2013 FRC Java API)";
}
}
</SCRIPT>
<NOSCRIPT>
</NOSCRIPT>
</HEAD>
<BODY BGCOLOR="white" onload="windowTitle();">
<HR>
<!-- ========= START OF TOP NAVBAR ======= -->
<A NAME="navbar_top"><!-- --></A>
<A HREF="#skip-navbar_top" title="Skip navigation links"></A>
<TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0" SUMMARY="">
<TR>
<TD COLSPAN=2 BGCOLOR="#EEEEFF" CLASS="NavBarCell1">
<A NAME="navbar_top_firstrow"><!-- --></A>
<TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3" SUMMARY="">
<TR ALIGN="center" VALIGN="top">
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../overview-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="package-summary.html"><FONT CLASS="NavBarFont1"><B>Package</B></FONT></A> </TD>
<TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> <FONT CLASS="NavBarFont1Rev"><B>Class</B></FONT> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="class-use/Packet.html"><FONT CLASS="NavBarFont1"><B>Use</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="package-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../index-all.html"><FONT CLASS="NavBarFont1"><B>Index</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A> </TD>
</TR>
</TABLE>
</TD>
<TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM>
"<p style=\"background-color:${javadoc.bgcolor}; color:${javadoc.fgcolor}; padding:4px 5px 2px 3px; margin-top:-1px\"><b>2013 FRC Java API</b></p>"</EM>
</TD>
</TR>
<TR>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
<A HREF="../../../../com/sun/squawk/debugger/Log.html" title="class in com.sun.squawk.debugger"><B>PREV CLASS</B></A>
<A HREF="../../../../com/sun/squawk/debugger/PacketInputStream.html" title="class in com.sun.squawk.debugger"><B>NEXT CLASS</B></A></FONT></TD>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
<A HREF="../../../../index.html?com/sun/squawk/debugger/Packet.html" target="_top"><B>FRAMES</B></A>
<A HREF="Packet.html" target="_top"><B>NO FRAMES</B></A>
<SCRIPT type="text/javascript">
<!--
if(window==top) {
document.writeln('<A HREF="../../../../allclasses-noframe.html"><B>All Classes</B></A>');
}
//-->
</SCRIPT>
<NOSCRIPT>
<A HREF="../../../../allclasses-noframe.html"><B>All Classes</B></A>
</NOSCRIPT>
</FONT></TD>
</TR>
<TR>
<TD VALIGN="top" CLASS="NavBarCell3"><FONT SIZE="-2">
SUMMARY: NESTED | <A HREF="#field_summary">FIELD</A> | <A HREF="#constructor_summary">CONSTR</A> | <A HREF="#method_summary">METHOD</A></FONT></TD>
<TD VALIGN="top" CLASS="NavBarCell3"><FONT SIZE="-2">
DETAIL: <A HREF="#field_detail">FIELD</A> | <A HREF="#constructor_detail">CONSTR</A> | <A HREF="#method_detail">METHOD</A></FONT></TD>
</TR>
</TABLE>
<A NAME="skip-navbar_top"></A>
<!-- ========= END OF TOP NAVBAR ========= -->
<HR>
<!-- ======== START OF CLASS DATA ======== -->
<H2>
<FONT SIZE="-1">
com.sun.squawk.debugger</FONT>
<BR>
Class Packet</H2>
<PRE>
<A HREF="../../../../java/lang/Object.html" title="class in java.lang">java.lang.Object</A>
<IMG SRC="../../../../resources/inherit.gif" ALT="extended by "><B>com.sun.squawk.debugger.Packet</B>
</PRE>
<DL>
<DT><B>Direct Known Subclasses:</B> <DD><A HREF="../../../../com/sun/squawk/debugger/CommandPacket.html" title="class in com.sun.squawk.debugger">CommandPacket</A>, <A HREF="../../../../com/sun/squawk/debugger/ReplyPacket.html" title="class in com.sun.squawk.debugger">ReplyPacket</A></DD>
</DL>
<HR>
<DL>
<DT><PRE>public abstract class <B>Packet</B><DT>extends <A HREF="../../../../java/lang/Object.html" title="class in java.lang">Object</A></DL>
</PRE>
<P>
A <code>Packet</code> encapsulates a JDWP command or reply packet.
<P>
<P>
<HR>
<P>
<!-- =========== FIELD SUMMARY =========== -->
<A NAME="field_summary"><!-- --></A>
<TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY="">
<TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor">
<TH ALIGN="left" COLSPAN="2"><FONT SIZE="+2">
<B>Field Summary</B></FONT></TH>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE>static short</CODE></FONT></TD>
<TD><CODE><B><A HREF="../../../../com/sun/squawk/debugger/Packet.html#FLAG_NEEDS_REPLY">FLAG_NEEDS_REPLY</A></B></CODE>
<BR>
Indicates a packet for which no reply is expected.</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE>static short</CODE></FONT></TD>
<TD><CODE><B><A HREF="../../../../com/sun/squawk/debugger/Packet.html#FLAG_REPLY">FLAG_REPLY</A></B></CODE>
<BR>
The flag bit value indicating a reply packet.</TD>
</TR>
</TABLE>
<!-- ======== CONSTRUCTOR SUMMARY ======== -->
<A NAME="constructor_summary"><!-- --></A>
<TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY="">
<TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor">
<TH ALIGN="left" COLSPAN="2"><FONT SIZE="+2">
<B>Constructor Summary</B></FONT></TH>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD><CODE><B><A HREF="../../../../com/sun/squawk/debugger/Packet.html#Packet(int)">Packet</A></B>(int id)</CODE>
<BR>
Creates a Packet for a new JDWP request.</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD><CODE><B><A HREF="../../../../com/sun/squawk/debugger/Packet.html#Packet(int, int, java.io.DataInputStream)">Packet</A></B>(int id,
int dataLength,
<A HREF="../../../../java/io/DataInputStream.html" title="class in java.io">DataInputStream</A> data)</CODE>
<BR>
Creates a Packet to encapsulate a received JDWP packet.</TD>
</TR>
</TABLE>
<!-- ========== METHOD SUMMARY =========== -->
<A NAME="method_summary"><!-- --></A>
<TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY="">
<TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor">
<TH ALIGN="left" COLSPAN="2"><FONT SIZE="+2">
<B>Method Summary</B></FONT></TH>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE>protected void</CODE></FONT></TD>
<TD><CODE><B><A HREF="../../../../com/sun/squawk/debugger/Packet.html#appendData(java.lang.StringBuffer)">appendData</A></B>(<A HREF="../../../../java/lang/StringBuffer.html" title="class in java.lang">StringBuffer</A> buf)</CODE>
<BR>
Appends a textualized form of this packet's data to a given StringBuffer.</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE>abstract int</CODE></FONT></TD>
<TD><CODE><B><A HREF="../../../../com/sun/squawk/debugger/Packet.html#getFlags()">getFlags</A></B>()</CODE>
<BR>
Gets the value for the 'flags' field in the header of this packet.</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE> int</CODE></FONT></TD>
<TD><CODE><B><A HREF="../../../../com/sun/squawk/debugger/Packet.html#getID()">getID</A></B>()</CODE>
<BR>
Gets the ID that is used to pair this packet with its associated command or reply packet (if any).</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE> <A HREF="../../../../com/sun/squawk/debugger/PacketInputStream.html" title="class in com.sun.squawk.debugger">PacketInputStream</A></CODE></FONT></TD>
<TD><CODE><B><A HREF="../../../../com/sun/squawk/debugger/Packet.html#getInputStream()">getInputStream</A></B>()</CODE>
<BR>
Gets a DataInputStream to read the data in this packet.</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE> <A HREF="../../../../com/sun/squawk/debugger/PacketOutputStream.html" title="class in com.sun.squawk.debugger">PacketOutputStream</A></CODE></FONT></TD>
<TD><CODE><B><A HREF="../../../../com/sun/squawk/debugger/Packet.html#getOutputStream()">getOutputStream</A></B>()</CODE>
<BR>
Gets a PacketOutputStream to write some data to this packet.</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE> int</CODE></FONT></TD>
<TD><CODE><B><A HREF="../../../../com/sun/squawk/debugger/Packet.html#getSize()">getSize</A></B>()</CODE>
<BR>
Gets the size (in bytes) of the entire packet.</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE>abstract <A HREF="../../../../java/lang/String.html" title="class in java.lang">String</A></CODE></FONT></TD>
<TD><CODE><B><A HREF="../../../../com/sun/squawk/debugger/Packet.html#toString()">toString</A></B>()</CODE>
<BR>
Returns a string representation of the object.</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE> void</CODE></FONT></TD>
<TD><CODE><B><A HREF="../../../../com/sun/squawk/debugger/Packet.html#write(java.io.DataOutputStream)">write</A></B>(<A HREF="../../../../java/io/DataOutputStream.html" title="class in java.io">DataOutputStream</A> dos)</CODE>
<BR>
Writes this packet to a given output stream.</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE>protected abstract void</CODE></FONT></TD>
<TD><CODE><B><A HREF="../../../../com/sun/squawk/debugger/Packet.html#writeFields(java.io.DataOutputStream)">writeFields</A></B>(<A HREF="../../../../java/io/DataOutputStream.html" title="class in java.io">DataOutputStream</A> dos)</CODE>
<BR>
Hook for sublasses to write their specific fields to a packet being sent.</TD>
</TR>
</TABLE>
<A NAME="methods_inherited_from_class_java.lang.Object"><!-- --></A>
<TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY="">
<TR BGCOLOR="#EEEEFF" CLASS="TableSubHeadingColor">
<TH ALIGN="left"><B>Methods inherited from class java.lang.<A HREF="../../../../java/lang/Object.html" title="class in java.lang">Object</A></B></TH>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD><CODE><A HREF="../../../../java/lang/Object.html#equals(java.lang.Object)">equals</A>, <A HREF="../../../../java/lang/Object.html#getClass()">getClass</A>, <A HREF="../../../../java/lang/Object.html#hashCode()">hashCode</A>, <A HREF="../../../../java/lang/Object.html#notify()">notify</A>, <A HREF="../../../../java/lang/Object.html#notifyAll()">notifyAll</A>, <A HREF="../../../../java/lang/Object.html#wait()">wait</A>, <A HREF="../../../../java/lang/Object.html#wait(long)">wait</A>, <A HREF="../../../../java/lang/Object.html#wait(long, int)">wait</A></CODE></TD>
</TR>
</TABLE>
<P>
<!-- ============ FIELD DETAIL =========== -->
<A NAME="field_detail"><!-- --></A>
<TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY="">
<TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor">
<TH ALIGN="left" COLSPAN="1"><FONT SIZE="+2">
<B>Field Detail</B></FONT></TH>
</TR>
</TABLE>
<A NAME="FLAG_REPLY"><!-- --></A><H3>
FLAG_REPLY</H3>
<PRE>
public static final short <B>FLAG_REPLY</B></PRE>
<DL>
<DD>The flag bit value indicating a reply packet.
<P>
<DL>
<DT><B>See Also:</B><DD><A HREF="../../../../constant-values.html#com.sun.squawk.debugger.Packet.FLAG_REPLY">Constant Field Values</A></DL>
</DL>
<HR>
<A NAME="FLAG_NEEDS_REPLY"><!-- --></A><H3>
FLAG_NEEDS_REPLY</H3>
<PRE>
public static final short <B>FLAG_NEEDS_REPLY</B></PRE>
<DL>
<DD>Indicates a packet for which no reply is expected.
<P>
<DL>
<DT><B>See Also:</B><DD><A HREF="../../../../constant-values.html#com.sun.squawk.debugger.Packet.FLAG_NEEDS_REPLY">Constant Field Values</A></DL>
</DL>
<!-- ========= CONSTRUCTOR DETAIL ======== -->
<A NAME="constructor_detail"><!-- --></A>
<TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY="">
<TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor">
<TH ALIGN="left" COLSPAN="1"><FONT SIZE="+2">
<B>Constructor Detail</B></FONT></TH>
</TR>
</TABLE>
<A NAME="Packet(int)"><!-- --></A><H3>
Packet</H3>
<PRE>
public <B>Packet</B>(int id)</PRE>
<DL>
<DD>Creates a Packet for a new JDWP request.
<P>
<DL>
<DT><B>Parameters:</B><DD><CODE>id</CODE> - the identifier of the new packet</DL>
</DL>
<HR>
<A NAME="Packet(int, int, java.io.DataInputStream)"><!-- --></A><H3>
Packet</H3>
<PRE>
public <B>Packet</B>(int id,
int dataLength,
<A HREF="../../../../java/io/DataInputStream.html" title="class in java.io">DataInputStream</A> data)
throws <A HREF="../../../../java/io/IOException.html" title="class in java.io">IOException</A></PRE>
<DL>
<DD>Creates a Packet to encapsulate a received JDWP packet.
<P>
<DL>
<DT><B>Parameters:</B><DD><CODE>owner</CODE> - the JDWPListener that received the packet<DD><CODE>id</CODE> - the identifier in the packet<DD><CODE>dataLength</CODE> - the length of the data to read from <code>data</code><DD><CODE>data</CODE> - the contents of the data field of the packet
<DT><B>Throws:</B>
<DD><CODE><A HREF="../../../../java/io/IOException.html" title="class in java.io">IOException</A></CODE></DL>
</DL>
<!-- ============ METHOD DETAIL ========== -->
<A NAME="method_detail"><!-- --></A>
<TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY="">
<TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor">
<TH ALIGN="left" COLSPAN="1"><FONT SIZE="+2">
<B>Method Detail</B></FONT></TH>
</TR>
</TABLE>
<A NAME="getInputStream()"><!-- --></A><H3>
getInputStream</H3>
<PRE>
public <A HREF="../../../../com/sun/squawk/debugger/PacketInputStream.html" title="class in com.sun.squawk.debugger">PacketInputStream</A> <B>getInputStream</B>()</PRE>
<DL>
<DD>Gets a DataInputStream to read the data in this packet.
<P>
<DD><DL>
<DT><B>Returns:</B><DD>a DataInputStream to read the data in this packet</DL>
</DD>
</DL>
<HR>
<A NAME="getOutputStream()"><!-- --></A><H3>
getOutputStream</H3>
<PRE>
public <A HREF="../../../../com/sun/squawk/debugger/PacketOutputStream.html" title="class in com.sun.squawk.debugger">PacketOutputStream</A> <B>getOutputStream</B>()</PRE>
<DL>
<DD>Gets a PacketOutputStream to write some data to this packet. This cannot be called on
a packet that was initialized with some received data.
<P>
<DD><DL>
<DT><B>Returns:</B><DD>a PacketOutputStream to write the data in this packet</DL>
</DD>
</DL>
<HR>
<A NAME="getID()"><!-- --></A><H3>
getID</H3>
<PRE>
public final int <B>getID</B>()</PRE>
<DL>
<DD>Gets the ID that is used to pair this packet with its associated command or reply packet (if any).
<P>
<DD><DL>
<DT><B>Returns:</B><DD>the ID that is unique to this command and reply packet pair this packet belongs to (if any)</DL>
</DD>
</DL>
<HR>
<A NAME="toString()"><!-- --></A><H3>
toString</H3>
<PRE>
public abstract <A HREF="../../../../java/lang/String.html" title="class in java.lang">String</A> <B>toString</B>()</PRE>
<DL>
<DD>Returns a string representation of the object. In general, the
<code>toString</code> method returns a string that
"textually represents" this object. The result should
be a concise but informative representation that is easy for a
person to read.
It is recommended that all subclasses override this method.
<p>
The <code>toString</code> method for class <code>Object</code>
returns a string consisting of the name of the class of which the
object is an instance, the at-sign character `<code>@</code>', and
the unsigned hexadecimal representation of the hash code of the
object. In other words, this method returns a string equal to the
value of:
<blockquote>
<pre>
getClass().getName() + '@' + Integer.toHexString(hashCode())
</pre></blockquote>
<P>
<DD><DL>
<DT><B>Overrides:</B><DD><CODE><A HREF="../../../../java/lang/Object.html#toString()">toString</A></CODE> in class <CODE><A HREF="../../../../java/lang/Object.html" title="class in java.lang">Object</A></CODE></DL>
</DD>
<DD><DL>
<DT><B>Returns:</B><DD>a string representation of the object.</DL>
</DD>
</DL>
<HR>
<A NAME="appendData(java.lang.StringBuffer)"><!-- --></A><H3>
appendData</H3>
<PRE>
protected void <B>appendData</B>(<A HREF="../../../../java/lang/StringBuffer.html" title="class in java.lang">StringBuffer</A> buf)</PRE>
<DL>
<DD>Appends a textualized form of this packet's data to a given StringBuffer.
<P>
<DD><DL>
<DT><B>Parameters:</B><DD><CODE>buf</CODE> - the buffer to extend</DL>
</DD>
</DL>
<HR>
<A NAME="getFlags()"><!-- --></A><H3>
getFlags</H3>
<PRE>
public abstract int <B>getFlags</B>()</PRE>
<DL>
<DD>Gets the value for the 'flags' field in the header of this packet.
<P>
<DD><DL>
</DL>
</DD>
</DL>
<HR>
<A NAME="writeFields(java.io.DataOutputStream)"><!-- --></A><H3>
writeFields</H3>
<PRE>
protected abstract void <B>writeFields</B>(<A HREF="../../../../java/io/DataOutputStream.html" title="class in java.io">DataOutputStream</A> dos)
throws <A HREF="../../../../java/io/IOException.html" title="class in java.io">IOException</A></PRE>
<DL>
<DD>Hook for sublasses to write their specific fields to a packet being sent.
<P>
<DD><DL>
<DT><B>Parameters:</B><DD><CODE>dos</CODE> - the stream to write the fields to
<DT><B>Throws:</B>
<DD><CODE><A HREF="../../../../java/io/IOException.html" title="class in java.io">IOException</A></CODE> - if an IO error occurs</DL>
</DD>
</DL>
<HR>
<A NAME="getSize()"><!-- --></A><H3>
getSize</H3>
<PRE>
public final int <B>getSize</B>()</PRE>
<DL>
<DD>Gets the size (in bytes) of the entire packet. This value may change if there
is currently an output stream adding data to the packet.
<P>
<DD><DL>
<DT><B>Returns:</B><DD>the size (in bytes) of the packets (include the header fields)</DL>
</DD>
</DL>
<HR>
<A NAME="write(java.io.DataOutputStream)"><!-- --></A><H3>
write</H3>
<PRE>
public final void <B>write</B>(<A HREF="../../../../java/io/DataOutputStream.html" title="class in java.io">DataOutputStream</A> dos)
throws <A HREF="../../../../java/io/IOException.html" title="class in java.io">IOException</A></PRE>
<DL>
<DD>Writes this packet to a given output stream. No further data can be added to this
packet once this operation is completed.
<P>
<DD><DL>
<DT><B>Parameters:</B><DD><CODE>dos</CODE> - where to write the packet
<DT><B>Throws:</B>
<DD><CODE><A HREF="../../../../java/io/IOException.html" title="class in java.io">IOException</A></CODE> - if an IO error occurs</DL>
</DD>
</DL>
<!-- ========= END OF CLASS DATA ========= -->
<HR>
<!-- ======= START OF BOTTOM NAVBAR ====== -->
<A NAME="navbar_bottom"><!-- --></A>
<A HREF="#skip-navbar_bottom" title="Skip navigation links"></A>
<TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0" SUMMARY="">
<TR>
<TD COLSPAN=2 BGCOLOR="#EEEEFF" CLASS="NavBarCell1">
<A NAME="navbar_bottom_firstrow"><!-- --></A>
<TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3" SUMMARY="">
<TR ALIGN="center" VALIGN="top">
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../overview-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="package-summary.html"><FONT CLASS="NavBarFont1"><B>Package</B></FONT></A> </TD>
<TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> <FONT CLASS="NavBarFont1Rev"><B>Class</B></FONT> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="class-use/Packet.html"><FONT CLASS="NavBarFont1"><B>Use</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="package-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../index-all.html"><FONT CLASS="NavBarFont1"><B>Index</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A> </TD>
</TR>
</TABLE>
</TD>
<TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM>
"<p style=\"background-color:${javadoc.bgcolor}; color:${javadoc.fgcolor}; padding:4px 5px 2px 3px; margin-top:-1px\"><b>2013 FRC Java API</b></p>"</EM>
</TD>
</TR>
<TR>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
<A HREF="../../../../com/sun/squawk/debugger/Log.html" title="class in com.sun.squawk.debugger"><B>PREV CLASS</B></A>
<A HREF="../../../../com/sun/squawk/debugger/PacketInputStream.html" title="class in com.sun.squawk.debugger"><B>NEXT CLASS</B></A></FONT></TD>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
<A HREF="../../../../index.html?com/sun/squawk/debugger/Packet.html" target="_top"><B>FRAMES</B></A>
<A HREF="Packet.html" target="_top"><B>NO FRAMES</B></A>
<SCRIPT type="text/javascript">
<!--
if(window==top) {
document.writeln('<A HREF="../../../../allclasses-noframe.html"><B>All Classes</B></A>');
}
//-->
</SCRIPT>
<NOSCRIPT>
<A HREF="../../../../allclasses-noframe.html"><B>All Classes</B></A>
</NOSCRIPT>
</FONT></TD>
</TR>
<TR>
<TD VALIGN="top" CLASS="NavBarCell3"><FONT SIZE="-2">
SUMMARY: NESTED | <A HREF="#field_summary">FIELD</A> | <A HREF="#constructor_summary">CONSTR</A> | <A HREF="#method_summary">METHOD</A></FONT></TD>
<TD VALIGN="top" CLASS="NavBarCell3"><FONT SIZE="-2">
DETAIL: <A HREF="#field_detail">FIELD</A> | <A HREF="#constructor_detail">CONSTR</A> | <A HREF="#method_detail">METHOD</A></FONT></TD>
</TR>
</TABLE>
<A NAME="skip-navbar_bottom"></A>
<!-- ======== END OF BOTTOM NAVBAR ======= -->
<HR>
"<center><i><font size=\"-1\">For updated information see the <a href=\"http://www.usfirst.org/roboticsprograms/frc/\">Java FRC site</a></font></i></center>"
</BODY>
</HTML>
| {
"content_hash": "f1114b3747aa47fe72b8f49dbcab3466",
"timestamp": "",
"source": "github",
"line_count": 549,
"max_line_length": 571,
"avg_line_length": 44.03825136612022,
"alnum_prop": 0.6244364478636721,
"repo_name": "arithehun/frc",
"id": "1a5a8f487b8fcdd9c688c62e8a7463590931ae3e",
"size": "24177",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "java/2013/com/sun/squawk/debugger/Packet.html",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "ASP",
"bytes": "48011"
},
{
"name": "CSS",
"bytes": "192075"
},
{
"name": "JavaScript",
"bytes": "47369283"
},
{
"name": "Opa",
"bytes": "126616"
},
{
"name": "PHP",
"bytes": "52603"
},
{
"name": "Shell",
"bytes": "518"
},
{
"name": "TypeScript",
"bytes": "24280"
}
],
"symlink_target": ""
} |
import { module, test } from 'qunit';
import { setupTest } from 'ember-qunit';
module('Unit | Route | lost at sea', function(hooks) {
setupTest(hooks);
test('it exists', function(assert) {
const route = this.owner.lookup('route:lost-at-sea');
assert.ok(route);
});
}); | {
"content_hash": "8a5594b65690c2cb35dcf46b067f183b",
"timestamp": "",
"source": "github",
"line_count": 11,
"max_line_length": 57,
"avg_line_length": 25.818181818181817,
"alnum_prop": 0.6443661971830986,
"repo_name": "shipshapecode/shipshape.io",
"id": "2ca08ddddc7ea2b51e1bec5262ffb8d069d5d0da",
"size": "284",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "tests/unit/routes/lost-at-sea.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "22920"
},
{
"name": "HTML",
"bytes": "71166"
},
{
"name": "JavaScript",
"bytes": "86889"
}
],
"symlink_target": ""
} |
package com.android.tools.build.bundletool.model;
import static com.android.bundle.Targeting.Abi.AbiAlias.MIPS;
import static com.android.bundle.Targeting.Abi.AbiAlias.X86;
import static com.android.bundle.Targeting.Abi.AbiAlias.X86_64;
import static com.android.tools.build.bundletool.testing.ManifestProtoUtils.androidManifest;
import static com.android.tools.build.bundletool.testing.TargetingUtils.nativeDirectoryTargeting;
import static com.android.tools.build.bundletool.testing.TargetingUtils.nativeLibraries;
import static com.android.tools.build.bundletool.testing.TargetingUtils.targetedNativeDirectory;
import static com.google.common.truth.Truth.assertThat;
import static com.google.common.truth.Truth8.assertThat;
import static com.google.common.truth.extensions.proto.ProtoTruth.assertThat;
import com.android.bundle.Files.NativeLibraries;
import com.android.tools.build.bundletool.testing.BundleModuleBuilder;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
@RunWith(JUnit4.class)
public class ModuleAbiSanitizerTest {
@Test
public void noNativeLibraries_moduleUnchanged() throws Exception {
BundleModule testModule =
new BundleModuleBuilder("testModule")
.addFile("assets/file.txt")
.setManifest(androidManifest("com.test.app"))
.build();
BundleModule sanitizedModule = new ModuleAbiSanitizer().sanitize(testModule);
assertThat(sanitizedModule).isEqualTo(testModule);
}
@Test
public void consistentNativeLibraries_moduleUnchanged() throws Exception {
NativeLibraries nativeConfig =
nativeLibraries(
targetedNativeDirectory("lib/x86", nativeDirectoryTargeting(X86)),
targetedNativeDirectory("lib/x86_64", nativeDirectoryTargeting(X86_64)),
targetedNativeDirectory("lib/mips", nativeDirectoryTargeting(MIPS)));
BundleModule testModule =
new BundleModuleBuilder("testModule")
.addFile("lib/x86/lib1.so")
.addFile("lib/x86/lib2.so")
.addFile("lib/x86/lib3.so")
.addFile("lib/x86_64/lib1.so")
.addFile("lib/x86_64/lib2.so")
.addFile("lib/x86_64/lib3.so")
.addFile("lib/mips/lib1.so")
.addFile("lib/mips/lib2.so")
.addFile("lib/mips/lib3.so")
.setNativeConfig(nativeConfig)
.setManifest(androidManifest("com.test.app"))
.build();
BundleModule sanitizedModule = new ModuleAbiSanitizer().sanitize(testModule);
assertThat(sanitizedModule.getNativeConfig().get())
.isEqualTo(testModule.getNativeConfig().get());
assertThat(sanitizedModule.getEntries()).containsExactlyElementsIn(testModule.getEntries());
// Sanity check that nothing else changed as well.
assertThat(sanitizedModule).isEqualTo(testModule);
}
@Test
public void inconsistentNativeLibraries_libFilesFilteredAwayAndNativeTargetingAdjusted()
throws Exception {
NativeLibraries nativeConfig =
nativeLibraries(
targetedNativeDirectory("lib/x86", nativeDirectoryTargeting(X86)),
targetedNativeDirectory("lib/x86_64", nativeDirectoryTargeting(X86_64)),
targetedNativeDirectory("lib/mips", nativeDirectoryTargeting(MIPS)));
BundleModule testModule =
new BundleModuleBuilder("testModule")
.addFile("lib/x86/lib1.so")
.addFile("lib/x86/lib2.so")
.addFile("lib/x86/lib3.so")
.addFile("lib/x86_64/lib1.so")
.addFile("lib/x86_64/lib2.so")
.addFile("lib/mips/lib1.so")
.setNativeConfig(nativeConfig)
.setManifest(androidManifest("com.test.app"))
.build();
BundleModule sanitizedModule = new ModuleAbiSanitizer().sanitize(testModule);
assertThat(
sanitizedModule
.getEntries()
.stream()
.map(ModuleEntry::getPath)
.filter(entryPath -> entryPath.startsWith(ZipPath.create("lib")))
.map(ZipPath::toString))
.containsExactly("lib/x86/lib1.so", "lib/x86/lib2.so", "lib/x86/lib3.so");
assertThat(sanitizedModule.getNativeConfig().get())
.isEqualTo(
nativeLibraries(targetedNativeDirectory("lib/x86", nativeDirectoryTargeting(X86))));
}
}
| {
"content_hash": "aa6a6fba8c8142f22c7d61d5eeaea863",
"timestamp": "",
"source": "github",
"line_count": 103,
"max_line_length": 97,
"avg_line_length": 42.29126213592233,
"alnum_prop": 0.695821854912764,
"repo_name": "google/bundletool",
"id": "c041dab98d72e656d4e15ee9bd6482c34a4106bc",
"size": "4974",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/test/java/com/android/tools/build/bundletool/model/ModuleAbiSanitizerTest.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Java",
"bytes": "5939670"
}
],
"symlink_target": ""
} |
var util = {
firstKey : function(o) {
for (var key in o) return key;
},
getUrlParamMap : function() {
var params = {};
var kvs = window.location.search.substring(1).split('&');
for (var i=0; i<kvs.length; i++) {
var kv = kvs[i].split('=');
params[decodeURIComponent(kv[0])] = decodeURIComponent(kv[1]);
}
return params;
},
ajax : function (args) {
if (!args) throw "missing args parameter";
jQuery.ajax({
url: args.url,
type: args.method || "GET",
crossDomain: true,
data: args.data,
dataType: "json",
success: function (response) {
if (args.onDone) {
args.onDone(response, args);
} else {
console.log(['rpc.done', args, response]);
}
},
error: function (xhr, status) {
if (args.onError) {
args.onError(xhr, status, args);
} else {
console.log(['rpc.error', args, xhr, status]);
}
}
});
},
ajaxSetup : function() {
jQuery.ajaxSetup({
converters:{"text json":function(json) {
return eval('('+json+')');
}}
});
}
};
| {
"content_hash": "a1f806ef3844940067372ee42cd43a42",
"timestamp": "",
"source": "github",
"line_count": 48,
"max_line_length": 74,
"avg_line_length": 28.791666666666668,
"alnum_prop": 0.42908827785817655,
"repo_name": "stewartoallen/cbs",
"id": "4e1c2296de8a2b0f3087cc0286d7964b7a65209d",
"size": "1382",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "config/template/me/lib/util.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "13238"
},
{
"name": "JavaScript",
"bytes": "503566"
},
{
"name": "Shell",
"bytes": "247"
}
],
"symlink_target": ""
} |
<!DOCTYPE html><html><head><meta charset="utf-8" />
<meta http-equiv="refresh" content="0;url=/place/gabon/legislation/" />
</head></html> | {
"content_hash": "e45ee76c8bd663bffb355a20b0f27303",
"timestamp": "",
"source": "github",
"line_count": 3,
"max_line_length": 71,
"avg_line_length": 46,
"alnum_prop": 0.6811594202898551,
"repo_name": "okfn/opendataindex-2015",
"id": "0568df79c9c7fa2f635af9ed0e711ca57d6e48ff",
"size": "138",
"binary": false,
"copies": "1",
"ref": "refs/heads/gh-pages",
"path": "country/overview/Gabon/legislation/index.html",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "277465"
},
{
"name": "HTML",
"bytes": "169425658"
},
{
"name": "JavaScript",
"bytes": "37060"
}
],
"symlink_target": ""
} |
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using AuthCodeClient.Models;
using Microsoft.AspNetCore.Authorization;
using System.Net.Http;
using System.Net.Http.Headers;
using IdentityServer4.Services;
using IdSrv.Infra;
using AuthCodeClient.ViewModels;
namespace AuthCodeClient.Controllers
{
public class HomeController : Controller
{
private readonly ILogger<HomeController> _logger;
private readonly IClaimsAccessor _claimsAccessor;
public HomeController(ILogger<HomeController> logger, IClaimsAccessor claimsAccessor)
{
_logger = logger;
_claimsAccessor = claimsAccessor;
}
[Authorize]
public IActionResult Index()
{
//_profileService.GetProfileDataAsync()
return View();
}
[Authorize]
public async Task<IActionResult> Privacy()
{
var accesstoken = _claimsAccessor.AccessToken;
var result = new List<WeatherForecast>();
using (var client = new HttpClient())
{
client.BaseAddress = new Uri("http://localhost:64521");
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", accesstoken);
var response = await client.GetAsync("weatherforecast");
if(response.IsSuccessStatusCode)
result = await response.Content.ReadAsAsync<List<WeatherForecast>>();
}
return View(result);
}
[ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)]
public IActionResult Error()
{
return View(new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier });
}
}
}
| {
"content_hash": "56dae3ae1e3c388a7bae3d23a6939162",
"timestamp": "",
"source": "github",
"line_count": 58,
"max_line_length": 114,
"avg_line_length": 33.775862068965516,
"alnum_prop": 0.6462480857580398,
"repo_name": "SudhersonV/DotNetRoot",
"id": "22434c3d743201332269564b9d9aae1b3b585170",
"size": "1961",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "Modules/IdentityServer/IdentityServer4/Clients/AuthCodeClient/Controllers/HomeController.cs",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "ASP",
"bytes": "2638"
},
{
"name": "Batchfile",
"bytes": "17"
},
{
"name": "C#",
"bytes": "2181546"
},
{
"name": "CSS",
"bytes": "310234"
},
{
"name": "HTML",
"bytes": "508222"
},
{
"name": "JavaScript",
"bytes": "594509"
},
{
"name": "Pascal",
"bytes": "109532"
},
{
"name": "PowerShell",
"bytes": "451694"
},
{
"name": "Puppet",
"bytes": "25968"
}
],
"symlink_target": ""
} |
<plugin-repository>
<category name="Settings">
<idea-plugin>
<id>com.agido.idea.settings</id>
<name>Settings Enforcer</name>
<version>0.1.3</version>
<downloadUrl>SettingsEnforcer.jar</downloadUrl>
</idea-plugin>
</category>
</plugin-repository>
| {
"content_hash": "8fc1d17f41dfb928aae0bdeebc78f939",
"timestamp": "",
"source": "github",
"line_count": 10,
"max_line_length": 59,
"avg_line_length": 31.8,
"alnum_prop": 0.5849056603773585,
"repo_name": "agido/settingsenforcer",
"id": "22c720a6310ab01cd6bb2de7bc888573c7f58207",
"size": "318",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "update/updatePlugins.xml",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Java",
"bytes": "56392"
}
],
"symlink_target": ""
} |
const mongoose = require('mongoose')
const passport = require('passport')
const { ExtractJwt, Strategy: JwtStrategy } = require('passport-jwt')
const User = mongoose.model('User')
passport.use(User.createStrategy())
passport.use(
new JwtStrategy(
{
jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
secretOrKey: process.env.SECRET,
},
async (payload, done) => {
const user = await User.findOne({ id: payload.id })
if (user) {
return done(null, user)
}
return done(null, false)
},
),
)
passport.serializeUser(User.serializeUser())
passport.deserializeUser(User.deserializeUser())
| {
"content_hash": "854198542310af9885124bc11969173d",
"timestamp": "",
"source": "github",
"line_count": 27,
"max_line_length": 69,
"avg_line_length": 24.296296296296298,
"alnum_prop": 0.6722560975609756,
"repo_name": "alexandernanberg/luncha",
"id": "349b7eabafb71c04fa2b1499e765a5cf37ec3a8f",
"size": "656",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "server/helpers/passport.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "HTML",
"bytes": "1082"
},
{
"name": "JavaScript",
"bytes": "48561"
}
],
"symlink_target": ""
} |
<!DOCTYPE html>
<html lang="en">
<head>
@include('layouts.partials.head')
</head>
<body class="no-skin">
@include('layouts.partials.navbar')
<div class="main-container" id="main-container">
<script type="text/javascript">
try{ace.settings.check('main-container' , 'fixed')}catch(e){}
</script>
<div id="sidebar" class="sidebar responsive">
@include('layouts.partials.sidebar')
</div>
<div class="main-content">
@include('layouts.partials.main-content')
</div>
<div class="footer">
@include('layouts.partials.footer')
</div>
<a href="#" id="btn-scroll-up" class="btn-scroll-up btn btn-sm btn-inverse">
<i class="ace-icon fa fa-angle-double-up icon-only bigger-110"></i>
</a>
</div>
<!--[if !IE]> -->
<script type="text/javascript">
window.jQuery || document.write("<script src='/assets/js/jquery.js'>"+"<"+"/script>");
</script>
<!-- <![endif]-->
<!--[if IE]>
<script type="text/javascript">
window.jQuery || document.write("<script src='/assets/js/jquery1x.js'>"+"<"+"/script>");
</script>
<![endif]-->
<script type="text/javascript">
if('ontouchstart' in document.documentElement) document.write("<script src='/assets/js/jquery.mobile.custom.js'>"+"<"+"/script>");
</script>
<script src="/assets/js/bootstrap.js"></script>
<script src="/assets/js/ace/ace.js"></script>
<script src="/assets/js/ace/ace.sidebar.js"></script>
@yield('plugin-scripts')
<!--<script src="/assets/js/dashboard.js"></script>-->
@yield('page-scripts')
</body>
</html> | {
"content_hash": "a421edaf53435e78e11af3d7ed390e8b",
"timestamp": "",
"source": "github",
"line_count": 45,
"max_line_length": 133,
"avg_line_length": 34.333333333333336,
"alnum_prop": 0.6297734627831715,
"repo_name": "morphatic/portphilio",
"id": "3927f71cc9e200a2923a4e71fb2a6ae0ffc08a02",
"size": "1545",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "resources/views/layouts/master.blade.php",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "ApacheConf",
"bytes": "412"
},
{
"name": "CSS",
"bytes": "72"
},
{
"name": "Cucumber",
"bytes": "13881"
},
{
"name": "JavaScript",
"bytes": "4230552"
},
{
"name": "PHP",
"bytes": "246450"
}
],
"symlink_target": ""
} |
SYNONYM
#### According to
The Catalogue of Life, 3rd January 2011
#### Published in
null
#### Original name
null
### Remarks
null | {
"content_hash": "7440ba6e187e23f4db874f739723eedb",
"timestamp": "",
"source": "github",
"line_count": 13,
"max_line_length": 39,
"avg_line_length": 10.23076923076923,
"alnum_prop": 0.6917293233082706,
"repo_name": "mdoering/backbone",
"id": "e8b5cb51535644e77de57fd5b69fb2d558de88cc",
"size": "184",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "life/Plantae/Magnoliophyta/Liliopsida/Asparagales/Iridaceae/Gladiolus/Gladiolus papilio/ Syn. Gladiolus spathulatus/README.md",
"mode": "33188",
"license": "apache-2.0",
"language": [],
"symlink_target": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.