text stringlengths 2 1.04M | meta dict |
|---|---|
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">
<solid android:color="#DFDFDF" />
<corners android:topLeftRadius="4dp"
android:topRightRadius="4dp"
android:bottomRightRadius="4dp"
android:bottomLeftRadius="4dp"/>
</shape> | {
"content_hash": "e3253b5f5d8f5bd6b6ddc6f13c5ed672",
"timestamp": "",
"source": "github",
"line_count": 8,
"max_line_length": 66,
"avg_line_length": 40.75,
"alnum_prop": 0.6441717791411042,
"repo_name": "miaoxw/HandyMuseum_Mobile",
"id": "beaed78c6d5625ba48ce6cdc46123c64b5fd9ee1",
"size": "326",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "app/src/main/res/drawable/description_bg.xml",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Java",
"bytes": "15272"
}
],
"symlink_target": ""
} |
<style type="text/css">
.tabContent {
overflow-y: auto;
}
.analyze-sub-header
{
font-size:1.3em;
margin-bottom: 4px;
margin-top: 4px;
}
.analyze-descriptor
{
/*margin-left: 16px;*/
width: 50%;
max-width:240px;
float:left;
clear: left;
font-weight: bold;
}
.frequency-descriptor
{
/*margin-left: 260px;*/
width:50%;
max-width:240px;
float:left;
clear: left;
font-style: italic;
font-weight: bold;
}
.analyze-value
{
float: left;
margin-bottom: 12px;
}
.analyze-search md-icon
{
font-size:35px;
color: #607d8b;
}
.analyzeControlPanel {
background-color: #EAEAEA;
width: 330px;
overflow-y: auto;
}
.analyzeControlPanelContent {
}
.analyzePanel {
overflow-y: auto;
background-color: #FAFAFA;
border-left: solid 1px #DDDDDD;
border-bottom: solid 1px #DDDDDD;
}
.panelTitle {
background-color: #AAAAAA;
color: white;
height: 20px;
line-height: 20px;
font-size: 0.9em;
padding-left: 10px;
font-weight: 500;
}
.bottomBar {
position: fixed;
left: 0;
bottom: 0;
}
</style>
<div class="statusBarToggle bottomBar pointer" ng-click="showSidebar = !showSidebar">
<md-icon md-font-set="material-icons" ng-show="!showSidebar" class="inspectorIcon"> exit_to_app </md-icon>
<md-icon md-font-set="material-icons" ng-show="showSidebar" class="inspectorIcon" style="transform: scaleX(-1);"> exit_to_app </md-icon>
<span ng-show="!showSidebar">Show Toolbar</span>
<span ng-show="showSidebar">Hide Toolbar</span>
</div>
<div layout="column" class="tabContent">
<div layout="row">
<div class="analyzeControlPanel" ng-show="showSidebar">
<div layout="column" class="analyzeControlPanelContent">
<md-card>
<md-toolbar>
<div class="md-toolbar-tools">
<h2><span>Layout</span></h2>
</div>
</md-toolbar>
<md-card-content>
<md-input-container style="padding-bottom: 2px !important">
<label>Grid Size</label>
<md-select ng-model="gridSize">
<md-option value="oneone">
1 x 1
</md-option>
<md-option value="twoone">
2 x 1
</md-option>
<md-option value="onetwo">
1 x 2
</md-option>
<md-option value="twotwo">
2 x 2
</md-option>
</md-select>
</md-input-container>
</md-card-content>
<md-divider></md-divider>
<md-subheader>Column analyses to show</md-subheader>
<section class="analyze-search" layout-padding="5">
<md-autocomplete
md-search-text="searchQuery1"
md-selected-item="selectedColumn1"
md-items="column in querySearch(searchQuery1)"
md-no-cache="true"
placeholder="Panel A">
<span md-highlight-text="searchQuery1">{{column}}</span>
<md-not-found>
No matching columns
</md-not-found>
</md-autocomplete>
</section>
<section class="analyze-search" layout-padding="5" ng-show="gridSize == 'twoone' || gridSize == 'twotwo'">
<md-autocomplete
md-search-text="searchQuery2"
md-selected-item="selectedColumn2"
md-items="column in querySearch(searchQuery2)"
md-no-cache="true"
placeholder="Panel B">
<span md-highlight-text="searchQuery2">{{column}}</span>
<md-not-found>
No matching columns
</md-not-found>
</md-autocomplete>
</section>
<section class="analyze-search" layout-padding="5" ng-show="gridSize == 'onetwo' || gridSize == 'twotwo'">
<md-autocomplete
md-search-text="searchQuery3"
md-selected-item="selectedColumn3"
md-items="column in querySearch(searchQuery3)"
md-no-cache="true"
placeholder="Panel C">
<span md-highlight-text="searchQuery3">{{column}}</span>
<md-not-found>
No matching columns
</md-not-found>
</md-autocomplete>
</section>
<section class="analyze-search" layout-padding="5" ng-show="gridSize == 'twotwo'">
<md-autocomplete
md-search-text="searchQuery4"
md-selected-item="selectedColumn4"
md-items="column in querySearch(searchQuery4)"
md-no-cache="true"
placeholder="Panel D">
<span md-highlight-text="searchQuery4">{{column}}</span>
<md-not-found>
No matching columns
</md-not-found>
</md-autocomplete>
</section>
</md-card>
<md-divider></md-divider>
<md-card>
<md-toolbar>
<div class="md-toolbar-tools">
<h2><span>Summary</span></h2>
</div>
</md-toolbar>
<md-card-content>
<div ng-repeat="(descriptor, value) in summaryStatistics">
<div class="md-body-1 analyze-descriptor">
{{ descriptor }}
</div>
<div style="" class="analyze-value md-body-1">
{{ value }}
</div>
</div>
</md-card-content>
</md-card>
</div>
</div>
<div layout="row" flex>
<div layout="column" flex>
<div class="panelTitle">Panel A</div>
<div layout="column" flex class="analyzePanel">
<clean-sidebar-no-tools ng-show="selectedColumn1 == '' || selectedColumn1 == undefined"></clean-sidebar-no-tools>
<analysis-column filter-query="selectedColumn1">
</analysis-column>
</div>
<div class="panelTitle" ng-show="gridSize == 'onetwo' || gridSize == 'twotwo'">Panel C</div>
<div layout="column" ng-show="gridSize == 'onetwo' || gridSize == 'twotwo'" flex class="analyzePanel">
<clean-sidebar-no-tools ng-show="selectedColumn3 == '' || selectedColumn3 == undefined"></clean-sidebar-no-tools>
<analysis-column filter-query="selectedColumn3">
</analysis-column>
</div>
</div>
<div layout="column" ng-show="gridSize == 'twoone' || gridSize == 'twotwo'" flex>
<div class="panelTitle">Panel B</div>
<div layout="column" flex class="analyzePanel">
<clean-sidebar-no-tools ng-show="selectedColumn2 == '' || selectedColumn2 == undefined"></clean-sidebar-no-tools>
<analysis-column filter-query="selectedColumn2">
</analysis-column>
</div>
<div class="panelTitle" ng-show="gridSize == 'twotwo'">Panel D</div>
<div layout="column" ng-show="gridSize == 'twotwo'" flex class="analyzePanel">
<clean-sidebar-no-tools ng-show="selectedColumn4 == '' || selectedColumn4 == undefined"></clean-sidebar-no-tools>
<analysis-column filter-query="selectedColumn4">
</analysis-column>
</div>
</div>
</div>
</div>
</div> | {
"content_hash": "c4e04e39ac1a07c39ca80b1710e24efe",
"timestamp": "",
"source": "github",
"line_count": 225,
"max_line_length": 138,
"avg_line_length": 34.05777777777778,
"alnum_prop": 0.5204228109095654,
"repo_name": "SeldonIO/seldon-ucl",
"id": "9a127b2f03ed55fa8dab7a5b825b4283590aa58f",
"size": "7663",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "flaskApp/static/partials/main.analyze.html",
"mode": "33261",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "9738"
},
{
"name": "HTML",
"bytes": "76234"
},
{
"name": "JavaScript",
"bytes": "139079"
},
{
"name": "Nginx",
"bytes": "1144"
},
{
"name": "Python",
"bytes": "135462"
},
{
"name": "Shell",
"bytes": "1597"
}
],
"symlink_target": ""
} |
@interface VoiceItLogo : UIView
@end
| {
"content_hash": "bb8d682921b9d56c3772bcf6fee2d928",
"timestamp": "",
"source": "github",
"line_count": 3,
"max_line_length": 31,
"avg_line_length": 12.666666666666666,
"alnum_prop": 0.7631578947368421,
"repo_name": "voiceittech/VoiceItApi2IosSDK",
"id": "817a1f1332b698c9f4463e6936a9727359abea2a",
"size": "223",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "VoiceIt2-IosSDK/Classes/VoiceItLogo.h",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Objective-C",
"bytes": "334537"
},
{
"name": "Ruby",
"bytes": "1993"
},
{
"name": "Shell",
"bytes": "561"
},
{
"name": "Swift",
"bytes": "40854"
}
],
"symlink_target": ""
} |
<?php if ( has_nav_menu( 'footer' ) ) : // Check if there's a menu assigned to the 'footer' location. ?>
<nav id="footer-nav" role="navigation" <?php hybrid_attr( 'menu' ); ?>>
<?php wp_nav_menu(
array(
'theme_location' => 'footer',
'container' => '',
)
); ?>
</nav><!-- #footer-nav -->
<?php endif; // End check for menu. ?> | {
"content_hash": "bd01fd7174523621f4d2ef7972f156e3",
"timestamp": "",
"source": "github",
"line_count": 14,
"max_line_length": 104,
"avg_line_length": 26.214285714285715,
"alnum_prop": 0.5204359673024523,
"repo_name": "cornelous/theprayingcoupleau",
"id": "c371075383c0a4e4468cc177d9ca05cff236ca9e",
"size": "367",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "content/themes/supernews/menu-footer.php",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "259174"
},
{
"name": "HTML",
"bytes": "9904"
},
{
"name": "JavaScript",
"bytes": "124888"
},
{
"name": "PHP",
"bytes": "547713"
},
{
"name": "Ruby",
"bytes": "5918"
},
{
"name": "Shell",
"bytes": "185"
}
],
"symlink_target": ""
} |
title: asi22
type: products
image: /img/Screen Shot 2017-05-09 at 11.56.54 AM.png
heading: i22
description: lksadjf lkasdjf lksajdf lksdaj flksadj flksa fdj
main:
heading: Foo Bar BAz
description: |-
***This is i a thing***kjh hjk kj
# Blah Blah
## Blah
### Baah
image1:
alt: kkkk
---
| {
"content_hash": "d63949b60f20d1aa97ed2657cee9ba38",
"timestamp": "",
"source": "github",
"line_count": 15,
"max_line_length": 61,
"avg_line_length": 22.333333333333332,
"alnum_prop": 0.6656716417910448,
"repo_name": "pblack/kaldi-hugo-cms-template",
"id": "9c0cb9a43eb77f23f846b44dbbeb26e1e4cd914f",
"size": "339",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "site/content/pages2/asi22.md",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "94394"
},
{
"name": "HTML",
"bytes": "18889"
},
{
"name": "JavaScript",
"bytes": "10014"
}
],
"symlink_target": ""
} |
<ul class="nav nav-tabs">
<li{% if active_page == "term" %} class="active"{% endif %}>
<a href="{{ url_for('main.show_term', selected_term=term.id) }}">Term</a>
</li>
<li{% if active_page == "documents" %} class="active"{% elif term.documents|length == 0 %} class="disabled"{% else %}{% endif %}>
<a href="{{ url_for('main.show_documents', selected_term=term.id) }}">
Related Documents{% if term.documents|length > 0 %} <span class="badge">{{ term.documents|length }}</span>{% endif %}
</a>
</li>
<li{% if active_page == "assets" %} class="active"{% elif not term.columns %} class="disabled"{% else %}{% endif %}>
<a href="{{ url_for('main.show_assets', selected_term=term.id) }}">
Related Assets{% if term.columns|length > 0 %} <span class="badge">{{ term.columns|length }}</span>{% endif %}
</a>
</li>
<li{% if active_page == "rules" %} class="active"{% elif not term.rules %} class="disabled"{% else %}{% endif %}>
<a href="{{ url_for('main.show_rules', selected_term=term.id) }}">
Related Rules{% if term.rules|length > 0 %} <span class="badge">{{ term.rules|length }}</span>{% endif %}
</a>
</li>
{% if current_user.is_active %}
<li class="pull-right">
<a href="{{ url_for('term_bp.delete_term', id=term.id) }}"><span class="glyphicon glyphicon-trash"></span></a>
</li>
<li class="pull-right">
<a href="{{ url_for('term_bp.edit_term', id=term.id) }}"><span class="glyphicon glyphicon-pencil"></span></a>
</li>
{% endif %}
</ul>
| {
"content_hash": "5e60a82a2e9d313c29e138a311a2a504",
"timestamp": "",
"source": "github",
"line_count": 28,
"max_line_length": 133,
"avg_line_length": 57.035714285714285,
"alnum_prop": 0.5547902316844082,
"repo_name": "atindale/business-glossary",
"id": "b0931b2557b45c8c24ffa818729843b8e64e6abc",
"size": "1597",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "app/templates/_term_tabs.html",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "13158"
},
{
"name": "HTML",
"bytes": "122645"
},
{
"name": "Mako",
"bytes": "412"
},
{
"name": "Python",
"bytes": "158304"
}
],
"symlink_target": ""
} |
package com.azure.cosmos.implementation.patch;
public enum PatchOperationType {
ADD(PatchConstants.OperationTypeNames_Add),
REMOVE(PatchConstants.OperationTypeNames_Remove),
REPLACE(PatchConstants.OperationTypeNames_Replace),
SET(PatchConstants.OperationTypeNames_Set),
INCREMENT(PatchConstants.OperationTypeNames_Increment);
PatchOperationType(String operationValue) {
this.operationValue = operationValue;
}
String getOperationValue() {
return operationValue;
}
private final String operationValue;
}
| {
"content_hash": "9d4bf4033a6967c6ee1c638e79611afa",
"timestamp": "",
"source": "github",
"line_count": 20,
"max_line_length": 59,
"avg_line_length": 28.2,
"alnum_prop": 0.7606382978723404,
"repo_name": "Azure/azure-sdk-for-java",
"id": "b53f365b106cd574bb951f2394181fa77ab2ef56",
"size": "661",
"binary": false,
"copies": "1",
"ref": "refs/heads/main",
"path": "sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/implementation/patch/PatchOperationType.java",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Batchfile",
"bytes": "8762"
},
{
"name": "Bicep",
"bytes": "15055"
},
{
"name": "CSS",
"bytes": "7676"
},
{
"name": "Dockerfile",
"bytes": "2028"
},
{
"name": "Groovy",
"bytes": "3237482"
},
{
"name": "HTML",
"bytes": "42090"
},
{
"name": "Java",
"bytes": "432409546"
},
{
"name": "JavaScript",
"bytes": "36557"
},
{
"name": "Jupyter Notebook",
"bytes": "95868"
},
{
"name": "PowerShell",
"bytes": "737517"
},
{
"name": "Python",
"bytes": "240542"
},
{
"name": "Scala",
"bytes": "1143898"
},
{
"name": "Shell",
"bytes": "18488"
},
{
"name": "XSLT",
"bytes": "755"
}
],
"symlink_target": ""
} |
<!doctype html>
<html lang="en">
<head>
<title>Code coverage report for models/User.js</title>
<meta charset="utf-8" />
<link rel="stylesheet" href="../prettify.css" />
<link rel="stylesheet" href="../base.css" />
<meta name="viewport" content="width=device-width, initial-scale=1">
<style type='text/css'>
.coverage-summary .sorter {
background-image: url(../sort-arrow-sprite.png);
}
</style>
</head>
<body>
<div class='wrapper'>
<div class='pad1'>
<h1>
<a href="../index.html">all files</a> / <a href="index.html">models/</a> User.js
</h1>
<div class='clearfix'>
<div class='fl pad1y space-right2'>
<span class="strong">81.82% </span>
<span class="quiet">Statements</span>
<span class='fraction'>9/11</span>
</div>
<div class='fl pad1y space-right2'>
<span class="strong">0% </span>
<span class="quiet">Branches</span>
<span class='fraction'>0/2</span>
</div>
<div class='fl pad1y space-right2'>
<span class="strong">83.33% </span>
<span class="quiet">Functions</span>
<span class='fraction'>5/6</span>
</div>
<div class='fl pad1y space-right2'>
<span class="strong">81.82% </span>
<span class="quiet">Lines</span>
<span class='fraction'>9/11</span>
</div>
</div>
</div>
<div class='status-line high'></div>
<pre><table class="coverage">
<tr><td class="line-count quiet">1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74</td><td class="line-coverage quiet"><span class="cline-any cline-yes">1×</span>
<span class="cline-any cline-neutral"> </span>
<span class="cline-any cline-yes">1×</span>
<span class="cline-any cline-yes">1×</span>
<span class="cline-any cline-neutral"> </span>
<span class="cline-any cline-neutral"> </span>
<span class="cline-any cline-neutral"> </span>
<span class="cline-any cline-neutral"> </span>
<span class="cline-any cline-neutral"> </span>
<span class="cline-any cline-neutral"> </span>
<span class="cline-any cline-neutral"> </span>
<span class="cline-any cline-neutral"> </span>
<span class="cline-any cline-neutral"> </span>
<span class="cline-any cline-neutral"> </span>
<span class="cline-any cline-neutral"> </span>
<span class="cline-any cline-neutral"> </span>
<span class="cline-any cline-neutral"> </span>
<span class="cline-any cline-neutral"> </span>
<span class="cline-any cline-neutral"> </span>
<span class="cline-any cline-neutral"> </span>
<span class="cline-any cline-neutral"> </span>
<span class="cline-any cline-neutral"> </span>
<span class="cline-any cline-neutral"> </span>
<span class="cline-any cline-neutral"> </span>
<span class="cline-any cline-neutral"> </span>
<span class="cline-any cline-neutral"> </span>
<span class="cline-any cline-neutral"> </span>
<span class="cline-any cline-neutral"> </span>
<span class="cline-any cline-neutral"> </span>
<span class="cline-any cline-neutral"> </span>
<span class="cline-any cline-neutral"> </span>
<span class="cline-any cline-neutral"> </span>
<span class="cline-any cline-neutral"> </span>
<span class="cline-any cline-neutral"> </span>
<span class="cline-any cline-neutral"> </span>
<span class="cline-any cline-neutral"> </span>
<span class="cline-any cline-neutral"> </span>
<span class="cline-any cline-neutral"> </span>
<span class="cline-any cline-neutral"> </span>
<span class="cline-any cline-neutral"> </span>
<span class="cline-any cline-neutral"> </span>
<span class="cline-any cline-neutral"> </span>
<span class="cline-any cline-neutral"> </span>
<span class="cline-any cline-neutral"> </span>
<span class="cline-any cline-neutral"> </span>
<span class="cline-any cline-yes">1×</span>
<span class="cline-any cline-yes">1×</span>
<span class="cline-any cline-neutral"> </span>
<span class="cline-any cline-neutral"> </span>
<span class="cline-any cline-neutral"> </span>
<span class="cline-any cline-neutral"> </span>
<span class="cline-any cline-neutral"> </span>
<span class="cline-any cline-neutral"> </span>
<span class="cline-any cline-neutral"> </span>
<span class="cline-any cline-yes">3×</span>
<span class="cline-any cline-neutral"> </span>
<span class="cline-any cline-neutral"> </span>
<span class="cline-any cline-yes">1×</span>
<span class="cline-any cline-neutral"> </span>
<span class="cline-any cline-neutral"> </span>
<span class="cline-any cline-neutral"> </span>
<span class="cline-any cline-neutral"> </span>
<span class="cline-any cline-yes">3×</span>
<span class="cline-any cline-neutral"> </span>
<span class="cline-any cline-neutral"> </span>
<span class="cline-any cline-no"> </span>
<span class="cline-any cline-no"> </span>
<span class="cline-any cline-neutral"> </span>
<span class="cline-any cline-neutral"> </span>
<span class="cline-any cline-neutral"> </span>
<span class="cline-any cline-neutral"> </span>
<span class="cline-any cline-yes">1×</span>
<span class="cline-any cline-neutral"> </span>
<span class="cline-any cline-neutral"> </span></td><td class="text"><pre class="prettyprint lang-js">const bcrypt = require('bcrypt-nodejs');
module.exports = (sequelize, DataTypes) => {
const User = sequelize.define('User', {
username: {
type: DataTypes.STRING,
allowNull: false,
unique: true,
validate: { notEmpty: true }
},
firstName: {
type: DataTypes.STRING,
allowNull: false,
validate: { notEmpty: true }
},
lastName: {
type: DataTypes.STRING,
allowNull: false,
validate: { notEmpty: true }
},
email: {
type: DataTypes.STRING,
allowNull: false,
unique: true,
validate: {
isEmail: true
}
},
password: {
type: DataTypes.STRING,
allowNull: false
},
roleId: {
type: DataTypes.INTEGER,
allowNull: true,
defaultValue: 2
},
active: {
type: DataTypes.BOOLEAN,
defaultValue: true,
allowNull: false
}
}, {
classMethods: {
associate: (models) => {
User.hasMany(models.Document, { foreignKey: 'ownerId' });
User.belongsTo(models.Role, {
foreignKey: 'roleId',
onDelete: 'SET NULL'
});
}
},
instanceMethods: {
generateHash() {
this.password = bcrypt.hashSync(this.password, bcrypt.genSaltSync(10));
},
validPassword(password) {
return bcrypt.compareSync(password, this.password);
},
},
hooks: {
beforeCreate(user) {
user.generateHash();
},
beforeUpdate(<span class="fstat-no" title="function not covered" >user) {</span>
if (<span class="cstat-no" title="statement not covered" >user.changed.password) {</span>
user.<span class="cstat-no" title="statement not covered" >generateHash();</span>
}
}
}
});
return User;
};
</pre></td></tr>
</table></pre>
<div class='push'></div><!-- for sticky footer -->
</div><!-- /wrapper -->
<div class='footer quiet pad2 space-top1 center small'>
Code coverage
generated by <a href="http://istanbul-js.org/" target="_blank">istanbul</a> at Sun Jun 11 2017 02:08:30 GMT+0100 (WAT)
</div>
</div>
<script src="../prettify.js"></script>
<script>
window.onload = function () {
if (typeof prettyPrint === 'function') {
prettyPrint();
}
};
</script>
<script src="../sorter.js"></script>
</body>
</html>
| {
"content_hash": "95500f996924a3089ac3dc0c31f89e22",
"timestamp": "",
"source": "github",
"line_count": 284,
"max_line_length": 146,
"avg_line_length": 27.929577464788732,
"alnum_prop": 0.6381744831064045,
"repo_name": "andela-oakinwa/document-management-system",
"id": "9d7d4581a725d54b5ad8b66bd4a5d4110ed3029e",
"size": "7941",
"binary": false,
"copies": "1",
"ref": "refs/heads/staging",
"path": "coverage/lcov-report/models/User.js.html",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "6877"
},
{
"name": "HTML",
"bytes": "954642"
},
{
"name": "JavaScript",
"bytes": "199029"
}
],
"symlink_target": ""
} |
/*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package de.fuberlin.wiwiss.silk.workbench.lift.util
import xml.NodeSeq
import net.liftweb.http.SHtml
import net.liftweb.util.Helpers._
import net.liftweb.http.js.JE.JsRaw
import net.liftweb.http.js.JsCmds.{OnLoad, Script}
import java.util.UUID
import net.liftweb.http.js.JsCmd
import de.fuberlin.wiwiss.silk.workbench.lift.util.JS._
/**
* Basic dialog with a number of fields.
*/
trait Dialog extends Form {
/** The title of this dialog */
def title : String
/** The parameters of this dialog e.g. ("with" -> "700") */
protected def dialogParams : List[(String, String)] = ("autoOpen" -> "false") :: ("width" -> "700") :: ("modal" -> "true") :: Nil
/** The id of this form */
private lazy val id : String = UUID.randomUUID.toString
/**
* Command which opens this dialog.
*/
def openCmd = Try("Open Dialog") {
//Update all fields and open the dialog
updateCmd &
JsRaw("$('#" + id + "').dialog('open');").cmd
}
/**
* Command which closes this dialog.
*/
def closeCmd = JsRaw("$('#" + id + "').dialog('close');").cmd
/**
* Renders this dialog.
*/
def render(xhtml : NodeSeq) : NodeSeq = {
def submit() = Try("Submit Dialog") {
val cmd = onSubmit()
closeCmd & cmd
}
<div id={id} title={title}> {
SHtml.ajaxForm(
super.render ++
<div style="float:right;">
{ SHtml.ajaxSubmit("OK", submit) }
</div> ++
Script(initCmd)
)
}
</div>
}
/**
* Command which initializes this dialog.
*/
private def initCmd = OnLoad(JsRaw("$('#" + id + "').dialog({ " + dialogParams.map(_.productIterator.mkString(": ")).mkString(", ") + " })").cmd)
/**
* Called when the dialog is submitted.
* Must be overloaded by sub classes in order to read the input values.
*/
protected def onSubmit(): JsCmd
} | {
"content_hash": "804db700de3d00dda0c5c2ecbb2ce40d",
"timestamp": "",
"source": "github",
"line_count": 84,
"max_line_length": 147,
"avg_line_length": 28.773809523809526,
"alnum_prop": 0.6338436077782375,
"repo_name": "fusepoolP3/p3-silk",
"id": "87b1a9c64775316efca1faf24e69f6d9c757964f",
"size": "2417",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "silk-workbench-outdated/src/main/scala/de/fuberlin/wiwiss/silk/workbench/lift/util/Dialog.scala",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "43338"
},
{
"name": "HTML",
"bytes": "125298"
},
{
"name": "Java",
"bytes": "1013"
},
{
"name": "JavaScript",
"bytes": "975385"
},
{
"name": "Scala",
"bytes": "3508272"
}
],
"symlink_target": ""
} |
import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
import { HomeComponent } from './home';
import { DefaultComponent } from './default';
import { LoginComponent } from './security/login';
import { DashboardComponent } from './dashboard';
import { UserRoleComponent } from './security/user-role';
import { UserGroupComponent } from './security/user-group';
import { UserAccountComponent } from './security/user-account';
import { GroupComponent } from './email/group/group.component';
import { ContactComponent } from './email/contact/contact.component';
import { EmailComponent } from './email/email/email.component';
import { EmailServerComponent } from './email/server/emailserver.component';
import {ChangePasswordComponent} from './security/change-password';
import {AnalyticsComponent} from './analytics/analytics.root.component';
import {FileUploadComponent} from './email/contact/fileupload.component';
import { RegistrationComponent } from './security/registration';
import { AccountApprovalComponent} from './security/account-approval/accountapproval.component';
const routes: Routes = [
{path:'',component:DefaultComponent},
{path:'send_email',component:EmailComponent},
{path:'contacts',component:ContactComponent},
{path:'groups',component:GroupComponent},
{path:'servers',component:EmailServerComponent},
{path:'user_roles',component:UserRoleComponent},
{path:'user_accounts',component:UserAccountComponent},
{path:'user_groups',component:UserGroupComponent},
{path:'dashboard',component:DashboardComponent},
{path:'appLogin',component:LoginComponent},
{path:'changePassword',component:ChangePasswordComponent},
{path:'analytics',component:AnalyticsComponent},
{path:'bulk_upload',component:FileUploadComponent},
{path:'appRegister',component:RegistrationComponent},
{path:'account_approval',component:AccountApprovalComponent}
];
@NgModule({
imports: [RouterModule.forRoot(routes,{ useHash: true })],
exports: [RouterModule],
providers: []
})
export class EmailAppRoutingModule { }
| {
"content_hash": "8d6297a5e1a962dc8c4fad071bfdbff8",
"timestamp": "",
"source": "github",
"line_count": 43,
"max_line_length": 96,
"avg_line_length": 48.41860465116279,
"alnum_prop": 0.7636887608069164,
"repo_name": "Sudhanshu-bluespace/EmailApp_FrontEnd",
"id": "9fb862a2478b2197d5a13fd674e841d3168a0490",
"size": "2082",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/app/app-routing.module.ts",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "158072"
},
{
"name": "HTML",
"bytes": "103697"
},
{
"name": "JavaScript",
"bytes": "1833"
},
{
"name": "TypeScript",
"bytes": "1532228"
}
],
"symlink_target": ""
} |
package com.udacity.akki.sunshine.data;
import android.content.UriMatcher;
import android.net.Uri;
import android.support.test.runner.AndroidJUnit4;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import static com.udacity.akki.sunshine.data.TestUtilities.getStaticIntegerField;
import static com.udacity.akki.sunshine.data.TestUtilities.studentReadableNoSuchField;
import static junit.framework.Assert.assertEquals;
import static junit.framework.Assert.fail;
@RunWith(AndroidJUnit4.class)
public class TestUriMatcher {
private static final Uri TEST_WEATHER_DIR = WeatherContract.WeatherEntry.CONTENT_URI;
private static final Uri TEST_WEATHER_WITH_DATE_DIR = WeatherContract.WeatherEntry
.buildWeatherUriWithDate(TestUtilities.DATE_NORMALIZED);
private static final String weatherCodeVariableName = "CODE_WEATHER";
private static int REFLECTED_WEATHER_CODE;
private static final String weatherCodeWithDateVariableName = "CODE_WEATHER_WITH_DATE";
private static int REFLECTED_WEATHER_WITH_DATE_CODE;
private UriMatcher testMatcher;
@Before
public void before() {
try {
Method buildUriMatcher = WeatherProvider.class.getDeclaredMethod("buildUriMatcher");
testMatcher = (UriMatcher) buildUriMatcher.invoke(WeatherProvider.class);
REFLECTED_WEATHER_CODE = getStaticIntegerField(
WeatherProvider.class,
weatherCodeVariableName);
REFLECTED_WEATHER_WITH_DATE_CODE = getStaticIntegerField(
WeatherProvider.class,
weatherCodeWithDateVariableName);
} catch (NoSuchFieldException e) {
fail(studentReadableNoSuchField(e));
} catch (IllegalAccessException e) {
fail(e.getMessage());
} catch (NoSuchMethodException e) {
String noBuildUriMatcherMethodFound =
"It doesn't appear that you have created a method called buildUriMatcher in " +
"the WeatherProvider class.";
fail(noBuildUriMatcherMethodFound);
} catch (InvocationTargetException e) {
fail(e.getMessage());
}
}
/**
* Students: This function tests that your UriMatcher returns the correct integer value for
* each of the Uri types that our ContentProvider can handle. Uncomment this when you are
* ready to test your UriMatcher.
*/
@Test
public void testUriMatcher() {
/* Test that the code returned from our matcher matches the expected weather code */
String weatherUriDoesNotMatch = "Error: The CODE_WEATHER URI was matched incorrectly.";
int actualWeatherCode = testMatcher.match(TEST_WEATHER_DIR);
int expectedWeatherCode = REFLECTED_WEATHER_CODE;
assertEquals(weatherUriDoesNotMatch,
expectedWeatherCode,
actualWeatherCode);
/*
* Test that the code returned from our matcher matches the expected weather with date code
*/
String weatherWithDateUriCodeDoesNotMatch =
"Error: The CODE_WEATHER WITH DATE URI was matched incorrectly.";
int actualWeatherWithDateCode = testMatcher.match(TEST_WEATHER_WITH_DATE_DIR);
int expectedWeatherWithDateCode = REFLECTED_WEATHER_WITH_DATE_CODE;
assertEquals(weatherWithDateUriCodeDoesNotMatch,
expectedWeatherWithDateCode,
actualWeatherWithDateCode);
}
}
| {
"content_hash": "69ba5354759d0339307e51015425eecc",
"timestamp": "",
"source": "github",
"line_count": 91,
"max_line_length": 99,
"avg_line_length": 39.84615384615385,
"alnum_prop": 0.696911196911197,
"repo_name": "AkshaySathe2/WearableSunshine",
"id": "af49b45c9d9d983a3f48760dd2619dcadfb0c571",
"size": "4245",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "app/src/androidTest/java/com/udacity/akki/sunshine/data/TestUriMatcher.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Java",
"bytes": "282893"
},
{
"name": "Python",
"bytes": "5942"
}
],
"symlink_target": ""
} |
@name(concentrate)
@author(Ryan Sandor Richards)
# Cooldown: Concentrate
Usage: `concentrate`
Cooldown: 120s
Special: Elven race only
The concentrate command is a special racial cooldown available only to elves.
When executed the `concentrating` buff will be applied for 10s during which
offensive `cooldowns` (both physical and magical) have double potency.
See also: `elf` (race)
| {
"content_hash": "cafdb423c24b01e997f4d253e2fd518f",
"timestamp": "",
"source": "github",
"line_count": 13,
"max_line_length": 77,
"avg_line_length": 29.615384615384617,
"alnum_prop": 0.7896103896103897,
"repo_name": "rsandor/Solace",
"id": "c1c2d0d3215710a0ccbaaa67de43641fc78b3b22",
"size": "385",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "game/races/elf/concentrate.help.md",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Java",
"bytes": "435091"
},
{
"name": "JavaScript",
"bytes": "38500"
}
],
"symlink_target": ""
} |
package org.apache.ivory.plugin;
import org.apache.ivory.aspect.ResourceMessage;
import org.apache.log4j.Logger;
public class LoggingPlugin implements MonitoringPlugin {
private static final Logger METRIC = Logger.getLogger("METRIC");
@Override
public void monitor(ResourceMessage message) {
METRIC.info(message);
}
}
| {
"content_hash": "1b4dea4c6e8fd8e788ad9b03696da9bb",
"timestamp": "",
"source": "github",
"line_count": 13,
"max_line_length": 68,
"avg_line_length": 26.53846153846154,
"alnum_prop": 0.7507246376811594,
"repo_name": "InMobi/ivory",
"id": "bdb72cfaa17c520181943e2824470c70e44d1b0c",
"size": "345",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "metrics/src/main/java/org/apache/ivory/plugin/LoggingPlugin.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Java",
"bytes": "976385"
},
{
"name": "Perl",
"bytes": "19647"
},
{
"name": "Shell",
"bytes": "1552"
}
],
"symlink_target": ""
} |
using System;
using System.IO;
using System.Collections;
using Alphora.Dataphor;
using Alphora.Dataphor.DAE;
using Alphora.Dataphor.DAE.Server;
using Schema = Alphora.Dataphor.DAE.Schema;
using Alphora.Dataphor.Frontend.Server.Derivation;
namespace Alphora.Dataphor.Frontend.Server
{
// FrontendServer class
// manages frontend sessions
public class FrontendServer : System.Object
{
private static Hashtable _servers = new Hashtable();
// returns the frontend server for the given DAE instance
public static FrontendServer GetFrontendServer(DAE.Server.Engine server)
{
lock (_servers)
{
FrontendServer localServer = _servers[server] as FrontendServer;
if (localServer == null)
{
localServer = new FrontendServer(server);
_servers.Add(server, localServer);
}
return localServer;
}
}
public FrontendServer(DAE.Server.Engine server)
{
_server = server;
_server.Disposed += new EventHandler(ServerDisposed);
}
[Reference]
private DAE.Server.Engine _server;
public DAE.Server.Engine Server { get { return _server; } }
private void ServerDisposed(object sender, EventArgs args)
{
if (_server != null)
{
lock (_servers)
{
_server.Disposed -= new EventHandler(ServerDisposed);
_servers.Remove(_server);
_server = null;
}
}
}
internal Hashtable _sessions = new Hashtable();
public FrontendSession GetFrontendSession(ServerSession session)
{
lock (_sessions)
{
FrontendSession localSession = _sessions[session] as FrontendSession;
if (localSession == null)
{
localSession = new FrontendSession(this, session);
_sessions.Add(session, localSession);
}
return localSession;
}
}
public void ClearDerivationCache()
{
lock (_sessions)
{
foreach (FrontendSession session in _sessions.Values)
session.ClearDerivationCache();
}
}
}
// FrontendSession class
// manages derivation cache and other session specific settings
public class FrontendSession : System.Object
{
public const int DefaultDerivationCacheSize = 50;
public FrontendSession(FrontendServer frontendServer, ServerSession session)
{
_frontendServer = frontendServer;
_session = session;
_session.Disposed += new EventHandler(SessionDisposed);
}
[Reference]
private FrontendServer _frontendServer;
public FrontendServer FrontendServer { get { return _frontendServer; } }
[Reference]
private ServerSession _session;
public ServerSession Session { get { return _session; } }
private void SessionDisposed(object sender, EventArgs args)
{
if (_session != null)
{
_session.Disposed -= new EventHandler(SessionDisposed);
_frontendServer._sessions.Remove(_session);
_session = null;
_frontendServer = null;
}
}
private bool _useDerivationCache = true;
public bool UseDerivationCache
{
get { return _useDerivationCache; }
set { _useDerivationCache = value; }
}
private FixedSizeCache<DerivationSeed, DerivationCacheItem> _derivationCache = new FixedSizeCache<DerivationSeed, DerivationCacheItem>(DefaultDerivationCacheSize);
public FixedSizeCache<DerivationSeed, DerivationCacheItem> DerivationCache { get { return _derivationCache; } }
private long _derivationTimeStamp;
public void EnsureDerivationCacheConsistent()
{
lock (_derivationCache)
{
if (_derivationTimeStamp < _frontendServer.Server.DerivationTimeStamp)
{
_derivationCache.Clear();
_derivationTimeStamp = _frontendServer.Server.DerivationTimeStamp;
}
}
}
public void ClearDerivationCache()
{
lock (_derivationCache)
{
_derivationCache.Clear();
}
}
}
}
| {
"content_hash": "9508404e0141b98bfc88785a3f8cbfa0",
"timestamp": "",
"source": "github",
"line_count": 150,
"max_line_length": 165,
"avg_line_length": 25.85333333333333,
"alnum_prop": 0.6812790097988654,
"repo_name": "DBCG/Dataphor",
"id": "3fe1444073190f327af96c6b306fcf0545eab5e6",
"size": "4055",
"binary": false,
"copies": "3",
"ref": "refs/heads/master",
"path": "Libraries/Frontend/Source/Server.cs",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "ASP",
"bytes": "11205"
},
{
"name": "Batchfile",
"bytes": "3373"
},
{
"name": "C",
"bytes": "115158"
},
{
"name": "C#",
"bytes": "12846956"
},
{
"name": "C++",
"bytes": "14130"
},
{
"name": "CSS",
"bytes": "70296"
},
{
"name": "HTML",
"bytes": "42535"
},
{
"name": "JavaScript",
"bytes": "45709"
},
{
"name": "Objective-C",
"bytes": "2416"
},
{
"name": "PLSQL",
"bytes": "10915"
},
{
"name": "PLpgSQL",
"bytes": "17015"
},
{
"name": "TSQL",
"bytes": "3047"
},
{
"name": "TypeScript",
"bytes": "1"
}
],
"symlink_target": ""
} |
package simulator
import (
"path/filepath"
"strings"
"time"
"github.com/docker/infrakit/pkg/launch/inproc"
logutil "github.com/docker/infrakit/pkg/log"
"github.com/docker/infrakit/pkg/plugin"
"github.com/docker/infrakit/pkg/run"
"github.com/docker/infrakit/pkg/run/local"
"github.com/docker/infrakit/pkg/run/scope"
"github.com/docker/infrakit/pkg/spi/instance"
"github.com/docker/infrakit/pkg/spi/loadbalancer"
"github.com/docker/infrakit/pkg/types"
)
const (
// Kind is the canonical name of the plugin for starting up, etc.
Kind = "simulator"
// EnvStore is the enviornment variable to control the backend to use. e.g. 'mem', 'file'
EnvStore = "mem"
// EnvDir is the env for directory for file storage
EnvDir = "INFRAKIT_SIMULATOR_DIR"
// EnvInstanceTypes is the env var to set for the instance spi type names (comma-delimited)
EnvInstanceTypes = "INFRAKIT_SIMULATOR_INSTANCE_TYPES"
// EnvL4Names is the env var to set for the L4 name
EnvL4Names = "INFRAKIT_SIMULATOR_L4_NAMES"
// EnvStartDelay is the delay to simulate slow start up
EnvStartDelay = "INFRAKIT_SIMULATOR_START_DELAY"
// EnvDescribeDelay is the delay to simulate delay of describe
EnvDescribeDelay = "INFRAKIT_SIMULATOR_DESCRIBE_DELAY"
// EnvProvisionDelay is the delay to simulate provision an instance
EnvProvisionDelay = "INFRAKIT_SIMULATOR_PROVISION_DELAY"
// StoreMem is the value for using memory store
StoreMem = "mem"
// StoreFile is the value for using file store
StoreFile = "file"
)
var (
log = logutil.New("module", "run/v0/simulator")
)
func init() {
inproc.Register(Kind, Run, DefaultOptions)
}
// Options capture the options for starting up the plugin.
type Options struct {
Store string
Dir string
InstanceTypes []string
L4Names []string
StartDelay time.Duration
DescribeDelay time.Duration
ProvisionDelay time.Duration
}
// DefaultOptions return an Options with default values filled in.
var DefaultOptions = Options{
Store: local.Getenv(EnvStore, "mem"),
Dir: local.Getenv(EnvDir, filepath.Join(local.InfrakitHome(), "simulator")),
InstanceTypes: strings.Split(local.Getenv(EnvInstanceTypes, "compute,net,disk"), ","),
L4Names: strings.Split(local.Getenv(EnvL4Names, "lb1,lb2,lb3"), ","),
StartDelay: types.MustParseDuration(local.Getenv(EnvStartDelay, "0s")).Duration(),
DescribeDelay: types.MustParseDuration(local.Getenv(EnvDescribeDelay, "0s")).Duration(),
ProvisionDelay: types.MustParseDuration(local.Getenv(EnvProvisionDelay, "0s")).Duration(),
}
// Run runs the plugin, blocking the current thread. Error is returned immediately
// if the plugin cannot be started.
func Run(scope scope.Scope, name plugin.Name,
config *types.Any) (transport plugin.Transport, impls map[run.PluginCode]interface{}, onStop func(), err error) {
options := DefaultOptions
err = config.Decode(&options)
if err != nil {
return
}
err = local.EnsureDir(options.Dir)
if err != nil {
return
}
impls = map[run.PluginCode]interface{}{}
instanceMap := map[string]instance.Plugin{}
if len(options.InstanceTypes) > 0 {
impls[run.Instance] = instanceMap
}
for _, n := range options.InstanceTypes {
instanceMap[n] = NewInstance(n, options)
}
l4Map := map[string]loadbalancer.L4{}
if len(options.L4Names) > 0 {
impls[run.L4] = func() (map[string]loadbalancer.L4, error) { return l4Map, nil }
}
for _, n := range options.L4Names {
l4Map[n] = NewL4(n, options)
}
transport.Name = name
return
}
| {
"content_hash": "20c0b24b1900d6fd8394f0741006a0ff",
"timestamp": "",
"source": "github",
"line_count": 117,
"max_line_length": 114,
"avg_line_length": 30.094017094017094,
"alnum_prop": 0.7250781028117013,
"repo_name": "kaufers/infrakit",
"id": "536943cbccd75add8b903214475381138a98a226",
"size": "3521",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "pkg/run/v0/simulator/simulator.go",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Go",
"bytes": "3020155"
},
{
"name": "HCL",
"bytes": "2075"
},
{
"name": "Makefile",
"bytes": "17453"
},
{
"name": "Nix",
"bytes": "652"
},
{
"name": "Ruby",
"bytes": "2453"
},
{
"name": "Shell",
"bytes": "28191"
}
],
"symlink_target": ""
} |
package ai.verta.swagger._public.modeldb.model
import scala.util.Try
import net.liftweb.json._
import ai.verta.swagger._public.modeldb.model.DatasetTypeEnumDatasetType._
import ai.verta.swagger._public.modeldb.model.DatasetVisibilityEnumDatasetVisibility._
import ai.verta.swagger._public.modeldb.model.OperatorEnumOperator._
import ai.verta.swagger._public.modeldb.model.PathLocationTypeEnumPathLocationType._
import ai.verta.swagger._public.modeldb.model.ProtobufNullValue._
import ai.verta.swagger._public.modeldb.model.ValueTypeEnumValueType._
import ai.verta.swagger.client.objects._
case class ModeldbAddDatasetVersionTags (
dataset_id: Option[String] = None,
id: Option[String] = None,
tags: Option[List[String]] = None
) extends BaseSwagger {
def toJson(): JValue = ModeldbAddDatasetVersionTags.toJson(this)
}
object ModeldbAddDatasetVersionTags {
def toJson(obj: ModeldbAddDatasetVersionTags): JObject = {
new JObject(
List[Option[JField]](
obj.dataset_id.map(x => JField("dataset_id", JString(x))),
obj.id.map(x => JField("id", JString(x))),
obj.tags.map(x => JField("tags", ((x: List[String]) => JArray(x.map(JString)))(x)))
).flatMap(x => x match {
case Some(y) => List(y)
case None => Nil
})
)
}
def fromJson(value: JValue): ModeldbAddDatasetVersionTags =
value match {
case JObject(fields) => {
val fieldsMap = fields.map(f => (f.name, f.value)).toMap
ModeldbAddDatasetVersionTags(
// TODO: handle required
dataset_id = fieldsMap.get("dataset_id").map(JsonConverter.fromJsonString),
id = fieldsMap.get("id").map(JsonConverter.fromJsonString),
tags = fieldsMap.get("tags").map((x: JValue) => x match {case JArray(elements) => elements.map(JsonConverter.fromJsonString); case _ => throw new IllegalArgumentException(s"unknown type ${x.getClass.toString}")})
)
}
case _ => throw new IllegalArgumentException(s"unknown type ${value.getClass.toString}")
}
}
| {
"content_hash": "917749d04c985086040343126556817f",
"timestamp": "",
"source": "github",
"line_count": 50,
"max_line_length": 222,
"avg_line_length": 40.86,
"alnum_prop": 0.697503671071953,
"repo_name": "mitdbg/modeldb",
"id": "480695657d30eb651c8ae70ff892edfc6e7c0608",
"size": "2087",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "client/scala/src/main/scala/ai/verta/swagger/_public/modeldb/model/ModeldbAddDatasetVersionTags.scala",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "43352"
},
{
"name": "Dockerfile",
"bytes": "235"
},
{
"name": "HTML",
"bytes": "30924"
},
{
"name": "Java",
"bytes": "393927"
},
{
"name": "JavaScript",
"bytes": "1017682"
},
{
"name": "Python",
"bytes": "178774"
},
{
"name": "Scala",
"bytes": "251259"
},
{
"name": "Shell",
"bytes": "16870"
},
{
"name": "Thrift",
"bytes": "55683"
}
],
"symlink_target": ""
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Lithogen.Core
{
public static class TaskFactory
{
//public static T MakeSubTask<T>(Task parent)
// where T : Task
//{
// return (T)MakeSubTask(typeof(T), parent);
//}
//public static Task MakeSubTask(Type taskType, Task parent)
//{
// Task task = (Task)Activator.CreateInstance(taskType);
// task.BuildEngine = parent.BuildEngine;
// task.HostObject = parent.HostObject;
// return task;
//}
//public static T MakeLithogenTask<T>(LithogenTask parent)
// where T : LithogenTask
//{
// return (T)MakeLithogenTask(typeof(T), parent);
//}
//public static LithogenTask MakeLithogenTask(Type taskType, LithogenTask parent)
//{
// LithogenTask task = (LithogenTask)Activator.CreateInstance(taskType);
// task.BuildEngine = parent.BuildEngine;
// task.HostObject = parent.HostObject;
// task.Logger = parent.Logger;
// return task;
//}
}
}
| {
"content_hash": "922aa488045b0b51acc9642f7cec4a7d",
"timestamp": "",
"source": "github",
"line_count": 40,
"max_line_length": 89,
"avg_line_length": 31.325,
"alnum_prop": 0.5658419792498005,
"repo_name": "PhilipDaniels/Lithogen.proto",
"id": "c30ed40d2c0eb3c5d541b2c1978bdafa12e6d46b",
"size": "1255",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "Lithogen.Core/TaskFactory.cs",
"mode": "33261",
"license": "mit",
"language": [
{
"name": "ASP",
"bytes": "112"
},
{
"name": "C#",
"bytes": "362908"
},
{
"name": "CSS",
"bytes": "5281"
},
{
"name": "JavaScript",
"bytes": "760"
}
],
"symlink_target": ""
} |
#include "hbondengine.h"
#include <avogadro/molecule.h>
#include <avogadro/atom.h>
#include <avogadro/bond.h>
#include <avogadro/color.h>
#include <avogadro/glwidget.h>
#include <avogadro/painterdevice.h>
#include <avogadro/neighborlist.h>
#include <openbabel/mol.h>
#include <openbabel/obiter.h>
#include <QMessageBox>
#include <QString>
#include <QDebug>
using namespace std;
using namespace OpenBabel;
using namespace Eigen;
namespace Avogadro {
HBondEngine::HBondEngine(QObject *parent) : Engine(parent), m_settingsWidget(0),
m_width(2), m_radius(2.0), m_angle(120)
{
}
Engine *HBondEngine::clone() const
{
HBondEngine *engine = new HBondEngine(parent());
engine->setAlias(alias());
engine->setWidth(m_width);
engine->setRadius(m_radius);
engine->setAngle(m_angle);
engine->setEnabled(isEnabled());
return engine;
}
HBondEngine::~HBondEngine()
{
}
unsigned long createUniqueHbondId(Atom *donorH, Atom *acceptor)
{
return acceptor->index() * static_cast<Molecule*>(acceptor->parent())->numAtoms() + donorH->index();
}
bool HBondEngine::renderOpaque(PainterDevice *pd)
{
Molecule *molecule = const_cast<Molecule *>(pd->molecule());
if (!molecule->numAtoms())
return false;
pd->painter()->setColor(1.0, 1.0, 0.3);
int stipple = 0xF0F0; // pattern for lines
QList<unsigned long> rendered;
NeighborList *nbrList = new NeighborList(molecule, m_radius);
//for (unsigned int i = 0; i < molecule->numAtoms(); ++i) {
foreach(Atom *atom, atoms()) {
bool atomIsH = atom->isHydrogen() ? true : false;
if (!atomIsH && !isHbondAcceptor(atom))
continue;
// get ALL possible pairs for atom (uniqueOnly = false)
QList<Atom*> nbrs = nbrList->nbrs(atom, false);
foreach(Atom *nbr, nbrs) {
double angle = 180.0;
Atom *hydrogen, *acceptor, *donor = 0;
if (atomIsH) {
if (!isHbondDonorH(atom) || !isHbondAcceptor(nbr))
continue;
hydrogen = atom;
acceptor = nbr;
foreach (unsigned long id, atom->neighbors())
donor = static_cast<Molecule*>(atom->parent())->atomById(id);
} else {
if (!isHbondDonorH(nbr) || !isHbondAcceptor(atom))
continue;
hydrogen = nbr;
acceptor = atom;
foreach (unsigned long id, nbr->neighbors())
donor = static_cast<Molecule*>(atom->parent())->atomById(id);
}
if (donor) {
Eigen::Vector3d ab = *donor->pos() - *hydrogen->pos();
Eigen::Vector3d bc = *acceptor->pos() - *hydrogen->pos();
angle = 180. * acos( ab.dot(bc) / (ab.norm() * bc.norm()) ) / M_PI;
}
if (angle < m_angle)
continue;
unsigned long HbondId = createUniqueHbondId(hydrogen, acceptor);
if (rendered.contains(HbondId))
continue;
rendered.append(HbondId);
pd->painter()->drawMultiLine(*atom->pos(), *nbr->pos(), m_width, 1, stipple);
} // for each nbr
} // for each atom
return true;
}
double HBondEngine::radius(const PainterDevice *, const Primitive *) const
{
return 0.0;
}
QWidget* HBondEngine::settingsWidget()
{
if(!m_settingsWidget)
{
m_settingsWidget = new HBondSettingsWidget();
connect(m_settingsWidget->widthSlider, SIGNAL(valueChanged(int)), this, SLOT(setWidth(int)));
connect(m_settingsWidget->radiusSpin, SIGNAL(valueChanged(double)), this, SLOT(setRadius(double)));
connect(m_settingsWidget->angleSpin, SIGNAL(valueChanged(double)), this, SLOT(setAngle(double)));
connect(m_settingsWidget, SIGNAL(destroyed()), this, SLOT(settingsWidgetDestroyed()));
m_settingsWidget->widthSlider->setValue(m_width);
m_settingsWidget->radiusSpin->setValue(m_radius);
m_settingsWidget->angleSpin->setValue(m_angle);
}
return m_settingsWidget;
}
void HBondEngine::setWidth(int value)
{
m_width = value;
emit changed();
}
void HBondEngine::setRadius(double value)
{
m_radius = value;
emit changed();
}
void HBondEngine::setAngle(double value)
{
m_angle = value;
emit changed();
}
void HBondEngine::settingsWidgetDestroyed()
{
m_settingsWidget = 0;
}
void HBondEngine::writeSettings(QSettings &settings) const
{
Engine::writeSettings(settings);
settings.setValue("width", m_width);
settings.setValue("radius", m_radius);
settings.setValue("angle", m_angle);
}
void HBondEngine::readSettings(QSettings &settings)
{
Engine::readSettings(settings);
setWidth(settings.value("width", 2).toInt());
setRadius(settings.value("radius", 2.0).toDouble());
setAngle(settings.value("angle", 120.0).toDouble());
if (m_settingsWidget) {
m_settingsWidget->widthSlider->setValue(m_width);
m_settingsWidget->radiusSpin->setValue(m_radius);
m_settingsWidget->angleSpin->setValue(m_angle);
}
}
bool HBondEngine::isHbondAcceptor(Atom *atom)
{
if (atom->atomicNumber() == 8 || atom->atomicNumber() == 9)
return true;
if (atom->atomicNumber() == 7) {
int boSum = 0;
Molecule *mol = atom->molecule();
if (mol) {
foreach (unsigned long id, atom->bonds())
boSum += mol->bondById(id)->order();
if (boSum != 4)
return true;
}
}
return false;
}
bool HBondEngine::isHbondDonor(Atom *atom)
{
switch (atom->atomicNumber()) {
case 7:
case 8:
case 9:
break;
default:
return false;
}
foreach (unsigned long id, atom->neighbors()) {
Atom *nbr = static_cast<Molecule*>(atom->parent())->atomById(id);
if (nbr->isHydrogen())
return true;
}
return false;
}
bool HBondEngine::isHbondDonorH(Atom *atom)
{
if (!atom->isHydrogen())
return false;
foreach (unsigned long id, atom->neighbors()) {
Atom *nbr = static_cast<Molecule*>(atom->parent())->atomById(id);
if (isHbondDonor(nbr))
return true;
}
return false;
}
}
Q_EXPORT_PLUGIN2(hbondengine, Avogadro::HBondEngineFactory)
| {
"content_hash": "b37d2df797dd067387eae3b9afaf3dce",
"timestamp": "",
"source": "github",
"line_count": 235,
"max_line_length": 107,
"avg_line_length": 26.629787234042553,
"alnum_prop": 0.6124960051134548,
"repo_name": "jjenki11/blaze-chem-rendering",
"id": "1c3fc0a5ad1b26e30c7aa9ed108aa627b11c6b2f",
"size": "7355",
"binary": false,
"copies": "3",
"ref": "refs/heads/master",
"path": "avogadro/avogadro-1.1.1/libavogadro/src/engines/hbondengine.cpp",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Shell",
"bytes": "2476"
}
],
"symlink_target": ""
} |
package org.zstack.network.l2;
import org.springframework.beans.factory.annotation.Autowired;
import org.zstack.core.Platform;
import org.zstack.core.cloudbus.CloudBus;
import org.zstack.core.cloudbus.CloudBusListCallBack;
import org.zstack.core.cloudbus.MessageSafe;
import org.zstack.core.componentloader.PluginRegistry;
import org.zstack.core.db.DatabaseFacade;
import org.zstack.core.db.DbEntityLister;
import org.zstack.core.db.SimpleQuery;
import org.zstack.core.errorcode.ErrorFacade;
import org.zstack.header.errorcode.SysErrors;
import org.zstack.header.AbstractService;
import org.zstack.header.core.Completion;
import org.zstack.header.errorcode.ErrorCode;
import org.zstack.header.exception.CloudRuntimeException;
import org.zstack.header.host.HostAddExtensionPoint;
import org.zstack.header.host.HostInventory;
import org.zstack.header.host.HypervisorType;
import org.zstack.header.message.APIMessage;
import org.zstack.header.message.Message;
import org.zstack.header.message.MessageReply;
import org.zstack.header.network.*;
import org.zstack.header.network.l2.*;
import org.zstack.search.GetQuery;
import org.zstack.search.SearchQuery;
import org.zstack.tag.TagManager;
import org.zstack.utils.ObjectUtils;
import org.zstack.utils.Utils;
import org.zstack.utils.logging.CLogger;
import java.util.*;
public class L2NetworkManagerImpl extends AbstractService implements L2NetworkManager, HostAddExtensionPoint {
private static final CLogger logger = Utils.getLogger(L2NetworkManagerImpl.class);
@Autowired
private CloudBus bus;
@Autowired
private DatabaseFacade dbf;
@Autowired
private PluginRegistry pluginRgty;
@Autowired
private DbEntityLister dl;
@Autowired
private TagManager tagMgr;
@Autowired
private ErrorFacade errf;
private Map<String, L2NetworkFactory> l2NetworkFactories = Collections.synchronizedMap(new HashMap<String, L2NetworkFactory>());
private Map<L2NetworkType, Map<HypervisorType, L2NetworkRealizationExtensionPoint>> realizationExts = new HashMap<L2NetworkType, Map<HypervisorType, L2NetworkRealizationExtensionPoint>>();
private List<L2NetworkCreateExtensionPoint> createExtensions = new ArrayList<L2NetworkCreateExtensionPoint>();
private static final Set<Class> allowedMessageAfterSoftDeletion = new HashSet<Class>();
static {
allowedMessageAfterSoftDeletion.add(L2NetworkDeletionMsg.class);
}
@Override
@MessageSafe
public void handleMessage(Message msg) {
if (msg instanceof APIMessage) {
handleApiMessage((APIMessage)msg);
} else {
handleLocalMessage(msg);
}
}
private void handleLocalMessage(Message msg) {
if (msg instanceof L2NetworkMessage) {
passThrough((L2NetworkMessage)msg);
} else {
bus.dealWithUnknownMessage(msg);
}
}
private void handleApiMessage(APIMessage msg) {
if (msg instanceof APICreateL2NetworkMsg) {
handle((APICreateL2NetworkMsg)msg);
} else if (msg instanceof APIListL2NetworkMsg) {
handle((APIListL2NetworkMsg) msg);
} else if (msg instanceof APISearchL2NetworkMsg) {
handle((APISearchL2NetworkMsg)msg);
} else if (msg instanceof APISearchL2VlanNetworkMsg) {
handle((APISearchL2VlanNetworkMsg)msg);
} else if (msg instanceof APIGetL2NetworkMsg) {
handle((APIGetL2NetworkMsg) msg);
} else if (msg instanceof APIGetL2VlanNetworkMsg) {
handle((APIGetL2VlanNetworkMsg)msg);
} else if (msg instanceof APIGetL2NetworkTypesMsg) {
handle((APIGetL2NetworkTypesMsg) msg);
} else if (msg instanceof L2NetworkMessage) {
passThrough((L2NetworkMessage) msg);
} else {
bus.dealWithUnknownMessage(msg);
}
}
private void handle(APIGetL2NetworkTypesMsg msg) {
List<String> types = new ArrayList<String>();
types.addAll(L2NetworkType.getAllTypeNames());
APIGetL2NetworkTypesReply reply = new APIGetL2NetworkTypesReply();
reply.setL2NetworkTypes(types);
bus.reply(msg, reply);
}
private void handle(APIGetL2VlanNetworkMsg msg) {
GetQuery q = new GetQuery();
String res = q.getAsString(msg, L2VlanNetworkInventory.class);
APIGetL2VlanNetworkReply reply = new APIGetL2VlanNetworkReply();
reply.setInventory(res);
bus.reply(msg, reply);
}
private void handle(APISearchL2VlanNetworkMsg msg) {
SearchQuery<L2VlanNetworkInventory> sq = SearchQuery.create(msg, L2VlanNetworkInventory.class);
String content = sq.listAsString();
APISearchL2VlanNetworkReply reply = new APISearchL2VlanNetworkReply();
reply.setContent(content);
bus.reply(msg, reply);
}
private void handle(APIGetL2NetworkMsg msg) {
GetQuery q = new GetQuery();
String res = q.getAsString(msg, L2NetworkInventory.class);
APIGetL2NetworkReply reply = new APIGetL2NetworkReply();
reply.setInventory(res);
bus.reply(msg, reply);
}
private void handle(APISearchL2NetworkMsg msg) {
SearchQuery<L2NetworkInventory> sq = SearchQuery.create(msg, L2NetworkInventory.class);
String content = sq.listAsString();
APISearchL2NetworkReply reply = new APISearchL2NetworkReply();
reply.setContent(content);
bus.reply(msg, reply);
}
private void passThrough(L2NetworkMessage msg) {
Message amsg = (Message) msg;
L2NetworkVO vo = dbf.findByUuid(msg.getL2NetworkUuid(), L2NetworkVO.class);
if (vo == null && allowedMessageAfterSoftDeletion.contains(msg.getClass())) {
L2NetworkEO eo = dbf.findByUuid(msg.getL2NetworkUuid(), L2NetworkEO.class);
vo = ObjectUtils.newAndCopy(eo, L2NetworkVO.class);
}
if (vo == null) {
ErrorCode errCode = errf.instantiateErrorCode(SysErrors.RESOURCE_NOT_FOUND, String.format("unable to find L2Network[uuid:%s], it may have been deleted", msg.getL2NetworkUuid()));
bus.replyErrorByMessageType((Message)msg, errCode);
return;
}
L2NetworkFactory factory = getL2NetworkFactory(L2NetworkType.valueOf(vo.getType()));
L2Network nw = factory.getL2Network(vo);
nw.handleMessage(amsg);
}
private void handle(APIListL2NetworkMsg msg) {
List<L2NetworkVO> vos = dl.listByApiMessage(msg, L2NetworkVO.class);
List<L2NetworkInventory> invs = L2NetworkInventory.valueOf(vos);
APIListL2NetworkReply reply = new APIListL2NetworkReply();
reply.setInventories(invs);
bus.reply(msg, reply);
}
private void handle(APICreateL2NetworkMsg msg) {
for (L2NetworkCreateExtensionPoint extp : createExtensions) {
try {
extp.beforeCreateL2Network(msg);
} catch (NetworkException e) {
String err = String.format("unable to create l2network[name:%s, type:%s], %s", msg.getName(), msg.getType(), e.getMessage());
logger.warn(err, e);
APICreateL2NetworkEvent evt = new APICreateL2NetworkEvent(msg.getId());
evt.setError(errf.instantiateErrorCode(SysErrors.CREATE_RESOURCE_ERROR, err));
bus.publish(evt);
return;
}
}
L2NetworkType type = L2NetworkType.valueOf(msg.getType());
L2NetworkFactory factory = getL2NetworkFactory(type);
L2NetworkVO vo = new L2NetworkVO();
if (msg.getResourceUuid() != null) {
vo.setUuid(msg.getResourceUuid());
} else {
vo.setUuid(Platform.getUuid());
}
vo.setDescription(msg.getDescription());
vo.setName(msg.getName());
vo.setPhysicalInterface(msg.getPhysicalInterface());
vo.setType(type.toString());
vo.setZoneUuid(msg.getZoneUuid());
L2NetworkInventory inv = factory.createL2Network(vo, msg);
tagMgr.createTagsFromAPICreateMessage(msg, inv.getUuid(), L2NetworkVO.class.getSimpleName());
for (L2NetworkCreateExtensionPoint extp : createExtensions) {
try {
extp.afterCreateL2Network(inv);
} catch (Exception e) {
logger.warn(String.format("unhandled exception happened when calling %s", extp.getClass().getName()), e);
}
}
APICreateL2NetworkEvent evt = new APICreateL2NetworkEvent(msg.getId());
evt.setInventory(inv);
bus.publish(evt);
}
@Override
public String getId() {
return bus.makeLocalServiceId(L2NetworkConstant.SERVICE_ID);
}
@Override
public boolean start() {
populateExtensions();
return true;
}
@Override
public boolean stop() {
return false;
}
@Override
public L2NetworkFactory getL2NetworkFactory(L2NetworkType type) {
L2NetworkFactory factory = l2NetworkFactories.get(type.toString());
if (factory == null) {
throw new CloudRuntimeException(String.format("Cannot find L2NetworkFactory for type(%s)", type));
}
return factory;
}
@Override
public L2NetworkRealizationExtensionPoint getRealizationExtension(L2NetworkType l2Type, HypervisorType hvType) {
Map<HypervisorType, L2NetworkRealizationExtensionPoint> map = realizationExts.get(l2Type);
if (map == null) {
throw new IllegalArgumentException(String.format("Cannot find L2NetworkRealizationExtensionPoint supporting L2NetworkType[%s]", l2Type));
}
L2NetworkRealizationExtensionPoint extp = map.get(hvType);
if (extp == null) {
throw new IllegalArgumentException(String.format("Cannot find L2NetworkRealizationExtensionPoint for L2NetworkType[%s] supporting hypervisor[%s]", l2Type, hvType));
}
return extp;
}
private void populateExtensions() {
for (L2NetworkFactory f : pluginRgty.getExtensionList(L2NetworkFactory.class)) {
L2NetworkFactory old = l2NetworkFactories.get(f.getType().toString());
if (old != null) {
throw new CloudRuntimeException(String.format("duplicate L2NetworkFactory[%s, %s] for type[%s]",
f.getClass().getName(), old.getClass().getName(), f.getType()));
}
l2NetworkFactories.put(f.getType().toString(), f);
}
for (L2NetworkRealizationExtensionPoint extp : pluginRgty.getExtensionList(L2NetworkRealizationExtensionPoint.class)) {
Map<HypervisorType, L2NetworkRealizationExtensionPoint> map = realizationExts.get(extp.getSupportedL2NetworkType());
if (map == null) {
map = new HashMap<HypervisorType, L2NetworkRealizationExtensionPoint>(1);
realizationExts.put(extp.getSupportedL2NetworkType(), map);
}
map.put(extp.getSupportedHypervisorType(), extp);
}
createExtensions = pluginRgty.getExtensionList(L2NetworkCreateExtensionPoint.class);
}
@Override
public void beforeAddHost(HostInventory host, Completion completion) {
completion.success();
}
@Override
public void afterAddHost(HostInventory host, final Completion completion) {
SimpleQuery<L2NetworkClusterRefVO> q = dbf.createQuery(L2NetworkClusterRefVO.class);
q.select(L2NetworkClusterRefVO_.l2NetworkUuid);
q.add(L2NetworkClusterRefVO_.clusterUuid, SimpleQuery.Op.EQ, host.getClusterUuid());
List<String> l2uuids = q.listValue();
if (l2uuids.isEmpty()) {
completion.success();
return;
}
List<PrepareL2NetworkOnHostMsg> msgs = new ArrayList<PrepareL2NetworkOnHostMsg>();
for (String l2uuid : l2uuids) {
PrepareL2NetworkOnHostMsg msg = new PrepareL2NetworkOnHostMsg();
msg.setL2NetworkUuid(l2uuid);
msg.setHost(host);
bus.makeTargetServiceIdByResourceUuid(msg, L2NetworkConstant.SERVICE_ID, l2uuid);
msgs.add(msg);
}
bus.send(msgs, new CloudBusListCallBack(completion) {
@Override
public void run(List<MessageReply> replies) {
for (MessageReply reply : replies) {
if (!reply.isSuccess()) {
completion.fail(reply.getError());
return;
}
}
completion.success();
}
});
}
}
| {
"content_hash": "beb1c17e4f18a901669a6ba636c3b1a5",
"timestamp": "",
"source": "github",
"line_count": 314,
"max_line_length": 192,
"avg_line_length": 39.8343949044586,
"alnum_prop": 0.6767668692037097,
"repo_name": "hhjuliet/zstack",
"id": "13cccb67f47de66bebd6024eb7fc475db1a667db",
"size": "12508",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "network/src/main/java/org/zstack/network/l2/L2NetworkManagerImpl.java",
"mode": "33261",
"license": "apache-2.0",
"language": [
{
"name": "AspectJ",
"bytes": "55279"
},
{
"name": "Batchfile",
"bytes": "1132"
},
{
"name": "Groovy",
"bytes": "830536"
},
{
"name": "Java",
"bytes": "15642072"
},
{
"name": "Shell",
"bytes": "152829"
}
],
"symlink_target": ""
} |
/**
* Interface for build configuration command parameters.
*/
import { BuildConfigurationOperation } from "./buildConfigurationOperation";
import { IEngineCommandParams } from "./IEngineCommandParams";
export interface IBuildConfigurationCommandParams extends IEngineCommandParams {
operation: BuildConfigurationOperation | undefined | null;
configurationName: string | undefined | null;
bundle: boolean | undefined;
minify: boolean | undefined;
sourcemaps: boolean | undefined;
pwa: boolean | undefined;
}
| {
"content_hash": "0b2f20ce78a06041ee858a2207e79ad8",
"timestamp": "",
"source": "github",
"line_count": 13,
"max_line_length": 80,
"avg_line_length": 41.07692307692308,
"alnum_prop": 0.7659176029962547,
"repo_name": "unitejs/engine",
"id": "35a500a528278e55793a8116f49d7dcdde74203a",
"size": "534",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "dist/interfaces/IBuildConfigurationCommandParams.d.ts",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "9458"
},
{
"name": "HTML",
"bytes": "1359"
},
{
"name": "JavaScript",
"bytes": "58087"
},
{
"name": "TypeScript",
"bytes": "1692524"
},
{
"name": "Vue",
"bytes": "409"
}
],
"symlink_target": ""
} |
package io.github.jayin.test2;
import java.util.List;
import android.content.Context;
import com.annotation.Unique;
import com.annotation.core.Creator;
import com.annotation.core.Model;
public class CreatorTest extends BaseTest{
public CreatorTest(Context context) {
super(context);
}
@Override
protected void testQueue() throws Exception {
create_test1();
}
public void create_test1() throws Exception{
String sql =new Creator().from(Student.class).build();
if(!sql.equals("Create Table Student (name TEXT ,id INTEGER Unique,age INTEGER ,height INTEGER ,wight INTEGER ,__id INTEGER )")){
throw new Exception("CreatorTest Error");
}
}
}
class Student extends Human {
@Unique
long id;
int age;
String name;
List<Integer> friendid;
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public List<Integer> getFriendid() {
return friendid;
}
public void setFriendid(List<Integer> friendid) {
this.friendid = friendid;
}
}
class Human extends Model {
int height;
int wight;
public int getHeight() {
return height;
}
public void setHeight(int height) {
this.height = height;
}
public int getWight() {
return wight;
}
public void setWight(int wight) {
this.wight = wight;
}
}
| {
"content_hash": "182ddfed4f328d3ff5489f4b3ebba759",
"timestamp": "",
"source": "github",
"line_count": 99,
"max_line_length": 131,
"avg_line_length": 16.1010101010101,
"alnum_prop": 0.6424090338770388,
"repo_name": "Jayin/SORM",
"id": "fcc18b1016d868fbb39b0c33e9f26a9cfa425c96",
"size": "1594",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "test/src/io/github/jayin/test2/CreatorTest.java",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Java",
"bytes": "62945"
}
],
"symlink_target": ""
} |
export type ValidatorRuleType =
RegExp
| Function;
export type ValidatorTextType =
'string'
| Function;
export interface IValidator {
name: string;
rule: ValidatorRuleType;
text: ValidatorTextType;
}
| {
"content_hash": "f0c0340d9c61ef2db963c56e485f4603",
"timestamp": "",
"source": "github",
"line_count": 14,
"max_line_length": 32,
"avg_line_length": 16.642857142857142,
"alnum_prop": 0.6824034334763949,
"repo_name": "xio4/unibot-manager",
"id": "2d7f3aa6293e6851551f4d5f23ee7aee6fb09cdf",
"size": "233",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/components/ui/form/validators/validatorTypes.ts",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "2260"
},
{
"name": "JavaScript",
"bytes": "10429"
},
{
"name": "Smarty",
"bytes": "391"
},
{
"name": "TypeScript",
"bytes": "23101"
}
],
"symlink_target": ""
} |
package com.star.tinker;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.Window;
import android.view.WindowManager;
import com.andrognito.patternlockview.PatternLockView;
import com.andrognito.patternlockview.listener.PatternLockViewListener;
import com.andrognito.patternlockview.utils.PatternLockUtils;
import com.andrognito.patternlockview.utils.ResourceUtils;
import com.andrognito.rxpatternlockview.RxPatternLockView;
import com.andrognito.rxpatternlockview.events.PatternLockCompleteEvent;
import com.andrognito.rxpatternlockview.events.PatternLockCompoundEvent;
import java.util.List;
import io.reactivex.functions.Consumer;
public class LockPatternActivity extends AppCompatActivity {
public static final String TAG = "MainActivity";
private PatternLockView mPatternLockView;
private PatternLockViewListener mPatternLockViewListener = new PatternLockViewListener() {
@Override
public void onStarted() {
Log.d(TAG, "Pattern drawing started");
}
@Override
public void onProgress(List<PatternLockView.Dot> progressPattern) {
Log.d(TAG, "Pattern progress: " +
PatternLockUtils.patternToString(mPatternLockView, progressPattern));
}
@Override
public void onComplete(List<PatternLockView.Dot> pattern) {
Log.d(TAG, "Pattern complete: " +
PatternLockUtils.patternToString(mPatternLockView, pattern));
Intent intent = new Intent(LockPatternActivity.this, MainActivity.class);
startActivity(intent);
finish();
}
@Override
public void onCleared() {
Log.d(TAG, "Pattern has been cleared");
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.activity_lock_pattern);
mPatternLockView = (PatternLockView) findViewById(R.id.patter_lock_view);
mPatternLockView.setDotCount(3);
mPatternLockView.setDotNormalSize((int) ResourceUtils.getDimensionInPx(this, R.dimen.pattern_lock_dot_size));
mPatternLockView.setDotSelectedSize((int) ResourceUtils.getDimensionInPx(this, R.dimen.pattern_lock_dot_selected_size));
mPatternLockView.setPathWidth((int) ResourceUtils.getDimensionInPx(this, R.dimen.pattern_lock_path_width));
mPatternLockView.setAspectRatioEnabled(true);
mPatternLockView.setAspectRatio(PatternLockView.AspectRatio.ASPECT_RATIO_HEIGHT_BIAS);
mPatternLockView.setViewMode(PatternLockView.PatternViewMode.CORRECT);
mPatternLockView.setDotAnimationDuration(150);
mPatternLockView.setPathEndAnimationDuration(100);
mPatternLockView.setCorrectStateColor(ResourceUtils.getColor(this, R.color.white));
mPatternLockView.setInStealthMode(false);
mPatternLockView.setTactileFeedbackEnabled(true);
mPatternLockView.setInputEnabled(true);
mPatternLockView.addPatternLockListener(mPatternLockViewListener);
RxPatternLockView.patternComplete(mPatternLockView)
.subscribe(new Consumer<PatternLockCompleteEvent>() {
@Override
public void accept(PatternLockCompleteEvent patternLockCompleteEvent) throws Exception {
Log.d(TAG, "Complete: " + patternLockCompleteEvent.getPattern().toString());
}
});
RxPatternLockView.patternChanges(mPatternLockView)
.subscribe(new Consumer<PatternLockCompoundEvent>() {
@Override
public void accept(PatternLockCompoundEvent event) throws Exception {
if (event.getEventType() == PatternLockCompoundEvent.EventType.PATTERN_STARTED) {
Log.d(TAG, "Pattern drawing started");
} else if (event.getEventType() == PatternLockCompoundEvent.EventType.PATTERN_PROGRESS) {
Log.d(TAG, "Pattern progress: " +
PatternLockUtils.patternToString(mPatternLockView, event.getPattern()));
} else if (event.getEventType() == PatternLockCompoundEvent.EventType.PATTERN_COMPLETE) {
Log.d(TAG, "Pattern complete: " +
PatternLockUtils.patternToString(mPatternLockView, event.getPattern()));
} else if (event.getEventType() == PatternLockCompoundEvent.EventType.PATTERN_CLEARED) {
Log.d(TAG, "Pattern has been cleared");
}
}
});
}
}
| {
"content_hash": "d8b9ef8cc2612b722f19754ad3686e00",
"timestamp": "",
"source": "github",
"line_count": 103,
"max_line_length": 128,
"avg_line_length": 48.699029126213595,
"alnum_prop": 0.6732456140350878,
"repo_name": "xingstarx/TinkerDemo",
"id": "dd94784d0d22ae70ebbb2de9d713060406bdd56a",
"size": "5016",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "app/src/main/java/com/star/tinker/LockPatternActivity.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Java",
"bytes": "80522"
}
],
"symlink_target": ""
} |
package com.amazonaws.services.gamelift.model;
import javax.annotation.Generated;
/**
*
*/
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public enum PlayerSessionStatus {
RESERVED("RESERVED"),
ACTIVE("ACTIVE"),
COMPLETED("COMPLETED"),
TIMEDOUT("TIMEDOUT");
private String value;
private PlayerSessionStatus(String value) {
this.value = value;
}
@Override
public String toString() {
return this.value;
}
/**
* Use this in place of valueOf.
*
* @param value
* real value
* @return PlayerSessionStatus corresponding to the value
*
* @throws IllegalArgumentException
* If the specified value does not map to one of the known values in this enum.
*/
public static PlayerSessionStatus fromValue(String value) {
if (value == null || "".equals(value)) {
throw new IllegalArgumentException("Value cannot be null or empty!");
}
for (PlayerSessionStatus enumEntry : PlayerSessionStatus.values()) {
if (enumEntry.toString().equals(value)) {
return enumEntry;
}
}
throw new IllegalArgumentException("Cannot create enum from " + value + " value!");
}
}
| {
"content_hash": "2f0dd946ed25e77952f6bd84184eac22",
"timestamp": "",
"source": "github",
"line_count": 51,
"max_line_length": 91,
"avg_line_length": 25.137254901960784,
"alnum_prop": 0.6154446177847114,
"repo_name": "aws/aws-sdk-java",
"id": "90f530d9c83397d42a9354c6a75a8b7f0ce152de",
"size": "1862",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "aws-java-sdk-gamelift/src/main/java/com/amazonaws/services/gamelift/model/PlayerSessionStatus.java",
"mode": "33188",
"license": "apache-2.0",
"language": [],
"symlink_target": ""
} |
<?php
namespace Gojira\Framework\Encryption;
use Gojira\Framework\App\Configuration\Configuration;
use Gojira\Framework\Math\Random;
/**
* Class Encryptor provides basic logic for hashing strings and encrypting/decrypting misc data
*
* @package Gojira\Framework\Encryption
* @author Toan Nguyen <me@nntoan.com>
*/
class Encryptor implements EncryptorInterface
{
/**
* Array key of encryption key in deployment config
*/
const PARAM_CRYPT_KEY = 'options/encryption_key';
/**#@+
* Cipher versions
*/
const CIPHER_BLOWFISH = 0;
const CIPHER_RIJNDAEL_128 = 1;
const CIPHER_RIJNDAEL_256 = 2;
const CIPHER_LATEST = 2;
/**#@-*/
/**
* Indicate cipher
*
* @var int
*/
protected $cipher = self::CIPHER_LATEST;
/**
* Version of encryption key
*
* @var int
*/
protected $keyVersion;
/**
* Array of encryption keys
*
* @var string[]
*/
protected $keys = [];
/**
* Random generator
*
* @var Random
*/
protected $random;
/**
* @param Random $random
* @param Configuration $configuration
*/
public function __construct(
Random $random,
Configuration $configuration
) {
$this->random = $random;
// load all possible keys
$this->keys = preg_split('/\s+/s', trim($configuration->getData(self::PARAM_CRYPT_KEY)));
$this->keyVersion = count($this->keys) - 1;
}
/**
* Check whether specified cipher version is supported
*
* Returns matched supported version or throws exception
*
* @param int $version
*
* @return int
* @throws \Exception
*/
public function validateCipher($version)
{
$types = [self::CIPHER_BLOWFISH, self::CIPHER_RIJNDAEL_128, self::CIPHER_RIJNDAEL_256];
$version = (int)$version;
if (!in_array($version, $types, true)) {
throw new \Exception((string)new \Gojira\Framework\Phrase('Not supported cipher version'));
}
return $version;
}
/**
* Prepend key and cipher versions to encrypted data after encrypting
*
* @param string $data
*
* @return string
*/
public function encrypt($data)
{
$crypt = $this->getCrypt();
if (null === $crypt) {
return $data;
}
return $this->keyVersion . ':' . $this->cipher . ':' . (MCRYPT_MODE_CBC ===
$crypt->getMode() ? $crypt->getInitVector() . ':' : '') . base64_encode(
$crypt->encrypt((string)$data)
);
}
/**
* Look for key and crypt versions in encrypted data before decrypting
*
* Unsupported/unspecified key version silently fallback to the oldest we have
* Unsupported cipher versions eventually throw exception
* Unspecified cipher version fallback to the oldest we support
*
* @param string $data
*
* @return string
*/
public function decrypt($data)
{
if ($data) {
$parts = explode(':', $data, 4);
$partsCount = count($parts);
$initVector = false;
// specified key, specified crypt, specified iv
if (4 === $partsCount) {
list($keyVersion, $cryptVersion, $iv, $data) = $parts;
$initVector = $iv ? $iv : false;
$keyVersion = (int)$keyVersion;
$cryptVersion = self::CIPHER_RIJNDAEL_256;
// specified key, specified crypt
} elseif (3 === $partsCount) {
list($keyVersion, $cryptVersion, $data) = $parts;
$keyVersion = (int)$keyVersion;
$cryptVersion = (int)$cryptVersion;
// no key version = oldest key, specified crypt
} elseif (2 === $partsCount) {
list($cryptVersion, $data) = $parts;
$keyVersion = 0;
$cryptVersion = (int)$cryptVersion;
// no key version = oldest key, no crypt version = oldest crypt
} elseif (1 === $partsCount) {
$keyVersion = 0;
$cryptVersion = self::CIPHER_BLOWFISH;
// not supported format
} else {
return '';
}
// no key for decryption
if (!isset($this->keys[$keyVersion])) {
return '';
}
$crypt = $this->getCrypt($this->keys[$keyVersion], $cryptVersion, $initVector);
if (null === $crypt) {
return '';
}
return trim($crypt->decrypt(base64_decode((string)$data)));
}
return '';
}
/**
* Return crypt model, instantiate if it is empty
*
* @param string|null $key NULL value means usage of the default key specified on constructor
*
* @return \Gojira\Framework\Encryption\Crypt
* @throws \Exception
*/
public function validateKey($key)
{
if (preg_match('/\s/s', $key)) {
throw new \Exception((string)new \Gojira\Framework\Phrase('The encryption key format is invalid.'));
}
return $this->getCrypt($key);
}
/**
* Attempt to append new key & version
*
* @param string $key
*
* @return $this
*/
public function setNewKey($key)
{
$this->validateKey($key);
$this->keys[] = $key;
$this->keyVersion += 1;
return $this;
}
/**
* Export current keys as string
*
* @return string
*/
public function exportKeys()
{
return implode("\n", $this->keys);
}
/**
* Initialize crypt module if needed
*
* By default initializes with latest key and crypt versions
*
* @param string $key
* @param int $cipherVersion
* @param bool $initVector
*
* @return Crypt|null
*/
protected function getCrypt($key = null, $cipherVersion = null, $initVector = true)
{
if (null === $key && null === $cipherVersion) {
$cipherVersion = self::CIPHER_RIJNDAEL_256;
}
if (null === $key) {
$key = $this->keys[$this->keyVersion];
}
if (!$key) {
return null;
}
if (null === $cipherVersion) {
$cipherVersion = $this->cipher;
}
$cipherVersion = $this->validateCipher($cipherVersion);
if ($cipherVersion === self::CIPHER_RIJNDAEL_128) {
$cipher = MCRYPT_RIJNDAEL_128;
$mode = MCRYPT_MODE_ECB;
} elseif ($cipherVersion === self::CIPHER_RIJNDAEL_256) {
$cipher = MCRYPT_RIJNDAEL_256;
$mode = MCRYPT_MODE_CBC;
} else {
$cipher = MCRYPT_BLOWFISH;
$mode = MCRYPT_MODE_ECB;
}
return new Crypt($key, $cipher, $mode, $initVector);
}
}
| {
"content_hash": "003d0cef23ff729e69d8d1b0b9768c71",
"timestamp": "",
"source": "github",
"line_count": 256,
"max_line_length": 112,
"avg_line_length": 27.2265625,
"alnum_prop": 0.530416068866571,
"repo_name": "nntoan/Gojira",
"id": "9532fcb4420231175691c9f52460ee7385b259a3",
"size": "7162",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/Gojira/Framework/Encryption/Encryptor.php",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "PHP",
"bytes": "210253"
},
{
"name": "Shell",
"bytes": "69"
}
],
"symlink_target": ""
} |
package org.ovirt.engine.ui.uicompat;
public interface IEventListener
{
void eventRaised(Event ev, Object sender, EventArgs args);
}
| {
"content_hash": "a1cb870e33981d868610c82248e774b0",
"timestamp": "",
"source": "github",
"line_count": 6,
"max_line_length": 62,
"avg_line_length": 23,
"alnum_prop": 0.7753623188405797,
"repo_name": "phoenixsbk/kvmmgr",
"id": "1fb64712868f6d54fa42306111a99da5887ea62a",
"size": "138",
"binary": false,
"copies": "3",
"ref": "refs/heads/master",
"path": "frontend/webadmin/modules/uicompat/src/main/java/org/ovirt/engine/ui/uicompat/IEventListener.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "2890497"
},
{
"name": "Groff",
"bytes": "10684"
},
{
"name": "HTML",
"bytes": "343765"
},
{
"name": "Java",
"bytes": "24621295"
},
{
"name": "JavaScript",
"bytes": "3433498"
},
{
"name": "Makefile",
"bytes": "23292"
},
{
"name": "PLSQL",
"bytes": "102200"
},
{
"name": "PLpgSQL",
"bytes": "62779"
},
{
"name": "Python",
"bytes": "757075"
},
{
"name": "SQLPL",
"bytes": "352649"
},
{
"name": "Shell",
"bytes": "119317"
},
{
"name": "SourcePawn",
"bytes": "1565"
},
{
"name": "XSLT",
"bytes": "18407"
}
],
"symlink_target": ""
} |
/* Define to prevent recursive inclusion -------------------------------------*/
#ifndef STM32H7xx_LL_FMAC_H
#define STM32H7xx_LL_FMAC_H
#ifdef __cplusplus
extern "C" {
#endif
/* Includes ------------------------------------------------------------------*/
#include "stm32h7xx.h"
/** @addtogroup STM32H7xx_LL_Driver
* @{
*/
#if defined(FMAC)
/** @defgroup FMAC_LL FMAC
* @{
*/
/* Exported types ------------------------------------------------------------*/
/* Exported constants --------------------------------------------------------*/
/** @defgroup FMAC_LL_Exported_Constants FMAC Exported Constants
* @{
*/
/** @defgroup FMAC_LL_EC_GET_FLAG Get Flag Defines
* @brief Flag defines which can be used with LL_FMAC_ReadReg function
* @{
*/
#define LL_FMAC_SR_SAT FMAC_SR_SAT /*!< Saturation Error Flag (this helps in debugging a filter) */
#define LL_FMAC_SR_UNFL FMAC_SR_UNFL /*!< Underflow Error Flag */
#define LL_FMAC_SR_OVFL FMAC_SR_OVFL /*!< Overflow Error Flag */
#define LL_FMAC_SR_X1FULL FMAC_SR_X1FULL /*!< X1 Buffer Full Flag */
#define LL_FMAC_SR_YEMPTY FMAC_SR_YEMPTY /*!< Y Buffer Empty Flag */
/**
* @}
*/
/** @defgroup FMAC_LL_EC_IT IT Defines
* @brief IT defines which can be used with LL_FMAC_ReadReg and LL_FMAC_WriteReg functions
* @{
*/
#define LL_FMAC_CR_SATIEN FMAC_CR_SATIEN /*!< Saturation Error Interrupt Enable (this helps in debugging a filter) */
#define LL_FMAC_CR_UNFLIEN FMAC_CR_UNFLIEN /*!< Underflow Error Interrupt Enable */
#define LL_FMAC_CR_OVFLIEN FMAC_CR_OVFLIEN /*!< Overflow Error Interrupt Enable */
#define LL_FMAC_CR_WIEN FMAC_CR_WIEN /*!< Write Interrupt Enable */
#define LL_FMAC_CR_RIEN FMAC_CR_RIEN /*!< Read Interrupt Enable */
/**
* @}
*/
/** @defgroup FMAC_LL_EC_WM FMAC watermarks
* @brief Watermark defines that can be used for buffer full (input) or buffer empty (output)
* @{
*/
#define LL_FMAC_WM_0_THRESHOLD_1 0x00000000U /*!< Buffer full/empty flag set if there is less than 1 free/unread space. */
#define LL_FMAC_WM_1_THRESHOLD_2 0x01000000U /*!< Buffer full/empty flag set if there are less than 2 free/unread spaces. */
#define LL_FMAC_WM_2_THRESHOLD_4 0x02000000U /*!< Buffer full/empty flag set if there are less than 4 free/unread spaces. */
#define LL_FMAC_WM_3_THRESHOLD_8 0x03000000U /*!< Buffer full/empty flag set if there are less than 8 free/empty spaces. */
/**
* @}
*/
/** @defgroup FMAC_LL_EC_FUNC FMAC functions
* @{
*/
#define LL_FMAC_FUNC_LOAD_X1 (FMAC_PARAM_FUNC_0) /*!< Load X1 buffer */
#define LL_FMAC_FUNC_LOAD_X2 (FMAC_PARAM_FUNC_1) /*!< Load X2 buffer */
#define LL_FMAC_FUNC_LOAD_Y (FMAC_PARAM_FUNC_1 | FMAC_PARAM_FUNC_0) /*!< Load Y buffer */
#define LL_FMAC_FUNC_CONVO_FIR (FMAC_PARAM_FUNC_3) /*!< Convolution (FIR filter) */
#define LL_FMAC_FUNC_IIR_DIRECT_FORM_1 (FMAC_PARAM_FUNC_3 | FMAC_PARAM_FUNC_0) /*!< IIR filter (direct form 1) */
/**
* @}
*/
/** @defgroup FMAC_LL_EC_PROCESSING FMAC processing
* @{
*/
#define LL_FMAC_PROCESSING_STOP 0x00U /*!< Stop FMAC Processing */
#define LL_FMAC_PROCESSING_START 0x01U /*!< Start FMAC Processing */
/**
* @}
*/
/**
* @}
*/
/* External variables --------------------------------------------------------*/
/* Exported macros -----------------------------------------------------------*/
/** @defgroup FMAC_LL_Exported_Macros FMAC Exported Macros
* @{
*/
/** @defgroup FMAC_LL_EM_WRITE_READ Common Write and read registers Macros
* @{
*/
/**
* @brief Write a value in FMAC register
* @param __INSTANCE__ FMAC Instance
* @param __REG__ Register to be written
* @param __VALUE__ Value to be written in the register
* @retval None
*/
#define LL_FMAC_WriteReg(__INSTANCE__, __REG__, __VALUE__) WRITE_REG(__INSTANCE__->__REG__, (__VALUE__))
/**
* @brief Read a value in FMAC register
* @param __INSTANCE__ FMAC Instance
* @param __REG__ Register to be read
* @retval Register value
*/
#define LL_FMAC_ReadReg(__INSTANCE__, __REG__) READ_REG(__INSTANCE__->__REG__)
/**
* @}
*/
/**
* @}
*/
/* Exported functions --------------------------------------------------------*/
/** @defgroup FMAC_LL_Exported_Functions FMAC Exported Functions
* @{
*/
/** @defgroup FMAC_LL_EF_Configuration FMAC Configuration functions
* @{
*/
/**
* @brief Configure X1 full watermark.
* @rmtoll X1BUFCFG FULL_WM LL_FMAC_SetX1FullWatermark
* @param FMACx FMAC instance
* @param Watermark This parameter can be one of the following values:
* @arg @ref LL_FMAC_WM_0_THRESHOLD_1
* @arg @ref LL_FMAC_WM_1_THRESHOLD_2
* @arg @ref LL_FMAC_WM_2_THRESHOLD_4
* @arg @ref LL_FMAC_WM_3_THRESHOLD_8
* @retval None
*/
__STATIC_INLINE void LL_FMAC_SetX1FullWatermark(FMAC_TypeDef *FMACx, uint32_t Watermark)
{
MODIFY_REG(FMACx->X1BUFCFG, FMAC_X1BUFCFG_FULL_WM, Watermark);
}
/**
* @brief Return X1 full watermark.
* @rmtoll X1BUFCFG FULL_WM LL_FMAC_GetX1FullWatermark
* @param FMACx FMAC instance
* @retval uint32_t Returned value can be one of the following values:
* @arg @ref LL_FMAC_WM_0_THRESHOLD_1
* @arg @ref LL_FMAC_WM_1_THRESHOLD_2
* @arg @ref LL_FMAC_WM_2_THRESHOLD_4
* @arg @ref LL_FMAC_WM_3_THRESHOLD_8
*/
__STATIC_INLINE uint32_t LL_FMAC_GetX1FullWatermark(FMAC_TypeDef *FMACx)
{
return (uint32_t)(READ_BIT(FMACx->X1BUFCFG, FMAC_X1BUFCFG_FULL_WM));
}
/**
* @brief Configure X1 buffer size.
* @rmtoll X1BUFCFG X1_BUF_SIZE LL_FMAC_SetX1BufferSize
* @param FMACx FMAC instance
* @param BufferSize Number of 16-bit words allocated to the input buffer (including the optional "headroom").
* This parameter must be a number between Min_Data=0x01 and Max_Data=0xFF.
* @retval None
*/
__STATIC_INLINE void LL_FMAC_SetX1BufferSize(FMAC_TypeDef *FMACx, uint8_t BufferSize)
{
MODIFY_REG(FMACx->X1BUFCFG, FMAC_X1BUFCFG_X1_BUF_SIZE, ((uint32_t)BufferSize) << FMAC_X1BUFCFG_X1_BUF_SIZE_Pos);
}
/**
* @brief Return X1 buffer size.
* @rmtoll X1BUFCFG X1_BUF_SIZE LL_FMAC_GetX1BufferSize
* @param FMACx FMAC instance
* @retval uint8_t Number of 16-bit words allocated to the input buffer
* (including the optional "headroom") (value between Min_Data=0x01 and Max_Data=0xFF).
*/
__STATIC_INLINE uint8_t LL_FMAC_GetX1BufferSize(FMAC_TypeDef *FMACx)
{
return (uint8_t)(READ_BIT(FMACx->X1BUFCFG, FMAC_X1BUFCFG_X1_BUF_SIZE) >> FMAC_X1BUFCFG_X1_BUF_SIZE_Pos);
}
/**
* @brief Configure X1 base.
* @rmtoll X1BUFCFG X1_BASE LL_FMAC_SetX1Base
* @param FMACx FMAC instance
* @param Base Base address of the input buffer (X1) within the internal memory.
* This parameter must be a value between Min_Data=0x00 and Max_Data=0xFF.
* @retval None
*/
__STATIC_INLINE void LL_FMAC_SetX1Base(FMAC_TypeDef *FMACx, uint8_t Base)
{
MODIFY_REG(FMACx->X1BUFCFG, FMAC_X1BUFCFG_X1_BASE, ((uint32_t)Base) << FMAC_X1BUFCFG_X1_BASE_Pos);
}
/**
* @brief Return X1 base.
* @rmtoll X1BUFCFG X1_BASE LL_FMAC_GetX1Base
* @param FMACx FMAC instance
* @retval uint8_t Base address of the input buffer (X1) within the internal memory
* (value between Min_Data=0x00 and Max_Data=0xFF).
*/
__STATIC_INLINE uint8_t LL_FMAC_GetX1Base(FMAC_TypeDef *FMACx)
{
return (uint8_t)(READ_BIT(FMACx->X1BUFCFG, FMAC_X1BUFCFG_X1_BASE) >> FMAC_X1BUFCFG_X1_BASE_Pos);
}
/**
* @brief Configure X2 buffer size.
* @rmtoll X2BUFCFG X2_BUF_SIZE LL_FMAC_SetX2BufferSize
* @param FMACx FMAC instance
* @param BufferSize Number of 16-bit words allocated to the coefficient buffer.
* This parameter must be a number between Min_Data=0x01 and Max_Data=0xFF.
* @retval None
*/
__STATIC_INLINE void LL_FMAC_SetX2BufferSize(FMAC_TypeDef *FMACx, uint8_t BufferSize)
{
MODIFY_REG(FMACx->X2BUFCFG, FMAC_X2BUFCFG_X2_BUF_SIZE, ((uint32_t)BufferSize) << FMAC_X2BUFCFG_X2_BUF_SIZE_Pos);
}
/**
* @brief Return X2 buffer size.
* @rmtoll X2BUFCFG X2_BUF_SIZE LL_FMAC_GetX2BufferSize
* @param FMACx FMAC instance
* @retval uint8_t Number of 16-bit words allocated to the coefficient buffer
* (value between Min_Data=0x01 and Max_Data=0xFF).
*/
__STATIC_INLINE uint8_t LL_FMAC_GetX2BufferSize(FMAC_TypeDef *FMACx)
{
return (uint8_t)(READ_BIT(FMACx->X2BUFCFG, FMAC_X2BUFCFG_X2_BUF_SIZE) >> FMAC_X2BUFCFG_X2_BUF_SIZE_Pos);
}
/**
* @brief Configure X2 base.
* @rmtoll X2BUFCFG X2_BASE LL_FMAC_SetX2Base
* @param FMACx FMAC instance
* @param Base Base address of the coefficient buffer (X2) within the internal memory.
* This parameter must be a value between Min_Data=0x00 and Max_Data=0xFF.
* @retval None
*/
__STATIC_INLINE void LL_FMAC_SetX2Base(FMAC_TypeDef *FMACx, uint8_t Base)
{
MODIFY_REG(FMACx->X2BUFCFG, FMAC_X2BUFCFG_X2_BASE, ((uint32_t)Base) << FMAC_X2BUFCFG_X2_BASE_Pos);
}
/**
* @brief Return X2 base.
* @rmtoll X2BUFCFG X2_BASE LL_FMAC_GetX2Base
* @param FMACx FMAC instance
* @retval uint8_t Base address of the coefficient buffer (X2) within the internal memory
* (value between Min_Data=0x00 and Max_Data=0xFF).
*/
__STATIC_INLINE uint8_t LL_FMAC_GetX2Base(FMAC_TypeDef *FMACx)
{
return (uint8_t)(READ_BIT(FMACx->X2BUFCFG, FMAC_X2BUFCFG_X2_BASE) >> FMAC_X2BUFCFG_X2_BASE_Pos);
}
/**
* @brief Configure Y empty watermark.
* @rmtoll YBUFCFG EMPTY_WM LL_FMAC_SetYEmptyWatermark
* @param FMACx FMAC instance
* @param Watermark This parameter can be one of the following values:
* @arg @ref LL_FMAC_WM_0_THRESHOLD_1
* @arg @ref LL_FMAC_WM_1_THRESHOLD_2
* @arg @ref LL_FMAC_WM_2_THRESHOLD_4
* @arg @ref LL_FMAC_WM_3_THRESHOLD_8
* @retval None
*/
__STATIC_INLINE void LL_FMAC_SetYEmptyWatermark(FMAC_TypeDef *FMACx, uint32_t Watermark)
{
MODIFY_REG(FMACx->YBUFCFG, FMAC_YBUFCFG_EMPTY_WM, Watermark);
}
/**
* @brief Return Y empty watermark.
* @rmtoll YBUFCFG EMPTY_WM LL_FMAC_GetYEmptyWatermark
* @param FMACx FMAC instance
* @retval uint32_t Returned value can be one of the following values:
* @arg @ref LL_FMAC_WM_0_THRESHOLD_1
* @arg @ref LL_FMAC_WM_1_THRESHOLD_2
* @arg @ref LL_FMAC_WM_2_THRESHOLD_4
* @arg @ref LL_FMAC_WM_3_THRESHOLD_8
*/
__STATIC_INLINE uint32_t LL_FMAC_GetYEmptyWatermark(FMAC_TypeDef *FMACx)
{
return (uint32_t)(READ_BIT(FMACx->YBUFCFG, FMAC_YBUFCFG_EMPTY_WM));
}
/**
* @brief Configure Y buffer size.
* @rmtoll YBUFCFG Y_BUF_SIZE LL_FMAC_SetYBufferSize
* @param FMACx FMAC instance
* @param BufferSize Number of 16-bit words allocated to the output buffer (including the optional "headroom").
* This parameter must be a number between Min_Data=0x01 and Max_Data=0xFF.
* @retval None
*/
__STATIC_INLINE void LL_FMAC_SetYBufferSize(FMAC_TypeDef *FMACx, uint8_t BufferSize)
{
MODIFY_REG(FMACx->YBUFCFG, FMAC_YBUFCFG_Y_BUF_SIZE, ((uint32_t)BufferSize) << FMAC_YBUFCFG_Y_BUF_SIZE_Pos);
}
/**
* @brief Return Y buffer size.
* @rmtoll YBUFCFG Y_BUF_SIZE LL_FMAC_GetYBufferSize
* @param FMACx FMAC instance
* @retval uint8_t Number of 16-bit words allocated to the output buffer
* (including the optional "headroom" - value between Min_Data=0x01 and Max_Data=0xFF).
*/
__STATIC_INLINE uint8_t LL_FMAC_GetYBufferSize(FMAC_TypeDef *FMACx)
{
return (uint8_t)(READ_BIT(FMACx->YBUFCFG, FMAC_YBUFCFG_Y_BUF_SIZE) >> FMAC_YBUFCFG_Y_BUF_SIZE_Pos);
}
/**
* @brief Configure Y base.
* @rmtoll YBUFCFG Y_BASE LL_FMAC_SetYBase
* @param FMACx FMAC instance
* @param Base Base address of the output buffer (Y) within the internal memory.
* This parameter must be a value between Min_Data=0x00 and Max_Data=0xFF.
* @retval None
*/
__STATIC_INLINE void LL_FMAC_SetYBase(FMAC_TypeDef *FMACx, uint8_t Base)
{
MODIFY_REG(FMACx->YBUFCFG, FMAC_YBUFCFG_Y_BASE, ((uint32_t)Base) << FMAC_YBUFCFG_Y_BASE_Pos);
}
/**
* @brief Return Y base.
* @rmtoll YBUFCFG Y_BASE LL_FMAC_GetYBase
* @param FMACx FMAC instance
* @retval uint8_t Base address of the output buffer (Y) within the internal memory
* (value between Min_Data=0x00 and Max_Data=0xFF).
*/
__STATIC_INLINE uint8_t LL_FMAC_GetYBase(FMAC_TypeDef *FMACx)
{
return (uint8_t)(READ_BIT(FMACx->YBUFCFG, FMAC_YBUFCFG_Y_BASE) >> FMAC_YBUFCFG_Y_BASE_Pos);
}
/**
* @brief Start FMAC processing.
* @rmtoll PARAM START LL_FMAC_EnableStart
* @param FMACx FMAC instance
* @retval None
*/
__STATIC_INLINE void LL_FMAC_EnableStart(FMAC_TypeDef *FMACx)
{
SET_BIT(FMACx->PARAM, FMAC_PARAM_START);
}
/**
* @brief Stop FMAC processing.
* @rmtoll PARAM START LL_FMAC_DisableStart
* @param FMACx FMAC instance
* @retval None
*/
__STATIC_INLINE void LL_FMAC_DisableStart(FMAC_TypeDef *FMACx)
{
CLEAR_BIT(FMACx->PARAM, FMAC_PARAM_START);
}
/**
* @brief Check the state of FMAC processing.
* @rmtoll PARAM START LL_FMAC_IsEnabledStart
* @param FMACx FMAC instance
* @retval uint32_t State of bit (1 or 0).
*/
__STATIC_INLINE uint32_t LL_FMAC_IsEnabledStart(FMAC_TypeDef *FMACx)
{
return ((READ_BIT(FMACx->PARAM, FMAC_PARAM_START) == (FMAC_PARAM_START)) ? 1UL : 0UL);
}
/**
* @brief Configure function.
* @rmtoll PARAM FUNC LL_FMAC_SetFunction
* @param FMACx FMAC instance
* @param Function This parameter can be one of the following values:
* @arg @ref LL_FMAC_FUNC_LOAD_X1
* @arg @ref LL_FMAC_FUNC_LOAD_X2
* @arg @ref LL_FMAC_FUNC_LOAD_Y
* @arg @ref LL_FMAC_FUNC_CONVO_FIR
* @arg @ref LL_FMAC_FUNC_IIR_DIRECT_FORM_1
* @retval None
*/
__STATIC_INLINE void LL_FMAC_SetFunction(FMAC_TypeDef *FMACx, uint32_t Function)
{
MODIFY_REG(FMACx->PARAM, FMAC_PARAM_FUNC, Function);
}
/**
* @brief Return function.
* @rmtoll PARAM FUNC LL_FMAC_GetFunction
* @param FMACx FMAC instance
* @retval uint32_t Returned value can be one of the following values:
* @arg @ref LL_FMAC_FUNC_LOAD_X1
* @arg @ref LL_FMAC_FUNC_LOAD_X2
* @arg @ref LL_FMAC_FUNC_LOAD_Y
* @arg @ref LL_FMAC_FUNC_CONVO_FIR
* @arg @ref LL_FMAC_FUNC_IIR_DIRECT_FORM_1
*/
__STATIC_INLINE uint32_t LL_FMAC_GetFunction(FMAC_TypeDef *FMACx)
{
return (uint32_t)(READ_BIT(FMACx->PARAM, FMAC_PARAM_FUNC));
}
/**
* @brief Configure input parameter R.
* @rmtoll PARAM R LL_FMAC_SetParamR
* @param FMACx FMAC instance
* @param Param Parameter R (gain, etc.).
* This parameter must be a value between Min_Data=0x00 and Max_Data=0xFF.
* @retval None
*/
__STATIC_INLINE void LL_FMAC_SetParamR(FMAC_TypeDef *FMACx, uint8_t Param)
{
MODIFY_REG(FMACx->PARAM, FMAC_PARAM_R, ((uint32_t)Param) << FMAC_PARAM_R_Pos);
}
/**
* @brief Return input parameter R.
* @rmtoll PARAM R LL_FMAC_GetParamR
* @param FMACx FMAC instance
* @retval uint8_t Parameter R (gain, etc.) (value between Min_Data=0x00 and Max_Data=0xFF).
*/
__STATIC_INLINE uint8_t LL_FMAC_GetParamR(FMAC_TypeDef *FMACx)
{
return (uint8_t)(READ_BIT(FMACx->PARAM, FMAC_PARAM_R) >> FMAC_PARAM_R_Pos);
}
/**
* @brief Configure input parameter Q.
* @rmtoll PARAM Q LL_FMAC_SetParamQ
* @param FMACx FMAC instance
* @param Param Parameter Q (vector length, etc.).
* This parameter must be a value between Min_Data=0x00 and Max_Data=0xFF.
* @retval None
*/
__STATIC_INLINE void LL_FMAC_SetParamQ(FMAC_TypeDef *FMACx, uint8_t Param)
{
MODIFY_REG(FMACx->PARAM, FMAC_PARAM_Q, ((uint32_t)Param) << FMAC_PARAM_Q_Pos);
}
/**
* @brief Return input parameter Q.
* @rmtoll PARAM Q LL_FMAC_GetParamQ
* @param FMACx FMAC instance
* @retval uint8_t Parameter Q (vector length, etc.) (value between Min_Data=0x00 and Max_Data=0xFF).
*/
__STATIC_INLINE uint8_t LL_FMAC_GetParamQ(FMAC_TypeDef *FMACx)
{
return (uint8_t)(READ_BIT(FMACx->PARAM, FMAC_PARAM_Q) >> FMAC_PARAM_Q_Pos);
}
/**
* @brief Configure input parameter P.
* @rmtoll PARAM P LL_FMAC_SetParamP
* @param FMACx FMAC instance
* @param Param Parameter P (vector length, number of filter taps, etc.).
* This parameter must be a value between Min_Data=0x00 and Max_Data=0xFF.
* @retval None
*/
__STATIC_INLINE void LL_FMAC_SetParamP(FMAC_TypeDef *FMACx, uint8_t Param)
{
MODIFY_REG(FMACx->PARAM, FMAC_PARAM_P, ((uint32_t)Param));
}
/**
* @brief Return input parameter P.
* @rmtoll PARAM P LL_FMAC_GetParamP
* @param FMACx FMAC instance
* @retval uint8_t Parameter P (vector length, number of filter taps, etc.)
* (value between Min_Data=0x00 and Max_Data=0xFF).
*/
__STATIC_INLINE uint8_t LL_FMAC_GetParamP(FMAC_TypeDef *FMACx)
{
return (uint8_t)(READ_BIT(FMACx->PARAM, FMAC_PARAM_P));
}
/**
* @}
*/
/** @defgroup FMAC_LL_EF_Reset_Management Reset_Management
* @{
*/
/**
* @brief Start the FMAC reset.
* @rmtoll CR RESET LL_FMAC_EnableReset
* @param FMACx FMAC instance
* @retval None
*/
__STATIC_INLINE void LL_FMAC_EnableReset(FMAC_TypeDef *FMACx)
{
SET_BIT(FMACx->CR, FMAC_CR_RESET);
}
/**
* @brief Check the state of the FMAC reset.
* @rmtoll CR RESET LL_FMAC_IsEnabledReset
* @param FMACx FMAC instance
* @retval uint32_t State of bit (1 or 0).
*/
__STATIC_INLINE uint32_t LL_FMAC_IsEnabledReset(FMAC_TypeDef *FMACx)
{
return ((READ_BIT(FMACx->CR, FMAC_CR_RESET) == (FMAC_CR_RESET)) ? 1UL : 0UL);
}
/**
* @}
*/
/** @defgroup FMAC_LL_EF_Configuration FMAC Configuration functions
* @{
*/
/**
* @brief Enable Clipping.
* @rmtoll CR CLIPEN LL_FMAC_EnableClipping
* @param FMACx FMAC instance
* @retval None
*/
__STATIC_INLINE void LL_FMAC_EnableClipping(FMAC_TypeDef *FMACx)
{
SET_BIT(FMACx->CR, FMAC_CR_CLIPEN);
}
/**
* @brief Disable Clipping.
* @rmtoll CR CLIPEN LL_FMAC_DisableClipping
* @param FMACx FMAC instance
* @retval None
*/
__STATIC_INLINE void LL_FMAC_DisableClipping(FMAC_TypeDef *FMACx)
{
CLEAR_BIT(FMACx->CR, FMAC_CR_CLIPEN);
}
/**
* @brief Check Clipping State.
* @rmtoll CR CLIPEN LL_FMAC_IsEnabledClipping
* @param FMACx FMAC instance
* @retval uint32_t State of bit (1 or 0).
*/
__STATIC_INLINE uint32_t LL_FMAC_IsEnabledClipping(FMAC_TypeDef *FMACx)
{
return ((READ_BIT(FMACx->CR, FMAC_CR_CLIPEN) == (FMAC_CR_CLIPEN)) ? 1UL : 0UL);
}
/**
* @}
*/
/** @defgroup FMAC_LL_EF_DMA_Management DMA_Management
* @{
*/
/**
* @brief Enable FMAC DMA write channel request.
* @rmtoll CR DMAWEN LL_FMAC_EnableDMAReq_WRITE
* @param FMACx FMAC instance
* @retval None
*/
__STATIC_INLINE void LL_FMAC_EnableDMAReq_WRITE(FMAC_TypeDef *FMACx)
{
SET_BIT(FMACx->CR, FMAC_CR_DMAWEN);
}
/**
* @brief Disable FMAC DMA write channel request.
* @rmtoll CR DMAWEN LL_FMAC_DisableDMAReq_WRITE
* @param FMACx FMAC instance
* @retval None
*/
__STATIC_INLINE void LL_FMAC_DisableDMAReq_WRITE(FMAC_TypeDef *FMACx)
{
CLEAR_BIT(FMACx->CR, FMAC_CR_DMAWEN);
}
/**
* @brief Check FMAC DMA write channel request state.
* @rmtoll CR DMAWEN LL_FMAC_IsEnabledDMAReq_WRITE
* @param FMACx FMAC instance
* @retval uint32_t State of bit (1 or 0).
*/
__STATIC_INLINE uint32_t LL_FMAC_IsEnabledDMAReq_WRITE(FMAC_TypeDef *FMACx)
{
return ((READ_BIT(FMACx->CR, FMAC_CR_DMAWEN) == (FMAC_CR_DMAWEN)) ? 1UL : 0UL);
}
/**
* @brief Enable FMAC DMA read channel request.
* @rmtoll CR DMAREN LL_FMAC_EnableDMAReq_READ
* @param FMACx FMAC instance
* @retval None
*/
__STATIC_INLINE void LL_FMAC_EnableDMAReq_READ(FMAC_TypeDef *FMACx)
{
SET_BIT(FMACx->CR, FMAC_CR_DMAREN);
}
/**
* @brief Disable FMAC DMA read channel request.
* @rmtoll CR DMAREN LL_FMAC_DisableDMAReq_READ
* @param FMACx FMAC instance
* @retval None
*/
__STATIC_INLINE void LL_FMAC_DisableDMAReq_READ(FMAC_TypeDef *FMACx)
{
CLEAR_BIT(FMACx->CR, FMAC_CR_DMAREN);
}
/**
* @brief Check FMAC DMA read channel request state.
* @rmtoll CR DMAREN LL_FMAC_IsEnabledDMAReq_READ
* @param FMACx FMAC instance
* @retval uint32_t State of bit (1 or 0).
*/
__STATIC_INLINE uint32_t LL_FMAC_IsEnabledDMAReq_READ(FMAC_TypeDef *FMACx)
{
return ((READ_BIT(FMACx->CR, FMAC_CR_DMAREN) == (FMAC_CR_DMAREN)) ? 1UL : 0UL);
}
/**
* @}
*/
/** @defgroup FMAC_LL_EF_IT_Management IT_Management
* @{
*/
/**
* @brief Enable FMAC saturation error interrupt.
* @rmtoll CR SATIEN LL_FMAC_EnableIT_SAT
* @param FMACx FMAC instance
* @retval None
*/
__STATIC_INLINE void LL_FMAC_EnableIT_SAT(FMAC_TypeDef *FMACx)
{
SET_BIT(FMACx->CR, FMAC_CR_SATIEN);
}
/**
* @brief Disable FMAC saturation error interrupt.
* @rmtoll CR SATIEN LL_FMAC_DisableIT_SAT
* @param FMACx FMAC instance
* @retval None
*/
__STATIC_INLINE void LL_FMAC_DisableIT_SAT(FMAC_TypeDef *FMACx)
{
CLEAR_BIT(FMACx->CR, FMAC_CR_SATIEN);
}
/**
* @brief Check FMAC saturation error interrupt state.
* @rmtoll CR SATIEN LL_FMAC_IsEnabledIT_SAT
* @param FMACx FMAC instance
* @retval uint32_t State of bit (1 or 0).
*/
__STATIC_INLINE uint32_t LL_FMAC_IsEnabledIT_SAT(FMAC_TypeDef *FMACx)
{
return ((READ_BIT(FMACx->CR, FMAC_CR_SATIEN) == (FMAC_CR_SATIEN)) ? 1UL : 0UL);
}
/**
* @brief Enable FMAC underflow error interrupt.
* @rmtoll CR UNFLIEN LL_FMAC_EnableIT_UNFL
* @param FMACx FMAC instance
* @retval None
*/
__STATIC_INLINE void LL_FMAC_EnableIT_UNFL(FMAC_TypeDef *FMACx)
{
SET_BIT(FMACx->CR, FMAC_CR_UNFLIEN);
}
/**
* @brief Disable FMAC underflow error interrupt.
* @rmtoll CR UNFLIEN LL_FMAC_DisableIT_UNFL
* @param FMACx FMAC instance
* @retval None
*/
__STATIC_INLINE void LL_FMAC_DisableIT_UNFL(FMAC_TypeDef *FMACx)
{
CLEAR_BIT(FMACx->CR, FMAC_CR_UNFLIEN);
}
/**
* @brief Check FMAC underflow error interrupt state.
* @rmtoll CR UNFLIEN LL_FMAC_IsEnabledIT_UNFL
* @param FMACx FMAC instance
* @retval uint32_t State of bit (1 or 0).
*/
__STATIC_INLINE uint32_t LL_FMAC_IsEnabledIT_UNFL(FMAC_TypeDef *FMACx)
{
return ((READ_BIT(FMACx->CR, FMAC_CR_UNFLIEN) == (FMAC_CR_UNFLIEN)) ? 1UL : 0UL);
}
/**
* @brief Enable FMAC overflow error interrupt.
* @rmtoll CR OVFLIEN LL_FMAC_EnableIT_OVFL
* @param FMACx FMAC instance
* @retval None
*/
__STATIC_INLINE void LL_FMAC_EnableIT_OVFL(FMAC_TypeDef *FMACx)
{
SET_BIT(FMACx->CR, FMAC_CR_OVFLIEN);
}
/**
* @brief Disable FMAC overflow error interrupt.
* @rmtoll CR OVFLIEN LL_FMAC_DisableIT_OVFL
* @param FMACx FMAC instance
* @retval None
*/
__STATIC_INLINE void LL_FMAC_DisableIT_OVFL(FMAC_TypeDef *FMACx)
{
CLEAR_BIT(FMACx->CR, FMAC_CR_OVFLIEN);
}
/**
* @brief Check FMAC overflow error interrupt state.
* @rmtoll CR OVFLIEN LL_FMAC_IsEnabledIT_OVFL
* @param FMACx FMAC instance
* @retval uint32_t State of bit (1 or 0).
*/
__STATIC_INLINE uint32_t LL_FMAC_IsEnabledIT_OVFL(FMAC_TypeDef *FMACx)
{
return ((READ_BIT(FMACx->CR, FMAC_CR_OVFLIEN) == (FMAC_CR_OVFLIEN)) ? 1UL : 0UL);
}
/**
* @brief Enable FMAC write interrupt.
* @rmtoll CR WIEN LL_FMAC_EnableIT_WR
* @param FMACx FMAC instance
* @retval None
*/
__STATIC_INLINE void LL_FMAC_EnableIT_WR(FMAC_TypeDef *FMACx)
{
SET_BIT(FMACx->CR, FMAC_CR_WIEN);
}
/**
* @brief Disable FMAC write interrupt.
* @rmtoll CR WIEN LL_FMAC_DisableIT_WR
* @param FMACx FMAC instance
* @retval None
*/
__STATIC_INLINE void LL_FMAC_DisableIT_WR(FMAC_TypeDef *FMACx)
{
CLEAR_BIT(FMACx->CR, FMAC_CR_WIEN);
}
/**
* @brief Check FMAC write interrupt state.
* @rmtoll CR WIEN LL_FMAC_IsEnabledIT_WR
* @param FMACx FMAC instance
* @retval uint32_t State of bit (1 or 0).
*/
__STATIC_INLINE uint32_t LL_FMAC_IsEnabledIT_WR(FMAC_TypeDef *FMACx)
{
return ((READ_BIT(FMACx->CR, FMAC_CR_WIEN) == (FMAC_CR_WIEN)) ? 1UL : 0UL);
}
/**
* @brief Enable FMAC read interrupt.
* @rmtoll CR RIEN LL_FMAC_EnableIT_RD
* @param FMACx FMAC instance
* @retval None
*/
__STATIC_INLINE void LL_FMAC_EnableIT_RD(FMAC_TypeDef *FMACx)
{
SET_BIT(FMACx->CR, FMAC_CR_RIEN);
}
/**
* @brief Disable FMAC read interrupt.
* @rmtoll CR RIEN LL_FMAC_DisableIT_RD
* @param FMACx FMAC instance
* @retval None
*/
__STATIC_INLINE void LL_FMAC_DisableIT_RD(FMAC_TypeDef *FMACx)
{
CLEAR_BIT(FMACx->CR, FMAC_CR_RIEN);
}
/**
* @brief Check FMAC read interrupt state.
* @rmtoll CR RIEN LL_FMAC_IsEnabledIT_RD
* @param FMACx FMAC instance
* @retval uint32_t State of bit (1 or 0).
*/
__STATIC_INLINE uint32_t LL_FMAC_IsEnabledIT_RD(FMAC_TypeDef *FMACx)
{
return ((READ_BIT(FMACx->CR, FMAC_CR_RIEN) == (FMAC_CR_RIEN)) ? 1UL : 0UL);
}
/**
* @}
*/
/** @defgroup FMAC_LL_EF_FLAG_Management FLAG_Management
* @{
*/
/**
* @brief Check FMAC saturation error flag state.
* @rmtoll SR SAT LL_FMAC_IsActiveFlag_SAT
* @param FMACx FMAC instance
* @retval uint32_t State of bit (1 or 0).
*/
__STATIC_INLINE uint32_t LL_FMAC_IsActiveFlag_SAT(FMAC_TypeDef *FMACx)
{
return ((READ_BIT(FMACx->SR, FMAC_SR_SAT) == (FMAC_SR_SAT)) ? 1UL : 0UL);
}
/**
* @brief Check FMAC underflow error flag state.
* @rmtoll SR UNFL LL_FMAC_IsActiveFlag_UNFL
* @param FMACx FMAC instance
* @retval uint32_t State of bit (1 or 0).
*/
__STATIC_INLINE uint32_t LL_FMAC_IsActiveFlag_UNFL(FMAC_TypeDef *FMACx)
{
return ((READ_BIT(FMACx->SR, FMAC_SR_UNFL) == (FMAC_SR_UNFL)) ? 1UL : 0UL);
}
/**
* @brief Check FMAC overflow error flag state.
* @rmtoll SR OVFL LL_FMAC_IsActiveFlag_OVFL
* @param FMACx FMAC instance
* @retval uint32_t State of bit (1 or 0).
*/
__STATIC_INLINE uint32_t LL_FMAC_IsActiveFlag_OVFL(FMAC_TypeDef *FMACx)
{
return ((READ_BIT(FMACx->SR, FMAC_SR_OVFL) == (FMAC_SR_OVFL)) ? 1UL : 0UL);
}
/**
* @brief Check FMAC X1 buffer full flag state.
* @rmtoll SR X1FULL LL_FMAC_IsActiveFlag_X1FULL
* @param FMACx FMAC instance
* @retval uint32_t State of bit (1 or 0).
*/
__STATIC_INLINE uint32_t LL_FMAC_IsActiveFlag_X1FULL(FMAC_TypeDef *FMACx)
{
return ((READ_BIT(FMACx->SR, FMAC_SR_X1FULL) == (FMAC_SR_X1FULL)) ? 1UL : 0UL);
}
/**
* @brief Check FMAC Y buffer empty flag state.
* @rmtoll SR YEMPTY LL_FMAC_IsActiveFlag_YEMPTY
* @param FMACx FMAC instance
* @retval uint32_t State of bit (1 or 0).
*/
__STATIC_INLINE uint32_t LL_FMAC_IsActiveFlag_YEMPTY(FMAC_TypeDef *FMACx)
{
return ((READ_BIT(FMACx->SR, FMAC_SR_YEMPTY) == (FMAC_SR_YEMPTY)) ? 1UL : 0UL);
}
/**
* @}
*/
/** @defgroup FMAC_LL_EF_Data_Management Data_Management
* @{
*/
/**
* @brief Write 16-bit input data for the FMAC processing.
* @rmtoll WDATA WDATA LL_FMAC_WriteData
* @param FMACx FMAC instance
* @param InData 16-bit value to be provided as input data for FMAC processing.
* This parameter must be a number between Min_Data=0x0000 and Max_Data=0xFFFF.
* @retval None
*/
__STATIC_INLINE void LL_FMAC_WriteData(FMAC_TypeDef *FMACx, uint16_t InData)
{
WRITE_REG(FMACx->WDATA, InData);
}
/**
* @brief Return 16-bit output data of FMAC processing.
* @rmtoll RDATA RDATA LL_FMAC_ReadData
* @param FMACx FMAC instance
* @retval uint16_t 16-bit output data of FMAC processing (value between Min_Data=0x0000 and Max_Data=0xFFFF).
*/
__STATIC_INLINE uint16_t LL_FMAC_ReadData(FMAC_TypeDef *FMACx)
{
return (uint16_t)(READ_REG(FMACx->RDATA));
}
/**
* @}
*/
/** @defgroup FMAC_LL_EF_Configuration FMAC Configuration functions
* @{
*/
/**
* @brief Configure memory for X1 buffer.
* @rmtoll X1BUFCFG FULL_WM LL_FMAC_ConfigX1\n
* X1BUFCFG X1_BASE LL_FMAC_ConfigX1\n
* X1BUFCFG X1_BUF_SIZE LL_FMAC_ConfigX1
* @param FMACx FMAC instance
* @param Watermark This parameter can be one of the following values:
* @arg @ref LL_FMAC_WM_0_THRESHOLD_1
* @arg @ref LL_FMAC_WM_1_THRESHOLD_2
* @arg @ref LL_FMAC_WM_2_THRESHOLD_4
* @arg @ref LL_FMAC_WM_3_THRESHOLD_8
* @param Base Base address of the input buffer (X1) within the internal memory.
* This parameter must be a value between Min_Data=0x00 and Max_Data=0xFF.
* @param BufferSize Number of 16-bit words allocated to the input buffer (including the optional "headroom").
* This parameter must be a number between Min_Data=0x01 and Max_Data=0xFF.
* @retval None
*/
__STATIC_INLINE void LL_FMAC_ConfigX1(FMAC_TypeDef *FMACx, uint32_t Watermark, uint8_t Base, uint8_t BufferSize)
{
MODIFY_REG(FMACx->X1BUFCFG, FMAC_X1BUFCFG_FULL_WM | FMAC_X1BUFCFG_X1_BASE | FMAC_X1BUFCFG_X1_BUF_SIZE,
Watermark | (((uint32_t)Base) << FMAC_X1BUFCFG_X1_BASE_Pos) |
(((uint32_t)BufferSize) << FMAC_X1BUFCFG_X1_BUF_SIZE_Pos));
}
/**
* @brief Configure memory for X2 buffer.
* @rmtoll X2BUFCFG X2_BASE LL_FMAC_ConfigX2\n
* X2BUFCFG X2_BUF_SIZE LL_FMAC_ConfigX2
* @param FMACx FMAC instance
* @param Base Base address of the coefficient buffer (X2) within the internal memory.
* This parameter must be a value between Min_Data=0x00 and Max_Data=0xFF.
* @param BufferSize Number of 16-bit words allocated to the coefficient buffer.
* This parameter must be a number between Min_Data=0x01 and Max_Data=0xFF.
* @retval None
*/
__STATIC_INLINE void LL_FMAC_ConfigX2(FMAC_TypeDef *FMACx, uint8_t Base, uint8_t BufferSize)
{
MODIFY_REG(FMACx->X2BUFCFG, FMAC_X2BUFCFG_X2_BASE | FMAC_X2BUFCFG_X2_BUF_SIZE,
(((uint32_t)Base) << FMAC_X2BUFCFG_X2_BASE_Pos) |
(((uint32_t)BufferSize) << FMAC_X2BUFCFG_X2_BUF_SIZE_Pos));
}
/**
* @brief Configure memory for Y buffer.
* @rmtoll YBUFCFG EMPTY_WM LL_FMAC_ConfigY\n
* YBUFCFG Y_BASE LL_FMAC_ConfigY\n
* YBUFCFG Y_BUF_SIZE LL_FMAC_ConfigY
* @param FMACx FMAC instance
* @param Watermark This parameter can be one of the following values:
* @arg @ref LL_FMAC_WM_0_THRESHOLD_1
* @arg @ref LL_FMAC_WM_1_THRESHOLD_2
* @arg @ref LL_FMAC_WM_2_THRESHOLD_4
* @arg @ref LL_FMAC_WM_3_THRESHOLD_8
* @param Base Base address of the output buffer (Y) within the internal memory.
* This parameter must be a value between Min_Data=0x00 and Max_Data=0xFF.
* @param BufferSize Number of 16-bit words allocated to the output buffer (including the optional "headroom").
* This parameter must be a number between Min_Data=0x01 and Max_Data=0xFF.
* @retval None
*/
__STATIC_INLINE void LL_FMAC_ConfigY(FMAC_TypeDef *FMACx, uint32_t Watermark, uint8_t Base, uint8_t BufferSize)
{
MODIFY_REG(FMACx->YBUFCFG, FMAC_YBUFCFG_EMPTY_WM | FMAC_YBUFCFG_Y_BASE | FMAC_YBUFCFG_Y_BUF_SIZE,
Watermark | (((uint32_t)Base) << FMAC_YBUFCFG_Y_BASE_Pos) |
(((uint32_t)BufferSize) << FMAC_YBUFCFG_Y_BUF_SIZE_Pos));
}
/**
* @brief Configure the FMAC processing.
* @rmtoll PARAM START LL_FMAC_ConfigFunc\n
* PARAM FUNC LL_FMAC_ConfigFunc\n
* PARAM P LL_FMAC_ConfigFunc\n
* PARAM Q LL_FMAC_ConfigFunc\n
* PARAM R LL_FMAC_ConfigFunc
* @param FMACx FMAC instance
* @param Start This parameter can be one of the following values:
* @arg @ref LL_FMAC_PROCESSING_STOP
* @arg @ref LL_FMAC_PROCESSING_START
* @param Function This parameter can be one of the following values:
* @arg @ref LL_FMAC_FUNC_LOAD_X1
* @arg @ref LL_FMAC_FUNC_LOAD_X2
* @arg @ref LL_FMAC_FUNC_LOAD_Y
* @arg @ref LL_FMAC_FUNC_CONVO_FIR
* @arg @ref LL_FMAC_FUNC_IIR_DIRECT_FORM_1
* @param ParamP Parameter P (vector length, number of filter taps, etc.).
* This parameter must be a value between Min_Data=0x00 and Max_Data=0xFF.
* @param ParamQ Parameter Q (vector length, etc.).
* This parameter must be a value between Min_Data=0x00 and Max_Data=0xFF.
* @param ParamR Parameter R (gain, etc.).
* This parameter must be a value between Min_Data=0x00 and Max_Data=0xFF.
* @retval None
*/
__STATIC_INLINE void LL_FMAC_ConfigFunc(FMAC_TypeDef *FMACx, uint8_t Start, uint32_t Function, uint8_t ParamP,
uint8_t ParamQ, uint8_t ParamR)
{
MODIFY_REG(FMACx->PARAM, FMAC_PARAM_START | FMAC_PARAM_FUNC | FMAC_PARAM_P | FMAC_PARAM_Q | FMAC_PARAM_R,
(((uint32_t)Start) << FMAC_PARAM_START_Pos) | Function | (((uint32_t)ParamP) << FMAC_PARAM_P_Pos) |
(((uint32_t)ParamQ) << FMAC_PARAM_Q_Pos) | (((uint32_t)ParamR) << FMAC_PARAM_R_Pos));
}
/**
* @}
*/
#if defined(USE_FULL_LL_DRIVER)
/** @defgroup FMAC_LL_EF_Init Initialization and de-initialization functions
* @{
*/
ErrorStatus LL_FMAC_Init(FMAC_TypeDef *FMACx);
ErrorStatus LL_FMAC_DeInit(FMAC_TypeDef *FMACx);
/**
* @}
*/
#endif /* USE_FULL_LL_DRIVER */
/**
* @}
*/
/**
* @}
*/
#endif /* defined(FMAC) */
/**
* @}
*/
#ifdef __cplusplus
}
#endif
#endif /* STM32H7xx_LL_FMAC_H */
| {
"content_hash": "d0385e11fffc53383853c12552e92900",
"timestamp": "",
"source": "github",
"line_count": 1047,
"max_line_length": 137,
"avg_line_length": 32.893982808022926,
"alnum_prop": 0.6240708478513357,
"repo_name": "STMicroelectronics/stm32h7xx_hal_driver",
"id": "b489388dbb39ea93be6b5cbd4eeb1d253c2c5ca3",
"size": "35102",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "Inc/stm32h7xx_ll_fmac.h",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "C",
"bytes": "14696143"
},
{
"name": "HTML",
"bytes": "166467"
}
],
"symlink_target": ""
} |
package com.codepath.apps.mytweeter.activities;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.content.ContextCompat;
import android.support.v4.graphics.drawable.RoundedBitmapDrawable;
import android.support.v4.graphics.drawable.RoundedBitmapDrawableFactory;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.widget.ImageView;
import android.widget.TextView;
import com.bumptech.glide.Glide;
import com.bumptech.glide.request.target.BitmapImageViewTarget;
import com.codepath.apps.mytweeter.R;
import com.codepath.apps.mytweeter.TwitterApp;
import com.codepath.apps.mytweeter.datamodels.User;
import com.codepath.apps.mytweeter.fragments.UserTimelineFragment;
import com.codepath.apps.mytweeter.network.TwitterClient;
import com.loopj.android.http.JsonHttpResponseHandler;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import cz.msebera.android.httpclient.Header;
public class ProfileActivity extends AppCompatActivity {
TwitterClient client;
User user;
private final String debugTAG = "ProfileActivity";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_profile);
String screenName = getIntent().getStringExtra("screenName");
Log.d(debugTAG, "onCreate: screenName = " + screenName);
UserTimelineFragment userTimelineFragment = UserTimelineFragment.newInstance(screenName);
FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
fragmentTransaction.replace(R.id.flContainer, userTimelineFragment);
fragmentTransaction.commit();
client = TwitterApp.getRestClient();
if (screenName == null) {
getAppUser();
}
else {
getUserInfo(screenName);
}
}
private void getAppUser() {
Log.d(debugTAG, "getAppUser()");
client.getAppUser(new JsonHttpResponseHandler() {
@Override
public void onSuccess(int statusCode, Header[] headers, JSONObject response) {
try {
//Log.d(debugTAG, response.toString());
user = User.fromJson(response);
populateUserDetails();
} catch (JSONException e) {
e.printStackTrace();
}
}
@Override
public void onFailure(int statusCode, Header[] headers, Throwable throwable, JSONObject errorResponse) {
Log.d(debugTAG, errorResponse.toString());
throwable.printStackTrace();
}
@Override
public void onFailure(int statusCode, Header[] headers, Throwable throwable, JSONArray errorResponse) {
Log.d(debugTAG, errorResponse.toString());
throwable.printStackTrace();
}
@Override
public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {
Log.d(debugTAG, responseString);
throwable.printStackTrace();
}
});
}
private void getUserInfo(String screenName) {
Log.d(debugTAG, "getUserInfo(" + screenName + ")");
client.getUserInfo(screenName, new JsonHttpResponseHandler() {
@Override
public void onSuccess(int statusCode, Header[] headers, JSONObject response) {
try {
Log.d(debugTAG, response.toString());
user = User.fromJson(response);
populateUserDetails();
} catch (JSONException e) {
e.printStackTrace();
}
}
@Override
public void onFailure(int statusCode, Header[] headers, Throwable throwable, JSONObject errorResponse) {
Log.d(debugTAG, errorResponse.toString());
throwable.printStackTrace();
}
@Override
public void onFailure(int statusCode, Header[] headers, Throwable throwable, JSONArray errorResponse) {
Log.d(debugTAG, errorResponse.toString());
throwable.printStackTrace();
}
@Override
public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {
Log.d(debugTAG, responseString);
throwable.printStackTrace();
}
});
}
private void populateUserDetails() {
ImageView ivUserHeaderBannerImg = (ImageView) findViewById(R.id.ivUserHeaderBannerImg);
TextView tvUserHeaderName = (TextView) findViewById(R.id.tvUserHeaderName);
TextView tvUserHeaderScreenName = (TextView) findViewById(R.id.tvUserHeaderScreenName);
TextView tvUserHeaderTagline = (TextView) findViewById(R.id.tvUserHeaderTagline);
TextView tvUserHeaderFollowingCount = (TextView) findViewById(R.id.tvUserHeaderFollowingCount);
TextView tvUserHeaderFollowersCount = (TextView) findViewById(R.id.tvUserHeaderFollowersCount);
final FloatingActionButton fabUserHeaderProfileImage = (FloatingActionButton) findViewById(R.id.fabUserHeaderProfileImage);
if (user.profileBannerUrl.isEmpty()) {
ivUserHeaderBannerImg.setBackgroundColor(ContextCompat.getColor(this, R.color.colorPrimary));
}
else {
Glide.with(this)
.load(user.profileBannerUrl)
.asBitmap()
.into(ivUserHeaderBannerImg);
}
tvUserHeaderName.setText(user.name);
tvUserHeaderScreenName.setText(user.screenName);
tvUserHeaderTagline.setText(user.tagLine);
tvUserHeaderFollowersCount.setText(user.getFollowersCount());
tvUserHeaderFollowingCount.setText(user.getFollowingCount());
Glide.with(this)
.load(user.profileImageUrl)
.asBitmap()
.centerCrop()
.into(new BitmapImageViewTarget(fabUserHeaderProfileImage) {
@Override
protected void setResource(Bitmap resource) {
RoundedBitmapDrawable circularBitmapDrawable =
RoundedBitmapDrawableFactory.create(getResources(), resource);
circularBitmapDrawable.setCircular(true);
fabUserHeaderProfileImage.setImageDrawable(circularBitmapDrawable);
}
});
}
}
| {
"content_hash": "51f6a698a098d84816f7f70d06b2e557",
"timestamp": "",
"source": "github",
"line_count": 167,
"max_line_length": 131,
"avg_line_length": 40.32335329341317,
"alnum_prop": 0.6504306504306504,
"repo_name": "mallikaviswas/mytweeter",
"id": "cb49ab94cb43255645f1b556d4c3c6aa81c10e3c",
"size": "6734",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "app/src/main/java/com/codepath/apps/mytweeter/activities/ProfileActivity.java",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Java",
"bytes": "1227008"
}
],
"symlink_target": ""
} |
<?xml version="1.0" encoding="utf-8"?>
<!-- Copyright (C) 2010 The Android Open Source Project
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.
-->
<transition xmlns:android="http://schemas.android.com/apk/res/android">
<item android:drawable="@drawable/abc_list_pressed_holo_light" />
<item android:drawable="@drawable/abc_list_longpressed_holo" />
</transition>
<!-- From: file:/usr/local/google/buildbot/src/googleplex-android/mnc-supportlib-release/frameworks/support/v7/appcompat/res/drawable/abc_list_selector_background_transition_holo_light.xml --><!-- From: file:/Users/saurabhj80/Desktop/BookSC/BookSC/build/intermediates/exploded-aar/com.android.support/appcompat-v7/23.1.1/res/drawable/abc_list_selector_background_transition_holo_light.xml --> | {
"content_hash": "cc5271d7e634a569823c8d109fa83d42",
"timestamp": "",
"source": "github",
"line_count": 21,
"max_line_length": 392,
"avg_line_length": 61.38095238095238,
"alnum_prop": 0.7470907680372382,
"repo_name": "saurabhj80/BookSC",
"id": "7260de15ebb090401b7d9c572df74b63a2eb386f",
"size": "1289",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "BookSC/build/intermediates/res/merged/debug/drawable/abc_list_selector_background_transition_holo_light.xml",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Java",
"bytes": "769586"
}
],
"symlink_target": ""
} |
<md-toolbar class="author-toolbar">
<div class="md-toolbar-tools">
<span class='md-headline' ng-bind="author"></span>
</div>
</md-toolbar>
<md-content flex>
<md-list class="books-list">
<md-list-item class="md-2-line book-line" ng-repeat="book in books" ng-click="bookInfo($index)">
<div class="md-list-item-text">
<h3 class="md-body-1">
{{book.title}}
</h3>
<p class='md-caption' ng-if="book.series">{{book.series}}<span ng-if="book.ser_no"> [{{book.ser_no}}]</span></p>
</div>
<md-button class="md-fab md-primary" layout-align="right" aria-label="Download" ng-click="downloadBook(book.ID, $event)">
<md-icon md-svg-icon="assets/icons/download.svg"></md-icon>
</md-button>
</md-list-item>
</md-list>
</md-content>
| {
"content_hash": "6e1fbcbdaec6bbdcd207ddf26ad63049",
"timestamp": "",
"source": "github",
"line_count": 20,
"max_line_length": 133,
"avg_line_length": 44.35,
"alnum_prop": 0.5456595264937993,
"repo_name": "alxeg/flibooks-web",
"id": "eff577376cee5755ebafca96828f72486a47ab85",
"size": "887",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "app/views/author-books.html",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "1478"
},
{
"name": "HTML",
"bytes": "8789"
},
{
"name": "JavaScript",
"bytes": "20225"
}
],
"symlink_target": ""
} |
package org.apache.isis.viewer.wicket.model.models;
import java.math.BigDecimal;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import com.google.common.collect.Lists;
import org.apache.isis.applib.annotation.Where;
import org.apache.isis.core.commons.authentication.AuthenticationSession;
import org.apache.isis.core.commons.authentication.AuthenticationSessionProvider;
import org.apache.isis.core.metamodel.adapter.ObjectAdapter;
import org.apache.isis.core.metamodel.adapter.mgr.AdapterManager.ConcurrencyChecking;
import org.apache.isis.core.metamodel.adapter.version.ConcurrencyException;
import org.apache.isis.core.metamodel.consent.Consent;
import org.apache.isis.core.metamodel.consent.InteractionInitiatedBy;
import org.apache.isis.core.metamodel.deployment.DeploymentCategory;
import org.apache.isis.core.metamodel.facetapi.Facet;
import org.apache.isis.core.metamodel.facetapi.FacetHolder;
import org.apache.isis.core.metamodel.facets.object.parseable.ParseableFacet;
import org.apache.isis.core.metamodel.facets.object.viewmodel.ViewModelFacet;
import org.apache.isis.core.metamodel.facets.objectvalue.fileaccept.FileAcceptFacet;
import org.apache.isis.core.metamodel.facets.objectvalue.mandatory.MandatoryFacet;
import org.apache.isis.core.metamodel.facets.objectvalue.typicallen.TypicalLengthFacet;
import org.apache.isis.core.metamodel.facets.value.bigdecimal.BigDecimalValueFacet;
import org.apache.isis.core.metamodel.facets.value.string.StringValueSemanticsProvider;
import org.apache.isis.core.metamodel.spec.ObjectSpecId;
import org.apache.isis.core.metamodel.spec.ObjectSpecification;
import org.apache.isis.core.metamodel.spec.feature.ObjectActionParameter;
import org.apache.isis.core.metamodel.spec.feature.OneToOneAssociation;
import org.apache.isis.viewer.wicket.model.links.LinkAndLabel;
import org.apache.isis.viewer.wicket.model.links.LinksProvider;
import org.apache.isis.viewer.wicket.model.mementos.ActionParameterMemento;
import org.apache.isis.viewer.wicket.model.mementos.ObjectAdapterMemento;
import org.apache.isis.viewer.wicket.model.mementos.PropertyMemento;
import org.apache.isis.viewer.wicket.model.mementos.SpecUtils;
/**
* Represents a scalar of an entity, either a {@link Kind#PROPERTY property} or
* a {@link Kind#PARAMETER parameter}.
*
* <p>
* Is the backing model to each of the fields that appear in forms (for entities
* or action dialogs).
*/
public class ScalarModel extends EntityModel implements LinksProvider,HasExecutingPanel {
private static final long serialVersionUID = 1L;
public enum Kind {
PROPERTY {
@Override
public String getName(final ScalarModel scalarModel) {
return scalarModel.getPropertyMemento().getProperty(scalarModel.getSpecificationLoader()).getName();
}
@Override
public ObjectSpecification getScalarTypeSpec(final ScalarModel scalarModel) {
ObjectSpecId type = scalarModel.getPropertyMemento().getType();
return SpecUtils.getSpecificationFor(type, scalarModel.getSpecificationLoader());
}
@Override
public String getIdentifier(final ScalarModel scalarModel) {
return scalarModel.getPropertyMemento().getIdentifier();
}
@Override
public String getLongName(final ScalarModel scalarModel) {
ObjectSpecId objectSpecId = scalarModel.parentObjectAdapterMemento.getObjectSpecId();
final String specShortName = SpecUtils.getSpecificationFor(objectSpecId, scalarModel.getSpecificationLoader()).getShortIdentifier();
return specShortName + "-" + scalarModel.getPropertyMemento().getProperty(scalarModel.getSpecificationLoader()).getId();
}
@Override
public String disable(final ScalarModel scalarModel, final Where where) {
final ObjectAdapter parentAdapter = scalarModel.parentObjectAdapterMemento.getObjectAdapter(
ConcurrencyChecking.CHECK, scalarModel.getPersistenceSession(), scalarModel.getSpecificationLoader());
final OneToOneAssociation property = scalarModel.getPropertyMemento().getProperty(scalarModel.getSpecificationLoader());
try {
final Consent usable = property.isUsable(parentAdapter, InteractionInitiatedBy.USER, where);
return usable.isAllowed() ? null : usable.getReason();
} catch (final Exception ex) {
return ex.getLocalizedMessage();
}
}
@Override
public String parseAndValidate(final ScalarModel scalarModel, final String proposedPojoAsStr) {
final OneToOneAssociation property = scalarModel.getPropertyMemento().getProperty(scalarModel.getSpecificationLoader());
ParseableFacet parseableFacet = property.getFacet(ParseableFacet.class);
if (parseableFacet == null) {
parseableFacet = property.getSpecification().getFacet(ParseableFacet.class);
}
try {
final ObjectAdapter parentAdapter = scalarModel.parentObjectAdapterMemento.getObjectAdapter(ConcurrencyChecking.CHECK,
scalarModel.getPersistenceSession(), scalarModel.getSpecificationLoader());
final ObjectAdapter currentValue = property.get(parentAdapter, InteractionInitiatedBy.USER);
final ObjectAdapter proposedAdapter =
parseableFacet.parseTextEntry(currentValue, proposedPojoAsStr, InteractionInitiatedBy.USER);
final Consent valid = property.isAssociationValid(parentAdapter, proposedAdapter,
InteractionInitiatedBy.USER);
return valid.isAllowed() ? null : valid.getReason();
} catch (final ConcurrencyException ex) {
// disregard concurrency exceptions because will pick up at the IFormValidator level rather
// than each individual property.
return null;
} catch (final Exception ex) {
return ex.getLocalizedMessage();
}
}
@Override
public String validate(final ScalarModel scalarModel, final ObjectAdapter proposedAdapter) {
final ObjectAdapter parentAdapter = scalarModel.parentObjectAdapterMemento.getObjectAdapter(ConcurrencyChecking.CHECK,
scalarModel.getPersistenceSession(), scalarModel.getSpecificationLoader());
final OneToOneAssociation property = scalarModel.getPropertyMemento().getProperty(scalarModel.getSpecificationLoader());
try {
final Consent valid = property.isAssociationValid(parentAdapter, proposedAdapter,
InteractionInitiatedBy.USER);
return valid.isAllowed() ? null : valid.getReason();
} catch (final Exception ex) {
return ex.getLocalizedMessage();
}
}
@Override
public boolean isRequired(final ScalarModel scalarModel) {
final FacetHolder facetHolder = scalarModel.getPropertyMemento().getProperty(scalarModel.getSpecificationLoader());
return isRequired(facetHolder);
}
@Override
public <T extends Facet> T getFacet(final ScalarModel scalarModel, final Class<T> facetType) {
final FacetHolder facetHolder = scalarModel.getPropertyMemento().getProperty(scalarModel.getSpecificationLoader());
return facetHolder.getFacet(facetType);
}
@Override
public boolean hasChoices(final ScalarModel scalarModel) {
final PropertyMemento propertyMemento = scalarModel.getPropertyMemento();
final OneToOneAssociation property = propertyMemento.getProperty(scalarModel.getSpecificationLoader());
return property.hasChoices();
}
@Override
public List<ObjectAdapter> getChoices(
final ScalarModel scalarModel,
final ObjectAdapter[] argumentsIfAvailable,
final AuthenticationSession authenticationSession,
final DeploymentCategory deploymentCategory) {
final PropertyMemento propertyMemento = scalarModel.getPropertyMemento();
final OneToOneAssociation property = propertyMemento.getProperty(scalarModel.getSpecificationLoader());
ObjectAdapter parentAdapter = scalarModel.parentObjectAdapterMemento
.getObjectAdapter(ConcurrencyChecking.NO_CHECK, scalarModel.getPersistenceSession(),
scalarModel.getSpecificationLoader());
final ObjectAdapter[] choices = property.getChoices(
parentAdapter,
InteractionInitiatedBy.USER);
return choicesAsList(choices);
}
@Override
public boolean hasAutoComplete(final ScalarModel scalarModel) {
final PropertyMemento propertyMemento = scalarModel.getPropertyMemento();
final OneToOneAssociation property = propertyMemento.getProperty(scalarModel.getSpecificationLoader());
return property.hasAutoComplete();
}
@Override
public List<ObjectAdapter> getAutoComplete(
final ScalarModel scalarModel,
final String searchArg,
final AuthenticationSession authenticationSession,
final DeploymentCategory deploymentCategory) {
final PropertyMemento propertyMemento = scalarModel.getPropertyMemento();
final OneToOneAssociation property = propertyMemento.getProperty(scalarModel.getSpecificationLoader());
final ObjectAdapter parentAdapter =
scalarModel.parentObjectAdapterMemento.getObjectAdapter(ConcurrencyChecking.NO_CHECK,
scalarModel.getPersistenceSession(), scalarModel.getSpecificationLoader());
final ObjectAdapter[] choices =
property.getAutoComplete(
parentAdapter, searchArg,
InteractionInitiatedBy.USER);
return choicesAsList(choices);
}
@Override
public int getAutoCompleteOrChoicesMinLength(ScalarModel scalarModel) {
if (scalarModel.hasAutoComplete()) {
final PropertyMemento propertyMemento = scalarModel.getPropertyMemento();
final OneToOneAssociation property = propertyMemento.getProperty(scalarModel.getSpecificationLoader());
return property.getAutoCompleteMinLength();
} else {
return 0;
}
}
@Override
public void resetVersion(ScalarModel scalarModel) {
scalarModel.parentObjectAdapterMemento.resetVersion(scalarModel.getPersistenceSession(),
scalarModel.getSpecificationLoader());
}
@Override
public String getDescribedAs(final ScalarModel scalarModel) {
final PropertyMemento propertyMemento = scalarModel.getPropertyMemento();
final OneToOneAssociation property = propertyMemento.getProperty(scalarModel.getSpecificationLoader());
return property.getDescription();
}
@Override
public Integer getLength(ScalarModel scalarModel) {
final PropertyMemento propertyMemento = scalarModel.getPropertyMemento();
final OneToOneAssociation property = propertyMemento.getProperty(scalarModel.getSpecificationLoader());
final BigDecimalValueFacet facet = property.getFacet(BigDecimalValueFacet.class);
return facet != null? facet.getLength(): null;
}
@Override
public Integer getScale(ScalarModel scalarModel) {
final PropertyMemento propertyMemento = scalarModel.getPropertyMemento();
final OneToOneAssociation property = propertyMemento.getProperty(scalarModel.getSpecificationLoader());
final BigDecimalValueFacet facet = property.getFacet(BigDecimalValueFacet.class);
return facet != null? facet.getScale(): null;
}
@Override
public int getTypicalLength(ScalarModel scalarModel) {
final PropertyMemento propertyMemento = scalarModel.getPropertyMemento();
final OneToOneAssociation property = propertyMemento.getProperty(scalarModel.getSpecificationLoader());
final TypicalLengthFacet facet = property.getFacet(TypicalLengthFacet.class);
return facet != null? facet.value() : StringValueSemanticsProvider.TYPICAL_LENGTH;
}
@Override
public String getFileAccept(ScalarModel scalarModel) {
final PropertyMemento propertyMemento = scalarModel.getPropertyMemento();
final OneToOneAssociation property = propertyMemento.getProperty(scalarModel.getSpecificationLoader());
final FileAcceptFacet facet = property.getFacet(FileAcceptFacet.class);
return facet != null? facet.value(): null;
}
@Override
public void init(final ScalarModel scalarModel) {
reset(scalarModel);
}
@Override
public void reset(ScalarModel scalarModel) {
final OneToOneAssociation property = scalarModel.propertyMemento.getProperty(scalarModel.getSpecificationLoader());
final ObjectAdapter parentAdapter =
scalarModel.parentObjectAdapterMemento.getObjectAdapter(ConcurrencyChecking.CHECK,
scalarModel.getPersistenceSession(), scalarModel.getSpecificationLoader());
final ObjectAdapter associatedAdapter =
property.get(parentAdapter, InteractionInitiatedBy.USER);
scalarModel.setObject(associatedAdapter);
}
},
PARAMETER {
@Override
public String getName(final ScalarModel scalarModel) {
return scalarModel.getParameterMemento().getActionParameter(scalarModel.getSpecificationLoader()).getName();
}
@Override
public ObjectSpecification getScalarTypeSpec(final ScalarModel scalarModel) {
return scalarModel.getParameterMemento().getSpecification(scalarModel.getSpecificationLoader());
}
@Override
public String getIdentifier(final ScalarModel scalarModel) {
return "" + scalarModel.getParameterMemento().getNumber();
}
@Override
public String getLongName(final ScalarModel scalarModel) {
final ObjectAdapterMemento adapterMemento = scalarModel.getObjectAdapterMemento();
if (adapterMemento == null) {
// shouldn't happen
return null;
}
ObjectSpecId objectSpecId = adapterMemento.getObjectSpecId();
final String specShortName = SpecUtils.getSpecificationFor(objectSpecId, scalarModel.getSpecificationLoader()).getShortIdentifier();
final String parmId = scalarModel.getParameterMemento().getActionParameter(scalarModel.getSpecificationLoader()).getIdentifier().toNameIdentityString();
return specShortName + "-" + parmId + "-" + scalarModel.getParameterMemento().getNumber();
}
@Override
public String disable(final ScalarModel scalarModel, Where where) {
// always enabled
return null;
}
@Override
public String parseAndValidate(final ScalarModel scalarModel, final String proposedPojoAsStr) {
final ObjectActionParameter parameter = scalarModel.getParameterMemento().getActionParameter(
scalarModel.getSpecificationLoader());
try {
final ObjectAdapter parentAdapter = scalarModel.parentObjectAdapterMemento.getObjectAdapter(ConcurrencyChecking.CHECK,
scalarModel.getPersistenceSession(), scalarModel.getSpecificationLoader());
final String invalidReasonIfAny = parameter.isValid(parentAdapter, proposedPojoAsStr,
InteractionInitiatedBy.USER
);
return invalidReasonIfAny;
} catch (final Exception ex) {
return ex.getLocalizedMessage();
}
}
@Override
public String validate(final ScalarModel scalarModel, final ObjectAdapter proposedAdapter) {
final ObjectActionParameter parameter = scalarModel.getParameterMemento().getActionParameter(
scalarModel.getSpecificationLoader());
try {
final ObjectAdapter parentAdapter = scalarModel.parentObjectAdapterMemento.getObjectAdapter(ConcurrencyChecking.CHECK,
scalarModel.getPersistenceSession(), scalarModel.getSpecificationLoader());
final String invalidReasonIfAny = parameter.isValid(parentAdapter, proposedAdapter.getObject(),
InteractionInitiatedBy.USER
);
return invalidReasonIfAny;
} catch (final Exception ex) {
return ex.getLocalizedMessage();
}
}
@Override
public boolean isRequired(final ScalarModel scalarModel) {
final FacetHolder facetHolder = scalarModel.getParameterMemento().getActionParameter(
scalarModel.getSpecificationLoader());
return isRequired(facetHolder);
}
@Override
public <T extends Facet> T getFacet(final ScalarModel scalarModel, final Class<T> facetType) {
final FacetHolder facetHolder = scalarModel.getParameterMemento().getActionParameter(
scalarModel.getSpecificationLoader());
return facetHolder.getFacet(facetType);
}
@Override
public boolean hasChoices(final ScalarModel scalarModel) {
final ActionParameterMemento parameterMemento = scalarModel.getParameterMemento();
final ObjectActionParameter actionParameter = parameterMemento.getActionParameter(scalarModel.getSpecificationLoader());
return actionParameter.hasChoices();
}
@Override
public List<ObjectAdapter> getChoices(
final ScalarModel scalarModel,
final ObjectAdapter[] argumentsIfAvailable,
final AuthenticationSession authenticationSession,
final DeploymentCategory deploymentCategory) {
final ActionParameterMemento parameterMemento = scalarModel.getParameterMemento();
final ObjectActionParameter actionParameter = parameterMemento.getActionParameter(scalarModel.getSpecificationLoader());
final ObjectAdapter parentAdapter =
scalarModel.parentObjectAdapterMemento.getObjectAdapter(ConcurrencyChecking.CHECK,
scalarModel.getPersistenceSession(), scalarModel.getSpecificationLoader());
final ObjectAdapter[] choices =
actionParameter.getChoices(
parentAdapter, argumentsIfAvailable,
InteractionInitiatedBy.USER);
return choicesAsList(choices);
}
@Override
public boolean hasAutoComplete(final ScalarModel scalarModel) {
final ActionParameterMemento parameterMemento = scalarModel.getParameterMemento();
final ObjectActionParameter actionParameter = parameterMemento.getActionParameter(scalarModel.getSpecificationLoader());
return actionParameter.hasAutoComplete();
}
@Override
public List<ObjectAdapter> getAutoComplete(
final ScalarModel scalarModel,
final String searchArg,
final AuthenticationSession authenticationSession,
final DeploymentCategory deploymentCategory) {
final ActionParameterMemento parameterMemento = scalarModel.getParameterMemento();
final ObjectActionParameter actionParameter = parameterMemento.getActionParameter(scalarModel.getSpecificationLoader());
final ObjectAdapter parentAdapter =
scalarModel.parentObjectAdapterMemento.getObjectAdapter(ConcurrencyChecking.NO_CHECK,
scalarModel.getPersistenceSession(), scalarModel.getSpecificationLoader());
final ObjectAdapter[] choices = actionParameter.getAutoComplete(
parentAdapter, searchArg,
InteractionInitiatedBy.USER);
return choicesAsList(choices);
}
@Override
public int getAutoCompleteOrChoicesMinLength(ScalarModel scalarModel) {
if (scalarModel.hasAutoComplete()) {
final ActionParameterMemento parameterMemento = scalarModel.getParameterMemento();
final ObjectActionParameter actionParameter = parameterMemento.getActionParameter(
scalarModel.getSpecificationLoader());
return actionParameter.getAutoCompleteMinLength();
} else {
return 0;
}
}
@Override
public void resetVersion(ScalarModel scalarModel) {
// no-op?
}
@Override
public String getDescribedAs(final ScalarModel scalarModel) {
final ActionParameterMemento parameterMemento = scalarModel.getParameterMemento();
final ObjectActionParameter actionParameter = parameterMemento.getActionParameter(scalarModel.getSpecificationLoader());
return actionParameter.getDescription();
}
@Override
public Integer getLength(ScalarModel scalarModel) {
final ActionParameterMemento parameterMemento = scalarModel.getParameterMemento();
final ObjectActionParameter actionParameter = parameterMemento.getActionParameter(scalarModel.getSpecificationLoader());
final BigDecimalValueFacet facet = actionParameter.getFacet(BigDecimalValueFacet.class);
return facet != null? facet.getLength(): null;
}
@Override
public Integer getScale(ScalarModel scalarModel) {
final ActionParameterMemento parameterMemento = scalarModel.getParameterMemento();
final ObjectActionParameter actionParameter = parameterMemento.getActionParameter(scalarModel.getSpecificationLoader());
final BigDecimalValueFacet facet = actionParameter.getFacet(BigDecimalValueFacet.class);
return facet != null? facet.getScale(): null;
}
@Override
public int getTypicalLength(ScalarModel scalarModel) {
final ActionParameterMemento parameterMemento = scalarModel.getParameterMemento();
final ObjectActionParameter actionParameter = parameterMemento.getActionParameter(scalarModel.getSpecificationLoader());
final TypicalLengthFacet facet = actionParameter.getFacet(TypicalLengthFacet.class);
return facet != null? facet.value() : StringValueSemanticsProvider.TYPICAL_LENGTH;
}
@Override
public String getFileAccept(ScalarModel scalarModel) {
final ActionParameterMemento parameterMemento = scalarModel.getParameterMemento();
final ObjectActionParameter actionParameter = parameterMemento.getActionParameter(scalarModel.getSpecificationLoader());
final FileAcceptFacet facet = actionParameter.getFacet(FileAcceptFacet.class);
return facet != null? facet.value(): null;
}
@Override
public void init(final ScalarModel scalarModel) {
// no-op
}
@Override
public void reset(ScalarModel scalarModel) {
final ObjectActionParameter actionParameter = scalarModel.parameterMemento.getActionParameter(
scalarModel.getSpecificationLoader());
final ObjectAdapter parentAdapter =
scalarModel.parentObjectAdapterMemento.getObjectAdapter(ConcurrencyChecking.NO_CHECK,
scalarModel.getPersistenceSession(), scalarModel.getSpecificationLoader());
final ObjectAdapter defaultAdapter = actionParameter.getDefault(parentAdapter);
scalarModel.setObject(defaultAdapter);
}
};
private static List<ObjectAdapter> choicesAsList(final ObjectAdapter[] choices) {
if (choices != null && choices.length > 0) {
return Arrays.asList(choices);
}
return Collections.emptyList();
}
public abstract String getName(ScalarModel scalarModel);
public abstract ObjectSpecification getScalarTypeSpec(ScalarModel scalarModel);
public abstract String getIdentifier(ScalarModel scalarModel);
public abstract String disable(ScalarModel scalarModel, Where where);
public abstract String parseAndValidate(ScalarModel scalarModel, String proposedPojoAsStr);
public abstract String validate(ScalarModel scalarModel, ObjectAdapter proposedAdapter);
public abstract String getLongName(ScalarModel scalarModel);
public abstract boolean isRequired(ScalarModel scalarModel);
public abstract <T extends Facet> T getFacet(ScalarModel scalarModel, Class<T> facetType);
static boolean isRequired(final FacetHolder facetHolder) {
final MandatoryFacet mandatoryFacet = facetHolder.getFacet(MandatoryFacet.class);
final boolean required = mandatoryFacet != null && !mandatoryFacet.isInvertedSemantics();
return required;
}
public abstract boolean hasChoices(ScalarModel scalarModel);
public abstract List<ObjectAdapter> getChoices(
final ScalarModel scalarModel,
final ObjectAdapter[] argumentsIfAvailable,
final AuthenticationSession authenticationSession,
final DeploymentCategory deploymentCategory);
public abstract boolean hasAutoComplete(ScalarModel scalarModel);
public abstract List<ObjectAdapter> getAutoComplete(
ScalarModel scalarModel,
String searchArg,
final AuthenticationSession authenticationSession, final DeploymentCategory deploymentCategory);
public abstract int getAutoCompleteOrChoicesMinLength(ScalarModel scalarModel);
public abstract void resetVersion(ScalarModel scalarModel);
public abstract String getDescribedAs(ScalarModel scalarModel);
public abstract Integer getLength(ScalarModel scalarModel);
public abstract Integer getScale(ScalarModel scalarModel);
public abstract int getTypicalLength(ScalarModel scalarModel);
public abstract String getFileAccept(ScalarModel scalarModel);
public abstract void init(ScalarModel scalarModel);
public abstract void reset(ScalarModel scalarModel);
}
private final Kind kind;
private final ObjectAdapterMemento parentObjectAdapterMemento;
/**
* Populated only if {@link #getKind()} is {@link Kind#PARAMETER}
*/
private ActionParameterMemento parameterMemento;
/**
* Populated only if {@link #getKind()} is {@link Kind#PROPERTY}
*/
private PropertyMemento propertyMemento;
/**
* Creates a model representing an action parameter of an action of a parent
* object, with the {@link #getObject() value of this model} to be default
* value (if any) of that action parameter.
*/
public ScalarModel(final ObjectAdapterMemento parentObjectAdapterMemento, final ActionParameterMemento apm) {
this.kind = Kind.PARAMETER;
this.parentObjectAdapterMemento = parentObjectAdapterMemento;
this.parameterMemento = apm;
init();
setMode(Mode.EDIT);
}
/**
* Creates a model representing a property of a parent object, with the
* {@link #getObject() value of this model} to be current value of the
* property.
*/
public ScalarModel(final ObjectAdapterMemento parentObjectAdapterMemento, final PropertyMemento pm) {
this.kind = Kind.PROPERTY;
this.parentObjectAdapterMemento = parentObjectAdapterMemento;
this.propertyMemento = pm;
init();
getAndStore(parentObjectAdapterMemento);
setMode(Mode.VIEW);
}
private void init() {
kind.init(this);
}
public void reset() {
kind.reset(this);
}
public ObjectAdapterMemento getParentObjectAdapterMemento() {
return parentObjectAdapterMemento;
}
private void getAndStore(final ObjectAdapterMemento parentAdapterMemento) {
final OneToOneAssociation property = propertyMemento.getProperty(getSpecificationLoader());
final ObjectAdapter parentAdapter = parentAdapterMemento.getObjectAdapter(ConcurrencyChecking.CHECK,
getPersistenceSession(), getSpecificationLoader());
final ObjectAdapter associatedAdapter = property.get(parentAdapter, InteractionInitiatedBy.USER);
setObject(associatedAdapter);
}
/**
* Whether the scalar represents a {@link Kind#PROPERTY property} or a
* {@link Kind#PARAMETER}.
*/
public Kind getKind() {
return kind;
}
public String getName() {
return kind.getName(this);
}
/**
* Populated only if {@link #getKind()} is {@link Kind#PROPERTY}
*/
public PropertyMemento getPropertyMemento() {
return propertyMemento;
}
/**
* Populated only if {@link #getKind()} is {@link Kind#PARAMETER}
*/
public ActionParameterMemento getParameterMemento() {
return parameterMemento;
}
/**
* Overrides superclass' implementation, because a {@link ScalarModel} can
* know the {@link ObjectSpecification of} the {@link ObjectAdapter adapter}
* without there necessarily being any adapter being
* {@link #setObject(ObjectAdapter) set}.
*/
@Override
public ObjectSpecification getTypeOfSpecification() {
return kind.getScalarTypeSpec(this);
}
public boolean isScalarTypeAnyOf(final Class<?>... requiredClass) {
final String fullName = getTypeOfSpecification().getFullIdentifier();
for (final Class<?> requiredCls : requiredClass) {
if (fullName.equals(requiredCls.getName())) {
return true;
}
}
return false;
}
public String getObjectAsString() {
final ObjectAdapter adapter = getObject();
if (adapter == null) {
return null;
}
return adapter.titleString(null);
}
@Override
public void setObject(final ObjectAdapter adapter) {
super.setObject(adapter); // associated value
}
public void setObjectAsString(final String enteredText) {
// parse text to get adapter
final ParseableFacet parseableFacet = getTypeOfSpecification().getFacet(ParseableFacet.class);
if (parseableFacet == null) {
throw new RuntimeException("unable to parse string for " + getTypeOfSpecification().getFullIdentifier());
}
final ObjectAdapter adapter = parseableFacet.parseTextEntry(getObject(), enteredText,
InteractionInitiatedBy.USER
);
setObject(adapter);
}
public String disable(Where where) {
return kind.disable(this, where);
}
public String validate(final ObjectAdapter proposedAdapter) {
return kind.validate(this, proposedAdapter);
}
/**
* Default implementation looks up from singleton, but can be overridden for
* testing.
*/
protected AuthenticationSession getAuthenticationSession() {
return getPersistenceSession().getServicesInjector().lookupService(AuthenticationSessionProvider.class).getAuthenticationSession();
}
public boolean isRequired() {
return kind.isRequired(this);
}
public String getLongName() {
return kind.getLongName(this);
}
public <T extends Facet> T getFacet(final Class<T> facetType) {
return kind.getFacet(this, facetType);
}
public String getDescribedAs() {
return kind.getDescribedAs(this);
}
public String getFileAccept() {
return kind.getFileAccept(this);
}
public boolean hasChoices() {
return kind.hasChoices(this);
}
public List<ObjectAdapter> getChoices(
final ObjectAdapter[] argumentsIfAvailable,
final AuthenticationSession authenticationSession,
final DeploymentCategory deploymentCategory) {
return kind.getChoices(this, argumentsIfAvailable, authenticationSession, deploymentCategory);
}
public boolean hasAutoComplete() {
return kind.hasAutoComplete(this);
}
public List<ObjectAdapter> getAutoComplete(
final String searchTerm,
final AuthenticationSession authenticationSession,
final DeploymentCategory deploymentCategory) {
return kind.getAutoComplete(this, searchTerm, authenticationSession, deploymentCategory);
}
/**
* for {@link BigDecimal}s only.
*
* @see #getScale()
*/
public int getLength() {
return kind.getLength(this);
}
/**
* for {@link BigDecimal}s only.
*
* @see #getLength()
*/
public Integer getScale() {
return kind.getScale(this);
}
/**
* Additional links to render (if any)
*/
private List<LinkAndLabel> entityActions = Lists.newArrayList();
@Override
public List<LinkAndLabel> getLinks() {
return Collections.unmodifiableList(entityActions);
}
/**
* @return
*/
public int getAutoCompleteMinLength() {
return kind.getAutoCompleteOrChoicesMinLength(this);
}
/**
* @return
*/
public ScalarModelWithPending asScalarModelWithPending() {
return new ScalarModelWithPending(){
private static final long serialVersionUID = 1L;
@Override
public ObjectAdapterMemento getPending() {
return ScalarModel.this.getPending();
}
@Override
public void setPending(ObjectAdapterMemento pending) {
ScalarModel.this.setPending(pending);
}
@Override
public ScalarModel getScalarModel() {
return ScalarModel.this;
}
};
}
public String getReasonInvalidIfAny() {
final OneToOneAssociation property = getPropertyMemento().getProperty(getSpecificationLoader());
final ObjectAdapter adapter = getParentObjectAdapterMemento().getObjectAdapter(ConcurrencyChecking.CHECK,
getPersistenceSession(), getSpecificationLoader());
final ObjectAdapter associate = getObject();
final Consent validity = property.isAssociationValid(adapter, associate, InteractionInitiatedBy.USER);
return validity.isAllowed() ? null : validity.getReason();
}
/**
* Apply changes to the underlying adapter (possibly returning a new adapter).
*
* @return adapter, which may be different from the original (if a {@link ViewModelFacet#isCloneable(Object) cloneable} view model, for example.
*/
public ObjectAdapter applyValue(ObjectAdapter adapter) {
final OneToOneAssociation property = getPropertyMemento().getProperty(getSpecificationLoader());
//
// previously there was a guard here to only apply changes provided:
//
// property.containsDoOpFacet(NotPersistedFacet.class) == null
//
// however, that logic is wrong; although a property may not be directly
// persisted so far as JDO is concerned, it may be indirectly persisted
// as the result of business logic in the setter.
//
// for example, see ExampleTaggableEntity (in isisaddons-module-tags).
//
//
// previously (prior to XML layouts and 'single property' edits) we also used to check if
// the property was disabled, using:
//
// if(property.containsDoOpFacet(DisabledFacet.class)) {
// // skip, as per comments above
// return;
// }
//
// However, this would seem to be wrong, because the presence of a DisabledFacet doesn't necessarily mean
// that the property is disabled (its disabledReason(...) might return null).
//
// In any case, the only code that calls this method already does the check, so think this is safe
// to just remove.
final ObjectAdapter associate = getObject();
property.set(adapter, associate, InteractionInitiatedBy.USER);
final ViewModelFacet recreatableObjectFacet = adapter.getSpecification().getFacet(ViewModelFacet.class);
if(recreatableObjectFacet != null) {
final Object viewModel = adapter.getObject();
final boolean cloneable = recreatableObjectFacet.isCloneable(viewModel);
if(cloneable) {
final Object newViewModel = recreatableObjectFacet.clone(viewModel);
adapter = getPersistenceSession().adapterFor(newViewModel);
}
}
return adapter;
}
// //////////////////////////////////////
private ExecutingPanel executingPanel;
/**
* A hint passed from one Wicket UI component to another.
*
* Mot actually used by the model itself.
*/
public ExecutingPanel getExecutingPanel() {
return executingPanel;
}
public void setExecutingPanel(final ExecutingPanel executingPanel) {
this.executingPanel = executingPanel;
}
// //////////////////////////////////////
/**
* transient because only temporary hint.
*/
private transient ObjectAdapter[] actionArgsHint;
public void setActionArgsHint(ObjectAdapter[] actionArgsHint) {
this.actionArgsHint = actionArgsHint;
}
/**
* The initial call of choicesXxx() for any given scalar argument needs the current values
* of all args (possibly as initialized through a defaultNXxx().
*/
public ObjectAdapter[] getActionArgsHint() {
return actionArgsHint;
}
}
| {
"content_hash": "aa7cd4881418f97cbfacc32cc4ffa235",
"timestamp": "",
"source": "github",
"line_count": 892,
"max_line_length": 168,
"avg_line_length": 44.850896860986545,
"alnum_prop": 0.6504611692953733,
"repo_name": "niv0/isis",
"id": "755da1be220345fa7fa1deac65fbdac437c30bac",
"size": "40832",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "core/viewer-wicket-model/src/main/java/org/apache/isis/viewer/wicket/model/models/ScalarModel.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "53186"
},
{
"name": "Cucumber",
"bytes": "2158"
},
{
"name": "Groovy",
"bytes": "28310"
},
{
"name": "HTML",
"bytes": "440399"
},
{
"name": "Java",
"bytes": "11833294"
},
{
"name": "JavaScript",
"bytes": "115833"
},
{
"name": "Shell",
"bytes": "14797"
}
],
"symlink_target": ""
} |
Mytranspo3::Application.configure do
# Settings specified here will take precedence over those in config/application.rb
# Code is not reloaded between requests
config.cache_classes = true
# Full error reports are disabled and caching is turned on
config.consider_all_requests_local = false
config.action_controller.perform_caching = true
# Disable Rails's static asset server (Apache or nginx will already do this)
config.serve_static_assets = false
# Compress JavaScripts and CSS
config.assets.compress = true
# Don't fallback to assets pipeline if a precompiled asset is missed
config.assets.compile = false
# Generate digests for assets URLs
config.assets.digest = true
# Defaults to nil and saved in location specified by config.assets.prefix
# config.assets.manifest = YOUR_PATH
# Specifies the header that your server uses for sending files
# config.action_dispatch.x_sendfile_header = "X-Sendfile" # for apache
# config.action_dispatch.x_sendfile_header = 'X-Accel-Redirect' # for nginx
# Force all access to the app over SSL, use Strict-Transport-Security, and use secure cookies.
# config.force_ssl = true
# See everything in the log (default is :info)
# config.log_level = :debug
# Prepend all log lines with the following tags
# config.log_tags = [ :subdomain, :uuid ]
# Use a different logger for distributed setups
# config.logger = ActiveSupport::TaggedLogging.new(SyslogLogger.new)
# Use a different cache store in production
# config.cache_store = :mem_cache_store
# Enable serving of images, stylesheets, and JavaScripts from an asset server
# config.action_controller.asset_host = "http://assets.example.com"
# Precompile additional assets (application.js, application.css, and all non-JS/CSS are already added)
# config.assets.precompile += %w( search.js )
# Disable delivery errors, bad email addresses will be ignored
# config.action_mailer.raise_delivery_errors = false
# Enable threaded mode
# config.threadsafe!
# Enable locale fallbacks for I18n (makes lookups for any locale fall back to
# the I18n.default_locale when a translation can not be found)
config.i18n.fallbacks = true
# Send deprecation notices to registered listeners
config.active_support.deprecation = :notify
# Log the query plan for queries taking more than this (works
# with SQLite, MySQL, and PostgreSQL)
# config.active_record.auto_explain_threshold_in_seconds = 0.5
end
| {
"content_hash": "ea3fcd89ca16278fbb6594705ccb7779",
"timestamp": "",
"source": "github",
"line_count": 67,
"max_line_length": 104,
"avg_line_length": 37.07462686567164,
"alnum_prop": 0.7467793880837359,
"repo_name": "rpeden/transpobuddy",
"id": "30fc8d14058ac70ef6cd2e2a3f294659351df1cd",
"size": "2484",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "config/environments/production.rb",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "1777"
},
{
"name": "CoffeeScript",
"bytes": "1750"
},
{
"name": "HTML",
"bytes": "12382"
},
{
"name": "JavaScript",
"bytes": "15424"
},
{
"name": "Ruby",
"bytes": "31134"
}
],
"symlink_target": ""
} |
An Arduino based display unit DIY kit
| {
"content_hash": "1c0cf38a306e8b40f69c372dd7d0dfb5",
"timestamp": "",
"source": "github",
"line_count": 1,
"max_line_length": 37,
"avg_line_length": 38,
"alnum_prop": 0.8157894736842105,
"repo_name": "curiouselectric/Display-O-Matic",
"id": "87ceeb098d6f8d6b979805d26722691a6972b842",
"size": "56",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "README.md",
"mode": "33188",
"license": "mit",
"language": [],
"symlink_target": ""
} |
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="app_name">LollipopDemo</string>
<string name="action_settings">Settings</string>
<!-- CardView -->
<string name="demo_cardview">CardView</string>
<string name="demo_cardview_title">Florida</string>
<string name="demo_cardview_message">Typical day in the Sunshine State.</string>
<!-- RecyclerView -->
<string name="demo_recycler_view">RecyclerView</string>
<string name="demo_recycler_touch_to_remove">Touch to remove item:</string>
<!-- Reveal -->
<string name="demo_reveal">Reveal</string>
<!-- Ripple -->
<string name="demo_ripple">Ripple</string>
<string name="demo_ripple_button">Ripple!</string>
<!-- SharedView -->
<string name="demo_activity_transitions">New Activity Transitions</string>
<string name="space_picture_detail_text">This dramatic image offers a peek inside a cavern of roiling dust and gas where thousands of stars are forming. More than 3,000 stars of various sizes appear in this image of the Orion Nebula. Some of them have never been seen in visible light. Ultraviolet light unleashed by the four central stars is carving a cavity in the nebula and disrupting the growth of hundreds of smaller stars.</string>
<string name="demo_shared_view">Shared View</string>
<!-- Wearable Notifications -->
<string name="demo_wearable_notifications">Wearable Notifications</string>
<string name="demo_wearable_notifications_edittext_send_text">Text to send</string>
<string name="demo_wearable_notifications_button_send">Send Notification</string>
<string name="demo_wearable_notifications_button_clear">Clear Text</string>
<string name="demo_wearable_notifications_notification_title">Important Message</string>
<string name="demo_wearable_notifications_notification_talk_back">Talk Back</string>
<!-- Wearable Sync -->
<string name="demo_wearable_sync">Wearable Sync</string>
</resources>
| {
"content_hash": "399b4aadd501c748c8da34c8107e8efe",
"timestamp": "",
"source": "github",
"line_count": 33,
"max_line_length": 442,
"avg_line_length": 60.03030303030303,
"alnum_prop": 0.7223624432104997,
"repo_name": "ToxicBakery/LollipopDemo",
"id": "65cfff6230ea17dc729f711a171d1c6c62bd3a6e",
"size": "1981",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "mobile/src/main/res/values/strings.xml",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Java",
"bytes": "53838"
}
],
"symlink_target": ""
} |
<?xml version="1.0" encoding="utf-8"?>
<appengine-web-app xmlns="http://appengine.google.com/ns/1.0">
<application>thymeleaf-template-test</application>
<version>1</version>
<threadsafe>true</threadsafe>
</appengine-web-app>
| {
"content_hash": "d2eeff462cbeaf51c0061c703f727dd9",
"timestamp": "",
"source": "github",
"line_count": 6,
"max_line_length": 62,
"avg_line_length": 39.5,
"alnum_prop": 0.7046413502109705,
"repo_name": "dsanoster/thymeleaf-template-test",
"id": "dfae087742b9adb5ef3ab4d2b7d89b25c30b171c",
"size": "237",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/main/webapp/WEB-INF/appengine-web.xml",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Java",
"bytes": "947"
}
],
"symlink_target": ""
} |
package com.farmafene.cas.integration.sample.ws;
import javax.jws.WebService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;
import com.farmafene.cas.integration.sample.ISampleBasicService;
import com.farmafene.cas.integration.sample.SampleBasicServiceWS;
import com.farmafene.cas.integration.sample.SampleRequest;
import com.farmafene.cas.integration.sample.SampleResponse;
@Service("sample3BasicEndPoint")
@WebService(
//
serviceName = "sampleBasic",
//
portName = "sampleBasicPort"
//
)
public class Sample3BasicImpl implements SampleBasicServiceWS {
@Autowired
@Qualifier("sample3Basic")
private ISampleBasicService service;
public SampleResponse echo(SampleRequest request) {
return this.service.echo(request);
}
}
| {
"content_hash": "9fc815c8642dcccc8468ecfe1d65bc3c",
"timestamp": "",
"source": "github",
"line_count": 33,
"max_line_length": 65,
"avg_line_length": 27.09090909090909,
"alnum_prop": 0.7919463087248322,
"repo_name": "venanciolm/cas-server",
"id": "1bcb78cd0e0d6c31a7683e26708532f407106b47",
"size": "2124",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "cxf/src/main/java/com/farmafene/cas/integration/sample/ws/Sample3BasicImpl.java",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "19048"
},
{
"name": "Java",
"bytes": "247506"
},
{
"name": "JavaScript",
"bytes": "15405"
}
],
"symlink_target": ""
} |
package pl.touk.sputnik.processor.tslint;
import com.google.common.collect.ImmutableMap;
import org.junit.jupiter.api.Test;
import pl.touk.sputnik.configuration.ConfigurationSetup;
import pl.touk.sputnik.configuration.GeneralOption;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.catchThrowable;
class TSLintScriptTest {
@Test
void shouldFailWhenConfigFileIsMissing() {
final String configFile = "tslint.xml.not.json";
new ConfigurationSetup().setUp(ImmutableMap.of(
GeneralOption.TSLINT_CONFIGURATION_FILE.getKey(), configFile));
TSLintScript tsLint = new TSLintScript(null, configFile);
Throwable thrown = catchThrowable(tsLint::validateConfiguration);
assertThat(thrown).isInstanceOf(TSLintException.class)
.hasMessageContaining("Could not find tslint configuration file: " + configFile);
}
@Test
void shouldPassWhenConfigFileIsValid() {
final String configFile = "src/main/resources/tslint.json";
new ConfigurationSetup().setUp(ImmutableMap.of(GeneralOption.TSLINT_CONFIGURATION_FILE.getKey(), configFile));
TSLintScript tsLint = new TSLintScript(null, configFile);
Throwable thrown = catchThrowable(tsLint::validateConfiguration);
assertThat(thrown).isNull();
}
}
| {
"content_hash": "f0b1ac62fef16f5c09392f82443e8f86",
"timestamp": "",
"source": "github",
"line_count": 39,
"max_line_length": 118,
"avg_line_length": 35.23076923076923,
"alnum_prop": 0.735080058224163,
"repo_name": "TouK/sputnik",
"id": "8d9db8d3f60e0e97e3fb6bc3c39207016e3097e7",
"size": "1374",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "src/test/java/pl/touk/sputnik/processor/tslint/TSLintScriptTest.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Groovy",
"bytes": "659"
},
{
"name": "Java",
"bytes": "386996"
},
{
"name": "JavaScript",
"bytes": "541"
},
{
"name": "Kotlin",
"bytes": "771"
},
{
"name": "Mustache",
"bytes": "112"
},
{
"name": "Scala",
"bytes": "196"
},
{
"name": "Shell",
"bytes": "2423"
},
{
"name": "TypeScript",
"bytes": "224"
}
],
"symlink_target": ""
} |
require "formula"
require "cli/parser"
module Homebrew
extend T::Sig
module_function
sig { returns(CLI::Parser) }
def vendor_gems_args
Homebrew::CLI::Parser.new do
usage_banner <<~EOS
`vendor-gems`
Install and commit Homebrew's vendored gems.
EOS
comma_array "--update",
description: "Update all vendored Gems to the latest version."
max_named 0
end
end
sig { void }
def vendor_gems
args = vendor_gems_args.parse
Homebrew.install_bundler!
ohai "cd #{HOMEBREW_LIBRARY_PATH}"
HOMEBREW_LIBRARY_PATH.cd do
if args.update
ohai "bundle update"
safe_system "bundle", "update", *args.update
ohai "git add Gemfile.lock"
system "git", "add", "Gemfile.lock"
end
ohai "bundle install --standalone"
safe_system "bundle", "install", "--standalone"
ohai "bundle pristine"
safe_system "bundle", "pristine"
ohai "git add vendor/bundle"
system "git", "add", "vendor/bundle"
Utils::Git.set_name_email!
Utils::Git.setup_gpg!
ohai "git commit"
system "git", "commit", "--message", "brew vendor-gems: commit updates."
end
end
end
| {
"content_hash": "28226782b6f8852f108739b8b916bddc",
"timestamp": "",
"source": "github",
"line_count": 57,
"max_line_length": 80,
"avg_line_length": 21.56140350877193,
"alnum_prop": 0.6069975589910497,
"repo_name": "konqui/brew",
"id": "a9394c890547eeda2e771f3bff60d1ea964b7b9b",
"size": "1275",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "Library/Homebrew/dev-cmd/vendor-gems.rb",
"mode": "33188",
"license": "bsd-2-clause",
"language": [
{
"name": "Dockerfile",
"bytes": "1460"
},
{
"name": "HTML",
"bytes": "12438"
},
{
"name": "PostScript",
"bytes": "485"
},
{
"name": "Roff",
"bytes": "72771"
},
{
"name": "Ruby",
"bytes": "2188228"
},
{
"name": "Shell",
"bytes": "124249"
},
{
"name": "Swift",
"bytes": "1788"
}
],
"symlink_target": ""
} |
<?xml version="1.0" encoding="UTF-8" ?>
<!--
Copyright 2009-2012 The MyBatis Team
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.
-->
<!DOCTYPE configuration
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
<settings>
<setting name="lazyLoadingEnabled" value="true"/>
<setting name="aggressiveLazyLoading" value="false" />
</settings>
<environments default="development">
<environment id="development">
<transactionManager type="JDBC">
<property name="" value="" />
</transactionManager>
<dataSource type="UNPOOLED">
<property name="driver" value="org.hsqldb.jdbcDriver" />
<property name="url" value="jdbc:hsqldb:mem:lazyload_proxyfactory_comparison_default" />
<property name="username" value="sa" />
</dataSource>
</environment>
</environments>
<mappers>
<mapper resource="org/apache/ibatis/submitted/lazyload_proxyfactory_comparison/Mapper.xml" />
</mappers>
</configuration>
| {
"content_hash": "a0b9013ae3075ac4ab16971403d3f7ab",
"timestamp": "",
"source": "github",
"line_count": 45,
"max_line_length": 95,
"avg_line_length": 35.577777777777776,
"alnum_prop": 0.6720799500312304,
"repo_name": "ekirkilevics/iBatis",
"id": "22370d35cf4732fc5ed2c898cf3fe8fc0d47ea0b",
"size": "1601",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/test/java/org/apache/ibatis/submitted/lazyload_proxyfactory_comparison/mybatis-config-default.xml",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Java",
"bytes": "2765639"
}
],
"symlink_target": ""
} |
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1" charset="UTF-8">
<title>name</title>
<link href="../../../../images/logo-icon.svg" rel="icon" type="image/svg">
<script>var pathToRoot = "../../../../";</script>
<script type="text/javascript" src="../../../../scripts/sourceset_dependencies.js" async="async"></script>
<link href="../../../../styles/style.css" rel="Stylesheet">
<link href="../../../../styles/logo-styles.css" rel="Stylesheet">
<link href="../../../../styles/jetbrains-mono.css" rel="Stylesheet">
<link href="../../../../styles/main.css" rel="Stylesheet">
<script type="text/javascript" src="../../../../scripts/clipboard.js" async="async"></script>
<script type="text/javascript" src="../../../../scripts/navigation-loader.js" async="async"></script>
<script type="text/javascript" src="../../../../scripts/platform-content-handler.js" async="async"></script>
<script type="text/javascript" src="../../../../scripts/main.js" async="async"></script>
</head>
<body>
<div id="container">
<div id="leftColumn">
<div id="logo"></div>
<div id="paneSearch"></div>
<div id="sideMenu"></div>
</div>
<div id="main">
<div id="leftToggler"><span class="icon-toggler"></span></div>
<script type="text/javascript" src="../../../../scripts/pages.js"></script>
<script type="text/javascript" src="../../../../scripts/main.js"></script>
<div class="main-content" id="content" pageIds="org.hexworks.zircon.api.uievent/KeyCode.KP_DOWN/name/#/PointingToDeclaration//-828656838">
<div class="navigation-wrapper" id="navigation-wrapper">
<div class="breadcrumbs"><a href="../../../index.html">zircon.core</a>/<a href="../../index.html">org.hexworks.zircon.api.uievent</a>/<a href="../index.html">KeyCode</a>/<a href="index.html">KP_DOWN</a>/<a href="name.html">name</a></div>
<div class="pull-right d-flex">
<div class="filter-section" id="filter-section"><button class="platform-tag platform-selector common-like" data-active="" data-filter=":zircon.core:dokkaHtml/commonMain">common</button></div>
<div id="searchBar"></div>
</div>
</div>
<div class="cover ">
<h1 class="cover"><span>name</span></h1>
</div>
<div class="divergent-group" data-filterable-current=":zircon.core:dokkaHtml/commonMain" data-filterable-set=":zircon.core:dokkaHtml/commonMain"><div class="with-platform-tags"><span class="pull-right"></span></div>
<div>
<div class="platform-hinted " data-platform-hinted="data-platform-hinted"><div class="content sourceset-depenent-content" data-active="" data-togglable=":zircon.core:dokkaHtml/commonMain"><div class="symbol monospace">val <a href="name.html">name</a>: <a href="https://kotlinlang.org/api/latest/jvm/stdlib/kotlin/-string/index.html">String</a><span class="top-right-position"><span class="copy-icon"></span><div class="copy-popup-wrapper popup-to-left"><span class="copy-popup-icon"></span><span>Content copied to clipboard</span></div></span></div></div></div>
</div>
</div>
</div>
<div class="footer"><span class="go-to-top-icon"><a href="#content"></a></span><span>© 2020 Copyright</span><span class="pull-right"><span>Sponsored and developed by dokka</span><a href="https://github.com/Kotlin/dokka"><span class="padded-icon"></span></a></span></div>
</div>
</div>
</body>
</html>
| {
"content_hash": "c48103e9aa2193c65f53e7bea5aaaacd",
"timestamp": "",
"source": "github",
"line_count": 51,
"max_line_length": 565,
"avg_line_length": 69.29411764705883,
"alnum_prop": 0.6236559139784946,
"repo_name": "Hexworks/zircon",
"id": "231d3ba5b4b73c9ef41b7fc0329b46eb00d2f58f",
"size": "3535",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "docs/2020.2.0-RELEASE-KOTLIN/zircon.core/zircon.core/org.hexworks.zircon.api.uievent/-key-code/-k-p_-d-o-w-n/name.html",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Java",
"bytes": "121457"
},
{
"name": "Kotlin",
"bytes": "1792092"
},
{
"name": "Shell",
"bytes": "152"
}
],
"symlink_target": ""
} |
def dictionary_builder(lang):
dict_name = lang + "_dictionary.txt"
file = open(dict_name, "r", -1, "UTF-8")
lines = file.readlines()
cleanedLines = [l.replace("\n", "") for l in lines]
encoder_dict = dict()
for entry in cleanedLines:
kv = entry.split("=")
encoder_dict[kv[0]] = kv[1]
return encoder_dict
| {
"content_hash": "716990f19eeae5ca5340f1ec47305c8d",
"timestamp": "",
"source": "github",
"line_count": 11,
"max_line_length": 55,
"avg_line_length": 31.727272727272727,
"alnum_prop": 0.5845272206303725,
"repo_name": "vbuchade/Spycraft",
"id": "bc190f708ee9fe33b11ba5ead39e0cec78d46eb0",
"size": "349",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "dictionary_builder.py",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Python",
"bytes": "5267"
}
],
"symlink_target": ""
} |
package me.androidbox.busbybaking.recipieslist;
import org.junit.Before;
import org.junit.Test;
import org.mockito.Mockito;
import java.util.ArrayList;
import java.util.List;
import me.androidbox.busbybaking.model.Recipe;
import static org.junit.Assert.assertNotNull;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
/**
* Created by smason on 6/14/2017 AD.
*/
public class RecipeListPresenterImpTest {
private RecipeListModelContract recipeListModelContract;
private RecipeListViewContract recipeListViewContract;
private RecipeListPresenterImp recipeListPresenterContract;
@Before
public void setUp() throws Exception {
recipeListModelContract = Mockito.mock(RecipeListModelContract.class);
recipeListViewContract = Mockito.mock(RecipeListViewContract.class);
recipeListPresenterContract = new RecipeListPresenterImp(recipeListModelContract);
recipeListPresenterContract.attachView(recipeListViewContract);
}
@Test(expected = NullPointerException.class)
public void testConstructorIsNotNULL() throws Exception {
new RecipeListPresenterImp(null);
}
@Test
public void testPresenterShouldNotBeNull() {
assertNotNull(recipeListPresenterContract);
}
@Test
public void testShouldRetrieveAllRecipes() throws Exception {
recipeListPresenterContract.retrieveAllRecipes();
verify(recipeListModelContract, times(1))
.getRecipesFromAPI(recipeListPresenterContract);
}
@Test
public void testOnRecipeGetAllSuccess() throws Exception {
List<Recipe> recipeList = new ArrayList<>();
recipeListPresenterContract.onRecipeGetAllSuccess(recipeList);
verify(recipeListViewContract, times(1))
.displayRecipeData(recipeList);
}
@Test
public void testOnRecipeGetAllFailure() throws Exception {
recipeListPresenterContract.onRecipeGetAllFailure(anyString());
verify(recipeListViewContract, times(1))
.displayRecipeError(anyString());
}
}
| {
"content_hash": "d67f78dfd0c9e7f4604db73df8d23609",
"timestamp": "",
"source": "github",
"line_count": 71,
"max_line_length": 90,
"avg_line_length": 30.3943661971831,
"alnum_prop": 0.7455977757182577,
"repo_name": "steve1rm/BusbyBaking",
"id": "6229d35f17a8e3ca1eb27a8d9bcb2ee2b1e18d49",
"size": "2158",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "app/src/test/java/me/androidbox/busbybaking/recipieslist/RecipeListPresenterImpTest.java",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Java",
"bytes": "87855"
}
],
"symlink_target": ""
} |
import inspect
import logging as std_logging
import os
import random
from oslo_config import cfg
from tacker.common import config
from tacker.common import rpc_compat
from tacker import context
from tacker.openstack.common import excutils
from tacker.openstack.common import importutils
from tacker.openstack.common import log as logging
from tacker.openstack.common import loopingcall
from tacker import wsgi
service_opts = [
cfg.IntOpt('periodic_interval',
default=40,
help=_('Seconds between running periodic tasks')),
cfg.IntOpt('api_workers',
default=0,
help=_('Number of separate worker processes for service')),
cfg.IntOpt('periodic_fuzzy_delay',
default=5,
help=_('Range of seconds to randomly delay when starting the '
'periodic task scheduler to reduce stampeding. '
'(Disable by setting to 0)')),
]
CONF = cfg.CONF
CONF.register_opts(service_opts)
LOG = logging.getLogger(__name__)
class WsgiService(object):
"""Base class for WSGI based services.
For each api you define, you must also define these flags:
:<api>_listen: The address on which to listen
:<api>_listen_port: The port on which to listen
"""
def __init__(self, app_name):
self.app_name = app_name
self.wsgi_app = None
def start(self):
self.wsgi_app = _run_wsgi(self.app_name)
def wait(self):
self.wsgi_app.wait()
class TackerApiService(WsgiService):
"""Class for tacker-api service."""
@classmethod
def create(cls, app_name='tacker'):
# Setup logging early, supplying both the CLI options and the
# configuration mapping from the config file
# We only update the conf dict for the verbose and debug
# flags. Everything else must be set up in the conf file...
# Log the options used when starting if we're in debug mode...
config.setup_logging(cfg.CONF)
# Dump the initial option values
cfg.CONF.log_opt_values(LOG, std_logging.DEBUG)
service = cls(app_name)
return service
def serve_wsgi(cls):
try:
service = cls.create()
service.start()
except Exception:
with excutils.save_and_reraise_exception():
LOG.exception(_('Unrecoverable error: please check log '
'for details.'))
return service
def _run_wsgi(app_name):
app = config.load_paste_app(app_name)
if not app:
LOG.error(_('No known API applications configured.'))
return
server = wsgi.Server("Tacker")
server.start(app, cfg.CONF.bind_port, cfg.CONF.bind_host,
workers=cfg.CONF.api_workers)
# Dump all option values here after all options are parsed
cfg.CONF.log_opt_values(LOG, std_logging.DEBUG)
LOG.info(_("Tacker service started, listening on %(host)s:%(port)s"),
{'host': cfg.CONF.bind_host,
'port': cfg.CONF.bind_port})
return server
class Service(rpc_compat.Service):
"""Service object for binaries running on hosts.
A service takes a manager and enables rpc by listening to queues based
on topic. It also periodically runs tasks on the manager.
"""
def __init__(self, host, binary, topic, manager, report_interval=None,
periodic_interval=None, periodic_fuzzy_delay=None,
*args, **kwargs):
self.binary = binary
self.manager_class_name = manager
manager_class = importutils.import_class(self.manager_class_name)
self.manager = manager_class(host=host, *args, **kwargs)
self.report_interval = report_interval
self.periodic_interval = periodic_interval
self.periodic_fuzzy_delay = periodic_fuzzy_delay
self.saved_args, self.saved_kwargs = args, kwargs
self.timers = []
super(Service, self).__init__(host, topic, manager=self.manager)
def start(self):
self.manager.init_host()
super(Service, self).start()
if self.report_interval:
pulse = loopingcall.FixedIntervalLoopingCall(self.report_state)
pulse.start(interval=self.report_interval,
initial_delay=self.report_interval)
self.timers.append(pulse)
if self.periodic_interval:
if self.periodic_fuzzy_delay:
initial_delay = random.randint(0, self.periodic_fuzzy_delay)
else:
initial_delay = None
periodic = loopingcall.FixedIntervalLoopingCall(
self.periodic_tasks)
periodic.start(interval=self.periodic_interval,
initial_delay=initial_delay)
self.timers.append(periodic)
self.manager.after_start()
def __getattr__(self, key):
manager = self.__dict__.get('manager', None)
return getattr(manager, key)
@classmethod
def create(cls, host=None, binary=None, topic=None, manager=None,
report_interval=None, periodic_interval=None,
periodic_fuzzy_delay=None):
"""Instantiates class and passes back application object.
:param host: defaults to CONF.host
:param binary: defaults to basename of executable
:param topic: defaults to bin_name - 'nova-' part
:param manager: defaults to CONF.<topic>_manager
:param report_interval: defaults to CONF.report_interval
:param periodic_interval: defaults to CONF.periodic_interval
:param periodic_fuzzy_delay: defaults to CONF.periodic_fuzzy_delay
"""
if not host:
host = CONF.host
if not binary:
binary = os.path.basename(inspect.stack()[-1][1])
if not topic:
topic = binary.rpartition('tacker-')[2]
topic = topic.replace("-", "_")
if not manager:
manager = CONF.get('%s_manager' % topic, None)
if report_interval is None:
report_interval = CONF.report_interval
if periodic_interval is None:
periodic_interval = CONF.periodic_interval
if periodic_fuzzy_delay is None:
periodic_fuzzy_delay = CONF.periodic_fuzzy_delay
service_obj = cls(host, binary, topic, manager,
report_interval=report_interval,
periodic_interval=periodic_interval,
periodic_fuzzy_delay=periodic_fuzzy_delay)
return service_obj
def kill(self):
"""Destroy the service object."""
self.stop()
def stop(self):
super(Service, self).stop()
for x in self.timers:
try:
x.stop()
except Exception:
LOG.exception(_("Exception occurs when timer stops"))
pass
self.timers = []
def wait(self):
super(Service, self).wait()
for x in self.timers:
try:
x.wait()
except Exception:
LOG.exception(_("Exception occurs when waiting for timer"))
pass
def periodic_tasks(self, raise_on_error=False):
"""Tasks to be run at a periodic interval."""
ctxt = context.get_admin_context()
self.manager.periodic_tasks(ctxt, raise_on_error=raise_on_error)
def report_state(self):
"""Update the state of this service."""
# Todo(gongysh) report state to tacker server
pass
| {
"content_hash": "2f7f121f8ec11dc406b46c48db7c325b",
"timestamp": "",
"source": "github",
"line_count": 221,
"max_line_length": 77,
"avg_line_length": 34.1447963800905,
"alnum_prop": 0.6102570898489266,
"repo_name": "SripriyaSeetharam/tacker",
"id": "0981f8f205a69e575154c137e3ffd5dda5a3e1d1",
"size": "8173",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "tacker/service.py",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Mako",
"bytes": "1142"
},
{
"name": "Python",
"bytes": "1204880"
},
{
"name": "Shell",
"bytes": "24370"
}
],
"symlink_target": ""
} |
#include "bistro/bistro/server/HTTPMonitor.h"
#include <boost/algorithm/string/predicate.hpp>
#include <glog/logging.h>
#include <zlib.h>
#include "bistro/bistro/config/Config.h"
#include "bistro/bistro/config/ConfigLoader.h"
#include "bistro/bistro/config/Job.h"
#include "bistro/bistro/config/Node.h"
#include "bistro/bistro/monitor/Monitor.h"
#include "bistro/bistro/nodes/Nodes.h"
#include "bistro/bistro/nodes/NodesLoader.h"
#include "bistro/bistro/runners/TaskRunner.h"
#include "bistro/bistro/statuses/TaskStatus.h"
#include "bistro/bistro/statuses/TaskStatuses.h"
#include "bistro/bistro/utils/Exception.h"
#include <folly/experimental/AutoTimer.h>
#include <folly/json.h>
DEFINE_int32(http_server_port, 8080, "Port to run HTTP server on");
DEFINE_string(http_server_address, "::", "Address to bind to");
namespace facebook { namespace bistro {
using namespace folly;
using namespace std;
HTTPMonitor::HTTPMonitor(
shared_ptr<ConfigLoader> config_loader,
shared_ptr<NodesLoader> nodes_loader,
shared_ptr<TaskStatuses> task_statuses,
shared_ptr<TaskRunner> task_runner,
shared_ptr<Monitor> monitor)
: configLoader_(config_loader),
nodesLoader_(nodes_loader),
taskStatuses_(task_statuses),
taskRunner_(task_runner),
monitor_(monitor),
server_(
FLAGS_http_server_port,
FLAGS_http_server_address,
bind(&HTTPMonitor::handleRequest, this, placeholders::_1)
),
serverThread_([this](){ server_.run(); }) {
LOG(INFO) << "Launched HTTP Monitor on port " << FLAGS_http_server_port;
}
string HTTPMonitor::handleRequest(const string& request) {
LOG(INFO) << "HTTPMonitor request: " << request;
folly::AutoTimer<> timer("Handled HTTP monitor request");
dynamic ret = dynamic::object;
bool zlib_compress = false;
try {
dynamic d(parseJson(request));
if (const auto* prefs = d.get_ptr("prefs")) {
if (auto* zlib = prefs->get_ptr("zlib_compress")) {
zlib_compress = zlib->asBool();
}
d.erase("prefs"); // Don't interpret this key as a handler.
}
// This can throw, so parse out 'zlib_compress' first
std::shared_ptr<const Config> c = configLoader_->getDataOrThrow();
for (const auto& pair : d.items()) {
try {
ret[pair.first] =
dynamic::object("data", handleSingle(*c, pair.second));
} catch (const std::exception& e) {
ret[pair.first] = dynamic::object("error", e.what());
}
}
} catch (const std::exception& e) {
LOG(ERROR) << "Error handling monitor request: " << e.what();
ret = e.what(); // zlib_compress would be ignored with "return"
}
auto json(folly::toJson(ret));
if (zlib_compress) {
string output;
// Output buffer must be 0.1% large + 12 bytes?
output.resize(json.size() + (json.size() / 1000) + 12);
uLongf resultLen = output.size();
int res = compress(
(Bytef*)&output[0],
&resultLen,
(const Bytef*)json.data(),
json.size()
);
if (res != Z_OK) {
LOG(ERROR) << "Error when compressing: " << res;
return "Unable to gzcompress data";
}
return output;
} else {
return json.toStdString();
}
}
namespace {
/**
* Validates the requested jobs against the current jobs. If no jobs are
* requested, returns all jobs.
*
* handleSingle() cannot call this eagerly, because the "task_logs" handler
* requires different semantics for the "jobs" field, which would throw here.
*/
vector<const Job*> getRequestedJobs(const Config& c, const dynamic& d) {
vector<const Job*> jobs;
if (auto* p = d.get_ptr("jobs")) {
for (const auto& j : *p) {
auto it = c.jobs.find(j.asString().toStdString());
if (it == c.jobs.end()) {
throw BistroException("Unknown job: ", j.asString());
}
jobs.emplace_back(it->second.get());
}
} else {
for (const auto& pair : c.jobs) {
jobs.emplace_back(pair.second.get());
}
}
return jobs;
}
}
dynamic HTTPMonitor::handleSingle(const Config& c, const dynamic& d) {
const auto& handler = d["handler"].asString();
if (handler == "errors") {
auto errors = monitor_->copyErrors();
dynamic d = dynamic::object;
for (const auto& key_and_error : errors) {
d[key_and_error.first] = key_and_error.second;
}
return d;
}
if (handler == "refresh_time") {
return dynamic(monitor_->getLastUpdateTime());
}
if (handler == "jobs") {
return handleJobs(c, getRequestedJobs(c, d));
}
if (handler == "sorted_node_names") {
return handleNodes(c);
}
// TODO: deprecate this in favor of running_tasks
if (handler == "job_node_runtime") {
return handleTaskRuntime(d);
}
if (handler == "running_tasks") {
return handleRunningTasks(d);
}
if (handler == "histogram") {
return handleHistograms(
c,
getRequestedJobs(c, d),
d.getDefault("num_samples", 0).asInt()
);
}
if (handler == "task_logs") {
return handleTaskLogs(c, d);
}
if (handler == "delete_job") {
configLoader_->deleteJob(d["job_id"].asString().toStdString());
return "deleted";
}
if (handler == "save_job") {
configLoader_->saveJob(d["job_id"].asString().toStdString(), d["job"]);
return "saved";
}
if (handler == "forgive_jobs") {
if (auto* p = d.get_ptr("jobs")) {
for (const auto& j : *p) {
taskStatuses_->forgiveJob(j.asString().toStdString());
}
}
return "forgiven";
}
if (handler == "kill_task") {
auto status_filter_str = d.getDefault(
"status_filter", "force_done_or_failed"
).asString().toStdString();
cpp2::KilledTaskStatusFilter status_filter;
if (status_filter_str == "force_done_or_failed") {
status_filter = cpp2::KilledTaskStatusFilter::FORCE_DONE_OR_FAILED;
} else if (status_filter_str == "force_done_or_incomplete_backoff") {
status_filter =
cpp2::KilledTaskStatusFilter::FORCE_DONE_OR_INCOMPLETE_BACKOFF;
} else if (status_filter_str == "force_done_or_incomplete") {
status_filter = cpp2::KilledTaskStatusFilter::FORCE_DONE_OR_INCOMPLETE;
} else if (status_filter_str == "none") {
status_filter = cpp2::KilledTaskStatusFilter::NONE;
} else {
throw BistroException("Unknown status_filter: ", status_filter_str);
}
// Throws on failure
taskRunner_->killTask(
d["job_id"].asString().toStdString(),
d["node_id"].asString().toStdString(),
status_filter
);
return "killed";
}
throw BistroException("Unknown handler: ", handler);
}
/**
* Input: {
* "jobs": ["array", "of", "job", "ids"], // all jobs if empty or missing
* "nodes": ["array", "of", "job", "ids"], // all nodes if empty or missing
* "sort": "asc" or "desc", // order in which to iterate through log lines
* "time": <secs since 1970 GMT; int>, // start iteration at this time
* "line_id": <opaque string, from next_line_id> // used to page thru lines
* }
*
* Output: {
* "next_line_id": <pass as line_id to your next call to get the next page>,
* "lines": [["job_id", "node_id", <time>, "content", "line_id"], ...]
* }
*
* Returns sequential log lines ordered by line ID. This ID is an opaque
* primary key for log lines. Its first ordering component is guaranteed to
* be the timestamp. Lines are filtered to match the specified "jobs" and
* "nodes". Unlike other handlers, jobs or nodes don't have to be current.
*
* You can request lines starting from a timestamp, or from a line ID
* (specifying both is an error). With ascending sort order, the time/line
* ID you specify will be the minimal one to show up in your results --
* otherwise, it'll be the maximal.
*
* The number of results you get is implementation-dependent, but you are
* guaranteed to get *some* lines as long as lines are available in your
* chosen direction. The absence of results signals that you can stop
* paging.
*
* To get the next page of results, invoke this handler again with "line_id"
* set to the "next_line_id" from your previous output. There are no more
* pages if "next_line_id" is -1. To get the previous page, keep line page
* ID (or time) the same, and toggle "sort".
*/
dynamic HTTPMonitor::handleTaskLogs(const Config& c, const dynamic& d) {
if (d.get_ptr("columns")) {
throw BistroException("Custom columns are currently not supported.");
}
vector<string> job_ids;
if (auto dyn_job_ids = d.get_ptr("jobs")) {
job_ids = folly::convertTo<vector<string>>(*dyn_job_ids);
}
vector<string> node_ids;
if (auto dyn_node_ids = d.get_ptr("nodes")) {
node_ids = folly::convertTo<vector<string>>(*dyn_node_ids);
}
bool is_ascending;
auto asc_or_desc = d.getDefault("sort", "desc").asString();
if (boost::iequals(asc_or_desc, "asc")) { // ignore case, like SQL
is_ascending = true;
} else if (boost::iequals(asc_or_desc, "desc")) {
is_ascending = false;
} else {
throw BistroException("Unknown sort order: ", asc_or_desc);
}
int64_t line_id = LogLine::kNotALineID;
if (const auto* dyn_time = d.get_ptr("time")) {
line_id = LogLine::lineIDFromTime(dyn_time->asInt(), is_ascending);
}
if (const auto* dyn_line_id = d.get_ptr("line_id")) {
if (line_id != LogLine::kNotALineID) {
throw BistroException("Cannot specify both time and line_id");
}
line_id = folly::to<int64_t>(dyn_line_id->asString()); // JS has no int64
}
auto log = taskRunner_->getJobLogs(
d["log_type"].asString().toStdString(),
job_ids,
node_ids,
line_id,
is_ascending,
// Server-side regex filtering of retrieved lines -- may cause 0 lines
// to be returned, but nextLineID will still be correct.
d.getDefault("regex_filter", "").asString().toStdString()
);
// Compose the output JSON
dynamic lines = {};
for (const LogLine& l : log.lines) {
lines.push_back({ // No emplace for dynamic???
l.jobID,
l.nodeID,
l.time,
l.line,
folly::to<string>(l.lineID) // JS has no int64
});
}
dynamic res = dynamic::object
("next_line_id", folly::to<string>(log.nextLineID)) // JS has no int64
("lines", lines);
return res;
}
dynamic HTTPMonitor::handleJobs(
const Config& c,
const vector<const Job*>& jobs) {
dynamic ret = dynamic::object;
for (const auto* job : jobs) {
ret[job->name()] = job->toDynamic(c);
}
return ret;
}
dynamic HTTPMonitor::handleNodes(const Config& c) {
// Returns a dict of level => list of node names
dynamic ret = dynamic::object;
auto nodes = nodesLoader_->getDataOrThrow();
for (const auto& n : *nodes) {
const auto& level = c.levels.lookup(n->level());
ret.setDefault(level, dynamic({})).push_back(n->name());
}
return ret;
}
namespace {
unordered_set<string> getJobNameSet(const dynamic& d) {
unordered_set<string> job_names;
if (auto* p = d.get_ptr("jobs")) {
for (const auto& j : *p) {
job_names.emplace(j.asString().toStdString());
}
}
return job_names;
}
} // anonymous namespace
dynamic HTTPMonitor::handleTaskRuntime(const dynamic& d) {
const auto& job_names = getJobNameSet(d);
// Returns a dict of job => node => runtime
dynamic ret = dynamic::object;
auto now = time(nullptr);
auto running_tasks = taskStatuses_->copyRunningTasks();
for (const auto& pair : running_tasks) {
const cpp2::RunningTask& rt = pair.second;
if (job_names.empty() || job_names.count(rt.job)) {
ret.setDefault(rt.job)[rt.node] = now - rt.invocationID.startTime;
}
}
return ret;
}
dynamic HTTPMonitor::handleRunningTasks(const dynamic& d) {
const auto& job_names = getJobNameSet(d);
// Returns a dict of job => node => {
// "start_time": since epoch, "worker_shard": "string"
// }
dynamic ret = dynamic::object;
auto running_tasks = taskStatuses_->copyRunningTasks();
for (const auto& pair : running_tasks) {
const cpp2::RunningTask& rt = pair.second;
if (job_names.empty() || job_names.count(rt.job)) {
ret.setDefault(rt.job)[rt.node] = dynamic::object()
("start_time", rt.invocationID.startTime)
("worker_shard", rt.workerShard);
}
}
return ret;
}
dynamic HTTPMonitor::handleHistograms(
const Config& c,
const vector<const Job*>& jobs,
int num_samples) {
const char* encoding =
"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_";
auto hists = monitor_->getHistograms(jobs);
dynamic ret = dynamic::object;
dynamic samples = dynamic::object;
for (const auto job : jobs) {
auto it = hists.find(job->id());
if (it == hists.end()) {
continue;
}
ret[job->name()] = dynamic::object;
samples[job->name()] = dynamic::object;
for (const auto& pair : it->second) {
auto& by_level = ret[job->name()].setDefault(pair.first);
auto& samples_by_level = samples[job->name()].setDefault(pair.first);
for (const auto& values : pair.second) {
const int bits = static_cast<int>(values.first);
std::string encoded;
encoded.append(1, encoding[bits & 63]);
if (bits >> 6) {
encoded.append(1, encoding[bits >> 6]);
}
by_level[encoded] = values.second.first;
if (num_samples) {
const auto& all_samples = values.second.second;
samples_by_level[encoded] = dynamic(
all_samples.begin(),
all_samples.size() <= num_samples
? all_samples.end()
: all_samples.begin() + num_samples
);
}
}
}
}
ret = dynamic::object("histograms", ret);
if (num_samples) {
ret["samples"] = samples;
}
return ret;
}
void HTTPMonitor::wait() {
serverThread_.join();
}
}}
| {
"content_hash": "8cae57a4f09e2fe6cc61ae07990ccac4",
"timestamp": "",
"source": "github",
"line_count": 427,
"max_line_length": 78,
"avg_line_length": 32.12646370023419,
"alnum_prop": 0.6341303396996647,
"repo_name": "linearregression/bistro",
"id": "f4b17d376c4ebb9a538f107b10bf41767e1018b8",
"size": "14025",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "bistro/server/HTTPMonitor.cpp",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "C",
"bytes": "515"
},
{
"name": "C++",
"bytes": "745411"
},
{
"name": "CMake",
"bytes": "9105"
},
{
"name": "Shell",
"bytes": "7632"
},
{
"name": "Thrift",
"bytes": "36459"
}
],
"symlink_target": ""
} |
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using AutoFixture;
namespace Provider
{
/// <summary>
/// Stock event generator
/// </summary>
public class StockEventGenerator : IStockEventGenerator
{
private readonly IStockEventSender sender;
/// <summary>
/// Initialises a new instance of the <see cref="StockEventSender"/> class.
/// </summary>
/// <param name="sender">Stock event sender</param>
public StockEventGenerator(IStockEventSender sender)
{
this.sender = sender;
}
/// <summary>
/// Generate new stock events
/// </summary>
/// <returns>Awaitable</returns>
public async ValueTask GenerateEventsAsync()
{
// source some new data from somewhere - e.g. an external system or database
// and publish them
ICollection<StockEvent> events = new Fixture().CreateMany<StockEvent>().ToArray();
await this.sender.SendAsync(events);
}
}
}
| {
"content_hash": "e2aa35c88fabb9e0f553c8c6d6ef6c33",
"timestamp": "",
"source": "github",
"line_count": 38,
"max_line_length": 94,
"avg_line_length": 28.57894736842105,
"alnum_prop": 0.6049723756906077,
"repo_name": "SEEK-Jobs/pact-net",
"id": "53aec33ceca64c3ba1dfc22221c49f2071b09dff",
"size": "1086",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "samples/Messaging/Provider/StockEventGenerator.cs",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C#",
"bytes": "200382"
},
{
"name": "PowerShell",
"bytes": "9516"
},
{
"name": "Ruby",
"bytes": "37"
},
{
"name": "Shell",
"bytes": "891"
}
],
"symlink_target": ""
} |
define(["require", "exports"], function (require, exports) {
var PasswordResetController = (function () {
function PasswordResetController(loginService, $location, $routeParams) {
this.loginService = loginService;
this.$location = $location;
this.$routeParams = $routeParams;
if ($routeParams['token']) {
this.token = $routeParams['token'];
}
}
PasswordResetController.prototype.reset = function () {
var _this = this;
this.loginService.reset(this.email).subscribe(function () {
_this.email = null;
_this.showProceed = true;
});
};
PasswordResetController.prototype.confirm = function () {
var _this = this;
this.loginService.confirmPasswordReset(this.token, this.password).subscribe(function () {
_this.$location.url("/login?passwordreset");
});
};
PasswordResetController.$inject = ['LoginService', '$location', '$routeParams'];
return PasswordResetController;
})();
return PasswordResetController;
});
| {
"content_hash": "109411136f9c077fd10449834137a683",
"timestamp": "",
"source": "github",
"line_count": 28,
"max_line_length": 101,
"avg_line_length": 42.035714285714285,
"alnum_prop": 0.5717926932880204,
"repo_name": "amdatu/amdatu-auth-angular",
"id": "a912b90e501f1597b90743f6a07650f7754fa472",
"size": "1237",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "login/PasswordResetController.js",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "HTML",
"bytes": "7495"
},
{
"name": "JavaScript",
"bytes": "19831"
},
{
"name": "TypeScript",
"bytes": "18842"
}
],
"symlink_target": ""
} |
<!DOCTYPE html>
<html xmlns:msxsl="urn:schemas-microsoft-com:xslt">
<head>
<meta content="en-us" http-equiv="Content-Language" />
<meta content="text/html; charset=utf-16" http-equiv="Content-Type" />
<title _locid="PortabilityAnalysis0">.NET Portability Report</title>
<style>
/* Body style, for the entire document */
body {
background: #F3F3F4;
color: #1E1E1F;
font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif;
padding: 0;
margin: 0;
}
/* Header1 style, used for the main title */
h1 {
padding: 10px 0px 10px 10px;
font-size: 21pt;
background-color: #E2E2E2;
border-bottom: 1px #C1C1C2 solid;
color: #201F20;
margin: 0;
font-weight: normal;
}
/* Header2 style, used for "Overview" and other sections */
h2 {
font-size: 18pt;
font-weight: normal;
padding: 15px 0 5px 0;
margin: 0;
}
/* Header3 style, used for sub-sections, such as project name */
h3 {
font-weight: normal;
font-size: 15pt;
margin: 0;
padding: 15px 0 5px 0;
background-color: transparent;
}
h4 {
font-weight: normal;
font-size: 12pt;
margin: 0;
padding: 0 0 0 0;
background-color: transparent;
}
/* Color all hyperlinks one color */
a {
color: #1382CE;
}
/* Paragraph text (for longer informational messages) */
p {
font-size: 10pt;
}
/* Table styles */
table {
border-spacing: 0 0;
border-collapse: collapse;
font-size: 10pt;
}
table th {
background: #E7E7E8;
text-align: left;
text-decoration: none;
font-weight: normal;
padding: 3px 6px 3px 6px;
}
table td {
vertical-align: top;
padding: 3px 6px 5px 5px;
margin: 0px;
border: 1px solid #E7E7E8;
background: #F7F7F8;
}
.NoBreakingChanges {
color: darkgreen;
font-weight:bold;
}
.FewBreakingChanges {
color: orange;
font-weight:bold;
}
.ManyBreakingChanges {
color: red;
font-weight:bold;
}
.BreakDetails {
margin-left: 30px;
}
.CompatMessage {
font-style: italic;
font-size: 10pt;
}
.GoodMessage {
color: darkgreen;
}
/* Local link is a style for hyperlinks that link to file:/// content, there are lots so color them as 'normal' text until the user mouse overs */
.localLink {
color: #1E1E1F;
background: #EEEEED;
text-decoration: none;
}
.localLink:hover {
color: #1382CE;
background: #FFFF99;
text-decoration: none;
}
/* Center text, used in the over views cells that contain message level counts */
.textCentered {
text-align: center;
}
/* The message cells in message tables should take up all avaliable space */
.messageCell {
width: 100%;
}
/* Padding around the content after the h1 */
#content {
padding: 0px 12px 12px 12px;
}
/* The overview table expands to width, with a max width of 97% */
#overview table {
width: auto;
max-width: 75%;
}
/* The messages tables are always 97% width */
#messages table {
width: 97%;
}
/* All Icons */
.IconSuccessEncoded, .IconInfoEncoded, .IconWarningEncoded, .IconErrorEncoded {
min-width: 18px;
min-height: 18px;
background-repeat: no-repeat;
background-position: center;
}
/* Success icon encoded */
.IconSuccessEncoded {
/* Note: Do not delete the comment below. It is used to verify the correctness of the encoded image resource below before the product is released */
/* [---XsltValidateInternal-Base64EncodedImage:IconSuccess#Begin#background-image: url(data:image/png;base64,#Separator#);#End#] */
background-image: url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAABPElEQVR4Xp1Tv0vDUBi8FqeA4NpBcBLcWnQSApncOnTo4FSnjP0DsnXpH5CxiwbHDg4Zuj4oOEXiJgiC4FDcCkLWmIMc1Pfw+eMgQ77v3Xf3Pe51YKGqqisAEwCR1TIAsiAIblSo6xrdHeJR85Xle3mdmCQKb0PsfqyxxzM8K15HZADl/H5+sHpZwYfxyRjTs+kWwKBx8yoHd2mRiuzF8mkJniWH/13u3Fjrs/EdhsdDFHGB/DLXEJBDLh1MWPAhPo1BLB4WX5yQywHR+m3tVe/t97D52CB/ziG0nIgD/qDuYg8WuCcVZ2YGwlJ3YDugkpR/VNcAEx6GEKhERSr71FuO4YCM4XBdwKvecjIlkSnsO0Hyp/GxSeJAdzBKzpOtnPwyyiPdAZhpZptT04tU+zk7s8czeges//s5C5+CwqrR4/gw+AAAAABJRU5ErkJggg==);
}
/* Information icon encoded */
.IconInfoEncoded {
/* Note: Do not delete the comment below. It is used to verify the correctness of the encoded image resource below before the product is released */
/* [---XsltValidateInternal-Base64EncodedImage:IconInformation#Begin#background-image: url(data:image/png;base64,#Separator#);#End#] */
background-image: url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAABHElEQVR4Xs2TsUoDQRRF7wwoziokjZUKadInhdhukR9YP8DMX1hYW+QvdsXa/QHBbcXC7W0CamWTQnclFutceIQJwwaWNLlwm5k5d94M76mmaeCrrmsLYOocY12FcxZFUeozCqKqqgYA8uevv1H6VuPxcwlfk5N92KHBxfFeCSAxxswlYAW/Xr989x/mv9gkhtyMDhcAxgzRsp7flj8B/HF1RsMXq+NZMkopaHe7lbKxQUEIGbKsYNoGn969060hZBkQex/W8oRQwsQaW2o3Ago2SVcJUzAgY3N0lTCZZm+zPS8HB51gMmS1DEYyOz9acKO1D8JWTlafKIMxdhvlfdyT94Vv5h7P8Ky7nQzACmhvKq3zk3PjW9asz9D/1oigecsioooAAAAASUVORK5CYII=);
}
/* Warning icon encoded */
.IconWarningEncoded {
/* Note: Do not delete the comment below. It is used to verify the correctness of the encoded image resource below before the product is released */
/* [---XsltValidateInternal-Base64EncodedImage:IconWarning#Begin#background-image: url(data:image/png;base64,#Separator#);#End#] */
background-image: url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAAACXBIWXMAAA7EAAAOxAGVKw4bAAAAx0lEQVR4XpWSMQ7CMAxFf4xAyBMLCxMrO8dhaBcuwdCJS3RJBw7SA/QGTCxdWJgiQYWKXJWKIXHIlyw5lqr34tQgEOdcBsCOx5yZK3hCCKdYXneQkh4pEfqzLfu+wVDSyyzFoJjfz9NB+pAF+eizx2Vruts0k15mPgvS6GYvpVtQhB61IB/dk6AF6fS4Ben0uIX5odtFe8Q/eW1KvFeH4e8khT6+gm5B+t3juyDt7n0jpe+CANTd+oTUjN/U3yVaABnSUjFz/gFq44JaVSCXeQAAAABJRU5ErkJggg==);
}
/* Error icon encoded */
.IconErrorEncoded {
/* Note: Do not delete the comment below. It is used to verify the correctness of the encoded image resource below before the product is released */
/* [---XsltValidateInternal-Base64EncodedImage:IconError#Begin#background-image: url(data:image/png;base64,#Separator#);#End#] */
background-image: url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAABQElEQVR4XqWTvUoEQRCE6wYPZUA80AfwAQz23uCMjA7MDRQEIzPBVEyNTQUFIw00vcQTTMzuAh/AxEQQT8HF/3G/oGGnEUGuoNnd6qoZuqltyKEsyzVJq5I6rnUp6SjGeGhESikzzlc1eL7opfuVbrqbU1Zw9NCgtQMaZpY0eNnaaL2fHusvTK5vKu7sjSS1Y4y3QUA6K3e3Mau5UFDyMP7tYF9o8cAHZv68vipoIJg971PZIZ5HiwdvYGGvFVFHmGmZ2MxwmQYPXubPl9Up0tfoMQGetXd6mRbvhBw+boZ6WF7Mbv1+GsHRk0fQmPAH1GfmZirbCfDJ61tw3Px8/8pZsPAG4jlVhcPgZ7adwNWBB68lkRQWFiTgFlbnLY3DGGM7izIJIyT/jjIvEJw6fdJTc6krDzh6aMwMP9bvDH4ADSsa9uSWVJkAAAAASUVORK5CYII=);
}
</style>
</head>
<body>
<h1 _locid="PortabilityReport">.NET Portability Report</h1>
<div id="content">
<div id="submissionId" style="font-size:8pt;">
<p>
<i>
Submission Id
dc343439-5508-4ef1-9053-95963239c02d
</i>
</p>
</div>
<h2 _locid="SummaryTitle">
<a name="Portability Summary"></a>Portability Summary
</h2>
<div id="summary">
<table>
<tbody>
<tr>
<th>Assembly</th>
<th>ASP.NET 5,Version=v1.0</th>
<th>Windows,Version=v8.1</th>
<th>.NET Framework,Version=v4.6</th>
<th>Windows Phone,Version=v8.1</th>
</tr>
<tr>
<td><strong><a href="#Rhino.ServiceBus.Castle">Rhino.ServiceBus.Castle</a></strong></td>
<td class="text-center">97.88 %</td>
<td class="text-center">97.53 %</td>
<td class="text-center">100.00 %</td>
<td class="text-center">97.53 %</td>
</tr>
</tbody>
</table>
</div>
<div id="details">
<a name="Rhino.ServiceBus.Castle"><h3>Rhino.ServiceBus.Castle</h3></a>
<table>
<tbody>
<tr>
<th>Target type</th>
<th>ASP.NET 5,Version=v1.0</th>
<th>Windows,Version=v8.1</th>
<th>.NET Framework,Version=v4.6</th>
<th>Windows Phone,Version=v8.1</th>
<th>Recommended changes</th>
</tr>
<tr>
<td>System.Converter`2</td>
<td class="IconErrorEncoded"></td>
<td class="IconErrorEncoded"></td>
<td class="IconSuccessEncoded"></td>
<td class="IconErrorEncoded"></td>
<td>Remove usage. Implement conversion code yourself if needed.</td>
</tr>
<tr>
<td style="padding-left:2em">#ctor(System.Object,System.IntPtr)</td>
<td class="IconErrorEncoded"></td>
<td class="IconErrorEncoded"></td>
<td class="IconSuccessEncoded"></td>
<td class="IconErrorEncoded"></td>
<td>Remove usage. Implement conversion code yourself if needed.</td>
</tr>
<tr>
<td> </td>
<td> </td>
<td> </td>
<td> </td>
<td> </td>
<td> </td>
</tr>
<tr>
<td>System.Runtime.Remoting.RemotingServices</td>
<td class="IconErrorEncoded"></td>
<td class="IconErrorEncoded"></td>
<td class="IconSuccessEncoded"></td>
<td class="IconErrorEncoded"></td>
<td></td>
</tr>
<tr>
<td style="padding-left:2em">IsTransparentProxy(System.Object)</td>
<td class="IconErrorEncoded"></td>
<td class="IconErrorEncoded"></td>
<td class="IconSuccessEncoded"></td>
<td class="IconErrorEncoded"></td>
<td></td>
</tr>
<tr>
<td> </td>
<td> </td>
<td> </td>
<td> </td>
<td> </td>
<td> </td>
</tr>
<tr>
<td>System.Type</td>
<td class="IconSuccessEncoded"></td>
<td class="IconErrorEncoded"></td>
<td class="IconSuccessEncoded"></td>
<td class="IconErrorEncoded"></td>
<td></td>
</tr>
<tr>
<td style="padding-left:2em">get_Assembly</td>
<td class="IconErrorEncoded"></td>
<td class="IconErrorEncoded"></td>
<td class="IconSuccessEncoded"></td>
<td class="IconErrorEncoded"></td>
<td>.GetTypeInfo().Assembly</td>
</tr>
<tr>
<td style="padding-left:2em">get_BaseType</td>
<td class="IconErrorEncoded"></td>
<td class="IconErrorEncoded"></td>
<td class="IconSuccessEncoded"></td>
<td class="IconErrorEncoded"></td>
<td>.GetTypeInfo().BaseType</td>
</tr>
<tr>
<td style="padding-left:2em">IsAssignableFrom(System.Type)</td>
<td class="IconSuccessEncoded"></td>
<td class="IconErrorEncoded"></td>
<td class="IconSuccessEncoded"></td>
<td class="IconErrorEncoded"></td>
<td></td>
</tr>
<tr>
<td> </td>
<td> </td>
<td> </td>
<td> </td>
<td> </td>
<td> </td>
</tr>
</tbody>
</table>
<p>
<a href="#Portability Summary">Back to Summary</a>
</p>
</div>
</div>
</body>
</html> | {
"content_hash": "1960b5334a73c20a0b853ec59639801e",
"timestamp": "",
"source": "github",
"line_count": 361,
"max_line_length": 562,
"avg_line_length": 42.02216066481994,
"alnum_prop": 0.4786420566908372,
"repo_name": "kuhlenh/port-to-core",
"id": "42ab3fc7c389a200d8db160021c19083a96cc9d4",
"size": "15170",
"binary": false,
"copies": "1",
"ref": "refs/heads/gh-pages",
"path": "Reports/rh/rhino.servicebus.castle.3.1.1/Rhino.ServiceBus.Castle-3.5.html",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "HTML",
"bytes": "2323514650"
}
],
"symlink_target": ""
} |
using System.Collections.Generic;
namespace ZocMonLib.Web
{
public interface IResourceContext
{
IDictionary<string, string> Parameters { get; }
}
} | {
"content_hash": "8ef49e18bf3e46d2abac31c7238f6e78",
"timestamp": "",
"source": "github",
"line_count": 9,
"max_line_length": 55,
"avg_line_length": 18.666666666666668,
"alnum_prop": 0.6964285714285714,
"repo_name": "modulexcite/ZocMon",
"id": "847d312124ed769a9edec3a3da87693b46efdbdc",
"size": "168",
"binary": false,
"copies": "2",
"ref": "refs/heads/develop",
"path": "source/ZocMonLib.Web/Framework/IResourceContext.cs",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "ASP",
"bytes": "574"
},
{
"name": "Batchfile",
"bytes": "256"
},
{
"name": "C#",
"bytes": "654104"
},
{
"name": "CSS",
"bytes": "61035"
},
{
"name": "HTML",
"bytes": "5233"
},
{
"name": "JavaScript",
"bytes": "843126"
},
{
"name": "PowerShell",
"bytes": "5672"
},
{
"name": "XSLT",
"bytes": "10348"
}
],
"symlink_target": ""
} |
ansible wordpress role
| {
"content_hash": "f3694f7fa8ff5b59ab2687f74f8c66f8",
"timestamp": "",
"source": "github",
"line_count": 1,
"max_line_length": 22,
"avg_line_length": 23,
"alnum_prop": 0.8695652173913043,
"repo_name": "tetuyoko/wordpress_role",
"id": "7abd16b27aab9fbb5768ff0ffbdb721a8627126e",
"size": "40",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "README.md",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "PHP",
"bytes": "2946"
}
],
"symlink_target": ""
} |
/*
* linux/kernel/floppy.c
*
* (C) 1991 Linus Torvalds
*/
/*
* 02.12.91 - Changed to static variables to indicate need for reset
* and recalibrate. This makes some things easier (output_byte reset
* checking etc), and means less interrupt jumping in case of errors,
* so the code is hopefully easier to understand.
*/
/*
* This file is certainly a mess. I've tried my best to get it working,
* but I don't like programming floppies, and I have only one anyway.
* Urgel. I should check for more errors, and do more graceful error
* recovery. Seems there are problems with several drives. I've tried to
* correct them. No promises.
*/
/*
* As with hd.c, all routines within this file can (and will) be called
* by interrupts, so extreme caution is needed. A hardware interrupt
* handler may not sleep, or a kernel panic will happen. Thus I cannot
* call "floppy-on" directly, but have to set a special timer interrupt
* etc.
*
* Also, I'm not certain this works on more than 1 floppy. Bugs may
* abund.
*/
#include <linux/sched.h>
#include <linux/fs.h>
#include <linux/kernel.h>
#include <linux/fdreg.h>
#include <asm/system.h>
#include <asm/io.h>
#include <asm/segment.h>
#define MAJOR_NR 2
#include "blk.h"
static int recalibrate = 0;
static int reset = 0;
static int seek = 0;
extern unsigned char current_DOR;
#define immoutb_p(val,port) \
__asm__("outb %0,%1\n\tjmp 1f\n1:\tjmp 1f\n1:"::"a" ((char) (val)),"i" (port))
#define TYPE(x) ((x)>>2)
#define DRIVE(x) ((x)&0x03)
/*
* Note that MAX_ERRORS=8 doesn't imply that we retry every bad read
* max 8 times - some types of errors increase the errorcount by 2,
* so we might actually retry only 5-6 times before giving up.
*/
#define MAX_ERRORS 8
/*
* globals used by 'result()'
*/
#define MAX_REPLIES 7
static unsigned char reply_buffer[MAX_REPLIES];
#define ST0 (reply_buffer[0])
#define ST1 (reply_buffer[1])
#define ST2 (reply_buffer[2])
#define ST3 (reply_buffer[3])
/*
* This struct defines the different floppy types. Unlike minix
* linux doesn't have a "search for right type"-type, as the code
* for that is convoluted and weird. I've got enough problems with
* this driver as it is.
*
* The 'stretch' tells if the tracks need to be boubled for some
* types (ie 360kB diskette in 1.2MB drive etc). Others should
* be self-explanatory.
*/
static struct floppy_struct {
unsigned int size, sect, head, track, stretch;
unsigned char gap,rate,spec1;
} floppy_type[] = {
{ 0, 0,0, 0,0,0x00,0x00,0x00 }, /* no testing */
{ 720, 9,2,40,0,0x2A,0x02,0xDF }, /* 360kB PC diskettes */
{ 2400,15,2,80,0,0x1B,0x00,0xDF }, /* 1.2 MB AT-diskettes */
{ 720, 9,2,40,1,0x2A,0x02,0xDF }, /* 360kB in 720kB drive */
{ 1440, 9,2,80,0,0x2A,0x02,0xDF }, /* 3.5" 720kB diskette */
{ 720, 9,2,40,1,0x23,0x01,0xDF }, /* 360kB in 1.2MB drive */
{ 1440, 9,2,80,0,0x23,0x01,0xDF }, /* 720kB in 1.2MB drive */
{ 2880,18,2,80,0,0x1B,0x00,0xCF }, /* 1.44MB diskette */
};
/*
* Rate is 0 for 500kb/s, 2 for 300kbps, 1 for 250kbps
* Spec1 is 0xSH, where S is stepping rate (F=1ms, E=2ms, D=3ms etc),
* H is head unload time (1=16ms, 2=32ms, etc)
*
* Spec2 is (HLD<<1 | ND), where HLD is head load time (1=2ms, 2=4 ms etc)
* and ND is set means no DMA. Hardcoded to 6 (HLD=6ms, use DMA).
*/
extern void floppy_interrupt(void);
extern char tmp_floppy_area[1024];
/*
* These are global variables, as that's the easiest way to give
* information to interrupts. They are the data used for the current
* request.
*/
static int cur_spec1 = -1;
static int cur_rate = -1;
static struct floppy_struct * floppy = floppy_type;
static unsigned char current_drive = 0;
static unsigned char sector = 0;
static unsigned char head = 0;
static unsigned char track = 0;
static unsigned char seek_track = 0;
static unsigned char current_track = 255;
static unsigned char command = 0;
unsigned char selected = 0;
struct task_struct * wait_on_floppy_select = NULL;
void floppy_deselect(unsigned int nr)
{
if (nr != (current_DOR & 3))
printk("floppy_deselect: drive not selected\n\r");
selected = 0;
wake_up(&wait_on_floppy_select);
}
/*
* floppy-change is never called from an interrupt, so we can relax a bit
* here, sleep etc. Note that floppy-on tries to set current_DOR to point
* to the desired drive, but it will probably not survive the sleep if
* several floppies are used at the same time: thus the loop.
*/
int floppy_change(unsigned int nr)
{
repeat:
floppy_on(nr);
while ((current_DOR & 3) != nr && selected)
sleep_on(&wait_on_floppy_select);
if ((current_DOR & 3) != nr)
goto repeat;
if (inb(FD_DIR) & 0x80) {
floppy_off(nr);
return 1;
}
floppy_off(nr);
return 0;
}
#define copy_buffer(from,to) \
__asm__("cld ; rep ; movsl" \
::"c" (BLOCK_SIZE/4),"S" ((long)(from)),"D" ((long)(to)) \
:"cx","di","si")
static void setup_DMA(void)
{
long addr = (long) CURRENT->buffer;
cli();
if (addr >= 0x100000) {
addr = (long) tmp_floppy_area;
if (command == FD_WRITE)
copy_buffer(CURRENT->buffer,tmp_floppy_area);
}
/* mask DMA 2 */
immoutb_p(4|2,10);
/* output command byte. I don't know why, but everyone (minix, */
/* sanches & canton) output this twice, first to 12 then to 11 */
__asm__("outb %%al,$12\n\tjmp 1f\n1:\tjmp 1f\n1:\t"
"outb %%al,$11\n\tjmp 1f\n1:\tjmp 1f\n1:"::
"a" ((char) ((command == FD_READ)?DMA_READ:DMA_WRITE)));
/* 8 low bits of addr */
immoutb_p(addr,4);
addr >>= 8;
/* bits 8-15 of addr */
immoutb_p(addr,4);
addr >>= 8;
/* bits 16-19 of addr */
immoutb_p(addr,0x81);
/* low 8 bits of count-1 (1024-1=0x3ff) */
immoutb_p(0xff,5);
/* high 8 bits of count-1 */
immoutb_p(3,5);
/* activate DMA 2 */
immoutb_p(0|2,10);
sti();
}
static void output_byte(char byte)
{
int counter;
unsigned char status;
if (reset)
return;
for(counter = 0 ; counter < 10000 ; counter++) {
status = inb_p(FD_STATUS) & (STATUS_READY | STATUS_DIR);
if (status == STATUS_READY) {
outb(byte,FD_DATA);
return;
}
}
reset = 1;
printk("Unable to send byte to FDC\n\r");
}
static int result(void)
{
int i = 0, counter, status;
if (reset)
return -1;
for (counter = 0 ; counter < 10000 ; counter++) {
status = inb_p(FD_STATUS)&(STATUS_DIR|STATUS_READY|STATUS_BUSY);
if (status == STATUS_READY)
return i;
if (status == (STATUS_DIR|STATUS_READY|STATUS_BUSY)) {
if (i >= MAX_REPLIES)
break;
reply_buffer[i++] = inb_p(FD_DATA);
}
}
reset = 1;
printk("Getstatus times out\n\r");
return -1;
}
static void bad_flp_intr(void)
{
CURRENT->errors++;
if (CURRENT->errors > MAX_ERRORS) {
floppy_deselect(current_drive);
end_request(0);
}
if (CURRENT->errors > MAX_ERRORS/2)
reset = 1;
else
recalibrate = 1;
}
/*
* Ok, this interrupt is called after a DMA read/write has succeeded,
* so we check the results, and copy any buffers.
*/
static void rw_interrupt(void)
{
if (result() != 7 || (ST0 & 0xf8) || (ST1 & 0xbf) || (ST2 & 0x73)) {
if (ST1 & 0x02) {
printk("Drive %d is write protected\n\r",current_drive);
floppy_deselect(current_drive);
end_request(0);
} else
bad_flp_intr();
do_fd_request();
return;
}
if (command == FD_READ && (unsigned long)(CURRENT->buffer) >= 0x100000)
copy_buffer(tmp_floppy_area,CURRENT->buffer);
floppy_deselect(current_drive);
end_request(1);
do_fd_request();
}
inline void setup_rw_floppy(void)
{
setup_DMA();
do_floppy = rw_interrupt;
output_byte(command);
output_byte(head<<2 | current_drive);
output_byte(track);
output_byte(head);
output_byte(sector);
output_byte(2); /* sector size = 512 */
output_byte(floppy->sect);
output_byte(floppy->gap);
output_byte(0xFF); /* sector size (0xff when n!=0 ?) */
if (reset)
do_fd_request();
}
/*
* This is the routine called after every seek (or recalibrate) interrupt
* from the floppy controller. Note that the "unexpected interrupt" routine
* also does a recalibrate, but doesn't come here.
*/
static void seek_interrupt(void)
{
/* sense drive status */
output_byte(FD_SENSEI);
if (result() != 2 || (ST0 & 0xF8) != 0x20 || ST1 != seek_track) {
bad_flp_intr();
do_fd_request();
return;
}
current_track = ST1;
setup_rw_floppy();
}
/*
* This routine is called when everything should be correctly set up
* for the transfer (ie floppy motor is on and the correct floppy is
* selected).
*/
static void transfer(void)
{
if (cur_spec1 != floppy->spec1) {
cur_spec1 = floppy->spec1;
output_byte(FD_SPECIFY);
output_byte(cur_spec1); /* hut etc */
output_byte(6); /* Head load time =6ms, DMA */
}
if (cur_rate != floppy->rate)
outb_p(cur_rate = floppy->rate,FD_DCR);
if (reset) {
do_fd_request();
return;
}
if (!seek) {
setup_rw_floppy();
return;
}
do_floppy = seek_interrupt;
if (seek_track) {
output_byte(FD_SEEK);
output_byte(head<<2 | current_drive);
output_byte(seek_track);
} else {
output_byte(FD_RECALIBRATE);
output_byte(head<<2 | current_drive);
}
if (reset)
do_fd_request();
}
/*
* Special case - used after a unexpected interrupt (or reset)
*/
static void recal_interrupt(void)
{
output_byte(FD_SENSEI);
if (result()!=2 || (ST0 & 0xE0) == 0x60)
reset = 1;
else
recalibrate = 0;
do_fd_request();
}
void unexpected_floppy_interrupt(void)
{
output_byte(FD_SENSEI);
if (result()!=2 || (ST0 & 0xE0) == 0x60)
reset = 1;
else
recalibrate = 1;
}
static void recalibrate_floppy(void)
{
recalibrate = 0;
current_track = 0;
do_floppy = recal_interrupt;
output_byte(FD_RECALIBRATE);
output_byte(head<<2 | current_drive);
if (reset)
do_fd_request();
}
static void reset_interrupt(void)
{
output_byte(FD_SENSEI);
(void) result();
output_byte(FD_SPECIFY);
output_byte(cur_spec1); /* hut etc */
output_byte(6); /* Head load time =6ms, DMA */
do_fd_request();
}
/*
* reset is done by pulling bit 2 of DOR low for a while.
*/
static void reset_floppy(void)
{
int i;
reset = 0;
cur_spec1 = -1;
cur_rate = -1;
recalibrate = 1;
printk("Reset-floppy called\n\r");
cli();
do_floppy = reset_interrupt;
outb_p(current_DOR & ~0x04,FD_DOR);
for (i=0 ; i<100 ; i++)
__asm__("nop");
outb(current_DOR,FD_DOR);
sti();
}
static void floppy_on_interrupt(void)
{
/* We cannot do a floppy-select, as that might sleep. We just force it */
selected = 1;
if (current_drive != (current_DOR & 3)) {
current_DOR &= 0xFC;
current_DOR |= current_drive;
outb(current_DOR,FD_DOR);
add_timer(2,&transfer);
} else
transfer();
}
void do_fd_request(void)
{
unsigned int block;
seek = 0;
if (reset) {
reset_floppy();
return;
}
if (recalibrate) {
recalibrate_floppy();
return;
}
INIT_REQUEST;
floppy = (MINOR(CURRENT->dev)>>2) + floppy_type;
if (current_drive != CURRENT_DEV)
seek = 1;
current_drive = CURRENT_DEV;
block = CURRENT->sector;
if (block+2 > floppy->size) {
end_request(0);
goto repeat;
}
sector = block % floppy->sect;
block /= floppy->sect;
head = block % floppy->head;
track = block / floppy->head;
seek_track = track << floppy->stretch;
if (seek_track != current_track)
seek = 1;
sector++;
if (CURRENT->cmd == READ)
command = FD_READ;
else if (CURRENT->cmd == WRITE)
command = FD_WRITE;
else
panic("do_fd_request: unknown command");
add_timer(ticks_to_floppy_on(current_drive),&floppy_on_interrupt);
}
static int floppy_sizes[] ={
0, 0, 0, 0,
360, 360 ,360, 360,
1200,1200,1200,1200,
360, 360, 360, 360,
720, 720, 720, 720,
360, 360, 360, 360,
720, 720, 720, 720,
1440,1440,1440,1440
};
void floppy_init(void)
{
blk_size[MAJOR_NR] = floppy_sizes;
blk_dev[MAJOR_NR].request_fn = DEVICE_REQUEST;
set_trap_gate(0x26,&floppy_interrupt);
outb(inb_p(0x21)&~0x40,0x21);
}
| {
"content_hash": "51c12e7011681a8ed06264b8ad3d10ba",
"timestamp": "",
"source": "github",
"line_count": 475,
"max_line_length": 78,
"avg_line_length": 24.54736842105263,
"alnum_prop": 0.6532590051457976,
"repo_name": "namoamitabha/StudyNotes",
"id": "3bccac08a38a8b136ac4b88edb33c8eeb772cb09",
"size": "11660",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "linux-0.12/kernel/blk_drv/floppy.c",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Assembly",
"bytes": "57390"
},
{
"name": "C",
"bytes": "1250201"
},
{
"name": "C++",
"bytes": "14759"
},
{
"name": "Common Lisp",
"bytes": "13421"
},
{
"name": "JavaScript",
"bytes": "2534"
},
{
"name": "Makefile",
"bytes": "247835"
},
{
"name": "NewLisp",
"bytes": "38884"
},
{
"name": "Shell",
"bytes": "6332"
}
],
"symlink_target": ""
} |
package org.apache.bookkeeper.bookie;
import java.util.concurrent.Future;
/**
* State management of Bookie, including register, turn bookie to w/r mode.
*/
public interface StateManager extends AutoCloseable {
/**
* Init state of Bookie when launch bookie.
*/
void initState();
/**
* Check if the bookie is available for high priority writes or not.
*
* @return true if the bookie is available for high priority writes; otherwise false.
*/
boolean isAvailableForHighPriorityWrites();
/**
* Enable/Disable the availability for high priority writes.
*
* @param available the flag to enable/disable the availability for high priority writes.
*/
void setHighPriorityWritesAvailability(boolean available);
/**
* Check is ReadOnly.
*/
boolean isReadOnly();
/**
* Check is Running.
*/
boolean isRunning();
/**
* Check is Shutting down.
*/
boolean isShuttingDown();
/**
* Close the manager, release its resources.
*/
@Override
void close();
/**
* Register the bookie to RegistrationManager.
* @params throwException, whether throwException or not
*/
Future<Void> registerBookie(boolean throwException);
// forceTos methods below should be called inside Bookie,
// which indicates important state of bookie and should be visible fast.
/**
* Turn state to the shutting down progress,just the flag.
*/
void forceToShuttingDown();
/**
* Turn state to the read only, just flag.
*/
void forceToReadOnly();
/**
* Turn state to not registered, just the flag.
*/
void forceToUnregistered();
/**
* Change the state of bookie to Writable mode.
*/
Future<Void> transitionToWritableMode();
/**
* Change the state of bookie to ReadOnly mode.
*/
Future<Void> transitionToReadOnlyMode();
/**
* ShutdownHandler used to shutdown bookie.
*/
interface ShutdownHandler {
void shutdown(int code);
}
void setShutdownHandler(ShutdownHandler handler);
}
| {
"content_hash": "ff9d66db8b7b6dd942e21908a6cd6487",
"timestamp": "",
"source": "github",
"line_count": 94,
"max_line_length": 93,
"avg_line_length": 22.851063829787233,
"alnum_prop": 0.6373370577281192,
"repo_name": "sijie/bookkeeper",
"id": "538f3ac19ef1f1ea0e13eb735e7d1a754866100e",
"size": "2953",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "bookkeeper-server/src/main/java/org/apache/bookkeeper/bookie/StateManager.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "C",
"bytes": "4163"
},
{
"name": "C++",
"bytes": "17844"
},
{
"name": "CSS",
"bytes": "6348"
},
{
"name": "Dockerfile",
"bytes": "12599"
},
{
"name": "Groovy",
"bytes": "111690"
},
{
"name": "HTML",
"bytes": "16892"
},
{
"name": "Java",
"bytes": "13173512"
},
{
"name": "JavaScript",
"bytes": "914"
},
{
"name": "Makefile",
"bytes": "7304"
},
{
"name": "Python",
"bytes": "241177"
},
{
"name": "Roff",
"bytes": "39396"
},
{
"name": "Ruby",
"bytes": "6445"
},
{
"name": "Shell",
"bytes": "172995"
},
{
"name": "Thrift",
"bytes": "1473"
}
],
"symlink_target": ""
} |
layout: single
title: 'Projects'
permalink: /projects/
author_profile: true
eth:
- image_path: /assets/images/telescope2/teaser.png
alt: "customizable"
title: Master thesis (at <a href="http://www.ibk.ethz.ch/">IBK</a>)<br>
excerpt: Structural Optimization of a Novel Type of Gamma-Ray Telescope.
url: /telescope2/
btn_label: "Explore more"
btn_class: "btn--small"
- image_path: /assets/images/wisba/teaser.jpg
alt: "customizable"
title: <a href="http://wisba.wienerberger.com/">WISBA</a> EU project
excerpt: Whole Building Analysis of [Building 2226](http://www.baumschlager-eberle.com/en/projects/project-details/project/buerogebaeude.html) from a "Climate Change" energy scenario point of view.
url: /wisba/
btn_label: "Explore more"
btn_class: "btn--small"
- image_path: /assets/images/telescope1/altaz.jpg
alt: "customizable"
title: Project Work at <a href="http://www.ibk.ethz.ch/">IBK</a>
excerpt: A comparative study between a novel and a traditional Gamma-Ray telescope concept.
url: /telescope1/
btn_label: "Explore more"
btn_class: "btn--small"
- image_path: /assets/images/project_ibi/limestone3.jpg
alt: "customizable"
title: Project Work at <a href="http://www.ibi.ethz.ch/">IBI</a>
excerpt: Study of the thermal behaviour of a 60-year-old stone building using BIM.
url: /project_ibi/
btn_label: "Explore more"
btn_class: "btn--small"
duth:
- image_path: /assets/images/xanthi/bw3d.jpg
alt: "customizable"
title: Master thesis<br><br>
excerpt: Design of a diving facility using Building Information Modelling (BIM).
url: /xanthi/
btn_label: "Explore more"
btn_class: "btn--small"
- image_path: /assets/images/kos3/teaser.jpg
alt: "customizable"
title: RC Structures III project
excerpt: Design of an irregular multi-storey concrete building against earthquake loads.
url: /kos3/
btn_label: "Explore more"
btn_class: "btn--small"
- image_path: /assets/images/kos1bg/teaser.jpg
alt: "customizable"
title: RC 1B/1C project
excerpt: Design of a typical residential building in a seismic prone area.
url: /kos1bg/
btn_label: "Explore more"
btn_class: "btn--small"
- image_path: /assets/images/con_bridges/teaser.jpg
alt: "customizable"
title: RC Bridges project
excerpt: Design of a pre-stressed concrete road bridge.
url: /con_bridges/
btn_label: "Explore more"
btn_class: "btn--small"
- image_path: /assets/images/xanthi3/xanthi33d.jpg
alt: "customizable"
title: Steel Design III project
excerpt: Design of a typical Steel Warehouse.
url: /xanthi3/
btn_label: "Explore more"
btn_class: "btn--small"
intro_duth:
- excerpt: <b>Projects during my Diploma in Democritus University of Thrace
intro_eth:
- excerpt: <b>Projects during my MSc in the Swiss Federal Institute of Technology
---
{% include feature_row id="intro_eth" type="center" %}
{% include feature_row id="eth" %}
{% include feature_row id="intro_duth" type="center" %}
{% include feature_row id="duth" %}
| {
"content_hash": "52c5a4e1dc8336fe359003f5f2394466",
"timestamp": "",
"source": "github",
"line_count": 80,
"max_line_length": 202,
"avg_line_length": 39,
"alnum_prop": 0.6913461538461538,
"repo_name": "spirosd/spirosd.github.io",
"id": "d822429f89858611e7b705eec3345bca9ca63d08",
"size": "3124",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "_pages/projects.md",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "70816"
},
{
"name": "HTML",
"bytes": "61145"
},
{
"name": "JavaScript",
"bytes": "53627"
},
{
"name": "Ruby",
"bytes": "2279"
}
],
"symlink_target": ""
} |
using System;
using SkiaSharp;
namespace FFImageLoading.Svg.Platform
{
internal struct SKSvgImage
{
public SKSvgImage(SKRect rect, string uri, byte[] bytes = null)
{
Rect = rect;
Uri = uri;
Bytes = bytes;
}
public SKRect Rect { get; }
public string Uri { get; }
public byte[] Bytes { get; }
}
}
| {
"content_hash": "f60f0f33a3955c59ff1913a5fb4b167f",
"timestamp": "",
"source": "github",
"line_count": 21,
"max_line_length": 71,
"avg_line_length": 18.857142857142858,
"alnum_prop": 0.5303030303030303,
"repo_name": "luberda-molinet/FFImageLoading",
"id": "b902b186d12edb05a427ca34057cdff79d24e7af",
"size": "398",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "source/FFImageLoading.Svg.Shared/SKSvgImage.cs",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Batchfile",
"bytes": "4153"
},
{
"name": "C#",
"bytes": "1286841"
},
{
"name": "Makefile",
"bytes": "120"
}
],
"symlink_target": ""
} |
import matplotlib as mpl
import networkx as nx
import pydotplus
import six
from loman.consts import NodeAttributes, States
state_colors = {
None: '#ffffff', # xkcd white
States.PLACEHOLDER: '#f97306', # xkcd orange
States.UNINITIALIZED: '#0343df', # xkcd blue
States.STALE: '#ffff14', # xkcd yellow
States.COMPUTABLE: '#9dff00', # xkcd bright yellow green
States.UPTODATE: '#15b01a', # xkcd green
States.ERROR: '#e50000', # xkcd red
States.PINNED: '#bf77f6' # xkcd light purple
}
def create_viz_dag(comp_dag, colors='state', cmap=None):
colors = colors.lower()
if colors == 'state':
if cmap is None:
cmap = state_colors
elif colors == 'timing':
if cmap is None:
cmap = mpl.colors.LinearSegmentedColormap.from_list('blend', ['#15b01a', '#ffff14', '#e50000'])
timings = nx.get_node_attributes(comp_dag, NodeAttributes.TIMING)
max_duration = max(timing.duration for timing in six.itervalues(timings) if hasattr(timing, 'duration'))
min_duration = min(timing.duration for timing in six.itervalues(timings) if hasattr(timing, 'duration'))
else:
raise ValueError('{} is not a valid loman colors parameter for visualization'.format(colors))
viz_dag = nx.DiGraph()
node_index_map = {}
for i, (name, data) in enumerate(comp_dag.nodes(data=True)):
short_name = "n{}".format(i)
attr_dict = {
'label': name,
'style': 'filled',
'_group': data.get(NodeAttributes.GROUP)
}
if colors == 'state':
attr_dict['fillcolor'] = cmap[data.get(NodeAttributes.STATE, None)]
elif colors == 'timing':
timing_data = data.get(NodeAttributes.TIMING)
if timing_data is None:
col = '#FFFFFF'
else:
duration = timing_data.duration
norm_duration = (duration - min_duration) / (max_duration - min_duration)
col = mpl.colors.rgb2hex(cmap(norm_duration))
attr_dict['fillcolor'] = col
viz_dag.add_node(short_name, **attr_dict)
node_index_map[name] = short_name
for name1, name2 in comp_dag.edges():
short_name_1 = node_index_map[name1]
short_name_2 = node_index_map[name2]
group1 = comp_dag.nodes[name1].get(NodeAttributes.GROUP)
group2 = comp_dag.nodes[name2].get(NodeAttributes.GROUP)
group = group1 if group1 == group2 else None
attr_dict = {'_group': group}
viz_dag.add_edge(short_name_1, short_name_2, **attr_dict)
return viz_dag
def to_pydot(viz_dag, graph_attr=None, node_attr=None, edge_attr=None):
node_groups = {}
for name, data in viz_dag.nodes(data=True):
group = data.get('_group')
node_groups.setdefault(group, []).append(name)
edge_groups = {}
for name1, name2, data in viz_dag.edges(data=True):
group = data.get('_group')
edge_groups.setdefault(group, []).append((name1, name2))
viz_dot = pydotplus.Dot()
if graph_attr is not None:
for k, v in six.iteritems(graph_attr):
viz_dot.set(k, v)
if node_attr is not None:
viz_dot.set_node_defaults(**node_attr)
if edge_attr is not None:
viz_dot.set_edge_defaults(**edge_attr)
for group, names in six.iteritems(node_groups):
if group is None:
continue
c = pydotplus.Subgraph('cluster_' + str(group))
for name in names:
node = pydotplus.Node(name)
for k, v in six.iteritems(viz_dag.node[name]):
if not k.startswith("_"):
node.set(k, v)
c.add_node(node)
for name1, name2 in edge_groups.get(group, []):
edge = pydotplus.Edge(name1, name2)
c.add_edge(edge)
c.obj_dict['label'] = str(group)
viz_dot.add_subgraph(c)
for name in node_groups.get(None, []):
node = pydotplus.Node(name)
for k, v in six.iteritems(viz_dag.nodes[name]):
if not k.startswith("_"):
node.set(k, v)
viz_dot.add_node(node)
for name1, name2 in edge_groups.get(None, []):
edge = pydotplus.Edge(name1, name2)
viz_dot.add_edge(edge)
return viz_dot | {
"content_hash": "a18ac23c72b158d56740ca8d0658fabb",
"timestamp": "",
"source": "github",
"line_count": 125,
"max_line_length": 112,
"avg_line_length": 35.024,
"alnum_prop": 0.5815440840566469,
"repo_name": "janusassetallocation/loman",
"id": "beef354c885a783b3526490619d0a0e861fd7fb2",
"size": "4378",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "loman/visualization.py",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "Python",
"bytes": "92557"
}
],
"symlink_target": ""
} |
@interface ExtensionDelegate : NSObject <WKExtensionDelegate>
@end | {
"content_hash": "5f172dc6c5f429974fe0d6d982aab43a",
"timestamp": "",
"source": "github",
"line_count": 3,
"max_line_length": 61,
"avg_line_length": 22.333333333333332,
"alnum_prop": 0.835820895522388,
"repo_name": "pivotal-ivan-rodriguez/PLComp",
"id": "b7dd9a52efe19603e35e8a810c420cead315dc41",
"size": "98",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "lication Extension/ExtensionDelegate.h",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Objective-C",
"bytes": "9020"
}
],
"symlink_target": ""
} |
<!doctype html public "-//W3C//DTD HTML 4.0 Transitional//EN" "http://www.w3.org/TR/REC-html40/loose.dtd">
<html>
<head>
<title>PHPXRef 0.7.1 : Unnamed Project : Variable Reference: $base_tag_name_re</title>
<link rel="stylesheet" href="../sample.css" type="text/css">
<link rel="stylesheet" href="../sample-print.css" type="text/css" media="print">
<style id="hilight" type="text/css"></style>
<meta http-equiv="content-type" content="text/html;charset=iso-8859-1">
</head>
<body bgcolor="#ffffff" text="#000000" link="#801800" vlink="#300540" alink="#ffffff">
<table class="pagetitle" width="100%">
<tr>
<td valign="top" class="pagetitle">
[ <a href="../index.html">Index</a> ]
</td>
<td align="right" class="pagetitle">
<h2 style="margin-bottom: 0px">PHP Cross Reference of Unnamed Project</h2>
</td>
</tr>
</table>
<!-- Generated by PHPXref 0.7.1 at Thu Oct 23 18:57:41 2014 -->
<!-- PHPXref (c) 2000-2010 Gareth Watts - gareth@omnipotent.net -->
<!-- http://phpxref.sourceforge.net/ -->
<script src="../phpxref.js" type="text/javascript"></script>
<script language="JavaScript" type="text/javascript">
<!--
ext='.html';
relbase='../';
subdir='_variables';
filename='index.html';
cookiekey='phpxref';
handleNavFrame(relbase, subdir, filename);
logVariable('base_tag_name_re');
// -->
</script>
<script language="JavaScript" type="text/javascript">
if (gwGetCookie('xrefnav')=='off')
document.write('<p class="navlinks">[ <a href="javascript:navOn()">Show Explorer<\/a> ]<\/p>');
else
document.write('<p class="navlinks">[ <a href="javascript:navOff()">Hide Explorer<\/a> ]<\/p>');
</script>
<noscript>
<p class="navlinks">
[ <a href="../nav.html" target="_top">Show Explorer</a> ]
[ <a href="index.html" target="_top">Hide Navbar</a> ]
</p>
</noscript>
[<a href="../index.html">Top level directory</a>]<br>
<script language="JavaScript" type="text/javascript">
<!--
document.writeln('<table align="right" class="searchbox-link"><tr><td><a class="searchbox-link" href="javascript:void(0)" onMouseOver="showSearchBox()">Search</a><br>');
document.writeln('<table border="0" cellspacing="0" cellpadding="0" class="searchbox" id="searchbox">');
document.writeln('<tr><td class="searchbox-title">');
document.writeln('<a class="searchbox-title" href="javascript:showSearchPopup()">Search History +</a>');
document.writeln('<\/td><\/tr>');
document.writeln('<tr><td class="searchbox-body" id="searchbox-body">');
document.writeln('<form name="search" style="margin:0px; padding:0px" onSubmit=\'return jump()\'>');
document.writeln('<a class="searchbox-body" href="../_classes/index.html">Class<\/a>: ');
document.writeln('<input type="text" size=10 value="" name="classname"><br>');
document.writeln('<a id="funcsearchlink" class="searchbox-body" href="../_functions/index.html">Function<\/a>: ');
document.writeln('<input type="text" size=10 value="" name="funcname"><br>');
document.writeln('<a class="searchbox-body" href="../_variables/index.html">Variable<\/a>: ');
document.writeln('<input type="text" size=10 value="" name="varname"><br>');
document.writeln('<a class="searchbox-body" href="../_constants/index.html">Constant<\/a>: ');
document.writeln('<input type="text" size=10 value="" name="constname"><br>');
document.writeln('<a class="searchbox-body" href="../_tables/index.html">Table<\/a>: ');
document.writeln('<input type="text" size=10 value="" name="tablename"><br>');
document.writeln('<input type="submit" class="searchbox-button" value="Search">');
document.writeln('<\/form>');
document.writeln('<\/td><\/tr><\/table>');
document.writeln('<\/td><\/tr><\/table>');
// -->
</script>
<div id="search-popup" class="searchpopup"><p id="searchpopup-title" class="searchpopup-title">title</p><div id="searchpopup-body" class="searchpopup-body">Body</div><p class="searchpopup-close"><a href="javascript:gwCloseActive()">[close]</a></p></div>
<h3>Variable Cross Reference</h3>
<h2><a href="index.html#base_tag_name_re">$base_tag_name_re</a></h2>
<b>Defined at:</b><ul>
<li><a href="../bonfire/helpers/markdown_helper.php.html">/bonfire/helpers/markdown_helper.php</A> -> <a href="../bonfire/helpers/markdown_helper.php.source.html#l2101"> line 2101</A></li>
</ul>
<br><b>Referenced 3 times:</b><ul>
<li><a href="../bonfire/helpers/markdown_helper.php.html">/bonfire/helpers/markdown_helper.php</a> -> <a href="../bonfire/helpers/markdown_helper.php.source.html#l2098"> line 2098</a></li>
<li><a href="../bonfire/helpers/markdown_helper.php.html">/bonfire/helpers/markdown_helper.php</a> -> <a href="../bonfire/helpers/markdown_helper.php.source.html#l2101"> line 2101</a></li>
<li><a href="../bonfire/helpers/markdown_helper.php.html">/bonfire/helpers/markdown_helper.php</a> -> <a href="../bonfire/helpers/markdown_helper.php.source.html#l2144"> line 2144</a></li>
</ul>
<!-- A link to the phpxref site in your customized footer file is appreciated ;-) -->
<br><hr>
<table width="100%">
<tr><td>Generated: Thu Oct 23 18:57:41 2014</td>
<td align="right"><i>Cross-referenced by <a href="http://phpxref.sourceforge.net/">PHPXref 0.7.1</a></i></td>
</tr>
</table>
</body></html>
| {
"content_hash": "257d5a87333f091cff2bb9b5ba77d67b",
"timestamp": "",
"source": "github",
"line_count": 98,
"max_line_length": 253,
"avg_line_length": 52.86734693877551,
"alnum_prop": 0.671685002895194,
"repo_name": "inputx/code-ref-doc",
"id": "d3b54b85b334e2eb37083551c08c1aaf59efd7d2",
"size": "5181",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "bonfire/_variables/base_tag_name_re.html",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "17952"
},
{
"name": "JavaScript",
"bytes": "255489"
}
],
"symlink_target": ""
} |
In this dark stream-processing landscape, `coast` is a ray of light.
## Why `coast`?
- **Simple:** `coast` provides a simple streaming model with strong ordering and
exactly-once semantics. This straightforward behaviour extends across multiple
machines, state aggregations, and even between independent jobs, making it
easier to reason about how your entire system behaves.
- **Easy:** Streams are built up and wired together using a concise, idiomatic
Scala API. These dataflow graphs can be as small or as large as you like:
no need to cram all your logic in one big job, or to write a bunch
of single-stage jobs and track their relationships by hand.
- **Kafkaesque:** `coast`'s core abstractions are patterned after Kafka's
data model, and it's designed to fit comfortably in the middle of a larger
Kafka-based infrastructure. By taking advantage of Kafka's messaging
guarantees, `coast` can implement [exactly-once semantics][impossible]
for messages and state without a heavy coordination cost.
## Quick Introduction
`coast`'s streams are closely patterned after Kafka's topics: a stream has
multiple partitions, and each partition has an ordered series of values. A
stream can have any number of partitions, each of which has a unique key.
You can create a stream by pulling data from a topic, but `coast` also
has a rich API for building derivative streams: applying transformations,
merging streams together, regrouping, aggregating state, or performing joins.
Once you've defined a stream you like, you can give it a name and publish it
out to another topic.
By defining streams and networking them together, it's possible to
express arbitrarily-complex dataflow graphs, including cycles and joins. You can
use the resulting graphs in multiple ways: print it out as a GraphViz image,
unit-test your logic using a simple in-memory implementation, or compile the
graph to multiple [Samza jobs][samza] and run it on a cluster.
Sound promising? You might be interested in:
- The [heavily-commented 'Twitter reach' example][twitter-reach],
which walks through all the pieces of a real job.
- A [fork of the `hello-samza` project][hello-coast] with setup and deployment instructions.
- Some [wiki documentation][wiki] on [the core concepts][wiki-overview],
nuances of the [graph-builder API][wiki-flow],
or [details on the Samza integration][wiki-samza].
[samza]: http://samza.apache.org/
[hello-coast]: https://github.com/bkirwi/incubator-samza-hello-samza/tree/hello-coast
[twitter-reach]: core/src/main/scala/com/monovore/example/coast/TwitterReach.scala
[impossible]: http://ben.kirw.in/2014/11/28/kafka-patterns/
[wiki]: https://github.com/bkirwi/coast/wiki
[wiki-overview]: https://github.com/bkirwi/coast/wiki/Overview
[wiki-flow]: https://github.com/bkirwi/coast/wiki/Flow
[wiki-samza]: https://github.com/bkirwi/coast/wiki/Samza
## Getting Started
The 0.2.0 release is published on Bintray.
If you're using maven, you'll want to point your `pom.xml` at the repo:
```xml
<repository>
<id>bintray-coast</id>
<url>https://dl.bintray.com/bkirwi/maven</url>
</repository>
```
...and add `coast` to your dependencies:
```xml
<dependency>
<groupId>com.monovore</groupId>
<artifactId>coast-samza_2.10</artifactId>
<version>0.2.0</version>
</dependency>
```
*Mutatis mutandis*, the same goes for SBT and Gradle.
## Mandatory Word Count Example
```scala
val Sentences = Topic[Source, String]("sentences")
val WordCounts = Topic[String, Int]("word-counts")
val graph = for {
words <- Flow.stream("words") {
Flow.source(Sentences)
.flatMap { _.split("\\s+") }
.map { _ -> 1 }
.groupByKey
}
_ <- Flow.sink(WordCounts) {
words.sum.updates
}
} yield ()
```
## Future Work
If you're interested in what the future holds for `coast` --
or have questions or bugs to report --
come on over to the [issue tracker][issues].
[issues]: https://github.com/bkirwi/coast/issues
| {
"content_hash": "5575b2cc99e24647b5db8bec6567f7a5",
"timestamp": "",
"source": "github",
"line_count": 107,
"max_line_length": 92,
"avg_line_length": 37.074766355140184,
"alnum_prop": 0.7418704310562138,
"repo_name": "milinda/coast",
"id": "157586d3cf5bb23bb6311f329ec7c96c3eeb121e",
"size": "3976",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "README.md",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Scala",
"bytes": "150277"
}
],
"symlink_target": ""
} |
.class public Lcom/htc/internal/telephony/HtcSimSmsUtils;
.super Ljava/lang/Object;
.source "HtcSimSmsUtils.java"
# static fields
.field private static final TAG:Ljava/lang/String; = "HtcSimSmsUtils"
# direct methods
.method public constructor <init>()V
.locals 0
.prologue
.line 36
invoke-direct {p0}, Ljava/lang/Object;-><init>()V
return-void
.end method
.method public static fragmentCdmaMtSmsWith172Length(Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;)Ljava/util/ArrayList;
.locals 17
.param p0, "text" # Ljava/lang/String;
.param p1, "originatorAddress" # Ljava/lang/String;
.param p2, "callbackNum" # Ljava/lang/String;
.annotation system Ldalvik/annotation/Signature;
value = {
"(",
"Ljava/lang/String;",
"Ljava/lang/String;",
"Ljava/lang/String;",
")",
"Ljava/util/ArrayList",
"<",
"Ljava/lang/String;",
">;"
}
.end annotation
.prologue
.line 82
const/4 v1, 0x0
.line 83
.local v1, "addressObj":Lcom/android/internal/telephony/cdma/sms/CdmaSmsAddress;
const/4 v2, 0x0
.line 84
.local v2, "callbackObj":Lcom/android/internal/telephony/cdma/sms/CdmaSmsAddress;
invoke-static/range {p1 .. p1}, Landroid/text/TextUtils;->isEmpty(Ljava/lang/CharSequence;)Z
move-result v14
if-nez v14, :cond_0
invoke-static/range {p1 .. p1}, Lcom/android/internal/telephony/cdma/sms/CdmaSmsAddress;->parse(Ljava/lang/String;)Lcom/android/internal/telephony/cdma/sms/CdmaSmsAddress;
move-result-object v1
.line 85
:cond_0
invoke-static/range {p2 .. p2}, Landroid/text/TextUtils;->isEmpty(Ljava/lang/CharSequence;)Z
move-result v14
if-nez v14, :cond_1
invoke-static/range {p2 .. p2}, Lcom/android/internal/telephony/cdma/sms/CdmaSmsAddress;->parse(Ljava/lang/String;)Lcom/android/internal/telephony/cdma/sms/CdmaSmsAddress;
move-result-object v2
.line 112
:cond_1
if-nez v1, :cond_4
const/4 v14, 0x0
:goto_0
add-int/lit8 v15, v14, 0x1c
if-nez v2, :cond_5
const/4 v14, 0x0
:goto_1
add-int v10, v15, v14
.line 116
.local v10, "retainBytes":I
rsub-int v4, v10, 0xac
.line 117
.local v4, "maxBytes":I
mul-int/lit8 v14, v4, 0x8
div-int/lit8 v5, v14, 0x7
.line 119
.local v5, "maxSeptets":I
new-instance v12, Lcom/android/internal/telephony/GsmAlphabet$TextEncodingDetails;
invoke-direct {v12}, Lcom/android/internal/telephony/GsmAlphabet$TextEncodingDetails;-><init>()V
.line 120
.local v12, "ted":Lcom/android/internal/telephony/GsmAlphabet$TextEncodingDetails;
const/4 v14, 0x0
move-object/from16 v0, p0
invoke-static {v0, v14}, Lcom/android/internal/telephony/cdma/sms/BearerData;->countAsciiSeptets(Ljava/lang/CharSequence;Z)I
move-result v11
.line 121
.local v11, "septets":I
const/4 v14, -0x1
if-eq v11, v14, :cond_8
.line 122
iput v11, v12, Lcom/android/internal/telephony/GsmAlphabet$TextEncodingDetails;->codeUnitCount:I
.line 123
if-le v11, v5, :cond_7
.line 124
rem-int v14, v11, v5
if-nez v14, :cond_6
.line 125
div-int v14, v11, v5
iput v14, v12, Lcom/android/internal/telephony/GsmAlphabet$TextEncodingDetails;->msgCount:I
.line 126
const/4 v14, 0x0
iput v14, v12, Lcom/android/internal/telephony/GsmAlphabet$TextEncodingDetails;->codeUnitsRemaining:I
.line 136
:goto_2
const/4 v14, 0x1
iput v14, v12, Lcom/android/internal/telephony/GsmAlphabet$TextEncodingDetails;->codeUnitSize:I
.line 153
:goto_3
iget v14, v12, Lcom/android/internal/telephony/GsmAlphabet$TextEncodingDetails;->codeUnitSize:I
const/4 v15, 0x1
if-ne v14, v15, :cond_a
move v3, v5
.line 156
.local v3, "limit":I
:goto_4
const/4 v8, 0x0
.line 157
.local v8, "pos":I
invoke-virtual/range {p0 .. p0}, Ljava/lang/String;->length()I
move-result v13
.line 158
.local v13, "textLen":I
new-instance v9, Ljava/util/ArrayList;
iget v14, v12, Lcom/android/internal/telephony/GsmAlphabet$TextEncodingDetails;->msgCount:I
invoke-direct {v9, v14}, Ljava/util/ArrayList;-><init>(I)V
.line 159
.local v9, "result":Ljava/util/ArrayList;, "Ljava/util/ArrayList<Ljava/lang/String;>;"
:goto_5
if-ge v8, v13, :cond_3
.line 160
const/4 v6, 0x0
.line 161
.local v6, "nextPos":I
iget v14, v12, Lcom/android/internal/telephony/GsmAlphabet$TextEncodingDetails;->codeUnitSize:I
const/4 v15, 0x1
if-ne v14, v15, :cond_b
.line 163
sub-int v14, v13, v8
invoke-static {v3, v14}, Ljava/lang/Math;->min(II)I
move-result v14
add-int v6, v8, v14
.line 167
:goto_6
if-le v6, v8, :cond_2
if-le v6, v13, :cond_c
.line 168
:cond_2
const-string v14, "HtcSimSmsUtils"
new-instance v15, Ljava/lang/StringBuilder;
invoke-direct {v15}, Ljava/lang/StringBuilder;-><init>()V
const-string v16, "fragmentMtSmsWith172Length failed ("
invoke-virtual/range {v15 .. v16}, Ljava/lang/StringBuilder;->append(Ljava/lang/String;)Ljava/lang/StringBuilder;
move-result-object v15
invoke-virtual {v15, v8}, Ljava/lang/StringBuilder;->append(I)Ljava/lang/StringBuilder;
move-result-object v15
const-string v16, " >= "
invoke-virtual/range {v15 .. v16}, Ljava/lang/StringBuilder;->append(Ljava/lang/String;)Ljava/lang/StringBuilder;
move-result-object v15
invoke-virtual {v15, v6}, Ljava/lang/StringBuilder;->append(I)Ljava/lang/StringBuilder;
move-result-object v15
const-string v16, " or "
invoke-virtual/range {v15 .. v16}, Ljava/lang/StringBuilder;->append(Ljava/lang/String;)Ljava/lang/StringBuilder;
move-result-object v15
invoke-virtual {v15, v6}, Ljava/lang/StringBuilder;->append(I)Ljava/lang/StringBuilder;
move-result-object v15
const-string v16, " >= "
invoke-virtual/range {v15 .. v16}, Ljava/lang/StringBuilder;->append(Ljava/lang/String;)Ljava/lang/StringBuilder;
move-result-object v15
invoke-virtual {v15, v13}, Ljava/lang/StringBuilder;->append(I)Ljava/lang/StringBuilder;
move-result-object v15
const-string v16, ")"
invoke-virtual/range {v15 .. v16}, Ljava/lang/StringBuilder;->append(Ljava/lang/String;)Ljava/lang/StringBuilder;
move-result-object v15
invoke-virtual {v15}, Ljava/lang/StringBuilder;->toString()Ljava/lang/String;
move-result-object v15
invoke-static {v14, v15}, Landroid/telephony/Rlog;->e(Ljava/lang/String;Ljava/lang/String;)I
.line 175
.end local v6 # "nextPos":I
:cond_3
return-object v9
.line 112
.end local v3 # "limit":I
.end local v4 # "maxBytes":I
.end local v5 # "maxSeptets":I
.end local v8 # "pos":I
.end local v9 # "result":Ljava/util/ArrayList;, "Ljava/util/ArrayList<Ljava/lang/String;>;"
.end local v10 # "retainBytes":I
.end local v11 # "septets":I
.end local v12 # "ted":Lcom/android/internal/telephony/GsmAlphabet$TextEncodingDetails;
.end local v13 # "textLen":I
:cond_4
invoke-static {v1}, Lcom/htc/internal/telephony/HtcSimSmsUtils;->getCdmaAddressFieldSize(Lcom/android/internal/telephony/cdma/sms/CdmaSmsAddress;)I
move-result v14
goto/16 :goto_0
:cond_5
invoke-static {v2}, Lcom/htc/internal/telephony/HtcSimSmsUtils;->getCdmaAddressFieldSize(Lcom/android/internal/telephony/cdma/sms/CdmaSmsAddress;)I
move-result v14
goto/16 :goto_1
.line 128
.restart local v4 # "maxBytes":I
.restart local v5 # "maxSeptets":I
.restart local v10 # "retainBytes":I
.restart local v11 # "septets":I
.restart local v12 # "ted":Lcom/android/internal/telephony/GsmAlphabet$TextEncodingDetails;
:cond_6
div-int v14, v11, v5
add-int/lit8 v14, v14, 0x1
iput v14, v12, Lcom/android/internal/telephony/GsmAlphabet$TextEncodingDetails;->msgCount:I
.line 129
rem-int v14, v11, v5
sub-int v14, v5, v14
iput v14, v12, Lcom/android/internal/telephony/GsmAlphabet$TextEncodingDetails;->codeUnitsRemaining:I
goto :goto_2
.line 133
:cond_7
const/4 v14, 0x1
iput v14, v12, Lcom/android/internal/telephony/GsmAlphabet$TextEncodingDetails;->msgCount:I
.line 134
sub-int v14, v5, v11
iput v14, v12, Lcom/android/internal/telephony/GsmAlphabet$TextEncodingDetails;->codeUnitsRemaining:I
goto/16 :goto_2
.line 138
:cond_8
invoke-virtual/range {p0 .. p0}, Ljava/lang/String;->length()I
move-result v14
mul-int/lit8 v7, v14, 0x2
.line 139
.local v7, "octets":I
invoke-virtual/range {p0 .. p0}, Ljava/lang/String;->length()I
move-result v14
iput v14, v12, Lcom/android/internal/telephony/GsmAlphabet$TextEncodingDetails;->codeUnitCount:I
.line 141
if-le v7, v4, :cond_9
.line 142
add-int/lit8 v14, v4, -0x1
add-int/2addr v14, v7
div-int/2addr v14, v4
iput v14, v12, Lcom/android/internal/telephony/GsmAlphabet$TextEncodingDetails;->msgCount:I
.line 144
iget v14, v12, Lcom/android/internal/telephony/GsmAlphabet$TextEncodingDetails;->msgCount:I
mul-int/2addr v14, v4
sub-int/2addr v14, v7
div-int/lit8 v14, v14, 0x2
iput v14, v12, Lcom/android/internal/telephony/GsmAlphabet$TextEncodingDetails;->codeUnitsRemaining:I
.line 150
:goto_7
const/4 v14, 0x3
iput v14, v12, Lcom/android/internal/telephony/GsmAlphabet$TextEncodingDetails;->codeUnitSize:I
goto/16 :goto_3
.line 147
:cond_9
const/4 v14, 0x1
iput v14, v12, Lcom/android/internal/telephony/GsmAlphabet$TextEncodingDetails;->msgCount:I
.line 148
sub-int v14, v4, v7
div-int/lit8 v14, v14, 0x2
iput v14, v12, Lcom/android/internal/telephony/GsmAlphabet$TextEncodingDetails;->codeUnitsRemaining:I
goto :goto_7
.end local v7 # "octets":I
:cond_a
move v3, v4
.line 153
goto/16 :goto_4
.line 165
.restart local v3 # "limit":I
.restart local v6 # "nextPos":I
.restart local v8 # "pos":I
.restart local v9 # "result":Ljava/util/ArrayList;, "Ljava/util/ArrayList<Ljava/lang/String;>;"
.restart local v13 # "textLen":I
:cond_b
div-int/lit8 v14, v3, 0x2
sub-int v15, v13, v8
invoke-static {v14, v15}, Ljava/lang/Math;->min(II)I
move-result v14
add-int v6, v8, v14
goto/16 :goto_6
.line 172
:cond_c
move-object/from16 v0, p0
invoke-virtual {v0, v8, v6}, Ljava/lang/String;->substring(II)Ljava/lang/String;
move-result-object v14
invoke-virtual {v9, v14}, Ljava/util/ArrayList;->add(Ljava/lang/Object;)Z
.line 173
move v8, v6
.line 174
goto/16 :goto_5
.end method
.method private static getCdmaAddressFieldSize(Lcom/android/internal/telephony/cdma/sms/CdmaSmsAddress;)I
.locals 3
.param p0, "address" # Lcom/android/internal/telephony/cdma/sms/CdmaSmsAddress;
.prologue
.line 183
const/4 v0, 0x0
.line 192
.local v0, "size":I
add-int/lit8 v0, v0, 0x12
.line 199
iget v1, p0, Lcom/android/internal/telephony/cdma/sms/CdmaSmsAddress;->digitMode:I
if-eqz v1, :cond_0
.line 200
add-int/lit8 v0, v0, 0x3
.line 208
:cond_0
iget v1, p0, Lcom/android/internal/telephony/cdma/sms/CdmaSmsAddress;->digitMode:I
if-eqz v1, :cond_1
iget v1, p0, Lcom/android/internal/telephony/cdma/sms/CdmaSmsAddress;->numberMode:I
const/4 v2, 0x1
if-eq v1, v2, :cond_1
.line 209
add-int/lit8 v0, v0, 0x4
.line 215
:cond_1
add-int/lit8 v0, v0, 0x8
.line 223
iget v1, p0, Lcom/android/internal/telephony/cdma/sms/CdmaSmsAddress;->digitMode:I
if-nez v1, :cond_2
.line 224
iget v1, p0, Lcom/android/internal/telephony/cdma/sms/CdmaSmsAddress;->numberOfDigits:I
mul-int/lit8 v1, v1, 0x4
add-int/2addr v0, v1
.line 228
:goto_0
add-int/lit8 v1, v0, 0x7
div-int/lit8 v1, v1, 0x8
return v1
.line 226
:cond_2
iget v1, p0, Lcom/android/internal/telephony/cdma/sms/CdmaSmsAddress;->numberOfDigits:I
mul-int/lit8 v1, v1, 0x8
add-int/2addr v0, v1
goto :goto_0
.end method
.method public static getMessageFromIccEf(Lcom/android/internal/telephony/PhoneBase;I)[B
.locals 7
.param p0, "phone" # Lcom/android/internal/telephony/PhoneBase;
.param p1, "index" # I
.prologue
.line 48
invoke-static {p0}, Lcom/htc/internal/telephony/HtcSmsUtilsHandler;->getSmsUtilsHandler(Lcom/android/internal/telephony/PhoneBase;)Lcom/htc/internal/telephony/HtcSmsUtilsHandler;
move-result-object v2
.line 50
.local v2, "handler":Lcom/htc/internal/telephony/HtcSmsUtilsHandler;
iget-object v5, v2, Lcom/htc/internal/telephony/HtcSmsUtilsHandler;->mLock:Ljava/lang/Object;
monitor-enter v5
.line 51
const/4 v4, 0x5
:try_start_0
invoke-virtual {v2, v4}, Lcom/htc/internal/telephony/HtcSmsUtilsHandler;->obtainMessage(I)Landroid/os/Message;
move-result-object v3
.line 53
.local v3, "response":Landroid/os/Message;
invoke-virtual {p0}, Lcom/android/internal/telephony/PhoneBase;->getIccFileHandler()Lcom/android/internal/telephony/uicc/IccFileHandler;
move-result-object v1
.line 54
.local v1, "fh":Lcom/android/internal/telephony/uicc/IccFileHandler;
if-nez v1, :cond_0
.line 55
const-string v4, "HtcSimSmsUtils"
const-string v6, "getMessageFromIccEf - aborting, no icc card present."
invoke-static {v4, v6}, Landroid/telephony/Rlog;->d(Ljava/lang/String;Ljava/lang/String;)I
.line 56
const/4 v4, 0x0
monitor-exit v5
.line 68
:goto_0
return-object v4
.line 59
:cond_0
const/16 v4, 0x6f3c
invoke-virtual {v1, v4, p1, v3}, Lcom/android/internal/telephony/uicc/IccFileHandler;->loadEFLinearFixed(IILandroid/os/Message;)V
:try_end_0
.catchall {:try_start_0 .. :try_end_0} :catchall_0
.line 62
:try_start_1
iget-object v4, v2, Lcom/htc/internal/telephony/HtcSmsUtilsHandler;->mLock:Ljava/lang/Object;
invoke-virtual {v4}, Ljava/lang/Object;->wait()V
:try_end_1
.catch Ljava/lang/InterruptedException; {:try_start_1 .. :try_end_1} :catch_0
.catchall {:try_start_1 .. :try_end_1} :catchall_0
.line 66
:goto_1
:try_start_2
monitor-exit v5
:try_end_2
.catchall {:try_start_2 .. :try_end_2} :catchall_0
.line 68
iget-object v4, v2, Lcom/htc/internal/telephony/HtcSmsUtilsHandler;->mSimSms:[B
goto :goto_0
.line 63
:catch_0
move-exception v0
.line 64
.local v0, "e":Ljava/lang/InterruptedException;
:try_start_3
const-string v4, "HtcSimSmsUtils"
const-string v6, "interrupted while trying to get Message from ICC"
invoke-static {v4, v6}, Landroid/telephony/Rlog;->d(Ljava/lang/String;Ljava/lang/String;)I
goto :goto_1
.line 66
.end local v0 # "e":Ljava/lang/InterruptedException;
.end local v1 # "fh":Lcom/android/internal/telephony/uicc/IccFileHandler;
.end local v3 # "response":Landroid/os/Message;
:catchall_0
move-exception v4
monitor-exit v5
:try_end_3
.catchall {:try_start_3 .. :try_end_3} :catchall_0
throw v4
.end method
| {
"content_hash": "50b896215db051830428912f556dbe5e",
"timestamp": "",
"source": "github",
"line_count": 613,
"max_line_length": 182,
"avg_line_length": 25.223491027732464,
"alnum_prop": 0.6659552451170612,
"repo_name": "shumxin/FlymeOS_A5DUG",
"id": "8fe02efbff40f74f28d2a487482eb003d11d797c",
"size": "15462",
"binary": false,
"copies": "1",
"ref": "refs/heads/lollipop-5.0",
"path": "telephony-common.jar.out/smali/com/htc/internal/telephony/HtcSimSmsUtils.smali",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "GLSL",
"bytes": "1500"
},
{
"name": "HTML",
"bytes": "96769"
},
{
"name": "Makefile",
"bytes": "13678"
},
{
"name": "Shell",
"bytes": "103420"
},
{
"name": "Smali",
"bytes": "189389087"
}
],
"symlink_target": ""
} |
package controllers
import javax.inject.Inject
import play.api.mvc._
import scala.concurrent.{ExecutionContext, Future}
import models.db
/**
*
* @author ponkotuy
* Date: 14/03/22.
*/
class RestSound @Inject()(implicit val ec: ExecutionContext) extends Controller {
import Common._
def ship(shipId: Int, soundId: Int) = Action.async {
Future {
db.ShipSound.findRandomBy(shipId, soundId) match {
case Some(record) => Ok(record.sound).as("audio/mp3")
case _ => NotFound(s"Not found sound (shipId=$shipId, soundId=$soundId)")
}
}
}
def shipHead(shipId: Int, soundId: Int) = Action.async {
Future {
db.ShipSound.findRandomBy(shipId, soundId) match {
case Some(record) => Ok(record.sound).as("audio/mp3")
case _ => NotFound(s"Not found sound (shipId=$shipId, soundId=$soundId)")
}
}
}
def shipKeyHead(shipKey: String, soundId: Int, version: Int) = Action.async {
Future {
db.ShipSound.findKey(shipKey, soundId, version) match {
case Some(record) => Ok(record.sound).as("audio/mp3")
case _ => NotFound(s"Not found sound (shipKey=$shipKey, soundId=$soundId, version=$version)")
}
}
}
def random() = actionAsync {
Ok(db.ShipSound.findRandom().sound).as("audio/mp3")
}
}
| {
"content_hash": "cded6289fe72f3e2b6cfdf87d1908f05",
"timestamp": "",
"source": "github",
"line_count": 47,
"max_line_length": 101,
"avg_line_length": 27.70212765957447,
"alnum_prop": 0.6428571428571429,
"repo_name": "kxbmap/MyFleetGirls",
"id": "004b6de3a8d256080a286ce728023a56b6e5dc82",
"size": "1302",
"binary": false,
"copies": "3",
"ref": "refs/heads/master",
"path": "server/app/controllers/RestSound.scala",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Batchfile",
"bytes": "758"
},
{
"name": "CSS",
"bytes": "1903"
},
{
"name": "CoffeeScript",
"bytes": "57041"
},
{
"name": "HTML",
"bytes": "137587"
},
{
"name": "Java",
"bytes": "9180"
},
{
"name": "JavaScript",
"bytes": "22570"
},
{
"name": "PLSQL",
"bytes": "1619"
},
{
"name": "Scala",
"bytes": "740538"
},
{
"name": "Shell",
"bytes": "1906"
}
],
"symlink_target": ""
} |
<?php
namespace Oro\Bundle\ApiBundle\Tests\Unit\Processor\Shared;
use Oro\Bundle\ApiBundle\Processor\Shared\EntityTypeFeatureCheck;
use Oro\Bundle\FeatureToggleBundle\Checker\FeatureChecker;
use Oro\Bundle\ApiBundle\Processor\Context;
use Symfony\Component\Security\Core\Exception\AccessDeniedException;
class EntityTypeFeatureCheckTest extends \PHPUnit_Framework_TestCase
{
/**
* @var FeatureChecker|\PHPUnit_Framework_MockObject_MockObject
*/
protected $featureChecker;
/**
* @var EntityTypeFeatureCheck
*/
protected $processor;
protected function setUp()
{
$this->featureChecker = $this->getMockBuilder(FeatureChecker::class)
->disableOriginalConstructor()
->getMock();
$this->processor = new EntityTypeFeatureCheck($this->featureChecker);
}
public function testProcessDisabled()
{
$className = 'TestClass';
$context = $this->getMockBuilder(Context::class)
->disableOriginalConstructor()
->getMock();
$context->expects($this->once())
->method('getClassName')
->willReturn($className);
$this->featureChecker->expects($this->once())
->method('isResourceEnabled')
->with($className, 'api_resources')
->willReturn(false);
$this->setExpectedException(AccessDeniedException::class);
$this->processor->process($context);
}
public function testProcessEnabled()
{
$className = 'TestClass';
$context = $this->getMockBuilder(Context::class)
->disableOriginalConstructor()
->getMock();
$context->expects($this->once())
->method('getClassName')
->willReturn($className);
$this->featureChecker->expects($this->once())
->method('isResourceEnabled')
->with($className, 'api_resources')
->willReturn(true);
$this->processor->process($context);
}
}
| {
"content_hash": "ecfb5ccf30d0dd04394b98109e546d69",
"timestamp": "",
"source": "github",
"line_count": 67,
"max_line_length": 77,
"avg_line_length": 30.059701492537314,
"alnum_prop": 0.6271102284011917,
"repo_name": "trustify/oroplatform",
"id": "0c4593899c7b6407765f6a503729511c85fec7f3",
"size": "2014",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/Oro/Bundle/ApiBundle/Tests/Unit/Processor/Shared/EntityTypeFeatureCheckTest.php",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "723257"
},
{
"name": "Cucumber",
"bytes": "8610"
},
{
"name": "HTML",
"bytes": "1597517"
},
{
"name": "JavaScript",
"bytes": "5554468"
},
{
"name": "PHP",
"bytes": "29776857"
}
],
"symlink_target": ""
} |
@interface UITableView (YAReusableCell)
- (id)dequeueReusableCellWithClass:(Class)aClass;
- (void)registerReuseCellClass:(Class)cellClass;
- (id)dequeueReusableHeaderFooterViewWithClass:(Class)aClass;
- (void)registerReuseHeaderFooterClass:(Class)aClass;
@end
| {
"content_hash": "44ba32cc8350b160f66bcc7fa6243c4c",
"timestamp": "",
"source": "github",
"line_count": 9,
"max_line_length": 61,
"avg_line_length": 29.22222222222222,
"alnum_prop": 0.8212927756653993,
"repo_name": "candyan/RepairMan",
"id": "1837bce66905937e84d2dca785e82eb772c9f40d",
"size": "371",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "Pods/YAUIKit/Source/Extend/UITableView/UITableView+YAReusableCell.h",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Objective-C",
"bytes": "10701"
},
{
"name": "Ruby",
"bytes": "531"
},
{
"name": "Swift",
"bytes": "65215"
}
],
"symlink_target": ""
} |
A deep learning method for predicting DNA methylation level of CpG sites from the sequence context, and predicting non-coding variants' effects on DNA methylation.
## Dependencies
+ [Docker](https://www.docker.com/)
+ GPU support
+ [NVIDIA-docker](https://github.com/NVIDIA/nvidia-docker)
+ [NVIDIA CUDA](https://developer.nvidia.com/cuda-zone): currently we support CUDA 7.0 and CUDA 8.0.
Note: You can run CpGenie on CPU by replacing all the `nvidia-docker` below with `docker`, but it will be extremely slow and thus highly not recommended.
## Predict DNA methylation level of CpG sites
+ Prepare a [FASTA](https://en.wikipedia.org/wiki/FASTA_format) file ([example](https://github.com/gifford-lab/CpGenie/blob/master/example/test.fa)) of the 1001 bp sequence context centered at the CpG you wish to predict, one sequence for one CpG. The 501 nucleotide should be the 'C' of the CpG.
+ Process the FASTA file and make predictions with 50 CpGenie models trained on RRBS datasets from ENCODE immortal cell lines.
```bash
docker pull haoyangz/cpgenie:CUDA_VER
mkdir -p OUTPUT_DIR
nvidia-docker run -u $(id -u) -v FASTA_FILE:/in.fa -v OUTPUT_DIR:/outdir \
--rm haoyangz/cpgenie:CUDA_VER python main.py ORDER -cpg_fa /in.fa -cpg_out /outdir
```
+ `CUDA_VER`: 'cuda7.0' or 'cuda8.0' depending on your NVIDIA driver version.
+ `FASTA_FILE`: the *absolute path* to the FASTA file of sequences to predict.
+ `OUTPUT_DIR`: the *absolute path* to the output directory, under which the prediction from each of the 50 CpGenie models will be saved.
+ `ORDER`: the following orders can be both used and seperated by space:
+ `-embed`: data preprocessing. The output will be saved under $OUTPUT_DIR/embedded.h5.
+ `-cpg`: make prediction and save under **$OUTPUT_DIR/CpGenie_pred**.
+ If you wish to only predict for a subset of the 50 CpGenie models
+ Download the 50 CpGenie models to a customized directory (e.g. YOUR_MODEL_DIR, an **absolute path**)
```bash
mkdir -p YOUR_MODEL_DIR
cd YOUR_MODEL_DIR
wget http://gerv.csail.mit.edu/CpGenie_models.tar.gz
tar -zxvf CpGenie_models.tar.gz
```
+ Keep only the models you want
+ Run the following instead:
```bash
docker pull haoyangz/cpgenie:CUDA_VER
mkdir -p OUTPUT_DIR
nvidia-docker run -u $(id -u) -v FASTA_FILE:/in.fa -v OUTPUT_DIR:/outdir \
-v YOUR_MODEL_DIR:/modeldir --rm haoyangz/cpgenie:CUDA_VER \
python main.py ORDER -cpg_fa /in.fa -cpg_out /outdir \
-modeltop /modeldir/models
```
## Predict the functional score of sequence variants
+ Prepare the variants to score in [VCF](http://www.1000genomes.org/wiki/Analysis/vcf4.0/) file ([example](https://github.com/gifford-lab/CpGenie/blob/master/example/test.vcf)).
+ Score each variant by the predicted impact on DNA methylation in 50 RRBS datasets.
```bash
docker pull haoyangz/cpgenie:CUDA_VER
mkdir -p OUTPUT_DIR
nvidia-docker run -u $(id -u) -v VCF_FILE:/in.vcf -v OUTPUT_DIR:/outdir \
--rm haoyangz/cpgenie:CUDA_VER python main.py ORDER -var_vcf /in.vcf -var_outdir /outdir
```
+ `CUDA_VER`: 'cuda7.0' or 'cuda8.0' depending on your NVIDIA driver version.
+ `VCF_FILE`: the *absolute path* to the VCF file to score.
+ `OUTPUT_DIR`: the *absolute path* to the output directory.
+ `ORDER`: the following orders can be both used and seperated by space:
+ `-var_prep`: find all CpG sites within 500 bp to each variant and prepare the right format under $OUTPUT_DIR/CpGenie_processed.
+ `-var_score`: make predictions on the data preprocessed in the previous step. For each variant, the predicted absolute change of the following metrics are generated for each of the 50 RRBS datasets, resulting in a 250-dim feature vector. The output will be saved as **$OUTPUT_DIR/CpGenie_var_pred**, where the first line is a header of feature names and then one line for each variant's 250-dim feature vector.
+ sum of methylation within 500 bp
+ max methylation within 500 bp
+ log odds of the max methylation within 500 bp
+ mean methylation within 500 bp
+ log odds of the mean methylation within 500 bp
| {
"content_hash": "a920832bd63e7c5eb85c01c1d0d342d2",
"timestamp": "",
"source": "github",
"line_count": 68,
"max_line_length": 414,
"avg_line_length": 60.76470588235294,
"alnum_prop": 0.7260406582768635,
"repo_name": "gifford-lab/CpGenie",
"id": "5974dbedce7879a992bd325ca30119675078d07b",
"size": "4142",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "README.md",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Dockerfile",
"bytes": "2853"
},
{
"name": "Python",
"bytes": "28998"
},
{
"name": "R",
"bytes": "9278"
}
],
"symlink_target": ""
} |
#include <UnitTest++.h>
#include "zone_stack.h"
namespace
{
struct Fixture
{
Lxt::ZoneStack zs;
};
Lxt::ZoneId alphaZoneId = Lxt::ZoneRegistry::DeclareZone( "alpha" );
Lxt::ZoneId betaZoneId = Lxt::ZoneRegistry::DeclareZone( "beta" );
Lxt::ZoneId gammaZoneId = Lxt::ZoneRegistry::DeclareZone( "gamma" );
}
namespace Lxt
{
TEST_FIXTURE( Fixture, ZoneStack_Default )
{
// This test cheats by "knowing" what the default zone id is
CHECK_EQUAL( ZoneId(ZR_DEFAULT_ZONE_ID), zs.CurrentZone() );
}
TEST( ZoneStack_Declared )
{
CHECK( alphaZoneId != 0 );
CHECK( alphaZoneId != betaZoneId );
CHECK( betaZoneId != gammaZoneId );
}
TEST( ZoneStack_ZoneNames )
{
CHECK_EQUAL( "Default Zone" , ZoneRegistry::GetZoneName( 0 ) );
CHECK_EQUAL( "alpha" , ZoneRegistry::GetZoneName( alphaZoneId ) );
CHECK_EQUAL( "beta" , ZoneRegistry::GetZoneName( betaZoneId ) );
CHECK_EQUAL( "gamma" , ZoneRegistry::GetZoneName( gammaZoneId ) );
}
TEST_FIXTURE( Fixture, ZoneStack_BeginEnd )
{
zs.EnterZone( alphaZoneId );
CHECK_EQUAL( alphaZoneId, zs.CurrentZone() );
zs.EnterZone( betaZoneId );
CHECK_EQUAL( betaZoneId, zs.CurrentZone() );
zs.EnterZone( gammaZoneId );
CHECK_EQUAL( gammaZoneId, zs.CurrentZone() );
zs.LeaveZone( gammaZoneId );
CHECK_EQUAL( betaZoneId, zs.CurrentZone() );
zs.LeaveZone( betaZoneId );
CHECK_EQUAL( alphaZoneId, zs.CurrentZone() );
zs.LeaveZone( alphaZoneId );
CHECK_EQUAL( 0, zs.CurrentZone() );
}
} | {
"content_hash": "d66e258890d022619936b70c9750cf21",
"timestamp": "",
"source": "github",
"line_count": 62,
"max_line_length": 69,
"avg_line_length": 24.14516129032258,
"alnum_prop": 0.6773547094188377,
"repo_name": "justinsaunders/luxatron",
"id": "22bf7443f58d6b02347c2b8dbf509d8432ff0dfa",
"size": "1644",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "lxt/core/unit_tests/test_zone_stack.cpp",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C",
"bytes": "14480"
},
{
"name": "C++",
"bytes": "265987"
},
{
"name": "Objective-C",
"bytes": "17609"
},
{
"name": "Objective-C++",
"bytes": "4761"
},
{
"name": "Roff",
"bytes": "3137"
}
],
"symlink_target": ""
} |
using testing::_;
using testing::Eq;
using testing::InSequence;
using testing::Invoke;
using testing::Return;
using testing::ReturnRef;
namespace Envoy {
namespace Extensions {
namespace NetworkFilters {
namespace ClientSslAuth {
TEST(ClientSslAuthAllowedPrincipalsTest, EmptyString) {
AllowedPrincipals principals;
principals.add("");
EXPECT_EQ(0UL, principals.size());
}
TEST(ClientSslAuthConfigTest, BadClientSslAuthConfig) {
std::string yaml = R"EOF(
stat_prefix: my_stat_prefix
auth_api_cluster: fake_cluster
ip_white_list:
- address_prefix: 192.168.3.0
prefix_len: 24
test: a
)EOF";
envoy::extensions::filters::network::client_ssl_auth::v3::ClientSSLAuth proto_config{};
EXPECT_THROW(TestUtility::loadFromYaml(yaml, proto_config), EnvoyException);
}
class ClientSslAuthFilterTest : public testing::Test {
protected:
ClientSslAuthFilterTest()
: request_(&cm_.async_client_), interval_timer_(new Event::MockTimer(&dispatcher_)),
api_(Api::createApiForTest(stats_store_)),
ssl_(std::make_shared<Ssl::MockConnectionInfo>()) {}
~ClientSslAuthFilterTest() override { tls_.shutdownThread(); }
void setup() {
std::string yaml = R"EOF(
auth_api_cluster: vpn
stat_prefix: vpn
ip_white_list:
- address_prefix: 1.2.3.4
prefix_len: 32
- address_prefix: '2001:abcd::'
prefix_len: 64
)EOF";
envoy::extensions::filters::network::client_ssl_auth::v3::ClientSSLAuth proto_config{};
TestUtility::loadFromYaml(yaml, proto_config);
EXPECT_CALL(cm_, get(Eq("vpn")));
setupRequest();
config_ =
ClientSslAuthConfig::create(proto_config, tls_, cm_, dispatcher_, stats_store_, random_);
createAuthFilter();
}
void createAuthFilter() {
filter_callbacks_.connection_.callbacks_.clear();
instance_ = std::make_unique<ClientSslAuthFilter>(config_);
instance_->initializeReadFilterCallbacks(filter_callbacks_);
// NOP currently.
instance_->onAboveWriteBufferHighWatermark();
instance_->onBelowWriteBufferLowWatermark();
}
void setupRequest() {
EXPECT_CALL(cm_, httpAsyncClientForCluster("vpn")).WillOnce(ReturnRef(cm_.async_client_));
EXPECT_CALL(cm_.async_client_, send_(_, _, _))
.WillOnce(
Invoke([this](Http::RequestMessagePtr&, Http::AsyncClient::Callbacks& callbacks,
const Http::AsyncClient::RequestOptions&) -> Http::AsyncClient::Request* {
callbacks_ = &callbacks;
return &request_;
}));
}
NiceMock<ThreadLocal::MockInstance> tls_;
Upstream::MockClusterManager cm_;
Event::MockDispatcher dispatcher_;
Http::MockAsyncClientRequest request_;
ClientSslAuthConfigSharedPtr config_;
NiceMock<Network::MockReadFilterCallbacks> filter_callbacks_;
std::unique_ptr<ClientSslAuthFilter> instance_;
Event::MockTimer* interval_timer_;
Http::AsyncClient::Callbacks* callbacks_;
Stats::TestUtil::TestStore stats_store_;
NiceMock<Random::MockRandomGenerator> random_;
Api::ApiPtr api_;
std::shared_ptr<Ssl::MockConnectionInfo> ssl_;
};
TEST_F(ClientSslAuthFilterTest, NoCluster) {
std::string yaml = R"EOF(
auth_api_cluster: bad_cluster
stat_prefix: bad_cluster
)EOF";
envoy::extensions::filters::network::client_ssl_auth::v3::ClientSSLAuth proto_config{};
TestUtility::loadFromYaml(yaml, proto_config);
EXPECT_CALL(cm_, get(Eq("bad_cluster"))).WillOnce(Return(nullptr));
EXPECT_THROW(
ClientSslAuthConfig::create(proto_config, tls_, cm_, dispatcher_, stats_store_, random_),
EnvoyException);
}
TEST_F(ClientSslAuthFilterTest, NoSsl) {
setup();
Buffer::OwnedImpl dummy("hello");
// Check no SSL case, multiple iterations.
EXPECT_CALL(filter_callbacks_.connection_, ssl()).WillOnce(Return(nullptr));
EXPECT_EQ(Network::FilterStatus::Continue, instance_->onNewConnection());
EXPECT_EQ(Network::FilterStatus::Continue, instance_->onData(dummy, false));
EXPECT_EQ(Network::FilterStatus::Continue, instance_->onData(dummy, false));
filter_callbacks_.connection_.raiseEvent(Network::ConnectionEvent::RemoteClose);
EXPECT_EQ(1U, stats_store_.counter("auth.clientssl.vpn.auth_no_ssl").value());
EXPECT_CALL(request_, cancel());
}
TEST_F(ClientSslAuthFilterTest, Ssl) {
InSequence s;
setup();
Buffer::OwnedImpl dummy("hello");
// Create a new filter for an SSL connection, with no backing auth data yet.
createAuthFilter();
ON_CALL(filter_callbacks_.connection_, ssl()).WillByDefault(Return(ssl_));
filter_callbacks_.connection_.remote_address_ =
std::make_shared<Network::Address::Ipv4Instance>("192.168.1.1");
std::string expected_sha_1("digest");
EXPECT_CALL(*ssl_, sha256PeerCertificateDigest()).WillOnce(ReturnRef(expected_sha_1));
EXPECT_CALL(filter_callbacks_.connection_, close(Network::ConnectionCloseType::NoFlush));
EXPECT_EQ(Network::FilterStatus::StopIteration, instance_->onNewConnection());
filter_callbacks_.connection_.raiseEvent(Network::ConnectionEvent::Connected);
filter_callbacks_.connection_.raiseEvent(Network::ConnectionEvent::RemoteClose);
// Respond.
EXPECT_CALL(*interval_timer_, enableTimer(_, _));
Http::ResponseMessagePtr message(new Http::ResponseMessageImpl(
Http::ResponseHeaderMapPtr{new Http::TestResponseHeaderMapImpl{{":status", "200"}}}));
message->body().add(api_->fileSystem().fileReadToEnd(TestEnvironment::runfilesPath(
"test/extensions/filters/network/client_ssl_auth/test_data/vpn_response_1.json")));
callbacks_->onSuccess(request_, std::move(message));
EXPECT_EQ(1U,
stats_store_
.gauge("auth.clientssl.vpn.total_principals", Stats::Gauge::ImportMode::NeverImport)
.value());
// Create a new filter for an SSL connection with an authorized cert.
createAuthFilter();
filter_callbacks_.connection_.remote_address_ =
std::make_shared<Network::Address::Ipv4Instance>("192.168.1.1");
std::string expected_sha_2("1b7d42ef0025ad89c1c911d6c10d7e86a4cb7c5863b2980abcbad1895f8b5314");
EXPECT_CALL(*ssl_, sha256PeerCertificateDigest()).WillOnce(ReturnRef(expected_sha_2));
EXPECT_EQ(Network::FilterStatus::StopIteration, instance_->onNewConnection());
EXPECT_CALL(filter_callbacks_, continueReading());
filter_callbacks_.connection_.raiseEvent(Network::ConnectionEvent::Connected);
EXPECT_EQ(Network::FilterStatus::Continue, instance_->onData(dummy, false));
EXPECT_EQ(Network::FilterStatus::Continue, instance_->onData(dummy, false));
filter_callbacks_.connection_.raiseEvent(Network::ConnectionEvent::RemoteClose);
// White list case.
createAuthFilter();
filter_callbacks_.connection_.remote_address_ =
std::make_shared<Network::Address::Ipv4Instance>("1.2.3.4");
EXPECT_EQ(Network::FilterStatus::StopIteration, instance_->onNewConnection());
EXPECT_CALL(filter_callbacks_, continueReading());
filter_callbacks_.connection_.raiseEvent(Network::ConnectionEvent::Connected);
EXPECT_EQ(Network::FilterStatus::Continue, instance_->onData(dummy, false));
EXPECT_EQ(Network::FilterStatus::Continue, instance_->onData(dummy, false));
filter_callbacks_.connection_.raiseEvent(Network::ConnectionEvent::RemoteClose);
// IPv6 White list case.
createAuthFilter();
filter_callbacks_.connection_.remote_address_ =
std::make_shared<Network::Address::Ipv6Instance>("2001:abcd::1");
EXPECT_EQ(Network::FilterStatus::StopIteration, instance_->onNewConnection());
EXPECT_CALL(filter_callbacks_, continueReading());
filter_callbacks_.connection_.raiseEvent(Network::ConnectionEvent::Connected);
EXPECT_EQ(Network::FilterStatus::Continue, instance_->onData(dummy, false));
EXPECT_EQ(Network::FilterStatus::Continue, instance_->onData(dummy, false));
filter_callbacks_.connection_.raiseEvent(Network::ConnectionEvent::RemoteClose);
EXPECT_EQ(1U, stats_store_.counter("auth.clientssl.vpn.update_success").value());
EXPECT_EQ(2U, stats_store_.counter("auth.clientssl.vpn.auth_ip_allowlist").value());
EXPECT_EQ(1U, stats_store_.counter("auth.clientssl.vpn.auth_digest_match").value());
EXPECT_EQ(1U, stats_store_.counter("auth.clientssl.vpn.auth_digest_no_match").value());
// Interval timer fires.
setupRequest();
interval_timer_->invokeCallback();
// Error response.
EXPECT_CALL(*interval_timer_, enableTimer(_, _));
message = std::make_unique<Http::ResponseMessageImpl>(
Http::ResponseHeaderMapPtr{new Http::TestResponseHeaderMapImpl{{":status", "503"}}});
callbacks_->onSuccess(request_, std::move(message));
// Interval timer fires.
setupRequest();
interval_timer_->invokeCallback();
// Parsing error
EXPECT_CALL(*interval_timer_, enableTimer(_, _));
message = std::make_unique<Http::ResponseMessageImpl>(
Http::ResponseHeaderMapPtr{new Http::TestResponseHeaderMapImpl{{":status", "200"}}});
message->body().add("bad_json");
callbacks_->onSuccess(request_, std::move(message));
// Interval timer fires.
setupRequest();
interval_timer_->invokeCallback();
// No response failure.
EXPECT_CALL(*interval_timer_, enableTimer(_, _));
callbacks_->onFailure(request_, Http::AsyncClient::FailureReason::Reset);
// Interval timer fires, cannot obtain async client.
EXPECT_CALL(cm_, httpAsyncClientForCluster("vpn")).WillOnce(ReturnRef(cm_.async_client_));
EXPECT_CALL(cm_.async_client_, send_(_, _, _))
.WillOnce(
Invoke([&](Http::RequestMessagePtr&, Http::AsyncClient::Callbacks& callbacks,
const Http::AsyncClient::RequestOptions&) -> Http::AsyncClient::Request* {
callbacks.onSuccess(
request_,
Http::ResponseMessagePtr{new Http::ResponseMessageImpl(Http::ResponseHeaderMapPtr{
new Http::TestResponseHeaderMapImpl{{":status", "503"}}})});
// Intentionally return nullptr (instead of request handle) to trigger a particular
// code path.
return nullptr;
}));
EXPECT_CALL(*interval_timer_, enableTimer(_, _));
interval_timer_->invokeCallback();
EXPECT_EQ(4U, stats_store_.counter("auth.clientssl.vpn.update_failure").value());
}
} // namespace ClientSslAuth
} // namespace NetworkFilters
} // namespace Extensions
} // namespace Envoy
| {
"content_hash": "d345c7a31aa9d7f9ddf6e11702e1b8cd",
"timestamp": "",
"source": "github",
"line_count": 250,
"max_line_length": 100,
"avg_line_length": 40.896,
"alnum_prop": 0.7124413145539906,
"repo_name": "envoyproxy/envoy-wasm",
"id": "beb76b7a997197ac6e6ef82fa70493d0ec71f3eb",
"size": "10890",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "test/extensions/filters/network/client_ssl_auth/client_ssl_auth_test.cc",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "C",
"bytes": "34272"
},
{
"name": "C++",
"bytes": "18917650"
},
{
"name": "Dockerfile",
"bytes": "245"
},
{
"name": "Emacs Lisp",
"bytes": "966"
},
{
"name": "Go",
"bytes": "695"
},
{
"name": "JavaScript",
"bytes": "1760"
},
{
"name": "Makefile",
"bytes": "1985"
},
{
"name": "PowerShell",
"bytes": "5725"
},
{
"name": "PureBasic",
"bytes": "472"
},
{
"name": "Python",
"bytes": "392412"
},
{
"name": "Rust",
"bytes": "3471"
},
{
"name": "Shell",
"bytes": "115198"
},
{
"name": "Starlark",
"bytes": "1134460"
},
{
"name": "Thrift",
"bytes": "748"
}
],
"symlink_target": ""
} |
/*
* Created on 21 五月 2015 ( Time 16:17:16 )
* Generated by Telosys Tools Generator ( version 2.1.0 )
*/
package com.dt.hippo.auto.model.base;
import java.io.Serializable;
import javax.validation.constraints.*;
import java.util.Date;
public class Targetlist extends com.dt.hippo.core.base.BaseBeanCommon implements Serializable {
private static final long serialVersionUID = 1L;
//----------------------------------------------------------------------
// ENTITY PRIMARY KEY ( BASED ON A SINGLE FIELD )
//----------------------------------------------------------------------
@NotNull
protected Long uid;
//----------------------------------------------------------------------
// ENTITY DATA FIELDS
//----------------------------------------------------------------------
protected Long targetid;
protected Integer type;
protected Long corpid;
protected Long targetvalue;
protected Date createdate;
protected Date modifydate;
@Size( max = 50 )
protected String createuser;
@Size( max = 50 )
protected String modifyuser;
protected Integer status;
@Size( max = 50 )
protected String platform;
//----------------------------------------------------------------------
// GETTER & SETTER FOR THE KEY FIELD
//----------------------------------------------------------------------
public void setUid( Long uid ) {
this.uid = uid ;
}
public Long getUid() {
return this.uid;
}
//----------------------------------------------------------------------
// GETTERS & SETTERS FOR FIELDS
//----------------------------------------------------------------------
public void setTargetid( Long targetid ) {
this.targetid = targetid;
}
public Long getTargetid() {
return this.targetid;
}
public void setType( Integer type ) {
this.type = type;
}
public Integer getType() {
return this.type;
}
public void setCorpid( Long corpid ) {
this.corpid = corpid;
}
public Long getCorpid() {
return this.corpid;
}
public void setTargetvalue( Long targetvalue ) {
this.targetvalue = targetvalue;
}
public Long getTargetvalue() {
return this.targetvalue;
}
public void setCreatedate( Date createdate ) {
this.createdate = createdate;
}
public Date getCreatedate() {
return this.createdate;
}
public void setModifydate( Date modifydate ) {
this.modifydate = modifydate;
}
public Date getModifydate() {
return this.modifydate;
}
public void setCreateuser( String createuser ) {
this.createuser = createuser;
}
public String getCreateuser() {
return this.createuser;
}
public void setModifyuser( String modifyuser ) {
this.modifyuser = modifyuser;
}
public String getModifyuser() {
return this.modifyuser;
}
public void setStatus( Integer status ) {
this.status = status;
}
public Integer getStatus() {
return this.status;
}
public void setPlatform( String platform ) {
this.platform = platform;
}
public String getPlatform() {
return this.platform;
}
//----------------------------------------------------------------------
// toString METHOD
//----------------------------------------------------------------------
public String toString() {
StringBuffer sb = new StringBuffer();
sb.append(uid);
sb.append("|");
sb.append(targetid);
sb.append("|");
sb.append(type);
sb.append("|");
sb.append(corpid);
sb.append("|");
sb.append(targetvalue);
sb.append("|");
sb.append(createdate);
sb.append("|");
sb.append(modifydate);
sb.append("|");
sb.append(createuser);
sb.append("|");
sb.append(modifyuser);
sb.append("|");
sb.append(status);
sb.append("|");
sb.append(platform);
return sb.toString();
}
}
| {
"content_hash": "07273a4f0241c9fe0ffc59d2b1c3390c",
"timestamp": "",
"source": "github",
"line_count": 175,
"max_line_length": 95,
"avg_line_length": 23.94857142857143,
"alnum_prop": 0.48365545215938915,
"repo_name": "cytochromewangdong/HippoStart",
"id": "2ab1f10cf1340e858ca7de3471d44b971493384a",
"size": "4195",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/main/java/com/dt/hippo/auto/model/base/Targetlist.java",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "203953"
},
{
"name": "HTML",
"bytes": "647372"
},
{
"name": "Java",
"bytes": "906680"
},
{
"name": "JavaScript",
"bytes": "3969828"
}
],
"symlink_target": ""
} |
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Members_Controller extends MY_Controller {
public function __construct()
{
parent::__construct();
$this->load->database();
$this->load->library(array('ion_auth','form_validation','breadcrumbs'));
$this->load->helper(array('url','language','form'));
$this->form_validation->set_error_delimiters($this->config->item('error_start_delimiter', 'ion_auth'), $this->config->item('error_end_delimiter', 'ion_auth'));
$this->lang->load('auth');
// $exception_url =array(
// 'index',
// 'members/logout',
//
// );
// if(in_array(uri_string(),$exception_url)== false){
// if($this->ion_auth->logged_in()==false){
// redirect('index/index');
// }
// }
}
}
| {
"content_hash": "d5cdfd60244d86695c37951834b9e3fd",
"timestamp": "",
"source": "github",
"line_count": 31,
"max_line_length": 171,
"avg_line_length": 30.483870967741936,
"alnum_prop": 0.5037037037037037,
"repo_name": "vbrainy/orriz",
"id": "3ede62dc23b5714c1b57bc82b5104f151c6fdac0",
"size": "945",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "mlm3/application/libraries/Members_Controller.php",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "ApacheConf",
"bytes": "1855"
},
{
"name": "CSS",
"bytes": "170613"
},
{
"name": "HTML",
"bytes": "11266"
},
{
"name": "JavaScript",
"bytes": "116106"
},
{
"name": "PHP",
"bytes": "4455090"
}
],
"symlink_target": ""
} |
package org.apache.camel.component.restlet;
import org.apache.camel.Exchange;
import org.apache.camel.Processor;
import org.apache.camel.builder.RouteBuilder;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.junit.Test;
public class RestletFaultTest extends RestletTestSupport {
@Override
protected RouteBuilder createRouteBuilder() {
return new RouteBuilder() {
@Override
public void configure() throws Exception {
from("restlet:http://localhost:" + portNum + "/users/{username}?restletMethod=POST").process(new Processor() {
public void process(Exchange exchange) throws Exception {
exchange.getOut().setFault(true);
exchange.getOut().setHeader(Exchange.HTTP_RESPONSE_CODE, "404");
exchange.getOut().setHeader(Exchange.CONTENT_TYPE, "text/plain");
exchange.getOut().setBody("Application fault");
}
});
}
};
}
@Test
public void testFaultResponse() throws Exception {
HttpResponse response = doExecute(new HttpPost("http://localhost:" + portNum + "/users/homer"));
assertHttpResponse(response, 404, "text/plain", "Application fault");
}
} | {
"content_hash": "be98392ee8bcd8a374b03095eb43baea",
"timestamp": "",
"source": "github",
"line_count": 37,
"max_line_length": 126,
"avg_line_length": 36.86486486486486,
"alnum_prop": 0.6202346041055719,
"repo_name": "kevinearls/camel",
"id": "3296093e310e371ce9a2c482a358fd431a8eb26b",
"size": "2167",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "components/camel-restlet/src/test/java/org/apache/camel/component/restlet/RestletFaultTest.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Apex",
"bytes": "6519"
},
{
"name": "Batchfile",
"bytes": "6512"
},
{
"name": "CSS",
"bytes": "30373"
},
{
"name": "Elm",
"bytes": "10852"
},
{
"name": "FreeMarker",
"bytes": "11410"
},
{
"name": "Groovy",
"bytes": "54390"
},
{
"name": "HTML",
"bytes": "190929"
},
{
"name": "Java",
"bytes": "70990879"
},
{
"name": "JavaScript",
"bytes": "90399"
},
{
"name": "Makefile",
"bytes": "513"
},
{
"name": "Python",
"bytes": "36"
},
{
"name": "Ruby",
"bytes": "4802"
},
{
"name": "Scala",
"bytes": "323982"
},
{
"name": "Shell",
"bytes": "23616"
},
{
"name": "Tcl",
"bytes": "4974"
},
{
"name": "Thrift",
"bytes": "6979"
},
{
"name": "XQuery",
"bytes": "546"
},
{
"name": "XSLT",
"bytes": "285105"
}
],
"symlink_target": ""
} |
/*
* Copyright 2011-2014, by Vladimir Kostyukov and Contributors.
*
* This file is part of la4j project (http://la4j.org)
*
* 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.
*
* Contributor(s): Daniel Renshaw
* Ewald Grusk
* Jakob Moellers
* Maxim Samoylov
* Miron Aseev
*/
package net.fec.openrq.util.linearalgebra.vector;
import static net.fec.openrq.util.linearalgebra.vector.ByteVectors.printVector;
import static net.fec.openrq.util.math.OctetOps.aDividedByB;
import static net.fec.openrq.util.math.OctetOps.aMinusB;
import static net.fec.openrq.util.math.OctetOps.aPlusB;
import static net.fec.openrq.util.math.OctetOps.aTimesB;
import java.util.Iterator;
import java.util.Random;
import net.fec.openrq.util.checking.Indexables;
import net.fec.openrq.util.linearalgebra.factory.Factory;
import net.fec.openrq.util.linearalgebra.io.ByteVectorIterator;
import net.fec.openrq.util.linearalgebra.matrix.ByteMatrix;
import net.fec.openrq.util.linearalgebra.vector.functor.VectorAccumulator;
import net.fec.openrq.util.linearalgebra.vector.functor.VectorFunction;
import net.fec.openrq.util.linearalgebra.vector.functor.VectorPredicate;
import net.fec.openrq.util.linearalgebra.vector.functor.VectorProcedure;
import net.fec.openrq.util.linearalgebra.vector.operation.VectorOperations;
public abstract class AbstractByteVector implements ByteVector {
private final int length;
private final Factory factory;
protected AbstractByteVector(Factory factory, int length) {
ensureLengthIsCorrect(length);
this.factory = factory;
this.length = length;
}
@Override
public final byte get(int i) {
Indexables.checkIndexBounds(i, length());
return safeGet(i);
}
protected abstract byte safeGet(int i);
@Override
public final void set(int i, byte value) {
Indexables.checkIndexBounds(i, length());
safeSet(i, value);
}
protected abstract void safeSet(int i, byte value);
@Override
public void swap(int i, int j) {
Indexables.checkIndexBounds(i, length());
Indexables.checkIndexBounds(j, length());
if (i != j) {
byte s = safeGet(i);
safeSet(i, safeGet(j));
safeSet(j, s);
}
}
@Override
public void clear() {
assign((byte)0);
}
@Override
public void assign(byte value) {
update(ByteVectors.asConstFunction(value));
}
@Override
public int length() {
return length;
}
@Override
public ByteVector add(byte value) {
return add(value, factory);
}
@Override
public ByteVector add(byte value, Factory factory) {
ensureFactoryIsNotNull(factory);
ByteVector result = blank(factory);
ByteVectorIterator it = iterator();
while (it.hasNext()) {
it.next();
result.set(it.index(), aPlusB(it.get(), value));
}
return result;
}
@Override
public void addInPlace(byte value) {
ByteVectorIterator it = iterator();
while (it.hasNext()) {
it.next();
it.set(aPlusB(it.get(), value));
}
}
@Override
public void addInPlace(int i, byte value) {
Indexables.checkIndexBounds(i, length());
set(i, aPlusB(get(i), value));
}
@Override
public ByteVector add(ByteVector vector) {
return add(vector, factory);
}
@Override
public ByteVector add(ByteVector vector, Factory factory) {
ensureFactoryIsNotNull(factory);
ensureArgumentIsNotNull(vector, "vector");
ensureVectorIsSimilar(vector);
return pipeTo(VectorOperations.ooPlaceVectorToVectorAddition(factory), vector);
}
@Override
public void addInPlace(ByteVector vector) {
ensureArgumentIsNotNull(vector, "vector");
ensureVectorIsSimilar(vector);
pipeTo(VectorOperations.inPlaceVectorToVectorAddition(), vector);
}
@Override
public void addInPlace(ByteVector vector, int fromIndex, int toIndex) {
ensureArgumentIsNotNull(vector, "vector");
ensureVectorIsSimilar(vector, fromIndex, toIndex);
pipeTo(VectorOperations.inPlaceVectorToVectorAddition(fromIndex, toIndex), vector);
}
@Override
public void addInPlace(byte multiplier, ByteVector vector) {
ensureArgumentIsNotNull(vector, "vector");
ensureVectorIsSimilar(vector);
if (multiplier != 0) {
pipeTo(VectorOperations.inPlaceVectorToVectorAdditionWithMultiplier(multiplier), vector);
}
}
@Override
public void addInPlace(byte multiplier, ByteVector vector, int fromIndex, int toIndex) {
ensureArgumentIsNotNull(vector, "vector");
ensureVectorIsSimilar(vector, fromIndex, toIndex);
if (multiplier != 0) {
pipeTo(VectorOperations.inPlaceVectorToVectorAdditionWithMultiplier(multiplier, fromIndex, toIndex), vector);
}
}
@Override
public ByteVector multiply(byte value) {
return multiply(value, factory);
}
@Override
public ByteVector multiply(byte value, Factory factory) {
ensureFactoryIsNotNull(factory);
ByteVector result = blank(factory);
if (value != 0) {
ByteVectorIterator it = iterator();
while (it.hasNext()) {
it.next();
result.set(it.index(), aTimesB(value, it.get()));
}
}
return result;
}
@Override
public void multiplyInPlace(byte value) {
if (value == 0) {
clear();
}
else {
ByteVectorIterator it = iterator();
while (it.hasNext()) {
it.next();
it.set(aTimesB(it.get(), value));
}
}
}
@Override
public ByteVector hadamardProduct(ByteVector vector) {
return hadamardProduct(vector, factory);
}
@Override
public ByteVector hadamardProduct(ByteVector vector, Factory factory) {
ensureFactoryIsNotNull(factory);
ensureArgumentIsNotNull(vector, "vector");
ensureVectorIsSimilar(vector);
return pipeTo(VectorOperations.ooPlaceHadamardProduct(factory), vector);
}
@Override
public ByteVector multiply(ByteMatrix matrix) {
return multiply(matrix, factory);
}
@Override
public ByteVector multiply(ByteMatrix matrix, Factory factory) {
ensureFactoryIsNotNull(factory);
ensureArgumentIsNotNull(matrix, "matrix");
if (length != matrix.rows()) {
fail("Wrong matrix dimensions: " + matrix.rows() + "x" + matrix.columns() +
". Should be: " + length + "x_.");
}
ByteVector result = factory.createVector(matrix.columns());
for (int j = 0; j < matrix.columns(); j++) {
byte acc = 0;
ByteVectorIterator it = iterator();
while (it.hasNext()) {
it.next();
final byte prod = aTimesB(it.get(), matrix.get(it.index(), j));
acc = aPlusB(acc, prod);
}
result.set(j, acc);
}
return result;
}
@Override
public ByteVector multiply(ByteMatrix matrix, int fromIndex, int toIndex) {
return multiply(matrix, fromIndex, toIndex, factory);
}
@Override
public ByteVector multiply(ByteMatrix matrix, int fromIndex, int toIndex, Factory factory) {
ensureFactoryIsNotNull(factory);
ensureArgumentIsNotNull(matrix, "matrix");
Indexables.checkFromToBounds(fromIndex, toIndex, length());
if ((toIndex - fromIndex) != matrix.rows()) {
fail("Wrong matrix dimensions: " + matrix.rows() + "x" + matrix.columns() +
". Should be: " + (toIndex - fromIndex) + "x_.");
}
ByteVector result = factory.createVector(matrix.columns());
for (int j = 0; j < matrix.columns(); j++) {
byte acc = 0;
ByteVectorIterator it = iterator(fromIndex, toIndex);
while (it.hasNext()) {
it.next();
final byte prod = aTimesB(it.get(), matrix.get(it.index() - fromIndex, j));
acc = aPlusB(acc, prod);
}
result.set(j, acc);
}
return result;
}
@Override
public ByteVector subtract(byte value) {
return subtract(value, factory);
}
@Override
public ByteVector subtract(byte value, Factory factory) {
ensureFactoryIsNotNull(factory);
ByteVector result = blank(factory);
ByteVectorIterator it = iterator();
while (it.hasNext()) {
it.next();
result.set(it.index(), aMinusB(it.get(), value));
}
return result;
}
@Override
public ByteVector subtract(ByteVector vector) {
return subtract(vector, factory);
}
@Override
public ByteVector subtract(ByteVector vector, Factory factory) {
ensureFactoryIsNotNull(factory);
ensureArgumentIsNotNull(vector, "vector");
ensureVectorIsSimilar(vector);
return pipeTo(VectorOperations.ooPlaceVectorFromVectorSubtraction(factory), vector);
}
@Override
public void subtractInPlace(byte value) {
ByteVectorIterator it = iterator();
while (it.hasNext()) {
it.next();
it.set(aMinusB(it.get(), value));
}
}
@Override
public void subtractInPlace(ByteVector vector) {
ensureArgumentIsNotNull(vector, "vector");
ensureVectorIsSimilar(vector);
pipeTo(VectorOperations.inPlaceVectorFromVectorSubtraction(), vector);
}
@Override
public ByteVector divide(byte value) {
return divide(value, factory);
}
@Override
public ByteVector divide(byte value, Factory factory) {
ensureFactoryIsNotNull(factory);
ByteVector result = blank(factory);
ByteVectorIterator it = iterator();
while (it.hasNext()) {
it.next();
result.set(it.index(), aDividedByB(it.get(), value));
}
return result;
}
@Override
public void divideInPlace(byte value) {
if (value != 1) {
ByteVectorIterator it = iterator();
while (it.hasNext()) {
it.next();
it.set(aDividedByB(it.get(), value));
}
}
}
@Override
public void divideInPlace(byte value, int fromIndex, int toIndex) {
Indexables.checkFromToBounds(fromIndex, toIndex, length());
if (value != 1) {
ByteVectorIterator it = iterator(fromIndex, toIndex);
while (it.hasNext()) {
it.next();
it.set(aDividedByB(it.get(), value));
}
}
}
@Override
public byte product() {
return fold(ByteVectors.asProductAccumulator((byte)1));
}
@Override
public byte sum() {
return fold(ByteVectors.asSumAccumulator((byte)0));
}
@Override
public ByteVector blank() {
return blank(factory);
}
@Override
public ByteVector blank(Factory factory) {
ensureFactoryIsNotNull(factory);
return factory.createVector(length);
}
@Override
public ByteVector copy() {
return copy(factory);
}
@Override
public ByteVector copy(Factory factory) {
ensureFactoryIsNotNull(factory);
return factory.createVector(this);
}
@Override
public ByteVector resize(int length) {
return resize(length, factory);
}
@Override
public ByteVector resize(int length, Factory factory) {
ensureFactoryIsNotNull(factory);
ByteVector result = factory.createVector(length);
for (int i = 0; i < Math.min(length, this.length); i++) {
result.set(i, safeGet(i));
}
return result;
}
@Override
public ByteVector shuffle() {
return shuffle(factory);
}
@Override
public ByteVector shuffle(Factory factory) {
ensureFactoryIsNotNull(factory);
ByteVector result = copy(factory);
// Conduct Fisher-Yates shuffle
Random rnd = new Random();
for (int i = 0; i < length; i++) {
int ii = rnd.nextInt(length - i) + i;
result.swap(i, ii);
}
return result;
}
@Override
public ByteVector sliceLeft(int until) {
return slice(0, until, factory);
}
@Override
public ByteVector sliceLeft(int until, Factory factory) {
return slice(0, until, factory);
}
@Override
public ByteVector sliceRight(int from) {
return slice(from, length, factory);
}
@Override
public ByteVector sliceRight(int from, Factory factory) {
return slice(from, length, factory);
}
@Override
public ByteVector slice(int from, int until) {
return slice(from, until, factory);
}
@Override
public ByteVector slice(int from, int until, Factory factory) {
Indexables.checkFromToBounds(from, until, length());
ensureFactoryIsNotNull(factory);
ByteVector result = factory.createVector(until - from);
for (int i = from; i < until; i++) {
result.set(i - from, safeGet(i));
}
return result;
}
@Override
public ByteVector select(int[] indices) {
return select(indices, factory);
}
@Override
public ByteVector select(int[] indices, Factory factory) {
int newLength = indices.length;
if (newLength == 0) {
fail("No elements selected.");
}
ByteVector result = factory.createVector(newLength);
for (int i = 0; i < newLength; i++) {
result.set(i, get(indices[i])); // use normal get for index bounds check
}
return result;
}
@Override
public Factory factory() {
return factory;
}
@Override
public boolean isZeroAt(int i) {
Indexables.checkIndexBounds(i, length());
return safeGet(i) == 0;
}
@Override
public boolean nonZeroAt(int i) {
Indexables.checkIndexBounds(i, length());
return safeGet(i) != 0;
}
@Override
public int nonZeros() {
ByteVectorIterator it = nonZeroIterator();
int nonZeros = 0;
while (it.hasNext()) {
it.next();
nonZeros++;
}
return nonZeros;
}
@Override
public int nonZeros(int fromIndex, int toIndex) {
ByteVectorIterator it = nonZeroIterator(fromIndex, toIndex);
int nonZeros = 0;
while (it.hasNext()) {
it.next();
nonZeros++;
}
return nonZeros;
}
@Override
public int[] nonZeroPositions() {
int[] positions = new int[nonZeros()];
ByteVectorIterator it = nonZeroIterator();
int i = 0;
while (it.hasNext()) {
it.next();
positions[i++] = it.index();
}
return positions;
}
@Override
public int[] nonZeroPositions(int fromIndex, int toIndex) {
int[] positions = new int[nonZeros(fromIndex, toIndex)];
ByteVectorIterator it = nonZeroIterator(fromIndex, toIndex);
int i = 0;
while (it.hasNext()) {
it.next();
positions[i++] = it.index();
}
return positions;
}
@Override
public void each(VectorProcedure procedure) {
ByteVectorIterator it = iterator();
while (it.hasNext()) {
it.next();
procedure.apply(it.index(), it.get());
}
}
@Override
public void each(VectorProcedure procedure, int fromIndex, int toIndex) {
ByteVectorIterator it = iterator(fromIndex, toIndex);
while (it.hasNext()) {
it.next();
procedure.apply(it.index(), it.get());
}
}
@Override
public void eachNonZero(VectorProcedure procedure) {
ByteVectorIterator it = nonZeroIterator();
while (it.hasNext()) {
it.next();
procedure.apply(it.index(), it.get());
}
}
@Override
public void eachNonZero(VectorProcedure procedure, int fromIndex, int toIndex) {
ByteVectorIterator it = nonZeroIterator(fromIndex, toIndex);
while (it.hasNext()) {
it.next();
procedure.apply(it.index(), it.get());
}
}
@Override
public void update(int i, VectorFunction function) {
Indexables.checkIndexBounds(i, length());
safeSet(i, function.evaluate(i, safeGet(i)));
}
@Override
public void update(VectorFunction function) {
ByteVectorIterator it = iterator();
while (it.hasNext()) {
it.next();
it.set(function.evaluate(it.index(), it.get()));
}
}
@Override
public void update(VectorFunction function, int fromIndex, int toIndex) {
ByteVectorIterator it = iterator(fromIndex, toIndex);
while (it.hasNext()) {
it.next();
it.set(function.evaluate(it.index(), it.get()));
}
}
@Override
public void updateNonZero(VectorFunction function) {
ByteVectorIterator it = nonZeroIterator();
while (it.hasNext()) {
it.next();
it.set(function.evaluate(it.index(), it.get()));
}
}
@Override
public void updateNonZero(VectorFunction function, int fromIndex, int toIndex) {
ByteVectorIterator it = nonZeroIterator(fromIndex, toIndex);
while (it.hasNext()) {
it.next();
it.set(function.evaluate(it.index(), it.get()));
}
}
@Override
public byte fold(VectorAccumulator accumulator) {
each(ByteVectors.asAccumulatorProcedure(accumulator));
return accumulator.accumulate();
}
@Override
public byte foldNonZero(VectorAccumulator accumulator) {
eachNonZero(ByteVectors.asAccumulatorProcedure(accumulator));
return accumulator.accumulate();
}
@Override
public boolean is(VectorPredicate predicate) {
boolean result = true;
ByteVectorIterator it = iterator();
while (it.hasNext()) {
it.next();
result = result && predicate.test(it.index(), it.get());
}
return result;
}
@Override
public final boolean non(VectorPredicate predicate) {
return !is(predicate);
}
@Override
public ByteMatrix toRowMatrix() {
return toRowMatrix(factory);
}
@Override
public ByteMatrix toRowMatrix(Factory factory) {
ByteMatrix result = factory.createMatrix(1, length);
result.setRow(0, this);
return result;
}
@Override
public ByteMatrix toColumnMatrix() {
return toColumnMatrix(factory);
}
@Override
public ByteMatrix toColumnMatrix(Factory factory) {
ByteMatrix result = factory.createMatrix(length, 1);
result.setColumn(0, this);
return result;
}
@Override
public byte max() {
return fold(ByteVectors.mkMaxAccumulator());
}
@Override
public byte min() {
return fold(ByteVectors.mkMinAccumulator());
}
@Override
public ByteVectorIterator iterator() {
return new VectorIterator(0, length());
}
@Override
public ByteVectorIterator iterator(int fromIndex, int toIndex) {
Indexables.checkFromToBounds(fromIndex, toIndex, length());
return new VectorIterator(fromIndex, toIndex);
}
private final class VectorIterator extends ByteVectorIterator {
private int i;
private final int end;
/*
* requires valid indexes
*/
VectorIterator(int fromIndex, int toIndex) {
super(toIndex - fromIndex);
this.i = fromIndex - 1;
this.end = toIndex;
}
@Override
public int index() {
return i;
}
@Override
public byte get() {
return safeGet(i);
}
@Override
public void set(byte value) {
safeSet(i, value);
}
@Override
public boolean hasNext() {
return i + 1 < end;
}
@Override
public Byte next() {
i++;
return get();
}
}
@Override
public ByteVectorIterator nonZeroIterator() {
return new NonZeroVectorIterator(0, length());
}
@Override
public ByteVectorIterator nonZeroIterator(int fromIndex, int toIndex) {
Indexables.checkFromToBounds(fromIndex, toIndex, length());
return new NonZeroVectorIterator(fromIndex, toIndex);
}
private final class NonZeroVectorIterator extends ByteVectorIterator {
private int index;
private final int end;
private int nextIndex;
private boolean hasNext;
/*
* Requires valid indices.
*/
protected NonZeroVectorIterator(int fromIndex, int toIndex) {
super(toIndex - fromIndex);
this.index = -1;
this.end = toIndex;
this.nextIndex = fromIndex;
findNextNonZero(); // this method initializes nextIndex and hasNext properly
}
@Override
public int index() {
return index;
}
@Override
public byte get() {
return safeGet(index);
}
@Override
public void set(byte value) {
safeSet(index, value);
}
@Override
public Byte next() {
index = nextIndex - 1;
findNextNonZero();
return get();
}
@Override
public boolean hasNext() {
return hasNext;
}
private void findNextNonZero() {
hasNext = false;
while (nextIndex < end) {
hasNext = nonZeroAt(nextIndex++);
if (hasNext) {
break;
}
}
}
}
@Override
public Iterable<Byte> skipZeros() {
return new Iterable<Byte>() {
@Override
public Iterator<Byte> iterator() {
return nonZeroIterator();
}
};
}
@Override
public int hashCode() {
int result = 17;
ByteVectorIterator it = iterator();
while (it.hasNext()) {
it.next();
long value = it.get();
result = 37 * result + (int)(value ^ (value >>> 32));
}
return result;
}
@Override
public boolean equals(Object object) {
if (this == object) {
return true;
}
// instanceof also checks for null
if (!(object instanceof ByteVector)) {
return false;
}
ByteVector vector = (ByteVector)object;
if (length != vector.length()) {
return false;
}
boolean result = true;
for (int i = 0; result && i < length; i++) {
result = safeGet(i) == vector.get(i);
}
return result;
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
printVector(this, sb);
return sb.toString();
}
protected void ensureFactoryIsNotNull(Factory factory) {
ensureArgumentIsNotNull(factory, "factory");
}
protected void ensureLengthIsCorrect(int length) {
if (length < 0) {
fail("Wrong vector length: " + length);
}
if (length == Integer.MAX_VALUE) {
fail("Wrong vector length: use 'Integer.MAX_VALUE - 1' instead.");
}
}
protected void ensureVectorIsSimilar(ByteVector that) {
if (length != that.length()) {
fail("Wong vector length: " + that.length() + ". Should be: " + length + ".");
}
}
protected void ensureVectorIsSimilar(ByteVector that, int fromIndex, int toIndex) {
Indexables.checkFromToBounds(fromIndex, toIndex, this.length());
Indexables.checkFromToBounds(fromIndex, toIndex, that.length());
}
protected void ensureArgumentIsNotNull(Object argument, String name) {
if (argument == null) {
fail("Bad argument: \"" + name + "\" is 'null'.");
}
}
protected void fail(String message) {
throw new IllegalArgumentException(message);
}
}
| {
"content_hash": "44d1c1a7383df8b61afd91cd3ce73544",
"timestamp": "",
"source": "github",
"line_count": 1073,
"max_line_length": 121,
"avg_line_length": 23.59645852749301,
"alnum_prop": 0.5854891583395869,
"repo_name": "openrq-team/OpenRQ",
"id": "580843d844c0eb080c0dee92ef381791ff11a751",
"size": "25912",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "src/main/net/fec/openrq/util/linearalgebra/vector/AbstractByteVector.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "11628"
},
{
"name": "Java",
"bytes": "1523709"
}
],
"symlink_target": ""
} |
<?xml version="1.0" encoding="utf-8"?>
<!-- File created by the Android Action Bar Style Generator
Copyright (C) 2011 The Android Open Source Project
Copyright (C) 2012 readyState Software Ltd
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.
-->
<resources>
<style name="Theme.My_actionbar" parent="@style/Theme.AppCompat.Light.DarkActionBar">
<item name="android:actionBarItemBackground">@drawable/selectable_background_my_actionbar</item>
<item name="android:popupMenuStyle">@style/PopupMenu.My_actionbar</item>
<item name="android:dropDownListViewStyle">@style/DropDownListView.My_actionbar</item>
<item name="android:actionBarTabStyle">@style/ActionBarTabStyle.My_actionbar</item>
<item name="android:actionDropDownStyle">@style/DropDownNav.My_actionbar</item>
<item name="android:actionBarStyle">@style/ActionBar.Solid.My_actionbar</item>
<item name="android:actionModeBackground">@drawable/cab_background_top_my_actionbar</item>
<item name="android:actionModeSplitBackground">@drawable/cab_background_bottom_my_actionbar</item>
<item name="android:actionModeCloseButtonStyle">@style/ActionButton.CloseMode.My_actionbar</item>
<!-- Light.DarkActionBar specific -->
<item name="android:actionBarWidgetTheme">@style/Theme.My_actionbar.Widget</item>
</style>
<style name="ActionBar.Solid.My_actionbar" parent="@style/Widget.AppCompat.Light.ActionBar.Solid.Inverse">
<item name="android:background">@drawable/ab_solid_my_actionbar</item>
<item name="android:backgroundStacked">@drawable/ab_stacked_solid_my_actionbar</item>
<item name="android:backgroundSplit">@drawable/ab_bottom_solid_my_actionbar</item>
<item name="android:progressBarStyle">@style/ProgressBar.My_actionbar</item>
</style>
<style name="ActionBar.Transparent.My_actionbar" parent="@style/Widget.AppCompat.ActionBar">
<item name="android:background">@drawable/ab_transparent_my_actionbar</item>
<item name="android:progressBarStyle">@style/ProgressBar.My_actionbar</item>
</style>
<!-- this style is only referenced in a Light.DarkActionBar based theme -->
<style name="Theme.My_actionbar.Widget" parent="@style/Theme.AppCompat">
<item name="android:popupMenuStyle">@style/PopupMenu.My_actionbar</item>
<item name="android:dropDownListViewStyle">@style/DropDownListView.My_actionbar</item>
</style>
</resources> | {
"content_hash": "1ccc1dedf93ec8ee1eecafb1ee6c042b",
"timestamp": "",
"source": "github",
"line_count": 56,
"max_line_length": 110,
"avg_line_length": 54.160714285714285,
"alnum_prop": 0.7200791295746786,
"repo_name": "NateshR/TaskTable",
"id": "bae8d5c13ecf640b2735cd064afb983e06400e30",
"size": "3033",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "res/values-v14/styles_my_actionbar.xml",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Java",
"bytes": "435275"
}
],
"symlink_target": ""
} |
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://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.9.1"/>
<title>V8 API Reference Guide for node.js v0.1.31: v8::Exception 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>
<script type="text/javascript">
$(document).ready(function() { init_search(); });
</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 style="padding-left: 0.5em;">
<div id="projectname">V8 API Reference Guide for node.js v0.1.31
</div>
</td>
</tr>
</tbody>
</table>
</div>
<!-- end header part -->
<!-- Generated by Doxygen 1.8.9.1 -->
<script type="text/javascript">
var searchBox = new SearchBox("searchBox", "search",false,'Search');
</script>
<div id="navrow1" class="tabs">
<ul class="tablist">
<li><a href="index.html"><span>Main Page</span></a></li>
<li><a href="namespaces.html"><span>Namespaces</span></a></li>
<li class="current"><a href="annotated.html"><span>Classes</span></a></li>
<li><a href="files.html"><span>Files</span></a></li>
<li><a href="examples.html"><span>Examples</span></a></li>
<li>
<div id="MSearchBox" class="MSearchBoxInactive">
<span class="left">
<img id="MSearchSelect" src="search/mag_sel.png"
onmouseover="return searchBox.OnSearchSelectShow()"
onmouseout="return searchBox.OnSearchSelectHide()"
alt=""/>
<input type="text" id="MSearchField" value="Search" accesskey="S"
onfocus="searchBox.OnSearchFieldFocus(true)"
onblur="searchBox.OnSearchFieldFocus(false)"
onkeyup="searchBox.OnSearchFieldChange(event)"/>
</span><span class="right">
<a id="MSearchClose" href="javascript:searchBox.CloseResultsWindow()"><img id="MSearchCloseImg" border="0" src="search/close.png" alt=""/></a>
</span>
</div>
</li>
</ul>
</div>
<div id="navrow2" class="tabs2">
<ul class="tablist">
<li><a href="annotated.html"><span>Class List</span></a></li>
<li><a href="classes.html"><span>Class Index</span></a></li>
<li><a href="hierarchy.html"><span>Class Hierarchy</span></a></li>
<li><a href="functions.html"><span>Class Members</span></a></li>
</ul>
</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 id="nav-path" class="navpath">
<ul>
<li class="navelem"><a class="el" href="namespacev8.html">v8</a></li><li class="navelem"><a class="el" href="classv8_1_1_exception.html">Exception</a></li> </ul>
</div>
</div><!-- top -->
<div class="header">
<div class="summary">
<a href="#pub-static-methods">Static Public Member Functions</a> |
<a href="classv8_1_1_exception-members.html">List of all members</a> </div>
<div class="headertitle">
<div class="title">v8::Exception Class Reference</div> </div>
</div><!--header-->
<div class="contents">
<p><code>#include <<a class="el" href="v8_8h_source.html">v8.h</a>></code></p>
<table class="memberdecls">
<tr class="heading"><td colspan="2"><h2 class="groupheader"><a name="pub-static-methods"></a>
Static Public Member Functions</h2></td></tr>
<tr class="memitem:a3ce2406b4aa50f8639450ec11baee26f"><td class="memItemLeft" align="right" valign="top"><a class="anchor" id="a3ce2406b4aa50f8639450ec11baee26f"></a>
static <a class="el" href="classv8_1_1_local.html">Local</a>< <a class="el" href="classv8_1_1_value.html">Value</a> > </td><td class="memItemRight" valign="bottom"><b>RangeError</b> (<a class="el" href="classv8_1_1_handle.html">Handle</a>< <a class="el" href="classv8_1_1_string.html">String</a> > message)</td></tr>
<tr class="separator:a3ce2406b4aa50f8639450ec11baee26f"><td class="memSeparator" colspan="2"> </td></tr>
<tr class="memitem:adef7d49c3370594fbc97ee68c3fcbf29"><td class="memItemLeft" align="right" valign="top"><a class="anchor" id="adef7d49c3370594fbc97ee68c3fcbf29"></a>
static <a class="el" href="classv8_1_1_local.html">Local</a>< <a class="el" href="classv8_1_1_value.html">Value</a> > </td><td class="memItemRight" valign="bottom"><b>ReferenceError</b> (<a class="el" href="classv8_1_1_handle.html">Handle</a>< <a class="el" href="classv8_1_1_string.html">String</a> > message)</td></tr>
<tr class="separator:adef7d49c3370594fbc97ee68c3fcbf29"><td class="memSeparator" colspan="2"> </td></tr>
<tr class="memitem:a938d1b571e9021121ad0f820c5e95114"><td class="memItemLeft" align="right" valign="top"><a class="anchor" id="a938d1b571e9021121ad0f820c5e95114"></a>
static <a class="el" href="classv8_1_1_local.html">Local</a>< <a class="el" href="classv8_1_1_value.html">Value</a> > </td><td class="memItemRight" valign="bottom"><b>SyntaxError</b> (<a class="el" href="classv8_1_1_handle.html">Handle</a>< <a class="el" href="classv8_1_1_string.html">String</a> > message)</td></tr>
<tr class="separator:a938d1b571e9021121ad0f820c5e95114"><td class="memSeparator" colspan="2"> </td></tr>
<tr class="memitem:a61645d9d6b46cf76f2a8eccfe7039b90"><td class="memItemLeft" align="right" valign="top"><a class="anchor" id="a61645d9d6b46cf76f2a8eccfe7039b90"></a>
static <a class="el" href="classv8_1_1_local.html">Local</a>< <a class="el" href="classv8_1_1_value.html">Value</a> > </td><td class="memItemRight" valign="bottom"><b>TypeError</b> (<a class="el" href="classv8_1_1_handle.html">Handle</a>< <a class="el" href="classv8_1_1_string.html">String</a> > message)</td></tr>
<tr class="separator:a61645d9d6b46cf76f2a8eccfe7039b90"><td class="memSeparator" colspan="2"> </td></tr>
<tr class="memitem:ae598e4b24cf37c9986b6ad1bed858aee"><td class="memItemLeft" align="right" valign="top"><a class="anchor" id="ae598e4b24cf37c9986b6ad1bed858aee"></a>
static <a class="el" href="classv8_1_1_local.html">Local</a>< <a class="el" href="classv8_1_1_value.html">Value</a> > </td><td class="memItemRight" valign="bottom"><b>Error</b> (<a class="el" href="classv8_1_1_handle.html">Handle</a>< <a class="el" href="classv8_1_1_string.html">String</a> > message)</td></tr>
<tr class="separator:ae598e4b24cf37c9986b6ad1bed858aee"><td class="memSeparator" colspan="2"> </td></tr>
</table>
<a name="details" id="details"></a><h2 class="groupheader">Detailed Description</h2>
<div class="textblock"><p>Create new error objects by calling the corresponding error object constructor with the message. </p>
</div><hr/>The documentation for this class was generated from the following file:<ul>
<li>deps/v8/include/<a class="el" href="v8_8h_source.html">v8.h</a></li>
</ul>
</div><!-- contents -->
<!-- start footer part -->
<hr class="footer"/><address class="footer"><small>
Generated on Tue Aug 11 2015 23:44:31 for V8 API Reference Guide for node.js v0.1.31 by  <a href="http://www.doxygen.org/index.html">
<img class="footer" src="doxygen.png" alt="doxygen"/>
</a> 1.8.9.1
</small></address>
</body>
</html>
| {
"content_hash": "cc07a97fd723d1c7f061ba017d37b753",
"timestamp": "",
"source": "github",
"line_count": 132,
"max_line_length": 337,
"avg_line_length": 61.78030303030303,
"alnum_prop": 0.6748007357449417,
"repo_name": "v8-dox/v8-dox.github.io",
"id": "bacf9526e8be9b7365189a1009a6363a58b13c2d",
"size": "8155",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "e0ecf4f/html/classv8_1_1_exception.html",
"mode": "33188",
"license": "mit",
"language": [],
"symlink_target": ""
} |
"""
pycclone.highlighters.pygments
------------------------------
pygment based code highlighther
"""
import os
import pygments
from pycclone.highlighters import BaseHighlighter
from pygments.lexers import get_lexer_by_name
from pygments.formatters import HtmlFormatter
class Highlighter(BaseHighlighter):
def __init__(self, **kwargs):
self.args = kwargs
self.formatter = HtmlFormatter(**self.args['formatter'])
def copy_static(self, outdir):
"""
Copies static files to the output directory
This is not called if outputting to stdout
"""
with open(os.path.join(outdir, 'pygments.css'), 'w') as f:
f.write(self.formatter.get_style_defs('.pygments'))
def highlight(self, code, language):
"""
Highlights a single chunk of code using the **Pygments** module.
kwargs is the dictionary `highlight_args` defined in `pycclone.json`
settings.
"""
lexer = get_lexer_by_name(language['name'], **self.args['lexer'])
return pygments.highlight(code, lexer, self.formatter)
| {
"content_hash": "8731f62590c80c230ba8ddeb31f69781",
"timestamp": "",
"source": "github",
"line_count": 37,
"max_line_length": 76,
"avg_line_length": 29.81081081081081,
"alnum_prop": 0.6436990027198549,
"repo_name": "kalhartt/pycclone",
"id": "63e66c8d3f50373a75a30df04153439cf7231ce9",
"size": "1103",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "pycclone/highlighters/hlt_pygments.py",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Python",
"bytes": "22562"
}
],
"symlink_target": ""
} |
function strEndOf(str, suffix){
var supposeIndex = str.length - suffix.length;
if(supposeIndex < 0)
return false;
return str.indexOf(suffix,supposeIndex) == supposeIndex;
}
function strEqualsIgnoreCase(s1, s2){
if(s1 == undefined){
return (s2 == undefined);
}
if(s2 == undefined)
return false;
return s1.toUpperCase() == s2.toUpperCase();
}
function arrayContains(array, str){
for(var i=0;i<array.length;++i){
if(array[i] == str)
return true;
}
return false;
} | {
"content_hash": "980ffb8a7fe6bf0e2b8454b865680dcf",
"timestamp": "",
"source": "github",
"line_count": 23,
"max_line_length": 57,
"avg_line_length": 21.956521739130434,
"alnum_prop": 0.6574257425742575,
"repo_name": "izenecloud/ijma",
"id": "45fabe68cccf4f9c220f63c8e3f108d48a31ddc2",
"size": "505",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "source/test_web/web/js/string.js",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "C",
"bytes": "7185854"
},
{
"name": "C++",
"bytes": "3955794"
},
{
"name": "CSS",
"bytes": "5961"
},
{
"name": "Java",
"bytes": "55334"
},
{
"name": "JavaScript",
"bytes": "41032"
},
{
"name": "Objective-C",
"bytes": "30568"
},
{
"name": "Perl",
"bytes": "14456"
},
{
"name": "Ruby",
"bytes": "11841"
},
{
"name": "Shell",
"bytes": "19741"
}
],
"symlink_target": ""
} |
class ElVfs::Command::ResizeImage < ElVfs::Command
register_in_connector :resize
end
| {
"content_hash": "cd3e609bc6e60f4242f7f7bd36f37d54",
"timestamp": "",
"source": "github",
"line_count": 3,
"max_line_length": 50,
"avg_line_length": 29,
"alnum_prop": 0.7816091954022989,
"repo_name": "openteam/el_vfs",
"id": "7d36aec43bb1f0c57349965bea4bcd1f7365b550",
"size": "87",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "lib/el_finder_api/el_vfs/command/resize_image.rb",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "JavaScript",
"bytes": "278063"
},
{
"name": "Ruby",
"bytes": "62931"
}
],
"symlink_target": ""
} |
require_relative '../spec_helper'
describe UserOrganization do
describe 'promoting a user to owner' do
include_context 'visualization creation helpers'
after(:all) do
stub_named_maps_calls
@organization.destroy_cascade if @organization
@owner = User.where(id: @owner.id).first
@owner.destroy if @owner
end
# See #3534: Quota trigger re-creation not done correctly when promoting user to org
it 'recreates existing tables triggers' do
User.any_instance.stubs(:create_in_central).returns(true)
User.any_instance.stubs(:update_in_central).returns(true)
@organization = Organization.new(quota_in_bytes: 1234567890, name: 'wadus', seats: 5).save
@owner = create_user(:quota_in_bytes => 524288000, :table_quota => 500)
table = create_random_table(@owner)
id = table.id
table.insert_row!({})
table.rows_counted.should == 1
owner_org = CartoDB::UserOrganization.new(@organization.id, @owner.id)
owner_org.promote_user_to_admin
@owner.reload
table = UserTable.where(id: id).first.service
table.insert_row!({})
table.rows_counted.should == 2
end
end
# See #5477 Error assigning as owner a user with non-cartodbfied tables
it 'can assign an owner user having non-cartodbfied tables' do
User.any_instance.stubs(:create_in_central).returns(true)
User.any_instance.stubs(:update_in_central).returns(true)
@organization = Organization.new(quota_in_bytes: 1234567890, name: 'non-cartodbfied-org', seats: 5).save
@owner = create_user(quota_in_bytes: 524288000, table_quota: 500)
@owner.in_database.run('create table no_cartodbfied_table (test integer)')
@owner.real_tables.count.should == 1
owner_org = CartoDB::UserOrganization.new(@organization.id, @owner.id)
owner_org.promote_user_to_admin
@owner.reload
@owner.real_tables.count.should == 1
end
end
| {
"content_hash": "b792d86e4655fc59d5c71aef8167f346",
"timestamp": "",
"source": "github",
"line_count": 54,
"max_line_length": 108,
"avg_line_length": 35.74074074074074,
"alnum_prop": 0.6911917098445596,
"repo_name": "nyimbi/cartodb",
"id": "97d2514b69f3fee7052e9e65a6b5d58685a90a79",
"size": "1930",
"binary": false,
"copies": "3",
"ref": "refs/heads/master",
"path": "spec/models/user_organization_spec.rb",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "CSS",
"bytes": "670278"
},
{
"name": "Game Maker Language",
"bytes": "182471"
},
{
"name": "HTML",
"bytes": "3094281"
},
{
"name": "JavaScript",
"bytes": "3268509"
},
{
"name": "Makefile",
"bytes": "9955"
},
{
"name": "PLpgSQL",
"bytes": "1233"
},
{
"name": "Python",
"bytes": "11060"
},
{
"name": "Ruby",
"bytes": "3185853"
},
{
"name": "Shell",
"bytes": "4956"
}
],
"symlink_target": ""
} |
class GithubTasks
def self.add_hook(org, repo_url)
group = Group.first :github_organization => org
if group.nil?
puts "Could not find organization: #{org}"
else
repo = repo_url.match(/github\.com\/([^\/]+\/[^\/]+)/)[1]
if repo.nil?
puts "Bad repo URL"
else
hooks_url = "https://api.github.com/repos/#{repo}/hooks"
response = RestClient.post hooks_url, GithubHelper.hook_payload(group.github_token).to_json, :authorization => "Bearer #{group.github_access_token}"
puts "Added hook to #{repo}"
puts response
end
end
end
def self.add_all_hooks
Account.all.each do |account|
account.groups.each do |group|
if group.github_access_token
continue = true
page = 1
while continue do
response = RestClient.get "https://api.github.com/orgs/#{group.github_organization}/repos?page=#{page}&per_page=100", :authorization => "Bearer #{group.github_access_token}"
repos = JSON.parse response
skip = false
repos.each do |repo|
# skip = false if repo["name"] == "Munin-Plugins"
# next if skip == true
puts "========================"
puts repo["name"]
overwrite = true
if overwrite
# Remove all existing hooks
json = RestClient.get repo["hooks_url"], :authorization => "Bearer #{group.github_access_token}"
hooks = JSON.parse json
hooks.each do |hook|
puts "Deleting #{hook["url"]}"
response = RestClient.delete hook["url"], :authorization => "Bearer #{group.github_access_token}"
#puts response
end
# Add the new hook
response = RestClient.post repo["hooks_url"], GithubHelper.hook_payload(group.github_token).to_json, :authorization => "Bearer #{group.github_access_token}"
puts "Added hook to #{repo['full_name']}"
puts response
else
# Check if the hook is already there
json = RestClient.get repo["hooks_url"], :authorization => "Bearer #{group.github_access_token}"
hooks = JSON.parse json
puts "Existing hooks: "
puts hooks
if hooks.select{|h| h['config']['url'] == hook_url}.length == 0
# Add the new hook
response = RestClient.post repo["hooks_url"], GithubHelper.hook_payload(group.github_token).to_json, :authorization => "Bearer #{group.github_access_token}"
puts response
end
end
# Find all forks of the repo and add the hook to them
# Will only have permission to add hooks if the repo is private
if repo['private']
response = RestClient.get "#{repo['url']}/forks", :authorization => "Bearer #{group.github_access_token}"
forks = JSON.parse response
if forks.length > 0
# Add the new hook
forks.each do |fork|
begin
response = RestClient.post fork["hooks_url"], GithubHelper.hook_payload(group.github_token).to_json, :authorization => "Bearer #{group.github_access_token}"
puts "Added hook to #{fork['full_name']}"
rescue
end
puts response
end
end
end
end
page = page + 1
continue = false if repos.length == 0
end #while
end
end #group
end #account
end
def self.find_forks
Account.all.each do |account|
account.groups.each do |group|
if group.github_access_token
org_repos = []
continue = true
page = 1
while continue do
response = RestClient.get "https://api.github.com/orgs/#{group.github_organization}/repos?page=#{page}&per_page=100", :authorization => "Bearer #{group.github_access_token}"
repos = JSON.parse response
skip = false
repos.each do |repo|
org_repos << repo
end
page = page + 1
continue = false if repos.length == 0
end #while
org_repos = org_repos.sort_by { |k| k['name'] }
# puts org_repos.map {|k| k["name"]}
puts "Found #{org_repos.length} repositories"
org_repos.each do |repo|
response = RestClient.get "https://api.github.com/repos/#{repo['full_name']}/forks", :authorization => "Bearer #{group.github_access_token}"
forks = JSON.parse response
if forks.length > 0
puts repo['name']
puts forks.map{ |k| " #{k['html_url']}" }.join("\n")
puts
end
end
end
end #group
end #account
end
end | {
"content_hash": "4792f761ed013a5784e3ec33e375bedd",
"timestamp": "",
"source": "github",
"line_count": 149,
"max_line_length": 185,
"avg_line_length": 34.18120805369127,
"alnum_prop": 0.5216964461024937,
"repo_name": "donereports/Done-Reports-API",
"id": "068c126a935e1ecf925196d012066261badef78a",
"size": "5093",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "lib/github_tasks.rb",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "HTML",
"bytes": "2875"
},
{
"name": "Ruby",
"bytes": "89245"
}
],
"symlink_target": ""
} |
# Using s2n
s2n is a C library, and is built using Make. To clone the latest
copy of s2n from git use:
```shell
git clone https://github.com/awslabs/s2n.git
cd s2n
```
## Building s2n with existing libcrypto
### make Instructions
To build s2n with an existing libcrypto installation, store its root folder in the
`LIBCRYPTO_ROOT` environment variable.
```shell
# /usr/local/ssl/lib should contain libcrypto.a
LIBCRYPTO_ROOT=/usr/local/ssl make
```
### CMake Instructions
Throughout this document, there are instructions for setting a `LIBCRYPTO_ROOT` environment variable, or setting install prefixes to `s2n/lib-crypto-root`. If you
are using CMake that step is unnecessary. Just follow the instructions here to use any build of libcrypto.
(Required): You need at least CMake version 3.0 to fully benefit from Modern CMake. See [this](https://www.youtube.com/watch?v=bsXLMQ6WgIk) for more information.
(Optional): Set the CMake variable `CMAKE_INSTALL_PREFIX` to the location libcrypto is installed to. If you do not,
the default installation on your machine will be used.
(Optional): Set the CMake variable `BUILD_SHARED_LIBS=ON` to build shared libraries. The default is static.
We recommend an out-of-source build. Suppose you have a directory `s2n` which contains the s2n source code. At the same level
we can create a directory called `s2n-build`
For example, we can build and install shared libs using ninja as our build system, and the system libcrypto implementation.
````shell
mkdir s2n-build
cd s2n-build
cmake ../s2n -DBUILD_SHARED_LIBS=ON -GNinja
ninja
ninja test
sudo ninja install
````
For another example, we can prepare an Xcode project using static libs using a libcrypto implementation in the directory `$HOME/s2n-user/builds/libcrypto-impl`.
````shell
mkdir s2n-build
cd s2n-build
cmake ../s2n -DCMAKE_INSTALL_PREFIX=$HOME/s2n-user/builds/libcrypto-impl -G "Xcode"
# now open the project in Xcode and build from there, or use the Xcode CLI
````
Or, for unix style vanilla builds:
````shell
mkdir s2n-build
cd s2n-build
cmake ../s2n
make
make test
sudo make install
````
### Consuming s2n via. CMake
s2n ships with modern CMake finder scripts if CMake is used for the build. To take advantage of this from your CMake script, all you need to do to compile and link against s2n in your project is:
````shell
find_package(s2n)
....
target_link_libraries(yourExecutableOrLibrary AWS::s2n)
````
And when invoking CMake for your project, do one of two things:
1. Set the `CMAKE_INSTALL_PREFIX` variable with the path to your s2n build.
2. If you have globally installed s2n, do nothing, it will automatically be found.
## Building s2n with OpenSSL-1.1.0
To build s2n with OpenSSL-1.1.0, do the following:
```shell
# We keep the build artifacts in the -build directory
cd libcrypto-build
# Download the latest version of OpenSSL
curl -LO https://www.openssl.org/source/openssl-1.1.0-latest.tar.gz
tar -xzvf openssl-1.1.0-latest.tar.gz
# Build openssl libcrypto (NOTE: check directory name 1.1.0-latest unpacked as)
cd openssl-1.1.0e
./config -fPIC no-shared \
no-md2 no-rc5 no-rfc3779 no-sctp no-ssl-trace no-zlib \
no-hw no-mdc2 no-seed no-idea enable-ec_nistp_64_gcc_128 no-camellia\
no-bf no-ripemd no-dsa no-ssl2 no-ssl3 no-capieng \
-DSSL_FORBID_ENULL -DOPENSSL_NO_DTLS1 -DOPENSSL_NO_HEARTBEATS \
--prefix=`pwd`/../../libcrypto-root/
make
make install
# Build s2n
cd ../../
make
```
# Note for 32-bit builds.
The previous instructions work fine with only a few tweaks to your config command. Example:
```shell
setarch i386 ./config -fPIC no-shared \
-m32 no-md2 no-rc5 no-rfc3779 no-sctp no-ssl-trace no-zlib \
no-hw no-mdc2 no-seed no-idea no-camellia\
no-bf no-ripemd no-dsa no-ssl2 no-ssl3 no-capieng \
-DSSL_FORBID_ENULL -DOPENSSL_NO_DTLS1 -DOPENSSL_NO_HEARTBEATS \
--prefix=`pwd`/../../libcrypto-root/
```
## Building s2n with OpenSSL-1.0.2
To build s2n with OpenSSL-1.0.2, do the following:
```shell
# We keep the build artifacts in the -build directory
cd libcrypto-build
# Download the latest version of OpenSSL
curl -LO https://www.openssl.org/source/openssl-1.0.2-latest.tar.gz
tar -xzvf openssl-1.0.2-latest.tar.gz
# Build openssl libcrypto (NOTE: check directory name 1.0.2-latest unpacked as)
cd openssl-1.0.2k
./config -fPIC no-shared no-libunbound no-gmp no-jpake no-krb5 \
no-md2 no-rc5 no-rfc3779 no-sctp no-ssl-trace no-store no-zlib \
no-hw no-mdc2 no-seed no-idea enable-ec-nistp_64_gcc_128 no-camellia\
no-bf no-ripemd no-dsa no-ssl2 no-ssl3 no-capieng \
-DSSL_FORBID_ENULL -DOPENSSL_NO_DTLS1 -DOPENSSL_NO_HEARTBEATS \
--prefix=`pwd`/../../libcrypto-root/
make depend
make
make install
# Build s2n
cd ../../
make
```
**Mac Users:** please replace "./config" with "./Configure darwin64-x86_64-cc".
## Building s2n with LibreSSL
To build s2n with LibreSSL, do the following:
```shell
# We keep the build artifacts in the -build directory
cd libcrypto-build
# Download the latest version of LibreSSL
curl -O http://ftp.openbsd.org/pub/OpenBSD/LibreSSL/libressl-x.y.z.tar.gz
tar -xzvf libressl-x.y.z.tar.gz
# Build LibreSSL's libcrypto
cd libressl-x.y.z
./configure --prefix=`pwd`/../../libcrypto-root/
make CFLAGS=-fPIC install
# Build s2n
cd ../../
make
```
once built, static and dynamic libraries for s2n will be available in the lib/
directory.
## Building s2n with BoringSSL
To build s2n with BoringSSL, you must check out a copy of the BoringSSL
directly via git. This procedure has been tested with
fb68d6c901b98ffe15b8890d00bc819bf44c5f01 of BoringSSL.
```shell
# We keep the build artifacts in the -build directory
cd libcrypto-build
# Clone BoringSSL
git clone https://boringssl.googlesource.com/boringssl
# Build BoringSSL
cd boringssl
mkdir build
cd build
cmake -DCMAKE_C_FLAGS="-fPIC" ../
make
# Copy the built library and includes
mkdir ../../../libcrypto-root/lib/
cp crypto/libcrypto.a ../../../libcrypto-root/lib/
cp -r ../include/ ../../../libcrypto-root/include
# Build s2n
cd ../../../
make
```
once built, static and dynamic libraries for s2n will be available in the lib/
directory.
## mlock() and system limits
Internally s2n uses mlock() to prevent memory from being swapped to disk. The
s2n build tests may fail in some environments where the default limit on locked
memory is too low. To check this limit, run:
```shell
ulimit -l
```
to raise the limit, consult the documentation for your platform.
### Disabling mlock()
To disable s2n's mlock behavior, run your application with the `S2N_DONT_MLOCK` environment variable set.
s2n also reads this for unit tests. Try `S2N_DONT_MLOCK=1 make` if you're having mlock failures during unit tests.
## client mode
At this time x509 certificate validation is undergoing further testing and client mode is
disabled as a precaution. To enable client mode for testing and development,
set the **S2N_ENABLE_CLIENT_MODE** environment variable.
```shell
export S2N_ENABLE_CLIENT_MODE=1
```
# s2n API
The API exposed by s2n is the set of functions and declarations that
are in the "s2n.h" header file. Any functions and declarations that are in the "s2n.h" file
are intended to be stable (API and ABI) within major version numbers of s2n releases. Other functions
and structures used in s2n internally can not be considered stable and their parameters, names, and
sizes may change.
At this time (Summer 2015), there has been no numbered release of s2n and all APIs are subject to change based
on the feedback and preferences of early adopters.
## Preprocessor macros
s2n defines five preprocessor macros that are used to determine what
version of SSL/TLS is in use on a connection.
```c
#define S2N_SSLv2 20
#define S2N_SSLv3 30
#define S2N_TLS10 31
#define S2N_TLS11 32
#define S2N_TLS12 33
```
These correspond to SSL2.0, SSL3.0, TLS1.0, TLS1.1 and TLS1.2 respectively.
Note that s2n does not support SSL2.0 for sending and receiving encrypted data,
but does accept SSL2.0 hello messages.
## Enums
s2n defines five enum types:
```c
typedef enum {
S2N_ERR_T_OK=0,
S2N_ERR_T_IO,
S2N_ERR_T_CLOSED,
S2N_ERR_T_BLOCKED,
S2N_ERR_T_ALERT,
S2N_ERR_T_PROTO,
S2N_ERR_T_INTERNAL,
S2N_ERR_T_USAGE
} s2n_error_type;
```
***s2n_error_type*** is used to help applications determine why an s2n function failed.
This enum is optimized for use in C switch statements. Each value in the enum represents
an error "category". See [Error Handling](#error-handling) for more detail.
```c
typedef enum { S2N_SERVER, S2N_CLIENT } s2n_mode;
```
**s2n_mode** is used to declare connections as server or client type,
respectively. At this time, s2n does not function as a client and only
S2N_SERVER should be used.
```c
typedef enum { S2N_NOT_BLOCKED, S2N_BLOCKED_ON_READ, S2N_BLOCKED_ON_WRITE } s2n_blocked_status;
```
**s2n_blocked_status** is used in non-blocking mode to indicate in which
direction s2n became blocked on I/O before it returned control to the caller.
This allows an application to avoid retrying s2n operations until I/O is
possible in that direction.
```c
typedef enum { S2N_BUILT_IN_BLINDING, S2N_SELF_SERVICE_BLINDING } s2n_blinding;
```
**s2n_blinding** is used to opt-out of s2n's built-in blinding. Blinding is a
mitigation against timing side-channels which in some cases can leak information
about encrypted data. By default s2n will cause a thread to sleep between 1ms and
10 seconds whenever tampering is detected.
Setting the **S2N_SELF_SERVICE_BLINDING** option with **s2n_connection_set_blinding**
turns off this behavior. This is useful for applications that are handling many connections
in a single thread. In that case, if s2n_recv() or s2n_negotiate() return an error,
self-service applications should call **s2n_connection_get_delay** and pause
activity on the connection for the specified number of nanoseconds before calling
close() or shutdown().
```c
typedef enum { S2N_STATUS_REQUEST_NONE, S2N_STATUS_REQUEST_OCSP } s2n_status_request_type;
```
**s2n_status_request_type** is used to define the type, if any, of certificate
status request an S2N_CLIENT should make during the handshake. The only
supported status request type is OCSP, **S2N_STATUS_REQUEST_OCSP**.
```c
typedef enum { S2N_CERT_AUTH_NONE, S2N_CERT_AUTH_REQUIRED, S2N_CERT_AUTH_OPTIONAL } s2n_cert_auth_type;
```
**s2n_cert_auth_type** is used to declare what type of client certificiate authentication to use.
Currently the default for s2n is for neither the server side or the client side to use Client (aka Mutual) authentication.
```c
typedef enum {
S2N_CERT_TYPE_RSA_SIGN = 1,
S2N_CERT_TYPE_DSS_SIGN = 2,
S2N_CERT_TYPE_RSA_FIXED_DH = 3,
S2N_CERT_TYPE_DSS_FIXED_DH = 4,
S2N_CERT_TYPE_RSA_EPHEMERAL_DH_RESERVED = 5,
S2N_CERT_TYPE_DSS_EPHEMERAL_DH_RESERVED = 6,
S2N_CERT_TYPE_FORTEZZA_DMS_RESERVED = 20,
S2N_CERT_TYPE_ECDSA_SIGN = 64,
S2N_CERT_TYPE_RSA_FIXED_ECDH = 65,
S2N_CERT_TYPE_ECDSA_FIXED_ECDH = 66,
} s2n_cert_type;
```
**s2n_cert_type** is used to define what type of Certificate was used in a connection.
## Opaque structures
s2n defines two opaque structures that are used for managed objects. Because
these structures are opaque, they can only be safely referenced indirectly through
pointers and their sizes may change with future versions of s2n.
```c
struct s2n_config;
struct s2n_connection;
```
**s2n_config** structures are a configuration object, used by servers for
holding cryptographic certificates, keys and preferences. **s2n_connection**
structures are used to track each connection.
```c
struct s2n_rsa_public_key;
struct s2n_cert_public_key;
```
**s2n_rsa_public_key** and **s2n_cert_public_key** can be used by consumers of s2n to get and set public keys through other API calls.
## Error handling
```
const char *s2n_strerror(int error, const char *lang);
const char *s2n_strerror_debug(int error, const char *lang);
````
s2n functions that return 'int' return 0 to indicate success and -1 to indicate
failure. s2n functions that return pointer types return NULL in the case of
failure. When an s2n function returns a failure, s2n_errno will be set to a value
corresponding to the error. This error value can be translated into a string
explaining the error in English by calling s2n_strerror(s2n_errno, "EN");
A string containing internal debug information, including filename and line number, can be generated with `s2n_strerror_debug`
This string is useful to include when reporting issues to the s2n development team.
Example:
```
if (s2n_config_set_cipher_preferences(config, prefs) < 0) {
printf("Setting cipher prefs failed! %s : %s", s2n_strerror(s2n_errno, "EN"), s2n_strerror_debug(s2n_errno, "EN"));
return -1;
}
```
**NOTE**: To avoid possible confusion, s2n_errno should be cleared after processing an error: `s2n_errno = S2N_ERR_T_OK`
### Error categories
s2n organizes errors into different "types" to allow applications to do logic on error values without catching all possibilities.
Applications using non-blocking I/O should check error type to determine if the I/O operation failed because it would block or for some other error. To retrieve the type for a given error use `s2n_error_get_type()`.
Applications should perform any error handling logic using these high level types:
```
S2N_ERR_T_OK=0, /* No error */
S2N_ERR_T_IO, /* Underlying I/O operation failed, check system errno */
S2N_ERR_T_CLOSED, /* EOF */
S2N_ERR_T_BLOCKED, /* Underlying I/O operation would block */
S2N_ERR_T_ALERT, /* Incoming Alert */
S2N_ERR_T_PROTO, /* Failure in some part of the TLS protocol. Ex: CBC verification failure */
S2N_ERR_T_INTERNAL, /* Error internal to s2n. A precondition could have failed. */
S2N_ERR_T_USAGE /* User input error. Ex: Providing an invalid cipher preference version */
```
Here's an example that handles errors based on type:
```
s2n_errno = S2N_ERR_T_OK;
if (s2n_recv(conn, &blocked) < 0) {
switch(s2n_error_get_type(s2n_errno)) {
case S2N_ERR_T_BLOCKED:
/* Blocked, come back later */
return -1;
case S2N_ERR_T_CLOSED:
return 0;
case S2N_ERR_T_IO:
handle_io_err();
return -1;
case S2N_ERR_T_PROTO:
handle_proto_err();
return -1;
case S2N_ERR_T_ALERT:
log_alert(s2n_connection_get_alert(conn));
return -1;
/* Everything else */
default:
log_other_error();
return -1;
}
}
```
## Initialization and teardown
### s2n\_init
```c
int s2n_init();
```
**s2n_init** initializes the s2n library and should be called once in your application,
before any other s2n functions are called. Failure to call s2n_init() will result
in errors from other s2n functions.
### s2n\_cleanup
```c
int s2n_cleanup();
```
**s2n_cleanup** cleans up any internal resources used by s2n. This function should be
called from each thread or process that is created subsequent to calling **s2n_init**
when that thread or process is done calling other s2n functions.
## Configuration-oriented functions
### s2n\_config\_new
```c
struct s2n_config * s2n_config_new();
```
**s2n_config_new** returns a new configuration object suitable for associating certs and keys.
This object can (and should) be associated with many connection objects.
### s2n\_config\_free
```c
int s2n_config_free(struct s2n_config *config);
```
**s2n_config_free** frees the memory associated with an **s2n_config** object.
### s2n\_config\_set\_cipher\_preferences
```c
int s2n_config_set_cipher_preferences(struct s2n_config *config,
const char *version);
```
**s2n_config_set_cipher_preferences** sets the ciphersuite and protocol versions. The currently supported versions are;
| version | SSLv3 | TLS1.0 | TLS1.1 | TLS1.2 | AES-CBC | ChaCha20-Poly1305 | AES-GCM | 3DES | RC4 | DHE | ECDHE |
|------------|-------|--------|--------|--------|---------|-------------------|---------|------|-----|-----|-------|
| "default" | | X | X | X | X | X | X | | | | X |
| "20170718" | | X | X | X | X | | X | | | | X |
| "20170405" | | X | X | X | X | | X | X | | | X |
| "20170328" | | X | X | X | X | | X | X | | X | X |
| "20170210" | | X | X | X | X | X | X | | | | X |
| "20160824" | | X | X | X | X | | X | | | | X |
| "20160804" | | X | X | X | X | | X | X | | | X |
| "20160411" | | X | X | X | X | | X | X | | | X |
| "20150306" | | X | X | X | X | | X | X | | | X |
| "20150214" | | X | X | X | X | | X | X | | X | |
| "20150202" | | X | X | X | X | | | X | | X | |
| "20141001" | | X | X | X | X | | | X | X | X | |
| "20140601" | X | X | X | X | X | | | X | X | X | |
The "default" version is special in that it will be updated with future s2n changes and ciphersuites and protocol versions may be added and removed, or their internal order of preference might change. Numbered versions are fixed and will never change.
"20160411" follows the same general preference order as "default". The main difference is it has a CBC cipher suite at the top. This is to accomodate certain Java clients that have poor GCM implementations. Users of s2n who have found GCM to be hurting performance for their clients should consider this version.
"20170405" is a FIPS compliant cipher suite preference list based on approved algorithms in the [FIPS 140-2 Annex A](http://csrc.nist.gov/publications/fips/fips140-2/fips1402annexa.pdf). Similarly to "20160411", this perference list has CBC cipher suites at the top to accomodate certain Java clients. Users of s2n who plan to enable FIPS mode should consider this version.
s2n does not expose an API to control the order of preference for each ciphersuite or protocol version. s2n follows the following order:
*NOTE*: All ChaCha20-Poly1305 cipher suites will not be available if s2n is not built with an Openssl 1.1.0 libcrypto. The
underlying encrpyt/decrypt functions are not available in older versions.
1. Always prefer the highest protocol version supported
2. Always use forward secrecy where possible. Prefer ECDHE over DHE.
3. Prefer encryption ciphers in the following order: AES128, AES256, ChaCha20, 3DES, RC4.
4. Prefer record authentication modes in the following order: GCM, Poly1305, SHA256, SHA1, MD5.
### s2n\_config\_add\_cert\_chain\_and\_key
```c
int s2n_config_add_cert_chain_and_key(struct s2n_config *config,
const char *cert_chain_pem,
const char *private_key_pem);
```
**s2n_config_add_cert_chain_and_key** associates a certificate chain and a
private key, with an **s2n_config** object. At present, only one
certificate-chain/key pair may be associated with a config.
**cert_chain_pem** should be a PEM encoded certificate chain, with the first
certificate in the chain being your servers certificate. **private_key_pem**
should be a PEM encoded private key corresponding to the server certificate.
### s2n\_config\_add\_dhparams
```c
int s2n_config_add_dhparams(struct s2n_config *config,
char *dhparams_pem);
```
**s2n_config_add_dhparams** associates a set of Diffie-Hellman parameters with
an **s2n_config** object. **dhparams_pem** should be PEM encoded DH parameters.
### s2n\_config\_set\_protocol\_preferences
```c
int s2n_config_set_protocol_preferences(struct s2n_config *config,
const char **protocols,
int protocol_count);
```
**s2n_config_set_protocol_preferences** sets the application protocol
preferences on an **s2n_config** object. **protocols** is a list in order of
preference, with most preferred protocol first, and of length
**protocol_count**. When acting as an **S2N_CLIENT** the protocol list is
included in the Client Hello message as the ALPN extension. As an
**S2N_SERVER**, the list is used to negotiate a mutual application protocol
with the client. After the negotiation for the connection has completed, the
agreed upon protocol can be retrieved with [s2n_get_application_protocol](#s2n_get_application_protocol)
### s2n\_config\_set\_status\_request\_type
```c
int s2n_config_set_status_request_type(struct s2n_config *config, s2n_status_request_type type);
```
**s2n_config_set_status_request_type** Sets up an S2N_CLIENT to request the
server certificate status during an SSL handshake. If set to
S2N_STATUS_REQUEST_NONE, no status request is made.
### s2n\_config\_set\_extension\_data
```c
int s2n_config_set_extension_data(struct s2n_config *config, s2n_tls_extension_type type, const uint8_t *data, uint32_t length);
```
**s2n_config_set_extension_data** Sets the extension data in the **s2n_config**
object for the specified extension. This method will clear any existing data
that is set. If the data and length parameters are set to NULL, no new data
is set in the **s2n_config** object, effectively clearing existing data.
`s2n_tls_extension_type` is defined as:
```c
typedef enum {
S2N_EXTENSION_SERVER_NAME = 0,
S2N_EXTENSION_MAX_FRAG_LEN = 1,
S2N_EXTENSION_OCSP_STAPLING = 5,
S2N_EXTENSION_ELLIPTIC_CURVES = 10,
S2N_EXTENSION_EC_POINT_FORMATS = 11,
S2N_EXTENSION_SIGNATURE_ALGORITHMS = 13,
S2N_EXTENSION_ALPN = 16,
S2N_EXTENSION_CERTIFICATE_TRANSPARENCY = 18,
S2N_EXTENSION_RENEGOTIATION_INFO = 65281,
} s2n_tls_extension_type;
```
At this time the following extensions are supported:
`S2N_EXTENSION_OCSP_STAPLING` - If a client requests the OCSP status of the server
certificate, this is the response used in the CertificateStatus handshake
message.
`S2N_EXTENSION_CERTIFICATE_TRANSPARENCY` - If a client supports receiving SCTs
via the TLS extension (section 3.3.1 of RFC6962) this data is returned within
the extension response during the handshake. The format of this data is the
SignedCertificateTimestampList structure defined in that document. See
http://www.certificate-transparency.org/ for more information about Certificate
Transparency.
### s2n\_config\_set\_wall\_clock
```c
int s2n_config_set_wall_clock(struct s2n_config *config, s2n_clock_time_nanoseconds clock_fn, void *data);
```
**s2n_config_set_wall_clock** allows the caller to set a
callback function that will be used to get the system time. The callback function
takes two arguments; a pointer to abitrary data for use within the callback,
and a pointer to a 64 bit unsigned integer. The first pointer will be set to
the value of **data** which supplied by the caller when setting the callback.
The integer pointed to by the second pointer should be set to the number of
nanoseconds since the Unix epoch (Midnight, January 1st, 1970). The function
should return 0 on success and -1 on error. The default implementation, which uses the REALTIME clock,
will be used if this callback is not manually set.
### s2n\_config\_set\_monotonic\_clock
```c
int s2n_config_set_monotonic_clock(struct s2n_config *config, s2n_clock_time_nanoseconds clock_fn, void *data);
```
**s2n_config_set_monotonic_clock** allows the caller to set a
callback function that will be used to get monotonic time. The callback function
takes two arguments; a pointer to abitrary data for use within the callback,
and a pointer to a 64 bit unsigned integer. The first pointer will be set to
the value of **data** which supplied by the caller when setting the callback.
The integer pointed to by the second pointer should be an always increasing value. The function
should return 0 on success and -1 on error. The default implementation, which uses the MONOTONIC clock,
will be used if this callback is not manually set.
### s2n\_config\_set\_verification\_ca\_location
```c
int s2n_config_set_verification_ca_location(struct s2n_config *config, const char *ca_pem_filename, const char *ca_dir);
```
**s2n_config_set_verification_ca_location** initializes the trust store from a CA file or directory
containing trusted certificates. By default, the trust store will be initialized to the common locations
for the host operating system. Call this function to override that behavior.
Returns 0 on success and -1 on failure.
### s2n\_config\_add\_pem\_to\_trust\_store
```c
int s2n_config_add_pem_to_trust_store(struct s2n_config *config, const char *pem);
```
**s2n_config_add_pem_to_trust_store** Initialize trust store from a PEM. This will allocate memory, and load PEM into the Trust Store
### s2n\_verify\_host\_fn
```c
typedef uint8_t (*s2n_verify_host_fn) (const char *host_name, size_t host_name_len, void *ctx);
```
**s2n_verify_host_fn** is invoked (usually multiple times) during X.509 validation for each name encountered in the leaf certificate.
Return 1 to trust that hostname or 0 to not trust the hostname. If this function returns 1, then the certificate is considered trusted and that portion
of the X.509 validation will succeed. If no hostname results in a 1 being returned,
the certificate will be untrusted and the validation will terminate immediately. The default behavior is to reject all host names found in a certificate
if client mode or client authentication is being used..
### s2n\_config\_set\_verify\_host\_callback
```c
int s2n_config_set_verify_host_callback(struct s2n_config *config, s2n_verify_host_fn, void *ctx);
```
**s2n_config_set_verify_host_callback** sets the callback to use for verifying that a hostname from an X.509 certificate
is trusted. By default, no certificate will be trusted. To override this behavior, set this callback.
See [s2n_verify_host_fn](#s2n_verify_host_fn) for details. This configuration will be inherited by default to new instances of **s2n_connection**.
If a separate callback for different connections using the same config is desired, see
[s2n_connection_set_verify_host_callback](#s2n_connection_set_verify_host_callback).
### s2n\_config\_set\_check\_stapled\_ocsp\_response
```c
int s2n_config_set_check_stapled_ocsp_response(struct s2n_config *config, uint8_t check_ocsp);
```
**s2n_config_set_check_stapled_ocsp_response** toggles whether or not to validate stapled OCSP responses. 1 means OCSP responses
will be validated when they are encountered, while 0 means this step will be skipped. The default value is 1 if the underlying
libCrypto implementation supports OCSP. Returns 0 on success and -1 on failure.
### s2n\_config\_disable\_x509\_verification
```c
int s2n_config_disable_x509_verification(struct s2n_config *config);
```
**s2n_config_disable_x509_verification** turns off all X.509 validation during the negotiation phase of the connection. This should only be used
for testing or debugging purposes.
```c
int s2n_config_set_max_cert_chain_depth(struct s2n_config *config, uint16_t max_depth);
```
**s2n_config_set_max_cert_chain_depth** sets the maximum allowed depth of a cert chain used for X509 validation. The default value is 7. If this limit
is exceeded, validation will fail if s2n_config_disable_x509_verification() has not been called. 0 is an illegal value and will return an error.
1 means only a root certificate will be used.
### s2n\_config\_set\_client\_hello\_cb
```c
int s2n_config_set_client_hello_cb(struct s2n_config *config, s2n_client_hello_fn client_hello_callback, void *ctx);
```
**s2n_config_set_client_hello_cb** allows the caller to set a callback function
that will be called after ClientHello was parsed.
```c
typedef int s2n_client_hello_fn(struct s2n_connection *conn, void *ctx);
```
The callback function take as an input s2n connection, which received
ClientHello and context provided in **s2n_config_set_client_hello_cb**. The
callback can get any ClientHello infromation from the connection and use
**s2n_connection_set_config** call to change the config of the connection.
The callback can return 0 to continue handshake in s2n or it can return negative
value to make s2n terminate handshake early with fatal handshake failure alert.
### s2n\_config\_set\_alert\_behavior
```c
int s2n_config_set_alert_behavior(struct s2n_config *config, s2n_alert_behavior alert_behavior);
```
Sets whether or not a should terminate connection on WARNING alert from peer. `alert_behavior` can take the following values:
- `S2N_ALERT_FAIL_ON_WARNINGS` - default behavior: s2n will terminate conneciton if peer sends WARNING alert.
- `S2N_ALERT_IGNORE_WARNINGS` - with the exception of `close_notify` s2n will ignore all WARNING alerts and keep communicating with its peer.
## Client Auth Related calls
Client Auth Related API's are not recommended for normal users. Use of these API's is discouraged.
1. Using these API's requires users to: Complete full x509 parsing and hostname validation in the application layer
2. Application knowledge of TLS code points for certificate types
3. Application dependency on libcrypto to give a libcrypto RSA struct back to s2n
### s2n\_config\_set\_client\_auth\_type and s2n\_connection\_set\_client\_auth\_type
```c
int s2n_config_set_client_auth_type(struct s2n_config *config, s2n_cert_auth_type cert_auth_type);
int s2n_connection_set_client_auth_type(struct s2n_connection *conn, s2n_cert_auth_type cert_auth_type);
```
Sets whether or not a Client Certificate should be required to complete the TLS Connection. If this is set to
**S2N_CERT_AUTH_OPTIONAL** the server will request a client certificate but allow the client to not provide one.
Rejecting a client certificate when using **S2N_CERT_AUTH_OPTIONAL** will terminate the handshake.
### Public Key API's
```c
int s2n_rsa_public_key_set_from_openssl(struct s2n_rsa_public_key *s2n_rsa, RSA *openssl_rsa);
int s2n_cert_public_key_set_cert_type(struct s2n_cert_public_key *cert_pub_key, s2n_cert_type cert_type);
int s2n_cert_public_key_get_rsa(struct s2n_cert_public_key *cert_pub_key, struct s2n_rsa_public_key **rsa);
int s2n_cert_public_key_set_rsa(struct s2n_cert_public_key *cert_pub_key, struct s2n_rsa_public_key rsa);
```
**s2n_rsa_public_key** and **s2n_cert_public_key** are opaque structs. These API's are intended to be used by Implementations of **verify_cert_trust_chain_fn** to
set the public keys found in the Certificate into **public_key_out**.
## Session Caching related calls
s2n includes support for resuming from cached SSL/TLS session, provided
the caller sets (and implements) three callback functions.
### s2n\_config\_set\_cache\_store\_callback
```c
int s2n_config_set_cache_store_callback(struct s2n_config *config, int (*cache_store)(void *, uint64_t ttl_in_seconds, const void *key, uint64_t key_size, const void *value, uint64_t value_size), void *data);
```
**s2n_config_set_cache_store_callback** allows the caller to set a callback
function that will be used to store SSL session data in a cache. The callback
function takes six arguments: a pointer to abitrary data for use within the
callback, a 64-bit unsigned integer specifying the number of seconds the
session data may be stored for, a pointer to a key which can be used to
retrieve the cached entry, a 64 bit unsigned integer specifying the size of
this key, a pointer to a value which should be stored, and a 64 bit unsigned
integer specified the size of this value.
### s2n\_config\_set\_cache\_retrieve\_callback
```c
int s2n_config_set_cache_retrieve_callback(struct s2n_config *config, int (*cache_retrieve)(void *, const void *key, uint64_t key_size, void *value, uint64_t *value_size), void *data)
```
**s2n_config_set_cache_retrieve_callback** allows the caller to set a callback
function that will be used to retrieve SSL session data from a cache. The
callback function takes five arguments: a pointer to abitrary data for use
within the callback, a pointer to a key which can be used to retrieve the
cached entry, a 64 bit unsigned integer specifying the size of this key, a
pointer to a memory location where the value should be stored,
and a pointer to a 64 bit unsigned integer specifing the size of this value.
Initially *value_size will be set to the amount of space allocated for
the value, the callback should set *value_size to the actual size of the
data returned. If there is insufficient space, -1 should be returned.
### s2n\_config\_set\_cache\_delete\_callback
```c
int s2n_config_set_cache_delete_callback(struct s2n_config *config, int (*cache_delete))(void *, const void *key, uint64_t key_size), void *data);
```
**s2n_config_set_cache_delete_callback** allows the caller to set a callback
function that will be used to delete SSL session data from a cache. The
callback function takes three arguments: a pointer to abitrary data for use
within the callback, a pointer to a key which can be used to delete the
cached entry, and a 64 bit unsigned integer specifying the size of this key.
### s2n\_config\_send\_max\_fragment\_length
```c
int s2n_config_send_max_fragment_length(struct s2n_config *config, uint8_t mfl_code);
```
**s2n_config_send_max_fragment_length** allows the caller to set a TLS Maximum
Fragment Length extension that will be used to fragment outgoing messages.
s2n currently does not reject fragments larger than the configured maximum when
in server mode. The TLS negotiated maximum fragment length overrides the preference set
by the **s2n_connection_prefer_throughput** and **s2n_connection_prefer_low_latency**.
### s2n\_config\_accept\_max\_fragment\_length
```c
int s2n_config_accept_max_fragment_length(struct s2n_config *config);
```
**s2n_config_accept_max_fragment_length** allows the server to opt-in to accept
client's TLS maximum fragment length extension requests.
If this API is not called, and client requests the extension, server will ignore the
request and continue TLS handshake with default maximum fragment length of 8k bytes
## Connection-oriented functions
### s2n\_connection\_new
```c
struct s2n_connection * s2n_connection_new(s2n_mode mode);
```
**s2n_connection_new** creates a new connection object. Each s2n SSL/TLS
connection uses one of these objects. These connection objects can be operated
on by up to two threads at a time, one sender and one receiver, but neither
sending nor receiving are atomic, so if these objects are being called by
multiple sender or receiver threads, you must perform your own locking to
ensure that only one sender or receiver is active at a time. The **mode**
parameters specifies if the caller is a server, or is a client.
Connections objects are re-usable across many connections, and should be
re-used (to avoid deallocating and allocating memory). You should wipe
connections immediately after use.
### s2n\_connection\_set\_config
```c
int s2n_connection_set_config(struct s2n_connection *conn,
struct s2n_config *config);
```
**s2n_connection_set_config** Associates a configuration object with a
connection.
### s2n\_connection\_set\_ctx
```c
int s2n_connection_set_ctx(struct s2n_connection *conn, void *ctx);
```
**s2n_connection_set_ctx** sets user defined context in **s2n_connection**
object.
### s2n\_connection\_get\_ctx
```c
void *s2n_connection_get_ctx(struct s2n_connection *conn);
```
**s2n_connection_get_ctx** gets user defined context from **s2n_connection**
object.
### s2n\_connection\_set\_fd
```c
int s2n_connection_set_fd(struct s2n_connection *conn,
int readfd);
int s2n_connection_set_read_fd(struct s2n_connection *conn,
int readfd);
int s2n_connection_set_write_fd(struct s2n_connection *conn,
int writefd);
```
**s2n_connection_set_fd** sets the file-descriptor for an s2n connection. This
file-descriptor should be active and connected. s2n also supports setting the
read and write file-descriptors to different values (for pipes or other unusual
types of I/O).
## s2n\_connection\_is\_valid\_for\_cipher\_preferences
```c
int s2n_connection_is_valid_for_cipher_preferences(struct s2n_connection *conn, const char *version);
```
**s2n_connection_is_valid_for_cipher_preferences** checks if the cipher used by current connection
is supported by a given cipher preferences. It returns
- 1 if the connection satisfies the cipher suite
- 0 if it does not
- -1 on any other errors
## s2n\_connection\_set\_cipher\_preferences
```c
int s2n_connection_set_cipher_preferences(struct s2n_connection *conn, const char *version);
```
**s2n_connection_set_cipher_preferences** sets the cipher preference override for the
s2n_connection. Calling this function is not necessary unless you want to set the
cipher preferences on the connection to something different than what is in the s2n_config.
## s2n\_connection\_set\_protocol\_preferences
```c
int s2n_connection_set_protocol_preferences(struct s2n_connection *conn, const char * const *protocols, int protocol_count);
```
**s2n_connection_set_protocol_preferences** sets the protocol preference override for the
s2n_connection. Calling this function is not necessary unless you want to set the
protocol preferences on the connection to something different than what is in the s2n_config.
### s2n\_set\_server\_name
```c
int s2n_set_server_name(struct s2n_connection *conn,
const char *server_name);
```
**s2n_set_server_name** Sets the server name for the connection. In future,
this can be used by clients who wish to use the TLS "Server Name indicator"
extension. At present, client functionality is disabled.
### s2n\_get\_server\_name
```c
const char *s2n_get_server_name(struct s2n_connection *conn);
```
**s2n_get_server_name** returns the server name associated with a connection,
or NULL if none is found. This can be used by a server to determine which server
name the client is using.
### s2n\_connection\_set\_blinding
```c
int s2n_connection_set_blinding(struct s2n_connection *conn, s2n_blinding blinding);
```
**s2n_connection_set_blinding** can be used to configure s2n to either use
built-in blinding (set blinding to S2N_BUILT_IN_BLINDING) or self-service blinding
(set blinding to S2N_SELF_SERVICE_BLINDING).
### s2n\_connection\_get\_delay
```c
uint64_t s2n_connection_get_delay(struct s2n_connection *conn);
```
**s2n_connection_get_delay** returns the number of nanoseconds an application
using self-service blinding should pause before calling close() or shutdown().
### s2n\_connection\_prefer\_throughput(struct s2n_connection *conn)
```c
int s2n_connection_prefer_throughput(struct s2n_connection *conn);
int s2n_connection_prefer_low_latency(struct s2n_connection *conn);
int s2n_connection_set_dynamic_record_threshold(struct s2n_connection *conn, uint32_t resize_threshold, uint16_t timeout_threshold);
```
**s2n_connection_prefer_throughput** and **s2n_connection_prefer_low_latency**
change the behavior of s2n when sending data to prefer either throughput
or low latency. Connections prefering low latency will be encrypted using small
record sizes that can be decrypted sooner by the recipient. Connections
prefering throughput will use large record sizes that minimize overhead.
-Connections default to an 8k outgoing maximum
**s2n_connection_set_dynamic_record_threshold**
provides a smooth transition from **s2n_connection_prefer_low_latency** to **s2n_connection_prefer_throughput**.
**s2n_send** uses small TLS records that fit into a single TCP segment for the resize_threshold bytes (cap to 8M) of data
and reset record size back to a single segment after timeout_threshold seconds of inactivity.
### s2n\_connection\_get\_wire\_bytes
```c
uint64_t s2n_connection_get_wire_bytes_in(struct s2n_connection *conn);
uint64_t s2n_connection_get_wire_bytes_out(struct s2n_connection *conn);
```
**s2n_connection_get_wire_bytes_in** and **s2n_connection_get_wire_bytes_out**
return the number of bytes transmitted by s2n "on the wire", in and out
respectively.
### s2n\_connection\_get\_protocol\_version
```c
int s2n_connection_get_client_hello_version(struct s2n_connection *conn);
int s2n_connection_get_client_protocol_version(struct s2n_connection *conn);
int s2n_connection_get_server_protocol_version(struct s2n_connection *conn);
int s2n_connection_get_actual_protocol_version(struct s2n_connection *conn);
```
**s2n_connection_get_client_protocol_version** returns the protocol version
number supported by the client, **s2n_connection_get_server_protocol_version**
returns the protocol version number supported by the server and
**s2n_connection_get_actual_protocol_version** returns the protocol version
number actually used by s2n for the connection. **s2n_connection_get_client_hello_version**
returns the protocol version used in the initial client hello message.
Each version number value corresponds to the macros defined as **S2N_SSLv2**,
**S2N_SSLv3**, **S2N_TLS10**, **S2N_TLS11** and **S2N_TLS12**.
### s2n\_connection\_set\_verify\_host\_callback
```c
int s2n_connection_set_verify_host_callback(struct s2n_connection *config, s2n_verify_host_fn host_fn, void *data);
```
Every connection inherits the value of **s2n_verify_host_fn** from it's instance of **s2n_config**.
Since a configuration can (and should) be used for multiple connections, it may be useful to override
this value on a per connection basis. For example, this may be based on a host header from an http request. In that case,
calling this function will override the value inherited from the configuration.
See [s2n_verify_host_fn](#s2n_verify_host_fn) for details.
### s2n\_connection\_get\_client\_hello
```c
struct s2n_client_hello *s2n_connection_get_client_hello(struct s2n_connection *conn);
```
For a given s2n_connection, **s2n_connection_get_client_hello** returns a handle
to the s2n_client_hello structure holding the client hello message sent by the client during the handshake.
NULL is returned if the connection has not yet received and parsed the client hello.
Earliest point during the handshake when this structure is available for use is in the client_hello_callback (see **s2n_config_set_client_hello_cb**).
### s2n\_client\_hello\_get\_raw\_message
```c
ssize_t s2n_client_hello_get_raw_message_length(struct s2n_client_hello *ch);
ssize_t s2n_client_hello_get_raw_message(struct s2n_client_hello *ch, uint8_t *out, uint32_t max_length);
```
- **ch** The s2n_client_hello on the s2n_connection. The handle can be obtained using **s2n_connection_get_client_hello**.
- **out** Pointer to a buffer into which the raw client hello bytes should be copied.
- **max_length** Max number of bytes to copy into the **out** buffer.
**s2n_client_hello_get_raw_message_length** returns the size of the ClientHello message received by the server; it can be used to allocate the **out** buffer.
**s2n_client_hello_get_raw_message** copies **max_lenght** bytes of the ClientHello message into the **out** buffer and returns the number of bytes that were copied.
The ClientHello instrumented using this function will have the Random bytes zero-ed out.
### s2n\_client\_hello\_get\_cipher\_suites
```c
ssize_t s2n_client_hello_get_cipher_suites_length(struct s2n_client_hello *ch);
ssize_t s2n_client_hello_get_cipher_suites(struct s2n_client_hello *ch, uint8_t *out, uint32_t max_length);
```
- **ch** The s2n_client_hello on the s2n_connection. The handle can be obtained using **s2n_connection_get_client_hello**.
- **out** Pointer to a buffer into which the cipher_suites bytes should be copied.
- **max_length** Max number of bytes to copy into the **out** buffer.
**s2n_client_hello_get_cipher_suites_length** returns the number of bytes the cipher_suites takes on the ClientHello message received by the server; it can be used to allocate the **out** buffer.
**s2n_client_hello_get_cipher_suites** copies into the **out** buffer **max_length** bytes of the cipher_suites on the ClienthHello and returns the number of bytes that were copied.
### s2n\_client\_hello\_get\_extensions
```c
ssize_t s2n_client_hello_get_extensions_length(struct s2n_client_hello *ch);
ssize_t s2n_client_hello_get_extensions(struct s2n_client_hello *ch, uint8_t *out, uint32_t max_length);
```
- **ch** The s2n_client_hello on the s2n_connection. The handle can be obtained using **s2n_connection_get_client_hello**.
- **out** Pointer to a buffer into which the cipher_suites bytes should be copied.
- **max_length** Max number of bytes to copy into the **out** buffer.
**s2n_client_hello_get_extensions_length** returns the number of bytes the extensions take on the ClientHello message received by the server; it can be used to allocate the **out** buffer.
**s2n_client_hello_get_extensions** copies into the **out** buffer **max_length** bytes of the extensions on the ClienthHello and returns the number of bytes that were copied.
### s2n\_client\_hello\_get\_extension
```c
ssize_t s2n_client_hello_get_extension_length(struct s2n_client_hello *ch, s2n_tls_extension_type extension_type);
ssize_t s2n_client_hello_get_extension_by_id(struct s2n_client_hello *ch, s2n_tls_extension_type extension_type, uint8_t *out, uint32_t max_length);
```
- **ch** The s2n_client_hello on the s2n_connection. The handle can be obtained using **s2n_connection_get_client_hello**.
- **s2n_tls_extension_type** Enum [s2n_tls_extension_type](#s2n\_config\_set\_extension\_data) lists all supported extension types.
- **out** Pointer to a buffer into which the extension bytes should be copied.
- **max_length** Max number of bytes to copy into the **out** buffer.
**s2n_client_hello_get_extension_length** returns the number of bytes the given extension type takes on the ClientHello message received by the server; it can be used to allocate the **out** buffer.
**s2n_client_hello_get_extension_by_id** copies into the **out** buffer **max_length** bytes of a given extension type on the ClienthHello and returns the number of bytes that were copied.
### s2n\_connection\_is\_client\_authenticated
```c
int s2n_connection_is_client_authenticated(struct s2n_connection *conn);
```
**s2n_connection_is_client_authenticated** returns 1 if the handshake completed and Client Auth was
negotiated during the handshake.
### s2n\_get\_application\_protocol
```c
const char *s2n_get_application_protocol(struct s2n_connection *conn);
```
**s2n_get_application_protocol** returns the negotiated application protocol
for a **s2n_connection**. In the event of no protocol being negotiated, NULL
is returned.
### s2n\_connection\_get\_ocsp\_response
```c
const uint8_t *s2n_connection_get_ocsp_response(struct s2n_connection *conn, uint32_t *length);
```
**s2n_connection_get_ocsp_response** returns the OCSP response sent by a server
during the handshake. If no status response is received, NULL is returned.
### s2n\_connection\_is\_ocsp\_stapled
```c
int s2n_connection_is_ocsp_stapled(struct s2n_connection *conn);
```
**s2n_connection_is_ocsp_stapled** returns 1 if OCSP response was sent (if connection is in S2N_SERVER mode) or received (if connection is in S2N_CLIENT mode) during handshake, otherwise it returns 0.
### s2n\_connection\_get\_alert
```c
int s2n_connection_get_alert(struct s2n_connection *conn);
```
If a connection was shut down by the peer, **s2n_connection_get_alert** returns
the TLS alert code that caused a connection to be shut down. s2n considers all
TLS alerts fatal and shuts down a connection whenever one is received.
### s2n\_connection\_get\_cipher
```c
const char * s2n_connection_get_cipher(struct s2n_connection *conn);
```
**s2n_connection_get_cipher** returns a string indicating the cipher suite
negotiated by s2n for a connection in Openssl format, e.g. "ECDHE-RSA-AES128-GCM-SHA256".
### s2n\_connection\_get\_curve
```c
const char * s2n_connection_get_curve(struct s2n_connection *conn);
```
**s2n_connection_get_curve** returns a string indicating the elliptic curve used during ECDHE key exchange. The string "NONE" is returned if no curve has was used.
### Session Resumption Related calls
```c
int s2n_config_set_session_state_lifetime(struct s2n_config *config, uint32_t lifetime_in_secs);
int s2n_connection_set_session(struct s2n_connection *conn, const uint8_t *session, size_t length);
int s2n_connection_get_session(struct s2n_connection *conn, uint8_t *session, size_t max_length);
int s2n_connection_get_session_ticket_lifetime_hint(struct s2n_connection *conn);
ssize_t s2n_connection_get_session_length(struct s2n_connection *conn);
ssize_t s2n_connection_get_session_id_length(struct s2n_connection *conn);
int s2n_connection_is_session_resumed(struct s2n_connection *conn);
```
- **lifetime_in_secs** lifetime of the cached session state required to resume a
handshake.
- **session** session will contain serialized session related information needed to resume handshake either using session id or session ticket.
- **length** length of the serialized session state.
- **max_length** Max number of bytes to copy into the **session** buffer.
**s2n_config_set_session_state_lifetime** sets the lifetime of the cached session state. The default value is 15 hours.
**s2n_connection_set_session** de-serializes the session state and updates the connection accordingly.
**s2n_connection_get_session** serializes the session state from connection and copies into the **session** buffer and returns the number of bytes that were copied. If the first byte in **session** is 1, then the next 2 bytes will contain the session ticket length, followed by session ticket and session state. If the first byte in **session** is 0, then the next byte will contain session id length, followed by session id and session state.
**s2n_connection_get_session_ticket_lifetime_hint** returns the session ticket lifetime hint in seconds from the server or -1 when session ticket was not used for resumption.
**s2n_connection_get_session_length** returns number of bytes needed to store serialized session state; it can be used to allocate the **session** buffer.
**s2n_connection_get_session_id_length** returns session id length from the connection.
**s2n_connection_is_session_resumed** returns 1 if the handshake was abbreviated, otherwise returns 0.
### Session Ticket Specific calls
```c
int s2n_config_set_session_tickets_onoff(struct s2n_config *config, uint8_t enabled);
int s2n_config_set_ticket_encrypt_decrypt_key_lifetime(struct s2n_config *config, uint64_t lifetime_in_secs);
int s2n_config_set_ticket_decrypt_key_lifetime(struct s2n_config *config, uint64_t lifetime_in_secs);
int s2n_config_add_ticket_crypto_key(struct s2n_config *config, const uint8_t *name, uint32_t name_len, uint8_t *key, uint32_t key_len, uint64_t intro_time_in_seconds_from_epoch);
```
- **enabled** when set to 0 will disable session resumption using session ticket
- **name** name of the session ticket key that should be randomly generated to avoid collisions
- **name_len** length of session ticket key name
- **key** key used to perform encryption/decryption of session ticket
- **key_len** length of the session ticket key
- **intro_time_in_seconds_from_epoch** time at which the session ticket key is introduced. If this is 0, then intro_time_in_seconds_from_epoch is set to now.
**s2n_config_set_session_tickets_onoff** enables and disables session resumption using session ticket
**s2n_config_set_ticket_encrypt_decrypt_key_lifetime** sets how long a session ticket key will be in a state where it can be used for both encryption and decryption of tickets on the server side. The default value is 2 hours.
**s2n_config_set_ticket_decrypt_key_lifetime** sets how long a session ticket key will be in a state where it can used just for decryption of already assigned tickets on the server side. Once decrypted, the session will resume and the server will issue a new session ticket encrypted using a key in encrypt-decrypt state. The default value is 13 hours.
**s2n_config_add_ticket_crypto_key** adds session ticket key on the server side. It would be ideal to add new keys after every (encrypt_decrypt_key_lifetime_in_nanos/2) nanos because
this will allow for gradual and linear transition of a key from encrypt-decrypt state to decrypt-only state.
### s2n\_connection\_wipe
```c
int s2n_connection_wipe(struct s2n_connection *conn);
```
**s2n_connection_wipe** wipes an existing connection and allows it to be reused. It erases all data associated with a connection including
pending reads. This function should be called after all I/O is completed and [s2n_shutdown](#s2n\_shutdown) has been called.
Reusing the same connection handle(s) is more performant than repeatedly calling [s2n_connection_new](#s2n\_connection\_new) and
[s2n_connection_free](#s2n\_connection\_free)
### s2n\_connection\_free
```c
int s2n_connection_free(struct s2n_connection *conn);
```
**s2n_connection_free** frees the memory associated with an s2n_connection
handle. The handle is considered invalid after **s2n_connection_free** is used.
[s2n_connection_wipe](#s2n\_connection\_wipe) does not need to be called prior to this function. **s2n_connection_free** performs its own wipe
of sensitive data.
## I/O functions
s2n supports both blocking and non-blocking I/O. To use s2n in non-blocking
mode, set the underlying file descriptors as non-blocking (i.e. with
**fcntl**). In blocking mode, each s2n I/O function will not return until it is
complete. In non-blocking mode an s2n I/O function may return while there is
still I/O pending. In this case the value of the **blocked** parameter will be set
to either **S2N_BLOCKED_ON_READ** or **S2N_BLOCKED_ON_WRITE**, depending on the
direction in which s2n is blocked.
s2n I/O functions should be called repeatedly until the **blocked** parameter is
**S2N_NOT_BLOCKED**.
### s2n\_negotiate
```c
int s2n_negotiate(struct s2n_connection *conn, s2n_blocked_status *blocked);
```
**s2n_negotiate** performs the initial "handshake" phase of a TLS connection and must be called before any **s2n_recv** or **s2n_send** calls.
### s2n\_send
```c
ssize_t s2n_send(struct s2n_connection *conn
void *buf,
ssize_t size,
s2n_blocked_status *blocked);
```
**s2n_send** writes and encrypts **size* of **buf** data to the associated connection. **s2n_send** will return the number of bytes written, and may indicate a partial write. Partial writes are possible not just for non-blocking I/O, but also for connections aborted while active. **NOTE:** Unlike OpenSSL, repeated calls to **s2n_send** should not duplicate the original parameters, but should update **buf** and **size** per the indication of size written. For example;
```c
s2n_blocked_status blocked;
int written = 0;
char data[10]; /* Some data we want to write */
do {
int w = s2n_send(conn, data + written, 10 - written, &blocked);
if (w < 0) {
/* Some kind of error */
break;
}
written += w;
} while (blocked != S2N_NOT_BLOCKED);
```
### s2n\_recv
```c
ssize_t s2n_recv(struct s2n_connection *conn,
void *buf,
ssize_t size,
s2n_blocked_status *blocked);
```
**s2n_recv** decrypts and reads **size* to **buf** data from the associated
connection. **s2n_recv** will return the number of bytes read and also return
"0" on connection shutdown by the peer.
**NOTE:** Unlike OpenSSL, repeated calls to **s2n_recv** should not duplicate the original parameters, but should update **buf** and **size** per the indication of size read. For example;
```c
s2n_blocked_status blocked;
int bytes_read = 0;
char data[10];
do {
int r = s2n_recv(conn, data + bytes_read, 10 - bytes_read, &blocked);
if (r < 0) {
/* Some kind of error */
break;
}
bytes_read += r;
} while (blocked != S2N_NOT_BLOCKED);
```
### s2n\_peek
```c
uint32_t s2n_peek(struct s2n_connection *conn);
```
**s2n_peek** allows users of S2N to peek inside the data buffer of an S2N connection to see if there more data to be read without actually reading it. This is useful when using select() on the underlying S2N file descriptor with a message based application layer protocol. As a single call to s2n_recv may read all data off the underlying file descriptor, select() will be unable to tell you there if there is more application data ready for processing already loaded into the S2N buffer. s2n_peek can then be used to determine if s2n_recv needs to be called before more data comes in on the raw fd.
### s2n\_connection\_set\_send\_cb
```c
int s2n_connection_set_recv_cb(struct s2n_connection *conn, s2n_connection_recv recv);
int s2n_connection_set_send_cb(struct s2n_connection *conn, s2n_connection_send send);
int s2n_connection_set_recv_ctx(struct s2n_connection *conn, void *ctx);
int s2n_connection_set_send_ctx(struct s2n_connection *conn, void *ctx);
```
s2n also provides an I/O abstraction layer in the event the application would
like to keep control over I/O operations. **s2n_connection_set_recv_cb** and
**s2n_connection_set_send_cb** may be used to send or receive data with callbacks
defined by the user. These may be blocking or nonblocking.
```c
typedef int s2n_connection_send(void *io_context, const uint8_t *buf, uint32_t len);
typedef int s2n_connection_recv(void *io_context, uint8_t *buf, uint32_t len);
```
These callbacks take as input a context containing anything needed in the
function (for example, a file descriptor), the buffer holding data to be sent
or received, and the length of the buffer. The **io_context** passed to the
callbacks may be set separately using **s2n_connection_set_recv_ctx** and
**s2n_connection_set_send_ctx**.
The callback may send or receive less than the requested length. The function
should return the number of bytes sent/received, or set errno and return an error code < 0.
### s2n_shutdown
```c
int s2n_shutdown(struct s2n_connection *conn,
s2n_blocked_status *blocked);
```
**s2n_shutdown** attempts a closure at the TLS layer. It does not close the underlying transport. The call may block in either direction.
Unlike other TLS implementations, **s2n_shutdown** attempts a graceful shutdown by default. It will not return with success unless a close_notify alert is successfully
sent and received. As a result, **s2n_shutdown** may fail when interacting with a non-conformant TLS implementation.
Once **s2n_shutdown** is complete:
* The s2n_connection handle cannot be used for reading for writing.
* The underlying transport can be closed. Most likely via `close()`.
* The s2n_connection handle can be freed via [s2n_connection_free](#s2n\_connection\_free) or reused via [s2n_connection_wipe](#s2n\_connection\_wipe)
# Examples
To understand the API it may be easiest to see examples in action. s2n's [bin/](https://github.com/awslabs/s2n/blob/master/bin/) directory
includes an example client (s2nc) and server (s2nd).
| {
"content_hash": "bd8a645aa8c2e996e7a70a80b58e7871",
"timestamp": "",
"source": "github",
"line_count": 1382,
"max_line_length": 599,
"avg_line_length": 43.313314037626625,
"alnum_prop": 0.7268079987971734,
"repo_name": "bpdavidson/s2n",
"id": "8eb9e39e9a00a4ac810ed240cd1c11b702de3a0a",
"size": "59859",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "docs/USAGE-GUIDE.md",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "C",
"bytes": "1598481"
},
{
"name": "C++",
"bytes": "5792"
},
{
"name": "CMake",
"bytes": "8220"
},
{
"name": "Coq",
"bytes": "29938"
},
{
"name": "Makefile",
"bytes": "34441"
},
{
"name": "Objective-C",
"bytes": "1772"
},
{
"name": "Perl",
"bytes": "4169"
},
{
"name": "Python",
"bytes": "72132"
},
{
"name": "Ruby",
"bytes": "6523"
},
{
"name": "Shell",
"bytes": "77714"
}
],
"symlink_target": ""
} |
<?php
namespace Shopware\Plugin\K10rDeployment\Command;
use Shopware\Commands\ShopwareCommand;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
class K10rUpdateNeededCommand extends ShopwareCommand
{
/**
* {@inheritdoc}
*/
protected function configure()
{
$this
->setName('k10r:update:needed')
->setDescription('Verifies if an update is needed for the application to be on a requested version. Return code 0 means an update is needed.')
->addArgument(
'version',
InputArgument::REQUIRED,
'Version of the requested update.'
);
}
/**
* {@inheritdoc}
*/
protected function execute(InputInterface $input, OutputInterface $output)
{
$currentVersion = $this->container->hasParameter('shopware.release.version')
? $this->container->getParameter('shopware.release.version')
: \Shopware::VERSION;
return (int) (version_compare($currentVersion, $input->getArgument('version')) >= 0);
}
}
| {
"content_hash": "7e2ad89bc43e1f0ad69000c4a51fb0d0",
"timestamp": "",
"source": "github",
"line_count": 38,
"max_line_length": 154,
"avg_line_length": 31.236842105263158,
"alnum_prop": 0.645324347093513,
"repo_name": "kellerkinderDE/K10rDeployment",
"id": "a55fe5391b3437c9d3221be242e4b9caff3e0549",
"size": "1187",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "Commands/UpdateNeededCommand.php",
"mode": "33261",
"license": "mit",
"language": [
{
"name": "PHP",
"bytes": "35821"
}
],
"symlink_target": ""
} |
sectionid: order
sectionclass: h3
parent-id: collection-entries
is-parent: yes
number: 3120
title: Order
---
Okay, I have touched upon the order before. As I said, you have two options on how to determine the order of your entries.
The choice of how you go about it, is yours. Both ways have pros and cons, that you have to check for yourself.
We went with the front matter version here, but might go with the numbered files on another Docs. So it might just depend on your mood as well. | {
"content_hash": "24732e2248366804f73f7bd1e682a708",
"timestamp": "",
"source": "github",
"line_count": 12,
"max_line_length": 143,
"avg_line_length": 40.75,
"alnum_prop": 0.7709611451942741,
"repo_name": "DigitalMindCH/docster-jekyll-theme",
"id": "289172320c3c64af7a5a50e22ae82d82a290839e",
"size": "493",
"binary": false,
"copies": "3",
"ref": "refs/heads/gh-pages",
"path": "_entries/order.md",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "15829"
},
{
"name": "HTML",
"bytes": "3737"
},
{
"name": "JavaScript",
"bytes": "10950"
}
],
"symlink_target": ""
} |
#ifndef FIpar_h_
#define FIpar_h_
/* Filter types */
enum {
FI_UNDEF = 0, /* undefined filter file identifier */
FI_FIR = 1, /* FIR filter, direct form */
FI_IIR = 2, /* IIR filter, cascade of biquad sections */
FI_ALL = 3, /* All-pole filter, direct form */
FI_WIN = 4, /* Window coefficients, direct form */
FI_CAS = 5 /* Cascade analog biquad sections */
};
#endif /* FIpar_h_ */
| {
"content_hash": "131cb59559f81f01015b296fce02e166",
"timestamp": "",
"source": "github",
"line_count": 17,
"max_line_length": 58,
"avg_line_length": 23.529411764705884,
"alnum_prop": 0.615,
"repo_name": "andresgonzalezfornell/TFM",
"id": "2b9fa2e40e844ded4d0e0c9f83ca4d300c55c09c",
"size": "771",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "lib/AFsp/include/libtsp/FIpar.h",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C",
"bytes": "3814464"
},
{
"name": "C++",
"bytes": "357361"
},
{
"name": "Makefile",
"bytes": "420567"
},
{
"name": "Objective-C",
"bytes": "5969"
},
{
"name": "QMake",
"bytes": "37093"
},
{
"name": "Roff",
"bytes": "25171"
},
{
"name": "Shell",
"bytes": "53186"
}
],
"symlink_target": ""
} |
package org.apache.activemq.broker.ft;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.SQLException;
import java.sql.SQLFeatureNotSupportedException;
import java.util.logging.Logger;
import javax.sql.DataSource;
import org.apache.derby.jdbc.EmbeddedDataSource;
// prevent concurrent calls from attempting to create the db at the same time
// can result in "already exists in this jvm" errors
public class SyncCreateDataSource implements DataSource {
final EmbeddedDataSource delegate;
SyncCreateDataSource(EmbeddedDataSource dataSource) {
this.delegate = dataSource;
}
@Override
public Connection getConnection() throws SQLException {
synchronized (this) {
return delegate.getConnection();
}
}
@Override
public Connection getConnection(String username, String password) throws SQLException {
synchronized (this) {
return delegate.getConnection();
}
}
@Override
public PrintWriter getLogWriter() throws SQLException {
return null;
}
@Override
public void setLogWriter(PrintWriter out) throws SQLException {
}
@Override
public int getLoginTimeout() throws SQLException {
return 0;
}
@Override
public void setLoginTimeout(int seconds) throws SQLException {
}
@Override
public <T> T unwrap(Class<T> iface) throws SQLException {
return null;
}
@Override
public boolean isWrapperFor(Class<?> iface) throws SQLException {
return false;
}
EmbeddedDataSource getDelegate() {
return delegate;
}
public Logger getParentLogger() throws SQLFeatureNotSupportedException {
return null;
}
} | {
"content_hash": "9ff5103ed7dc8fb89c6b6f707bb9fddc",
"timestamp": "",
"source": "github",
"line_count": 71,
"max_line_length": 91,
"avg_line_length": 24.633802816901408,
"alnum_prop": 0.692967409948542,
"repo_name": "rogerchina/activemq-artemis",
"id": "5331a226a60607c2db3c7965ceec3638ebdee9e2",
"size": "2552",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/ft/SyncCreateDataSource.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Batchfile",
"bytes": "5879"
},
{
"name": "C",
"bytes": "2088"
},
{
"name": "C++",
"bytes": "39402"
},
{
"name": "CSS",
"bytes": "17993"
},
{
"name": "HTML",
"bytes": "658306"
},
{
"name": "Java",
"bytes": "24171053"
},
{
"name": "JavaScript",
"bytes": "31054"
},
{
"name": "Python",
"bytes": "3626"
},
{
"name": "Ruby",
"bytes": "3412"
},
{
"name": "Shell",
"bytes": "11252"
}
],
"symlink_target": ""
} |
#include <iostream>
#include <string>
#include <algorithm>
#include <ctype.h>
using namespace std;
class Palindrome {
private:
string text; // String variable to hold the user inputted string of text to test.
public:
bool Check(string text, unsigned int place = 0) {
/* ************************************
This function checks if the text string
is a Palindrome or not.
Returns true if it is, false if not.
************************************ */
// Set len to the length of the new string.
unsigned int len = text.length();
if (place >= len / 2) {
/*
If place is already reached an integer that is greater than
or equal to half the string length, return true since it is
a Palindrome.
*/
return true;
}
else {
char a = text.at(place); // Set a to the current string place from the beginning of the string.
while (!isalpha(a)) {
// This loop will filter out any non-alphabet characters and adjust the string as necessary.
text.erase(text.begin() + place);
len = text.length();
a = text.at(place);
}
char b = text.at(len - 1 - place); // Set b to the current string place from the end of the string.
while (!isalpha(b)) {
// This loop will filter out any non-alphabet characters and adjust the string as necessary.
text.erase(text.end() - place);
len = text.length();
b = text.at(len - 1 - place);
}
if (tolower(a) == tolower(b)) { // Compare a and b.
if (!Check(text, place + 1)) { // If a == b, continue recursion.
return false; // If any recursion returns false, the rest of the stack will return false.
}
}
else {
// If a ever does not equal b, this will return false and cause the rest of the stack to return false.
return false;
}
}
}
void AskUser() {
/* ************************************
This function asks the user to input
a string to be checked.
It will continually ask for new strings
until the user inputs nothing and
presses enter.
************************************ */
do {
cout << "Please input a string: ";
getline(cin, this->text);
if (this->Check(this->text) && this->text != "") {
cout << "The string entered is a Palindrome." << endl;
}
else if (!this->Check(this->text)) {
cout << "The string entered is not a Palindrome" << endl;
}
else {
return;
}
} while (this->text != "");
}
};
int main() {
Palindrome test; // Initialize the class object.
test.AskUser(); // Run the AskUser() function to begin the program.
return 0;
}
| {
"content_hash": "bd317c94108cfa511c15cd2a233b3398",
"timestamp": "",
"source": "github",
"line_count": 89,
"max_line_length": 106,
"avg_line_length": 28.719101123595507,
"alnum_prop": 0.5985915492957746,
"repo_name": "Vinlock/Moorpark-M10A",
"id": "79d782345d41448c170ef31a3dee5806251a1654",
"size": "2556",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "M10B/Homework/Homework-4/While-Loop-Filter-Version.cpp",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C++",
"bytes": "75585"
}
],
"symlink_target": ""
} |
namespace llvm {
/// Helper class that can build very simple Modules
class TrivialModuleBuilder {
protected:
LLVMContext Context;
IRBuilder<> Builder;
std::string BuilderTriple;
TrivialModuleBuilder(const std::string &Triple)
: Builder(Context), BuilderTriple(Triple) {}
Module *createEmptyModule(StringRef Name = StringRef()) {
Module * M = new Module(Name, Context);
M->setTargetTriple(Triple::normalize(BuilderTriple));
return M;
}
template<typename FuncType>
Function *startFunction(Module *M, StringRef Name) {
Function *Result = Function::Create(
TypeBuilder<FuncType, false>::get(Context),
GlobalValue::ExternalLinkage, Name, M);
BasicBlock *BB = BasicBlock::Create(Context, Name, Result);
Builder.SetInsertPoint(BB);
return Result;
}
void endFunctionWithRet(Function *Func, Value *RetValue) {
Builder.CreateRet(RetValue);
}
// Inserts a simple function that invokes Callee and takes the same arguments:
// int Caller(...) { return Callee(...); }
template<typename Signature>
Function *insertSimpleCallFunction(Module *M, Function *Callee) {
Function *Result = startFunction<Signature>(M, "caller");
SmallVector<Value*, 1> CallArgs;
for (Argument &A : Result->args())
CallArgs.push_back(&A);
Value *ReturnCode = Builder.CreateCall(Callee, CallArgs);
Builder.CreateRet(ReturnCode);
return Result;
}
// Inserts a function named 'main' that returns a uint32_t:
// int32_t main() { return X; }
// where X is given by returnCode
Function *insertMainFunction(Module *M, uint32_t returnCode) {
Function *Result = startFunction<int32_t(void)>(M, "main");
Value *ReturnVal = ConstantInt::get(Context, APInt(32, returnCode));
endFunctionWithRet(Result, ReturnVal);
return Result;
}
// Inserts a function
// int32_t add(int32_t a, int32_t b) { return a + b; }
// in the current module and returns a pointer to it.
Function *insertAddFunction(Module *M, StringRef Name = "add") {
Function *Result = startFunction<int32_t(int32_t, int32_t)>(M, Name);
Function::arg_iterator args = Result->arg_begin();
Value *Arg1 = &*args;
Value *Arg2 = &*++args;
Value *AddResult = Builder.CreateAdd(Arg1, Arg2);
endFunctionWithRet(Result, AddResult);
return Result;
}
// Inserts a declaration to a function defined elsewhere
template <typename FuncType>
Function *insertExternalReferenceToFunction(Module *M, StringRef Name) {
Function *Result = Function::Create(
TypeBuilder<FuncType, false>::get(Context),
GlobalValue::ExternalLinkage, Name, M);
return Result;
}
// Inserts an declaration to a function defined elsewhere
Function *insertExternalReferenceToFunction(Module *M, StringRef Name,
FunctionType *FuncTy) {
Function *Result = Function::Create(FuncTy,
GlobalValue::ExternalLinkage,
Name, M);
return Result;
}
// Inserts an declaration to a function defined elsewhere
Function *insertExternalReferenceToFunction(Module *M, Function *Func) {
Function *Result = Function::Create(Func->getFunctionType(),
GlobalValue::ExternalLinkage,
Func->getName(), M);
return Result;
}
// Inserts a global variable of type int32
// FIXME: make this a template function to support any type
GlobalVariable *insertGlobalInt32(Module *M,
StringRef name,
int32_t InitialValue) {
Type *GlobalTy = TypeBuilder<types::i<32>, true>::get(Context);
Constant *IV = ConstantInt::get(Context, APInt(32, InitialValue));
GlobalVariable *Global = new GlobalVariable(*M,
GlobalTy,
false,
GlobalValue::ExternalLinkage,
IV,
name);
return Global;
}
// Inserts a function
// int32_t recursive_add(int32_t num) {
// if (num == 0) {
// return num;
// } else {
// int32_t recursive_param = num - 1;
// return num + Helper(recursive_param);
// }
// }
// NOTE: if Helper is left as the default parameter, Helper == recursive_add.
Function *insertAccumulateFunction(Module *M,
Function *Helper = nullptr,
StringRef Name = "accumulate") {
Function *Result = startFunction<int32_t(int32_t)>(M, Name);
if (!Helper)
Helper = Result;
BasicBlock *BaseCase = BasicBlock::Create(Context, "", Result);
BasicBlock *RecursiveCase = BasicBlock::Create(Context, "", Result);
// if (num == 0)
Value *Param = &*Result->arg_begin();
Value *Zero = ConstantInt::get(Context, APInt(32, 0));
Builder.CreateCondBr(Builder.CreateICmpEQ(Param, Zero),
BaseCase, RecursiveCase);
// return num;
Builder.SetInsertPoint(BaseCase);
Builder.CreateRet(Param);
// int32_t recursive_param = num - 1;
// return Helper(recursive_param);
Builder.SetInsertPoint(RecursiveCase);
Value *One = ConstantInt::get(Context, APInt(32, 1));
Value *RecursiveParam = Builder.CreateSub(Param, One);
Value *RecursiveReturn = Builder.CreateCall(Helper, RecursiveParam);
Value *Accumulator = Builder.CreateAdd(Param, RecursiveReturn);
Builder.CreateRet(Accumulator);
return Result;
}
// Populates Modules A and B:
// Module A { Extern FB1, Function FA which calls FB1 },
// Module B { Extern FA, Function FB1, Function FB2 which calls FA },
void createCrossModuleRecursiveCase(std::unique_ptr<Module> &A, Function *&FA,
std::unique_ptr<Module> &B,
Function *&FB1, Function *&FB2) {
// Define FB1 in B.
B.reset(createEmptyModule("B"));
FB1 = insertAccumulateFunction(B.get(), nullptr, "FB1");
// Declare FB1 in A (as an external).
A.reset(createEmptyModule("A"));
Function *FB1Extern = insertExternalReferenceToFunction(A.get(), FB1);
// Define FA in A (with a call to FB1).
FA = insertAccumulateFunction(A.get(), FB1Extern, "FA");
// Declare FA in B (as an external)
Function *FAExtern = insertExternalReferenceToFunction(B.get(), FA);
// Define FB2 in B (with a call to FA)
FB2 = insertAccumulateFunction(B.get(), FAExtern, "FB2");
}
// Module A { Function FA },
// Module B { Extern FA, Function FB which calls FA },
// Module C { Extern FB, Function FC which calls FB },
void
createThreeModuleChainedCallsCase(std::unique_ptr<Module> &A, Function *&FA,
std::unique_ptr<Module> &B, Function *&FB,
std::unique_ptr<Module> &C, Function *&FC) {
A.reset(createEmptyModule("A"));
FA = insertAddFunction(A.get());
B.reset(createEmptyModule("B"));
Function *FAExtern_in_B = insertExternalReferenceToFunction(B.get(), FA);
FB = insertSimpleCallFunction<int32_t(int32_t, int32_t)>(B.get(), FAExtern_in_B);
C.reset(createEmptyModule("C"));
Function *FBExtern_in_C = insertExternalReferenceToFunction(C.get(), FB);
FC = insertSimpleCallFunction<int32_t(int32_t, int32_t)>(C.get(), FBExtern_in_C);
}
// Module A { Function FA },
// Populates Modules A and B:
// Module B { Function FB }
void createTwoModuleCase(std::unique_ptr<Module> &A, Function *&FA,
std::unique_ptr<Module> &B, Function *&FB) {
A.reset(createEmptyModule("A"));
FA = insertAddFunction(A.get());
B.reset(createEmptyModule("B"));
FB = insertAddFunction(B.get());
}
// Module A { Function FA },
// Module B { Extern FA, Function FB which calls FA }
void createTwoModuleExternCase(std::unique_ptr<Module> &A, Function *&FA,
std::unique_ptr<Module> &B, Function *&FB) {
A.reset(createEmptyModule("A"));
FA = insertAddFunction(A.get());
B.reset(createEmptyModule("B"));
Function *FAExtern_in_B = insertExternalReferenceToFunction(B.get(), FA);
FB = insertSimpleCallFunction<int32_t(int32_t, int32_t)>(B.get(),
FAExtern_in_B);
}
// Module A { Function FA },
// Module B { Extern FA, Function FB which calls FA },
// Module C { Extern FB, Function FC which calls FA },
void createThreeModuleCase(std::unique_ptr<Module> &A, Function *&FA,
std::unique_ptr<Module> &B, Function *&FB,
std::unique_ptr<Module> &C, Function *&FC) {
A.reset(createEmptyModule("A"));
FA = insertAddFunction(A.get());
B.reset(createEmptyModule("B"));
Function *FAExtern_in_B = insertExternalReferenceToFunction(B.get(), FA);
FB = insertSimpleCallFunction<int32_t(int32_t, int32_t)>(B.get(), FAExtern_in_B);
C.reset(createEmptyModule("C"));
Function *FAExtern_in_C = insertExternalReferenceToFunction(C.get(), FA);
FC = insertSimpleCallFunction<int32_t(int32_t, int32_t)>(C.get(), FAExtern_in_C);
}
};
class MCJITTestBase : public MCJITTestAPICommon, public TrivialModuleBuilder {
protected:
MCJITTestBase()
: TrivialModuleBuilder(HostTriple), OptLevel(CodeGenOpt::None),
CodeModel(CodeModel::Small), MArch(""), MM(new SectionMemoryManager) {
// The architectures below are known to be compatible with MCJIT as they
// are copied from test/ExecutionEngine/MCJIT/lit.local.cfg and should be
// kept in sync.
SupportedArchs.push_back(Triple::aarch64);
SupportedArchs.push_back(Triple::arm);
SupportedArchs.push_back(Triple::mips);
SupportedArchs.push_back(Triple::mipsel);
SupportedArchs.push_back(Triple::mips64);
SupportedArchs.push_back(Triple::mips64el);
SupportedArchs.push_back(Triple::x86);
SupportedArchs.push_back(Triple::x86_64);
// Some architectures have sub-architectures in which tests will fail, like
// ARM. These two vectors will define if they do have sub-archs (to avoid
// extra work for those who don't), and if so, if they are listed to work
HasSubArchs.push_back(Triple::arm);
SupportedSubArchs.push_back("armv6");
SupportedSubArchs.push_back("armv7");
UnsupportedEnvironments.push_back(Triple::Cygnus);
}
void createJIT(std::unique_ptr<Module> M) {
// Due to the EngineBuilder constructor, it is required to have a Module
// in order to construct an ExecutionEngine (i.e. MCJIT)
assert(M != 0 && "a non-null Module must be provided to create MCJIT");
EngineBuilder EB(std::move(M));
std::string Error;
TheJIT.reset(EB.setEngineKind(EngineKind::JIT)
.setMCJITMemoryManager(std::move(MM))
.setErrorStr(&Error)
.setOptLevel(CodeGenOpt::None)
.setMArch(MArch)
.setMCPU(sys::getHostCPUName())
//.setMAttrs(MAttrs)
.create());
// At this point, we cannot modify the module any more.
assert(TheJIT.get() != NULL && "error creating MCJIT with EngineBuilder");
}
CodeGenOpt::Level OptLevel;
CodeModel::Model CodeModel;
StringRef MArch;
SmallVector<std::string, 1> MAttrs;
std::unique_ptr<ExecutionEngine> TheJIT;
std::unique_ptr<RTDyldMemoryManager> MM;
std::unique_ptr<Module> M;
};
} // namespace llvm
#endif // LLVM_UNITTESTS_EXECUTIONENGINE_MCJIT_MCJITTESTBASE_H
| {
"content_hash": "454f24decb3263700fe571a9f3c15981",
"timestamp": "",
"source": "github",
"line_count": 309,
"max_line_length": 85,
"avg_line_length": 38.20388349514563,
"alnum_prop": 0.6234646336298179,
"repo_name": "youtube/cobalt",
"id": "a768920ff479ce6d02437cb512125bd0008b4d5a",
"size": "12885",
"binary": false,
"copies": "8",
"ref": "refs/heads/master",
"path": "third_party/llvm-project/llvm/unittests/ExecutionEngine/MCJIT/MCJITTestBase.h",
"mode": "33188",
"license": "bsd-3-clause",
"language": [],
"symlink_target": ""
} |
<?php
/**
* CFileHelper provides a set of helper methods for common file system operations.
*
* @author Qiang Xue <qiang.xue@gmail.com>
* @package system.utils
* @since 1.0
*/
class CFileHelper
{
/**
* Returns the extension name of a file path.
* For example, the path "path/to/something.php" would return "php".
* @param string $path the file path
* @return string the extension name without the dot character.
* @since 1.1.2
*/
public static function getExtension($path)
{
return pathinfo($path,PATHINFO_EXTENSION);
}
/**
* Copies a directory recursively as another.
* If the destination directory does not exist, it will be created recursively.
* @param string $src the source directory
* @param string $dst the destination directory
* @param array $options options for directory copy. Valid options are:
* <ul>
* <li>fileTypes: array, list of file name suffix (without dot). Only files with these suffixes will be copied.</li>
* <li>exclude: array, list of directory and file exclusions. Each exclusion can be either a name or a path.
* If a file or directory name or path matches the exclusion, it will not be copied. For example, an exclusion of
* '.svn' will exclude all files and directories whose name is '.svn'. And an exclusion of '/a/b' will exclude
* file or directory '$src/a/b'. Note, that '/' should be used as separator regardless of the value of the DIRECTORY_SEPARATOR constant.
* </li>
* <li>level: integer, recursion depth, default=-1.
* Level -1 means copying all directories and files under the directory;
* Level 0 means copying only the files DIRECTLY under the directory;
* level N means copying those directories that are within N levels.
* </li>
* <li>newDirMode - the permission to be set for newly copied directories (defaults to 0777);</li>
* <li>newFileMode - the permission to be set for newly copied files (defaults to the current environment setting).</li>
* </ul>
*/
public static function copyDirectory($src,$dst,$options=array())
{
$fileTypes=array();
$exclude=array();
$level=-1;
extract($options);
if(!is_dir($dst))
self::createDirectory($dst,isset($options['newDirMode'])?$options['newDirMode']:null,true);
self::copyDirectoryRecursive($src,$dst,'',$fileTypes,$exclude,$level,$options);
}
/**
* Removes a directory recursively.
* @param string $directory to be deleted recursively.
* @since 1.1.14
*/
public static function removeDirectory($directory)
{
$items=glob($directory.DIRECTORY_SEPARATOR.'{,.}*',GLOB_MARK | GLOB_BRACE);
foreach($items as $item)
{
if(basename($item)=='.' || basename($item)=='..')
continue;
if(substr($item,-1)==DIRECTORY_SEPARATOR)
self::removeDirectory($item);
else
unlink($item);
}
if(is_dir($directory))
rmdir($directory);
}
/**
* Returns the files found under the specified directory and subdirectories.
* @param string $dir the directory under which the files will be looked for
* @param array $options options for file searching. Valid options are:
* <ul>
* <li>fileTypes: array, list of file name suffix (without dot). Only files with these suffixes will be returned.</li>
* <li>exclude: array, list of directory and file exclusions. Each exclusion can be either a name or a path.
* If a file or directory name or path matches the exclusion, it will not be copied. For example, an exclusion of
* '.svn' will exclude all files and directories whose name is '.svn'. And an exclusion of '/a/b' will exclude
* file or directory '$src/a/b'. Note, that '/' should be used as separator regardless of the value of the DIRECTORY_SEPARATOR constant.
* </li>
* <li>level: integer, recursion depth, default=-1.
* Level -1 means searching for all directories and files under the directory;
* Level 0 means searching for only the files DIRECTLY under the directory;
* level N means searching for those directories that are within N levels.
* </li>
* <li>absolutePaths: boolean, whether to return absolute paths or relative ones, defaults to true.</li>
* </ul>
* @return array files found under the directory. The file list is sorted.
*/
public static function findFiles($dir,$options=array())
{
$fileTypes=array();
$exclude=array();
$level=-1;
$absolutePaths=true;
extract($options);
$list=self::findFilesRecursive($dir,'',$fileTypes,$exclude,$level,$absolutePaths);
sort($list);
return $list;
}
/**
* Copies a directory.
* This method is mainly used by {@link copyDirectory}.
* @param string $src the source directory
* @param string $dst the destination directory
* @param string $base the path relative to the original source directory
* @param array $fileTypes list of file name suffix (without dot). Only files with these suffixes will be copied.
* @param array $exclude list of directory and file exclusions. Each exclusion can be either a name or a path.
* If a file or directory name or path matches the exclusion, it will not be copied. For example, an exclusion of
* '.svn' will exclude all files and directories whose name is '.svn'. And an exclusion of '/a/b' will exclude
* file or directory '$src/a/b'. Note, that '/' should be used as separator regardless of the value of the DIRECTORY_SEPARATOR constant.
* @param integer $level recursion depth. It defaults to -1.
* Level -1 means copying all directories and files under the directory;
* Level 0 means copying only the files DIRECTLY under the directory;
* level N means copying those directories that are within N levels.
* @param array $options additional options. The following options are supported:
* newDirMode - the permission to be set for newly copied directories (defaults to 0777);
* newFileMode - the permission to be set for newly copied files (defaults to the current environment setting).
*/
protected static function copyDirectoryRecursive($src,$dst,$base,$fileTypes,$exclude,$level,$options)
{
if(!is_dir($dst))
self::createDirectory($dst,isset($options['newDirMode'])?$options['newDirMode']:null,false);
$folder=opendir($src);
while(($file=readdir($folder))!==false)
{
if($file==='.' || $file==='..')
continue;
$path=$src.DIRECTORY_SEPARATOR.$file;
$isFile=is_file($path);
if(self::validatePath($base,$file,$isFile,$fileTypes,$exclude))
{
if($isFile)
{
copy($path,$dst.DIRECTORY_SEPARATOR.$file);
if(isset($options['newFileMode']))
@chmod($dst.DIRECTORY_SEPARATOR.$file,$options['newFileMode']);
}
elseif($level)
self::copyDirectoryRecursive($path,$dst.DIRECTORY_SEPARATOR.$file,$base.'/'.$file,$fileTypes,$exclude,$level-1,$options);
}
}
closedir($folder);
}
/**
* Returns the files found under the specified directory and subdirectories.
* This method is mainly used by {@link findFiles}.
* @param string $dir the source directory
* @param string $base the path relative to the original source directory
* @param array $fileTypes list of file name suffix (without dot). Only files with these suffixes will be returned.
* @param array $exclude list of directory and file exclusions. Each exclusion can be either a name or a path.
* If a file or directory name or path matches the exclusion, it will not be copied. For example, an exclusion of
* '.svn' will exclude all files and directories whose name is '.svn'. And an exclusion of '/a/b' will exclude
* file or directory '$src/a/b'. Note, that '/' should be used as separator regardless of the value of the DIRECTORY_SEPARATOR constant.
* @param integer $level recursion depth. It defaults to -1.
* Level -1 means searching for all directories and files under the directory;
* Level 0 means searching for only the files DIRECTLY under the directory;
* level N means searching for those directories that are within N levels.
* @param boolean $absolutePaths whether to return absolute paths or relative ones
* @return array files found under the directory.
*/
protected static function findFilesRecursive($dir,$base,$fileTypes,$exclude,$level,$absolutePaths)
{
$list=array();
$handle=opendir($dir.$base);
while(($file=readdir($handle))!==false)
{
if($file==='.' || $file==='..')
continue;
$path=substr($base.DIRECTORY_SEPARATOR.$file,1);
$fullPath=$dir.DIRECTORY_SEPARATOR.$path;
$isFile=is_file($fullPath);
if(self::validatePath($base,$file,$isFile,$fileTypes,$exclude))
{
if($isFile)
$list[]=$absolutePaths?$fullPath:$path;
elseif($level)
$list=array_merge($list,self::findFilesRecursive($dir,$base.'/'.$file,$fileTypes,$exclude,$level-1,$absolutePaths));
}
}
closedir($handle);
return $list;
}
/**
* Validates a file or directory.
* @param string $base the path relative to the original source directory
* @param string $file the file or directory name
* @param boolean $isFile whether this is a file
* @param array $fileTypes list of valid file name suffixes (without dot).
* @param array $exclude list of directory and file exclusions. Each exclusion can be either a name or a path.
* If a file or directory name or path matches the exclusion, false will be returned. For example, an exclusion of
* '.svn' will return false for all files and directories whose name is '.svn'. And an exclusion of '/a/b' will return false for
* file or directory '$src/a/b'. Note, that '/' should be used as separator regardless of the value of the DIRECTORY_SEPARATOR constant.
* @return boolean whether the file or directory is valid
*/
protected static function validatePath($base,$file,$isFile,$fileTypes,$exclude)
{
foreach($exclude as $e)
{
if($file===$e || strpos($base.'/'.$file,$e)===0)
return false;
}
if(!$isFile || empty($fileTypes))
return true;
if(($type=pathinfo($file,PATHINFO_EXTENSION))!=='')
return in_array($type,$fileTypes);
else
return false;
}
/**
* Determines the MIME type of the specified file.
* This method will attempt the following approaches in order:
* <ol>
* <li>finfo</li>
* <li>mime_content_type</li>
* <li>{@link getMimeTypeByExtension}, when $checkExtension is set true.</li>
* </ol>
* @param string $file the file name.
* @param string $magicFile name of a magic database file, usually something like /path/to/magic.mime.
* This will be passed as the second parameter to {@link http://php.net/manual/en/function.finfo-open.php finfo_open}.
* Magic file format described in {@link http://linux.die.net/man/5/magic man 5 magic}, note that this file does not
* contain a standard PHP array as you might suppose. Specified magic file will be used only when fileinfo
* PHP extension is available. This parameter has been available since version 1.1.3.
* @param boolean $checkExtension whether to check the file extension in case the MIME type cannot be determined
* based on finfo and mime_content_type. Defaults to true. This parameter has been available since version 1.1.4.
* @return string the MIME type. Null is returned if the MIME type cannot be determined.
*/
public static function getMimeType($file,$magicFile=null,$checkExtension=true)
{
if(function_exists('finfo_open'))
{
$options=defined('FILEINFO_MIME_TYPE') ? FILEINFO_MIME_TYPE : FILEINFO_MIME;
$info=$magicFile===null ? finfo_open($options) : finfo_open($options,$magicFile);
if($info && ($result=finfo_file($info,$file))!==false)
return $result;
}
if(function_exists('mime_content_type') && ($result=mime_content_type($file))!==false)
return $result;
return $checkExtension ? self::getMimeTypeByExtension($file) : null;
}
/**
* Determines the MIME type based on the extension name of the specified file.
* This method will use a local map between extension name and MIME type.
* @param string $file the file name.
* @param string $magicFile the path of the file that contains all available MIME type information.
* If this is not set, the default 'system.utils.mimeTypes' file will be used.
* This parameter has been available since version 1.1.3.
* @return string the MIME type. Null is returned if the MIME type cannot be determined.
*/
public static function getMimeTypeByExtension($file,$magicFile=null)
{
static $extensions,$customExtensions=array();
if($magicFile===null && $extensions===null)
$extensions=require(Yii::getPathOfAlias('system.utils.mimeTypes').'.php');
elseif($magicFile!==null && !isset($customExtensions[$magicFile]))
$customExtensions[$magicFile]=require($magicFile);
if(($ext=pathinfo($file,PATHINFO_EXTENSION))!=='')
{
$ext=strtolower($ext);
if($magicFile===null && isset($extensions[$ext]))
return $extensions[$ext];
elseif($magicFile!==null && isset($customExtensions[$magicFile][$ext]))
return $customExtensions[$magicFile][$ext];
}
return null;
}
/**
* Shared environment safe version of mkdir. Supports recursive creation.
* For avoidance of umask side-effects chmod is used.
*
* @param string $dst path to be created
* @param integer $mode the permission to be set for newly created directories, if not set - 0777 will be used
* @param boolean $recursive whether to create directory structure recursive if parent dirs do not exist
* @return boolean result of mkdir
* @see mkdir
*/
public static function createDirectory($dst,$mode=null,$recursive=false)
{
if($mode===null)
$mode=0777;
$prevDir=dirname($dst);
if($recursive && !is_dir($dst) && !is_dir($prevDir))
self::createDirectory(dirname($dst),$mode,true);
$res=mkdir($dst, $mode);
@chmod($dst,$mode);
return $res;
}
}
| {
"content_hash": "df605d319358ef77e19eeaf7c1ba8379",
"timestamp": "",
"source": "github",
"line_count": 308,
"max_line_length": 137,
"avg_line_length": 44.22727272727273,
"alnum_prop": 0.7077521656144472,
"repo_name": "silago/yiiproject",
"id": "f659e61c876339d44ac30053758bb9ab0a012ebf",
"size": "13830",
"binary": false,
"copies": "4",
"ref": "refs/heads/master",
"path": "framework/utils/CFileHelper.php",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "C",
"bytes": "30990"
},
{
"name": "CSS",
"bytes": "881998"
},
{
"name": "Erlang",
"bytes": "259"
},
{
"name": "JavaScript",
"bytes": "3486286"
},
{
"name": "PHP",
"bytes": "18785174"
},
{
"name": "Perl",
"bytes": "32121"
},
{
"name": "Shell",
"bytes": "2935"
},
{
"name": "TeX",
"bytes": "16114"
}
],
"symlink_target": ""
} |
<?php
declare(strict_types=1);
namespace Sylius\Bundle\CoreBundle\Doctrine\DQL;
use Doctrine\DBAL\Platforms\MySQLPlatform;
use Doctrine\DBAL\Platforms\PostgreSQLPlatform;
use Doctrine\ORM\Query\AST\Functions\FunctionNode;
use Doctrine\ORM\Query\AST\Node;
use Doctrine\ORM\Query\Lexer;
use Doctrine\ORM\Query\Parser;
use Doctrine\ORM\Query\SqlWalker;
final class Hour extends FunctionNode
{
/** @var Node|string|null */
public $date;
public function parse(Parser $parser): void
{
$parser->match(Lexer::T_IDENTIFIER);
$parser->match(Lexer::T_OPEN_PARENTHESIS);
$this->date = $parser->ArithmeticPrimary();
$parser->match(Lexer::T_CLOSE_PARENTHESIS);
}
public function getSql(SqlWalker $sqlWalker): string
{
$platform = $sqlWalker->getConnection()->getDatabasePlatform();
if (is_a($platform, MySQLPlatform::class, true)) {
return sprintf('HOUR(%s)', $sqlWalker->walkArithmeticPrimary($this->date));
}
if (is_a($platform, PostgreSQLPlatform::class, true)) {
return sprintf('EXTRACT(HOUR FROM %s)', $sqlWalker->walkArithmeticPrimary($this->date));
}
throw new \RuntimeException(sprintf('Platform "%s" is not supported!', get_class($platform)));
}
}
| {
"content_hash": "6c0e3c4cfb3eadc600f41ac51f812004",
"timestamp": "",
"source": "github",
"line_count": 46,
"max_line_length": 102,
"avg_line_length": 28.08695652173913,
"alnum_prop": 0.6718266253869969,
"repo_name": "diimpp/Sylius",
"id": "e1308762a0ee7efbbc56ce6da6de55aec245a81c",
"size": "1503",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "src/Sylius/Bundle/CoreBundle/Doctrine/DQL/Hour.php",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Dockerfile",
"bytes": "674"
},
{
"name": "Gherkin",
"bytes": "1269548"
},
{
"name": "JavaScript",
"bytes": "102771"
},
{
"name": "Makefile",
"bytes": "1478"
},
{
"name": "PHP",
"bytes": "8145147"
},
{
"name": "SCSS",
"bytes": "53880"
},
{
"name": "Shell",
"bytes": "11411"
},
{
"name": "Twig",
"bytes": "446530"
}
],
"symlink_target": ""
} |
import tensorflow as tf
import random
from sklearn import datasets, metrics
from sklearn.cross_validation import train_test_split
import skflow
class CustomDecayTest(tf.test.TestCase):
def testIrisExponentialDecay(self):
random.seed(42)
iris = datasets.load_iris()
X_train, X_test, y_train, y_test = train_test_split(iris.data,
iris.target,
test_size=0.2,
random_state=42)
# setup exponential decay function
def exp_decay(global_step):
return tf.train.exponential_decay(
learning_rate=0.1, global_step=global_step,
decay_steps=100, decay_rate=0.001)
classifier = skflow.TensorFlowDNNClassifier(hidden_units=[10, 20, 10],
n_classes=3, steps=800,
learning_rate=exp_decay)
classifier.fit(X_train, y_train)
score = metrics.accuracy_score(y_test, classifier.predict(X_test))
self.assertGreater(score, 0.7, "Failed with score = {0}".format(score))
if __name__ == "__main__":
tf.test.main()
| {
"content_hash": "7bb0409b8bb63f6f0aa9ed17347713cc",
"timestamp": "",
"source": "github",
"line_count": 34,
"max_line_length": 79,
"avg_line_length": 38.23529411764706,
"alnum_prop": 0.52,
"repo_name": "RTHMaK/RPGOne",
"id": "0281c81881e1b54382866705bb5186720c5dc843",
"size": "1921",
"binary": false,
"copies": "3",
"ref": "refs/heads/master",
"path": "Documents/skflow-master/skflow/tests/test_custom_decay.py",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "1C Enterprise",
"bytes": "36"
},
{
"name": "Batchfile",
"bytes": "15029"
},
{
"name": "CSS",
"bytes": "41709"
},
{
"name": "Erlang",
"bytes": "39438"
},
{
"name": "Go",
"bytes": "287"
},
{
"name": "HTML",
"bytes": "633076"
},
{
"name": "JavaScript",
"bytes": "1128791"
},
{
"name": "Jupyter Notebook",
"bytes": "927247"
},
{
"name": "Makefile",
"bytes": "31756"
},
{
"name": "Mako",
"bytes": "494"
},
{
"name": "Matlab",
"bytes": "9454"
},
{
"name": "PHP",
"bytes": "708541"
},
{
"name": "PowerShell",
"bytes": "68503"
},
{
"name": "Python",
"bytes": "2278740"
},
{
"name": "Ruby",
"bytes": "1136"
},
{
"name": "Shell",
"bytes": "62555"
},
{
"name": "Smarty",
"bytes": "5752"
},
{
"name": "TeX",
"bytes": "34544"
}
],
"symlink_target": ""
} |
package de.nx42.maps4cim.map.texture.data;
import de.nx42.maps4cim.config.texture.ColorDef;
import de.nx42.maps4cim.util.math.MathExt;
public class TexHexTriplet {
protected static final int sigDigits = 4;
public final int roughgrass;
public final int mud;
public final int dirt;
public TexHexTriplet(int roughgrass, int mud, int dirt) {
this.roughgrass = roughgrass;
this.mud = mud;
this.dirt = dirt;
}
// getters
/**
* @return the roughgrass
*/
public int getRoughgrass() {
return roughgrass;
}
/**
* @return the mud
*/
public int getMud() {
return mud;
}
/**
* @return the dirt
*/
public int getDirt() {
return dirt;
}
public String getHexString() {
return toTwoDigitHex(roughgrass) + toTwoDigitHex(mud) + toTwoDigitHex(dirt);
}
public int getTexture() {
return Texture.draw(roughgrass, mud, dirt);
}
public ColorDef getColorDef() {
final double r = MathExt.round(roughgrass / 255d, sigDigits);
final double m = MathExt.round(mud / 255d, sigDigits);
final double d = MathExt.round(dirt / 255d, sigDigits);
return new ColorDef() {{
roughGrass = r;
mud = m;
dirt = d;
}};
}
// constructors / parsers
public static TexHexTriplet of(double roughgrass, double mud, double dirt) {
int r = (int) (minMaxCutoff(roughgrass, 0, 1) * 255);
int m = (int) (minMaxCutoff(mud, 0, 1) * 255);
int d = (int) (minMaxCutoff(dirt, 0, 1) * 255);
return new TexHexTriplet(r, m, d);
}
public static TexHexTriplet of(int roughgrass, int mud, int dirt) {
return new TexHexTriplet(roughgrass, mud, dirt);
}
public static TexHexTriplet of(ColorDef c) {
return TexHexTriplet.of(c.getSafeRoughGrass(), c.getSafeMud(), c.getSafeDirt());
}
public static TexHexTriplet parse(String s) throws NumberFormatException {
String hex = s.startsWith("#") ? s.substring(1) : s;
if(hex.length() == 6) {
return parse(Integer.parseInt(hex, 16));
} else {
throw new NumberFormatException(hex + " is not a valid hex triplet");
}
}
public static TexHexTriplet parse(int hex) {
int r = (hex >>> 16) & 0xFF;
int m = (hex >>> 8) & 0xFF;
int d = (hex ) & 0xFF;
return new TexHexTriplet(r, m, d);
}
// static helpers
public static String convertToHexString(int roughgrass, int mud, int dirt) {
return toTwoDigitHex(roughgrass) + toTwoDigitHex(mud) + toTwoDigitHex(dirt);
}
protected static double minMaxCutoff(double input, double min, double max) {
return input > max ? max : input < min ? min : input;
}
protected static String toTwoDigitHex(int input) {
int normalized = (int) minMaxCutoff(input, 0, 255);
String hex = Integer.toHexString(normalized);
return normalized < 16 ? "0" + hex : hex;
}
// Object overrides
/* (non-Javadoc)
* @see java.lang.Object#hashCode()
*/
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + dirt;
result = prime * result + mud;
result = prime * result + roughgrass;
return result;
}
/* (non-Javadoc)
* @see java.lang.Object#equals(java.lang.Object)
*/
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
TexHexTriplet other = (TexHexTriplet) obj;
if (dirt != other.dirt)
return false;
if (mud != other.mud)
return false;
if (roughgrass != other.roughgrass)
return false;
return true;
}
/* (non-Javadoc)
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
return "#" + getHexString();
}
}
| {
"content_hash": "45a20bf798db151b14a68fc595a465e1",
"timestamp": "",
"source": "github",
"line_count": 157,
"max_line_length": 88,
"avg_line_length": 26.528662420382165,
"alnum_prop": 0.5723889555822329,
"repo_name": "Klamann/maps4cim",
"id": "b5923287761159d5555994ce5082068b22370722",
"size": "4823",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "maps4cim-core/src/main/java/de/nx42/maps4cim/map/texture/data/TexHexTriplet.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "HTML",
"bytes": "815298"
},
{
"name": "Java",
"bytes": "1012653"
},
{
"name": "Shell",
"bytes": "42"
}
],
"symlink_target": ""
} |
module EnderecosHelper
end
| {
"content_hash": "101ae6e3397a3e90a71f36380581371b",
"timestamp": "",
"source": "github",
"line_count": 2,
"max_line_length": 22,
"avg_line_length": 13.5,
"alnum_prop": 0.8888888888888888,
"repo_name": "gledsoncruz/center-click-sistema-de-condominio",
"id": "2e939bde468211fa2315fde62d9426829d5bd97b",
"size": "27",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "app/helpers/enderecos_helper.rb",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "2556"
},
{
"name": "CoffeeScript",
"bytes": "1581"
},
{
"name": "HTML",
"bytes": "25136"
},
{
"name": "JavaScript",
"bytes": "691"
},
{
"name": "Ruby",
"bytes": "68080"
}
],
"symlink_target": ""
} |
title: arh44
type: products
image: /img/Screen Shot 2017-05-09 at 11.56.54 AM.png
heading: h44
description: lksadjf lkasdjf lksajdf lksdaj flksadj flksa fdj
main:
heading: Foo Bar BAz
description: |-
***This is i a thing***kjh hjk kj
# Blah Blah
## Blah
### Baah
image1:
alt: kkkk
---
| {
"content_hash": "66562d6e9cbcbe7c6a1a0d34098d7e32",
"timestamp": "",
"source": "github",
"line_count": 15,
"max_line_length": 61,
"avg_line_length": 22.333333333333332,
"alnum_prop": 0.6656716417910448,
"repo_name": "pblack/kaldi-hugo-cms-template",
"id": "f538e173fd9a7f24baccf3a4bc3494b338ce6e99",
"size": "339",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "site/content/pages2/arh44.md",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "94394"
},
{
"name": "HTML",
"bytes": "18889"
},
{
"name": "JavaScript",
"bytes": "10014"
}
],
"symlink_target": ""
} |
package org.apache.camel.component.file.remote;
import org.apache.camel.builder.RouteBuilder;
import org.apache.camel.component.mock.MockEndpoint;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
public class FromFtpRecursiveNotStepwiseNoBasePathTest extends FtpServerTestSupport {
protected String getFtpUrl() {
return "ftp://admin@localhost:{{ftp.server.port}}?password=admin&initialDelay=3000&stepwise=false&recursive=true";
}
@Override
@BeforeEach
public void setUp() throws Exception {
super.setUp();
prepareFtpServer();
}
@Test
public void testRecursiveNotStepwiseNoBasePath() throws Exception {
// CAMEL-13400
MockEndpoint mock = getMockEndpoint("mock:result");
mock.expectedBodiesReceivedInAnyOrder("Bye World", "Hello World", "Goodday World");
assertMockEndpointsSatisfied();
}
@Override
protected RouteBuilder createRouteBuilder() throws Exception {
return new RouteBuilder() {
@Override
public void configure() throws Exception {
from(getFtpUrl()).convertBodyTo(String.class).to("log:ftp").to("mock:result");
}
};
}
private void prepareFtpServer() throws Exception {
sendFile(getFtpUrl(), "Bye World", "bye.txt");
sendFile(getFtpUrl(), "Hello World", "sub/hello.txt");
sendFile(getFtpUrl(), "Goodday World", "sub/sub2/godday.txt");
}
}
| {
"content_hash": "c1170cbd775a463dcf229d8aa2b5ae05",
"timestamp": "",
"source": "github",
"line_count": 45,
"max_line_length": 122,
"avg_line_length": 33.022222222222226,
"alnum_prop": 0.6729475100942126,
"repo_name": "gnodet/camel",
"id": "d274b7e0069cbb0c04fe1fe11d1b22c392218c08",
"size": "2288",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "components/camel-ftp/src/test/java/org/apache/camel/component/file/remote/FromFtpRecursiveNotStepwiseNoBasePathTest.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Apex",
"bytes": "6521"
},
{
"name": "Batchfile",
"bytes": "2353"
},
{
"name": "CSS",
"bytes": "5472"
},
{
"name": "Dockerfile",
"bytes": "5462"
},
{
"name": "Elm",
"bytes": "10852"
},
{
"name": "FreeMarker",
"bytes": "8015"
},
{
"name": "Groovy",
"bytes": "25954"
},
{
"name": "HTML",
"bytes": "205030"
},
{
"name": "Java",
"bytes": "106323474"
},
{
"name": "JavaScript",
"bytes": "101298"
},
{
"name": "Jsonnet",
"bytes": "1734"
},
{
"name": "RobotFramework",
"bytes": "8461"
},
{
"name": "Ruby",
"bytes": "88"
},
{
"name": "Shell",
"bytes": "16564"
},
{
"name": "Tcl",
"bytes": "4974"
},
{
"name": "Thrift",
"bytes": "6979"
},
{
"name": "XQuery",
"bytes": "546"
},
{
"name": "XSLT",
"bytes": "280836"
}
],
"symlink_target": ""
} |
#include <kmx/kmx_processevent.h>
#include "path.hpp"
#include "state.hpp"
#include <map>
#include "../test_assert.h"
#include "../test_color.h"
using namespace km::kbp::kmx;
km_kbp_option_item test_env_opts[] =
{
KM_KBP_OPTIONS_END
};
int error_args() {
std::cerr << "kmx: Not enough arguments." << std::endl;
return 1;
}
#define NO_MODIFIER_FLAGS 0
#define CHAR_CODE_LOWER_A 97
#define CHAR_CODE_LOWER_B 98
std::map<std::pair<km_kbp_virtual_key,uint32_t>, uint32_t> kb_key_expected_key_list {{{KM_KBP_VKEY_1, 0},0},
{{KM_KBP_VKEY_2, 0},0},
{{KM_KBP_VKEY_A, 0},0},
{{KM_KBP_VKEY_B, 0},0},
{{KM_KBP_VKEY_B, KM_KBP_MODIFIER_CTRL},KM_KBP_MODIFIER_CTRL},
{{KM_KBP_VKEY_C, 0},0},
{{KM_KBP_VKEY_C, KM_KBP_MODIFIER_ALT},KM_KBP_MODIFIER_ALT},
};
/**
* The purpose of this test is to verify that `km_kbp_keyboard_get_key_list`
* returns list of all the keys used for a keyboard that core as loaded.
*
* @param source_file Path to kmx keyboard file
*/
void test_key_list(const km::kbp::path &source_file){
km_kbp_keyboard * test_kb = nullptr;
km_kbp_state * test_state = nullptr;
km_kbp_keyboard_key * kb_key_list;
km::kbp::path full_path = source_file;
try_status(km_kbp_keyboard_load(full_path.native().c_str(), &test_kb));
// Setup state, environment
try_status(km_kbp_state_create(test_kb, test_env_opts, &test_state));
try_status(km_kbp_keyboard_get_key_list(test_kb,&kb_key_list));
km_kbp_keyboard_key *key_rule_it = kb_key_list;
std::map<std::pair<km_kbp_virtual_key,uint32_t>, uint32_t> map_key_list;
auto n = 0;
// Internally the list is created using a map so we should not rely on order elemnts
// in the returned array. Therefore we will put the array items back into a map to verify
// against our expected map.
for (; key_rule_it->key; ++key_rule_it) {
std::cout << "key:" << key_rule_it->key << " modifer: " << key_rule_it->modifier_flag << std::endl;
map_key_list[std::make_pair(key_rule_it->key, key_rule_it->modifier_flag)] = key_rule_it->modifier_flag;
++n;
}
assert(n==7);
std::map<std::pair<km_kbp_virtual_key,uint32_t>, uint32_t>::iterator it_expected;
std::map<std::pair<km_kbp_virtual_key,uint32_t>, uint32_t>::iterator it_key_list = map_key_list.begin();
while (it_key_list != map_key_list.end()){
it_expected = kb_key_expected_key_list.find(it_key_list->first);
assert (it_expected != kb_key_expected_key_list.end());
it_key_list++;
}
km_kbp_keyboard_key_list_dispose(kb_key_list);
km_kbp_state_dispose(test_state);
km_kbp_keyboard_dispose(test_kb);
}
int main(int argc, char *argv []) {
int first_arg = 1;
if (argc < 2) {
return error_args();
}
auto arg_color = std::string(argv[1]) == "--color";
if(arg_color) {
first_arg++;
if(argc < 3) {
return error_args();
}
}
console_color::enabled = console_color::isaterminal() || arg_color;
test_key_list(argv[first_arg]);
return 0;
}
| {
"content_hash": "2783b945d26536fadf2033a62e555140",
"timestamp": "",
"source": "github",
"line_count": 107,
"max_line_length": 108,
"avg_line_length": 30.588785046728972,
"alnum_prop": 0.5853956614726551,
"repo_name": "tavultesoft/keymanweb",
"id": "0bd2bce2483c0971f57537030422aeff8de760b8",
"size": "3494",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "common/core/desktop/tests/unit/kmx/kmx_key_list.cpp",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Batchfile",
"bytes": "3974"
},
{
"name": "CSS",
"bytes": "29800"
},
{
"name": "HTML",
"bytes": "1145"
},
{
"name": "JavaScript",
"bytes": "556520"
}
],
"symlink_target": ""
} |
Unicenta / Openbravo Database Translation
======
Translation of Unicenta/OpenBravo files not included into locales, plus default database and original files content.
| {
"content_hash": "dfe4e216344dee48381b23bb71093470",
"timestamp": "",
"source": "github",
"line_count": 4,
"max_line_length": 116,
"avg_line_length": 41.75,
"alnum_prop": 0.8083832335329342,
"repo_name": "fran-diaz/Unicenta-Openbravo-Database-Translation",
"id": "7f2bab3d14a00866edce7eb2b14b098f61f715bc",
"size": "167",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "README.md",
"mode": "33188",
"license": "mit",
"language": [],
"symlink_target": ""
} |
@interface MOBProjectionEPSG5554 : MOBProjection
@end
| {
"content_hash": "5cb977dfd58b61f1e89245c92da68aef",
"timestamp": "",
"source": "github",
"line_count": 3,
"max_line_length": 48,
"avg_line_length": 18.333333333333332,
"alnum_prop": 0.8363636363636363,
"repo_name": "jkdubr/Proj4",
"id": "87a04098b63ec5519f7888e3832bcaead3fc4241",
"size": "82",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "Pod/Classes/Projection/MOBProjectionEPSG5554.h",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C",
"bytes": "1141"
},
{
"name": "Objective-C",
"bytes": "1689233"
},
{
"name": "Ruby",
"bytes": "1604"
},
{
"name": "Shell",
"bytes": "7202"
}
],
"symlink_target": ""
} |
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package io.subutai.common.tracker;
/**
* State of operation
*/
public enum OperationState
{
RUNNING, SUCCEEDED, FAILED
}
| {
"content_hash": "994dc81c5d510815205eda9fa06e00db",
"timestamp": "",
"source": "github",
"line_count": 16,
"max_line_length": 79,
"avg_line_length": 19.6875,
"alnum_prop": 0.7238095238095238,
"repo_name": "subutai-io/base",
"id": "da05ca736daef1495a5bfb92df5cce5be050a9d2",
"size": "315",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "management/server/subutai-common/src/main/java/io/subutai/common/tracker/OperationState.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "171335"
},
{
"name": "HTML",
"bytes": "208876"
},
{
"name": "Java",
"bytes": "3733788"
},
{
"name": "JavaScript",
"bytes": "699472"
},
{
"name": "Shell",
"bytes": "30183"
}
],
"symlink_target": ""
} |
package cmd
import (
"fmt"
"io"
"math/rand"
"reflect"
"strings"
"time"
"github.com/spf13/cobra"
"k8s.io/apimachinery/pkg/api/errors"
"k8s.io/apimachinery/pkg/api/meta"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/runtime"
"k8s.io/apimachinery/pkg/runtime/schema"
kerrors "k8s.io/apimachinery/pkg/util/errors"
"k8s.io/apimachinery/pkg/util/sets"
"k8s.io/kubernetes/pkg/api/legacyscheme"
kapi "k8s.io/kubernetes/pkg/apis/core"
"k8s.io/kubernetes/pkg/kubectl"
"k8s.io/kubernetes/pkg/kubectl/cmd/templates"
kcmdutil "k8s.io/kubernetes/pkg/kubectl/cmd/util"
"k8s.io/kubernetes/pkg/kubectl/resource"
kprinters "k8s.io/kubernetes/pkg/printers"
cmdutil "github.com/openshift/origin/pkg/cmd/util"
"github.com/openshift/origin/pkg/oc/cli/describe"
"github.com/openshift/origin/pkg/oc/cli/util/clientcmd"
"github.com/openshift/origin/pkg/oc/generate/app"
"github.com/openshift/origin/pkg/template"
templateapi "github.com/openshift/origin/pkg/template/apis/template"
templatevalidation "github.com/openshift/origin/pkg/template/apis/template/validation"
templateinternalclient "github.com/openshift/origin/pkg/template/client/internalversion"
templateclient "github.com/openshift/origin/pkg/template/generated/internalclientset/typed/template/internalversion"
"github.com/openshift/origin/pkg/template/generator"
)
var (
processLong = templates.LongDesc(`
Process template into a list of resources specified in filename or stdin
Templates allow parameterization of resources prior to being sent to the server for creation or
update. Templates have "parameters", which may either be generated on creation or set by the user,
as well as metadata describing the template.
The output of the process command is always a list of one or more resources. You may pipe the
output to the create command over STDIN (using the '-f -' option) or redirect it to a file.
Process resolves the template on the server, but you may pass --local to parameterize the template
locally. When running locally be aware that the version of your client tools will determine what
template transformations are supported, rather than the server.`)
processExample = templates.Examples(`
# Convert template.json file into resource list and pass to create
%[1]s process -f template.json | %[1]s create -f -
# Process a file locally instead of contacting the server
%[1]s process -f template.json --local -o yaml
# Process template while passing a user-defined label
%[1]s process -f template.json -l name=mytemplate
# Convert stored template into resource list
%[1]s process foo
# Convert stored template into resource list by setting/overriding parameter values
%[1]s process foo PARM1=VALUE1 PARM2=VALUE2
# Convert template stored in different namespace into a resource list
%[1]s process openshift//foo
# Convert template.json into resource list
cat template.json | %[1]s process -f -`)
)
// NewCmdProcess implements the OpenShift cli process command
func NewCmdProcess(fullName string, f *clientcmd.Factory, in io.Reader, out, errout io.Writer) *cobra.Command {
cmd := &cobra.Command{
Use: "process (TEMPLATE | -f FILENAME) [-p=KEY=VALUE]",
Short: "Process a template into list of resources",
Long: processLong,
Example: fmt.Sprintf(processExample, fullName),
Run: func(cmd *cobra.Command, args []string) {
err := RunProcess(f, in, out, errout, cmd, args)
kcmdutil.CheckErr(err)
},
}
cmd.Flags().StringP("filename", "f", "", "Filename or URL to file to read a template")
cmd.MarkFlagFilename("filename", "yaml", "yml", "json")
params := cmd.Flags().StringArrayP("value", "v", nil, "Specify a key-value pair (eg. -v FOO=BAR) to set/override a parameter value in the template.")
cmd.Flags().MarkDeprecated("value", "Use -p, --param instead.")
cmd.Flags().MarkHidden("value")
cmd.Flags().StringArrayVarP(params, "param", "p", nil, "Specify a key-value pair (eg. -p FOO=BAR) to set/override a parameter value in the template.")
cmd.Flags().StringArray("param-file", []string{}, "File containing template parameter values to set/override in the template.")
cmd.MarkFlagFilename("param-file")
cmd.Flags().Bool("ignore-unknown-parameters", false, "If true, will not stop processing if a provided parameter does not exist in the template.")
cmd.Flags().BoolP("local", "", false, "If true process the template locally instead of contacting the server.")
cmd.Flags().BoolP("parameters", "", false, "If true, do not process but only print available parameters")
cmd.Flags().StringP("labels", "l", "", "Label to set in all resources for this template")
cmd.Flags().StringP("output", "o", "json", "Output format. One of: describe|json|yaml|name|go-template=...|go-template-file=...|jsonpath=...|jsonpath-file=...")
cmd.Flags().Bool("raw", false, "If true, output the processed template instead of the template's objects. Implied by -o describe")
cmd.Flags().String("output-version", "", "Output the formatted object with the given version (default api-version).")
cmd.Flags().StringP("template", "t", "", "Template string or path to template file to use when -o=go-template, -o=go-templatefile. The template format is golang templates [http://golang.org/pkg/text/template/#pkg-overview]")
// kcmdutil.PrinterForCommand needs these flags, however they are useless
// here because oc process returns list of heterogeneous objects that is
// not suitable for formatting as a table.
cmd.Flags().BoolP("show-all", "a", false, "When printing, show all resources (default hide terminated pods.)")
cmd.Flags().Bool("show-labels", false, "When printing, show all labels as the last column (default hide labels column)")
cmd.Flags().Bool("no-headers", false, "When using the default output, don't print headers.")
cmd.Flags().MarkHidden("no-headers")
cmd.Flags().String("sort-by", "", "If non-empty, sort list types using this field specification. The field specification is expressed as a JSONPath expression (e.g. 'ObjectMeta.Name'). The field in the API resource specified by this JSONPath expression must be an integer or a string.")
cmd.Flags().MarkHidden("sort-by")
return cmd
}
// RunProcess contains all the necessary functionality for the OpenShift cli process command
func RunProcess(f *clientcmd.Factory, in io.Reader, out, errout io.Writer, cmd *cobra.Command, args []string) error {
templateName, templateParams := "", []string{}
for _, s := range args {
isValue := strings.Contains(s, "=")
switch {
case isValue:
templateParams = append(templateParams, s)
case !isValue && len(templateName) == 0:
templateName = s
case !isValue && len(templateName) > 0:
return kcmdutil.UsageErrorf(cmd, "template name must be specified only once: %s", s)
}
}
local := kcmdutil.GetFlagBool(cmd, "local")
if cmd.Flag("value").Changed || cmd.Flag("param").Changed {
flagValues := getFlagStringArray(cmd, "param")
cmdutil.WarnAboutCommaSeparation(errout, flagValues, "--param")
templateParams = append(templateParams, flagValues...)
}
duplicatedKeys := sets.NewString()
params, paramErr := app.ParseAndCombineEnvironment(templateParams, getFlagStringArray(cmd, "param-file"), in, func(key, file string) error {
if file == "" {
duplicatedKeys.Insert(key)
} else {
fmt.Fprintf(errout, "warning: Template parameter %q already defined, ignoring value from file %q", key, file)
}
return nil
})
if len(duplicatedKeys) != 0 {
return kcmdutil.UsageErrorf(cmd, fmt.Sprintf("The following parameters were provided more than once: %s", strings.Join(duplicatedKeys.List(), ", ")))
}
filename := kcmdutil.GetFlagString(cmd, "filename")
if len(templateName) == 0 && len(filename) == 0 {
return kcmdutil.UsageErrorf(cmd, "Must pass a filename or name of stored template")
}
if kcmdutil.GetFlagBool(cmd, "parameters") {
for _, flag := range []string{"value", "param", "labels", "output", "output-version", "raw", "template"} {
if f := cmd.Flags().Lookup(flag); f != nil && f.Changed {
return kcmdutil.UsageErrorf(cmd, "The --parameters flag does not process the template, can't be used with --%v", flag)
}
}
}
namespace, explicit, err := f.DefaultNamespace()
if err != nil {
return err
}
var (
objects []runtime.Object
infos []*resource.Info
mapper meta.RESTMapper
client templateclient.TemplateInterface
)
if local {
// TODO: Change f.Object() so that it can fall back to local RESTMapper safely (currently glog.Fatals)
mapper = legacyscheme.Registry.RESTMapper()
// client is deliberately left nil
} else {
templateClient, err := f.OpenshiftInternalTemplateClient()
if err != nil {
return err
}
client = templateClient.Template()
mapper, _ = f.Object()
}
mapping, err := mapper.RESTMapping(templateapi.Kind("Template"))
if err != nil {
return err
}
// When templateName is not empty, then we fetch the template from the
// server, otherwise we require to set the `-f` parameter.
if len(templateName) > 0 {
var (
storedTemplate, rs string
sourceNamespace string
ok bool
)
sourceNamespace, rs, storedTemplate, ok = parseNamespaceResourceName(templateName, namespace)
if !ok {
return fmt.Errorf("invalid argument %q", templateName)
}
if len(rs) > 0 && (rs != "template" && rs != "templates") {
return fmt.Errorf("unable to process invalid resource %q", rs)
}
if len(storedTemplate) == 0 {
return fmt.Errorf("invalid value syntax %q", templateName)
}
templateObj, err := client.Templates(sourceNamespace).Get(storedTemplate, metav1.GetOptions{})
if err != nil {
if errors.IsNotFound(err) {
return fmt.Errorf("template %q could not be found", storedTemplate)
}
return err
}
templateObj.CreationTimestamp = metav1.Now()
infos = append(infos, &resource.Info{Object: templateObj})
} else {
infos, err = f.NewBuilder().
Internal().
LocalParam(local).
FilenameParam(explicit, &resource.FilenameOptions{Recursive: false, Filenames: []string{filename}}).
Do().
Infos()
if err != nil {
return fmt.Errorf("failed to read input object (not a Template?): %v", err)
}
}
if len(infos) > 1 {
// in order to run validation on the input given to us by a user, we only support the processing
// of one template in a list. For instance, we want to be able to fail when a user does not give
// a parameter that the template wants or when they give a parameter the template doesn't need,
// as this may indicate that they have mis-used `oc process`. This is much less complicated when
// we process at most one template.
fmt.Fprintf(out, "%d input templates found, but only the first will be processed", len(infos))
}
obj, ok := infos[0].Object.(*templateapi.Template)
if !ok {
sourceName := filename
if len(templateName) > 0 {
sourceName = namespace + "/" + templateName
}
return fmt.Errorf("unable to parse %q, not a valid Template but %s\n", sourceName, reflect.TypeOf(infos[0].Object))
}
// If 'parameters' flag is set it does not do processing but only print
// the template parameters to console for inspection.
if kcmdutil.GetFlagBool(cmd, "parameters") {
return describe.PrintTemplateParameters(obj.Parameters, out)
}
if label := kcmdutil.GetFlagString(cmd, "labels"); len(label) > 0 {
lbl, err := kubectl.ParseLabels(label)
if err != nil {
return fmt.Errorf("error parsing labels: %v\n", err)
}
if obj.ObjectLabels == nil {
obj.ObjectLabels = make(map[string]string)
}
for key, value := range lbl {
obj.ObjectLabels[key] = value
}
}
// Raise parameter parsing errors here after we had chance to return UsageErrors first
if paramErr != nil {
return paramErr
}
if errs := injectUserVars(params, obj, kcmdutil.GetFlagBool(cmd, "ignore-unknown-parameters")); errs != nil {
return kerrors.NewAggregate(errs)
}
resultObj := obj
if local {
if err := processTemplateLocally(obj); err != nil {
return err
}
} else {
processor := templateinternalclient.NewTemplateProcessorClient(client.RESTClient(), namespace)
resultObj, err = processor.Process(obj)
if err != nil {
if err, ok := err.(*errors.StatusError); ok && err.ErrStatus.Details != nil {
errstr := "unable to process template\n"
for _, cause := range err.ErrStatus.Details.Causes {
errstr += fmt.Sprintf(" %s\n", cause.Message)
}
// if no error causes found, fallback to returning original
// error message received from the server
if len(err.ErrStatus.Details.Causes) == 0 {
errstr += fmt.Sprintf(" %v\n", err)
}
return fmt.Errorf(errstr)
}
return fmt.Errorf("unable to process template: %v\n", err)
}
}
outputFormat := kcmdutil.GetFlagString(cmd, "output")
if outputFormat == "describe" {
if s, err := (&describe.TemplateDescriber{
MetadataAccessor: meta.NewAccessor(),
ObjectTyper: legacyscheme.Scheme,
ObjectDescriber: nil,
}).DescribeTemplate(resultObj); err != nil {
return fmt.Errorf("error describing %q: %v\n", obj.Name, err)
} else {
_, err := fmt.Fprintf(out, s)
return err
}
}
objects = append(objects, resultObj.Objects...)
p, err := f.PrinterForOptions(kcmdutil.ExtractCmdPrintOptions(cmd, false))
if err != nil {
return err
}
var version schema.GroupVersion
outputVersionString := kcmdutil.GetFlagString(cmd, "output-version")
if len(outputVersionString) == 0 {
version = mapping.GroupVersionKind.GroupVersion()
} else {
version, err = schema.ParseGroupVersion(outputVersionString)
if err != nil {
return err
}
}
// Prefer the Kubernetes core group for the List over the template.openshift.io
version.Group = kapi.GroupName
p = kprinters.NewVersionedPrinter(p, legacyscheme.Scheme, version)
// use generic output
if kcmdutil.GetFlagBool(cmd, "raw") {
for i := range objects {
p.PrintObj(objects[i], out)
}
return nil
}
return p.PrintObj(&kapi.List{
ListMeta: metav1.ListMeta{},
Items: objects,
}, out)
}
// injectUserVars injects user specified variables into the Template
func injectUserVars(values app.Environment, t *templateapi.Template, ignoreUnknownParameters bool) []error {
var errors []error
for param, val := range values {
v := template.GetParameterByName(t, param)
if v != nil {
v.Value = val
v.Generate = ""
} else if !ignoreUnknownParameters {
errors = append(errors, fmt.Errorf("unknown parameter name %q\n", param))
}
}
return errors
}
// processTemplateLocally applies the same logic that a remote call would make but makes no
// connection to the server.
func processTemplateLocally(tpl *templateapi.Template) error {
if errs := templatevalidation.ValidateProcessedTemplate(tpl); len(errs) > 0 {
return errors.NewInvalid(templateapi.Kind("Template"), tpl.Name, errs)
}
processor := template.NewProcessor(map[string]generator.Generator{
"expression": generator.NewExpressionValueGenerator(rand.New(rand.NewSource(time.Now().UnixNano()))),
})
if errs := processor.Process(tpl); len(errs) > 0 {
return errors.NewInvalid(templateapi.Kind("Template"), tpl.Name, errs)
}
return nil
}
| {
"content_hash": "d63924864b308064c91aa5b42c9e818f",
"timestamp": "",
"source": "github",
"line_count": 386,
"max_line_length": 288,
"avg_line_length": 39.2720207253886,
"alnum_prop": 0.7143611056138268,
"repo_name": "sg00dwin/origin",
"id": "2a8de73027667bd0d2d82b40b0e2179d9ec421a5",
"size": "15159",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "pkg/oc/cli/cmd/process.go",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Awk",
"bytes": "921"
},
{
"name": "DIGITAL Command Language",
"bytes": "117"
},
{
"name": "Go",
"bytes": "15034102"
},
{
"name": "Makefile",
"bytes": "7677"
},
{
"name": "Protocol Buffer",
"bytes": "561272"
},
{
"name": "Python",
"bytes": "7834"
},
{
"name": "Roff",
"bytes": "2049"
},
{
"name": "Ruby",
"bytes": "363"
},
{
"name": "Shell",
"bytes": "1504922"
}
],
"symlink_target": ""
} |
Collider::Collider()
{
mShape = 0;
mPhysicsComponent = 0;
}
Collider::~Collider()
{
}
physx::PxShape *Collider::GetShape()
{
return mShape;
}
physx::PxGeometry Collider::GetGeometry()
{
// IN SUBLCASS: create and return a physx-geometry
// Also do scaling, if neccessary
return physx::PxBoxGeometry(0.5f,0.5f,0.5f);
}
void Collider::SetParent(PhysicsComponent *arg_comp)
{
mPhysicsComponent = arg_comp;
} | {
"content_hash": "dd3727c05b42a50c40f170bef931e2f1",
"timestamp": "",
"source": "github",
"line_count": 29,
"max_line_length": 52,
"avg_line_length": 14.413793103448276,
"alnum_prop": 0.7081339712918661,
"repo_name": "mlavik1/SillyTech3D",
"id": "d1759f27e957a5b2183ebde90886895504c7d399",
"size": "473",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "SillyTech3D/src/Physics/collider.cpp",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C",
"bytes": "3221090"
},
{
"name": "C++",
"bytes": "13968657"
},
{
"name": "CMake",
"bytes": "32967"
},
{
"name": "GLSL",
"bytes": "8715"
},
{
"name": "JavaScript",
"bytes": "2039"
},
{
"name": "Lua",
"bytes": "7813"
},
{
"name": "Makefile",
"bytes": "97246"
},
{
"name": "Objective-C",
"bytes": "9097"
},
{
"name": "RenderScript",
"bytes": "113"
}
],
"symlink_target": ""
} |
// MESSAGE SCALED_PRESSURE PACKING
#define MAVLINK_MSG_ID_SCALED_PRESSURE 29
typedef struct MAVLINK_PACKED __mavlink_scaled_pressure_t
{
uint32_t time_boot_ms; /*< Timestamp (milliseconds since system boot)*/
float press_abs; /*< Absolute pressure (hectopascal)*/
float press_diff; /*< Differential pressure 1 (hectopascal)*/
int16_t temperature; /*< Temperature measurement (0.01 degrees celsius)*/
} mavlink_scaled_pressure_t;
#define MAVLINK_MSG_ID_SCALED_PRESSURE_LEN 14
#define MAVLINK_MSG_ID_SCALED_PRESSURE_MIN_LEN 14
#define MAVLINK_MSG_ID_29_LEN 14
#define MAVLINK_MSG_ID_29_MIN_LEN 14
#define MAVLINK_MSG_ID_SCALED_PRESSURE_CRC 115
#define MAVLINK_MSG_ID_29_CRC 115
#if MAVLINK_COMMAND_24BIT
#define MAVLINK_MESSAGE_INFO_SCALED_PRESSURE { \
29, \
"SCALED_PRESSURE", \
4, \
{ { "time_boot_ms", NULL, MAVLINK_TYPE_UINT32_T, 0, 0, offsetof(mavlink_scaled_pressure_t, time_boot_ms) }, \
{ "press_abs", NULL, MAVLINK_TYPE_FLOAT, 0, 4, offsetof(mavlink_scaled_pressure_t, press_abs) }, \
{ "press_diff", NULL, MAVLINK_TYPE_FLOAT, 0, 8, offsetof(mavlink_scaled_pressure_t, press_diff) }, \
{ "temperature", NULL, MAVLINK_TYPE_INT16_T, 0, 12, offsetof(mavlink_scaled_pressure_t, temperature) }, \
} \
}
#else
#define MAVLINK_MESSAGE_INFO_SCALED_PRESSURE { \
"SCALED_PRESSURE", \
4, \
{ { "time_boot_ms", NULL, MAVLINK_TYPE_UINT32_T, 0, 0, offsetof(mavlink_scaled_pressure_t, time_boot_ms) }, \
{ "press_abs", NULL, MAVLINK_TYPE_FLOAT, 0, 4, offsetof(mavlink_scaled_pressure_t, press_abs) }, \
{ "press_diff", NULL, MAVLINK_TYPE_FLOAT, 0, 8, offsetof(mavlink_scaled_pressure_t, press_diff) }, \
{ "temperature", NULL, MAVLINK_TYPE_INT16_T, 0, 12, offsetof(mavlink_scaled_pressure_t, temperature) }, \
} \
}
#endif
/**
* @brief Pack a scaled_pressure message
* @param system_id ID of this system
* @param component_id ID of this component (e.g. 200 for IMU)
* @param msg The MAVLink message to compress the data into
*
* @param time_boot_ms Timestamp (milliseconds since system boot)
* @param press_abs Absolute pressure (hectopascal)
* @param press_diff Differential pressure 1 (hectopascal)
* @param temperature Temperature measurement (0.01 degrees celsius)
* @return length of the message in bytes (excluding serial stream start sign)
*/
static inline uint16_t mavlink_msg_scaled_pressure_pack(uint8_t system_id, uint8_t component_id, mavlink_message_t* msg,
uint32_t time_boot_ms, float press_abs, float press_diff, int16_t temperature)
{
#if MAVLINK_NEED_BYTE_SWAP || !MAVLINK_ALIGNED_FIELDS
char buf[MAVLINK_MSG_ID_SCALED_PRESSURE_LEN];
_mav_put_uint32_t(buf, 0, time_boot_ms);
_mav_put_float(buf, 4, press_abs);
_mav_put_float(buf, 8, press_diff);
_mav_put_int16_t(buf, 12, temperature);
memcpy(_MAV_PAYLOAD_NON_CONST(msg), buf, MAVLINK_MSG_ID_SCALED_PRESSURE_LEN);
#else
mavlink_scaled_pressure_t packet;
packet.time_boot_ms = time_boot_ms;
packet.press_abs = press_abs;
packet.press_diff = press_diff;
packet.temperature = temperature;
memcpy(_MAV_PAYLOAD_NON_CONST(msg), &packet, MAVLINK_MSG_ID_SCALED_PRESSURE_LEN);
#endif
msg->msgid = MAVLINK_MSG_ID_SCALED_PRESSURE;
return mavlink_finalize_message(msg, system_id, component_id, MAVLINK_MSG_ID_SCALED_PRESSURE_MIN_LEN, MAVLINK_MSG_ID_SCALED_PRESSURE_LEN, MAVLINK_MSG_ID_SCALED_PRESSURE_CRC);
}
/**
* @brief Pack a scaled_pressure message on a channel
* @param system_id ID of this system
* @param component_id ID of this component (e.g. 200 for IMU)
* @param chan The MAVLink channel this message will be sent over
* @param msg The MAVLink message to compress the data into
* @param time_boot_ms Timestamp (milliseconds since system boot)
* @param press_abs Absolute pressure (hectopascal)
* @param press_diff Differential pressure 1 (hectopascal)
* @param temperature Temperature measurement (0.01 degrees celsius)
* @return length of the message in bytes (excluding serial stream start sign)
*/
static inline uint16_t mavlink_msg_scaled_pressure_pack_chan(uint8_t system_id, uint8_t component_id, uint8_t chan,
mavlink_message_t* msg,
uint32_t time_boot_ms,float press_abs,float press_diff,int16_t temperature)
{
#if MAVLINK_NEED_BYTE_SWAP || !MAVLINK_ALIGNED_FIELDS
char buf[MAVLINK_MSG_ID_SCALED_PRESSURE_LEN];
_mav_put_uint32_t(buf, 0, time_boot_ms);
_mav_put_float(buf, 4, press_abs);
_mav_put_float(buf, 8, press_diff);
_mav_put_int16_t(buf, 12, temperature);
memcpy(_MAV_PAYLOAD_NON_CONST(msg), buf, MAVLINK_MSG_ID_SCALED_PRESSURE_LEN);
#else
mavlink_scaled_pressure_t packet;
packet.time_boot_ms = time_boot_ms;
packet.press_abs = press_abs;
packet.press_diff = press_diff;
packet.temperature = temperature;
memcpy(_MAV_PAYLOAD_NON_CONST(msg), &packet, MAVLINK_MSG_ID_SCALED_PRESSURE_LEN);
#endif
msg->msgid = MAVLINK_MSG_ID_SCALED_PRESSURE;
return mavlink_finalize_message_chan(msg, system_id, component_id, chan, MAVLINK_MSG_ID_SCALED_PRESSURE_MIN_LEN, MAVLINK_MSG_ID_SCALED_PRESSURE_LEN, MAVLINK_MSG_ID_SCALED_PRESSURE_CRC);
}
/**
* @brief Encode a scaled_pressure struct
*
* @param system_id ID of this system
* @param component_id ID of this component (e.g. 200 for IMU)
* @param msg The MAVLink message to compress the data into
* @param scaled_pressure C-struct to read the message contents from
*/
static inline uint16_t mavlink_msg_scaled_pressure_encode(uint8_t system_id, uint8_t component_id, mavlink_message_t* msg, const mavlink_scaled_pressure_t* scaled_pressure)
{
return mavlink_msg_scaled_pressure_pack(system_id, component_id, msg, scaled_pressure->time_boot_ms, scaled_pressure->press_abs, scaled_pressure->press_diff, scaled_pressure->temperature);
}
/**
* @brief Encode a scaled_pressure struct on a channel
*
* @param system_id ID of this system
* @param component_id ID of this component (e.g. 200 for IMU)
* @param chan The MAVLink channel this message will be sent over
* @param msg The MAVLink message to compress the data into
* @param scaled_pressure C-struct to read the message contents from
*/
static inline uint16_t mavlink_msg_scaled_pressure_encode_chan(uint8_t system_id, uint8_t component_id, uint8_t chan, mavlink_message_t* msg, const mavlink_scaled_pressure_t* scaled_pressure)
{
return mavlink_msg_scaled_pressure_pack_chan(system_id, component_id, chan, msg, scaled_pressure->time_boot_ms, scaled_pressure->press_abs, scaled_pressure->press_diff, scaled_pressure->temperature);
}
/**
* @brief Send a scaled_pressure message
* @param chan MAVLink channel to send the message
*
* @param time_boot_ms Timestamp (milliseconds since system boot)
* @param press_abs Absolute pressure (hectopascal)
* @param press_diff Differential pressure 1 (hectopascal)
* @param temperature Temperature measurement (0.01 degrees celsius)
*/
#ifdef MAVLINK_USE_CONVENIENCE_FUNCTIONS
static inline void mavlink_msg_scaled_pressure_send(mavlink_channel_t chan, uint32_t time_boot_ms, float press_abs, float press_diff, int16_t temperature)
{
#if MAVLINK_NEED_BYTE_SWAP || !MAVLINK_ALIGNED_FIELDS
char buf[MAVLINK_MSG_ID_SCALED_PRESSURE_LEN];
_mav_put_uint32_t(buf, 0, time_boot_ms);
_mav_put_float(buf, 4, press_abs);
_mav_put_float(buf, 8, press_diff);
_mav_put_int16_t(buf, 12, temperature);
_mav_finalize_message_chan_send(chan, MAVLINK_MSG_ID_SCALED_PRESSURE, buf, MAVLINK_MSG_ID_SCALED_PRESSURE_MIN_LEN, MAVLINK_MSG_ID_SCALED_PRESSURE_LEN, MAVLINK_MSG_ID_SCALED_PRESSURE_CRC);
#else
mavlink_scaled_pressure_t packet;
packet.time_boot_ms = time_boot_ms;
packet.press_abs = press_abs;
packet.press_diff = press_diff;
packet.temperature = temperature;
_mav_finalize_message_chan_send(chan, MAVLINK_MSG_ID_SCALED_PRESSURE, (const char *)&packet, MAVLINK_MSG_ID_SCALED_PRESSURE_MIN_LEN, MAVLINK_MSG_ID_SCALED_PRESSURE_LEN, MAVLINK_MSG_ID_SCALED_PRESSURE_CRC);
#endif
}
/**
* @brief Send a scaled_pressure message
* @param chan MAVLink channel to send the message
* @param struct The MAVLink struct to serialize
*/
static inline void mavlink_msg_scaled_pressure_send_struct(mavlink_channel_t chan, const mavlink_scaled_pressure_t* scaled_pressure)
{
#if MAVLINK_NEED_BYTE_SWAP || !MAVLINK_ALIGNED_FIELDS
mavlink_msg_scaled_pressure_send(chan, scaled_pressure->time_boot_ms, scaled_pressure->press_abs, scaled_pressure->press_diff, scaled_pressure->temperature);
#else
_mav_finalize_message_chan_send(chan, MAVLINK_MSG_ID_SCALED_PRESSURE, (const char *)scaled_pressure, MAVLINK_MSG_ID_SCALED_PRESSURE_MIN_LEN, MAVLINK_MSG_ID_SCALED_PRESSURE_LEN, MAVLINK_MSG_ID_SCALED_PRESSURE_CRC);
#endif
}
#if MAVLINK_MSG_ID_SCALED_PRESSURE_LEN <= MAVLINK_MAX_PAYLOAD_LEN
/*
This varient of _send() can be used to save stack space by re-using
memory from the receive buffer. The caller provides a
mavlink_message_t which is the size of a full mavlink message. This
is usually the receive buffer for the channel, and allows a reply to an
incoming message with minimum stack space usage.
*/
static inline void mavlink_msg_scaled_pressure_send_buf(mavlink_message_t *msgbuf, mavlink_channel_t chan, uint32_t time_boot_ms, float press_abs, float press_diff, int16_t temperature)
{
#if MAVLINK_NEED_BYTE_SWAP || !MAVLINK_ALIGNED_FIELDS
char *buf = (char *)msgbuf;
_mav_put_uint32_t(buf, 0, time_boot_ms);
_mav_put_float(buf, 4, press_abs);
_mav_put_float(buf, 8, press_diff);
_mav_put_int16_t(buf, 12, temperature);
_mav_finalize_message_chan_send(chan, MAVLINK_MSG_ID_SCALED_PRESSURE, buf, MAVLINK_MSG_ID_SCALED_PRESSURE_MIN_LEN, MAVLINK_MSG_ID_SCALED_PRESSURE_LEN, MAVLINK_MSG_ID_SCALED_PRESSURE_CRC);
#else
mavlink_scaled_pressure_t *packet = (mavlink_scaled_pressure_t *)msgbuf;
packet->time_boot_ms = time_boot_ms;
packet->press_abs = press_abs;
packet->press_diff = press_diff;
packet->temperature = temperature;
_mav_finalize_message_chan_send(chan, MAVLINK_MSG_ID_SCALED_PRESSURE, (const char *)packet, MAVLINK_MSG_ID_SCALED_PRESSURE_MIN_LEN, MAVLINK_MSG_ID_SCALED_PRESSURE_LEN, MAVLINK_MSG_ID_SCALED_PRESSURE_CRC);
#endif
}
#endif
#endif
// MESSAGE SCALED_PRESSURE UNPACKING
/**
* @brief Get field time_boot_ms from scaled_pressure message
*
* @return Timestamp (milliseconds since system boot)
*/
static inline uint32_t mavlink_msg_scaled_pressure_get_time_boot_ms(const mavlink_message_t* msg)
{
return _MAV_RETURN_uint32_t(msg, 0);
}
/**
* @brief Get field press_abs from scaled_pressure message
*
* @return Absolute pressure (hectopascal)
*/
static inline float mavlink_msg_scaled_pressure_get_press_abs(const mavlink_message_t* msg)
{
return _MAV_RETURN_float(msg, 4);
}
/**
* @brief Get field press_diff from scaled_pressure message
*
* @return Differential pressure 1 (hectopascal)
*/
static inline float mavlink_msg_scaled_pressure_get_press_diff(const mavlink_message_t* msg)
{
return _MAV_RETURN_float(msg, 8);
}
/**
* @brief Get field temperature from scaled_pressure message
*
* @return Temperature measurement (0.01 degrees celsius)
*/
static inline int16_t mavlink_msg_scaled_pressure_get_temperature(const mavlink_message_t* msg)
{
return _MAV_RETURN_int16_t(msg, 12);
}
/**
* @brief Decode a scaled_pressure message into a struct
*
* @param msg The message to decode
* @param scaled_pressure C-struct to decode the message contents into
*/
static inline void mavlink_msg_scaled_pressure_decode(const mavlink_message_t* msg, mavlink_scaled_pressure_t* scaled_pressure)
{
#if MAVLINK_NEED_BYTE_SWAP || !MAVLINK_ALIGNED_FIELDS
scaled_pressure->time_boot_ms = mavlink_msg_scaled_pressure_get_time_boot_ms(msg);
scaled_pressure->press_abs = mavlink_msg_scaled_pressure_get_press_abs(msg);
scaled_pressure->press_diff = mavlink_msg_scaled_pressure_get_press_diff(msg);
scaled_pressure->temperature = mavlink_msg_scaled_pressure_get_temperature(msg);
#else
uint8_t len = msg->len < MAVLINK_MSG_ID_SCALED_PRESSURE_LEN? msg->len : MAVLINK_MSG_ID_SCALED_PRESSURE_LEN;
memset(scaled_pressure, 0, MAVLINK_MSG_ID_SCALED_PRESSURE_LEN);
memcpy(scaled_pressure, _MAV_PAYLOAD(msg), len);
#endif
}
| {
"content_hash": "3cf4df89fc0e033335622ffa7f960860",
"timestamp": "",
"source": "github",
"line_count": 287,
"max_line_length": 217,
"avg_line_length": 42.34494773519164,
"alnum_prop": 0.7330700238624208,
"repo_name": "cea-ufmg/aeroprobe",
"id": "223325461fb6c210e0a2a7a529584a43938556a4",
"size": "12153",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "mavlink/common/mavlink_msg_scaled_pressure.h",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C",
"bytes": "2888201"
},
{
"name": "C++",
"bytes": "25590"
},
{
"name": "Makefile",
"bytes": "153"
},
{
"name": "Objective-C",
"bytes": "106460"
}
],
"symlink_target": ""
} |
<?xml version="1.0" encoding="utf-8"?>
<resources>
<!-- From: file:/home/shivababa/TimeTable/app/build/intermediates/exploded-aar/com.android.support/appcompat-v7/22.1.1/res/values-v21/values.xml -->
<eat-comment/>
<style name="Base.TextAppearance.AppCompat" parent="android:TextAppearance.Material"/>
<style name="Base.TextAppearance.AppCompat.Body1" parent="android:TextAppearance.Material.Body1"/>
<style name="Base.TextAppearance.AppCompat.Body2" parent="android:TextAppearance.Material.Body2"/>
<style name="Base.TextAppearance.AppCompat.Button" parent="android:TextAppearance.Material.Button"/>
<style name="Base.TextAppearance.AppCompat.Caption" parent="android:TextAppearance.Material.Caption"/>
<style name="Base.TextAppearance.AppCompat.Display1" parent="android:TextAppearance.Material.Display1"/>
<style name="Base.TextAppearance.AppCompat.Display2" parent="android:TextAppearance.Material.Display2"/>
<style name="Base.TextAppearance.AppCompat.Display3" parent="android:TextAppearance.Material.Display3"/>
<style name="Base.TextAppearance.AppCompat.Display4" parent="android:TextAppearance.Material.Display4"/>
<style name="Base.TextAppearance.AppCompat.Headline" parent="android:TextAppearance.Material.Headline"/>
<style name="Base.TextAppearance.AppCompat.Inverse" parent="android:TextAppearance.Material.Inverse"/>
<style name="Base.TextAppearance.AppCompat.Large" parent="android:TextAppearance.Material.Large"/>
<style name="Base.TextAppearance.AppCompat.Large.Inverse" parent="android:TextAppearance.Material.Large.Inverse"/>
<style name="Base.TextAppearance.AppCompat.Light.Widget.PopupMenu.Large" parent="android:TextAppearance.Material.Widget.PopupMenu.Large">
</style>
<style name="Base.TextAppearance.AppCompat.Light.Widget.PopupMenu.Small" parent="android:TextAppearance.Material.Widget.PopupMenu.Small">
</style>
<style name="Base.TextAppearance.AppCompat.Medium" parent="android:TextAppearance.Material.Medium"/>
<style name="Base.TextAppearance.AppCompat.Medium.Inverse" parent="android:TextAppearance.Material.Medium.Inverse"/>
<style name="Base.TextAppearance.AppCompat.Menu" parent="android:TextAppearance.Material.Menu"/>
<style name="Base.TextAppearance.AppCompat.SearchResult.Subtitle" parent="android:TextAppearance.Material.SearchResult.Subtitle">
</style>
<style name="Base.TextAppearance.AppCompat.SearchResult.Title" parent="android:TextAppearance.Material.SearchResult.Title">
</style>
<style name="Base.TextAppearance.AppCompat.Small" parent="android:TextAppearance.Material.Small"/>
<style name="Base.TextAppearance.AppCompat.Small.Inverse" parent="android:TextAppearance.Material.Small.Inverse"/>
<style name="Base.TextAppearance.AppCompat.Subhead" parent="android:TextAppearance.Material.Subhead"/>
<style name="Base.TextAppearance.AppCompat.Title" parent="android:TextAppearance.Material.Title"/>
<style name="Base.TextAppearance.AppCompat.Widget.ActionBar.Menu" parent="android:TextAppearance.Material.Widget.ActionBar.Menu">
</style>
<style name="Base.TextAppearance.AppCompat.Widget.ActionBar.Subtitle" parent="android:TextAppearance.Material.Widget.ActionBar.Subtitle">
</style>
<style name="Base.TextAppearance.AppCompat.Widget.ActionBar.Subtitle.Inverse" parent="android:TextAppearance.Material.Widget.ActionBar.Subtitle.Inverse">
</style>
<style name="Base.TextAppearance.AppCompat.Widget.ActionBar.Title" parent="android:TextAppearance.Material.Widget.ActionBar.Title">
</style>
<style name="Base.TextAppearance.AppCompat.Widget.ActionBar.Title.Inverse" parent="android:TextAppearance.Material.Widget.ActionBar.Title.Inverse">
</style>
<style name="Base.TextAppearance.AppCompat.Widget.ActionMode.Subtitle" parent="android:TextAppearance.Material.Widget.ActionMode.Subtitle">
</style>
<style name="Base.TextAppearance.AppCompat.Widget.ActionMode.Title" parent="android:TextAppearance.Material.Widget.ActionMode.Title">
</style>
<style name="Base.TextAppearance.AppCompat.Widget.PopupMenu.Large" parent="android:TextAppearance.Material.Widget.PopupMenu.Large">
</style>
<style name="Base.TextAppearance.AppCompat.Widget.PopupMenu.Small" parent="android:TextAppearance.Material.Widget.PopupMenu.Small">
</style>
<style name="Base.TextAppearance.AppCompat.Widget.Switch" parent="android:TextAppearance.Material.Button"/>
<style name="Base.TextAppearance.AppCompat.Widget.TextView.SpinnerItem" parent="android:TextAppearance.Material.Widget.TextView.SpinnerItem"/>
<style name="Base.TextAppearance.Widget.AppCompat.Toolbar.Subtitle" parent="android:TextAppearance.Material.Widget.ActionBar.Subtitle">
</style>
<style name="Base.TextAppearance.Widget.AppCompat.Toolbar.Title" parent="android:TextAppearance.Material.Widget.ActionBar.Title">
</style>
<style name="Base.Theme.AppCompat" parent="Base.V21.Theme.AppCompat"/>
<style name="Base.Theme.AppCompat.Dialog" parent="Base.V21.Theme.AppCompat.Dialog"/>
<style name="Base.Theme.AppCompat.Light" parent="Base.V21.Theme.AppCompat.Light"/>
<style name="Base.Theme.AppCompat.Light.Dialog" parent="Base.V21.Theme.AppCompat.Light.Dialog"/>
<style name="Base.V21.Theme.AppCompat" parent="Base.V7.Theme.AppCompat">
<!-- Action Bar styling attributes -->
<item name="actionBarSize">?android:attr/actionBarSize</item>
<item name="actionBarDivider">?android:attr/actionBarDivider</item>
<item name="actionBarItemBackground">?android:attr/actionBarItemBackground</item>
<item name="actionButtonStyle">?android:attr/actionButtonStyle</item>
<item name="actionMenuTextColor">?android:attr/actionMenuTextColor</item>
<item name="actionMenuTextAppearance">?android:attr/actionMenuTextAppearance</item>
<item name="actionModeBackground">?android:attr/actionModeBackground</item>
<item name="actionModeCloseDrawable">?android:attr/actionModeCloseDrawable</item>
<item name="actionModeShareDrawable">?android:attr/actionModeShareDrawable</item>
<item name="actionOverflowButtonStyle">?android:attr/actionOverflowButtonStyle</item>
<item name="homeAsUpIndicator">?android:attr/homeAsUpIndicator</item>
<!-- For PopupMenu -->
<item name="listPreferredItemHeightSmall">?android:attr/listPreferredItemHeightSmall</item>
<item name="textAppearanceLargePopupMenu">?android:attr/textAppearanceLargePopupMenu</item>
<item name="textAppearanceSmallPopupMenu">?android:attr/textAppearanceSmallPopupMenu</item>
<!-- General view attributes -->
<item name="selectableItemBackground">?android:attr/selectableItemBackground</item>
<item name="selectableItemBackgroundBorderless">?android:attr/selectableItemBackgroundBorderless</item>
<item name="dividerHorizontal">?android:attr/dividerHorizontal</item>
<item name="dividerVertical">?android:attr/dividerVertical</item>
<item name="editTextBackground">?android:attr/editTextBackground</item>
<item name="editTextColor">?android:attr/editTextColor</item>
<item name="listChoiceBackgroundIndicator">?android:attr/listChoiceBackgroundIndicator</item>
<!-- Copy the platform default styles for the AppCompat widgets -->
<item name="autoCompleteTextViewStyle">?android:attr/autoCompleteTextViewStyle</item>
<item name="buttonStyle">?android:attr/buttonStyle</item>
<item name="buttonStyleSmall">?android:attr/buttonStyleSmall</item>
<item name="checkboxStyle">?android:attr/checkboxStyle</item>
<item name="checkedTextViewStyle">?android:attr/checkedTextViewStyle</item>
<item name="editTextStyle">?android:attr/editTextStyle</item>
<item name="radioButtonStyle">?android:attr/radioButtonStyle</item>
<item name="ratingBarStyle">?android:attr/ratingBarStyle</item>
<item name="spinnerStyle">?android:attr/spinnerStyle</item>
<!-- Copy our color theme attributes to the framework -->
<item name="android:colorPrimary">?attr/colorPrimary</item>
<item name="android:colorPrimaryDark">?attr/colorPrimaryDark</item>
<item name="android:colorAccent">?attr/colorAccent</item>
<item name="android:colorControlNormal">?attr/colorControlNormal</item>
<item name="android:colorControlActivated">?attr/colorControlActivated</item>
<item name="android:colorControlHighlight">?attr/colorControlHighlight</item>
<item name="android:colorButtonNormal">?attr/colorButtonNormal</item>
</style>
<style name="Base.V21.Theme.AppCompat.Dialog" parent="Base.V11.Theme.AppCompat.Dialog">
<item name="android:windowElevation">@dimen/abc_floating_window_z</item>
</style>
<style name="Base.V21.Theme.AppCompat.Light" parent="Base.V7.Theme.AppCompat.Light">
<!-- Action Bar styling attributes -->
<item name="actionBarSize">?android:attr/actionBarSize</item>
<item name="actionBarDivider">?android:attr/actionBarDivider</item>
<item name="actionBarItemBackground">?android:attr/actionBarItemBackground</item>
<item name="actionButtonStyle">?android:attr/actionButtonStyle</item>
<item name="actionMenuTextColor">?android:attr/actionMenuTextColor</item>
<item name="actionMenuTextAppearance">?android:attr/actionMenuTextAppearance</item>
<item name="actionModeBackground">?android:attr/actionModeBackground</item>
<item name="actionModeCloseDrawable">?android:attr/actionModeCloseDrawable</item>
<item name="actionModeShareDrawable">?android:attr/actionModeShareDrawable</item>
<item name="actionOverflowButtonStyle">?android:attr/actionOverflowButtonStyle</item>
<item name="homeAsUpIndicator">?android:attr/homeAsUpIndicator</item>
<!-- For PopupMenu -->
<item name="listPreferredItemHeightSmall">?android:attr/listPreferredItemHeightSmall</item>
<item name="textAppearanceLargePopupMenu">?android:attr/textAppearanceLargePopupMenu</item>
<item name="textAppearanceSmallPopupMenu">?android:attr/textAppearanceSmallPopupMenu</item>
<!-- General view attributes -->
<item name="selectableItemBackground">?android:attr/selectableItemBackground</item>
<item name="selectableItemBackgroundBorderless">?android:attr/selectableItemBackgroundBorderless</item>
<item name="dividerHorizontal">?android:attr/dividerHorizontal</item>
<item name="dividerVertical">?android:attr/dividerVertical</item>
<item name="editTextBackground">?android:attr/editTextBackground</item>
<item name="editTextColor">?android:attr/editTextColor</item>
<item name="listChoiceBackgroundIndicator">?android:attr/listChoiceBackgroundIndicator</item>
<!-- Copy the platform default styles for the AppCompat widgets -->
<item name="autoCompleteTextViewStyle">?android:attr/autoCompleteTextViewStyle</item>
<item name="buttonStyle">?android:attr/buttonStyle</item>
<item name="buttonStyleSmall">?android:attr/buttonStyleSmall</item>
<item name="checkboxStyle">?android:attr/checkboxStyle</item>
<item name="checkedTextViewStyle">?android:attr/checkedTextViewStyle</item>
<item name="editTextStyle">?android:attr/editTextStyle</item>
<item name="radioButtonStyle">?android:attr/radioButtonStyle</item>
<item name="ratingBarStyle">?android:attr/ratingBarStyle</item>
<item name="spinnerStyle">?android:attr/spinnerStyle</item>
<!-- Copy our color theme attributes to the framework -->
<item name="android:colorPrimary">?attr/colorPrimary</item>
<item name="android:colorPrimaryDark">?attr/colorPrimaryDark</item>
<item name="android:colorAccent">?attr/colorAccent</item>
<item name="android:colorControlNormal">?attr/colorControlNormal</item>
<item name="android:colorControlActivated">?attr/colorControlActivated</item>
<item name="android:colorControlHighlight">?attr/colorControlHighlight</item>
<item name="android:colorButtonNormal">?attr/colorButtonNormal</item>
</style>
<style name="Base.V21.Theme.AppCompat.Light.Dialog" parent="Base.V11.Theme.AppCompat.Light.Dialog">
<item name="android:windowElevation">@dimen/abc_floating_window_z</item>
</style>
<style name="Base.Widget.AppCompat.ActionBar.TabText" parent="android:Widget.Material.ActionBar.TabText">
</style>
<style name="Base.Widget.AppCompat.ActionBar.TabView" parent="android:Widget.Material.ActionBar.TabView">
</style>
<style name="Base.Widget.AppCompat.ActionButton" parent="android:Widget.Material.ActionButton">
</style>
<style name="Base.Widget.AppCompat.ActionButton.CloseMode" parent="android:Widget.Material.ActionButton.CloseMode">
<item name="android:minWidth">56dp</item>
</style>
<style name="Base.Widget.AppCompat.ActionButton.Overflow" parent="android:Widget.Material.ActionButton.Overflow">
</style>
<style name="Base.Widget.AppCompat.AutoCompleteTextView" parent="android:Widget.Material.AutoCompleteTextView"/>
<style name="Base.Widget.AppCompat.Button" parent="android:Widget.Material.Button"/>
<style name="Base.Widget.AppCompat.Button.Borderless" parent="android:Widget.Material.Button.Borderless"/>
<style name="Base.Widget.AppCompat.Button.Borderless.Colored" parent="android:Widget.Material.Button.Borderless.Colored"/>
<style name="Base.Widget.AppCompat.Button.Small" parent="android:Widget.Material.Button.Small"/>
<style name="Base.Widget.AppCompat.ButtonBar" parent="android:Widget.Material.ButtonBar"/>
<style name="Base.Widget.AppCompat.CompoundButton.CheckBox" parent="android:Widget.Material.CompoundButton.CheckBox"/>
<style name="Base.Widget.AppCompat.CompoundButton.RadioButton" parent="android:Widget.Material.CompoundButton.RadioButton"/>
<style name="Base.Widget.AppCompat.DropDownItem.Spinner" parent="android:Widget.Material.DropDownItem.Spinner"/>
<style name="Base.Widget.AppCompat.Light.ActionBar.TabText" parent="android:Widget.Material.Light.ActionBar.TabText">
</style>
<style name="Base.Widget.AppCompat.Light.ActionBar.TabText.Inverse" parent="android:Widget.Material.Light.ActionBar.TabText">
</style>
<style name="Base.Widget.AppCompat.Light.ActionBar.TabView" parent="android:Widget.Material.Light.ActionBar.TabView">
</style>
<style name="Base.Widget.AppCompat.Light.PopupMenu" parent="android:Widget.Material.Light.PopupMenu">
</style>
<style name="Base.Widget.AppCompat.Light.PopupMenu.Overflow">
<item name="android:dropDownHorizontalOffset">-4dip</item>
<item name="android:overlapAnchor">true</item>
</style>
<style name="Base.Widget.AppCompat.ListPopupWindow" parent="android:Widget.Material.ListPopupWindow">
</style>
<style name="Base.Widget.AppCompat.ListView" parent="android:Widget.Material.ListView"/>
<style name="Base.Widget.AppCompat.ListView.DropDown" parent="android:Widget.Material.ListView.DropDown"/>
<style name="Base.Widget.AppCompat.ListView.Menu"/>
<style name="Base.Widget.AppCompat.PopupMenu" parent="android:Widget.Material.PopupMenu">
</style>
<style name="Base.Widget.AppCompat.PopupMenu.Overflow">
<item name="android:dropDownHorizontalOffset">-4dip</item>
<item name="android:overlapAnchor">true</item>
</style>
<style name="Base.Widget.AppCompat.ProgressBar" parent="android:Widget.Material.ProgressBar">
</style>
<style name="Base.Widget.AppCompat.ProgressBar.Horizontal" parent="android:Widget.Material.ProgressBar.Horizontal">
</style>
<style name="Base.Widget.AppCompat.RatingBar" parent="android:Widget.Material.RatingBar"/>
<style name="Base.Widget.AppCompat.Spinner" parent="android:Widget.Material.Spinner"/>
<style name="Base.Widget.AppCompat.Spinner.DropDown.ActionBar" parent="android:Widget.Material.Spinner">
<item name="spinnerMode">dropdown</item>
<item name="disableChildrenWhenDisabled">true</item>
<item name="popupPromptView">@layout/abc_simple_dropdown_hint</item>
</style>
<style name="Base.Widget.AppCompat.Spinner.Underlined" parent="android:Widget.Material.Spinner.Underlined"/>
<style name="Base.Widget.AppCompat.TextView.SpinnerItem" parent="android:Widget.Material.TextView.SpinnerItem"/>
<style name="Base.Widget.AppCompat.Toolbar.Button.Navigation" parent="android:Widget.Material.Toolbar.Button.Navigation">
</style>
<style name="Platform.AppCompat" parent="android:Theme.Material">
<item name="android:windowNoTitle">true</item>
<item name="android:windowActionBar">false</item>
<item name="android:buttonBarStyle">?attr/buttonBarStyle</item>
<item name="android:buttonBarButtonStyle">?attr/buttonBarButtonStyle</item>
</style>
<style name="Platform.AppCompat.Light" parent="android:Theme.Material.Light">
<item name="android:windowNoTitle">true</item>
<item name="android:windowActionBar">false</item>
<item name="android:buttonBarStyle">?attr/buttonBarStyle</item>
<item name="android:buttonBarButtonStyle">?attr/buttonBarButtonStyle</item>
</style>
<style name="Platform.ThemeOverlay.AppCompat.Dark" parent="">
<!-- Copy our color theme attributes to the framework -->
<item name="android:colorPrimary">?attr/colorPrimary</item>
<item name="android:colorPrimaryDark">?attr/colorPrimaryDark</item>
<item name="android:colorAccent">?attr/colorAccent</item>
<item name="android:colorControlNormal">?attr/colorControlNormal</item>
<item name="android:colorControlActivated">?attr/colorControlActivated</item>
<item name="android:colorControlHighlight">?attr/colorControlHighlight</item>
<item name="android:colorButtonNormal">?attr/colorButtonNormal</item>
</style>
<style name="Platform.ThemeOverlay.AppCompat.Light" parent="">
<!-- Copy our color theme attributes to the framework -->
<item name="android:colorPrimary">?attr/colorPrimary</item>
<item name="android:colorPrimaryDark">?attr/colorPrimaryDark</item>
<item name="android:colorAccent">?attr/colorAccent</item>
<item name="android:colorControlNormal">?attr/colorControlNormal</item>
<item name="android:colorControlActivated">?attr/colorControlActivated</item>
<item name="android:colorControlHighlight">?attr/colorControlHighlight</item>
<item name="android:colorButtonNormal">?attr/colorButtonNormal</item>
</style>
</resources> | {
"content_hash": "e770579bd425f06f2eec0c6b006b756a",
"timestamp": "",
"source": "github",
"line_count": 255,
"max_line_length": 157,
"avg_line_length": 73.62352941176471,
"alnum_prop": 0.7468307233407905,
"repo_name": "krishnachaitanya9/TimeTable-Android-app",
"id": "42fb87d0a36623d32b9c8c890a1b6df8b3c0c4ce",
"size": "18774",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "app/build/intermediates/res/debug/values-v21/values-v21.xml",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Java",
"bytes": "499403"
}
],
"symlink_target": ""
} |
ActiveAdmin.register User do
menu priority: 3
index do
column :full_name
column :email
column :current_sign_in_at
column :last_sign_in_at
column :sign_in_count
column :created_at
default_actions
end
filter :username
filter :email
form do |f|
f.inputs "User Details" do
f.input :first_name
f.input :last_name
f.input :email
f.input :password
f.input :password_confirmation
f.input :entity_name
end
f.buttons
end
show do
attributes_table do
row :full_name
row :email
row :current_sign_in_at
row :last_sign_in_at
row :sign_in_count
row :created_at
end
active_admin_comments
end
end | {
"content_hash": "bd32f7ac379a5421a7cf07f44b072861",
"timestamp": "",
"source": "github",
"line_count": 39,
"max_line_length": 36,
"avg_line_length": 18.23076923076923,
"alnum_prop": 0.6315049226441631,
"repo_name": "mwanamayi/tozoya",
"id": "aa16410322f958628cdfaff824a983bbc7bce50d",
"size": "711",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "app/admin/user.rb",
"mode": "33261",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "275300"
},
{
"name": "CoffeeScript",
"bytes": "916"
},
{
"name": "HTML",
"bytes": "160917"
},
{
"name": "JavaScript",
"bytes": "50992"
},
{
"name": "Ruby",
"bytes": "152181"
}
],
"symlink_target": ""
} |
@interface ViewController : UIViewController
@end
| {
"content_hash": "df5db78ce53ce0732c8745310d56c44c",
"timestamp": "",
"source": "github",
"line_count": 5,
"max_line_length": 44,
"avg_line_length": 10.6,
"alnum_prop": 0.7924528301886793,
"repo_name": "Ero-Radio/PDFGenerator",
"id": "292a6c7486455afdf184ef2a98b48cabfb86fff3",
"size": "223",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "PDFGenerator/ViewController.h",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Objective-C",
"bytes": "20048"
}
],
"symlink_target": ""
} |
<!-- Master layout. -->
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:padding="16dp">
<!-- Header: Day, Date -->
<TextView
android:id="@+id/detail_day_textview"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Tomorrow" />
<TextView
android:id="@+id/detail_date_textview"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="June 24"/>
<!-- Main content: high, low, art, weather state -->
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginTop="16dp"
android:orientation="horizontal">
<LinearLayout
android:layout_width="0dp"
android:layout_weight="1"
android:layout_height="wrap_content"
android:orientation="vertical">
<TextView
android:id="@+id/detail_high_textview"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="21°"/>
<TextView
android:id="@+id/detail_low_textview"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="11°" />
</LinearLayout>
<LinearLayout
android:layout_width="0dp"
android:layout_weight="1"
android:layout_height="wrap_content"
android:gravity="center_horizontal"
android:orientation="vertical">
<ImageView
android:id="@+id/detail_icon"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<TextView
android:id="@+id/detail_forecast_textview"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Clear" />
</LinearLayout>
</LinearLayout>
<!-- Humidity, wind, pressure -->
<TextView
android:id="@+id/detail_humidity_textview"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="48%" />
<TextView
android:id="@+id/detail_wind_textview"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="6 km/h NW" />
<TextView
android:id="@+id/detail_pressure_textview"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="1014" />
</LinearLayout>
</ScrollView>
| {
"content_hash": "7e3555d4450f587acb6b2d60ee11e4a3",
"timestamp": "",
"source": "github",
"line_count": 90,
"max_line_length": 70,
"avg_line_length": 36.044444444444444,
"alnum_prop": 0.532983970406905,
"repo_name": "brnewby602/sunshine",
"id": "85074b16dfaf9ed517d8f9df18c625212df9ae2a",
"size": "3246",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "app/src/main/res/layout/fragment_forecast_detail.xml",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Java",
"bytes": "134943"
}
],
"symlink_target": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.