text stringlengths 2 1.04M | meta dict |
|---|---|
class DeviseCreateUsers < ActiveRecord::Migration
def change
create_table(:users) do |t|
## Database authenticatable
t.string :email, :null => false, :default => ""
t.string :encrypted_password, :null => false, :default => ""
## Role
t.integer :roles_mask
## Recoverable
t.string :reset_password_token
t.datetime :reset_password_sent_at
## Rememberable
t.datetime :remember_created_at
## Trackable
t.integer :sign_in_count, :default => 0
t.datetime :current_sign_in_at
t.datetime :last_sign_in_at
t.string :current_sign_in_ip
t.string :last_sign_in_ip
## Confirmable
# t.string :confirmation_token
# t.datetime :confirmed_at
# t.datetime :confirmation_sent_at
# t.string :unconfirmed_email # Only if using reconfirmable
## Lockable
# t.integer :failed_attempts, :default => 0 # Only if lock strategy is :failed_attempts
# t.string :unlock_token # Only if unlock strategy is :email or :both
# t.datetime :locked_at
## Token authenticatable
# t.string :authentication_token
t.timestamps
end
add_index :users, :email, :unique => true
add_index :users, :reset_password_token, :unique => true
# add_index :users, :confirmation_token, :unique => true
# add_index :users, :unlock_token, :unique => true
# add_index :users, :authentication_token, :unique => true
end
end
| {
"content_hash": "da91aa35ac5215e67ec85dbe5ba7d252",
"timestamp": "",
"source": "github",
"line_count": 49,
"max_line_length": 94,
"avg_line_length": 31.122448979591837,
"alnum_prop": 0.6078688524590163,
"repo_name": "paulocesar/template-rails",
"id": "a657b066f9b7ceeb9d73006191e20026bb767b9a",
"size": "1525",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "db/migrate/20130807005112_devise_create_users.rb",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "780"
},
{
"name": "CoffeeScript",
"bytes": "211"
},
{
"name": "JavaScript",
"bytes": "690"
},
{
"name": "Ruby",
"bytes": "38344"
}
],
"symlink_target": ""
} |
package com.hearthproject.oneclient.fx.contentpane.base;
import com.hearthproject.oneclient.Main;
import javafx.scene.layout.VBox;
public enum ButtonDisplay {
TOP(Main.mainController.topButtonBox), ABOVE_DIVIDER(Main.mainController.aboveDividerButtonBox), BELOW_DIVIDER(Main.mainController.belowDividerButtonBox), NONE(null);
VBox container;
ButtonDisplay(VBox container) {
this.container = container;
}
public VBox getContainer() {
return container;
}
}
| {
"content_hash": "166233a6e46d30365f50f826ab2a1b10",
"timestamp": "",
"source": "github",
"line_count": 18,
"max_line_length": 167,
"avg_line_length": 26.11111111111111,
"alnum_prop": 0.7978723404255319,
"repo_name": "HearthProject/OneClient",
"id": "e06328cf9c63a1775cbd3c7cca543e1defa0109a",
"size": "470",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/main/java/com/hearthproject/oneclient/fx/contentpane/base/ButtonDisplay.java",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "40204"
},
{
"name": "Java",
"bytes": "279791"
}
],
"symlink_target": ""
} |
Mac
===
```bash
$ qlmanage -p <image>
```
```bash
$ screencapture -c <image>
$ screencapture -i <image>
# Capture the contents of the screen, including the cursor, and attach the resulting image to a new Mail message
$ screencapture -C -M <image>.png
# Select a window using your mouse, then capture its contents without the window's drop shadow and copy the image to the clipboard
$ screencapture -c -W
# Capture the screen after a delay of 10 seconds and the open the new image in Preview
$ screencapture -T 10 -P <image>.png
# Select a portion of the screen with your mouse, capture its contents, and save the image as a pdf
$ screencapture -s -t pdf <image>.pdf
```
```bash
$ sips --resampleWidth 100 <image> --out <image>
```
```bash
# http://www.cyberciti.biz/faq/apple-macosx-disable-sleeping-from-bash-command/
# Prevent the display from sleeping
$ caffeinate -d
# Prevent the system from idle sleeping
$ caffeinate -i
# Prevent the disk from idle sleeping
$ caffeinate -m
# Prevent the system from sleeping when system is running on AC power
$ caffeinate -s
# How do I declare that user is active?
$ caffeinate -u vivek
$ caffeinate -u vivek wget url
# How do I set timeout?
$ caffeinate -t 60
$ caffeinate -t 120 wget url
```
```bash
# http://www.cyberciti.biz/faq/howto-restart-airport-wireless-from-bash-command-line-in-macosx/
$ sudo ifconfig en0 stop
$ sudo ifconfig en0 start
$ sudo ifconfig -u en0
# Restart Mac OS X networking
# off
$ networksetup -setairportpower en0 off
$ networksetup -setairportpower 'Wi-Fi' off
# on
$ networksetup -setairportpower en0 on
$ networksetup -setairportpower 'Wi-Fi' on
```
```bash
# http://other-zbx1.sakura.ad.jp/zabbix/screens.php?sid=40a24461748c1a5b&form_refresh=1&fullscreen=0&elementid=97
# -a: to choose the app yourself
$ open -a
# -e: to open the file for editing in TextEdit
$ open -e
# mdfind: locate alternative
$ mdfind
$ diskutil list
```
| {
"content_hash": "af623cda662b0a867861619ec7a4e823",
"timestamp": "",
"source": "github",
"line_count": 66,
"max_line_length": 130,
"avg_line_length": 28.954545454545453,
"alnum_prop": 0.7346938775510204,
"repo_name": "knakayama/my-fuc",
"id": "d323ae2a2494d69684e7487537650cc96ef8c9b8",
"size": "1911",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "mac.md",
"mode": "33188",
"license": "mit",
"language": [],
"symlink_target": ""
} |
#ifndef _LINUX_HASH_H
#define _LINUX_HASH_H
/* Fast hashing routine for ints, longs and pointers.
(C) 2002 William Lee Irwin III, IBM */
/*
* Knuth recommends primes in approximately golden ratio to the maximum
* integer representable by a machine word for multiplicative hashing.
* Chuck Lever verified the effectiveness of this technique:
* http://www.citi.umich.edu/techreports/reports/citi-tr-00-1.pdf
*
* These primes are chosen to be bit-sparse, that is operations on
* them can use shifts and additions instead of multiplications for
* machines where multiplications are slow.
*/
#include <stdint.h>
/* 2^31 + 2^29 - 2^25 + 2^22 - 2^19 - 2^16 + 1 */
#define GOLDEN_RATIO_PRIME_32 0x9e370001UL
/* 2^63 + 2^61 - 2^57 + 2^54 - 2^51 - 2^18 + 1 */
#define GOLDEN_RATIO_PRIME_64 0x9e37fffffffc0001UL
#if defined(__ILP32__)
#define GOLDEN_RATIO_PRIME GOLDEN_RATIO_PRIME_32
#define hash_long(val, bits) hash_32(val, bits)
#elif defined(__LP64__)
#define hash_long(val, bits) hash_64(val, bits)
#define GOLDEN_RATIO_PRIME GOLDEN_RATIO_PRIME_64
#else
#error Wordsize not 32 or 64
#endif
static inline uint64_t hash_64(const uint64_t val, const unsigned int bits)
{
uint64_t hash = val;
/* Sigh, gcc can't optimise this alone like it does for 32 bits. */
uint64_t n = hash;
n <<= 18;
hash -= n;
n <<= 33;
hash -= n;
n <<= 3;
hash += n;
n <<= 3;
hash -= n;
n <<= 4;
hash += n;
n <<= 2;
hash += n;
/* High bits are more random, so use them. */
return hash >> (64 - bits);
}
static inline uint32_t hash_32(uint32_t val, unsigned int bits)
{
/* On some cpus multiply is faster, on others gcc will do shifts */
uint32_t hash = val * GOLDEN_RATIO_PRIME_32;
/* High bits are more random, so use them. */
return hash >> (32 - bits);
}
static inline unsigned long hash_ptr(void *ptr, unsigned int bits)
{
return hash_long((unsigned long)ptr, bits);
}
#endif /* _LINUX_HASH_H */
| {
"content_hash": "1b3ace3278493116ba6a1f282a7d8b14",
"timestamp": "",
"source": "github",
"line_count": 70,
"max_line_length": 75,
"avg_line_length": 27.314285714285713,
"alnum_prop": 0.6778242677824268,
"repo_name": "taviso/ctypes.sh",
"id": "00cfd41117d852f3eab93eb0bd8cfc2a27412bf1",
"size": "1912",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/struct/hash.h",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C",
"bytes": "421149"
},
{
"name": "C++",
"bytes": "20987"
},
{
"name": "M4",
"bytes": "5006"
},
{
"name": "Makefile",
"bytes": "1329"
},
{
"name": "Shell",
"bytes": "18732"
}
],
"symlink_target": ""
} |
package org.jimmutable.cloud.cache;
import org.jimmutable.core.exceptions.ValidationException;
import org.jimmutable.core.objects.Stringable;
import org.jimmutable.core.utils.Validator;
/**
*
* Stringable, the format is path://name
*
* Cache path(s) are / separated elements. Elements are normalized to lower case
* and limited to letters, numbers and dashes. There is no practical length
* limit on cache keys.
*
* Name(s) can contain any character. Name(s) are trimmed (whitespace at the beginning
* and ending deleted). Name(s) are case sensitive.
*
* Examples of valid cache keys include
*
* foo/bar://quz
* foo/bar://https://www.google.com
* foo://11248
*
* @author kanej
*/
/*
* CODEREVIEW
* I'm super confused. I've read the docs and classes for CachePatha and CacheKey.
* I can't figure out what's what. You have what I think are copy-paste errors in
* class comments where you use CachePath/path and CacheKey/key interchangeably.
* See the first paragraph above. "Cache path(s) are / separated....limit on cache keys."
* Also, the field is called "name", but the error message says "value".
* Finally, neither javadoc gives a reasonable explanation for _what_ a CachePath or CacheKey
* _is_, what it is used for, and how they differ/relate. What would be a real-world
* example of a CachePath and CacheKey's?
*
* Since this is a client-facing concept, I want to make sure it is nailed down.
* -JMD
*/
public class CacheKey extends Stringable
{
static public final MyConverter CONVERTER = new MyConverter();
private CachePath path;
private String name;
public CacheKey(String str)
{
super(str);
}
public void normalize()
{
}
public void validate()
{
Validator.notNull(getSimpleValue());
Validator.min(getSimpleValue().length(), 1);
int idx = getSimpleValue().indexOf("://");
if ( idx == -1 )
throw new ValidationException("Cache keys must contain a \"://\" to separate the cache path and the value");
path = new CachePath(getSimpleValue().substring(0, idx));
name = getSimpleValue().substring(idx+3, getSimpleValue().length()).trim();
setValue(path+"://"+name);
}
static public class MyConverter extends Stringable.Converter<CacheKey>
{
public CacheKey fromString(String str, CacheKey default_value)
{
try
{
return new CacheKey(str);
}
catch(Exception e)
{
return default_value;
}
}
}
public CachePath getSimplePath() { return path; }
public String getSimpleName() { return name; }
}
| {
"content_hash": "72dc4fcc79399ede1bb2d9073c461d38",
"timestamp": "",
"source": "github",
"line_count": 91,
"max_line_length": 111,
"avg_line_length": 27.78021978021978,
"alnum_prop": 0.7037183544303798,
"repo_name": "jimmutable/core",
"id": "c0d9ef6ab4d6db3df3c2ce72a50f879c6100b6bb",
"size": "2528",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "cloud/src/main/java/org/jimmutable/cloud/cache/CacheKey.java",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "HTML",
"bytes": "2185"
},
{
"name": "Java",
"bytes": "1632103"
}
],
"symlink_target": ""
} |
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>angles: 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.8.1 / angles - 8.5.0</a></li>
</ul>
</div>
</div>
</div>
<div class="article">
<div class="row">
<div class="col-md-12">
<a href="../..">« Up</a>
<h1>
angles
<small>
8.5.0
<span class="label label-info">Not compatible 👼</span>
</small>
</h1>
<p>📅 <em><script>document.write(moment("2022-10-06 05:16:16 +0000", "YYYY-MM-DD HH:mm:ss Z").fromNow());</script> (2022-10-06 05:16:16 UTC)</em><p>
<h2>Context</h2>
<pre># Packages matching: installed
# Name # Installed # Synopsis
base-bigarray base
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.8.1 Formal proof management system
num 1.4 The legacy Num library for arbitrary-precision integer and rational arithmetic
ocaml 4.08.1 The OCaml compiler (virtual package)
ocaml-base-compiler 4.08.1 Official release 4.08.1
ocaml-config 1 OCaml Switch Configuration
ocamlfind 1.9.5 A library manager for OCaml
# opam file:
opam-version: "2.0"
maintainer: "matej.kosik@inria.fr"
homepage: "https://github.com/coq-contribs/angles"
license: "Proprietary"
build: [make "-j%{jobs}%"]
install: [make "install"]
remove: ["rm" "-R" "%{lib}%/coq/user-contrib/Angles"]
depends: [
"ocaml"
"coq" {>= "8.5" & < "8.6~"}
]
tags: [ "keyword:pcoq" "keyword:geometry" "keyword:plane geometry" "keyword:oriented angles" "category:Mathematics/Geometry/General" "date:2002-01-15" ]
authors: [ "Frédérique Guilhot <Frederique.Guilhot@sophia.inria.fr>" ]
bug-reports: "https://github.com/coq-contribs/angles/issues"
dev-repo: "git+https://github.com/coq-contribs/angles.git"
synopsis: "Formalization of the oriented angles theory"
description: """
The basis of the contribution is a formalization of the
theory of oriented angles of non-zero vectors. Then, we prove some
classical plane geometry theorems: the theorem which gives a necessary
and sufficient condition so that four points are cocyclic, the one
which shows that the reflected points with respect to the sides of a
triangle orthocenter are on its circumscribed circle, the Simson's
theorem and the Napoleon's theorem. The reader can refer to the
associated research report (http://www-sop.inria.fr/lemme/FGRR.ps) and
the README file of the contribution."""
flags: light-uninstall
url {
src: "https://github.com/coq-contribs/angles/archive/v8.5.0.tar.gz"
checksum: "md5=b1baa89405d3b97124934377ba7fb2f7"
}
</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-angles.8.5.0 coq.8.8.1</code></dd>
<dt>Return code</dt>
<dd>5120</dd>
<dt>Output</dt>
<dd><pre>[NOTE] Package coq is already installed (current version is 8.8.1).
The following dependencies couldn't be met:
- coq-angles -> coq < 8.6~ -> ocaml < 4.06.0
base of this switch (use `--unlock-base' to force)
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-angles.8.5.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": "ad608d1b7d24728184ebb1ec3bf2a66d",
"timestamp": "",
"source": "github",
"line_count": 171,
"max_line_length": 212,
"avg_line_length": 43.16959064327485,
"alnum_prop": 0.5582497968030344,
"repo_name": "coq-bench/coq-bench.github.io",
"id": "9b2f794c5b47b1fc0884c2b1ce610f052cc004b4",
"size": "7409",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "clean/Linux-x86_64-4.08.1-2.0.5/released/8.8.1/angles/8.5.0.html",
"mode": "33188",
"license": "mit",
"language": [],
"symlink_target": ""
} |
package samples
//go:generate go-bindata -o samples.go -pkg samples source
| {
"content_hash": "01a8541e9164bf779a903f1e6fd2d449",
"timestamp": "",
"source": "github",
"line_count": 3,
"max_line_length": 58,
"avg_line_length": 25.333333333333332,
"alnum_prop": 0.7763157894736842,
"repo_name": "wy-z/tspec",
"id": "926644f5a9762925aa77626507696c1ec8e5ee81",
"size": "76",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "samples/source.go",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Go",
"bytes": "19738"
}
],
"symlink_target": ""
} |
using System.Web.Mvc;
using System.Web.Routing;
using Nop.Web.Framework.Mvc.Routes;
namespace Nop.Plugin.Payments.Simplify
{
public partial class RouteProvider : IRouteProvider
{
public void RegisterRoutes(RouteCollection routes)
{
//HostedPaymentRedirect - redirect to hosted payment form
routes.MapRoute("Plugin.Payments.Simplify.HostedPaymentRedirect",
"Plugins/PaymentSimplify/HostedPaymentRedirect",
new { controller = "Simplify", action = "HostedPaymentRedirect" },
new[] { "Nop.Plugin.Payments.Simplify.Controllers" }
);
//PostHostedPaymentHandler - return url of hosted payment
routes.MapRoute("Plugin.Payments.Simplify.PostHostedPaymentHandler",
"Plugins/PaymentSimplify/PostHostedPaymentHandler",
new { controller = "Simplify", action = "PostHostedPaymentHandler" },
new[] { "Nop.Plugin.Payments.Simplify.Controllers" }
);
}
public int Priority
{
get
{
return 0;
}
}
}
}
| {
"content_hash": "26461595155fb2b596adc248958aa1f2",
"timestamp": "",
"source": "github",
"line_count": 34,
"max_line_length": 86,
"avg_line_length": 34.44117647058823,
"alnum_prop": 0.5952177625960717,
"repo_name": "simplifycom/simplify-nopcommerce-module",
"id": "3f4cc659633eeed512ea8a3505ea8af0ae23aa81",
"size": "1173",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "Nop.Plugin.Payments.Simplify/RouteProvider.cs",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "C#",
"bytes": "78898"
}
],
"symlink_target": ""
} |
use super::RuntimeContext;
use crate::{
beam::disp_result::DispatchResult,
defs::Arity,
emulator::{process::Process, vm::VM},
fail::{self, RtResult},
term::{boxed, *},
};
fn module() -> &'static str {
"runtime_ctx.call_closure: "
}
/// The `closure` is a callable closure with some frozen variables made with
/// `fun() -> code end`.
pub fn apply(
vm: &mut VM,
ctx: &mut RuntimeContext,
_curr_p: &mut Process,
closure: *mut boxed::Closure,
args: &[Term],
) -> RtResult<DispatchResult> {
let args_len = args.len();
let (closure_arity, closure_nfrozen) =
unsafe { ((*closure).mfa.arity as usize, (*closure).nfrozen) };
// The call is performed for passed args + frozen args, so the actual arity
// will be incoming args length + frozen length
let actual_call_arity = closure_nfrozen + args_len;
unsafe {
let frozen = (*closure).get_frozen();
// copy frozen values into registers after the arity
ctx
.registers_slice_mut(args_len, closure_nfrozen)
.copy_from_slice(frozen);
}
ctx.live = actual_call_arity;
println!("{}", ctx);
if actual_call_arity != closure_arity as Arity {
println!(
"{}badarity call_arity={} nfrozen={} args_len={}",
module(),
closure_arity,
closure_nfrozen,
args_len
);
return fail::create::badarity();
}
ctx.cp = ctx.ip;
let dst = unsafe { (*closure).dst.clone() };
// For dst, extract the code pointer, or update it
// TODO: Verify code pointer module version, and possibly invalidate it.
// OR TODO: subscribe from all exports to the module and get invalidation notifications
ctx.ip = match dst {
Some(p) => p.ptr,
None => unsafe {
let cs = vm.get_code_server_p();
(*closure).update_location(&mut (*cs))?
},
};
Ok(DispatchResult::Normal)
}
| {
"content_hash": "80677f97bd8f1dd6acffec107c499642",
"timestamp": "",
"source": "github",
"line_count": 67,
"max_line_length": 89,
"avg_line_length": 27.208955223880597,
"alnum_prop": 0.6330224904004388,
"repo_name": "kvakvs/ErlangRT",
"id": "c3cfdacf526b23e09279103c501896ce0adea079",
"size": "1823",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "lib-erlangrt/src/emulator/runtime_ctx/call_closure.rs",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Erlang",
"bytes": "36433"
},
{
"name": "Makefile",
"bytes": "2675"
},
{
"name": "Python",
"bytes": "15022"
},
{
"name": "Rust",
"bytes": "485644"
}
],
"symlink_target": ""
} |
<HTML>
<HEAD>
<TITLE>
EMBOSS: textget
</TITLE>
</HEAD>
<BODY BGCOLOR="#FFFFFF" text="#000000">
<table align=center border=0 cellspacing=0 cellpadding=0>
<tr><td valign=top>
<A HREF="/" ONMOUSEOVER="self.status='Go to the EMBOSS home page';return true"><img border=0 src="/images/emboss_icon.jpg" alt="" width=150 height=48></a>
</td>
<td align=left valign=middle>
<b><font size="+6">
textget
</font></b>
</td></tr>
</table>
<br>
<p>
<H2>
Wiki
</H2>
The master copies of EMBOSS documentation are available
at <a href="http://emboss.open-bio.org/wiki/Appdocs">
http://emboss.open-bio.org/wiki/Appdocs</a>
on the EMBOSS Wiki.
<p>
Please help by correcting and extending the Wiki pages.
<H2>
Function
</H2>
Get text data entries
<!--
DON'T WRITE ANYTHING HERE.
IT IS DONE FOR YOU.
-->
<H2>
Description
</H2>
<b>textget</b> reads text data, usually from a named database, and
writes a text file containing the original text of the entry or
entries.
<H2>
Usage
</H2>
<!--
Example usage, as run from the command-line.
Many examples illustrating different behaviours is good.
-->
Here is a sample session with <b>textget</b>
<p>
<p>
<table width="90%"><tr><td bgcolor="#CCFFFF"><pre>
% <b>textget "srs:unilib:99" </b>
Get text data entries
Text output file [outfile.text]: <b></b>
</pre></td></tr></table><p>
<p>
<a href="#input.1">Go to the input files for this example</a><br><a href="#output.1">Go to the output files for this example</a><p><p>
<H2>
Command line arguments
</H2>
<table CELLSPACING=0 CELLPADDING=3 BGCOLOR="#f5f5ff" ><tr><td>
<pre>
Get text data entries
Version: EMBOSS:6.6.0.0
Standard (Mandatory) qualifiers:
[-text] text Text filename and optional format, or
reference (input query)
[-outfile] outtext (no help text) outtext value
Additional (Optional) qualifiers: (none)
Advanced (Unprompted) qualifiers: (none)
Associated qualifiers:
"-text" associated qualifiers
-iformat1 string Input text format
-iquery1 string Input query fields or ID list
-ioffset1 integer Input start position offset
-idbname1 string User-provided database name
"-outfile" associated qualifiers
-odirectory2 string Output directory
-oformat2 string Text output format
General qualifiers:
-auto boolean Turn off prompts
-stdout boolean Write first file to standard output
-filter boolean Read first file from standard input, write
first file to standard output
-options boolean Prompt for standard and additional values
-debug boolean Write debug output to program.dbg
-verbose boolean Report some/full command line options
-help boolean Report command line options and exit. More
information on associated and general
qualifiers can be found with -help -verbose
-warning boolean Report warnings
-error boolean Report errors
-fatal boolean Report fatal errors
-die boolean Report dying program messages
-version boolean Report version number and exit
</pre>
</td></tr></table>
<P>
<table border cellspacing=0 cellpadding=3 bgcolor="#ccccff">
<tr bgcolor="#FFFFCC">
<th align="left">Qualifier</th>
<th align="left">Type</th>
<th align="left">Description</th>
<th align="left">Allowed values</th>
<th align="left">Default</th>
</tr>
<tr bgcolor="#FFFFCC">
<th align="left" colspan=5>Standard (Mandatory) qualifiers</th>
</tr>
<tr bgcolor="#FFFFCC">
<td>[-text]<br>(Parameter 1)</td>
<td>text</td>
<td>Text filename and optional format, or reference (input query)</td>
<td>Text entries</td>
<td> </td>
</tr>
<tr bgcolor="#FFFFCC">
<td>[-outfile]<br>(Parameter 2)</td>
<td>outtext</td>
<td>(no help text) outtext value</td>
<td>Text entries</td>
<td> </td>
</tr>
<tr bgcolor="#FFFFCC">
<th align="left" colspan=5>Additional (Optional) qualifiers</th>
</tr>
<tr>
<td colspan=5>(none)</td>
</tr>
<tr bgcolor="#FFFFCC">
<th align="left" colspan=5>Advanced (Unprompted) qualifiers</th>
</tr>
<tr>
<td colspan=5>(none)</td>
</tr>
<tr bgcolor="#FFFFCC">
<th align="left" colspan=5>Associated qualifiers</th>
</tr>
<tr bgcolor="#FFFFCC">
<td align="left" colspan=5>"-text" associated text qualifiers
</td>
</tr>
<tr bgcolor="#FFFFCC">
<td> -iformat1<br>-iformat_text</td>
<td>string</td>
<td>Input text format</td>
<td>Any string</td>
<td> </td>
</tr>
<tr bgcolor="#FFFFCC">
<td> -iquery1<br>-iquery_text</td>
<td>string</td>
<td>Input query fields or ID list</td>
<td>Any string</td>
<td> </td>
</tr>
<tr bgcolor="#FFFFCC">
<td> -ioffset1<br>-ioffset_text</td>
<td>integer</td>
<td>Input start position offset</td>
<td>Any integer value</td>
<td>0</td>
</tr>
<tr bgcolor="#FFFFCC">
<td> -idbname1<br>-idbname_text</td>
<td>string</td>
<td>User-provided database name</td>
<td>Any string</td>
<td> </td>
</tr>
<tr bgcolor="#FFFFCC">
<td align="left" colspan=5>"-outfile" associated outtext qualifiers
</td>
</tr>
<tr bgcolor="#FFFFCC">
<td> -odirectory2<br>-odirectory_outfile</td>
<td>string</td>
<td>Output directory</td>
<td>Any string</td>
<td> </td>
</tr>
<tr bgcolor="#FFFFCC">
<td> -oformat2<br>-oformat_outfile</td>
<td>string</td>
<td>Text output format</td>
<td>Any string</td>
<td> </td>
</tr>
<tr bgcolor="#FFFFCC">
<th align="left" colspan=5>General qualifiers</th>
</tr>
<tr bgcolor="#FFFFCC">
<td> -auto</td>
<td>boolean</td>
<td>Turn off prompts</td>
<td>Boolean value Yes/No</td>
<td>N</td>
</tr>
<tr bgcolor="#FFFFCC">
<td> -stdout</td>
<td>boolean</td>
<td>Write first file to standard output</td>
<td>Boolean value Yes/No</td>
<td>N</td>
</tr>
<tr bgcolor="#FFFFCC">
<td> -filter</td>
<td>boolean</td>
<td>Read first file from standard input, write first file to standard output</td>
<td>Boolean value Yes/No</td>
<td>N</td>
</tr>
<tr bgcolor="#FFFFCC">
<td> -options</td>
<td>boolean</td>
<td>Prompt for standard and additional values</td>
<td>Boolean value Yes/No</td>
<td>N</td>
</tr>
<tr bgcolor="#FFFFCC">
<td> -debug</td>
<td>boolean</td>
<td>Write debug output to program.dbg</td>
<td>Boolean value Yes/No</td>
<td>N</td>
</tr>
<tr bgcolor="#FFFFCC">
<td> -verbose</td>
<td>boolean</td>
<td>Report some/full command line options</td>
<td>Boolean value Yes/No</td>
<td>Y</td>
</tr>
<tr bgcolor="#FFFFCC">
<td> -help</td>
<td>boolean</td>
<td>Report command line options and exit. More information on associated and general qualifiers can be found with -help -verbose</td>
<td>Boolean value Yes/No</td>
<td>N</td>
</tr>
<tr bgcolor="#FFFFCC">
<td> -warning</td>
<td>boolean</td>
<td>Report warnings</td>
<td>Boolean value Yes/No</td>
<td>Y</td>
</tr>
<tr bgcolor="#FFFFCC">
<td> -error</td>
<td>boolean</td>
<td>Report errors</td>
<td>Boolean value Yes/No</td>
<td>Y</td>
</tr>
<tr bgcolor="#FFFFCC">
<td> -fatal</td>
<td>boolean</td>
<td>Report fatal errors</td>
<td>Boolean value Yes/No</td>
<td>Y</td>
</tr>
<tr bgcolor="#FFFFCC">
<td> -die</td>
<td>boolean</td>
<td>Report dying program messages</td>
<td>Boolean value Yes/No</td>
<td>Y</td>
</tr>
<tr bgcolor="#FFFFCC">
<td> -version</td>
<td>boolean</td>
<td>Report version number and exit</td>
<td>Boolean value Yes/No</td>
<td>N</td>
</tr>
</table>
<!--
DON'T WRITE ANYTHING HERE.
IT IS DONE FOR YOU.
-->
<H2>
Input file format
</H2>
<p>
The input is a standard EMBOSS text query.
<p>
The major text sources defined as standard in EMBOSS installations are
non-standard types on the srs server and databases with a "text" query
in the Data Resource Catalogue database DRCAT.
<p>
Data can also be read from text output in any supported text format
written by an EMBOSS or third-party application. The text format is
needed to identify the start and end of a single "entry" within a
larger text file.
<p>
The input format can be specified by using the command-line qualifier
<tt>-format xxx</tt>, where 'xxx' is replaced by the name of the
required format. The available format names are: text, html, xml (uniprotxml),
obo, embl (swissprot)
<p>
See:
<A href="http://emboss.sf.net/docs/themes/TextFormats.html">
http://emboss.sf.net/docs/themes/TextFormats.html</A>
for further information on text formats.
<p>
<p>
<a name="input.1"></a>
<h3>Input files for usage example </h3>
<p><h3>Database entry: "srs:unilib:99"</h3>
<table width="90%"><tr><td bgcolor="#FFCCFF">
<pre>
> 99
CGAP Lib id: 182
Unigene id: 729
dbEST lib id: 1452
Keyword: lymph node
Keyword: follicular lymphoma
Keyword: non-normalized
Keyword: bulk
Keyword: CGAP
Keyword: EST
Keyword: Stratagene non-normalized
Keyword: unknown developmental stage
Keyword: size fractionated
Keyword: directionally cloned
Keyword: phagemid
Keyword: oligo-dT primed
Keyword: EST
Keyword: CGAP
Lib Name: NCI_CGAP_Lym5
Organism: Homo sapiens
Organ: lymph node
Tissue_type: follicular lymphoma
Lab host: SOLR (Stratagene, kanamycin resistant)
Vector: pBluescript SK-
Vector type: phagemid (ampicillin resistant)
R. Site 1: EcoRI
R. Site 2: XhoI
Description: Cloned unidirectionally. Primer: Oligo dT. Average insert size 1.2 kb. Non-amplified library. ~5' adaptor sequence: 5' GAATTCGGCACGAG 3' ~3' adaptor sequence: 5' CTCGAGTTTTTTTTTTTTTTTTTT 3'
Library treatment: non-normalized
Tissue description: Lymph node, follicular lymphoma, node 2
Tissue supplier: Mark Raffeld, M.D.
Sample type: Bulk
Image legend:
Producer: Stratagene, Inc.
Clones generated to date: 2304
Sequences generated to date: 1293
</pre>
</td></tr></table><p>
<H2>
Output file format
</H2>
<p>
The output is a standard text file.
<p>
The results can be output in one of several styles by using the
command-line qualifier <tt>-oformat xxx</tt>, where 'xxx' is replaced by
the name of the required format. The available format names are:
text, html, xml, json and list
<p>
See:
<A href="http://emboss.sf.net/docs/themes/TextFormats.html">
http://emboss.sf.net/docs/themes/TextFormats.html</A>
for further information on text formats.
<p>
<p>
<a name="output.1"></a>
<h3>Output files for usage example </h3>
<p><h3>File: outfile.text</h3>
<table width="90%"><tr><td bgcolor="#CCFFCC">
<pre>
> 99
CGAP Lib id: 182
Unigene id: 729
dbEST lib id: 1452
Keyword: lymph node
Keyword: follicular lymphoma
Keyword: non-normalized
Keyword: bulk
Keyword: CGAP
Keyword: EST
Keyword: Stratagene non-normalized
Keyword: unknown developmental stage
Keyword: size fractionated
Keyword: directionally cloned
Keyword: phagemid
Keyword: oligo-dT primed
Keyword: EST
Keyword: CGAP
Lib Name: NCI_CGAP_Lym5
Organism: Homo sapiens
Organ: lymph node
Tissue_type: follicular lymphoma
Lab host: SOLR (Stratagene, kanamycin resistant)
Vector: pBluescript SK-
Vector type: phagemid (ampicillin resistant)
R. Site 1: EcoRI
R. Site 2: XhoI
Description: Cloned unidirectionally. Primer: Oligo dT. Average insert size 1.2 kb. Non-amplified library. ~5' adaptor sequence: 5' GAATTCGGCACGAG 3' ~3' adaptor sequence: 5' CTCGAGTTTTTTTTTTTTTTTTTT 3'
Library treatment: non-normalized
Tissue description: Lymph node, follicular lymphoma, node 2
Tissue supplier: Mark Raffeld, M.D.
Sample type: Bulk
Image legend:
Producer: Stratagene, Inc.
Clones generated to date: 2304
Sequences generated to date: 1293
</pre>
</td></tr></table><p>
<H2>
Data files
</H2>
None.
<H2>
Notes
</H2>
<!--
Restrictions.
Interesting behaviour.
Useful things you can do with this program.
-->
None.
<H2>
References
</H2>
<!--
Bibliography for methods used.
<ol>
<li>
</ol>
-->
None.
<H2>
Warnings
</H2>
<!--
Potentially stupid things the program will let you do.
-->
None.
<H2>
Diagnostic Error Messages
</H2>
<!--
Error messages specific to this program, eg:
"FATAL xxx" - means you have not set up the xxx data using program <b>prog</b>.<p>
-->
None.
<H2>
Exit status
</H2>
<!--
Description of the exit status for various error conditions
-->
It always exits with status 0.
<H2>
Known bugs
</H2>
<!--
Bugs noted but not yet fixed.
-->
None.
<!--
<H2>
See also
</H2>
-->
<h2><a name="See also">See also</a></h2>
<table border cellpadding=4 bgcolor="#FFFFF0">
<tr><th>Program name</th>
<th>Description</th></tr>
<tr>
<td><a href="drtext.html">drtext</a></td>
<td>Get data resource entries complete text</td>
</tr>
<tr>
<td><a href="entret.html">entret</a></td>
<td>Retrieve sequence entries from flatfile databases and files</td>
</tr>
<tr>
<td><a href="ontotext.html">ontotext</a></td>
<td>Get ontology term(s) original full text</td>
</tr>
<tr>
<td><a href="textsearch.html">textsearch</a></td>
<td>Search the textual description of sequence(s)</td>
</tr>
<tr>
<td><a href="xmltext.html">xmltext</a></td>
<td>Get XML document original full text</td>
</tr>
</table>
<!--
Add any comments about other associated programs (to prepare
data files?) that seealso doesn't find.
-->
<H2>
Author(s)
</H2>
Peter Rice
<br>
European Bioinformatics Institute, Wellcome Trust Genome Campus, Hinxton, Cambridge CB10 1SD, UK
<p>
Please report all bugs to the EMBOSS bug team (emboss-bug © emboss.open-bio.org) not to the original author.
<H2>
History
</H2>
<!--
Date written and what changes have been made go in this file.
-->
<H2>
Target users
</H2>
<!--
For general users, use this text
-->
This program is intended to be used by everyone and everything, from naive users to embedded scripts.
<H2>
Comments
</H2>
<!--
User/developer/other comments go in this file.
-->
None
</BODY>
</HTML>
| {
"content_hash": "5133ae41b804aa31a37a47649c4c46a4",
"timestamp": "",
"source": "github",
"line_count": 719,
"max_line_length": 203,
"avg_line_length": 19.478442280945757,
"alnum_prop": 0.6666190646197786,
"repo_name": "lauringlab/CodonShuffle",
"id": "aa7f580b86c852171cee529151b2d324ae002a84",
"size": "14005",
"binary": false,
"copies": "3",
"ref": "refs/heads/master",
"path": "lib/EMBOSS-6.6.0/doc/programs/html/textget.html",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Assembly",
"bytes": "26005"
},
{
"name": "Batchfile",
"bytes": "410"
},
{
"name": "C",
"bytes": "32248936"
},
{
"name": "C++",
"bytes": "666976"
},
{
"name": "CSS",
"bytes": "24950"
},
{
"name": "DIGITAL Command Language",
"bytes": "1919"
},
{
"name": "Eiffel",
"bytes": "9228"
},
{
"name": "FORTRAN",
"bytes": "7327"
},
{
"name": "Groff",
"bytes": "385461"
},
{
"name": "HTML",
"bytes": "21580322"
},
{
"name": "Java",
"bytes": "1268950"
},
{
"name": "JavaScript",
"bytes": "144823"
},
{
"name": "Makefile",
"bytes": "662688"
},
{
"name": "Max",
"bytes": "224"
},
{
"name": "Module Management System",
"bytes": "3943"
},
{
"name": "Parrot",
"bytes": "5376"
},
{
"name": "Perl",
"bytes": "652946"
},
{
"name": "Perl6",
"bytes": "4794"
},
{
"name": "PostScript",
"bytes": "606530"
},
{
"name": "Prolog",
"bytes": "1731"
},
{
"name": "Python",
"bytes": "158248"
},
{
"name": "QMake",
"bytes": "7518"
},
{
"name": "R",
"bytes": "7233"
},
{
"name": "Shell",
"bytes": "709299"
},
{
"name": "SourcePawn",
"bytes": "10316"
},
{
"name": "Standard ML",
"bytes": "1327"
},
{
"name": "TeX",
"bytes": "741088"
},
{
"name": "XS",
"bytes": "12050"
}
],
"symlink_target": ""
} |
import unittest, random, sys, time
sys.path.extend(['.','..','py'])
import h2o, h2o_cmd, h2o_hosts, h2o_browse as h2b, h2o_import as h2i, h2o_gbm, h2o_jobs as h2j, h2o_import
DO_PLOT = True
print "This will also test set_column_names into GBM, with changing col names per test"
def write_syn_dataset(csvPathname, rowCount, colCount, SEED):
r1 = random.Random(SEED)
dsf = open(csvPathname, "w+")
for i in range(rowCount):
rowData = []
for j in range(colCount):
ri = r1.randint(0,1)
rowData.append(ri)
ri = r1.randint(0,1)
rowData.append(ri)
rowDataCsv = ",".join(map(str,rowData))
dsf.write(rowDataCsv + "\n")
dsf.close()
def write_syn_header(hdrPathname, rowCount, colCount, prefix):
dsf = open(hdrPathname, "w+")
rowData = [prefix + "_" + str(j) for j in range(colCount)]
# add 1 for the output
rowData.append(prefix + '_response')
dsf.write(",".join(rowData) + "\n")
dsf.close()
class Basic(unittest.TestCase):
def tearDown(self):
h2o.check_sandbox_for_errors()
@classmethod
def setUpClass(cls):
global SEED, localhost
SEED = h2o.setup_random_seed()
localhost = h2o.decide_if_localhost()
if (localhost):
h2o.build_cloud(1,java_heap_GB=10, enable_benchmark_log=True)
else:
h2o_hosts.build_cloud_with_hosts(enable_benchmark_log=True)
@classmethod
def tearDownClass(cls):
### time.sleep(3600)
h2o.tear_down_cloud()
def test_GBM_many_cols(self):
h2o.beta_features = True
SYNDATASETS_DIR = h2o.make_syn_dir()
if localhost:
tryList = [
(10000, 100, 'cA', 300),
]
else:
tryList = [
# (10000, 10, 'cB', 300),
# (10000, 50, 'cC', 300),
(10000, 100, 'cD', 300),
(10000, 200, 'cE', 300),
(10000, 300, 'cF', 300),
(10000, 400, 'cG', 300),
(10000, 500, 'cH', 300),
(10000, 1000, 'cI', 300),
]
for (rowCount, colCount, hex_key, timeoutSecs) in tryList:
SEEDPERFILE = random.randint(0, sys.maxint)
# csvFilename = 'syn_' + str(SEEDPERFILE) + "_" + str(rowCount) + 'x' + str(colCount) + '.csv'
csvFilename = 'syn_' + "binary" + "_" + str(rowCount) + 'x' + str(colCount) + '.csv'
hdrFilename = 'hdr_' + "binary" + "_" + str(rowCount) + 'x' + str(colCount) + '.csv'
csvPathname = SYNDATASETS_DIR + '/' + csvFilename
hdrPathname = SYNDATASETS_DIR + '/' + hdrFilename
print "Creating random", csvPathname
write_syn_dataset(csvPathname, rowCount, colCount, SEEDPERFILE)
# PARSE train****************************************
start = time.time()
xList = []
eList = []
fList = []
modelKey = 'GBMModelKey'
# Parse (train)****************************************
parseTrainResult = h2i.import_parse(bucket=None, path=csvPathname, schema='put',
hex_key=hex_key, timeoutSecs=timeoutSecs,
doSummary=False)
# hack
elapsed = time.time() - start
print "train parse end on ", csvPathname, 'took', elapsed, 'seconds',\
"%d pct. of timeout" % ((elapsed*100)/timeoutSecs)
print "train parse result:", parseTrainResult['destination_key']
# Logging to a benchmark file
algo = "Parse"
l = '{:d} jvms, {:d}GB heap, {:s} {:s} {:6.2f} secs'.format(
len(h2o.nodes), h2o.nodes[0].java_heap_GB, algo, csvFilename, elapsed)
print l
h2o.cloudPerfH2O.message(l)
inspect = h2o_cmd.runInspect(key=parseTrainResult['destination_key'])
print "\n" + csvPathname, \
" numRows:", "{:,}".format(inspect['numRows']), \
" numCols:", "{:,}".format(inspect['numCols'])
numRows = inspect['numRows']
numCols = inspect['numCols']
### h2o_cmd.runSummary(key=parsTraineResult['destination_key'])
# GBM(train iterate)****************************************
ntrees = 5
prefixList = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H']
# for max_depth in [5,10,20,40]:
for max_depth in [5, 10, 20]:
# PARSE a new header****************************************
print "Creating new header", hdrPathname
prefix = prefixList.pop(0)
write_syn_header(hdrPathname, rowCount, colCount, prefix)
# upload and parse the header to a hex
hdr_hex_key = prefix + "_hdr.hex"
parseHdrResult = h2i.import_parse(bucket=None, path=hdrPathname, schema='put',
header=1, # REQUIRED! otherwise will interpret as enums
hex_key=hdr_hex_key, timeoutSecs=timeoutSecs, doSummary=False)
# Set Column Names (before autoframe is created)
h2o.nodes[0].set_column_names(source=hex_key, copy_from=hdr_hex_key)
# GBM
print "response col name is changing each iteration: parsing a new header"
params = {
'learn_rate': .2,
'nbins': 1024,
'ntrees': ntrees,
'max_depth': max_depth,
'min_rows': 10,
'response': prefix + "_response",
'ignored_cols_by_name': None,
}
print "Using these parameters for GBM: ", params
kwargs = params.copy()
trainStart = time.time()
gbmTrainResult = h2o_cmd.runGBM(parseResult=parseTrainResult,
timeoutSecs=timeoutSecs, destination_key=modelKey, **kwargs)
trainElapsed = time.time() - trainStart
print "GBM training completed in", trainElapsed, "seconds. On dataset: ", csvPathname
# Logging to a benchmark file
algo = "GBM " + " ntrees=" + str(ntrees) + " max_depth=" + str(max_depth)
l = '{:d} jvms, {:d}GB heap, {:s} {:s} {:6.2f} secs'.format(
len(h2o.nodes), h2o.nodes[0].java_heap_GB, algo, csvFilename, trainElapsed)
print l
h2o.cloudPerfH2O.message(l)
gbmTrainView = h2o_cmd.runGBMView(model_key=modelKey)
# errrs from end of list? is that the last tree?
errsLast = gbmTrainView['gbm_model']['errs'][-1]
print "GBM 'errsLast'", errsLast
cm = gbmTrainView['gbm_model']['cms'][-1]['_arr'] # use the last one
pctWrongTrain = h2o_gbm.pp_cm_summary(cm);
print "\nTrain\n==========\n"
print h2o_gbm.pp_cm(cm)
# xList.append(ntrees)
xList.append(max_depth)
eList.append(pctWrongTrain)
fList.append(trainElapsed)
# works if you delete the autoframe
### h2o_import.delete_keys_at_all_nodes(pattern='autoframe')
# just plot the last one
if DO_PLOT:
xLabel = 'max_depth'
eLabel = 'pctWrong'
fLabel = 'trainElapsed'
eListTitle = ""
fListTitle = ""
h2o_gbm.plotLists(xList, xLabel, eListTitle, eList, eLabel, fListTitle, fList, fLabel)
if __name__ == '__main__':
h2o.unit_main()
| {
"content_hash": "5bdde0316cb097a31abbc76ccceaf459",
"timestamp": "",
"source": "github",
"line_count": 197,
"max_line_length": 106,
"avg_line_length": 39.27918781725889,
"alnum_prop": 0.5067200827087103,
"repo_name": "woobe/h2o",
"id": "67fbad3e1543d7063d6f276d1536a23c57580ca6",
"size": "7738",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "py/testdir_single_jvm/test_GBM_many_cols.py",
"mode": "33188",
"license": "apache-2.0",
"language": [],
"symlink_target": ""
} |
"""
Test cases for L{twisted.words.protocols.msn}.
"""
# System imports
import StringIO
# Twisted imports
# t.w.p.msn requires an HTTP client
try:
# So try to get one - do it directly instead of catching an ImportError
# from t.w.p.msn so that other problems which cause that module to fail
# to import don't cause the tests to be skipped.
from twisted.web import client
except ImportError:
# If there isn't one, we're going to skip all the tests.
msn = None
else:
# Otherwise importing it should work, so do it.
from twisted.words.protocols import msn
from twisted.python.hashlib import md5
from twisted.protocols import loopback
from twisted.internet.defer import Deferred
from twisted.trial import unittest
from twisted.test.proto_helpers import StringTransport, StringIOWithoutClosing
def printError(f):
print f
class PassportTests(unittest.TestCase):
def setUp(self):
self.result = []
self.deferred = Deferred()
self.deferred.addCallback(lambda r: self.result.append(r))
self.deferred.addErrback(printError)
def test_nexus(self):
"""
When L{msn.PassportNexus} receives enough information to identify the
address of the login server, it fires the L{Deferred} passed to its
initializer with that address.
"""
protocol = msn.PassportNexus(self.deferred, 'https://foobar.com/somepage.quux')
headers = {
'Content-Length' : '0',
'Content-Type' : 'text/html',
'PassportURLs' : 'DARealm=Passport.Net,DALogin=login.myserver.com/,DAReg=reg.myserver.com'
}
transport = StringTransport()
protocol.makeConnection(transport)
protocol.dataReceived('HTTP/1.0 200 OK\r\n')
for (h, v) in headers.items():
protocol.dataReceived('%s: %s\r\n' % (h,v))
protocol.dataReceived('\r\n')
self.assertEqual(self.result[0], "https://login.myserver.com/")
def _doLoginTest(self, response, headers):
protocol = msn.PassportLogin(self.deferred,'foo@foo.com','testpass','https://foo.com/', 'a')
protocol.makeConnection(StringTransport())
protocol.dataReceived(response)
for (h,v) in headers.items(): protocol.dataReceived('%s: %s\r\n' % (h,v))
protocol.dataReceived('\r\n')
def testPassportLoginSuccess(self):
headers = {
'Content-Length' : '0',
'Content-Type' : 'text/html',
'Authentication-Info' : "Passport1.4 da-status=success,tname=MSPAuth," +
"tname=MSPProf,tname=MSPSec,from-PP='somekey'," +
"ru=http://messenger.msn.com"
}
self._doLoginTest('HTTP/1.1 200 OK\r\n', headers)
self.failUnless(self.result[0] == (msn.LOGIN_SUCCESS, 'somekey'))
def testPassportLoginFailure(self):
headers = {
'Content-Type' : 'text/html',
'WWW-Authenticate' : 'Passport1.4 da-status=failed,' +
'srealm=Passport.NET,ts=-3,prompt,cburl=http://host.com,' +
'cbtxt=the%20error%20message'
}
self._doLoginTest('HTTP/1.1 401 Unauthorized\r\n', headers)
self.failUnless(self.result[0] == (msn.LOGIN_FAILURE, 'the error message'))
def testPassportLoginRedirect(self):
headers = {
'Content-Type' : 'text/html',
'Authentication-Info' : 'Passport1.4 da-status=redir',
'Location' : 'https://newlogin.host.com/'
}
self._doLoginTest('HTTP/1.1 302 Found\r\n', headers)
self.failUnless(self.result[0] == (msn.LOGIN_REDIRECT, 'https://newlogin.host.com/', 'a'))
if msn is not None:
class DummySwitchboardClient(msn.SwitchboardClient):
def userTyping(self, message):
self.state = 'TYPING'
def gotSendRequest(self, fileName, fileSize, cookie, message):
if fileName == 'foobar.ext' and fileSize == 31337 and cookie == 1234: self.state = 'INVITATION'
class DummyNotificationClient(msn.NotificationClient):
def loggedIn(self, userHandle, screenName, verified):
if userHandle == 'foo@bar.com' and screenName == 'Test Screen Name' and verified:
self.state = 'LOGIN'
def gotProfile(self, message):
self.state = 'PROFILE'
def gotContactStatus(self, code, userHandle, screenName):
if code == msn.STATUS_AWAY and userHandle == "foo@bar.com" and screenName == "Test Screen Name":
self.state = 'INITSTATUS'
def contactStatusChanged(self, code, userHandle, screenName):
if code == msn.STATUS_LUNCH and userHandle == "foo@bar.com" and screenName == "Test Name":
self.state = 'NEWSTATUS'
def contactOffline(self, userHandle):
if userHandle == "foo@bar.com": self.state = 'OFFLINE'
def statusChanged(self, code):
if code == msn.STATUS_HIDDEN: self.state = 'MYSTATUS'
def listSynchronized(self, *args):
self.state = 'GOTLIST'
def gotPhoneNumber(self, listVersion, userHandle, phoneType, number):
msn.NotificationClient.gotPhoneNumber(self, listVersion, userHandle, phoneType, number)
self.state = 'GOTPHONE'
def userRemovedMe(self, userHandle, listVersion):
msn.NotificationClient.userRemovedMe(self, userHandle, listVersion)
c = self.factory.contacts.getContact(userHandle)
if not c and self.factory.contacts.version == listVersion: self.state = 'USERREMOVEDME'
def userAddedMe(self, userHandle, screenName, listVersion):
msn.NotificationClient.userAddedMe(self, userHandle, screenName, listVersion)
c = self.factory.contacts.getContact(userHandle)
if c and (c.lists | msn.REVERSE_LIST) and (self.factory.contacts.version == listVersion) and \
(screenName == 'Screen Name'):
self.state = 'USERADDEDME'
def gotSwitchboardInvitation(self, sessionID, host, port, key, userHandle, screenName):
if sessionID == 1234 and \
host == '192.168.1.1' and \
port == 1863 and \
key == '123.456' and \
userHandle == 'foo@foo.com' and \
screenName == 'Screen Name':
self.state = 'SBINVITED'
class DispatchTests(unittest.TestCase):
"""
Tests for L{DispatchClient}.
"""
def _versionTest(self, serverVersionResponse):
"""
Test L{DispatchClient} version negotiation.
"""
client = msn.DispatchClient()
client.userHandle = "foo"
transport = StringTransport()
client.makeConnection(transport)
self.assertEqual(
transport.value(), "VER 1 MSNP8 CVR0\r\n")
transport.clear()
client.dataReceived(serverVersionResponse)
self.assertEqual(
transport.value(),
"CVR 2 0x0409 win 4.10 i386 MSNMSGR 5.0.0544 MSMSGS foo\r\n")
def test_version(self):
"""
L{DispatchClient.connectionMade} greets the server with a I{VER}
(version) message and then L{NotificationClient.dataReceived}
handles the server's I{VER} response by sending a I{CVR} (client
version) message.
"""
self._versionTest("VER 1 MSNP8 CVR0\r\n")
def test_versionWithoutCVR0(self):
"""
If the server responds to a I{VER} command without including the
I{CVR0} protocol, L{DispatchClient} behaves in the same way as if
that protocol were included.
Starting in August 2008, CVR0 disappeared from the I{VER} response.
"""
self._versionTest("VER 1 MSNP8\r\n")
class NotificationTests(unittest.TestCase):
""" testing the various events in NotificationClient """
def setUp(self):
self.client = DummyNotificationClient()
self.client.factory = msn.NotificationFactory()
self.client.state = 'START'
def tearDown(self):
self.client = None
def _versionTest(self, serverVersionResponse):
"""
Test L{NotificationClient} version negotiation.
"""
self.client.factory.userHandle = "foo"
transport = StringTransport()
self.client.makeConnection(transport)
self.assertEqual(
transport.value(), "VER 1 MSNP8 CVR0\r\n")
transport.clear()
self.client.dataReceived(serverVersionResponse)
self.assertEqual(
transport.value(),
"CVR 2 0x0409 win 4.10 i386 MSNMSGR 5.0.0544 MSMSGS foo\r\n")
def test_version(self):
"""
L{NotificationClient.connectionMade} greets the server with a I{VER}
(version) message and then L{NotificationClient.dataReceived}
handles the server's I{VER} response by sending a I{CVR} (client
version) message.
"""
self._versionTest("VER 1 MSNP8 CVR0\r\n")
def test_versionWithoutCVR0(self):
"""
If the server responds to a I{VER} command without including the
I{CVR0} protocol, L{NotificationClient} behaves in the same way as
if that protocol were included.
Starting in August 2008, CVR0 disappeared from the I{VER} response.
"""
self._versionTest("VER 1 MSNP8\r\n")
def test_challenge(self):
"""
L{NotificationClient} responds to a I{CHL} message by sending a I{QRY}
back which included a hash based on the parameters of the I{CHL}.
"""
transport = StringTransport()
self.client.makeConnection(transport)
transport.clear()
challenge = "15570131571988941333"
self.client.dataReceived('CHL 0 ' + challenge + '\r\n')
# md5 of the challenge and a magic string defined by the protocol
response = "8f2f5a91b72102cd28355e9fc9000d6e"
# Sanity check - the response is what the comment above says it is.
self.assertEqual(
response, md5(challenge + "Q1P7W2E4J9R8U3S5").hexdigest())
self.assertEqual(
transport.value(),
# 2 is the next transaction identifier. 32 is the length of the
# response.
"QRY 2 msmsgs@msnmsgr.com 32\r\n" + response)
def testLogin(self):
self.client.lineReceived('USR 1 OK foo@bar.com Test%20Screen%20Name 1 0')
self.failUnless((self.client.state == 'LOGIN'), msg='Failed to detect successful login')
def test_loginWithoutSSLFailure(self):
"""
L{NotificationClient.loginFailure} is called if the necessary SSL APIs
are unavailable.
"""
self.patch(msn, 'ClientContextFactory', None)
success = []
self.client.loggedIn = lambda *args: success.append(args)
failure = []
self.client.loginFailure = failure.append
self.client.lineReceived('USR 6 TWN S opaque-string-goes-here')
self.assertEqual(success, [])
self.assertEqual(
failure,
["Exception while authenticating: "
"Connecting to the Passport server requires SSL, but SSL is "
"unavailable."])
def testProfile(self):
m = 'MSG Hotmail Hotmail 353\r\nMIME-Version: 1.0\r\nContent-Type: text/x-msmsgsprofile; charset=UTF-8\r\n'
m += 'LoginTime: 1016941010\r\nEmailEnabled: 1\r\nMemberIdHigh: 40000\r\nMemberIdLow: -600000000\r\nlang_preference: 1033\r\n'
m += 'preferredEmail: foo@bar.com\r\ncountry: AU\r\nPostalCode: 90210\r\nGender: M\r\nKid: 0\r\nAge:\r\nsid: 400\r\n'
m += 'kv: 2\r\nMSPAuth: 2CACCBCCADMoV8ORoz64BVwmjtksIg!kmR!Rj5tBBqEaW9hc4YnPHSOQ$$\r\n\r\n'
map(self.client.lineReceived, m.split('\r\n')[:-1])
self.failUnless((self.client.state == 'PROFILE'), msg='Failed to detect initial profile')
def testStatus(self):
t = [('ILN 1 AWY foo@bar.com Test%20Screen%20Name 0', 'INITSTATUS', 'Failed to detect initial status report'),
('NLN LUN foo@bar.com Test%20Name 0', 'NEWSTATUS', 'Failed to detect contact status change'),
('FLN foo@bar.com', 'OFFLINE', 'Failed to detect contact signing off'),
('CHG 1 HDN 0', 'MYSTATUS', 'Failed to detect my status changing')]
for i in t:
self.client.lineReceived(i[0])
self.failUnless((self.client.state == i[1]), msg=i[2])
def testListSync(self):
# currently this test does not take into account the fact
# that BPRs sent as part of the SYN reply may not be interpreted
# as such if they are for the last LST -- maybe I should
# factor this in later.
self.client.makeConnection(StringTransport())
msn.NotificationClient.loggedIn(self.client, 'foo@foo.com', 'foobar', 1)
lines = [
"SYN %s 100 1 1" % self.client.currentID,
"GTC A",
"BLP AL",
"LSG 0 Other%20Contacts 0",
"LST userHandle@email.com Some%20Name 11 0"
]
map(self.client.lineReceived, lines)
contacts = self.client.factory.contacts
contact = contacts.getContact('userHandle@email.com')
self.failUnless(contacts.version == 100, "Invalid contact list version")
self.failUnless(contact.screenName == 'Some Name', "Invalid screen-name for user")
self.failUnless(contacts.groups == {0 : 'Other Contacts'}, "Did not get proper group list")
self.failUnless(contact.groups == [0] and contact.lists == 11, "Invalid contact list/group info")
self.failUnless(self.client.state == 'GOTLIST', "Failed to call list sync handler")
def testAsyncPhoneChange(self):
c = msn.MSNContact(userHandle='userHandle@email.com')
self.client.factory.contacts = msn.MSNContactList()
self.client.factory.contacts.addContact(c)
self.client.makeConnection(StringTransport())
self.client.lineReceived("BPR 101 userHandle@email.com PHH 123%20456")
c = self.client.factory.contacts.getContact('userHandle@email.com')
self.failUnless(self.client.state == 'GOTPHONE', "Did not fire phone change callback")
self.failUnless(c.homePhone == '123 456', "Did not update the contact's phone number")
self.failUnless(self.client.factory.contacts.version == 101, "Did not update list version")
def testLateBPR(self):
"""
This test makes sure that if a BPR response that was meant
to be part of a SYN response (but came after the last LST)
is received, the correct contact is updated and all is well
"""
self.client.makeConnection(StringTransport())
msn.NotificationClient.loggedIn(self.client, 'foo@foo.com', 'foo', 1)
lines = [
"SYN %s 100 1 1" % self.client.currentID,
"GTC A",
"BLP AL",
"LSG 0 Other%20Contacts 0",
"LST userHandle@email.com Some%20Name 11 0",
"BPR PHH 123%20456"
]
map(self.client.lineReceived, lines)
contact = self.client.factory.contacts.getContact('userHandle@email.com')
self.failUnless(contact.homePhone == '123 456', "Did not update contact's phone number")
def testUserRemovedMe(self):
self.client.factory.contacts = msn.MSNContactList()
contact = msn.MSNContact(userHandle='foo@foo.com')
contact.addToList(msn.REVERSE_LIST)
self.client.factory.contacts.addContact(contact)
self.client.lineReceived("REM 0 RL 100 foo@foo.com")
self.failUnless(self.client.state == 'USERREMOVEDME', "Failed to remove user from reverse list")
def testUserAddedMe(self):
self.client.factory.contacts = msn.MSNContactList()
self.client.lineReceived("ADD 0 RL 100 foo@foo.com Screen%20Name")
self.failUnless(self.client.state == 'USERADDEDME', "Failed to add user to reverse lise")
def testAsyncSwitchboardInvitation(self):
self.client.lineReceived("RNG 1234 192.168.1.1:1863 CKI 123.456 foo@foo.com Screen%20Name")
self.failUnless(self.client.state == "SBINVITED")
def testCommandFailed(self):
"""
Ensures that error responses from the server fires an errback with
MSNCommandFailed.
"""
id, d = self.client._createIDMapping()
self.client.lineReceived("201 %s" % id)
d = self.assertFailure(d, msn.MSNCommandFailed)
def assertErrorCode(exception):
self.assertEqual(201, exception.errorCode)
return d.addCallback(assertErrorCode)
class MessageHandlingTests(unittest.TestCase):
""" testing various message handling methods from SwichboardClient """
def setUp(self):
self.client = DummySwitchboardClient()
self.client.state = 'START'
def tearDown(self):
self.client = None
def testClientCapabilitiesCheck(self):
m = msn.MSNMessage()
m.setHeader('Content-Type', 'text/x-clientcaps')
self.assertEqual(self.client.checkMessage(m), 0, 'Failed to detect client capability message')
def testTypingCheck(self):
m = msn.MSNMessage()
m.setHeader('Content-Type', 'text/x-msmsgscontrol')
m.setHeader('TypingUser', 'foo@bar')
self.client.checkMessage(m)
self.failUnless((self.client.state == 'TYPING'), msg='Failed to detect typing notification')
def testFileInvitation(self, lazyClient=False):
m = msn.MSNMessage()
m.setHeader('Content-Type', 'text/x-msmsgsinvite; charset=UTF-8')
m.message += 'Application-Name: File Transfer\r\n'
if not lazyClient:
m.message += 'Application-GUID: {5D3E02AB-6190-11d3-BBBB-00C04F795683}\r\n'
m.message += 'Invitation-Command: Invite\r\n'
m.message += 'Invitation-Cookie: 1234\r\n'
m.message += 'Application-File: foobar.ext\r\n'
m.message += 'Application-FileSize: 31337\r\n\r\n'
self.client.checkMessage(m)
self.failUnless((self.client.state == 'INVITATION'), msg='Failed to detect file transfer invitation')
def testFileInvitationMissingGUID(self):
return self.testFileInvitation(True)
def testFileResponse(self):
d = Deferred()
d.addCallback(self.fileResponse)
self.client.cookies['iCookies'][1234] = (d, None)
m = msn.MSNMessage()
m.setHeader('Content-Type', 'text/x-msmsgsinvite; charset=UTF-8')
m.message += 'Invitation-Command: ACCEPT\r\n'
m.message += 'Invitation-Cookie: 1234\r\n\r\n'
self.client.checkMessage(m)
self.failUnless((self.client.state == 'RESPONSE'), msg='Failed to detect file transfer response')
def testFileInfo(self):
d = Deferred()
d.addCallback(self.fileInfo)
self.client.cookies['external'][1234] = (d, None)
m = msn.MSNMessage()
m.setHeader('Content-Type', 'text/x-msmsgsinvite; charset=UTF-8')
m.message += 'Invitation-Command: ACCEPT\r\n'
m.message += 'Invitation-Cookie: 1234\r\n'
m.message += 'IP-Address: 192.168.0.1\r\n'
m.message += 'Port: 6891\r\n'
m.message += 'AuthCookie: 4321\r\n\r\n'
self.client.checkMessage(m)
self.failUnless((self.client.state == 'INFO'), msg='Failed to detect file transfer info')
def fileResponse(self, (accept, cookie, info)):
if accept and cookie == 1234: self.client.state = 'RESPONSE'
def fileInfo(self, (accept, ip, port, aCookie, info)):
if accept and ip == '192.168.0.1' and port == 6891 and aCookie == 4321: self.client.state = 'INFO'
class FileTransferTestCase(unittest.TestCase):
"""
test FileSend against FileReceive
"""
def setUp(self):
self.input = 'a' * 7000
self.output = StringIOWithoutClosing()
def tearDown(self):
self.input = None
self.output = None
def test_fileTransfer(self):
"""
Test L{FileSend} against L{FileReceive} using a loopback transport.
"""
auth = 1234
sender = msn.FileSend(StringIO.StringIO(self.input))
sender.auth = auth
sender.fileSize = 7000
client = msn.FileReceive(auth, "foo@bar.com", self.output)
client.fileSize = 7000
def check(ignored):
self.assertTrue(
client.completed and sender.completed,
msg="send failed to complete")
self.assertEqual(
self.input, self.output.getvalue(),
msg="saved file does not match original")
d = loopback.loopbackAsync(sender, client)
d.addCallback(check)
return d
if msn is None:
for testClass in [DispatchTests, PassportTests, NotificationTests,
MessageHandlingTests, FileTransferTestCase]:
testClass.skip = (
"MSN requires an HTTP client but none is available, "
"skipping tests.")
| {
"content_hash": "93380ac16f0ea28b243da8cd00bc7fab",
"timestamp": "",
"source": "github",
"line_count": 519,
"max_line_length": 134,
"avg_line_length": 40.554913294797686,
"alnum_prop": 0.6266628658304827,
"repo_name": "Varriount/Colliberation",
"id": "ece580fedd45ec48ca18bb7729c75cbdaf823164",
"size": "21121",
"binary": false,
"copies": "11",
"ref": "refs/heads/master",
"path": "libs/twisted/words/test/test_msn.py",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C",
"bytes": "509005"
},
{
"name": "D",
"bytes": "29"
},
{
"name": "GAP",
"bytes": "14120"
},
{
"name": "Objective-C",
"bytes": "1291"
},
{
"name": "Python",
"bytes": "10503398"
},
{
"name": "Shell",
"bytes": "1512"
}
],
"symlink_target": ""
} |
#import <UIKit/UIKit.h>
#import <QuickLook/QuickLook.h>
#import "DirectoryWatcher.h"
@interface DITableViewController : UITableViewController <QLPreviewControllerDataSource,
QLPreviewControllerDelegate,
DirectoryWatcherDelegate,
UIDocumentInteractionControllerDelegate>
@end
| {
"content_hash": "c29ad72136f20d860518e7112f23604d",
"timestamp": "",
"source": "github",
"line_count": 12,
"max_line_length": 98,
"avg_line_length": 37.75,
"alnum_prop": 0.5253863134657837,
"repo_name": "jcamiel/radars",
"id": "83860696de18932ca2b9f03e6b52ef64ee56731f",
"size": "2946",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "17792460/DocInteraction/Classes/DITableViewController.h",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "HTML",
"bytes": "1003"
},
{
"name": "Objective-C",
"bytes": "33850"
}
],
"symlink_target": ""
} |
package alt.beanmapper.compile.primitive;
/**
*
* @author Albert Shift
*
*/
public class PrimitiveSource {
private boolean booleanValue;
private byte byteValue;
private char charValue;
private short shortValue;
private int intValue;
private long longValue;
private float floatValue;
private double doubleValue;
public boolean isBooleanValue() {
return booleanValue;
}
public void setBooleanValue(boolean booleanValue) {
this.booleanValue = booleanValue;
}
public byte getByteValue() {
return byteValue;
}
public void setByteValue(byte byteValue) {
this.byteValue = byteValue;
}
public char getCharValue() {
return charValue;
}
public void setCharValue(char charValue) {
this.charValue = charValue;
}
public short getShortValue() {
return shortValue;
}
public void setShortValue(short shortValue) {
this.shortValue = shortValue;
}
public int getIntValue() {
return intValue;
}
public void setIntValue(int intValue) {
this.intValue = intValue;
}
public long getLongValue() {
return longValue;
}
public void setLongValue(long longValue) {
this.longValue = longValue;
}
public float getFloatValue() {
return floatValue;
}
public void setFloatValue(float floatValue) {
this.floatValue = floatValue;
}
public double getDoubleValue() {
return doubleValue;
}
public void setDoubleValue(double doubleValue) {
this.doubleValue = doubleValue;
}
}
| {
"content_hash": "10f70d664c34c17e4694f2d07ddf772d",
"timestamp": "",
"source": "github",
"line_count": 84,
"max_line_length": 52,
"avg_line_length": 17.05952380952381,
"alnum_prop": 0.732728541521284,
"repo_name": "albertshift/beanmapper",
"id": "4b54ac7bb74b30c3f56a354b9c2be215bd7ededd",
"size": "1433",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/test/java/alt/beanmapper/compile/primitive/PrimitiveSource.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Java",
"bytes": "165745"
}
],
"symlink_target": ""
} |
FROM balenalib/aarch64-alpine:edge-run
ENV NODE_VERSION 15.14.0
ENV YARN_VERSION 1.22.4
# Install dependencies
RUN apk add --no-cache libgcc libstdc++ libuv \
&& apk add --no-cache libssl1.0 || apk add --no-cache libssl1.1
RUN buildDeps='curl' \
&& set -x \
&& 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 \
&& apk add --no-cache $buildDeps \
&& curl -SLO "http://resin-packages.s3.amazonaws.com/node/v$NODE_VERSION/node-v$NODE_VERSION-linux-aarch64-alpine.tar.gz" \
&& echo "1dec2f32770b6c864c5f2c59861d91547010deb63adff2c0298a8c150fd7e3f8 node-v$NODE_VERSION-linux-aarch64-alpine.tar.gz" | sha256sum -c - \
&& tar -xzf "node-v$NODE_VERSION-linux-aarch64-alpine.tar.gz" -C /usr/local --strip-components=1 \
&& rm "node-v$NODE_VERSION-linux-aarch64-alpine.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: Alpine Linux edge \nVariant: run variant \nDefault variable(s): UDEV=off \nThe following software stack is preinstalled: \nNode.js v15.14.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/bash\nbalena-info\nbusybox ln -sf /bin/busybox /bin/sh\n/bin/sh "$@"' > /bin/sh-shim \
&& chmod +x /bin/sh-shim \
&& ln -f /bin/sh /bin/sh.real \
&& ln -f /bin/sh-shim /bin/sh | {
"content_hash": "67d797793167bfc4f443a16de63f8822",
"timestamp": "",
"source": "github",
"line_count": 48,
"max_line_length": 697,
"avg_line_length": 62.520833333333336,
"alnum_prop": 0.7074308563812063,
"repo_name": "nghiant2710/base-images",
"id": "58b25c3b2c29c5d04b3c441dd88149811b5674f0",
"size": "3022",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "balena-base-images/node/aarch64/alpine/edge/15.14.0/run/Dockerfile",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Dockerfile",
"bytes": "144558581"
},
{
"name": "JavaScript",
"bytes": "16316"
},
{
"name": "Shell",
"bytes": "368690"
}
],
"symlink_target": ""
} |
#ifndef NACL_TRUSTED_BUT_NOT_TCB
#error("This file is not meant for use in the TCB")
#endif
/*
* cpu_x86_test.c
* test main and subroutines for cpu_x86
*/
#include "native_client/src/include/build_config.h"
#include "native_client/src/include/portability.h"
#include <stdio.h>
#include "native_client/src/trusted/cpu_features/arch/x86/cpu_x86.h"
int main(void) {
NaClCPUFeaturesX86 fv;
NaClCPUData cpu_data;
int feature_id;
NaClCPUDataGet(&cpu_data);
NaClGetCurrentCPUFeaturesX86((NaClCPUFeatures *) &fv);
if (NaClArchSupportedX86(&fv)) {
printf("This is a native client %d-bit %s compatible computer\n",
NACL_BUILD_SUBARCH, GetCPUIDString(&cpu_data));
} else {
if (!NaClGetCPUFeatureX86(&fv, NaClCPUFeatureX86_CPUIDSupported)) {
printf("Computer doesn't support CPUID\n");
}
if (!NaClGetCPUFeatureX86(&fv, NaClCPUFeatureX86_CPUSupported)) {
printf("Computer id %s is not supported\n", GetCPUIDString(&cpu_data));
}
}
printf("This processor has:\n");
for (feature_id = 0; feature_id < NaClCPUFeatureX86_Max; ++feature_id) {
if (NaClGetCPUFeatureX86(&fv, feature_id))
printf(" %s\n", NaClGetCPUFeatureX86Name(feature_id));
}
return 0;
}
| {
"content_hash": "e260df5c8e78e9fc2a60833d92e72cff",
"timestamp": "",
"source": "github",
"line_count": 41,
"max_line_length": 77,
"avg_line_length": 29.975609756097562,
"alnum_prop": 0.6908055329536208,
"repo_name": "cohortfsllc/cohort-cocl2-sandbox",
"id": "61bac8ca34e5d9a86a21e21445dc662a3eeda5d2",
"size": "1409",
"binary": false,
"copies": "7",
"ref": "refs/heads/master",
"path": "src/trusted/cpu_features/arch/x86/cpu_x86_test.c",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "Assembly",
"bytes": "202996"
},
{
"name": "Batchfile",
"bytes": "10099"
},
{
"name": "C",
"bytes": "8029732"
},
{
"name": "C++",
"bytes": "7442866"
},
{
"name": "HTML",
"bytes": "127706"
},
{
"name": "JavaScript",
"bytes": "5925"
},
{
"name": "LLVM",
"bytes": "1169"
},
{
"name": "Logos",
"bytes": "6893"
},
{
"name": "Makefile",
"bytes": "19801"
},
{
"name": "Objective-C++",
"bytes": "2658"
},
{
"name": "Python",
"bytes": "2794043"
},
{
"name": "Ragel in Ruby Host",
"bytes": "104923"
},
{
"name": "Shell",
"bytes": "176787"
}
],
"symlink_target": ""
} |
#pragma once
#include "IPv6Map.h"
#include "Global.h"
#include <stdint.h>
#include "CPH_Threads.h"
#include <stdbool.h>
#include <openssl/ossl_typ.h>
#include "DNS.h"
#define PROXY_IDENTIFIER_LEN 32
typedef enum _PROXY_TYPE {
PROXY_TYPE_HTTP = 1,
PROXY_TYPE_HTTPS = 2,
PROXY_TYPE_SOCKS4 = 4,
PROXY_TYPE_SOCKS4A = 8,
PROXY_TYPE_SOCKS5 = 16,
PROXY_TYPE_SOCKS4_TO_SSL = 32,
PROXY_TYPE_SOCKS4A_TO_SSL = 64,
PROXY_TYPE_SOCKS5_TO_SSL = 128,
PROXY_TYPE_SOCKS5_WITH_UDP = 256
} PROXY_TYPE;
#define PROXY_TYPE_COUNT 9
#define PROXY_TYPE_SOCKS_GENERIC (PROXY_TYPE_SOCKS4 | PROXY_TYPE_SOCKS4A | PROXY_TYPE_SOCKS5)
#define PROXY_TYPE_SOCKS_GENERIC_SSL (PROXY_TYPE_SOCKS4_TO_SSL | PROXY_TYPE_SOCKS4A_TO_SSL | PROXY_TYPE_SOCKS5_TO_SSL)
#define PROXY_TYPE_ALL (PROXY_TYPE_HTTP | PROXY_TYPE_HTTPS | PROXY_TYPE_SOCKS_GENERIC | PROXY_TYPE_SOCKS_GENERIC_SSL | PROXY_TYPE_SOCKS5_WITH_UDP)
typedef enum _ANONYMITY {
ANONYMITY_NONE = 0,
ANONYMITY_TRANSPARENT = 1,
ANONYMITY_ANONYMOUS = 2,
ANONYMITY_MAX = 3
} ANONYMITY;
typedef struct _PROXY {
IPv6Map *ip;
uint16_t port;
PROXY_TYPE type; // PROXY_TYPE
ANONYMITY anonymity; // ANONYMITY
const char *country;
bool rechecking;
uint64_t httpTimeoutMs;
uint64_t timeoutMs;
uint64_t liveSinceMs;
uint64_t lastCheckedMs;
uint8_t retries;
uint32_t successfulChecks;
uint32_t failedChecks;
int certErr;
X509 *invalidCert;
uint8_t identifier[PROXY_IDENTIFIER_LEN];
} PROXY;
typedef void(*SingleCheckCallback)(void *UProxy);
typedef enum _UPROXY_CUSTOM_PAGE_STAGE {
UPROXY_CUSTOM_PAGE_STAGE_INITIAL_PACKET = 0,
UPROXY_CUSTOM_PAGE_STAGE_DDL_PAGE = 1,
UPROXY_CUSTOM_PAGE_STAGE_END = 2
} UPROXY_CUSTOM_PAGE_STAGE;
typedef void(*SingleCheckCallbackCPage)(void *UProxy, UPROXY_CUSTOM_PAGE_STAGE Stage);
typedef enum _UPROXY_STAGE {
UPROXY_STAGE_INITIAL_PACKET = 0,
UPROXY_STAGE_INITIAL_RESPONSE = 1,
UPROXY_STAGE_SOCKS5_MAIN_PACKET = 2,
UPROXY_STAGE_SOCKS5_DNS_RESOLVE = 2, // This is not a typo
UPROXY_STAGE_SOCKS5_RESPONSE = 3,
UPROXY_STAGE_UDP_PACKET = 4,
UPROXY_STAGE_SSL_HANDSHAKE = 5,
UPROXY_STAGE_HTTP_REQUEST = 6,
UPROXY_STAGE_HTTP_RESPONSE = 7,
UPROXY_STAGE_HTTP_DDL_PAGE = 8
} UPROXY_STAGE;
typedef struct _UNCHECKED_PROXY {
IPv6Map *ip;
uint16_t port;
uint16_t targetPort;
IPv6Map *targetIPv4;
IPv6Map *targetIPv6;
PROXY_TYPE type;
bool checking;
uint8_t retries;
bool checkSuccess;
struct bufferevent *assocBufferEvent;
/* PROXY_TYPE_HTTP
* 6 - Send HTTP request
* 7, 8 - Download legit page
* PROXY_TYPE_HTTPS
* 0 - Send CONNECT request
* 1 - Receive CONNECT response
* 5 - SSL hanshake
* 6 - Send HTTP request
* 7, 8 - Download legit page
* PROXY_TYPE_SOCKS4/A
* 0 - Send SOCKS4/A packet
* 1 - Receive answer
* 6 - Send HTTP request
* 7, 8 - Download legit page
* PROXY_TYPE_SOCKS5
* 0 - Send SOCKS5 auth packet
* 1 - Receive auth response
* 2 - Send SOCKS5 main packet
* 3 - Receive response
* 6 - Send HTTP request
* 7, 8 - Download legit page
* PROXY_TYPE_SOCKS4/A_TO_SSL
* 0 - Send SOCKS4/A packet
* 1 - Receive answer
* 5 - SSL hanshake
* 6 - Send HTTP request
* 7, 8 - Download legit page
* PROXY_TYPE_SOCKS5_TO_SSL
* 0 - Send SOCKS5 auth packet
* 1 - Receive auth response
* 2 - Send SOCKS5 main packet
* 3 - Receive response
* 5 - SSL hanshake
* 6 - Send HTTP request
* 7, 8 - Download legit page
* PROXY_TYPE_SOCKS5_WITH_UDP
* 0 - Send SOCKS5 auth packet
* 1 - Receive auth response
* 2 - Send SOCKS5 main packet
* 3 - Receive response
* 4 - Send UDP packet
* 7, 8 - Receive UDP packet
*/
// Universal stages - 5, 6, 7, 8
UPROXY_STAGE stage;
// This one blocks EVWrite called timeout event in case the Server is processing UProxy while EVWrite timeout event tries to free it
pthread_mutex_t processing;
struct event *timeout;
struct event *udpRead;
uint8_t identifier[PROXY_IDENTIFIER_LEN];
uint64_t requestTimeMs;
uint64_t requestTimeHttpMs;
PROXY *associatedProxy;
X509 *invalidCert;
char *pageTarget;
char *pageTargetPostData;
bool getResponse;
SingleCheckCallback singleCheckCallback;
void *singleCheckCallbackExtraData;
IP_TYPE dnsResolveInProgress;
DNS_LOOKUP_ASYNC_EX **dnsLookups;
size_t dnsLookupsCount;
} UNCHECKED_PROXY;
UNCHECKED_PROXY **UncheckedProxies;
uint64_t SizeUncheckedProxies;
pthread_mutex_t LockUncheckedProxies;
PROXY **CheckedProxies;
uint64_t SizeCheckedProxies;
pthread_mutex_t LockCheckedProxies;
bool ProxyIsSSL(PROXY_TYPE In);
char *ProxyGetTypeString(PROXY_TYPE In);
bool ProxyAdd(PROXY *Proxy);
uint8_t UProxyAdd(UNCHECKED_PROXY *UProxy);
bool UProxyRemove(UNCHECKED_PROXY *UProxy);
bool ProxyRemove(PROXY *Proxy);
void GenerateHashForUProxy(UNCHECKED_PROXY *In);
void UProxyFree(UNCHECKED_PROXY *In);
void ProxyFree(PROXY *In);
UNCHECKED_PROXY *UProxyFromProxy(PROXY *In);
UNCHECKED_PROXY *AllocUProxy(IPv6Map *Ip, uint16_t Port, PROXY_TYPE Type, struct event *Timeout, PROXY *AssociatedProxy);
PROXY *GetProxyByIdentifier(uint8_t *In); | {
"content_hash": "9b22598f016e887fe2edbf83321cae0f",
"timestamp": "",
"source": "github",
"line_count": 183,
"max_line_length": 146,
"avg_line_length": 27.284153005464482,
"alnum_prop": 0.7292209092729822,
"repo_name": "TETYYS/LiveProxies",
"id": "77ae0a6b7e6286a4bc62acacd2b7c4bf8a740846",
"size": "4993",
"binary": false,
"copies": "1",
"ref": "refs/heads/devel",
"path": "ProxyLists.h",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Batchfile",
"bytes": "40"
},
{
"name": "C",
"bytes": "300840"
},
{
"name": "C++",
"bytes": "170"
},
{
"name": "CMake",
"bytes": "5132"
},
{
"name": "CSS",
"bytes": "11288"
},
{
"name": "JavaScript",
"bytes": "37671"
},
{
"name": "Objective-C",
"bytes": "4694"
},
{
"name": "Python",
"bytes": "653"
}
],
"symlink_target": ""
} |
package com.nulabinc.backlog4j.internal.json.activities;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
import org.apache.commons.lang3.builder.EqualsBuilder;
import org.apache.commons.lang3.builder.HashCodeBuilder;
import org.apache.commons.lang3.builder.ToStringBuilder;
/**
* @author nulab-inc
*/
@JsonIgnoreProperties(ignoreUnknown = true)
public class WikiUpdatedActivity extends ActivityJSONImpl {
private int type = 6;
@JsonDeserialize(as=WikiUpdatedContent.class)
private WikiUpdatedContent content;
@Override
public Type getType() {
return Type.valueOf(this.type);
}
@Override
public WikiUpdatedContent getContent() {
return this.content;
}
@Override
public boolean equals(Object obj) {
if (obj == null) {
return false;
}
if (obj == this) {
return true;
}
if (obj.getClass() != getClass()) {
return false;
}
WikiUpdatedActivity rhs = (WikiUpdatedActivity) obj;
return new EqualsBuilder()
.append(this.type, rhs.type)
.append(this.content, rhs.content)
.isEquals();
}
@Override
public int hashCode() {
return new HashCodeBuilder()
.append(type)
.append(content)
.toHashCode();
}
@Override
public String toString() {
return new ToStringBuilder(this)
.append("type", type)
.append("content", content)
.toString();
}
}
| {
"content_hash": "96d9cd469fbcbba7f68432e9cae11649",
"timestamp": "",
"source": "github",
"line_count": 63,
"max_line_length": 65,
"avg_line_length": 26.41269841269841,
"alnum_prop": 0.6105769230769231,
"repo_name": "nulab/backlog4j",
"id": "8bf0dc2db387a1262240961175aa4dd89716dee7",
"size": "1664",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/main/java/com/nulabinc/backlog4j/internal/json/activities/WikiUpdatedActivity.java",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Java",
"bytes": "776786"
}
],
"symlink_target": ""
} |
package edu.uw.apl.tupelo.fuse;
import java.io.File;
import java.io.IOException;
import java.util.Collection;
import java.util.Collections;
import java.util.ArrayList;
import java.util.List;
import java.util.HashMap;
import java.util.Map;
import java.util.HashSet;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.nio.ByteBuffer;
import fuse.*;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import edu.uw.apl.tupelo.model.ManagedDisk;
import edu.uw.apl.tupelo.model.ManagedDiskDescriptor;
import edu.uw.apl.tupelo.model.SeekableInputStream;
import edu.uw.apl.tupelo.model.Session;
import edu.uw.apl.tupelo.store.Store;
/**
* Expose the contents of a Tupelo store as a <em>filesystem</em>,
* suitable for inspection by e.g. <code>md5sum, dd, mmls, fls,
* etc</code>. Each file exposed is a <em>device file</em> rather
* than a regular file, so think <code>/dev/sda</code> and not
* <code>/etc/fstab</code>. Only device-aware tools like the ones
* mentioned above can make any sense of this filesystem.
* Typical usage is
* <pre>
*
* Store s = new FilesystemStore();
* ManagedDiskFileSystem mdfs = new ManagedDiskFileSystem( s );
* File mountPoint = new File( "mount" );
* mountPoint.mkdirs();
* boolean ownThread = true|false;
* mdfs.mount( mountPoint, ownThread );
* </pre>
*
* where <code>ownThread</code> depends on the calling code needing to
* continue or not. When used in a main program (see e.g. {@link
* Main}), set to false. When used in e.g. a web application, set to
* true.
* <p>
* To unmount, externally run {@code fusermount -u mount}. This
* same command could also be wrapped in a
* <code>Process/ProcessBuilder</code> if to be run locally, which is
* how the {@link #umount() umount} method works.
*
* <p>
* The filessytem layout for the managed disks is then
*
* <pre>
* /diskIDX/sessionIDY
* </pre>
*
* for all disks X and all sessions Y. You could then do this, for
* some available file, <p>
*
* <pre>
* $ md5sum /path/to/mount/diskID1/sessionID2
* </pre>
*
* Note how we access the 'Store' object totally by the base Store
* interface. We do NOT need to know here HOW the Store is
* implemented (though of course the likely implementation is a
* FilesystemStore).
*/
public class ManagedDiskFileSystem extends AbstractFilesystem3 {
/**
* Construct a ManagedDiskFileSystem given a Tupelo store. Will
* expose each managed disk (a what/when pair) as a device file
* under the ManagedDiskFileSystem mount point.
*
@param s the Tupelo store whose managed disks are to exposed as a
filesystem.
*/
public ManagedDiskFileSystem( Store s ) {
store = s;
startTime = (int) (System.currentTimeMillis() / 1000L);
readBuffers = new HashMap<Object,byte[]>();
log = LogFactory.getLog( getClass() );
try {
Collection<ManagedDiskDescriptor> mdds = store.enumerate();
for( ManagedDiskDescriptor mdd : mdds ) {
log.info( "Exposing: " + mdd.getDiskID() +
"/" + mdd.getSession() );
}
} catch( IOException ioe ) {
log.warn( "Exception creating MDFS", ioe );
}
}
/**
* Do the fuse mount. Until this command called, the store's
* contents are not visible to the host filesystem.
*
* @param mountPoint a directory on the host file system at which
* to do the mount. Must exist a priori.
* @param ownThread false if caller willing to block until the
* mount is torn down (by an external <code>fusermount -u
* mount</code>). A caller which needs a new thread spawned
* supplies true.
*/
public void mount( File mountPoint, boolean ownThread ) throws Exception {
if( !mountPoint.isDirectory() )
throw new IllegalArgumentException( "Mountpoint not a dir: " +
mountPoint );
this.mountPoint = mountPoint;
/*
The -f says no fork, we need this!!
The -s says single-threaded, we need this!!
LOOK: Consider relaxing this and synchronizing on the
SeekableInputStream objects, may improve performance ??
Can't have arbitrary multi-threaded access to each
SeekableInputStream (since it has state and is NOT
synchronized internally) but MT-access to distinct
SeekableInputStreams likely OK. Likely we are not achieving
this latter situation even with the current -s option set to
true. Not sure if 'fuse single threaded' means a single
thread for the entire filesystem, or a single thread per
opened file.
The -r says read-only, which makes sense here
*/
String[] args = { mountPoint.getPath(), "-f", "-s", "-r" };
/*
If we supply the fuse package OUR logger, we cannot separate
out logging by package name, like we usually do. So create
two loggers, one for US and one for THEM
*/
Log logFuse = LogFactory.getLog( "fuse" );
if( ownThread ) {
ThreadGroup tg = new ThreadGroup( "MDFS.Threads" );
FuseMount.mount( args, this, tg, logFuse );
} else {
FuseMount.mount( args, this, logFuse );
}
}
/**
* Unmount the filesystem, the dual of {@link #mount(java.io.File,
* boolean) mount}. Only makes sense if the mount was done such
* that the caller was able to continue, with the file system
* running in its own thread.
*
* @return The exit code of the 'fusermount -u' sub-process
*/
public int umount() throws Exception {
String cmdLine = "fusermount -u " + mountPoint;
log.info( "Execing: " + cmdLine );
// Process p = Runtime.getRuntime().exec( cmdLine );
ProcessBuilder pb = new ProcessBuilder( "fusermount", "-u",
mountPoint.toString() );
// Use the same IO as the java process
pb.inheritIO();
Process p = pb.start();
p.waitFor();
log.info( "Result: " + p.exitValue() );
return p.exitValue();
}
// LOOK: how do we handle io errors from store?
private Collection<ManagedDiskDescriptor> descriptors() {
try {
return store.enumerate();
} catch( IOException ioe ) {
log.warn( "Exception getting descriptors", ioe );
return Collections.emptyList();
}
}
/**
Convenience method, for applications to derive where in the
mounted file system a ManagedDisk can be located.
@param mdd a descriptor (diskID+sessionID) for the managed disk
of interest
*/
public File pathTo( ManagedDiskDescriptor mdd ) {
File f = new File( mountPoint, mdd.getDiskID() );
f = new File( f, mdd.getSession().toString() );
return f;
}
@Override
public int getattr( String path, FuseGetattrSetter getattrSetter )
throws FuseException {
if( log.isTraceEnabled() ) {
log.trace( "getattr " + path );
}
Collection<ManagedDiskDescriptor> mdds = descriptors();
if( path.equals( "/" ) ) {
int count = mdds.size();
int time = startTime;
getattrSetter.set
( path.hashCode(), FuseFtypeConstants.TYPE_DIR | 0755, 2,
0, 0, 0,
// size, blocks lifted from example FakeFilesystem...
count * 128, (count * 128 + 512 - 1) / 512,
time, time, time);
return 0;
}
String details = path.substring(1);
Matcher m1 = DISKIDPATHREGEX.matcher( details );
if( m1.matches() ) {
String diskID = m1.group(1);
List<ManagedDiskDescriptor> matching =
new ArrayList<ManagedDiskDescriptor>();
for( ManagedDiskDescriptor mdd : mdds ) {
if( mdd.getDiskID().equals( diskID ) ) {
matching.add( mdd );
}
}
if( matching.isEmpty() )
return Errno.ENOENT;
int count = matching.size();
int time = startTime;
getattrSetter.set
( path.hashCode(),
FuseFtypeConstants.TYPE_DIR | 0755, 2,
0, 0, 0,
// size, blocks lifted from example FakeFilesystem...
count * 128, (count * 128 + 512 - 1) / 512,
time, time, time);
return 0;
}
Matcher m2 = MANAGEDDISKDESCRIPTORPATHREGEX.matcher( details );
if( m2.matches() ) {
//System.out.println( "getAttr(VD)." + m.group(0) );
String diskID = m2.group(1);
String sessionID = m2.group(2);
ManagedDiskDescriptor matching = null;
for( ManagedDiskDescriptor mdd : mdds ) {
if( mdd.getDiskID().equals( diskID ) &&
mdd.getSession().toString().equals( sessionID ) ) {
/*
System.out.println( "getattr.Matched: " + mdd +
" to " + MANAGEDDISKDESCRIPTORPATHREGEX );
*/
matching = mdd;
break;
}
}
if( matching == null )
return Errno.ENOENT;
int time = startTime;// LOOK: link to session date/time?
ManagedDisk md = store.locate( matching );
long size = md.size();
getattrSetter.set
( matching.hashCode(), FuseFtypeConstants.TYPE_FILE | 0444,
1, 0, 0, 0, size, (size + 512 - 1) / 512,
time, time, time );
return 0;
}
return Errno.ENOENT;
}
@Override
public int getdir(String path, FuseDirFiller filler )
throws FuseException {
Collection<ManagedDiskDescriptor> mdds = descriptors();
if( log.isTraceEnabled() )
log.trace( "getdir: " + path );
// System.out.println( "getdir: " + path );
if( "/".equals( path ) ) {
Set<String> matching = new HashSet<String>();
for( ManagedDiskDescriptor mdd : mdds ) {
matching.add( mdd.getDiskID() );
}
for( String s : matching ) {
filler.add( s, s.hashCode(),
FuseFtypeConstants.TYPE_DIR | 0755 );
}
return 0;
}
String details = path.substring(1);
Matcher m1 = DISKIDPATHREGEX.matcher( details );
if( m1.matches() ) {
String needle = m1.group(0);
List<String> matchingDirs = new ArrayList<String>();
for( ManagedDiskDescriptor mdd : mdds ) {
// System.out.println( mdd );
if( mdd.getDiskID().equals( needle ) ) {
matchingDirs.add( mdd.getSession().toString() );
// System.out.println( "Matched: " + mdd );
}
}
if( matchingDirs.isEmpty() )
return Errno.ENOENT;
for( String s : matchingDirs )
filler.add( s, s.hashCode(),
FuseFtypeConstants.TYPE_FILE| 0644 );
return 0;
}
return Errno.ENOENT;
}
/*
If open returns a filehandle by calling FuseOpenSetter.setFh()
method, it will be passed to every method that supports 'fh'
argument
*/
@Override
public int open( String path, int flags, FuseOpenSetter openSetter )
throws FuseException {
Collection<ManagedDiskDescriptor> mdds = descriptors();
String details = path.substring( 1 );
Matcher m = MANAGEDDISKDESCRIPTORPATHREGEX.matcher( details );
if( m.matches() ) {
String diskID = m.group(1);
String sessionID = m.group(2);
ManagedDiskDescriptor matching = null;
for( ManagedDiskDescriptor mdd : mdds ) {
if( mdd.getDiskID().equals( diskID ) &&
mdd.getSession().toString().equals( sessionID ) ) {
/*
System.out.println( "open.Matched: " + mdd +
" to " + MANAGEDDISKDESCRIPTORPATHREGEX );
*/
matching = mdd;
break;
}
}
if( matching == null )
return Errno.ENOENT;
ManagedDisk md = store.locate( matching );
// LOOK: could be null ??
// System.out.println( "open.Matched: " + md );
try {
SeekableInputStream sis = md.getSeekableInputStream();
openSetter.setFh( sis );
// System.out.println( "open.rar: " + rar );
return 0;
} catch( IOException e ) {
throw new FuseException( e );
}
}
return Errno.ENOENT;
}
/**
@param path the file to read. Represents a single managed disk
(what/when).
@param fh filehandle passed from {@link #open(String, int,
fuse.FuseOpenSetter) open)}. We know it represents a
SeekableInputStream.
@param buf a buffer to store the read data. Has a known
available space, which governs how much data we should/can read.
@param offset file offset at which to read. We seek to it.
*/
@Override
public int read(String path, Object fh, ByteBuffer buf, long offset)
throws FuseException {
if( log.isDebugEnabled() )
log.debug( "read.: " + path );
SeekableInputStream sis = (SeekableInputStream)fh;
try {
sis.seek( offset );
/*
We keep building a bigger read buffer for each open 'file'.
Remember that any read may be for a smaller byte count
than the previous one, so use the 3-arg version of read
*/
byte[] ba;
int nin;
ba = readBuffers.get( fh );
if( ba == null || buf.remaining() > ba.length ) {
ba = new byte[buf.remaining()];
readBuffers.put( fh, ba );
if( log.isInfoEnabled() )
log.info( "New read buffer for " + path +
" = " + ba.length );
}
nin = sis.read( ba, 0, buf.remaining() );
// ba = new byte[buf.remaining()];
// nin = sis.read( ba );
if( log.isDebugEnabled() ) {
log.debug( "sis.read " + nin );
}
if( nin > -1 )
buf.put( ba, 0, nin );
else
// need this?? does this tells fuse we are at eof???
buf.put( ba, 0, 0 );
/*
the fuse4j api says we return 0, NOT the byte count written
to the ByteBuffer
*/
return 0;
} catch( Exception e ) {
log.warn( "Exception reading", e );
log.warn( path + " " + offset + " " + buf.remaining() );
throw new FuseException( e );
}
}
// fh is filehandle passed from open,
// isWritepage indicates that write was caused by a writepage
@Override
public int write(String path, Object fh, boolean isWritepage,
ByteBuffer buf, long offset) throws FuseException {
return Errno.EROFS;
}
// called when last filehandle is closed, fh is filehandle passed from open
@Override
public int release(String path, Object fh, int flags) throws FuseException {
log.info( "Release read buffer for " + path );
readBuffers.remove( fh );
return 0;
}
private final Store store;
private final int startTime;
private File mountPoint;
private final Map<Object,byte[]> readBuffers;
private final Log log;
/*
We check provided paths as identifying valid managed disk content
via these two regexs
*/
static final Pattern DISKIDPATHREGEX = Pattern.compile
( "^(" + ManagedDiskDescriptor.DISKIDREGEX.pattern() + ")/?$" );
static final Pattern MANAGEDDISKDESCRIPTORPATHREGEX = Pattern.compile
( "^(" + ManagedDiskDescriptor.DISKIDREGEX.pattern() + ")/(" +
Session.SHORTREGEX.pattern() + ")/?$" );
}
// eof
| {
"content_hash": "a3f032ed28453df58d0e8dae515a057b",
"timestamp": "",
"source": "github",
"line_count": 471,
"max_line_length": 78,
"avg_line_length": 29.912951167728238,
"alnum_prop": 0.6610121371282561,
"repo_name": "uw-dims/tupelo",
"id": "7031dc48c7144b7709309ffb2e45abf2d4b0b4d3",
"size": "15725",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "fuse/src/main/java/edu/uw/apl/tupelo/fuse/ManagedDiskFileSystem.java",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "C",
"bytes": "21747"
},
{
"name": "C++",
"bytes": "834"
},
{
"name": "HTML",
"bytes": "1260"
},
{
"name": "Java",
"bytes": "644369"
},
{
"name": "Makefile",
"bytes": "5018"
},
{
"name": "Shell",
"bytes": "15743"
}
],
"symlink_target": ""
} |
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Management.Automation;
using System.Management.Automation.Provider;
using System.Text;
namespace ProviderFramework_1_TheNullProvider
{
/// <summary>
/// The provider class.
/// </summary>
[CmdletProvider("NullProvider", ProviderCapabilities.ShouldProcess)]
public class NullProvider : CodeOwls.PowerShell.Provider.Provider
{
/// <summary>
/// a required P2F override
///
/// supplies P2F with the path processor for this provider
/// </summary>
protected override CodeOwls.PowerShell.Paths.Processors.IPathResolver PathResolver
{
get { return new NullPathResolver(); }
}
/// <summary>
/// overridden to supply a default drive when the provider is loaded
/// </summary>
protected override Collection<PSDriveInfo> InitializeDefaultDrives()
{
return new Collection<PSDriveInfo>
{
new NullDrive(
new PSDriveInfo( "Null", ProviderInfo, String.Empty, "Null Drive", null )
)
};
}
}
}
| {
"content_hash": "76f99e74d62caf74eb5ccb61c90f7a83",
"timestamp": "",
"source": "github",
"line_count": 40,
"max_line_length": 105,
"avg_line_length": 33.4,
"alnum_prop": 0.5755988023952096,
"repo_name": "SpotLabsNET/p2f",
"id": "3df71dd2e4fb7f58da549746faa774f37e05e5bf",
"size": "1338",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "src/Samples/P2F_Sample1_NullProvider/NullProvider.cs",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C#",
"bytes": "23259"
},
{
"name": "PowerShell",
"bytes": "4116"
},
{
"name": "Smalltalk",
"bytes": "271310"
}
],
"symlink_target": ""
} |
from django.core.management.base import BaseCommand
from django.core.urlresolvers import reverse
from rest_framework.test import APIClient
class Command(BaseCommand):
args = 'no arguments'
help = 'Display YAML for airports.'
def handle(self, *args, **options):
client = APIClient()
response = client.get(reverse('api:export-instructors'),
{'format': 'yaml'})
print(response.content.decode('utf-8'))
| {
"content_hash": "088349b1cb9a8e35852055ffd77c946c",
"timestamp": "",
"source": "github",
"line_count": 14,
"max_line_length": 64,
"avg_line_length": 33.42857142857143,
"alnum_prop": 0.655982905982906,
"repo_name": "wking/swc-amy",
"id": "3d24a27c36311203c0fb64e331ba8f94107b64b5",
"size": "468",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "workshops/management/commands/export_airports.py",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "3519"
},
{
"name": "HTML",
"bytes": "110663"
},
{
"name": "JavaScript",
"bytes": "1373"
},
{
"name": "Makefile",
"bytes": "2953"
},
{
"name": "PLpgSQL",
"bytes": "11848977"
},
{
"name": "Python",
"bytes": "464347"
},
{
"name": "Shell",
"bytes": "373"
}
],
"symlink_target": ""
} |
<!DOCTYPE html>
<html>
<head>
<title>Blog | Arrays and Hashes</title>
<meta charset="UTF-8">
<meta name="description" content="Arrays and Hashes">
<link rel="stylesheet" type="text/css" href="../stylesheets/default.css">
<link rel="stylesheet" type="text/css" href="../stylesheets/blog.css">
<meta name="author" content="Ian Fricker">
</head>
<body>
<nav class="navbar">
<div id="nav-left">
<a href="http://ifricker.github.io/">Ian <span class="heavy">Fricker</span></a>
</div>
<div id="nav-right">
<a href="http://ifricker.github.io/#aboutme">About Me</a>
<a href="http://ifricker.github.io/#experience">Experience</a>
<a href="http://ifricker.github.io/#education">Education</a>
<a href="http://ifricker.github.io/#projects">Projects</a>
<a href="http://ifricker.github.io/blog">Blog</a>
<a href="http://ifricker.github.io/#contact">Contact</a>
</div>
</nav>
<div class="blog-post">
<div class="blog-entry">
<p id="blog-title">Arrays and Hashes</p>
<p id="blog-date">January 21, 2016</p>
<p id="blog-author">By Ian Fricker</p>
<p id="blog-subtitle">What and Which</p>
<p id="blog-paragraph">Ruby is a very powerful object oriented programing language. Ruby can take many things as arguments, some being arrays and hashes. Arrays are simply list of information. While a hash is a list of information that has specific relation to other information.</p>
<p id="blog-paragraph">Arrays can consist of strings, numbers and other arrays. One thing that arrays do well is hold a specific order. You can place an item in an array at a specific spot and rely on that staying in that location. See the code bellow for some examples of arrays.</p>
<br>
<code>first_array = []<br>second_array = ["cat", "dog", "fish"]<br>third_array = [27, "pancake", ["apple", "orange", "pineapple"]]</code>
<br><br>
<p id="blog-paragraph">Looking at the above arrays you can see that the first is an empty array. The second is an array that contains three strings, cat, dog, and fish. While the third array contains a number, a string, and another array. To access a specific location in the array please look at the code bellow.</p>
<br>
<code>puts second_array[1]<br>#=> dog</code>
<br><br>
<p id="blog-paragraph">You will notice that calling the position of [1] pulls the second item in the list. Counting in arrays starts with 0.</p>
<br>
<code>puts second_array[0]<br>#=> cat</code>
<br><br>
<p id="blog-paragraph">Now hashes are something very different. Hashes are made up of a key that have corresponding values. Look at the example before moving on.</p>
<br>
<code>population_hash = { USA => "322,687,000", Mexico => "122,273,500", Canada => "35,985,751"}</code>
<br><br>
<p id="blog-paragraph">Looking at the example you see that the hash "population_hash" contains three pairs of information relating to country population. Hashes are useful for recalling information.</p>
<br>
<code>puts population_hash[Mexico]<br>#=> 122,273,500</code>
<br><br>
<p id="blog-paragraph">The hash population_hash is asked to output the corresponding data for the key Mexico. The output is the information originally setup within the hash.</p>
<p id="blog-paragraph">After reviewing this basic summary of arrays and hashes, can you think of ways to use them and make your coding even better.</p>
</div>
<div id="previous-button">
<a href="./css-concepts.html" id="resume-button">Previous</a>
</div>
<div id="next-button">
<a href="./online-security.html" id="resume-button">Next</a>
</div>
</div>
<footer class="footbar">
<a href="mailto:imfricker@gmail.com"><img src="../imgs/email-white.png" onmouseover="this.src='../imgs/email-color.png'" onmouseout="this.src='../imgs/email-white.png'" alt="email" class="icon-style"></a>
<a href="https://www.linkedin.com/in/ianfricker"><img src="../imgs/linkedin-white.png" onmouseover="this.src='../imgs/linkedin-color.png'" onmouseout="this.src='../imgs/linkedin-white.png'" alt="linkedin" class="icon-style"></a>
<a href="https://github.com/ifricker"><img src="../imgs/github-white.png" onmouseover="this.src='../imgs/github-color.png'" onmouseout="this.src='../imgs/github-white.png'" alt="github" class="icon-style"></a>
<a href="https://www.instagram.com/ifricker/"><img src="../imgs/instagram-white.png" onmouseover="this.src='../imgs/instagram-color.png'" onmouseout="this.src='../imgs/instagram-white.png'" alt="instagram" class="icon-style"></a>
<h4>Copyright © Ian Fricker 2016</h4>
</footer>
</body>
</html> | {
"content_hash": "be91f480cce72cb09598364648bad28d",
"timestamp": "",
"source": "github",
"line_count": 71,
"max_line_length": 328,
"avg_line_length": 68.32394366197182,
"alnum_prop": 0.6538857967429396,
"repo_name": "ifricker/ifricker.github.io",
"id": "8b9617c48d104bd9febef408e58a4b1f2cf6add1",
"size": "4851",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "blog/arrays-hashes.html",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "6130"
},
{
"name": "HTML",
"bytes": "55215"
},
{
"name": "JavaScript",
"bytes": "4873"
}
],
"symlink_target": ""
} |
require 'spec_helper'
module MockModuleToInclude
def self.included(dsl)
end
end
describe ActiveAdmin::DSL do
let(:config){ mock }
let(:application) { ActiveAdmin::Application.new }
let(:namespace) { ActiveAdmin::Namespace.new application, :admin }
let(:resource_config) { ActiveAdmin::Resource.new namespace, Post }
let(:dsl){ ActiveAdmin::DSL.new(config) }
describe "#include" do
it "should call the included class method on the module that is included" do
MockModuleToInclude.should_receive(:included).with(dsl)
dsl.run_registration_block do
include MockModuleToInclude
end
end
end
describe "#menu" do
it "should set the menu_item_options on the configuration" do
config.should_receive(:menu_item_options=).with({:parent => "Admin"})
dsl.run_registration_block do
menu :parent => "Admin"
end
end
end
describe "#navigation_menu" do
it "should set the navigation_menu_name on the configuration" do
config.should_receive(:navigation_menu_name=).with(:admin)
dsl.run_registration_block do
navigation_menu :admin
end
end
it "should accept a block" do
dsl = ActiveAdmin::DSL.new(resource_config)
dsl.run_registration_block do
navigation_menu { :dynamic_menu }
end
resource_config.navigation_menu_name.should == :dynamic_menu
end
end
end
| {
"content_hash": "c0aaf980325dabbe2033025f7e299472",
"timestamp": "",
"source": "github",
"line_count": 61,
"max_line_length": 80,
"avg_line_length": 23.262295081967213,
"alnum_prop": 0.6758280479210712,
"repo_name": "piousbox/microsites2-cities",
"id": "2b048bf8a2b58aa47002e3a4ca78345e4b5b78c4",
"size": "1419",
"binary": false,
"copies": "1",
"ref": "refs/heads/cities2",
"path": "vendor/ruby/1.9.1/gems/activeadmin-0.6.0/spec/unit/dsl_spec.rb",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "34286"
},
{
"name": "JavaScript",
"bytes": "32921"
},
{
"name": "Ruby",
"bytes": "153682"
},
{
"name": "Shell",
"bytes": "1616"
}
],
"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_20) on Sun Jun 06 00:15:53 JST 2010 -->
<META http-equiv="Content-Type" content="text/html; charset=UTF-8">
<TITLE>
インタフェース org.apache.mina.handler.chain.IoHandlerCommand の使用 (Apache MINA Core 2.0.0-RC1 API)
</TITLE>
<META NAME="date" CONTENT="2010-06-06">
<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="インタフェース org.apache.mina.handler.chain.IoHandlerCommand の使用 (Apache MINA Core 2.0.0-RC1 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="ナビゲーションリンクをスキップ"></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>概要</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../package-summary.html"><FONT CLASS="NavBarFont1"><B>パッケージ</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../org/apache/mina/handler/chain/IoHandlerCommand.html" title="org.apache.mina.handler.chain 内のインタフェース"><FONT CLASS="NavBarFont1"><B>クラス</B></FONT></A> </TD>
<TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> <FONT CLASS="NavBarFont1Rev"><B>使用</B></FONT> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../package-tree.html"><FONT CLASS="NavBarFont1"><B>階層ツリー</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>非推奨 API</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../index-all.html"><FONT CLASS="NavBarFont1"><B>索引</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../help-doc.html"><FONT CLASS="NavBarFont1"><B>ヘルプ</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">
前
次</FONT></TD>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
<A HREF="../../../../../../index.html?org/apache/mina/handler/chain//class-useIoHandlerCommand.html" target="_top"><B>フレームあり</B></A>
<A HREF="IoHandlerCommand.html" target="_top"><B>フレームなし</B></A>
<SCRIPT type="text/javascript">
<!--
if(window==top) {
document.writeln('<A HREF="../../../../../../allclasses-noframe.html"><B>すべてのクラス</B></A>');
}
//-->
</SCRIPT>
<NOSCRIPT>
<A HREF="../../../../../../allclasses-noframe.html"><B>すべてのクラス</B></A>
</NOSCRIPT>
</FONT></TD>
</TR>
</TABLE>
<A NAME="skip-navbar_top"></A>
<!-- ========= END OF TOP NAVBAR ========= -->
<HR>
<CENTER>
<H2>
<B>インタフェース<br>org.apache.mina.handler.chain.IoHandlerCommand の使用</B></H2>
</CENTER>
<TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY="">
<TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor">
<TH ALIGN="left" COLSPAN="2"><FONT SIZE="+2">
<A HREF="../../../../../../org/apache/mina/handler/chain/IoHandlerCommand.html" title="org.apache.mina.handler.chain 内のインタフェース">IoHandlerCommand</A> を使用しているパッケージ</FONT></TH>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD><A HREF="#org.apache.mina.handler.chain"><B>org.apache.mina.handler.chain</B></A></TD>
<TD>Chains of Responsibility パターンを使って、階層化されたプロトコルを順番に実装するのを支援するハンドラ実装です。 </TD>
</TR>
</TABLE>
<P>
<A NAME="org.apache.mina.handler.chain"><!-- --></A>
<TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY="">
<TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor">
<TH ALIGN="left" COLSPAN="2"><FONT SIZE="+2">
<A HREF="../../../../../../org/apache/mina/handler/chain/package-summary.html">org.apache.mina.handler.chain</A> での <A HREF="../../../../../../org/apache/mina/handler/chain/IoHandlerCommand.html" title="org.apache.mina.handler.chain 内のインタフェース">IoHandlerCommand</A> の使用</FONT></TH>
</TR>
</TABLE>
<P>
<TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY="">
<TR BGCOLOR="#CCCCFF" CLASS="TableSubHeadingColor">
<TH ALIGN="left" COLSPAN="2"><A HREF="../../../../../../org/apache/mina/handler/chain/IoHandlerCommand.html" title="org.apache.mina.handler.chain 内のインタフェース">IoHandlerCommand</A> を実装している <A HREF="../../../../../../org/apache/mina/handler/chain/package-summary.html">org.apache.mina.handler.chain</A> のクラス</FONT></TH>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE> class</CODE></FONT></TD>
<TD><CODE><B><A HREF="../../../../../../org/apache/mina/handler/chain/IoHandlerChain.html" title="org.apache.mina.handler.chain 内のクラス">IoHandlerChain</A></B></CODE>
<BR>
A chain of <A HREF="../../../../../../org/apache/mina/handler/chain/IoHandlerCommand.html" title="org.apache.mina.handler.chain 内のインタフェース"><CODE>IoHandlerCommand</CODE></A>s.</TD>
</TR>
</TABLE>
<P>
<TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY="">
<TR BGCOLOR="#CCCCFF" CLASS="TableSubHeadingColor">
<TH ALIGN="left" COLSPAN="2"><A HREF="../../../../../../org/apache/mina/handler/chain/IoHandlerCommand.html" title="org.apache.mina.handler.chain 内のインタフェース">IoHandlerCommand</A> を返す <A HREF="../../../../../../org/apache/mina/handler/chain/package-summary.html">org.apache.mina.handler.chain</A> のメソッド</FONT></TH>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE> <A HREF="../../../../../../org/apache/mina/handler/chain/IoHandlerCommand.html" title="org.apache.mina.handler.chain 内のインタフェース">IoHandlerCommand</A></CODE></FONT></TD>
<TD><CODE><B>IoHandlerChain.</B><B><A HREF="../../../../../../org/apache/mina/handler/chain/IoHandlerChain.html#get(java.lang.String)">get</A></B>(java.lang.String name)</CODE>
<BR>
</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE> <A HREF="../../../../../../org/apache/mina/handler/chain/IoHandlerCommand.html" title="org.apache.mina.handler.chain 内のインタフェース">IoHandlerCommand</A></CODE></FONT></TD>
<TD><CODE><B>IoHandlerChain.Entry.</B><B><A HREF="../../../../../../org/apache/mina/handler/chain/IoHandlerChain.Entry.html#getCommand()">getCommand</A></B>()</CODE>
<BR>
Returns the command.</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE> <A HREF="../../../../../../org/apache/mina/handler/chain/IoHandlerCommand.html" title="org.apache.mina.handler.chain 内のインタフェース">IoHandlerCommand</A></CODE></FONT></TD>
<TD><CODE><B>IoHandlerChain.</B><B><A HREF="../../../../../../org/apache/mina/handler/chain/IoHandlerChain.html#remove(java.lang.String)">remove</A></B>(java.lang.String name)</CODE>
<BR>
</TD>
</TR>
</TABLE>
<P>
<TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY="">
<TR BGCOLOR="#CCCCFF" CLASS="TableSubHeadingColor">
<TH ALIGN="left" COLSPAN="2"><A HREF="../../../../../../org/apache/mina/handler/chain/IoHandlerCommand.html" title="org.apache.mina.handler.chain 内のインタフェース">IoHandlerCommand</A> 型のパラメータを持つ <A HREF="../../../../../../org/apache/mina/handler/chain/package-summary.html">org.apache.mina.handler.chain</A> のメソッド</FONT></TH>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE> void</CODE></FONT></TD>
<TD><CODE><B>IoHandlerChain.</B><B><A HREF="../../../../../../org/apache/mina/handler/chain/IoHandlerChain.html#addAfter(java.lang.String, java.lang.String, org.apache.mina.handler.chain.IoHandlerCommand)">addAfter</A></B>(java.lang.String baseName,
java.lang.String name,
<A HREF="../../../../../../org/apache/mina/handler/chain/IoHandlerCommand.html" title="org.apache.mina.handler.chain 内のインタフェース">IoHandlerCommand</A> command)</CODE>
<BR>
</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>IoHandlerChain.</B><B><A HREF="../../../../../../org/apache/mina/handler/chain/IoHandlerChain.html#addBefore(java.lang.String, java.lang.String, org.apache.mina.handler.chain.IoHandlerCommand)">addBefore</A></B>(java.lang.String baseName,
java.lang.String name,
<A HREF="../../../../../../org/apache/mina/handler/chain/IoHandlerCommand.html" title="org.apache.mina.handler.chain 内のインタフェース">IoHandlerCommand</A> command)</CODE>
<BR>
</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>IoHandlerChain.</B><B><A HREF="../../../../../../org/apache/mina/handler/chain/IoHandlerChain.html#addFirst(java.lang.String, org.apache.mina.handler.chain.IoHandlerCommand)">addFirst</A></B>(java.lang.String name,
<A HREF="../../../../../../org/apache/mina/handler/chain/IoHandlerCommand.html" title="org.apache.mina.handler.chain 内のインタフェース">IoHandlerCommand</A> command)</CODE>
<BR>
</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>IoHandlerChain.</B><B><A HREF="../../../../../../org/apache/mina/handler/chain/IoHandlerChain.html#addLast(java.lang.String, org.apache.mina.handler.chain.IoHandlerCommand)">addLast</A></B>(java.lang.String name,
<A HREF="../../../../../../org/apache/mina/handler/chain/IoHandlerCommand.html" title="org.apache.mina.handler.chain 内のインタフェース">IoHandlerCommand</A> command)</CODE>
<BR>
</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE> boolean</CODE></FONT></TD>
<TD><CODE><B>IoHandlerChain.</B><B><A HREF="../../../../../../org/apache/mina/handler/chain/IoHandlerChain.html#contains(org.apache.mina.handler.chain.IoHandlerCommand)">contains</A></B>(<A HREF="../../../../../../org/apache/mina/handler/chain/IoHandlerCommand.html" title="org.apache.mina.handler.chain 内のインタフェース">IoHandlerCommand</A> command)</CODE>
<BR>
</TD>
</TR>
</TABLE>
<P>
<TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY="">
<TR BGCOLOR="#CCCCFF" CLASS="TableSubHeadingColor">
<TH ALIGN="left" COLSPAN="2"><A HREF="../../../../../../org/apache/mina/handler/chain/IoHandlerCommand.html" title="org.apache.mina.handler.chain 内のインタフェース">IoHandlerCommand</A> 型の型引数を持つ <A HREF="../../../../../../org/apache/mina/handler/chain/package-summary.html">org.apache.mina.handler.chain</A> のメソッドパラメータ</FONT></TH>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE> boolean</CODE></FONT></TD>
<TD><CODE><B>IoHandlerChain.</B><B><A HREF="../../../../../../org/apache/mina/handler/chain/IoHandlerChain.html#contains(java.lang.Class)">contains</A></B>(java.lang.Class<? extends <A HREF="../../../../../../org/apache/mina/handler/chain/IoHandlerCommand.html" title="org.apache.mina.handler.chain 内のインタフェース">IoHandlerCommand</A>> commandType)</CODE>
<BR>
</TD>
</TR>
</TABLE>
<P>
<HR>
<!-- ======= START OF BOTTOM NAVBAR ====== -->
<A NAME="navbar_bottom"><!-- --></A>
<A HREF="#skip-navbar_bottom" title="ナビゲーションリンクをスキップ"></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>概要</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../package-summary.html"><FONT CLASS="NavBarFont1"><B>パッケージ</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../org/apache/mina/handler/chain/IoHandlerCommand.html" title="org.apache.mina.handler.chain 内のインタフェース"><FONT CLASS="NavBarFont1"><B>クラス</B></FONT></A> </TD>
<TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> <FONT CLASS="NavBarFont1Rev"><B>使用</B></FONT> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../package-tree.html"><FONT CLASS="NavBarFont1"><B>階層ツリー</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>非推奨 API</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../index-all.html"><FONT CLASS="NavBarFont1"><B>索引</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../help-doc.html"><FONT CLASS="NavBarFont1"><B>ヘルプ</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">
前
次</FONT></TD>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
<A HREF="../../../../../../index.html?org/apache/mina/handler/chain//class-useIoHandlerCommand.html" target="_top"><B>フレームあり</B></A>
<A HREF="IoHandlerCommand.html" target="_top"><B>フレームなし</B></A>
<SCRIPT type="text/javascript">
<!--
if(window==top) {
document.writeln('<A HREF="../../../../../../allclasses-noframe.html"><B>すべてのクラス</B></A>');
}
//-->
</SCRIPT>
<NOSCRIPT>
<A HREF="../../../../../../allclasses-noframe.html"><B>すべてのクラス</B></A>
</NOSCRIPT>
</FONT></TD>
</TR>
</TABLE>
<A NAME="skip-navbar_bottom"></A>
<!-- ======== END OF BOTTOM NAVBAR ======= -->
<HR>
Copyright © 2004-2010 <a href="http://mina.apache.org/">Apache MINA Project</a>. All Rights Reserved.
</BODY>
</HTML>
| {
"content_hash": "2aef64f691f99fb9b1b2a7bba157999f",
"timestamp": "",
"source": "github",
"line_count": 283,
"max_line_length": 362,
"avg_line_length": 53.60424028268551,
"alnum_prop": 0.6484508899143046,
"repo_name": "sardine/mina-ja",
"id": "14686ca70950296b01ea5153ee4f5b7e929a2aba",
"size": "16060",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "docs/apidocs/org/apache/mina/handler/chain/class-use/IoHandlerCommand.html",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Java",
"bytes": "2917667"
}
],
"symlink_target": ""
} |
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" type="text/css" href="../stylesheets/blog-stylesheet.css">
<title>Integrity and Openness</title>
<script>
(function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
})(window,document,'script','//www.google-analytics.com/analytics.js','ga');
ga('create', 'UA-54343932-1', 'auto');
ga('send', 'pageview');
</script>
</head>
<body>
<aside>
<div class="wrapper">
<div class="group" id="profile">
<img src="../imgs/stefano-schiavi_r.png">
<h2>Stefano Schiavi</h2>
</div>
<nav class="group">
<ul>
<li><a href="/about-me.html">About Me</a></li>
<li><a href="/blog-posts/">Blog</a></li>
<li><a href="/projects/">Projects</a></li>
<li><a href="/contact.html">Contact</a></li>
</ul>
</nav>
<p>
Passionate explorer of life interested in creating great solutions with the use of code & technology to contribute to the world<br>
I am deeply inspired and motivated by <a href="http://www.balancedview.org">Balanced View</a>
</p>
<div class="group" id="social-profiles">
<a href="https://github.com/stefanosc"><img src="../imgs/GitHub-Mark.png"></a>
<a href="https://www.facebook.com/stefanoschiavi"><img src="../imgs/fb-Logo_blue.png"></a>
<a href="https://www.linkedin.com/profile/view?id=257399430"><img src="../imgs/LinkedIn.png"></a>
<a href="https://twitter.com/stefanoschiavi"><img src="../imgs/Twitter_logo_blue.png"></a>
</div>
</div>
</aside>
<section id="content">
<article>
<div class="group title">
<h1>Integrity and Openness</h1>
<p class="date">Oct 12th, 2014</p>
</div>
<div class="content-body">
<p>
I thought I'd write a few words regarding some of the values that have shaped up to be the key values in all my relationships and for very good reason.
</p>
<p>
If I look back in my life I notice how I have gone through many lessons, where I made mistakes, I learned, I did things I am proud of, I nurtured great relationships, and I broke others (and others were broken).
We can all state the above, it's surely part of life. What I find incredible and at times unintuitive is that in all these experiences integrity and openness where always among the top 3 qualities / aspects that supported me the most and enabled me to make the best of any circumstance.
</p>
<p>
The most powerful and most beneficial circumstances were when openness and integrity were somewhat unintuitive. When it felt that being completely open was "dangerous" for example, or uncomfortable to say the least, allowing myself to open up and relate to others with no goal and objectives, simply considering how to be of best support turned out to be a transformative experience where everyone involved felt completely respected, supported and appreciated.
</p>
<p>
When I think of integrity I think of 2 main circumstances:
</p>
<ul>
<li>honoring a commitment</li>
<li>being unable to honor a commitment</li>
</ul>
<p>
Again, I consider the most rewarding experience the one that felt somewhat not so pleasant in some way, at least initially.
Nobody likes to not honor a commitment and some times there are serious consequences to this. But even when there are no obvious consequences the most important aspect to me has been to learn that as a human being I make mistakes, we all do at times. In this the key is to take responsibility for my action and make amends when my actions affect others causing issues.
</p>
<p>
It takes courage to do this and it's a great muscle to exercise, being willing to go where it doesn't seem to feel good if necessary and notice how making integrity and openness the basis of the relationship I build has contributed greatly in my life.
</p>
<p>
As I wrote above I do make mistakes from time to time and these are key circumstances where I can learn and grow in my ability to be the very best I can be.
</p>
</div>
</article>
</section>
</body>
</html> | {
"content_hash": "d361b4d084b0d90ae7f99f3957a17b25",
"timestamp": "",
"source": "github",
"line_count": 83,
"max_line_length": 470,
"avg_line_length": 54.21686746987952,
"alnum_prop": 0.6513333333333333,
"repo_name": "stefanosc/stefanosc.github.io",
"id": "27a04cef4e7b960eb569ff4609237f466848f069",
"size": "4500",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "blog-posts/week7_cultural.html",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "9577"
}
],
"symlink_target": ""
} |
[](https://waffle.io/guaka/radio-meteor)
radio-meteor
============
**Radio Meteor** is an Internet Radio player based on HTML5 and
[Meteor](http://meteor.com). Currently there are only [ad-free](http://moneyless.org/tags/advertising) radio
stations, such as SomaFM and Radio Paradise. There is a plan to allow
anyone to add their favorite streams.
There was a buggy Android app. There may be a working one again in the future.
It's playing at [radio.meteor.com](http://radio.meteor.com/).
## Channels
[Here are the channels](https://github.com/guaka/radio-meteor/blob/master/channels.coffee.md).
You're welcome to add channels and metadata by editting (i.e. fork and send pull requests).
## Background
Radio Meteor was inspired by [somafm-popup](https://github.com/joe-roth/somafm-popup) and the need for
a nice way to play Soma.fm streams, [Radio Paradise](http://www.radioparadise.com/), [Radio Fip](http://www.fipradio.fr/) and more.
It's not really excellent but it does the job. [guaka](http://twitter.com/guaka) is quite happy with it.
Links
-----
* [radio.meteor.com](http://radio.meteor.com/)
* [Mozilla Dev resources](https://developer.mozilla.org/en-US/docs/DOM/HTMLMediaElement)
| {
"content_hash": "7c4810f3d6c8d6360081f0cf58098448",
"timestamp": "",
"source": "github",
"line_count": 33,
"max_line_length": 131,
"avg_line_length": 39.303030303030305,
"alnum_prop": 0.7370855821125675,
"repo_name": "simison/radio-meteor",
"id": "6590e11a400d6bed0f37bad8ba300d25bb1e34a2",
"size": "1297",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "README.md",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "390"
},
{
"name": "CoffeeScript",
"bytes": "3672"
},
{
"name": "HTML",
"bytes": "3482"
},
{
"name": "JavaScript",
"bytes": "40281"
}
],
"symlink_target": ""
} |
#ifndef _CK_SPINLOCK_HCLH_H
#define _CK_SPINLOCK_HCLH_H
#include <ck_cc.h>
#include <ck_pr.h>
#include <stdbool.h>
#include <stddef.h>
#ifndef CK_F_SPINLOCK_HCLH
#define CK_F_SPINLOCK_HCLH
struct ck_spinlock_hclh {
unsigned int wait;
unsigned int splice;
int cluster_id;
struct ck_spinlock_hclh *previous;
};
typedef struct ck_spinlock_hclh ck_spinlock_hclh_t;
CK_CC_INLINE static void
ck_spinlock_hclh_init(struct ck_spinlock_hclh **lock,
struct ck_spinlock_hclh *unowned,
int cluster_id)
{
unowned->previous = NULL;
unowned->wait = false;
unowned->splice = false;
unowned->cluster_id = cluster_id;
*lock = unowned;
ck_pr_barrier();
return;
}
CK_CC_INLINE static bool
ck_spinlock_hclh_locked(struct ck_spinlock_hclh **queue)
{
struct ck_spinlock_hclh *head;
ck_pr_fence_load();
head = ck_pr_load_ptr(queue);
ck_pr_fence_load();
return ck_pr_load_uint(&head->wait);
}
CK_CC_INLINE static void
ck_spinlock_hclh_lock(struct ck_spinlock_hclh **glob_queue,
struct ck_spinlock_hclh **local_queue,
struct ck_spinlock_hclh *thread)
{
struct ck_spinlock_hclh *previous, *local_tail;
/* Indicate to the next thread on queue that they will have to block. */
thread->wait = true;
thread->splice = false;
thread->cluster_id = (*local_queue)->cluster_id;
/* Serialize with respect to update of local queue. */
ck_pr_fence_store_atomic();
/* Mark current request as last request. Save reference to previous request. */
previous = ck_pr_fas_ptr(local_queue, thread);
thread->previous = previous;
/* Wait until previous thread from the local queue is done with lock. */
ck_pr_fence_load();
if (previous->previous != NULL &&
previous->cluster_id == thread->cluster_id) {
while (ck_pr_load_uint(&previous->wait) == true)
ck_pr_stall();
/* We're head of the global queue, we're done */
if (ck_pr_load_uint(&previous->splice) == false)
return;
}
/* Now we need to splice the local queue into the global queue. */
local_tail = ck_pr_load_ptr(local_queue);
previous = ck_pr_fas_ptr(glob_queue, local_tail);
ck_pr_store_uint(&local_tail->splice, true);
/* Wait until previous thread from the global queue is done with lock. */
while (ck_pr_load_uint(&previous->wait) == true)
ck_pr_stall();
ck_pr_fence_load();
return;
}
CK_CC_INLINE static void
ck_spinlock_hclh_unlock(struct ck_spinlock_hclh **thread)
{
struct ck_spinlock_hclh *previous;
/*
* If there are waiters, they are spinning on the current node wait
* flag. The flag is cleared so that the successor may complete an
* acquisition. If the caller is pre-empted then the predecessor field
* may be updated by a successor's lock operation. In order to avoid
* this, save a copy of the predecessor before setting the flag.
*/
previous = thread[0]->previous;
/* We have to pay this cost anyways, use it as a compiler barrier too. */
ck_pr_fence_release();
ck_pr_store_uint(&(*thread)->wait, false);
/*
* Predecessor is guaranteed not to be spinning on previous request,
* so update caller to use previous structure. This allows successor
* all the time in the world to successfully read updated wait flag.
*/
*thread = previous;
return;
}
#endif /* CK_F_SPINLOCK_HCLH */
#endif /* _CK_SPINLOCK_HCLH_H */
| {
"content_hash": "03dc5c6a6feb39f7d3e646c2e80b37de",
"timestamp": "",
"source": "github",
"line_count": 120,
"max_line_length": 80,
"avg_line_length": 27.183333333333334,
"alnum_prop": 0.700797057020233,
"repo_name": "GregBowyer/softheap",
"id": "edaeacaa3c1925d56645a69515aefe1e36d3a6b5",
"size": "4657",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "ck/include/spinlock/hclh.h",
"mode": "33188",
"license": "bsd-2-clause",
"language": [
{
"name": "C",
"bytes": "1291199"
},
{
"name": "C++",
"bytes": "84008"
},
{
"name": "Makefile",
"bytes": "33011"
},
{
"name": "Python",
"bytes": "6557"
},
{
"name": "Shell",
"bytes": "282"
}
],
"symlink_target": ""
} |
require "active_record/attribute_methods"
module ActiveRecord
module ConnectionAdapters
module SQLServer
module CoreExt
module AttributeMethods
private
def attributes_for_update(attribute_names)
return super unless self.class.connection.adapter_name == "SQLServer"
super.reject do |name|
column = self.class.columns_hash[name]
column && column.respond_to?(:is_identity?) && column.is_identity?
end
end
end
end
end
end
end
ActiveSupport.on_load(:active_record) do
include ActiveRecord::ConnectionAdapters::SQLServer::CoreExt::AttributeMethods
end
| {
"content_hash": "26a0ea2829ef7dbcb3ddbe2c1f22daeb",
"timestamp": "",
"source": "github",
"line_count": 26,
"max_line_length": 81,
"avg_line_length": 26.384615384615383,
"alnum_prop": 0.6501457725947521,
"repo_name": "rails-sqlserver/activerecord-sqlserver-adapter",
"id": "af0e6a4e70b315f65e5c4677d33f4905a3c6deb5",
"size": "717",
"binary": false,
"copies": "1",
"ref": "refs/heads/main",
"path": "lib/active_record/connection_adapters/sqlserver/core_ext/attribute_methods.rb",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "PowerShell",
"bytes": "1006"
},
{
"name": "Ruby",
"bytes": "403591"
},
{
"name": "Shell",
"bytes": "1183"
},
{
"name": "TSQL",
"bytes": "3375"
}
],
"symlink_target": ""
} |
package com.vatril.fluffy.bot.annotation;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
@Retention(RetentionPolicy.RUNTIME)
public @interface SelfAction {
public int value() default 0;
} | {
"content_hash": "4f0acc7b65d25fe9dcb0941e064701df",
"timestamp": "",
"source": "github",
"line_count": 10,
"max_line_length": 44,
"avg_line_length": 22.8,
"alnum_prop": 0.8114035087719298,
"repo_name": "Vatril/FluffyBot2.0",
"id": "97c6db07b98de9051176a018a6643fe918b90a52",
"size": "228",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/main/java/com/vatril/fluffy/bot/annotation/SelfAction.java",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "194"
},
{
"name": "HTML",
"bytes": "1602"
},
{
"name": "Java",
"bytes": "39011"
},
{
"name": "JavaScript",
"bytes": "1053"
}
],
"symlink_target": ""
} |
#ifndef FEBlend_h
#define FEBlend_h
#include "platform/graphics/filters/FilterEffect.h"
#include "public/platform/WebBlendMode.h"
namespace blink {
class PLATFORM_EXPORT FEBlend final : public FilterEffect {
public:
static FEBlend* create(Filter*, WebBlendMode);
WebBlendMode blendMode() const;
bool setBlendMode(WebBlendMode);
TextStream& externalRepresentation(TextStream&, int indention) const override;
private:
FEBlend(Filter*, WebBlendMode);
PassRefPtr<SkImageFilter> createImageFilter(SkiaImageFilterBuilder&) override;
WebBlendMode m_mode;
};
} // namespace blink
#endif // FEBlend_h
| {
"content_hash": "7ef5305a170990acc3b566a40cddf358",
"timestamp": "",
"source": "github",
"line_count": 30,
"max_line_length": 82,
"avg_line_length": 21.066666666666666,
"alnum_prop": 0.7563291139240507,
"repo_name": "was4444/chromium.src",
"id": "0ac88ab8d245a0a78cb6318131d495c360b9bcf8",
"size": "1652",
"binary": false,
"copies": "1",
"ref": "refs/heads/nw15",
"path": "third_party/WebKit/Source/platform/graphics/filters/FEBlend.h",
"mode": "33188",
"license": "bsd-3-clause",
"language": [],
"symlink_target": ""
} |
package org.team2168.utils;
import edu.wpi.first.wpilibj.Timer;
/**
* Compensates for "jumps" in analog signals sources.
*
* Original source from:
* https://github.com/Team254/FRC-2013/blob/master/src/com/team254/lib/util/Debouncer.java
*
* Modified to add comments and to auto-reset if update hasn't been called for
* longer than the timer period.
*
* @author tom@team254.com (Tom Bottiglieri)
* @author James
*/
public class Debouncer {
private Timer t = new Timer();
private double time;
private double lastUpdate = 0.0;
private boolean first = true;
/**
* The default constructor
* @param time positive duration (seconds) that the value needs to be
* maintained before returning true.
*/
public Debouncer(double time) {
if (time < 0.0) {
time = 0.0;
}
this.time = time;
}
/**
* This method should be called periodically with the boolean value
* under inspection. This method must be called periodically at a
* frequency greater than the time specified in the constructor.
* @param val the value to check.
* @return true if the value has held true for the duration
* specified in the constructor
*/
public boolean update(boolean val) {
if (first) {
first = false;
t.start();
}
if (!val || (t.get() - lastUpdate) >= time) {
t.reset();
}
lastUpdate = t.get();
return t.get() > time;
}
/**
* Reset the timer.
*/
public void reset() {
t.reset();
lastUpdate = t.get();
}
} | {
"content_hash": "9a64eb5027085540663c30b6a759cb13",
"timestamp": "",
"source": "github",
"line_count": 64,
"max_line_length": 90,
"avg_line_length": 23.140625,
"alnum_prop": 0.6617150573936529,
"repo_name": "Team2168/FRC2014_Main_Robot",
"id": "d5bf1afa038ccfb020004f40c2068d48035d2809",
"size": "1481",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/org/team2168/utils/Debouncer.java",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "Java",
"bytes": "276890"
}
],
"symlink_target": ""
} |
CREATE TABLE person (
id INTEGER PRIMARY KEY,
first_name TEXT,
last_name Text,
age INTEGER
);
| {
"content_hash": "78c1838b658186edc10dd515ee8502a3",
"timestamp": "",
"source": "github",
"line_count": 6,
"max_line_length": 35,
"avg_line_length": 21,
"alnum_prop": 0.5634920634920635,
"repo_name": "nfiles/Learn_SQL_The_Hard_Way",
"id": "c619a03700f6fc261818a9100a076b3cd3f1d899",
"size": "210",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "exercises/exercise01.sql",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Shell",
"bytes": "600"
}
],
"symlink_target": ""
} |
<?xml version="1.0" encoding="UTF-8"?>
<persistence xmlns="http://java.sun.com/xml/ns/persistence" version="2.0">
<persistence-unit name="MicPersistenceUnit">
<provider>org.hibernate.jpa.HibernatePersistenceProvider</provider>
<class>com.fpt.mic.micweb.model.entity.AccidentEntity</class>
<class>com.fpt.mic.micweb.model.entity.CardInstanceEntity</class>
<class>com.fpt.mic.micweb.model.entity.CardAccessLogEntity</class>
<class>com.fpt.mic.micweb.model.entity.CompensationEntity</class>
<class>com.fpt.mic.micweb.model.entity.ContractEntity</class>
<class>com.fpt.mic.micweb.model.entity.ContractTypeEntity</class>
<class>com.fpt.mic.micweb.model.entity.CustomerEntity</class>
<class>com.fpt.mic.micweb.model.entity.NewCardRequestEntity</class>
<class>com.fpt.mic.micweb.model.entity.PaymentEntity</class>
<class>com.fpt.mic.micweb.model.entity.PunishmentEntity</class>
<class>com.fpt.mic.micweb.model.entity.StaffEntity</class>
<class>com.fpt.mic.micweb.model.entity.helper.IncrementsEntity</class>
<class>com.fpt.mic.micweb.model.entity.helper.NotificationEntity</class>
<class>com.fpt.mic.micweb.model.entity.helper.NotificationReadEntity</class>
<class>com.fpt.mic.micweb.model.entity.CardEntity</class>
<properties>
<property name="hibernate.connection.url" value="${db.connectionURL}/mic_data?useEncoding=true&characterEncoding=UTF-8" />
<property name="hibernate.connection.driver_class" value="com.mysql.jdbc.Driver" />
<property name="hibernate.connection.username" value="${db.username}" />
<property name="hibernate.connection.password" value="${db.password}" />
<property name="hibernate.archive.autodetection" value="class" />
<property name="hibernate.show_sql" value="false" />
<property name="hibernate.format_sql" value="false" />
<property name="hbm2ddl.auto" value="update" />
</properties>
</persistence-unit>
</persistence>
| {
"content_hash": "8a2b3b90a0afa63616867d4d99538768",
"timestamp": "",
"source": "github",
"line_count": 33,
"max_line_length": 138,
"avg_line_length": 63.63636363636363,
"alnum_prop": 0.6933333333333334,
"repo_name": "trungdq88/insurance-card",
"id": "70624ef9b123b0a68df9f1a59ae8dd75aa12f7c1",
"size": "2100",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "Source code/MICWeb/src/main/resources/META-INF/persistence.xml",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "242281"
},
{
"name": "HTML",
"bytes": "416170"
},
{
"name": "Java",
"bytes": "1844256"
},
{
"name": "JavaScript",
"bytes": "803794"
}
],
"symlink_target": ""
} |
require 'test_helper'
class LinksControllerTest < ActionController::TestCase
test "should get index" do
get :index
assert_response :success
assert_not_nil assigns(:links)
end
test "should get new" do
get :new
assert_response :success
end
test "should create link" do
assert_difference('Link.count') do
post :create, link: { }
end
assert_redirected_to link_path(assigns(:link))
end
test "should show link" do
get :show, id: links(:one).to_param
assert_response :success
end
test "should get edit" do
get :edit, id: links(:one).to_param
assert_response :success
end
test "should update link" do
put :update, id: links(:one).to_param, link: { }
assert_redirected_to link_path(assigns(:link))
end
test "should destroy link" do
assert_difference('Link.count', -1) do
delete :destroy, id: links(:one).to_param
end
assert_redirected_to links_path
end
end
| {
"content_hash": "be20a2efe946b3a173bed6e7ba9a35d2",
"timestamp": "",
"source": "github",
"line_count": 45,
"max_line_length": 54,
"avg_line_length": 21.444444444444443,
"alnum_prop": 0.6621761658031088,
"repo_name": "YaleSTC/shifts",
"id": "6e303df81ba6918180b75385a353509ffb69a44d",
"size": "965",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "test/functional/links_controller_test.rb",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "55115"
},
{
"name": "CoffeeScript",
"bytes": "840"
},
{
"name": "Cucumber",
"bytes": "68733"
},
{
"name": "HTML",
"bytes": "377152"
},
{
"name": "JavaScript",
"bytes": "30596"
},
{
"name": "Ruby",
"bytes": "708464"
}
],
"symlink_target": ""
} |
package com.hazelcast.topic.impl.reliable;
import com.hazelcast.config.Config;
import com.hazelcast.config.ReliableTopicConfig;
import com.hazelcast.config.RingbufferConfig;
import com.hazelcast.core.HazelcastInstance;
import com.hazelcast.test.HazelcastParallelClassRunner;
import com.hazelcast.test.annotation.ParallelJVMTest;
import com.hazelcast.test.annotation.QuickTest;
import com.hazelcast.topic.TopicOverloadPolicy;
import org.junit.Before;
import org.junit.experimental.categories.Category;
import org.junit.runner.RunWith;
import static com.hazelcast.test.AbstractHazelcastClassRunner.getTestMethodName;
import static com.hazelcast.test.Accessors.getSerializationService;
@RunWith(HazelcastParallelClassRunner.class)
@Category({QuickTest.class, ParallelJVMTest.class})
public class TopicOverloadDistributedTest extends TopicOverloadAbstractTest {
@Before
public void setupCluster() {
Config config = new Config();
config.addRingBufferConfig(new RingbufferConfig("when*")
.setCapacity(100).setTimeToLiveSeconds(Integer.MAX_VALUE));
config.addReliableTopicConfig(new ReliableTopicConfig("whenError_*")
.setTopicOverloadPolicy(TopicOverloadPolicy.ERROR));
config.addReliableTopicConfig(new ReliableTopicConfig("whenDiscardOldest_*")
.setTopicOverloadPolicy(TopicOverloadPolicy.DISCARD_OLDEST));
config.addReliableTopicConfig(new ReliableTopicConfig("whenDiscardNewest_*")
.setTopicOverloadPolicy(TopicOverloadPolicy.DISCARD_NEWEST));
config.addReliableTopicConfig(new ReliableTopicConfig("whenBlock_*")
.setTopicOverloadPolicy(TopicOverloadPolicy.BLOCK));
HazelcastInstance[] hazelcastInstances = createHazelcastInstanceFactory(2).newInstances(config);
HazelcastInstance hz = hazelcastInstances[0];
warmUpPartitions(hazelcastInstances);
serializationService = getSerializationService(hz);
String topicName = getTestMethodName();
topic = hz.<String>getReliableTopic(topicName);
ringbuffer = ((ReliableTopicProxy<String>) topic).ringbuffer;
}
}
| {
"content_hash": "9435b34b18521b918145a9f5dc6405a0",
"timestamp": "",
"source": "github",
"line_count": 49,
"max_line_length": 104,
"avg_line_length": 44.02040816326531,
"alnum_prop": 0.770978210477515,
"repo_name": "mesutcelik/hazelcast",
"id": "a01e036461c8190e5a8717e7cd5d127084587614",
"size": "2782",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "hazelcast/src/test/java/com/hazelcast/topic/impl/reliable/TopicOverloadDistributedTest.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Batchfile",
"bytes": "1261"
},
{
"name": "C",
"bytes": "353"
},
{
"name": "Java",
"bytes": "39634706"
},
{
"name": "Shell",
"bytes": "29479"
}
],
"symlink_target": ""
} |
#include "config.h"
#include "bindings/core/v8/ArrayValue.h"
#include "bindings/core/v8/DictionaryHelperForBindings.h"
#include "bindings/core/v8/ExceptionMessages.h"
#include "bindings/core/v8/ExceptionState.h"
#include "bindings/core/v8/V8ArrayBufferView.h"
#include "bindings/core/v8/V8Binding.h"
#include "bindings/core/v8/V8DOMError.h"
#include "bindings/core/v8/V8Element.h"
#include "bindings/core/v8/V8EventTarget.h"
#include "bindings/core/v8/V8MediaKeyError.h"
#include "bindings/core/v8/V8MessagePort.h"
#include "bindings/core/v8/V8TextTrack.h"
#include "bindings/core/v8/V8Uint8Array.h"
#include "bindings/core/v8/V8VoidCallback.h"
#include "bindings/core/v8/V8Window.h"
#include "core/html/track/TrackBase.h"
#include "wtf/MathExtras.h"
namespace blink {
template <>
CORE_EXPORT bool DictionaryHelper::get(const Dictionary& dictionary, const String& key, v8::Local<v8::Value>& value)
{
return dictionary.get(key, value);
}
template <>
CORE_EXPORT bool DictionaryHelper::get(const Dictionary& dictionary, const String& key, Dictionary& value)
{
return dictionary.get(key, value);
}
template <>
CORE_EXPORT bool DictionaryHelper::get(const Dictionary& dictionary, const String& key, bool& value)
{
v8::Local<v8::Value> v8Value;
if (!dictionary.get(key, v8Value))
return false;
return v8Call(v8Value->BooleanValue(dictionary.v8Context()), value);
}
template <>
CORE_EXPORT bool DictionaryHelper::get(const Dictionary& dictionary, const String& key, int32_t& value)
{
v8::Local<v8::Value> v8Value;
if (!dictionary.get(key, v8Value))
return false;
return v8Call(v8Value->Int32Value(dictionary.v8Context()), value);
}
template <>
CORE_EXPORT bool DictionaryHelper::get(const Dictionary& dictionary, const String& key, double& value, bool& hasValue)
{
v8::Local<v8::Value> v8Value;
if (!dictionary.get(key, v8Value)) {
hasValue = false;
return false;
}
hasValue = true;
return v8Call(v8Value->NumberValue(dictionary.v8Context()), value);
}
template <>
bool DictionaryHelper::get(const Dictionary& dictionary, const String& key, double& value)
{
bool unused;
return DictionaryHelper::get(dictionary, key, value, unused);
}
template<typename StringType>
bool getStringType(const Dictionary& dictionary, const String& key, StringType& value)
{
v8::Local<v8::Value> v8Value;
if (!dictionary.get(key, v8Value))
return false;
V8StringResource<> stringValue(v8Value);
if (!stringValue.prepare())
return false;
value = stringValue;
return true;
}
template <>
CORE_EXPORT bool DictionaryHelper::get(const Dictionary& dictionary, const String& key, String& value)
{
return getStringType(dictionary, key, value);
}
template <>
CORE_EXPORT bool DictionaryHelper::get(const Dictionary& dictionary, const String& key, AtomicString& value)
{
return getStringType(dictionary, key, value);
}
template <>
bool DictionaryHelper::get(const Dictionary& dictionary, const String& key, ScriptValue& value)
{
v8::Local<v8::Value> v8Value;
if (!dictionary.get(key, v8Value))
return false;
value = ScriptValue(ScriptState::current(dictionary.isolate()), v8Value);
return true;
}
template<typename NumericType>
bool getNumericType(const Dictionary& dictionary, const String& key, NumericType& value)
{
int32_t int32Value;
if (!DictionaryHelper::get(dictionary, key, int32Value))
return false;
value = static_cast<NumericType>(int32Value);
return true;
}
template <>
bool DictionaryHelper::get(const Dictionary& dictionary, const String& key, short& value)
{
return getNumericType<short>(dictionary, key, value);
}
template <>
CORE_EXPORT bool DictionaryHelper::get(const Dictionary& dictionary, const String& key, unsigned short& value)
{
return getNumericType<unsigned short>(dictionary, key, value);
}
template <>
bool DictionaryHelper::get(const Dictionary& dictionary, const String& key, unsigned& value)
{
return getNumericType<unsigned>(dictionary, key, value);
}
template <>
bool DictionaryHelper::get(const Dictionary& dictionary, const String& key, unsigned long& value)
{
v8::Local<v8::Value> v8Value;
if (!dictionary.get(key, v8Value))
return false;
int64_t int64Value;
if (!v8Call(v8Value->IntegerValue(dictionary.v8Context()), int64Value))
return false;
value = int64Value;
return true;
}
template <>
bool DictionaryHelper::get(const Dictionary& dictionary, const String& key, unsigned long long& value)
{
v8::Local<v8::Value> v8Value;
if (!dictionary.get(key, v8Value))
return false;
double doubleValue;
if (!v8Call(v8Value->NumberValue(dictionary.v8Context()), doubleValue))
return false;
doubleToInteger(doubleValue, value);
return true;
}
template <>
bool DictionaryHelper::get(const Dictionary& dictionary, const String& key, RefPtrWillBeMember<DOMWindow>& value)
{
v8::Local<v8::Value> v8Value;
if (!dictionary.get(key, v8Value))
return false;
// We need to handle a DOMWindow specially, because a DOMWindow wrapper
// exists on a prototype chain of v8Value.
value = toDOMWindow(dictionary.isolate(), v8Value);
return true;
}
template <>
bool DictionaryHelper::get(const Dictionary& dictionary, const String& key, Member<TrackBase>& value)
{
v8::Local<v8::Value> v8Value;
if (!dictionary.get(key, v8Value))
return false;
TrackBase* source = 0;
if (v8Value->IsObject()) {
v8::Local<v8::Object> wrapper = v8::Local<v8::Object>::Cast(v8Value);
// FIXME: this will need to be changed so it can also return an AudioTrack or a VideoTrack once
// we add them.
v8::Local<v8::Object> track = V8TextTrack::findInstanceInPrototypeChain(wrapper, dictionary.isolate());
if (!track.IsEmpty())
source = V8TextTrack::toImpl(track);
}
value = source;
return true;
}
template <>
bool DictionaryHelper::get(const Dictionary& dictionary, const String& key, RefPtrWillBeMember<EventTarget>& value)
{
v8::Local<v8::Value> v8Value;
if (!dictionary.get(key, v8Value))
return false;
value = nullptr;
// We need to handle a DOMWindow specially, because a DOMWindow wrapper
// exists on a prototype chain of v8Value.
if (v8Value->IsObject()) {
v8::Local<v8::Object> wrapper = v8::Local<v8::Object>::Cast(v8Value);
v8::Local<v8::Object> window = V8Window::findInstanceInPrototypeChain(wrapper, dictionary.isolate());
if (!window.IsEmpty()) {
value = toWrapperTypeInfo(window)->toEventTarget(window);
return true;
}
}
if (V8DOMWrapper::isWrapper(dictionary.isolate(), v8Value)) {
v8::Local<v8::Object> wrapper = v8::Local<v8::Object>::Cast(v8Value);
value = toWrapperTypeInfo(wrapper)->toEventTarget(wrapper);
}
return true;
}
template <>
CORE_EXPORT bool DictionaryHelper::get(const Dictionary& dictionary, const String& key, Vector<String>& value)
{
v8::Local<v8::Value> v8Value;
if (!dictionary.get(key, v8Value))
return false;
if (!v8Value->IsArray())
return false;
v8::Local<v8::Array> v8Array = v8::Local<v8::Array>::Cast(v8Value);
for (size_t i = 0; i < v8Array->Length(); ++i) {
v8::Local<v8::Value> indexedValue;
if (!v8Array->Get(dictionary.v8Context(), v8::Uint32::New(dictionary.isolate(), i)).ToLocal(&indexedValue))
return false;
TOSTRING_DEFAULT(V8StringResource<>, stringValue, indexedValue, false);
value.append(stringValue);
}
return true;
}
template <>
CORE_EXPORT bool DictionaryHelper::get(const Dictionary& dictionary, const String& key, Vector<Vector<String>>& value, ExceptionState& exceptionState)
{
v8::Local<v8::Value> v8Value;
if (!dictionary.get(key, v8Value))
return false;
if (!v8Value->IsArray())
return false;
v8::Local<v8::Array> v8Array = v8::Local<v8::Array>::Cast(v8Value);
for (size_t i = 0; i < v8Array->Length(); ++i) {
v8::Local<v8::Value> v8IndexedValue;
if (!v8Array->Get(dictionary.v8Context(), v8::Uint32::New(dictionary.isolate(), i)).ToLocal(&v8IndexedValue))
return false;
Vector<String> indexedValue = toImplArray<Vector<String>>(v8IndexedValue, i, dictionary.isolate(), exceptionState);
if (exceptionState.hadException())
return false;
value.append(indexedValue);
}
return true;
}
template <>
CORE_EXPORT bool DictionaryHelper::get(const Dictionary& dictionary, const String& key, ArrayValue& value)
{
v8::Local<v8::Value> v8Value;
if (!dictionary.get(key, v8Value))
return false;
if (!v8Value->IsArray())
return false;
ASSERT(dictionary.isolate());
ASSERT(dictionary.isolate() == v8::Isolate::GetCurrent());
value = ArrayValue(v8::Local<v8::Array>::Cast(v8Value), dictionary.isolate());
return true;
}
template CORE_EXPORT bool DictionaryHelper::get(const Dictionary&, const String& key, RefPtr<DOMUint8Array>& value);
template <typename T>
struct IntegralTypeTraits {
};
template <>
struct IntegralTypeTraits<uint8_t> {
static inline uint8_t toIntegral(v8::Isolate* isolate, v8::Local<v8::Value> value, IntegerConversionConfiguration configuration, ExceptionState& exceptionState)
{
return toUInt8(isolate, value, configuration, exceptionState);
}
static const String typeName() { return "UInt8"; }
};
template <>
struct IntegralTypeTraits<int8_t> {
static inline int8_t toIntegral(v8::Isolate* isolate, v8::Local<v8::Value> value, IntegerConversionConfiguration configuration, ExceptionState& exceptionState)
{
return toInt8(isolate, value, configuration, exceptionState);
}
static const String typeName() { return "Int8"; }
};
template <>
struct IntegralTypeTraits<unsigned short> {
static inline uint16_t toIntegral(v8::Isolate* isolate, v8::Local<v8::Value> value, IntegerConversionConfiguration configuration, ExceptionState& exceptionState)
{
return toUInt16(isolate, value, configuration, exceptionState);
}
static const String typeName() { return "UInt16"; }
};
template <>
struct IntegralTypeTraits<short> {
static inline int16_t toIntegral(v8::Isolate* isolate, v8::Local<v8::Value> value, IntegerConversionConfiguration configuration, ExceptionState& exceptionState)
{
return toInt16(isolate, value, configuration, exceptionState);
}
static const String typeName() { return "Int16"; }
};
template <>
struct IntegralTypeTraits<unsigned> {
static inline uint32_t toIntegral(v8::Isolate* isolate, v8::Local<v8::Value> value, IntegerConversionConfiguration configuration, ExceptionState& exceptionState)
{
return toUInt32(isolate, value, configuration, exceptionState);
}
static const String typeName() { return "UInt32"; }
};
template <>
struct IntegralTypeTraits<unsigned long> {
static inline uint32_t toIntegral(v8::Isolate* isolate, v8::Local<v8::Value> value, IntegerConversionConfiguration configuration, ExceptionState& exceptionState)
{
return toUInt32(isolate, value, configuration, exceptionState);
}
static const String typeName() { return "UInt32"; }
};
template <>
struct IntegralTypeTraits<int> {
static inline int32_t toIntegral(v8::Isolate* isolate, v8::Local<v8::Value> value, IntegerConversionConfiguration configuration, ExceptionState& exceptionState)
{
return toInt32(isolate, value, configuration, exceptionState);
}
static const String typeName() { return "Int32"; }
};
template <>
struct IntegralTypeTraits<long> {
static inline int32_t toIntegral(v8::Isolate* isolate, v8::Local<v8::Value> value, IntegerConversionConfiguration configuration, ExceptionState& exceptionState)
{
return toInt32(isolate, value, configuration, exceptionState);
}
static const String typeName() { return "Int32"; }
};
template <>
struct IntegralTypeTraits<unsigned long long> {
static inline unsigned long long toIntegral(v8::Isolate* isolate, v8::Local<v8::Value> value, IntegerConversionConfiguration configuration, ExceptionState& exceptionState)
{
return toUInt64(isolate, value, configuration, exceptionState);
}
static const String typeName() { return "UInt64"; }
};
template <>
struct IntegralTypeTraits<long long> {
static inline long long toIntegral(v8::Isolate* isolate, v8::Local<v8::Value> value, IntegerConversionConfiguration configuration, ExceptionState& exceptionState)
{
return toInt64(isolate, value, configuration, exceptionState);
}
static const String typeName() { return "Int64"; }
};
} // namespace blink
| {
"content_hash": "d8b4f67857627b9266a3a33f3a9f904d",
"timestamp": "",
"source": "github",
"line_count": 388,
"max_line_length": 175,
"avg_line_length": 33.04381443298969,
"alnum_prop": 0.7032992746275641,
"repo_name": "Bysmyyr/chromium-crosswalk",
"id": "455f60404129a0b458370941758663ef9fb5e312",
"size": "14169",
"binary": false,
"copies": "5",
"ref": "refs/heads/master",
"path": "third_party/WebKit/Source/bindings/core/v8/DictionaryHelperForCore.cpp",
"mode": "33188",
"license": "bsd-3-clause",
"language": [],
"symlink_target": ""
} |
import pLimit from 'p-limit';
import _ from 'lodash';
import { DepGraph } from 'dependency-graph';
import { promisify } from 'util';
import strings from '../../resources';
import { Plugin } from '../../types';
function validatePlugins(plugins: unknown[]): asserts plugins is Plugin[] {
for (let idx = 0; idx < plugins.length; idx++) {
const plugin = plugins[idx];
if (
!_.isObject((plugin as Plugin).register) ||
typeof (plugin as Plugin).register.register !== 'function' ||
typeof (plugin as Plugin).register.execute !== 'function' ||
typeof (plugin as Plugin).name !== 'string'
) {
throw new Error(
strings.errors.registry.PLUGIN_NOT_VALID(
(plugin as Plugin).name || String(idx + 1)
)
);
}
}
}
function checkDependencies(plugins: Plugin[]) {
const graph = new DepGraph();
plugins.forEach(p => graph.addNode(p.name));
plugins.forEach(p => {
if (!p.register.dependencies) {
return;
}
p.register.dependencies.forEach(d => {
try {
graph.addDependency(p.name, d);
} catch (err) {
throw new Error(`unknown plugin dependency: ${d}`);
}
});
});
return graph.overallOrder();
}
let deferredLoads: Plugin[] = [];
type PluginFunctions = Record<string, (...args: unknown[]) => void>;
export async function init(
pluginsToRegister: unknown[]
): Promise<PluginFunctions> {
const registered: PluginFunctions = {};
validatePlugins(pluginsToRegister);
checkDependencies(pluginsToRegister);
const dependenciesRegistered = (dependencies: string[]) => {
if (dependencies.length === 0) {
return true;
}
let present = true;
dependencies.forEach(d => {
if (!registered[d]) {
present = false;
}
});
return present;
};
const loadPlugin = async (plugin: Plugin): Promise<void> => {
if (registered[plugin.name]) {
return;
}
if (!plugin.register.dependencies) {
plugin.register.dependencies = [];
}
if (!dependenciesRegistered(plugin.register.dependencies)) {
deferredLoads.push(plugin);
return;
}
const dependencies = _.pick(registered, plugin.register.dependencies);
const register = promisify(plugin.register.register);
const pluginCallback = plugin.callback || _.noop;
await register(plugin.options || {}, dependencies).catch(err => {
pluginCallback(err);
throw err;
});
// Overriding toString so implementation details of plugins do not
// leak to OC consumers
plugin.register.execute.toString = () => plugin.description || '';
registered[plugin.name] = plugin.register.execute;
pluginCallback();
};
const terminator = async (): Promise<PluginFunctions> => {
if (deferredLoads.length > 0) {
const deferredPlugins = _.clone(deferredLoads);
deferredLoads = [];
await Promise.all(
deferredPlugins.map(plugin => onSeries(() => loadPlugin(plugin)))
);
return terminator();
}
return registered;
};
const onSeries = pLimit(1);
await Promise.all(
pluginsToRegister.map(plugin => onSeries(() => loadPlugin(plugin)))
);
return terminator();
}
| {
"content_hash": "7f35f1003f2b2ff5822be4d02de7cebe",
"timestamp": "",
"source": "github",
"line_count": 127,
"max_line_length": 75,
"avg_line_length": 25.338582677165356,
"alnum_prop": 0.6252330640149161,
"repo_name": "opentable/oc",
"id": "029ca02acf1bd1e02a68c2835323beacc392138f",
"size": "3218",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/registry/domain/plugins-initialiser.ts",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "2838"
},
{
"name": "HTML",
"bytes": "12062"
},
{
"name": "JavaScript",
"bytes": "507506"
}
],
"symlink_target": ""
} |
SYNONYM
#### According to
The Catalogue of Life, 3rd January 2011
#### Published in
null
#### Original name
null
### Remarks
null | {
"content_hash": "e83cb14b54ebfddc99722ad46dd68662",
"timestamp": "",
"source": "github",
"line_count": 13,
"max_line_length": 39,
"avg_line_length": 10.23076923076923,
"alnum_prop": 0.6917293233082706,
"repo_name": "mdoering/backbone",
"id": "b30406f4931ea033dbdb54dd0c2e3917f8b0c0c8",
"size": "187",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "life/Plantae/Magnoliophyta/Liliopsida/Poales/Cyperaceae/Carpha/Carpha capitellata/ Syn. Ficinia trinkleriana/README.md",
"mode": "33188",
"license": "apache-2.0",
"language": [],
"symlink_target": ""
} |
package org.apache.struts2.util;
import com.opensymphony.xwork2.Action;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import java.util.*;
/**
* A bean that takes a source and comparator then attempt to sort the source
* utilizing the comparator. It is being used in SortIteratorTag.
*
* @see org.apache.struts2.views.jsp.iterator.SortIteratorTag
*/
public class SortIteratorFilter extends IteratorFilterSupport implements Iterator, Action {
private static final Logger LOG = LogManager.getLogger(IteratorGenerator.class);
Comparator comparator;
Iterator iterator;
List list;
// Attributes ----------------------------------------------------
Object source;
public void setComparator(Comparator aComparator) {
this.comparator = aComparator;
}
public List getList() {
return list;
}
// Public --------------------------------------------------------
public void setSource(Object anIterator) {
source = anIterator;
}
// Action implementation -----------------------------------------
public String execute() {
if (source == null) {
return ERROR;
} else {
try {
if (!MakeIterator.isIterable(source)) {
LOG.warn("Cannot create SortIterator for source: {}", source);
return ERROR;
}
list = new ArrayList();
Iterator i = MakeIterator.convert(source);
while (i.hasNext()) {
list.add(i.next());
}
// Sort it
Collections.sort(list, comparator);
iterator = list.iterator();
return SUCCESS;
} catch (Exception e) {
LOG.warn("Error creating sort iterator.", e);
return ERROR;
}
}
}
// Iterator implementation ---------------------------------------
public boolean hasNext() {
return (source == null) ? false : iterator.hasNext();
}
public Object next() {
return iterator.next();
}
public void remove() {
throw new UnsupportedOperationException("Remove is not supported in SortIteratorFilter.");
}
}
| {
"content_hash": "1e77c1fe3b115be4aa57cfbcce4370e5",
"timestamp": "",
"source": "github",
"line_count": 85,
"max_line_length": 98,
"avg_line_length": 27.223529411764705,
"alnum_prop": 0.5345721694036301,
"repo_name": "Ile2/struts2-showcase-demo",
"id": "b5850ff2989df30f3fc13560a4d41e74f1e637cf",
"size": "3131",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "src/core/src/main/java/org/apache/struts2/util/SortIteratorFilter.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "26665"
},
{
"name": "FreeMarker",
"bytes": "254694"
},
{
"name": "HTML",
"bytes": "913364"
},
{
"name": "Java",
"bytes": "9755409"
},
{
"name": "JavaScript",
"bytes": "35286"
},
{
"name": "XSLT",
"bytes": "10909"
}
],
"symlink_target": ""
} |
namespace webkit_media {
class StreamTextureProxyFactory {
public:
virtual ~StreamTextureProxyFactory() { }
static StreamTextureProxyFactory* Create(int view_id, int player_id);
virtual WebKit::WebStreamTextureProxy* CreateProxy(
int stream_id, int width, int height) = 0;
virtual void ReestablishPeer(int stream_id) = 0;
protected:
StreamTextureProxyFactory() { }
};
} // namespace webkit_media
#endif // WEBKIT_MEDIA_STREAMTEXTUREPROXY_FACTORY_ANDROID_H_
| {
"content_hash": "194c30034a2d87868a941cf966fe13e6",
"timestamp": "",
"source": "github",
"line_count": 20,
"max_line_length": 71,
"avg_line_length": 24.15,
"alnum_prop": 0.7453416149068323,
"repo_name": "paul99/clank",
"id": "b04739939c8bab4a96a9358dcfcb301ffb130e1e",
"size": "857",
"binary": false,
"copies": "1",
"ref": "refs/heads/chrome-18.0.1025.469",
"path": "webkit/media/streamtextureproxy_factory_android.h",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "Assembly",
"bytes": "56689"
},
{
"name": "C",
"bytes": "8707669"
},
{
"name": "C++",
"bytes": "89569069"
},
{
"name": "Go",
"bytes": "10440"
},
{
"name": "Java",
"bytes": "1201391"
},
{
"name": "JavaScript",
"bytes": "5587454"
},
{
"name": "Lua",
"bytes": "13641"
},
{
"name": "Objective-C",
"bytes": "4568468"
},
{
"name": "PHP",
"bytes": "11278"
},
{
"name": "Perl",
"bytes": "51521"
},
{
"name": "Python",
"bytes": "2615443"
},
{
"name": "R",
"bytes": "262"
},
{
"name": "Ruby",
"bytes": "107"
},
{
"name": "Scheme",
"bytes": "10604"
},
{
"name": "Shell",
"bytes": "588836"
}
],
"symlink_target": ""
} |
require 'spec_helper'
describe ProxyList do
it 'has a version number' do
expect(ProxyList::VERSION).not_to be nil
end
it 'get proxy list' do
puts ProxyList.get_lists
expect(ProxyList.get_lists.count).to be > 0
puts ProxyList.get_lists('GB')
expect(ProxyList.get_lists.count).to be > 0
puts ProxyList.get_lists('JP')
expect(ProxyList.get_lists.count).to be > 0
puts ProxyList.get_lists('KR')
expect(ProxyList.get_lists.count).to be > 0
# puts ProxyList.get_lists('TW')
# expect(ProxyList.get_lists.count).to be > 0
# puts ProxyList.get_lists('HK')
# expect(ProxyList.get_lists.count).to be > 0
# puts ProxyList.get_lists('CN')
# expect(ProxyList.get_lists.count).to be > 0
# puts ProxyList.get_lists('CA')
# expect(ProxyList.get_lists.count).to be > 0
# puts ProxyList.get_lists('FR')
# expect(ProxyList.get_lists.count).to be > 0
end
end
| {
"content_hash": "d5a51f2309fe55f7d0f5928ebacbd6f4",
"timestamp": "",
"source": "github",
"line_count": 28,
"max_line_length": 48,
"avg_line_length": 32.642857142857146,
"alnum_prop": 0.6739606126914661,
"repo_name": "tatsu07/proxy_list",
"id": "9f698f01f268466b5d770a8f371a88d806e971e5",
"size": "914",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "spec/proxy_list_spec.rb",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Ruby",
"bytes": "6710"
}
],
"symlink_target": ""
} |
<?php
namespace App\Controllers;
use Silex\Application;
use Silex\Api\ControllerProviderInterface;
use Silex\ControllerCollection;
class IndexController implements ControllerProviderInterface {
public function connect(Application $app) {
$index = $app['controllers_factory'];
$index->get('/', function() use ($app) {
return $app->json(['status' =>
'funcionando']);
});
$index->get('/server', function() use ($app) {
return $app->json(['version' => phpversion()]);
});
$index->get('/version', function() use ($app) {
return phpinfo();
});
return $index;
}
}
| {
"content_hash": "7115add636ca966d6b09b713f72088d6",
"timestamp": "",
"source": "github",
"line_count": 29,
"max_line_length": 62,
"avg_line_length": 20.517241379310345,
"alnum_prop": 0.6588235294117647,
"repo_name": "msfidelis/TDD-Multi-Ambiente-Docker",
"id": "a4810569a334804595bcc9ce4f09d90589bbce05",
"size": "595",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "web/src/Controllers/IndexController.php",
"mode": "33261",
"license": "apache-2.0",
"language": [
{
"name": "ApacheConf",
"bytes": "229"
},
{
"name": "PHP",
"bytes": "25630"
},
{
"name": "Shell",
"bytes": "487"
}
],
"symlink_target": ""
} |
<?php
namespace App\Utils;
/**
* Utility :
*
* @category Awesomeness
* @package Utility
* @author euonymus
* @license euonymus
* @version 1.0.0
*/
use Cake\Cache\Cache;
use Cake\Cache\Engine\FileEngine;
use Cake\Log\Log;
class U
{
public function __construct(array $token = array(), array $consumer = array())
{
}
/*******************************************************/
/* Regex Modules */
/*******************************************************/
public static function regReplace($src, $option)
{
if (!is_string($src)) return false;
if (!is_array($option)) return false;
if (!array_key_exists('replacement', $option) || !array_key_exists('pattern', $option)) return false;
if (!is_string($option['replacement']) || !is_string($option['pattern'])) return false;
return preg_replace($option['pattern'], $option['replacement'], $src);
}
/**
* @param $src: original source text
* @param array $options:
*/
public static function multipleRegex($src, $options)
{
if (!is_array($options)) return false;
$ret = $src;
foreach($options as $option) {
$ret = self::regReplace($ret, $option);
if ($ret === false) return false; // MEMO: 空文字の場合もあるので。
}
return $ret;
}
public static function buildRegexOption($replacement, $pattern, $s = false, $m = false, $i = false, $u = true)
{
if (!is_string($replacement)) return false;
$regex = self::buildRegex($pattern, $s, $m, $i, $u);
if (!$regex) return false;
$ret = array('replacement' => $replacement, 'pattern' => $regex);
return $ret;
}
// MEMO: PHP doesn't have g modifier, instead use preg_match_all.
// s ワイルドカードのドット( . )が改行にもマッチするようにする
// m 文字列を複数行として扱う
// i 英字の大文字、小文字を区別しない
// g 繰り返してマッチ
// o PATTERNの評価を 1回だけにする
// x 拡張正規表現を使用する
//public static function buildRegex($pattern, $g = false, $s = false, $m = false, $i = false)
public static function buildRegex($pattern, $s = false, $m = false, $i = false, $u = true)
{
if (!is_string($pattern)) return false;
$options = '';
//if ($g) $options .= 'g';
if ($s) $options .= 's';
if ($m) $options .= 'm';
if ($i) $options .= 'i';
if ($u) $options .= 'u';
return $pattern . $options;
}
public static function regExUrl()
{
$regex = "((https?|ftp)\:\/\/)?"; // SCHEME
$regex .= "([a-zA-Z0-9+!*(),;?&=\$_.-]+(\:[a-zA-Z0-9+!*(),;?&=\$_.-]+)?@)?"; // User and Pass
$regex .= "([a-zA-Z0-9-.]*)\.([a-zA-Z]{2,3})"; // Host or IP
$regex .= "(\:[0-9]{2,5})?"; // Port
//$regex .= "(\/([a-zA-Z0-9+\$\_-]\.?)+)*\/?"; // Path
//$regex .= "(\/([a-zA-Z0-9+\$\_\-\:\/]\.?)+)*\/?"; // Path
$regex .= "(\/([a-zA-Z0-9+\$\_\-\:\/\%\,]\.?)+)*\/?"; // Path
//$regex .= "(\?[a-zA-Z+&\$_.-][a-zA-Z0-9;:@&%=+\/\$_.-]*)?"; // GET Query
$regex .= "(\?[a-zA-Z0-9+&\$_.-][a-zA-Z0-9;:@&%=+\/\$_.-]*)?"; // GET Query. gekisakaのURLが変なのでしょうがなく 0-9を追加
$regex .= "(#[a-zA-Z_.-][a-zA-Z0-9+\$_.-]*)?"; // Anchor
return $regex;
}
/*******************************************************/
/* XML Modules */
/*******************************************************/
const FEED_TYPE_RSS = 'rss';
const FEED_TYPE_ATOM = 'atom';
const FEED_TYPE_RDF = 'rdf';
const XMLNS_PREF_RELATE = 'relate';
const XMLNS_PREF_DC = 'dc';
const XMLNS_PREF_GEO = 'geo';
const XMLNS_PREF_CONTENT = 'content';
const XMLNS_PREF_MEDIA = 'media';
const XMLNS_PREF_YT = 'yt';
const XMLNS_PREF_ATOM = 'atom';
const XMLNS_PREF_FEEDBURNER = 'feedburner';
public static function getFeedType($xml) {
if ($ret = self::getFeedTypeByXml($xml)) return $ret;
return self::getFeedTypeByItem($xml);
}
public static function getFeedTypeByXml($xml) {
if (isset($xml->item)) return self::FEED_TYPE_RDF;
elseif (isset($xml->channel)) return self::FEED_TYPE_RSS;
elseif (isset($xml->entry)) return self::FEED_TYPE_ATOM;
return false;
}
public static function getFeedTypeByItem($item) {
if (isset($item->pubDate)) return self::FEED_TYPE_RSS;
if (isset($item->updated)) return self::FEED_TYPE_ATOM;
return self::FEED_TYPE_RDF;
}
// $nameSpaceにはxmlns:content='url'のurl部分を渡す。
public static function getChildren($item, $nameSpace) {
$data = $item->children($nameSpace);
return $data ? $data : $item->children($nameSpace . '/');
}
// MEMO: 同じrelate:linkに対して異なるURLでの宣言が存在したためgetChildren()ではなくgetChildrenOnPrefix()を使う事にした。
// $nameSpaceにはcontent:encodedのcontent文字列を渡す
public static function getChildrenOnPrefix($item, $nameSpace) {
return $item->children($nameSpace, true);
}
public static function getXmlItem($xml, $item)
{
$layer = explode('.', $item);
if (empty($layer)) return false;
$srcObj = self::recursiveCall($xml, $layer);
if (!$srcObj) return false;
return $srcObj;
}
public static function recursiveCall($node, $funcs)
{
if (!is_array($funcs)) return false;
$current = array_shift($funcs);
if (!is_string($current)) return false;
if ($current == 'attributes()') {
$current = 'attributes';
$next = $node->{$current}();
} else {
if (!property_exists($node, $current)) return false;
$next = $node->{$current};
}
if (empty($funcs)) return $next;
return self::recursiveCall($next, $funcs);
}
// 壊れたXMLを提供する外部サイトのスクレイプのためXMLテキストをサニタイズ。
// 例: e-talentbank(総合) http://e-talentbank.co.jp/feeds/entertainment_feed/
public static function sanitizeXml($text)
{
// XMLの先頭に改行が含まれる場合があるので
$pattern = '/\A[\r\n]*/';
$replacement = '';
$options = self::buildRegexOption($replacement, $pattern);
return self::regReplace($text, $options);
}
// 参照: http://qiita.com/kobake@github/items/3c5d09f9584a8786339d
// 文字化け防止のため htmlのcharsetを正しく設定する
public static function sanitizeHtmlCharset($text)
{
if (!is_string($text) || empty($text)) return false;
// 既に '<meta http-equiv' partがあればオリジナルテキストを返す。
$patternBase = '\<meta[^\>]*?http\-equiv\=\"[Cc]ontent\-[Tt]ype\"[^\>]*?[Cc]harset';
if (self::matchesRegex($text, $patternBase)) return $text;
// tv-asahi などがShift_JISを使っている。
// '<meta charset="Shift_JIS"' の場合 強制的にutf-8にする。regReplace()でu指定をしているため。
$patternBase = '\<meta[^\>]*?[cC]harset\=\"([sS]hift_(jis|JIS|Jis))\".*?\>';
if (self::matchesRegex($text, $patternBase)) {
// 文字コードを強制的にutf-8に返還
$text = mb_convert_encoding($text, 'utf-8', 'SJIS'); // 'SJIS'を明示しないとうまくいかない。
// 文中のshift_jis文字列をutf-8に返還
$pattern = '/[sS]hift_(jis|JIS|Jis)/';
$replacement = 'utf-8';
$options = self::buildRegexOption($replacement, $pattern);
$text = self::regReplace($text, $options);
}
// MEMO: nikkansports等で変な文字コードが混じるケースがあり、その場合、self::regReplace で壊れてfalseになるためconvertしておく
$text = mb_convert_encoding($text, 'utf-8'); // 何が入っているか分からないので返還前は明示しない。
// '<meta charset'の有無確認
$patternBase = '\<meta[^\>]*?[cC]harset\=\"([^\"]*)\".*?\>';
if (self::matchesRegex($text, $patternBase)) {
$pattern = '/' . $patternBase . '/';
$replacement = '$0<meta http-equiv="Content-Type" content="text/html; charset=$1" />';
$options = self::buildRegexOption($replacement, $pattern);
return self::regReplace($text, $options);
}
// それすら無い場合は単純に以下を追加
$pattern = '/\<\/title\>/';
$replacement = '</title><meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />';
$options = self::buildRegexOption($replacement, $pattern);
return self::regReplace($text, $options);
}
// htmlテキストをSimpleXMLElementにして返却
public static function simplexml_from_html($html)
{
// 文字化け防止
$html = self::sanitizeHtmlCharset($html);
$dom = new \DOMDocument(); // MEMO: \を付ける事でnamespacingの問題を解決できるみたい。
// MEMO: if ($dom instanceof DOMDocument) がなぜか効かない。
$ret = @$dom->loadHTML($html);
if (!($dom instanceof \DOMDocument)) return false;
if (!$ret) return false;
$simplexml = @simplexml_import_dom($dom);
if (!($simplexml instanceof \SimpleXMLElement)) return false;
if (!$simplexml) return false;
return $simplexml;
}
// samples
//debug((string)$xml->single);
//debug((string)$xml->recursive->recursiveinside);
//debug((string)$xml->link->attributes()->href);
//debug((string)$xml->related[0]->title);
//debug((string)$xml->relatedItem[0]->title);
//debug((string)self::getChildrenOnPrefix($xml, 'nhknews')->new);
//debug((string)self::getChildrenOnPrefix($xml, 'feedburner')->origLink);
//debug((string)self::getChildrenOnPrefix($xml, 'relate')->link[0]->attributes()->title);
//debug((string)self::getChildrenOnPrefix($xml, 'dc')->rellink[0]->attributes()->title);
public static function getXmlItem2($xml, $item)
{
if (!is_string($item) || empty($item)) return false;
// Check if using namespace
$namespaceArr = explode(':', $item);
if (count($namespaceArr) > 1) {
// deeper call
$targetObj = self::getChildrenOnPrefix($xml, $namespaceArr[0]);
$targetElm = $namespaceArr[1];
} else {
$targetObj = $xml;
$targetElm = $item;
}
// Check if recursive elements
$deeperElm = false;
$recursiveArr = explode('.', $targetElm);
if (count($recursiveArr) > 1) {
// deeper call
$targetElm = $recursiveArr[0];
array_shift($recursiveArr); // 配列の最初の要素を削除
$deeperElm = implode('.', $recursiveArr);
}
// MEMO: Parsing attribute must be before the parsing of condition
// Check if attribute.
$targetAttr = false;
$attributeArr = explode('@', $targetElm);
if (count($attributeArr) > 1) {
if ($deeperElm) return false; // attribute call should be the last. shouldn't have $deeperElm
$targetElm = $attributeArr[0];
$targetAttr = $attributeArr[1];
}
// Check if it has a condition
$conditionAttr = false;
$conditionArr = explode('/', $targetElm);
if (count($conditionArr) > 1) {
$targetElm = $conditionArr[0];
// get condition
$attributeCnd = explode('=', $conditionArr[1]);
if (count($attributeCnd) <= 1) return false; // 構造的に = が入る必要がある。無い場合はエラー。
$conditionAttr = $attributeCnd[0];
$conditionVal = $attributeCnd[1];
}
// Finally get the item or items
if (!is_object($targetObj) || !property_exists($targetObj, $targetElm)) return false;
$elm = $targetObj->{$targetElm};
if (is_string($elm)) $elm = [$elm]; // source_type = 5(html)の場合などsimplexmlobjectではなく文字列になる場合がある。
// 複数アイテム存在する場合がある。
$arr = [];
foreach($elm as $val) {
if ($conditionAttr) {
$matchVal = (string)$val->attributes()->{$conditionAttr};
if ($matchVal != $conditionVal) continue; // if attribute condition doesn't match skip it.
}
if ($targetAttr) {
$single = (string)$val->attributes()->{$targetAttr};
} elseif ($deeperElm) {
$single = self::getXmlItem2($val, $deeperElm);
} else {
$single = (string)$val;
}
$arr[] = $single;
}
if (count($arr) == 0) {
$ret = false;
} elseif (count($arr) == 1) {
$ret = $arr[0];
} else {
$ret = $arr;
}
return $ret;
}
public static function avoidSelfclosing($html)
{
$pattern = '/(\<((?!(area|base|br|col|command|embed|hr|img|input|keygen|link|meta|param|source|track|wbr))\w*?) [^>]*?)\/\>/';
$replacement = '$1></$2>';
$option = self::buildRegexOption($replacement, $pattern, false, false, false);
return self::regReplace($html, $option);
}
/*******************************************************/
/* Filter modules */
/*******************************************************/
const FLAG_FORMER_HALF = 1;
const FLAG_LATTER_HALF = 2;
const FILTER_TYPE_CONTAIN = 0;
const FILTER_TYPE_NOT_CONTAIN = 1;
const FILTER_TYPE_MATCH_REGEX = 2;
const FILTER_TYPE_GREATER = 3;
const FILTER_TYPE_IS = 4;
const FILTER_TYPE_LESS = 5;
const FILTER_TYPE_AFTER = 6;
const FILTER_TYPE_BEFORE = 7;
/**
* @param $src: input string
* @param $type: 0: Contains, 1: Does not contain, 2: Matches regex,
* 3: is greater than, 4: is, 5: is less than,
* 6: is after, 7: is before
* @param $condition:
*/
public static function filterMatch($src, $type, $condition)
{
if (!is_numeric($type)) return false;
switch ($type) {
case self::FILTER_TYPE_CONTAIN:
$res = self::doesContain($src, $condition);
break;
case self::FILTER_TYPE_NOT_CONTAIN:
$res = !self::doesContain($src, $condition);
break;
case self::FILTER_TYPE_MATCH_REGEX:
$res = self::matchesRegex($src, $condition);
break;
case self::FILTER_TYPE_GREATER:
$res = self::isGreater($src, $condition);
break;
case self::FILTER_TYPE_IS:
$res = self::isSame($src, $condition);
break;
case self::FILTER_TYPE_LESS:
$res = self::isLess($src, $condition);
break;
case self::FILTER_TYPE_AFTER:
$res = self::isAfter($src, $condition);
break;
case self::FILTER_TYPE_BEFORE:
$res = self::isBefore($src, $condition);
break;
default:
$res = false;
break;
}
return $res;
}
/*******************************************************/
/* Judge */
/*******************************************************/
public static function isUrl($str)
{
if (!is_string($str)) return false;
$regex = self::regExUrl();
return self::matchesRegex($str, "\A$regex\z");
}
public static function isImagefile($str)
{
// MEMO: gifを入れるか悩む所
$regex = '\.(jpg|jpeg|jpe|jfif|bmp|png|gif)$';
return self::matchesRegex($str, $regex);
}
public static function doesContain($src, $needle) {
return (stripos($src, $needle) !== false);
}
public static function matchesRegex($src, $regBase) {
if (!is_string($src) || empty($src)) return false;
if (!is_string($regBase) || empty($regBase)) return false;
$reg = '/' . $regBase . '/';
return !!preg_match($reg, $src, $matches);
}
public static function isSame($src, $condition) {
return ($src == $condition);
}
public static function isGreater($src, $condition) {
return (self::compareNumbers($src, $condition) === self::FLAG_FORMER_HALF);
}
public static function isLess($src, $condition) {
return (self::compareNumbers($src, $condition) === self::FLAG_LATTER_HALF);
}
public static function compareNumbers($num1, $num2) {
if (!is_numeric($num1) || !is_numeric($num2)) return false;
return ($num1 == $num2) ? 'same' : (($num1 > $num2) ? self::FLAG_FORMER_HALF : self::FLAG_LATTER_HALF);
}
public static function isAfter($src, $condition) {
return (self::compareDates($src, $condition) === self::FLAG_FORMER_HALF);
}
public static function isBefore($src, $condition) {
return (self::compareDates($src, $condition) === self::FLAG_LATTER_HALF);
}
// returns newer side. if $num1 is newer than $num2, return $num1.
public static function compareDates($date1, $date2) {
$time1 = strtotime($date1);
$time2 = strtotime($date2);
if (($time1 == false) || ($time2 == false)) return false;
return ($time1 == $time2) ? 'same' : (($time1 > $time2) ? self::FLAG_FORMER_HALF : self::FLAG_LATTER_HALF);
}
public static function sameStr($str1, $str2)
{
$str1 = self::trimSpace($str1);
$str2 = self::trimSpace($str2);
$res = strcmp($str1, $str2);
return ($res === 0);
}
/*******************************************************/
/* Date Times */
/*******************************************************/
public static function feedDate($str)
{
$time = strtotime($str);
if (!$time) return false;
return self::feedDateFromTime($time);
}
public static function tableDate($str)
{
$time = strtotime($str);
if (!$time) return false;
return self::tableDateFromTime($time);
}
public static function feedDateFromTime($time)
{
if (!is_numeric($time)) return false;
return date('D, d M Y H:i:s O', $time);
}
public static function tableDateFromTime($time)
{
if (!is_numeric($time)) return false;
return date('Y-m-d H:i:s', $time);
}
public static function getStartDateFromText($txt)
{
$period = self::salvagePeriodFromText($txt);
if (!$period) return false;
$roughDateTxt = self::salvageStartFromPeriodText($period);
if (!$roughDateTxt) return false;
return self::normalizeDateFormat($roughDateTxt);
}
public static function getEndDateFromText($txt)
{
$period = self::salvagePeriodFromText($txt);
if (!$period) return false;
$roughDateTxt = self::salvageEndFromPeriodText($period);
if (!$roughDateTxt) return false;
return self::normalizeDateFormat($roughDateTxt);
}
// 和暦と区別つかないため、3桁以上の年にしか対応できない
static $pattern_date = '(()?\d{3,4} ?年())?( ?\d{1,2} ?月( ?\d{1,2} ?日)?)?';
public static function salvageDateFromText($txt)
{
$pattern = '/' . self::$pattern_date . '/';
$res = preg_match($pattern, $txt, $matches);
if (!$res) return false;
return $matches[0];
}
public static function salvagePeriodFromText($txt)
{
// \D{6} はUTF-8漢字二文字(昭和・平成など)に対応
$pattern = '/' . self::$pattern_date . ' ?[\-\~] ?(\D{6}\d{1,2} ?年 ?)?(' . self::$pattern_date . ')?/';
$res = preg_match($pattern, $txt, $matches);
if (!$res) return false;
return $matches[0];
}
public static function salvageStartFromPeriodText($roughPeriodTxt)
{
$pattern = '/\A' . self::$pattern_date . '/';
$res = preg_match($pattern, $roughPeriodTxt, $matches);
if (!$res) return false;
return $matches[0];
}
public static function salvageEndFromPeriodText($roughPeriodTxt)
{
$pattern = '/' . self::$pattern_date . '\z/';
$res = preg_match($pattern, $roughPeriodTxt, $matches);
if (!$res) return false;
return $matches[0];
}
public static function normalizeDateFormat($roughDateTxt)
{
$pattern = '/(\d{3,4} ?)年/';
$res = preg_match($pattern, $roughDateTxt, $matches);
if (!$res) return false;
$ret = $matches[1];
$pattern = '/(\d{1,2}) ?月/';
$res = preg_match($pattern, $roughDateTxt, $matches);
if ($res) {
$month = $matches[1];
$ret = sprintf($ret . '-%02d', $month);
$pattern = '/(\d{1,2}) ?日/';
$res = preg_match($pattern, $roughDateTxt, $matches);
if ($res) {
$day = $matches[1];
$ret = sprintf($ret . '-%02d', $day);
}
}
return $ret;
}
// $dateTxt: 'y-m-d'
public static function normalizeDateArrayFormat($dateTxt)
{
if (!is_string($dateTxt)) return false;
$arr = explode('-', $dateTxt);
if (count($arr) == 1) {
if (!is_numeric($arr[0])) return false;
$date = $arr[0] . '-01-01 00:00:00';
$accuracy = 'year';
} elseif (count($arr) == 2) {
if (!is_numeric($arr[0]) || !is_numeric($arr[1])) return false;
$date = $arr[0] . '-' .sprintf('%02d', $arr[1]) .'-01 00:00:00';
$accuracy = 'month';
} elseif (count($arr) == 3) {
if (!is_numeric($arr[0]) || !is_numeric($arr[1]) || !is_numeric($arr[2])) return false;
$date = $arr[0] . '-' .sprintf('%02d', $arr[1]) . '-' . sprintf('%02d', $arr[2]) .' 00:00:00';
$accuracy = NULL;
} else {
return false;
}
return ['date' => $date, 'date_accuracy' => $accuracy];
}
/*******************************************************/
/* Sanitize Strings */
/*******************************************************/
public static function trimSpace($str)
{
if (!is_string($str)) return '';
// MEMO: pregに渡せる文字列には限界があり、下記パターンの正規表現にたいしては、14155が限界値。
// これより長い値を渡すとセグメンテーションフォルトとなってしまう。
if (strlen($str) > 14155) return $str;
// MEMO: (?:.|\n)は改行を含む全ての文字列。因に、\rは.に含まれる。
// return preg_replace('/^[ \r\n]*(.*?)[ \r\n]*$/u', '$1', $str);
return preg_replace('/^[ \r\n]*((?:.|\n)*?)[ \r\n]*$/u', '$1', $str);
}
// remove all the spaces.
// this will remove all the spaces, even in between the strings.
// TODO: 全角スペースの有無をコンフィグできるようにする。
public static function removeAllSpaces($str, $includeIdeographicSpace = true)
{
$tmp = preg_replace('/ /', '', $str);
return preg_replace('/ /', '', $tmp);
}
public static function abbreviateStr($str, $length)
{
$str = self::trimSpace($str);
$count = mb_strlen($str, "UTF-8" );
if( $count <= $length ) return $str;
return mb_substr($str, 0, $length, "UTF-8" ) . '…';
}
public static function shortenDots($str)
{
$replacement = '…';
$pattern = '/[\・]{6,}/'; // どうも半角の文字数でカウントされてるっぽいので2ではなく6(3bite x 2)。(文字化け回避)
$option = self::buildRegexOption($replacement, $pattern, false, false, false, false);
return self::regReplace($str, $option);
}
public static function stripParenthesisBold($str)
{
$str = self::trimSpace($str);
$replacement = '$1:';
$pattern = '/^【(.+?)】/';
$option = self::buildRegexOption($replacement, $pattern, false, false, false);
return self::regReplace($str, $option);
}
public static function removeWWWW($str)
{
$replacement = '$1';
$pattern = '/w{2,}([^w^\.^\s])/';
$option1 = self::buildRegexOption($replacement, $pattern, false, false, false);
$replacement = '';
$pattern = '/w+$/';
$option2 = self::buildRegexOption($replacement, $pattern, false, false, false);
$option = array($option1, $option2);
return self::multipleRegex($str, $option);
}
public static function omitUrlInText($str)
{
if (!is_string($str)) return false;
$regex = self::regExUrl();
$option = self::buildRegexOption('', '/' . $regex . '/');
$replaced = self::regReplace($str, $option);
if ($replaced === false) return false;
return self::trimSpace($replaced);
}
/*******************************************************/
/* Retrieve data */
/*******************************************************/
// Get Json data
public static function retrieveJsonFromUrl($path, $withAgent = false)
{
$file = self::retrieveFileFromUrl($path, $withAgent);
if (!$file) return false;
$res = json_decode($file);
if (!$res) return false;
return $res;
}
// Get Json data as an array
public static function retrieveJsonArrayFromUrl($path, $withAgent = false)
{
$file = self::retrieveFileFromUrl($path, $withAgent);
if (!$file) return false;
$res = json_decode($file, true);
if (!$res) return false;
return $res;
}
// Get RSS items
public static function retrieveFeedItemsFromUrl($path, $withAgent = false)
{
$res = self::retrieveFeedFromUrl($path, $withAgent);
if (!$res || !property_exists($res, 'channel') || !property_exists($res->channel, 'item')) return false;
return $res->channel->item;
}
// Get RDF items
public static function retrieveRdfItemsFromUrl($path, $withAgent = false)
{
$res = self::retrieveFeedFromUrl($path, $withAgent);
if (!$res || !property_exists($res, 'item')) return false;
return $res->item;
}
// Get Atom items
public static function retrieveAtomItemsFromUrl($path, $withAgent = false)
{
$res = self::retrieveFeedFromUrl($path, $withAgent);
if (!$res || !property_exists($res, 'entry')) return false;
return $res->entry;
}
// You can choose how to retrieve simplexml from either way of simplexml_load_file or file_get_contents.
static $retrieveXmlViaText = false; // simplexml_load_file is prefered.
public static function retrieveFeedFromUrl($path, $withAgent = false)
{
if (self::$retrieveXmlViaText) {
$ret = self::retrieveXmlViaTextFromUrl($path, $withAgent);
} else {
$ret = self::retrieveXmlFromUrl($path, $withAgent);
}
return $ret;
}
// Get Xpath data from html
public static function getXpathFromUrl($url, $xpath, $asString = false, $withAgent = false)
{
$xml = self::simplexml_from_html_path($url, $withAgent);
if (!($xml instanceof \SimpleXMLElement)) return false;
$node = @$xml->xpath($xpath);
if (!$node) return false;
if ($asString) {
$ret = array();
foreach ($node as $item) {
$ret[] = (string)$item;
}
} else {
$ret = $node;
}
return $ret;
}
/*******************************************************/
/* Retrieve data primitive */
/*******************************************************/
const USER_AGENT = 'gluons crawler';
// Get text data
public static function retrieveFileFromUrl($path, $withAgent = false)
{
if ($withAgent) {
ini_set('user_agent', self::USER_AGENT);
}
return self::cachedRetrieve($path, 'file_get_contents');
}
// Get XML data
public static function retrieveXmlFromUrl($path, $withAgent = false)
{
if ($withAgent) {
ini_set('user_agent', self::USER_AGENT);
}
//ini_set("max_execution_time", 0);
//ini_set("memory_limit", "10000M");
//return @simplexml_load_file($path);
return self::cachedRetrieveForXml($path, 'simplexml_load_file');
}
// Get XML data of html
public static function simplexml_from_html_path($path, $withAgent = false)
{
$html = self::retrieveFileFromUrl($path, $withAgent);
if (empty($html)) return false;
return self::simplexml_from_html($html);
}
// Get broken XML data
public static function retrieveXmlViaTextFromUrl($path, $withAgent = false)
{
$text = self::retrieveFileFromUrl($path, $withAgent);
if (!$text) return false;
$clean = self::sanitizeXml($text);
return @simplexml_load_string($clean);
}
static $retrieveCacheConfig = false;
static $logForCachedCall = false;
public static function cachedRetrieve($path, $func)
{
$useCache = false;
if (is_string(self::$retrieveCacheConfig)) {
// $pathから作成されるkeyの長さチェック
$FileEngine = new FileEngine;
$key = 'cake_' . self::$retrieveCacheConfig . '_' . $FileEngine->key($path);
if (strlen($key) <= 255) $useCache = true;
}
if ($useCache) {
$type = 'USING CACHE:';
if (($data = Cache::read($path, self::$retrieveCacheConfig)) === false) {
$type .= 'actual call:';
$data = @$func($path);
Cache::write($path, $data, self::$retrieveCacheConfig);
}
} else {
$type = 'WITHOUT CACHE:';
$data = @$func($path);
}
if (self::$logForCachedCall) Log::info($type . $path, 'retrieval');
return $data;
}
// MEMO: SimpleXMLElementがCache::write()できないため cachedRetrieve()と分けて関数作成
public static function cachedRetrieveForXml($path, $func)
{
if (self::$retrieveCacheConfig) {
$asText = Cache::read($path, self::$retrieveCacheConfig);
if ($asText !== false) {
$data = @simplexml_load_string($asText);
} else {
$data = @$func($path);
if ($data) {
// SimpleXMLElementはそのままcacheできないっぽい。一度xmlテキストにする。
$caching = $data->asXML();
} else $caching = false;
Cache::write($path, $caching, self::$retrieveCacheConfig);
}
} else {
$data = @$func($path);
}
return $data;
}
/*******************************************************/
/* Primitives */
/*******************************************************/
public static function buildGuid()
{
return sprintf('%04x%04x-%04x-%04x-%04x-%04x%04x%04x', mt_rand(0, 65535), mt_rand(0, 65535), mt_rand(0, 65535), mt_rand(16384, 20479), mt_rand(32768, 49151), mt_rand(0, 65535), mt_rand(0, 65535), mt_rand(0, 65535));
}
public static function expandUrl($short_url)
{
$h = @get_headers($short_url, 1);
if (!$h) return false;
if(!isset($h['Location'])) return false;
$long_url = $h['Location'];
if(is_array($long_url)){
$long_url = end($long_url);
}
return $long_url;
}
public static function smartArrayUnique($arr)
{
if (!is_array($arr)) return false;
return array_merge(array_unique($arr)); // 歯抜けを直すためのarray_merge()
}
// 100レコードずつに分離する
public static function objChunk($feed, $limit = 100)
{
$chunk = [];
$arr = [];
foreach($feed as $item) {
$arr[] = $item;
if (count($arr) >= $limit) {
$chunk[] = $arr;
$arr = [];
}
}
if (count($arr) > 0) {
$chunk[] = $arr;
}
return $chunk;
}
// 改行を除外する
public static function removeLineBreak($text)
{
if (!is_string($text)) return false;
$pattern = '/[\r\n]+/';
$replacement = ' ';
$options = self::buildRegexOption($replacement, $pattern);
return self::regReplace($text, $options);
}
public static function stripQueryString($url)
{
if (!self::isUrl($url)) return false;
$regex = '/\?.*$/'; // querystring を削除する。
return preg_replace($regex, "", $url);
}
// U以外からの呼び出しで$url毎にキャッシュで扱うケースが多かったので共通的に使うために作成した。
public static function cachedFuncByUrl($func, $url, $retrieveCacheConfig = 'halfhour')
{
// config retrieveCache setting
$cacheOrigin = self::$retrieveCacheConfig;
self::$retrieveCacheConfig = $retrieveCacheConfig;
// get result with $url arg
$ret = self::{$func}($url);
// put the cache setting back
self::$retrieveCacheConfig = $cacheOrigin;
return $ret;
}
public static function getSubdomain()
{
$domain = 'gluons.link';
$domain_local = 'localhost:8765';
$domain_virtualbox = 'local.gluons';
$original = $_SERVER["HTTP_HOST"];
$tmp = str_replace('.' . $domain, '', $original);
$tmp = str_replace('.' . $domain_local, '', $tmp);
$ret = str_replace('.' . $domain_virtualbox, '', $tmp);
if (($tmp == $domain) || ($tmp == $domain_local) || ($tmp == $domain_virtualbox)) {
$ret = '';
}
return $ret;
}
}
| {
"content_hash": "d84925a7aa1268e014e07ac13d7e4d2c",
"timestamp": "",
"source": "github",
"line_count": 882,
"max_line_length": 219,
"avg_line_length": 34.012471655328795,
"alnum_prop": 0.5740191339711324,
"repo_name": "euonymus/belongsto",
"id": "b4216bb2ac43e387b64ce94dfaa44d88d2d5edf7",
"size": "31765",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/Utils/U.php",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "Batchfile",
"bytes": "834"
},
{
"name": "CSS",
"bytes": "12790"
},
{
"name": "HTML",
"bytes": "51792"
},
{
"name": "JavaScript",
"bytes": "1125"
},
{
"name": "PHP",
"bytes": "840935"
},
{
"name": "Shell",
"bytes": "1457"
}
],
"symlink_target": ""
} |
<assembly>
<id>cli</id>
<formats>
<format>tar.gz</format>
<!--
<format>zip</format>
-->
<format>dir</format>
</formats>
<fileSets>
<fileSet>
<directory>target/appassembler/bin</directory>
<outputDirectory>bin</outputDirectory>
<includes>
<include>*.bat</include>
</includes>
<lineEnding>keep</lineEnding>
</fileSet>
<fileSet>
<directory>target/appassembler/bin</directory>
<outputDirectory>bin</outputDirectory>
<excludes>
<exclude>*.bat</exclude>
</excludes>
<fileMode>744</fileMode>
<lineEnding>keep</lineEnding>
</fileSet>
<fileSet>
<directory>${project.basedir}</directory>
<outputDirectory>/</outputDirectory>
<includes>
<include>README*</include>
<include>LICENSE*</include>
<include>NOTICE*</include>
</includes>
</fileSet>
</fileSets>
<dependencySets>
<dependencySet>
<outputDirectory>lib</outputDirectory>
</dependencySet>
</dependencySets>
</assembly>
| {
"content_hash": "dab8ba173f2a17fd1ce3efa8e9d41656",
"timestamp": "",
"source": "github",
"line_count": 43,
"max_line_length": 52,
"avg_line_length": 24.558139534883722,
"alnum_prop": 0.6107954545454546,
"repo_name": "cygri/vocidex",
"id": "939f86674ccc172c487a7fa251652d416ff9b476",
"size": "1056",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "assembly.xml",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Java",
"bytes": "49866"
},
{
"name": "JavaScript",
"bytes": "4295"
}
],
"symlink_target": ""
} |
ACCEPTED
#### According to
International Plant Names Index
#### Published in
null
#### Original name
null
### Remarks
null | {
"content_hash": "2fd193187ad2cf2414d039c2554d9873",
"timestamp": "",
"source": "github",
"line_count": 13,
"max_line_length": 31,
"avg_line_length": 9.692307692307692,
"alnum_prop": 0.7063492063492064,
"repo_name": "mdoering/backbone",
"id": "479ca7855227f15f2132b81851c9d123c6d77bdd",
"size": "178",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "life/Plantae/Magnoliophyta/Magnoliopsida/Ranunculales/Lardizabalaceae/Stauntonia/Stauntonia trifoliata/README.md",
"mode": "33188",
"license": "apache-2.0",
"language": [],
"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 (1.8.0_60-ea) on Mon Oct 03 10:36:49 EDT 2016 -->
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Uses of Class org.wildfly.swarm.config.infinispan.cache_container.TransactionComponent.Locking (Public javadocs 2016.10.0 API)</title>
<meta name="date" content="2016-10-03">
<link rel="stylesheet" type="text/css" href="../../../../../../../stylesheet.css" title="Style">
<script type="text/javascript" src="../../../../../../../script.js"></script>
</head>
<body>
<script type="text/javascript"><!--
try {
if (location.href.indexOf('is-external=true') == -1) {
parent.document.title="Uses of Class org.wildfly.swarm.config.infinispan.cache_container.TransactionComponent.Locking (Public javadocs 2016.10.0 API)";
}
}
catch(err) {
}
//-->
</script>
<noscript>
<div>JavaScript is disabled on your browser.</div>
</noscript>
<!-- ========= START OF TOP NAVBAR ======= -->
<div class="topNav"><a name="navbar.top">
<!-- -->
</a>
<div class="skipNav"><a href="#skip.navbar.top" title="Skip navigation links">Skip navigation links</a></div>
<a name="navbar.top.firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../../../../../overview-summary.html">Overview</a></li>
<li><a href="../package-summary.html">Package</a></li>
<li><a href="../../../../../../../org/wildfly/swarm/config/infinispan/cache_container/TransactionComponent.Locking.html" title="enum in org.wildfly.swarm.config.infinispan.cache_container">Class</a></li>
<li class="navBarCell1Rev">Use</li>
<li><a href="../../../../../../../overview-tree.html">Tree</a></li>
<li><a href="../../../../../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../../../../../index-all.html">Index</a></li>
<li><a href="../../../../../../../help-doc.html">Help</a></li>
</ul>
<div class="aboutLanguage">WildFly Swarm API, 2016.10.0</div>
</div>
<div class="subNav">
<ul class="navList">
<li>Prev</li>
<li>Next</li>
</ul>
<ul class="navList">
<li><a href="../../../../../../../index.html?org/wildfly/swarm/config/infinispan/cache_container/class-use/TransactionComponent.Locking.html" target="_top">Frames</a></li>
<li><a href="TransactionComponent.Locking.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_top">
<li><a href="../../../../../../../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_top");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
</div>
<a name="skip.navbar.top">
<!-- -->
</a></div>
<!-- ========= END OF TOP NAVBAR ========= -->
<div class="header">
<h2 title="Uses of Class org.wildfly.swarm.config.infinispan.cache_container.TransactionComponent.Locking" class="title">Uses of Class<br>org.wildfly.swarm.config.infinispan.cache_container.TransactionComponent.Locking</h2>
</div>
<div class="classUseContainer">
<ul class="blockList">
<li class="blockList">
<table class="useSummary" border="0" cellpadding="3" cellspacing="0" summary="Use table, listing packages, and an explanation">
<caption><span>Packages that use <a href="../../../../../../../org/wildfly/swarm/config/infinispan/cache_container/TransactionComponent.Locking.html" title="enum in org.wildfly.swarm.config.infinispan.cache_container">TransactionComponent.Locking</a></span><span class="tabEnd"> </span></caption>
<tr>
<th class="colFirst" scope="col">Package</th>
<th class="colLast" scope="col">Description</th>
</tr>
<tbody>
<tr class="altColor">
<td class="colFirst"><a href="#org.wildfly.swarm.config.infinispan.cache_container">org.wildfly.swarm.config.infinispan.cache_container</a></td>
<td class="colLast"> </td>
</tr>
</tbody>
</table>
</li>
<li class="blockList">
<ul class="blockList">
<li class="blockList"><a name="org.wildfly.swarm.config.infinispan.cache_container">
<!-- -->
</a>
<h3>Uses of <a href="../../../../../../../org/wildfly/swarm/config/infinispan/cache_container/TransactionComponent.Locking.html" title="enum in org.wildfly.swarm.config.infinispan.cache_container">TransactionComponent.Locking</a> in <a href="../../../../../../../org/wildfly/swarm/config/infinispan/cache_container/package-summary.html">org.wildfly.swarm.config.infinispan.cache_container</a></h3>
<table class="useSummary" border="0" cellpadding="3" cellspacing="0" summary="Use table, listing methods, and an explanation">
<caption><span>Methods in <a href="../../../../../../../org/wildfly/swarm/config/infinispan/cache_container/package-summary.html">org.wildfly.swarm.config.infinispan.cache_container</a> that return <a href="../../../../../../../org/wildfly/swarm/config/infinispan/cache_container/TransactionComponent.Locking.html" title="enum in org.wildfly.swarm.config.infinispan.cache_container">TransactionComponent.Locking</a></span><span class="tabEnd"> </span></caption>
<tr>
<th class="colFirst" scope="col">Modifier and Type</th>
<th class="colLast" scope="col">Method and Description</th>
</tr>
<tbody>
<tr class="altColor">
<td class="colFirst"><code><a href="../../../../../../../org/wildfly/swarm/config/infinispan/cache_container/TransactionComponent.Locking.html" title="enum in org.wildfly.swarm.config.infinispan.cache_container">TransactionComponent.Locking</a></code></td>
<td class="colLast"><span class="typeNameLabel">TransactionComponent.</span><code><span class="memberNameLink"><a href="../../../../../../../org/wildfly/swarm/config/infinispan/cache_container/TransactionComponent.html#locking--">locking</a></span>()</code>
<div class="block">The locking mode for this cache, one of OPTIMISTIC or PESSIMISTIC.</div>
</td>
</tr>
<tr class="rowColor">
<td class="colFirst"><code>static <a href="../../../../../../../org/wildfly/swarm/config/infinispan/cache_container/TransactionComponent.Locking.html" title="enum in org.wildfly.swarm.config.infinispan.cache_container">TransactionComponent.Locking</a></code></td>
<td class="colLast"><span class="typeNameLabel">TransactionComponent.Locking.</span><code><span class="memberNameLink"><a href="../../../../../../../org/wildfly/swarm/config/infinispan/cache_container/TransactionComponent.Locking.html#valueOf-java.lang.String-">valueOf</a></span>(<a href="http://docs.oracle.com/javase/8/docs/api/java/lang/String.html?is-external=true" title="class or interface in java.lang">String</a> name)</code>
<div class="block">Returns the enum constant of this type with the specified name.</div>
</td>
</tr>
<tr class="altColor">
<td class="colFirst"><code>static <a href="../../../../../../../org/wildfly/swarm/config/infinispan/cache_container/TransactionComponent.Locking.html" title="enum in org.wildfly.swarm.config.infinispan.cache_container">TransactionComponent.Locking</a>[]</code></td>
<td class="colLast"><span class="typeNameLabel">TransactionComponent.Locking.</span><code><span class="memberNameLink"><a href="../../../../../../../org/wildfly/swarm/config/infinispan/cache_container/TransactionComponent.Locking.html#values--">values</a></span>()</code>
<div class="block">Returns an array containing the constants of this enum type, in
the order they are declared.</div>
</td>
</tr>
</tbody>
</table>
<table class="useSummary" border="0" cellpadding="3" cellspacing="0" summary="Use table, listing methods, and an explanation">
<caption><span>Methods in <a href="../../../../../../../org/wildfly/swarm/config/infinispan/cache_container/package-summary.html">org.wildfly.swarm.config.infinispan.cache_container</a> with parameters of type <a href="../../../../../../../org/wildfly/swarm/config/infinispan/cache_container/TransactionComponent.Locking.html" title="enum in org.wildfly.swarm.config.infinispan.cache_container">TransactionComponent.Locking</a></span><span class="tabEnd"> </span></caption>
<tr>
<th class="colFirst" scope="col">Modifier and Type</th>
<th class="colLast" scope="col">Method and Description</th>
</tr>
<tbody>
<tr class="altColor">
<td class="colFirst"><code><a href="../../../../../../../org/wildfly/swarm/config/infinispan/cache_container/TransactionComponent.html" title="type parameter in TransactionComponent">T</a></code></td>
<td class="colLast"><span class="typeNameLabel">TransactionComponent.</span><code><span class="memberNameLink"><a href="../../../../../../../org/wildfly/swarm/config/infinispan/cache_container/TransactionComponent.html#locking-org.wildfly.swarm.config.infinispan.cache_container.TransactionComponent.Locking-">locking</a></span>(<a href="../../../../../../../org/wildfly/swarm/config/infinispan/cache_container/TransactionComponent.Locking.html" title="enum in org.wildfly.swarm.config.infinispan.cache_container">TransactionComponent.Locking</a> value)</code>
<div class="block">The locking mode for this cache, one of OPTIMISTIC or PESSIMISTIC.</div>
</td>
</tr>
</tbody>
</table>
</li>
</ul>
</li>
</ul>
</div>
<!-- ======= START OF BOTTOM NAVBAR ====== -->
<div class="bottomNav"><a name="navbar.bottom">
<!-- -->
</a>
<div class="skipNav"><a href="#skip.navbar.bottom" title="Skip navigation links">Skip navigation links</a></div>
<a name="navbar.bottom.firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../../../../../overview-summary.html">Overview</a></li>
<li><a href="../package-summary.html">Package</a></li>
<li><a href="../../../../../../../org/wildfly/swarm/config/infinispan/cache_container/TransactionComponent.Locking.html" title="enum in org.wildfly.swarm.config.infinispan.cache_container">Class</a></li>
<li class="navBarCell1Rev">Use</li>
<li><a href="../../../../../../../overview-tree.html">Tree</a></li>
<li><a href="../../../../../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../../../../../index-all.html">Index</a></li>
<li><a href="../../../../../../../help-doc.html">Help</a></li>
</ul>
<div class="aboutLanguage">WildFly Swarm API, 2016.10.0</div>
</div>
<div class="subNav">
<ul class="navList">
<li>Prev</li>
<li>Next</li>
</ul>
<ul class="navList">
<li><a href="../../../../../../../index.html?org/wildfly/swarm/config/infinispan/cache_container/class-use/TransactionComponent.Locking.html" target="_top">Frames</a></li>
<li><a href="TransactionComponent.Locking.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 ======= -->
<p class="legalCopy"><small>Copyright © 2016 <a href="http://www.jboss.org">JBoss by Red Hat</a>. All rights reserved.</small></p>
</body>
</html>
| {
"content_hash": "050a17104412922f692fc4e81ff0c07f",
"timestamp": "",
"source": "github",
"line_count": 198,
"max_line_length": 565,
"avg_line_length": 56.67171717171717,
"alnum_prop": 0.6785491489172089,
"repo_name": "wildfly-swarm/wildfly-swarm-javadocs",
"id": "a9dd40913f2f5efcd2bc51d43fcd119a8ed50da1",
"size": "11221",
"binary": false,
"copies": "1",
"ref": "refs/heads/gh-pages",
"path": "2016.10.0/apidocs/org/wildfly/swarm/config/infinispan/cache_container/class-use/TransactionComponent.Locking.html",
"mode": "33188",
"license": "apache-2.0",
"language": [],
"symlink_target": ""
} |
package org.raistlic.common.taskqueue;
import org.raistlic.common.precondition.InvalidContextException;
import org.raistlic.common.precondition.InvalidParameterException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
/**
* This interface defines the API of a single thread runnable queue implementation.
*
* @author Lei Chen (2013-12-19)
* @since 1.0
*/
public interface TaskQueue {
/**
* The method submits a runnable task into the task queue to be executed.
*
* @param task the task to be scheduled, cannot be {@code null}.
* @throws InvalidParameterException when {@code task} is {@code null}.
* @throws InvalidContextException if the task queue is not running.
*/
void schedule(Runnable task) throws InvalidParameterException, InvalidContextException;
/**
* The method submits a runnable task that has a returned result when executed into the queue,
* and returns a {@link Promise} that references to the task.
*
* @param task the task to be scheduled, cannot be {@code null}.
* @param <R> the actual return type of the {@link Task}'s run method.
* @return the promise that references the scheduled task.
* @throws InvalidParameterException when {@code task} is {@code null}.
* @throws InvalidContextException if the task queue is not running.
*/
<R> Promise<R> schedule(Task<R> task) throws InvalidParameterException, InvalidContextException;
/**
* The method submits the {@code task} into the task queue, waits until it's executed,
* and returns the returned execution result.
*
* @param task the task to execute, cannot be {@code null}.
* @param <R> the actual return type of the {@link Task}'s run method.
* @return the {@code task} 's execution result.
* @throws InvalidParameterException when {@code task} is {@code null}.
* @throws InvalidContextException if the task queue is not running.
* @throws InvalidContextException when the method is called within the task queue execution thread,
* see {@link #isTaskExecutionThread()} .
* @throws TaskExecutionException if the {@code task}'s {@link java.util.concurrent.Callable#call()}
* method throws exception.
* @throws java.lang.InterruptedException if the current calling thread is interrupted when waiting
* for the {@code task} to be executed.
*/
<R> R scheduleAndWait(Task<R> task) throws InvalidParameterException,
InvalidContextException,
InvalidContextException,
TaskExecutionException,
InterruptedException;
/**
* The method submits the {@code task} into the task queue, waits up to {@code timeout} for it to
* be executed, and returns the returned execution result.
*
* @param task the task to execute, cannot be {@code null}.
* @param timeout the max amount of time that calling thread is going to wait for the task to be
* executed, cannot be negative.
* @param timeUnit the unit of the {@code timeout} .
* @param <R> the actual return type of the {@link Task}'s run method.
* @return the {@code task} 's execution result.
* @throws InvalidParameterException when {@code task} is {@code null}, or when {@code timeout} is
* less than {@code 0} .
* @throws InvalidContextException if the task queue is not running.
* @throws InvalidContextException when the method is called within the task queue execution thread,
* see {@link #isTaskExecutionThread()} .
* @throws TaskExecutionException if the {@code task}'s {@link java.util.concurrent.Callable#call()}
* method throws exception.
* @throws java.lang.InterruptedException if the current calling thread is interrupted when waiting
* for the {@code task} to be executed.
* @throws java.util.concurrent.TimeoutException if the task is not executed within {@code timeout} .
*/
<R> R scheduleAndWait(Task<R> task, long timeout, TimeUnit timeUnit)
throws InvalidParameterException,
InvalidContextException,
InvalidContextException,
TaskExecutionException,
InterruptedException,
TimeoutException;
/**
* The method returns whether the current (calling) thread is the task queue thread.
*
* @return {@code true} if the current (calling) thread is the task queue thread.
* @throws InvalidContextException if the task queue is not running.
*/
boolean isTaskExecutionThread() throws InvalidContextException;
/**
* The method returns whether the task queue is running. Attempting to submit a task to a not
* running task queue will cause {@link IllegalStateException} .
*
* @return {@code true} if the task queue is running.
*/
boolean isRunning();
/**
* The controller that holds the instance of the task queue, and controls its life cycle.
*/
public static interface Controller {
/**
* The method returns the task queue that the handler is handling.
*
* @return the task queue that the handler is handling.
*/
TaskQueue get();
/**
* Starts the task queue, if it is not already running; otherwise the method simply does nothing
* and returns {@code false}.
*
* @return {@code true} if the task queue's running state is successfully changed as a result of
* the call.
*/
boolean start();
/**
* Shuts down the task queue(if the queue is running), and the current (calling) thread waits
* for the queue to shutdown, for {@code timeout} milliseconds.
*
* @param timeout the maximum number of milli-seconds to wait for the queue shutdown.
* @param timeUnit the unit of the {@code timeout} .
* @return {@code true} if the queue's running state is changed as a result of the call.
* @throws java.lang.InterruptedException if the current (calling) thread is interrupted while
* waiting for the queue to shutdown.
* @throws java.util.concurrent.TimeoutException if waiting time out, in which case the signal
* to shut down the queue is already sent, and that the queue may very well shut down
* at any time later after the exception is thrown.
*/
boolean stop(long timeout, TimeUnit timeUnit) throws InterruptedException, TimeoutException;
/**
* The method signals the task queue to stop at an appropriate time.
*
* @param interruptCurrentTask {@code true} if the currently executed task should be interrupted.
*/
void stop(boolean interruptCurrentTask);
}
}
| {
"content_hash": "7e7d686728eb83e37a9c15efa2dac0a6",
"timestamp": "",
"source": "github",
"line_count": 150,
"max_line_length": 135,
"avg_line_length": 46.693333333333335,
"alnum_prop": 0.655197030268418,
"repo_name": "raistlic/raistlic-lib-commons-core",
"id": "58ef021ecc46132c18fa4b36ede57e67edd8c735",
"size": "7612",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/main/java/org/raistlic/common/taskqueue/TaskQueue.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Groovy",
"bytes": "23066"
},
{
"name": "Java",
"bytes": "670737"
},
{
"name": "Shell",
"bytes": "1786"
}
],
"symlink_target": ""
} |
<!DOCTYPE html>
<html class="reftest-wait">
<title>WebVTT rendering, set align start and the cue contains two lines with different writing directions</title>
<link rel="match" href="start_alignment-ref.html">
<style>
html { overflow:hidden }
body { margin:0 }
::cue {
font-family: sans-serif;
color: green;
}
</style>
<script src="/common/reftest-wait.js"></script>
<video width="320" height="180" autoplay onplaying="this.onplaying = null; this.pause(); takeScreenshot();">
<source src="/media/white.webm" type="video/webm">
<source src="/media/white.mp4" type="video/mp4">
<track src="../support/start_alignment.vtt" default>
</video>
</html>
| {
"content_hash": "3e8795b00c73e278defd521a207363ba",
"timestamp": "",
"source": "github",
"line_count": 19,
"max_line_length": 113,
"avg_line_length": 35,
"alnum_prop": 0.6962406015037594,
"repo_name": "nwjs/chromium.src",
"id": "2b6cd76c20109c39c2a5ed06540a92c782f639b1",
"size": "665",
"binary": false,
"copies": "31",
"ref": "refs/heads/nw70",
"path": "third_party/blink/web_tests/external/wpt/webvtt/rendering/cues-with-video/processing-model/bidi/start_alignment.html",
"mode": "33188",
"license": "bsd-3-clause",
"language": [],
"symlink_target": ""
} |
ACCEPTED
#### According to
International Plant Names Index
#### Published in
null
#### Original name
null
### Remarks
null | {
"content_hash": "a1e3d61ddefa22ec4d2a84af2b69d72c",
"timestamp": "",
"source": "github",
"line_count": 13,
"max_line_length": 31,
"avg_line_length": 9.692307692307692,
"alnum_prop": 0.7063492063492064,
"repo_name": "mdoering/backbone",
"id": "ff3f11cc1918b205d73dabeecae9b2970b4a73f0",
"size": "178",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "life/Plantae/Magnoliophyta/Magnoliopsida/Ericales/Theaceae/Adinandra/Adinandra kostermansii/README.md",
"mode": "33188",
"license": "apache-2.0",
"language": [],
"symlink_target": ""
} |
monitor Windows(32 bit or 64 bit) services by heartbeat.
restart service when heartbeat stopped or configuration changed.
status:
- OK (heartbeat is OK)
- not OK
- app heartbeat timeout
- no response (PC power off) / supervisor heartbeat timeout | {
"content_hash": "8d51ec30105d0159a1adf0e63e2c696d",
"timestamp": "",
"source": "github",
"line_count": 10,
"max_line_length": 64,
"avg_line_length": 25.1,
"alnum_prop": 0.7649402390438247,
"repo_name": "mabotech/mabo_sup",
"id": "51fe1f5095d0c1502640af22b5e94f8b32b5558a",
"size": "267",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "py/mabo_sup/README.md",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Python",
"bytes": "6612"
}
],
"symlink_target": ""
} |
#region license
// Copyright (c) 2004, Rodrigo B. de Oliveira (rbo@acm.org)
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
// * Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
// * Neither the name of Rodrigo B. de Oliveira nor the names of its
// contributors may be used to endorse or promote products derived from this
// software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE
// FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
// DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
// OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
// THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#endregion
using System;
using System.Reflection;
using Boo.Lang.Compiler.Ast;
using Boo.Lang.Compiler.TypeSystem;
using Boo.Lang.Compiler.TypeSystem.Internal;
using Boo.Lang.Compiler.TypeSystem.Reflection;
using Boo.Lang.Compiler.TypeSystem.Services;
using Boo.Lang.Environments;
using Module = Boo.Lang.Compiler.Ast.Module;
namespace Boo.Lang.Compiler.Steps.MacroProcessing
{
sealed class ApplyAttributeTask
{
CompilerContext _context;
Ast.Attribute _attribute;
Type _type;
Node _targetNode;
public ApplyAttributeTask(CompilerContext context, Ast.Attribute attribute, Type type)
{
_context = context;
_attribute = attribute;
_type = type;
_targetNode = TargetNode();
}
private Node TargetNode()
{
return IsAssemblyAttribute() ? _context.CompileUnit : _attribute.ParentNode;
}
private bool IsAssemblyAttribute()
{
var module = _attribute.ParentNode as Module;
return module != null && module.AssemblyAttributes.Contains(_attribute);
}
public void Execute()
{
try
{
var attribute = CreateAstAttributeInstance();
if (attribute != null)
{
attribute.Initialize(_context);
attribute.Apply(_targetNode);
}
}
catch (Exception x)
{
_context.TraceError(x);
_context.Errors.Add(CompilerErrorFactory.AttributeApplicationError(x, _attribute, _type));
}
}
public IAstAttribute CreateAstAttributeInstance()
{
var attribute = CreateInstance(ConstructorArguments());
if (attribute == null) return null;
return _attribute.NamedArguments.Count > 0 ? InitializeProperties(attribute) : attribute;
}
private object[] ConstructorArguments()
{
return _attribute.Arguments.Count > 0 ? _attribute.Arguments.ToArray() : new object[0];
}
private IAstAttribute CreateInstance(object[] arguments)
{
try
{
var aa = (IAstAttribute)Activator.CreateInstance(_type, arguments);
aa.Attribute = _attribute;
return aa;
}
catch (MissingMethodException x)
{
_context.Errors.Add(CompilerErrorFactory.MissingConstructor(x, _attribute, _type, arguments));
return null;
}
}
private IAstAttribute InitializeProperties(IAstAttribute aa)
{
var initialized = true;
foreach (var p in _attribute.NamedArguments)
{
var success = SetFieldOrProperty(aa, p);
initialized = initialized && success;
}
return initialized ? aa : null;
}
bool SetFieldOrProperty(IAstAttribute aa, ExpressionPair p)
{
var name = p.First as ReferenceExpression;
if (name == null)
{
_context.Errors.Add(CompilerErrorFactory.NamedParameterMustBeIdentifier(p));
return false;
}
var members = FindMembers(name);
if (members.Length <= 0)
{
_context.Errors.Add(CompilerErrorFactory.NotAPublicFieldOrProperty(name, name.Name, Type()));
return false;
}
if (members.Length > 1)
{
_context.Errors.Add(CompilerErrorFactory.AmbiguousReference(name, members));
return false;
}
var member = members[0];
var property = member as PropertyInfo;
if (property != null)
{
property.SetValue(aa, p.Second, null);
return true;
}
var field = (FieldInfo)member;
field.SetValue(aa, p.Second);
return true;
}
private IType Type()
{
return My<TypeSystemServices>.Instance.Map(_type);
}
private MemberInfo[] FindMembers(ReferenceExpression name)
{
return _type.FindMembers(MemberTypes.Property | MemberTypes.Field, BindingFlags.Instance | BindingFlags.Public, System.Type.FilterName, name.Name);
}
}
/// <summary>
/// Step 2. Processes AST attributes.
/// </summary>
public class BindAndApplyAttributes : AbstractNamespaceSensitiveTransformerCompilerStep
{
private readonly List<ApplyAttributeTask> _pendingApplications = new List<ApplyAttributeTask>();
System.Text.StringBuilder _buffer = new System.Text.StringBuilder();
IType _astAttributeInterface;
public override void Initialize(CompilerContext context)
{
base.Initialize(context);
_astAttributeInterface = TypeSystemServices.Map(typeof(IAstAttribute));
}
override public void Run()
{
int iteration = 0;
while (iteration < Parameters.MaxExpansionIterations)
{
if (!BindAndApply())
break;
++iteration;
}
}
public bool BindAndApply()
{
return BindAndApply(CompileUnit);
}
public bool BindAndApply(Node node)
{
Visit(node);
return FlushPendingApplications();
}
private bool FlushPendingApplications()
{
if (_pendingApplications.Count == 0)
return false;
foreach (var application in _pendingApplications)
application.Execute();
_pendingApplications.Clear();
return true;
}
override public void OnModule(Module module)
{
EnterNamespace(InternalModule.ScopeFor(module));
try
{
Visit(module.Members);
Visit(module.Globals);
Visit(module.Attributes);
Visit(module.AssemblyAttributes);
}
finally
{
LeaveNamespace();
}
}
void VisitTypeDefinition(TypeDefinition node)
{
Visit(node.Members);
Visit(node.Attributes);
}
override public void OnClassDefinition(ClassDefinition node)
{
VisitTypeDefinition(node);
}
override public void OnInterfaceDefinition(InterfaceDefinition node)
{
VisitTypeDefinition(node);
}
override public void OnStructDefinition(StructDefinition node)
{
VisitTypeDefinition(node);
}
override public void OnEnumDefinition(EnumDefinition node)
{
VisitTypeDefinition(node);
}
override public void OnAttribute(Ast.Attribute attribute)
{
if (null != attribute.Entity)
return;
var entity = NameResolutionService.ResolveQualifiedName(BuildAttributeName(attribute.Name, true))
?? NameResolutionService.ResolveQualifiedName(BuildAttributeName(attribute.Name, false))
?? NameResolutionService.ResolveQualifiedName(attribute.Name);
if (entity == null)
{
var suggestion = NameResolutionService.GetMostSimilarTypeName(BuildAttributeName(attribute.Name, true))
?? NameResolutionService.GetMostSimilarTypeName(BuildAttributeName(attribute.Name, false));
Error(attribute, CompilerErrorFactory.UnknownAttribute(attribute, attribute.Name, suggestion));
return;
}
if (entity.IsAmbiguous())
{
Error(attribute, CompilerErrorFactory.AmbiguousReference(
attribute,
attribute.Name,
((Ambiguous)entity).Entities));
return;
}
if (EntityType.Type != entity.EntityType)
{
Error(attribute, CompilerErrorFactory.NameNotType(attribute, attribute.Name, entity, null));
return;
}
IType attributeType = ((ITypedEntity)entity).Type;
if (IsAstAttribute(attributeType))
{
ExternalType externalType = attributeType as ExternalType;
if (null == externalType)
{
Error(attribute, CompilerErrorFactory.AstAttributeMustBeExternal(attribute, attributeType));
}
else
{
ScheduleAttributeApplication(attribute, externalType.ActualType);
RemoveCurrentNode();
}
}
else
{
if (!IsSystemAttribute(attributeType))
{
Error(attribute, CompilerErrorFactory.TypeNotAttribute(attribute, attributeType));
}
else
{
// remember the attribute's type
attribute.Name = attributeType.FullName;
attribute.Entity = entity;
CheckAttributeParameters(attribute);
}
}
}
private void CheckAttributeParameters(Ast.Attribute node)
{
foreach (var e in node.Arguments)
if (e.NodeType == NodeType.BinaryExpression && ((BinaryExpression) e).Operator == BinaryOperatorType.Assign)
Error(node, CompilerErrorFactory.ColonInsteadOfEquals(node));
}
void Error(Ast.Attribute node, CompilerError error)
{
node.Entity = TypeSystemServices.ErrorEntity;
Errors.Add(error);
}
void ScheduleAttributeApplication(Ast.Attribute attribute, Type type)
{
_pendingApplications.Add(new ApplyAttributeTask(Context, attribute, type));
}
string BuildAttributeName(string name, bool forcePascalNaming)
{
_buffer.Length = 0;
if (forcePascalNaming && !Char.IsUpper(name[0]))
{
_buffer.Append(Char.ToUpper(name[0]));
_buffer.Append(name.Substring(1));
_buffer.Append("Attribute");
}
else
{
_buffer.Append(name);
_buffer.Append("Attribute");
}
return _buffer.ToString();
}
bool IsSystemAttribute(IType type)
{
return TypeSystemServices.IsAttribute(type);
}
bool IsAstAttribute(IType type)
{
return TypeCompatibilityRules.IsAssignableFrom(_astAttributeInterface, type);
}
}
}
| {
"content_hash": "00d7963ddf41bfa1b942a397951cee33",
"timestamp": "",
"source": "github",
"line_count": 375,
"max_line_length": 150,
"avg_line_length": 28.258666666666667,
"alnum_prop": 0.6871756157403038,
"repo_name": "KidFashion/boo",
"id": "27443ab28fee75b2ca5fe5f42c03a5960affabf9",
"size": "10599",
"binary": false,
"copies": "5",
"ref": "refs/heads/master",
"path": "src/Boo.Lang.Compiler/Steps/MacroProcessing/BindAndApplyAttributes.cs",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "ANTLR",
"bytes": "2999"
},
{
"name": "Batchfile",
"bytes": "2897"
},
{
"name": "Boo",
"bytes": "1588426"
},
{
"name": "C",
"bytes": "2360"
},
{
"name": "C#",
"bytes": "4897998"
},
{
"name": "C++",
"bytes": "275896"
},
{
"name": "Emacs Lisp",
"bytes": "106020"
},
{
"name": "GAP",
"bytes": "770238"
},
{
"name": "Groff",
"bytes": "5142"
},
{
"name": "HTML",
"bytes": "413429"
},
{
"name": "Java",
"bytes": "2086700"
},
{
"name": "Lex",
"bytes": "4633"
},
{
"name": "Makefile",
"bytes": "392646"
},
{
"name": "Pascal",
"bytes": "179584"
},
{
"name": "Python",
"bytes": "156485"
},
{
"name": "Shell",
"bytes": "146672"
},
{
"name": "VimL",
"bytes": "9521"
},
{
"name": "Visual Basic",
"bytes": "908"
}
],
"symlink_target": ""
} |
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>tortoise-hare-algorithm: 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.15.0 / tortoise-hare-algorithm - 8.8.0</a></li>
</ul>
</div>
</div>
</div>
<div class="article">
<div class="row">
<div class="col-md-12">
<a href="../..">« Up</a>
<h1>
tortoise-hare-algorithm
<small>
8.8.0
<span class="label label-info">Not compatible 👼</span>
</small>
</h1>
<p>📅 <em><script>document.write(moment("2022-06-02 22:30:29 +0000", "YYYY-MM-DD HH:mm:ss Z").fromNow());</script> (2022-06-02 22:30:29 UTC)</em><p>
<h2>Context</h2>
<pre># Packages matching: installed
# Name # Installed # Synopsis
base-bigarray base
base-threads base
base-unix base
conf-findutils 1 Virtual package relying on findutils
conf-gmp 4 Virtual package relying on a GMP lib system installation
coq 8.15.0 Formal proof management system
dune 3.2.0 Fast, portable, and opinionated build system
ocaml 4.14.0 The OCaml compiler (virtual package)
ocaml-base-compiler 4.14.0 Official release 4.14.0
ocaml-config 2 OCaml Switch Configuration
ocaml-options-vanilla 1 Ensure that OCaml is compiled with no special options enabled
ocamlfind 1.9.3 A library manager for OCaml
zarith 1.12 Implements arithmetic and logical operations over arbitrary-precision integers
# opam file:
opam-version: "2.0"
maintainer: "Hugo.Herbelin@inria.fr"
homepage: "https://github.com/coq-contribs/tortoise-hare-algorithm"
license: "Unknown"
build: [make "-j%{jobs}%"]
install: [make "install"]
remove: ["rm" "-R" "%{lib}%/coq/user-contrib/TortoiseHareAlgorithm"]
depends: [
"ocaml"
"coq" {>= "8.8" & < "8.9~"}
]
tags: [
"keyword: program verification"
"keyword: paths"
"keyword: cycle detection"
"keyword: graphs"
"keyword: graph theory"
"keyword: finite sets"
"keyword: Floyd"
"category: Computer Science/Decision Procedures and Certified Algorithms/Correctness proofs of algorithms"
"date: 2007-02"
]
authors: [ "Jean-Christophe Filliâtre" ]
bug-reports: "https://github.com/coq-contribs/tortoise-hare-algorithm/issues"
dev-repo: "git+https://github.com/coq-contribs/tortoise-hare-algorithm.git"
synopsis: "Tortoise and the hare algorithm"
description: """
Correctness proof of Floyd's cycle-finding algorithm, also known as
the "tortoise and the hare"-algorithm.
See http://en.wikipedia.org/wiki/Floyd's_cycle-finding_algorithm"""
flags: light-uninstall
url {
src:
"https://github.com/coq-contribs/tortoise-hare-algorithm/archive/v8.8.0.tar.gz"
checksum: "md5=5fdf82dd175770a66c50d9e6213309c4"
}
</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-tortoise-hare-algorithm.8.8.0 coq.8.15.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.15.0).
The following dependencies couldn't be met:
- coq-tortoise-hare-algorithm -> coq < 8.9~ -> ocaml < 4.10
base of this switch (use `--unlock-base' to force)
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-tortoise-hare-algorithm.8.8.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": "3acd8729c63e2a2af30f00c4383e33ea",
"timestamp": "",
"source": "github",
"line_count": 177,
"max_line_length": 159,
"avg_line_length": 42.23728813559322,
"alnum_prop": 0.5571161048689138,
"repo_name": "coq-bench/coq-bench.github.io",
"id": "c37407233574baaae5539b99e0e57b4bcd08d9bf",
"size": "7502",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "clean/Linux-x86_64-4.14.0-2.0.10/released/8.15.0/tortoise-hare-algorithm/8.8.0.html",
"mode": "33188",
"license": "mit",
"language": [],
"symlink_target": ""
} |
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<!-- This file documents the GNU Assembler "as".
Copyright (C) 1991-2017 Free Software Foundation, Inc.
Permission is granted to copy, distribute and/or modify this document
under the terms of the GNU Free Documentation License, Version 1.3
or any later version published by the Free Software Foundation;
with no Invariant Sections, with no Front-Cover Texts, and with no
Back-Cover Texts. A copy of the license is included in the
section entitled "GNU Free Documentation License".
-->
<!-- Created by GNU Texinfo 5.2, http://www.gnu.org/software/texinfo/ -->
<head>
<title>Using as: TILEPro-Dependent</title>
<meta name="description" content="Using as: TILEPro-Dependent">
<meta name="keywords" content="Using as: TILEPro-Dependent">
<meta name="resource-type" content="document">
<meta name="distribution" content="global">
<meta name="Generator" content="makeinfo">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<link href="index.html#Top" rel="start" title="Top">
<link href="AS-Index.html#AS-Index" rel="index" title="AS Index">
<link href="index.html#SEC_Contents" rel="contents" title="Table of Contents">
<link href="Machine-Dependencies.html#Machine-Dependencies" rel="up" title="Machine Dependencies">
<link href="TILEPro-Options.html#TILEPro-Options" rel="next" title="TILEPro Options">
<link href="TILE_002dGx-Directives.html#TILE_002dGx-Directives" rel="prev" title="TILE-Gx Directives">
<style type="text/css">
<!--
a.summary-letter {text-decoration: none}
blockquote.smallquotation {font-size: smaller}
div.display {margin-left: 3.2em}
div.example {margin-left: 3.2em}
div.indentedblock {margin-left: 3.2em}
div.lisp {margin-left: 3.2em}
div.smalldisplay {margin-left: 3.2em}
div.smallexample {margin-left: 3.2em}
div.smallindentedblock {margin-left: 3.2em; font-size: smaller}
div.smalllisp {margin-left: 3.2em}
kbd {font-style:oblique}
pre.display {font-family: inherit}
pre.format {font-family: inherit}
pre.menu-comment {font-family: serif}
pre.menu-preformatted {font-family: serif}
pre.smalldisplay {font-family: inherit; font-size: smaller}
pre.smallexample {font-size: smaller}
pre.smallformat {font-family: inherit; font-size: smaller}
pre.smalllisp {font-size: smaller}
span.nocodebreak {white-space:nowrap}
span.nolinebreak {white-space:nowrap}
span.roman {font-family:serif; font-weight:normal}
span.sansserif {font-family:sans-serif; font-weight:normal}
ul.no-bullet {list-style: none}
-->
</style>
</head>
<body lang="en" bgcolor="#FFFFFF" text="#000000" link="#0000FF" vlink="#800080" alink="#FF0000">
<a name="TILEPro_002dDependent"></a>
<div class="header">
<p>
Next: <a href="V850_002dDependent.html#V850_002dDependent" accesskey="n" rel="next">V850-Dependent</a>, Previous: <a href="TILE_002dGx_002dDependent.html#TILE_002dGx_002dDependent" accesskey="p" rel="prev">TILE-Gx-Dependent</a>, Up: <a href="Machine-Dependencies.html#Machine-Dependencies" accesskey="u" rel="up">Machine Dependencies</a> [<a href="index.html#SEC_Contents" title="Table of contents" rel="contents">Contents</a>][<a href="AS-Index.html#AS-Index" title="Index" rel="index">Index</a>]</p>
</div>
<hr>
<a name="TILEPro-Dependent-Features"></a>
<h3 class="section">9.47 TILEPro Dependent Features</h3>
<a name="index-TILEPro-support"></a>
<table class="menu" border="0" cellspacing="0">
<tr><td align="left" valign="top">• <a href="TILEPro-Options.html#TILEPro-Options" accesskey="1">TILEPro Options</a>:</td><td> </td><td align="left" valign="top">TILEPro Options
</td></tr>
<tr><td align="left" valign="top">• <a href="TILEPro-Syntax.html#TILEPro-Syntax" accesskey="2">TILEPro Syntax</a>:</td><td> </td><td align="left" valign="top">TILEPro Syntax
</td></tr>
<tr><td align="left" valign="top">• <a href="TILEPro-Directives.html#TILEPro-Directives" accesskey="3">TILEPro Directives</a>:</td><td> </td><td align="left" valign="top">TILEPro Directives
</td></tr>
</table>
</body>
</html>
| {
"content_hash": "cb8b0ffff506c4b2c25bb58da1de6883",
"timestamp": "",
"source": "github",
"line_count": 86,
"max_line_length": 508,
"avg_line_length": 47.58139534883721,
"alnum_prop": 0.7331378299120235,
"repo_name": "ATM-HSW/mbed_target",
"id": "64c51000ee6dcbda871ee649eb904dd727afc0c9",
"size": "4092",
"binary": false,
"copies": "4",
"ref": "refs/heads/master",
"path": "buildtools/gcc-arm-none-eabi-6-2017-q2/share/doc/gcc-arm-none-eabi/html/as.html/TILEPro_002dDependent.html",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Assembly",
"bytes": "29493"
},
{
"name": "Batchfile",
"bytes": "948"
},
{
"name": "C",
"bytes": "3167609"
},
{
"name": "C++",
"bytes": "12419698"
},
{
"name": "HTML",
"bytes": "27891106"
},
{
"name": "MATLAB",
"bytes": "230413"
},
{
"name": "Makefile",
"bytes": "2798"
},
{
"name": "Python",
"bytes": "225136"
},
{
"name": "Shell",
"bytes": "50803"
},
{
"name": "XC",
"bytes": "9173"
},
{
"name": "XS",
"bytes": "9123"
}
],
"symlink_target": ""
} |
<?php
/**
* @package silverstripe-multisites
*/
class MultisitesFileFieldExtension extends Extension {
/**
* prepends an assets/currentsite folder to the upload folder name.
**/
public function useMultisitesFolder(){
$site = Multisites::inst()->getActiveSite();
$multisiteFolder = $site->Folder();
if(!$multisiteFolder->exists()){
$site->createAssetsSubfolder(true);
$multisiteFolder = $site->Folder();
}
$this->owner->setFolderName($multisiteFolder->Name . '/' . $this->owner->getFolderName());
return $this->owner;
}
}
| {
"content_hash": "92770ef2078c1fece3ee5afc5cf70942",
"timestamp": "",
"source": "github",
"line_count": 24,
"max_line_length": 92,
"avg_line_length": 23.041666666666668,
"alnum_prop": 0.6853526220614828,
"repo_name": "Zauberfisch/silverstripe-multisites",
"id": "d619e895f79cbbd4e1e94044886e0e8253907097",
"size": "553",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "code/extensions/MultisitesFileFieldExtension.php",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "CSS",
"bytes": "211"
},
{
"name": "JavaScript",
"bytes": "4375"
},
{
"name": "PHP",
"bytes": "48750"
},
{
"name": "Scheme",
"bytes": "428"
}
],
"symlink_target": ""
} |
These examples demonstrate how to perform several Amazon Relational Database Service (Amazon RDS) operations using the developer preview version of the AWS SDK for Rust.
Amazon RDS is a web service that makes it easier to set up, operate, and scale a relational database in the cloud.
## Code examples
- [Describe instances](src/bin/rds-helloworld.rs) (DescribeDbInstances)
## ⚠ Important
- We recommend that you grant this code least privilege,
or at most the minimum permissions required to perform the task.
For more information, see
[Grant Least Privilege](https://docs.aws.amazon.com/IAM/latest/UserGuide/best-practices.html#grant-least-privilege)
in the AWS Identity and Access Management User Guide.
- This code has not been tested in all AWS Regions.
Some AWS services are available only in specific
[Regions](https://aws.amazon.com/about-aws/global-infrastructure/regional-product-services).
- Running this code might result in charges to your AWS account.
## Running the code examples
### Prerequisites
You must have an AWS account, and have configured your default credentials and AWS Region as described in [https://github.com/awslabs/aws-sdk-rust](https://github.com/awslabs/aws-sdk-rust).
## rds-helloworld
This code example displays information about your RDS instances in the Region.
### Usage
```cargo run --bin rds-helloworld [-r REGION] [-v]```
where:
- _REGION_ is the Region in which the client is created.
If not supplied, uses the value of the **AWS_REGION** environment variable.
If the environment variable is not set, defaults to **us-west-2**.
- __-v__ enables displaying additional information.
## Resources
- [AWS SDK for Rust repo](https://github.com/awslabs/aws-sdk-rust)
- [AWS SDK for Rust API Reference for Amazon RDS](https://docs.rs/aws-sdk-rds)
- [AWS SDK for Rust API Reference Guide](https://awslabs.github.io/aws-sdk-rust/aws_sdk_config/index.html)
## Contributing
To propose a new code example to the AWS documentation team,
see [CONTRIBUTING.md](https://github.com/awsdocs/aws-doc-sdk-examples/blob/master/CONTRIBUTING.md).
The team prefers to create code examples that show broad scenarios rather than individual API calls.
Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. SPDX-License-Identifier: Apache-2.0
| {
"content_hash": "ffdf7d89e14fe68e7386130f85634046",
"timestamp": "",
"source": "github",
"line_count": 54,
"max_line_length": 189,
"avg_line_length": 42.75925925925926,
"alnum_prop": 0.7652663490688609,
"repo_name": "awsdocs/aws-doc-sdk-examples",
"id": "4363bd35daa0fbee9f96ad9712dcc54edd8dbfb1",
"size": "2372",
"binary": false,
"copies": "1",
"ref": "refs/heads/main",
"path": "rust_dev_preview/rds/README.md",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "ABAP",
"bytes": "476653"
},
{
"name": "Batchfile",
"bytes": "900"
},
{
"name": "C",
"bytes": "3852"
},
{
"name": "C#",
"bytes": "2051923"
},
{
"name": "C++",
"bytes": "943634"
},
{
"name": "CMake",
"bytes": "82068"
},
{
"name": "CSS",
"bytes": "33378"
},
{
"name": "Dockerfile",
"bytes": "2243"
},
{
"name": "Go",
"bytes": "1764292"
},
{
"name": "HTML",
"bytes": "319090"
},
{
"name": "Java",
"bytes": "4966853"
},
{
"name": "JavaScript",
"bytes": "1655476"
},
{
"name": "Jupyter Notebook",
"bytes": "9749"
},
{
"name": "Kotlin",
"bytes": "1099902"
},
{
"name": "Makefile",
"bytes": "4922"
},
{
"name": "PHP",
"bytes": "1220594"
},
{
"name": "Python",
"bytes": "2507509"
},
{
"name": "Ruby",
"bytes": "500331"
},
{
"name": "Rust",
"bytes": "558811"
},
{
"name": "Shell",
"bytes": "63776"
},
{
"name": "Swift",
"bytes": "267325"
},
{
"name": "TypeScript",
"bytes": "119632"
}
],
"symlink_target": ""
} |
<!DOCTYPE html>
<html>
<head>
<!-- Required meta tags-->
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, minimum-scale=1, user-scalable=no, minimal-ui">
<meta name="apple-mobile-web-app-capable" content="yes">
<!-- Color theme for statusbar -->
<meta name="theme-color" content="#2196f3">
<!-- Your app title -->
<title>Maths Easy</title>
<!-- Path to Framework7 Library CSS, Material Theme -->
<link rel="stylesheet" href="css/framework7.material.min.css">
<!-- Path to Framework7 color related styles, Material Theme -->
<link rel="stylesheet" href="css/framework7.material.colors.min.css">
<!-- Path to your custom app styles-->
<link rel="stylesheet" href="css/my-app.css">
<!-- Path to Framework7 icons -->
<link rel="stylesheet" href="css/framework7-icons.css">
</head>
<body>
<!-- Views -->
<div class="views">
<!-- Your main view, should have "view-main" class -->
<div class="view view-main">
<!-- Pages container, because we use fixed navbar and toolbar, it has additional appropriate classes-->
<div class="pages navbar-fixed toolbar-fixed">
<!-- Page, "data-page" contains page name -->
<div data-page="index" class="page">
<!-- Top Navbar. In Material theme it should be inside of the page-->
<div class="navbar">
<div class="navbar-inner">
<div class="center">Maths Easy</div>
</div>
</div>
<!-- Toolbar. In Material theme it should be inside of the page-->
<div class="toolbar toolbar-bottom">
<div class="toolbar-inner">
<a href="index.html" class="link"><i class="f7-icons size-22">collection</i>Lessons</a>
<a href="about.html" class="link"><i class="f7-icons size-22">info</i>About</a>
<a href="contact.html" class="link"><i class="f7-icons size-22">chat</i>Contact</a>
</div>
</div>
<!-- Scrollable page content -->
<div class="page-content">
<div class="list-block homelistblock">
<ul>
<li><p class="homebuttons"><a href="numbersystem.html" class="button button-big button-fill button-raised color-pink">Number System</a></p></li>
<li><p class="homebuttons"><a href="average.html" class="button button-big button-fill button-raised color-red">Average</a></p></li>
<li><p class="homebuttons"><a href="timedistanceandwork.html" class="button button-big button-fill button-raised color-cyan">Time Distance & Work</a></p></li>
<li><p class="homebuttons"><a href="percentage.html" class="button button-big button-fill button-raised color-green">Percentage</a></p></li>
<li><p class="homebuttons"><a href="profitandloss.html" class="button button-big button-fill button-raised color-purple">Profit & Loss</a></p></li>
<li><p class="homebuttons"><a href="simpleandcompound.html" class="button button-big button-fill button-raised color-indigo">Simple & Compound Interest</a></p></li>
</ul>
</div>
</div>
</div>
</div>
</div>
<!-- Path to Framework7 Library JS-->
<script type="text/javascript" src="js/framework7.min.js"></script>
<!-- Path to your app js-->
<script type="text/javascript" src="js/my-app.js"></script>
<!-- Path to your cordova js-->
<script type="text/javascript" src="js/index.js"></script>
<!-- For Maths Expressions -->
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/mathjax/2.7.0/MathJax.js?config=TeX-MML-AM_CHTML"></script>
</body>
</html> | {
"content_hash": "a810988499e2c427e204efac5d765280",
"timestamp": "",
"source": "github",
"line_count": 72,
"max_line_length": 168,
"avg_line_length": 49.486111111111114,
"alnum_prop": 0.6424361493123772,
"repo_name": "alapanme/Maths-Easy",
"id": "b86ef97091fc06a13e77104a0daa957536265fa9",
"size": "3563",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "index.html",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "996100"
},
{
"name": "HTML",
"bytes": "17153"
},
{
"name": "JavaScript",
"bytes": "835632"
}
],
"symlink_target": ""
} |
package org.msgpack.template.builder;
import java.io.IOException;
import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import java.lang.reflect.Type;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.msgpack.MessageTypeException;
import org.msgpack.packer.Packer;
import org.msgpack.template.Template;
import org.msgpack.template.AbstractTemplate;
import org.msgpack.template.TemplateRegistry;
import org.msgpack.unpacker.Unpacker;
@SuppressWarnings({ "rawtypes", "unchecked" })
public class ReflectionTemplateBuilder extends AbstractTemplateBuilder {
private static Logger LOG = Logger.getLogger(ReflectionBeansTemplateBuilder.class.getName());
protected static abstract class ReflectionFieldTemplate extends AbstractTemplate<Object> {
protected FieldEntry entry;
ReflectionFieldTemplate(final FieldEntry entry) {
this.entry = entry;
}
void setNil(Object v) {
entry.set(v, null);
}
}
static final class FieldTemplateImpl extends ReflectionFieldTemplate {
private Template template;
public FieldTemplateImpl(final FieldEntry entry, final Template template) {
super(entry);
this.template = template;
}
@Override
public void write(Packer packer, Object v, boolean required)
throws IOException {
template.write(packer, v, required);
}
@Override
public Object read(Unpacker unpacker, Object to, boolean required)
throws IOException {
// Class<Object> type = (Class<Object>) entry.getType();
Object f = entry.get(to);
Object o = template.read(unpacker, f, required);
if (o != f) {
entry.set(to, o);
}
return o;
}
}
protected static class ReflectionClassTemplate<T> extends AbstractTemplate<T> {
protected Class<T> targetClass;
protected ReflectionFieldTemplate[] templates;
protected ReflectionClassTemplate(Class<T> targetClass, ReflectionFieldTemplate[] templates) {
this.targetClass = targetClass;
this.templates = templates;
}
@Override
public void write(Packer packer, T target, boolean required)
throws IOException {
if (target == null) {
if (required) {
throw new MessageTypeException("attempted to write null");
}
packer.writeNil();
return;
}
try {
packer.writeArrayBegin(templates.length);
for (ReflectionFieldTemplate tmpl : templates) {
if (!tmpl.entry.isAvailable()) {
packer.writeNil();
continue;
}
Object obj = tmpl.entry.get(target);
if (obj == null) {
if (tmpl.entry.isNotNullable()) {
throw new MessageTypeException(tmpl.entry.getName()
+ " cannot be null by @NotNullable");
}
packer.writeNil();
} else {
tmpl.write(packer, obj, true);
}
}
packer.writeArrayEnd();
} catch (IOException e) {
throw e;
} catch (Exception e) {
throw new MessageTypeException(e);
}
}
@Override
public T read(Unpacker unpacker, T to, boolean required)
throws IOException {
if (!required && unpacker.trySkipNil()) {
return null;
}
try {
if (to == null) {
to = targetClass.newInstance();
}
unpacker.readArrayBegin();
for (int i = 0; i < templates.length; i++) {
ReflectionFieldTemplate tmpl = templates[i];
if (!tmpl.entry.isAvailable()) {
unpacker.skip();
} else if (tmpl.entry.isOptional() && unpacker.trySkipNil()) {
// if Optional + nil, than keep default value
} else {
tmpl.read(unpacker, to, false);
}
}
unpacker.readArrayEnd();
return to;
} catch (IOException e) {
throw e;
} catch (Exception e) {
throw new MessageTypeException(e);
}
}
}
public ReflectionTemplateBuilder(TemplateRegistry registry) {
this(registry, null);
}
public ReflectionTemplateBuilder(TemplateRegistry registry, ClassLoader cl) {
super(registry);
}
@Override
public boolean matchType(Type targetType, boolean hasAnnotation) {
Class<?> targetClass = (Class<?>) targetType;
boolean matched = matchAtClassTemplateBuilder(targetClass, hasAnnotation);
if (matched && LOG.isLoggable(Level.FINE)) {
LOG.fine("matched type: " + targetClass.getName());
}
return matched;
}
@Override
public <T> Template<T> buildTemplate(Class<T> targetClass, FieldEntry[] entries) {
if (entries == null) {
throw new NullPointerException("entries is null: " + targetClass);
}
ReflectionFieldTemplate[] tmpls = toTemplates(entries);
return new ReflectionClassTemplate<T>(targetClass, tmpls);
}
protected ReflectionFieldTemplate[] toTemplates(FieldEntry[] entries) {
// TODO Now it is simply cast. #SF
for (FieldEntry entry : entries) {
Field field = ((DefaultFieldEntry) entry).getField();
int mod = field.getModifiers();
if (!Modifier.isPublic(mod)) {
field.setAccessible(true);
}
}
ReflectionFieldTemplate[] templates = new ReflectionFieldTemplate[entries.length];
for (int i = 0; i < entries.length; i++) {
FieldEntry entry = entries[i];
// Class<?> t = entry.getType();
Template template = registry.lookup(entry.getGenericType());
templates[i] = new FieldTemplateImpl(entry, template);
}
return templates;
}
}
| {
"content_hash": "3d7fc79fbe379a97459bdfa90992d302",
"timestamp": "",
"source": "github",
"line_count": 187,
"max_line_length": 102,
"avg_line_length": 34.79679144385027,
"alnum_prop": 0.5506377747041648,
"repo_name": "mikolak-net/msgpack-java",
"id": "1db9752314e0f3d25812ac0556df6fe36a9bf8f2",
"size": "7173",
"binary": false,
"copies": "3",
"ref": "refs/heads/master",
"path": "src/main/java/org/msgpack/template/builder/ReflectionTemplateBuilder.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Java",
"bytes": "1710403"
},
{
"name": "Shell",
"bytes": "91"
}
],
"symlink_target": ""
} |
<?php
/**
* Credit Card (Payflow Pro) Payment method xml renderer
*
* @category Mage
* @package Mage_XmlConnect
* @author Magento Core Team <core@magentocommerce.com>
*/
class Mage_XmlConnect_Block_Checkout_Payment_Method_Paypal_Payflow extends Mage_Payment_Block_Form_Ccsave
{
/**
* Prevent any rendering
*
* @return string
*/
protected function _toHtml()
{
return '';
}
/**
* Retrieve payment method model
*
* @return Mage_Payment_Model_Method_Abstract
*/
public function getMethod()
{
$method = $this->getData('method');
if (!$method) {
$method = Mage::getModel('paypal/payflowpro');
$this->setData('method', $method);
}
return $method;
}
/**
* Add Payflow Pro payment method form to payment XML object
*
* @param Mage_XmlConnect_Model_Simplexml_Element $paymentItemXmlObj
* @return Mage_XmlConnect_Model_Simplexml_Element
*/
public function addPaymentFormToXmlObj(Mage_XmlConnect_Model_Simplexml_Element $paymentItemXmlObj)
{
$method = $this->getMethod();
if (!$method) {
return $paymentItemXmlObj;
}
$formXmlObj = $paymentItemXmlObj->addChild('form');
$formXmlObj->addAttribute('name', 'payment_form_' . $method->getCode());
$formXmlObj->addAttribute('method', 'post');
$_ccType = $this->getInfoData('cc_type');
$ccTypes = '';
foreach ($this->getCcAvailableTypes() as $_typeCode => $_typeName) {
if (!$_typeCode) {
continue;
}
$ccTypes .= '
<item' . ($_typeCode == $_ccType ? ' selected="1"' : '') . '>
<label>' . $_typeName . '</label>
<value>' . $_typeCode . '</value>
</item>';
}
$ccMonthes = '';
$_ccExpMonth = $this->getInfoData('cc_exp_month');
foreach ($this->getCcMonths() as $k => $v) {
if (!$k) {
continue;
}
$ccMonthes .= '
<item' . ($k == $_ccExpMonth ? ' selected="1"' : '') . '>
<label>' . $v . '</label>
<value>' . ($k ? $k : '') . '</value>
</item>';
}
$ccYears = '';
$_ccExpYear = $this->getInfoData('cc_exp_year');
foreach ($this->getCcYears() as $k => $v) {
if (!$k) {
continue;
}
$ccYears .= '
<item' . ($k == $_ccExpYear ? ' selected="1"' : '') . '>
<label>' . $v . '</label>
<value>' . ($k ? $k : '') . '</value>
</item>';
}
$verification = '';
if ($this->hasVerification()) {
$verification = <<<EOT
<field name="payment[cc_cid]" type="text" label="{$this->__('Card Verification Number')}" required="true">
<validators>
<validator relation="payment[cc_type]" type="credit_card_svn" message="{$this->__('Card verification number is wrong')}'"/>
</validators>
</field>
EOT;
}
$xml = <<<EOT
<fieldset>
<field name="payment[cc_type]" type="select" label="{$this->__('Credit Card Type')}" required="true">
<values>
$ccTypes
</values>
</field>
<field name="payment[cc_number]" type="text" label="{$this->__('Credit Card Number')}" required="true">
<validators>
<validator relation="payment[cc_type]" type="credit_card" message="{$this->__('Credit card number does not match credit card type.')}"/>
</validators>
</field>
<field name="payment[cc_exp_month]" type="select" label="{$this->__('Expiration Date - Month')}" required="true">
<values>
$ccMonthes
</values>
</field>
<field name="payment[cc_exp_year]" type="select" label="{$this->helper('xmlconnect')->__('Expiration Date - Year')}" required="true">
<values>
$ccYears
</values>
</field>
$verification
</fieldset>
EOT;
$fieldsetXmlObj = Mage::getModel('xmlconnect/simplexml_element', $xml);
$formXmlObj->appendChild($fieldsetXmlObj);
}
}
| {
"content_hash": "c14b1a4a1e8befa0c593ad4466fffdda",
"timestamp": "",
"source": "github",
"line_count": 136,
"max_line_length": 148,
"avg_line_length": 31.08823529411765,
"alnum_prop": 0.5137180700094608,
"repo_name": "5452/durex",
"id": "97b9bb7cc2b944f22875ee806098dd839812855f",
"size": "5187",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "includes/src/Mage_XmlConnect_Block_Checkout_Payment_Method_Paypal_Payflow.php",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "ActionScript",
"bytes": "19946"
},
{
"name": "CSS",
"bytes": "2190550"
},
{
"name": "JavaScript",
"bytes": "1290492"
},
{
"name": "PHP",
"bytes": "102689019"
},
{
"name": "Shell",
"bytes": "642"
},
{
"name": "XSLT",
"bytes": "2066"
}
],
"symlink_target": ""
} |
static std::string getJavaStirng(JNIEnv *env, jstring str)
{
const char* tmp = env->GetStringUTFChars(str, NULL);
std::string result(tmp);
env->ReleaseStringUTFChars(str, tmp);
return result;
}
extern "C" {
using namespace vmf;
//n_delete(long nativeObj);
JNIEXPORT void JNICALL Java_com_intel_vmf_Compressor_n_1delete(JNIEnv *env, jclass, jlong self);
JNIEXPORT void JNICALL Java_com_intel_vmf_Compressor_n_1delete(JNIEnv *env, jclass, jlong self)
{
static const char method_name[] = "Compressor::n_1delete";
try
{
std::shared_ptr<Compressor>* obj = (std::shared_ptr<Compressor>*) self;
if (obj == NULL || *obj == NULL) VMF_EXCEPTION(NullPointerException, "Compressor (self) is null pointer.");
delete obj;
}
catch (const std::exception &e) { throwJavaException(env, &e, method_name); }
catch (...) { throwJavaException(env, 0, method_name); }
}
//long n_create(String str);
JNIEXPORT jlong JNICALL Java_com_intel_vmf_Compressor_n_1create(JNIEnv *env, jclass, jstring id);
JNIEXPORT jlong JNICALL Java_com_intel_vmf_Compressor_n_1create(JNIEnv *env, jclass, jstring id)
{
static const char method_name[] = "Compressor::n_1create";
try
{
if (id == 0) VMF_EXCEPTION(NullPointerException, "Compressor ID can't be null.");
return (jlong) new std::shared_ptr<Compressor>(Compressor::create(getJavaStirng(env, id)));
}
catch (const std::exception &e) { throwJavaException(env, &e, method_name); }
catch (...) { throwJavaException(env, 0, method_name); }
return 0;
}
//String n_getId(long self);
JNIEXPORT jstring JNICALL Java_com_intel_vmf_Compressor_n_1getId(JNIEnv *env, jclass, jlong self);
JNIEXPORT jstring JNICALL Java_com_intel_vmf_Compressor_n_1getId(JNIEnv *env, jclass, jlong self)
{
static const char method_name[] = "Compressor::n_1getId";
try
{
std::shared_ptr<Compressor>* obj = (std::shared_ptr<Compressor>*) self;
if (obj == NULL || *obj == NULL) VMF_EXCEPTION(NullPointerException, "Compressor (self) is null pointer.");
return env->NewStringUTF((*obj)->getId().c_str());
}
catch (const std::exception &e) { throwJavaException(env, &e, method_name); }
catch (...) { throwJavaException(env, 0, method_name); }
return 0;
}
//long n_createNewInstance(long self);
JNIEXPORT jlong JNICALL Java_com_intel_vmf_Compressor_n_1createNewInstance(JNIEnv *env, jclass, jlong self);
JNIEXPORT jlong JNICALL Java_com_intel_vmf_Compressor_n_1createNewInstance(JNIEnv *env, jclass, jlong self)
{
static const char method_name[] = "Compressor::n_1createNewInstance";
try
{
std::shared_ptr<Compressor>* obj = (std::shared_ptr<Compressor>*) self;
if (obj == NULL || *obj == NULL) VMF_EXCEPTION(NullPointerException, "Compressor (self) is null pointer.");
return (jlong) new std::shared_ptr<Compressor>( (*obj)->createNewInstance() );
}
catch (const std::exception &e) { throwJavaException(env, &e, method_name); }
catch (...) { throwJavaException(env, 0, method_name); }
return 0;
}
//long n_compress(long self, String str);
JNIEXPORT jlong JNICALL Java_com_intel_vmf_Compressor_n_1compress(JNIEnv *env, jclass, jlong self, jstring str);
JNIEXPORT jlong JNICALL Java_com_intel_vmf_Compressor_n_1compress(JNIEnv *env, jclass, jlong self, jstring str)
{
static const char method_name[] = "Compressor::n_1compress";
try
{
std::shared_ptr<Compressor>* obj = (std::shared_ptr<Compressor>*) self;
if (obj == NULL || *obj == NULL) VMF_EXCEPTION(NullPointerException, "Compressor (self) is null pointer.");
if (str == 0) VMF_EXCEPTION(NullPointerException, "String to compress can't be null.");
vmf_rawbuffer rbuf;
(*obj)->compress(getJavaStirng(env, str), rbuf);
return (jlong) new std::shared_ptr<Variant>( new Variant( rbuf ) );
}
catch (const std::exception &e) { throwJavaException(env, &e, method_name); }
catch (...) { throwJavaException(env, 0, method_name); }
return 0;
}
//String n_decompress(long self, long variantAddr);
JNIEXPORT jstring JNICALL Java_com_intel_vmf_Compressor_n_1decompress(JNIEnv *env, jclass, jlong self, jlong variantAddr);
JNIEXPORT jstring JNICALL Java_com_intel_vmf_Compressor_n_1decompress(JNIEnv *env, jclass, jlong self, jlong variantAddr)
{
static const char method_name[] = "Compressor::n_1decompress";
try
{
std::shared_ptr<Compressor>* obj = (std::shared_ptr<Compressor>*) self;
std::shared_ptr<Variant>* var = (std::shared_ptr<Variant>*) variantAddr;
if (obj == NULL || *obj == NULL) VMF_EXCEPTION(NullPointerException, "Compressor (self) is null pointer.");
if (var == NULL || *var == NULL) VMF_EXCEPTION(NullPointerException, "Input data is null pointer.");
std::string text;
(*obj)->decompress((*var)->get_rawbuffer(), text);
return env->NewStringUTF(text.c_str());
}
catch (const std::exception &e) { throwJavaException(env, &e, method_name); }
catch (...) { throwJavaException(env, 0, method_name); }
return 0;
}
}
| {
"content_hash": "8c979bfc8c21e81993285884e44b4653",
"timestamp": "",
"source": "github",
"line_count": 120,
"max_line_length": 122,
"avg_line_length": 42.833333333333336,
"alnum_prop": 0.6710116731517509,
"repo_name": "apavlenko/vmf",
"id": "5d4dddbc794d35cd3cdd590d6c66837a83a22ebb",
"size": "5278",
"binary": false,
"copies": "1",
"ref": "refs/heads/vmf-3.0",
"path": "modules/vmfcore/java/jni/com_intel_vmf_Compressor.cpp",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Batchfile",
"bytes": "416"
},
{
"name": "C++",
"bytes": "1067536"
},
{
"name": "CMake",
"bytes": "117761"
},
{
"name": "HTML",
"bytes": "2276"
},
{
"name": "Java",
"bytes": "219648"
},
{
"name": "Objective-C",
"bytes": "58920"
},
{
"name": "Objective-C++",
"bytes": "50718"
},
{
"name": "Python",
"bytes": "8170"
},
{
"name": "QML",
"bytes": "15245"
},
{
"name": "QMake",
"bytes": "1197"
},
{
"name": "Shell",
"bytes": "397"
}
],
"symlink_target": ""
} |
//---------------------------------------------------------------------------
// Pre-compilation
#include "MediaInfo/PreComp.h"
#ifdef __BORLANDC__
#pragma hdrstop
#endif
//---------------------------------------------------------------------------
//---------------------------------------------------------------------------
#include "MediaInfo/Setup.h"
//---------------------------------------------------------------------------
//---------------------------------------------------------------------------
#if defined(MEDIAINFO_XM_YES)
//---------------------------------------------------------------------------
//---------------------------------------------------------------------------
#include "MediaInfo/Audio/File_ExtendedModule.h"
//---------------------------------------------------------------------------
namespace MediaInfoLib
{
//***************************************************************************
// Static stuff
//***************************************************************************
//---------------------------------------------------------------------------
bool File_ExtendedModule::FileHeader_Begin()
{
//Element_Size
if (Buffer_Size<38)
return false; //Must wait for more data
if (CC8(Buffer)!=0x457874656E646564LL || CC8(Buffer+8)!=0x204D6F64756C653ALL //"Extended Module: "
|| CC1(Buffer+16)!=0x20 || CC1(Buffer+37)!=0x1A)
{
Reject("Extended Module");
return false;
}
//All should be OK...
return true;
}
//***************************************************************************
// Buffer - Global
//***************************************************************************
//---------------------------------------------------------------------------
void File_ExtendedModule::Read_Buffer_Continue()
{
//Parsing
Ztring ModuleName, TrackerName;
int32u HeaderSize;
int16u Length, Channels, Patterns, Instruments, Flags, Tempo, BPM;
int8u VersionMinor, VersionMajor;
Skip_String(17, "Signature");
Get_Local(20, ModuleName, "Module name");
Skip_L1( "0x1A");
Get_Local(20, TrackerName, "Tracker name");
Get_L1 (VersionMinor, "Version (minor)");
Get_L1 (VersionMajor, "Version (major)");
Get_L4 (HeaderSize, "Header size");
Get_L2 (Length, "Song Length");
Skip_L2( "Restart position");
Get_L2 (Channels, "Number of channels");
Get_L2 (Patterns, "Number of patterns");
Get_L2 (Instruments, "Number of instruments");
Get_L2 (Flags, "Flags");
Get_L2 (Tempo, "Tempo");
Get_L2 (BPM, "BPM");
Skip_XX(256, "Pattern order table");
FILLING_BEGIN();
Accept("Extended Module");
Fill(Stream_General, 0, General_Format, "Extended Module");
Fill(Stream_General, 0, General_Format_Version, Ztring::ToZtring(VersionMajor)+__T(".")+Ztring::ToZtring(VersionMinor/10)+Ztring::ToZtring(VersionMinor%10));
Fill(Stream_General, 0, General_Track, ModuleName.Trim(__T(' ')));
Fill(Stream_General, 0, General_Encoded_Application, TrackerName.Trim(__T(' ')));
Fill(Stream_General, 0, "Tempo", Tempo);
Fill(Stream_General, 0, "BPM", BPM);
Stream_Prepare(Stream_Audio);
Fill(Stream_Audio, 0, "Sampler, Channels", Channels);
Fill(Stream_Audio, 0, "Sampler, Patterns", Patterns);
Fill(Stream_Audio, 0, "Sampler, Instruments", Instruments);
//No more need data
Finish("Extended Module");
FILLING_END();
}
//***************************************************************************
// C++
//***************************************************************************
} //NameSpace
#endif //MEDIAINFO_XM_YES
| {
"content_hash": "5cb5d51365cf89ec2d3a7527b21aad39",
"timestamp": "",
"source": "github",
"line_count": 103,
"max_line_length": 165,
"avg_line_length": 43.55339805825243,
"alnum_prop": 0.3504235399019171,
"repo_name": "MediaArea/MediaInfoLib",
"id": "9f7f17e0dd70f4ca55ac4836bf84d6a4f07f7309",
"size": "4697",
"binary": false,
"copies": "13",
"ref": "refs/heads/master",
"path": "Source/MediaInfo/Audio/File_ExtendedModule.cpp",
"mode": "33188",
"license": "bsd-2-clause",
"language": [
{
"name": "ASP.NET",
"bytes": "7721"
},
{
"name": "AutoIt",
"bytes": "5982"
},
{
"name": "Batchfile",
"bytes": "48643"
},
{
"name": "C",
"bytes": "50514"
},
{
"name": "C#",
"bytes": "108365"
},
{
"name": "C++",
"bytes": "11178253"
},
{
"name": "CMake",
"bytes": "29075"
},
{
"name": "HTML",
"bytes": "12031"
},
{
"name": "Java",
"bytes": "117793"
},
{
"name": "JavaScript",
"bytes": "5140"
},
{
"name": "Kotlin",
"bytes": "4606"
},
{
"name": "M4",
"bytes": "81392"
},
{
"name": "Makefile",
"bytes": "21863"
},
{
"name": "NSIS",
"bytes": "11873"
},
{
"name": "Pascal",
"bytes": "13620"
},
{
"name": "PureBasic",
"bytes": "13384"
},
{
"name": "Python",
"bytes": "54732"
},
{
"name": "QMake",
"bytes": "26782"
},
{
"name": "Shell",
"bytes": "51652"
},
{
"name": "VBA",
"bytes": "10256"
},
{
"name": "VBScript",
"bytes": "2771"
},
{
"name": "Visual Basic .NET",
"bytes": "24066"
},
{
"name": "Visual Basic 6.0",
"bytes": "9861"
}
],
"symlink_target": ""
} |
<?xml version="1.0" encoding="UTF-8"?>
<!--
~ Copyright (c) 2010-2013 Evolveum
~
~ 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.
-->
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd"
default-lazy-init="true" default-autowire="byName">
<bean name="midpointConfiguration" class="com.evolveum.midpoint.init.StartupConfiguration" init-method="init">
<constructor-arg value="config-test.xml" />
</bean>
<import resource="ctx-repository.xml" />
<import resource="classpath:ctx-repo-cache.xml" />
<import resource="classpath:ctx-common.xml" />
<import resource="ctx-configuration-sql-test.xml" />
</beans> | {
"content_hash": "2adf8bb18d0bb23deec39bd0d6a24323",
"timestamp": "",
"source": "github",
"line_count": 33,
"max_line_length": 114,
"avg_line_length": 41.81818181818182,
"alnum_prop": 0.7050724637681159,
"repo_name": "gureronder/midpoint",
"id": "0ea5dc1e159571539af5a532ebf1230801e8af96",
"size": "1380",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "repo/repo-sql-impl-test/src/test/resources/ctx-test.xml",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "176525"
},
{
"name": "Groovy",
"bytes": "10361"
},
{
"name": "HTML",
"bytes": "450709"
},
{
"name": "Java",
"bytes": "19619257"
},
{
"name": "JavaScript",
"bytes": "70636"
},
{
"name": "PLSQL",
"bytes": "2171"
},
{
"name": "PLpgSQL",
"bytes": "3307"
},
{
"name": "SQLPL",
"bytes": "4091"
},
{
"name": "Shell",
"bytes": "3606"
}
],
"symlink_target": ""
} |
package com.google.firebase.database;
import static com.google.firebase.database.TestHelpers.fromSingleQuotedString;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.fail;
import com.google.firebase.database.utilities.encoding.CustomClassMapper;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.junit.Test;
public class MapperTest {
private static final double EPSILON = 0.00001f;
private static <T> T deserialize(String jsonString, Class<T> clazz) {
Map<String, Object> json = fromSingleQuotedString(jsonString);
return CustomClassMapper.convertToCustomClass(json, clazz);
}
private static <T> T deserialize(String jsonString, GenericTypeIndicator<T> typeIndicator) {
Map<String, Object> json = fromSingleQuotedString(jsonString);
return CustomClassMapper.convertToCustomClass(json, typeIndicator);
}
private static Object serialize(Object object) {
return CustomClassMapper.convertToPlainJavaTypes(object);
}
private static void assertJson(String expected, Object actual) {
assertEquals(fromSingleQuotedString(expected), actual);
}
@Test
public void primitiveDeserializeString() {
StringBean bean = deserialize("{'value': 'foo'}", StringBean.class);
assertEquals("foo", bean.value);
// Double
try {
deserialize("{'value': 1.1}", StringBean.class);
fail("Should throw");
} catch (DatabaseException e) { // ignore
}
// Int
try {
deserialize("{'value': 1}", StringBean.class);
fail("Should throw");
} catch (DatabaseException e) { // ignore
}
// Long
try {
deserialize("{'value': 1234567890123}", StringBean.class);
fail("Should throw");
} catch (DatabaseException e) { // ignore
}
// Boolean
try {
deserialize("{'value': true}", StringBean.class);
fail("Should throw");
} catch (DatabaseException e) { // ignore
}
}
@Test
public void primitiveDeserializeBoolean() {
BooleanBean beanBoolean = deserialize("{'value': true}", BooleanBean.class);
assertEquals(true, beanBoolean.value);
// Double
try {
deserialize("{'value': 1.1}", BooleanBean.class);
fail("Should throw");
} catch (DatabaseException e) { // ignore
}
// Long
try {
deserialize("{'value': 1234567890123}", BooleanBean.class);
fail("Should throw");
} catch (DatabaseException e) { // ignore
}
// Int
try {
deserialize("{'value': 1}", BooleanBean.class);
fail("Should throw");
} catch (DatabaseException e) { // ignore
}
// String
try {
deserialize("{'value': 'foo'}", BooleanBean.class);
fail("Should throw");
} catch (DatabaseException e) { // ignore
}
}
@Test
public void primitiveDeserializeDouble() {
DoubleBean beanDouble = deserialize("{'value': 1.1}", DoubleBean.class);
assertEquals(1.1, beanDouble.value, EPSILON);
// Int
DoubleBean beanInt = deserialize("{'value': 1}", DoubleBean.class);
assertEquals(1, beanInt.value, EPSILON);
// Long
DoubleBean beanLong = deserialize("{'value': 1234567890123}", DoubleBean.class);
assertEquals(1234567890123L, beanLong.value, EPSILON);
// Boolean
try {
deserialize("{'value': true}", DoubleBean.class);
fail("Should throw");
} catch (DatabaseException e) { // ignore
}
// String
try {
deserialize("{'value': 'foo'}", DoubleBean.class);
fail("Should throw");
} catch (DatabaseException e) { // ignore
}
}
@Test
public void primitiveDeserializeFloat() {
FloatBean beanFloat = deserialize("{'value': 1.1}", FloatBean.class);
assertEquals(1.1, beanFloat.value, EPSILON);
// Int
FloatBean beanInt = deserialize("{'value': 1}", FloatBean.class);
assertEquals(1, beanInt.value, EPSILON);
// Long
FloatBean beanLong = deserialize("{'value': 1234567890123}", FloatBean.class);
assertEquals(Long.valueOf(1234567890123L).floatValue(), beanLong.value, EPSILON);
// Boolean
try {
deserialize("{'value': true}", FloatBean.class);
fail("Should throw");
} catch (DatabaseException e) { // ignore
}
// String
try {
deserialize("{'value': 'foo'}", FloatBean.class);
fail("Should throw");
} catch (DatabaseException e) { // ignore
}
}
@Test
public void primitiveDeserializeInt() {
IntBean beanInt = deserialize("{'value': 1}", IntBean.class);
assertEquals(1, beanInt.value);
// Double
IntBean beanDouble = deserialize("{'value': 1.1}", IntBean.class);
assertEquals(1, beanDouble.value);
// Large doubles
try {
deserialize("{'value': 1e10}", IntBean.class);
fail("Should throw");
} catch (DatabaseException e) { // ignore
}
// Long
try {
deserialize("{'value': 1234567890123}", IntBean.class);
fail("Should throw");
} catch (DatabaseException e) { // ignore
}
// Boolean
try {
deserialize("{'value': true}", IntBean.class);
fail("Should throw");
} catch (DatabaseException e) { // ignore
}
// String
try {
deserialize("{'value': 'foo'}", IntBean.class);
fail("Should throw");
} catch (DatabaseException e) { // ignore
}
}
@Test
public void primitiveDeserializeLong() {
LongBean beanLong = deserialize("{'value': 1234567890123}", LongBean.class);
assertEquals(1234567890123L, beanLong.value);
//Int
LongBean beanInt = deserialize("{'value': 1}", LongBean.class);
assertEquals(1, beanInt.value);
// Double
LongBean beanDouble = deserialize("{'value': 1.1}", LongBean.class);
assertEquals(1, beanDouble.value);
// Large doubles
try {
deserialize("{'value': 1e300}", LongBean.class);
fail("Should throw");
} catch (DatabaseException e) { // ignore
}
// Boolean
try {
deserialize("{'value': true}", LongBean.class);
fail("Should throw");
} catch (DatabaseException e) { // ignore
}
// String
try {
deserialize("{'value': 'foo'}", LongBean.class);
fail("Should throw");
} catch (DatabaseException e) { // ignore
}
}
@Test(expected = DatabaseException.class)
public void primitiveDeserializeWrongTypeMap() {
deserialize("{'value': {'foo': 'bar'}}", StringBean.class);
}
@Test(expected = DatabaseException.class)
public void primitiveDeserializeWrongTypeList() {
deserialize("{'value': ['foo']}", StringBean.class);
}
@Test
public void publicFieldDeserialze() {
PublicFieldBean bean = deserialize("{'value': 'foo'}", PublicFieldBean.class);
assertEquals("foo", bean.value);
}
@Test
public void publicPrivateFieldDeserialze() {
PublicPrivateFieldBean bean =
deserialize(
"{'value1': 'foo', 'value2': 'bar', 'value3': 'baz'}", PublicPrivateFieldBean.class);
assertEquals("foo", bean.value1);
assertEquals(null, bean.value2);
assertEquals(null, bean.value3);
}
@Test(expected = DatabaseException.class)
public void packageFieldDeserialze() {
deserialize("{'value': 'foo'}", PackageFieldBean.class);
}
@Test(expected = DatabaseException.class)
public void privateFieldDeserialize() {
deserialize("{'value': 'foo'}", PrivateFieldBean.class);
}
@Test
public void packageGetterDeserialize() {
PackageGetterBean bean =
deserialize("{'publicValue': 'foo', 'packageValue': 'bar'}", PackageGetterBean.class);
assertEquals("foo", bean.publicValue);
assertNull(bean.packageValue);
}
@Test
public void packageGetterSerialize() {
PackageGetterBean bean = new PackageGetterBean();
bean.packageValue = "foo";
bean.publicValue = "bar";
assertJson("{'publicValue': 'bar'}", serialize(bean));
}
@Test
public void ignoreExtraProperties() {
PublicFieldBean bean = deserialize("{'value': 'foo', 'unknown': 'bar'}", PublicFieldBean.class);
assertEquals("foo", bean.value);
}
@Test(expected = DatabaseException.class)
public void throwOnUnknownProperties() {
deserialize("{'value': 'foo', 'unknown': 'bar'}", ThrowOnUnknownPropertiesBean.class);
}
@Test(expected = DatabaseException.class)
public void twoSetterBean() {
deserialize("{'value': 'foo'}", TwoSetterBean.class);
}
@Test
public void testXmlAndUrlBean() {
XMLAndURLBean bean =
deserialize("{'xmlandURL1': 'foo', 'XMLAndURL2': 'bar'}", XMLAndURLBean.class);
assertEquals("foo", bean.XMLAndURL1);
assertEquals("bar", bean.XMLAndURL2);
}
@Test
public void setterIsCalledWhenPresent() {
SetterBean bean = deserialize("{'value': 'foo'}", SetterBean.class);
assertEquals("setter:foo", bean.value);
}
@Test
public void privateSetterIsCalledWhenPresent() {
PrivateSetterBean bean = deserialize("{'value': 'foo'}", PrivateSetterBean.class);
assertEquals("setter:foo", bean.value);
}
@Test(expected = DatabaseException.class)
public void setterIsCaseSensitive1() {
deserialize("{'value': 'foo'}", CaseSensitiveSetterBean1.class);
}
@Test(expected = DatabaseException.class)
public void setterIsCaseSensitive2() {
deserialize("{'value': 'foo'}", CaseSensitiveSetterBean2.class);
}
@Test
public void caseSensitiveSetterIsCalledWhenPresent1() {
CaseSensitiveSetterBean3 bean = deserialize("{'value': 'foo'}", CaseSensitiveSetterBean3.class);
assertEquals("setter:foo", bean.value);
}
@Test
public void caseSensitiveSetterIsCalledWhenPresent2() {
CaseSensitiveSetterBean4 bean = deserialize("{'value': 'foo'}", CaseSensitiveSetterBean4.class);
assertEquals("setter:foo", bean.value);
}
@Test
public void caseSensitiveSetterIsCalledWhenPresent3() {
CaseSensitiveSetterBean5 bean = deserialize("{'value': 'foo'}", CaseSensitiveSetterBean5.class);
assertEquals("foo", bean.value);
}
@Test(expected = DatabaseException.class)
public void caseSensitiveSetterMustHaveSameCaseAsSetter() {
deserialize("{'value': 'foo'}", CaseSensitiveSetterBean6.class);
}
@Test
public void wrongSetterIsNotCalledWhenPresent() {
WrongSetterBean bean = deserialize("{'value': 'foo'}", WrongSetterBean.class);
assertEquals("foo", bean.value);
}
@Test
public void recursiveParsingWorks() {
RecursiveBean bean = deserialize("{'bean': {'value': 'foo'}}", RecursiveBean.class);
assertEquals("foo", bean.bean.value);
}
@Test
public void beansCanContainLists() {
ListBean bean = deserialize("{'values': ['foo', 'bar']}", ListBean.class);
assertEquals(Arrays.asList("foo", "bar"), bean.values);
}
@Test
public void beansCanContainMaps() {
MapBean bean = deserialize("{'values': {'foo': 'bar'}}", MapBean.class);
Map<String, Object> expected = fromSingleQuotedString("{'foo': 'bar'}");
assertEquals(expected, bean.values);
}
@Test
public void beansCanContainBeanLists() {
RecursiveListBean bean = deserialize("{'values': [{'value': 'foo'}]}", RecursiveListBean.class);
assertEquals(1, bean.values.size());
assertEquals("foo", bean.values.get(0).value);
}
@Test
public void beansCanContainBeanMaps() {
RecursiveMapBean bean =
deserialize("{'values': {'key': {'value': 'foo'}}}", RecursiveMapBean.class);
assertEquals(1, bean.values.size());
assertEquals("foo", bean.values.get("key").value);
}
@Test(expected = DatabaseException.class)
public void beanMapsMustHaveStringKeys() {
deserialize("{'values': {'1': 'bar'}}", IllegalKeyMapBean.class);
}
@Test
public void serializeStringBean() {
StringBean bean = new StringBean();
bean.value = "foo";
assertJson("{'value': 'foo'}", serialize(bean));
}
@Test
public void serializeDoubleBean() {
DoubleBean bean = new DoubleBean();
bean.value = 1.1;
assertJson("{'value': 1.1}", serialize(bean));
}
@Test
public void serializeDoubleBeanAsLong() {
DoubleBean bean = new DoubleBean();
bean.value = 1234567890123L;
assertJson("{'value': 1234567890123}", serialize(bean));
bean.value = 1234567890123.0;
assertJson("{'value': 1234567890123}", serialize(bean));
}
@Test
public void serializeIntBean() {
IntBean bean = new IntBean();
bean.value = 1;
assertJson("{'value': 1}", serialize(bean));
}
@Test
public void serializeLongBean() {
LongBean bean = new LongBean();
bean.value = 1234567890123L;
assertJson("{'value': 1234567890123}", serialize(bean));
}
@Test
public void serializeBooleanBean() {
BooleanBean bean = new BooleanBean();
bean.value = true;
assertJson("{'value': true}", serialize(bean));
}
@Test
public void serializeFloatBean() {
FloatBean bean = new FloatBean();
bean.value = 0.5f;
assertJson("{'value': 0.5}", serialize(bean));
}
@Test
public void serializePublicFieldBean() {
PublicFieldBean bean = new PublicFieldBean();
bean.value = "foo";
assertJson("{'value': 'foo'}", serialize(bean));
}
@Test(expected = DatabaseException.class)
public void serializePrivateFieldBean() {
PrivateFieldBean bean = new PrivateFieldBean();
bean.value = "foo";
serialize(bean);
}
@Test(expected = DatabaseException.class)
public void serializePackageFieldBean() {
PackageFieldBean bean = new PackageFieldBean();
bean.value = "foo";
serialize(bean);
}
@Test
public void serializePublicPrivateFieldBean() {
PublicPrivateFieldBean bean = new PublicPrivateFieldBean();
bean.value1 = "foo";
bean.value2 = "bar";
bean.value3 = "baz";
assertJson("{'value1': 'foo'}", serialize(bean));
}
@Test
public void getterOverridesField() {
GetterBean bean = new GetterBean();
bean.value = "foo";
assertJson("{'value': 'getter:foo'}", serialize(bean));
}
@Test
public void getterOverridesPublicField() {
GetterPublicFieldBean bean = new GetterPublicFieldBean();
bean.value = "foo";
assertJson("{'value': 'getter:foo'}", serialize(bean));
}
@Test(expected = DatabaseException.class)
public void getterAndPublicFieldsConflictOnCaseSensitivity() {
GetterPublicFieldBeanCaseSensitive bean = new GetterPublicFieldBeanCaseSensitive();
bean.valueCase = "foo";
serialize(bean);
}
@Test
public void caseSensitveGetterBean1() {
CaseSensitiveGetterBean1 bean = new CaseSensitiveGetterBean1();
bean.value = "foo";
assertJson("{'value': 'foo'}", serialize(bean));
}
@Test
public void caseSensitveGetterBean2() {
CaseSensitiveGetterBean2 bean = new CaseSensitiveGetterBean2();
bean.value = "foo";
assertJson("{'value': 'foo'}", serialize(bean));
}
@Test
public void caseSensitveGetterBean3() {
CaseSensitiveGetterBean3 bean = new CaseSensitiveGetterBean3();
bean.value = "foo";
assertJson("{'value': 'foo'}", serialize(bean));
}
@Test
public void caseSensitveGetterBean4() {
CaseSensitiveGetterBean4 bean = new CaseSensitiveGetterBean4();
bean.value = "foo";
assertJson("{'vaLUE': 'foo'}", serialize(bean));
}
@Test
public void recursiveSerializingWorks() {
RecursiveBean bean = new RecursiveBean();
bean.bean = new StringBean();
bean.bean.value = "foo";
assertJson("{'bean': {'value': 'foo'}}", serialize(bean));
}
@Test
public void serializingListsWorks() {
ListBean bean = new ListBean();
bean.values = Arrays.asList("foo", "bar");
assertJson("{'values': ['foo', 'bar']}", serialize(bean));
}
@Test
public void serializingMapsWorks() {
MapBean bean = new MapBean();
bean.values =
new HashMap<String, String>() {
{
put("foo", "bar");
}
};
assertJson("{'values': {'foo': 'bar'}}", serialize(bean));
}
@Test
public void serializeListOfBeansWorks() {
RecursiveListBean bean = new RecursiveListBean();
bean.values =
new ArrayList<StringBean>() {
{
StringBean bean = new StringBean();
bean.value = "foo";
add(bean);
}
};
assertJson("{'values': [{'value': 'foo'}]}", serialize(bean));
}
@Test
public void serializeMapOfBeansWorks() {
RecursiveMapBean bean = new RecursiveMapBean();
bean.values =
new HashMap<String, StringBean>() {
{
StringBean bean = new StringBean();
bean.value = "foo";
put("key", bean);
}
};
assertJson("{'values': {'key': {'value': 'foo'}}}", serialize(bean));
}
@Test(expected = DatabaseException.class)
public void beanMapsMustHaveStringKeysForSerializing() {
IllegalKeyMapBean bean = new IllegalKeyMapBean();
bean.values =
new HashMap<Integer, StringBean>() {
{
StringBean bean = new StringBean();
bean.value = "foo";
put(1, bean);
}
};
serialize(bean);
}
@Test(expected = DatabaseException.class)
public void twoGettersThrows() {
TwoGetterBean bean = new TwoGetterBean();
bean.value = "foo";
serialize(bean);
}
@Test
public void serializeUpperCase() {
XMLAndURLBean bean = new XMLAndURLBean();
bean.XMLAndURL1 = "foo";
bean.XMLAndURL2 = "bar";
assertJson("{'xmlandURL1': 'foo', 'XMLAndURL2': 'bar'}", serialize(bean));
}
@Test
public void onlySerializesGetterWithCorrectArguments() {
GetterArgumentsBean bean = new GetterArgumentsBean();
bean.value = "foo";
assertJson("{'value1': 'foo1', 'value4': 'foo4'}", serialize(bean));
}
@Test
public void roundTripCaseSensitiveFieldBean1() {
CaseSensitiveFieldBean1 bean = new CaseSensitiveFieldBean1();
bean.VALUE = "foo";
assertJson("{'VALUE': 'foo'}", serialize(bean));
CaseSensitiveFieldBean1 deserialized =
deserialize("{'VALUE': 'foo'}", CaseSensitiveFieldBean1.class);
assertEquals("foo", deserialized.VALUE);
}
@Test
public void roundTripCaseSensitiveFieldBean2() {
CaseSensitiveFieldBean2 bean = new CaseSensitiveFieldBean2();
bean.value = "foo";
assertJson("{'value': 'foo'}", serialize(bean));
CaseSensitiveFieldBean2 deserialized =
deserialize("{'value': 'foo'}", CaseSensitiveFieldBean2.class);
assertEquals("foo", deserialized.value);
}
@Test
public void roundTripCaseSensitiveFieldBean3() {
CaseSensitiveFieldBean3 bean = new CaseSensitiveFieldBean3();
bean.Value = "foo";
assertJson("{'Value': 'foo'}", serialize(bean));
CaseSensitiveFieldBean3 deserialized =
deserialize("{'Value': 'foo'}", CaseSensitiveFieldBean3.class);
assertEquals("foo", deserialized.Value);
}
@Test
public void roundTripCaseSensitiveFieldBean4() {
CaseSensitiveFieldBean4 bean = new CaseSensitiveFieldBean4();
bean.valUE = "foo";
assertJson("{'valUE': 'foo'}", serialize(bean));
CaseSensitiveFieldBean4 deserialized =
deserialize("{'valUE': 'foo'}", CaseSensitiveFieldBean4.class);
assertEquals("foo", deserialized.valUE);
}
@Test
public void roundTripUnicodeBean() {
UnicodeBean bean = new UnicodeBean();
bean.漢字 = "foo";
assertJson("{'漢字': 'foo'}", serialize(bean));
UnicodeBean deserialized = deserialize("{'漢字': 'foo'}", UnicodeBean.class);
assertEquals("foo", deserialized.漢字);
}
@Test(expected = DatabaseException.class)
public void shortsCantBeSerialized() {
ShortBean bean = new ShortBean();
bean.value = 1;
serialize(bean);
}
@Test(expected = DatabaseException.class)
public void bytesCantBeSerialized() {
ByteBean bean = new ByteBean();
bean.value = 1;
serialize(bean);
}
@Test(expected = DatabaseException.class)
public void charsCantBeSerialized() {
CharBean bean = new CharBean();
bean.value = 1;
serialize(bean);
}
@Test(expected = DatabaseException.class)
public void intArraysCantBeSerialized() {
IntArrayBean bean = new IntArrayBean();
bean.values = new int[] {1};
serialize(bean);
}
@Test(expected = DatabaseException.class)
public void objectArraysCantBeSerialized() {
StringArrayBean bean = new StringArrayBean();
bean.values = new String[] {"foo"};
serialize(bean);
}
@Test(expected = DatabaseException.class)
public void shortsCantBeDeserialized() {
deserialize("{'value': 1}", ShortBean.class);
}
@Test(expected = DatabaseException.class)
public void bytesCantBeDeserialized() {
deserialize("{'value': 1}", ByteBean.class);
}
@Test(expected = DatabaseException.class)
public void charsCantBeDeserialized() {
deserialize("{'value': '1'}", CharBean.class);
}
@Test(expected = DatabaseException.class)
public void intArraysCantBeDeserialized() {
deserialize("{'values': [1]}", IntArrayBean.class);
}
@Test(expected = DatabaseException.class)
public void objectArraysCantBeDeserialized() {
deserialize("{'values': ['foo']}", StringArrayBean.class);
}
@Test
public void publicConstructorCanBeDeserialized() {
PublicConstructorBean bean = deserialize("{'value': 'foo'}", PublicConstructorBean.class);
assertEquals("foo", bean.value);
}
@Test
public void privateConstructorCanBeDeserialized() {
PrivateConstructorBean bean = deserialize("{'value': 'foo'}", PrivateConstructorBean.class);
assertEquals("foo", bean.value);
}
@Test(expected = DatabaseException.class)
public void argConstructorCantBeDeserialized() {
deserialize("{'value': 'foo'}", ArgConstructorBean.class);
}
@Test
public void packageConstructorCanBeDeserialized() {
PackageConstructorBean bean = deserialize("{'value': 'foo'}", PackageConstructorBean.class);
assertEquals("foo", bean.value);
}
@Test
public void multipleConstructorsCanBeDeserialized() {
MultipleConstructorBean bean = deserialize("{'value': 'foo'}", MultipleConstructorBean.class);
assertEquals("foo", bean.value);
}
@Test
public void objectAcceptsAnyObject() {
ObjectBean stringValue = deserialize("{'value': 'foo'}", ObjectBean.class);
assertEquals("foo", stringValue.value);
ObjectBean listValue = deserialize("{'value': ['foo']}", ObjectBean.class);
assertEquals(Collections.singletonList("foo"), listValue.value);
ObjectBean mapValue = deserialize("{'value': {'foo':'bar'}}", ObjectBean.class);
assertEquals(fromSingleQuotedString("{'foo':'bar'}"), mapValue.value);
String complex =
"{'value': {'foo':['bar', ['baz'], {'bam': 'qux'}]}, " + "'other':{'a': ['b']}}";
ObjectBean complexValue = deserialize(complex, ObjectBean.class);
assertEquals(fromSingleQuotedString(complex).get("value"), complexValue.value);
}
@Test
public void objectClassCanBePassedInAtTopLevel() {
assertEquals("foo", CustomClassMapper.convertToCustomClass("foo", Object.class));
assertEquals(1, CustomClassMapper.convertToCustomClass(1, Object.class));
assertEquals(1L, CustomClassMapper.convertToCustomClass(1L, Object.class));
assertEquals(true, CustomClassMapper.convertToCustomClass(true, Object.class));
assertEquals(1.1, CustomClassMapper.convertToCustomClass(1.1, Object.class));
List<String> fooList = Collections.singletonList("foo");
assertEquals(fooList, CustomClassMapper.convertToCustomClass(fooList, Object.class));
Map<String, String> fooMap = Collections.singletonMap("foo", "bar");
assertEquals(fooMap, CustomClassMapper.convertToCustomClass(fooMap, Object.class));
}
@Test
public void primitiveClassesCanBePassedInTopLevel() {
assertEquals("foo", CustomClassMapper.convertToCustomClass("foo", String.class));
assertEquals((Integer) 1, CustomClassMapper.convertToCustomClass(1, Integer.class));
assertEquals((Long) 1L, CustomClassMapper.convertToCustomClass(1L, Long.class));
assertEquals(true, CustomClassMapper.convertToCustomClass(true, Boolean.class));
assertEquals((Double) 1.1, CustomClassMapper.convertToCustomClass(1.1, Double.class));
}
@Test(expected = DatabaseException.class)
public void passingInListTopLevelThrows() {
CustomClassMapper.convertToCustomClass(Collections.singletonList("foo"), List.class);
}
@Test(expected = DatabaseException.class)
public void passingInMapTopLevelThrows() {
CustomClassMapper.convertToCustomClass(Collections.singletonMap("foo", "bar"), Map.class);
}
@Test(expected = DatabaseException.class)
public void passingInCharacterTopLevelThrows() {
CustomClassMapper.convertToCustomClass('1', Character.class);
}
@Test(expected = DatabaseException.class)
public void passingInShortTopLevelThrows() {
CustomClassMapper.convertToCustomClass(1, Short.class);
}
@Test(expected = DatabaseException.class)
public void passingInByteTopLevelThrows() {
CustomClassMapper.convertToCustomClass(1, Byte.class);
}
@Test(expected = DatabaseException.class)
public void passingInGenericBeanTopLevelThrows() {
deserialize("{'value': 'foo'}", GenericBean.class);
}
@Test
public void collectionsCanBeSerializedWhenList() {
CollectionBean bean = new CollectionBean();
bean.values = Collections.singletonList("foo");
assertJson("{'values': ['foo']}", serialize(bean));
}
@Test(expected = DatabaseException.class)
public void collectionsCantBeSerializedWhenSet() {
CollectionBean bean = new CollectionBean();
bean.values = Collections.singleton("foo");
serialize(bean);
}
@Test(expected = DatabaseException.class)
public void collectionsCantBeDeserialized() {
deserialize("{'values': ['foo']}", CollectionBean.class);
}
@Test
public void allowNullEverywhere() {
assertNull(CustomClassMapper.convertToCustomClass(null, Integer.class));
assertNull(CustomClassMapper.convertToCustomClass(null, String.class));
assertNull(CustomClassMapper.convertToCustomClass(null, Double.class));
assertNull(CustomClassMapper.convertToCustomClass(null, Long.class));
assertNull(CustomClassMapper.convertToCustomClass(null, Boolean.class));
assertNull(CustomClassMapper.convertToCustomClass(null, StringBean.class));
assertNull(CustomClassMapper.convertToCustomClass(null, Object.class));
assertNull(CustomClassMapper.convertToCustomClass(null, new GenericTypeIndicator<String>() {}));
assertNull(
CustomClassMapper.convertToCustomClass(
null, new GenericTypeIndicator<Map<String, String>>() {}));
}
@Test
public void parsingGenericBeansSupportedUsingGenericTypeIndicator() {
GenericBean<String> stringBean =
deserialize("{'value': 'foo'}", new GenericTypeIndicator<GenericBean<String>>() {});
assertEquals("foo", stringBean.value);
GenericBean<Map<String, String>> mapBean =
deserialize(
"{'value': {'foo': 'bar'}}",
new GenericTypeIndicator<GenericBean<Map<String, String>>>() {});
assertEquals(Collections.singletonMap("foo", "bar"), mapBean.value);
GenericBean<List<String>> listBean =
deserialize("{'value': ['foo']}", new GenericTypeIndicator<GenericBean<List<String>>>() {});
assertEquals(Collections.singletonList("foo"), listBean.value);
GenericBean<GenericBean<String>> recursiveBean =
deserialize(
"{'value': {'value': 'foo'}}",
new GenericTypeIndicator<GenericBean<GenericBean<String>>>() {});
assertEquals("foo", recursiveBean.value.value);
DoubleGenericBean<String, Integer> doubleBean =
deserialize(
"{'valueA': 'foo', 'valueB': 1}",
new GenericTypeIndicator<DoubleGenericBean<String, Integer>>() {});
assertEquals("foo", doubleBean.valueA);
assertEquals((Integer) 1, doubleBean.valueB);
}
@Test
public void serializingGenericBeansSupported() {
GenericBean<String> stringBean = new GenericBean<>();
stringBean.value = "foo";
assertJson("{'value': 'foo'}", serialize(stringBean));
GenericBean<Map<String, String>> mapBean = new GenericBean<>();
mapBean.value = Collections.singletonMap("foo", "bar");
assertJson("{'value': {'foo': 'bar'}}", serialize(mapBean));
GenericBean<List<String>> listBean = new GenericBean<>();
listBean.value = Collections.singletonList("foo");
assertJson("{'value': ['foo']}", serialize(listBean));
GenericBean<GenericBean<String>> recursiveBean = new GenericBean<>();
recursiveBean.value = new GenericBean<>();
recursiveBean.value.value = "foo";
assertJson("{'value': {'value': 'foo'}}", serialize(recursiveBean));
DoubleGenericBean<String, Integer> doubleBean = new DoubleGenericBean<>();
doubleBean.valueA = "foo";
doubleBean.valueB = 1;
assertJson("{'valueA': 'foo', 'valueB': 1}", serialize(doubleBean));
}
@Test(expected = DatabaseException.class)
public void deserializingWrongTypeThrows() {
deserialize("{'value': 'foo'}", WrongTypeBean.class);
}
@Test
public void serializingWrongTypeWorks() {
WrongTypeBean bean = new WrongTypeBean();
bean.value = 1;
assertJson("{'value': '1'}", serialize(bean));
}
@Test(expected = DatabaseException.class)
public void extendingGenericTypeIndicatorIsForbidden1() {
deserialize("{'value': 'foo'}", new GenericTypeIndicatorSubclass<GenericBean<String>>() {});
}
@Test(expected = DatabaseException.class)
public void extendingGenericTypeIndicatorIsForbidden2() {
deserialize("{'value': 'foo'}", new NonGenericTypeIndicatorSubclass() {});
}
@Test(expected = DatabaseException.class)
public void extendingGenericTypeIndicatorIsForbidden3() {
deserialize("{'value': 'foo'}", new NonGenericTypeIndicatorSubclassConcreteSubclass());
}
@Test
public void subclassingGenericTypeIndicatorIsAllowed() {
GenericBean<String> bean =
deserialize("{'value': 'foo'}", new NonGenericTypeIndicatorConcreteSubclass());
assertEquals("foo", bean.value);
}
@Test(expected = DatabaseException.class)
public void unknownTypeParametersNotSupported() {
deserialize("{'value': 'foo'}", new GenericTypeIndicatorSubclass<GenericBean<?>>() {});
}
@Test(expected = DatabaseException.class)
public void unknownTypeParametersSupportedIfBoundedByKnownType() {
GenericBean<? extends String> bean =
deserialize(
"{'value': 'foo'}",
new GenericTypeIndicatorSubclass<GenericBean<? extends String>>() {});
assertEquals("foo", bean.value);
}
@Test
public void excludedFieldsAreExcluded() {
ExcludedBean bean = new ExcludedBean();
assertJson("{'includedGetter': 'no-value'}", serialize(bean));
}
@Test
public void excludedFieldsAreNotParsed() {
ExcludedBean bean =
deserialize(
"{'includedGetter': 'foo', 'excludedField': 'bar', " + "'excludedGetter': 'qux'}",
ExcludedBean.class);
assertEquals("no-value", bean.excludedField);
assertEquals("no-value", bean.excludedGetter);
assertEquals("foo", bean.includedGetter);
}
@Test
public void excludedSettersAreIgnored() {
ExcludedSetterBean bean = deserialize("{'value': 'foo'}", ExcludedSetterBean.class);
assertEquals("foo", bean.value);
}
@Test
public void propertyNamesAreSerialized() {
PropertyNameBean bean = new PropertyNameBean();
bean.key = "foo";
bean.setValue("bar");
assertJson("{'my_key': 'foo', 'my_value': 'bar'}", serialize(bean));
}
@Test
public void propertyNamesAreParsed() {
PropertyNameBean bean =
deserialize("{'my_key': 'foo', 'my_value': 'bar'}", PropertyNameBean.class);
assertEquals("foo", bean.key);
assertEquals("bar", bean.getValue());
}
@Test
public void staticFieldsAreNotParsed() {
StaticFieldBean bean = deserialize("{'value1': 'foo', 'value2': 'bar'}", StaticFieldBean.class);
assertEquals("static-value", StaticFieldBean.value1);
assertEquals("bar", bean.value2);
}
@Test
public void staticFieldsAreNotSerialized() {
StaticFieldBean bean = new StaticFieldBean();
bean.value2 = "foo";
assertJson("{'value2': 'foo'}", serialize(bean));
}
@Test
public void staticSettersAreNotUsed() {
StaticMethodBean bean =
deserialize("{'value1': 'foo', 'value2': 'bar'}", StaticMethodBean.class);
assertEquals("static-value", StaticMethodBean.value1);
assertEquals("bar", bean.value2);
}
@Test
public void staticMethodsAreNotSerialized() {
StaticMethodBean bean = new StaticMethodBean();
bean.value2 = "foo";
assertJson("{'value2': 'foo'}", serialize(bean));
}
@Test
public void enumsAreSerialized() {
EnumBean bean = new EnumBean();
bean.enumField = Enum.Bar;
bean.complexEnum = ComplexEnum.One;
bean.setEnumValue(Enum.Foo);
assertJson("{'enumField': 'Bar', 'enumValue': 'Foo', 'complexEnum': 'One'}", serialize(bean));
}
@Test
public void enumsAreParsed() {
String json = "{'enumField': 'Bar', 'enumValue': 'Foo', 'complexEnum': 'One'}";
EnumBean bean = deserialize(json, EnumBean.class);
assertEquals(bean.enumField, Enum.Bar);
assertEquals(bean.enumValue, Enum.Foo);
assertEquals(bean.complexEnum, ComplexEnum.One);
}
@Test
public void enumsCanBeParsedToNull() {
String json = "{'enumField': null}";
EnumBean bean = deserialize(json, EnumBean.class);
assertNull(bean.enumField);
assertNull(bean.enumValue);
assertNull(bean.complexEnum);
}
@Test(expected = DatabaseException.class)
public void throwsOnUnmatchedEnums() {
String json = "{'enumField': 'Unavailable', 'enumValue': 'Foo', 'complexEnum': 'One'}";
deserialize(json, EnumBean.class);
}
@Test
public void inheritedFieldsAndGettersAreSerialized() {
FinalBean bean = new FinalBean();
bean.finalValue = "final-value";
bean.inheritedValue = "inherited-value";
bean.baseValue = "base-value";
bean.overrideValue = "override-value";
bean.classPrivateValue = "private-value";
bean.packageBaseValue = "package-base-value";
bean.setFinalMethod("final-method");
bean.setInheritedMethod("inherited-method");
bean.setBaseMethod("base-method");
assertJson(
"{'baseValue': 'base-value', "
+ "'baseMethod': 'base-method', "
+ "'classPrivateValue': 'private-value', "
+ "'finalMethod': 'final-method', "
+ "'finalValue': 'final-value', "
+ "'inheritedMethod': 'inherited-method', "
+ "'inheritedValue': 'inherited-value', "
+ "'overrideValue': 'override-value-final', "
+ "'packageBaseValue': 'package-base-value'}",
serialize(bean));
}
@Test
public void inheritedFieldsAndSettersAreParsed() {
String bean =
"{'baseValue': 'base-value', "
+ "'baseMethod': 'base-method', "
+ "'classPrivateValue': 'private-value', "
+ "'finalMethod': 'final-method', "
+ "'finalValue': 'final-value', "
+ "'inheritedMethod': 'inherited-method', "
+ "'inheritedValue': 'inherited-value', "
+ "'overrideValue': 'override-value', "
+ "'packageBaseValue': 'package-base-value'}";
FinalBean finalBean = deserialize(bean, FinalBean.class);
assertEquals("base-value", finalBean.baseValue);
assertEquals("inherited-value", finalBean.inheritedValue);
assertEquals("final-value", finalBean.finalValue);
assertEquals("base-method", finalBean.getBaseMethod());
assertEquals("inherited-method", finalBean.getInheritedMethod());
assertEquals("final-method", finalBean.getFinalMethod());
assertEquals("override-value-final", finalBean.overrideValue);
assertEquals("private-value", finalBean.classPrivateValue);
assertNull(((InheritedBean) finalBean).classPrivateValue);
assertNull(((BaseBean) finalBean).classPrivateValue);
InheritedBean inheritedBean = deserialize(bean, InheritedBean.class);
assertEquals("base-value", inheritedBean.baseValue);
assertEquals("inherited-value", inheritedBean.inheritedValue);
assertEquals("base-method", inheritedBean.getBaseMethod());
assertEquals("inherited-method", inheritedBean.getInheritedMethod());
assertEquals("override-value-inherited", inheritedBean.overrideValue);
assertEquals("private-value", inheritedBean.classPrivateValue);
assertNull(((BaseBean) inheritedBean).classPrivateValue);
BaseBean baseBean = deserialize(bean, BaseBean.class);
assertEquals("base-value", baseBean.baseValue);
assertEquals("base-method", baseBean.getBaseMethod());
assertEquals("override-value", baseBean.overrideValue);
assertEquals("private-value", baseBean.classPrivateValue);
}
@Test(expected = DatabaseException.class)
public void settersFromSubclassConflictsWithBaseClass() {
ConflictingSetterSubBean bean = new ConflictingSetterSubBean();
bean.value = 1;
serialize(bean);
}
@Test(expected = DatabaseException.class)
public void settersFromSubclassConflictsWithBaseClass2() {
ConflictingSetterSubBean2 bean = new ConflictingSetterSubBean2();
bean.value = 1;
serialize(bean);
}
@Test
public void settersCanOverridePrimitiveSettersSerializing() {
NonConflictingSetterSubBean bean = new NonConflictingSetterSubBean();
bean.value = 1;
assertJson("{'value': 1}", serialize(bean));
}
@Test
public void settersCanOverridePrimitiveSettersParsing() {
NonConflictingSetterSubBean bean =
deserialize("{'value': 2}", NonConflictingSetterSubBean.class);
// sub-bean converts to negative value
assertEquals(-2, bean.value);
}
@Test(expected = DatabaseException.class)
public void genericSettersFromSubclassConflictsWithBaseClass() {
ConflictingGenericSetterSubBean<String> bean = new ConflictingGenericSetterSubBean<>();
bean.value = "hello";
serialize(bean);
}
// This should work, but generics and subclassing are tricky to get right. For now we will just
// throw and we can add support for generics & subclassing if it becomes a high demand feature
@Test(expected = DatabaseException.class)
public void settersCanOverrideGenericSettersParsingNot() {
NonConflictingGenericSetterSubBean bean =
deserialize("{'value': 'value'}", NonConflictingGenericSetterSubBean.class);
assertEquals("subsetter:value", bean.value);
}
private enum Enum {
Foo,
Bar
}
private enum ComplexEnum {
One("one"),
Two("two");
private String value;
ComplexEnum(String value) {
this.value = value;
}
public String getValue() {
return this.value;
}
public void setValue(String value) {
this.value = value;
}
}
private static class StringBean {
private String value;
public String getValue() {
return value;
}
}
private static class DoubleBean {
private double value;
public double getValue() {
return value;
}
}
private static class FloatBean {
private float value;
public float getValue() {
return value;
}
}
private static class LongBean {
private long value;
public long getValue() {
return value;
}
}
private static class IntBean {
private int value;
public int getValue() {
return value;
}
}
private static class BooleanBean {
private boolean value;
public boolean isValue() {
return value;
}
}
private static class ShortBean {
private short value;
public short getValue() {
return value;
}
}
private static class ByteBean {
private byte value;
public byte getValue() {
return value;
}
}
private static class CharBean {
private char value;
public char getValue() {
return value;
}
}
private static class IntArrayBean {
private int[] values;
public int[] getValues() {
return this.values;
}
}
private static class StringArrayBean {
private String[] values;
public String[] getValues() {
return this.values;
}
}
// CSOFF: MemberName
private static class XMLAndURLBean {
public String XMLAndURL2;
private String XMLAndURL1;
public String getXMLAndURL1() {
return XMLAndURL1;
}
public void setXMLAndURL1(String value) {
this.XMLAndURL1 = value;
}
}
private static class SetterBean {
private String value;
public String getValue() {
return this.value;
}
public void setValue(String value) {
this.value = "setter:" + value;
}
}
private static class PrivateSetterBean {
public String value;
private void setValue(String value) {
this.value = "setter:" + value;
}
}
private static class GetterBean {
private String value;
public String getValue() {
return "getter:" + this.value;
}
}
private static class GetterPublicFieldBean {
public String value;
public String getValue() {
return "getter:" + this.value;
}
}
private static class GetterPublicFieldBeanCaseSensitive {
public String valueCase;
public String getValueCASE() {
return "getter:" + this.valueCase;
}
}
// CSOFF: AbbreviationAsWordInNameCheck
private static class CaseSensitiveGetterBean1 {
private String value;
public String getVALUE() {
return this.value;
}
}
private static class CaseSensitiveGetterBean2 {
private String value;
public String getvalue() {
return this.value;
}
}
private static class CaseSensitiveGetterBean3 {
private String value;
public String getVAlue() {
return this.value;
}
}
private static class CaseSensitiveGetterBean4 {
private String value;
public String getvaLUE() {
return this.value;
}
}
private static class CaseSensitiveSetterBean1 {
private String value;
public String getValue() {
return this.value;
}
public void setValue(String value) {
this.value = "setter:" + value;
}
public void setVAlue(String value) {
this.value = "wrong setter!";
}
}
private static class CaseSensitiveSetterBean2 {
private String value;
public String getValue() {
return this.value;
}
public void setValue(String value) {
this.value = "setter:" + value;
}
public void setvalue(String value) {
this.value = "wrong setter!";
}
}
private static class CaseSensitiveSetterBean3 {
private String value;
public String getValue() {
return this.value;
}
public void setvalue(String value) {
this.value = "setter:" + value;
}
}
private static class CaseSensitiveSetterBean4 {
private String value;
public String getValue() {
return this.value;
}
public void setVALUE(String value) {
this.value = "setter:" + value;
}
}
//CSOFF: MethodName
private static class CaseSensitiveSetterBean5 {
private String value;
public String getValue() {
return this.value;
}
public void SETVALUE(String value) {
this.value = "wrong setter!";
}
}
private static class CaseSensitiveSetterBean6 {
private String value;
public String getValue() {
return this.value;
}
public void setVaLUE(String value) {
this.value = "setter:" + value;
}
}
@SuppressWarnings("ConstantField")
private static class CaseSensitiveFieldBean1 {
public String VALUE;
}
private static class CaseSensitiveFieldBean2 {
public String value;
}
private static class CaseSensitiveFieldBean3 {
public String Value;
}
private static class CaseSensitiveFieldBean4 {
public String valUE;
}
private static class WrongSetterBean {
private String value;
public String getValue() {
return this.value;
}
public void setValue() {
this.value = "wrong setter!";
}
public void setValue(String one, String two) {
this.value = "wrong setter!";
}
}
private static class WrongTypeBean {
private Integer value;
public String getValue() {
return "" + this.value;
}
}
private static class RecursiveBean {
private StringBean bean;
public StringBean getBean() {
return this.bean;
}
}
private static class ObjectBean {
private Object value;
public Object getValue() {
return value;
}
}
private static class GenericBean<B> {
private B value;
public B getValue() {
return value;
}
}
private static class DoubleGenericBean<A, B> {
private A valueA;
private B valueB;
public A getValueA() {
return valueA;
}
public B getValueB() {
return valueB;
}
}
private static class ListBean {
private List<String> values;
public List<String> getValues() {
return this.values;
}
}
private static class SetBean {
private Set<String> values;
public Set<String> getValues() {
return this.values;
}
}
private static class CollectionBean {
private Collection<String> values;
public Collection<String> getValues() {
return this.values;
}
}
private static class MapBean {
private Map<String, String> values;
public Map<String, String> getValues() {
return this.values;
}
}
private static class RecursiveListBean {
private List<StringBean> values;
public List<StringBean> getValues() {
return this.values;
}
}
private static class RecursiveMapBean {
private Map<String, StringBean> values;
public Map<String, StringBean> getValues() {
return this.values;
}
}
private static class IllegalKeyMapBean {
private Map<Integer, StringBean> values;
public Map<Integer, StringBean> getValues() {
return this.values;
}
}
private static class PublicFieldBean {
public String value;
}
@ThrowOnExtraProperties
private static class ThrowOnUnknownPropertiesBean {
public String value;
}
@ThrowOnExtraProperties
private static class PackageFieldBean {
String value;
}
@ThrowOnExtraProperties
@SuppressWarnings("unused") // Unused, but required for the test
private static class PrivateFieldBean {
private String value;
}
private static class PackageGetterBean {
private String packageValue;
private String publicValue;
String getPackageValue() {
return this.packageValue;
}
public String getPublicValue() {
return this.publicValue;
}
}
private static class ExcludedBean {
@Exclude public String excludedField = "no-value";
private String excludedGetter = "no-value";
private String includedGetter = "no-value";
@Exclude
public String getExcludedGetter() {
return this.excludedGetter;
}
public String getIncludedGetter() {
return this.includedGetter;
}
}
private static class ExcludedSetterBean {
private String value;
public String getValue() {
return this.value;
}
@Exclude
public void setValue(String value) {
this.value = "wrong setter";
}
}
private static class PropertyNameBean {
@PropertyName("my_key")
public String key;
private String value;
@PropertyName("my_value")
public String getValue() {
return this.value;
}
@PropertyName("my_value")
public void setValue(String value) {
this.value = value;
}
}
private static class PublicPrivateFieldBean {
public String value1;
String value2;
private String value3;
}
private static class TwoSetterBean {
private String value;
public String getValue() {
return this.value;
}
public void setValue(Integer value) {
this.value = "int:" + value;
}
public void setValue(String value) {
this.value = "string:" + value;
}
}
private static class TwoGetterBean {
private String value;
public String getValue() {
return this.value;
}
public String getVALUE() {
return this.value;
}
}
//CSON: AbbreviationAsWordInNameCheck
private static class GetterArgumentsBean {
private String value;
public String getValue1() {
return this.value + "1";
}
public void getValue2() {}
public String getValue3(boolean flag) {
return this.value + "3";
}
public String getValue4() {
return this.value + "4";
}
}
@SuppressWarnings("ConstantField")
private static class UnicodeBean {
private String 漢字;
public String get漢字() {
return this.漢字;
}
}
//CSON: MethodName
//CSON: MemberName
private static class PublicConstructorBean {
private String value;
public PublicConstructorBean() {}
public String getValue() {
return this.value;
}
}
private static class PrivateConstructorBean {
private String value;
private PrivateConstructorBean() {}
public String getValue() {
return this.value;
}
}
private static class PackageConstructorBean {
private String value;
PackageConstructorBean() {}
public String getValue() {
return this.value;
}
}
private static class ArgConstructorBean {
private String value;
public ArgConstructorBean(String value) {
this.value = value;
}
public String getValue() {
return this.value;
}
}
private static class MultipleConstructorBean {
private String value;
public MultipleConstructorBean(String value) {
this.value = "wrong-value";
}
public MultipleConstructorBean() {}
public String getValue() {
return this.value;
}
}
private static class StaticFieldBean {
public static String value1 = "static-value";
public String value2;
}
private static class StaticMethodBean {
private static String value1 = "static-value";
public String value2;
public static String getValue1() {
return StaticMethodBean.value1;
}
public static void setValue1(String value1) {
StaticMethodBean.value1 = value1;
}
}
private static class EnumBean {
public Enum enumField;
public ComplexEnum complexEnum;
private Enum enumValue;
public Enum getEnumValue() {
return this.enumValue;
}
public void setEnumValue(Enum enumValue) {
this.enumValue = enumValue;
}
}
private static class BaseBean {
// Public field on base class
public String baseValue;
// Value that is accessed through overridden methods in subclasses
public String overrideValue;
// Field that is package private in base class
String packageBaseValue;
// Private field that is used in getter/setter in base class
private String baseMethodValue;
// Private field that has field with same name in subclasses
private String classPrivateValue;
public String getClassPrivateValue() {
return this.classPrivateValue;
}
public String getBaseMethod() {
return this.baseMethodValue;
}
public void setBaseMethod(String value) {
this.baseMethodValue = value;
}
public String getPackageBaseValue() {
return this.packageBaseValue;
}
}
private static class InheritedBean extends BaseBean {
public String inheritedValue;
private String inheritedMethodValue;
private String classPrivateValue;
@Override
public String getClassPrivateValue() {
return this.classPrivateValue;
}
public String getInheritedMethod() {
return this.inheritedMethodValue;
}
public void setInheritedMethod(String value) {
this.inheritedMethodValue = value;
}
public String getOverrideValue() {
return this.overrideValue + "-inherited";
}
public void setOverrideValue(String value) {
this.overrideValue = value + "-inherited";
}
}
private static final class FinalBean extends InheritedBean {
public String finalValue;
private String finalMethodValue;
private String classPrivateValue;
@Override
public String getClassPrivateValue() {
return this.classPrivateValue;
}
public String getFinalMethod() {
return this.finalMethodValue;
}
public void setFinalMethod(String value) {
this.finalMethodValue = value;
}
@Override
public String getOverrideValue() {
return this.overrideValue + "-final";
}
@Override
public void setOverrideValue(String value) {
this.overrideValue = value + "-final";
}
}
// Conflicting setters are not supported. When inheriting from a base class we require all
// setters be an override of a base class
private static class ConflictingSetterBean {
public int value;
// package private so override can be public
void setValue(int value) {
this.value = value;
}
}
private static class ConflictingSetterSubBean extends ConflictingSetterBean {
public void setValue(String value) {
this.value = -1;
}
}
private static class ConflictingSetterSubBean2 extends ConflictingSetterBean {
public void setValue(Integer value) {
this.value = -1;
}
}
private static class NonConflictingSetterSubBean extends ConflictingSetterBean {
@Override
public void setValue(int value) {
this.value = value * -1;
}
}
private static class GenericSetterBaseBean<T> {
public T value;
void setValue(T value) {
this.value = value;
}
}
private static class ConflictingGenericSetterSubBean<T> extends GenericSetterBaseBean<T> {
public void setValue(String value) {
// wrong setter
}
}
private static class NonConflictingGenericSetterSubBean extends GenericSetterBaseBean<String> {
@Override
public void setValue(String value) {
this.value = "subsetter:" + value;
}
}
private abstract static class GenericTypeIndicatorSubclass<T> extends GenericTypeIndicator<T> {}
private abstract static class NonGenericTypeIndicatorSubclass
extends GenericTypeIndicator<GenericBean<String>> {}
private static class NonGenericTypeIndicatorConcreteSubclass
extends GenericTypeIndicator<GenericBean<String>> {}
private static class NonGenericTypeIndicatorSubclassConcreteSubclass
extends GenericTypeIndicatorSubclass<GenericBean<String>> {}
}
| {
"content_hash": "b6910ba0c6c6f62439b84ac763f8359b",
"timestamp": "",
"source": "github",
"line_count": 2059,
"max_line_length": 100,
"avg_line_length": 26.528411850412823,
"alnum_prop": 0.6691992237559957,
"repo_name": "firebase/firebase-admin-java",
"id": "941fbde9d1835b8bd438030adbbf69864676eda3",
"size": "55244",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/test/java/com/google/firebase/database/MapperTest.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Java",
"bytes": "3736707"
},
{
"name": "Shell",
"bytes": "2174"
}
],
"symlink_target": ""
} |
Rails.application.config.session_store :cookie_store, key: '_chalmersit_session'
| {
"content_hash": "d24667f4e76245a02c9073b4db470f90",
"timestamp": "",
"source": "github",
"line_count": 1,
"max_line_length": 80,
"avg_line_length": 81,
"alnum_prop": 0.8024691358024691,
"repo_name": "cthit/chalmersit-account-rails",
"id": "7bb717e24563fde047d9edf311f43f1097eb12e2",
"size": "142",
"binary": false,
"copies": "1",
"ref": "refs/heads/develop",
"path": "config/initializers/session_store.rb",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "4925"
},
{
"name": "CoffeeScript",
"bytes": "2077"
},
{
"name": "HTML",
"bytes": "68760"
},
{
"name": "JavaScript",
"bytes": "1944"
},
{
"name": "Ruby",
"bytes": "114927"
}
],
"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 -->
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Uses of Class io.permazen.parse.expr.MethodReferenceNode (Permazen 4.1.9 API)</title>
<link rel="stylesheet" type="text/css" href="../../../../../stylesheet.css" title="Style">
<script type="text/javascript" src="../../../../../script.js"></script>
</head>
<body>
<script type="text/javascript"><!--
try {
if (location.href.indexOf('is-external=true') == -1) {
parent.document.title="Uses of Class io.permazen.parse.expr.MethodReferenceNode (Permazen 4.1.9 API)";
}
}
catch(err) {
}
//-->
</script>
<noscript>
<div>JavaScript is disabled on your browser.</div>
</noscript>
<!-- ========= START OF TOP NAVBAR ======= -->
<div class="topNav"><a name="navbar.top">
<!-- -->
</a>
<div class="skipNav"><a href="#skip.navbar.top" title="Skip navigation links">Skip navigation links</a></div>
<a name="navbar.top.firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../../../overview-summary.html">Overview</a></li>
<li><a href="../package-summary.html">Package</a></li>
<li><a href="../../../../../io/permazen/parse/expr/MethodReferenceNode.html" title="class in io.permazen.parse.expr">Class</a></li>
<li class="navBarCell1Rev">Use</li>
<li><a href="../package-tree.html">Tree</a></li>
<li><a href="../../../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../../../index-all.html">Index</a></li>
<li><a href="../../../../../help-doc.html">Help</a></li>
</ul>
</div>
<div class="subNav">
<ul class="navList">
<li>Prev</li>
<li>Next</li>
</ul>
<ul class="navList">
<li><a href="../../../../../index.html?io/permazen/parse/expr/class-use/MethodReferenceNode.html" target="_top">Frames</a></li>
<li><a href="MethodReferenceNode.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_top">
<li><a href="../../../../../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_top");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
</div>
<a name="skip.navbar.top">
<!-- -->
</a></div>
<!-- ========= END OF TOP NAVBAR ========= -->
<div class="header">
<h2 title="Uses of Class io.permazen.parse.expr.MethodReferenceNode" class="title">Uses of Class<br>io.permazen.parse.expr.MethodReferenceNode</h2>
</div>
<div class="classUseContainer">
<ul class="blockList">
<li class="blockList">
<table class="useSummary" border="0" cellpadding="3" cellspacing="0" summary="Use table, listing packages, and an explanation">
<caption><span>Packages that use <a href="../../../../../io/permazen/parse/expr/MethodReferenceNode.html" title="class in io.permazen.parse.expr">MethodReferenceNode</a></span><span class="tabEnd"> </span></caption>
<tr>
<th class="colFirst" scope="col">Package</th>
<th class="colLast" scope="col">Description</th>
</tr>
<tbody>
<tr class="altColor">
<td class="colFirst"><a href="#io.permazen.parse.expr">io.permazen.parse.expr</a></td>
<td class="colLast">
<div class="block">Classes for parsing Java expressions with Permazen-specific extensions.</div>
</td>
</tr>
</tbody>
</table>
</li>
<li class="blockList">
<ul class="blockList">
<li class="blockList"><a name="io.permazen.parse.expr">
<!-- -->
</a>
<h3>Uses of <a href="../../../../../io/permazen/parse/expr/MethodReferenceNode.html" title="class in io.permazen.parse.expr">MethodReferenceNode</a> in <a href="../../../../../io/permazen/parse/expr/package-summary.html">io.permazen.parse.expr</a></h3>
<table class="useSummary" border="0" cellpadding="3" cellspacing="0" summary="Use table, listing subclasses, and an explanation">
<caption><span>Subclasses of <a href="../../../../../io/permazen/parse/expr/MethodReferenceNode.html" title="class in io.permazen.parse.expr">MethodReferenceNode</a> in <a href="../../../../../io/permazen/parse/expr/package-summary.html">io.permazen.parse.expr</a></span><span class="tabEnd"> </span></caption>
<tr>
<th class="colFirst" scope="col">Modifier and Type</th>
<th class="colLast" scope="col">Class and Description</th>
</tr>
<tbody>
<tr class="altColor">
<td class="colFirst"><code>class </code></td>
<td class="colLast"><code><span class="memberNameLink"><a href="../../../../../io/permazen/parse/expr/BoundMethodReferenceNode.html" title="class in io.permazen.parse.expr">BoundMethodReferenceNode</a></span></code>
<div class="block"><a href="../../../../../io/permazen/parse/expr/Node.html" title="interface in io.permazen.parse.expr"><code>Node</code></a> representing a bound method reference like <code>"foobar"::indexOf</code>.</div>
</td>
</tr>
<tr class="rowColor">
<td class="colFirst"><code>class </code></td>
<td class="colLast"><code><span class="memberNameLink"><a href="../../../../../io/permazen/parse/expr/UnboundMethodReferenceNode.html" title="class in io.permazen.parse.expr">UnboundMethodReferenceNode</a></span></code>
<div class="block"><a href="../../../../../io/permazen/parse/expr/Node.html" title="interface in io.permazen.parse.expr"><code>Node</code></a> representing an unbound method reference like <code>String::valueOf</code> or <code>String::length</code>.</div>
</td>
</tr>
</tbody>
</table>
</li>
</ul>
</li>
</ul>
</div>
<!-- ======= START OF BOTTOM NAVBAR ====== -->
<div class="bottomNav"><a name="navbar.bottom">
<!-- -->
</a>
<div class="skipNav"><a href="#skip.navbar.bottom" title="Skip navigation links">Skip navigation links</a></div>
<a name="navbar.bottom.firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../../../overview-summary.html">Overview</a></li>
<li><a href="../package-summary.html">Package</a></li>
<li><a href="../../../../../io/permazen/parse/expr/MethodReferenceNode.html" title="class in io.permazen.parse.expr">Class</a></li>
<li class="navBarCell1Rev">Use</li>
<li><a href="../package-tree.html">Tree</a></li>
<li><a href="../../../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../../../index-all.html">Index</a></li>
<li><a href="../../../../../help-doc.html">Help</a></li>
</ul>
</div>
<div class="subNav">
<ul class="navList">
<li>Prev</li>
<li>Next</li>
</ul>
<ul class="navList">
<li><a href="../../../../../index.html?io/permazen/parse/expr/class-use/MethodReferenceNode.html" target="_top">Frames</a></li>
<li><a href="MethodReferenceNode.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 ======= -->
<p class="legalCopy"><small>Copyright © 2022. All rights reserved.</small></p>
</body>
</html>
| {
"content_hash": "4bb7f0e3585273ab8262d761095179f8",
"timestamp": "",
"source": "github",
"line_count": 175,
"max_line_length": 315,
"avg_line_length": 41.89142857142857,
"alnum_prop": 0.6452052925930978,
"repo_name": "permazen/permazen",
"id": "93b0c615dfbb7402c42f8194c19517c61d6ac2f5",
"size": "7331",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "site/apidocs/io/permazen/parse/expr/class-use/MethodReferenceNode.html",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "297472"
},
{
"name": "HTML",
"bytes": "36524914"
},
{
"name": "Java",
"bytes": "5423144"
},
{
"name": "JavaScript",
"bytes": "827"
}
],
"symlink_target": ""
} |
package com.sleepycat.util;
import java.io.IOException;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
/**
* A replacement for ByteArrayOutputStream that does not synchronize every
* byte read.
*
* <p>This class extends {@link OutputStream} and its <code>write()</code>
* methods allow it to be used as a standard output stream. In addition, it
* provides <code>writeFast()</code> methods that are not declared to throw
* <code>IOException</code>. <code>IOException</code> is never thrown by this
* class.</p>
*
* @author Mark Hayes
*/
public class FastOutputStream extends OutputStream {
/**
* The default initial size of the buffer if no initialSize parameter is
* specified. This constant is 100 bytes.
*/
public static final int DEFAULT_INIT_SIZE = 100;
/**
* The default amount that the buffer is increased when it is full. This
* constant is zero, which means to double the current buffer size.
*/
public static final int DEFAULT_BUMP_SIZE = 0;
private int len;
private int bumpLen;
private byte[] buf;
/*
* We can return the same byte[] for 0 length arrays.
*/
private static byte[] ZERO_LENGTH_BYTE_ARRAY = new byte[0];
/**
* Creates an output stream with default sizes.
*/
public FastOutputStream() {
initBuffer(DEFAULT_INIT_SIZE, DEFAULT_BUMP_SIZE);
}
/**
* Creates an output stream with a default bump size and a given initial
* size.
*
* @param initialSize the initial size of the buffer.
*/
public FastOutputStream(int initialSize) {
initBuffer(initialSize, DEFAULT_BUMP_SIZE);
}
/**
* Creates an output stream with a given bump size and initial size.
*
* @param initialSize the initial size of the buffer.
*
* @param bumpSize the amount to increment the buffer.
*/
public FastOutputStream(int initialSize, int bumpSize) {
initBuffer(initialSize, bumpSize);
}
/**
* Creates an output stream with a given initial buffer and a default
* bump size.
*
* @param buffer the initial buffer; will be owned by this object.
*/
public FastOutputStream(byte[] buffer) {
buf = buffer;
bumpLen = DEFAULT_BUMP_SIZE;
}
/**
* Creates an output stream with a given initial buffer and a given
* bump size.
*
* @param buffer the initial buffer; will be owned by this object.
*
* @param bumpSize the amount to increment the buffer. If zero (the
* default), the current buffer size will be doubled when the buffer is
* full.
*/
public FastOutputStream(byte[] buffer, int bumpSize) {
buf = buffer;
bumpLen = bumpSize;
}
private void initBuffer(int bufferSize, int bumplength) {
buf = new byte[bufferSize];
this.bumpLen = bumplength;
}
// --- begin ByteArrayOutputStream compatible methods ---
public int size() {
return len;
}
public void reset() {
len = 0;
}
@Override
public void write(int b) {
writeFast(b);
}
@Override
public void write(byte[] fromBuf) {
writeFast(fromBuf);
}
@Override
public void write(byte[] fromBuf, int offset, int length) {
writeFast(fromBuf, offset, length);
}
public void writeTo(OutputStream out) throws IOException {
out.write(buf, 0, len);
}
@Override
public String toString() {
return new String(buf, 0, len);
}
public String toString(String encoding)
throws UnsupportedEncodingException {
return new String(buf, 0, len, encoding);
}
public byte[] toByteArray() {
if (len == 0) {
return ZERO_LENGTH_BYTE_ARRAY;
}
byte[] toBuf = new byte[len];
System.arraycopy(buf, 0, toBuf, 0, len);
return toBuf;
}
// --- end ByteArrayOutputStream compatible methods ---
/**
* Equivalent to <code>write(int)<code> but does not throw
* <code>IOException</code>.
* @see #write(int)
*/
public final void writeFast(int b) {
if (len + 1 > buf.length)
bump(1);
buf[len++] = (byte) b;
}
/**
* Equivalent to <code>write(byte[])<code> but does not throw
* <code>IOException</code>.
* @see #write(byte[])
*/
public final void writeFast(byte[] fromBuf) {
int needed = len + fromBuf.length - buf.length;
if (needed > 0)
bump(needed);
System.arraycopy(fromBuf, 0, buf, len, fromBuf.length);
len += fromBuf.length;
}
/**
* Equivalent to <code>write(byte[],int,int)<code> but does not throw
* <code>IOException</code>.
* @see #write(byte[],int,int)
*/
public final void writeFast(byte[] fromBuf, int offset, int length) {
int needed = len + length - buf.length;
if (needed > 0)
bump(needed);
System.arraycopy(fromBuf, offset, buf, len, length);
len += length;
}
/**
* Returns the buffer owned by this object.
*
* @return the buffer.
*/
public byte[] getBufferBytes() {
return buf;
}
/**
* Returns the offset of the internal buffer.
*
* @return always zero currently.
*/
public int getBufferOffset() {
return 0;
}
/**
* Returns the length used in the internal buffer, i.e., the offset at
* which data will be written next.
*
* @return the buffer length.
*/
public int getBufferLength() {
return len;
}
/**
* Ensure that at least the given number of bytes are available in the
* internal buffer.
*
* @param sizeNeeded the number of bytes desired.
*/
public void makeSpace(int sizeNeeded) {
int needed = len + sizeNeeded - buf.length;
if (needed > 0)
bump(needed);
}
/**
* Skip the given number of bytes in the buffer.
*
* @param sizeAdded number of bytes to skip.
*/
public void addSize(int sizeAdded) {
len += sizeAdded;
}
private void bump(int needed) {
/* Double the buffer if the bumpLen is zero. */
int bump = (bumpLen > 0) ? bumpLen : buf.length;
byte[] toBuf = new byte[buf.length + needed + bump];
System.arraycopy(buf, 0, toBuf, 0, len);
buf = toBuf;
}
}
| {
"content_hash": "af15861876430673bbb1fba999eb7f5d",
"timestamp": "",
"source": "github",
"line_count": 276,
"max_line_length": 78,
"avg_line_length": 23.634057971014492,
"alnum_prop": 0.593131994481067,
"repo_name": "prat0318/dbms",
"id": "a9b4f95f8a3b1f3d069fc2d68ed60a876d5bff4b",
"size": "8115",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "mini_dbms/je-5.0.103/src/com/sleepycat/util/FastOutputStream.java",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Java",
"bytes": "10102975"
},
{
"name": "SQL",
"bytes": "1981542"
},
{
"name": "Scala",
"bytes": "4121"
},
{
"name": "Shell",
"bytes": "3212"
}
],
"symlink_target": ""
} |
ACCEPTED
#### According to
Index Fungorum
#### Published in
in Rambo (Ed. ), Iheringia, Sér. Bot. 5: 170 (1959)
#### Original name
Pseudasterodon griseoglaucus Rick
### Remarks
null | {
"content_hash": "9b9eb8aec4f4ec9426d9543511e20f18",
"timestamp": "",
"source": "github",
"line_count": 13,
"max_line_length": 51,
"avg_line_length": 14.23076923076923,
"alnum_prop": 0.6972972972972973,
"repo_name": "mdoering/backbone",
"id": "d74be4b0b0af9e665ec1bee31f8df31d79fd8227",
"size": "243",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "life/Fungi/Basidiomycota/Agaricomycetes/Pseudasterodon/Pseudasterodon griseoglaucus/README.md",
"mode": "33188",
"license": "apache-2.0",
"language": [],
"symlink_target": ""
} |
"""Setup file for pip installation."""
from setuptools import setup
setup(
name="jax-particles",
version="0.1",
description="a 2D physics simulator for circles",
packages=["jax_particles"],
python_requires=">=3.7",
install_requires=["jax", "inputs"],
)
| {
"content_hash": "e511d7cf2f15259519c2e2aa6af18b26",
"timestamp": "",
"source": "github",
"line_count": 11,
"max_line_length": 53,
"avg_line_length": 25.272727272727273,
"alnum_prop": 0.6546762589928058,
"repo_name": "google-research/google-research",
"id": "bcfb86097875b2797ac31def04f4554434f4983e",
"size": "886",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "jax_particles/setup.py",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "C",
"bytes": "9817"
},
{
"name": "C++",
"bytes": "4166670"
},
{
"name": "CMake",
"bytes": "6412"
},
{
"name": "CSS",
"bytes": "27092"
},
{
"name": "Cuda",
"bytes": "1431"
},
{
"name": "Dockerfile",
"bytes": "7145"
},
{
"name": "Gnuplot",
"bytes": "11125"
},
{
"name": "HTML",
"bytes": "77599"
},
{
"name": "ImageJ Macro",
"bytes": "50488"
},
{
"name": "Java",
"bytes": "487585"
},
{
"name": "JavaScript",
"bytes": "896512"
},
{
"name": "Julia",
"bytes": "67986"
},
{
"name": "Jupyter Notebook",
"bytes": "71290299"
},
{
"name": "Lua",
"bytes": "29905"
},
{
"name": "MATLAB",
"bytes": "103813"
},
{
"name": "Makefile",
"bytes": "5636"
},
{
"name": "NASL",
"bytes": "63883"
},
{
"name": "Perl",
"bytes": "8590"
},
{
"name": "Python",
"bytes": "53790200"
},
{
"name": "R",
"bytes": "101058"
},
{
"name": "Roff",
"bytes": "1208"
},
{
"name": "Rust",
"bytes": "2389"
},
{
"name": "Shell",
"bytes": "730444"
},
{
"name": "Smarty",
"bytes": "5966"
},
{
"name": "Starlark",
"bytes": "245038"
}
],
"symlink_target": ""
} |
{% extends "layout.html" %}
{% block page_title %}
GOV.UK prototyping kit
{% endblock %}
{% block propositionHeader %}
{% include "includes/propositional_navigation.html" %}
{% endblock %}
{% block content %}
<main id="content" role="main">
<div class="grid-row">
<div class="column-quarter grid-col" style="padding-bottom:90px; padding-top:30px; margin-left:-40px">
<ul class="main-nav">
<li id="nav-home"><a href="job">Search</a></li>
<li id="nav-job"><a href="job_new">Create record</a></li>
<li id="nav-perf"><a href="performance">Caseload</a></li>
</ul>
</div>
<!-- Start three quarters container for main content columns -->
<div class="column-three-quarters">
<h1 class="heading-large"> Edit basic record</h1>
<div class="column">
<!-- 3rd level nav buttons -->
<div id="id-claimant-actions" class="grid-wrapper gutter-half-top">
<div class="grid grid-1-5">
<div class="inner-block left">
<a id="Summary" href="job_record_confirm" class="menu-item">
<strong>Summary</strong>
</a>
</div>
</div>
<div class="grid grid-1-5">
<div class="inner-block left">
<a id="edit_record" href="job_edit" class="menu-item selected">
<strong>Claimant</strong>
</a>
</div>
</div>
<div class="grid grid-1-5">
<div class="inner-block left">
<a id="appointments" href="job_next_new" class="menu-item">
<strong>Appointment</strong>
</a>
</div>
</div>
<div class="grid grid-1-5">
<div class="inner-block left">
<a id="claim_active" href="job_claim_active" class="menu-item">
<strong>Claim</strong>
</a>
</div>
</div>
</div>
</div>
<div class="column">
<ul class="tabs" id="claimant_details">
<li><a href="job_edit_confirm">View record</a></li>
<li class="selected"><a href="job_edit">Edit record</a></li>
<li><a href="job_edit_details">Markers</a></li>
<!-- <li><a href="job_edit_disability">Disability</a></li> -->
<li><a href="job_sector">Sector</a></li>
<!-- <li><a href="job_day_one">Day one</a></li> -->
<li><a href="job_prog">Programmes</a></li>
<!-- <li><a href="job_exp">Experience</a></li>
<li><a href="job_vol">Voluntary</a></li> -->
</ul>
</div>
<div class="column-half">
<form method="post" class="group" id="form" data-parsley-validate>
<div class="form-group">
<label class="form-label" for="nino">National Insurance number</label>
<input class="form-control" id="nino" type="text" value="JC628596A">
</div>
<div class="form-group title">
<label class="form-label" for="title">Title</label>
<select class="form-control" id="title">
<option value="Mr">Mr</option>
<option value="Mrs">Mrs</option>
<option value="Miss">Miss</option>
<option value="Ms">Ms</option>
<option value="Dr">Dr</option>
</select>
</div>
<div class="form-group initial">
<label class="form-label" for="inital">Initial</label>
<input class="form-control" id="inital" type="text" value="J">
</div>
<div class="form-group">
<label class="form-label" for="Surname">Surname</label>
<input class="form-control" id="Surname" type="text" value="Smith">
</div>
<div class="form-group">
<fieldset class="inline">
<legend class="form-label">Gender</legend>
<label class="block-label" for="male">
<input id="male" name="male" type="radio" value="male" checked>
Male
</label>
<label class="block-label" for="female">
<input id="female" name="female" type="radio" value="female">
Female
</label>
</fieldset>
</div>
<div class="form-group">
<fieldset>
<legend>
<span class="form-label">
Date of birth
</span>
</legend>
<div class="form-date">
<p class="form-hint">For example, 03 1980</p>
<div class="form-group form-group-month">
<label for="dob-month">Month</label>
<input class="form-control" id="dob-month" type="number" pattern="[0-9]*" min="0" max="12" value="08">
</div>
<div class="form-group form-group-year">
<label for="dob-year">Year</label>
<input class="form-control" id="dob-year" type="number" pattern="[0-9]*" min="0" max="2014" value="1981">
</div>
</div>
</fieldset>
</div>
</div>
<!-- End col -->
<!-- Start col -->
<div class="column-half">
<div class="form-group">
<label class="form-label" for="email">Email address</label>
<input class="form-control" id="email" type="text" value="john_smith@gmail.com"><br>
<label class="block-label" for="contact">
<input id="contact" name="contact" type="checkbox" value="Do not contact">
Do not contact
</label>
</div>
<div class="form-group">
<label class="form-label" for="mobile">Mobile number</label>
<input class="form-control" id="mobile" type="text" value="07585747358"><br>
<label class="block-label" for="contact">
<input id="contact" name="contact" type="checkbox" value="Do not contact">
Do not contact
</label>
</div>
<div class="form-group">
<label class="form-label" for="postcode">Postcode</label>
<input class="form-control" id="postcode" type="text">
</div>
<div class="form-group">
<label class="form-label" for="mobile">Language</label>
<label class="block-label" for="contact1">
<input id="contact1" name="contact1" type="checkbox" value="Do not contact">
Welsh speaker
</label>
</div>
<!-- End column-->
</div>
<div class="column">
<div class="form-group" id="save">
<a href="job_edit_confirm" class="button" value="Save">Save</a>
</div>
</div>
</form>
<!-- End three quarters column-->
</div>
<!-- End row-->
</div>
</main>
{% endblock %}
| {
"content_hash": "fca53ff5f0644c86705341114281ff60",
"timestamp": "",
"source": "github",
"line_count": 219,
"max_line_length": 129,
"avg_line_length": 35.337899543378995,
"alnum_prop": 0.45005814704742214,
"repo_name": "dwpdigitaltech/ejs-prototype",
"id": "c5d586399ca4c941e94ba378637cc531d6bfa460",
"size": "7739",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "app/views/sprint_10_c/job_edit.html",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "94097"
},
{
"name": "HTML",
"bytes": "23756156"
},
{
"name": "JavaScript",
"bytes": "107357"
},
{
"name": "Shell",
"bytes": "1495"
}
],
"symlink_target": ""
} |
#ifndef WEBDRIVER_IE_MOUSEMOVETOCOMMANDHANDLER_H_
#define WEBDRIVER_IE_MOUSEMOVETOCOMMANDHANDLER_H_
#include "interactions.h"
#include "Session.h"
namespace webdriver {
class MouseMoveToCommandHandler : public CommandHandler {
public:
MouseMoveToCommandHandler(void) {
}
virtual ~MouseMoveToCommandHandler(void) {
}
protected:
void MouseMoveToCommandHandler::ExecuteInternal(const IESessionWindow& session, const LocatorMap& locator_parameters, const ParametersMap& command_parameters, Response * response) {
ParametersMap::const_iterator element_parameter_iterator = command_parameters.find("element");
ParametersMap::const_iterator xoffset_parameter_iterator = command_parameters.find("xoffset");
ParametersMap::const_iterator yoffset_parameter_iterator = command_parameters.find("yoffset");
bool element_specified(element_parameter_iterator != command_parameters.end());
bool offset_specified((xoffset_parameter_iterator != command_parameters.end()) && (yoffset_parameter_iterator != command_parameters.end()));
if (!element_specified && !offset_specified) {
response->SetErrorResponse(400, "Missing parameters: element, xoffset, yoffset");
return;
} else {
int status_code = SUCCESS;
long start_x = session.last_known_mouse_x();
long start_y = session.last_known_mouse_y();
long end_x = start_x;
long end_y = start_y;
if (element_specified && !element_parameter_iterator->second.isNull()) {
std::wstring element_id = CA2W(element_parameter_iterator->second.asCString(), CP_UTF8);
status_code = this->GetElementCoordinates(session, element_id, offset_specified, &end_x, &end_y);
if (status_code != SUCCESS) {
response->SetErrorResponse(status_code, "Unable to locate element with id " + element_parameter_iterator->second.asString());
}
}
if (offset_specified) {
end_x += xoffset_parameter_iterator->second.asInt();
end_y += yoffset_parameter_iterator->second.asInt();
}
BrowserHandle browser_wrapper;
status_code = session.GetCurrentBrowser(&browser_wrapper);
if (status_code != SUCCESS) {
response->SetErrorResponse(status_code, "Unable to get current browser");
}
HWND browser_window_handle = browser_wrapper->GetWindowHandle();
LRESULT move_result = mouseMoveTo(browser_window_handle, session.speed(), start_x, start_y, end_x, end_y);
IESessionWindow& mutable_session = const_cast<IESessionWindow&>(session);
mutable_session.set_last_known_mouse_x(end_x);
mutable_session.set_last_known_mouse_y(end_y);
response->SetResponse(SUCCESS, Json::Value::null);
return;
}
}
private:
int MouseMoveToCommandHandler::GetElementCoordinates(const IESessionWindow& session, const std::wstring& element_id, bool get_element_origin, long *x_coordinate, long *y_coordinate) {
ElementHandle target_element;
int status_code = this->GetElement(session, element_id, &target_element);
if (status_code != SUCCESS) {
return status_code;
}
long element_x, element_y, element_width, element_height;
status_code = target_element->GetLocationOnceScrolledIntoView(&element_x, &element_y, &element_width, &element_height);
if (status_code == SUCCESS) {
if (get_element_origin) {
*x_coordinate = element_x;
*y_coordinate = element_y;
} else {
*x_coordinate = element_x + (element_width / 2);
*y_coordinate = element_y + (element_height / 2);
}
}
return SUCCESS;
}
};
} // namespace webdriver
#endif // WEBDRIVER_IE_MOUSEMOVETOCOMMANDHANDLER_H_
| {
"content_hash": "00c90de3b48eb3d47d85311da1b73274",
"timestamp": "",
"source": "github",
"line_count": 93,
"max_line_length": 184,
"avg_line_length": 38.70967741935484,
"alnum_prop": 0.7080555555555555,
"repo_name": "akiellor/selenium",
"id": "b1caddfb67cdfb9f1fec74dee1782a2c59dee095",
"size": "4206",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "cpp/IEDriver/CommandHandlers/MouseMoveToCommandHandler.h",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "ASP",
"bytes": "22777"
},
{
"name": "C",
"bytes": "13787069"
},
{
"name": "C#",
"bytes": "1592944"
},
{
"name": "C++",
"bytes": "39839762"
},
{
"name": "Java",
"bytes": "5948691"
},
{
"name": "JavaScript",
"bytes": "15038006"
},
{
"name": "Objective-C",
"bytes": "331601"
},
{
"name": "Python",
"bytes": "544265"
},
{
"name": "Ruby",
"bytes": "557579"
},
{
"name": "Shell",
"bytes": "21701"
}
],
"symlink_target": ""
} |
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "https://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=9"/>
<meta name="generator" content="Doxygen 1.8.18"/>
<meta name="viewport" content="width=device-width, initial-scale=1"/>
<title>OmEspHelpers: HtmlItem Class Reference</title>
<link href="tabs.css" rel="stylesheet" type="text/css"/>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript" src="dynsections.js"></script>
<link href="search/search.css" rel="stylesheet" type="text/css"/>
<script type="text/javascript" src="search/searchdata.js"></script>
<script type="text/javascript" src="search/search.js"></script>
<link href="doxygen.css" rel="stylesheet" type="text/css" />
</head>
<body>
<div id="top"><!-- do not remove this div, it is closed by doxygen! -->
<div id="titlearea">
<table cellspacing="0" cellpadding="0">
<tbody>
<tr style="height: 56px;">
<td id="projectalign" style="padding-left: 0.5em;">
<div id="projectname">OmEspHelpers
</div>
</td>
</tr>
</tbody>
</table>
</div>
<!-- end header part -->
<!-- Generated by Doxygen 1.8.18 -->
<script type="text/javascript">
/* @license magnet:?xt=urn:btih:cf05388f2679ee054f2beb29a391d25f4e673ac3&dn=gpl-2.0.txt GPL-v2 */
var searchBox = new SearchBox("searchBox", "search",false,'Search');
/* @license-end */
</script>
<script type="text/javascript" src="menudata.js"></script>
<script type="text/javascript" src="menu.js"></script>
<script type="text/javascript">
/* @license magnet:?xt=urn:btih:cf05388f2679ee054f2beb29a391d25f4e673ac3&dn=gpl-2.0.txt GPL-v2 */
$(function() {
initMenu('',true,false,'search.php','Search');
$(document).ready(function() { init_search(); });
});
/* @license-end */</script>
<div id="main-nav"></div>
<!-- window showing the filter options -->
<div id="MSearchSelectWindow"
onmouseover="return searchBox.OnSearchSelectShow()"
onmouseout="return searchBox.OnSearchSelectHide()"
onkeydown="return searchBox.OnSearchSelectKey(event)">
</div>
<!-- iframe showing the search results (closed by default) -->
<div id="MSearchResultsWindow">
<iframe src="javascript:void(0)" frameborder="0"
name="MSearchResults" id="MSearchResults">
</iframe>
</div>
</div><!-- top -->
<div class="header">
<div class="summary">
<a href="#pub-methods">Public Member Functions</a> |
<a href="#pub-attribs">Public Attributes</a> |
<a href="class_html_item-members.html">List of all members</a> </div>
<div class="headertitle">
<div class="title">HtmlItem Class Reference</div> </div>
</div><!--header-->
<div class="contents">
<p>Call the HtmlProc to render balanced HTML.
<a href="class_html_item.html#details">More...</a></p>
<div class="dynheader">
Inheritance diagram for HtmlItem:</div>
<div class="dyncontent">
<div class="center">
<img src="class_html_item.png" usemap="#HtmlItem_map" alt=""/>
<map id="HtmlItem_map" name="HtmlItem_map">
<area href="class_page_item.html" alt="PageItem" shape="rect" coords="0,0,63,24"/>
</map>
</div></div>
<table class="memberdecls">
<tr class="heading"><td colspan="2"><h2 class="groupheader"><a name="pub-methods"></a>
Public Member Functions</h2></td></tr>
<tr class="memitem:a7b6c6f7c4766f3e61fd0ff0335513ff2"><td class="memItemLeft" align="right" valign="top"><a id="a7b6c6f7c4766f3e61fd0ff0335513ff2"></a>
void </td><td class="memItemRight" valign="bottom"><b>render</b> (<a class="el" href="class_om_xml_writer.html">OmXmlWriter</a> &w, <a class="el" href="class_page.html">Page</a> *inPage) override</td></tr>
<tr class="separator:a7b6c6f7c4766f3e61fd0ff0335513ff2"><td class="memSeparator" colspan="2"> </td></tr>
<tr class="memitem:ad0c138f45f15f6007e07f8c801f3055f"><td class="memItemLeft" align="right" valign="top"><a id="ad0c138f45f15f6007e07f8c801f3055f"></a>
bool </td><td class="memItemRight" valign="bottom"><b>doAction</b> (<a class="el" href="class_page.html">Page</a> *fromPage) override</td></tr>
<tr class="separator:ad0c138f45f15f6007e07f8c801f3055f"><td class="memSeparator" colspan="2"> </td></tr>
<tr class="memitem:ae3d837c28f5cb175a81ad4e95c1bf1c0"><td class="memItemLeft" align="right" valign="top"><a id="ae3d837c28f5cb175a81ad4e95c1bf1c0"></a>
void </td><td class="memItemRight" valign="bottom"><b>renderStatusey</b> (<a class="el" href="class_om_xml_writer.html">OmXmlWriter</a> &w) override</td></tr>
<tr class="separator:ae3d837c28f5cb175a81ad4e95c1bf1c0"><td class="memSeparator" colspan="2"> </td></tr>
<tr class="inherit_header pub_methods_class_page_item"><td colspan="2" onclick="javascript:toggleInherit('pub_methods_class_page_item')"><img src="closed.png" alt="-"/> Public Member Functions inherited from <a class="el" href="class_page_item.html">PageItem</a></td></tr>
<tr class="memitem:a135efef3cb1afb2dfdc215da1c00a1f3 inherit pub_methods_class_page_item"><td class="memItemLeft" align="right" valign="top"><a id="a135efef3cb1afb2dfdc215da1c00a1f3"></a>
void </td><td class="memItemRight" valign="bottom"><b>setValue</b> (int value)</td></tr>
<tr class="separator:a135efef3cb1afb2dfdc215da1c00a1f3 inherit pub_methods_class_page_item"><td class="memSeparator" colspan="2"> </td></tr>
</table><table class="memberdecls">
<tr class="heading"><td colspan="2"><h2 class="groupheader"><a name="pub-attribs"></a>
Public Attributes</h2></td></tr>
<tr class="memitem:a2f284130527105080c593e252b7aca20"><td class="memItemLeft" align="right" valign="top"><a id="a2f284130527105080c593e252b7aca20"></a>
HtmlProc </td><td class="memItemRight" valign="bottom"><b>proc</b></td></tr>
<tr class="separator:a2f284130527105080c593e252b7aca20"><td class="memSeparator" colspan="2"> </td></tr>
<tr class="inherit_header pub_attribs_class_page_item"><td colspan="2" onclick="javascript:toggleInherit('pub_attribs_class_page_item')"><img src="closed.png" alt="-"/> Public Attributes inherited from <a class="el" href="class_page_item.html">PageItem</a></td></tr>
<tr class="memitem:aeefc33d9e29e960bad7b9bbd4942cd09 inherit pub_attribs_class_page_item"><td class="memItemLeft" align="right" valign="top"><a id="aeefc33d9e29e960bad7b9bbd4942cd09"></a>
const char * </td><td class="memItemRight" valign="bottom"><b>name</b> = ""</td></tr>
<tr class="separator:aeefc33d9e29e960bad7b9bbd4942cd09 inherit pub_attribs_class_page_item"><td class="memSeparator" colspan="2"> </td></tr>
<tr class="memitem:aab29c7f8f13cc98e5074632247b5a813 inherit pub_attribs_class_page_item"><td class="memItemLeft" align="right" valign="top"><a id="aab29c7f8f13cc98e5074632247b5a813"></a>
char </td><td class="memItemRight" valign="bottom"><b>id</b> [6]</td></tr>
<tr class="separator:aab29c7f8f13cc98e5074632247b5a813 inherit pub_attribs_class_page_item"><td class="memSeparator" colspan="2"> </td></tr>
<tr class="memitem:abb6d2980c04aa2ce699d191d0fbb849f inherit pub_attribs_class_page_item"><td class="memItemLeft" align="right" valign="top"><a id="abb6d2980c04aa2ce699d191d0fbb849f"></a>
const char * </td><td class="memItemRight" valign="bottom"><b>pageLink</b> = ""</td></tr>
<tr class="separator:abb6d2980c04aa2ce699d191d0fbb849f inherit pub_attribs_class_page_item"><td class="memSeparator" colspan="2"> </td></tr>
<tr class="memitem:a729a4e7d40c034c52919a0e5ba095488 inherit pub_attribs_class_page_item"><td class="memItemLeft" align="right" valign="top"><a id="a729a4e7d40c034c52919a0e5ba095488"></a>
int </td><td class="memItemRight" valign="bottom"><b>ref1</b> = 0</td></tr>
<tr class="separator:a729a4e7d40c034c52919a0e5ba095488 inherit pub_attribs_class_page_item"><td class="memSeparator" colspan="2"> </td></tr>
<tr class="memitem:aa92c13a041b28f1b862371db48865983 inherit pub_attribs_class_page_item"><td class="memItemLeft" align="right" valign="top"><a id="aa92c13a041b28f1b862371db48865983"></a>
void * </td><td class="memItemRight" valign="bottom"><b>ref2</b> = 0</td></tr>
<tr class="separator:aa92c13a041b28f1b862371db48865983 inherit pub_attribs_class_page_item"><td class="memSeparator" colspan="2"> </td></tr>
<tr class="memitem:aa19c25221ea95a31fa95e90d4a5b9614 inherit pub_attribs_class_page_item"><td class="memItemLeft" align="right" valign="top"><a id="aa19c25221ea95a31fa95e90d4a5b9614"></a>
int </td><td class="memItemRight" valign="bottom"><b>value</b> = 0</td></tr>
<tr class="separator:aa19c25221ea95a31fa95e90d4a5b9614 inherit pub_attribs_class_page_item"><td class="memSeparator" colspan="2"> </td></tr>
<tr class="memitem:a12e0831d4f15f09d1778121b1ac1a742 inherit pub_attribs_class_page_item"><td class="memItemLeft" align="right" valign="top"><a id="a12e0831d4f15f09d1778121b1ac1a742"></a>
bool </td><td class="memItemRight" valign="bottom"><b>visible</b> = true</td></tr>
<tr class="separator:a12e0831d4f15f09d1778121b1ac1a742 inherit pub_attribs_class_page_item"><td class="memSeparator" colspan="2"> </td></tr>
<tr class="memitem:a52238e3359e54018a645683b149eebdd inherit pub_attribs_class_page_item"><td class="memItemLeft" align="right" valign="top"><a id="a52238e3359e54018a645683b149eebdd"></a>
<a class="el" href="class_om_web_page_item.html">OmWebPageItem</a> </td><td class="memItemRight" valign="bottom"><b>item</b></td></tr>
<tr class="separator:a52238e3359e54018a645683b149eebdd inherit pub_attribs_class_page_item"><td class="memSeparator" colspan="2"> </td></tr>
</table>
<a name="details" id="details"></a><h2 class="groupheader">Detailed Description</h2>
<div class="textblock"><p>Call the HtmlProc to render balanced HTML. </p>
</div><hr/>The documentation for this class was generated from the following file:<ul>
<li>src/OmWebPages.cpp</li>
</ul>
</div><!-- contents -->
<!-- start footer part -->
<hr class="footer"/><address class="footer"><small>
Generated by  <a href="http://www.doxygen.org/index.html">
<img class="footer" src="doxygen.png" alt="doxygen"/>
</a> 1.8.18
</small></address>
</body>
</html>
| {
"content_hash": "77fbe164c8a5777495ea4be9f95d552f",
"timestamp": "",
"source": "github",
"line_count": 145,
"max_line_length": 277,
"avg_line_length": 70.08275862068966,
"alnum_prop": 0.7244636882503445,
"repo_name": "distrakt/OmEspHelpers",
"id": "492269b0e4fc74695f4a66388be20612dc0219e6",
"size": "10162",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "docs/class_html_item.html",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C",
"bytes": "1693"
},
{
"name": "C++",
"bytes": "209717"
},
{
"name": "Makefile",
"bytes": "544"
},
{
"name": "Objective-C",
"bytes": "6441"
},
{
"name": "PostScript",
"bytes": "69463"
},
{
"name": "TeX",
"bytes": "290750"
}
],
"symlink_target": ""
} |
package cf_command_test
import (
"testing"
. "github.com/onsi/ginkgo"
. "github.com/onsi/gomega"
)
func TestCfCommand(t *testing.T) {
RegisterFailHandler(Fail)
RunSpecs(t, "CfCommand Suite")
}
| {
"content_hash": "6174e9ea30081ff1dce9da761038b1ab",
"timestamp": "",
"source": "github",
"line_count": 13,
"max_line_length": 34,
"avg_line_length": 15.461538461538462,
"alnum_prop": 0.7114427860696517,
"repo_name": "cloudfoundry-incubator/cf-networking-release",
"id": "15d04fefaa61f6422a42a4fe8866e4f1280c086d",
"size": "201",
"binary": false,
"copies": "1",
"ref": "refs/heads/develop",
"path": "src/code.cloudfoundry.org/cf-pusher/cf_command/cf_command_suite_test.go",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Go",
"bytes": "1160603"
},
{
"name": "HTML",
"bytes": "17265"
},
{
"name": "Java",
"bytes": "4327"
},
{
"name": "Shell",
"bytes": "38500"
}
],
"symlink_target": ""
} |
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta charset="utf-8" />
<title>statsmodels.duration.hazard_regression.PHReg.efron_hessian — statsmodels v0.10.1 documentation</title>
<link rel="stylesheet" href="../_static/nature.css" type="text/css" />
<link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
<link rel="stylesheet" type="text/css" href="../_static/graphviz.css" />
<script type="text/javascript" id="documentation_options" data-url_root="../" src="../_static/documentation_options.js"></script>
<script type="text/javascript" src="../_static/jquery.js"></script>
<script type="text/javascript" src="../_static/underscore.js"></script>
<script type="text/javascript" src="../_static/doctools.js"></script>
<script type="text/javascript" src="../_static/language_data.js"></script>
<script async="async" type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/mathjax/2.7.5/latest.js?config=TeX-AMS-MML_HTMLorMML"></script>
<link rel="shortcut icon" href="../_static/statsmodels_hybi_favico.ico"/>
<link rel="author" title="About these documents" href="../about.html" />
<link rel="index" title="Index" href="../genindex.html" />
<link rel="search" title="Search" href="../search.html" />
<link rel="next" title="statsmodels.duration.hazard_regression.PHReg.efron_loglike" href="statsmodels.duration.hazard_regression.PHReg.efron_loglike.html" />
<link rel="prev" title="statsmodels.duration.hazard_regression.PHReg.efron_gradient" href="statsmodels.duration.hazard_regression.PHReg.efron_gradient.html" />
<link rel="stylesheet" href="../_static/examples.css" type="text/css" />
<link rel="stylesheet" href="../_static/facebox.css" type="text/css" />
<script type="text/javascript" src="../_static/scripts.js">
</script>
<script type="text/javascript" src="../_static/facebox.js">
</script>
<script type="text/javascript">
$.facebox.settings.closeImage = "../_static/closelabel.png"
$.facebox.settings.loadingImage = "../_static/loading.gif"
</script>
<script>
$(document).ready(function() {
$.getJSON("../../versions.json", function(versions) {
var dropdown = document.createElement("div");
dropdown.className = "dropdown";
var button = document.createElement("button");
button.className = "dropbtn";
button.innerHTML = "Other Versions";
var content = document.createElement("div");
content.className = "dropdown-content";
dropdown.appendChild(button);
dropdown.appendChild(content);
$(".header").prepend(dropdown);
for (var i = 0; i < versions.length; i++) {
if (versions[i].substring(0, 1) == "v") {
versions[i] = [versions[i], versions[i].substring(1)];
} else {
versions[i] = [versions[i], versions[i]];
};
};
for (var i = 0; i < versions.length; i++) {
var a = document.createElement("a");
a.innerHTML = versions[i][1];
a.href = "../../" + versions[i][0] + "/index.html";
a.title = versions[i][1];
$(".dropdown-content").append(a);
};
});
});
</script>
</head><body>
<div class="headerwrap">
<div class = "header">
<a href = "../index.html">
<img src="../_static/statsmodels_hybi_banner.png" alt="Logo"
style="padding-left: 15px"/></a>
</div>
</div>
<div class="related" role="navigation" aria-label="related navigation">
<h3>Navigation</h3>
<ul>
<li class="right" style="margin-right: 10px">
<a href="../genindex.html" title="General Index"
accesskey="I">index</a></li>
<li class="right" >
<a href="../py-modindex.html" title="Python Module Index"
>modules</a> |</li>
<li class="right" >
<a href="statsmodels.duration.hazard_regression.PHReg.efron_loglike.html" title="statsmodels.duration.hazard_regression.PHReg.efron_loglike"
accesskey="N">next</a> |</li>
<li class="right" >
<a href="statsmodels.duration.hazard_regression.PHReg.efron_gradient.html" title="statsmodels.duration.hazard_regression.PHReg.efron_gradient"
accesskey="P">previous</a> |</li>
<li><a href ="../install.html">Install</a></li> |
<li><a href="https://groups.google.com/forum/?hl=en#!forum/pystatsmodels">Support</a></li> |
<li><a href="https://github.com/statsmodels/statsmodels/issues">Bugs</a></li> |
<li><a href="../dev/index.html">Develop</a></li> |
<li><a href="../examples/index.html">Examples</a></li> |
<li><a href="../faq.html">FAQ</a></li> |
<li class="nav-item nav-item-1"><a href="../duration.html" >Methods for Survival and Duration Analysis</a> |</li>
<li class="nav-item nav-item-2"><a href="statsmodels.duration.hazard_regression.PHReg.html" accesskey="U">statsmodels.duration.hazard_regression.PHReg</a> |</li>
</ul>
</div>
<div class="document">
<div class="documentwrapper">
<div class="bodywrapper">
<div class="body" role="main">
<div class="section" id="statsmodels-duration-hazard-regression-phreg-efron-hessian">
<h1>statsmodels.duration.hazard_regression.PHReg.efron_hessian<a class="headerlink" href="#statsmodels-duration-hazard-regression-phreg-efron-hessian" title="Permalink to this headline">¶</a></h1>
<p>method</p>
<dl class="method">
<dt id="statsmodels.duration.hazard_regression.PHReg.efron_hessian">
<code class="sig-prename descclassname">PHReg.</code><code class="sig-name descname">efron_hessian</code><span class="sig-paren">(</span><em class="sig-param">params</em><span class="sig-paren">)</span><a class="reference internal" href="../_modules/statsmodels/duration/hazard_regression.html#PHReg.efron_hessian"><span class="viewcode-link">[source]</span></a><a class="headerlink" href="#statsmodels.duration.hazard_regression.PHReg.efron_hessian" title="Permalink to this definition">¶</a></dt>
<dd><p>Returns the Hessian matrix of the partial log-likelihood
evaluated at <cite>params</cite>, using the Efron method to handle tied
times.</p>
</dd></dl>
</div>
</div>
</div>
</div>
<div class="sphinxsidebar" role="navigation" aria-label="main navigation">
<div class="sphinxsidebarwrapper">
<h4>Previous topic</h4>
<p class="topless"><a href="statsmodels.duration.hazard_regression.PHReg.efron_gradient.html"
title="previous chapter">statsmodels.duration.hazard_regression.PHReg.efron_gradient</a></p>
<h4>Next topic</h4>
<p class="topless"><a href="statsmodels.duration.hazard_regression.PHReg.efron_loglike.html"
title="next chapter">statsmodels.duration.hazard_regression.PHReg.efron_loglike</a></p>
<div role="note" aria-label="source link">
<h3>This Page</h3>
<ul class="this-page-menu">
<li><a href="../_sources/generated/statsmodels.duration.hazard_regression.PHReg.efron_hessian.rst.txt"
rel="nofollow">Show Source</a></li>
</ul>
</div>
<div id="searchbox" style="display: none" role="search">
<h3 id="searchlabel">Quick search</h3>
<div class="searchformwrapper">
<form class="search" action="../search.html" method="get">
<input type="text" name="q" aria-labelledby="searchlabel" />
<input type="submit" value="Go" />
</form>
</div>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
</div>
</div>
<div class="clearer"></div>
</div>
<div class="footer" role="contentinfo">
© Copyright 2009-2018, Josef Perktold, Skipper Seabold, Jonathan Taylor, statsmodels-developers.
Created using <a href="http://sphinx-doc.org/">Sphinx</a> 2.1.2.
</div>
</body>
</html> | {
"content_hash": "0e4e2cf64b248792efe6fc221b7ec679",
"timestamp": "",
"source": "github",
"line_count": 166,
"max_line_length": 498,
"avg_line_length": 47.18674698795181,
"alnum_prop": 0.6501978807608835,
"repo_name": "statsmodels/statsmodels.github.io",
"id": "ac086f17fdee53db41889272ac5c5cb307d0ef0f",
"size": "7837",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "v0.10.1/generated/statsmodels.duration.hazard_regression.PHReg.efron_hessian.html",
"mode": "33188",
"license": "bsd-3-clause",
"language": [],
"symlink_target": ""
} |
package sculture.models.response;
import sculture.dao.TagStoryDao;
import sculture.dao.UserDao;
import sculture.dao.VoteStoryDao;
import sculture.models.tables.Story;
import sculture.models.tables.User;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
public class StoryResponse {
private class User {
private long id;
private String username;
public long getId() {
return id;
}
public String getUsername() {
return username;
}
}
private long id;
private String title;
private Date creation_date;
private Date update_date;
private User last_editor = new User();
private User owner = new User();
private List<String> tags;
private long positive_vote;
private long negative_vote;
private long report_count;
private String content;
private List<String> media;
private int vote;
public StoryResponse(Story story, sculture.models.tables.User current_user, TagStoryDao tagStoryDao, UserDao userDao, VoteStoryDao voteStoryDao) {
this.id = story.getStory_id();
this.title = story.getTitle();
this.creation_date = story.getCreate_date();
this.update_date = story.getLast_edit_date();
this.last_editor.id = story.getLast_editor_id();
this.owner.id = story.getOwner_id();
this.positive_vote = story.getPositive_vote();
this.negative_vote = story.getNegative_vote();
this.report_count = story.getReport_count();
this.tags = tagStoryDao.getTagTitlesByStoryId(this.id);
this.owner.username = userDao.getById(story.getOwner_id()).getUsername();
this.last_editor.username = userDao.getById(story.getLast_editor_id()).getUsername();
this.content = story.getContent();
this.media = story.getMediaList();
if (current_user == null)
vote = 0;
else {
vote = voteStoryDao.get(current_user.getUser_id(), story.getStory_id()).getVote();
}
}
public long getId() {
return id;
}
public String getTitle() {
return title;
}
public Date getCreation_date() {
return creation_date;
}
public Date getUpdate_date() {
return update_date;
}
public User getLast_editor() {
return last_editor;
}
public User getOwner() {
return owner;
}
public List<String> getTags() {
return tags;
}
public long getPositive_vote() {
return positive_vote;
}
public long getNegative_vote() {
return negative_vote;
}
public long getReport_count() {
return report_count;
}
public void setId(long id) {
this.id = id;
}
public void setTitle(String title) {
this.title = title;
}
public void setCreation_date(Date creation_date) {
this.creation_date = creation_date;
}
public void setUpdate_date(Date update_date) {
this.update_date = update_date;
}
public void setLast_editor(User last_editor) {
this.last_editor = last_editor;
}
public void setOwner(User owner) {
this.owner = owner;
}
public void setTags(List<String> tags) {
this.tags = tags;
}
public void setPositive_vote(long positive_vote) {
this.positive_vote = positive_vote;
}
public void setNegative_vote(long negative_vote) {
this.negative_vote = negative_vote;
}
public void setReport_count(long report_count) {
this.report_count = report_count;
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
public List<String> getMedia() {
return media;
}
public void setMedia(List<String> media) {
this.media = media;
}
public int getVote() {
return vote;
}
public void setVote(int vote) {
this.vote = vote;
}
}
| {
"content_hash": "7dd4270ebfc6deefed0ce489cef1daa9",
"timestamp": "",
"source": "github",
"line_count": 171,
"max_line_length": 150,
"avg_line_length": 23.818713450292396,
"alnum_prop": 0.6164988951632703,
"repo_name": "bounswe/bounswe2015group7",
"id": "2d0f8dd0d7ec1cf881b87fd1af1955cae3ba9d67",
"size": "4073",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "sculture-rest/src/main/java/sculture/models/response/StoryResponse.java",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "37403"
},
{
"name": "Java",
"bytes": "476629"
},
{
"name": "JavaScript",
"bytes": "160226"
},
{
"name": "Makefile",
"bytes": "9338"
},
{
"name": "Perl",
"bytes": "7494480"
},
{
"name": "Shell",
"bytes": "112"
}
],
"symlink_target": ""
} |
Applying on-demand learning strategies for self-paced "learning in the wild" can augment professional learning from massively open online courses (MOOC) such as EdX, Udacity, and videos available from YouTube and other sources.
### Using Resources and Technology to Optimize Your Productivity
A forthcoming article will explain key points of self-directed online learning, including how to develop a transmedia learning framework (TLF) leveraging massively open online courses (MOOC), podcasts, social media, videos, practice environments, and more. The article is based on material presented in a tutorial at the [2nd Annual ECP Annual Meeting](https://www.ecpannualmeeting.com). The tutorial featured a walk-through of relevant learning applications organized in a transmedia learning framework (TLF). Take-away practical strategies, resources, and tools that can be applied toward learning more productively were provided.
**Subresources:**
- [TLF Example: Git](CuratedContent/OnlineLearningTLF.Git.md)
- [TLF Example: Python2](CuratedContent/OnlineLearningTLF.Python.md)
#### Contributed by [Elaine Raybourn](https://github.com/elaineraybourn "Elaine Raybourn")
#### Publication date: February 3, 2018
<!---
Publish: yes
Categories: development
Topics: [import from subresources]
Tags: [import from subresources]
Level: 2
Prerequisites: [import from subresources]
Aggregate: base
--->
| {
"content_hash": "fbc67abd77627475ba26ca7b2dc8a0f4",
"timestamp": "",
"source": "github",
"line_count": 23,
"max_line_length": 633,
"avg_line_length": 60.73913043478261,
"alnum_prop": 0.7967072297780959,
"repo_name": "william76/betterscientificsoftware.github.io",
"id": "0f9a3f6ea04ceefb13aad10e11c3ed680f76cfdb",
"size": "1450",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "CuratedContent/OnDemandLearningForBetterScientificSoftware.md",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Python",
"bytes": "5104"
}
],
"symlink_target": ""
} |
package org.apache.dubbo.rpc.protocol.hessian;
import org.apache.dubbo.common.Constants;
import org.apache.dubbo.rpc.RpcContext;
import com.caucho.hessian.client.HessianConnection;
import com.caucho.hessian.client.HessianURLConnectionFactory;
import java.io.IOException;
import java.net.URL;
public class DubboHessianURLConnectionFactory extends HessianURLConnectionFactory {
@Override
public HessianConnection open(URL url) throws IOException {
HessianConnection connection = super.open(url);
RpcContext context = RpcContext.getContext();
for (String key : context.getAttachments().keySet()) {
connection.addHeader(Constants.DEFAULT_EXCHANGER + key, context.getAttachment(key));
}
return connection;
}
}
| {
"content_hash": "9bf08d1f42b1a52a29ff167c26c822aa",
"timestamp": "",
"source": "github",
"line_count": 26,
"max_line_length": 96,
"avg_line_length": 29.884615384615383,
"alnum_prop": 0.749034749034749,
"repo_name": "alibaba/dubbo",
"id": "21c566fe0fbd322c18b90e85e638e3837977af2b",
"size": "1578",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "dubbo-rpc/dubbo-rpc-hessian/src/main/java/org/apache/dubbo/rpc/protocol/hessian/DubboHessianURLConnectionFactory.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Batchfile",
"bytes": "1024"
},
{
"name": "Java",
"bytes": "5691835"
},
{
"name": "Lex",
"bytes": "4154"
},
{
"name": "Shell",
"bytes": "7242"
},
{
"name": "Thrift",
"bytes": "668"
}
],
"symlink_target": ""
} |
const webpack = require('webpack');
let config = require('./webpack.config.es6.js');
config.plugins = config.plugins || [];
config.plugins.push(new webpack.optimize.UglifyJsPlugin());
module.exports = config;
| {
"content_hash": "2711b379768fbf6cd52afc062cd6380f",
"timestamp": "",
"source": "github",
"line_count": 6,
"max_line_length": 59,
"avg_line_length": 35,
"alnum_prop": 0.7333333333333333,
"repo_name": "mdittmer/web-apis",
"id": "10b987ab2fff754dc1d1e780c6e6cd3b9ff4aaba",
"size": "210",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "config/webpack.prod.config.es6.js",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "HTML",
"bytes": "9540"
},
{
"name": "JavaScript",
"bytes": "217761"
},
{
"name": "Shell",
"bytes": "6101"
}
],
"symlink_target": ""
} |
<?php
/* @WebProfiler/Profiler/base_js.html.twig */
class __TwigTemplate_3efd1bacc3519295227295bf49d30d640097945474b88d764074b0e746bb9987 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 "<script>/*<![CDATA[*/
Sfjs = (function() {
\"use strict\";
var noop = function() {},
profilerStorageKey = 'sf2/profiler/',
request = function(url, onSuccess, onError, payload, options) {
var xhr = window.XMLHttpRequest ? new XMLHttpRequest() : new ActiveXObject('Microsoft.XMLHTTP');
options = options || {};
options.maxTries = options.maxTries || 0;
xhr.open(options.method || 'GET', url, true);
xhr.setRequestHeader('X-Requested-With', 'XMLHttpRequest');
xhr.onreadystatechange = function(state) {
if (4 !== xhr.readyState) {
return null;
}
if (xhr.status == 404 && options.maxTries > 1) {
setTimeout(function(){
options.maxTries--;
request(url, onSuccess, onError, payload, options);
}, 500);
return null;
}
if (200 === xhr.status) {
(onSuccess || noop)(xhr);
} else {
(onError || noop)(xhr);
}
};
xhr.send(payload || '');
},
hasClass = function(el, klass) {
return el.className.match(new RegExp('\\\\b' + klass + '\\\\b'));
},
removeClass = function(el, klass) {
el.className = el.className.replace(new RegExp('\\\\b' + klass + '\\\\b'), ' ');
},
addClass = function(el, klass) {
if (!hasClass(el, klass)) { el.className += \" \" + klass; }
},
getPreference = function(name) {
if (!window.localStorage) {
return null;
}
return localStorage.getItem(profilerStorageKey + name);
},
setPreference = function(name, value) {
if (!window.localStorage) {
return null;
}
localStorage.setItem(profilerStorageKey + name, value);
};
return {
hasClass: hasClass,
removeClass: removeClass,
addClass: addClass,
getPreference: getPreference,
setPreference: setPreference,
request: request,
load: function(selector, url, onSuccess, onError, options) {
var el = document.getElementById(selector);
if (el && el.getAttribute('data-sfurl') !== url) {
request(
url,
function(xhr) {
el.innerHTML = xhr.responseText;
el.setAttribute('data-sfurl', url);
removeClass(el, 'loading');
(onSuccess || noop)(xhr, el);
},
function(xhr) { (onError || noop)(xhr, el); },
'',
options
);
}
return this;
},
toggle: function(selector, elOn, elOff) {
var tmp = elOn.style.display,
el = document.getElementById(selector);
elOn.style.display = elOff.style.display;
elOff.style.display = tmp;
if (el) {
el.style.display = 'none' === tmp ? 'none' : 'block';
}
return this;
}
}
})();
/*]]>*/</script>
";
}
public function getTemplateName()
{
return "@WebProfiler/Profiler/base_js.html.twig";
}
public function getDebugInfo()
{
return array ( 19 => 1,);
}
/** @deprecated since 1.27 (to be removed in 2.0). Use getSourceContext() instead */
public function getSource()
{
@trigger_error('The '.__METHOD__.' method is deprecated since version 1.27 and will be removed in 2.0. Use getSourceContext() instead.', E_USER_DEPRECATED);
return $this->getSourceContext()->getCode();
}
public function getSourceContext()
{
return new Twig_Source("<script>/*<![CDATA[*/
Sfjs = (function() {
\"use strict\";
var noop = function() {},
profilerStorageKey = 'sf2/profiler/',
request = function(url, onSuccess, onError, payload, options) {
var xhr = window.XMLHttpRequest ? new XMLHttpRequest() : new ActiveXObject('Microsoft.XMLHTTP');
options = options || {};
options.maxTries = options.maxTries || 0;
xhr.open(options.method || 'GET', url, true);
xhr.setRequestHeader('X-Requested-With', 'XMLHttpRequest');
xhr.onreadystatechange = function(state) {
if (4 !== xhr.readyState) {
return null;
}
if (xhr.status == 404 && options.maxTries > 1) {
setTimeout(function(){
options.maxTries--;
request(url, onSuccess, onError, payload, options);
}, 500);
return null;
}
if (200 === xhr.status) {
(onSuccess || noop)(xhr);
} else {
(onError || noop)(xhr);
}
};
xhr.send(payload || '');
},
hasClass = function(el, klass) {
return el.className.match(new RegExp('\\\\b' + klass + '\\\\b'));
},
removeClass = function(el, klass) {
el.className = el.className.replace(new RegExp('\\\\b' + klass + '\\\\b'), ' ');
},
addClass = function(el, klass) {
if (!hasClass(el, klass)) { el.className += \" \" + klass; }
},
getPreference = function(name) {
if (!window.localStorage) {
return null;
}
return localStorage.getItem(profilerStorageKey + name);
},
setPreference = function(name, value) {
if (!window.localStorage) {
return null;
}
localStorage.setItem(profilerStorageKey + name, value);
};
return {
hasClass: hasClass,
removeClass: removeClass,
addClass: addClass,
getPreference: getPreference,
setPreference: setPreference,
request: request,
load: function(selector, url, onSuccess, onError, options) {
var el = document.getElementById(selector);
if (el && el.getAttribute('data-sfurl') !== url) {
request(
url,
function(xhr) {
el.innerHTML = xhr.responseText;
el.setAttribute('data-sfurl', url);
removeClass(el, 'loading');
(onSuccess || noop)(xhr, el);
},
function(xhr) { (onError || noop)(xhr, el); },
'',
options
);
}
return this;
},
toggle: function(selector, elOn, elOff) {
var tmp = elOn.style.display,
el = document.getElementById(selector);
elOn.style.display = elOff.style.display;
elOff.style.display = tmp;
if (el) {
el.style.display = 'none' === tmp ? 'none' : 'block';
}
return this;
}
}
})();
/*]]>*/</script>
", "@WebProfiler/Profiler/base_js.html.twig", "C:\\xampp\\htdocs\\Prueba\\vendor\\symfony\\symfony\\src\\Symfony\\Bundle\\WebProfilerBundle\\Resources\\views\\Profiler\\base_js.html.twig");
}
}
| {
"content_hash": "847e22f251bac463c5905eeb2f0237ae",
"timestamp": "",
"source": "github",
"line_count": 274,
"max_line_length": 189,
"avg_line_length": 32.06204379562044,
"alnum_prop": 0.44223107569721115,
"repo_name": "CarmeloRP93/Prueba",
"id": "07e8929de263d0c792315a7c336184f185496a4c",
"size": "8785",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "app/cache/dev/twig/9c/9c91ebf80b31b820381ba53ea38fc4cc5622fe4c703a116fc1f7efabfac6c298.php",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "ApacheConf",
"bytes": "3297"
},
{
"name": "Batchfile",
"bytes": "256"
},
{
"name": "CSS",
"bytes": "195466"
},
{
"name": "HTML",
"bytes": "573486"
},
{
"name": "JavaScript",
"bytes": "6869"
},
{
"name": "PHP",
"bytes": "825036"
},
{
"name": "Shell",
"bytes": "1228"
}
],
"symlink_target": ""
} |
---
title: Dynamic Throw Type Extensions
---
To support [precise try-catch-finally analysis](/blog/precise-try-catch-finally-analysis), you can write a dynamic throw type extension to describe functions and methods that might throw an exception only when specific types of arguments are passed during a call.
The implementation is all about applying the [core concepts](/developing-extensions/core-concepts) so check out that guide first and then continue here.
Because you have to write the code with the type-resolving logic, it can be as complex as you want.
This is [the interface](https://apiref.phpstan.org/1.9.x/PHPStan.Type.DynamicMethodThrowTypeExtension.html) for dynamic throw type extension:
```php
namespace PHPStan\Type;
use PhpParser\Node\Expr\MethodCall;
use PHPStan\Analyser\Scope;
use PHPStan\Reflection\MethodReflection;
interface DynamicMethodThrowTypeExtension
{
public function isMethodSupported(MethodReflection $methodReflection): bool;
public function getThrowTypeFromMethodCall(
MethodReflection $methodReflection,
MethodCall $methodCall,
Scope $scope
): ?Type;
}
```
An example
----------------
Let's say you have a method with an implementation that looks like this:
```php
/** @throws ComponentNotFoundException */
public function getComponent(string $name, bool $throw): ?Component
{
if (!array_key_exists($name, $this->components)) {
if ($throw) {
throw new ComponentNotFoundException($name);
}
return null;
}
return $this->components[$name];
}
```
This is how you'd write the extension that tells PHPStan the exception can be thrown only when `$throw` is `true`:
```php
public function isMethodSupported(MethodReflection $methodReflection): bool
{
return $methodReflection->getDeclaringClass()->getName() === ComponentContainer::class
&& $methodReflection->getName() === 'getComponent';
}
public function getThrowTypeFromMethodCall(
MethodReflection $methodReflection,
MethodCall $methodCall,
Scope $scope
): ?Type
{
if (count($methodCall->getArgs()) < 2) {
return $methodReflection->getThrowType();
}
$argType = $scope->getType($methodCall->getArgs()[1]->value);
if ((new ConstantBooleanType(true))->isSuperTypeOf($argType)->yes()) {
return $methodReflection->getThrowType();
}
return null;
}
```
And finally, register the extension in the [configuration file](/config-reference):
```yaml
services:
-
class: App\PHPStan\GetComponentThrowTypeExtension
tags:
- phpstan.dynamicMethodThrowTypeExtension
```
There's also analogous functionality for:
* **static methods** using [`DynamicStaticMethodThrowTypeExtension`](https://apiref.phpstan.org/1.9.x/PHPStan.Type.DynamicStaticMethodThrowTypeExtension.html) interface and `phpstan.dynamicStaticMethodThrowTypeExtension` service tag.
* **functions** using [`DynamicFunctionThrowTypeExtension`](https://apiref.phpstan.org/1.9.x/PHPStan.Type.DynamicFunctionThrowTypeExtension.html) interface and `phpstan.dynamicFunctionThrowTypeExtension` service tag.
| {
"content_hash": "2abc3e2469a8ef1fd9972fd6d4ab856c",
"timestamp": "",
"source": "github",
"line_count": 96,
"max_line_length": 263,
"avg_line_length": 31.229166666666668,
"alnum_prop": 0.7681787858572382,
"repo_name": "phpstan/phpstan",
"id": "6870e4d1eb41106733b9022a6c37c7398c3c697a",
"size": "2998",
"binary": false,
"copies": "1",
"ref": "refs/heads/1.9.x",
"path": "website/src/developing-extensions/dynamic-throw-type-extensions.md",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "2508"
},
{
"name": "JavaScript",
"bytes": "3488"
},
{
"name": "Nunjucks",
"bytes": "112916"
},
{
"name": "PHP",
"bytes": "41305"
},
{
"name": "Roff",
"bytes": "1219"
},
{
"name": "Shell",
"bytes": "1886"
},
{
"name": "TypeScript",
"bytes": "57234"
}
],
"symlink_target": ""
} |
import bandicoot as bc
from bandicoot.helper.group import group_records
from bandicoot.core import User, Record
from bisect import bisect_right
from functools import partial
import datetime as dt
import itertools
import csv
import math
def create_punchcards(user, split_interval=60):
"""
Computes raw indicators (e.g. number of outgoing calls) for intervals of ~1 hour
across each week of user data. These "punchcards" are returned in a nested list
with each sublist containing [user.name, channel, weekday, section, value].
Parameters
----------
user : object
The user to create punchcards for.
split_interval : int
The interval in minutes for which each indicator is computed. Defaults to 60.
Needs to be able to split a day (24*60 minutes) evenly.
"""
if not float(24 * 60 / split_interval).is_integer():
raise ValueError(
"The minute interval set for the punchcard structure does not evenly divide the day!")
contacts_in = partial(bc.individual.number_of_contacts,
direction='in', interaction='callandtext', summary=None)
contacts_out = partial(bc.individual.number_of_contacts,
direction='out', interaction='callandtext', summary=None)
calls_in = partial(bc.individual.number_of_interactions,
direction='in', interaction='call', summary=None)
calls_out = partial(bc.individual.number_of_interactions,
direction='out', interaction='call', summary=None)
texts_in = partial(bc.individual.number_of_interactions,
direction='in', interaction='text', summary=None)
texts_out = partial(bc.individual.number_of_interactions,
direction='out', interaction='text', summary=None)
time_spent_in = partial(bc.individual.call_duration,
direction='in', interaction='call', summary=None)
time_spent_out = partial(bc.individual.call_duration,
direction='out', interaction='call', summary=None)
core_func = [
(contacts_in, "scalar"),
(contacts_out, "scalar"),
(calls_in, "scalar"),
(calls_out, "scalar"),
(texts_in, "scalar"),
(texts_out, "scalar")
]
time_func = [
(time_spent_in, "summarystats"),
(time_spent_out, "summarystats")
]
pc = []
sections = [
(i + 1) * split_interval for i in range(7 * 24 * 60 / split_interval)]
temp_user = _extract_user_info(user)
for grouped_records in group_records(user, groupby='week'):
week_records = list(grouped_records)
time_spent_rec = _transform_to_time_spent(
week_records, split_interval, sections)
pc.extend(_calculate_channels(
week_records, sections, split_interval, core_func, temp_user))
pc.extend(_calculate_channels(
time_spent_rec, sections, split_interval, time_func, temp_user, len(core_func)))
return pc
def to_csv(punchcards, filename, digits=5):
"""
Exports a list of punchcards to a specified filename in the CSV format.
Parameters
----------
punchcards : list
The punchcards to export.
filename : string
Path for the exported CSV file.
"""
with open(filename, 'wb') as f:
w = csv.writer(f)
w.writerow(['year_week', 'channel', 'weekday', 'section', 'value'])
def make_repr(item):
if item is None:
return None
elif isinstance(item, float):
return repr(round(item, digits))
else:
return str(item)
for row in punchcards:
w.writerow([make_repr(item) for item in row])
def read_csv(filename):
"""
Read a list of punchcards from a CSV file.
"""
with open(filename, 'rb') as f:
r = csv.reader(f)
next(r) # remove header
pc = list(r)
# remove header and convert to numeric
for i, row in enumerate(pc):
row[1:4] = map(int, row[1:4])
row[4] = float(row[4])
return pc
def _calculate_channels(records, sections, split_interval, channel_funcs, user, c_start=0):
"""
Used to group a list of records across a week as defined by the supplied sections.
Outputs a list containing records in each section and a list with info to identify those sections.
Parameters
----------
records : list
The week of records to calculate the channels for.
sections : list
The list of sections for grouping. Each section will have an integer value
stating the minutes away from midnight between Sunday and Monday.
split_interval : int
The interval in minutes for which each indicator is computed.
channel_funcs : list
Indicator functions that generate the values for the punchcard.
user : object
The user to calculate channels for.
c_start : num
Start numbering of channels from this value. Optional parameter. Default value of 0.
Used when adding channels to the same user using different lists of records.
"""
week_matrix = []
if len(records) == 0:
return week_matrix
if not isinstance(records, list):
records = [records]
year_week = str(records[0].datetime.isocalendar()[
0]) + '-' + str(records[0].datetime.isocalendar()[1])
section_lists, section_id = _punchcard_grouping(records, sections, split_interval)
for c, fun in enumerate(channel_funcs):
for b, section_records in enumerate(section_lists):
indicator_fun, return_type = fun
# _records is used to avoid recomputing home
user._records = section_records
output = indicator_fun(user)['allweek']['allday'].values()[0]
if return_type == 'scalar':
indicator = sum(d for d in output if d is not None)
elif return_type == 'summarystats':
indicator = sum(d for group in output for d in group if d is not None)
if indicator != 0:
week_matrix.append(
[year_week, c + c_start, section_id[b][0], section_id[b][1], float(indicator)])
return week_matrix
def _punchcard_grouping(records, sections, split_interval):
"""
Used to group a list of records across a week as defined by the supplied sections.
Outputs a list containing records in each section and a list with info to identify those sections.
Parameters
----------
records : list
The week of records to group across the different weekdays/sections.
sections : list
The list of sections for grouping. Each section will have an integer value
stating the minutes away from midnight between Sunday and Monday.
split_interval : int
The interval in minutes for which each indicator is computed.
"""
def _group_by_weektime(records, sections):
for _, group in itertools.groupby(records, key=lambda r: bisect_right(sections, _find_weektime(r.datetime))):
yield group
section_records = _group_by_weektime(records, sections)
section_lists = _extract_list_from_generator(section_records)
section_indices = [bisect_right(
sections, _find_weektime(r_list[0].datetime)) for r_list in section_lists]
section_id = _find_day_section_from_indices(
section_indices, split_interval)
assert(len(section_lists) == len(section_id) and len(
section_indices) == len(set(section_indices)))
return section_lists, section_id
def _transform_to_time_spent(records, split_interval, sections):
"""
Each call that crosses a boundary of the sections in the punchcard is split.
These new records contain the amount of time (in record.call_duration) spent
talking in that specific section.
"""
t_records = []
week_nr = records[0].datetime.isocalendar()[1]
# contrary to the rest of the binning process, this is done with second
# precision
for r in filter(lambda rec: rec.interaction == 'call' and rec.call_duration > 0, records):
t_left = r.call_duration
t_to_next_section = _seconds_to_section_split(r, sections)
t_spent_total = 0
while (t_left > 0):
t_spent = min(t_to_next_section, t_left)
dt_new = r.datetime + dt.timedelta(seconds=t_spent_total)
if dt_new.isocalendar()[1] > week_nr:
dt_new -= dt.timedelta(days=7)
t_records.append(
Record('call', r.direction, None, dt_new, t_spent, None))
t_left -= t_spent
t_spent_total += t_spent
t_to_next_section = split_interval * 60
return sorted(t_records, key=lambda r: _find_weektime(r.datetime))
def _extract_user_info(user):
"""
Creates a new user class with extracted user attributes for later use.
A new user is needed when wanting to avoid overwritting e.g. ``user.records``.
"""
temp_user = User()
copy_attributes = [
'antennas', 'name', 'night_start', 'night_end', 'weekend', 'home']
for attr in copy_attributes:
setattr(temp_user, attr, getattr(user, attr))
return temp_user
def _find_weektime(datetime, time_type='min'):
"""
Finds the minutes/seconds aways from midnight between Sunday and Monday.
Parameters
----------
datetime : datetime
The date and time that needs to be converted.
time_type : 'min' or 'sec'
States whether the time difference should be specified in seconds or minutes.
"""
if time_type == 'sec':
return datetime.weekday() * 24 * 60 * 60 + datetime.hour * 60 * 60 + datetime.minute * 60 + datetime.second
elif time_type == 'min':
return datetime.weekday() * 24 * 60 + datetime.hour * 60 + datetime.minute
else:
raise ValueError("Invalid time type specified.")
def _extract_list_from_generator(generator):
"""
Iterates over a generator to extract all the objects and add them to a list.
Useful when the objects have to be used multiple times.
"""
extracted = []
for i in generator:
extracted.append(list(i))
return extracted
def _seconds_to_section_split(record, sections):
"""
Finds the seconds to the next section from the datetime of a record.
"""
next_section = sections[
bisect_right(sections, _find_weektime(record.datetime))] * 60
return next_section - _find_weektime(record.datetime, time_type='sec')
def _find_day_section_from_indices(indices, split_interval):
"""
Returns a list with [weekday, section] identifiers found using a list of indices.
"""
cells_day = 24 * 60 / split_interval
return [[int(math.floor(i / cells_day)), i % cells_day] for i in indices]
| {
"content_hash": "c74c1dead18ec1815f71b8f314695ebb",
"timestamp": "",
"source": "github",
"line_count": 310,
"max_line_length": 117,
"avg_line_length": 35.20322580645161,
"alnum_prop": 0.6292495189223861,
"repo_name": "econandrew/bandicoot",
"id": "50e421f5ac1bbebbef956d80dfa68d29954afd92",
"size": "10913",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "bandicoot/special/punchcard.py",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "6104"
},
{
"name": "HTML",
"bytes": "3596"
},
{
"name": "JavaScript",
"bytes": "43017"
},
{
"name": "Makefile",
"bytes": "120"
},
{
"name": "Python",
"bytes": "144105"
}
],
"symlink_target": ""
} |
{% extends "base.html" %}
{% block content %}
<div class="row">
<div class="col-xs-12 col-sm-8 col-sm-offset-2 col-md-6 col-md-offset-3 col-lg-4 col-lg-offset-4">
<form id="loginform" method="POST" action="">
{% csrf_token %}
<h2 class="text-center">로그인</h2>
{% if error %}
<h3>* {{ error }}</h3>
{% endif %}
<div class="form-group">
<label for="id_username">아이디</label>
<input type="text" class="form-control" id="id_username" name="username" autofocus="autofocus" required="required">
</div>
<div class="form-group">
<label for="id_password2">비밀번호</label>
<input type="password" class="form-control" id="id_password" name="password" required="required">
</div>
<button class="btn btn-lg btn-primary btn-block" type="submit">제출하기</button>
</form>
</div>
</div>
{% endblock %}
| {
"content_hash": "513c120cb4b885fc872703448ef7ba4a",
"timestamp": "",
"source": "github",
"line_count": 27,
"max_line_length": 119,
"avg_line_length": 30.88888888888889,
"alnum_prop": 0.6223021582733813,
"repo_name": "bestgunman/Gitwaxingproduct",
"id": "4a213ff37baae54c7f2e09c4034efa7d86b99e68",
"size": "862",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "Projectreview/templates/account/login.html",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "2272"
},
{
"name": "HTML",
"bytes": "19823"
},
{
"name": "Python",
"bytes": "26036"
}
],
"symlink_target": ""
} |
'use strict';
describe('TreeFactory', function () {
var TreeFactory;
var trees;
var formattedTrees;
beforeEach(function () {
module('okra');
});
beforeEach(inject(function (_TreeFactory_) {
TreeFactory = _TreeFactory_;
trees = [{
"Name": "Monthly 12/14",
"Id": "549dcb2befb6f7203e000001",
"Active": true
}, {
"Name": "yearly 12/14",
"Id": "549dcbe9efb6f7204b000001",
"Active": true
}, {
"Name": "Make bread",
"Id": "549dcbf2efb6f7204b000002",
"Active": true
}];
}));
describe('formatTrees should take in trees and format properly', function () {
it('Should inject the TreeFactory', function () {
expect(TreeFactory).not.toBeUndefined();
});
it('Should take in less than four trees and return an array with one array nested inside',
function () {
formattedTrees = TreeFactory.formatTrees(trees);
expect(formattedTrees.length).toBe(1);
});
it('Should take in more than four trees and return an array with two arrays nested inside',
function () {
trees.push({
"Name": "Make bread",
"Id": "549dcbf2efb6f7204b000002",
"Active": true
}, {
"Name": "Make bread",
"Id": "549dcbf2efb6f7204b000002",
"Active": true
});
formattedTrees = TreeFactory.formatTrees(trees);
expect(formattedTrees.length).toBe(2);
});
});
});
| {
"content_hash": "d1354a15923a58dc6c3e7c724ae1dcb4",
"timestamp": "",
"source": "github",
"line_count": 57,
"max_line_length": 99,
"avg_line_length": 30.385964912280702,
"alnum_prop": 0.49364896073903003,
"repo_name": "dmonay/okra_client",
"id": "775fc74c7dd6b027ffdda1e32f3a4482b7d92ef8",
"size": "1732",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/app/tree/TreesFactory.spec.js",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "770515"
},
{
"name": "HTML",
"bytes": "27255"
},
{
"name": "JavaScript",
"bytes": "770423"
},
{
"name": "Shell",
"bytes": "369"
}
],
"symlink_target": ""
} |
import { Component } from '@angular/core';
import { Router } from '@angular/router';
// import { FormGroup, FormControl, Validators, FormBuilder } from '@angular/forms';
import { AlertService, UserService } from '../../services/index';
import { ToastComponent } from "app/shared/toast/toast.component";
// import { DataService } from '../services/data.service';
// import { ToastComponent } from '../shared/toast/toast.component';
@Component({
selector: 'app-signup',
templateUrl: './signup.component.html',
styleUrls: ['./signup.component.scss']
})
export class SignupComponent {
model: any = {};
isLoading = false;
constructor(
private router: Router,
private userService: UserService,
private toast: ToastComponent) { }
register() {
this.isLoading = true;
this.userService.create(this.model)
.subscribe(
data => {
// set success message and pass true paramater to persist the message after redirecting to the login page
// this.alertService.success('Registration successful', true);
this.toast.setMessage('Registration successful', 'warning');
this.router.navigate(['/login']);
},
error => {
// this.alertService.error(error);
this.toast.setMessage('Could not register - ' + error, 'warning');
this.isLoading = false;
});
}
}
| {
"content_hash": "2300e8223c228ab3471276355e4aec1b",
"timestamp": "",
"source": "github",
"line_count": 39,
"max_line_length": 113,
"avg_line_length": 34.717948717948715,
"alnum_prop": 0.6617429837518464,
"repo_name": "jaecuong/LinkReview",
"id": "1fc6e9ea078867e0aa8ec89818c69571e04ce304",
"size": "1354",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "client/app/account/signup/signup.component.ts",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "2631"
},
{
"name": "HTML",
"bytes": "15518"
},
{
"name": "JavaScript",
"bytes": "2002"
},
{
"name": "TypeScript",
"bytes": "31734"
}
],
"symlink_target": ""
} |
// Copyright (c) Jeremy W. Kuhne. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using WInterop.Registry;
using WInterop.Errors;
using WInterop.Shell;
namespace ShellTests;
public class AssociationTests
{
[Fact]
public void GetTextAssociation_ProgID()
{
string value = ShellMethods.AssocQueryString(
AssociationFlags.NoUserSettings,
AssociationString.ProgId,
".txt",
null);
if (!string.Equals(value, "txtfile") && value.StartsWith("Appl"))
{
// Example: Applications\notepad++.exe
value.Should().StartWith("Applications\\").And.EndWith(".exe");
}
}
[Fact]
public void GetTextAssociation_OpenCommand()
{
string value = ShellMethods.AssocQueryString(AssociationFlags.None, AssociationString.Command, ".txt", "open");
// Example: "C:\Program Files (x86)\Notepad++\notepad++.exe" "%1"
value.Should().Contain(".exe");
}
[Fact]
public void GetTextAssociation_OpenCommandExecutable()
{
string value = ShellMethods.AssocQueryString(AssociationFlags.None, AssociationString.Executable, ".txt", "open");
// Example: C:\Program Files (x86)\Notepad++\notepad++.exe
value.Should().EndWithEquivalent(".exe");
}
[Fact]
public void GetTextAssociation_FriendlyDocName()
{
string value = ShellMethods.AssocQueryString(AssociationFlags.None, AssociationString.FriendlyDocName, ".txt", null);
value.Should().BeOneOf("TXT File", "Text Document");
}
[Fact]
public void GetTextAssociation_FriendlyAppName()
{
string value = ShellMethods.AssocQueryString(AssociationFlags.None, AssociationString.FriendlyAppName, ".txt", null);
// Example: Notepad++ : a free (GNU) source code editor
value.Should().StartWith("Notepad");
}
[Fact]
public void GetTextAssociation_AppId()
{
try
{
string association = ShellMethods.AssocQueryString(
AssociationFlags.NoUserSettings,
AssociationString.AppId,
".txt",
null);
association.Should().NotBeNullOrEmpty();
}
catch (Exception e)
{
// No application is associated with the specified file for this operation.
e.HResult.Should().Be((int)WindowsError.ERROR_NO_ASSOCIATION.ToHResult());
}
}
[Fact]
public void GetTextAssociation_ContentType()
{
string value = ShellMethods.AssocQueryString(AssociationFlags.None, AssociationString.ContentType, ".txt", null);
value.Should().Be(@"text/plain");
}
[Fact]
public void GetTextAssociation_QuickTip()
{
string value = ShellMethods.AssocQueryString(AssociationFlags.None, AssociationString.QuickTip, ".txt", null);
value.Should().Be("prop:System.ItemTypeText;System.Size;System.DateModified");
IPropertyDescriptionList list = ShellMethods.GetPropertyDescriptionListFromString(value);
list.GetCount().Should().Be(3);
IPropertyDescription desc = list.GetAt(0, new Guid(InterfaceIds.IID_IPropertyDescription));
desc.GetCanonicalName().Should().Be("System.ItemTypeText");
desc = list.GetAt(1, new Guid(InterfaceIds.IID_IPropertyDescription));
desc.GetCanonicalName().Should().Be("System.Size");
desc = list.GetAt(2, new Guid(InterfaceIds.IID_IPropertyDescription));
desc.GetCanonicalName().Should().Be("System.DateModified");
}
[Fact]
public void GetTextAssociation_AppKey()
{
RegistryKeyHandle key = ShellMethods.AssocQueryKey(AssociationFlags.None, AssociationKey.App, ".txt", null);
string name = Registry.QueryKeyName(key);
if (name.StartsWith(@"\REGISTRY\MACHINE"))
{
// No user overrides.
name.Should().StartWith(@"\REGISTRY\MACHINE\SOFTWARE\Classes\Applications\notepad.exe");
}
else
{
// Has a user setting, should be something like:
// \REGISTRY\USER\S-1-5-21-2477298427-4111324449-2912218533-1001_Classes\Applications\notepad++.exe
name.Should().StartWith(@"\REGISTRY\USER\S-").And.EndWith(".exe");
}
}
[Fact]
public void GetTextAssociation_BaseClassKey()
{
RegistryKeyHandle key = ShellMethods.AssocQueryKey(AssociationFlags.None, AssociationKey.BaseClass, ".txt", null);
string name = Registry.QueryKeyName(key);
// \REGISTRY\USER\S-1-5-21-2477298427-4111324449-2912218533-1001_Classes\*
name.Should().StartWith(@"\REGISTRY\USER\S-").And.EndWith(@"_Classes\*");
}
[Fact]
public void GetTextAssociation_ClassKey()
{
RegistryKeyHandle key = ShellMethods.AssocQueryKey(AssociationFlags.None, AssociationKey.Class, ".txt", null);
// \REGISTRY\USER\S-1-5-21-2477298427-4111324449-2912218533-1001_Classes\Applications\notepad++.exe
string name = Registry.QueryKeyName(key);
if (name.StartsWith(@"\REGISTRY\MACHINE"))
{
// No user overrides.
name.Should().StartWith(@"\REGISTRY\MACHINE\SOFTWARE\Classes\txtfile");
}
else
{
// Has a user setting, should be something like:
name.Should().StartWith(@"\REGISTRY\USER\S-");
}
}
[Fact]
public void GetTextAssociation_ShellExecClassKey()
{
RegistryKeyHandle key = ShellMethods.AssocQueryKey(AssociationFlags.None, AssociationKey.ShellExecClass, ".txt", null);
string name = Registry.QueryKeyName(key);
if (name.StartsWith(@"\REGISTRY\MACHINE"))
{
// No user overrides.
name.Should().StartWith(@"\REGISTRY\MACHINE\SOFTWARE\Classes\txtfile");
}
else
{
// Has a user setting, should be something like:
name.Should().StartWith(@"\REGISTRY\USER\S-");
}
}
}
| {
"content_hash": "83c66b1eb5c6ccf1736cd307679ec303",
"timestamp": "",
"source": "github",
"line_count": 172,
"max_line_length": 127,
"avg_line_length": 35.325581395348834,
"alnum_prop": 0.6357801184990125,
"repo_name": "JeremyKuhne/WInterop",
"id": "ceff503ee40d7a2162f95fea2e2ba86f1a8d2ad0",
"size": "6078",
"binary": false,
"copies": "1",
"ref": "refs/heads/main",
"path": "src/Tests/WInterop.Tests/Shell/AssociationTests.cs",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C",
"bytes": "2121"
},
{
"name": "C#",
"bytes": "2686796"
},
{
"name": "C++",
"bytes": "1778"
},
{
"name": "HTML",
"bytes": "92156"
}
],
"symlink_target": ""
} |
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Formatting;
using System.Net.Http.Headers;
using System.Web.Http.Description;
using System.Xml.Linq;
using Newtonsoft.Json;
namespace TestingApp.Areas.HelpPage
{
/// <summary>
/// This class will generate the samples for the help page.
/// </summary>
public class HelpPageSampleGenerator
{
/// <summary>
/// Initializes a new instance of the <see cref="HelpPageSampleGenerator"/> class.
/// </summary>
public HelpPageSampleGenerator()
{
ActualHttpMessageTypes = new Dictionary<HelpPageSampleKey, Type>();
ActionSamples = new Dictionary<HelpPageSampleKey, object>();
SampleObjects = new Dictionary<Type, object>();
SampleObjectFactories = new List<Func<HelpPageSampleGenerator, Type, object>>
{
DefaultSampleObjectFactory,
};
}
/// <summary>
/// Gets CLR types that are used as the content of <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/>.
/// </summary>
public IDictionary<HelpPageSampleKey, Type> ActualHttpMessageTypes { get; internal set; }
/// <summary>
/// Gets the objects that are used directly as samples for certain actions.
/// </summary>
public IDictionary<HelpPageSampleKey, object> ActionSamples { get; internal set; }
/// <summary>
/// Gets the objects that are serialized as samples by the supported formatters.
/// </summary>
public IDictionary<Type, object> SampleObjects { get; internal set; }
/// <summary>
/// Gets factories for the objects that the supported formatters will serialize as samples. Processed in order,
/// stopping when the factory successfully returns a non-<see langref="null"/> object.
/// </summary>
/// <remarks>
/// Collection includes just <see cref="ObjectGenerator.GenerateObject(Type)"/> initially. Use
/// <code>SampleObjectFactories.Insert(0, func)</code> to provide an override and
/// <code>SampleObjectFactories.Add(func)</code> to provide a fallback.</remarks>
[SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures",
Justification = "This is an appropriate nesting of generic types")]
public IList<Func<HelpPageSampleGenerator, Type, object>> SampleObjectFactories { get; private set; }
/// <summary>
/// Gets the request body samples for a given <see cref="ApiDescription"/>.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <returns>The samples keyed by media type.</returns>
public IDictionary<MediaTypeHeaderValue, object> GetSampleRequests(ApiDescription api)
{
return GetSample(api, SampleDirection.Request);
}
/// <summary>
/// Gets the response body samples for a given <see cref="ApiDescription"/>.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <returns>The samples keyed by media type.</returns>
public IDictionary<MediaTypeHeaderValue, object> GetSampleResponses(ApiDescription api)
{
return GetSample(api, SampleDirection.Response);
}
/// <summary>
/// Gets the request or response body samples.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param>
/// <returns>The samples keyed by media type.</returns>
public virtual IDictionary<MediaTypeHeaderValue, object> GetSample(ApiDescription api, SampleDirection sampleDirection)
{
if (api == null)
{
throw new ArgumentNullException("api");
}
string controllerName = api.ActionDescriptor.ControllerDescriptor.ControllerName;
string actionName = api.ActionDescriptor.ActionName;
IEnumerable<string> parameterNames = api.ParameterDescriptions.Select(p => p.Name);
Collection<MediaTypeFormatter> formatters;
Type type = ResolveType(api, controllerName, actionName, parameterNames, sampleDirection, out formatters);
var samples = new Dictionary<MediaTypeHeaderValue, object>();
// Use the samples provided directly for actions
var actionSamples = GetAllActionSamples(controllerName, actionName, parameterNames, sampleDirection);
foreach (var actionSample in actionSamples)
{
samples.Add(actionSample.Key.MediaType, WrapSampleIfString(actionSample.Value));
}
// Do the sample generation based on formatters only if an action doesn't return an HttpResponseMessage.
// Here we cannot rely on formatters because we don't know what's in the HttpResponseMessage, it might not even use formatters.
if (type != null && !typeof(HttpResponseMessage).IsAssignableFrom(type))
{
object sampleObject = GetSampleObject(type);
foreach (var formatter in formatters)
{
foreach (MediaTypeHeaderValue mediaType in formatter.SupportedMediaTypes)
{
if (!samples.ContainsKey(mediaType))
{
object sample = GetActionSample(controllerName, actionName, parameterNames, type, formatter, mediaType, sampleDirection);
// If no sample found, try generate sample using formatter and sample object
if (sample == null && sampleObject != null)
{
sample = WriteSampleObjectUsingFormatter(formatter, sampleObject, type, mediaType);
}
samples.Add(mediaType, WrapSampleIfString(sample));
}
}
}
}
return samples;
}
/// <summary>
/// Search for samples that are provided directly through <see cref="ActionSamples"/>.
/// </summary>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
/// <param name="type">The CLR type.</param>
/// <param name="formatter">The formatter.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param>
/// <returns>The sample that matches the parameters.</returns>
public virtual object GetActionSample(string controllerName, string actionName, IEnumerable<string> parameterNames, Type type, MediaTypeFormatter formatter, MediaTypeHeaderValue mediaType, SampleDirection sampleDirection)
{
object sample;
// First, try to get the sample provided for the specified mediaType, sampleDirection, controllerName, actionName and parameterNames.
// If not found, try to get the sample provided for the specified mediaType, sampleDirection, controllerName and actionName regardless of the parameterNames.
// If still not found, try to get the sample provided for the specified mediaType and type.
// Finally, try to get the sample provided for the specified mediaType.
if (ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, parameterNames), out sample) ||
ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, new[] { "*" }), out sample) ||
ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, type), out sample) ||
ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType), out sample))
{
return sample;
}
return null;
}
/// <summary>
/// Gets the sample object that will be serialized by the formatters.
/// First, it will look at the <see cref="SampleObjects"/>. If no sample object is found, it will try to create
/// one using <see cref="DefaultSampleObjectFactory"/> (which wraps an <see cref="ObjectGenerator"/>) and other
/// factories in <see cref="SampleObjectFactories"/>.
/// </summary>
/// <param name="type">The type.</param>
/// <returns>The sample object.</returns>
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes",
Justification = "Even if all items in SampleObjectFactories throw, problem will be visible as missing sample.")]
public virtual object GetSampleObject(Type type)
{
object sampleObject;
if (!SampleObjects.TryGetValue(type, out sampleObject))
{
// No specific object available, try our factories.
foreach (Func<HelpPageSampleGenerator, Type, object> factory in SampleObjectFactories)
{
if (factory == null)
{
continue;
}
try
{
sampleObject = factory(this, type);
if (sampleObject != null)
{
break;
}
}
catch
{
// Ignore any problems encountered in the factory; go on to the next one (if any).
}
}
}
return sampleObject;
}
/// <summary>
/// Resolves the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <returns>The type.</returns>
public virtual Type ResolveHttpRequestMessageType(ApiDescription api)
{
string controllerName = api.ActionDescriptor.ControllerDescriptor.ControllerName;
string actionName = api.ActionDescriptor.ActionName;
IEnumerable<string> parameterNames = api.ParameterDescriptions.Select(p => p.Name);
Collection<MediaTypeFormatter> formatters;
return ResolveType(api, controllerName, actionName, parameterNames, SampleDirection.Request, out formatters);
}
/// <summary>
/// Resolves the type of the action parameter or return value when <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/> is used.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
/// <param name="sampleDirection">The value indicating whether the sample is for a request or a response.</param>
/// <param name="formatters">The formatters.</param>
[SuppressMessage("Microsoft.Design", "CA1021:AvoidOutParameters", Justification = "This is only used in advanced scenarios.")]
public virtual Type ResolveType(ApiDescription api, string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection, out Collection<MediaTypeFormatter> formatters)
{
if (!Enum.IsDefined(typeof(SampleDirection), sampleDirection))
{
throw new InvalidEnumArgumentException("sampleDirection", (int)sampleDirection, typeof(SampleDirection));
}
if (api == null)
{
throw new ArgumentNullException("api");
}
Type type;
if (ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, parameterNames), out type) ||
ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, new[] { "*" }), out type))
{
// Re-compute the supported formatters based on type
Collection<MediaTypeFormatter> newFormatters = new Collection<MediaTypeFormatter>();
foreach (var formatter in api.ActionDescriptor.Configuration.Formatters)
{
if (IsFormatSupported(sampleDirection, formatter, type))
{
newFormatters.Add(formatter);
}
}
formatters = newFormatters;
}
else
{
switch (sampleDirection)
{
case SampleDirection.Request:
ApiParameterDescription requestBodyParameter = api.ParameterDescriptions.FirstOrDefault(p => p.Source == ApiParameterSource.FromBody);
type = requestBodyParameter == null ? null : requestBodyParameter.ParameterDescriptor.ParameterType;
formatters = api.SupportedRequestBodyFormatters;
break;
case SampleDirection.Response:
default:
type = api.ResponseDescription.ResponseType ?? api.ResponseDescription.DeclaredType;
formatters = api.SupportedResponseFormatters;
break;
}
}
return type;
}
/// <summary>
/// Writes the sample object using formatter.
/// </summary>
/// <param name="formatter">The formatter.</param>
/// <param name="value">The value.</param>
/// <param name="type">The type.</param>
/// <param name="mediaType">Type of the media.</param>
/// <returns></returns>
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as InvalidSample.")]
public virtual object WriteSampleObjectUsingFormatter(MediaTypeFormatter formatter, object value, Type type, MediaTypeHeaderValue mediaType)
{
if (formatter == null)
{
throw new ArgumentNullException("formatter");
}
if (mediaType == null)
{
throw new ArgumentNullException("mediaType");
}
object sample = String.Empty;
MemoryStream ms = null;
HttpContent content = null;
try
{
if (formatter.CanWriteType(type))
{
ms = new MemoryStream();
content = new ObjectContent(type, value, formatter, mediaType);
formatter.WriteToStreamAsync(type, value, ms, content, null).Wait();
ms.Position = 0;
StreamReader reader = new StreamReader(ms);
string serializedSampleString = reader.ReadToEnd();
if (mediaType.MediaType.ToUpperInvariant().Contains("XML"))
{
serializedSampleString = TryFormatXml(serializedSampleString);
}
else if (mediaType.MediaType.ToUpperInvariant().Contains("JSON"))
{
serializedSampleString = TryFormatJson(serializedSampleString);
}
sample = new TextSample(serializedSampleString);
}
else
{
sample = new InvalidSample(String.Format(
CultureInfo.CurrentCulture,
"Failed to generate the sample for media type '{0}'. Cannot use formatter '{1}' to write type '{2}'.",
mediaType,
formatter.GetType().Name,
type.Name));
}
}
catch (Exception e)
{
sample = new InvalidSample(String.Format(
CultureInfo.CurrentCulture,
"An exception has occurred while using the formatter '{0}' to generate sample for media type '{1}'. Exception message: {2}",
formatter.GetType().Name,
mediaType.MediaType,
UnwrapException(e).Message));
}
finally
{
if (ms != null)
{
ms.Dispose();
}
if (content != null)
{
content.Dispose();
}
}
return sample;
}
internal static Exception UnwrapException(Exception exception)
{
AggregateException aggregateException = exception as AggregateException;
if (aggregateException != null)
{
return aggregateException.Flatten().InnerException;
}
return exception;
}
// Default factory for sample objects
private static object DefaultSampleObjectFactory(HelpPageSampleGenerator sampleGenerator, Type type)
{
// Try to create a default sample object
ObjectGenerator objectGenerator = new ObjectGenerator();
return objectGenerator.GenerateObject(type);
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")]
private static string TryFormatJson(string str)
{
try
{
object parsedJson = JsonConvert.DeserializeObject(str);
return JsonConvert.SerializeObject(parsedJson, Formatting.Indented);
}
catch
{
// can't parse JSON, return the original string
return str;
}
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")]
private static string TryFormatXml(string str)
{
try
{
XDocument xml = XDocument.Parse(str);
return xml.ToString();
}
catch
{
// can't parse XML, return the original string
return str;
}
}
private static bool IsFormatSupported(SampleDirection sampleDirection, MediaTypeFormatter formatter, Type type)
{
switch (sampleDirection)
{
case SampleDirection.Request:
return formatter.CanReadType(type);
case SampleDirection.Response:
return formatter.CanWriteType(type);
}
return false;
}
private IEnumerable<KeyValuePair<HelpPageSampleKey, object>> GetAllActionSamples(string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection)
{
HashSet<string> parameterNamesSet = new HashSet<string>(parameterNames, StringComparer.OrdinalIgnoreCase);
foreach (var sample in ActionSamples)
{
HelpPageSampleKey sampleKey = sample.Key;
if (String.Equals(controllerName, sampleKey.ControllerName, StringComparison.OrdinalIgnoreCase) &&
String.Equals(actionName, sampleKey.ActionName, StringComparison.OrdinalIgnoreCase) &&
(sampleKey.ParameterNames.SetEquals(new[] { "*" }) || parameterNamesSet.SetEquals(sampleKey.ParameterNames)) &&
sampleDirection == sampleKey.SampleDirection)
{
yield return sample;
}
}
}
private static object WrapSampleIfString(object sample)
{
string stringSample = sample as string;
if (stringSample != null)
{
return new TextSample(stringSample);
}
return sample;
}
}
} | {
"content_hash": "ff6976e8aa184cb67e417178426aee3c",
"timestamp": "",
"source": "github",
"line_count": 444,
"max_line_length": 229,
"avg_line_length": 47.207207207207205,
"alnum_prop": 0.5864503816793893,
"repo_name": "stewart-itopia/ExportToExcel",
"id": "beffdb6dbcf6ebb0f2c97e63e4416acb3c06dc63",
"size": "20960",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "TestingApp/Areas/HelpPage/SampleGeneration/HelpPageSampleGenerator.cs",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "ASP",
"bytes": "101"
},
{
"name": "C#",
"bytes": "235602"
},
{
"name": "CSS",
"bytes": "3049"
},
{
"name": "HTML",
"bytes": "5083"
},
{
"name": "JavaScript",
"bytes": "298528"
},
{
"name": "Pascal",
"bytes": "130881"
},
{
"name": "PowerShell",
"bytes": "130485"
},
{
"name": "Puppet",
"bytes": "3202"
}
],
"symlink_target": ""
} |
import { connect } from 'react-redux'
import { fetchQuestionnaires } from '../modules/counter'
/* This is a container component. Notice it does not contain any JSX,
nor does it import React. This component is **only** responsible for
wiring in the actions and state necessary to render a presentational
component - in this case, the counter: */
import Counter from '../components/Counter'
/* Object of action creators (can also be function that returns object).
Keys will be passed as props to presentational components. Here we are
implementing our wrapper around increment; the component doesn't care */
const mapDispatchToProps = {
fetchQuestionnaires
}
const mapStateToProps = (state) => ({
questionnaire : state.questionnaire
})
/* Note: mapStateToProps is where you should use `reselect` to create selectors, ie:
import { createSelector } from 'reselect'
const counter = (state) => state.counter
const tripleCount = createSelector(counter, (count) => count * 3)
const mapStateToProps = (state) => ({
counter: tripleCount(state)
})
Selectors can compute derived data, allowing Redux to store the minimal possible state.
Selectors are efficient. A selector is not recomputed unless one of its arguments change.
Selectors are composable. They can be used as input to other selectors.
https://github.com/reactjs/reselect */
export default connect(mapStateToProps, mapDispatchToProps)(Counter)
| {
"content_hash": "d08d3a648a856bf2346a901196c17b66",
"timestamp": "",
"source": "github",
"line_count": 37,
"max_line_length": 93,
"avg_line_length": 40,
"alnum_prop": 0.7324324324324324,
"repo_name": "tkshi/q",
"id": "2ace54f487c21c7d2a19322cbebae58b5d38c28d",
"size": "1480",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/routes/Questionnaire/containers/CounterContainer.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "802"
},
{
"name": "HTML",
"bytes": "356"
},
{
"name": "JavaScript",
"bytes": "50233"
}
],
"symlink_target": ""
} |
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Net.Http.Headers;
namespace CodeJewelApi.Areas.HelpPage
{
/// <summary>
/// This is used to identify the place where the sample should be applied.
/// </summary>
public class HelpPageSampleKey
{
/// <summary>
/// Creates a new <see cref="HelpPageSampleKey"/> based on media type and CLR type.
/// </summary>
/// <param name="mediaType">The media type.</param>
/// <param name="type">The CLR type.</param>
public HelpPageSampleKey(MediaTypeHeaderValue mediaType, Type type)
{
if (mediaType == null)
{
throw new ArgumentNullException("mediaType");
}
if (type == null)
{
throw new ArgumentNullException("type");
}
ControllerName = String.Empty;
ActionName = String.Empty;
ParameterNames = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
ParameterType = type;
MediaType = mediaType;
}
/// <summary>
/// Creates a new <see cref="HelpPageSampleKey"/> based on <see cref="SampleDirection"/>, controller name, action name and parameter names.
/// </summary>
/// <param name="sampleDirection">The <see cref="SampleDirection"/>.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public HelpPageSampleKey(SampleDirection sampleDirection, string controllerName, string actionName, IEnumerable<string> parameterNames)
{
if (!Enum.IsDefined(typeof(SampleDirection), sampleDirection))
{
throw new InvalidEnumArgumentException("sampleDirection", (int)sampleDirection, typeof(SampleDirection));
}
if (controllerName == null)
{
throw new ArgumentNullException("controllerName");
}
if (actionName == null)
{
throw new ArgumentNullException("actionName");
}
if (parameterNames == null)
{
throw new ArgumentNullException("parameterNames");
}
ControllerName = controllerName;
ActionName = actionName;
ParameterNames = new HashSet<string>(parameterNames, StringComparer.OrdinalIgnoreCase);
SampleDirection = sampleDirection;
}
/// <summary>
/// Creates a new <see cref="HelpPageSampleKey"/> based on media type, <see cref="SampleDirection"/>, controller name, action name and parameter names.
/// </summary>
/// <param name="mediaType">The media type.</param>
/// <param name="sampleDirection">The <see cref="SampleDirection"/>.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public HelpPageSampleKey(MediaTypeHeaderValue mediaType, SampleDirection sampleDirection, string controllerName, string actionName, IEnumerable<string> parameterNames)
{
if (mediaType == null)
{
throw new ArgumentNullException("mediaType");
}
if (!Enum.IsDefined(typeof(SampleDirection), sampleDirection))
{
throw new InvalidEnumArgumentException("sampleDirection", (int)sampleDirection, typeof(SampleDirection));
}
if (controllerName == null)
{
throw new ArgumentNullException("controllerName");
}
if (actionName == null)
{
throw new ArgumentNullException("actionName");
}
if (parameterNames == null)
{
throw new ArgumentNullException("parameterNames");
}
ControllerName = controllerName;
ActionName = actionName;
MediaType = mediaType;
ParameterNames = new HashSet<string>(parameterNames, StringComparer.OrdinalIgnoreCase);
SampleDirection = sampleDirection;
}
/// <summary>
/// Gets the name of the controller.
/// </summary>
/// <value>
/// The name of the controller.
/// </value>
public string ControllerName { get; private set; }
/// <summary>
/// Gets the name of the action.
/// </summary>
/// <value>
/// The name of the action.
/// </value>
public string ActionName { get; private set; }
/// <summary>
/// Gets the media type.
/// </summary>
/// <value>
/// The media type.
/// </value>
public MediaTypeHeaderValue MediaType { get; private set; }
/// <summary>
/// Gets the parameter names.
/// </summary>
public HashSet<string> ParameterNames { get; private set; }
public Type ParameterType { get; private set; }
/// <summary>
/// Gets the <see cref="SampleDirection"/>.
/// </summary>
public SampleDirection? SampleDirection { get; private set; }
public override bool Equals(object obj)
{
HelpPageSampleKey otherKey = obj as HelpPageSampleKey;
if (otherKey == null)
{
return false;
}
return String.Equals(ControllerName, otherKey.ControllerName, StringComparison.OrdinalIgnoreCase) &&
String.Equals(ActionName, otherKey.ActionName, StringComparison.OrdinalIgnoreCase) &&
(MediaType == otherKey.MediaType || (MediaType != null && MediaType.Equals(otherKey.MediaType))) &&
ParameterType == otherKey.ParameterType &&
SampleDirection == otherKey.SampleDirection &&
ParameterNames.SetEquals(otherKey.ParameterNames);
}
public override int GetHashCode()
{
int hashCode = ControllerName.ToUpperInvariant().GetHashCode() ^ ActionName.ToUpperInvariant().GetHashCode();
if (MediaType != null)
{
hashCode ^= MediaType.GetHashCode();
}
if (SampleDirection != null)
{
hashCode ^= SampleDirection.GetHashCode();
}
if (ParameterType != null)
{
hashCode ^= ParameterType.GetHashCode();
}
foreach (string parameterName in ParameterNames)
{
hashCode ^= parameterName.ToUpperInvariant().GetHashCode();
}
return hashCode;
}
}
}
| {
"content_hash": "fc6d472979a4abce79559a047abf0dbc",
"timestamp": "",
"source": "github",
"line_count": 178,
"max_line_length": 175,
"avg_line_length": 39.00561797752809,
"alnum_prop": 0.5679101253060637,
"repo_name": "niki-funky/Telerik_Academy",
"id": "b860a9b636505ec0eefbb0c1547e70979ba479e5",
"size": "6943",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "Web Development/Web_and_Cloud/10. AppHarbor/CodeJewelApi/Areas/HelpPage/SampleGeneration/HelpPageSampleKey.cs",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "ASP",
"bytes": "2773"
},
{
"name": "C#",
"bytes": "4074086"
},
{
"name": "CSS",
"bytes": "850276"
},
{
"name": "JavaScript",
"bytes": "5915582"
},
{
"name": "PowerShell",
"bytes": "785001"
},
{
"name": "Puppet",
"bytes": "329334"
}
],
"symlink_target": ""
} |
<?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class AddFeaturetypeIdToFeaturesTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::table('features', function (Blueprint $table) {
$table->integer('featuretype_id')->unsigned()->nullable()->default(null);
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::table('features', function (Blueprint $table) {
$table->dropColumn('featuretype_id');
});
}
}
| {
"content_hash": "d54d11549f04e6033cbb64597731bcd6",
"timestamp": "",
"source": "github",
"line_count": 33,
"max_line_length": 81,
"avg_line_length": 21.242424242424242,
"alnum_prop": 0.5934379457917262,
"repo_name": "UnrulyNatives/helpers-for-laravel-projects",
"id": "1a89d74a653c4f95f13dadba717705e0ee898786",
"size": "701",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/unstarter_migrations/2016_09_14_104713_add_featuretype_id_to_features_table.php",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "1208805"
},
{
"name": "HTML",
"bytes": "233045"
},
{
"name": "JavaScript",
"bytes": "336762"
},
{
"name": "PHP",
"bytes": "171378"
}
],
"symlink_target": ""
} |
<?php
namespace Intacct\Functions\AccountsReceivable;
use Intacct\Xml\XMLWriter;
use InvalidArgumentException;
/**
* @coversDefaultClass \Intacct\Functions\AccountsReceivable\ArAccountLabelUpdate
*/
class ArAccountLabelUpdateTest extends \PHPUnit\Framework\TestCase
{
public function testConstruct(): void
{
$expected = <<<EOF
<?xml version="1.0" encoding="UTF-8"?>
<function controlid="unittest">
<update>
<ARACCOUNTLABEL>
<ACCOUNTLABEL>revenue</ACCOUNTLABEL>
<DESCRIPTION>hello world</DESCRIPTION>
<GLACCOUNTNO>4000</GLACCOUNTNO>
</ARACCOUNTLABEL>
</update>
</function>
EOF;
$xml = new XMLWriter();
$xml->openMemory();
$xml->setIndent(true);
$xml->setIndentString(' ');
$xml->startDocument();
$label = new ArAccountLabelUpdate('unittest');
$label->setAccountLabel('revenue');
$label->setDescription('hello world');
$label->setGlAccountNo('4000');
$label->writeXml($xml);
$this->assertXmlStringEqualsXmlString($expected, $xml->flush());
}
public function testRequiredAccountLabel(): void
{
$this->expectException(InvalidArgumentException::class);
$this->expectExceptionMessage("Account Label is required for update");
$xml = new XMLWriter();
$xml->openMemory();
$xml->setIndent(true);
$xml->setIndentString(' ');
$xml->startDocument();
$label = new ArAccountLabelUpdate('unittest');
//$label->setAccountLabel('revenue');
$label->setDescription('hello world');
$label->setGlAccountNo('4000');
$label->writeXml($xml);
}
}
| {
"content_hash": "51f20260635d12d823a84d3e8620de1e",
"timestamp": "",
"source": "github",
"line_count": 65,
"max_line_length": 81,
"avg_line_length": 26.446153846153845,
"alnum_prop": 0.6242001163467132,
"repo_name": "Intacct/intacct-sdk-php",
"id": "c814758d5ad78d95ab911f8b3edc981c04a606e3",
"size": "2275",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "test/Intacct/Functions/AccountsReceivable/ArAccountLabelUpdateTest.php",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "PHP",
"bytes": "1694380"
}
],
"symlink_target": ""
} |
FROM balenalib/intel-nuc-alpine:3.11-run
# remove several traces of python
RUN apk del python*
# http://bugs.python.org/issue19846
# > At the moment, setting "LANG=C" on a Linux system *fundamentally breaks Python 3*, and that's not OK.
ENV LANG C.UTF-8
# install python dependencies
RUN apk add --no-cache ca-certificates libffi \
&& apk add --no-cache libssl1.0 || apk add --no-cache libssl1.1
# key 63C7CC90: public key "Simon McVittie <smcv@pseudorandom.co.uk>" imported
# key 3372DCFA: public key "Donald Stufft (dstufft) <donald@stufft.io>" imported
RUN gpg --keyserver keyring.debian.org --recv-keys 4DE8FF2A63C7CC90 \
&& gpg --keyserver keyserver.ubuntu.com --recv-key 6E3CBCE93372DCFA \
&& gpg --keyserver keyserver.ubuntu.com --recv-keys 0x52a43a1e4b77b059
# point Python at a system-provided certificate database. Otherwise, we might hit CERTIFICATE_VERIFY_FAILED.
# https://www.python.org/dev/peps/pep-0476/#trust-database
ENV SSL_CERT_FILE /etc/ssl/certs/ca-certificates.crt
ENV PYTHON_VERSION 3.8.9
# if this is called "PIP_VERSION", pip explodes with "ValueError: invalid truth value '<VERSION>'"
ENV PYTHON_PIP_VERSION 21.0.1
ENV SETUPTOOLS_VERSION 56.0.0
RUN set -x \
&& buildDeps=' \
curl \
gnupg \
' \
&& apk add --no-cache --virtual .build-deps $buildDeps \
&& curl -SLO "http://resin-packages.s3.amazonaws.com/python/v$PYTHON_VERSION/Python-$PYTHON_VERSION.linux-alpine-amd64-openssl1.1.tar.gz" \
&& echo "57f5474bdcb0d87be365d5e1094eae095b85a003accae2b8968b336e0e5e0ca6 Python-$PYTHON_VERSION.linux-alpine-amd64-openssl1.1.tar.gz" | sha256sum -c - \
&& tar -xzf "Python-$PYTHON_VERSION.linux-alpine-amd64-openssl1.1.tar.gz" --strip-components=1 \
&& rm -rf "Python-$PYTHON_VERSION.linux-alpine-amd64-openssl1.1.tar.gz" \
&& if [ ! -e /usr/local/bin/pip3 ]; then : \
&& curl -SLO "https://raw.githubusercontent.com/pypa/get-pip/430ba37776ae2ad89f794c7a43b90dc23bac334c/get-pip.py" \
&& echo "19dae841a150c86e2a09d475b5eb0602861f2a5b7761ec268049a662dbd2bd0c get-pip.py" | sha256sum -c - \
&& python3 get-pip.py \
&& rm get-pip.py \
; fi \
&& pip3 install --no-cache-dir --upgrade --force-reinstall pip=="$PYTHON_PIP_VERSION" setuptools=="$SETUPTOOLS_VERSION" \
&& find /usr/local \
\( -type d -a -name test -o -name tests \) \
-o \( -type f -a -name '*.pyc' -o -name '*.pyo' \) \
-exec rm -rf '{}' + \
&& cd / \
&& rm -rf /usr/src/python ~/.cache
# make some useful symlinks that are expected to exist
RUN cd /usr/local/bin \
&& ln -sf pip3 pip \
&& { [ -e easy_install ] || ln -s easy_install-* easy_install; } \
&& ln -sf idle3 idle \
&& ln -sf pydoc3 pydoc \
&& ln -sf python3 python \
&& ln -sf python3-config python-config
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@python.sh" \
&& echo "Running test-stack@python" \
&& chmod +x test-stack@python.sh \
&& bash test-stack@python.sh \
&& rm -rf test-stack@python.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: Intel 64-bit (x86-64) \nOS: Alpine Linux 3.11 \nVariant: run variant \nDefault variable(s): UDEV=off \nThe following software stack is preinstalled: \nPython v3.8.9, Pip v21.0.1, Setuptools v56.0.0 \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/bash\nbalena-info\nbusybox ln -sf /bin/busybox /bin/sh\n/bin/sh "$@"' > /bin/sh-shim \
&& chmod +x /bin/sh-shim \
&& ln -f /bin/sh /bin/sh.real \
&& ln -f /bin/sh-shim /bin/sh | {
"content_hash": "70d6c501da2c41cfe6f3239ff2fc221c",
"timestamp": "",
"source": "github",
"line_count": 77,
"max_line_length": 728,
"avg_line_length": 53.44155844155844,
"alnum_prop": 0.7110571081409478,
"repo_name": "nghiant2710/base-images",
"id": "0a8d9c2b7fb046a3508a4b20c9d9a0b8c59be5f0",
"size": "4136",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "balena-base-images/python/intel-nuc/alpine/3.11/3.8.9/run/Dockerfile",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Dockerfile",
"bytes": "144558581"
},
{
"name": "JavaScript",
"bytes": "16316"
},
{
"name": "Shell",
"bytes": "368690"
}
],
"symlink_target": ""
} |
/**
*
*/
package com.ocean.test;
/**
* @author junfang
*
*/
public class BB {
public static String getString() {
System.out.println("1111");
return " dggdgdgdgdg";
}
public static String getString2() {
System.out.println("222");
return " wwwwwwwwwwwwwww";
}
public String getString3() {
System.out.println("3333");
return " dggdgdgdgdg";
}
public String getString4() {
System.out.println("44444");
return " wwwwwwwwwwwwwww";
}
/**
* @param args
*/
public static void main(String[] args) {
BB bb=new BB();
String temp=bb.getString4()+bb.getString3();
System.out.println(temp);
}
}
| {
"content_hash": "d970ac4d874eb2decf1b7a7a81c3d1ee",
"timestamp": "",
"source": "github",
"line_count": 44,
"max_line_length": 47,
"avg_line_length": 14.477272727272727,
"alnum_prop": 0.631083202511774,
"repo_name": "zhangjunfang/eclipse-dir",
"id": "08f82ceb57a0b5291fc312618b1b8dfb8f46d02b",
"size": "637",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "fensy/src/test/java/com/ocean/test/BB.java",
"mode": "33188",
"license": "bsd-2-clause",
"language": [
{
"name": "ASP",
"bytes": "341592"
},
{
"name": "Assembly",
"bytes": "11762"
},
{
"name": "CSS",
"bytes": "5838098"
},
{
"name": "ColdFusion",
"bytes": "998340"
},
{
"name": "Java",
"bytes": "11143836"
},
{
"name": "JavaScript",
"bytes": "37580201"
},
{
"name": "Lasso",
"bytes": "140040"
},
{
"name": "PHP",
"bytes": "610596"
},
{
"name": "Perl",
"bytes": "280108"
},
{
"name": "Python",
"bytes": "389792"
},
{
"name": "Scala",
"bytes": "652118"
},
{
"name": "Shell",
"bytes": "18696"
},
{
"name": "Slash",
"bytes": "4374192"
}
],
"symlink_target": ""
} |
require "mkmf"
create_makefile "fast_secure_compare/fast_secure_compare"
| {
"content_hash": "efb46e99b4ae49c8bf8d0b6919b5a45b",
"timestamp": "",
"source": "github",
"line_count": 3,
"max_line_length": 57,
"avg_line_length": 24.666666666666668,
"alnum_prop": 0.7972972972972973,
"repo_name": "daxtens/fast_secure_compare",
"id": "adbad7cbce7021b4dce6ac16e9a786b533f8ab51",
"size": "74",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "ext/fast_secure_compare/extconf.rb",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C",
"bytes": "1048"
},
{
"name": "Ruby",
"bytes": "3766"
}
],
"symlink_target": ""
} |
layout: page
title: Morales - Hayden Wedding
date: 2016-05-24
author: Kelly Sexton
tags: weekly links, java
status: published
summary: Etiam eu sapien rutrum, ornare.
banner: images/banner/office-01.jpg
booking:
startDate: 01/28/2016
endDate: 02/01/2016
ctyhocn: TLAREHX
groupCode: MHW
published: true
---
Sed et rhoncus lectus. Nunc sollicitudin, purus at efficitur posuere, dui quam euismod sapien, et condimentum velit ligula in nisi. Pellentesque sit amet orci sollicitudin, pulvinar mauris a, semper orci. Integer faucibus orci ac ullamcorper mattis. In rutrum facilisis lorem ac porta. Nam iaculis turpis sit amet gravida fermentum. Vestibulum tincidunt diam non dolor vestibulum viverra.
* Praesent in lacus eget nisl bibendum eleifend ut eu est
* Pellentesque molestie felis sed cursus posuere
* Pellentesque pretium felis a lobortis dapibus
* Morbi rhoncus ipsum ut mollis pretium
* In iaculis lorem id venenatis eleifend.
Fusce pretium egestas massa, at interdum lectus pulvinar non. Nulla vitae est sodales, efficitur ex in, rhoncus arcu. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Curabitur pharetra tempor ante. Integer vel nisl sit amet sem pretium pharetra. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos. Sed dapibus enim varius vulputate eleifend. Pellentesque maximus vel neque eu laoreet. Integer nunc sapien, elementum eu purus id, rutrum suscipit ante.
| {
"content_hash": "10a542ab913d806488b0af59ed7762f0",
"timestamp": "",
"source": "github",
"line_count": 24,
"max_line_length": 530,
"avg_line_length": 61.375,
"alnum_prop": 0.8065173116089613,
"repo_name": "KlishGroup/prose-pogs",
"id": "acba4e7aa3698f1dd3c902ea1996fc662cb8d205",
"size": "1477",
"binary": false,
"copies": "1",
"ref": "refs/heads/gh-pages",
"path": "pogs/T/TLAREHX/MHW/index.md",
"mode": "33188",
"license": "mit",
"language": [],
"symlink_target": ""
} |
"""
Key manager implementation for Barbican
"""
import array
import base64
import binascii
from barbicanclient import client as barbican_client
from keystoneauth1 import loading as ks_loading
from keystoneauth1 import session
from oslo_log import log as logging
from oslo_utils import excutils
import nova.conf
from nova import exception
from nova.i18n import _
from nova.i18n import _LE
from nova.keymgr import key as keymgr_key
from nova.keymgr import key_mgr
CONF = nova.conf.CONF
LOG = logging.getLogger(__name__)
class BarbicanKeyManager(key_mgr.KeyManager):
"""Key Manager Interface that wraps the Barbican client API."""
def __init__(self):
self._barbican_client = None
self._current_context = None
self._base_url = None
def _get_barbican_client(self, ctxt):
"""Creates a client to connect to the Barbican service.
:param ctxt: the user context for authentication
:return: a Barbican Client object
:raises Forbidden: if the ctxt is None
"""
# Confirm context is provided, if not raise forbidden
if not ctxt:
msg = _("User is not authorized to use key manager.")
LOG.error(msg)
raise exception.Forbidden(msg)
if not hasattr(ctxt, 'project_id') or ctxt.project_id is None:
msg = _("Unable to create Barbican Client without project_id.")
LOG.error(msg)
raise exception.KeyManagerError(msg)
# If same context, return cached barbican client
if self._barbican_client and self._current_context == ctxt:
return self._barbican_client
try:
_SESSION = ks_loading.load_session_from_conf_options(
CONF,
nova.conf.barbican.barbican_group)
auth = ctxt.get_auth_plugin()
service_type, service_name, interface = (CONF.
barbican.
catalog_info.
split(':'))
region_name = CONF.barbican.os_region_name
service_parameters = {'service_type': service_type,
'service_name': service_name,
'interface': interface,
'region_name': region_name}
if CONF.barbican.endpoint_template:
self._base_url = (CONF.barbican.endpoint_template %
ctxt.to_dict())
else:
self._base_url = _SESSION.get_endpoint(
auth, **service_parameters)
# the barbican endpoint can't have the '/v1' on the end
self._barbican_endpoint = self._base_url.rpartition('/')[0]
sess = session.Session(auth=auth)
self._barbican_client = barbican_client.Client(
session=sess,
endpoint=self._barbican_endpoint)
self._current_context = ctxt
except Exception as e:
with excutils.save_and_reraise_exception():
LOG.error(_LE("Error creating Barbican client: %s"), e)
return self._barbican_client
def create_key(self, ctxt, expiration=None, name='Nova Compute Key',
payload_content_type='application/octet-stream', mode='CBC',
algorithm='AES', length=256):
"""Creates a key.
:param ctxt: contains information of the user and the environment
for the request (nova/context.py)
:param expiration: the date the key will expire
:param name: a friendly name for the secret
:param payload_content_type: the format/type of the secret data
:param mode: the algorithm mode (e.g. CBC or CTR mode)
:param algorithm: the algorithm associated with the secret
:param length: the bit length of the secret
:return: the UUID of the new key
:raises Exception: if key creation fails
"""
barbican_client = self._get_barbican_client(ctxt)
try:
key_order = barbican_client.orders.create_key(
name,
algorithm,
length,
mode,
payload_content_type,
expiration)
order_ref = key_order.submit()
order = barbican_client.orders.get(order_ref)
return self._retrieve_secret_uuid(order.secret_ref)
except Exception as e:
with excutils.save_and_reraise_exception():
LOG.error(_LE("Error creating key: %s"), e)
def store_key(self, ctxt, key, expiration=None, name='Nova Compute Key',
payload_content_type='application/octet-stream',
payload_content_encoding='base64', algorithm='AES',
bit_length=256, mode='CBC', from_copy=False):
"""Stores (i.e., registers) a key with the key manager.
:param ctxt: contains information of the user and the environment for
the request (nova/context.py)
:param key: the unencrypted secret data. Known as "payload" to the
barbicanclient api
:param expiration: the expiration time of the secret in ISO 8601
format
:param name: a friendly name for the key
:param payload_content_type: the format/type of the secret data
:param payload_content_encoding: the encoding of the secret data
:param algorithm: the algorithm associated with this secret key
:param bit_length: the bit length of this secret key
:param mode: the algorithm mode used with this secret key
:param from_copy: establishes whether the function is being used
to copy a key. In case of the latter, it does not
try to decode the key
:returns: the UUID of the stored key
:raises Exception: if key storage fails
"""
barbican_client = self._get_barbican_client(ctxt)
try:
if key.get_algorithm():
algorithm = key.get_algorithm()
if payload_content_type == 'text/plain':
payload_content_encoding = None
encoded_key = key.get_encoded()
elif (payload_content_type == 'application/octet-stream' and
not from_copy):
key_list = key.get_encoded()
string_key = ''.join(map(lambda byte: "%02x" % byte, key_list))
encoded_key = base64.b64encode(binascii.unhexlify(string_key))
else:
encoded_key = key.get_encoded()
secret = barbican_client.secrets.create(name,
encoded_key,
payload_content_type,
payload_content_encoding,
algorithm,
bit_length,
mode,
expiration)
secret_ref = secret.store()
return self._retrieve_secret_uuid(secret_ref)
except Exception as e:
with excutils.save_and_reraise_exception():
LOG.error(_LE("Error storing key: %s"), e)
def copy_key(self, ctxt, key_id):
"""Copies (i.e., clones) a key stored by barbican.
:param ctxt: contains information of the user and the environment for
the request (nova/context.py)
:param key_id: the UUID of the key to copy
:return: the UUID of the key copy
:raises Exception: if key copying fails
"""
try:
secret = self._get_secret(ctxt, key_id)
con_type = secret.content_types['default']
secret_data = self._get_secret_data(secret,
payload_content_type=con_type)
key = keymgr_key.SymmetricKey(secret.algorithm, secret_data)
copy_uuid = self.store_key(ctxt, key, secret.expiration,
secret.name, con_type,
'base64',
secret.algorithm, secret.bit_length,
secret.mode, True)
return copy_uuid
except Exception as e:
with excutils.save_and_reraise_exception():
LOG.error(_LE("Error copying key: %s"), e)
def _create_secret_ref(self, key_id):
"""Creates the URL required for accessing a secret.
:param key_id: the UUID of the key to copy
:return: the URL of the requested secret
"""
if not key_id:
msg = "Key ID is None"
raise exception.KeyManagerError(msg)
return self._base_url + "/secrets/" + key_id
def _retrieve_secret_uuid(self, secret_ref):
"""Retrieves the UUID of the secret from the secret_ref.
:param secret_ref: the href of the secret
:return: the UUID of the secret
"""
# The secret_ref is assumed to be of a form similar to
# http://host:9311/v1/secrets/d152fa13-2b41-42ca-a934-6c21566c0f40
# with the UUID at the end. This command retrieves everything
# after the last '/', which is the UUID.
return secret_ref.rpartition('/')[2]
def _get_secret_data(self,
secret,
payload_content_type='application/octet-stream'):
"""Retrieves the secret data given a secret and content_type.
:param ctxt: contains information of the user and the environment for
the request (nova/context.py)
:param secret: the secret from barbican with the payload of data
:param payload_content_type: the format/type of the secret data
:returns: the secret data
:raises Exception: if data cannot be retrieved
"""
try:
generated_data = secret.payload
if payload_content_type == 'application/octet-stream':
secret_data = base64.b64encode(generated_data)
else:
secret_data = generated_data
return secret_data
except Exception as e:
with excutils.save_and_reraise_exception():
LOG.error(_LE("Error getting secret data: %s"), e)
def _get_secret(self, ctxt, key_id):
"""Returns the metadata of the secret.
:param ctxt: contains information of the user and the environment for
the request (nova/context.py)
:param key_id: UUID of the secret
:return: the secret's metadata
:raises Exception: if there is an error retrieving the data
"""
barbican_client = self._get_barbican_client(ctxt)
try:
secret_ref = self._create_secret_ref(key_id)
return barbican_client.secrets.get(secret_ref)
except Exception as e:
with excutils.save_and_reraise_exception():
LOG.error(_LE("Error getting secret metadata: %s"), e)
def get_key(self, ctxt, key_id,
payload_content_type='application/octet-stream'):
"""Retrieves the specified key.
:param ctxt: contains information of the user and the environment for
the request (nova/context.py)
:param key_id: the UUID of the key to retrieve
:param payload_content_type: The format/type of the secret data
:return: SymmetricKey representation of the key
:raises Exception: if key retrieval fails
"""
try:
secret = self._get_secret(ctxt, key_id)
secret_data = self._get_secret_data(secret,
payload_content_type)
if payload_content_type == 'application/octet-stream':
# convert decoded string to list of unsigned ints for each byte
key_data = array.array('B',
base64.b64decode(secret_data)).tolist()
else:
key_data = secret_data
key = keymgr_key.SymmetricKey(secret.algorithm, key_data)
return key
except Exception as e:
with excutils.save_and_reraise_exception():
LOG.error(_LE("Error getting key: %s"), e)
def delete_key(self, ctxt, key_id):
"""Deletes the specified key.
:param ctxt: contains information of the user and the environment for
the request (nova/context.py)
:param key_id: the UUID of the key to delete
:raises Exception: if key deletion fails
"""
barbican_client = self._get_barbican_client(ctxt)
try:
secret_ref = self._create_secret_ref(key_id)
barbican_client.secrets.delete(secret_ref)
except Exception as e:
with excutils.save_and_reraise_exception():
LOG.error(_LE("Error deleting key: %s"), e)
| {
"content_hash": "cfa949f5dd6a6eed710a943560a9d681",
"timestamp": "",
"source": "github",
"line_count": 325,
"max_line_length": 79,
"avg_line_length": 40.89230769230769,
"alnum_prop": 0.5577125658389767,
"repo_name": "zhimin711/nova",
"id": "50faf8ea29af581562461c432d0302bac9b7ae7d",
"size": "13965",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "nova/keymgr/barbican.py",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Python",
"bytes": "16549579"
},
{
"name": "Shell",
"bytes": "20716"
},
{
"name": "Smarty",
"bytes": "259485"
}
],
"symlink_target": ""
} |
use BaselinePosition;
use Buildable;
use Container;
use Orientable;
use PositionType;
use Widget;
use ffi;
use glib;
use glib::StaticType;
use glib::Value;
use glib::object::Downcast;
use glib::object::IsA;
use glib::signal::SignalHandlerId;
use glib::signal::connect;
use glib::translate::*;
use glib_ffi;
use gobject_ffi;
use std::boxed::Box as Box_;
use std::mem;
use std::mem::transmute;
use std::ptr;
glib_wrapper! {
pub struct Grid(Object<ffi::GtkGrid, ffi::GtkGridClass>): Container, Widget, Buildable, Orientable;
match fn {
get_type => || ffi::gtk_grid_get_type(),
}
}
impl Grid {
pub fn new() -> Grid {
assert_initialized_main_thread!();
unsafe {
Widget::from_glib_none(ffi::gtk_grid_new()).downcast_unchecked()
}
}
}
impl Default for Grid {
fn default() -> Self {
Self::new()
}
}
pub trait GridExt {
fn attach<P: IsA<Widget>>(&self, child: &P, left: i32, top: i32, width: i32, height: i32);
fn attach_next_to<'a, P: IsA<Widget>, Q: IsA<Widget> + 'a, R: Into<Option<&'a Q>>>(&self, child: &P, sibling: R, side: PositionType, width: i32, height: i32);
#[cfg(any(feature = "v3_10", feature = "dox"))]
fn get_baseline_row(&self) -> i32;
fn get_child_at(&self, left: i32, top: i32) -> Option<Widget>;
fn get_column_homogeneous(&self) -> bool;
fn get_column_spacing(&self) -> u32;
#[cfg(any(feature = "v3_10", feature = "dox"))]
fn get_row_baseline_position(&self, row: i32) -> BaselinePosition;
fn get_row_homogeneous(&self) -> bool;
fn get_row_spacing(&self) -> u32;
fn insert_column(&self, position: i32);
fn insert_next_to<P: IsA<Widget>>(&self, sibling: &P, side: PositionType);
fn insert_row(&self, position: i32);
#[cfg(any(feature = "v3_10", feature = "dox"))]
fn remove_column(&self, position: i32);
#[cfg(any(feature = "v3_10", feature = "dox"))]
fn remove_row(&self, position: i32);
#[cfg(any(feature = "v3_10", feature = "dox"))]
fn set_baseline_row(&self, row: i32);
fn set_column_homogeneous(&self, homogeneous: bool);
fn set_column_spacing(&self, spacing: u32);
#[cfg(any(feature = "v3_10", feature = "dox"))]
fn set_row_baseline_position(&self, row: i32, pos: BaselinePosition);
fn set_row_homogeneous(&self, homogeneous: bool);
fn set_row_spacing(&self, spacing: u32);
fn get_property_baseline_row(&self) -> i32;
fn set_property_baseline_row(&self, baseline_row: i32);
fn get_cell_height<T: IsA<Widget>>(&self, item: &T) -> i32;
fn set_cell_height<T: IsA<Widget>>(&self, item: &T, height: i32);
fn get_cell_width<T: IsA<Widget>>(&self, item: &T) -> i32;
fn set_cell_width<T: IsA<Widget>>(&self, item: &T, width: i32);
fn get_cell_left_attach<T: IsA<Widget>>(&self, item: &T) -> i32;
fn set_cell_left_attach<T: IsA<Widget>>(&self, item: &T, left_attach: i32);
fn get_cell_top_attach<T: IsA<Widget>>(&self, item: &T) -> i32;
fn set_cell_top_attach<T: IsA<Widget>>(&self, item: &T, top_attach: i32);
fn connect_property_baseline_row_notify<F: Fn(&Self) + 'static>(&self, f: F) -> SignalHandlerId;
fn connect_property_column_homogeneous_notify<F: Fn(&Self) + 'static>(&self, f: F) -> SignalHandlerId;
fn connect_property_column_spacing_notify<F: Fn(&Self) + 'static>(&self, f: F) -> SignalHandlerId;
fn connect_property_row_homogeneous_notify<F: Fn(&Self) + 'static>(&self, f: F) -> SignalHandlerId;
fn connect_property_row_spacing_notify<F: Fn(&Self) + 'static>(&self, f: F) -> SignalHandlerId;
}
impl<O: IsA<Grid> + IsA<Container> + IsA<glib::object::Object>> GridExt for O {
fn attach<P: IsA<Widget>>(&self, child: &P, left: i32, top: i32, width: i32, height: i32) {
unsafe {
ffi::gtk_grid_attach(self.to_glib_none().0, child.to_glib_none().0, left, top, width, height);
}
}
fn attach_next_to<'a, P: IsA<Widget>, Q: IsA<Widget> + 'a, R: Into<Option<&'a Q>>>(&self, child: &P, sibling: R, side: PositionType, width: i32, height: i32) {
let sibling = sibling.into();
let sibling = sibling.to_glib_none();
unsafe {
ffi::gtk_grid_attach_next_to(self.to_glib_none().0, child.to_glib_none().0, sibling.0, side.to_glib(), width, height);
}
}
#[cfg(any(feature = "v3_10", feature = "dox"))]
fn get_baseline_row(&self) -> i32 {
unsafe {
ffi::gtk_grid_get_baseline_row(self.to_glib_none().0)
}
}
fn get_child_at(&self, left: i32, top: i32) -> Option<Widget> {
unsafe {
from_glib_none(ffi::gtk_grid_get_child_at(self.to_glib_none().0, left, top))
}
}
fn get_column_homogeneous(&self) -> bool {
unsafe {
from_glib(ffi::gtk_grid_get_column_homogeneous(self.to_glib_none().0))
}
}
fn get_column_spacing(&self) -> u32 {
unsafe {
ffi::gtk_grid_get_column_spacing(self.to_glib_none().0)
}
}
#[cfg(any(feature = "v3_10", feature = "dox"))]
fn get_row_baseline_position(&self, row: i32) -> BaselinePosition {
unsafe {
from_glib(ffi::gtk_grid_get_row_baseline_position(self.to_glib_none().0, row))
}
}
fn get_row_homogeneous(&self) -> bool {
unsafe {
from_glib(ffi::gtk_grid_get_row_homogeneous(self.to_glib_none().0))
}
}
fn get_row_spacing(&self) -> u32 {
unsafe {
ffi::gtk_grid_get_row_spacing(self.to_glib_none().0)
}
}
fn insert_column(&self, position: i32) {
unsafe {
ffi::gtk_grid_insert_column(self.to_glib_none().0, position);
}
}
fn insert_next_to<P: IsA<Widget>>(&self, sibling: &P, side: PositionType) {
unsafe {
ffi::gtk_grid_insert_next_to(self.to_glib_none().0, sibling.to_glib_none().0, side.to_glib());
}
}
fn insert_row(&self, position: i32) {
unsafe {
ffi::gtk_grid_insert_row(self.to_glib_none().0, position);
}
}
#[cfg(any(feature = "v3_10", feature = "dox"))]
fn remove_column(&self, position: i32) {
unsafe {
ffi::gtk_grid_remove_column(self.to_glib_none().0, position);
}
}
#[cfg(any(feature = "v3_10", feature = "dox"))]
fn remove_row(&self, position: i32) {
unsafe {
ffi::gtk_grid_remove_row(self.to_glib_none().0, position);
}
}
#[cfg(any(feature = "v3_10", feature = "dox"))]
fn set_baseline_row(&self, row: i32) {
unsafe {
ffi::gtk_grid_set_baseline_row(self.to_glib_none().0, row);
}
}
fn set_column_homogeneous(&self, homogeneous: bool) {
unsafe {
ffi::gtk_grid_set_column_homogeneous(self.to_glib_none().0, homogeneous.to_glib());
}
}
fn set_column_spacing(&self, spacing: u32) {
unsafe {
ffi::gtk_grid_set_column_spacing(self.to_glib_none().0, spacing);
}
}
#[cfg(any(feature = "v3_10", feature = "dox"))]
fn set_row_baseline_position(&self, row: i32, pos: BaselinePosition) {
unsafe {
ffi::gtk_grid_set_row_baseline_position(self.to_glib_none().0, row, pos.to_glib());
}
}
fn set_row_homogeneous(&self, homogeneous: bool) {
unsafe {
ffi::gtk_grid_set_row_homogeneous(self.to_glib_none().0, homogeneous.to_glib());
}
}
fn set_row_spacing(&self, spacing: u32) {
unsafe {
ffi::gtk_grid_set_row_spacing(self.to_glib_none().0, spacing);
}
}
fn get_property_baseline_row(&self) -> i32 {
unsafe {
let mut value = Value::from_type(<i32 as StaticType>::static_type());
gobject_ffi::g_object_get_property(self.to_glib_none().0, "baseline-row".to_glib_none().0, value.to_glib_none_mut().0);
value.get().unwrap()
}
}
fn set_property_baseline_row(&self, baseline_row: i32) {
unsafe {
gobject_ffi::g_object_set_property(self.to_glib_none().0, "baseline-row".to_glib_none().0, Value::from(&baseline_row).to_glib_none().0);
}
}
fn get_cell_height<T: IsA<Widget>>(&self, item: &T) -> i32 {
unsafe {
let mut value = Value::from_type(<i32 as StaticType>::static_type());
ffi::gtk_container_child_get_property(self.to_glib_none().0, item.to_glib_none().0, "height".to_glib_none().0, value.to_glib_none_mut().0);
value.get().unwrap()
}
}
fn set_cell_height<T: IsA<Widget>>(&self, item: &T, height: i32) {
unsafe {
ffi::gtk_container_child_set_property(self.to_glib_none().0, item.to_glib_none().0, "height".to_glib_none().0, Value::from(&height).to_glib_none().0);
}
}
fn get_cell_width<T: IsA<Widget>>(&self, item: &T) -> i32 {
unsafe {
let mut value = Value::from_type(<i32 as StaticType>::static_type());
ffi::gtk_container_child_get_property(self.to_glib_none().0, item.to_glib_none().0, "width".to_glib_none().0, value.to_glib_none_mut().0);
value.get().unwrap()
}
}
fn set_cell_width<T: IsA<Widget>>(&self, item: &T, width: i32) {
unsafe {
ffi::gtk_container_child_set_property(self.to_glib_none().0, item.to_glib_none().0, "width".to_glib_none().0, Value::from(&width).to_glib_none().0);
}
}
fn get_cell_left_attach<T: IsA<Widget>>(&self, item: &T) -> i32 {
unsafe {
let mut value = Value::from_type(<i32 as StaticType>::static_type());
ffi::gtk_container_child_get_property(self.to_glib_none().0, item.to_glib_none().0, "left-attach".to_glib_none().0, value.to_glib_none_mut().0);
value.get().unwrap()
}
}
fn set_cell_left_attach<T: IsA<Widget>>(&self, item: &T, left_attach: i32) {
unsafe {
ffi::gtk_container_child_set_property(self.to_glib_none().0, item.to_glib_none().0, "left-attach".to_glib_none().0, Value::from(&left_attach).to_glib_none().0);
}
}
fn get_cell_top_attach<T: IsA<Widget>>(&self, item: &T) -> i32 {
unsafe {
let mut value = Value::from_type(<i32 as StaticType>::static_type());
ffi::gtk_container_child_get_property(self.to_glib_none().0, item.to_glib_none().0, "top-attach".to_glib_none().0, value.to_glib_none_mut().0);
value.get().unwrap()
}
}
fn set_cell_top_attach<T: IsA<Widget>>(&self, item: &T, top_attach: i32) {
unsafe {
ffi::gtk_container_child_set_property(self.to_glib_none().0, item.to_glib_none().0, "top-attach".to_glib_none().0, Value::from(&top_attach).to_glib_none().0);
}
}
fn connect_property_baseline_row_notify<F: Fn(&Self) + 'static>(&self, f: F) -> SignalHandlerId {
unsafe {
let f: Box_<Box_<Fn(&Self) + 'static>> = Box_::new(Box_::new(f));
connect(self.to_glib_none().0, "notify::baseline-row",
transmute(notify_baseline_row_trampoline::<Self> as usize), Box_::into_raw(f) as *mut _)
}
}
fn connect_property_column_homogeneous_notify<F: Fn(&Self) + 'static>(&self, f: F) -> SignalHandlerId {
unsafe {
let f: Box_<Box_<Fn(&Self) + 'static>> = Box_::new(Box_::new(f));
connect(self.to_glib_none().0, "notify::column-homogeneous",
transmute(notify_column_homogeneous_trampoline::<Self> as usize), Box_::into_raw(f) as *mut _)
}
}
fn connect_property_column_spacing_notify<F: Fn(&Self) + 'static>(&self, f: F) -> SignalHandlerId {
unsafe {
let f: Box_<Box_<Fn(&Self) + 'static>> = Box_::new(Box_::new(f));
connect(self.to_glib_none().0, "notify::column-spacing",
transmute(notify_column_spacing_trampoline::<Self> as usize), Box_::into_raw(f) as *mut _)
}
}
fn connect_property_row_homogeneous_notify<F: Fn(&Self) + 'static>(&self, f: F) -> SignalHandlerId {
unsafe {
let f: Box_<Box_<Fn(&Self) + 'static>> = Box_::new(Box_::new(f));
connect(self.to_glib_none().0, "notify::row-homogeneous",
transmute(notify_row_homogeneous_trampoline::<Self> as usize), Box_::into_raw(f) as *mut _)
}
}
fn connect_property_row_spacing_notify<F: Fn(&Self) + 'static>(&self, f: F) -> SignalHandlerId {
unsafe {
let f: Box_<Box_<Fn(&Self) + 'static>> = Box_::new(Box_::new(f));
connect(self.to_glib_none().0, "notify::row-spacing",
transmute(notify_row_spacing_trampoline::<Self> as usize), Box_::into_raw(f) as *mut _)
}
}
}
unsafe extern "C" fn notify_baseline_row_trampoline<P>(this: *mut ffi::GtkGrid, _param_spec: glib_ffi::gpointer, f: glib_ffi::gpointer)
where P: IsA<Grid> {
let f: &&(Fn(&P) + 'static) = transmute(f);
f(&Grid::from_glib_borrow(this).downcast_unchecked())
}
unsafe extern "C" fn notify_column_homogeneous_trampoline<P>(this: *mut ffi::GtkGrid, _param_spec: glib_ffi::gpointer, f: glib_ffi::gpointer)
where P: IsA<Grid> {
let f: &&(Fn(&P) + 'static) = transmute(f);
f(&Grid::from_glib_borrow(this).downcast_unchecked())
}
unsafe extern "C" fn notify_column_spacing_trampoline<P>(this: *mut ffi::GtkGrid, _param_spec: glib_ffi::gpointer, f: glib_ffi::gpointer)
where P: IsA<Grid> {
let f: &&(Fn(&P) + 'static) = transmute(f);
f(&Grid::from_glib_borrow(this).downcast_unchecked())
}
unsafe extern "C" fn notify_row_homogeneous_trampoline<P>(this: *mut ffi::GtkGrid, _param_spec: glib_ffi::gpointer, f: glib_ffi::gpointer)
where P: IsA<Grid> {
let f: &&(Fn(&P) + 'static) = transmute(f);
f(&Grid::from_glib_borrow(this).downcast_unchecked())
}
unsafe extern "C" fn notify_row_spacing_trampoline<P>(this: *mut ffi::GtkGrid, _param_spec: glib_ffi::gpointer, f: glib_ffi::gpointer)
where P: IsA<Grid> {
let f: &&(Fn(&P) + 'static) = transmute(f);
f(&Grid::from_glib_borrow(this).downcast_unchecked())
}
| {
"content_hash": "af63da6b9796a9298b73ee62c07cc3d1",
"timestamp": "",
"source": "github",
"line_count": 392,
"max_line_length": 172,
"avg_line_length": 35.954081632653065,
"alnum_prop": 0.581311196253725,
"repo_name": "EPashkin/rust-gnome-gtk",
"id": "0c3c03ffaeb360c4d3008d482549944085f44bf2",
"size": "14280",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "src/auto/grid.rs",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Makefile",
"bytes": "452"
},
{
"name": "Rust",
"bytes": "1521443"
},
{
"name": "Shell",
"bytes": "558"
}
],
"symlink_target": ""
} |
// $Id: xxRareModeSavePrompts.cc 4497 2012-05-27 00:33:09Z flaterco $
#include "xtide.hh"
#include "xxHorizDialog.hh"
#include "xxMultiChoice.hh"
#include "xxTimestampDialog.hh"
#include "xxTimestamp.hh"
#include "xxRareModeSavePrompts.hh"
#include "xxTextMode.hh"
static void xxRareModeSavePromptsCallback (
Widget w unusedParameter,
XtPointer client_data,
XtPointer call_data unusedParameter) {
assert (client_data);
xxRareModeSavePrompts *prompts ((xxRareModeSavePrompts *)client_data);
prompts->callback();
delete prompts->dismiss();
}
void xxRareModeSavePrompts::callback() {
Dstr filename (filenameDiag->val());
if (filename.strchr ('\n') != -1 ||
filename.strchr ('\r') != -1 ||
filename.strchr (' ') != -1 ||
filename[0] == '-') {
Dstr details ("Well, it's not that I can't do it, it's that you probably\n\
don't want me to. The filename that you entered is '");
details += filename;
details += "'.\n";
if (filename[0] == '-')
details += "Filenames that begin with a dash are considered harmful.";
else
details += "Whitespace in filenames is considered harmful.";
Global::barf (Error::CANT_OPEN_FILE, details, Error::nonfatal);
} else {
Dstr startTimeString, endTimeString;
beginTimeDiag->val (startTimeString);
Timestamp startTime (startTimeString, _timezone);
endTimeDiag->val (endTimeString);
Timestamp endTime (endTimeString, _timezone);
if (startTime.isNull())
Global::cant_mktime (startTimeString, _timezone, Error::nonfatal);
else if (endTime.isNull())
Global::cant_mktime (endTimeString, _timezone, Error::nonfatal);
else {
if (startTime <= endTime)
_caller.save (filename, startTime, endTime);
else
_caller.save (filename, endTime, startTime);
}
}
}
static void xxRareModeSavePromptsCancelCallback (
Widget w unusedParameter,
XtPointer client_data,
XtPointer call_data unusedParameter) {
assert (client_data);
delete ((xxRareModeSavePrompts *)client_data)->dismiss();
}
xxRareModeSavePrompts::~xxRareModeSavePrompts() {
unrealize();
_caller.noClose = false;
}
xxRareModeSavePrompts::xxRareModeSavePrompts (const xxWidget &parent,
xxTextMode &caller,
constString initFilename,
Timestamp initStartTime,
Timestamp initEndTime,
const Dstr &timezone):
xxWindow (parent, boxContainer, XtGrabExclusive),
_caller(caller),
_timezone(timezone) {
_caller.noClose = true;
setTitle ("Save prompts");
Arg labelArgs[3] = {
{XtNbackground, (XtArgVal)xxX::pixels[Colors::background]},
{XtNforeground, (XtArgVal)xxX::pixels[Colors::foreground]},
{XtNborderWidth, (XtArgVal)0}
};
Arg buttonArgs[4] = {
{XtNvisual, (XtArgVal)xxX::visual},
{XtNcolormap, (XtArgVal)xxX::colormap},
{XtNbackground, (XtArgVal)xxX::pixels[Colors::button]},
{XtNforeground, (XtArgVal)xxX::pixels[Colors::foreground]}
};
{
Dstr helptext ("\
Please enter the name of the file in which to save output.\n\
You can also change the begin and end times for the listing.\n\
The active time zone is ");
if (Global::settings["z"].c == 'n')
helptext += _timezone;
else
helptext += "UTC0";
helptext += ".";
Widget labelWidget = xxX::createXtWidget (helptext.aschar(),
labelWidgetClass, container->widget(), labelArgs, 3);
helpLabel = xxX::wrap (labelWidget);
}
filenameDiag = std::auto_ptr<xxHorizDialog> (new xxHorizDialog (
*container,
"Filename:",
initFilename));
beginTimeDiag = std::auto_ptr<xxTimestampDialog> (new xxTimestampDialog (
*container,
"Start at:",
initStartTime,
_timezone));
endTimeDiag = std::auto_ptr<xxTimestampDialog> (new xxTimestampDialog (
*container,
"End at:",
initEndTime,
_timezone));
{
Widget labelWidget = xxX::createXtWidget (" ", labelWidgetClass,
container->widget(), labelArgs, 3);
spaceLabel = xxX::wrap (labelWidget);
}{
Widget buttonWidget = xxX::createXtWidget ("Go", commandWidgetClass,
container->widget(), buttonArgs, 4);
XtAddCallback (buttonWidget, XtNcallback, xxRareModeSavePromptsCallback,
(XtPointer)this);
goButton = xxX::wrap (buttonWidget);
}{
Widget buttonWidget = xxX::createXtWidget ("Cancel", commandWidgetClass,
container->widget(), buttonArgs, 4);
XtAddCallback (buttonWidget, XtNcallback,
xxRareModeSavePromptsCancelCallback, (XtPointer)this);
cancelButton = xxX::wrap (buttonWidget);
}
realize();
}
// Cleanup2006 Done
| {
"content_hash": "ba0c60bc8c8a2da501b748e1bba891fe",
"timestamp": "",
"source": "github",
"line_count": 151,
"max_line_length": 79,
"avg_line_length": 33.88741721854305,
"alnum_prop": 0.6068008598788353,
"repo_name": "lobrien/TideMonkey",
"id": "9f4e2cbd1a2bca45d44dc36d8724a03749be3b25",
"size": "5955",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "Xtide/xtide-2.14/xxRareModeSavePrompts.cc",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Batchfile",
"bytes": "2631"
},
{
"name": "C",
"bytes": "240611"
},
{
"name": "C++",
"bytes": "1480817"
},
{
"name": "F#",
"bytes": "106029"
},
{
"name": "Groff",
"bytes": "25157"
},
{
"name": "HTML",
"bytes": "65324"
},
{
"name": "Hack",
"bytes": "21484"
},
{
"name": "LLVM",
"bytes": "2414"
},
{
"name": "M4",
"bytes": "24814"
},
{
"name": "Makefile",
"bytes": "142677"
},
{
"name": "Shell",
"bytes": "669911"
},
{
"name": "Yacc",
"bytes": "3745"
}
],
"symlink_target": ""
} |
<ul class="nav nav-pills nav-stacked">
<li><a href="http://news.baidu.com" target="navTab" data-tabid="external"><i class="icon-file"></i>url页面</a></li>
<li><a href="newpage_2.html" target="navTab" data-tabid="iframe" data-external="true"><i class="icon-file"></i>iframe页面</a></li>
<li><a href="newpage_1.html" target="navTab" data-tabid="page1"><i class="icon-file"></i>页面1</a></li>
<li><a href="newpage_3.html" target="navTab" data-tabid="page2"><i class="icon-file"></i>页面2</a></li>
</ul> | {
"content_hash": "4f3fbb7bda9993b4509c11b840afd8a2",
"timestamp": "",
"source": "github",
"line_count": 7,
"max_line_length": 129,
"avg_line_length": 70.85714285714286,
"alnum_prop": 0.655241935483871,
"repo_name": "ruoyousi/js-spa",
"id": "51b22270474bccb3ccc1ec3d1971c75a732250dc",
"size": "512",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "client/sidebar_3.html",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Batchfile",
"bytes": "3023"
},
{
"name": "CSS",
"bytes": "54370"
},
{
"name": "HTML",
"bytes": "39543"
},
{
"name": "JavaScript",
"bytes": "241077"
}
],
"symlink_target": ""
} |
Safe Integer
===
[![NPM version][npm-image]][npm-url] [![Build Status][travis-image]][travis-url] [![Coverage Status][coveralls-image]][coveralls-url] [![Dependencies][dependencies-image]][dependencies-url]
> Validates if a value is a [safe integer](http://www.2ality.com/2013/10/safe-integers.html).
## Installation
``` bash
$ npm install validate.io-safe-integer
```
For use in the browser, use [browserify](https://github.com/substack/node-browserify).
## Usage
``` javascript
var isSafeInteger = require( 'validate.io-safe-integer' );
```
#### isSafeInteger( value )
Validates if a value is a [safe integer](http://www.2ality.com/2013/10/safe-integers.html).
``` javascript
var bool = isSafeInteger( 3 );
// returns true
bool = isSafeInteger( Math.pow( 2, 53 ) - 1 );
// returns true
```
## Examples
``` javascript
var isSafeInteger = require( 'validate.io-safe-integer' );
console.log( isSafeInteger( 3 ) );
// returns true
console.log( isSafeInteger( 3.0 ) );
// returns true
console.log( isSafeInteger( Math.pow( 2, 53 ) - 1 ) );
// returns true
console.log( isSafeInteger( 3.1 ) );
// returns false
console.log( isSafeInteger( Math.pow( 2, 53 ) ) );
// returns false
console.log( isSafeInteger( NaN ) );
// returns false
console.log( isSafeInteger( Number.POSITIVE_INFINITY ) );
// returns false
console.log( isSafeInteger( new Number( 3 ) ) );
// returns false
console.log( isSafeInteger( '3' ) );
// returns false
```
To run the example code from the top-level application directory,
``` bash
$ node ./examples/index.js
```
## Tests
### Unit
Unit tests use the [Mocha](http://mochajs.org) test framework with [Chai](http://chaijs.com) assertions. To run the tests, execute the following command in the top-level application directory:
``` bash
$ make test
```
All new feature development should have corresponding unit tests to validate correct functionality.
### Test Coverage
This repository uses [Istanbul](https://github.com/gotwarlost/istanbul) as its code coverage tool. To generate a test coverage report, execute the following command in the top-level application directory:
``` bash
$ make test-cov
```
Istanbul creates a `./reports/coverage` directory. To access an HTML version of the report,
``` bash
$ make view-cov
```
---
## License
[MIT license](http://opensource.org/licenses/MIT).
## Copyright
Copyright © 2015. Athan Reines.
[npm-image]: http://img.shields.io/npm/v/validate.io-safe-integer.svg
[npm-url]: https://npmjs.org/package/validate.io-safe-integer
[travis-image]: http://img.shields.io/travis/validate-io/safe-integer/master.svg
[travis-url]: https://travis-ci.org/validate-io/safe-integer
[coveralls-image]: https://img.shields.io/coveralls/validate-io/safe-integer/master.svg
[coveralls-url]: https://coveralls.io/r/validate-io/safe-integer?branch=master
[dependencies-image]: http://img.shields.io/david/validate-io/safe-integer.svg
[dependencies-url]: https://david-dm.org/validate-io/safe-integer
[dev-dependencies-image]: http://img.shields.io/david/dev/validate-io/safe-integer.svg
[dev-dependencies-url]: https://david-dm.org/dev/validate-io/safe-integer
[github-issues-image]: http://img.shields.io/github/issues/validate-io/safe-integer.svg
[github-issues-url]: https://github.com/validate-io/safe-integer/issues
| {
"content_hash": "e8eba76ead458286596543a1cb55bda7",
"timestamp": "",
"source": "github",
"line_count": 131,
"max_line_length": 204,
"avg_line_length": 25.328244274809162,
"alnum_prop": 0.7221217600964437,
"repo_name": "validate-io/safe-integer",
"id": "687ea8b9f2f2a3d84f2e66d503ea815d7780b986",
"size": "3318",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "README.md",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "JavaScript",
"bytes": "3231"
},
{
"name": "Makefile",
"bytes": "1896"
}
],
"symlink_target": ""
} |
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<LinearLayout
android:id="@+id/zoneViewLayout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginBottom="@dimen/resourceStateViewMarginBottom"
android:layout_toLeftOf="@+id/zoneStateText"
android:layout_toStartOf="@+id/zoneStateText"
android:background="@drawable/border"
android:orientation="vertical" />
<TextView
android:id="@+id/zoneStateText"
android:layout_width="@dimen/resourceStateViewWidth"
android:layout_height="match_parent"
android:layout_alignParentEnd="true"
android:layout_alignParentRight="true"
android:layout_alignParentTop="true"
android:layout_marginBottom="@dimen/resourceStateViewMarginBottom" />
</RelativeLayout> | {
"content_hash": "67256a641433580fc11d246db174d979",
"timestamp": "",
"source": "github",
"line_count": 24,
"max_line_length": 77,
"avg_line_length": 40.458333333333336,
"alnum_prop": 0.6992790937178167,
"repo_name": "lukacsd/aws-scheme",
"id": "f66901198f60482776354b03176dad03e38ead01",
"size": "971",
"binary": false,
"copies": "1",
"ref": "refs/heads/main",
"path": "res/layout/zone_view.xml",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Java",
"bytes": "133576"
}
],
"symlink_target": ""
} |
package light
import (
"fmt"
"github.com/tmacychen/UFG/font"
"github.com/tmacychen/UFG/framework"
"github.com/tmacychen/UFG/theme/basic"
"github.com/tmacychen/UFG/widget/tools"
)
func CreateTheme(driver framework.Driver) framework.Theme {
defaultFont, err := font.CreateFont(font.Default, 12)
if err == nil {
defaultFont.LoadGlyphs(32, 126)
} else {
fmt.Printf("Warning: Failed to load default font - %v\n", err)
}
defaultMonospaceFont, err := font.CreateFont(font.Monospace, 12)
if err == nil {
defaultFont.LoadGlyphs(32, 126)
} else {
fmt.Printf("Warning: Failed to load default monospace font - %v\n", err)
}
scrollBarRailDefaultBg := tools.Black
scrollBarRailDefaultBg.A = 0.7
scrollBarRailOverBg := tools.Gray20
scrollBarRailOverBg.A = 0.7
neonBlue := tools.ColorFromHex(0xFF5C8CFF)
focus := tools.ColorFromHex(0xFFC4D6FF)
return &basic.Theme{
DriverInfo: driver,
DefaultFontInfo: defaultFont,
DefaultMonospaceFontInfo: defaultMonospaceFont,
WindowBackground: tools.White,
// fontColor brushColor penColor
BubbleOverlayStyle: basic.CreateStyle(tools.Gray40, tools.Gray20, tools.Gray40, 1.0),
ButtonDefaultStyle: basic.CreateStyle(tools.Gray40, tools.White, tools.Gray40, 1.0),
ButtonOverStyle: basic.CreateStyle(tools.Gray40, tools.Gray90, tools.Gray40, 1.0),
ButtonPressedStyle: basic.CreateStyle(tools.Gray20, tools.Gray70, tools.Gray30, 1.0),
CodeSuggestionListStyle: basic.CreateStyle(tools.Gray40, tools.Gray20, tools.Gray10, 1.0),
DropDownListDefaultStyle: basic.CreateStyle(tools.Gray40, tools.White, tools.Gray20, 1.0),
DropDownListOverStyle: basic.CreateStyle(tools.Gray40, tools.Gray90, tools.Gray50, 1.0),
FocusedStyle: basic.CreateStyle(tools.Gray20, tools.Transparent, focus, 1.0),
HighlightStyle: basic.CreateStyle(tools.Gray40, tools.Transparent, neonBlue, 2.0),
LabelStyle: basic.CreateStyle(tools.Gray40, tools.Transparent, tools.Transparent, 0.0),
PanelBackgroundStyle: basic.CreateStyle(tools.Gray40, tools.White, tools.Gray15, 1.0),
ScrollBarBarDefaultStyle: basic.CreateStyle(tools.Gray40, tools.Gray30, tools.Gray40, 1.0),
ScrollBarBarOverStyle: basic.CreateStyle(tools.Gray40, tools.Gray50, tools.Gray60, 1.0),
ScrollBarRailDefaultStyle: basic.CreateStyle(tools.Gray40, scrollBarRailDefaultBg, tools.Transparent, 1.0),
ScrollBarRailOverStyle: basic.CreateStyle(tools.Gray40, scrollBarRailOverBg, tools.Gray20, 1.0),
SplitterBarDefaultStyle: basic.CreateStyle(tools.Gray40, tools.Gray80, tools.Gray40, 1.0),
SplitterBarOverStyle: basic.CreateStyle(tools.Gray40, tools.Gray80, tools.Gray50, 1.0),
TabActiveHighlightStyle: basic.CreateStyle(tools.Gray30, neonBlue, neonBlue, 0.0),
TabDefaultStyle: basic.CreateStyle(tools.Gray40, tools.White, tools.Gray40, 1.0),
TabOverStyle: basic.CreateStyle(tools.Gray30, tools.Gray90, tools.Gray50, 1.0),
TabPressedStyle: basic.CreateStyle(tools.Gray20, tools.Gray70, tools.Gray30, 1.0),
TextBoxDefaultStyle: basic.CreateStyle(tools.Gray40, tools.White, tools.Gray20, 1.0),
TextBoxOverStyle: basic.CreateStyle(tools.Gray40, tools.White, tools.Gray50, 1.0),
}
}
| {
"content_hash": "dfa39ea88209cab1b9d91254ff06694b",
"timestamp": "",
"source": "github",
"line_count": 67,
"max_line_length": 109,
"avg_line_length": 49.88059701492537,
"alnum_prop": 0.7211250748055057,
"repo_name": "tmacychen/UFG",
"id": "85bef2e437249cdd334fa9acc2dc5681cc67be56",
"size": "3502",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "theme/light/light.go",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "Go",
"bytes": "1203451"
}
],
"symlink_target": ""
} |
package edu.northwestern.bioinformatics.studycalendar.service.presenter;
import edu.northwestern.bioinformatics.studycalendar.StudyCalendarSystemException;
import org.restlet.routing.Template;
import org.springframework.util.StringUtils;
import java.util.HashMap;
import java.util.Map;
/**
* @author Rhett Sutphin
*/
public class WorkflowMessage {
public static final String MESSAGE_TEMPLATE_VARIABLE_ACTION = "action";
private WorkflowStep step;
private Map<String, String> uriTemplateValues, messageTemplateValues;
private String applicationMountPoint;
private boolean mayPerform;
public WorkflowMessage(
WorkflowStep step, String applicationMountPoint, boolean mayPerform
) {
this.step = step;
this.applicationMountPoint = applicationMountPoint;
this.mayPerform = mayPerform;
uriTemplateValues = new HashMap<String, String>();
messageTemplateValues = new HashMap<String, String>();
}
public boolean getMayPerform() {
return mayPerform;
}
public String getHtml() {
String actionHtml = getMayPerform() ? getActionLink() : step.getActionPhrase();
Map<String, String> messageVariableValues = new HashMap<String, String>(messageTemplateValues);
messageVariableValues.put(MESSAGE_TEMPLATE_VARIABLE_ACTION, actionHtml);
StringBuilder html = new StringBuilder().append(stepMessage(messageVariableValues));
if (!getMayPerform()) {
html.append(" A <em>").append(step.getNecessaryRole().getDisplayName()).append("</em> can do this.");
}
return html.toString();
}
public String getText() {
Map<String, String> messageVariableValues = new HashMap<String, String>(messageTemplateValues);
messageVariableValues.put(MESSAGE_TEMPLATE_VARIABLE_ACTION, step.getActionPhrase());
StringBuilder text = new StringBuilder().append(stepMessage(messageVariableValues));
if (getMayPerform()) {
text.append(" You can do this.");
} else {
text.append(" A ").append(step.getNecessaryRole().getDisplayName()).append(" can do this.");
}
return text.toString();
}
public WorkflowMessage setUriVariable(String name, String value) {
uriTemplateValues.put(name, value);
return this;
}
public WorkflowMessage setMessageVariable(String name, String value) {
messageTemplateValues.put(name, value);
return this;
}
public String getActionLink() {
if (step.getUriTemplate() == null) {
return step.getActionPhrase();
} else {
return String.format("<a href=\"%s\" class=\"control\">%s</a>",
getUri(), step.getActionPhrase());
}
}
public String getUri() {
verifyTemplateVariablesAvailable(step.getUriTemplate(), uriTemplateValues);
StringBuilder uri = new StringBuilder();
if (StringUtils.hasText(applicationMountPoint)) {
uri.append(applicationMountPoint);
if (uri.charAt(uri.length() - 1) == '/') {
uri.deleteCharAt(uri.length() - 1);
}
}
return uri.append(step.getUriTemplate().format(uriTemplateValues)).toString();
}
private String stepMessage(Map<String, String> messageVariableValues) {
verifyTemplateVariablesAvailable(step.getMessageTemplate(), messageVariableValues);
return step.getMessageTemplate().format(messageVariableValues);
}
private void verifyTemplateVariablesAvailable(Template template, Map<String, String> values) {
for (String v : template.getVariableNames()) {
if (!values.keySet().contains(v)) {
throw new StudyCalendarSystemException(
"Missing %s variable value for workflow message", v);
}
}
}
public WorkflowStep getStep() {
return step;
}
////// OBJECT METHODS
@Override
public String toString() {
return new StringBuilder(getClass().getSimpleName()).
append("[step=").append(getStep()).
append("; mayPerform=").append(getMayPerform()).
append("]").toString();
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof WorkflowMessage)) return false;
WorkflowMessage that = (WorkflowMessage) o;
if (step != null ? !step.equals(that.step) : that.step != null) return false;
if (applicationMountPoint != null ? !applicationMountPoint.equals(that.applicationMountPoint) : that.applicationMountPoint != null) return false;
if (mayPerform != that.mayPerform) return false;
if (uriTemplateValues != null ? !uriTemplateValues.equals(that.uriTemplateValues) : that.uriTemplateValues != null) return false;
if (messageTemplateValues != null ? !messageTemplateValues .equals(that.messageTemplateValues ) : that.messageTemplateValues != null) return false;
return true;
}
@Override
public int hashCode() {
int result = step != null ? step.hashCode() : 0;
result = 31 * result + (applicationMountPoint != null ? applicationMountPoint.hashCode() : 0);
result = 31 * result + (mayPerform ? 1 : 0);
result = 31 * result + (uriTemplateValues != null ? uriTemplateValues .hashCode() : 0);
result = 31 * result + (messageTemplateValues != null ? messageTemplateValues .hashCode() : 0);
return result;
}
}
| {
"content_hash": "8a55b1bc9ef189294273e8a4a56a748d",
"timestamp": "",
"source": "github",
"line_count": 149,
"max_line_length": 155,
"avg_line_length": 37.281879194630875,
"alnum_prop": 0.6531053105310531,
"repo_name": "NCIP/psc",
"id": "fd1dc1b37656d2a107db5371f5292a2be70d6907",
"size": "5721",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "core/src/main/java/edu/northwestern/bioinformatics/studycalendar/service/presenter/WorkflowMessage.java",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "Groovy",
"bytes": "169396"
},
{
"name": "Java",
"bytes": "6565287"
},
{
"name": "JavaScript",
"bytes": "809902"
},
{
"name": "Ruby",
"bytes": "381123"
},
{
"name": "Shell",
"bytes": "364"
},
{
"name": "XML",
"bytes": "227992"
}
],
"symlink_target": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.